Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat: v0.3.0 — workspaces, auto-sync hooks, graph intelligence (#76)

Raghav Chamadiyaa901cc985cbd
diff --git a/.gitignore b/.gitignore
index bb1789512..6d68a1771 100644
--- a/.gitignore
+++ b/.gitignore
@@ -80,6 +80,8 @@ next-env.d.ts
# repowise runtime data
.repowise/
!.repowise/mcp.json.example
+.repowise-workspace/
+.repowise-workspace.yaml
# Database
*.db
@@ -111,3 +113,11 @@ ehthumbs.db
# Claude Code
.claude/
+
+# repowise API keys (local)
+.repowise/.env
+
+# Internal docs (not for distribution)
+docs/COMPETITIVE_ANALYSIS.md
+docs/GRAPH_INTELLIGENCE_UPGRADE.md
+docs/multi-repo/
diff --git a/README.md b/README.md
index 9b8b0d3dd..baed7e357 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
<img src=".github/assets/logo.png" width="280" alt="repowise" /><br />
**Codebase intelligence for AI-assisted engineering teams.**
-Four intelligence layers. Eleven MCP tools. One `pip install`.
+Four intelligence layers. Seven MCP tools. Multi-repo workspaces. Auto-sync hooks. One `pip install`.
[![PyPI version](https://img.shields.io/pypi/v/repowise?color=F59520&labelColor=0A0A0A)](https://pypi.org/project/repowise/)
[![License: AGPL v3](https://img.shields.io/badge/license-AGPL--v3-F59520?labelColor=0A0A0A)](https://www.gnu.org/licenses/agpl-3.0)
@@ -23,7 +23,7 @@ Four intelligence layers. Eleven MCP tools. One `pip install`.
Your AI coding agent reads files. It does not know who owns them, which ones change together, which ones are dead, or why they were built the way they were. It has the source code and zero institutional knowledge.
-repowise fixes that. It indexes your codebase into four intelligence layers — dependency graph, git history, auto-generated documentation, and architectural decisions — and exposes them to Claude Code (and any MCP-compatible AI agent) through eleven precisely designed tools. **27× fewer tokens per query. 36% cheaper. Same answer quality.**
+repowise fixes that. It indexes your codebase into four intelligence layers — dependency graph, git history, auto-generated documentation, and architectural decisions — and exposes them to Claude Code (and any MCP-compatible AI agent) through seven precisely designed tools. Multi-repo? Initialize a workspace and get cross-repo co-change detection, API contract extraction, and federated MCP queries across all your services. **27× fewer tokens per query. 36% cheaper. Same answer quality.**
The result: your agent answers *"why does auth work this way?"* instead of *"here is what auth.ts contains."*
@@ -65,7 +65,7 @@ There's a small genre of "token efficiency" benchmarks going around. It would be
repowise runs once, builds everything, then keeps it in sync on every commit.
### ◈ Graph Intelligence
-tree-sitter parses every file into symbols. NetworkX builds a dependency graph — files, classes, functions, imports, inheritance, and call relationships. PageRank identifies your most central code. Community detection finds logical modules even when your directory structure doesn't reflect them.
+tree-sitter parses every file into symbols. NetworkX builds a two-tier dependency graph — file nodes for module-level relationships and symbol nodes (functions, classes, methods) for fine-grained call resolution. A 3-tier resolver links call sites to their targets with confidence scoring. Import aliases, barrel re-exports, and namespace imports all resolve correctly. Inheritance hierarchies are extracted across 11 languages (extends, implements, trait impls, mixins) and resolved to concrete symbol edges. Leiden community detection identifies logical modules at both file and symbol level — with cohesion scoring and heuristic labeling — even when your directory structure doesn't reflect them. Execution flow tracing discovers call paths from entry points through your codebase, classifying them as intra- or cross-community. PageRank, betweenness centrality, and SCC analysis identify your most central and most coupled code.
### ◈ Git Intelligence
500 commits of history turned into signals: hotspot files (high churn × high complexity), ownership percentages per engineer, co-change pairs (files that change together without an import link — hidden coupling), and significant commit messages that explain *why* code evolved.
@@ -92,13 +92,25 @@ These become structured decision records, queryable by Claude Code via `get_why(
pip install repowise
```
+### Single repo
+
```bash
cd your-project
repowise init # builds all four intelligence layers (~25 min first time)
repowise serve # starts MCP server + local dashboard
```
-Add to your Claude Code config (optional, `repowise init` already initializes `.mcp.json` under the project root):
+### Multi-repo workspace
+
+```bash
+cd my-workspace/ # parent dir containing backend/, frontend/, shared-libs/
+repowise init . # scans for git repos, indexes each, runs cross-repo analysis
+repowise serve # workspace dashboard + per-repo pages
+```
+
+That's it. `repowise init` automatically registers the MCP server, installs PreToolUse/PostToolUse hooks in `~/.claude/settings.json`, generates `.mcp.json` at the project root, and offers to install a post-commit git hook that keeps everything in sync after every commit. See [Auto-Sync](docs/AUTO_SYNC.md) for all sync methods (hooks, file watcher, GitHub/GitLab webhooks, polling).
+
+To manually add the MCP server to another editor:
```json
{
@@ -111,27 +123,61 @@ Add to your Claude Code config (optional, `repowise init` already initializes `.
}
```
-> **Note on init time:** Initial indexing analyzes your entire codebase — AST parsing, 500-commit git history, LLM doc generation, embedding indexing, and decision archaeology. This is a one-time cost (~25 minutes for a 3,000-file project). Every subsequent update after a commit takes under 30 seconds.
+> **Note on init time:** Initial indexing analyzes your entire codebase — AST parsing, 500-commit git history, LLM doc generation, embedding indexing, and decision archaeology. This is a one-time cost (~25 minutes for a 3,000-file project). Every subsequent update after a commit takes under 30 seconds and only regenerates the few pages affected by your changes.
+
+> **Full docs:** [Quickstart](docs/QUICKSTART.md) · [User Guide](docs/USER_GUIDE.md) · [CLI Reference](docs/CLI_REFERENCE.md) · [MCP Tools](docs/MCP_TOOLS.md) · [Workspaces](docs/WORKSPACES.md) · [Auto-Sync](docs/AUTO_SYNC.md)
---
-## Eleven MCP tools
+## Workspaces — multi-repo intelligence
+
+Most codebases aren't one repo. repowise workspaces let you index and query multiple repositories together — with cross-repo intelligence that single-repo tools can't provide.
+
+```bash
+cd my-workspace/ # backend/, frontend/, shared-libs/ under one parent
+repowise init . # scan, select repos, index each, run cross-repo analysis
+```
+
+**What you get on top of per-repo intelligence:**
+
+| Feature | What it does |
+|---|---|
+| **Cross-repo co-changes** | Finds files across repos that change in the same time window — e.g., `backend/api/routes.py` and `frontend/src/api/client.ts` always move together |
+| **API contract extraction** | Scans for HTTP route handlers (Express, FastAPI, Spring, Go), gRPC service defs, and message topic publishers/subscribers — then matches providers with consumers across repos |
+| **Package dependency mapping** | Reads `package.json`, `pyproject.toml`, `go.mod`, `pom.xml` to detect when one repo depends on another as a package |
+| **Federated MCP queries** | One MCP server serves all repos. Pass `repo="backend"` or `repo="all"` to any tool |
+| **Workspace dashboard** | Aggregate stats, repo cards, contract links, co-change pairs — all in the web UI |
+| **Workspace CLAUDE.md** | Auto-generated context file covering all repos, their relationships, and cross-repo signals |
-Most tools are designed around data entities — one module, one file, one symbol — which forces AI agents into long chains of sequential calls. repowise tools are designed around **tasks**. Pass multiple targets in one call. Get complete context back.
+**Workspace CLI:**
+
+```bash
+repowise workspace list # show all repos and their status
+repowise workspace add ../new-service # add a repo to the workspace
+repowise workspace remove api-gateway # remove a repo (doesn't delete files)
+repowise workspace scan # re-scan for new repos
+repowise update --workspace # update all stale repos + cross-repo analysis
+repowise watch --workspace # auto-update all repos on file change
+repowise hook install --workspace # install post-commit hooks for all repos
+```
+
+Full guide: [docs/WORKSPACES.md](docs/WORKSPACES.md)
+
+---
+
+## Seven MCP tools
+
+Most tools are designed around data entities — one module, one file, one symbol — which forces AI agents into long chains of sequential calls. repowise tools are designed around **tasks**. Pass multiple targets in one call. Get complete context back. Full reference: [docs/MCP_TOOLS.md](docs/MCP_TOOLS.md)
| Tool | What it answers | When Claude Code calls it |
|---|---|---|
-| `get_answer(question)` | One-call RAG: retrieves over the wiki, gates on confidence, and synthesizes a cited 2–5 sentence answer. High-confidence answers cite directly; ambiguous queries return ranked excerpts. Responses are cached per repository by question hash. | First call on any code question — collapses search → read → reason into one round-trip |
-| `get_symbol(symbol_id)` | Resolves a qualified symbol id (`path::Class::method`) to its source body, signature, and docstring | When the question names a specific class, function, or method |
-| `get_overview()` | Architecture summary, module map, entry points | First call on any unfamiliar codebase |
-| `get_context(targets, include?, compact?)` | Docs, ownership, decisions, freshness for any targets — files, modules, or symbols. `compact=True` is the default and bounds the response to ~10K characters; pass `compact=False` for the full structure block, importer list, and per-symbol docstrings | Before reading or modifying code. Pass all relevant targets in one call. |
+| `get_overview()` | Architecture summary, module map, entry points, git health, community summary | First call on any unfamiliar codebase |
+| `get_answer(question)` | One-call RAG: retrieves over the wiki, gates on confidence, and synthesizes a cited 2–5 sentence answer. High-confidence answers cite directly; ambiguous queries return ranked excerpts. | First call on any code question — collapses search → read → reason into one round-trip |
+| `get_context(targets, include?)` | The workhorse. Docs, symbols, ownership, freshness, community membership for any targets. `include` options: `"source"` (symbol body), `"callers"`/`"callees"` (call graph), `"metrics"` (PageRank, centrality), `"community"` (cluster membership). Batch multiple targets. In workspace mode, pass `repo` to target a specific repo. | Before reading or modifying code. Pass all relevant targets in one call. |
+| `search_codebase(query)` | Semantic search over the full wiki. Natural language. In workspace mode, searches across all repos. | When `get_answer` returned low confidence and you need to discover candidate pages by topic |
| `get_risk(targets?, changed_files?)` | Hotspot scores, dependents, co-change partners, blast radius, recommended reviewers, test gaps, security signals, 0–10 risk score | Before modifying files — understand what could break |
| `get_why(query?)` | Three modes: NL search over decisions · path-based decisions for a file · no-arg health dashboard | Before architectural changes — understand existing intent |
-| `search_codebase(query)` | Semantic search over the full wiki. Natural language. | When `get_answer` returned low confidence and you need to discover candidate pages by topic |
-| `get_dependency_path(from, to)` | Connection path between two files, modules, or symbols | When tracing how two things are connected |
-| `get_dead_code(min_confidence?, include_internals?, include_zombie_packages?)` | Unreachable code sorted by confidence and cleanup impact | Cleanup tasks |
-| `get_architecture_diagram(module?)` | Mermaid diagram for the repo or a specific module | Documentation and presentation |
-| `annotate_file(target, notes)` | Attach human-authored notes to a wiki page — survives re-indexing | Adding rationale, known issues, or context that the LLM shouldn't overwrite |
+| `get_dead_code(min_confidence?, include_internals?)` | Unreachable code sorted by confidence tier with cleanup impact estimates | Cleanup tasks |
### Tool call comparison — a real task
@@ -140,7 +186,7 @@ Most tools are designed around data entities — one module, one file, one symbo
| Approach | Tool calls | Time to first change | What it misses |
|---|---|---|---|
| Claude Code alone (no MCP) | grep + read ~30 files | ~8 min | Ownership, prior decisions, hidden coupling |
-| **repowise (10 tools)** | **5 calls** | **~2 min** | **Nothing** |
+| **repowise (7 tools)** | **5 calls** | **~2 min** | **Nothing** |
The 5 calls for that task:
@@ -197,10 +243,10 @@ This is what happens when an AI agent has real codebase intelligence.
| View | What it shows |
|---|---|
| **Chat** | Ask anything about your codebase in natural language |
-| **Docs** | AI-generated wiki with syntax highlighting and Mermaid diagrams |
-| **Graph** | Interactive dependency graph — handles 2,000+ nodes |
+| **Docs** | AI-generated wiki with syntax highlighting, Mermaid diagrams, and a graph intelligence sidebar showing PageRank/betweenness percentiles, community membership, and degree |
+| **Graph** | Interactive dependency graph — handles 2,000+ nodes. Community color mode with real labels, community detail panel on click, path finder |
| **Search** | Full-text and semantic search with global command palette (Ctrl+K) |
-| **Symbols** | Searchable index of every function, class, and method |
+| **Symbols** | Searchable index of every function, class, and method. Click any symbol for graph metrics, callers/callees, and class heritage |
| **Coverage** | Doc freshness per file with one-click regeneration |
| **Ownership** | Contributor attribution and bus factor risk |
| **Hotspots** | Ranked by trend-weighted score (180-day decay) and churn |
@@ -209,10 +255,84 @@ This is what happens when an AI agent has real codebase intelligence.
| **Costs** | LLM spend by day, model, or operation, with running session totals |
| **Blast Radius** | Paste a PR file list, see transitive impact, reviewers, and test gaps |
| **Knowledge Map** | Top owners, bus-factor silos, and onboarding targets on the dashboard |
+| **Graph Intelligence** | Architecture communities with expandable detail, execution flows with call traces, community coupling analysis — all on the overview dashboard |
+| **Workspace Dashboard** | Aggregate stats across repos, repo cards, cross-repo intelligence summary (workspace mode) |
+| **Workspace Contracts** | Detected API contracts (HTTP, gRPC, topics) with provider/consumer matching across repos |
+| **Workspace Co-Changes** | Cross-repo file pairs ranked by co-change strength |
| **System Health** | SQL/vector/graph drift status from the atomic store coordinator |
---
+## Proactive context enrichment — hooks
+
+Most MCP tools are passive — the agent has to know to call them. repowise hooks are **active**. They inject graph context into every search automatically, so agents are smarter even when they don't explicitly ask for help.
+
+### PreToolUse — every search gets graph context
+
+When your AI agent runs `Grep` or `Glob`, repowise intercepts the call and enriches it with:
+
+- **Matching files** from the wiki's full-text search index
+- **Symbols** — functions, classes, and methods in those files
+- **Importers** — who depends on this file (callers)
+- **Dependencies** — what this file imports (callees)
+- **Git signals** — hotspot status, bus factor, primary owner
+
+Average latency: **24ms**. No LLM calls. No network. Pure local SQLite queries.
+
+```
+[repowise] 2 related file(s) found:
+
+ src/auth/middleware.ts
+ Symbols: class:AuthMiddleware, function:validateToken, function:refreshSession
+ Imported by: api/routes/index.ts, api/routes/payments.ts, api/routes/admin.ts
+ Depends on: auth/jwt.ts, db/sessions.ts, config/auth.ts
+ Git: HOTSPOT, bus-factor=1, owner=@alex
+```
+
+### PostToolUse — auto-detect stale wiki
+
+After a successful `git commit`, repowise checks whether the wiki is out of date and notifies the agent:
+
+```
+[repowise] Wiki is stale — last indexed at commit a1b2c3d4, HEAD is now f9a0499b.
+Run `repowise update` to refresh documentation and graph context.
+```
+
+Hooks are installed automatically during `repowise init`. No manual configuration needed. Full details: [docs/AUTO_SYNC.md](docs/AUTO_SYNC.md)
+
+---
+
+## Auto-sync — five ways to keep your wiki current
+
+repowise keeps your intelligence layers in sync with your code. Pick the method that fits your workflow:
+
+| Method | Command | Best for |
+|--------|---------|----------|
+| **Post-commit hook** | `repowise hook install` | Set-and-forget local development |
+| **File watcher** | `repowise watch` | Active development without committing |
+| **GitHub webhook** | Configure in repo settings | Teams, CI/CD |
+| **GitLab webhook** | Configure in project settings | Teams, CI/CD |
+| **Polling fallback** | Automatic with `repowise serve` | Safety net for missed webhooks |
+
+```bash
+# Install post-commit hook for one repo
+repowise hook install
+
+# Install for all repos in a workspace
+repowise hook install --workspace
+
+# Check hook status
+repowise hook status
+
+# Or use the file watcher
+repowise watch # single repo
+repowise watch --workspace # all workspace repos
+```
+
+A typical single-commit update touches 3–10 pages and completes in under 30 seconds. Full guide: [docs/AUTO_SYNC.md](docs/AUTO_SYNC.md)
+
+---
+
## Auto-generated CLAUDE.md
After every `repowise init` and `repowise update`, repowise regenerates your `CLAUDE.md` from actual codebase intelligence — not a template. No LLM calls. Under 5 seconds.
@@ -318,7 +438,9 @@ When a senior engineer leaves, the "why" usually leaves with them. Decision inte
| Git intelligence (hotspots, ownership, co-changes) | ✅ | ❌ | ❌ | ❌ | ✅ |
| Bus factor analysis | ✅ | ❌ | ❌ | ❌ | ✅ |
| Architectural decision records | ✅ | ❌ | ❌ | ❌ | ❌ |
-| MCP server for AI agents | ✅ 11 tools | ❌ | ✅ 3 tools | ✅ | ✅ |
+| Multi-repo workspace intelligence | ✅ co-changes, contracts, federated MCP | ❌ | ❌ | ❌ | ❌ |
+| MCP server for AI agents | ✅ 7 tools | ❌ | ✅ 3 tools | ✅ | ✅ |
+| Proactive agent hooks | ✅ PreToolUse + PostToolUse | ❌ | ❌ | ❌ | ❌ |
| Auto-generated CLAUDE.md | ✅ | ❌ | ❌ | ❌ | ❌ |
| Doc freshness scoring | ✅ | ❌ | ❌ | ⚠️ staleness only | ❌ |
| Incremental updates on commit | ✅ <30s | ✅ | ❌ | ✅ | ✅ |
@@ -332,7 +454,7 @@ When a senior engineer leaves, the "why" usually leaves with them. Decision inte
- **vs Swimm** — Swimm's strength is keeping manually-written docs linked to code snippets with staleness detection. No graph, no git behavioral analytics, no dead code, no MCP by default. Enterprise pricing for private hosting.
- **vs CodeScene** — CodeScene has excellent git intelligence (hotspots, co-changes, ownership, bus factor). No documentation generation, no RAG, no architectural decisions. Closed source, per-author pricing.
-repowise is the intersection: CodeScene-level git intelligence + auto-generated documentation + agent-native MCP + architectural decisions, self-hostable and open source.
+repowise is the intersection: CodeScene-level git intelligence + auto-generated documentation + agent-native MCP + architectural decisions + multi-repo workspace intelligence, self-hostable and open source.
---
@@ -348,7 +470,7 @@ Hosted adds what only makes sense in a managed, multi-user environment:
- **Engineering leader dashboard** — bus factor trends, hotspot evolution over time, cross-repo dead code, ownership drift
- **Managed webhooks** — zero-configuration auto re-index on every commit to any branch
- **Integrations** — Slack alerts, Jira and Linear decision linking, Confluence and Notion doc sync, GitHub and GitLab webhooks, PagerDuty escalation routing
-- **Cross-repo intelligence** — hotspots, dead code, and ownership across all your repositories at once
+- **Cross-repo intelligence at scale** — hotspots, dead code, and ownership across all your repositories with centralized dashboards (beyond what local workspaces provide)
[Get in touch →](https://www.repowise.dev/#contact) · [[email protected]](mailto:[email protected])
@@ -358,13 +480,22 @@ Hosted adds what only makes sense in a managed, multi-user environment:
```bash
# Core
-repowise init [PATH] # index codebase (one-time)
+repowise init [PATH] # index codebase (one-time, offers hook setup)
repowise init --index-only # graph + git + dead code, no LLM, no cost
repowise init -x vendor/ -x proto/ # exclude patterns (gitignore syntax)
repowise init --include-submodules # include git submodule directories
repowise update [PATH] # incremental update (<30 seconds)
+repowise update --workspace # update all stale repos in workspace
+repowise update --repo backend # update a specific workspace repo
repowise serve [PATH] # MCP server + local dashboard
repowise watch [PATH] # auto-update on file save
+repowise watch --workspace # auto-update all workspace repos
+
+# Auto-sync hooks
+repowise hook install # install post-commit hook (current repo)
+repowise hook install --workspace # install for all workspace repos
+repowise hook status # check if hooks are installed
+repowise hook uninstall # remove hooks
# Query
repowise query "<question>" # ask anything from the terminal
@@ -394,6 +525,9 @@ repowise decision health # stale, conflicts, ungoverned hotspots
# Editor files
repowise generate-claude-md # regenerate CLAUDE.md
+# Proactive hooks (auto-installed by init — not called manually)
+repowise augment # enriches agent tool calls with graph context
+
# Utilities
repowise export [PATH] # export wiki as markdown files
repowise export --full --format json # full export with decisions, dead code, hotspots
@@ -408,13 +542,14 @@ repowise reindex # rebuild vector store (no LLM calls)
| Tier | Languages | What works |
|------|-----------|------------|
-| **Full** | Python · TypeScript · JavaScript · Java | AST parsing, import resolution, dependency graph edges |
-| **Good** | Go · Rust | AST parsing, partial import resolution (`crate::` / module paths) |
-| **Basic** | C · C++ | AST parsing (structs, functions, classes), `#include` resolution with `compile_commands.json` |
-| **Traversal** | Ruby · Kotlin · C# · Swift · Scala · PHP | Files indexed and searchable, but no AST symbol extraction yet |
+| **Full** | Python · TypeScript · JavaScript · Java · Go · Rust | AST parsing, import resolution, named bindings, dependency graph edges, call resolution, heritage extraction |
+| **Partial** | C++ | AST parsing, symbol extraction, heritage extraction, `compile_commands.json` import resolution |
+| **Partial** | C | AST parsing (structs, functions, macros), `#include` resolution with `compile_commands.json` |
+| **Scaffolded** | Kotlin · Ruby | Tree-sitter queries and heritage extractors exist but grammars not yet wired — install `tree-sitter-kotlin` / `tree-sitter-ruby` separately |
+| **Traversal** | C# · Swift · Scala · PHP | Files indexed and searchable, but no AST symbol extraction yet |
| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · SQL · Terraform | Included in the file tree; special handlers extract endpoints/targets where applicable |
-Dart and Elixir are on the roadmap. Adding a new language requires one `.scm` tree-sitter query file and one config entry. No changes to the parser core. PRs welcome. See [Adding a new language](docs/CONTRIBUTING.md#adding-a-new-language).
+Kotlin, Ruby, C#, Swift, Scala, PHP, Dart, and Elixir are on the [language support roadmap](docs/LANGUAGE_SUPPORT_PLAN.md). Adding a new language requires one `.scm` tree-sitter query file and one config entry. No changes to the parser core. PRs welcome. See [Adding a new language](docs/CONTRIBUTING.md#adding-a-new-language).
---
@@ -424,7 +559,7 @@ Dart and Elixir are on the roadmap. Adding a new language requires one `.scm` tr
**BYOK:** Bring your own Anthropic or OpenAI API key. We never see your LLM calls. Zero data retention via Anthropic's API policy — your code is never used to train any model.
-**What is stored:** NetworkX graph (file and symbol relationships), LanceDB embeddings (non-reversible vectors), generated wiki pages, git metadata. Raw source code is processed transiently and never persisted.
+**What is stored:** NetworkX graph (file and symbol relationships, communities, call edges with confidence), LanceDB embeddings (non-reversible vectors), generated wiki pages, git metadata. Raw source code is processed transiently and never persisted.
**Fully offline:** Ollama for LLM + local embedding models = zero external API calls.
diff --git a/docs/AUTO_SYNC.md b/docs/AUTO_SYNC.md
index 65a433d5e..0a79208b5 100644
--- a/docs/AUTO_SYNC.md
+++ b/docs/AUTO_SYNC.md
@@ -13,50 +13,47 @@ method that fits your setup.
---
-## 1. Post-Commit Git Hook
+## 1. Post-Commit Git Hook (Recommended)
Runs `repowise update` in the background after every local commit. Your
-terminal is never blocked.
+terminal is never blocked. This is the recommended auto-sync method for
+local development.
### Setup
+`repowise init` will offer to install the hook automatically at the end
+of the setup wizard. You can also install or manage it manually:
+
```bash
-cat > .git/hooks/post-commit << 'EOF'
-#!/bin/sh
-echo "[repowise] Triggering wiki update..."
-(
- cd "$(git rev-parse --show-toplevel)" || exit 1
- repowise update > /tmp/repowise-update.log 2>&1
-) &
-exit 0
-EOF
-chmod +x .git/hooks/post-commit
+repowise hook install # install for current repo
+repowise hook install --workspace # install for all workspace repos
+repowise hook status # check if installed
+repowise hook uninstall # remove the hook
```
-> **Windows (Git Bash):** If `repowise` isn't on your bash PATH (e.g. installed
-> via `uv`), replace the `repowise update` line with:
-> ```bash
-> powershell.exe -Command "uv run repowise update" > /tmp/repowise-update.log 2>&1
-> ```
+The hook is marker-delimited, so it safely coexists with other tools'
+hooks (linters, formatters, etc.) in the same `post-commit` file.
### What happens
1. You run `git commit`
-2. The hook fires in the background
+2. The hook fires in the background (non-blocking)
3. `repowise update` diffs the new commit against the last synced commit
4. Only affected pages are regenerated (typically 3-10 for a small commit)
-5. Output is logged to `/tmp/repowise-update.log`
+5. Graph, git stats, dead code, and decisions are also refreshed
-### Check the last run
+### Check hook status
```bash
-cat /tmp/repowise-update.log
+repowise hook status
+repowise hook status --workspace # check all repos in workspace
```
### Remove the hook
```bash
-rm .git/hooks/post-commit
+repowise hook uninstall
+repowise hook uninstall --workspace
```
---
@@ -170,20 +167,50 @@ with `repowise serve`.
---
-## How Incremental Updates Work
+## How Updates Work
+
+There are two update paths, depending on the trigger:
-Regardless of which trigger method you use, the update process is the same:
+### CLI incremental update (`repowise update`)
1. **Diff** -- compare the new HEAD against the last synced commit
-2. **Detect affected pages** -- find directly changed files, then cascade to
- files that import them (1-hop), capped at 30 pages per run
-3. **Regenerate** -- call the LLM only for affected pages
-4. **Persist** -- update the database and search index
-5. **Save state** -- record the new HEAD as the last synced commit
+2. **Full graph rebuild** -- re-traverse and re-parse all files to rebuild
+ the dependency graph (needed for cascade analysis)
+3. **Incremental git re-index** -- re-index git metadata only for changed files,
+ then recompute percentiles across the whole repo
+4. **Dead code analysis** -- run partial dead code detection on changed files
+ and their graph neighbors
+5. **Decision re-scan** -- re-scan changed files for inline decision markers
+6. **Detect affected pages** -- find directly changed files, cascade to 1-hop
+ importers, capped by an adaptive budget (auto-scaled based on change size)
+7. **Regenerate** -- call the LLM only for affected pages
+8. **Cross-repo hooks** -- if the repo is part of a workspace, re-run cross-repo
+ co-change and contract analysis
+9. **Persist** -- update the database, search index, and record a GenerationJob
+10. **Save state** -- record the new HEAD as the last synced commit
A typical single-commit update touches 3-10 pages and completes in under a
minute.
+### Server sync (`POST /api/repos/{id}/sync`)
+
+1. **Full re-traverse** -- re-parse all files and rebuild the dependency graph
+2. **Full git re-index** -- re-index git metadata for all files
+3. **Dead code analysis** -- full dead code scan
+4. **Decision extraction** -- full decision marker scan
+5. **Persist** -- update the database
+6. **Save state** -- record the new HEAD
+
+Server sync does **not** regenerate wiki pages (no LLM cost). Use
+**Full Re-index** (`POST /api/repos/{id}/full-resync`) to also regenerate
+all wiki pages.
+
+### Workspace updates (`repowise update --workspace`)
+
+Updates all stale repos in parallel (up to 4 concurrent), then re-runs
+cross-repo analysis (co-changes, package dependencies, API contracts).
+Use `--repo <alias>` to target a single repo within the workspace.
+
### Dry run
To see what would be updated without actually regenerating:
@@ -195,9 +222,12 @@ repowise update --dry-run
### Manual update
```bash
-repowise update # diff since last sync
-repowise update --since abc123 # diff from a specific commit
-repowise update --cascade-budget 50 # allow more cascade pages (default: 30)
+repowise update # diff since last sync
+repowise update --since abc123 # diff from a specific commit
+repowise update --cascade-budget 50 # allow more cascade pages (default: auto)
+repowise update --workspace # update all stale workspace repos
+repowise update --repo backend # update a specific workspace repo
+repowise watch --workspace # auto-update all workspace repos on file change
```
---
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 0ebfe3f3f..918c8a016 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -9,6 +9,58 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
---
+## [0.3.0] — 2026-04-13
+
+### Added
+
+#### Multi-repo workspaces
+- **Workspace support** — `repowise init .` from a parent directory scans for git repos (up to 3 levels deep), prompts for selection, and indexes each repo with cross-repo analysis. Config stored in `.repowise-workspace.yaml`.
+- **Workspace CLI commands** — `repowise workspace list`, `workspace add <path>`, `workspace remove <alias>`, `workspace scan`, `workspace set-default <alias>` for managing repos in a workspace.
+- **Workspace-aware MCP server** — a single MCP server instance serves all workspace repos. Tools accept an optional `repo` parameter to target a specific repo or `"all"` to query across the workspace. Lazy-loading with LRU eviction (max 5 repos loaded simultaneously).
+- **Cross-repo co-change detection** — analyzes git history across repos to find files that frequently change in the same time window.
+- **API contract extraction** — scans for HTTP route handlers (Express, FastAPI, Spring, Go), gRPC service definitions, and message topic publishers/subscribers. Matches providers with consumers across repos.
+- **Package dependency scanning** — reads package manifests (`package.json`, `pyproject.toml`, `go.mod`, `pom.xml`) to detect inter-repo package dependencies.
+- **Workspace CLAUDE.md** — auto-generated context file at the workspace root covering all repos, their relationships, cross-repo signals, and contract links.
+- **Workspace web UI** — workspace dashboard (`/workspace`) with aggregate stats and repo cards, contracts view (`/workspace/contracts`) with provider/consumer matching, and co-changes view (`/workspace/co-changes`) with cross-repo file pairs ranked by strength.
+- **Workspace update** — `repowise update --workspace` updates all stale repos in parallel (up to 4 concurrent) then re-runs cross-repo analysis. `--repo <alias>` targets a single repo.
+- **Workspace watch** — `repowise watch --workspace` auto-updates all workspace repos on file change.
+
+#### Auto-sync hooks
+- **`repowise hook` CLI** — `repowise hook install` installs a marker-delimited post-commit git hook that runs `repowise update` in the background after every commit. `hook install --workspace` installs for all workspace repos. `hook status` and `hook uninstall` for management.
+- **Proactive context enrichment via Claude Code hooks** — `repowise init` registers PreToolUse and PostToolUse hooks in `~/.claude/settings.json`. PreToolUse enriches every `Grep`/`Glob` call with graph context (importers, dependencies, symbols, git signals) at ~24ms latency. PostToolUse detects git commits and notifies the agent when the wiki is stale.
+- **Polling scheduler** — when the server is running, a background job polls registered repositories every 15 minutes and triggers updates for new commits missed by webhooks.
+
+#### Graph intelligence
+- **Symbol-level dependency graph** — the dependency graph is now two-tier: file nodes for module-level relationships and symbol nodes (functions, classes, methods) for fine-grained call resolution. Call edges carry confidence scores (0.0–1.0).
+- **3-tier call resolution** — Tier 1: same-file targets (confidence 0.95). Tier 2: import-scoped targets via named bindings (0.85–0.93). Tier 3: global unique match (0.50). Extracted by tree-sitter for Python, TypeScript, JavaScript, Go, Rust, Java, and C++.
+- **Named binding resolution** — tracks import aliases, barrel re-exports (`__init__.py`, `index.ts`), and namespace imports across all 7 full-tier languages.
+- **Heritage extraction** — class inheritance and interface implementation for 11 languages (Python, TypeScript, JavaScript, Java, Go, Rust, C++, Kotlin, Ruby, C#, C) with `extends`/`implements` graph edges.
+- **Leiden community detection** — two-level community detection (file communities from import edges, symbol communities from call/heritage edges) with cohesion scoring and heuristic labeling. Falls back to NetworkX Louvain when graspologic is unavailable.
+- **Execution flow tracing** — 5-signal entry point scoring (fan-out ratio, in-degree, visibility, name pattern, framework hint) with BFS call-path discovery and cross-community classification.
+- **Graph query indexes** (migration `0017`) — composite indexes for sub-millisecond graph queries.
+
+#### Web UI
+- **Graph Intelligence on Overview** — expandable community list (labels, cohesion, member counts) and execution flows panel with call-path traces on the overview dashboard.
+- **Wiki sidebar** — new collapsible section showing PageRank and betweenness percentile bars, community label, and in/out degree for the current file.
+- **Symbols drawer** — right panel with graph metrics, callers/callees (with confidence scores), and heritage (extends/implements) for class nodes.
+- **Graph page** — community color mode uses real community labels from Leiden detection. Clicking a node opens a community detail panel. Active color mode preserved as a URL parameter.
+- **Contributor network, hotspot, and ownership pages** — new dedicated pages for git intelligence.
+- **Docs viewer** — enriched with graph intelligence sidebar, version history, and improved markdown rendering.
+- **5 new graph REST API endpoints** — communities list, community detail, node metrics, callers/callees, and execution flows.
+
+#### Other
+- **Improved init UX** — pre-scan phase shows repo size and language breakdown before confirming. Advanced config options grouped logically with live insights during indexing.
+- **Doc generation enriched with graph intelligence** — wiki page generation prompts now include community context, caller/callee information, and heritage relationships.
+
+### Changed
+- **`get_overview`** now includes `community_summary` — top communities by size with labels and cohesion scores.
+- **`get_context`** now includes `community` block per file target with community ID and label (when `compact=False`). In workspace mode, enriched with cross-repo co-change and contract data.
+- **`get_risk`** enriched with cross-repo signals in workspace mode — co-change partners from other repos and contract dependencies.
+- **`search_codebase`** in workspace mode searches across all repos and merges results.
+- **Job executor** — improved progress tracking, concurrent run detection (HTTP 409), and crash recovery for stale running jobs on server startup.
+
+---
+
## [0.2.3] — 2026-04-11
### Added
@@ -234,6 +286,8 @@ See git history for releases prior to 0.2.0.
---
+[0.3.0]: https://github.com/repowise-dev/repowise/compare/v0.2.3...HEAD
+[0.2.3]: https://github.com/repowise-dev/repowise/compare/v0.2.2...v0.2.3
[0.2.2]: https://github.com/repowise-dev/repowise/compare/v0.2.1...v0.2.2
[0.2.1]: https://github.com/repowise-dev/repowise/compare/v0.2.0...v0.2.1
[0.2.0]: https://github.com/repowise-dev/repowise/compare/v0.1.31...v0.2.0
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md
new file mode 100644
index 000000000..5d5123011
--- /dev/null
+++ b/docs/CLI_REFERENCE.md
@@ -0,0 +1,395 @@
+# CLI Reference
+
+Complete reference for all `repowise` commands. For a guided introduction, see the [Quickstart](QUICKSTART.md).
+
+---
+
+## Core Commands
+
+### `repowise init [PATH]`
+
+Index a codebase and generate wiki documentation. This is the starting point.
+
+**Single repo:**
+
+```bash
+cd your-project
+repowise init
+```
+
+**Multi-repo workspace:**
+
+```bash
+cd my-workspace/ # parent dir containing multiple git repos
+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 `CLAUDE.md`, registers MCP server and Claude Code hooks
+
+In workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (co-changes, contracts, package deps), workspace CLAUDE.md generation.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--provider` | LLM provider: `anthropic`, `openai`, `gemini`, `ollama`, `mock` |
+| `--model` | Model name override (e.g., `claude-sonnet-4-6`) |
+| `--embedder` | Embedder for semantic search: `gemini`, `openai`, `mock` |
+| `--index-only` | Skip LLM generation. Only parse, build graph, and index git. Free. |
+| `--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: 5). |
+| `--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). |
+| `--follow-renames` | Track file renames in git history. |
+| `--no-claude-md` | Don't generate `CLAUDE.md`. |
+| `--yes / -y` | Skip confirmation prompts. |
+
+**Examples:**
+
+```bash
+repowise init # interactive
+repowise init --provider anthropic --yes # automated
+repowise init --index-only # free, no LLM
+repowise init --dry-run # preview cost
+repowise init --test-run # quick test (10 files)
+repowise init -x vendor/ -x "*.gen.go" # exclude patterns
+repowise init --include-submodules # include submodules
+repowise init . # workspace mode
+repowise init . --index-only -x "node_modules/" # workspace, no LLM
+```
+
+---
+
+### `repowise update [PATH]`
+
+Incrementally update wiki pages for files changed since the last sync.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--provider` | Override LLM provider for this run |
+| `--model` | Override model |
+| `--since` | Git ref to diff from (overrides `state.json`) |
+| `--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 |
+| `--repo` | Update a specific workspace repo by alias |
+
+**Examples:**
+
+```bash
+repowise update # diff since last sync
+repowise update --dry-run # preview
+repowise update --since v1.0.0 # diff from a tag
+repowise update --workspace # all workspace repos
+repowise update --repo backend # specific workspace repo
+```
+
+---
+
+### `repowise serve [PATH]`
+
+Start the API server and web UI.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--port` | API server port (default: 7337) |
+| `--host` | Host to bind to (default: 127.0.0.1) |
+| `--workers` | Uvicorn workers (default: 1) |
+| `--ui-port` | Web UI port (default: 3000) |
+| `--no-ui` | Start API server only |
+
+```bash
+repowise serve # API + Web UI
+repowise serve --no-ui # API only
+repowise serve --port 8080 --ui-port 8081
+```
+
+---
+
+### `repowise watch [PATH]`
+
+Watch for file changes and auto-update wiki pages. Press `Ctrl+C` to stop.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--provider` | LLM provider |
+| `--model` | Model override |
+| `--debounce` | Delay in ms after last change (default: 2000) |
+| `--workspace` | Watch all workspace repos |
+
+```bash
+repowise watch # single repo
+repowise watch --debounce 5000 # 5s debounce
+repowise watch --workspace # all workspace repos
+```
+
+---
+
+## Query Commands
+
+### `repowise search QUERY [PATH]`
+
+Search wiki pages by keyword, meaning, or symbol name.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--mode` | `fulltext` (default), `semantic`, `symbol` |
+| `--limit` | Max results (default: 10) |
+
+```bash
+repowise search "rate limiting"
+repowise search "how are errors handled" --mode semantic
+repowise search "AuthService" --mode symbol
+```
+
+---
+
+### `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?"
+```
+
+---
+
+### `repowise status [PATH]`
+
+Show wiki sync state, page statistics, and coverage.
+
+```bash
+repowise status # single repo
+repowise status --workspace # all workspace repos
+```
+
+---
+
+## Analysis Commands
+
+### `repowise dead-code [PATH]`
+
+Detect dead and unused code.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--min-confidence` | Minimum confidence threshold (default: 0.4) |
+| `--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 |
+
+```bash
+repowise dead-code
+repowise dead-code --safe-only --min-confidence 0.8
+repowise dead-code --format json
+repowise dead-code resolve <id> # mark resolved / false positive
+```
+
+---
+
+### `repowise decision`
+
+Manage architectural decision records.
+
+**Subcommands:**
+
+```bash
+repowise decision list [PATH] # list decisions
+repowise decision show ID [PATH] # full details
+repowise decision add [PATH] # interactive add
+repowise decision confirm ID [PATH] # confirm a proposal
+repowise decision dismiss ID [PATH] # delete a proposal
+repowise decision deprecate ID [PATH] # mark deprecated
+repowise decision health [PATH] # health dashboard
+```
+
+**List options:**
+
+| Flag | Description |
+|------|-------------|
+| `--status` | `active`, `proposed`, `deprecated`, `superseded`, `all` |
+| `--source` | `git_archaeology`, `inline_marker`, `readme_mining`, `cli`, `all` |
+| `--proposed` | Shortcut for `--status proposed` |
+| `--stale-only` | Only stale decisions |
+
+---
+
+### `repowise costs`
+
+Show LLM spend tracking.
+
+```bash
+repowise costs # total spend
+repowise costs --by operation # grouped by operation
+repowise costs --by model # grouped by model
+repowise costs --by day # grouped by day
+```
+
+---
+
+## Workspace Commands
+
+### `repowise workspace list`
+
+Show all repos in the workspace with their index status.
+
+### `repowise workspace add <path>`
+
+Add a new repo to an existing workspace and index it.
+
+```bash
+repowise workspace add ../new-service --alias api-gateway
+```
+
+### `repowise workspace remove <alias>`
+
+Remove a repo from the workspace (does not delete files).
+
+### `repowise workspace scan`
+
+Re-scan the workspace directory for new repos not yet added.
+
+### `repowise workspace set-default <alias>`
+
+Change which repo is the default for MCP queries.
+
+See [Workspaces](WORKSPACES.md) for the full multi-repo guide.
+
+---
+
+## Auto-Sync Commands
+
+### `repowise hook install`
+
+Install a post-commit git hook that runs `repowise update` in the background after every commit.
+
+```bash
+repowise hook install # current repo
+repowise hook install --workspace # all workspace repos
+```
+
+### `repowise hook status`
+
+Check if hooks are installed.
+
+```bash
+repowise hook status
+repowise hook status --workspace
+```
+
+### `repowise hook uninstall`
+
+Remove the post-commit hook.
+
+```bash
+repowise hook uninstall
+repowise hook uninstall --workspace
+```
+
+See [Auto-Sync](AUTO_SYNC.md) for all sync methods (hooks, file watcher, webhooks, polling).
+
+---
+
+## Utility Commands
+
+### `repowise mcp [PATH]`
+
+Start the MCP server for AI editor integration.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--transport` | `stdio` (default, for editors) or `sse` (for web clients) |
+| `--port` | Port for SSE transport (default: 7338) |
+
+```bash
+repowise mcp --transport stdio # for Claude Code, Cursor, etc.
+repowise mcp --transport sse --port 7338 # for web clients
+```
+
+See [MCP Tools](MCP_TOOLS.md) for all 7 exposed tools.
+
+---
+
+### `repowise generate-claude-md [PATH]`
+
+Generate or update `CLAUDE.md` with codebase intelligence. Custom instructions at the top are preserved.
+
+```bash
+repowise generate-claude-md
+repowise generate-claude-md -o custom-path.md
+repowise generate-claude-md --stdout
+```
+
+---
+
+### `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/
+```
+
+---
+
+### `repowise reindex [PATH]`
+
+Rebuild vector search index from existing wiki pages.
+
+```bash
+repowise reindex
+repowise reindex --embedder gemini --batch-size 50
+```
+
+---
+
+### `repowise doctor [PATH]`
+
+Run health checks on the wiki setup.
+
+```bash
+repowise doctor
+repowise doctor --repair # fix detected store mismatches
+```
+
+---
+
+### `repowise augment`
+
+Hook-driven context enrichment engine. Not meant to be called manually — invoked by Claude Code hooks installed during `repowise init`.
diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md
new file mode 100644
index 000000000..45bc7569a
--- /dev/null
+++ b/docs/MCP_TOOLS.md
@@ -0,0 +1,230 @@
+# MCP Tools Reference
+
+repowise exposes 7 tools via the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). These tools give AI coding assistants (Claude Code, Cursor, Cline, Windsurf) structured access to your codebase intelligence — dependency graph, git history, documentation, and architectural decisions.
+
+**Start the MCP server:**
+
+```bash
+repowise mcp --transport stdio # for Claude Code, Cursor, etc.
+repowise mcp --transport sse --port 7338 # for web clients
+```
+
+**Auto-setup for Claude Code:** `repowise init` automatically registers the MCP server and installs proactive hooks. No manual configuration needed.
+
+---
+
+## Tool Overview
+
+| Tool | Purpose | Typical use |
+|------|---------|-------------|
+| `get_overview` | Architecture summary | First call on any unfamiliar codebase |
+| `get_answer` | One-call RAG Q&A | First call on any code question |
+| `get_context` | Rich context for targets | Before reading or modifying code |
+| `search_codebase` | Semantic search | Discovering code by topic |
+| `get_risk` | Modification risk | Before changing hotspot files |
+| `get_why` | Architectural decisions | Before structural changes |
+| `get_dead_code` | Unreachable code | Cleanup tasks |
+
+---
+
+## `get_overview`
+
+Architecture summary, module map, entry points, git health, and community summary.
+
+**Parameters:** None required.
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `repo` | string | *(workspace only)* Target repo alias, or `"all"` |
+
+**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).
+
+**When to use:** First call on any unfamiliar codebase. Gives the agent a mental map before diving into specifics.
+
+**Example call:**
+
+```
+get_overview()
+```
+
+---
+
+## `get_answer`
+
+One-call RAG: retrieves over the wiki, gates synthesis on confidence, and returns a cited 2–5 sentence answer.
+
+**Parameters:**
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `question` | string | Yes | Natural language question about the codebase |
+| `repo` | string | No | *(workspace only)* Target repo alias |
+
+**Returns:** A synthesized answer with file/symbol citations and a confidence label (`high`, `medium`, `low`). High-confidence answers can be cited directly. Low-confidence answers return ranked wiki excerpts instead.
+
+**When to use:** First call on any code question. Collapses search → read → reason into one round-trip. If confidence is low, follow up with `search_codebase` to discover candidate pages.
+
+**Example call:**
+
+```
+get_answer(question="How does the authentication flow work?")
+```
+
+---
+
+## `get_context`
+
+The workhorse tool. Returns docs, symbols, ownership, freshness, and community membership for any combination of files, modules, or symbols.
+
+**Parameters:**
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `targets` | list[string] | Yes | File paths, module names, or symbol IDs. Batch multiple targets in one call. |
+| `include` | list[string] | No | Additional data to include: `"source"` (symbol body), `"callers"` (who calls this), `"callees"` (what this calls), `"metrics"` (PageRank, centrality), `"community"` (cluster membership) |
+| `compact` | boolean | No | Default `true`. Set `false` for full structure block and importer list. |
+| `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` |
+
+**Returns per target:** Documentation summary, symbols defined, ownership percentages, freshness score, co-change partners, architectural decisions governing the file. With `include` options: source code, call graph, graph metrics, community membership.
+
+**When to use:** Before reading or modifying code. Pass all relevant targets in one call to minimize round-trips. In workspace mode, enriched with cross-repo co-change and contract data.
+
+**Example calls:**
+
+```
+get_context(targets=["src/auth/middleware.ts"])
+get_context(targets=["middleware", "api/routes", "payments"], include=["callers", "metrics"])
+get_context(targets=["src/auth"], compact=false, include=["community"])
+```
+
+---
+
+## `search_codebase`
+
+Semantic search over the full wiki. Natural language queries.
+
+**Parameters:**
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `query` | string | Yes | Natural language search query |
+| `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` to search across workspace |
+
+**Returns:** Ranked wiki pages with relevance scores, snippets, and file paths.
+
+**When to use:** When `get_answer` returned low confidence and you need to discover candidate pages by topic. Also useful for broad exploration ("how do we handle retries?", "payment processing flow").
+
+In workspace mode, searches across all repos and merges results.
+
+**Example call:**
+
+```
+search_codebase(query="rate limit OR throttle OR retry")
+```
+
+---
+
+## `get_risk`
+
+Modification risk assessment for files or a set of changed files.
+
+**Parameters:**
+
+| 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 |
+| `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.
+
+**When to use:** Before modifying files — especially hotspots. Understand what could break, who to involve in review, and whether tests cover the affected area.
+
+**Example calls:**
+
+```
+get_risk(targets=["src/auth/middleware.ts"])
+get_risk(changed_files=["src/api/routes.ts", "src/middleware/cors.ts"])
+```
+
+---
+
+## `get_why`
+
+Architectural decision intelligence. Three modes depending on parameters.
+
+**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 |
+
+**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
+
+**Returns:** Matching decision records with title, rationale, alternatives considered, affected files, staleness score. Health mode returns stale decisions, conflicts, and ungoverned hotspots.
+
+**When to use:** Before architectural changes — understand existing intent and constraints. After changes — record new decisions.
+
+**Example calls:**
+
+```
+get_why(query="rate limiting")
+get_why(query="src/payments/processor.ts")
+get_why()
+```
+
+---
+
+## `get_dead_code`
+
+Unreachable code sorted by confidence tier with cleanup impact estimates.
+
+**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.
+
+**Example calls:**
+
+```
+get_dead_code()
+get_dead_code(min_confidence=0.8, include_internals=true)
+```
+
+---
+
+## Workspace Mode
+
+In 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`)
+
+The MCP server automatically enriches responses with cross-repo intelligence:
+- **Co-change partners** from other repos surfaced in `get_context` and `get_risk`
+- **API contract links** (HTTP, gRPC, topics) between repos
+- **Package dependencies** between repos
+
+---
+
+## Proactive Hooks (Complementary)
+
+In addition to the 7 MCP tools, `repowise init` installs Claude Code hooks that provide **passive, automatic** context enrichment:
+
+- **PreToolUse** — every `Grep`/`Glob` call is enriched with graph context (symbols, importers, dependencies, git signals) at ~24ms latency
+- **PostToolUse** — after git commits, the agent is notified when the wiki is stale
+
+Hooks fire automatically on every search. MCP tools are for deeper, on-demand investigation. See [Auto-Sync](AUTO_SYNC.md) for details.
diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md
index fc82355b2..18d0adfee 100644
--- a/docs/QUICKSTART.md
+++ b/docs/QUICKSTART.md
@@ -73,6 +73,8 @@ If Node.js 20+ is installed, the web UI starts automatically. Otherwise, use Doc
repowise mcp --transport stdio
```
+> **Automatic for Claude Code:** `repowise init` already registers the MCP server and installs PreToolUse/PostToolUse hooks in `~/.claude/settings.json`. Every `Grep`/`Glob` call is automatically enriched with graph context (importers, dependencies, symbols, git signals). After git commits, the agent is notified when the wiki is stale.
+
## 5. Keep It in Sync
After pulling changes or editing code:
@@ -81,17 +83,47 @@ After pulling changes or editing code:
repowise update
```
+Or install a post-commit hook for automatic sync:
+
+```bash
+repowise hook install
+```
+
Or run continuous sync while you work:
```bash
repowise watch
```
+See [Auto-Sync](AUTO_SYNC.md) for all sync methods (hooks, file watcher, GitHub/GitLab webhooks, polling).
+
+---
+
+## Multi-Repo Workspace
+
+If your project spans multiple repos, initialize a workspace instead:
+
+```bash
+cd my-workspace/ # parent dir containing backend/, frontend/, shared-libs/
+repowise init . # scans for git repos, indexes each, runs cross-repo analysis
+```
+
+Repowise will scan for git repos, prompt you to select which to index, and run cross-repo analysis (co-changes, API contracts, package dependencies). The MCP server serves all repos from a single instance.
+
+```bash
+repowise workspace list # show repos and their status
+repowise workspace add ../new-svc # add a repo
+repowise update --workspace # update all stale repos
+repowise hook install --workspace # install post-commit hooks for all repos
+```
+
+Full guide: [Workspaces](WORKSPACES.md)
+
---
## Web UI
-Repowise includes a full web dashboard with a repository overview, wiki browser, interactive dependency graph, codebase chat, search, code ownership, hotspots, and dead code detection. The overview page shows a health score, attention items, language breakdown, ownership treemap, and quick actions.
+Repowise includes a full web dashboard with a repository overview, wiki browser, interactive dependency graph, codebase chat, search, code ownership, hotspots, and dead code detection. In workspace mode, additional pages show a workspace dashboard, cross-repo API contracts, and co-change pairs. The overview page shows a health score, attention items, language breakdown, ownership treemap, quick actions, and a "Graph Intelligence" section with architectural communities and execution flow traces.
### With Node.js installed
@@ -151,5 +183,9 @@ REPOWISE_API_URL=http://localhost:7337 npm run dev --workspace packages/web
## What's Next
-- **[User Guide](USER_GUIDE.md)** — full CLI reference (all 13 commands with every flag), web UI features, MCP setup, common workflows, and troubleshooting
-- **[Architecture](ARCHITECTURE.md)** — how repowise is built internally
+- **[User Guide](USER_GUIDE.md)** — full CLI reference, web UI features, MCP setup, common workflows, and troubleshooting
+- **[CLI Reference](CLI_REFERENCE.md)** — every command with every flag
+- **[MCP Tools](MCP_TOOLS.md)** — all 7 MCP tools with parameters and examples
+- **[Workspaces](WORKSPACES.md)** — multi-repo workspace setup and cross-repo intelligence
+- **[Auto-Sync](AUTO_SYNC.md)** — hooks, file watcher, webhooks, polling
+- **[Architecture](architecture/ARCHITECTURE.md)** — how repowise is built internally
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 692fbf2ed..9987c8f5b 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -22,11 +22,15 @@ Everything you need to know to install, use, and get the most out of repowise.
- [reindex](#repowise-reindex)
- [status](#repowise-status)
- [doctor](#repowise-doctor)
+ - [workspace](#repowise-workspace)
+ - [hook](#repowise-hook)
4. [Web UI](#web-ui)
5. [MCP Integration with AI Editors](#mcp-integration-with-ai-editors)
-6. [Environment Variables](#environment-variables)
-7. [Common Workflows](#common-workflows)
-8. [Troubleshooting](#troubleshooting)
+6. [Proactive Context Enrichment (Hooks)](#proactive-context-enrichment-hooks)
+7. [Auto-Sync](#auto-sync)
+8. [Environment Variables](#environment-variables)
+9. [Common Workflows](#common-workflows)
+10. [Troubleshooting](#troubleshooting)
---
@@ -315,23 +319,21 @@ This is how you connect repowise to Claude Code, Cursor, Cline, Windsurf, and ot
| `--transport` | Protocol: `stdio` (default, for editors) or `sse` (for web clients) |
| `--port` | Port for SSE transport (default: 7338) |
-**MCP tools exposed (11 tools):**
+**MCP tools exposed (7 tools):**
| Tool | What it does |
|------|-------------|
+| `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_symbol` | Resolve a qualified symbol id (`path::Class::method`) to its source body, signature, and docstring |
-| `get_overview` | Repository architecture summary, key modules, entry points, git health |
-| `get_context` | Complete context for files/modules/symbols — docs, ownership, decisions, freshness. Defaults to `compact=True`; pass `compact=False` for the full structure block and importer list. |
-| `get_risk` | Modification risk assessment — hotspot score, dependents, bus factor, trend |
-| `get_why` | Why code is structured the way it is — architectural decisions, git archaeology |
-| `search_codebase` | Semantic search over wiki with git freshness boosting |
-| `get_dependency_path` | Find how two modules connect through the dependency graph |
-| `get_dead_code` | Tiered dead code report grouped by confidence |
-| `get_architecture_diagram` | Mermaid diagram with optional churn heat map |
-| `annotate_file` | Attach human-authored notes to a wiki page — survives re-indexing |
-
-See [MCP Integration](#mcp-integration-with-ai-editors) for setup instructions.
+| `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. |
+| `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_dead_code` | Tiered dead code report grouped by confidence with cleanup impact estimates |
+
+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)
---
@@ -550,6 +552,56 @@ Checks:
---
+### `repowise workspace`
+
+Manage multi-repo workspaces. See [Workspaces](WORKSPACES.md) for the full guide.
+
+**Subcommands:**
+
+```bash
+repowise workspace list # Show all repos with index status
+repowise workspace add <path> [--alias NAME] # Add a repo to the workspace
+repowise workspace remove <alias> # Remove a repo (doesn't delete files)
+repowise workspace scan # Re-scan for new repos
+repowise workspace set-default <alias> # Change the default repo for MCP queries
+```
+
+**Examples:**
+
+```bash
+# Initialize a workspace
+cd my-workspace/
+repowise init .
+
+# Add a repo that lives outside the workspace directory
+repowise workspace add /path/to/external-repo --alias api-gateway
+
+# Update all workspace repos
+repowise update --workspace
+
+# Update just one repo
+repowise update --repo backend
+```
+
+---
+
+### `repowise hook`
+
+Manage post-commit git hooks that auto-sync the wiki after every commit.
+
+```bash
+repowise hook install # Install hook for current repo
+repowise hook install --workspace # Install for all workspace repos
+repowise hook status # Check if hooks are installed
+repowise hook status --workspace # Check all workspace repos
+repowise hook uninstall # Remove the hook
+repowise 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.
+
+---
+
## Web UI
Repowise includes a full web dashboard built with Next.js, React, and D3.js.
@@ -635,7 +687,7 @@ A single-page dashboard for each repository that aggregates key health signals.
- **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
-The overview page degrades gracefully — each data section loads independently, so partial data (e.g., missing git metadata) still renders a useful dashboard.
+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.
**Wiki Browser** (`/repos/[id]/wiki/...`)
The heart of repowise. Browse AI-generated documentation for every file and module. Each page includes:
@@ -644,6 +696,7 @@ The heart of repowise. Browse AI-generated documentation for every file and modu
- 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
**Dependency Graph** (`/repos/[id]/graph`)
Interactive force-directed graph rendered on HTML Canvas with D3.js. Handles 2000+ nodes. Six view modes:
@@ -654,13 +707,13 @@ Interactive force-directed graph rendered on HTML Canvas with D3.js. Handles 200
- **Hot files view** — commit activity heatmap
- **Full graph** — everything
-Supports pan, zoom, click-to-inspect, path finding between nodes, filtering by language, and PNG export.
+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.
**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.
**Symbol Index** (`/repos/[id]/symbols`)
-Searchable, sortable table of every extracted symbol (functions, classes, methods, interfaces). Click any row for the full signature, docstring, and source location.
+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.
**Documentation Coverage** (`/repos/[id]/coverage`)
Donut chart and table showing freshness breakdown. Regenerate stale pages directly from the UI.
@@ -683,6 +736,15 @@ Ask questions about your codebase in natural language. Streaming responses power
**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 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.
+
---
## MCP Integration with AI Editors
@@ -730,6 +792,112 @@ Once connected, your AI editor can:
---
+## Proactive Context Enrichment (Hooks)
+
+Repowise automatically enriches AI agent tool calls with codebase graph context via Claude Code hooks. This is installed automatically during `repowise init` — no manual configuration required.
+
+Unlike MCP tools (which agents must explicitly call), hooks fire on every search automatically. Every `Grep` or `Glob` an agent runs gets graph context injected alongside the results, without the agent having to think about it.
+
+### How it works
+
+#### PreToolUse Hook — Grep/Glob enrichment
+
+Whenever an AI agent runs `Grep` or `Glob`, repowise intercepts the call and queries the local `wiki.db` for each matching file. The enrichment is appended to the tool result before the agent sees it:
+
+| Field | What it tells the agent |
+|-------|------------------------|
+| **Symbols** | Functions, classes, and methods defined in the file |
+| **Imported by** | Which files depend on this file (reverse dependency) |
+| **Depends on** | What this file imports (forward dependency) |
+| **Git signals** | Hotspot status, bus factor, and owner |
+
+Average latency is ~24ms — well under the 500ms target. No LLM calls, no network requests — pure local SQLite queries against `wiki.db`.
+
+#### PostToolUse Hook — Git commit detection
+
+After 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`. If the wiki is out of date, the agent is notified:
+
+```
+Wiki is stale — run `repowise update` to refresh
+```
+
+This ensures agents are never silently working from outdated documentation.
+
+### Configuration
+
+Hooks are written to `~/.claude/settings.json` automatically during `repowise init`. The installed configuration:
+
+| Hook type | Matcher | Action |
+|-----------|---------|--------|
+| `PreToolUse` | `Grep\|Glob` | Query `wiki.db` and prepend graph context to the result |
+| `PostToolUse` | `Bash` | Check for git operations and notify if wiki is stale |
+
+Both hooks call the `repowise augment` CLI command internally. Hooks are designed for graceful failure — any error results in a silent exit so a repowise issue never breaks the agent.
+
+### CLI command
+
+```bash
+repowise augment # Not meant to be called manually — invoked by Claude Code hooks
+```
+
+### Sample enrichment output
+
+When an agent runs `Grep` or `Glob`, it sees its normal results followed by context like this:
+
+```
+[repowise] 2 related file(s) found:
+
+ packages/core/.../page_generator.py
+ Symbols: function:_now_iso, class:PageGenerator, method:__init__
+ Imported by: init_cmd.py, update_cmd.py, generation/__init__.py
+ Depends on: context_assembler.py, base.py, models.py
+ Git: HOTSPOT, bus-factor=1, owner=RaghavChamadiya
+
+ packages/cli/.../init_cmd.py
+ Symbols: function:_resolve_embedder, function:_register_mcp_with_claude
+ Imported by: reindex_cmd.py, search_cmd.py, main.py
+ Depends 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.
+
+### Relationship to MCP tools
+
+Hooks 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.
+
+For most day-to-day coding tasks, hooks provide sufficient context automatically. MCP tools remain the right choice for deeper investigation.
+
+---
+
+## Auto-Sync
+
+repowise supports five methods to keep your wiki in sync with code changes. See [Auto-Sync](AUTO_SYNC.md) for the full guide.
+
+| Method | Command | Best for |
+|--------|---------|----------|
+| **Post-commit hook** | `repowise hook install` | Set-and-forget local dev |
+| **File watcher** | `repowise watch` | Active development |
+| **GitHub webhook** | Server endpoint | Teams, CI/CD |
+| **GitLab webhook** | Server endpoint | Teams, CI/CD |
+| **Polling fallback** | Automatic with `repowise serve` | Safety net |
+
+### Quick setup
+
+```bash
+# Post-commit hook (recommended)
+repowise hook install
+repowise hook install --workspace # all workspace repos
+
+# File watcher
+repowise watch
+repowise watch --workspace # all workspace repos
+```
+
+---
+
## Environment Variables
| Variable | Required | Description |
@@ -746,13 +914,24 @@ Once connected, your AI editor can:
## Common Workflows
-### First-time setup for a new project
+### First-time setup for a single repo
```bash
pip install "repowise[anthropic]"
export ANTHROPIC_API_KEY="sk-ant-..."
cd /path/to/your-project
repowise init
+repowise hook install # auto-sync after every commit
+```
+
+### First-time setup for a multi-repo workspace
+
+```bash
+pip install "repowise[anthropic]"
+export ANTHROPIC_API_KEY="sk-ant-..."
+cd /path/to/workspace/ # parent dir with backend/, frontend/, etc.
+repowise init .
+repowise hook install --workspace
```
### Daily development workflow
@@ -764,6 +943,9 @@ repowise update
# Option B: Continuous sync while coding
repowise watch
+
+# Option C: Set-and-forget (if hook installed)
+# Just code and commit — the hook handles it
```
### Before a code review
diff --git a/docs/WORKSPACES.md b/docs/WORKSPACES.md
new file mode 100644
index 000000000..c4561650a
--- /dev/null
+++ b/docs/WORKSPACES.md
@@ -0,0 +1,305 @@
+# Workspaces — Multi-Repo Support
+
+Repowise 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.
+
+---
+
+## Table of Contents
+
+1. [When to Use Workspaces](#when-to-use-workspaces)
+2. [Quick Start](#quick-start)
+3. [How It Works](#how-it-works)
+4. [Workspace Commands](#workspace-commands)
+5. [Cross-Repo Intelligence](#cross-repo-intelligence)
+6. [Web UI](#web-ui)
+7. [MCP Integration](#mcp-integration)
+8. [File Layout](#file-layout)
+9. [FAQ](#faq)
+
+---
+
+## When to Use Workspaces
+
+Use a workspace when your project spans multiple git repositories that are related:
+
+- A **backend + frontend** in separate repos
+- A **monorepo root** with standalone service repos alongside it
+- **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.
+
+---
+
+## Quick Start
+
+### 1. Organize your repos
+
+Put related repos under a common parent directory:
+
+```
+my-workspace/
+ backend/ # git repo
+ frontend/ # git repo
+ shared-libs/ # git repo
+```
+
+Or, if your workspace root is itself a git repo (e.g., a monorepo with sub-repos):
+
+```
+my-project/ # git repo (monorepo)
+ .git/
+ backend/ # git repo
+ frontend/ # git repo
+```
+
+### 2. Initialize the workspace
+
+```bash
+cd my-workspace
+repowise init .
+```
+
+Repowise will:
+
+1. **Scan** for git repositories (up to 3 levels deep)
+2. **Prompt you to select** which repos to index
+3. **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
+6. **Generate documentation** for each repo (unless `--index-only`)
+7. **Run cross-repo analysis** — co-changes, API contracts, package deps
+8. **Register MCP servers** with Claude Desktop and Claude Code
+
+### 3. Explore
+
+```bash
+# Check workspace status
+repowise status --workspace
+
+# List workspace repos
+repowise workspace list
+
+# Start the web UI
+repowise serve
+
+# Search across all repos
+repowise search "authentication flow"
+```
+
+---
+
+## How It Works
+
+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.
+
+### Single-Repo vs Workspace
+
+| Feature | Single-Repo | Workspace |
+|---------|-------------|-----------|
+| Per-repo docs, graph, search | Yes | Yes (for each repo) |
+| Co-change detection | Within repo | Within + across repos |
+| API contract extraction | No | Yes (HTTP, gRPC, topics) |
+| Package dependency mapping | No | Yes |
+| Web UI | Repo pages | Repo pages + workspace dashboard |
+| MCP | One server per repo | One server, all repos |
+
+---
+
+## Workspace Commands
+
+### `repowise init .`
+
+Initialize a workspace in the current directory. Scans for git repos, prompts for selection, and indexes everything.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--index-only` | Parse and analyze without LLM generation (free) |
+| `-x, --exclude` | Glob patterns to exclude (e.g., `-x "node_modules/"`) |
+| `--yes` | Skip confirmation prompts |
+| `--concurrency N` | Max concurrent file parses (default: auto) |
+
+**Example:**
+
+```bash
+repowise init . -x "node_modules/" -x "*.lock" -x "vendor/"
+```
+
+### `repowise workspace list`
+
+Show all repos in the workspace with their index status.
+
+```bash
+repowise workspace list
+```
+
+### `repowise workspace add <path>`
+
+Add a new repo to an existing workspace and index it.
+
+```bash
+repowise workspace add ../new-service --alias api-gateway
+```
+
+### `repowise workspace remove <alias>`
+
+Remove a repo from the workspace (does not delete files).
+
+```bash
+repowise workspace remove api-gateway
+```
+
+### `repowise workspace scan`
+
+Re-scan the workspace directory for new repos that haven't been added yet.
+
+```bash
+repowise workspace scan
+```
+
+### `repowise workspace set-default <alias>`
+
+Change which repo is the default for MCP queries.
+
+```bash
+repowise workspace set-default backend
+```
+
+---
+
+## Cross-Repo Intelligence
+
+When you initialize a workspace with 2+ repos, repowise runs three types of cross-repo analysis:
+
+### Co-Change Detection
+
+Analyzes git history across repos to find files that frequently change together. For example, if `backend/api/routes.py` and `frontend/src/api/client.ts` are always modified in the same time window, they get a high co-change score.
+
+Useful for:
+- Understanding implicit dependencies between repos
+- Knowing what frontend files to check when a backend API changes
+- Identifying tightly coupled components
+
+### API Contract Extraction
+
+Scans source files for HTTP route handlers, gRPC service definitions, and message topic publishers/subscribers. Then matches providers (servers) with consumers (clients) across repos.
+
+**Supported patterns:**
+
+| 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 |
+
+### Package Dependency Scanning
+
+Reads package manifests (`package.json`, `pyproject.toml`, `go.mod`, `pom.xml`, etc.) to detect when one repo depends on another as a package.
+
+---
+
+## Web UI
+
+Start the web server:
+
+```bash
+repowise serve
+```
+
+In 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
+- **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
+
+The sidebar shows all workspace repos under **Repositories**. Click any repo to access its full per-repo pages (overview, docs, graph, search, hotspots, etc.).
+
+---
+
+## MCP Integration
+
+Workspace 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
+- **Repo parameter** — most tools accept an optional `repo` parameter to target a specific repo, or `"all"` to query across the workspace
+
+---
+
+## File Layout
+
+After workspace init, your directory looks like:
+
+```
+my-workspace/
+ .repowise-workspace.yaml # Workspace config (repo list, default, settings)
+ .repowise-workspace/ # Shared cross-repo data
+ cross_repo_edges.json # Co-change pairs and package deps
+ contracts.json # Extracted API contracts and links
+ .claude/
+ CLAUDE.md # Workspace-level CLAUDE.md for AI editors
+ backend/
+ .repowise/ # Per-repo index data
+ wiki.db # SQLite database (pages, graph, symbols, git)
+ lancedb/ # Vector embeddings
+ config.yaml # Repo-level config
+ mcp.json # MCP server config
+ frontend/
+ .repowise/
+ wiki.db
+ lancedb/
+ ...
+```
+
+### What goes in `.gitignore`
+
+Add these to your `.gitignore`:
+
+```gitignore
+.repowise/
+.repowise-workspace/
+.repowise-workspace.yaml
+```
+
+The workspace config and data are local — they reference absolute paths and contain generated analysis that should be rebuilt per-machine.
+
+---
+
+## FAQ
+
+### Can I add repos that live outside the workspace directory?
+
+Yes. Use `repowise workspace add /path/to/external-repo`. The path will be stored relative to the workspace root if possible, or as an absolute path otherwise.
+
+### What happens if I run `repowise init` (without `.`) in a workspace?
+
+It runs in single-repo mode for the current directory, ignoring the workspace. Use `repowise init .` from the workspace root to initialize or re-initialize the workspace.
+
+### Can I have nested workspaces?
+
+No. Repowise searches upward for `.repowise-workspace.yaml` and uses the first one it finds. Nested workspace configs are not supported.
+
+### How do I update a workspace after code changes?
+
+```bash
+repowise update # Update the primary repo
+repowise update --workspace # Update all workspace repos
+```
+
+Or use watch mode for automatic updates:
+
+```bash
+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.
+
+### Does the MCP server handle multiple repos?
+
+Yes. A single MCP server instance serves all workspace repos. It uses lazy-loading with LRU eviction (max 5 repos loaded simultaneously) to manage memory. The default repo is always kept in memory.
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md
index 7a394df92..683b86e3b 100644
--- a/docs/architecture/ARCHITECTURE.md
+++ b/docs/architecture/ARCHITECTURE.md
@@ -111,13 +111,14 @@ repowise/
│ │ ├── src/repowise/core/
│ │ │ ├── ingestion/
│ │ │ │ ├── traverser.py # file tree walking + gitignore + per-dir .repowiseIgnore + extra exclude patterns
-│ │ │ │ ├── parser.py # ASTParser — one class, all languages
+│ │ │ │ ├── parser.py # ASTParser — one class, all languages; _extract_calls(), _extract_import_bindings()
│ │ │ │ ├── parsers/ # per-language parser helpers
-│ │ │ │ ├── graph.py # NetworkX dep graph builder
+│ │ │ │ ├── graph.py # NetworkX dep graph builder; add_file(), _resolve_calls(), file_subgraph()
+│ │ │ │ ├── call_resolver.py # CallResolver — 3-tier call resolution engine (NEW)
│ │ │ │ ├── change_detector.py # git diff + change propagation
│ │ │ │ ├── git_indexer.py # git history mining → git_metadata table
│ │ │ │ ├── special_handlers.py # OpenAPI, Protobuf, GraphQL, Dockerfile, CI YAML
-│ │ │ │ └── models.py # ParsedFile, FileInfo, Symbol, Import, etc.
+│ │ │ │ └── models.py # ParsedFile, FileInfo, Symbol, Import, CallSite, NamedBinding, EdgeType, etc.
│ │ │ ├── analysis/
│ │ │ │ └── dead_code.py # dead code detection (graph + SQL, no LLM)
│ │ │ ├── generation/
@@ -276,12 +277,17 @@ the configured embedder (Gemini or OpenAI). No LLM calls — only embedding API
**Answers: how are things connected, and how important are they.**
-The dependency graph is a directed multigraph where nodes are files and symbols,
-and edges are relationships (`imports`, `calls`, `inherits`, `implements`, etc.).
+The dependency graph is a two-tier directed graph where **file nodes** represent source
+files and **symbol nodes** represent individual functions, classes, and methods. Edges
+include `imports`, `DEFINES`, `HAS_METHOD`, `CALLS` (with confidence 0.0–1.0),
+`inherits`, `implements`, and `co_changes`. `CALLS` edges are built by `CallResolver`
+using 3-tier resolution; all others are built by `GraphBuilder` during AST ingestion.
-It is built by the `ASTParser` + `GraphBuilder` during ingestion and persisted to
-`.repowise/graph.json` (for repos ≤ 30K nodes) or the `graph_nodes`/`graph_edges`
-SQL tables (for larger repos, using the `networkit` library as a drop-in).
+It is built by the `ASTParser` + `GraphBuilder` + `CallResolver` during ingestion and
+persisted to `.repowise/graph.json` (for repos ≤ 30K nodes) or the `graph_nodes`/`graph_edges`
+SQL tables (for larger repos, using the `networkit` library as a drop-in). The `graph_nodes`
+table includes a `kind` column (file, symbol, package, external) and `confidence` column;
+`graph_edges` includes a `confidence` column for `CALLS` edges (Alembic migration `0015`).
The graph is used for:
@@ -290,8 +296,8 @@ The graph is used for:
richer context is available via RAG when the importing file is generated)
- **Change propagation** — when a file changes, walk the graph to find all
pages that reference its symbols and mark them as stale
-- **PageRank** — identifies the most central, important symbols; these get
- "spotlight" wiki pages and richer generation prompts
+- **PageRank** — runs on `file_subgraph()` (file + package nodes only) to identify
+ the most central files; these get "spotlight" wiki pages and richer generation prompts
- **SCC detection** — circular dependency clusters require a special generation
strategy (see [Section 5.3](#53-circular-dependencies))
- **Co-change edges** — temporal coupling from git history. Files that frequently
@@ -473,13 +479,15 @@ instead of tree-sitter.
**Node types:**
- `file` — every source file
-- `symbol` — every function, class, interface, etc.
+- `symbol` — every function, class, method, interface, etc. (added via `add_file()`)
- `package` — every package/module directory
- `external` — third-party packages (lightweight node, not fully documented)
**Edge types:**
- `imports` — file A imports from file B
-- `calls` — symbol A calls symbol B
+- `DEFINES` — file A defines symbol B
+- `HAS_METHOD` — class A has method B
+- `CALLS` — symbol A calls symbol B (with confidence score 0.0–1.0)
- `inherits` — class A extends class B
- `implements` — class A implements interface B
- `instantiates` — code in A creates an instance of B
@@ -490,6 +498,32 @@ instead of tree-sitter.
added by `GitIndexer` after graph construction). Weight = co-change count.
Filtered out of PageRank but included in change propagation and visualization.
+**Call resolution** is handled by the `CallResolver` module (`ingestion/call_resolver.py`),
+which runs after the static import graph is built. It operates in three tiers:
+
+1. **Same-file resolution** (confidence 0.95) — call target defined in the same file
+2. **Import-scoped resolution** (confidence 0.85–0.93) — target matched via named bindings
+ from the file's import list
+3. **Global unique match** (confidence 0.50) — target is unique across the whole repo
+
+Call sites are extracted by tree-sitter for all 7 supported languages (Python, TypeScript,
+JavaScript, Go, Rust, Java, C++) using per-language `.scm` query files. Results are stored
+as `CallSite` dataclasses and become `CALLS` edges in the graph.
+
+**Named binding resolution** (`NamedBinding` dataclass in `ingestion/models.py`) ensures
+that aliased imports, barrel re-exports, and namespace imports resolve to the correct
+definition site. The parser's `_extract_import_bindings()` produces bindings for each
+import statement, and `GraphBuilder.build()` populates `Import.resolved_file` from them.
+Barrel files (`__init__.py`, `index.ts`) are followed one hop to resolve re-exports.
+
+**Two-tier graph isolation:**
+
+Symbol nodes and their `DEFINES`/`HAS_METHOD`/`CALLS` edges are stored in the same
+`DiGraph` as file nodes, but `file_subgraph()` returns a view containing only `file`
+and `package` nodes. All file-level metrics (PageRank, betweenness, SCCs, Louvain)
+run on this subgraph so that the large number of symbol nodes does not distort centrality
+scores.
+
After graph construction, the builder computes:
- **PageRank** — nodes with high PageRank are central and well-connected.
diff --git a/docs/architecture/graph-algorithms.md b/docs/architecture/graph-algorithms.md
index 7b55e7e79..a468e00e5 100644
--- a/docs/architecture/graph-algorithms.md
+++ b/docs/architecture/graph-algorithms.md
@@ -6,13 +6,11 @@ This document covers every graph algorithm used in Repowise: what it does, the i
## The Foundation: What Is the Graph?
-Before any algorithm runs, Repowise builds a **directed graph** from your codebase.
+Before any algorithm runs, Repowise builds a **directed graph** from your codebase. The graph is two-tier: it contains both **file nodes** and **symbol nodes** in the same `networkx.DiGraph`, connected by different edge types.
-- Each **node** is a source file (e.g., `auth/login.py`)
-- Each **edge** is an import (e.g., `login.py` imports `utils.py` → edge from `login.py` to `utils.py`)
-- Edge direction matters: `A → B` means "A depends on B", not the other way around
+**File-level nodes** (e.g., `auth/login.py`) represent source files. **Symbol-level nodes** represent individual functions, classes, methods, and interfaces extracted by the AST parser.
-There are three types of edges:
+File-level edges:
| Edge type | Source | Example |
|-----------|--------|---------|
@@ -20,9 +18,21 @@ There are three types of edges:
| `co_changes` | Git co-change analysis | `auth.py` and `config.py` frequently change together |
| `framework` | Framework-aware synthetic edges | pytest conftest→tests, Django admin→models, FastAPI include_router→routers, Flask register_blueprint→blueprints |
+Symbol-level edges (all carry a `confidence` score from 0.0 to 1.0):
+
+| Edge type | Source | Example |
+|-----------|--------|---------|
+| `DEFINES` | GraphBuilder `add_file()` | `login.py` DEFINES `validate_token` |
+| `HAS_METHOD` | GraphBuilder `add_file()` | `AuthService` HAS_METHOD `login` |
+| `CALLS` | `CallResolver` (3-tier resolution) | `validate_token` CALLS `hash_password` |
+
Framework edges are detected automatically when the tech stack includes Django, FastAPI, Flask, or pytest. They capture real runtime dependencies that static import resolution misses (e.g., `conftest.py` fixtures are loaded by pytest, not imported directly by test files).
-This is the raw material. Every algorithm below operates on this graph.
+**`file_subgraph()` — keeping metrics accurate across both tiers**
+
+All centrality algorithms (PageRank, betweenness, SCCs, Louvain) operate on the file-level subgraph, not the full graph. `file_subgraph()` returns a view of the `DiGraph` containing only `file` and `package` nodes. Without this isolation, the large number of symbol nodes would inflate degree counts and distort every metric. Call `file_subgraph()` before running any file-level algorithm; call the full graph when you need symbol-level traversal.
+
+This is the raw material. Every algorithm below operates on the file subgraph unless otherwise noted.
---
@@ -134,15 +144,11 @@ except nx.PowerIterationFailedConvergence:
If PageRank doesn't converge, every file gets equal score `1/N`. This is safe — no file gets unfairly prioritized.
-### Why co-change edges are excluded
+### Why co-change edges and symbol edges are excluded
-Repowise's graph has two edge types:
-1. **Import edges**: `auth.py` imports `utils.py` (structural dependency)
-2. **Co-change edges**: `auth.py` and `config.py` often change in the same commit (behavioral correlation)
+Repowise's graph has several edge types. PageRank runs only on `imports` edges within the file subgraph. Why?
-PageRank runs only on import edges. Why?
-
-Co-change is noisy and doesn't indicate dependency. Examples of co-change that would corrupt PageRank:
+**Co-change** is noisy and doesn't indicate dependency. Examples of co-change that would corrupt PageRank:
- A developer renames a constant across 20 files in one commit. None of those files structurally depend on each other through that rename.
- Every bug fix touches `handler.py` and `test_handler.py`. The test file isn't architecturally important just because it changes alongside the handler.
@@ -150,6 +156,8 @@ Co-change is noisy and doesn't indicate dependency. Examples of co-change that w
If co-change edges fed into PageRank, files that happen to change alongside many others would appear "important" even when nothing imports them. PageRank should answer "if this file breaks, what else breaks?" — that's a structural question, answered only by import edges.
+**Symbol edges** (`DEFINES`, `HAS_METHOD`, `CALLS`) are also excluded from file-level PageRank for a different reason: they operate at a finer granularity than files. Including them would give outsized weight to files that define many small functions. `file_subgraph()` filters them out before any file-level metric runs. Symbol-level PageRank (when needed) runs on the full graph separately.
+
### How Repowise uses PageRank
1. **Documentation priority**: High PageRank files get wiki pages generated first. If budget is limited, the most depended-on files are documented.
diff --git a/docs/architecture/implementation-deep-dive.md b/docs/architecture/implementation-deep-dive.md
index 1b0ed3c5d..51976aaef 100644
--- a/docs/architecture/implementation-deep-dive.md
+++ b/docs/architecture/implementation-deep-dive.md
@@ -204,7 +204,21 @@ ParsedFile
### 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.
+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:
@@ -225,6 +239,8 @@ Go: "github.com/foo/bar" → match last segment "bar" by st
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?
diff --git a/packages/cli/src/repowise/cli/__init__.py b/packages/cli/src/repowise/cli/__init__.py
index f53d600ae..9283444b2 100644
--- a/packages/cli/src/repowise/cli/__init__.py
+++ b/packages/cli/src/repowise/cli/__init__.py
@@ -6,4 +6,4 @@ git signals, dead code detection, architectural decisions, and
AI-generated documentation.
"""
-__version__ = "0.2.3"
+__version__ = "0.3.0"
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd.py b/packages/cli/src/repowise/cli/commands/augment_cmd.py
new file mode 100644
index 000000000..4463db774
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd.py
@@ -0,0 +1,422 @@
+"""``repowise augment`` — hook-driven context enrichment for AI coding agents.
+
+Reads a Claude Code hook payload from stdin (JSON), queries the local wiki.db
+for graph context (importers, dependencies, symbols), and writes enriched
+context back to stdout as the hook response.
+
+Also handles PostToolUse events: detects git commits and notifies the agent
+when the wiki is stale.
+
+Design goals:
+ - Cold start < 500ms (lazy imports, minimal work)
+ - Graceful failure: any error → exit 0 with empty output
+ - No LLM calls, no network — pure local SQLite queries
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+
+import click
+
+
+def augment_command() -> None:
+ """Enrich AI agent tool calls with codebase graph context (hook mode)."""
+ try:
+ _run_augment()
+ except (SystemExit, KeyboardInterrupt):
+ raise
+ except Exception:
+ # Hooks must never fail — exit silently on any error.
+ sys.exit(0)
+
+
+def _run_augment() -> None:
+ """Main entry point — reads stdin, dispatches to pre/post handler."""
+ raw = sys.stdin.read()
+ if not raw.strip():
+ return
+
+ try:
+ payload = json.loads(raw)
+ except json.JSONDecodeError:
+ return
+
+ event = payload.get("hook_event_name", "")
+ tool_name = payload.get("tool_name", "")
+ tool_input = payload.get("tool_input", {})
+ cwd = payload.get("cwd", "")
+
+ if event == "PreToolUse" and tool_name in ("Grep", "Glob", "Bash"):
+ result = _handle_pre_tool_use(tool_name, tool_input, cwd)
+ if result:
+ _emit_response(event, result)
+
+ elif event == "PostToolUse" and tool_name == "Bash":
+ tool_output = payload.get("tool_output", {})
+ result = _handle_post_tool_use(tool_input, tool_output, cwd)
+ if result:
+ _emit_response(event, result)
+
+
+def _emit_response(event: str, context: str) -> None:
+ """Write the hook JSON response to stdout."""
+ response = {
+ "hookSpecificOutput": {
+ "hookEventName": event,
+ "additionalContext": context,
+ }
+ }
+ sys.stdout.write(json.dumps(response))
+ sys.stdout.flush()
+
+
+# ---------------------------------------------------------------------------
+# PreToolUse — enrich search/grep/glob with graph context
+# ---------------------------------------------------------------------------
+
+
+def _extract_search_pattern(tool_name: str, tool_input: dict) -> str | None:
+ """Extract the search pattern from the tool input."""
+ if tool_name == "Grep":
+ return tool_input.get("pattern")
+ if tool_name == "Glob":
+ return tool_input.get("pattern")
+ if tool_name == "Bash":
+ cmd = tool_input.get("command", "")
+ # Only augment grep/rg/find commands, not arbitrary bash
+ import re
+
+ m = re.search(r"\b(?:grep|rg|find|ag|ack)\b.*?['\"]([^'\"]+)['\"]", cmd)
+ if m:
+ return m.group(1)
+ # Also match: grep pattern (unquoted, first non-flag arg)
+ m = re.search(r"\b(?:grep|rg)\s+(?:-\S+\s+)*(\S+)", cmd)
+ if m and not m.group(1).startswith("-"):
+ return m.group(1)
+ return None
+
+
+def _handle_pre_tool_use(tool_name: str, tool_input: dict, cwd: str) -> str | None:
+ """Query the wiki DB for graph context related to the search pattern."""
+ pattern = _extract_search_pattern(tool_name, tool_input)
+ if not pattern:
+ return None
+
+ from pathlib import Path
+
+ repo_path = _find_repo_root(Path(cwd))
+ if repo_path is None:
+ return None
+
+ import asyncio
+
+ return asyncio.run(_query_graph_context(repo_path, pattern))
+
+
+async def _query_graph_context(repo_path: "Path", pattern: str) -> str | None:
+ """Run FTS + graph queries and format the enrichment context."""
+ from pathlib import Path as _Path
+
+ from repowise.core.persistence import (
+ FullTextSearch,
+ create_engine,
+ )
+ from repowise.core.persistence.database import resolve_db_url
+
+ db_path = repo_path / ".repowise" / "wiki.db"
+ if not db_path.exists():
+ return None
+
+ url = resolve_db_url(repo_path)
+ engine = create_engine(url)
+
+ try:
+ # Phase 1: FTS search to find relevant files
+ fts = FullTextSearch(engine)
+ try:
+ results = await fts.search(pattern, limit=5)
+ except Exception:
+ results = []
+
+ if not results:
+ # Fallback: try matching graph nodes by path pattern
+ results = await _search_nodes_by_path(engine, repo_path, pattern)
+ if not results:
+ return None
+
+ # Collect file paths from search results — prefer file-level pages
+ file_paths = []
+ for r in results:
+ target = getattr(r, "target_path", None) or getattr(r, "node_id", None)
+ if not target:
+ continue
+ # Skip non-file pages — they don't map to graph nodes
+ page_type = getattr(r, "page_type", "")
+ if page_type and page_type not in ("file", "file_page", "infra_page", "api_contract"):
+ continue
+ # Symbol spotlight pages have target_path like "file.py::SymbolName"
+ if "::" in target:
+ target = target.split("::")[0]
+ file_paths.append(target)
+
+ # Deduplicate while preserving order
+ seen: set[str] = set()
+ unique_paths = []
+ for fp in file_paths:
+ if fp not in seen:
+ seen.add(fp)
+ unique_paths.append(fp)
+ file_paths = unique_paths[:5]
+
+ if not file_paths:
+ # All FTS results were module-level — try path-based fallback
+ results = await _search_nodes_by_path(engine, repo_path, pattern)
+ file_paths = [r.node_id for r in results if hasattr(r, "node_id")][:5]
+
+ if not file_paths:
+ return None
+
+ # Phase 2: Batch graph queries for importers, dependencies, and symbols
+ from repowise.core.persistence import (
+ GraphEdge,
+ GraphNode,
+ WikiSymbol,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.crud import get_repository_by_path
+ from sqlalchemy import select
+
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await get_repository_by_path(session, str(repo_path))
+ if repo is None:
+ return None
+ repo_id = repo.id
+
+ # Importers: who imports these files? (limit 3 per file)
+ importers_stmt = select(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.target_node_id.in_(file_paths),
+ )
+ importers_result = await session.execute(importers_stmt)
+ importers_by_file: dict[str, list[str]] = {}
+ for edge in importers_result.scalars().all():
+ lst = importers_by_file.setdefault(edge.target_node_id, [])
+ if len(lst) < 3:
+ lst.append(edge.source_node_id)
+
+ # Dependencies: what do these files import?
+ deps_stmt = select(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.source_node_id.in_(file_paths),
+ )
+ deps_result = await session.execute(deps_stmt)
+ deps_by_file: dict[str, list[str]] = {}
+ for edge in deps_result.scalars().all():
+ lst = deps_by_file.setdefault(edge.source_node_id, [])
+ if len(lst) < 3:
+ lst.append(edge.target_node_id)
+
+ # Symbols: key symbols in these files
+ symbols_stmt = (
+ select(WikiSymbol)
+ .where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.file_path.in_(file_paths),
+ )
+ .order_by(WikiSymbol.start_line)
+ )
+ symbols_result = await session.execute(symbols_stmt)
+ symbols_by_file: dict[str, list] = {}
+ for sym in symbols_result.scalars().all():
+ lst = symbols_by_file.setdefault(sym.file_path, [])
+ if len(lst) < 5:
+ lst.append(sym)
+
+ # Hotspot info (best-effort — DB schema may not have all columns)
+ git_by_file: dict = {}
+ try:
+ from repowise.core.persistence.models import GitMetadata
+
+ git_stmt = select(GitMetadata).where(
+ GitMetadata.repository_id == repo_id,
+ GitMetadata.file_path.in_(file_paths),
+ )
+ git_result = await session.execute(git_stmt)
+ for gm in git_result.scalars().all():
+ git_by_file[gm.file_path] = gm
+ except Exception:
+ pass # git metadata is optional enrichment
+
+ # Phase 3: Format the enrichment text
+ lines = [f"[repowise] {len(file_paths)} related file(s) found:\n"]
+
+ for fp in file_paths[:5]:
+ lines.append(f" {fp}")
+
+ # Symbols
+ syms = symbols_by_file.get(fp, [])
+ if syms:
+ sym_strs = [f"{s.kind}:{s.name}" for s in syms]
+ lines.append(f" Symbols: {', '.join(sym_strs)}")
+
+ # Importers
+ imps = importers_by_file.get(fp, [])
+ if imps:
+ lines.append(f" Imported by: {', '.join(imps)}")
+
+ # Dependencies
+ deps = deps_by_file.get(fp, [])
+ if deps:
+ lines.append(f" Depends on: {', '.join(deps)}")
+
+ # Git signals
+ gm = git_by_file.get(fp)
+ if gm:
+ signals = []
+ if gm.is_hotspot:
+ signals.append("HOTSPOT")
+ if gm.bus_factor and gm.bus_factor <= 1:
+ signals.append(f"bus-factor={gm.bus_factor}")
+ if gm.primary_owner_name:
+ signals.append(f"owner={gm.primary_owner_name}")
+ if signals:
+ lines.append(f" Git: {', '.join(signals)}")
+
+ lines.append("")
+
+ return "\n".join(lines)
+
+ finally:
+ await engine.dispose()
+
+
+async def _search_nodes_by_path(engine, repo_path: "Path", pattern: str) -> list:
+ """Fallback: search GraphNode.node_id by LIKE pattern."""
+ from repowise.core.persistence import (
+ GraphNode,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.crud import get_repository_by_path
+ from sqlalchemy import select
+
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await get_repository_by_path(session, str(repo_path))
+ if repo is None:
+ return []
+ # Clean pattern for LIKE query: strip regex chars, use as substring
+ import re
+
+ clean = re.sub(r"[^\w/._-]", "", pattern)
+ if not clean:
+ return []
+
+ stmt = (
+ select(GraphNode)
+ .where(
+ GraphNode.repository_id == repo.id,
+ GraphNode.node_id.like(f"%{clean}%"),
+ )
+ .order_by(GraphNode.pagerank.desc())
+ .limit(5)
+ )
+ result = await session.execute(stmt)
+ return list(result.scalars().all())
+
+
+# ---------------------------------------------------------------------------
+# PostToolUse — detect git commits and flag stale wiki
+# ---------------------------------------------------------------------------
+
+_GIT_COMMIT_PATTERNS = (
+ "git commit",
+ "git merge",
+ "git rebase",
+ "git cherry-pick",
+ "git pull",
+)
+
+
+def _handle_post_tool_use(tool_input: dict, tool_output: dict, cwd: str) -> str | None:
+ """After a successful git commit, check if the wiki needs updating."""
+ # Only act on successful commands
+ exit_code = tool_output.get("exit_code")
+ if exit_code is None:
+ # Try stdout-based detection (some hook formats differ)
+ stdout = tool_output.get("stdout", "")
+ if "error" in stdout.lower() or "fatal" in stdout.lower():
+ return None
+ elif exit_code != 0:
+ return None
+
+ cmd = tool_input.get("command", "")
+ if not any(p in cmd for p in _GIT_COMMIT_PATTERNS):
+ return None
+
+ from pathlib import Path
+
+ repo_path = _find_repo_root(Path(cwd))
+ if repo_path is None:
+ return None
+
+ state_path = repo_path / ".repowise" / "state.json"
+ if not state_path.exists():
+ return None
+
+ try:
+ state = json.loads(state_path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ return None
+
+ last_sync = state.get("last_sync_commit")
+ if not last_sync:
+ return None
+
+ # Compare HEAD against last sync
+ try:
+ import subprocess
+
+ head = subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=str(repo_path),
+ capture_output=True,
+ text=True,
+ timeout=5,
+ ).stdout.strip()
+ except Exception:
+ return None
+
+ if head == last_sync:
+ return None
+
+ return (
+ "[repowise] Wiki is stale — last indexed at commit "
+ f"{last_sync[:8]}, HEAD is now {head[:8]}. "
+ "Run `repowise update` to refresh documentation and graph context."
+ )
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _find_repo_root(cwd: "Path") -> "Path | None":
+ """Walk up from cwd to find a directory with .repowise/."""
+ from pathlib import Path
+
+ current = Path(cwd).resolve()
+ for _ in range(20): # safety limit
+ if (current / ".repowise").is_dir():
+ return current
+ parent = current.parent
+ if parent == current:
+ break
+ current = parent
+ return None
diff --git a/packages/cli/src/repowise/cli/commands/claude_md_cmd.py b/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
index cf6f3567c..13f318919 100644
--- a/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
@@ -1,13 +1,15 @@
-"""repowise generate-claude-md — generate/update CLAUDE.md for a repository."""
+"""repowise generate-claude-md — generate/update CLAUDE.md for a repository or workspace."""
from __future__ import annotations
+import json
from pathlib import Path
import click
from repowise.cli.helpers import (
ensure_repowise_dir,
+ find_workspace_root,
get_db_url_for_repo,
run_async,
)
@@ -29,10 +31,22 @@ from repowise.cli.helpers import (
default=False,
help="Print generated content to stdout instead of writing a file.",
)
+ "--workspace",
+ "-w",
+ "workspace_mode",
+ is_flag=True,
+ default=False,
+ help=(
+ "Generate a workspace-level CLAUDE.md that includes cross-repo contracts, "
+ "co-changes, package dependencies, and per-repo summaries."
+ ),
+)
def claude_md_command(
path: str | None,
output_path: str | None,
to_stdout: bool,
+ workspace_mode: bool,
) -> None:
"""Generate or update CLAUDE.md with codebase intelligence context.
@@ -43,8 +57,22 @@ def claude_md_command(
- Repowise-managed section (between markers) — auto-updated from the index.
Run 'repowise init' or 'repowise update' to keep it current automatically.
+
+ Pass --workspace / -w to generate a workspace-level CLAUDE.md at the workspace
+ root instead of a per-repo file.
"""
- repo_path = Path(path).resolve() if path else Path.cwd()
+ start_path = Path(path).resolve() if path else Path.cwd()
+
+ if workspace_mode:
+ try:
+ content = _generate_workspace(start_path, output_path, to_stdout)
+ except Exception as exc:
+ raise click.ClickException(str(exc)) from exc
+ if to_stdout:
+ click.echo(content, nl=False)
+ return
+
+ repo_path = start_path
ensure_repowise_dir(repo_path)
try:
@@ -56,6 +84,11 @@ def claude_md_command(
click.echo(content, nl=False)
+# ---------------------------------------------------------------------------
+# Per-repo generation (original behaviour)
+# ---------------------------------------------------------------------------
+
+
async def _generate(
repo_path: Path,
output_path: str | None,
@@ -101,3 +134,136 @@ async def _generate(
click.echo(f".claude/CLAUDE.md updated: {written}")
return None
+
+
+# ---------------------------------------------------------------------------
+# Workspace generation
+# ---------------------------------------------------------------------------
+
+
+def _generate_workspace(
+ start_path: Path,
+ output_path: str | None,
+ to_stdout: bool,
+) -> str | None:
+ """Build and write (or render) a workspace-level CLAUDE.md."""
+ from repowise.cli.commands.status_cmd import _query_repo_counts
+ from repowise.core.generation.editor_files import (
+ WorkspaceClaudeMdGenerator,
+ WorkspaceEditorFileData,
+ WorkspaceRepoSummary,
+ )
+ from repowise.core.workspace.config import (
+ WORKSPACE_DATA_DIR,
+ WorkspaceConfig,
+ )
+ from repowise.core.workspace.cross_repo import CROSS_REPO_EDGES_FILENAME
+ from repowise.core.workspace.contracts import CONTRACTS_FILENAME
+
+ ws_root = find_workspace_root(start_path)
+ if ws_root is None:
+ raise click.ClickException(
+ "No .repowise-workspace.yaml found. "
+ "Run 'repowise init <workspace-dir>' first."
+ )
+
+ ws_config = WorkspaceConfig.load(ws_root)
+ data_dir = ws_root / WORKSPACE_DATA_DIR
+
+ # ------------------------------------------------------------------
+ # Load cross-repo edges (co-changes + package deps)
+ # ------------------------------------------------------------------
+ co_changes: list[dict] = []
+ package_deps: list[dict] = []
+ edges_file = data_dir / CROSS_REPO_EDGES_FILENAME
+ if edges_file.exists():
+ try:
+ overlay = json.loads(edges_file.read_text(encoding="utf-8"))
+ co_changes = overlay.get("co_changes", [])
+ package_deps = overlay.get("package_deps", [])
+ except Exception:
+ pass # non-fatal; workspace data may not exist yet
+
+ # Sort co-changes by frequency descending so the top entries are most useful
+ co_changes = sorted(co_changes, key=lambda c: c.get("frequency", 0), reverse=True)
+
+ # ------------------------------------------------------------------
+ # Load contracts
+ # ------------------------------------------------------------------
+ contract_links: list[dict] = []
+ contracts_by_type: dict[str, int] = {}
+ contracts_file = data_dir / CONTRACTS_FILENAME
+ if contracts_file.exists():
+ try:
+ contracts_data = json.loads(contracts_file.read_text(encoding="utf-8"))
+ contract_links = contracts_data.get("contract_links", [])
+ # Build counts by type from raw contracts list
+ for contract in contracts_data.get("contracts", []):
+ ctype = contract.get("contract_type") or contract.get("type", "unknown")
+ contracts_by_type[ctype] = contracts_by_type.get(ctype, 0) + 1
+ except Exception:
+ pass # non-fatal
+
+ # ------------------------------------------------------------------
+ # Build per-repo summaries (file/symbol counts from each repo's DB)
+ # ------------------------------------------------------------------
+ repo_summaries: list[WorkspaceRepoSummary] = []
+ for entry in ws_config.repos:
+ abs_path = (ws_root / entry.path).resolve()
+ file_count, symbol_count = _query_repo_counts(abs_path)
+
+ # Hotspot count: try to read from the overlay's repo_summaries if available
+ hotspot_count = 0
+ if edges_file.exists():
+ try:
+ overlay_data = json.loads(edges_file.read_text(encoding="utf-8"))
+ repo_sum = overlay_data.get("repo_summaries", {}).get(entry.alias, {})
+ hotspot_count = repo_sum.get("hotspot_count", 0)
+ except Exception:
+ pass
+
+ # Entry points: read from overlay repo_summaries if present, else empty
+ entry_points: list[str] = []
+ if edges_file.exists():
+ try:
+ overlay_data = json.loads(edges_file.read_text(encoding="utf-8"))
+ repo_sum = overlay_data.get("repo_summaries", {}).get(entry.alias, {})
+ entry_points = repo_sum.get("entry_points", [])
+ except Exception:
+ pass
+
+ repo_summaries.append(
+ WorkspaceRepoSummary(
+ alias=entry.alias,
+ is_primary=entry.is_primary,
+ file_count=file_count,
+ symbol_count=symbol_count,
+ hotspot_count=hotspot_count,
+ entry_points=entry_points,
+ )
+ )
+
+ data = WorkspaceEditorFileData(
+ workspace_name=ws_root.name,
+ workspace_root=str(ws_root),
+ repos=repo_summaries,
+ default_repo=ws_config.default_repo or "",
+ co_changes=co_changes,
+ package_deps=package_deps,
+ contract_links=contract_links,
+ contracts_by_type=contracts_by_type,
+ )
+
+ gen = WorkspaceClaudeMdGenerator()
+
+ if to_stdout:
+ return gen.render_full(ws_root, data)
+
+ dest = Path(output_path).resolve() if output_path else None
+ written = gen.write(dest.parent if dest else ws_root, data)
+ if dest and dest != written:
+ written.rename(dest)
+ written = dest
+
+ click.echo(f"Workspace CLAUDE.md updated: {written}")
+ return None
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
new file mode 100644
index 000000000..3aee50324
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -0,0 +1,110 @@
+"""``repowise hook`` — manage git post-commit hooks for auto-sync."""
+
+from __future__ import annotations
+
+import click
+
+from repowise.cli.helpers import console, find_workspace_root, resolve_repo_path
+
+
+def hook_group() -> None:
+ """Manage git hooks for automatic wiki sync."""
+
+
+@hook_group.command("install")
[email protected]("path", required=False, default=None)
+ "--workspace",
+ "-w",
+ is_flag=True,
+ default=False,
+ help="Install hooks for all repos in the workspace.",
+)
+def hook_install(path: str | None, workspace: bool) -> None:
+ """Install a post-commit hook that auto-syncs after every commit."""
+ from repowise.cli.hooks import install
+
+ repo_path = resolve_repo_path(path)
+
+ if workspace:
+ ws_root = find_workspace_root(repo_path)
+ if ws_root is None:
+ raise click.ClickException("No workspace found.")
+
+ from repowise.core.workspace import WorkspaceConfig
+
+ ws_config = WorkspaceConfig.load(ws_root)
+ for entry in ws_config.repos:
+ abs_path = (ws_root / entry.path).resolve()
+ result = install(abs_path)
+ console.print(f" {entry.alias}: [green]{result}[/green]")
+ else:
+ result = install(repo_path)
+ console.print(f"Post-commit hook: [green]{result}[/green]")
+
+
+@hook_group.command("uninstall")
[email protected]("path", required=False, default=None)
+ "--workspace",
+ "-w",
+ is_flag=True,
+ default=False,
+ help="Uninstall hooks from all repos in the workspace.",
+)
+def hook_uninstall(path: str | None, workspace: bool) -> None:
+ """Remove the repowise post-commit hook."""
+ from repowise.cli.hooks import uninstall
+
+ repo_path = resolve_repo_path(path)
+
+ if workspace:
+ ws_root = find_workspace_root(repo_path)
+ if ws_root is None:
+ raise click.ClickException("No workspace found.")
+
+ from repowise.core.workspace import WorkspaceConfig
+
+ ws_config = WorkspaceConfig.load(ws_root)
+ for entry in ws_config.repos:
+ abs_path = (ws_root / entry.path).resolve()
+ result = uninstall(abs_path)
+ console.print(f" {entry.alias}: {result}")
+ else:
+ result = uninstall(repo_path)
+ console.print(f"Post-commit hook: {result}")
+
+
+@hook_group.command("status")
[email protected]("path", required=False, default=None)
+ "--workspace",
+ "-w",
+ is_flag=True,
+ default=False,
+ help="Check hooks for all repos in the workspace.",
+)
+def hook_status(path: str | None, workspace: bool) -> None:
+ """Check if the repowise post-commit hook is installed."""
+ from repowise.cli.hooks import status
+
+ repo_path = resolve_repo_path(path)
+
+ if workspace:
+ ws_root = find_workspace_root(repo_path)
+ if ws_root is None:
+ raise click.ClickException("No workspace found.")
+
+ from repowise.core.workspace import WorkspaceConfig
+
+ ws_config = WorkspaceConfig.load(ws_root)
+ for entry in ws_config.repos:
+ abs_path = (ws_root / entry.path).resolve()
+ result = status(abs_path)
+ icon = "[green]✓[/green]" if result == "installed" else "[dim]✗[/dim]"
+ console.print(f" {icon} {entry.alias}: {result}")
+ else:
+ result = status(repo_path)
+ icon = "[green]✓[/green]" if result == "installed" else "[dim]✗[/dim]"
+ console.print(f" {icon} post-commit: {result}")
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.py
index 2f66e85c4..96b01dc1e 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py
@@ -26,12 +26,88 @@ from repowise.cli.helpers import (
save_config,
save_state,
)
+from repowise.cli.ui import MaybeCountColumn
# ---------------------------------------------------------------------------
# Helpers (kept in this file; _resolve_embedder also imported by other cmds)
# ---------------------------------------------------------------------------
+def _offer_hook_install(
+ console_obj: Any,
+ repo_paths: list[Path],
+ aliases: list[str] | None = None,
+) -> None:
+ """Interactively offer to install post-commit hooks for auto-sync.
+
+ For a single repo, asks yes/no. For multiple repos (workspace), lets the
+ user pick which repos to install hooks for.
+ """
+ if not sys.stdin.isatty():
+ return # Non-interactive — skip
+
+ from repowise.cli.hooks import install, status
+
+ # Filter to repos that don't already have the hook
+ candidates: list[tuple[Path, str]] = []
+ for i, rp in enumerate(repo_paths):
+ label = aliases[i] if aliases else rp.name
+ if status(rp) != "installed":
+ candidates.append((rp, label))
+
+ if not candidates:
+ return # All already have hooks
+
+ console_obj.print()
+ console_obj.print(
+ "[bold]Auto-sync:[/bold] Install a post-commit hook to keep the wiki "
+ "in sync after every commit?"
+ )
+
+ if len(candidates) == 1:
+ rp, label = candidates[0]
+ if click.confirm(f" Install post-commit hook for {label}?", default=True):
+ result = install(rp)
+ console_obj.print(f" [green]✓[/green] {label}: {result}")
+ else:
+ console_obj.print(
+ " [dim]Skipped. Run 'repowise hook install' later to set up.[/dim]"
+ )
+ else:
+ # Workspace: show checkboxes-style selection
+ console_obj.print(" Select repos (enter numbers, comma-separated, or 'all'):")
+ for i, (rp, label) in enumerate(candidates, 1):
+ console_obj.print(f" [{i}] {label}")
+
+ raw = click.prompt(
+ " Repos",
+ default="all",
+ show_default=True,
+ )
+ if raw.strip().lower() == "all":
+ selected_indices = list(range(len(candidates)))
+ elif raw.strip().lower() in ("none", "skip", ""):
+ selected_indices = []
+ else:
+ try:
+ selected_indices = [int(x.strip()) - 1 for x in raw.split(",") if x.strip()]
+ except ValueError:
+ selected_indices = []
+
+ installed = 0
+ for idx in selected_indices:
+ if 0 <= idx < len(candidates):
+ rp, label = candidates[idx]
+ result = install(rp)
+ console_obj.print(f" [green]✓[/green] {label}: {result}")
+ installed += 1
+
+ if installed == 0:
+ console_obj.print(
+ " [dim]Skipped. Run 'repowise hook install --workspace' later.[/dim]"
+ )
+
+
def _resolve_embedder(embedder_flag: str | None) -> str:
"""Auto-detect embedder from env vars, or use the flag value."""
if embedder_flag:
@@ -44,8 +120,12 @@ def _resolve_embedder(embedder_flag: str | None) -> str:
def _register_mcp_with_claude(console_obj: Any, repo_path: Path) -> None:
- """Register the repowise MCP server with Claude Desktop and Claude Code."""
- from repowise.cli.mcp_config import register_with_claude_code, register_with_claude_desktop
+ """Register the repowise MCP server and hooks with Claude Desktop and Claude Code."""
+ from repowise.cli.mcp_config import (
+ install_claude_code_hooks,
+ register_with_claude_code,
+ register_with_claude_desktop,
+ )
desktop = register_with_claude_desktop(repo_path)
if desktop:
@@ -55,6 +135,12 @@ def _register_mcp_with_claude(console_obj: Any, repo_path: Path) -> None:
if code:
console_obj.print(f" [green]✓[/green] Claude Code MCP registered ({code})")
+ hooks = install_claude_code_hooks()
+ if hooks:
+ console_obj.print(
+ f" [green]✓[/green] Claude Code hooks registered (PreToolUse + PostToolUse)"
+ )
+
def _maybe_generate_claude_md(
console_obj: Any,
@@ -161,6 +247,24 @@ async def _persist_result(
)
await persist_pipeline_result(result, session, repo.id)
+ # Record a completed GenerationJob so the web UI can show
+ # "last synced" / "last re-indexed" timestamps.
+ from datetime import datetime, UTC as _UTC
+ from repowise.core.persistence.crud import upsert_generation_job
+
+ now = datetime.now(_UTC)
+ page_count = len(result.generated_pages) if result.generated_pages else 0
+ job = await upsert_generation_job(
+ session,
+ repository_id=repo.id,
+ status="completed",
+ total_pages=page_count,
+ config={"mode": "full_resync", "source": "cli_init"},
+ )
+ job.completed_pages = page_count
+ job.started_at = now
+ job.finished_at = now
+
# FTS indexing is done outside the session to avoid SQLite write conflicts
if fts is not None and result.generated_pages:
for page in result.generated_pages:
@@ -169,6 +273,490 @@ async def _persist_result(
await engine.dispose()
+# ---------------------------------------------------------------------------
+# Workspace generation helper (per-repo)
+# ---------------------------------------------------------------------------
+
+
+def _run_workspace_generation(
+ *,
+ repo_path: Path,
+ result: Any,
+ provider: Any,
+ embedder_name_resolved: str,
+ concurrency: int,
+ yes: bool,
+ resume: bool,
+ skip_tests: bool,
+ skip_infra: bool,
+ test_run: bool,
+) -> list[Any]:
+ """Run LLM generation for a single repo in the workspace init flow.
+
+ Returns the list of generated pages. Raises on unrecoverable errors so
+ the caller can catch and log per-repo failures without aborting the whole
+ workspace run.
+ """
+ from repowise.cli.cost_estimator import build_generation_plan, estimate_cost
+ from repowise.cli.ui import BRAND, RichProgressCallback
+ from repowise.core.generation import GenerationConfig
+ from repowise.core.generation.cost_tracker import CostTracker
+ from repowise.core.persistence.vector_store import InMemoryVectorStore
+ from repowise.core.providers.embedding.base import MockEmbedder
+ from repowise.core.pipeline import run_generation
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.persistence import (
+ create_engine as _ce,
+ create_session_factory as _csf,
+ get_session as _gs,
+ init_db as _idb,
+ upsert_repository as _ur,
+ )
+
+ # Build embedder
+ embedder_impl: Any
+ if embedder_name_resolved == "gemini":
+ try:
+ from repowise.core.providers.embedding.gemini import GeminiEmbedder
+
+ embedder_impl = GeminiEmbedder()
+ except Exception:
+ embedder_impl = MockEmbedder()
+ elif embedder_name_resolved == "openai":
+ try:
+ from repowise.core.providers.embedding.openai import OpenAIEmbedder
+
+ embedder_impl = OpenAIEmbedder()
+ except Exception:
+ embedder_impl = MockEmbedder()
+ else:
+ embedder_impl = MockEmbedder()
+
+ # Build vector store
+ lance_dir = repo_path / ".repowise" / "lancedb"
+ try:
+ from repowise.core.persistence.vector_store import LanceDBVectorStore
+
+ lance_dir.mkdir(parents=True, exist_ok=True)
+ vector_store: Any = LanceDBVectorStore(str(lance_dir), embedder=embedder_impl)
+ except ImportError:
+ vector_store = InMemoryVectorStore(embedder_impl)
+
+ # Cost estimate
+ gen_config = GenerationConfig(max_concurrency=concurrency)
+ plans = build_generation_plan(
+ result.parsed_files, result.graph_builder, gen_config, skip_tests, skip_infra
+ )
+ est = estimate_cost(plans, provider.provider_name, provider.model_name)
+
+ console.print(
+ f" Estimated tokens: ~{est.estimated_input_tokens + est.estimated_output_tokens:,} "
+ f"(${est.estimated_cost_usd:.2f} USD, {est.total_pages} pages)"
+ )
+
+ if (
+ est.estimated_cost_usd > 2.00
+ and not yes
+ and not click.confirm(f" Cost for {repo_path.name} exceeds $2.00. Continue?")
+ ):
+ console.print(" [yellow]Skipped.[/yellow]")
+ return []
+
+ # Cost tracker (DB-backed when possible)
+ from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
+
+ async def _make_cost_tracker() -> CostTracker:
+ url = get_db_url_for_repo(repo_path)
+ engine = _ce(url)
+ await _idb(engine)
+ sf = _csf(engine)
+ async with _gs(sf) as _sess:
+ _repo = await _ur(_sess, name=result.repo_name, local_path=str(repo_path))
+ _repo_id = _repo.id
+ return CostTracker(session_factory=sf, repo_id=_repo_id)
+
+ try:
+ cost_tracker = run_async(_make_cost_tracker())
+ except Exception:
+ cost_tracker = CostTracker()
+
+ provider._cost_tracker = cost_tracker
+
+ with Progress(
+ SpinnerColumn(),
+ TextColumn("[progress.description]{task.description}"),
+ BarColumn(),
+ MaybeCountColumn(),
+ TimeElapsedColumn(),
+ TextColumn("[green]${task.fields[cost]:.3f}[/green]"),
+ console=console,
+ ) as gen_progress:
+ gen_callback = RichProgressCallback(gen_progress, console)
+
+ generated_pages = run_async(
+ run_generation(
+ repo_path=repo_path,
+ parsed_files=result.parsed_files,
+ source_map=result.source_map,
+ graph_builder=result.graph_builder,
+ repo_structure=result.repo_structure,
+ git_meta_map=result.git_meta_map,
+ llm_client=provider,
+ embedder=embedder_impl,
+ vector_store=vector_store,
+ concurrency=concurrency,
+ progress=gen_callback,
+ resume=resume,
+ cost_tracker=cost_tracker,
+ )
+ )
+
+ return generated_pages
+
+
+# ---------------------------------------------------------------------------
+# Workspace init — multi-repo flow
+# ---------------------------------------------------------------------------
+
+
+def _workspace_init(
+ *,
+ scan: Any,
+ init_all: bool,
+ exclude_patterns: list[str],
+ commit_limit: int | None,
+ follow_renames: bool,
+ no_claude_md: bool,
+ include_submodules: bool,
+ # Generation params (passed through from init_command)
+ provider_name: str | None = None,
+ model: str | None = None,
+ embedder_name: str | None = None,
+ index_only: bool = False,
+ skip_tests: bool = False,
+ skip_infra: bool = False,
+ concurrency: int = 5,
+ test_run: bool = False,
+ yes: bool = False,
+ dry_run: bool = False,
+ resume: bool = False,
+ force: bool = False,
+) -> None:
+ """Multi-repo workspace initialization.
+
+ Detects repos, prompts for selection and primary, creates a workspace
+ config, then runs ingestion on each repo. When the user selects full or
+ advanced mode (interactively) or passes an explicit provider, also runs
+ LLM generation per repo.
+ """
+ import logging
+
+ logging.getLogger("httpx").setLevel(logging.ERROR)
+ logging.getLogger("httpcore").setLevel(logging.ERROR)
+ for _logger_name in ("repowise.core", "repowise.server"):
+ logging.getLogger(_logger_name).setLevel(logging.ERROR)
+ try:
+ import structlog
+
+ structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(logging.ERROR))
+ except ImportError:
+ pass
+
+ from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
+
+ from repowise.cli.mcp_config import save_mcp_config, save_root_mcp_config
+ from repowise.cli.ui import (
+ BRAND,
+ RichProgressCallback,
+ build_completion_panel,
+ format_elapsed,
+ interactive_advanced_config,
+ interactive_mode_select,
+ interactive_primary_select,
+ interactive_provider_select,
+ interactive_repo_select,
+ load_dotenv,
+ print_banner,
+ )
+ from repowise.core.pipeline import run_pipeline
+ from repowise.core.workspace import RepoEntry, WorkspaceConfig
+
+ start = time.monotonic()
+ root = scan.root
+
+ print_banner(console, repo_name=f"Workspace: {root.name}")
+ console.print(f" Detected [bold]{len(scan.repos)}[/bold] repositories in {root}\n")
+
+ # Step 1: Select repos to index
+ if init_all:
+ selected = list(scan.repos)
+ else:
+ selected = interactive_repo_select(console, scan.repos)
+
+ if not selected:
+ console.print("[yellow]No repositories selected. Aborting.[/yellow]")
+ return
+
+ # Step 2: Select primary repo
+ if init_all:
+ primary_alias = selected[0].alias
+ else:
+ primary_alias = interactive_primary_select(console, selected)
+
+ # Determine root path (for provider resolution + dotenv)
+ primary_repo = next((r for r in selected if r.alias == primary_alias), selected[0])
+ load_dotenv(primary_repo.path)
+
+ # Step 2b: Mode selection + provider setup
+ # When running interactively with no explicit flags, present the mode menu.
+ is_interactive = sys.stdin.isatty() and provider_name is None and not index_only
+
+ embedder_name_resolved = _resolve_embedder(embedder_name)
+
+ if is_interactive:
+ mode = interactive_mode_select(console)
+ if mode == "index_only":
+ index_only = True
+ elif mode == "advanced":
+ provider_name, model = interactive_provider_select(
+ console, model, repo_path=primary_repo.path
+ )
+ adv = interactive_advanced_config(console)
+ commit_limit = adv.get("commit_limit") or commit_limit
+ follow_renames = adv.get("follow_renames", follow_renames)
+ skip_tests = adv.get("skip_tests", skip_tests)
+ skip_infra = adv.get("skip_infra", skip_infra)
+ concurrency = adv.get("concurrency", concurrency)
+ if adv.get("exclude"):
+ exclude_patterns = list(exclude_patterns) + list(adv["exclude"])
+ test_run = adv.get("test_run", test_run)
+ embedder_name_resolved = _resolve_embedder(adv.get("embedder") or embedder_name)
+ elif not index_only:
+ # "full" mode
+ provider_name, model = interactive_provider_select(
+ console, model, repo_path=primary_repo.path
+ )
+
+ # Resolve provider once (shared across all repos for generation)
+ provider = None
+ if not index_only:
+ try:
+ provider = resolve_provider(provider_name, model, primary_repo.path)
+ console.print(
+ f" Provider: [cyan]{provider.provider_name}[/cyan] / "
+ f"Model: [cyan]{provider.model_name}[/cyan]"
+ )
+ console.print(f" Embedder: [cyan]{embedder_name_resolved}[/cyan]\n")
+ except Exception as exc:
+ console.print(f" [yellow]Provider setup failed ({exc}); falling back to index-only.[/yellow]")
+ index_only = True
+ provider = None
+
+ # Step 3: Create workspace config
+ entries = [
+ RepoEntry(
+ path=repo.path.relative_to(root).as_posix(),
+ alias=repo.alias,
+ is_primary=(repo.alias == primary_alias),
+ )
+ for repo in selected
+ ]
+ ws_config = WorkspaceConfig(
+ version=1,
+ repos=entries,
+ default_repo=primary_alias,
+ )
+ config_path = ws_config.save(root)
+ console.print(f" [green]\u2713[/green] Created {config_path.name}")
+ console.print()
+
+ # Step 4: Index each selected repo (always generate_docs=False; generation is separate)
+ resolved_commit_limit = max(1, min(commit_limit or 500, 5000))
+ total_files = 0
+ total_symbols = 0
+ total_pages = 0
+ errors: list[tuple[str, str]] = []
+
+ for i, repo in enumerate(selected, 1):
+ console.print(
+ f" [{BRAND}][{i}/{len(selected)}][/] Indexing [bold]{repo.alias}[/bold] ({repo.path.name})..."
+ )
+ ensure_repowise_dir(repo.path)
+
+ try:
+ with Progress(
+ SpinnerColumn(),
+ TextColumn("[progress.description]{task.description}"),
+ BarColumn(),
+ MaybeCountColumn(),
+ TimeElapsedColumn(),
+ console=console,
+ ) as progress_bar:
+ callback = RichProgressCallback(progress_bar, console)
+
+ result = run_async(
+ run_pipeline(
+ repo.path,
+ commit_depth=resolved_commit_limit,
+ follow_renames=follow_renames,
+ exclude_patterns=exclude_patterns if exclude_patterns else None,
+ include_submodules=include_submodules,
+ generate_docs=False,
+ progress=callback,
+ )
+ )
+
+ total_files += result.file_count
+ total_symbols += result.symbol_count
+ console.print(
+ f" [green]\u2713[/green] {result.file_count} files, "
+ f"{result.symbol_count:,} symbols"
+ )
+
+ except Exception as exc:
+ errors.append((repo.alias, str(exc)))
+ console.print(f" [red]\u2717 Failed: {exc}[/red]\n")
+ continue
+
+ # Generation phase (per-repo, only when not index-only)
+ if not index_only and provider is not None:
+ if dry_run:
+ console.print(" [yellow]Dry run — skipping generation for this repo.[/yellow]\n")
+ else:
+ try:
+ generated_pages = _run_workspace_generation(
+ repo_path=repo.path,
+ result=result,
+ provider=provider,
+ embedder_name_resolved=embedder_name_resolved,
+ concurrency=concurrency,
+ yes=yes,
+ resume=resume,
+ skip_tests=skip_tests,
+ skip_infra=skip_infra,
+ test_run=test_run,
+ )
+ result.generated_pages = generated_pages
+ total_pages += len(generated_pages)
+ console.print(
+ f" [green]\u2713[/green] Generated {len(generated_pages)} pages\n"
+ )
+ except Exception as gen_exc:
+ console.print(f" [yellow]Generation failed: {gen_exc}[/yellow]\n")
+ else:
+ console.print()
+
+ # Persist to repo-local DB
+ run_async(_persist_result(result, repo.path))
+
+ # Write state.json so `repowise update` knows the base commit
+ head = get_head_commit(repo.path)
+ pages_count = len(result.generated_pages or [])
+ state: dict[str, Any] = {
+ "last_sync_commit": head,
+ "total_pages": pages_count,
+ }
+ if not index_only and provider is not None:
+ state["provider"] = provider.provider_name
+ state["model"] = provider.model_name
+ save_state(repo.path, state)
+
+ # Update workspace config with indexing metadata
+ from datetime import datetime, timezone
+
+ entry = ws_config.get_repo(repo.alias)
+ if entry is not None:
+ entry.indexed_at = datetime.now(timezone.utc).isoformat()
+ entry.last_commit_at_index = head
+
+ # MCP config + CLAUDE.md per repo
+ save_mcp_config(repo.path)
+ save_root_mcp_config(repo.path)
+ _maybe_generate_claude_md(console, repo.path, no_claude_md=no_claude_md)
+
+ # Persist provider/model config per-repo when doing full generation
+ if not index_only and provider is not None:
+ save_config(
+ repo.path,
+ provider.provider_name,
+ provider.model_name,
+ embedder_name_resolved,
+ exclude_patterns=exclude_patterns if exclude_patterns else None,
+ commit_limit=resolved_commit_limit,
+ )
+
+ # Save workspace config with updated timestamps
+ ws_config.save(root)
+
+ # Step 5: Cross-repo analysis (co-changes, package deps, contracts)
+ indexed_aliases = [
+ repo.alias for repo in selected
+ if repo.alias not in [e[0] for e in errors]
+ ]
+ if len(indexed_aliases) >= 2:
+ console.print(" Running cross-repo analysis...")
+ try:
+ from repowise.core.workspace.update import run_cross_repo_hooks
+
+ run_async(run_cross_repo_hooks(ws_config, root, indexed_aliases))
+ console.print(" [green]✓[/green] Cross-repo analysis complete")
+ except Exception as exc:
+ console.print(f" [yellow]⚠ Cross-repo analysis failed: {exc}[/yellow]")
+
+ # Step 6: Register MCP for primary repo with Claude
+ primary_entry = ws_config.get_primary()
+ if primary_entry:
+ primary_path = (root / primary_entry.path).resolve()
+ _register_mcp_with_claude(console, primary_path)
+
+ # Step 7: Completion summary
+ elapsed = time.monotonic() - start
+ metrics: list[tuple[str, str]] = [
+ ("Repositories", f"{len(selected) - len(errors)} indexed"),
+ ("Total files", str(total_files)),
+ ("Total symbols", f"{total_symbols:,}"),
+ ("Primary repo", primary_alias),
+ ("Elapsed", format_elapsed(elapsed)),
+ ]
+ if not index_only and provider is not None:
+ metrics.insert(3, ("Pages generated", str(total_pages)))
+ metrics.insert(4, ("Provider", f"{provider.provider_name} / {provider.model_name}"))
+ if errors:
+ metrics.append(("Errors", f"{len(errors)} repos failed"))
+
+ if index_only or provider is None:
+ next_steps = [
+ ("repowise mcp <repo-path>", "start MCP server for a repo"),
+ ("repowise status --workspace", "show workspace status"),
+ ("repowise init <repo> --provider gemini", "generate full docs for a repo"),
+ ]
+ else:
+ next_steps = [
+ ("repowise mcp <repo-path>", "start MCP server for a repo"),
+ ("repowise status --workspace", "show workspace status"),
+ ("repowise search <query>", "search across all indexed repos"),
+ ]
+
+ console.print()
+ console.print(
+ build_completion_panel("repowise workspace init complete", metrics, next_steps=next_steps)
+ )
+ console.print()
+
+ # Offer to install post-commit hooks
+ indexed_repos = [
+ repo for repo in selected
+ if repo.alias not in [e[0] for e in errors]
+ ]
+ if indexed_repos:
+ _offer_hook_install(
+ console,
+ [r.path for r in indexed_repos],
+ aliases=[r.alias for r in indexed_repos],
+ )
+ console.print()
+
+
# ---------------------------------------------------------------------------
# CLI command
# ---------------------------------------------------------------------------
@@ -245,6 +833,13 @@ async def _persist_result(
default=False,
help="Include git submodule directories (excluded by default).",
)
+ "--all",
+ "init_all",
+ is_flag=True,
+ default=False,
+ help="In multi-repo mode, index all detected repos without prompting.",
+)
def init_command(
path: str | None,
provider_name: str | None,
@@ -264,6 +859,7 @@ def init_command(
follow_renames: bool,
no_claude_md: bool,
include_submodules: bool,
+ init_all: bool,
) -> None:
"""Generate wiki documentation for a codebase.
@@ -273,7 +869,9 @@ def init_command(
from repowise.cli.ui import (
BRAND,
RichProgressCallback,
+ build_analysis_summary_panel,
build_completion_panel,
+ build_contextual_next_steps,
format_elapsed,
interactive_advanced_config,
interactive_mode_select,
@@ -282,6 +880,8 @@ def init_command(
print_banner,
print_index_only_intro,
print_phase_header,
+ print_scan_summary,
+ quick_repo_scan,
)
start = time.monotonic()
@@ -290,6 +890,41 @@ def init_command(
if not repo_path.is_dir():
raise click.ClickException(f"Not a directory: {repo_path}")
+ # ---- Workspace detection ----
+ # If the path contains multiple git repos (and is not itself a single repo),
+ # branch into the multi-repo workspace flow.
+ from repowise.core.workspace import scan_for_repos
+
+ scan = scan_for_repos(repo_path, include_submodules=include_submodules)
+ if len(scan.repos) > 1:
+ _workspace_init(
+ scan=scan,
+ init_all=init_all,
+ exclude_patterns=list(exclude),
+ commit_limit=commit_limit,
+ follow_renames=follow_renames,
+ no_claude_md=no_claude_md,
+ include_submodules=include_submodules,
+ provider_name=provider_name,
+ model=model,
+ embedder_name=embedder_name,
+ index_only=index_only,
+ skip_tests=skip_tests,
+ skip_infra=skip_infra,
+ concurrency=concurrency,
+ test_run=test_run,
+ yes=yes,
+ dry_run=dry_run,
+ resume=resume,
+ force=force,
+ )
+ return
+
+ # If a single repo was found inside the given directory (not at root),
+ # redirect to it so the user doesn't have to specify the exact path.
+ if len(scan.repos) == 1 and scan.repos[0].path != repo_path:
+ repo_path = scan.repos[0].path
+
ensure_repowise_dir(repo_path)
load_dotenv(repo_path)
@@ -313,15 +948,20 @@ def init_command(
# ---- Interactive mode (TTY, no explicit flags) ----
is_interactive = sys.stdin.isatty() and provider_name is None and not index_only
+ # Pre-scan for interactive mode — fast stats to inform choices
+ scan_info = None
if is_interactive:
print_banner(console, repo_name=repo_path.name)
+ with console.status(" Scanning repository…", spinner="dots"):
+ scan_info = quick_repo_scan(repo_path)
+ print_scan_summary(console, scan_info)
mode = interactive_mode_select(console)
if mode == "index_only":
index_only = True
elif mode == "advanced":
provider_name, model = interactive_provider_select(console, model, repo_path=repo_path)
- adv = interactive_advanced_config(console)
+ adv = interactive_advanced_config(console, scan=scan_info)
commit_limit = adv["commit_limit"]
follow_renames = adv["follow_renames"]
skip_tests = adv["skip_tests"]
@@ -329,6 +969,9 @@ def init_command(
concurrency = adv["concurrency"]
exclude = adv["exclude"]
test_run = adv["test_run"]
+ embedder_name = adv.get("embedder") or embedder_name
+ include_submodules = adv.get("include_submodules", include_submodules)
+ no_claude_md = adv.get("no_claude_md", no_claude_md)
else:
provider_name, model = interactive_provider_select(console, model, repo_path=repo_path)
@@ -416,7 +1059,7 @@ def init_command(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
- TextColumn("{task.completed}/{task.total}"),
+ MaybeCountColumn(),
TimeElapsedColumn(),
TextColumn("[green]${task.fields[cost]:.3f}[/green]"),
console=console,
@@ -442,6 +1085,58 @@ def init_command(
)
)
+ # ---- Analysis summary (shown between analysis and generation) ----
+ _graph = result.graph_builder.graph()
+ _dc_unreachable_pre = sum(
+ 1
+ for f in (result.dead_code_report.findings if result.dead_code_report else [])
+ if f.kind.value == "unreachable_file"
+ )
+ _dc_unused_pre = sum(
+ 1
+ for f in (result.dead_code_report.findings if result.dead_code_report else [])
+ if f.kind.value == "unused_export"
+ )
+ _dc_lines_pre = result.dead_code_report.deletable_lines if result.dead_code_report else 0
+ _n_decisions_pre = (
+ sum(result.decision_report.by_source.values()) if result.decision_report else 0
+ )
+ _lang_dist = result.repo_structure.root_language_distribution
+ _lang_summary = ""
+ if _lang_dist:
+ _top = sorted(_lang_dist.items(), key=lambda x: -x[1])[:4]
+ _lang_summary = ", ".join(f"{lang} {pct:.0%}" for lang, pct in _top)
+ if len(_lang_dist) > 4:
+ _lang_summary += f" +{len(_lang_dist) - 4} more"
+
+ # Community count (best-effort)
+ _community_count = 0
+ try:
+ if hasattr(result.graph_builder, "communities"):
+ _community_count = len(result.graph_builder.communities())
+ except Exception:
+ pass
+
+ console.print()
+ console.print(
+ build_analysis_summary_panel(
+ file_count=result.file_count,
+ symbol_count=result.symbol_count,
+ graph_nodes=_graph.number_of_nodes(),
+ graph_edges=_graph.number_of_edges(),
+ dead_unreachable=_dc_unreachable_pre,
+ dead_unused=_dc_unused_pre,
+ dead_lines=_dc_lines_pre,
+ decision_count=_n_decisions_pre,
+ git_files=result.git_summary.files_indexed if result.git_summary else 0,
+ hotspot_count=result.git_summary.hotspots
+ if result.git_summary and hasattr(result.git_summary, "hotspots")
+ else 0,
+ community_count=_community_count,
+ lang_summary=_lang_summary,
+ )
+ )
+
# ---- Phase 3: Generation (full mode only) ----
if not index_only:
print_phase_header(
@@ -534,7 +1229,7 @@ def init_command(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
- TextColumn("{task.completed}/{task.total}"),
+ MaybeCountColumn(),
TimeElapsedColumn(),
TextColumn("[green]${task.fields[cost]:.3f}[/green]"),
console=console,
@@ -690,7 +1385,7 @@ def init_command(
# ---- Completion panel ----
elapsed = time.monotonic() - start
- _graph = result.graph_builder.graph()
+ _graph_final = result.graph_builder.graph()
_dc_unreachable = sum(
1
for f in (result.dead_code_report.findings if result.dead_code_report else [])
@@ -702,27 +1397,46 @@ def init_command(
if f.kind.value == "unused_export"
)
_n_decisions = sum(result.decision_report.by_source.values()) if result.decision_report else 0
+ _hotspot_count_final = (
+ result.git_summary.hotspots
+ if result.git_summary and hasattr(result.git_summary, "hotspots")
+ else 0
+ )
+
+ # Find top hotspot file for contextual next steps
+ _top_hotspot = ""
+ if result.git_meta_map:
+ _by_churn = sorted(
+ result.git_meta_map.items(),
+ key=lambda x: x[1].get("commit_count", 0),
+ reverse=True,
+ )
+ if _by_churn:
+ _top_hotspot = _by_churn[0][0]
+ # Shorten to basename for display
+ if "/" in _top_hotspot:
+ _top_hotspot = _top_hotspot.rsplit("/", 1)[-1]
# Build a compact language summary for the completion panel
- _lang_dist = result.repo_structure.root_language_distribution
- if _lang_dist:
- _top = sorted(_lang_dist.items(), key=lambda x: -x[1])[:4]
- _lang_summary = ", ".join(f"{lang} {pct:.0%}" for lang, pct in _top)
- if len(_lang_dist) > 4:
- _lang_summary += f" +{len(_lang_dist) - 4} more"
+ _lang_dist_final = result.repo_structure.root_language_distribution
+ if _lang_dist_final:
+ _top_final = sorted(_lang_dist_final.items(), key=lambda x: -x[1])[:4]
+ _lang_summary_final = ", ".join(f"{lang} {pct:.0%}" for lang, pct in _top_final)
+ if len(_lang_dist_final) > 4:
+ _lang_summary_final += f" +{len(_lang_dist_final) - 4} more"
else:
- _lang_summary = str(len(result.languages))
+ _lang_summary_final = str(len(result.languages))
if index_only:
metrics: list[tuple[str, str]] = [
("Files indexed", str(result.file_count)),
("Symbols", f"{result.symbol_count:,}"),
- ("Languages", _lang_summary),
+ ("Languages", _lang_summary_final),
("Elapsed", format_elapsed(elapsed)),
("", ""),
(
"Graph",
- f"{_graph.number_of_nodes()} nodes · {_graph.number_of_edges()} edges",
+ f"{_graph_final.number_of_nodes()} nodes · {_graph_final.number_of_edges()} edges",
),
("Dead code", f"{_dc_unreachable} unreachable · {_dc_unused} unused exports"),
("Decisions", str(_n_decisions)),
@@ -731,16 +1445,18 @@ def init_command(
metrics.append(
(
"Git history",
- f"{result.git_summary.files_indexed} files · {result.git_summary.hotspots} hotspots",
+ f"{result.git_summary.files_indexed} files · {_hotspot_count_final} hotspots",
)
)
- next_steps = [
- ("repowise mcp .", "start MCP server for AI assistants"),
- ("repowise init --provider gemini", "generate full documentation"),
- ("repowise dead-code", "explore dead code findings"),
- ("repowise search <query>", "search the index"),
- ]
+ next_steps = build_contextual_next_steps(
+ index_only=True,
+ dead_unreachable=_dc_unreachable,
+ dead_unused=_dc_unused,
+ hotspot_count=_hotspot_count_final,
+ decision_count=_n_decisions,
+ top_hotspot=_top_hotspot,
+ )
console.print()
console.print(
build_completion_panel("repowise index complete", metrics, next_steps=next_steps)
@@ -761,14 +1477,28 @@ def init_command(
metrics.append(
(
"Git history",
- f"{result.git_summary.files_indexed} files · {result.git_summary.hotspots} hotspots",
+ f"{result.git_summary.files_indexed} files · {_hotspot_count_final} hotspots",
)
)
+ next_steps = build_contextual_next_steps(
+ index_only=False,
+ dead_unreachable=_dc_unreachable,
+ dead_unused=_dc_unused,
+ hotspot_count=_hotspot_count_final,
+ decision_count=_n_decisions,
+ top_hotspot=_top_hotspot,
+ )
+
from repowise.cli.mcp_config import format_setup_instructions
console.print()
- console.print(build_completion_panel("repowise init complete", metrics))
+ console.print(
+ build_completion_panel("repowise init complete", metrics, next_steps=next_steps)
+ )
console.print()
console.print(format_setup_instructions(repo_path))
console.print()
+
+ # Offer to install post-commit hook (both index-only and full modes)
+ _offer_hook_install(console, [repo_path])
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index 1f4dc186c..70fa1d4d9 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -2,11 +2,15 @@
from __future__ import annotations
+from pathlib import Path
+from typing import Any
+
import click
from rich.table import Table
from repowise.cli.helpers import (
console,
+ find_workspace_root,
get_db_url_for_repo,
get_repowise_dir,
load_state,
@@ -15,11 +19,187 @@ from repowise.cli.helpers import (
)
+# ---------------------------------------------------------------------------
+# Workspace status
+# ---------------------------------------------------------------------------
+
+
+def _query_repo_counts(repo_path: Path) -> tuple[int, int]:
+ """Return ``(file_count, symbol_count)`` from a repo's DB."""
+
+ async def _query() -> tuple[int, int]:
+ from sqlalchemy import func as sa_func
+ from sqlalchemy import select as sa_select
+
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.models import GraphNode, Repository
+
+ url = get_db_url_for_repo(repo_path)
+ engine = create_engine(url)
+ sf = create_session_factory(engine)
+
+ try:
+ async with get_session(sf) as session:
+ repo_result = await session.execute(
+ sa_select(Repository.id).where(Repository.local_path == str(repo_path))
+ )
+ repo_id = repo_result.scalar_one_or_none()
+ if repo_id is None:
+ return 0, 0
+
+ # Count file nodes and symbol nodes
+ file_count_result = await session.execute(
+ sa_select(sa_func.count())
+ .select_from(GraphNode)
+ .where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "file",
+ )
+ )
+ symbol_count_result = await session.execute(
+ sa_select(sa_func.count())
+ .select_from(GraphNode)
+ .where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "symbol",
+ )
+ )
+ return (
+ file_count_result.scalar_one(),
+ symbol_count_result.scalar_one(),
+ )
+ finally:
+ await engine.dispose()
+
+ db_path = get_repowise_dir(repo_path) / "wiki.db"
+ if not db_path.exists():
+ return 0, 0
+ try:
+ return run_async(_query())
+ except Exception:
+ return 0, 0
+
+
+def _format_relative_time(iso_timestamp: str | None) -> str:
+ """Format an ISO 8601 timestamp as a relative time string."""
+ if not iso_timestamp:
+ return "-"
+ try:
+ from datetime import datetime, timezone
+
+ dt = datetime.fromisoformat(iso_timestamp)
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ now = datetime.now(timezone.utc)
+ delta = now - dt
+ seconds = int(delta.total_seconds())
+ if seconds < 60:
+ return f"{seconds}s ago"
+ if seconds < 3600:
+ return f"{seconds // 60}m ago"
+ if seconds < 86400:
+ return f"{seconds // 3600}h ago"
+ return f"{seconds // 86400}d ago"
+ except Exception:
+ return iso_timestamp[:10] if len(iso_timestamp) >= 10 else iso_timestamp
+
+
+def _workspace_status(start_path: Path) -> None:
+ """Show status for all repos in a workspace."""
+ from repowise.cli.helpers import get_head_commit as _get_head
+ from repowise.core.workspace import WorkspaceConfig, check_repo_staleness
+
+ ws_root = find_workspace_root(start_path)
+ if ws_root is None:
+ console.print(
+ "[yellow]No .repowise-workspace.yaml found. "
+ "Run 'repowise init <workspace-dir>' first.[/yellow]"
+ )
+ return
+
+ ws_config = WorkspaceConfig.load(ws_root)
+
+ table = Table(title=f"Workspace: {ws_root.name}")
+ table.add_column("Repo", style="cyan", min_width=16)
+ table.add_column("Files", justify="right")
+ table.add_column("Symbols", justify="right")
+ table.add_column("Indexed", style="dim")
+ table.add_column("HEAD", style="dim")
+ table.add_column("Status")
+
+ total_stale = 0
+
+ for entry in ws_config.repos:
+ abs_path = (ws_root / entry.path).resolve()
+ repowise_dir = abs_path / ".repowise"
+ label = entry.alias
+ if entry.alias == ws_config.default_repo:
+ label += " [bold](primary)[/bold]"
+
+ if not repowise_dir.exists():
+ table.add_row(label, "-", "-", "-", "-", "[yellow]not indexed[/yellow]")
+ continue
+
+ file_count, symbol_count = _query_repo_counts(abs_path)
+ indexed_ago = _format_relative_time(entry.indexed_at)
+
+ # Check staleness by comparing stored commit to current HEAD
+ stored_commit = entry.last_commit_at_index
+ is_stale, current_head, behind = check_repo_staleness(abs_path, stored_commit)
+ head_short = (current_head or "-")[:7]
+
+ if is_stale and behind > 0:
+ status = f"[yellow]{behind} new commit(s)[/yellow]"
+ total_stale += 1
+ elif is_stale:
+ status = "[yellow]stale[/yellow]"
+ total_stale += 1
+ elif file_count > 0:
+ status = "[green]up to date[/green]"
+ else:
+ status = "[yellow]empty[/yellow]"
+
+ table.add_row(
+ label, str(file_count), f"{symbol_count:,}", indexed_ago, head_short, status
+ )
+
+ console.print(table)
+
+ # Summary line
+ total_repos = len(ws_config.repos)
+ indexed = sum(1 for e in ws_config.repos if (ws_root / e.path / ".repowise").exists())
+ summary = f"\n {indexed}/{total_repos} repos indexed. Default: {ws_config.default_repo}"
+ if total_stale:
+ summary += f". [yellow]{total_stale} stale[/yellow]"
+ console.print(summary)
+
+
+# ---------------------------------------------------------------------------
+# CLI command
+# ---------------------------------------------------------------------------
+
+
@click.command("status")
@click.argument("path", required=False, default=None)
-def status_command(path: str | None) -> None:
+ "--workspace",
+ "-w",
+ is_flag=True,
+ default=False,
+ help="Show status for all repos in the workspace.",
+)
+def status_command(path: str | None, workspace: bool) -> None:
"""Show wiki sync state and page statistics."""
repo_path = resolve_repo_path(path)
+
+ if workspace:
+ _workspace_status(repo_path)
+ return
+
repowise_dir = get_repowise_dir(repo_path)
if not repowise_dir.exists():
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.py
index 5835b42e9..d228f1c0e 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py
@@ -5,10 +5,12 @@ from __future__ import annotations
import time
import click
+from rich.table import Table
from repowise.cli.helpers import (
console,
ensure_repowise_dir,
+ find_workspace_root,
get_head_commit,
load_config,
load_state,
@@ -19,6 +21,101 @@ from repowise.cli.helpers import (
)
+# ---------------------------------------------------------------------------
+# Workspace update flow
+# ---------------------------------------------------------------------------
+
+
+def _workspace_update(
+ start_path: "Path",
+ *,
+ repo_alias: str | None = None,
+ dry_run: bool = False,
+) -> None:
+ """Update stale repos in a workspace."""
+ from pathlib import Path
+
+ from repowise.core.workspace import WorkspaceConfig, check_repo_staleness, update_workspace
+
+ ws_root = find_workspace_root(start_path)
+ if ws_root is None:
+ raise click.ClickException(
+ "No .repowise-workspace.yaml found. "
+ "Run 'repowise init <workspace-dir>' first."
+ )
+
+ ws_config = WorkspaceConfig.load(ws_root)
+
+ # Show staleness summary first
+ console.print(f"[bold]repowise update[/bold] — workspace: {ws_root.name}")
+ console.print()
+
+ stale_count = 0
+ for entry in ws_config.repos:
+ if repo_alias and entry.alias != repo_alias:
+ continue
+ abs_path = (ws_root / entry.path).resolve()
+ stored = entry.last_commit_at_index
+ is_stale, head, behind = check_repo_staleness(abs_path, stored)
+ status = f"[yellow]{behind} new commit(s)[/yellow]" if is_stale else "[green]up to date[/green]"
+ if not (abs_path / ".repowise").is_dir():
+ status = "[dim]not indexed[/dim]"
+ console.print(f" {entry.alias:<20} {status}")
+ if is_stale:
+ stale_count += 1
+
+ console.print()
+
+ if stale_count == 0:
+ console.print("[green]All repos are up to date.[/green]")
+ return
+
+ if dry_run:
+ console.print(f"[yellow]Dry run — {stale_count} repo(s) would be updated.[/yellow]")
+ return
+
+ # Run the updates
+ def _on_start(alias: str) -> None:
+ console.print(f" Updating [bold]{alias}[/bold]...")
+
+ def _on_done(result: "RepoUpdateResult") -> None:
+ if result.error:
+ console.print(f" [red]\u2717 {result.alias}: {result.error}[/red]")
+ elif result.updated:
+ console.print(
+ f" [green]\u2713[/green] {result.alias}: "
+ f"{result.file_count} files, {result.symbol_count:,} symbols"
+ )
+
+ from repowise.core.workspace import RepoUpdateResult
+
+ results = run_async(
+ update_workspace(
+ ws_root,
+ ws_config,
+ repo_filter=repo_alias,
+ dry_run=False,
+ on_repo_start=_on_start,
+ on_repo_done=_on_done,
+ )
+ )
+
+ # Summary
+ updated = sum(1 for r in results if r.updated)
+ errors = sum(1 for r in results if r.error)
+ skipped = sum(1 for r in results if r.skipped_reason)
+ console.print()
+ console.print(
+ f"[bold]Done:[/bold] {updated} updated, {skipped} skipped"
+ + (f", {errors} errors" if errors else "")
+ )
+
+
+# ---------------------------------------------------------------------------
+# CLI command
+# ---------------------------------------------------------------------------
+
+
@click.command("update")
@click.argument("path", required=False, default=None)
@click.option("--provider", "provider_name", default=None, help="LLM provider name.")
@@ -33,6 +130,19 @@ from repowise.cli.helpers import (
@click.option(
"--dry-run", is_flag=True, default=False, help="Show affected pages without regenerating."
)
+ "--workspace",
+ "-w",
+ is_flag=True,
+ default=False,
+ help="Update all stale repos in the workspace.",
+)
+ "--repo",
+ "repo_alias",
+ default=None,
+ help="Update only this repo alias within the workspace.",
+)
def update_command(
path: str | None,
provider_name: str | None,
@@ -40,10 +150,18 @@ def update_command(
since: str | None,
cascade_budget: int | None,
dry_run: bool,
+ workspace: bool,
+ repo_alias: str | None,
) -> None:
"""Incrementally update wiki pages for files changed since last sync."""
start = time.monotonic()
repo_path = resolve_repo_path(path)
+
+ # --- Workspace mode ---
+ if workspace or repo_alias:
+ _workspace_update(repo_path, repo_alias=repo_alias, dry_run=dry_run)
+ return
+
ensure_repowise_dir(repo_path)
# Load saved API keys from .repowise/.env (won't overwrite existing env vars)
@@ -166,6 +284,21 @@ def update_command(
provider = resolve_provider(provider_name, model, repo_path=repo_path)
+ # Run partial dead code analysis on affected files
+ dead_code_report = None
+ try:
+ from repowise.core.analysis.dead_code import DeadCodeAnalyzer
+
+ analyzer = DeadCodeAnalyzer(graph_builder.graph(), git_meta_map)
+ changed_paths = [fd.path for fd in file_diffs]
+ dead_code_report = analyzer.analyze_partial(changed_paths)
+ if dead_code_report.total_findings:
+ console.print(
+ f"Dead code findings (partial): [yellow]{dead_code_report.total_findings}[/yellow]"
+ )
+ except Exception as exc:
+ console.print(f"[yellow]Dead code analysis skipped: {exc}[/yellow]")
+
# Re-scan changed files for inline decision markers
new_decision_markers: list = []
try:
@@ -274,6 +407,43 @@ def update_command(
except Exception:
pass # never fail update due to decision processing
+ # Persist dead code findings (partial)
+ if dead_code_report and dead_code_report.findings:
+ try:
+ import dataclasses as _dc_dead
+
+ from repowise.core.persistence.crud import save_dead_code_findings
+
+ async with get_session(sf) as session:
+ await save_dead_code_findings(
+ session,
+ repo_id,
+ [_dc_dead.asdict(f) for f in dead_code_report.findings],
+ )
+ except Exception:
+ pass # dead code persistence is best-effort
+
+ # Record a GenerationJob so the web UI "last synced" timestamp updates
+ try:
+ from datetime import datetime, UTC as _UTC
+ from repowise.core.persistence.crud import upsert_generation_job
+
+ async with get_session(sf) as session:
+ now = datetime.now(_UTC)
+ page_count = len(generated_pages)
+ job = await upsert_generation_job(
+ session,
+ repository_id=repo_id,
+ status="completed",
+ total_pages=page_count,
+ config={"mode": "incremental", "source": "cli_update"},
+ )
+ job.completed_pages = page_count
+ job.started_at = now
+ job.finished_at = now
+ except Exception:
+ pass # job recording is best-effort
+
fts = FullTextSearch(engine)
await fts.ensure_index()
for page in generated_pages:
@@ -325,6 +495,29 @@ def update_command(
state["total_pages"] = state.get("total_pages", 0) + len(generated_pages)
save_state(repo_path, state)
+ # Trigger cross-repo hooks if this repo is part of a workspace
+ try:
+ ws_root = find_workspace_root(repo_path)
+ if ws_root is not None:
+ from repowise.core.workspace import WorkspaceConfig
+ from repowise.core.workspace.update import run_cross_repo_hooks
+
+ ws_config = WorkspaceConfig.load(ws_root)
+ # Find this repo's alias in the workspace config
+ from pathlib import Path as _P
+ repo_abs = repo_path.resolve()
+ alias = None
+ for entry in ws_config.repos:
+ if (ws_root / entry.path).resolve() == repo_abs:
+ alias = entry.alias
+ break
+ if alias and len(ws_config.repos) >= 2:
+ console.print("Running cross-repo analysis...")
+ run_async(run_cross_repo_hooks(ws_config, ws_root, [alias]))
+ console.print("[green]Cross-repo analysis updated.[/green]")
+ except Exception:
+ pass # cross-repo hooks must never fail the update
+
elapsed = time.monotonic() - start
# Print generation report
diff --git a/packages/cli/src/repowise/cli/commands/watch_cmd.py b/packages/cli/src/repowise/cli/commands/watch_cmd.py
index a6685c6dc..e58e3fb73 100644
--- a/packages/cli/src/repowise/cli/commands/watch_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/watch_cmd.py
@@ -11,26 +11,27 @@ import click
from repowise.cli.helpers import (
console,
ensure_repowise_dir,
+ find_workspace_root,
resolve_repo_path,
+ run_async,
)
[email protected]("path", required=False, default=None)
[email protected]("--provider", "provider_name", default=None, help="LLM provider name.")
[email protected]("--model", default=None, help="Model identifier override.")
[email protected]("--debounce", "debounce_ms", type=int, default=2000, help="Debounce delay in ms.")
-def watch_command(
- path: str | None,
+# ---------------------------------------------------------------------------
+# Single-repo watch (existing behavior)
+# ---------------------------------------------------------------------------
+
+
+def _watch_single_repo(
+ repo_path: Path,
provider_name: str | None,
model: str | None,
debounce_ms: int,
) -> None:
- """Watch for file changes and auto-update wiki pages."""
+ """Watch a single repo for changes and trigger updates."""
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
- repo_path = resolve_repo_path(path)
ensure_repowise_dir(repo_path)
changed_paths: set[str] = set()
@@ -49,7 +50,6 @@ def watch_command(
console.print(f"[cyan]Detected {len(paths)} changed file(s), updating...[/cyan]")
try:
- # Invoke update via Click context
from click.testing import CliRunner
from repowise.cli.commands.update_cmd import update_command
@@ -71,7 +71,6 @@ def watch_command(
nonlocal timer
if event.is_directory:
return
- # Ignore .repowise/ directory changes
rel = str(Path(event.src_path).relative_to(repo_path))
if rel.startswith(".repowise"):
return
@@ -97,3 +96,173 @@ def watch_command(
observer.stop()
console.print("\n[yellow]Stopped watching.[/yellow]")
observer.join()
+
+
+# ---------------------------------------------------------------------------
+# Workspace watch — per-repo handlers with independent debounce
+# ---------------------------------------------------------------------------
+
+
+def _watch_workspace(
+ ws_root: Path,
+ debounce_ms: int,
+) -> None:
+ """Watch all repos in a workspace with per-repo debounce timers."""
+ from watchdog.events import FileSystemEventHandler
+ from watchdog.observers import Observer
+
+ from repowise.core.workspace import WorkspaceConfig, update_workspace
+
+ ws_config = WorkspaceConfig.load(ws_root)
+
+ if not ws_config.repos:
+ console.print("[yellow]No repos in workspace config.[/yellow]")
+ return
+
+ # Per-repo state: each repo gets its own change set and debounce timer
+ repo_locks: dict[str, threading.Lock] = {}
+ repo_changed: dict[str, set[str]] = {}
+ repo_timers: dict[str, threading.Timer | None] = {}
+
+ for entry in ws_config.repos:
+ repo_locks[entry.alias] = threading.Lock()
+ repo_changed[entry.alias] = set()
+ repo_timers[entry.alias] = None
+
+ def _make_trigger(alias: str) -> callable:
+ """Create a trigger function for a specific repo."""
+
+ def _on_trigger() -> None:
+ with repo_locks[alias]:
+ paths = set(repo_changed[alias])
+ repo_changed[alias].clear()
+ repo_timers[alias] = None
+
+ if not paths:
+ return
+
+ console.print(
+ f"[cyan]{alias}: {len(paths)} changed file(s), updating...[/cyan]"
+ )
+ try:
+ # Reload config in case it was updated
+ current_config = WorkspaceConfig.load(ws_root)
+ results = run_async(
+ update_workspace(
+ ws_root,
+ current_config,
+ repo_filter=alias,
+ )
+ )
+ for r in results:
+ if r.error:
+ console.print(f" [red]{alias}: {r.error}[/red]")
+ elif r.updated:
+ console.print(
+ f" [green]\u2713[/green] {alias}: "
+ f"{r.file_count} files, {r.symbol_count:,} symbols"
+ )
+ elif r.skipped_reason == "up_to_date":
+ console.print(f" [dim]{alias}: already up to date[/dim]")
+ except Exception as e:
+ console.print(f" [red]{alias} update failed: {e}[/red]")
+
+ return _on_trigger
+
+ class WorkspaceRepoHandler(FileSystemEventHandler):
+ """Handler for a single repo directory within the workspace."""
+
+ def __init__(self, alias: str, repo_path: Path):
+ super().__init__()
+ self._alias = alias
+ self._repo_path = repo_path
+
+ def on_any_event(self, event):
+ if event.is_directory:
+ return
+ try:
+ rel = str(Path(event.src_path).relative_to(self._repo_path))
+ except ValueError:
+ return
+ if rel.startswith(".repowise"):
+ return
+
+ alias = self._alias
+ with repo_locks[alias]:
+ repo_changed[alias].add(rel)
+ old_timer = repo_timers[alias]
+ if old_timer is not None:
+ old_timer.cancel()
+ new_timer = threading.Timer(
+ debounce_ms / 1000.0, _make_trigger(alias),
+ )
+ new_timer.daemon = True
+ new_timer.start()
+ repo_timers[alias] = new_timer
+
+ observer = Observer()
+ scheduled = 0
+ for entry in ws_config.repos:
+ abs_path = (ws_root / entry.path).resolve()
+ if not abs_path.is_dir():
+ console.print(f" [yellow]Skipping {entry.alias}: directory not found[/yellow]")
+ continue
+ handler = WorkspaceRepoHandler(entry.alias, abs_path)
+ observer.schedule(handler, str(abs_path), recursive=True)
+ scheduled += 1
+
+ if scheduled == 0:
+ console.print("[yellow]No repo directories found to watch.[/yellow]")
+ return
+
+ observer.start()
+
+ repo_list = ", ".join(e.alias for e in ws_config.repos)
+ console.print(f"[bold]Watching workspace ({scheduled} repos: {repo_list})... Ctrl+C to stop[/bold]")
+
+ try:
+ while True:
+ time.sleep(1)
+ except KeyboardInterrupt:
+ observer.stop()
+ console.print("\n[yellow]Stopped watching.[/yellow]")
+ observer.join()
+
+
+# ---------------------------------------------------------------------------
+# CLI command
+# ---------------------------------------------------------------------------
+
+
[email protected]("path", required=False, default=None)
[email protected]("--provider", "provider_name", default=None, help="LLM provider name.")
[email protected]("--model", default=None, help="Model identifier override.")
[email protected]("--debounce", "debounce_ms", type=int, default=2000, help="Debounce delay in ms.")
+ "--workspace",
+ "-w",
+ is_flag=True,
+ default=False,
+ help="Watch all repos in the workspace.",
+)
+def watch_command(
+ path: str | None,
+ provider_name: str | None,
+ model: str | None,
+ debounce_ms: int,
+ workspace: bool,
+) -> None:
+ """Watch for file changes and auto-update wiki pages."""
+ repo_path = resolve_repo_path(path)
+
+ if workspace:
+ ws_root = find_workspace_root(repo_path)
+ if ws_root is None:
+ raise click.ClickException(
+ "No .repowise-workspace.yaml found. "
+ "Run 'repowise init <workspace-dir>' first."
+ )
+ _watch_workspace(ws_root, debounce_ms)
+ else:
+ _watch_single_repo(repo_path, provider_name, model, debounce_ms)
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
new file mode 100644
index 000000000..02dce318d
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -0,0 +1,493 @@
+"""``repowise workspace`` — manage multi-repo workspaces."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import click
+from rich.table import Table
+
+from repowise.cli.helpers import (
+ console,
+ find_workspace_root,
+ resolve_repo_path,
+ run_async,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _require_workspace(start: Path | None = None) -> tuple[Path, "WorkspaceConfig"]: # type: ignore[name-defined]
+ """Load the workspace config or abort with a helpful message.
+
+ Returns ``(ws_root, ws_config)``.
+ """
+ from repowise.core.workspace.config import WorkspaceConfig
+
+ ws_root = find_workspace_root(start)
+ if ws_root is None:
+ raise click.ClickException(
+ "No .repowise-workspace.yaml found. "
+ "Run 'repowise init <workspace-dir>' to create a workspace."
+ )
+ ws_config = WorkspaceConfig.load(ws_root)
+ return ws_root, ws_config
+
+
+# ---------------------------------------------------------------------------
+# Command group
+# ---------------------------------------------------------------------------
+
+
[email protected]("workspace")
+def workspace_group() -> None:
+ """Manage multi-repo workspaces."""
+
+
+# ---------------------------------------------------------------------------
+# workspace list
+# ---------------------------------------------------------------------------
+
+
+@workspace_group.command("list")
[email protected]("path", required=False, default=None)
+def workspace_list(path: str | None) -> None:
+ """Show all repos in the workspace with their status."""
+ from repowise.cli.helpers import get_repowise_dir
+ from repowise.core.workspace import check_repo_staleness
+
+ start = resolve_repo_path(path)
+ ws_root, ws_config = _require_workspace(start)
+
+ table = Table(title=f"Workspace: {ws_root.name}")
+ table.add_column("Repo", style="cyan", min_width=16)
+ table.add_column("Path", style="dim")
+ table.add_column("Files", justify="right")
+ table.add_column("Symbols", justify="right")
+ table.add_column("Indexed", style="dim")
+ table.add_column("Status")
+
+ indexed_count = 0
+
+ for entry in ws_config.repos:
+ abs_path = (ws_root / entry.path).resolve()
+ repowise_dir = get_repowise_dir(abs_path)
+
+ label = entry.alias
+ if entry.alias == ws_config.default_repo:
+ label += " [bold](primary)[/bold]"
+
+ rel_path = entry.path
+
+ if not repowise_dir.exists():
+ table.add_row(label, rel_path, "-", "-", "-", "[yellow]not indexed[/yellow]")
+ continue
+
+ indexed_count += 1
+
+ # Query file/symbol counts from DB
+ file_count, symbol_count = _query_repo_counts(abs_path)
+
+ # Indexed timestamp
+ indexed_ago = _format_relative_time(entry.indexed_at)
+
+ # Staleness check
+ is_stale, _head, behind = check_repo_staleness(abs_path, entry.last_commit_at_index)
+
+ if is_stale and behind > 0:
+ status = f"[yellow]{behind} new commit(s)[/yellow]"
+ elif is_stale:
+ status = "[yellow]stale[/yellow]"
+ elif file_count > 0:
+ status = "[green]up to date[/green]"
+ else:
+ status = "[yellow]empty[/yellow]"
+
+ table.add_row(
+ label,
+ rel_path,
+ str(file_count),
+ f"{symbol_count:,}",
+ indexed_ago,
+ status,
+ )
+
+ console.print(table)
+
+ total_repos = len(ws_config.repos)
+ summary = f"\n {indexed_count}/{total_repos} repos indexed."
+ if ws_config.default_repo:
+ summary += f" Default: {ws_config.default_repo}"
+ console.print(summary)
+
+
+def _query_repo_counts(repo_path: Path) -> tuple[int, int]:
+ """Return ``(file_count, symbol_count)`` from a repo's DB, or ``(0, 0)``."""
+ from repowise.cli.helpers import get_db_url_for_repo, get_repowise_dir
+
+ db_path = get_repowise_dir(repo_path) / "wiki.db"
+ if not db_path.exists():
+ return 0, 0
+
+ async def _query() -> tuple[int, int]:
+ from sqlalchemy import func as sa_func
+ from sqlalchemy import select as sa_select
+
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.models import GraphNode, Repository
+
+ url = get_db_url_for_repo(repo_path)
+ engine = create_engine(url)
+ sf = create_session_factory(engine)
+ try:
+ async with get_session(sf) as session:
+ repo_result = await session.execute(
+ sa_select(Repository.id).where(Repository.local_path == str(repo_path))
+ )
+ repo_id = repo_result.scalar_one_or_none()
+ if repo_id is None:
+ return 0, 0
+ file_result = await session.execute(
+ sa_select(sa_func.count())
+ .select_from(GraphNode)
+ .where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "file",
+ )
+ )
+ symbol_result = await session.execute(
+ sa_select(sa_func.count())
+ .select_from(GraphNode)
+ .where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "symbol",
+ )
+ )
+ return file_result.scalar_one(), symbol_result.scalar_one()
+ finally:
+ await engine.dispose()
+
+ try:
+ return run_async(_query())
+ except Exception:
+ return 0, 0
+
+
+def _format_relative_time(iso_timestamp: str | None) -> str:
+ """Format an ISO 8601 timestamp as a human-readable relative string."""
+ if not iso_timestamp:
+ return "-"
+ try:
+ from datetime import datetime, timezone
+
+ dt = datetime.fromisoformat(iso_timestamp)
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ now = datetime.now(timezone.utc)
+ delta = now - dt
+ seconds = int(delta.total_seconds())
+ if seconds < 60:
+ return f"{seconds}s ago"
+ if seconds < 3600:
+ return f"{seconds // 60}m ago"
+ if seconds < 86400:
+ return f"{seconds // 3600}h ago"
+ return f"{seconds // 86400}d ago"
+ except Exception:
+ return iso_timestamp[:10] if len(iso_timestamp) >= 10 else iso_timestamp
+
+
+# ---------------------------------------------------------------------------
+# workspace add
+# ---------------------------------------------------------------------------
+
+
+@workspace_group.command("add")
[email protected]("--alias", default=None, help="Short name for the repo (default: directory name).")
+ "--index",
+ "run_index",
+ is_flag=True,
+ default=False,
+ help="Run indexing on the repo after adding it.",
+)
+def workspace_add(path: str, alias: str | None, run_index: bool) -> None:
+ """Add a repo to the workspace.
+
+ PATH is a relative or absolute path to a git repository.
+ """
+ from repowise.core.workspace.config import RepoEntry
+
+ repo_path = Path(path).resolve()
+ ws_root, ws_config = _require_workspace(Path.cwd())
+
+ # Validate path exists
+ if not repo_path.exists():
+ raise click.ClickException(f"Path does not exist: {repo_path}")
+
+ # Validate it is a git repo
+ if not (repo_path / ".git").exists():
+ raise click.ClickException(
+ f"Not a git repository (no .git found): {repo_path}"
+ )
+
+ # Default alias to directory name
+ if alias is None:
+ alias = repo_path.name.lower()
+
+ # Validate alias is not already in workspace
+ if ws_config.get_repo(alias) is not None:
+ raise click.ClickException(
+ f"Alias '{alias}' already exists in this workspace. "
+ "Use --alias to specify a different name."
+ )
+
+ # Build a relative path from ws_root
+ try:
+ rel_path = repo_path.relative_to(ws_root).as_posix()
+ except ValueError:
+ # Repo is outside workspace root — store absolute path as-is
+ rel_path = repo_path.as_posix()
+
+ entry = RepoEntry(path=rel_path, alias=alias)
+
+ try:
+ ws_config.add_repo(entry)
+ except ValueError as exc:
+ raise click.ClickException(str(exc)) from exc
+
+ ws_config.save(ws_root)
+ console.print(f"[green]✓[/green] Added repo '{alias}' ({rel_path}) to workspace.")
+
+ if run_index:
+ _run_index_for_repo(repo_path, alias, ws_root, ws_config)
+
+
+def _run_index_for_repo(
+ repo_path: Path,
+ alias: str,
+ ws_root: Path,
+ ws_config: "WorkspaceConfig", # type: ignore[name-defined]
+) -> None:
+ """Run the ingestion pipeline on a single repo and update workspace config."""
+ from datetime import datetime, timezone
+
+ from repowise.core.pipeline.orchestrator import run_pipeline
+ from repowise.core.workspace.update import run_cross_repo_hooks
+
+ console.print(f" Indexing [cyan]{alias}[/cyan]…")
+
+ async def _do_index() -> None:
+ result = await run_pipeline(repo_path, generate_docs=False)
+
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+ from repowise.core.persistence.database import resolve_db_url
+ from repowise.core.pipeline import persist_pipeline_result
+
+ url = resolve_db_url(repo_path)
+ engine = create_engine(url)
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await upsert_repository(
+ session, name=result.repo_name, local_path=str(repo_path)
+ )
+ await persist_pipeline_result(result, session, repo.id)
+ await engine.dispose()
+
+ # Update workspace entry timestamps
+ entry = ws_config.get_repo(alias)
+ if entry is not None:
+ entry.indexed_at = datetime.now(timezone.utc).isoformat()
+ from repowise.cli.helpers import get_head_commit
+
+ entry.last_commit_at_index = get_head_commit(repo_path)
+ ws_config.save(ws_root)
+
+ # Cross-repo hooks
+ await run_cross_repo_hooks(ws_config, ws_root, [alias])
+
+ try:
+ run_async(_do_index())
+ console.print(f"[green]✓[/green] Indexed '{alias}' successfully.")
+ except Exception as exc:
+ console.print(f"[yellow]Warning:[/yellow] Indexing failed for '{alias}': {exc}")
+
+
+# ---------------------------------------------------------------------------
+# workspace remove
+# ---------------------------------------------------------------------------
+
+
+@workspace_group.command("remove")
+def workspace_remove(alias: str) -> None:
+ """Remove a repo from the workspace config.
+
+ The repo's .repowise/ directory is preserved; only the workspace
+ entry is deleted.
+ """
+ ws_root, ws_config = _require_workspace(Path.cwd())
+
+ entry = ws_config.get_repo(alias)
+ if entry is None:
+ available = ", ".join(ws_config.repo_aliases()) or "(none)"
+ raise click.ClickException(
+ f"No repo with alias '{alias}' found. Available: {available}"
+ )
+
+ is_default = alias == ws_config.default_repo
+
+ removed = ws_config.remove_repo(alias)
+ if removed is None:
+ raise click.ClickException(f"Failed to remove repo '{alias}'.")
+
+ ws_config.save(ws_root)
+ console.print(f"[green]✓[/green] Removed repo '{alias}' from workspace.")
+
+ if is_default and ws_config.repos:
+ new_default = ws_config.repos[0].alias
+ console.print(
+ f"[yellow]Note:[/yellow] '{alias}' was the default repo. "
+ f"New default is '{new_default}'."
+ )
+ elif is_default:
+ console.print(
+ "[yellow]Note:[/yellow] Workspace now has no repos and no default."
+ )
+
+ console.print(
+ f" (Indexed data at {removed.path}/.repowise/ was [bold]not[/bold] deleted.)"
+ )
+
+
+# ---------------------------------------------------------------------------
+# workspace scan
+# ---------------------------------------------------------------------------
+
+
+@workspace_group.command("scan")
[email protected]("path", required=False, default=None)
+ "--yes",
+ "-y",
+ is_flag=True,
+ default=False,
+ help="Auto-add all discovered repos without prompting.",
+)
+def workspace_scan(path: str | None, yes: bool) -> None:
+ """Scan the workspace root for new repos not yet in the config."""
+ from repowise.core.workspace.config import RepoEntry
+ from repowise.core.workspace.scanner import scan_for_repos
+
+ start = resolve_repo_path(path)
+ ws_root, ws_config = _require_workspace(start)
+
+ console.print(f"Scanning [cyan]{ws_root}[/cyan] for git repositories…")
+ scan_result = scan_for_repos(ws_root)
+
+ existing_aliases = set(ws_config.repo_aliases())
+ existing_paths = {
+ (ws_root / e.path).resolve().as_posix()
+ for e in ws_config.repos
+ }
+
+ new_repos = [
+ r for r in scan_result.repos
+ if r.path.as_posix() not in existing_paths
+ and r.alias not in existing_aliases
+ ]
+
+ if not new_repos:
+ console.print("[green]No new repositories discovered.[/green]")
+ return
+
+ console.print(f"\nFound [bold]{len(new_repos)}[/bold] new repo(s) not in workspace:\n")
+ for repo in new_repos:
+ indexed_marker = " [green](indexed)[/green]" if repo.has_repowise else ""
+ console.print(f" [cyan]{repo.alias}[/cyan] — {repo.path}{indexed_marker}")
+
+ console.print()
+
+ added = 0
+ for repo in new_repos:
+ alias = repo.alias
+
+ # Resolve alias collisions
+ base_alias = alias
+ suffix = 2
+ while ws_config.get_repo(alias) is not None:
+ alias = f"{base_alias}-{suffix}"
+ suffix += 1
+
+ if yes:
+ do_add = True
+ else:
+ do_add = click.confirm(f"Add '{alias}' ({repo.path.relative_to(ws_root)})?")
+
+ if do_add:
+ try:
+ rel_path = repo.path.relative_to(ws_root).as_posix()
+ except ValueError:
+ rel_path = repo.path.as_posix()
+
+ entry = RepoEntry(path=rel_path, alias=alias)
+ ws_config.add_repo(entry)
+ console.print(f" [green]✓[/green] Added '{alias}'.")
+ added += 1
+
+ if added > 0:
+ ws_config.save(ws_root)
+ console.print(f"\n[green]{added} repo(s) added to workspace.[/green]")
+ else:
+ console.print("\nNo repos added.")
+
+
+# ---------------------------------------------------------------------------
+# workspace set-default
+# ---------------------------------------------------------------------------
+
+
+@workspace_group.command("set-default")
+def workspace_set_default(alias: str) -> None:
+ """Change the default (primary) repo in the workspace."""
+ ws_root, ws_config = _require_workspace(Path.cwd())
+
+ entry = ws_config.get_repo(alias)
+ if entry is None:
+ available = ", ".join(ws_config.repo_aliases()) or "(none)"
+ raise click.ClickException(
+ f"No repo with alias '{alias}' found. Available: {available}"
+ )
+
+ previous_default = ws_config.default_repo
+
+ # Update is_primary flags on all entries
+ for repo_entry in ws_config.repos:
+ repo_entry.is_primary = repo_entry.alias == alias
+
+ ws_config.default_repo = alias
+ ws_config.save(ws_root)
+
+ if previous_default and previous_default != alias:
+ console.print(
+ f"[green]✓[/green] Default repo changed from "
+ f"'[dim]{previous_default}[/dim]' to '[bold]{alias}[/bold]'."
+ )
+ else:
+ console.print(f"[green]✓[/green] Default repo set to '[bold]{alias}[/bold]'.")
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 68518c31f..d5c338339 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -48,6 +48,17 @@ def resolve_repo_path(path: str | None) -> Path:
return Path(path).resolve()
+def find_workspace_root(start: Path | None = None) -> Path | None:
+ """Walk up from *start* (default: cwd) looking for ``.repowise-workspace.yaml``.
+
+ Returns the directory containing the file, or ``None`` if not found.
+ Delegates to :func:`repowise.core.workspace.config.find_workspace_root`.
+ """
+ from repowise.core.workspace.config import find_workspace_root as _find
+
+ return _find(start)
+
+
def get_repowise_dir(repo_path: Path) -> Path:
"""Return the ``.repowise/`` directory for a given repo root."""
return repo_path / REPOWISE_DIR
diff --git a/packages/cli/src/repowise/cli/hooks.py b/packages/cli/src/repowise/cli/hooks.py
new file mode 100644
index 000000000..6998cbc13
--- /dev/null
+++ b/packages/cli/src/repowise/cli/hooks.py
@@ -0,0 +1,134 @@
+"""Git hook management for repowise auto-sync.
+
+Installs/uninstalls a post-commit hook that runs ``repowise update`` in the
+background after every commit, keeping the wiki in sync automatically.
+
+The hook uses start/end markers so it can safely coexist with other hooks
+in the same file (e.g. lint hooks, graphify hooks).
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import stat
+import sys
+from pathlib import Path
+
+_HOOK_MARKER = "# repowise-hook-start"
+_HOOK_MARKER_END = "# repowise-hook-end"
+
+# The hook script detects the platform and runs repowise update in the
+# background so the commit is never blocked.
+_HOOK_SCRIPT = """\
+# repowise-hook-start
+# Auto-syncs repowise wiki after each commit (background, non-blocking).
+# Installed by: repowise hook install
+(
+ cd "$(git rev-parse --show-toplevel)" || exit 1
+ if [ -d ".repowise" ]; then
+ # Detect the right way to invoke repowise
+ if command -v repowise >/dev/null 2>&1; then
+ repowise update > /dev/null 2>&1
+ elif command -v uv >/dev/null 2>&1; then
+ uv run repowise update > /dev/null 2>&1
+ elif command -v powershell.exe >/dev/null 2>&1; then
+ powershell.exe -Command "uv run repowise update" > /dev/null 2>&1
+ fi
+ fi
+) &
+# repowise-hook-end
+"""
+
+
+def _git_root(path: Path) -> Path | None:
+ """Walk up to find .git directory."""
+ current = path.resolve()
+ for parent in [current, *current.parents]:
+ if (parent / ".git").exists():
+ return parent
+ return None
+
+
+def install(repo_path: Path) -> str:
+ """Install a repowise post-commit hook in the repo's .git/hooks/.
+
+ Appends to an existing post-commit hook if one exists (preserving
+ other tools' hooks). Returns a human-readable status message.
+ """
+ root = _git_root(repo_path)
+ if root is None:
+ return "not a git repository"
+
+ hooks_dir = root / ".git" / "hooks"
+ hooks_dir.mkdir(exist_ok=True)
+ hook_path = hooks_dir / "post-commit"
+
+ if hook_path.exists():
+ content = hook_path.read_text(encoding="utf-8")
+ if _HOOK_MARKER in content:
+ return "already installed"
+ # Append to existing hook
+ hook_path.write_text(
+ content.rstrip() + "\n\n" + _HOOK_SCRIPT,
+ encoding="utf-8",
+ )
+ else:
+ hook_path.write_text("#!/bin/sh\n" + _HOOK_SCRIPT, encoding="utf-8")
+
+ # Make executable (no-op on Windows but harmless)
+ try:
+ hook_path.chmod(hook_path.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
+ except OSError:
+ pass
+
+ return "installed"
+
+
+def uninstall(repo_path: Path) -> str:
+ """Remove the repowise section from the post-commit hook.
+
+ Preserves other tools' hook content. Deletes the file entirely if
+ repowise was the only content.
+ """
+ root = _git_root(repo_path)
+ if root is None:
+ return "not a git repository"
+
+ hook_path = root / ".git" / "hooks" / "post-commit"
+ if not hook_path.exists():
+ return "no post-commit hook found"
+
+ content = hook_path.read_text(encoding="utf-8")
+ if _HOOK_MARKER not in content:
+ return "repowise hook not found in post-commit"
+
+ new_content = re.sub(
+ rf"{re.escape(_HOOK_MARKER)}.*?{re.escape(_HOOK_MARKER_END)}\n?",
+ "",
+ content,
+ flags=re.DOTALL,
+ ).strip()
+
+ if not new_content or new_content in ("#!/bin/bash", "#!/bin/sh"):
+ hook_path.unlink()
+ return "removed"
+ else:
+ hook_path.write_text(new_content + "\n", encoding="utf-8")
+ return "removed (other hook content preserved)"
+
+
+def status(repo_path: Path) -> str:
+ """Check if the repowise post-commit hook is installed."""
+ root = _git_root(repo_path)
+ if root is None:
+ return "not a git repository"
+
+ hook_path = root / ".git" / "hooks" / "post-commit"
+ if not hook_path.exists():
+ return "not installed"
+
+ content = hook_path.read_text(encoding="utf-8")
+ if _HOOK_MARKER in content:
+ return "installed"
+ return "not installed"
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index 7fa3650e6..3f5e76d30 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -5,12 +5,14 @@ from __future__ import annotations
import click
from repowise.cli import __version__
+from repowise.cli.commands.augment_cmd import augment_command
from repowise.cli.commands.claude_md_cmd import claude_md_command
from repowise.cli.commands.costs_cmd import costs_command
from repowise.cli.commands.dead_code_cmd import dead_code_command
from repowise.cli.commands.decision_cmd import decision_group
from repowise.cli.commands.doctor_cmd import doctor_command
from repowise.cli.commands.export_cmd import export_command
+from repowise.cli.commands.hook_cmd import hook_group
from repowise.cli.commands.init_cmd import init_command
from repowise.cli.commands.mcp_cmd import mcp_command
from repowise.cli.commands.reindex_cmd import reindex_command
@@ -19,6 +21,7 @@ from repowise.cli.commands.serve_cmd import serve_command
from repowise.cli.commands.status_cmd import status_command
from repowise.cli.commands.update_cmd import update_command
from repowise.cli.commands.watch_cmd import watch_command
+from repowise.cli.commands.workspace_cmd import workspace_group
@click.group()
@@ -27,6 +30,7 @@ def cli() -> None:
"""repowise -- codebase intelligence for developers and AI."""
+cli.add_command(augment_command)
cli.add_command(init_command)
cli.add_command(claude_md_command)
cli.add_command(costs_command)
@@ -35,9 +39,11 @@ cli.add_command(dead_code_command)
cli.add_command(decision_group)
cli.add_command(search_command)
cli.add_command(export_command)
+cli.add_command(hook_group)
cli.add_command(status_command)
cli.add_command(doctor_command)
cli.add_command(watch_command)
cli.add_command(serve_command)
cli.add_command(mcp_command)
cli.add_command(reindex_command)
+cli.add_command(workspace_group)
diff --git a/packages/cli/src/repowise/cli/mcp_config.py b/packages/cli/src/repowise/cli/mcp_config.py
index af53c56d5..685fa3462 100644
--- a/packages/cli/src/repowise/cli/mcp_config.py
+++ b/packages/cli/src/repowise/cli/mcp_config.py
@@ -131,6 +131,84 @@ def register_with_claude_code(repo_path: Path) -> Path | None:
return settings_path if _merge_mcp_entry(settings_path, entry) else None
+def install_claude_code_hooks() -> Path | None:
+ """Register PreToolUse and PostToolUse hooks in ~/.claude/settings.json.
+
+ PreToolUse: enriches Grep/Glob searches with graph context (importers,
+ dependencies, symbols) from the local wiki.db.
+
+ PostToolUse: detects git commits and notifies the agent when the wiki
+ is stale.
+
+ Merges into existing hooks without clobbering user-defined entries.
+ Returns the settings path on success, None on failure.
+ """
+ settings_path = _claude_code_settings_path()
+
+ pre_hook_entry = {
+ "matcher": "Grep|Glob",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "repowise augment",
+ "timeout": 10,
+ "statusMessage": "Enriching with codebase context...",
+ }
+ ],
+ }
+
+ post_hook_entry = {
+ "matcher": "Bash",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "repowise augment",
+ "timeout": 10,
+ "statusMessage": "Checking wiki freshness...",
+ }
+ ],
+ }
+
+ try:
+ if settings_path.exists():
+ try:
+ existing = json.loads(settings_path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ existing = {}
+ else:
+ settings_path.parent.mkdir(parents=True, exist_ok=True)
+ existing = {}
+
+ hooks = existing.setdefault("hooks", {})
+
+ # Merge PreToolUse — avoid duplicates
+ pre_hooks = hooks.setdefault("PreToolUse", [])
+ if not _has_repowise_hook(pre_hooks):
+ pre_hooks.append(pre_hook_entry)
+
+ # Merge PostToolUse — avoid duplicates
+ post_hooks = hooks.setdefault("PostToolUse", [])
+ if not _has_repowise_hook(post_hooks):
+ post_hooks.append(post_hook_entry)
+
+ settings_path.write_text(
+ json.dumps(existing, indent=2) + "\n", encoding="utf-8"
+ )
+ return settings_path
+ except OSError:
+ return None
+
+
+def _has_repowise_hook(hook_list: list) -> bool:
+ """Check if a repowise augment hook is already registered."""
+ for entry in hook_list:
+ for hook in entry.get("hooks", []):
+ cmd = hook.get("command", "")
+ if "repowise augment" in cmd:
+ return True
+ return False
+
+
def format_setup_instructions(repo_path: Path) -> str:
"""Return human-readable setup instructions for MCP clients."""
config = generate_mcp_config(repo_path)
diff --git a/packages/cli/src/repowise/cli/ui.py b/packages/cli/src/repowise/cli/ui.py
index 087fc3303..597c99cf2 100644
--- a/packages/cli/src/repowise/cli/ui.py
+++ b/packages/cli/src/repowise/cli/ui.py
@@ -3,12 +3,15 @@
from __future__ import annotations
import os
+import subprocess
+from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import click
from rich.console import Console, Group
from rich.panel import Panel
+from rich.progress import ProgressColumn, Task
from rich.prompt import Prompt
from rich.rule import Rule
from rich.table import Table
@@ -47,6 +50,192 @@ def print_banner(console: Console, repo_name: str | None = None) -> None:
console.print()
+# ---------------------------------------------------------------------------
+# Quick repo pre-scan (fast, no AST)
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class RepoScanInfo:
+ """Lightweight repo stats collected before mode selection."""
+
+ total_files: int = 0
+ language_counts: dict[str, int] = field(default_factory=dict)
+ total_commits: int = 0
+ test_file_count: int = 0
+ infra_file_count: int = 0
+ submodule_count: int = 0
+ large_dirs: list[tuple[str, int]] = field(default_factory=list)
+ """(dir_name, file_count) for dirs with >50 files — used for exclude suggestions."""
+
+
+_TEST_PATTERNS = {"test_", "_test.", ".test.", "tests/", "test/", "__tests__/", "spec/"}
+_INFRA_NAMES = {"dockerfile", "makefile", "jenkinsfile", "terraform", ".tf", ".sh", ".bash"}
+_LANG_MAP: dict[str, list[str]] = {
+ "Python": [".py"],
+ "TypeScript": [".ts", ".tsx"],
+ "JavaScript": [".js", ".jsx", ".mjs", ".cjs"],
+ "Go": [".go"],
+ "Rust": [".rs"],
+ "Java": [".java"],
+ "C#": [".cs"],
+ "Ruby": [".rb"],
+ "PHP": [".php"],
+ "Swift": [".swift"],
+ "Kotlin": [".kt", ".kts"],
+ "C/C++": [".c", ".cpp", ".cc", ".h", ".hpp"],
+ "Scala": [".scala"],
+ "Dart": [".dart"],
+ "Lua": [".lua"],
+ "Shell": [".sh", ".bash", ".zsh"],
+ "HTML": [".html", ".htm"],
+ "CSS": [".css", ".scss", ".sass", ".less"],
+ "YAML": [".yaml", ".yml"],
+ "JSON": [".json"],
+ "Markdown": [".md", ".mdx"],
+ "SQL": [".sql"],
+}
+_EXT_TO_LANG: dict[str, str] = {}
+for _lang, _exts in _LANG_MAP.items():
+ for _ext in _exts:
+ _EXT_TO_LANG[_ext] = _lang
+
+_SKIP_DIRS = {
+ "node_modules",
+ ".venv",
+ "venv",
+ "__pycache__",
+ "dist",
+ "build",
+ ".next",
+ "target",
+ "vendor",
+ ".git",
+ ".hg",
+ "env",
+ ".tox",
+ ".mypy_cache",
+ ".ruff_cache",
+ ".pytest_cache",
+ "site-packages",
+}
+
+
+def quick_repo_scan(repo_path: Path) -> RepoScanInfo:
+ """Fast pre-scan: count files, detect languages, count git commits.
+
+ No AST parsing — just ``os.walk`` + extension histogram + ``git rev-list --count``.
+ Typically completes in <2s even on large repos.
+ """
+ info = RepoScanInfo()
+ dir_counts: dict[str, int] = {}
+
+ for dirpath, dirnames, filenames in os.walk(repo_path):
+ # Prune heavy/irrelevant directories in-place
+ dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS and not d.startswith(".")]
+
+ rel_dir = os.path.relpath(dirpath, repo_path)
+ top_dir = rel_dir.split(os.sep)[0] if rel_dir != "." else "."
+
+ for fname in filenames:
+ info.total_files += 1
+ lower = fname.lower()
+ ext = os.path.splitext(lower)[1]
+
+ # Language detection
+ lang = _EXT_TO_LANG.get(ext)
+ if lang:
+ info.language_counts[lang] = info.language_counts.get(lang, 0) + 1
+
+ # Test file detection
+ full_rel = os.path.join(rel_dir, lower).replace("\\", "/")
+ if any(p in full_rel for p in _TEST_PATTERNS):
+ info.test_file_count += 1
+
+ # Infra file detection
+ if lower in _INFRA_NAMES or ext in _INFRA_NAMES:
+ info.infra_file_count += 1
+
+ # Track top-level dir sizes for exclude suggestions
+ if top_dir != ".":
+ dir_counts[top_dir] = dir_counts.get(top_dir, 0) + 1
+
+ # Large dirs (>50 files) sorted by size
+ info.large_dirs = sorted(
+ [(d, c) for d, c in dir_counts.items() if c > 50],
+ key=lambda x: -x[1],
+ )
+
+ # Git commit count (fast)
+ try:
+ result = subprocess.run(
+ ["git", "rev-list", "--count", "HEAD"],
+ cwd=str(repo_path),
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ if result.returncode == 0:
+ info.total_commits = int(result.stdout.strip())
+ except Exception:
+ pass
+
+ # Submodule count
+ gitmodules = repo_path / ".gitmodules"
+ if gitmodules.exists():
+ try:
+ content = gitmodules.read_text(encoding="utf-8", errors="ignore")
+ info.submodule_count = content.count("[submodule ")
+ except Exception:
+ pass
+
+ return info
+
+
+def print_scan_summary(console: Console, scan: RepoScanInfo) -> None:
+ """Print a compact pre-scan summary below the banner."""
+ # File count + language count
+ lang_count = len(
+ [
+ name
+ for name, c in scan.language_counts.items()
+ if c > 0 and name not in ("JSON", "YAML", "Markdown", "HTML", "CSS")
+ ]
+ )
+
+ parts = [f"[bold]{scan.total_files:,}[/bold] files"]
+ if lang_count:
+ parts.append(f"[bold]{lang_count}[/bold] languages")
+ if scan.total_commits:
+ parts.append(f"[bold]{scan.total_commits:,}[/bold] commits")
+
+ header_line = " · ".join(parts)
+
+ # Top languages (source code only, top 4)
+ source_langs = {
+ lang: count
+ for lang, count in scan.language_counts.items()
+ if lang not in ("JSON", "YAML", "Markdown", "HTML", "CSS")
+ }
+ total_source = sum(source_langs.values()) or 1
+ top_langs = sorted(source_langs.items(), key=lambda x: -x[1])[:4]
+ lang_parts = [f"{lang} {count / total_source:.0%}" for lang, count in top_langs]
+ if len(source_langs) > 4:
+ lang_parts.append(f"+{len(source_langs) - 4} more")
+ lang_line = ", ".join(lang_parts) if lang_parts else "no source files detected"
+
+ body = f" {header_line}\n [dim]{lang_line}[/dim]"
+
+ console.print(
+ Panel(
+ body,
+ border_style="dim",
+ padding=(0, 1),
+ )
+ )
+ console.print()
+
+
# ---------------------------------------------------------------------------
# Phase headers
# ---------------------------------------------------------------------------
@@ -354,12 +543,19 @@ def _prompt_api_key(
# ---------------------------------------------------------------------------
-def interactive_advanced_config(console: Console) -> dict[str, Any]:
- """Prompt for advanced init options.
+def interactive_advanced_config(
+ console: Console,
+ scan: RepoScanInfo | None = None,
+) -> dict[str, Any]:
+ """Prompt for advanced init options, grouped into logical sections.
+
+ When *scan* is provided, uses it for smart defaults and contextual hints
+ (file counts, suggested exclude patterns, etc.).
Returns a dict with keys matching init_command kwargs:
``commit_limit``, ``follow_renames``, ``skip_tests``, ``skip_infra``,
- ``concurrency``, ``exclude``, ``test_run``.
+ ``concurrency``, ``exclude``, ``test_run``, ``embedder``,
+ ``include_submodules``, ``no_claude_md``.
"""
console.print()
console.print(
@@ -368,81 +564,157 @@ def interactive_advanced_config(console: Console) -> dict[str, Any]:
style=DIM,
)
)
- console.print()
result: dict[str, Any] = {}
- # --- commit limit ---
+ # ── Scope ─────────────────────────────────────────────────────────────
+ console.print()
+ console.print(f" [{BRAND}]Scope[/]")
+ console.print(" [dim]Choose what to include in the analysis[/dim]")
+ console.print()
+
+ test_hint = f" ({scan.test_file_count:,} found)" if scan and scan.test_file_count else ""
+ result["skip_tests"] = click.confirm(
+ f" Skip test files?{test_hint}",
+ default=False,
+ )
+
+ infra_hint = f" ({scan.infra_file_count:,} found)" if scan and scan.infra_file_count else ""
+ result["skip_infra"] = click.confirm(
+ f" Skip infrastructure files?{infra_hint} (Dockerfile, CI, Makefile …)",
+ default=False,
+ )
+
+ if scan and scan.submodule_count:
+ result["include_submodules"] = click.confirm(
+ f" Include git submodules? ({scan.submodule_count} found)",
+ default=False,
+ )
+ else:
+ result["include_submodules"] = False
+
+ # ── Exclude Patterns ──────────────────────────────────────────────────
+ console.print()
+ console.print(f" [{BRAND}]Exclude Patterns[/]")
+
+ # Show suggestions from large dirs
+ if scan and scan.large_dirs:
+ suggestions = scan.large_dirs[:5]
+ console.print(" [dim]Large directories detected:[/dim]")
+ for dirname, count in suggestions:
+ console.print(f" [dim]{dirname}/[/dim] [dim]({count:,} files)[/dim]")
+ console.print()
+
+ console.print(" [dim]Gitignore-style patterns, comma-separated or one per line.[/dim]")
+ console.print(" [dim]Press Enter with empty input to finish.[/dim]")
+ patterns: list[str] = []
+ while True:
+ raw = click.prompt(" Pattern", default="", show_default=False)
+ raw = raw.strip()
+ if not raw:
+ break
+ # Support comma-separated input
+ for part in raw.split(","):
+ part = part.strip()
+ if part:
+ patterns.append(part)
+ result["exclude"] = tuple(patterns)
+
+ # ── Git Analysis ──────────────────────────────────────────────────────
+ console.print()
+ console.print(f" [{BRAND}]Git Analysis[/]")
+ commit_hint = ""
+ if scan and scan.total_commits:
+ commit_hint = f" [dim](repo has ~{scan.total_commits:,} total commits)[/dim]"
+ console.print(f" [dim]Controls how deeply git history is analyzed[/dim]{commit_hint}")
+ console.print()
+
+ # Smart default based on repo size
+ default_limit = 500
+ if scan:
+ if scan.total_files < 500:
+ default_limit = 1000
+ elif scan.total_files > 5000:
+ default_limit = 200
+
val = click.prompt(
- " Max commits to analyze per file",
- default=500,
+ " Max commits per file",
+ default=default_limit,
type=int,
)
val = max(1, min(val, 5000))
result["commit_limit"] = val
- # --- follow renames ---
result["follow_renames"] = click.confirm(
" Track files across git renames? (slower but more accurate)",
default=False,
)
- # --- skip tests ---
- result["skip_tests"] = click.confirm(
- " Skip test files?",
- default=False,
- )
+ # ── Generation ────────────────────────────────────────────────────────
+ console.print()
+ console.print(f" [{BRAND}]Generation[/]")
+ console.print(" [dim]LLM page generation settings[/dim]")
+ console.print()
- # --- skip infra ---
- result["skip_infra"] = click.confirm(
- " Skip infrastructure files? (Dockerfile, CI, Makefile …)",
- default=False,
- )
+ # Smart concurrency default
+ default_concurrency = 5
+ if scan and scan.total_files < 200:
+ default_concurrency = 8
+ elif scan and scan.total_files > 5000:
+ default_concurrency = 3
- # --- concurrency ---
result["concurrency"] = click.prompt(
" Max concurrent LLM calls",
- default=5,
+ default=default_concurrency,
type=int,
)
- # --- exclude patterns ---
- console.print(
- " [dim]Exclude patterns (gitignore-style). Enter one per line, empty line to finish:[/dim]"
+ # Embedder selection
+ detected_embedder = _resolve_embedder_from_env()
+ embedder_choices = ["gemini", "openai", "mock"]
+ result["embedder"] = click.prompt(
+ " Embedder for RAG",
+ default=detected_embedder,
+ type=click.Choice(embedder_choices),
)
- patterns: list[str] = []
- while True:
- raw = click.prompt(" Exclude pattern", default="", show_default=False)
- raw = raw.strip()
- if not raw:
- break
- patterns.append(raw)
- result["exclude"] = tuple(patterns)
- # --- test run ---
result["test_run"] = click.confirm(
" Test run? (limit to top 10 files for quick validation)",
default=False,
)
- # --- summary ---
+ # ── Editor Integration ────────────────────────────────────────────────
+ console.print()
+ console.print(f" [{BRAND}]Editor Integration[/]")
+ console.print()
+
+ result["no_claude_md"] = not click.confirm(
+ " Generate .claude/CLAUDE.md?",
+ default=True,
+ )
+
+ # ── Summary ───────────────────────────────────────────────────────────
console.print()
summary = Table(box=None, padding=(0, 2), show_header=False)
summary.add_column("Option", style="dim")
summary.add_column("Value", style="bold")
- summary.add_row("Commit limit", str(result["commit_limit"]))
- summary.add_row("Follow renames", "yes" if result["follow_renames"] else "no")
summary.add_row("Skip tests", "yes" if result["skip_tests"] else "no")
summary.add_row("Skip infra", "yes" if result["skip_infra"] else "no")
+ if result["include_submodules"]:
+ summary.add_row("Include submodules", "yes")
+ summary.add_row("Commit limit", str(result["commit_limit"]))
+ summary.add_row("Follow renames", "yes" if result["follow_renames"] else "no")
summary.add_row("Concurrency", str(result["concurrency"]))
+ summary.add_row("Embedder", result["embedder"])
if patterns:
summary.add_row("Exclude", ", ".join(patterns))
summary.add_row("Test run", "yes" if result["test_run"] else "no")
+ summary.add_row("CLAUDE.md", "no" if result["no_claude_md"] else "yes")
console.print(
Panel(
summary,
- title="[bold]Configuration[/bold]",
+ title="[bold]Configuration Summary[/bold]",
border_style=BRAND,
padding=(0, 1),
)
@@ -451,6 +723,15 @@ def interactive_advanced_config(console: Console) -> dict[str, Any]:
return result
+def _resolve_embedder_from_env() -> str:
+ """Auto-detect embedder from env vars (for advanced config default)."""
+ if os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY"):
+ return "gemini"
+ if os.environ.get("OPENAI_API_KEY"):
+ return "openai"
+ return "mock"
+
+
# ---------------------------------------------------------------------------
# Index-only confirmation screen
# ---------------------------------------------------------------------------
@@ -484,6 +765,61 @@ def print_index_only_intro(console: Console, has_provider: bool = False) -> None
console.print()
+# ---------------------------------------------------------------------------
+# Analysis summary panel (shown between analysis and generation)
+# ---------------------------------------------------------------------------
+
+
+def build_analysis_summary_panel(
+ *,
+ file_count: int,
+ symbol_count: int,
+ graph_nodes: int,
+ graph_edges: int,
+ dead_unreachable: int = 0,
+ dead_unused: int = 0,
+ dead_lines: int = 0,
+ decision_count: int = 0,
+ git_files: int = 0,
+ hotspot_count: int = 0,
+ community_count: int = 0,
+ lang_summary: str = "",
+) -> Panel:
+ """Compact analysis-complete interstitial shown before generation."""
+ lines: list[str] = []
+ lines.append(
+ f" [bold]{file_count:,}[/bold] files · "
+ f"[bold]{symbol_count:,}[/bold] symbols"
+ + (f" · [bold]{community_count}[/bold] communities" if community_count else "")
+ )
+ if lang_summary:
+ lines.append(f" [dim]{lang_summary}[/dim]")
+ lines.append("")
+ lines.append(
+ f" Graph [bold]{graph_nodes:,}[/bold] nodes · [bold]{graph_edges:,}[/bold] edges"
+ )
+ if git_files:
+ lines.append(
+ f" Git [bold]{git_files:,}[/bold] files indexed"
+ + (f" · [bold]{hotspot_count}[/bold] hotspots" if hotspot_count else "")
+ )
+ if dead_unreachable or dead_unused:
+ lines.append(
+ f" Dead [bold]{dead_unreachable}[/bold] unreachable · "
+ f"[bold]{dead_unused}[/bold] unused exports"
+ + (f" · ~{dead_lines:,} lines" if dead_lines else "")
+ )
+ if decision_count:
+ lines.append(f" Decisions [bold]{decision_count}[/bold] extracted")
+
+ return Panel(
+ "\n".join(lines),
+ title="[bold]Analysis Complete[/bold]",
+ border_style=BRAND,
+ padding=(1, 1),
+ )
+
+
# ---------------------------------------------------------------------------
# Completion panels
# ---------------------------------------------------------------------------
@@ -523,6 +859,171 @@ def build_completion_panel(
)
+def build_contextual_next_steps(
+ *,
+ index_only: bool,
+ dead_unreachable: int = 0,
+ dead_unused: int = 0,
+ hotspot_count: int = 0,
+ decision_count: int = 0,
+ top_hotspot: str = "",
+) -> list[tuple[str, str]]:
+ """Build next-step suggestions based on what the analysis actually found."""
+ steps: list[tuple[str, str]] = []
+
+ if index_only:
+ steps.append(("repowise mcp .", "start MCP server for AI assistants"))
+ steps.append(("repowise init --provider gemini", "generate full documentation"))
+ else:
+ steps.append(("repowise mcp .", "start MCP server for AI assistants"))
+ steps.append(("repowise search <query>", "search the generated wiki"))
+
+ if dead_unreachable + dead_unused > 0:
+ steps.append(
+ ("repowise dead-code", f"explore {dead_unreachable + dead_unused} dead code findings")
+ )
+
+ if hotspot_count > 0 and top_hotspot:
+ steps.append((f"repowise risk {top_hotspot}", "assess risk for top hotspot"))
+
+ if decision_count > 0:
+ steps.append(("repowise decisions", f"browse {decision_count} architectural decisions"))
+
+ if not steps:
+ steps.append(("repowise mcp .", "start MCP server for AI assistants"))
+ steps.append(("repowise search <query>", "search the index"))
+
+ return steps
+
+
+# ---------------------------------------------------------------------------
+# Workspace: interactive repo selection
+# ---------------------------------------------------------------------------
+
+
+def interactive_repo_select(
+ console: Console,
+ repos: list[Any],
+) -> list[Any]:
+ """Display discovered repos and let the user pick which ones to index.
+
+ *repos* is a list of :class:`~repowise.core.workspace.scanner.DiscoveredRepo`.
+ Returns the selected subset in original order.
+ """
+ # Build display table
+ table = Table(
+ show_header=True,
+ box=None,
+ padding=(0, 2),
+ title="[bold]Discovered Repositories[/bold]",
+ title_style="",
+ )
+ table.add_column("#", style=BRAND_STYLE, width=4)
+ table.add_column("Repository", style="bold", min_width=16)
+ table.add_column("Path", style="dim", min_width=20)
+ table.add_column("Status", min_width=14)
+
+ for idx, repo in enumerate(repos, 1):
+ status = f"[{OK}]indexed[/]" if repo.has_repowise else "[dim]new[/dim]"
+ if repo.is_submodule:
+ status += " [dim](submodule)[/dim]"
+ table.add_row(f"[{idx}]", repo.name, str(repo.path.name), status)
+
+ console.print()
+ console.print(table)
+ console.print()
+
+ # Selection prompt with retry
+ while True:
+ raw = Prompt.ask(
+ " Select repos to index",
+ default="all",
+ console=console,
+ )
+ raw = raw.strip().lower()
+
+ if raw == "all":
+ return list(repos)
+ if raw == "none":
+ return []
+
+ selected = _parse_selection(raw, len(repos))
+ if selected is not None:
+ return [repos[i] for i in selected]
+
+ console.print(
+ f" [{WARN}]Invalid selection. Use numbers (1,2,3), ranges (1-3), 'all', or 'none'.[/]"
+ )
+
+
+def _parse_selection(raw: str, count: int) -> list[int] | None:
+ """Parse a comma-separated selection string into zero-based indices.
+
+ Supports: ``"1,2,3"``, ``"1-3"``, ``"1,3-5"``, ``"1-3,5"``.
+ Returns ``None`` on invalid input.
+ """
+ indices: list[int] = []
+ for part in raw.split(","):
+ part = part.strip()
+ if not part:
+ continue
+ if "-" in part:
+ bounds = part.split("-", 1)
+ try:
+ lo, hi = int(bounds[0]), int(bounds[1])
+ except ValueError:
+ return None
+ if lo < 1 or hi > count or lo > hi:
+ return None
+ indices.extend(range(lo - 1, hi))
+ else:
+ try:
+ num = int(part)
+ except ValueError:
+ return None
+ if num < 1 or num > count:
+ return None
+ indices.append(num - 1)
+
+ if not indices:
+ return None
+
+ # Deduplicate while preserving order
+ seen: set[int] = set()
+ result: list[int] = []
+ for i in indices:
+ if i not in seen:
+ seen.add(i)
+ result.append(i)
+ return result
+
+
+def interactive_primary_select(
+ console: Console,
+ repos: list[Any],
+) -> str:
+ """Ask which repo is the primary/default. Returns the alias.
+
+ *repos* is the list of selected :class:`DiscoveredRepo` objects.
+ """
+ if len(repos) == 1:
+ return repos[0].alias
+
+ console.print()
+ for idx, repo in enumerate(repos, 1):
+ console.print(f" [{BRAND_STYLE}][{idx}][/] {repo.name}")
+ console.print()
+
+ choices = [str(i) for i in range(1, len(repos) + 1)]
+ chosen = Prompt.ask(
+ " Which is your primary repo?",
+ choices=choices,
+ default="1",
+ console=console,
+ )
+ return repos[int(chosen) - 1].alias
+
+
# ---------------------------------------------------------------------------
# Utility
# ---------------------------------------------------------------------------
@@ -537,6 +1038,29 @@ def format_elapsed(seconds: float) -> str:
return f"{seconds:.1f}s"
+# ---------------------------------------------------------------------------
+# Rich progress helpers
+# ---------------------------------------------------------------------------
+
+
+class MaybeCountColumn(ProgressColumn):
+ """Progress column that shows ``completed/total`` when total is known,
+ or just ``completed`` when total is ``None`` (indeterminate phase).
+
+ This prevents the ugly ``1214/None`` display that appears for phases
+ like file traversal and dead-code detection whose total is not known
+ upfront.
+ """
+
+ def render(self, task: Task) -> Text:
+ if task.total is None:
+ return Text(str(int(task.completed)), style="progress.download")
+ return Text(
+ f"{int(task.completed)}/{int(task.total)}",
+ style="progress.download",
+ )
+
+
# ---------------------------------------------------------------------------
# Rich progress callback — implements core ProgressCallback protocol
# ---------------------------------------------------------------------------
@@ -585,7 +1109,10 @@ class RichProgressCallback:
def on_message(self, level: str, text: str) -> None:
style_map = {"info": OK, "warning": WARN, "error": ERR}
style = style_map.get(level, "")
- if style:
+ # Insight lines (indented with →) get special formatting
+ if text.lstrip().startswith("→"):
+ self._progress.console.print(f" [dim]{text}[/dim]")
+ elif style:
self._progress.console.print(f" [{style}]{text}[/{style}]")
else:
self._progress.console.print(f" {text}")
diff --git a/packages/core/alembic/versions/0015_symbol_graph.py b/packages/core/alembic/versions/0015_symbol_graph.py
new file mode 100644
index 000000000..07a219451
--- /dev/null
+++ b/packages/core/alembic/versions/0015_symbol_graph.py
@@ -0,0 +1,79 @@
+"""Add symbol-level graph nodes and call edges with confidence scoring.
+
+Extends graph_nodes with symbol-specific columns (kind, name, file_path,
+start_line, end_line, visibility, signature, parent_symbol_id) and adds
+confidence to graph_edges. Updates the unique constraint on graph_edges
+to include edge_type for multi-edge support.
+
+Revision ID: 0015
+Revises: 0014
+Create Date: 2026-04-11
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "0015"
+down_revision = "0014"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ # --- graph_nodes: add symbol-level columns ---
+ with op.batch_alter_table("graph_nodes") as batch_op:
+ batch_op.add_column(sa.Column("kind", sa.String(32), nullable=True))
+ batch_op.add_column(sa.Column("name", sa.String(255), nullable=True))
+ batch_op.add_column(sa.Column("qualified_name", sa.Text(), nullable=True))
+ batch_op.add_column(sa.Column("file_path", sa.Text(), nullable=True))
+ batch_op.add_column(sa.Column("start_line", sa.Integer(), nullable=True))
+ batch_op.add_column(sa.Column("end_line", sa.Integer(), nullable=True))
+ batch_op.add_column(sa.Column("visibility", sa.String(16), nullable=True))
+ batch_op.add_column(sa.Column("signature", sa.Text(), nullable=True))
+ batch_op.add_column(sa.Column("parent_symbol_id", sa.Text(), nullable=True))
+
+ # --- graph_edges: add confidence column ---
+ with op.batch_alter_table("graph_edges") as batch_op:
+ batch_op.add_column(
+ sa.Column("confidence", sa.Float(), nullable=False, server_default="1.0")
+ )
+ # Make edge_type non-nullable with a default
+ batch_op.alter_column(
+ "edge_type",
+ existing_type=sa.String(64),
+ nullable=False,
+ server_default="imports",
+ )
+ # Drop old unique constraint, add new one that includes edge_type
+ batch_op.drop_constraint("uq_graph_edge", type_="unique")
+ batch_op.create_unique_constraint(
+ "uq_graph_edge_typed",
+ ["repository_id", "source_node_id", "target_node_id", "edge_type"],
+ )
+
+
+def downgrade() -> None:
+ with op.batch_alter_table("graph_edges") as batch_op:
+ batch_op.drop_constraint("uq_graph_edge_typed", type_="unique")
+ batch_op.create_unique_constraint(
+ "uq_graph_edge",
+ ["repository_id", "source_node_id", "target_node_id"],
+ )
+ batch_op.alter_column(
+ "edge_type",
+ existing_type=sa.String(64),
+ nullable=True,
+ server_default=None,
+ )
+ batch_op.drop_column("confidence")
+
+ with op.batch_alter_table("graph_nodes") as batch_op:
+ batch_op.drop_column("parent_symbol_id")
+ batch_op.drop_column("signature")
+ batch_op.drop_column("visibility")
+ batch_op.drop_column("end_line")
+ batch_op.drop_column("start_line")
+ batch_op.drop_column("file_path")
+ batch_op.drop_column("qualified_name")
+ batch_op.drop_column("name")
+ batch_op.drop_column("kind")
diff --git a/packages/core/alembic/versions/0016_community_meta.py b/packages/core/alembic/versions/0016_community_meta.py
new file mode 100644
index 000000000..4ace9f096
--- /dev/null
+++ b/packages/core/alembic/versions/0016_community_meta.py
@@ -0,0 +1,34 @@
+"""Add community_meta_json column to graph_nodes.
+
+Stores per-node community metadata (label, cohesion for file nodes;
+symbol_community_id for symbol nodes) as a JSON text column.
+
+Revision ID: 0016
+Revises: 0015
+Create Date: 2026-04-11
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "0016"
+down_revision = "0015"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ with op.batch_alter_table("graph_nodes") as batch_op:
+ batch_op.add_column(
+ sa.Column(
+ "community_meta_json",
+ sa.Text(),
+ nullable=False,
+ server_default="{}",
+ )
+ )
+
+
+def downgrade() -> None:
+ with op.batch_alter_table("graph_nodes") as batch_op:
+ batch_op.drop_column("community_meta_json")
diff --git a/packages/core/alembic/versions/0017_graph_query_indexes.py b/packages/core/alembic/versions/0017_graph_query_indexes.py
new file mode 100644
index 000000000..78c856758
--- /dev/null
+++ b/packages/core/alembic/versions/0017_graph_query_indexes.py
@@ -0,0 +1,41 @@
+"""Add composite indexes for performant graph queries.
+
+Indexes support the new MCP graph query tools (get_callers_callees,
+get_community, get_graph_metrics, get_execution_flows) which filter
+by (repo, node_type, community) and (repo, source/target, edge_type).
+
+Revision ID: 0017
+Revises: 0016
+Create Date: 2026-04-12
+"""
+
+from alembic import op
+
+revision = "0017"
+down_revision = "0016"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.create_index(
+ "ix_graph_nodes_repo_type_community",
+ "graph_nodes",
+ ["repository_id", "node_type", "community_id"],
+ )
+ op.create_index(
+ "ix_graph_edges_repo_target_type",
+ "graph_edges",
+ ["repository_id", "target_node_id", "edge_type"],
+ )
+ op.create_index(
+ "ix_graph_edges_repo_source_type",
+ "graph_edges",
+ ["repository_id", "source_node_id", "edge_type"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_graph_edges_repo_source_type", table_name="graph_edges")
+ op.drop_index("ix_graph_edges_repo_target_type", table_name="graph_edges")
+ op.drop_index("ix_graph_nodes_repo_type_community", table_name="graph_nodes")
diff --git a/packages/core/src/repowise/core/__init__.py b/packages/core/src/repowise/core/__init__.py
index db3ddfd2e..5120e7968 100644
--- a/packages/core/src/repowise/core/__init__.py
+++ b/packages/core/src/repowise/core/__init__.py
@@ -6,4 +6,4 @@ generation engine. This is the heart of repowise — all other packages depend o
Namespace package: repowise.core is part of the repowise namespace.
"""
-__version__ = "0.2.3"
+__version__ = "0.3.0"
diff --git a/packages/core/src/repowise/core/analysis/communities.py b/packages/core/src/repowise/core/analysis/communities.py
new file mode 100644
index 000000000..3f10fb2ba
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/communities.py
@@ -0,0 +1,583 @@
+"""Community detection on dependency graphs.
+
+Uses Leiden (graspologic) when available, falls back to Louvain (networkx).
+Supports both file-level and symbol-level community detection with:
+- Oversized community splitting (second pass on communities >25% of graph)
+- Cohesion scoring (intra-community edge density)
+- Heuristic labeling (dominant directory / keyword analysis)
+"""
+
+from __future__ import annotations
+
+import contextlib
+import inspect
+import io
+import re
+import sys
+from collections import Counter
+from dataclasses import dataclass, field
+from pathlib import PurePosixPath
+
+import networkx as nx
+import structlog
+
+log = structlog.get_logger(__name__)
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+_MAX_COMMUNITY_FRACTION = 0.30
+_MIN_SPLIT_SIZE = 20
+
+# Edge types to include when building file-level community subgraph
+_FILE_COMMUNITY_EDGE_TYPES = frozenset({
+ "imports", "framework", "dynamic", "extends", "implements",
+})
+
+# Edge types to include when building symbol-level community subgraph
+_SYMBOL_COMMUNITY_EDGE_TYPES = frozenset({
+ "calls", "extends", "implements", "has_method",
+})
+
+# Generic directory segments excluded from heuristic labeling.
+# These are organisational containers, not meaningful domain labels.
+_GENERIC_SEGMENTS = frozenset({
+ "src", "lib", "core", "common", "shared", "internal", "pkg",
+ "main", "app", "utils", "helpers", "index", "mod",
+ # Monorepo organisational directories
+ "packages", "modules", "workspace", "workspaces", "libs",
+ "projects", "services", "apps",
+})
+
+# Keywords checked in filename stems for fallback labeling
+_LABEL_KEYWORDS = (
+ "api", "auth", "model", "service", "handler", "router", "db",
+ "cache", "worker", "util", "test", "config", "middleware", "schema",
+ "controller", "view", "store", "hook", "plugin", "adapter",
+)
+
+
+# ---------------------------------------------------------------------------
+# Data models
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class CommunityInfo:
+ """Metadata for a single detected community."""
+
+ community_id: int
+ label: str
+ members: list[str]
+ size: int
+ cohesion: float
+ dominant_language: str
+
+
+# ---------------------------------------------------------------------------
+# Output suppression (Windows PowerShell 5.1 ANSI fix)
+# ---------------------------------------------------------------------------
+
+
+def _suppress_graspologic_output():
+ """Suppress stdout/stderr during graspologic calls.
+
+ graspologic's leiden() emits ANSI escape sequences that corrupt
+ PowerShell 5.1's scroll buffer on Windows.
+ """
+ old_stderr = sys.stderr
+ try:
+ sys.stderr = io.StringIO()
+ with contextlib.redirect_stdout(io.StringIO()):
+ yield
+ finally:
+ sys.stderr = old_stderr
+
+
+# ---------------------------------------------------------------------------
+# Partition (Leiden / Louvain)
+# ---------------------------------------------------------------------------
+
+
+def _partition(G: nx.Graph) -> tuple[dict, str]:
+ """Run community detection. Returns ({node: community_id}, algorithm_name).
+
+ Tries Leiden (graspologic) first, falls back to Louvain (networkx).
+ """
+ try:
+ from graspologic.partition import leiden
+
+ with _suppress_graspologic_output():
+ result = leiden(G)
+ return result, "leiden"
+ except ImportError:
+ pass
+
+ # Fallback: networkx Louvain
+ kwargs: dict = {"seed": 42, "threshold": 1e-4}
+ if "max_level" in inspect.signature(nx.community.louvain_communities).parameters:
+ kwargs["max_level"] = 10
+
+ communities = nx.community.louvain_communities(G, **kwargs)
+ assignment = {node: cid for cid, nodes in enumerate(communities) for node in nodes}
+ return assignment, "louvain"
+
+
+# ---------------------------------------------------------------------------
+# Oversized community splitting
+# ---------------------------------------------------------------------------
+
+
+def _split_community(
+ G: nx.Graph, nodes: list[str],
+) -> list[list[str]]:
+ """Run a second partition pass on an oversized community subgraph."""
+ subgraph = G.subgraph(nodes)
+ if subgraph.number_of_edges() == 0:
+ return [[n] for n in sorted(nodes)]
+ try:
+ sub_partition, _ = _partition(subgraph)
+ sub_communities: dict[int, list[str]] = {}
+ for node, cid in sub_partition.items():
+ sub_communities.setdefault(cid, []).append(node)
+ if len(sub_communities) <= 1:
+ return [sorted(nodes)]
+ return [sorted(v) for v in sub_communities.values()]
+ except Exception:
+ return [sorted(nodes)]
+
+
+def _split_oversized(
+ G: nx.Graph,
+ communities: dict[int, list[str]],
+ max_fraction: float = _MAX_COMMUNITY_FRACTION,
+ min_split_size: int = _MIN_SPLIT_SIZE,
+) -> list[list[str]]:
+ """Split any community exceeding max_fraction of total nodes."""
+ total = sum(len(v) for v in communities.values())
+ max_size = max(min_split_size, int(total * max_fraction))
+
+ result: list[list[str]] = []
+ for nodes in communities.values():
+ if len(nodes) > max_size:
+ result.extend(_split_community(G, nodes))
+ else:
+ result.append(nodes)
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Cohesion scoring
+# ---------------------------------------------------------------------------
+
+
+def _cohesion_score(G: nx.Graph, community_nodes: list[str]) -> float:
+ """Ratio of actual intra-community edges to maximum possible."""
+ n = len(community_nodes)
+ if n <= 1:
+ return 1.0
+ subgraph = G.subgraph(community_nodes)
+ actual = subgraph.number_of_edges()
+ possible = n * (n - 1) / 2
+ return round(actual / possible, 4) if possible > 0 else 0.0
+
+
+# ---------------------------------------------------------------------------
+# Heuristic labeling
+# ---------------------------------------------------------------------------
+
+
+def _collect_path_segments(member_paths: list[str]) -> Counter[str]:
+ """Count non-generic directory segments across all member paths.
+
+ Each path contributes at most once per segment to avoid
+ double-counting files deep in the same directory tree.
+ """
+ counter: Counter[str] = Counter()
+ for path in member_paths:
+ parts = PurePosixPath(path).parts
+ seen: set[str] = set()
+ for part in parts[:-1]: # exclude filename
+ lower = part.lower()
+ if lower not in _GENERIC_SEGMENTS and len(lower) > 1 and not lower.startswith("."):
+ if lower not in seen:
+ counter[lower] += 1
+ seen.add(lower)
+ return counter
+
+
+def _best_sub_label(member_paths: list[str], primary: str) -> str:
+ """Find the best distinguishing sub-segment within paths that contain *primary*.
+
+ Given a community labeled "web", looks at paths containing "web" and
+ picks the most common *other* non-generic segment (e.g. "components",
+ "api", "hooks") as a sub-label.
+ """
+ sub_counter: Counter[str] = Counter()
+ primary_lower = primary.lower()
+
+ for path in member_paths:
+ parts = PurePosixPath(path).parts
+ # Only consider paths that actually contain the primary segment
+ lowers = [p.lower() for p in parts[:-1]]
+ if primary_lower not in lowers:
+ continue
+ seen: set[str] = set()
+ for part in parts[:-1]:
+ lower = part.lower()
+ if (
+ lower != primary_lower
+ and lower not in _GENERIC_SEGMENTS
+ and len(lower) > 1
+ and not lower.startswith(".")
+ and lower not in seen
+ ):
+ sub_counter[lower] += 1
+ seen.add(lower)
+
+ if sub_counter:
+ best, best_count = sub_counter.most_common(1)[0]
+ # Require at least 30% of members to share this sub-segment
+ if best_count / max(len(member_paths), 1) >= 0.3:
+ return best
+ return ""
+
+
+def _heuristic_label(member_paths: list[str], community_id: int) -> str:
+ """Derive a human-readable label from member file paths.
+
+ Produces labels like ``"web/components"`` or ``"repowise/ingestion"``.
+ When multiple communities share the same top-level segment, the
+ sub-label differentiates them.
+ """
+ if not member_paths:
+ return f"cluster_{community_id}"
+
+ # Strategy 1: most common non-generic directory segment
+ seg_counter = _collect_path_segments(member_paths)
+
+ if seg_counter:
+ best_seg, best_count = seg_counter.most_common(1)[0]
+ if best_count / len(member_paths) >= 0.4:
+ # Try to find a distinguishing sub-segment
+ sub = _best_sub_label(member_paths, best_seg)
+ return f"{best_seg}/{sub}" if sub else best_seg
+
+ # Strategy 2: keyword frequency in filenames
+ stem_counter: Counter[str] = Counter()
+ for path in member_paths:
+ stem = PurePosixPath(path).stem.lower()
+ for kw in _LABEL_KEYWORDS:
+ if kw in stem:
+ stem_counter[kw] += 1
+
+ if stem_counter:
+ best_kw, best_kw_count = stem_counter.most_common(1)[0]
+ if best_kw_count / len(member_paths) >= 0.3:
+ return best_kw
+
+ # Strategy 3: most common filename stem (excluding generic names)
+ stem_counter2: Counter[str] = Counter()
+ for path in member_paths:
+ stem = PurePosixPath(path).stem.lower()
+ if stem not in _GENERIC_SEGMENTS and len(stem) > 1:
+ stem_counter2[stem] += 1
+ if stem_counter2:
+ return stem_counter2.most_common(1)[0][0]
+
+ return f"cluster_{community_id}"
+
+
+def _deduplicate_labels(communities_info: dict[int, "CommunityInfo"]) -> None:
+ """Add sub-labels to disambiguate communities that share the same label.
+
+ Mutates *communities_info* in place. Only touches communities whose
+ label (before the ``/``) duplicates another community.
+ """
+ # Group by base label (part before "/")
+ by_base: dict[str, list[int]] = {}
+ for cid, ci in communities_info.items():
+ base = ci.label.split("/")[0]
+ by_base.setdefault(base, []).append(cid)
+
+ for base, cids in by_base.items():
+ if len(cids) <= 1:
+ continue
+
+ # Multiple communities share the same base — try to differentiate
+ for cid in cids:
+ ci = communities_info[cid]
+ if "/" in ci.label:
+ continue # already has a sub-label
+
+ sub = _best_sub_label(ci.members, base)
+ if sub:
+ ci.label = f"{base}/{sub}"
+
+ # If duplicates still remain, append size as disambiguator
+ seen_labels: dict[str, int] = {}
+ for cid in sorted(cids, key=lambda c: -communities_info[c].size):
+ ci = communities_info[cid]
+ if ci.label in seen_labels:
+ ci.label = f"{ci.label} ({ci.size})"
+ seen_labels[ci.label] = cid
+
+
+def _dominant_language(
+ members: list[str], graph: nx.DiGraph,
+) -> str:
+ """Find the most common language among community members."""
+ lang_counter: Counter[str] = Counter()
+ for node_id in members:
+ data = graph.nodes.get(node_id, {})
+ lang = data.get("language")
+ if lang and lang != "unknown":
+ lang_counter[lang] += 1
+ if lang_counter:
+ return lang_counter.most_common(1)[0][0]
+ return "unknown"
+
+
+# ---------------------------------------------------------------------------
+# Test / production separation
+# ---------------------------------------------------------------------------
+
+_TEST_PATH_RE = re.compile(
+ r"(test[s_/]|_test\.|\.test\.|\.spec\.|__tests__|conftest|fixture[s]?[/.])",
+ re.IGNORECASE,
+)
+
+
+def _is_test_file(path: str) -> bool:
+ """True if *path* looks like a test, fixture, or spec file."""
+ return bool(_TEST_PATH_RE.search(path))
+
+
+def _assign_tests_to_communities(
+ test_nodes: list[str],
+ prod_assignment: dict[str, int],
+ graph: nx.DiGraph,
+) -> dict[str, int]:
+ """Assign each test file to the community of its most-imported production file.
+
+ Falls back to a catch-all "tests" community when no import link exists.
+ """
+ result: dict[str, int] = {}
+ next_cid = max(prod_assignment.values(), default=-1) + 1
+ test_community_id = next_cid # shared fallback
+
+ for test_path in test_nodes:
+ # Find which production file this test imports most
+ best_prod: str | None = None
+ best_weight = 0
+ for _, target, d in graph.out_edges(test_path, data=True):
+ if target in prod_assignment:
+ w = 1
+ best_prod = target if w > best_weight else best_prod
+ best_weight = max(best_weight, w)
+ for source, _, d in graph.in_edges(test_path, data=True):
+ if source in prod_assignment:
+ w = 1
+ best_prod = source if w > best_weight else best_prod
+ best_weight = max(best_weight, w)
+
+ if best_prod is not None:
+ result[test_path] = prod_assignment[best_prod]
+ else:
+ result[test_path] = test_community_id
+
+ return result
+
+
+# ---------------------------------------------------------------------------
+# File-level community detection
+# ---------------------------------------------------------------------------
+
+
+def detect_file_communities(
+ graph: nx.DiGraph,
+) -> tuple[dict[str, int], dict[int, CommunityInfo], str]:
+ """Detect communities among file nodes.
+
+ Returns:
+ (file_assignment, communities_info, algorithm_used)
+ - file_assignment: {file_path: community_id}
+ - communities_info: {community_id: CommunityInfo}
+ - algorithm_used: "leiden" or "louvain"
+ """
+ # Extract file nodes (exclude external nodes — they're structural noise)
+ file_nodes = [
+ n for n, d in graph.nodes(data=True)
+ if d.get("node_type", "file") == "file"
+ ]
+
+ if not file_nodes:
+ return {}, {}, "none"
+
+ # Separate test files from production files. Test files are clustered
+ # separately then assigned to the community of their most-imported
+ # production file, preventing test directories from dominating labels
+ # and mixing unrelated production modules.
+ prod_nodes = [n for n in file_nodes if not _is_test_file(n)]
+ test_nodes = [n for n in file_nodes if _is_test_file(n)]
+
+ # Build undirected subgraph from production files + relevant edges
+ undirected = nx.Graph()
+ undirected.add_nodes_from(prod_nodes)
+
+ for u, v, d in graph.edges(data=True):
+ edge_type = d.get("edge_type", "imports")
+ if edge_type in _FILE_COMMUNITY_EDGE_TYPES and u in undirected and v in undirected:
+ if not undirected.has_edge(u, v):
+ undirected.add_edge(u, v)
+
+ # Separate isolates
+ isolates = [n for n in undirected.nodes() if undirected.degree(n) == 0]
+ connected = [n for n in undirected.nodes() if undirected.degree(n) > 0]
+
+ raw_communities: dict[int, list[str]] = {}
+ algorithm = "none"
+
+ if connected:
+ connected_subgraph = undirected.subgraph(connected)
+ partition, algorithm = _partition(connected_subgraph)
+
+ for node, cid in partition.items():
+ raw_communities.setdefault(cid, []).append(node)
+
+ # Each isolate gets its own community
+ next_cid = max(raw_communities.keys(), default=-1) + 1
+ for node in isolates:
+ raw_communities[next_cid] = [node]
+ next_cid += 1
+
+ # Split oversized communities
+ split_lists = _split_oversized(undirected, raw_communities)
+
+ # Re-index by size descending for deterministic ordering
+ split_lists.sort(key=len, reverse=True)
+
+ # Build production file assignment
+ prod_assignment: dict[str, int] = {}
+ for cid, members in enumerate(split_lists):
+ for node in members:
+ prod_assignment[node] = cid
+
+ # Assign test files to their most-related production community
+ test_assignment = _assign_tests_to_communities(test_nodes, prod_assignment, graph)
+ file_assignment = {**prod_assignment, **test_assignment}
+
+ # Build community info (using all members including tests)
+ community_members: dict[int, list[str]] = {}
+ for node, cid in file_assignment.items():
+ community_members.setdefault(cid, []).append(node)
+
+ communities_info: dict[int, CommunityInfo] = {}
+ # Also build an undirected graph including test edges for cohesion scoring
+ full_undirected = nx.Graph()
+ full_undirected.add_nodes_from(file_nodes)
+ for u, v, d in graph.edges(data=True):
+ edge_type = d.get("edge_type", "imports")
+ if edge_type in _FILE_COMMUNITY_EDGE_TYPES and u in full_undirected and v in full_undirected:
+ if not full_undirected.has_edge(u, v):
+ full_undirected.add_edge(u, v)
+
+ for cid, members in community_members.items():
+ sorted_members = sorted(members)
+ communities_info[cid] = CommunityInfo(
+ community_id=cid,
+ label=_heuristic_label(sorted_members, cid),
+ members=sorted_members,
+ size=len(sorted_members),
+ cohesion=_cohesion_score(full_undirected, sorted_members),
+ dominant_language=_dominant_language(sorted_members, graph),
+ )
+
+ # Deduplicate labels — add sub-labels when multiple communities
+ # share the same base (e.g. "web" → "web/components", "web/api")
+ _deduplicate_labels(communities_info)
+
+ log.info(
+ "file_communities_detected",
+ total_files=len(file_nodes),
+ prod_files=len(prod_nodes),
+ test_files=len(test_nodes),
+ communities=len(communities_info),
+ algorithm=algorithm,
+ )
+
+ return file_assignment, communities_info, algorithm
+
+
+# ---------------------------------------------------------------------------
+# Symbol-level community detection
+# ---------------------------------------------------------------------------
+
+
+def detect_symbol_communities(graph: nx.DiGraph) -> dict[str, int]:
+ """Detect communities among symbol nodes using calls/heritage edges.
+
+ Returns {symbol_id: community_id}.
+ """
+ symbol_nodes = [
+ n for n, d in graph.nodes(data=True)
+ if d.get("node_type") == "symbol"
+ ]
+
+ if not symbol_nodes:
+ return {}
+
+ # Build undirected subgraph from call/heritage edges only
+ symbol_set = frozenset(symbol_nodes)
+ undirected = nx.Graph()
+ undirected.add_nodes_from(symbol_nodes)
+
+ for u, v, d in graph.edges(data=True):
+ edge_type = d.get("edge_type")
+ if (
+ edge_type in _SYMBOL_COMMUNITY_EDGE_TYPES
+ and u in symbol_set
+ and v in symbol_set
+ ):
+ if not undirected.has_edge(u, v):
+ undirected.add_edge(u, v)
+
+ # Separate isolates
+ connected = [n for n in undirected.nodes() if undirected.degree(n) > 0]
+
+ if not connected:
+ # No edges — each symbol is its own community
+ return {sym: i for i, sym in enumerate(sorted(symbol_nodes))}
+
+ connected_subgraph = undirected.subgraph(connected)
+ partition, _ = _partition(connected_subgraph)
+
+ # Build communities dict for re-indexing
+ raw: dict[int, list[str]] = {}
+ for node, cid in partition.items():
+ raw.setdefault(cid, []).append(node)
+
+ # Assign isolates
+ next_cid = max(raw.keys(), default=-1) + 1
+ isolates = [n for n in undirected.nodes() if undirected.degree(n) == 0]
+ for node in isolates:
+ raw[next_cid] = [node]
+ next_cid += 1
+
+ # Re-index by size descending
+ ordered = sorted(raw.values(), key=len, reverse=True)
+ result: dict[str, int] = {}
+ for cid, members in enumerate(ordered):
+ for node in members:
+ result[node] = cid
+
+ log.info(
+ "symbol_communities_detected",
+ total_symbols=len(symbol_nodes),
+ connected=len(connected),
+ communities=len(ordered),
+ )
+
+ return result
diff --git a/packages/core/src/repowise/core/analysis/dead_code.py b/packages/core/src/repowise/core/analysis/dead_code.py
index c01798866..dc623ac7f 100644
--- a/packages/core/src/repowise/core/analysis/dead_code.py
+++ b/packages/core/src/repowise/core/analysis/dead_code.py
@@ -96,6 +96,23 @@ _NEVER_FLAG_PATTERNS = (
"*postcss.config.*",
"*jest.config.*",
"*vitest.config.*",
+ # Next.js / Remix / SvelteKit framework route files — loaded by the
+ # framework at runtime, never imported via module imports.
+ "*/page.tsx",
+ "*/page.ts",
+ "*/page.jsx",
+ "*/page.js",
+ "*/layout.tsx",
+ "*/layout.ts",
+ "*/route.tsx",
+ "*/route.ts",
+ "*/loading.tsx",
+ "*/error.tsx",
+ "*/not-found.tsx",
+ "*/template.tsx",
+ "*/default.tsx",
+ # Nuxt route pages
+ "*/pages/*.vue",
)
# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)
@@ -353,11 +370,18 @@ class DeadCodeAnalyzer:
age_days = git_meta.get("age_days")
primary_owner = git_meta.get("primary_owner_name")
- # Confidence rules
- if commit_90d == 0 and last_commit and self._is_old(last_commit, days=180):
- confidence = 1.0
+ # Confidence rules — differentiate by age and activity.
+ # _is_old uses strict >, so pass days-1 to get >= semantics.
+ if commit_90d == 0 and last_commit and self._is_old(last_commit, days=364):
+ confidence = 1.0 # Untouched for a year+ — very likely dead
+ elif commit_90d == 0 and last_commit and self._is_old(last_commit, days=179):
+ confidence = 0.9 # Untouched for 6+ months
+ elif commit_90d == 0 and last_commit and self._is_old(last_commit, days=89):
+ confidence = 0.8 # Untouched for 3+ months
+ elif commit_90d == 0 and age_days is not None and age_days < 30:
+ confidence = 0.55 # Recently created but no imports — may be WIP
elif commit_90d == 0:
- confidence = 0.7
+ confidence = 0.7 # No recent activity, unknown age
else:
confidence = 0.4
@@ -548,6 +572,28 @@ class DeadCodeAnalyzer:
for f in files
if f in self.graph
)
+ # Aggregate git metadata across package files for enrichment
+ pkg_last_commit: datetime | None = None
+ pkg_total_commits_90d = 0
+ pkg_owner: str | None = None
+ owner_counts: dict[str, int] = {}
+ for f in files:
+ gm = self.git_meta_map.get(f)
+ if gm is None:
+ continue
+ f_last = getattr(gm, "last_commit_at", None)
+ if f_last and (pkg_last_commit is None or f_last > pkg_last_commit):
+ pkg_last_commit = f_last
+ pkg_total_commits_90d += getattr(gm, "commit_count_90d", 0) or 0
+ f_owner = getattr(gm, "primary_owner_name", None)
+ if f_owner:
+ owner_counts[f_owner] = owner_counts.get(f_owner, 0) + 1
+ if owner_counts:
+ pkg_owner = max(owner_counts, key=lambda k: owner_counts[k])
+ pkg_age_days: int | None = None
+ if pkg_last_commit:
+ pkg_age_days = (datetime.now(UTC) - pkg_last_commit).days
+
findings.append(
DeadCodeFindingData(
kind=DeadCodeKind.ZOMBIE_PACKAGE,
@@ -556,14 +602,14 @@ class DeadCodeAnalyzer:
symbol_kind=None,
confidence=0.5,
reason=f"Package '{pkg}' has no importers from other packages",
- last_commit_at=None,
- commit_count_90d=0,
+ last_commit_at=pkg_last_commit,
+ commit_count_90d=pkg_total_commits_90d,
lines=total_lines,
package=pkg,
evidence=[f"No inter-package imports into '{pkg}'"],
safe_to_delete=False,
- primary_owner=None,
- age_days=None,
+ primary_owner=pkg_owner,
+ age_days=pkg_age_days,
)
)
diff --git a/packages/core/src/repowise/core/analysis/decision_extractor.py b/packages/core/src/repowise/core/analysis/decision_extractor.py
index 0a2c281a5..2148c8cc3 100644
--- a/packages/core/src/repowise/core/analysis/decision_extractor.py
+++ b/packages/core/src/repowise/core/analysis/decision_extractor.py
@@ -83,6 +83,9 @@ _SKIP_DIRS = frozenset(
}
)
+# Regex to detect fenced code blocks in markdown files (``` or ~~~).
+_CODE_FENCE_RE = re.compile(r"^\s*(`{3,}|~{3,})")
+
_BINARY_EXTENSIONS = frozenset(
{
".png",
@@ -289,7 +292,18 @@ class DecisionExtractor:
continue
lines = text.splitlines()
+ # Track whether we're inside a fenced code block in markdown
+ # files so we don't treat example markers as real decisions.
+ is_markdown = file_path.suffix.lower() in (".md", ".mdx", ".rst")
+ in_code_fence = False
for line_num, line in enumerate(lines, start=1):
+ if is_markdown:
+ fence_match = _CODE_FENCE_RE.match(line)
+ if fence_match:
+ in_code_fence = not in_code_fence
+ continue
+ if in_code_fence:
+ continue
m = MARKER_RE.match(line)
if m:
# Collect continuation lines (same comment prefix, no keyword)
@@ -559,6 +573,10 @@ class DecisionExtractor:
if len(content) > 50_000:
continue
+ # Strip fenced code blocks to avoid treating example markers
+ # (e.g. `# WHY: ...` in code examples) as real decisions.
+ content = self._strip_code_blocks(content)
+
try:
rel_path = str(doc_path.relative_to(self._repo_path))
except ValueError:
@@ -761,12 +779,27 @@ class DecisionExtractor:
# ------------------------------------------------------------------
def _iter_source_files(self):
- """Yield source files under repo_path, skipping irrelevant dirs."""
- for child in self._repo_path.rglob("*"):
- if any(part in _SKIP_DIRS for part in child.parts):
- continue
- if child.is_file() and child.suffix.lower() not in _BINARY_EXTENSIONS:
- yield child
+ """Yield source files under repo_path, skipping irrelevant dirs.
+
+ Uses os.walk so we can prune entire subtrees (nested git repos,
+ node_modules, etc.) without descending into them.
+ """
+ import os
+
+ for dirpath, dirnames, filenames in os.walk(self._repo_path):
+ # Prune skip-listed directories in-place so os.walk won't descend
+ dirnames[:] = [
+ d for d in dirnames
+ if d not in _SKIP_DIRS
+ # Skip nested git repositories — they are separate codebases
+ # and should not contribute decisions to the parent repo.
+ and not (Path(dirpath) / d / ".git").exists()
+ ]
+
+ for fname in filenames:
+ fpath = Path(dirpath) / fname
+ if fpath.suffix.lower() not in _BINARY_EXTENSIONS:
+ yield fpath
def _get_neighbors(self, file_path: str) -> list[str]:
"""Get 1-hop graph neighbors for a file."""
@@ -779,6 +812,20 @@ class DecisionExtractor:
neighbors.discard(file_path)
return list(neighbors)[:20] # Cap at 20
+ @staticmethod
+ def _strip_code_blocks(text: str) -> str:
+ """Remove fenced code blocks from markdown to avoid parsing examples."""
+ lines = text.splitlines()
+ out: list[str] = []
+ in_fence = False
+ for line in lines:
+ if _CODE_FENCE_RE.match(line):
+ in_fence = not in_fence
+ continue
+ if not in_fence:
+ out.append(line)
+ return "\n".join(out)
+
def _infer_modules(self, file_paths: list[str]) -> list[str]:
"""Infer top-level module paths from file paths."""
modules: set[str] = set()
diff --git a/packages/core/src/repowise/core/analysis/execution_flows.py b/packages/core/src/repowise/core/analysis/execution_flows.py
new file mode 100644
index 000000000..87efe5a83
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/execution_flows.py
@@ -0,0 +1,359 @@
+"""Execution flow tracing on dependency graphs.
+
+Identifies entry points via composite scoring, then traces call paths
+via BFS to discover execution flows. Flows are classified as
+intra-community or cross-community based on community assignments.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import deque
+from dataclasses import dataclass, field
+
+import networkx as nx
+import structlog
+
+log = structlog.get_logger(__name__)
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+_MIN_ENTRY_POINT_SCORE = 0.3
+
+# Name patterns for entry point scoring (compiled once)
+_TIER1_NAMES = re.compile(
+ r"^(main|run|start|serve|cli|__main__|app|execute|bootstrap|init)$", re.IGNORECASE,
+)
+_TIER2_NAMES = re.compile(
+ r"^(handle_|on_|dispatch_|process_|route_|do_)", re.IGNORECASE,
+)
+_TIER3_NAMES = re.compile(
+ r"^(get_|create_|execute_|invoke_|fetch_|submit_|send_|post_)", re.IGNORECASE,
+)
+
+# Files to exclude from entry point scoring — test, demo, fixture, etc.
+_EXCLUDE_PATH_PATTERNS = re.compile(
+ r"("
+ r"test[s_/]|_test\.|\.test\.|\.spec\.|__tests__|conftest|"
+ r"fixture[s]?[/.]|mock[s]?[/.]|stub[s]?[/.]|fake[s]?[/.]|"
+ r"demo[_/.]|example[s]?[/.]|sample[s]?[/.]|"
+ r"benchmark[s]?[/.]|_bench\.|"
+ r"scripts?/"
+ r")",
+ re.IGNORECASE,
+)
+
+
+# ---------------------------------------------------------------------------
+# Data models
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class FlowConfig:
+ """Configuration for execution flow tracing."""
+
+ max_depth: int = 8
+ max_flows: int = 50
+ min_fan_out: int = 2
+ deduplicate: bool = True
+
+
+@dataclass
+class ExecutionFlow:
+ """A traced execution path from an entry point."""
+
+ entry_point_id: str
+ entry_point_name: str
+ entry_point_score: float
+ trace: list[str]
+ depth: int
+ crosses_community: bool
+ communities_visited: list[int]
+
+
+@dataclass
+class ExecutionFlowReport:
+ """Summary of all traced execution flows."""
+
+ total_entry_points_scored: int
+ total_flows: int
+ flows: list[ExecutionFlow]
+
+
+# ---------------------------------------------------------------------------
+# Entry point scoring
+# ---------------------------------------------------------------------------
+
+
+def _count_edges_by_type(
+ node_id: str, graph: nx.DiGraph, edge_type: str, direction: str,
+) -> int:
+ """Count edges of a specific type in a given direction."""
+ if direction == "out":
+ return sum(
+ 1 for _, _, d in graph.out_edges(node_id, data=True)
+ if d.get("edge_type") == edge_type
+ )
+ return sum(
+ 1 for _, _, d in graph.in_edges(node_id, data=True)
+ if d.get("edge_type") == edge_type
+ )
+
+
+def _score_entry_point(
+ node_id: str,
+ graph: nx.DiGraph,
+ community_map: dict[str, int],
+) -> float:
+ """Score a symbol as a potential entry point. Returns 0.0-1.0."""
+ data = graph.nodes.get(node_id, {})
+
+ # Skip external nodes and test files
+ if data.get("node_type") == "external":
+ return 0.0
+ file_path = data.get("file_path", "") or ""
+ if _EXCLUDE_PATH_PATTERNS.search(file_path):
+ return 0.0
+
+ # Signal 1: Fan-out ratio (weight 0.35)
+ out_calls = _count_edges_by_type(node_id, graph, "calls", "out")
+ in_calls = _count_edges_by_type(node_id, graph, "calls", "in")
+ total = in_calls + out_calls + 1
+ fan_out_signal = out_calls / total
+
+ # Signal 2: In-degree threshold (weight 0.25)
+ if in_calls == 0:
+ in_degree_signal = 1.0
+ elif in_calls == 1:
+ in_degree_signal = 0.5
+ else:
+ in_degree_signal = 0.0
+
+ # Signal 3: Visibility (weight 0.20)
+ visibility = data.get("visibility", "public")
+ if visibility == "public":
+ visibility_signal = 1.0
+ elif visibility == "protected":
+ visibility_signal = 0.3
+ else:
+ visibility_signal = 0.0
+
+ # Signal 4: Name pattern (weight 0.15)
+ name = data.get("name", "")
+ if _TIER1_NAMES.match(name):
+ name_signal = 1.0
+ elif _TIER2_NAMES.match(name):
+ name_signal = 0.7
+ elif _TIER3_NAMES.match(name):
+ name_signal = 0.4
+ else:
+ name_signal = 0.1
+
+ # Signal 5: Framework entry point hint (weight 0.05)
+ # Check if the containing file is marked as an entry point
+ file_node_data = graph.nodes.get(file_path, {})
+ framework_signal = 1.0 if file_node_data.get("is_entry_point", False) else 0.0
+
+ score = (
+ 0.35 * fan_out_signal
+ + 0.25 * in_degree_signal
+ + 0.20 * visibility_signal
+ + 0.15 * name_signal
+ + 0.05 * framework_signal
+ )
+
+ return round(score, 4)
+
+
+# ---------------------------------------------------------------------------
+# BFS tracing
+# ---------------------------------------------------------------------------
+
+
+def _get_call_successors(
+ node_id: str, graph: nx.DiGraph,
+) -> list[str]:
+ """Get outgoing call targets, sorted by out-degree descending."""
+ successors = []
+ for _, target, d in graph.out_edges(node_id, data=True):
+ if d.get("edge_type") == "calls" and d.get("confidence", 0) >= 0.5:
+ successors.append(target)
+
+ # Sort by out-degree descending to follow primary execution path
+ successors.sort(
+ key=lambda n: sum(
+ 1 for _, _, d in graph.out_edges(n, data=True)
+ if d.get("edge_type") == "calls"
+ ),
+ reverse=True,
+ )
+ return successors
+
+
+def _bfs_trace(
+ entry_id: str,
+ graph: nx.DiGraph,
+ community_map: dict[str, int],
+ config: FlowConfig,
+) -> ExecutionFlow | None:
+ """BFS trace from an entry point following call edges.
+
+ Follows the highest-fan-out successor at each step to build
+ the primary execution path.
+ """
+ data = graph.nodes.get(entry_id, {})
+ entry_name = data.get("name", entry_id.split("::")[-1] if "::" in entry_id else entry_id)
+
+ visited: set[str] = {entry_id}
+ trace: list[str] = [entry_id]
+ current = entry_id
+
+ for _ in range(config.max_depth):
+ successors = _get_call_successors(current, graph)
+ # Pick the first unvisited successor (highest fan-out)
+ next_node = None
+ for s in successors:
+ if s not in visited:
+ next_node = s
+ break
+
+ if next_node is None:
+ break
+
+ visited.add(next_node)
+ trace.append(next_node)
+ current = next_node
+
+ # Need at least 2 nodes for a meaningful trace
+ if len(trace) < 2:
+ return None
+
+ # Determine communities visited
+ communities_seen: list[int] = []
+ seen_cids: set[int] = set()
+ for node in trace:
+ cid = community_map.get(node, -1)
+ if cid not in seen_cids:
+ seen_cids.add(cid)
+ communities_seen.append(cid)
+
+ crosses = len(seen_cids) > 1
+
+ return ExecutionFlow(
+ entry_point_id=entry_id,
+ entry_point_name=entry_name,
+ entry_point_score=0.0, # filled by caller
+ trace=trace,
+ depth=len(trace) - 1,
+ crosses_community=crosses,
+ communities_visited=communities_seen,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Deduplication
+# ---------------------------------------------------------------------------
+
+
+def _deduplicate_flows(flows: list[ExecutionFlow]) -> list[ExecutionFlow]:
+ """Remove flows that share the same first 3 trace nodes, keeping the longest."""
+ if not flows:
+ return []
+
+ # Group by prefix key (first 3 nodes or full trace if shorter)
+ groups: dict[tuple[str, ...], ExecutionFlow] = {}
+ for flow in flows:
+ key = tuple(flow.trace[:3])
+ existing = groups.get(key)
+ if existing is None or len(flow.trace) > len(existing.trace):
+ groups[key] = flow
+
+ return list(groups.values())
+
+
+# ---------------------------------------------------------------------------
+# Main public function
+# ---------------------------------------------------------------------------
+
+
+def trace_execution_flows(
+ graph: nx.DiGraph,
+ community_map: dict[str, int],
+ config: FlowConfig | None = None,
+) -> ExecutionFlowReport:
+ """Trace execution flows from top-scored entry points.
+
+ Args:
+ graph: The full dependency graph with symbol nodes and call edges.
+ community_map: {node_id: community_id} from community detection.
+ config: Optional flow tracing configuration.
+
+ Returns:
+ ExecutionFlowReport with traced flows sorted by entry point score.
+ """
+ if config is None:
+ config = FlowConfig()
+
+ if graph.number_of_nodes() == 0:
+ return ExecutionFlowReport(
+ total_entry_points_scored=0, total_flows=0, flows=[],
+ )
+
+ # Score all symbol nodes that are functions/methods
+ candidates: list[tuple[str, float]] = []
+ for node_id, data in graph.nodes(data=True):
+ if data.get("node_type") != "symbol":
+ continue
+ kind = data.get("kind", "")
+ if kind not in ("function", "method"):
+ continue
+
+ # Must have minimum fan-out to be interesting
+ out_calls = sum(
+ 1 for _, _, d in graph.out_edges(node_id, data=True)
+ if d.get("edge_type") == "calls"
+ )
+ if out_calls < config.min_fan_out:
+ continue
+
+ score = _score_entry_point(node_id, graph, community_map)
+ if score >= _MIN_ENTRY_POINT_SCORE:
+ candidates.append((node_id, score))
+
+ candidates.sort(key=lambda x: -x[1])
+ top_candidates = candidates[:config.max_flows]
+
+ # Trace from each candidate
+ flows: list[ExecutionFlow] = []
+ for node_id, score in top_candidates:
+ flow = _bfs_trace(node_id, graph, community_map, config)
+ if flow is not None:
+ flow.entry_point_score = score
+ flows.append(flow)
+
+ # Deduplicate
+ if config.deduplicate:
+ before = len(flows)
+ flows = _deduplicate_flows(flows)
+ deduped = before - len(flows)
+ else:
+ deduped = 0
+
+ # Sort by score descending
+ flows.sort(key=lambda f: -f.entry_point_score)
+
+ log.info(
+ "execution_flows_traced",
+ candidates_scored=len(candidates),
+ traced=len(flows),
+ deduplicated=deduped,
+ )
+
+ return ExecutionFlowReport(
+ total_entry_points_scored=len(candidates),
+ total_flows=len(flows),
+ flows=flows,
+ )
diff --git a/packages/core/src/repowise/core/analysis/pr_blast.py b/packages/core/src/repowise/core/analysis/pr_blast.py
index 3404714c1..4d645bfd2 100644
--- a/packages/core/src/repowise/core/analysis/pr_blast.py
+++ b/packages/core/src/repowise/core/analysis/pr_blast.py
@@ -231,21 +231,35 @@ class PRBlastRadiusAnalyzer:
"""Return files that lack a corresponding test file.
Checks graph_nodes for paths matching test_<name>, <name>_test, or
- <name>.spec.* patterns.
+ <name>.spec.* patterns. Test files themselves are excluded — they
+ don't need their own tests.
"""
if not affected_files:
return []
node_res = await self._session.execute(
+ select(GraphNode.node_id, GraphNode.is_test).where(
+ GraphNode.repository_id == self._repo_id,
+ GraphNode.node_id.in_(affected_files),
+ )
+ )
+ # Build a set of affected files that are themselves test files
+ test_file_set = {row[0] for row in node_res.all() if row[1]}
+
+ # Fetch all test paths for matching
+ all_test_res = await self._session.execute(
select(GraphNode.node_id).where(
GraphNode.repository_id == self._repo_id,
GraphNode.is_test == True, # noqa: E712
)
)
- test_paths = {row[0] for row in node_res.all()}
+ test_paths = {row[0] for row in all_test_res.all()}
gaps = []
for path in affected_files:
+ # Skip test files — they don't need their own tests
+ if path in test_file_set:
+ continue
base = os.path.splitext(os.path.basename(path))[0]
ext = os.path.splitext(path)[1].lstrip(".")
has_test = any(
diff --git a/packages/core/src/repowise/core/generation/context_assembler.py b/packages/core/src/repowise/core/generation/context_assembler.py
index a06bdfb31..f879c3112 100644
--- a/packages/core/src/repowise/core/generation/context_assembler.py
+++ b/packages/core/src/repowise/core/generation/context_assembler.py
@@ -62,6 +62,11 @@ class FilePageContext:
dead_code_findings: list[dict] = field(default_factory=list)
depth: str = "standard"
dependency_summaries: dict[str, str] = field(default_factory=dict)
+ # Graph intelligence (Phase 5 enrichment)
+ call_graph: list[dict] = field(default_factory=list)
+ heritage: list[dict] = field(default_factory=list)
+ community_label: str = ""
+ community_cohesion: float = 0.0
@dataclass
@@ -90,6 +95,11 @@ class ModulePageContext:
dependents: list[str]
pagerank_mean: float
files: list[str]
+ # Graph intelligence enrichment
+ file_summaries: dict[str, str] = field(default_factory=dict)
+ community_label: str = ""
+ community_cohesion: float = 0.0
+ key_classes: list[dict] = field(default_factory=list)
@dataclass
@@ -123,6 +133,9 @@ class RepoOverviewContext:
entry_points: list[str]
top_files_by_pagerank: list[_TopFile]
circular_dependency_count: int
+ # Graph intelligence enrichment
+ communities: list[dict] = field(default_factory=list)
+ execution_flows: list[dict] = field(default_factory=list)
@dataclass
@@ -305,6 +318,11 @@ class ContextAssembler:
# Generation depth
depth = self._select_generation_depth(path, git_meta, pagerank.get(path, 0.0))
+ # Graph intelligence: call graph, heritage, community metadata
+ call_graph_entries = self._extract_call_graph(path, graph)
+ heritage_entries = self._extract_heritage(path, graph)
+ community_label, community_cohesion = self._extract_community_meta(path, graph)
+
return FilePageContext(
file_path=path,
language=parsed.file_info.language,
@@ -327,6 +345,10 @@ class ContextAssembler:
dead_code_findings=dead_code_findings or [],
depth=depth,
dependency_summaries=dep_summaries,
+ call_graph=call_graph_entries,
+ heritage=heritage_entries,
+ community_label=community_label,
+ community_cohesion=community_cohesion,
)
# ------------------------------------------------------------------
@@ -383,6 +405,7 @@ class ContextAssembler:
language: str,
file_contexts: list[FilePageContext],
graph: Any, # nx.DiGraph
+ page_summaries: dict[str, str] | None = None,
) -> ModulePageContext:
"""Assemble context for the module_page template."""
total_symbols = sum(len(fc.symbols) for fc in file_contexts)
@@ -406,6 +429,31 @@ class ContextAssembler:
if file_contexts:
pagerank_mean = sum(fc.pagerank_score for fc in file_contexts) / len(file_contexts)
+ # File summaries from completed pages (enriches module docs with what each file does)
+ file_summaries: dict[str, str] = {}
+ if page_summaries:
+ for fp in files:
+ if fp in page_summaries:
+ file_summaries[fp] = page_summaries[fp][:200]
+
+ # Community info: pick the dominant community label across files
+ community_label = ""
+ community_cohesion = 0.0
+ labels = [fc.community_label for fc in file_contexts if fc.community_label]
+ if labels:
+ from collections import Counter
+ community_label = Counter(labels).most_common(1)[0][0]
+ cohesions = [fc.community_cohesion for fc in file_contexts if fc.community_cohesion > 0]
+ if cohesions:
+ community_cohesion = sum(cohesions) / len(cohesions)
+
+ # Key classes: collect classes with heritage info from file contexts
+ key_classes: list[dict] = []
+ for fc in file_contexts:
+ for h in fc.heritage[:5]: # cap per file
+ key_classes.append(h)
+ key_classes = key_classes[:10] # cap total
+
return ModulePageContext(
module_path=module_path,
language=language,
@@ -416,6 +464,10 @@ class ContextAssembler:
dependents=sorted(all_dependents),
pagerank_mean=pagerank_mean,
files=files,
+ file_summaries=file_summaries,
+ community_label=community_label,
+ community_cohesion=community_cohesion,
+ key_classes=key_classes,
)
# ------------------------------------------------------------------
@@ -465,6 +517,7 @@ class ContextAssembler:
pagerank: dict[str, float],
sccs: list[Any], # list[frozenset[str]]
community: dict[str, int],
+ graph_builder: Any | None = None,
) -> RepoOverviewContext:
"""Assemble context for the repo_overview template."""
# Top files sorted by PageRank descending
@@ -478,6 +531,35 @@ class ContextAssembler:
# SCCs with len > 1 are true circular deps
circular_count = sum(1 for scc in sccs if len(scc) > 1)
+ # Community metadata from graph builder
+ communities_list: list[dict] = []
+ execution_flows_list: list[dict] = []
+ if graph_builder is not None:
+ try:
+ for ci in graph_builder.community_info():
+ communities_list.append({
+ "id": ci.id,
+ "label": ci.label,
+ "size": ci.size,
+ "cohesion": round(ci.cohesion, 2),
+ })
+ communities_list.sort(key=lambda c: c["size"], reverse=True)
+ communities_list = communities_list[:10]
+ except Exception:
+ pass
+
+ try:
+ flow_report = graph_builder.execution_flows()
+ if flow_report and hasattr(flow_report, "flows"):
+ for flow in flow_report.flows[:5]:
+ execution_flows_list.append({
+ "entry_point": flow.entry_point,
+ "score": round(flow.score, 3),
+ "trace_length": len(flow.trace) if hasattr(flow, "trace") else 0,
+ })
+ except Exception:
+ pass
+
return RepoOverviewContext(
repo_name=getattr(repo_structure, "name", "repo"),
is_monorepo=repo_structure.is_monorepo,
@@ -488,6 +570,8 @@ class ContextAssembler:
entry_points=repo_structure.entry_points,
top_files_by_pagerank=top_files,
circular_dependency_count=circular_count,
+ communities=communities_list,
+ execution_flows=execution_flows_list,
)
# ------------------------------------------------------------------
@@ -706,6 +790,99 @@ class ContextAssembler:
return self._trim_to_budget("\n".join(parts), budget)
+ # ------------------------------------------------------------------
+ # Graph intelligence extraction helpers
+ # ------------------------------------------------------------------
+
+ def _extract_call_graph(self, file_path: str, graph: Any) -> list[dict]:
+ """Extract symbol-level call edges for symbols defined in this file."""
+ entries: list[dict] = []
+ try:
+ for node, data in graph.nodes(data=True):
+ if data.get("node_type") != "symbol":
+ continue
+ if data.get("file_path") != file_path:
+ continue
+ # Outgoing calls from this symbol
+ for _, target, edata in graph.out_edges(node, data=True):
+ if edata.get("edge_type") == "calls":
+ tdata = graph.nodes.get(target, {})
+ entries.append({
+ "caller": data.get("name", node),
+ "callee": tdata.get("name", target),
+ "callee_file": tdata.get("file_path", ""),
+ "confidence": edata.get("confidence", 0.0),
+ })
+ # Incoming calls to this symbol
+ for source, _, edata in graph.in_edges(node, data=True):
+ if edata.get("edge_type") == "calls":
+ sdata = graph.nodes.get(source, {})
+ entries.append({
+ "caller": sdata.get("name", source),
+ "callee": data.get("name", node),
+ "callee_file": file_path,
+ "caller_file": sdata.get("file_path", ""),
+ "confidence": edata.get("confidence", 0.0),
+ })
+ except Exception:
+ pass
+ # Deduplicate and cap
+ seen: set[str] = set()
+ unique: list[dict] = []
+ for e in entries:
+ key = f"{e.get('caller')}→{e.get('callee')}"
+ if key not in seen:
+ seen.add(key)
+ unique.append(e)
+ return unique[:15]
+
+ def _extract_heritage(self, file_path: str, graph: Any) -> list[dict]:
+ """Extract extends/implements edges for symbols in this file."""
+ entries: list[dict] = []
+ try:
+ for node, data in graph.nodes(data=True):
+ if data.get("node_type") != "symbol":
+ continue
+ if data.get("file_path") != file_path:
+ continue
+ for _, target, edata in graph.out_edges(node, data=True):
+ etype = edata.get("edge_type", "")
+ if etype in ("extends", "implements"):
+ tdata = graph.nodes.get(target, {})
+ entries.append({
+ "child": data.get("name", node),
+ "parent": tdata.get("name", target),
+ "kind": etype,
+ "parent_file": tdata.get("file_path", ""),
+ })
+ for source, _, edata in graph.in_edges(node, data=True):
+ etype = edata.get("edge_type", "")
+ if etype in ("extends", "implements"):
+ sdata = graph.nodes.get(source, {})
+ entries.append({
+ "child": sdata.get("name", source),
+ "parent": data.get("name", node),
+ "kind": etype,
+ "child_file": sdata.get("file_path", ""),
+ })
+ except Exception:
+ pass
+ return entries[:10]
+
+ def _extract_community_meta(self, file_path: str, graph: Any) -> tuple[str, float]:
+ """Extract community label and cohesion for a file node."""
+ try:
+ node_data = graph.nodes.get(file_path, {})
+ meta = node_data.get("community_meta_json")
+ if meta:
+ import json as _json
+ if isinstance(meta, str):
+ meta = _json.loads(meta)
+ return meta.get("label", ""), meta.get("cohesion", 0.0)
+ except Exception:
+ pass
+ return "", 0.0
+
# ------------------------------------------------------------------
# Generation depth selection (Phase 5.5)
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/generation/editor_files/__init__.py b/packages/core/src/repowise/core/generation/editor_files/__init__.py
index 8cbf009c7..3af8106a3 100644
--- a/packages/core/src/repowise/core/generation/editor_files/__init__.py
+++ b/packages/core/src/repowise/core/generation/editor_files/__init__.py
@@ -6,25 +6,30 @@ Provides generators that create and maintain AI-editor configuration files
No LLM calls are made — all content is derived from the repowise DB.
"""
-from .claude_md import ClaudeMdGenerator
+from .claude_md import ClaudeMdGenerator, WorkspaceClaudeMdGenerator
from .data import (
DecisionSummary,
EditorFileData,
HotspotFile,
KeyModule,
TechStackItem,
+ WorkspaceEditorFileData,
+ WorkspaceRepoSummary,
)
from .fetcher import EditorFileDataFetcher
__all__ = [
# Generators
"ClaudeMdGenerator",
+ "WorkspaceClaudeMdGenerator",
# Data containers
"DecisionSummary",
"EditorFileData",
- # Fetcher
- "EditorFileDataFetcher",
"HotspotFile",
"KeyModule",
"TechStackItem",
+ "WorkspaceEditorFileData",
+ "WorkspaceRepoSummary",
+ # Fetcher
+ "EditorFileDataFetcher",
]
diff --git a/packages/core/src/repowise/core/generation/editor_files/claude_md.py b/packages/core/src/repowise/core/generation/editor_files/claude_md.py
index 76233ca15..b6b8fa37f 100644
--- a/packages/core/src/repowise/core/generation/editor_files/claude_md.py
+++ b/packages/core/src/repowise/core/generation/editor_files/claude_md.py
@@ -1,11 +1,14 @@
-"""ClaudeMdGenerator — generates and maintains .claude/CLAUDE.md for a repository."""
+"""ClaudeMdGenerator — generates and maintains .claude/CLAUDE.md for a repository.
+
+Also provides WorkspaceClaudeMdGenerator for workspace-level CLAUDE.md output.
+"""
from __future__ import annotations
from pathlib import Path
from .base import BaseEditorFileGenerator
-from .data import EditorFileData
+from .data import EditorFileData, WorkspaceEditorFileData
class ClaudeMdGenerator(BaseEditorFileGenerator):
@@ -38,3 +41,35 @@ class ClaudeMdGenerator(BaseEditorFileGenerator):
"""Preview what .claude/CLAUDE.md would contain without writing."""
dot_claude = repo_path / ".claude"
return super().render_full(dot_claude, data)
+
+
+class WorkspaceClaudeMdGenerator(BaseEditorFileGenerator):
+ """Generates and maintains a workspace-level .claude/CLAUDE.md.
+
+ Writes to <workspace_root>/.claude/CLAUDE.md and includes cross-repo
+ contracts, co-changes, package dependencies, and per-repo summaries.
+
+ The file has two sections:
+ - User section (above the REPOWISE markers): never touched by Repowise.
+ - Repowise section (between markers): auto-generated from workspace data.
+ """
+
+ filename = "CLAUDE.md"
+ marker_tag = "REPOWISE"
+ template_name = "workspace_claude_md.j2"
+ user_placeholder = (
+ "# CLAUDE.md\n\n"
+ "<!-- Workspace-level instructions for all repos. "
+ "Repowise will never modify anything outside the REPOWISE markers. -->\n"
+ )
+
+ def write(self, workspace_root: Path, data: WorkspaceEditorFileData) -> Path: # type: ignore[override]
+ """Write to <workspace_root>/.claude/CLAUDE.md, creating the directory if needed."""
+ dot_claude = workspace_root / ".claude"
+ dot_claude.mkdir(parents=True, exist_ok=True)
+ return super().write(dot_claude, data)
+
+ def render_full(self, workspace_root: Path, data: WorkspaceEditorFileData) -> str: # type: ignore[override]
+ """Preview what .claude/CLAUDE.md would contain without writing."""
+ dot_claude = workspace_root / ".claude"
+ return super().render_full(dot_claude, data)
diff --git a/packages/core/src/repowise/core/generation/editor_files/data.py b/packages/core/src/repowise/core/generation/editor_files/data.py
index 5761a84b8..183bd6716 100644
--- a/packages/core/src/repowise/core/generation/editor_files/data.py
+++ b/packages/core/src/repowise/core/generation/editor_files/data.py
@@ -38,6 +38,7 @@ class DecisionSummary:
title: str
status: str # active | deprecated | superseded | proposed
rationale: str # first ~100 chars of decision.rationale
+ decision: str = "" # what was chosen (first ~120 chars)
@dataclass(frozen=True)
@@ -53,3 +54,34 @@ class EditorFileData:
decisions: list[DecisionSummary] = field(default_factory=list)
build_commands: dict[str, str] = field(default_factory=dict)
avg_confidence: float = 0.0
+
+
+# ---------------------------------------------------------------------------
+# Workspace-level data containers
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class WorkspaceRepoSummary:
+ """Per-repo summary row within a workspace CLAUDE.md."""
+
+ alias: str
+ is_primary: bool
+ file_count: int
+ symbol_count: int
+ hotspot_count: int
+ entry_points: list[str] = field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class WorkspaceEditorFileData:
+ """All data needed to render the workspace-level CLAUDE.md template."""
+
+ workspace_name: str
+ workspace_root: str # absolute path string (for display only)
+ repos: list[WorkspaceRepoSummary] = field(default_factory=list)
+ default_repo: str = ""
+ co_changes: list[dict] = field(default_factory=list) # from cross_repo_edges.json
+ package_deps: list[dict] = field(default_factory=list) # package dep entries
+ contract_links: list[dict] = field(default_factory=list) # matched contract links
+ contracts_by_type: dict[str, int] = field(default_factory=dict) # {"http": 5, …}
diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
index 2de6c26a7..9f27cb0f9 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -179,13 +179,16 @@ class EditorFileDataFetcher:
records = list(result.scalars().all())
summaries: list[DecisionSummary] = []
for rec in records:
- rationale = (rec.rationale or rec.decision or "").strip()
+ rationale = (rec.rationale or "").strip()
rationale = rationale[:100].rstrip(".,;") if rationale else ""
+ decision_text = (rec.decision or "").strip()
+ decision_text = decision_text[:120].rstrip(".,;") if decision_text else ""
summaries.append(
DecisionSummary(
title=rec.title,
status=rec.status,
rationale=rationale,
+ decision=decision_text,
)
)
return summaries
diff --git a/packages/core/src/repowise/core/generation/page_generator.py b/packages/core/src/repowise/core/generation/page_generator.py
index 97f505049..24150a355 100644
--- a/packages/core/src/repowise/core/generation/page_generator.py
+++ b/packages/core/src/repowise/core/generation/page_generator.py
@@ -232,8 +232,12 @@ class PageGenerator:
file_contexts: list[FilePageContext],
graph: Any,
git_meta_map: dict[str, dict] | None = None,
+ page_summaries: dict[str, str] | None = None,
) -> GeneratedPage:
- ctx = self._assembler.assemble_module_page(module_path, language, file_contexts, graph)
+ ctx = self._assembler.assemble_module_page(
+ module_path, language, file_contexts, graph,
+ page_summaries=page_summaries,
+ )
module_git_summary = None
if git_meta_map:
from collections import Counter
@@ -288,8 +292,12 @@ class PageGenerator:
sccs: list[Any],
community: dict[str, int],
git_meta_map: dict[str, dict] | None = None,
+ graph_builder: Any | None = None,
) -> GeneratedPage:
- ctx = self._assembler.assemble_repo_overview(repo_structure, pagerank, sccs, community)
+ ctx = self._assembler.assemble_repo_overview(
+ repo_structure, pagerank, sccs, community,
+ graph_builder=graph_builder,
+ )
repo_git_summary = None
if git_meta_map:
metas = list(git_meta_map.values())
@@ -741,6 +749,7 @@ class PageGenerator:
betweenness,
community,
source_map.get(p.file_info.path, b""),
+ git_meta=git_meta_map.get(p.file_info.path) if git_meta_map else None,
page_summaries=completed_page_summaries,
)
file_page_contexts[p.file_info.path] = ctx
@@ -788,6 +797,7 @@ class PageGenerator:
fcs,
graph,
git_meta_map=git_meta_map,
+ page_summaries=completed_page_summaries,
),
)
for module, fcs in module_groups.items()
@@ -833,7 +843,9 @@ class PageGenerator:
(
compute_page_id("repo_overview", repo_name),
self.generate_repo_overview(
- repo_structure, pagerank, sccs, community, git_meta_map=git_meta_map
+ repo_structure, pagerank, sccs, community,
+ git_meta_map=git_meta_map,
+ graph_builder=graph_builder,
),
)
)
@@ -1088,70 +1100,44 @@ def _is_significant_file(
# Common words that appear in backticks but are not code symbols.
_BACKTICK_SKIP = frozenset(
{
- "True",
- "False",
- "None",
- "null",
- "undefined",
- "self",
- "cls",
- "this",
- "str",
- "int",
- "float",
- "bool",
- "list",
- "dict",
- "set",
- "tuple",
- "bytes",
- "object",
- "type",
- "Any",
- "Optional",
- "Union",
- "async",
- "await",
- "return",
- "yield",
- "import",
- "from",
- "class",
- "def",
- "if",
- "else",
- "for",
- "while",
- "try",
- "except",
- "raise",
- "with",
- "pass",
- "break",
- "continue",
- "lambda",
- "in",
- "not",
- "and",
- "or",
- "is",
- "del",
- "assert",
- "finally",
- "elif",
- "as",
- "pip",
- "npm",
- "go",
- "rust",
- "python",
- "node",
+ # Python builtins & keywords
+ "True", "False", "None", "self", "cls", "super",
+ "str", "int", "float", "bool", "list", "dict", "set", "tuple",
+ "bytes", "object", "type", "Any", "Optional", "Union",
+ "async", "await", "return", "yield", "import", "from",
+ "class", "def", "if", "else", "for", "while", "try", "except",
+ "raise", "with", "pass", "break", "continue", "lambda",
+ "in", "not", "and", "or", "is", "del", "assert", "finally",
+ "elif", "as", "global", "nonlocal",
+ # JS/TS keywords
+ "null", "undefined", "this", "const", "let", "var", "function",
+ "export", "default", "extends", "implements", "interface",
+ "enum", "new", "typeof", "instanceof", "void", "never",
+ "string", "number", "boolean", "symbol", "bigint", "unknown",
+ "readonly", "abstract", "static", "private", "protected", "public",
+ "require", "module", "exports", "Promise", "Map", "Set", "Array",
+ "Object", "Error", "Date", "RegExp", "JSON", "Math", "console",
+ # Common tool/ecosystem names
+ "pip", "npm", "npx", "yarn", "pnpm", "go", "rust", "python",
+ "node", "cargo", "uv", "git", "docker", "make",
+ # Common framework/lib names the LLM mentions in prose
+ "FastAPI", "React", "Next", "Express", "Django", "Flask",
+ "SQLAlchemy", "Pydantic", "Click", "Typer", "pytest",
+ "asyncio", "pathlib", "dataclass", "dataclasses",
}
)
# Regex: single-backtick references that look like identifiers.
_BACKTICK_REF_RE = re.compile(r"(?<!`)` *([A-Za-z_]\w*(?:\.\w+)*) *`(?!`)")
+# Patterns that indicate the backtick content is a path, command, or
+# value rather than a symbol reference — these should never be flagged.
+_PATH_OR_CMD_RE = re.compile(
+ r"[/\\]" # contains path separator
+ r"|\.(?:py|ts|js|json|yaml|yml|toml|md|sh|sql|css|html)$" # file extension
+ r"|^[a-z][\w-]*$" # all-lowercase with hyphens = CLI command/flag
+)
+
def _validate_symbol_references(
content: str,
@@ -1160,27 +1146,67 @@ def _validate_symbol_references(
"""Cross-check backtick-quoted names in LLM output against actual symbols.
Returns a list of warning strings for references that don't match any
- known symbol, export, or import in the ParsedFile.
+ known symbol, export, or import in the ParsedFile. Designed to have low
+ false-positive rates — only flags references that look like symbol names
+ but can't be found anywhere in the file's AST, imports, or source text.
"""
refs = set(_BACKTICK_REF_RE.findall(content))
if not refs:
return []
+ # Build the known-names set from AST data
known: set[str] = set()
for s in parsed.symbols:
known.add(s.name)
known.add(s.qualified_name)
+ # Decorator names are valid references (e.g. @app.command("init"))
+ for dec in s.decorators:
+ # Extract the decorator function name: "@app.command" → "command"
+ dec_name = dec.lstrip("@").split("(")[0]
+ known.add(dec_name)
+ known.add(dec_name.split(".")[-1])
known.update(parsed.exports)
for imp in parsed.imports:
if imp.module_path:
- known.add(imp.module_path.split(".")[-1])
+ # Add both the final component and intermediate segments
+ parts = imp.module_path.split(".")
+ known.update(parts)
known.update(imp.imported_names)
+ # Named bindings from import resolution
+ for binding in getattr(imp, "bindings", []):
+ known.add(binding.local_name)
+ if binding.exported_name:
+ known.add(binding.exported_name)
+
+ # Also add all string literals from the source that look like identifiers
+ # (catches Click command names, decorator arguments, dict keys, etc.)
+ source_text = ""
+ if hasattr(parsed, "file_info") and hasattr(parsed.file_info, "path"):
+ # The source is in the context, but we only have the parsed file here.
+ # Use docstring and symbol names as a cheap approximation.
+ if parsed.docstring:
+ known.update(w for w in parsed.docstring.split() if w.isidentifier())
warnings: list[str] = []
for ref in refs:
- if ref in _BACKTICK_SKIP or len(ref) < 2:
+ if ref in _BACKTICK_SKIP:
+ continue
+ # Skip short refs (1-2 chars are usually variables like `x`, `i`, `db`)
+ if len(ref) <= 2:
+ continue
+ # Skip anything that looks like a path, file, or CLI command
+ if _PATH_OR_CMD_RE.search(ref):
continue
+ # Skip all-uppercase (likely constants from other files: `MAX_RETRIES`)
+ if ref.isupper():
+ continue
+ # Check against known names
base = ref.split(".")[-1]
- if ref not in known and base not in known:
- warnings.append(ref)
+ if ref in known or base in known:
+ continue
+ # Skip if the ref is a substring of any known symbol (covers partial
+ # references like `parse` when `parse_file` exists)
+ if any(ref in k for k in known if len(k) > len(ref)):
+ continue
+ warnings.append(ref)
return warnings
diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2
index a25a872f8..0f870a752 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -77,19 +77,11 @@ This project has a Repowise MCP server configured. These tools provide documenta
| `get_dependency_path(source=..., target=...)` | When tracing module connections |
| `get_dead_code()` | Before any cleanup or removal |
| `get_architecture_diagram(scope=...)` | For visual structure or documentation |
-{% if data.decisions or data.build_commands %}
+{% if data.build_commands %}
### Codebase Conventions
-{% if data.decisions %}
-**Architectural Decisions:**
-{% for d in data.decisions %}
-- **{{ d.title }}**: {{ d.rationale }}{% if d.rationale %}.{% endif %}
-{% endfor %}
-{% endif %}
-{% if data.build_commands %}
**Commands:**
{% for label, cmd in data.build_commands.items() %}
- {{ label | capitalize }}: `{{ cmd }}`
{% endfor %}
{% endif %}
-{% endif %}
diff --git a/packages/core/src/repowise/core/generation/templates/file_page.j2 b/packages/core/src/repowise/core/generation/templates/file_page.j2
index 8206d8f83..dd27ebffc 100644
--- a/packages/core/src/repowise/core/generation/templates/file_page.j2
+++ b/packages/core/src/repowise/core/generation/templates/file_page.j2
@@ -119,6 +119,30 @@ Mention this relationship explicitly.
{% endif %}
{# ── End git context block ────────────────────────────────────── #}
+{% if ctx.call_graph %}
+## Call Graph
+Key function calls involving this file's symbols:
+{% for cg in ctx.call_graph %}
+- `{{ cg.caller }}` → `{{ cg.callee }}`{% if cg.callee_file and cg.callee_file != ctx.file_path %} (in `{{ cg.callee_file }}`){% endif %}{% if cg.caller_file is defined and cg.caller_file and cg.caller_file != ctx.file_path %} (from `{{ cg.caller_file }}`){% endif %}
+
+{% endfor %}
+Use this to explain how the file's functions connect to callers and callees.
+{% endif %}
+
+{% if ctx.heritage %}
+## Class Hierarchy
+{% for h in ctx.heritage %}
+- `{{ h.child }}` {{ h.kind }} `{{ h.parent }}`{% if h.parent_file is defined and h.parent_file %} (in `{{ h.parent_file }}`){% endif %}{% if h.child_file is defined and h.child_file %} (from `{{ h.child_file }}`){% endif %}
+
+{% endfor %}
+{% endif %}
+
+{% if ctx.community_label %}
+## Architectural Community
+This file belongs to the **{{ ctx.community_label }}** community{% if ctx.community_cohesion > 0 %} (cohesion: {{ "%.2f"|format(ctx.community_cohesion) }}){% endif %}.
+Use this to explain the file's role within its architectural cluster.
+{% endif %}
+
{% if ctx.dead_code_findings %}
## Potentially unused code
{% for finding in ctx.dead_code_findings %}
diff --git a/packages/core/src/repowise/core/generation/templates/module_page.j2 b/packages/core/src/repowise/core/generation/templates/module_page.j2
index 583a7a6d9..4927fc750 100644
--- a/packages/core/src/repowise/core/generation/templates/module_page.j2
+++ b/packages/core/src/repowise/core/generation/templates/module_page.j2
@@ -22,11 +22,29 @@ You are documenting the module at `{{ ctx.module_path }}` (language: {{ ctx.lang
- `{{ dep }}`
{% endfor %}
+{% if ctx.community_label %}
+## Architectural Community
+This module belongs to the **{{ ctx.community_label }}** cluster{% if ctx.community_cohesion > 0 %} (cohesion: {{ "%.2f"|format(ctx.community_cohesion) }}){% endif %}.
+{% endif %}
+
## Files in Module
{% for f in ctx.files %}
+{% set summary = ctx.file_summaries.get(f, '') %}
+{% if summary %}
+- `{{ f }}` — {{ summary }}
+{% else %}
- `{{ f }}`
+{% endif %}
{% endfor %}
+{% if ctx.key_classes %}
+## Class Hierarchy
+{% for h in ctx.key_classes %}
+- `{{ h.child }}` {{ h.kind }} `{{ h.parent }}`{% if h.parent_file is defined and h.parent_file %} (in `{{ h.parent_file }}`){% endif %}
+
+{% endfor %}
+{% endif %}
+
{% if module_git_summary is defined and module_git_summary %}
## Team ownership
{% for pkg_owner in module_git_summary.top_owners %}
diff --git a/packages/core/src/repowise/core/generation/templates/repo_overview.j2 b/packages/core/src/repowise/core/generation/templates/repo_overview.j2
index cfde9358d..f4e76bf6f 100644
--- a/packages/core/src/repowise/core/generation/templates/repo_overview.j2
+++ b/packages/core/src/repowise/core/generation/templates/repo_overview.j2
@@ -35,4 +35,20 @@ You are generating a high-level overview for the repository `{{ ctx.repo_name }}
- **Oldest file:** `{{ repo_git_summary.oldest_file }}` ({{ repo_git_summary.oldest_file_age_days }} days)
{% endif %}
+{% if ctx.communities %}
+## Architectural Communities
+The codebase organizes into these architectural clusters (detected via dependency analysis):
+{% for c in ctx.communities %}
+- **{{ c.label or "Community " ~ c.id }}** — {{ c.size }} files (cohesion: {{ c.cohesion }})
+{% endfor %}
+{% endif %}
+
+{% if ctx.execution_flows %}
+## Primary Execution Flows
+Key entry points and their execution paths:
+{% for f in ctx.execution_flows %}
+- `{{ f.entry_point }}` (score: {{ f.score }}{% if f.trace_length %}, {{ f.trace_length }} steps{% endif %})
+{% endfor %}
+{% endif %}
+
Generate a complete wiki page following the sections above.
diff --git a/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2 b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2
new file mode 100644
index 000000000..855109179
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2
@@ -0,0 +1,84 @@
+## Workspace: {{ data.workspace_name }} ({{ data.repos|length }} repo{{ "s" if data.repos|length != 1 else "" }})
+
+> Indexed by [Repowise](https://repowise.dev). Use `repo="all"` for workspace-wide queries, or `repo="alias"` for a specific repo.
+
+### Repositories
+| Repo | Files | Symbols | Hotspots | Role |
+|------|-------|---------|----------|------|
+{% for r in data.repos %}
+| `{{ r.alias }}` | {{ r.file_count }} | {{ r.symbol_count }} | {{ r.hotspot_count }} | {{ "default" if r.alias == data.default_repo else ("primary" if r.is_primary else "") }} |
+{% endfor %}
+
+{% if data.contract_links %}
+### Cross-Repo API Contracts
+{% if data.contracts_by_type %}
+**By type:** {% for ctype, count in data.contracts_by_type.items() %}{{ ctype }}: {{ count }}{% if not loop.last %}, {% endif %}{% endfor %}
+
+{% endif %}
+| Provider | Consumer | Type | Contract |
+|----------|----------|------|----------|
+{% for link in data.contract_links %}
+| `{{ link.provider_repo }}:{{ link.provider_file }}` | `{{ link.consumer_repo }}:{{ link.consumer_file }}` | {{ link.contract_type }} | `{{ link.contract_id }}` |
+{% endfor %}
+{% endif %}
+
+{% if data.co_changes %}
+### Cross-Repo Co-Changes
+Files that frequently change together across repos — consider reviewing both when editing either.
+
+| Source | Target | Co-changes |
+|--------|--------|------------|
+{% for cc in data.co_changes[:10] %}
+| `{{ cc.source_repo }}:{{ cc.source_file }}` | `{{ cc.target_repo }}:{{ cc.target_file }}` | {{ cc.frequency }} |
+{% endfor %}
+{% endif %}
+
+{% if data.package_deps %}
+### Package Dependencies
+{% for dep in data.package_deps %}
+- `{{ dep.source_repo }}` → `{{ dep.target_repo }}` ({{ dep.kind }})
+{% endfor %}
+{% endif %}
+
+### Per-Repo Entry Points
+{% for r in data.repos %}
+#### `{{ r.alias }}`{% if r.alias == data.default_repo %} (default){% elif r.is_primary %} (primary){% endif %}
+
+{% if r.entry_points %}
+{% for ep in r.entry_points %}
+- `{{ ep }}`
+{% endfor %}
+{% else %}
+_No entry points indexed._
+{% endif %}
+{% endfor %}
+
+### Repowise MCP Tools
+
+These tools work across all repos in this workspace. Pass `repo="alias"` to scope queries, or omit for the default repo.
+
+**Recommended workflow:**
+
+1. Start with `get_overview()` on a new task to orient yourself.
+2. Call `get_context(targets=["path/to/file.py"])` for enriched context on unfamiliar files — but always read the source before editing.
+3. Call `get_risk(targets=["path/to/file.py"])` before changing hotspot files.
+4. Don't know where something lives? Call `search_codebase(query="authentication flow")`.
+5. Need to understand why code is structured a certain way? Call `get_why(query="why JWT over sessions")` before architectural changes.
+6. After **architectural changes**, consider calling `update_decision_records(action="create", ...)` to record the rationale.
+7. Need to understand how two modules connect? Call `get_dependency_path(source="src/auth", target="src/db")`.
+8. Before cleanup tasks, call `get_dead_code()` to find confirmed unused code.
+9. For documentation or diagrams, call `get_architecture_diagram(scope="src/auth")`.
+
+**Note:** MCP tool responses reflect the last index run. If the index is stale, verify against source files.
+
+| Tool | When to use |
+|------|-------------|
+| `get_overview()` | Orient yourself on a new task |
+| `get_context(targets=[...])` | Enriched context on unfamiliar files |
+| `get_risk(targets=[...])` | Before changing hotspot files |
+| `get_why(query="...")` | Before architectural changes |
+| `update_decision_records(action=...)` | After architectural changes — record decisions |
+| `search_codebase(query="...")` | When locating code |
+| `get_dependency_path(source=..., target=...)` | When tracing module connections |
+| `get_dead_code()` | Before any cleanup or removal |
+| `get_architecture_diagram(scope=...)` | For visual structure or documentation |
diff --git a/packages/core/src/repowise/core/ingestion/__init__.py b/packages/core/src/repowise/core/ingestion/__init__.py
index bce70f167..a892b6c69 100644
--- a/packages/core/src/repowise/core/ingestion/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/__init__.py
@@ -14,8 +14,12 @@ from .change_detector import AffectedPages, ChangeDetector, FileDiff, SymbolDiff
from .graph import GraphBuilder
from .models import (
EXTENSION_TO_LANGUAGE,
+ CallSite,
+ EdgeType,
FileInfo,
+ HeritageRelation,
Import,
+ NamedBinding,
PackageInfo,
ParsedFile,
RepoStructure,
@@ -29,7 +33,11 @@ from .tsconfig_resolver import TsconfigResolver
__all__ = [
# Models
+ "CallSite",
+ "EdgeType",
"EXTENSION_TO_LANGUAGE",
+ "HeritageRelation",
+ "NamedBinding",
"LANGUAGE_CONFIGS",
# Parsing
"ASTParser",
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
new file mode 100644
index 000000000..32d9a9388
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -0,0 +1,318 @@
+"""Three-tier call resolution engine for the symbol-level dependency graph.
+
+Resolves CallSite objects (extracted from AST) to concrete symbol node IDs
+in the graph, producing CALLS edges with confidence scores.
+
+Resolution tiers (checked in order, first match wins):
+
+ Tier 1 — Same-file exact match (confidence 0.95)
+ The call target matches a symbol defined in the same file.
+
+ Tier 2 — Import-scoped match (confidence 0.90)
+ The call target matches a symbol in a file that the caller imports,
+ optionally scoped by the specific imported names.
+
+ Tier 3 — Global unique match (confidence 0.50)
+ The call target matches exactly one symbol across the entire codebase.
+ Only fires when the match is unambiguous to avoid false edges.
+
+Each resolved call produces a (source_id, target_id, confidence) triple that
+the GraphBuilder converts into a CALLS edge.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from dataclasses import dataclass
+
+import structlog
+
+from .models import CallSite, NamedBinding, ParsedFile
+
+log = structlog.get_logger(__name__)
+
+
+def _file_language(
+ parsed_files: dict[str, ParsedFile], symbol_id: str
+) -> str | None:
+ """Extract language from a symbol ID's file via the parsed files map."""
+ file_path = symbol_id.split("::")[0] if "::" in symbol_id else symbol_id
+ parsed = parsed_files.get(file_path)
+ return parsed.file_info.language if parsed else None
+
+
+@dataclass(frozen=True, slots=True)
+class ResolvedCall:
+ """A call resolved to concrete symbol IDs with a confidence score."""
+
+ caller_id: str # symbol node ID of the calling function/method
+ callee_id: str # symbol node ID of the called function/method
+ confidence: float # 0.0–1.0
+ line: int # call site line number (for diagnostics)
+
+
+class CallResolver:
+ """Resolve raw CallSites to symbol-level edges.
+
+ Constructed once per ``GraphBuilder.build()`` call with the full set
+ of parsed files and import edges. Stateless after construction —
+ ``resolve_file()`` can be called concurrently for different files.
+ """
+
+ def __init__(
+ self,
+ parsed_files: dict[str, ParsedFile],
+ import_targets: dict[str, set[str]],
+ ) -> None:
+ # Per-file symbol index: {file_path: {symbol_name: symbol_id}}
+ self._file_symbols: dict[str, dict[str, str]] = {}
+
+ # Per-file method index: {file_path: {(class_name, method_name): symbol_id}}
+ self._file_methods: dict[str, dict[tuple[str, str], str]] = {}
+
+ # Global symbol index: {name: [symbol_ids]} — for Tier 3
+ self._global_symbols: dict[str, list[str]] = defaultdict(list)
+
+ # Global class index: {name: symbol_id} — for receiver resolution
+ self._global_classes: dict[str, list[str]] = defaultdict(list)
+
+ # Import graph: {file_path: set of imported file paths}
+ self._import_targets = import_targets
+
+ # Import name mapping: {file_path: {local_name: source_file}}
+ self._import_names: dict[str, dict[str, str]] = defaultdict(dict)
+
+ # Full binding data: {file_path: {local_name: NamedBinding}}
+ self._import_bindings: dict[str, dict[str, NamedBinding]] = defaultdict(dict)
+
+ # Module alias mapping: {file_path: {alias: source_file}}
+ self._module_aliases: dict[str, dict[str, str]] = defaultdict(dict)
+
+ # Barrel re-export origins: {barrel_file: {name: origin_file}}
+ self._barrel_origins: dict[str, dict[str, str]] = defaultdict(dict)
+
+ # Keep reference for cross-language checks in Tier 3
+ self._parsed_files = parsed_files
+
+ self._build_indices(parsed_files)
+ self._follow_barrel_exports()
+
+ def _follow_barrel_exports(self) -> None:
+ """Detect barrel/re-export files and record origin mappings.
+
+ A barrel file imports a name and re-exports it without defining it
+ locally (e.g., ``__init__.py`` with ``from .calculator import Calculator``).
+ When downstream code imports from the barrel, we follow one hop to
+ find the actual defining file.
+ """
+ for path, name_to_file in self._import_names.items():
+ file_syms = self._file_symbols.get(path, {})
+ for name, source_file in name_to_file.items():
+ if name not in file_syms:
+ self._barrel_origins[path][name] = source_file
+
+ def _build_indices(self, parsed_files: dict[str, ParsedFile]) -> None:
+ """Build all lookup indices from parsed file data."""
+ for path, parsed in parsed_files.items():
+ file_syms: dict[str, str] = {}
+ file_methods: dict[tuple[str, str], str] = {}
+
+ for sym in parsed.symbols:
+ # File-level symbol index (top-level symbols and methods)
+ file_syms[sym.name] = sym.id
+
+ # Method index: (class_name, method_name) → symbol_id
+ if sym.parent_name:
+ file_methods[(sym.parent_name, sym.name)] = sym.id
+
+ # Global indices
+ self._global_symbols[sym.name].append(sym.id)
+ if sym.kind in ("class", "struct", "interface", "enum"):
+ self._global_classes[sym.name].append(sym.id)
+
+ self._file_symbols[path] = file_syms
+ self._file_methods[path] = file_methods
+
+ # Build import-name mapping using per-import resolved_file
+ for imp in parsed.imports:
+ if imp.resolved_file is None:
+ continue
+ resolved = imp.resolved_file
+ if imp.bindings:
+ for binding in imp.bindings:
+ if binding.local_name == "*":
+ continue
+ binding.source_file = resolved
+ self._import_names[path][binding.local_name] = resolved
+ self._import_bindings[path][binding.local_name] = binding
+ if binding.is_module_alias:
+ self._module_aliases[path][binding.local_name] = resolved
+ else:
+ # Fallback for imports without binding data
+ for name in imp.imported_names:
+ if name != "*":
+ self._import_names[path][name] = resolved
+
+ def resolve_file(self, file_path: str, calls: list[CallSite]) -> list[ResolvedCall]:
+ """Resolve all calls in a single file to symbol-level edges."""
+ results: list[ResolvedCall] = []
+
+ for call in calls:
+ if not call.caller_symbol_id:
+ # Calls at module level (outside any function) — skip for now
+ # as they don't have a clear caller node
+ continue
+
+ resolved = self._resolve_one(file_path, call)
+ if resolved:
+ results.append(resolved)
+
+ return results
+
+ def _resolve_one(self, file_path: str, call: CallSite) -> ResolvedCall | None:
+ """Resolve a single CallSite through the three-tier fallback."""
+ caller_id = call.caller_symbol_id
+ assert caller_id is not None
+
+ # --- Method call with receiver: receiver.method() ---
+ if call.receiver_name:
+ return self._resolve_member_call(file_path, call, caller_id)
+
+ # --- Free function call: function() ---
+ return self._resolve_free_call(file_path, call, caller_id)
+
+ def _resolve_free_call(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """Resolve a free function call (no receiver)."""
+ target_name = call.target_name
+
+ # Tier 1: same-file
+ file_syms = self._file_symbols.get(file_path, {})
+ if target_name in file_syms:
+ callee_id = file_syms[target_name]
+ if callee_id != caller_id: # no self-recursion edges for now
+ return ResolvedCall(caller_id, callee_id, 0.95, call.line)
+
+ # Tier 2: import-scoped
+ # 2a: Check specific imported name → source file (binding-aware)
+ binding = self._import_bindings.get(file_path, {}).get(target_name)
+ if binding and binding.source_file:
+ source_file = binding.source_file
+ # Follow barrel re-export one hop
+ barrel = self._barrel_origins.get(source_file, {})
+ lookup_name = binding.exported_name or target_name
+ if lookup_name in barrel:
+ source_file = barrel[lookup_name]
+ source_syms = self._file_symbols.get(source_file, {})
+ if lookup_name in source_syms:
+ return ResolvedCall(caller_id, source_syms[lookup_name], 0.90, call.line)
+
+ # 2a fallback: plain _import_names (for imports without binding data)
+ name_to_file = self._import_names.get(file_path, {})
+ if target_name in name_to_file and not binding:
+ source_file = name_to_file[target_name]
+ barrel = self._barrel_origins.get(source_file, {})
+ if target_name in barrel:
+ source_file = barrel[target_name]
+ source_syms = self._file_symbols.get(source_file, {})
+ if target_name in source_syms:
+ return ResolvedCall(caller_id, source_syms[target_name], 0.90, call.line)
+
+ # 2b: Check all imported files for the symbol
+ for imported_file in self._import_targets.get(file_path, set()):
+ if imported_file.startswith("external:"):
+ continue
+ imported_syms = self._file_symbols.get(imported_file, {})
+ if target_name in imported_syms:
+ return ResolvedCall(caller_id, imported_syms[target_name], 0.85, call.line)
+
+ # Tier 3: global unique match — only within the same language
+ candidates = self._global_symbols.get(target_name, [])
+ if len(candidates) == 1 and candidates[0] != caller_id:
+ caller_lang = _file_language(self._parsed_files, caller_id)
+ callee_lang = _file_language(self._parsed_files, candidates[0])
+ if caller_lang and callee_lang and caller_lang != callee_lang:
+ return None # reject cross-language Tier 3 match
+ return ResolvedCall(caller_id, candidates[0], 0.50, call.line)
+
+ return None
+
+ def _resolve_member_call(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """Resolve receiver.method() calls."""
+ receiver_name = call.receiver_name
+ method_name = call.target_name
+ assert receiver_name is not None
+
+ # Strategy 1: receiver is a module alias (e.g. "import models" → "models.User()")
+ module_file = self._module_aliases.get(file_path, {}).get(receiver_name)
+ if module_file:
+ source_syms = self._file_symbols.get(module_file, {})
+ if method_name in source_syms:
+ return ResolvedCall(caller_id, source_syms[method_name], 0.88, call.line)
+
+ # Strategy 1b: receiver in import names (non-alias fallback for backward compat)
+ name_to_file = self._import_names.get(file_path, {})
+ if receiver_name in name_to_file and not module_file:
+ source_file = name_to_file[receiver_name]
+ source_syms = self._file_symbols.get(source_file, {})
+ if method_name in source_syms:
+ return ResolvedCall(caller_id, source_syms[method_name], 0.88, call.line)
+
+ # Strategy 2: receiver is a known class name → look for method on that class
+ # Check same-file classes first
+ file_methods = self._file_methods.get(file_path, {})
+ key = (receiver_name, method_name)
+ if key in file_methods:
+ return ResolvedCall(caller_id, file_methods[key], 0.93, call.line)
+
+ # Check imported files for (class, method) pairs
+ for imported_file in self._import_targets.get(file_path, set()):
+ if imported_file.startswith("external:"):
+ continue
+ imp_methods = self._file_methods.get(imported_file, {})
+ if key in imp_methods:
+ return ResolvedCall(caller_id, imp_methods[key], 0.88, call.line)
+
+ # Strategy 3: receiver is "self" or "this" — look in same class
+ if receiver_name in ("self", "this"):
+ # The caller is inside a class method — find its parent class
+ # and resolve the method within that class's methods
+ for path_key, methods in self._file_methods.items():
+ if path_key != file_path:
+ continue
+ for (cls_name, meth_name), sym_id in methods.items():
+ if meth_name == method_name and sym_id != caller_id:
+ # Verify caller is in the same class
+ caller_class = _extract_class_from_symbol_id(caller_id)
+ if caller_class and caller_class == cls_name:
+ return ResolvedCall(caller_id, sym_id, 0.95, call.line)
+
+ # Strategy 4: global class match for receiver
+ class_candidates = self._global_classes.get(receiver_name, [])
+ if len(class_candidates) == 1:
+ # Found unique class — look for the method in any file
+ # that defines methods for this class
+ for _path, methods in self._file_methods.items():
+ if (receiver_name, method_name) in methods:
+ return ResolvedCall(
+ caller_id, methods[(receiver_name, method_name)], 0.50, call.line
+ )
+
+ return None
+
+
+def _extract_class_from_symbol_id(symbol_id: str) -> str | None:
+ """Extract parent class name from a symbol ID like 'path::ClassName::method'."""
+ parts = symbol_id.split("::")
+ if len(parts) >= 3:
+ return parts[-2]
+ return None
diff --git a/packages/core/src/repowise/core/ingestion/graph.py b/packages/core/src/repowise/core/ingestion/graph.py
index 1869c9a98..5fd39bf46 100644
--- a/packages/core/src/repowise/core/ingestion/graph.py
+++ b/packages/core/src/repowise/core/ingestion/graph.py
@@ -1,21 +1,26 @@
"""Dependency graph builder for the repowise ingestion pipeline.
-GraphBuilder constructs a directed multigraph from ParsedFile objects.
+GraphBuilder constructs a directed graph from ParsedFile objects with two
+tiers of nodes:
-Node types:
- "file" — every source file
- "external" — third-party / unresolvable imports (prefix "external:")
+ File-level nodes:
+ "file" — every source file
+ "external" — third-party / unresolvable imports (prefix "external:")
-Edge attributes:
- imported_names: list[str] — specific names imported across this edge
+ Symbol-level nodes:
+ "symbol" — functions, classes, methods, interfaces, etc.
+ keyed by Symbol.id (e.g. "src/app.py::main")
+
+Edge types:
+ "imports" — file-to-file import relationship
+ "defines" — file-to-symbol containment
+ "has_method" — class-to-method ownership
+ "calls" — symbol-to-symbol call relationship (with confidence)
After calling build(), graph metrics are available:
pagerank() — dict[path, float]
strongly_connected_components() — list[frozenset[str]]
betweenness_centrality() — dict[path, float]
-
-Graph persistence uses a lightweight SQLite schema (two tables: graph_nodes,
-graph_edges). Phase 4 will replace this with the full SQLAlchemy schema.
"""
from __future__ import annotations
@@ -123,6 +128,12 @@ class GraphBuilder:
self._tsconfig_resolver: Any | None = None # TsconfigResolver (lazy import)
self._go_module_path: str | None = self._read_go_module_path()
+ # Community / flow caches (invalidated on build)
+ self._community_cache: dict[str, int] | None = None
+ self._symbol_community_cache: dict[str, int] | None = None
+ self._community_info_cache: dict[int, Any] | None = None
+ self._community_algo: str = ""
+
def set_tsconfig_resolver(self, resolver: Any) -> None:
"""Attach a :class:`TsconfigResolver` for TS/JS path-alias resolution."""
self._tsconfig_resolver = resolver
@@ -132,12 +143,15 @@ class GraphBuilder:
# ------------------------------------------------------------------
def add_file(self, parsed: ParsedFile) -> None:
- """Register one parsed file in the graph."""
+ """Register one parsed file and its symbols in the graph."""
path = parsed.file_info.path
self._parsed_files[path] = parsed
self._built = False # invalidate cached metrics
+
+ # --- File node ---
self._graph.add_node(
path,
+ node_type="file",
language=parsed.file_info.language,
symbol_count=len(parsed.symbols),
has_error=bool(parsed.parse_errors),
@@ -145,24 +159,78 @@ class GraphBuilder:
is_entry_point=parsed.file_info.is_entry_point,
)
+ # --- Symbol nodes ---
+ for sym in parsed.symbols:
+ self._graph.add_node(
+ sym.id,
+ node_type="symbol",
+ kind=sym.kind,
+ name=sym.name,
+ qualified_name=sym.qualified_name,
+ file_path=path,
+ start_line=sym.start_line,
+ end_line=sym.end_line,
+ visibility=sym.visibility,
+ is_async=sym.is_async,
+ language=sym.language,
+ parent_name=sym.parent_name,
+ signature=sym.signature,
+ )
+
+ # DEFINES edge: file → symbol
+ self._graph.add_edge(
+ path,
+ sym.id,
+ edge_type="defines",
+ )
+
+ # HAS_METHOD edge: class/struct → method
+ if sym.parent_name and sym.kind == "method":
+ parent_id = f"{path}::{sym.parent_name}"
+ if parent_id in self._graph:
+ self._graph.add_edge(
+ parent_id,
+ sym.id,
+ edge_type="has_method",
+ )
+
def build(self) -> nx.DiGraph:
- """Resolve imports and add edges. Returns the finalized graph.
+ """Resolve imports and calls, add edges. Returns the finalized graph.
Idempotent: can be called multiple times; re-resolves edges each time.
+ Preserves symbol nodes and structural edges (defines, has_method)
+ while rebuilding import and call edges.
"""
- # Clear old edges, keep nodes
- self._graph.remove_edges_from(list(self._graph.edges()))
+ # Invalidate cached metrics
+ self._community_cache = None
+ self._symbol_community_cache = None
+ self._community_info_cache = None
+ self._community_algo = ""
+
+ # Clear import/call edges but keep structural edges (defines, has_method)
+ edges_to_remove = [
+ (u, v)
+ for u, v, d in self._graph.edges(data=True)
+ if d.get("edge_type") not in ("defines", "has_method")
+ ]
+ self._graph.remove_edges_from(edges_to_remove)
# Build lookup tables for import resolution
path_set = set(self._parsed_files.keys())
stem_map = self._build_stem_map(path_set)
+ # --- Phase 1: Resolve file-level imports ---
+ import_targets: dict[str, set[str]] = {} # file → set of imported files
+
for path, parsed in self._parsed_files.items():
+ file_imports: set[str] = set()
for imp in parsed.imports:
target = self._resolve_import(
imp.module_path, path, path_set, stem_map, parsed.file_info.language
)
if target:
+ imp.resolved_file = target
+ file_imports.add(target)
# Aggregate imported_names on parallel edges
if self._graph.has_edge(path, target):
existing = self._graph[path][target].get("imported_names", [])
@@ -172,17 +240,102 @@ class GraphBuilder:
self._graph.add_edge(
path,
target,
+ edge_type="imports",
imported_names=list(imp.imported_names),
)
+ import_targets[path] = file_imports
+
+ # --- Phase 2: Resolve heritage (extends/implements) ---
+ self._resolve_heritage(import_targets)
+
+ # --- Phase 3: Resolve symbol-level calls ---
+ self._resolve_calls(import_targets)
self._built = True
+
+ # Count edge types for logging
+ edge_counts: dict[str, int] = {}
+ for _, _, d in self._graph.edges(data=True):
+ et = d.get("edge_type", "imports")
+ edge_counts[et] = edge_counts.get(et, 0) + 1
+
+ file_nodes = sum(
+ 1 for _, d in self._graph.nodes(data=True) if d.get("node_type", "file") == "file"
+ )
+ symbol_nodes = sum(
+ 1 for _, d in self._graph.nodes(data=True) if d.get("node_type") == "symbol"
+ )
+
log.info(
"Graph built",
- nodes=self._graph.number_of_nodes(),
+ file_nodes=file_nodes,
+ symbol_nodes=symbol_nodes,
edges=self._graph.number_of_edges(),
+ edge_types=edge_counts,
)
return self._graph
+ def _resolve_heritage(self, import_targets: dict[str, set[str]]) -> None:
+ """Resolve heritage relations and add EXTENDS/IMPLEMENTS edges."""
+ from .heritage_resolver import HeritageResolver
+
+ resolver = HeritageResolver(self._parsed_files, import_targets)
+ total_resolved = 0
+
+ for path, parsed in self._parsed_files.items():
+ if not parsed.heritage:
+ continue
+
+ resolved = resolver.resolve_file(path, parsed.heritage)
+ for rh in resolved:
+ if rh.child_id in self._graph and rh.parent_id in self._graph:
+ if not self._graph.has_edge(rh.child_id, rh.parent_id):
+ self._graph.add_edge(
+ rh.child_id,
+ rh.parent_id,
+ edge_type=rh.edge_type,
+ confidence=rh.confidence,
+ )
+ total_resolved += 1
+ else:
+ existing = self._graph[rh.child_id][rh.parent_id]
+ if rh.confidence > existing.get("confidence", 0):
+ existing["confidence"] = rh.confidence
+
+ log.info("Heritage edges resolved", total=total_resolved)
+
+ def _resolve_calls(self, import_targets: dict[str, set[str]]) -> None:
+ """Run three-tier call resolution and add CALLS edges to the graph."""
+ from .call_resolver import CallResolver
+
+ resolver = CallResolver(self._parsed_files, import_targets)
+ total_resolved = 0
+
+ for path, parsed in self._parsed_files.items():
+ if not parsed.calls:
+ continue
+
+ resolved = resolver.resolve_file(path, parsed.calls)
+ for rc in resolved:
+ # Only add edge if both nodes exist in graph
+ if rc.caller_id in self._graph and rc.callee_id in self._graph:
+ # Avoid duplicate call edges between same pair
+ if not self._graph.has_edge(rc.caller_id, rc.callee_id):
+ self._graph.add_edge(
+ rc.caller_id,
+ rc.callee_id,
+ edge_type="calls",
+ confidence=rc.confidence,
+ )
+ total_resolved += 1
+ else:
+ # Update confidence if this resolution is higher
+ existing = self._graph[rc.caller_id][rc.callee_id]
+ if rc.confidence > existing.get("confidence", 0):
+ existing["confidence"] = rc.confidence
+
+ log.info("Call edges resolved", total=total_resolved)
+
def graph(self) -> nx.DiGraph:
"""Return the graph (building it first if necessary)."""
if not self._built:
@@ -194,15 +347,19 @@ class GraphBuilder:
# ------------------------------------------------------------------
def strongly_connected_components(self) -> list[frozenset[str]]:
- """Return SCCs as a list of frozensets. SCCs of size > 1 are circular deps."""
- return [frozenset(scc) for scc in nx.strongly_connected_components(self.graph())]
+ """Return SCCs as a list of frozensets. SCCs of size > 1 are circular deps.
+
+ Operates on the file-level subgraph only.
+ """
+ return [frozenset(scc) for scc in nx.strongly_connected_components(self.file_subgraph())]
def betweenness_centrality(self) -> dict[str, float]:
- """Return betweenness centrality. High value → bridge file.
+ """Return betweenness centrality for file nodes. High value → bridge file.
Approximated with k=min(500, n) samples for large graphs.
+ Operates on the file-level subgraph only.
"""
- g = self.graph()
+ g = self.file_subgraph()
n = g.number_of_nodes()
if n == 0:
return {}
@@ -212,23 +369,96 @@ class GraphBuilder:
return nx.betweenness_centrality(g, normalized=True)
def community_detection(self) -> dict[str, int]:
- """Assign a community ID to each node using the Louvain algorithm.
+ """Assign a community ID to each file node.
+ Uses Leiden (graspologic) when available, falls back to Louvain.
+ Results are cached until the next ``build()`` call.
Returns dict[path, community_id].
"""
- g = self.graph()
- if g.number_of_nodes() == 0:
- return {}
+ if self._community_cache is not None:
+ return self._community_cache
+
+ from repowise.core.analysis.communities import detect_file_communities
+
try:
- communities = nx.community.louvain_communities(g.to_undirected(), seed=42)
- result: dict[str, int] = {}
- for community_id, members in enumerate(communities):
- for node in members:
- result[node] = community_id
- return result
+ assignment, info, algo = detect_file_communities(self._graph)
+ self._community_cache = assignment
+ self._community_info_cache = info
+ self._community_algo = algo
+ except Exception as exc:
+ log.warning("community_detection_failed", error=str(exc))
+ file_nodes = [
+ n for n, d in self._graph.nodes(data=True)
+ if d.get("node_type", "file") == "file"
+ ]
+ self._community_cache = {n: 0 for n in file_nodes}
+ self._community_info_cache = {}
+ self._community_algo = "failed"
+ return self._community_cache
+
+ def symbol_communities(self) -> dict[str, int]:
+ """Assign a community ID to each symbol node using call/heritage edges.
+
+ Returns dict[symbol_id, community_id]. Cached until next ``build()``.
+ """
+ if self._symbol_community_cache is not None:
+ return self._symbol_community_cache
+
+ from repowise.core.analysis.communities import detect_symbol_communities
+
+ try:
+ self._symbol_community_cache = detect_symbol_communities(self._graph)
except Exception as exc:
- log.warning("Community detection failed", error=str(exc))
- return {node: 0 for node in g.nodes()}
+ log.warning("symbol_community_detection_failed", error=str(exc))
+ self._symbol_community_cache = {}
+ return self._symbol_community_cache
+
+ def community_info(self) -> dict[int, Any]:
+ """Return metadata for each file-level community.
+
+ Returns dict[community_id, CommunityInfo]. Populates cache via
+ ``community_detection()`` if not yet computed.
+ """
+ if self._community_info_cache is None:
+ self.community_detection()
+ return self._community_info_cache or {}
+
+ def execution_flows(self, config: Any | None = None) -> Any:
+ """Trace execution flows from entry-point symbols.
+
+ Returns an ``ExecutionFlowReport``. Requires symbol nodes and call
+ edges to be present in the graph.
+ """
+ from repowise.core.analysis.execution_flows import (
+ ExecutionFlowReport,
+ trace_execution_flows,
+ )
+
+ # Build a merged community map that covers both file paths and
+ # symbol IDs, so crosses_community detection works correctly.
+ # community_detection() returns {file_path: cid} but traces
+ # contain symbol IDs like "path::Name".
+ file_cd = self.community_detection()
+ merged_cd: dict[str, int] = dict(file_cd)
+
+ # Add symbol-level communities
+ sym_cd = self.symbol_communities()
+ merged_cd.update(sym_cd)
+
+ # For symbols missing from both maps, inherit from their file
+ for node_id in self._graph.nodes():
+ if node_id not in merged_cd and "::" in node_id:
+ file_path = node_id.split("::")[0]
+ if file_path in file_cd:
+ merged_cd[node_id] = file_cd[file_path]
+
+ try:
+ return trace_execution_flows(self._graph, merged_cd, config)
+ except Exception as exc:
+ log.warning("execution_flow_tracing_failed", error=str(exc))
+ return ExecutionFlowReport(
+ total_entry_points_scored=0, total_flows=0, flows=[],
+ )
# ------------------------------------------------------------------
# Serialisation
@@ -1009,23 +1239,36 @@ class GraphBuilder:
count += 1
return count
+ def file_subgraph(self) -> nx.DiGraph:
+ """Return a subgraph containing only file-level nodes and import edges.
+
+ Used for PageRank, betweenness, and other file-level metrics that
+ should not be affected by symbol-level nodes.
+ """
+ g = self.graph()
+ file_nodes = [
+ n
+ for n, d in g.nodes(data=True)
+ if d.get("node_type", "file") in ("file", "external")
+ ]
+ sub = g.subgraph(file_nodes).copy()
+ # Remove non-import edges (co_changes, framework, dynamic)
+ edges_to_remove = [
+ (u, v) for u, v, d in sub.edges(data=True) if d.get("edge_type") in ("co_changes",)
+ ]
+ sub.remove_edges_from(edges_to_remove)
+ return sub
+
def pagerank(self, alpha: float = 0.85) -> dict[str, float]:
- """Return PageRank scores for each node.
+ """Return PageRank scores for file nodes only.
High PageRank → file is imported by many others → high documentation priority.
- Co-change edges are filtered out before computing PageRank.
+ Operates on the file-level subgraph (excludes symbol nodes and co-change edges).
"""
- g = self.graph()
- if g.number_of_nodes() == 0:
+ filtered = self.file_subgraph()
+ if filtered.number_of_nodes() == 0:
return {}
- # Create a filtered view excluding co_changes edges
- filtered = nx.DiGraph()
- filtered.add_nodes_from(g.nodes(data=True))
- for u, v, data in g.edges(data=True):
- if data.get("edge_type") != "co_changes":
- filtered.add_edge(u, v, **data)
-
try:
return nx.pagerank(filtered, alpha=alpha)
except nx.PowerIterationFailedConvergence:
diff --git a/packages/core/src/repowise/core/ingestion/heritage_resolver.py b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
new file mode 100644
index 000000000..bfe12820c
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
@@ -0,0 +1,199 @@
+"""Heritage (inheritance/implementation) resolution engine.
+
+Resolves HeritageRelation objects (extracted from AST class definitions) to
+concrete symbol node IDs in the graph, producing EXTENDS, IMPLEMENTS, and
+TRAIT_IMPL edges with confidence scores.
+
+Resolution tiers (checked in order, first match wins):
+
+ Tier 1 — Same-file exact match (confidence 0.95)
+ The parent name matches a class/interface/trait in the same file.
+
+ Tier 2 — Import-scoped match (confidence 0.90)
+ The parent name matches a class/interface/trait in an imported file.
+
+ Tier 3 — Global unique match (confidence 0.50)
+ The parent name matches exactly one class/interface/trait globally.
+
+Each resolved relation produces a (child_id, parent_id, edge_type, confidence)
+tuple that the GraphBuilder converts into graph edges.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from dataclasses import dataclass
+
+import structlog
+
+from .models import HeritageRelation, ParsedFile
+
+log = structlog.get_logger(__name__)
+
+
+def _file_language(
+ parsed_files: dict[str, ParsedFile], symbol_id: str
+) -> str | None:
+ """Extract language from a symbol ID's file via the parsed files map."""
+ file_path = symbol_id.split("::")[0] if "::" in symbol_id else symbol_id
+ parsed = parsed_files.get(file_path)
+ return parsed.file_info.language if parsed else None
+
+# Symbol kinds that can be parents in heritage relationships
+_PARENT_KINDS = frozenset({
+ "class", "interface", "trait", "struct", "enum", "type_alias", "impl",
+})
+
+
+@dataclass(frozen=True, slots=True)
+class ResolvedHeritage:
+ """A heritage relation resolved to concrete symbol IDs."""
+
+ child_id: str # symbol node ID of the child class/struct
+ parent_id: str # symbol node ID of the parent class/interface/trait
+ edge_type: str # "extends", "implements", or "trait_impl"
+ confidence: float # 0.0–1.0
+ line: int # line of the class definition (for diagnostics)
+
+
+class HeritageResolver:
+ """Resolve raw HeritageRelations to symbol-level edges.
+
+ Constructed once per ``GraphBuilder.build()`` call with the full set
+ of parsed files and import edges. Follows the same architecture as
+ CallResolver for consistency.
+ """
+
+ def __init__(
+ self,
+ parsed_files: dict[str, ParsedFile],
+ import_targets: dict[str, set[str]],
+ ) -> None:
+ # Per-file class/interface/trait index: {file: {name: symbol_id}}
+ self._file_types: dict[str, dict[str, str]] = {}
+
+ # Global class/interface/trait index: {name: [symbol_ids]}
+ self._global_types: dict[str, list[str]] = defaultdict(list)
+
+ # Import graph
+ self._import_targets = import_targets
+
+ # Import name mapping (reuses resolved_file from Import objects)
+ self._import_names: dict[str, dict[str, str]] = defaultdict(dict)
+
+ # Keep reference for cross-language checks in Tier 3
+ self._parsed_files = parsed_files
+
+ self._build_indices(parsed_files)
+
+ def _build_indices(self, parsed_files: dict[str, ParsedFile]) -> None:
+ """Build type-level lookup indices from parsed file data."""
+ for path, parsed in parsed_files.items():
+ file_types: dict[str, str] = {}
+
+ for sym in parsed.symbols:
+ if sym.kind in _PARENT_KINDS:
+ file_types[sym.name] = sym.id
+ self._global_types[sym.name].append(sym.id)
+
+ self._file_types[path] = file_types
+
+ # Build import name mapping using resolved_file
+ for imp in parsed.imports:
+ if imp.resolved_file is None:
+ continue
+ for binding in imp.bindings:
+ if binding.local_name != "*":
+ self._import_names[path][binding.local_name] = imp.resolved_file
+ # Fallback for imports without bindings
+ if not imp.bindings:
+ for name in imp.imported_names:
+ if name != "*":
+ self._import_names[path][name] = imp.resolved_file
+
+ def resolve_file(
+ self, file_path: str, relations: list[HeritageRelation]
+ ) -> list[ResolvedHeritage]:
+ """Resolve all heritage relations in a single file."""
+ results: list[ResolvedHeritage] = []
+
+ for rel in relations:
+ resolved = self._resolve_one(file_path, rel)
+ if resolved:
+ results.append(resolved)
+
+ return results
+
+ def _resolve_one(
+ self, file_path: str, rel: HeritageRelation
+ ) -> ResolvedHeritage | None:
+ """Resolve a single HeritageRelation through three-tier fallback."""
+ child_id = f"{file_path}::{rel.child_name}"
+ parent_name = rel.parent_name
+ edge_type = _heritage_kind_to_edge_type(rel.kind)
+
+ # Tier 1: same-file
+ file_types = self._file_types.get(file_path, {})
+ if parent_name in file_types:
+ return ResolvedHeritage(
+ child_id=child_id,
+ parent_id=file_types[parent_name],
+ edge_type=edge_type,
+ confidence=0.95,
+ line=rel.line,
+ )
+
+ # Tier 2a: specific imported name
+ name_to_file = self._import_names.get(file_path, {})
+ if parent_name in name_to_file:
+ source_file = name_to_file[parent_name]
+ source_types = self._file_types.get(source_file, {})
+ if parent_name in source_types:
+ return ResolvedHeritage(
+ child_id=child_id,
+ parent_id=source_types[parent_name],
+ edge_type=edge_type,
+ confidence=0.90,
+ line=rel.line,
+ )
+
+ # Tier 2b: scan all imported files
+ for imported_file in self._import_targets.get(file_path, set()):
+ if imported_file.startswith("external:"):
+ continue
+ imported_types = self._file_types.get(imported_file, {})
+ if parent_name in imported_types:
+ return ResolvedHeritage(
+ child_id=child_id,
+ parent_id=imported_types[parent_name],
+ edge_type=edge_type,
+ confidence=0.85,
+ line=rel.line,
+ )
+
+ # Tier 3: global unique match — only within the same language
+ candidates = self._global_types.get(parent_name, [])
+ if len(candidates) == 1:
+ caller_lang = _file_language(self._parsed_files, child_id)
+ callee_lang = _file_language(self._parsed_files, candidates[0])
+ if caller_lang and callee_lang and caller_lang != callee_lang:
+ return None # reject cross-language Tier 3 match
+ return ResolvedHeritage(
+ child_id=child_id,
+ parent_id=candidates[0],
+ edge_type=edge_type,
+ confidence=0.50,
+ line=rel.line,
+ )
+
+ return None
+
+
+def _heritage_kind_to_edge_type(kind: str) -> str:
+ """Map HeritageKind to graph edge_type string."""
+ if kind == "implements":
+ return "implements"
+ if kind == "trait_impl":
+ return "implements"
+ # extends, mixin → extends
+ return "extends"
diff --git a/packages/core/src/repowise/core/ingestion/language_data.py b/packages/core/src/repowise/core/ingestion/language_data.py
new file mode 100644
index 000000000..8ab84c036
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/language_data.py
@@ -0,0 +1,224 @@
+"""Per-language constants for call/heritage resolution filtering.
+
+Centralises all language-specific data tables (builtin functions, builtin
+parent types, test path patterns) in one place so they can be adjusted
+without touching resolution or extraction logic.
+
+Adding a new language:
+ 1. Add its builtins to ``BUILTIN_CALLS`` (functions the language provides
+ globally that should NOT create graph edges).
+ 2. Add its builtin parent types to ``BUILTIN_PARENTS`` (base classes /
+ traits / interfaces provided by the language runtime that should NOT
+ create heritage edges).
+ 3. That's it — the resolver and parser import these dicts automatically.
+"""
+
+from __future__ import annotations
+
+# ---------------------------------------------------------------------------
+# Builtin function calls — filtered during call extraction (parser.py)
+#
+# These are names that appear as function calls in source code but refer to
+# language-provided builtins, not user-defined symbols. Extracting them
+# pollutes the call graph because Tier 3 global resolution can match them
+# to unrelated user symbols with the same name in other files/languages.
+# ---------------------------------------------------------------------------
+
+BUILTIN_CALLS: dict[str, frozenset[str]] = {
+ "python": frozenset({
+ # builtins module — https://docs.python.org/3/library/functions.html
+ "abs", "aiter", "all", "anext", "any", "ascii",
+ "bin", "bool", "breakpoint", "bytearray", "bytes",
+ "callable", "chr", "classmethod", "compile", "complex",
+ "delattr", "dict", "dir", "divmod",
+ "enumerate", "eval", "exec",
+ "filter", "float", "format", "frozenset",
+ "getattr", "globals",
+ "hasattr", "hash", "help", "hex",
+ "id", "input", "int", "isinstance", "issubclass", "iter",
+ "len", "list", "locals",
+ "map", "max", "memoryview", "min",
+ "next",
+ "object", "oct", "open", "ord",
+ "pow", "print", "property",
+ "range", "repr", "reversed", "round",
+ "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super",
+ "tuple", "type",
+ "vars",
+ "zip",
+ "__import__",
+ }),
+ "typescript": frozenset({
+ # Global functions & constructors
+ "parseInt", "parseFloat", "isNaN", "isFinite",
+ "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent",
+ "setTimeout", "setInterval", "clearTimeout", "clearInterval",
+ "fetch", "require", "eval", "atob", "btoa",
+ # Global object namespaces (not user-callable symbols)
+ "JSON", "Math", "console", "Reflect", "Proxy",
+ # Builtin constructors — user code rarely shadows these
+ "Object", "Array", "String", "Number", "Boolean",
+ "Date", "RegExp", "Promise", "Set", "Map", "WeakMap", "WeakSet",
+ "Symbol", "ArrayBuffer", "DataView", "Uint8Array",
+ "Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError",
+ "Int8Array", "Int16Array", "Int32Array", "Float32Array", "Float64Array",
+ }),
+ # JavaScript shares the TypeScript set
+ "javascript": None,
+ "java": frozenset({
+ # java.lang auto-imported types used as static calls
+ "System", "Objects", "Arrays", "Collections", "Math",
+ "Integer", "Long", "Double", "Float", "Boolean", "Character",
+ "Byte", "Short",
+ "String", "Object", "Class", "Thread",
+ "Throwable", "Exception", "RuntimeException", "Error",
+ "StringBuilder", "StringBuffer",
+ }),
+ "go": frozenset({
+ # Go builtins — https://pkg.go.dev/builtin
+ "make", "len", "cap", "new", "append", "copy", "close",
+ "delete", "complex", "real", "imag",
+ "panic", "recover",
+ "print", "println",
+ }),
+ "rust": frozenset({
+ # Macros and builtins that tree-sitter extracts as calls
+ "println", "eprintln", "print", "eprint",
+ "format", "format_args",
+ "vec", "panic", "todo", "unimplemented", "unreachable",
+ "assert", "assert_eq", "assert_ne",
+ "debug_assert", "debug_assert_eq", "debug_assert_ne",
+ "cfg", "include", "include_str", "include_bytes",
+ "env", "option_env", "concat", "stringify", "line", "column", "file",
+ "write", "writeln",
+ }),
+ "kotlin": frozenset({
+ "println", "print", "readLine",
+ "arrayOf", "listOf", "mutableListOf", "setOf", "mutableSetOf",
+ "mapOf", "mutableMapOf", "hashMapOf",
+ "lazy", "require", "check", "error",
+ "TODO", "run", "let", "also", "apply", "with",
+ }),
+ "ruby": frozenset({
+ "puts", "print", "p", "pp", "raise", "fail",
+ "require", "require_relative", "include", "extend", "prepend",
+ "attr_reader", "attr_writer", "attr_accessor",
+ "lambda", "proc",
+ }),
+ "cpp": frozenset({
+ # C++ stdlib commonly-extracted calls
+ "printf", "scanf", "fprintf", "sprintf", "snprintf",
+ "malloc", "calloc", "realloc", "free",
+ "sizeof", "alignof", "typeid", "decltype",
+ "static_cast", "dynamic_cast", "const_cast", "reinterpret_cast",
+ "move", "forward", "make_shared", "make_unique", "make_pair",
+ "cout", "cerr", "endl",
+ }),
+ "csharp": frozenset({
+ "Console", "Math", "Convert",
+ "String", "Object", "Array",
+ "GC", "Environment", "Activator",
+ "Task", "Interlocked",
+ "nameof", "typeof", "sizeof", "default",
+ }),
+ "c": frozenset({
+ "printf", "scanf", "fprintf", "sprintf", "snprintf",
+ "malloc", "calloc", "realloc", "free",
+ "memcpy", "memset", "memmove", "memcmp",
+ "strlen", "strcpy", "strncpy", "strcat", "strcmp", "strncmp",
+ "sizeof", "offsetof",
+ "assert", "abort", "exit",
+ }),
+}
+
+
+# ---------------------------------------------------------------------------
+# Builtin parent types — filtered during heritage extraction (parser.py)
+#
+# Base classes, interfaces, and traits provided by the language runtime.
+# Creating heritage edges to these pollutes the graph because they are
+# universally inherited and carry no architectural signal.
+# ---------------------------------------------------------------------------
+
+BUILTIN_PARENTS: dict[str, frozenset[str]] = {
+ "python": frozenset({
+ "object", "Exception", "BaseException",
+ "type", "ABC", "ABCMeta",
+ "Protocol", # typing.Protocol
+ "NamedTuple", "TypedDict",
+ "Enum", "IntEnum", "Flag", "IntFlag", # enum base classes
+ }),
+ "typescript": frozenset({
+ "Error", "Object",
+ }),
+ "javascript": frozenset({
+ "Error", "Object",
+ }),
+ "java": frozenset({
+ "Object", "Throwable", "Exception", "RuntimeException", "Error",
+ "Enum",
+ "Serializable", "Cloneable", "Comparable", "Iterable",
+ "AutoCloseable", "Closeable",
+ }),
+ "go": frozenset({
+ "error", # Go's error interface
+ }),
+ "rust": frozenset({
+ # std::fmt, std::cmp, std::ops, std::marker traits
+ "Error", "Display", "Debug",
+ "Clone", "Copy", "Default",
+ "PartialEq", "Eq", "PartialOrd", "Ord", "Hash",
+ "Send", "Sync", "Sized", "Unpin",
+ "Iterator", "IntoIterator",
+ "From", "Into", "TryFrom", "TryInto",
+ "AsRef", "AsMut", "Borrow", "BorrowMut",
+ "Drop", "Deref", "DerefMut",
+ "Add", "Sub", "Mul", "Div", "Rem", "Neg",
+ "Fn", "FnMut", "FnOnce",
+ }),
+ "kotlin": frozenset({
+ "Any", "Throwable", "Exception", "RuntimeException", "Error",
+ "Enum",
+ "Comparable", "Iterable", "Serializable",
+ }),
+ "cpp": frozenset({
+ "exception", "runtime_error", "logic_error",
+ "invalid_argument", "out_of_range", "overflow_error",
+ # STL containers (not architectural parents)
+ "string", "vector", "map", "set", "list", "deque",
+ "unordered_map", "unordered_set",
+ "shared_ptr", "unique_ptr", "weak_ptr",
+ }),
+ "csharp": frozenset({
+ "Object", "ValueType", "Enum",
+ "Exception", "SystemException", "ApplicationException",
+ "IDisposable", "IEnumerable", "IEnumerator",
+ "IComparable", "ICloneable", "IEquatable",
+ }),
+ "ruby": frozenset({
+ "Object", "BasicObject",
+ "Exception", "StandardError", "RuntimeError",
+ "ScriptError", "LoadError", "SyntaxError",
+ "Comparable", "Enumerable", "Kernel",
+ }),
+}
+
+
+def get_builtin_calls(language: str) -> frozenset[str]:
+ """Return the builtin call names for a language.
+
+ Falls back to the ``typescript`` set for ``javascript`` when the
+ javascript key is ``None``.
+ """
+ result = BUILTIN_CALLS.get(language)
+ if result is not None:
+ return result
+ # javascript → typescript fallback
+ if language == "javascript":
+ return BUILTIN_CALLS.get("typescript", frozenset())
+ return frozenset()
+
+
+def get_builtin_parents(language: str) -> frozenset[str]:
+ """Return the builtin parent type names for a language."""
+ return BUILTIN_PARENTS.get(language, frozenset())
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index beafb3587..e3aa0fab7 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -184,6 +184,20 @@ class Symbol:
parent_name: str | None = None # for methods: the containing class name
+@dataclass
+class NamedBinding:
+ """One resolved name from an import statement.
+
+ Tracks the local alias, the original exported name, and the resolved
+ source file so that call resolution can map aliases back to symbols.
+ """
+
+ local_name: str # name used in calling file (e.g., "np", "Calc")
+ exported_name: str | None # original name in source (None for module aliases)
+ source_file: str | None # resolved file path (populated during graph build)
+ is_module_alias: bool = False # True for "import x" / "import * as ns"
+
+
@dataclass
class Import:
"""An import statement extracted from a source file."""
@@ -193,6 +207,58 @@ class Import:
imported_names: list[str] # specific names, or ["*"] for wildcard
is_relative: bool
resolved_file: str | None # absolute path if successfully resolved
+ bindings: list[NamedBinding] = field(default_factory=list)
+
+
+@dataclass
+class CallSite:
+ """A function or method call extracted from a source file.
+
+ Used by GraphBuilder to create CALLS edges between symbol nodes.
+ """
+
+ target_name: str # function/method name being called
+ receiver_name: str | None # object/class for method calls (e.g. "user" in user.save())
+ caller_symbol_id: str | None # enclosing symbol ID (e.g. "src/app.py::main")
+ line: int # 1-indexed line number of the call
+ argument_count: int | None # number of arguments (None if unknown)
+
+
+HeritageKind = Literal["extends", "implements", "trait_impl", "mixin"]
+
+
+@dataclass
+class HeritageRelation:
+ """A class/struct/impl inheritance or interface implementation relationship.
+
+ Extracted from AST class definitions. Resolved to graph edges by
+ HeritageResolver during the graph build phase.
+ """
+
+ child_name: str # the class/struct being defined
+ parent_name: str # superclass, interface, or trait name
+ kind: HeritageKind # relationship type
+ line: int # 1-indexed line of the class definition
+
+
+# ---------------------------------------------------------------------------
+# Edge types used in the symbol-level dependency graph
+# ---------------------------------------------------------------------------
+
+EdgeType = Literal[
+ "imports",
+ "defines",
+ "calls",
+ "has_method",
+ "has_property",
+ "extends",
+ "implements",
+ "method_overrides",
+ "method_implements",
+ "co_changes",
+ "framework",
+ "dynamic",
+]
@dataclass
@@ -203,8 +269,10 @@ class ParsedFile:
symbols: list[Symbol]
imports: list[Import]
exports: list[str] # names exported by this file
- docstring: str | None # module/file-level docstring
- parse_errors: list[str] # non-fatal parser warnings/errors
+ calls: list[CallSite] = field(default_factory=list)
+ heritage: list[HeritageRelation] = field(default_factory=list)
+ docstring: str | None = None # module/file-level docstring
+ parse_errors: list[str] = field(default_factory=list) # non-fatal parser warnings/errors
content_hash: str = "" # SHA-256 hex of raw file bytes
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 1e6e88c67..e7d6f0a96 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -31,7 +31,15 @@ from pathlib import Path
import structlog
from tree_sitter import Language, Node, Parser
-from .models import FileInfo, Import, ParsedFile, Symbol
+from .models import (
+ CallSite,
+ FileInfo,
+ HeritageRelation,
+ Import,
+ NamedBinding,
+ ParsedFile,
+ Symbol,
+)
log = structlog.get_logger(__name__)
@@ -398,6 +406,8 @@ class ASTParser:
symbols = self._extract_symbols(tree, query, config, file_info, src)
imports = self._extract_imports(tree, query, config, file_info, src)
+ calls = self._extract_calls(tree, query, config, file_info, src, symbols)
+ heritage = _extract_heritage(tree, query, config, file_info, src)
exports = self._derive_exports(symbols, config, src)
docstring = _extract_module_docstring(root, src, lang)
@@ -406,6 +416,8 @@ class ASTParser:
symbols=symbols,
imports=imports,
exports=exports,
+ calls=calls,
+ heritage=heritage,
docstring=docstring,
parse_errors=parse_errors,
)
@@ -609,8 +621,10 @@ class ASTParser:
if not module_text:
continue
- # Language-specific import name extraction
- imported_names = _extract_import_names(stmt_node, src, file_info.language)
+ # Language-specific import name + binding extraction
+ imported_names, bindings = _extract_import_bindings(
+ stmt_node, src, file_info.language
+ )
is_relative = module_text.startswith(".") or module_text.startswith("./")
imports.append(
@@ -620,11 +634,100 @@ class ASTParser:
imported_names=imported_names,
is_relative=is_relative,
resolved_file=None,
+ bindings=bindings,
)
)
return imports
+ # ------------------------------------------------------------------
+ # Call extraction
+ # ------------------------------------------------------------------
+
+ def _extract_calls(
+ self,
+ tree: object,
+ query: object,
+ config: LanguageConfig,
+ file_info: FileInfo,
+ src: str,
+ symbols: list[Symbol],
+ ) -> list[CallSite]:
+ """Extract function/method call sites from the AST.
+
+ Uses @call.target, @call.receiver, and @call.arguments captures
+ defined in the .scm query files. Each call is associated with its
+ enclosing symbol (caller) by checking which symbol's line range
+ contains the call site.
+ """
+ if query is None:
+ return []
+
+ from .language_data import get_builtin_calls
+
+ _call_builtins = get_builtin_calls(file_info.language)
+
+ # Build a sorted list of (start_line, end_line, symbol_id) for
+ # fast enclosing-symbol lookup via binary search.
+ symbol_ranges = sorted(
+ [(s.start_line, s.end_line, s.id) for s in symbols],
+ key=lambda t: (t[0], -t[1]), # start asc, widest span first
+ )
+
+ calls: list[CallSite] = []
+ seen: set[tuple[int, str, str | None]] = set() # (line, target, receiver) dedup
+
+ for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]
+ site_nodes = capture_dict.get("call.site", [])
+ target_nodes = capture_dict.get("call.target", [])
+ arg_nodes = capture_dict.get("call.arguments", [])
+ receiver_nodes = capture_dict.get("call.receiver", [])
+
+ if not site_nodes or not target_nodes:
+ continue
+
+ site_node = site_nodes[0]
+ target_name = _node_text(target_nodes[0], src).strip()
+ if not target_name:
+ continue
+
+ # Skip language builtins — they pollute the call graph
+ # because Tier 3 global resolution can match them to
+ # unrelated user symbols with the same name.
+ if target_name in _call_builtins:
+ continue
+
+ line = site_node.start_point[0] + 1 # 1-indexed
+ receiver_name = _node_text(receiver_nodes[0], src).strip() if receiver_nodes else None
+
+ # Dedup: same line + target + receiver means same call captured
+ # by multiple overlapping query patterns
+ dedup_key = (line, target_name, receiver_name)
+ if dedup_key in seen:
+ continue
+ seen.add(dedup_key)
+
+ # Count arguments
+ arg_count: int | None = None
+ if arg_nodes:
+ arg_node = arg_nodes[0]
+ arg_count = _count_arguments(arg_node)
+
+ # Find enclosing symbol
+ caller_id = _find_enclosing_symbol(line, symbol_ranges)
+
+ calls.append(
+ CallSite(
+ target_name=target_name,
+ receiver_name=receiver_name,
+ caller_symbol_id=caller_id,
+ line=line,
+ argument_count=arg_count,
+ )
+ )
+
+ return calls
+
# ------------------------------------------------------------------
# Export derivation
# ------------------------------------------------------------------
@@ -878,49 +981,665 @@ def _build_signature(node_type: str, name: str, params_text: str, def_node: Node
return f"{name}{params_text}"
-def _extract_import_names(stmt_node: Node, src: str, lang: str) -> list[str]:
- """Extract specific imported names from an import statement node."""
+def _extract_import_bindings(
+ stmt_node: Node, src: str, lang: str
+) -> tuple[list[str], list[NamedBinding]]:
+ """Extract imported names and structured bindings from an import statement.
+
+ Returns (imported_names, bindings) where imported_names is the backward-
+ compatible list of local names and bindings carries alias/source detail.
+ """
names: list[str] = []
+ bindings: list[NamedBinding] = []
if lang == "python":
- for child in stmt_node.children:
- if child.type == "wildcard_import":
- return ["*"]
- if child.type == "dotted_name":
- text = _node_text(child, src)
- # Skip the module name itself (it's the first dotted_name in import_from)
- if names or stmt_node.type == "import_statement":
- names.append(text.split(".")[-1])
+ return _extract_python_bindings(stmt_node, src)
+
+ if lang in ("typescript", "javascript"):
+ return _extract_ts_js_bindings(stmt_node, src)
+
+ if lang == "go":
+ return _extract_go_bindings(stmt_node, src)
+
+ if lang == "rust":
+ return _extract_rust_bindings(stmt_node, src)
+
+ if lang == "java":
+ return _extract_java_bindings(stmt_node, src)
+
+ return names, bindings
+
+
+def _extract_python_bindings(
+ stmt_node: Node, src: str
+) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Python import/import_from statements."""
+ names: list[str] = []
+ bindings: list[NamedBinding] = []
+ is_from_import = stmt_node.type == "import_from_statement"
+ first_dotted_seen = False
+
+ for child in stmt_node.children:
+ if child.type == "wildcard_import":
+ return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
+
+ if child.type == "aliased_import":
+ name_node = child.child_by_field_name("name") or (
+ child.children[0] if child.children else None
+ )
+ alias_node = child.child_by_field_name("alias")
+ if name_node:
+ exported = _node_text(name_node, src)
+ local = _node_text(alias_node, src) if alias_node else exported
+ if is_from_import:
+ # from X import Y as Z
+ names.append(local)
+ bindings.append(
+ NamedBinding(local_name=local, exported_name=exported, source_file=None)
+ )
else:
- names.append(text.split(".")[-1])
- elif child.type == "aliased_import":
- name_child = child.child_by_field_name("name") or (
- child.children[0] if child.children else None
+ # import X.Y as Z — module alias
+ bare = exported.split(".")[-1]
+ local = _node_text(alias_node, src) if alias_node else bare
+ names.append(local)
+ bindings.append(
+ NamedBinding(
+ local_name=local,
+ exported_name=None,
+ source_file=None,
+ is_module_alias=True,
+ )
+ )
+
+ elif child.type == "dotted_name":
+ text = _node_text(child, src)
+ bare = text.split(".")[-1]
+ if is_from_import and not first_dotted_seen:
+ # First dotted_name in from-import is the module path — skip
+ first_dotted_seen = True
+ continue
+ names.append(bare)
+ if is_from_import:
+ bindings.append(
+ NamedBinding(local_name=bare, exported_name=bare, source_file=None)
+ )
+ else:
+ # import X.Y.Z — module alias
+ bindings.append(
+ NamedBinding(
+ local_name=bare,
+ exported_name=None,
+ source_file=None,
+ is_module_alias=True,
+ )
)
- if name_child:
- names.append(_node_text(name_child, src))
- return names
- if lang in ("typescript", "javascript"):
- # Find import_clause → named_imports → import_specifier
+ return names, bindings
+
+
+def _extract_ts_js_bindings(
+ stmt_node: Node, src: str
+) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from TypeScript/JavaScript import statements."""
+ names: list[str] = []
+ bindings: list[NamedBinding] = []
+
+ for child in stmt_node.children:
+ if child.type != "import_clause":
+ continue
+ for sub in child.children:
+ if sub.type == "identifier":
+ # default import: import React from 'react'
+ local = _node_text(sub, src)
+ names.append(local)
+ bindings.append(
+ NamedBinding(local_name=local, exported_name="default", source_file=None)
+ )
+ elif sub.type == "named_imports":
+ for spec in sub.children:
+ if spec.type != "import_specifier":
+ continue
+ name_node = spec.child_by_field_name("name") or (
+ spec.children[0] if spec.children else None
+ )
+ alias_node = spec.child_by_field_name("alias")
+ if name_node:
+ exported = _node_text(name_node, src)
+ local = _node_text(alias_node, src) if alias_node else exported
+ names.append(local)
+ bindings.append(
+ NamedBinding(
+ local_name=local, exported_name=exported, source_file=None
+ )
+ )
+ elif sub.type == "namespace_import":
+ # import * as ns from 'mod'
+ ns_name = None
+ for ns_child in sub.children:
+ if ns_child.type == "identifier":
+ ns_name = _node_text(ns_child, src)
+ if ns_name:
+ names.append(ns_name)
+ bindings.append(
+ NamedBinding(
+ local_name=ns_name,
+ exported_name=None,
+ source_file=None,
+ is_module_alias=True,
+ )
+ )
+ else:
+ names.append("*")
+ bindings.append(
+ NamedBinding(local_name="*", exported_name=None, source_file=None)
+ )
+
+ return names, bindings
+
+
+def _extract_go_bindings(
+ stmt_node: Node, src: str
+) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Go import specs."""
+ # Go import_spec: optional alias identifier + string literal path
+ alias_node = stmt_node.child_by_field_name("name")
+ path_node = stmt_node.child_by_field_name("path")
+
+ if path_node is None:
+ # Fallback: find the first string literal child
for child in stmt_node.children:
- if child.type == "import_clause":
- for sub in child.children:
- if sub.type == "identifier":
- names.append(_node_text(sub, src)) # default import
- elif sub.type == "named_imports":
- for spec in sub.children:
- if spec.type == "import_specifier":
- name_node = spec.child_by_field_name("name") or (
- spec.children[0] if spec.children else None
- )
- if name_node:
- names.append(_node_text(name_node, src))
- elif sub.type == "namespace_import":
- names = ["*"]
- return names
-
- return []
+ if child.type == "interpreted_string_literal":
+ path_node = child
+ break
+ if path_node is None:
+ return [], []
+
+ path_text = _node_text(path_node, src).strip("\"'` ")
+ default_name = path_text.rsplit("/", 1)[-1]
+
+ if alias_node:
+ alias = _node_text(alias_node, src)
+ if alias == ".":
+ return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
+ if alias == "_":
+ return [], []
+ return [alias], [
+ NamedBinding(
+ local_name=alias, exported_name=None, source_file=None, is_module_alias=True
+ )
+ ]
+
+ return [default_name], [
+ NamedBinding(
+ local_name=default_name,
+ exported_name=None,
+ source_file=None,
+ is_module_alias=True,
+ )
+ ]
+
+
+def _extract_rust_bindings(
+ stmt_node: Node, src: str
+) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Rust use declarations."""
+ arg_node = stmt_node.child_by_field_name("argument")
+ if arg_node is None:
+ # Fallback: first meaningful child
+ for child in stmt_node.children:
+ if child.type not in ("use", ";", "pub", "visibility_modifier"):
+ arg_node = child
+ break
+ if arg_node is None:
+ return [], []
+
+ names: list[str] = []
+ bindings: list[NamedBinding] = []
+ _parse_rust_use_tree(arg_node, src, names, bindings, depth=0)
+ return names, bindings
+
+
+def _parse_rust_use_tree(
+ node: Node,
+ src: str,
+ names: list[str],
+ bindings: list[NamedBinding],
+ depth: int,
+) -> None:
+ """Recursively parse a Rust use-tree into named bindings."""
+ if depth > 10:
+ return
+
+ if node.type == "use_as_clause":
+ path_child = node.child_by_field_name("path") or (
+ node.children[0] if node.children else None
+ )
+ alias_child = node.child_by_field_name("alias") or (
+ node.children[-1] if len(node.children) >= 2 else None
+ )
+ if path_child and alias_child and path_child != alias_child:
+ exported = _node_text(path_child, src).rsplit("::", 1)[-1]
+ local = _node_text(alias_child, src)
+ names.append(local)
+ bindings.append(
+ NamedBinding(local_name=local, exported_name=exported, source_file=None)
+ )
+ return
+
+ if node.type == "use_wildcard":
+ names.append("*")
+ bindings.append(NamedBinding(local_name="*", exported_name=None, source_file=None))
+ return
+
+ if node.type == "use_list":
+ for child in node.children:
+ if child.type in ("{", "}", ","):
+ continue
+ _parse_rust_use_tree(child, src, names, bindings, depth + 1)
+ return
+
+ if node.type == "scoped_use_list":
+ # e.g., std::collections::{HashMap, BTreeMap}
+ for child in node.children:
+ if child.type == "use_list":
+ _parse_rust_use_tree(child, src, names, bindings, depth + 1)
+ return
+
+ # scoped_identifier or identifier — bare name, last segment
+ text = _node_text(node, src)
+ bare = text.rsplit("::", 1)[-1]
+ if bare and bare != "*":
+ names.append(bare)
+ bindings.append(
+ NamedBinding(local_name=bare, exported_name=bare, source_file=None)
+ )
+
+
+def _extract_java_bindings(
+ stmt_node: Node, src: str
+) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Java import declarations."""
+ # Java: import com.example.Foo; → local_name="Foo"
+ for child in stmt_node.children:
+ if child.type == "scoped_identifier":
+ full = _node_text(child, src)
+ local = full.rsplit(".", 1)[-1]
+ if local == "*":
+ return ["*"], [
+ NamedBinding(local_name="*", exported_name=None, source_file=None)
+ ]
+ return [local], [
+ NamedBinding(local_name=local, exported_name=local, source_file=None)
+ ]
+ if child.type == "asterisk":
+ return ["*"], [
+ NamedBinding(local_name="*", exported_name=None, source_file=None)
+ ]
+ return [], []
+
+
+# ---------------------------------------------------------------------------
+# Heritage (inheritance / interface implementation) extraction
+# ---------------------------------------------------------------------------
+
+# Maps language → set of node types that can have heritage info
+_HERITAGE_NODE_TYPES: dict[str, frozenset[str]] = {
+ "python": frozenset({"class_definition"}),
+ "typescript": frozenset({"class_declaration", "abstract_class_declaration", "interface_declaration"}),
+ "javascript": frozenset({"class_declaration"}),
+ "java": frozenset({"class_declaration", "interface_declaration", "enum_declaration"}),
+ "go": frozenset({"type_spec"}),
+ "rust": frozenset({"impl_item", "trait_item"}),
+ "cpp": frozenset({"class_specifier", "struct_specifier"}),
+ "c": frozenset(),
+ "kotlin": frozenset({"class_declaration", "object_declaration"}),
+ "ruby": frozenset({"class"}),
+ "csharp": frozenset({"class_declaration", "interface_declaration", "struct_declaration"}),
+}
+
+
+def _extract_heritage(
+ tree: object,
+ query: object,
+ config: "LanguageConfig",
+ file_info: "FileInfo",
+ src: str,
+) -> list[HeritageRelation]:
+ """Extract inheritance/implementation relationships from class definitions.
+
+ Walks the same @symbol.def captures used by _extract_symbols, extracting
+ superclass/interface/trait information from the definition AST nodes.
+ """
+ if query is None:
+ return []
+
+ lang = file_info.language
+ heritage_types = _HERITAGE_NODE_TYPES.get(lang, frozenset())
+ if not heritage_types:
+ return []
+
+ from .language_data import get_builtin_parents
+
+ _parent_builtins = get_builtin_parents(lang)
+
+ relations: list[HeritageRelation] = []
+ seen: set[tuple[int, str]] = set()
+
+ for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]
+ def_nodes = capture_dict.get("symbol.def", [])
+ name_nodes = capture_dict.get("symbol.name", [])
+
+ if not def_nodes or not name_nodes:
+ continue
+
+ def_node = def_nodes[0]
+ if def_node.type not in heritage_types:
+ continue
+
+ name = _node_text(name_nodes[0], src)
+ if not name:
+ continue
+
+ line = def_node.start_point[0] + 1
+ dedup_key = (line, name)
+ if dedup_key in seen:
+ continue
+ seen.add(dedup_key)
+
+ extractor = _HERITAGE_EXTRACTORS.get(lang)
+ if extractor:
+ extractor(def_node, name, line, src, relations)
+
+ # Filter out builtin/stdlib parent types — they carry no architectural
+ # signal and pollute the heritage graph.
+ if _parent_builtins:
+ relations = [r for r in relations if r.parent_name not in _parent_builtins]
+
+ return relations
+
+
+def _extract_python_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Python: class Foo(Bar, Baz, metaclass=Meta)."""
+ superclasses = def_node.child_by_field_name("superclasses")
+ if superclasses is None:
+ # Also check for argument_list child (some grammar versions)
+ for child in def_node.children:
+ if child.type == "argument_list":
+ superclasses = child
+ break
+ if superclasses is None:
+ return
+
+ for child in superclasses.children:
+ if child.type in ("(", ")", ","):
+ continue
+ # Skip keyword arguments like metaclass=Meta
+ if child.type == "keyword_argument":
+ continue
+ parent = _node_text(child, src).strip()
+ if parent:
+ # Strip module prefix for qualified names (e.g., abc.ABC → ABC)
+ bare = parent.split(".")[-1]
+ out.append(HeritageRelation(
+ child_name=name, parent_name=bare, kind="extends", line=line
+ ))
+
+
+def _extract_ts_js_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """TypeScript/JavaScript: class Foo extends Bar implements IFoo, IBar."""
+ for child in def_node.children:
+ if child.type == "class_heritage":
+ for clause in child.children:
+ if clause.type == "extends_clause":
+ for type_node in clause.children:
+ if type_node.type in ("extends", ","):
+ continue
+ parent = _node_text(type_node, src).strip()
+ if parent:
+ out.append(HeritageRelation(
+ child_name=name, parent_name=parent,
+ kind="extends", line=line,
+ ))
+ elif clause.type == "implements_clause":
+ for type_node in clause.children:
+ if type_node.type in ("implements", ","):
+ continue
+ parent = _node_text(type_node, src).strip()
+ if parent:
+ out.append(HeritageRelation(
+ child_name=name, parent_name=parent,
+ kind="implements", line=line,
+ ))
+ # interface extends: interface Foo extends Bar
+ if child.type == "extends_type_clause":
+ for type_node in child.children:
+ if type_node.type in ("extends", ","):
+ continue
+ parent = _node_text(type_node, src).strip()
+ if parent:
+ out.append(HeritageRelation(
+ child_name=name, parent_name=parent,
+ kind="extends", line=line,
+ ))
+
+
+def _extract_java_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Java: class Foo extends Bar implements IFoo, IBar."""
+ superclass = def_node.child_by_field_name("superclass")
+ if superclass:
+ parent = _node_text(superclass, src).strip()
+ # Strip 'extends' keyword if captured
+ parent = parent.removeprefix("extends").strip()
+ if parent:
+ out.append(HeritageRelation(
+ child_name=name, parent_name=parent.split(".")[-1],
+ kind="extends", line=line,
+ ))
+
+ interfaces = def_node.child_by_field_name("interfaces")
+ if interfaces:
+ for child in interfaces.children:
+ if child.type in ("implements", "extends", ",", "type_list"):
+ if child.type == "type_list":
+ for type_node in child.children:
+ if type_node.type != ",":
+ parent = _node_text(type_node, src).strip().split(".")[-1]
+ if parent:
+ kind = "implements" if def_node.type == "class_declaration" else "extends"
+ out.append(HeritageRelation(
+ child_name=name, parent_name=parent,
+ kind=kind, line=line,
+ ))
+ continue
+ parent = _node_text(child, src).strip().split(".")[-1]
+ if parent and parent not in ("implements", "extends"):
+ kind = "implements" if def_node.type == "class_declaration" else "extends"
+ out.append(HeritageRelation(
+ child_name=name, parent_name=parent, kind=kind, line=line,
+ ))
+
+
+def _extract_go_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Go: struct embedding (type Foo struct { Bar; baz.Qux })."""
+ # type_spec → type field is the body (struct_type or interface_type)
+ type_node = def_node.child_by_field_name("type")
+ if type_node is None:
+ return
+
+ if type_node.type == "struct_type":
+ body = type_node.child_by_field_name("body") or type_node
+ if body is None:
+ return
+ for field_decl in body.children:
+ if field_decl.type != "field_declaration":
+ continue
+ # Embedded field: no name, just a type
+ name_node = field_decl.child_by_field_name("name")
+ type_child = field_decl.child_by_field_name("type")
+ if name_node is None and type_child is not None:
+ # This is an embedded field
+ parent = _node_text(type_child, src).strip().lstrip("*")
+ bare = parent.split(".")[-1]
+ if bare:
+ out.append(HeritageRelation(
+ child_name=name, parent_name=bare,
+ kind="mixin", line=line,
+ ))
+
+ elif type_node.type == "interface_type":
+ # Interface embedding: interface { io.Reader }
+ for child in type_node.children:
+ if child.type in ("{", "}", "\n"):
+ continue
+ # Embedded interfaces appear as type names without method signatures
+ if child.type in ("type_identifier", "qualified_type"):
+ parent = _node_text(child, src).strip()
+ bare = parent.split(".")[-1]
+ if bare:
+ out.append(HeritageRelation(
+ child_name=name, parent_name=bare,
+ kind="extends", line=line,
+ ))
+
+
+def _extract_rust_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Rust: impl Trait for Type, trait Foo: Bar + Baz."""
+ if def_node.type == "impl_item":
+ # Check for 'impl Trait for Type' pattern
+ trait_node = def_node.child_by_field_name("trait")
+ type_node = def_node.child_by_field_name("type")
+ if trait_node and type_node:
+ trait_name = _node_text(trait_node, src).strip().rsplit("::", 1)[-1]
+ type_name = _node_text(type_node, src).strip()
+ if trait_name and type_name:
+ out.append(HeritageRelation(
+ child_name=type_name, parent_name=trait_name,
+ kind="trait_impl", line=line,
+ ))
+
+ elif def_node.type == "trait_item":
+ # trait Foo: Bar + Baz (supertrait bounds)
+ bounds = def_node.child_by_field_name("bounds")
+ if bounds:
+ for child in bounds.children:
+ if child.type in ("+", ":"):
+ continue
+ parent = _node_text(child, src).strip().rsplit("::", 1)[-1]
+ if parent:
+ out.append(HeritageRelation(
+ child_name=name, parent_name=parent,
+ kind="extends", line=line,
+ ))
+
+
+def _extract_cpp_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """C++: class Foo : public Bar, protected Baz."""
+ for child in def_node.children:
+ if child.type == "base_class_clause":
+ for base in child.children:
+ if base.type in (":", ","):
+ continue
+ # base_class_clause children may include access specifiers
+ text = _node_text(base, src).strip()
+ # Strip access specifier (public/protected/private/virtual)
+ for prefix in ("public", "protected", "private", "virtual"):
+ text = text.removeprefix(prefix).strip()
+ bare = text.split("::")[-1].strip()
+ if bare:
+ out.append(HeritageRelation(
+ child_name=name, parent_name=bare,
+ kind="extends", line=line,
+ ))
+
+
+def _extract_kotlin_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Kotlin: class Foo : Bar(), IFoo."""
+ for child in def_node.children:
+ if child.type == "delegation_specifier":
+ for delegate in child.children:
+ text = _node_text(delegate, src).strip()
+ # Remove constructor call parens
+ bare = text.split("(")[0].split(".")[-1].strip()
+ if bare and bare != name:
+ out.append(HeritageRelation(
+ child_name=name, parent_name=bare,
+ kind="extends", line=line,
+ ))
+ elif child.type == "delegation_specifiers":
+ for delegate in child.children:
+ if delegate.type in (":", ","):
+ continue
+ text = _node_text(delegate, src).strip()
+ bare = text.split("(")[0].split(".")[-1].strip()
+ if bare and bare != name:
+ out.append(HeritageRelation(
+ child_name=name, parent_name=bare,
+ kind="extends", line=line,
+ ))
+
+
+def _extract_ruby_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Ruby: class Foo < Bar."""
+ superclass = def_node.child_by_field_name("superclass")
+ if superclass:
+ parent = _node_text(superclass, src).strip()
+ # Strip the '<' if it was captured
+ parent = parent.removeprefix("<").strip()
+ bare = parent.split("::")[-1]
+ if bare:
+ out.append(HeritageRelation(
+ child_name=name, parent_name=bare, kind="extends", line=line,
+ ))
+
+
+def _extract_csharp_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """C#: class Foo : Bar, IFoo."""
+ for child in def_node.children:
+ if child.type == "base_list":
+ for base in child.children:
+ if base.type in (":", ","):
+ continue
+ text = _node_text(base, src).strip()
+ bare = text.split(".")[-1].split("<")[0].strip()
+ if bare and bare != name:
+ # Convention: interfaces start with I
+ kind = "implements" if bare.startswith("I") and len(bare) > 1 and bare[1].isupper() else "extends"
+ out.append(HeritageRelation(
+ child_name=name, parent_name=bare, kind=kind, line=line,
+ ))
+
+
+_HERITAGE_EXTRACTORS: dict[str, Callable[..., None]] = {
+ "python": _extract_python_heritage,
+ "typescript": _extract_ts_js_heritage,
+ "javascript": _extract_ts_js_heritage,
+ "java": _extract_java_heritage,
+ "go": _extract_go_heritage,
+ "rust": _extract_rust_heritage,
+ "cpp": _extract_cpp_heritage,
+ "c": lambda *_: None,
+ "kotlin": _extract_kotlin_heritage,
+ "ruby": _extract_ruby_heritage,
+ "csharp": _extract_csharp_heritage,
+}
def _extract_go_receiver_type(receiver_text: str) -> str | None:
@@ -1009,3 +1728,44 @@ def _build_qualified_name(file_path: str, parent_name: str | None, name: str) ->
if parent_name:
return f"{module}.{parent_name}.{name}"
return f"{module}.{name}"
+
+
+# ---------------------------------------------------------------------------
+# Call extraction helpers
+# ---------------------------------------------------------------------------
+
+
+def _count_arguments(arg_node: Node) -> int:
+ """Count the number of arguments in an argument/argument_list node.
+
+ Skips punctuation children (commas, parens) and counts only
+ substantive argument nodes.
+ """
+ _SKIP_TYPES = frozenset({"(", ")", ",", "[", "]"})
+ return sum(1 for child in arg_node.children if child.type not in _SKIP_TYPES)
+
+
+def _find_enclosing_symbol(
+ line: int,
+ symbol_ranges: list[tuple[int, int, str]],
+) -> str | None:
+ """Find the innermost symbol whose line range contains *line*.
+
+ Uses a linear scan on the pre-sorted ranges. For typical file sizes
+ (< 500 symbols) this is faster than bisect due to low constant factor.
+ Returns the tightest (smallest span) enclosing symbol ID, or None if
+ the call is at module level.
+ """
+ best_id: str | None = None
+ best_span = float("inf")
+
+ for start, end, sym_id in symbol_ranges:
+ if start > line:
+ break # ranges sorted by start_line — no further match possible
+ if start <= line <= end:
+ span = end - start
+ if span < best_span:
+ best_span = span
+ best_id = sym_id
+
+ return best_id
diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
index e03ce803d..9a6f7e97e 100644
--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
@@ -115,3 +115,39 @@
(preproc_include
path: (string_literal) @import.module
) @import.statement
+
+; ---------------------------------------------------------------------------
+; Calls
+; ---------------------------------------------------------------------------
+
+; Simple function call: foo(args)
+(call_expression
+ function: (identifier) @call.target
+ arguments: (argument_list) @call.arguments
+) @call.site
+
+; Method call: obj.method(args) or obj->method(args)
+(call_expression
+ function: (field_expression
+ argument: (identifier) @call.receiver
+ field: (field_identifier) @call.target
+ )
+ arguments: (argument_list) @call.arguments
+) @call.site
+
+; Scoped call: ClassName::method(args) or namespace::function(args)
+(call_expression
+ function: (qualified_identifier
+ name: (identifier) @call.target
+ )
+ arguments: (argument_list) @call.arguments
+) @call.site
+
+; Chained call: obj.method1().method2(args)
+(call_expression
+ function: (field_expression
+ argument: (call_expression)
+ field: (field_identifier) @call.target
+ )
+ arguments: (argument_list) @call.arguments
+) @call.site
diff --git a/packages/core/src/repowise/core/ingestion/queries/go.scm b/packages/core/src/repowise/core/ingestion/queries/go.scm
index 6ba262a09..a649fc0d8 100644
--- a/packages/core/src/repowise/core/ingestion/queries/go.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/go.scm
@@ -44,3 +44,35 @@
(import_spec
(interpreted_string_literal) @import.module
) @import.statement
+
+; ---------------------------------------------------------------------------
+; Calls
+; ---------------------------------------------------------------------------
+
+; Simple function call: foo(arg1, arg2)
+(call_expression
+ function: (identifier) @call.target
+ arguments: (argument_list) @call.arguments
+) @call.site
+
+; Method call: obj.Method(args)
+(call_expression
+ function: (selector_expression
+ operand: (identifier) @call.receiver
+ field: (field_identifier) @call.target
+ )
+ arguments: (argument_list) @call.arguments
+) @call.site
+
+; Package-qualified call: pkg.Function(args)
+; (same pattern as method call — receiver is the package alias)
+; Captured by the selector_expression pattern above.
+
+; Chained call: obj.Method1().Method2(args)
+(call_expression
+ function: (selector_expression
+ operand: (call_expression)
+ field: (field_identifier) @call.target
+ )
+ arguments: (argument_list) @call.arguments
+) @call.site
diff --git a/packages/core/src/repowise/core/ingestion/queries/java.scm b/packages/core/src/repowise/core/ingestion/queries/java.scm
index a3d7428e7..cf2814a54 100644
--- a/packages/core/src/repowise/core/ingestion/queries/java.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/java.scm
@@ -42,3 +42,33 @@
(import_declaration
(scoped_identifier) @import.module
) @import.statement
+
+; ---------------------------------------------------------------------------
+; Calls
+; ---------------------------------------------------------------------------
+
+; Simple function/static method call: foo(args)
+(method_invocation
+ name: (identifier) @call.target
+ arguments: (argument_list) @call.arguments
+) @call.site
+
+; Method call on object: obj.method(args)
+(method_invocation
+ object: (identifier) @call.receiver
+ name: (identifier) @call.target
+ arguments: (argument_list) @call.arguments
+) @call.site
+
+; Chained method call: obj.method1().method2(args)
+(method_invocation
+ object: (method_invocation)
+ name: (identifier) @call.target
+ arguments: (argument_list) @call.arguments
+) @call.site
+
+; Constructor: new ClassName(args)
+(object_creation_expression
+ type: (type_identifier) @call.target
+ arguments: (argument_list) @call.arguments
+) @call.site
diff --git a/packages/core/src/repowise/core/ingestion/queries/javascript.scm b/packages/core/src/repowise/core/ingestion/queries/javascript.scm
index 503866a29..20c78d359 100644
--- a/packages/core/src/repowise/core/ingestion/queries/javascript.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/javascript.scm
@@ -43,3 +43,37 @@
(import_statement
source: (string) @import.module
) @import.statement
+
+; ---------------------------------------------------------------------------
+; Calls
+; ---------------------------------------------------------------------------
+
+; Simple function call: foo(arg1, arg2)
+(call_expression
+ function: (identifier) @call.target
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Method call: obj.method(args)
+(call_expression
+ function: (member_expression
+ object: (identifier) @call.receiver
+ property: (property_identifier) @call.target
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Chained call: obj.method1().method2(args)
+(call_expression
+ function: (member_expression
+ object: (call_expression)
+ property: (property_identifier) @call.target
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; new expression: new Foo(args)
+(new_expression
+ constructor: (identifier) @call.target
+ arguments: (arguments) @call.arguments
+) @call.site
diff --git a/packages/core/src/repowise/core/ingestion/queries/python.scm b/packages/core/src/repowise/core/ingestion/queries/python.scm
index 6558b115b..394948561 100644
--- a/packages/core/src/repowise/core/ingestion/queries/python.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/python.scm
@@ -57,3 +57,34 @@
(import_statement
name: (_) @import.module
) @import.statement
+
+; ---------------------------------------------------------------------------
+; Calls
+; ---------------------------------------------------------------------------
+
+; Simple function call: foo(arg1, arg2)
+(call
+ function: (identifier) @call.target
+ arguments: (argument_list) @call.arguments
+) @call.site
+
+; Method call: obj.method(arg1, arg2)
+(call
+ function: (attribute
+ object: (identifier) @call.receiver
+ attribute: (identifier) @call.target
+ )
+ arguments: (argument_list) @call.arguments
+) @call.site
+
+; Chained method call: obj.method1().method2(args)
+(call
+ function: (attribute
+ object: (call)
+ attribute: (identifier) @call.target
+ )
+ arguments: (argument_list) @call.arguments
+) @call.site
+
+; Constructor call via class name: MyClass(args)
+; (captured by the simple function call pattern above — class names are identifiers)
diff --git a/packages/core/src/repowise/core/ingestion/queries/rust.scm b/packages/core/src/repowise/core/ingestion/queries/rust.scm
index f332f0f9b..329a770a4 100644
--- a/packages/core/src/repowise/core/ingestion/queries/rust.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/rust.scm
@@ -59,3 +59,44 @@
(use_declaration
argument: (_) @import.module
) @import.statement
+
+; ---------------------------------------------------------------------------
+; Calls
+; ---------------------------------------------------------------------------
+
+; Simple function call: foo(arg1, arg2)
+(call_expression
+ function: (identifier) @call.target
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Method call: obj.method(args)
+(call_expression
+ function: (field_expression
+ value: (identifier) @call.receiver
+ field: (field_identifier) @call.target
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Scoped function call: module::function(args)
+(call_expression
+ function: (scoped_identifier
+ name: (identifier) @call.target
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Chained call: obj.method1().method2(args)
+(call_expression
+ function: (field_expression
+ value: (call_expression)
+ field: (field_identifier) @call.target
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Macro invocation: println!(...), vec![...]
+(macro_invocation
+ macro: (identifier) @call.target
+) @call.site
diff --git a/packages/core/src/repowise/core/ingestion/queries/typescript.scm b/packages/core/src/repowise/core/ingestion/queries/typescript.scm
index a02f871b1..b8916e8c9 100644
--- a/packages/core/src/repowise/core/ingestion/queries/typescript.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/typescript.scm
@@ -76,3 +76,37 @@
(import_statement
source: (string) @import.module
) @import.statement
+
+; ---------------------------------------------------------------------------
+; Calls
+; ---------------------------------------------------------------------------
+
+; Simple function call: foo(arg1, arg2)
+(call_expression
+ function: (identifier) @call.target
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Method call: obj.method(args)
+(call_expression
+ function: (member_expression
+ object: (identifier) @call.receiver
+ property: (property_identifier) @call.target
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; Chained call: obj.method1().method2(args)
+(call_expression
+ function: (member_expression
+ object: (call_expression)
+ property: (property_identifier) @call.target
+ )
+ arguments: (arguments) @call.arguments
+) @call.site
+
+; new expression: new Foo(args)
+(new_expression
+ constructor: (identifier) @call.target
+ arguments: (arguments) @call.arguments
+) @call.site
diff --git a/packages/core/src/repowise/core/persistence/__init__.py b/packages/core/src/repowise/core/persistence/__init__.py
index 790afc80e..16505ed2b 100644
--- a/packages/core/src/repowise/core/persistence/__init__.py
+++ b/packages/core/src/repowise/core/persistence/__init__.py
@@ -26,8 +26,11 @@ from .crud import (
create_conversation,
delete_conversation,
delete_decision,
+ get_all_file_metrics,
get_all_git_metadata,
+ get_community_members,
get_conversation,
+ get_cross_community_edges,
get_dead_code_findings,
get_dead_code_summary,
get_decision,
@@ -35,12 +38,17 @@ from .crud import (
get_generation_job,
get_git_metadata,
get_git_metadata_bulk,
+ get_graph_edges_for_node,
+ get_graph_node,
+ get_graph_nodes_by_ids,
+ get_node_degree_counts,
get_page,
get_page_versions,
get_repository,
get_repository_by_path,
get_stale_decisions,
get_stale_pages,
+ get_top_entry_points,
list_chat_messages,
list_conversations,
list_decisions,
@@ -138,6 +146,15 @@ __all__ = [
"bulk_upsert_decisions",
# chat crud
"count_chat_messages",
+ # graph read-side queries
+ "get_all_file_metrics",
+ "get_community_members",
+ "get_cross_community_edges",
+ "get_graph_edges_for_node",
+ "get_graph_node",
+ "get_graph_nodes_by_ids",
+ "get_node_degree_counts",
+ "get_top_entry_points",
"create_chat_message",
"create_conversation",
"create_engine",
diff --git a/packages/core/src/repowise/core/persistence/crud.py b/packages/core/src/repowise/core/persistence/crud.py
index b3654bd45..2624b67be 100644
--- a/packages/core/src/repowise/core/persistence/crud.py
+++ b/packages/core/src/repowise/core/persistence/crud.py
@@ -18,7 +18,7 @@ import json
from datetime import UTC, datetime
from typing import Any
-from sqlalchemy import select, text
+from sqlalchemy import func, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from .models import (
@@ -455,16 +455,21 @@ async def batch_upsert_graph_edges(
"""Upsert graph edges for a repository.
Each element of *edges* should have ``source_node_id``, ``target_node_id``,
- and optionally ``imported_names_json``.
+ ``edge_type``, and optionally ``imported_names_json`` and ``confidence``.
+
+ The unique constraint is (repository_id, source, target, edge_type),
+ allowing multiple edge types between the same pair of nodes.
"""
for edge_data in edges:
source = edge_data.get("source_node_id", "")
target = edge_data.get("target_node_id", "")
+ edge_type = edge_data.get("edge_type", "imports")
result = await session.execute(
select(GraphEdge).where(
GraphEdge.repository_id == repository_id,
GraphEdge.source_node_id == source,
GraphEdge.target_node_id == target,
+ GraphEdge.edge_type == edge_type,
)
)
existing = result.scalar_one_or_none()
@@ -473,9 +478,9 @@ async def batch_upsert_graph_edges(
imported = edge_data.get("imported_names_json")
if imported is not None:
existing.imported_names_json = imported
- edge_type = edge_data.get("edge_type")
- if edge_type is not None:
- existing.edge_type = edge_type
+ confidence = edge_data.get("confidence")
+ if confidence is not None:
+ existing.confidence = confidence
else:
session.add(
GraphEdge(
@@ -484,7 +489,8 @@ async def batch_upsert_graph_edges(
source_node_id=source,
target_node_id=target,
imported_names_json=edge_data.get("imported_names_json", "[]"),
- edge_type=edge_data.get("edge_type", "imports"),
+ edge_type=edge_type,
+ confidence=edge_data.get("confidence", 1.0),
)
)
@@ -1013,9 +1019,12 @@ async def list_decisions(
if source is not None:
q = q.where(DecisionRecord.source == source)
if tag is not None:
- q = q.where(DecisionRecord.tags_json.contains(tag))
+ # Match exact tag value in JSON array, not substring.
+ # JSON arrays store as '["tag1", "tag2"]', so we match '"tag"'
+ q = q.where(DecisionRecord.tags_json.contains(f'"{tag}"'))
if module is not None:
- q = q.where(DecisionRecord.affected_modules_json.contains(module))
+ # Match exact module path in JSON array
+ q = q.where(DecisionRecord.affected_modules_json.contains(f'"{module}"'))
q = q.order_by(DecisionRecord.created_at.desc()).limit(limit).offset(offset)
result = await session.execute(q)
return list(result.scalars().all())
@@ -1106,14 +1115,54 @@ async def delete_decision(session: AsyncSession, decision_id: str) -> bool:
return True
+def _normalize_title(title: str) -> str:
+ """Normalize a decision title for cross-source dedup comparison."""
+ import re as _re
+ t = title.lower().strip()
+ t = _re.sub(r"[^a-z0-9\s]", "", t)
+ t = _re.sub(r"\s+", " ", t)
+ return t
+
+
async def bulk_upsert_decisions(
session: AsyncSession,
repository_id: str,
decisions: list[dict],
) -> None:
- """Bulk upsert decision records from a list of dicts."""
- for i in range(0, len(decisions), _BATCH_SIZE):
- batch = decisions[i : i + _BATCH_SIZE]
+ """Bulk upsert decision records from a list of dicts.
+
+ Performs cross-source deduplication: if two decisions from different
+ sources have near-identical normalized titles, the one with higher
+ confidence wins and the other is skipped.
+ """
+ # Cross-source dedup: group by normalized title, keep highest confidence
+ seen: dict[str, dict] = {} # normalized_title → best decision dict
+ for d in decisions:
+ title = d.get("title", "")
+ norm = _normalize_title(title)
+ if not norm:
+ continue
+ existing = seen.get(norm)
+ if existing is None:
+ seen[norm] = d
+ else:
+ # Keep the one with higher confidence; on tie, prefer more specific source
+ new_conf = d.get("confidence", 0.0)
+ old_conf = existing.get("confidence", 0.0)
+ if new_conf > old_conf:
+ seen[norm] = d
+ elif new_conf == old_conf:
+ # Prefer inline_marker > readme_mining > git_archaeology
+ source_priority = {"inline_marker": 3, "readme_mining": 2, "git_archaeology": 1}
+ if source_priority.get(d.get("source", ""), 0) > source_priority.get(
+ existing.get("source", ""), 0
+ ):
+ seen[norm] = d
+
+ deduped = list(seen.values())
+
+ for i in range(0, len(deduped), _BATCH_SIZE):
+ batch = deduped[i : i + _BATCH_SIZE]
for d in batch:
await upsert_decision(
session,
@@ -1334,11 +1383,247 @@ async def list_chat_messages(session: AsyncSession, conversation_id: str) -> lis
async def count_chat_messages(session: AsyncSession, conversation_id: str) -> int:
- from sqlalchemy import func
-
result = await session.execute(
select(func.count())
.select_from(ChatMessage)
.where(ChatMessage.conversation_id == conversation_id)
)
return result.scalar() or 0
+
+
+# ---------------------------------------------------------------------------
+# Graph read-side queries (Phase 5 — MCP graph tools)
+# ---------------------------------------------------------------------------
+
+
+async def get_graph_node(
+ session: AsyncSession,
+ repository_id: str,
+ node_id: str,
+) -> GraphNode | None:
+ """Look up a single GraphNode by its ``node_id`` (file path or symbol ID)."""
+ result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repository_id,
+ GraphNode.node_id == node_id,
+ )
+ )
+ return result.scalar_one_or_none()
+
+
+async def get_graph_edges_for_node(
+ session: AsyncSession,
+ repository_id: str,
+ node_id: str,
+ *,
+ direction: str = "both",
+ edge_types: list[str] | None = None,
+ limit: int = 50,
+) -> list[GraphEdge]:
+ """Return edges adjacent to *node_id*.
+
+ Parameters
+ ----------
+ direction:
+ ``"callers"`` → inbound edges (target == node_id),
+ ``"callees"`` → outbound edges (source == node_id),
+ ``"both"`` → union of both.
+ edge_types:
+ Optional filter, e.g. ``["calls"]`` or ``["extends", "implements"]``.
+ limit:
+ Max edges per direction.
+ """
+ results: list[GraphEdge] = []
+
+ if direction in ("callers", "both"):
+ q = select(GraphEdge).where(
+ GraphEdge.repository_id == repository_id,
+ GraphEdge.target_node_id == node_id,
+ )
+ if edge_types:
+ q = q.where(GraphEdge.edge_type.in_(edge_types))
+ q = q.limit(limit)
+ res = await session.execute(q)
+ results.extend(res.scalars().all())
+
+ if direction in ("callees", "both"):
+ q = select(GraphEdge).where(
+ GraphEdge.repository_id == repository_id,
+ GraphEdge.source_node_id == node_id,
+ )
+ if edge_types:
+ q = q.where(GraphEdge.edge_type.in_(edge_types))
+ q = q.limit(limit)
+ res = await session.execute(q)
+ results.extend(res.scalars().all())
+
+ return results
+
+
+async def get_graph_nodes_by_ids(
+ session: AsyncSession,
+ repository_id: str,
+ node_ids: list[str],
+) -> dict[str, GraphNode]:
+ """Batch-lookup GraphNodes by node_id. Returns ``{node_id: GraphNode}``."""
+ if not node_ids:
+ return {}
+ # Process in batches to stay under SQLite parameter limits
+ out: dict[str, GraphNode] = {}
+ for i in range(0, len(node_ids), _BATCH_SIZE):
+ batch = node_ids[i : i + _BATCH_SIZE]
+ result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repository_id,
+ GraphNode.node_id.in_(batch),
+ )
+ )
+ for node in result.scalars().all():
+ out[node.node_id] = node
+ return out
+
+
+async def get_community_members(
+ session: AsyncSession,
+ repository_id: str,
+ community_id: int,
+ *,
+ node_type: str = "file",
+ limit: int = 50,
+) -> list[GraphNode]:
+ """Return all nodes in a community, ordered by PageRank descending."""
+ result = await session.execute(
+ select(GraphNode)
+ .where(
+ GraphNode.repository_id == repository_id,
+ GraphNode.node_type == node_type,
+ GraphNode.community_id == community_id,
+ )
+ .order_by(GraphNode.pagerank.desc())
+ .limit(limit)
+ )
+ return list(result.scalars().all())
+
+
+async def get_all_file_metrics(
+ session: AsyncSession,
+ repository_id: str,
+) -> list[GraphNode]:
+ """Return all file-type GraphNodes (for percentile computation)."""
+ result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repository_id,
+ GraphNode.node_type == "file",
+ )
+ )
+ return list(result.scalars().all())
+
+
+async def get_cross_community_edges(
+ session: AsyncSession,
+ repository_id: str,
+ community_id: int,
+) -> list[dict]:
+ """Count edges crossing from *community_id* to other communities.
+
+ Returns a list of ``{"target_community_id": int, "edge_count": int}``.
+ Uses a join through ``graph_nodes`` to resolve target community.
+ """
+ # Alias for the target node lookup
+ target_node = GraphNode.__table__.alias("tn")
+ source_node = GraphNode.__table__.alias("sn")
+
+ q = (
+ select(
+ target_node.c.community_id.label("target_community_id"),
+ func.count().label("edge_count"),
+ )
+ .select_from(GraphEdge.__table__)
+ .join(
+ source_node,
+ (GraphEdge.__table__.c.source_node_id == source_node.c.node_id)
+ & (GraphEdge.__table__.c.repository_id == source_node.c.repository_id),
+ )
+ .join(
+ target_node,
+ (GraphEdge.__table__.c.target_node_id == target_node.c.node_id)
+ & (GraphEdge.__table__.c.repository_id == target_node.c.repository_id),
+ )
+ .where(
+ GraphEdge.__table__.c.repository_id == repository_id,
+ source_node.c.community_id == community_id,
+ target_node.c.community_id != community_id,
+ # Only count file-level edges for meaningful community crossing
+ source_node.c.node_type == "file",
+ target_node.c.node_type == "file",
+ )
+ .group_by(target_node.c.community_id)
+ .order_by(func.count().desc())
+ )
+ result = await session.execute(q)
+ return [
+ {"target_community_id": row.target_community_id, "edge_count": row.edge_count}
+ for row in result.all()
+ ]
+
+
+async def get_top_entry_points(
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ min_score: float = 0.3,
+ limit: int = 20,
+) -> list[GraphNode]:
+ """Return symbol nodes with stored entry_point_score >= *min_score*.
+
+ Scores are stored inside ``community_meta_json``. Since the count of
+ symbol nodes is typically < 5000, an in-memory filter is acceptable.
+ """
+ result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repository_id,
+ GraphNode.node_type == "symbol",
+ )
+ )
+ all_symbols = result.scalars().all()
+
+ scored: list[tuple[float, GraphNode]] = []
+ for node in all_symbols:
+ try:
+ meta = json.loads(node.community_meta_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ continue
+ score = meta.get("entry_point_score")
+ if score is not None and score >= min_score:
+ scored.append((score, node))
+
+ scored.sort(key=lambda x: x[0], reverse=True)
+ return [node for _, node in scored[:limit]]
+
+
+async def get_node_degree_counts(
+ session: AsyncSession,
+ repository_id: str,
+ node_id: str,
+) -> dict[str, int]:
+ """Return in-degree and out-degree for a node from edge counts."""
+ in_result = await session.execute(
+ select(func.count())
+ .select_from(GraphEdge)
+ .where(
+ GraphEdge.repository_id == repository_id,
+ GraphEdge.target_node_id == node_id,
+ )
+ )
+ out_result = await session.execute(
+ select(func.count())
+ .select_from(GraphEdge)
+ .where(
+ GraphEdge.repository_id == repository_id,
+ GraphEdge.source_node_id == node_id,
+ )
+ )
+ return {
+ "in_degree": in_result.scalar() or 0,
+ "out_degree": out_result.scalar() or 0,
+ }
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 2daeb00ad..4ce670e8b 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -154,7 +154,7 @@ class GraphNode(Base):
repository_id: Mapped[str] = mapped_column(
String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False
)
- # Relative file path (the logical node identifier within a repo)
+ # Relative file path (for file nodes) or symbol ID (for symbol nodes)
node_id: Mapped[str] = mapped_column(Text, nullable=False)
node_type: Mapped[str] = mapped_column(String(32), nullable=False, default="file")
language: Mapped[str] = mapped_column(String(32), nullable=False, default="")
@@ -165,6 +165,17 @@ class GraphNode(Base):
pagerank: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
betweenness: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
community_id: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+ community_meta_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
+ # Symbol-level fields (null for file nodes)
+ kind: Mapped[str | None] = mapped_column(String(32), nullable=True)
+ name: Mapped[str | None] = mapped_column(String(255), nullable=True)
+ qualified_name: Mapped[str | None] = mapped_column(Text, nullable=True)
+ file_path: Mapped[str | None] = mapped_column(Text, nullable=True)
+ start_line: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ end_line: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ visibility: Mapped[str | None] = mapped_column(String(16), nullable=True)
+ signature: Mapped[str | None] = mapped_column(Text, nullable=True)
+ parent_symbol_id: Mapped[str | None] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
)
@@ -182,13 +193,17 @@ class GraphEdge(Base):
source_node_id: Mapped[str] = mapped_column(Text, nullable=False)
target_node_id: Mapped[str] = mapped_column(Text, nullable=False)
imported_names_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
- edge_type: Mapped[str | None] = mapped_column(String(64), nullable=True, default="imports")
+ edge_type: Mapped[str] = mapped_column(String(64), nullable=False, default="imports")
+ confidence: Mapped[float] = mapped_column(Float, nullable=False, default=1.0)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
)
__table_args__ = (
- UniqueConstraint("repository_id", "source_node_id", "target_node_id", name="uq_graph_edge"),
+ UniqueConstraint(
+ "repository_id", "source_node_id", "target_node_id", "edge_type",
+ name="uq_graph_edge_typed",
+ ),
)
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index 70e54dfaa..65535cde1 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -121,6 +121,9 @@ class PipelineResult:
languages: set[str] = field(default_factory=set)
elapsed_seconds: float = 0.0
+ execution_flow_report: Any | None = None
+ """``ExecutionFlowReport`` or None (populated after graph build)."""
+
# Traversal stats
traversal_stats: Any | None = None
"""``TraversalStats`` from the file traverser, or None."""
@@ -245,16 +248,28 @@ async def run_pipeline(
if git_meta_map:
graph_builder.add_co_change_edges(git_meta_map)
+ # Emit rich insight summary for the ingestion phase
if progress:
+ _g = graph_builder.graph()
+ _n_nodes = _g.number_of_nodes()
+ _n_edges = _g.number_of_edges()
progress.on_message(
"info",
- f"Ingested {len(parsed_files)} files"
- + (
- f" · Git: {git_summary.files_indexed} files"
- if git_summary and git_summary.files_indexed
- else ""
- ),
+ f"→ {len(parsed_files):,} files parsed · "
+ f"{sum(len(pf.symbols) for pf in parsed_files):,} symbols extracted",
)
+ progress.on_message(
+ "info",
+ f"→ Graph: {_n_nodes:,} nodes · {_n_edges:,} edges",
+ )
+ if git_summary and git_summary.files_indexed:
+ _hotspot_msg = ""
+ if hasattr(git_summary, "hotspots") and git_summary.hotspots:
+ _hotspot_msg = f" · {git_summary.hotspots} hotspots"
+ progress.on_message(
+ "info",
+ f"→ Git: {git_summary.files_indexed:,} files indexed{_hotspot_msg}",
+ )
# Test-run: limit to top 10 files by PageRank
if test_run and generate_docs:
@@ -308,6 +323,13 @@ async def run_pipeline(
resume=resume,
)
+ # ---- Execution flow tracing -----------------------------------------------
+ execution_flow_report = None
+ try:
+ execution_flow_report = graph_builder.execution_flows()
+ except Exception as _flow_err:
+ logger.warning("execution_flow_tracing_skipped", error=str(_flow_err))
+
# ---- Build result -------------------------------------------------------
elapsed = time.monotonic() - start
languages = {fi.language for fi in file_infos if hasattr(fi, "language") and fi.language}
@@ -324,6 +346,7 @@ async def run_pipeline(
git_summary=git_summary,
dead_code_report=dead_code_report,
decision_report=decision_report,
+ execution_flow_report=execution_flow_report,
generated_pages=generated_pages,
traversal_stats=traversal_stats,
repo_name=repo_path.name,
@@ -630,8 +653,8 @@ async def _run_dead_code_analysis(
unused_exports = sum(1 for f in report.findings if f.kind.value == "unused_export")
progress.on_message(
"info",
- f"Dead code: {unreachable} unreachable files "
- f"· {unused_exports} unused exports (~{report.deletable_lines:,} lines)",
+ f"→ {unreachable} unreachable files · "
+ f"{unused_exports} unused exports · ~{report.deletable_lines:,} deletable lines",
)
return report
@@ -672,9 +695,10 @@ async def _run_decision_extraction(
inline = report.by_source.get("inline_marker", 0)
readme = report.by_source.get("readme_mining", 0)
git_arch = report.by_source.get("git_archaeology", 0)
+ total_decisions = inline + readme + git_arch
progress.on_message(
"info",
- f"Decisions: {inline} inline · {readme} from docs · {git_arch} from git",
+ f"→ {total_decisions} decisions: {inline} inline · {readme} from docs · {git_arch} from git",
)
return report
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 2b9c517c8..e54de4b46 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -62,23 +62,71 @@ async def persist_pipeline_result(
pr = result.graph_builder.pagerank()
bc = result.graph_builder.betweenness_centrality()
cd = result.graph_builder.community_detection()
+ sc = result.graph_builder.symbol_communities()
+ ci = result.graph_builder.community_info()
+
+ # Entry point scores from execution flow analysis
+ ep_scores: dict[str, float] = {}
+ if result.execution_flow_report and getattr(result.execution_flow_report, "flows", None):
+ ep_scores = {
+ f.entry_point_id: f.entry_point_score
+ for f in result.execution_flow_report.flows
+ if hasattr(f, "entry_point_id") and hasattr(f, "entry_point_score")
+ }
nodes = []
- for node_path in graph.nodes:
- data = graph.nodes[node_path]
- nodes.append(
- {
- "node_id": node_path,
- "symbol_count": data.get("symbol_count", 0),
- "has_error": data.get("has_error", False),
- "is_test": data.get("is_test", False),
- "is_entry_point": data.get("is_entry_point", False),
- "language": data.get("language", "unknown"),
- "pagerank": pr.get(node_path, 0.0),
- "betweenness": bc.get(node_path, 0.0),
- "community_id": cd.get(node_path, 0),
- }
- )
+ for node_id in graph.nodes:
+ data = graph.nodes[node_id]
+ node_type = data.get("node_type", "file")
+
+ node_dict: dict[str, Any] = {
+ "node_id": node_id,
+ "node_type": node_type,
+ "language": data.get("language", "unknown"),
+ "symbol_count": data.get("symbol_count", 0),
+ "has_error": data.get("has_error", False),
+ "is_test": data.get("is_test", False),
+ "is_entry_point": data.get("is_entry_point", False),
+ "pagerank": pr.get(node_id, 0.0),
+ "betweenness": bc.get(node_id, 0.0),
+ "community_id": cd.get(node_id, 0),
+ }
+
+ # Community metadata
+ community_meta: dict[str, Any] = {}
+ if node_type == "file":
+ cid = cd.get(node_id, 0)
+ comm_info = ci.get(cid)
+ if comm_info:
+ community_meta = {
+ "label": comm_info.label,
+ "cohesion": comm_info.cohesion,
+ }
+ elif node_type == "symbol":
+ sym_cid = sc.get(node_id)
+ if sym_cid is not None:
+ community_meta = {"symbol_community_id": sym_cid}
+ if node_id in ep_scores:
+ community_meta["entry_point_score"] = ep_scores[node_id]
+ node_dict["community_meta_json"] = json.dumps(community_meta)
+
+ # Symbol-specific fields
+ if node_type == "symbol":
+ node_dict.update(
+ {
+ "kind": data.get("kind"),
+ "name": data.get("name"),
+ "qualified_name": data.get("qualified_name"),
+ "file_path": data.get("file_path"),
+ "start_line": data.get("start_line"),
+ "end_line": data.get("end_line"),
+ "visibility": data.get("visibility"),
+ "signature": data.get("signature"),
+ "parent_symbol_id": data.get("parent_name"),
+ }
+ )
+
+ nodes.append(node_dict)
if nodes:
await batch_upsert_graph_nodes(session, repo_id, nodes)
@@ -91,6 +139,7 @@ async def persist_pipeline_result(
"target_node_id": v,
"imported_names_json": json.dumps(data.get("imported_names", [])),
"edge_type": data.get("edge_type", "imports"),
+ "confidence": data.get("confidence", 1.0),
}
)
if edges:
diff --git a/packages/core/src/repowise/core/workspace/__init__.py b/packages/core/src/repowise/core/workspace/__init__.py
new file mode 100644
index 000000000..89f691062
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/__init__.py
@@ -0,0 +1,92 @@
+"""Workspace support — multi-repo detection, configuration, and analysis.
+
+Public API re-exports for the workspace package.
+"""
+
+from __future__ import annotations
+
+from .config import (
+ WORKSPACE_CONFIG_FILENAME,
+ WORKSPACE_DATA_DIR,
+ ContractConfig,
+ ManualContractLink,
+ RepoEntry,
+ WorkspaceConfig,
+ ensure_workspace_data_dir,
+ find_workspace_root,
+)
+from .scanner import (
+ DiscoveredRepo,
+ ScanResult,
+ scan_for_repos,
+)
+from .registry import (
+ RepoContext,
+ RepoRegistry,
+)
+from .update import (
+ RepoUpdateResult,
+ check_repo_staleness,
+ run_cross_repo_hooks,
+ update_single_repo_index,
+ update_workspace,
+)
+from .cross_repo import (
+ CROSS_REPO_EDGES_FILENAME,
+ CrossRepoCoChange,
+ CrossRepoOverlay,
+ CrossRepoPackageDep,
+ load_overlay,
+ run_cross_repo_analysis,
+ save_overlay,
+)
+from .contracts import (
+ CONTRACTS_FILENAME,
+ Contract,
+ ContractLink,
+ ContractStore,
+ load_contract_store,
+ run_contract_extraction,
+ save_contract_store,
+)
+
+__all__ = [
+ # Scanner
+ "DiscoveredRepo",
+ "ScanResult",
+ "scan_for_repos",
+ # Config
+ "WORKSPACE_CONFIG_FILENAME",
+ "WORKSPACE_DATA_DIR",
+ "ContractConfig",
+ "ManualContractLink",
+ "RepoEntry",
+ "WorkspaceConfig",
+ "ensure_workspace_data_dir",
+ "find_workspace_root",
+ # Registry
+ "RepoContext",
+ "RepoRegistry",
+ # Update
+ "RepoUpdateResult",
+ "check_repo_staleness",
+ "run_cross_repo_hooks",
+ "update_single_repo_index",
+ "update_workspace",
+ # Cross-repo intelligence
+ "CROSS_REPO_EDGES_FILENAME",
+ "CrossRepoCoChange",
+ "CrossRepoOverlay",
+ "CrossRepoPackageDep",
+ "load_overlay",
+ "run_cross_repo_analysis",
+ "save_overlay",
+ # Contracts (Phase 4)
+ "CONTRACTS_FILENAME",
+ "Contract",
+ "ContractLink",
+ "ContractStore",
+ "load_contract_store",
+ "run_contract_extraction",
+ "save_contract_store",
+]
diff --git a/packages/core/src/repowise/core/workspace/config.py b/packages/core/src/repowise/core/workspace/config.py
new file mode 100644
index 000000000..c01c61d50
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/config.py
@@ -0,0 +1,285 @@
+"""Workspace configuration — dataclass and YAML persistence.
+
+Pure data module with no CLI or DB dependencies. Handles the
+``.repowise-workspace.yaml`` file at the workspace root.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+WORKSPACE_CONFIG_FILENAME = ".repowise-workspace.yaml"
+WORKSPACE_DATA_DIR = ".repowise-workspace"
+CURRENT_VERSION = 1
+
+
+# ---------------------------------------------------------------------------
+# Data models
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class RepoEntry:
+ """One repository within a workspace."""
+
+ path: str # Relative to workspace root, POSIX-style forward slashes
+ alias: str # Unique short name
+ is_primary: bool = False
+ indexed_at: str | None = None # ISO 8601 timestamp of last index
+ last_commit_at_index: str | None = None # Git SHA at last index
+
+ def to_dict(self) -> dict[str, Any]:
+ d: dict[str, Any] = {"path": self.path, "alias": self.alias}
+ if self.is_primary:
+ d["is_primary"] = True
+ if self.indexed_at is not None:
+ d["indexed_at"] = self.indexed_at
+ if self.last_commit_at_index is not None:
+ d["last_commit_at_index"] = self.last_commit_at_index
+ return d
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> RepoEntry:
+ if "path" not in data or "alias" not in data:
+ raise ValueError(f"RepoEntry requires 'path' and 'alias', got: {sorted(data.keys())}")
+ return cls(
+ path=str(data["path"]),
+ alias=str(data["alias"]),
+ is_primary=bool(data.get("is_primary", False)),
+ indexed_at=data.get("indexed_at"),
+ last_commit_at_index=data.get("last_commit_at_index"),
+ )
+
+
+@dataclass
+class ManualContractLink:
+ """A manually declared cross-repo contract link in the workspace config."""
+
+ from_repo: str
+ to_repo: str
+ contract_type: str # "http" | "grpc" | "topic"
+ contract_id: str # normalized contract ID
+ from_role: str = "consumer" # the from_repo's role
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "from_repo": self.from_repo,
+ "to_repo": self.to_repo,
+ "contract_type": self.contract_type,
+ "contract_id": self.contract_id,
+ "from_role": self.from_role,
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> ManualContractLink:
+ return cls(
+ from_repo=str(data["from_repo"]),
+ to_repo=str(data["to_repo"]),
+ contract_type=str(data["contract_type"]),
+ contract_id=str(data["contract_id"]),
+ from_role=str(data.get("from_role", "consumer")),
+ )
+
+
+@dataclass
+class ContractConfig:
+ """Configuration for contract detection (Phase 4)."""
+
+ detect_http: bool = True
+ detect_grpc: bool = True
+ detect_topics: bool = True
+ manual_links: list[ManualContractLink] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, Any]:
+ d: dict[str, Any] = {
+ "detect_http": self.detect_http,
+ "detect_grpc": self.detect_grpc,
+ "detect_topics": self.detect_topics,
+ }
+ if self.manual_links:
+ d["manual_links"] = [ml.to_dict() for ml in self.manual_links]
+ return d
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> ContractConfig:
+ manual = [
+ ManualContractLink.from_dict(ml)
+ for ml in data.get("manual_links", [])
+ ]
+ return cls(
+ detect_http=bool(data.get("detect_http", True)),
+ detect_grpc=bool(data.get("detect_grpc", True)),
+ detect_topics=bool(data.get("detect_topics", True)),
+ manual_links=manual,
+ )
+
+
+@dataclass
+class WorkspaceConfig:
+ """Workspace-level configuration stored in ``.repowise-workspace.yaml``."""
+
+ version: int = CURRENT_VERSION
+ repos: list[RepoEntry] = field(default_factory=list)
+ default_repo: str | None = None
+ contracts: ContractConfig = field(default_factory=ContractConfig)
+
+ # ------------------------------------------------------------------
+ # Serialization
+ # ------------------------------------------------------------------
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert to a plain dict suitable for ``yaml.dump``."""
+ d: dict[str, Any] = {
+ "version": self.version,
+ "default_repo": self.default_repo,
+ "repos": [r.to_dict() for r in self.repos],
+ }
+ # Only include contracts section if non-default
+ contracts_d = self.contracts.to_dict()
+ if self.contracts.manual_links or not all([
+ self.contracts.detect_http,
+ self.contracts.detect_grpc,
+ self.contracts.detect_topics,
+ ]):
+ d["contracts"] = contracts_d
+ return d
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> WorkspaceConfig:
+ """Construct from a parsed YAML dict."""
+ version = int(data.get("version", CURRENT_VERSION))
+ default_repo = data.get("default_repo")
+
+ repos: list[RepoEntry] = []
+ for entry in data.get("repos", []):
+ repos.append(RepoEntry.from_dict(entry))
+
+ contracts = ContractConfig.from_dict(data.get("contracts", {}))
+
+ return cls(
+ version=version,
+ repos=repos,
+ default_repo=str(default_repo) if default_repo else None,
+ contracts=contracts,
+ )
+
+ def save(self, workspace_root: Path) -> Path:
+ """Write config to ``workspace_root / .repowise-workspace.yaml``.
+
+ Returns the path to the written file.
+ """
+ config_path = workspace_root / WORKSPACE_CONFIG_FILENAME
+ content = yaml.dump(
+ self.to_dict(),
+ default_flow_style=False,
+ sort_keys=False,
+ allow_unicode=True,
+ )
+ config_path.write_text(content, encoding="utf-8")
+ return config_path
+
+ @classmethod
+ def load(cls, workspace_root: Path) -> WorkspaceConfig:
+ """Load from ``workspace_root / .repowise-workspace.yaml``.
+
+ Raises :class:`FileNotFoundError` if the config file does not exist.
+ """
+ config_path = workspace_root / WORKSPACE_CONFIG_FILENAME
+ if not config_path.is_file():
+ raise FileNotFoundError(f"Workspace config not found: {config_path}")
+ text = config_path.read_text(encoding="utf-8")
+ data = yaml.safe_load(text) or {}
+ return cls.from_dict(data)
+
+ # ------------------------------------------------------------------
+ # Query helpers
+ # ------------------------------------------------------------------
+
+ def get_repo(self, alias: str) -> RepoEntry | None:
+ """Find a repo by alias. Returns ``None`` if not found."""
+ for repo in self.repos:
+ if repo.alias == alias:
+ return repo
+ return None
+
+ def get_primary(self) -> RepoEntry | None:
+ """Return the primary/default repo entry, or ``None``."""
+ if self.default_repo:
+ found = self.get_repo(self.default_repo)
+ if found:
+ return found
+ # Fallback: first repo marked as primary
+ for repo in self.repos:
+ if repo.is_primary:
+ return repo
+ # Fallback: first repo
+ return self.repos[0] if self.repos else None
+
+ def repo_paths(self, workspace_root: Path) -> list[Path]:
+ """Return absolute resolved paths for all repos."""
+ root = Path(workspace_root).resolve()
+ return [(root / entry.path).resolve() for entry in self.repos]
+
+ def repo_aliases(self) -> list[str]:
+ """Return all repo aliases in order."""
+ return [r.alias for r in self.repos]
+
+ # ------------------------------------------------------------------
+ # Mutation helpers
+ # ------------------------------------------------------------------
+
+ def add_repo(self, entry: RepoEntry) -> None:
+ """Add a repo entry. Raises ``ValueError`` if alias already exists."""
+ if self.get_repo(entry.alias) is not None:
+ raise ValueError(f"Repo alias already exists: {entry.alias}")
+ self.repos.append(entry)
+
+ def remove_repo(self, alias: str) -> RepoEntry | None:
+ """Remove a repo by alias. Returns the removed entry or ``None``."""
+ for i, repo in enumerate(self.repos):
+ if repo.alias == alias:
+ removed = self.repos.pop(i)
+ if self.default_repo == alias:
+ self.default_repo = self.repos[0].alias if self.repos else None
+ return removed
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Workspace root detection
+# ---------------------------------------------------------------------------
+
+
+def find_workspace_root(start: Path | None = None) -> Path | None:
+ """Walk up from *start* (default: cwd) looking for ``.repowise-workspace.yaml``.
+
+ Returns the directory containing the file, or ``None`` if not found.
+ Stops at the filesystem root.
+ """
+ current = (start or Path.cwd()).resolve()
+ while True:
+ if (current / WORKSPACE_CONFIG_FILENAME).is_file():
+ return current
+ parent = current.parent
+ if parent == current:
+ return None # reached filesystem root
+ current = parent
+
+
+def ensure_workspace_data_dir(workspace_root: Path) -> Path:
+ """Create the ``.repowise-workspace/`` data directory if it doesn't exist.
+
+ This directory holds workspace-level artifacts (overlay graph, cross-repo
+ analysis results). Distinct from the config file.
+ """
+ data_dir = workspace_root / WORKSPACE_DATA_DIR
+ data_dir.mkdir(parents=True, exist_ok=True)
+ return data_dir
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.py
new file mode 100644
index 000000000..a1a1dd754
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/contracts.py
@@ -0,0 +1,463 @@
+"""Contract extraction — HTTP routes, gRPC services, message topics.
+
+Write path: runs during ``repowise update --workspace``.
+Results read by ``CrossRepoEnricher`` in the MCP server (read path).
+
+Contracts are persisted as ``.repowise-workspace/contracts.json`` — separate
+from ``cross_repo_edges.json`` so Phase 3 and Phase 4 fail independently.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+from collections import defaultdict
+from dataclasses import asdict, dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from repowise.core.workspace.config import (
+ WORKSPACE_DATA_DIR,
+ WorkspaceConfig,
+ ensure_workspace_data_dir,
+)
+
+_log = logging.getLogger("repowise.workspace.contracts")
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+CONTRACTS_FILENAME = "contracts.json"
+
+
+# ---------------------------------------------------------------------------
+# Data models
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class Contract:
+ """A single API contract extracted from source code."""
+
+ repo: str # repo alias
+ contract_id: str # e.g. "http::GET::/api/users/{param}"
+ contract_type: str # "http" | "grpc" | "topic"
+ role: str # "provider" | "consumer"
+ file_path: str # relative to repo root
+ symbol_name: str # handler name, service.method, etc.
+ confidence: float # 0.7–0.9 based on extraction strategy
+ service: str | None = None # service boundary path (monorepo)
+ meta: dict = field(default_factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ d = asdict(self)
+ if d["service"] is None:
+ del d["service"]
+ if not d["meta"]:
+ del d["meta"]
+ return d
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> Contract:
+ return cls(
+ repo=data["repo"],
+ contract_id=data["contract_id"],
+ contract_type=data["contract_type"],
+ role=data["role"],
+ file_path=data["file_path"],
+ symbol_name=data["symbol_name"],
+ confidence=data["confidence"],
+ service=data.get("service"),
+ meta=data.get("meta", {}),
+ )
+
+
+@dataclass
+class ContractLink:
+ """A matched provider↔consumer pair across repos."""
+
+ contract_id: str
+ contract_type: str # "http" | "grpc" | "topic"
+ match_type: str # always "exact" in Phase 4
+ confidence: float
+ provider_repo: str
+ provider_file: str
+ provider_symbol: str
+ provider_service: str | None
+ consumer_repo: str
+ consumer_file: str
+ consumer_symbol: str
+ consumer_service: str | None
+
+ def to_dict(self) -> dict[str, Any]:
+ d = asdict(self)
+ if d["provider_service"] is None:
+ del d["provider_service"]
+ if d["consumer_service"] is None:
+ del d["consumer_service"]
+ return d
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> ContractLink:
+ return cls(
+ contract_id=data["contract_id"],
+ contract_type=data["contract_type"],
+ match_type=data.get("match_type", "exact"),
+ confidence=data.get("confidence", 1.0),
+ provider_repo=data["provider_repo"],
+ provider_file=data["provider_file"],
+ provider_symbol=data.get("provider_symbol", ""),
+ provider_service=data.get("provider_service"),
+ consumer_repo=data["consumer_repo"],
+ consumer_file=data["consumer_file"],
+ consumer_symbol=data.get("consumer_symbol", ""),
+ consumer_service=data.get("consumer_service"),
+ )
+
+
+@dataclass
+class ContractStore:
+ """Top-level container for contract data, serialized to JSON."""
+
+ version: int = 1
+ generated_at: str = ""
+ contracts: list[Contract] = field(default_factory=list)
+ contract_links: list[ContractLink] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "version": self.version,
+ "generated_at": self.generated_at,
+ "contracts": [c.to_dict() for c in self.contracts],
+ "contract_links": [lk.to_dict() for lk in self.contract_links],
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> ContractStore:
+ return cls(
+ version=data.get("version", 1),
+ generated_at=data.get("generated_at", ""),
+ contracts=[Contract.from_dict(c) for c in data.get("contracts", [])],
+ contract_links=[
+ ContractLink.from_dict(lk) for lk in data.get("contract_links", [])
+ ],
+ )
+
+
+# ---------------------------------------------------------------------------
+# Contract ID normalization
+# ---------------------------------------------------------------------------
+
+
+def normalize_contract_id(contract_id: str) -> str:
+ """Normalize a contract ID for matching.
+
+ - ``http::GET::/Api/Users/`` → ``http::GET::/api/users``
+ - ``grpc::PKG.Service/Method`` → ``grpc::pkg.service/Method``
+ - ``topic::Orders`` → ``topic::orders``
+ """
+ parts = contract_id.split("::", 2)
+ if len(parts) < 2:
+ return contract_id.lower()
+
+ ctype = parts[0].lower()
+
+ if ctype == "http" and len(parts) == 3:
+ method = parts[1].upper()
+ path = parts[2].lower().rstrip("/")
+ if not path:
+ path = "/"
+ return f"http::{method}::{path}"
+
+ if ctype == "grpc" and len(parts) == 2:
+ value = parts[1]
+ # Split package.Service/Method — lowercase package+service, keep method case
+ slash_idx = value.rfind("/")
+ if slash_idx >= 0:
+ prefix = value[:slash_idx].lower()
+ method = value[slash_idx:] # includes the /
+ return f"grpc::{prefix}{method}"
+ return f"grpc::{value.lower()}"
+
+ if ctype == "topic" and len(parts) == 2:
+ return f"topic::{parts[1].lower()}"
+
+ return contract_id.lower()
+
+
+# ---------------------------------------------------------------------------
+# Matching engine
+# ---------------------------------------------------------------------------
+
+
+def _find_matching_keys(
+ consumer_id: str,
+ provider_index: dict[str, list[Contract]],
+) -> list[str]:
+ """Find provider index keys that match *consumer_id*."""
+ normalized = normalize_contract_id(consumer_id)
+
+ if normalized in provider_index:
+ return [normalized]
+
+ # HTTP wildcard: consumer http::*::/path matches any method on that path
+ if normalized.startswith("http::*::"):
+ path_suffix = normalized[len("http::*::"):]
+ return [
+ k for k in provider_index
+ if k.startswith("http::") and k.endswith(f"::{path_suffix}")
+ ]
+
+ # HTTP: check for wildcard providers (http::*::/path from Go HandleFunc)
+ if normalized.startswith("http::") and not normalized.startswith("http::*::"):
+ parts = normalized.split("::", 2)
+ if len(parts) == 3:
+ wildcard_key = f"http::*::{parts[2]}"
+ if wildcard_key in provider_index:
+ return [wildcard_key]
+
+ # gRPC wildcard: grpc::service/* matches grpc::service/Method
+ if normalized.endswith("/*"):
+ prefix = normalized[:-1] # "grpc::service/"
+ return [k for k in provider_index if k.startswith(prefix)]
+
+ return []
+
+
+def match_contracts(contracts: list[Contract]) -> list[ContractLink]:
+ """Match providers to consumers using exact normalized ID comparison.
+
+ - HTTP wildcard: ``http::*::/path`` matches any method on that path.
+ - gRPC wildcard: ``grpc::Service/*`` matches any method on that service.
+ - Same-repo same-service calls are filtered out.
+ """
+ provider_index: dict[str, list[Contract]] = defaultdict(list)
+ consumers: list[Contract] = []
+
+ for c in contracts:
+ if c.role == "provider":
+ key = normalize_contract_id(c.contract_id)
+ provider_index[key].append(c)
+ else:
+ consumers.append(c)
+
+ links: list[ContractLink] = []
+ seen: set[tuple[str, str, str, str, str]] = set()
+
+ for consumer in consumers:
+ matching_keys = _find_matching_keys(consumer.contract_id, provider_index)
+
+ for key in matching_keys:
+ for provider in provider_index[key]:
+ # Same-repo same-service filter: skip internal calls
+ if provider.repo == consumer.repo:
+ if (
+ provider.service == consumer.service # includes both-None case
+ ):
+ continue
+
+ dedup_key = (
+ normalize_contract_id(consumer.contract_id),
+ consumer.repo,
+ consumer.file_path,
+ provider.repo,
+ provider.file_path,
+ )
+ if dedup_key in seen:
+ continue
+ seen.add(dedup_key)
+
+ links.append(ContractLink(
+ contract_id=consumer.contract_id,
+ contract_type=consumer.contract_type,
+ match_type="exact",
+ confidence=min(provider.confidence, consumer.confidence),
+ provider_repo=provider.repo,
+ provider_file=provider.file_path,
+ provider_symbol=provider.symbol_name,
+ provider_service=provider.service,
+ consumer_repo=consumer.repo,
+ consumer_file=consumer.file_path,
+ consumer_symbol=consumer.symbol_name,
+ consumer_service=consumer.service,
+ ))
+
+ return links
+
+
+# ---------------------------------------------------------------------------
+# Manual links
+# ---------------------------------------------------------------------------
+
+
+def _build_manual_links(
+ manual_links: list, # list[ManualContractLink]
+) -> list[ContractLink]:
+ """Convert manual links from workspace config to ContractLink objects."""
+ result: list[ContractLink] = []
+ for ml in manual_links:
+ if ml.from_role == "consumer":
+ result.append(ContractLink(
+ contract_id=ml.contract_id,
+ contract_type=ml.contract_type,
+ match_type="manual",
+ confidence=1.0,
+ provider_repo=ml.to_repo,
+ provider_file="",
+ provider_symbol="",
+ provider_service=None,
+ consumer_repo=ml.from_repo,
+ consumer_file="",
+ consumer_symbol="",
+ consumer_service=None,
+ ))
+ else:
+ result.append(ContractLink(
+ contract_id=ml.contract_id,
+ contract_type=ml.contract_type,
+ match_type="manual",
+ confidence=1.0,
+ provider_repo=ml.from_repo,
+ provider_file="",
+ provider_symbol="",
+ provider_service=None,
+ consumer_repo=ml.to_repo,
+ consumer_file="",
+ consumer_symbol="",
+ consumer_service=None,
+ ))
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Persistence
+# ---------------------------------------------------------------------------
+
+
+def save_contract_store(store: ContractStore, workspace_root: Path) -> Path:
+ """Write contract store to ``.repowise-workspace/contracts.json``."""
+ data_dir = ensure_workspace_data_dir(workspace_root)
+ out_path = data_dir / CONTRACTS_FILENAME
+ out_path.write_text(
+ json.dumps(store.to_dict(), indent=2, ensure_ascii=False),
+ encoding="utf-8",
+ )
+ return out_path
+
+
+def load_contract_store(workspace_root: Path) -> ContractStore | None:
+ """Load contract store from ``.repowise-workspace/contracts.json``.
+
+ Returns ``None`` if the file is missing or unparseable.
+ """
+ path = workspace_root / WORKSPACE_DATA_DIR / CONTRACTS_FILENAME
+ if not path.is_file():
+ return None
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ return ContractStore.from_dict(data)
+ except Exception:
+ _log.warning("Failed to load contract store from %s", path, exc_info=True)
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Orchestrator
+# ---------------------------------------------------------------------------
+
+
+async def run_contract_extraction(
+ ws_config: WorkspaceConfig,
+ workspace_root: Path,
+ changed_repos: list[str],
+) -> ContractStore:
+ """Full contract extraction pipeline.
+
+ Called from :func:`run_cross_repo_hooks` during ``repowise update --workspace``.
+
+ 1. For each repo: scan files with each extractor (via ``to_thread``)
+ 2. Detect service boundaries per repo
+ 3. Assign service to each contract
+ 4. Run matching engine
+ 5. Merge manual links from ``WorkspaceConfig``
+ 6. Save ``contracts.json``
+ """
+ from .extractors import (
+ GrpcExtractor,
+ HttpExtractor,
+ TopicExtractor,
+ assign_service,
+ detect_service_boundaries,
+ )
+
+ contract_config = ws_config.contracts
+
+ # Build repo_paths — only include repos that have been indexed
+ # (have a .repowise/ directory). Non-indexed repos must not participate
+ # in contract extraction.
+ repo_paths: dict[str, Path] = {}
+ for entry in ws_config.repos:
+ resolved = (workspace_root / entry.path).resolve()
+ if resolved.is_dir() and (resolved / ".repowise").is_dir():
+ repo_paths[entry.alias] = resolved
+
+ if len(repo_paths) < 2:
+ return ContractStore()
+
+ # Per-repo extraction
+ async def _extract_one_repo(alias: str, repo_path: Path) -> list[Contract]:
+ contracts: list[Contract] = []
+
+ # Service boundary detection
+ boundaries = await asyncio.to_thread(detect_service_boundaries, repo_path)
+
+ # Run enabled extractors
+ extractors = []
+ if contract_config.detect_http:
+ extractors.append(HttpExtractor())
+ if contract_config.detect_grpc:
+ extractors.append(GrpcExtractor())
+ if contract_config.detect_topics:
+ extractors.append(TopicExtractor())
+
+ for extractor in extractors:
+ found = await asyncio.to_thread(extractor.extract, repo_path, alias)
+ for c in found:
+ c.service = assign_service(c.file_path, boundaries)
+ contracts.extend(found)
+
+ return contracts
+
+ results = await asyncio.gather(*[
+ _extract_one_repo(alias, path) for alias, path in repo_paths.items()
+ ])
+ all_contracts: list[Contract] = []
+ for repo_contracts in results:
+ all_contracts.extend(repo_contracts)
+
+ # Match contracts
+ links = match_contracts(all_contracts)
+
+ # Merge manual links
+ if contract_config.manual_links:
+ links.extend(_build_manual_links(contract_config.manual_links))
+
+ store = ContractStore(
+ version=1,
+ generated_at=datetime.now(timezone.utc).isoformat(),
+ contracts=all_contracts,
+ contract_links=links,
+ )
+
+ out_path = save_contract_store(store, workspace_root)
+ _log.info(
+ "Contract extraction complete: %d contracts, %d links → %s",
+ len(all_contracts),
+ len(links),
+ out_path,
+ )
+
+ return store
diff --git a/packages/core/src/repowise/core/workspace/cross_repo.py b/packages/core/src/repowise/core/workspace/cross_repo.py
new file mode 100644
index 000000000..aed0915f0
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/cross_repo.py
@@ -0,0 +1,655 @@
+"""Cross-repo intelligence — co-change detection, manifest scanning, overlay persistence.
+
+Runs during ``repowise update --workspace`` (write path). The resulting JSON
+is loaded by :class:`CrossRepoEnricher` in the MCP server (read path).
+
+No new DB tables — all cross-repo data lives in
+``.repowise-workspace/cross_repo_edges.json``.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import math
+import subprocess
+import time
+from collections import defaultdict
+from dataclasses import asdict, dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from .config import WorkspaceConfig, ensure_workspace_data_dir
+
+_log = logging.getLogger("repowise.workspace.cross_repo")
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+CROSS_REPO_EDGES_FILENAME = "cross_repo_edges.json"
+
+# Same decay constant as intra-repo co-change (git_indexer.py)
+_CO_CHANGE_DECAY_TAU: float = 180.0
+
+_DEFAULT_TIME_WINDOW_HOURS: int = 24
+_DEFAULT_COMMIT_LIMIT: int = 500
+_MIN_CROSS_REPO_SCORE: float = 1.0
+_MAX_EDGES: int = 200
+
+
+# ---------------------------------------------------------------------------
+# Data structures
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class CrossRepoCoChange:
+ source_repo: str
+ source_file: str
+ target_repo: str
+ target_file: str
+ strength: float # decay-weighted co-change score
+ frequency: int # raw count of temporally-correlated commit pairs
+ last_date: str # ISO date of most recent co-change
+
+
+@dataclass
+class CrossRepoPackageDep:
+ source_repo: str
+ target_repo: str
+ source_manifest: str
+ kind: str # npm_local_path, pip_path, cargo_path, go_replace
+
+
+@dataclass
+class CrossRepoOverlay:
+ version: int = 1
+ generated_at: str = ""
+ co_changes: list[CrossRepoCoChange] = field(default_factory=list)
+ package_deps: list[CrossRepoPackageDep] = field(default_factory=list)
+ repo_summaries: dict[str, dict] = field(default_factory=dict)
+
+ def to_dict(self) -> dict:
+ return {
+ "version": self.version,
+ "generated_at": self.generated_at,
+ "co_changes": [asdict(c) for c in self.co_changes],
+ "package_deps": [asdict(d) for d in self.package_deps],
+ "repo_summaries": self.repo_summaries,
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict) -> CrossRepoOverlay:
+ return cls(
+ version=data.get("version", 1),
+ generated_at=data.get("generated_at", ""),
+ co_changes=[
+ CrossRepoCoChange(**c) for c in data.get("co_changes", [])
+ ],
+ package_deps=[
+ CrossRepoPackageDep(**d) for d in data.get("package_deps", [])
+ ],
+ repo_summaries=data.get("repo_summaries", {}),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Git log mining
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class _GitCommit:
+ author_email: str
+ timestamp: int # Unix epoch
+ files: list[str] = field(default_factory=list)
+
+
+def _parse_git_log(
+ repo_path: Path,
+ commit_limit: int = _DEFAULT_COMMIT_LIMIT,
+) -> list[_GitCommit]:
+ """Run ``git log`` and parse into structured commit records.
+
+ Returns list of commits with author email, timestamp, and changed files.
+ Uses subprocess.run — same pattern as ``update.py:get_head_commit()``.
+ """
+ try:
+ result = subprocess.run(
+ [
+ "git", "log",
+ f"-{commit_limit}",
+ "--format=%x00%ae|%ct",
+ "--name-only",
+ "--no-merges",
+ ],
+ cwd=str(repo_path),
+ capture_output=True,
+ text=True,
+ timeout=60,
+ encoding="utf-8",
+ )
+ if result.returncode != 0:
+ _log.debug("git log failed for %s: %s", repo_path, result.stderr)
+ return []
+ except Exception:
+ _log.debug("git log subprocess failed for %s", repo_path, exc_info=True)
+ return []
+
+ commits: list[_GitCommit] = []
+ current: _GitCommit | None = None
+
+ for line in result.stdout.splitlines():
+ if line.startswith("\x00") or line == "\x00":
+ # Commit boundary — flush previous, parse header
+ if current is not None and current.files:
+ commits.append(current)
+
+ header = line.lstrip("\x00").strip()
+ parts = header.split("|", 1)
+ if len(parts) == 2:
+ email = parts[0].strip()
+ try:
+ ts = int(parts[1].strip())
+ except (ValueError, TypeError):
+ ts = 0
+ current = _GitCommit(author_email=email, timestamp=ts)
+ else:
+ current = None
+ elif current is not None:
+ path = line.strip()
+ if path:
+ current.files.append(path)
+
+ # Flush last commit
+ if current is not None and current.files:
+ commits.append(current)
+
+ return commits
+
+
+# ---------------------------------------------------------------------------
+# Cross-repo co-change detection
+# ---------------------------------------------------------------------------
+
+
+def detect_cross_repo_co_changes(
+ repo_paths: dict[str, Path],
+ *,
+ time_window_hours: int = _DEFAULT_TIME_WINDOW_HOURS,
+ commit_limit: int = _DEFAULT_COMMIT_LIMIT,
+ min_score: float = _MIN_CROSS_REPO_SCORE,
+) -> list[CrossRepoCoChange]:
+ """Find files across repos committed by same author within *time_window*.
+
+ Algorithm:
+ 1. Parse git logs for all repos
+ 2. Group commits by author email
+ 3. For same author, find commit pairs from different repos within window
+ 4. All files from correlated commits are cross-repo co-change partners
+ 5. Apply temporal decay (same as intra-repo)
+ 6. Filter by min_score, cap at MAX_EDGES
+ """
+ if len(repo_paths) < 2:
+ return []
+
+ now_ts = time.time()
+ window_seconds = time_window_hours * 3600
+
+ # Step 1: Parse git logs for all repos
+ repo_commits: dict[str, list[_GitCommit]] = {}
+ for alias, path in repo_paths.items():
+ commits = _parse_git_log(path, commit_limit)
+ if commits:
+ repo_commits[alias] = commits
+
+ if len(repo_commits) < 2:
+ return []
+
+ # Step 2: Group all commits by author, tagged with repo alias
+ author_commits: dict[str, list[tuple[str, _GitCommit]]] = defaultdict(list)
+ for alias, commits in repo_commits.items():
+ for c in commits:
+ author_commits[c.author_email].append((alias, c))
+
+ # Step 3: For each author, find temporally-correlated cross-repo pairs
+ # Accumulate (src_repo, src_file, tgt_repo, tgt_file) -> (score, frequency, last_ts)
+ pair_scores: dict[tuple[str, str, str, str], float] = defaultdict(float)
+ pair_freq: dict[tuple[str, str, str, str], int] = defaultdict(int)
+ pair_last_ts: dict[tuple[str, str, str, str], int] = {}
+
+ for author, tagged_commits in author_commits.items():
+ if len(tagged_commits) < 2:
+ continue
+
+ # Sort by timestamp
+ tagged_commits.sort(key=lambda x: x[1].timestamp)
+
+ # Sliding window: for each commit, look ahead for commits from
+ # different repos within the time window
+ for i in range(len(tagged_commits)):
+ repo_a, commit_a = tagged_commits[i]
+ for j in range(i + 1, len(tagged_commits)):
+ repo_b, commit_b = tagged_commits[j]
+
+ time_diff = commit_b.timestamp - commit_a.timestamp
+ if time_diff > window_seconds:
+ break # Past window — no more matches for commit_a
+
+ if repo_a == repo_b:
+ continue # Same repo — skip
+
+ # Cross-repo match found
+ age_days = max((now_ts - commit_b.timestamp) / 86400.0, 0.0)
+ weight = math.exp(-age_days / _CO_CHANGE_DECAY_TAU)
+
+ # Create file pairs (limit to avoid O(N*M) explosion on huge commits)
+ files_a = commit_a.files[:20]
+ files_b = commit_b.files[:20]
+
+ for fa in files_a:
+ for fb in files_b:
+ # Normalize key ordering to avoid symmetric duplicates
+ if (repo_a, fa) > (repo_b, fb):
+ key = (repo_b, fb, repo_a, fa)
+ else:
+ key = (repo_a, fa, repo_b, fb)
+ pair_scores[key] += weight
+ pair_freq[key] += 1
+ ts = max(commit_a.timestamp, commit_b.timestamp)
+ if key not in pair_last_ts or ts > pair_last_ts[key]:
+ pair_last_ts[key] = ts
+
+ # Step 4: Filter and build results
+ results: list[CrossRepoCoChange] = []
+ for (src_repo, src_file, tgt_repo, tgt_file), score in pair_scores.items():
+ if score < min_score:
+ continue
+ freq = pair_freq[(src_repo, src_file, tgt_repo, tgt_file)]
+ last_ts = pair_last_ts.get((src_repo, src_file, tgt_repo, tgt_file), 0)
+ last_date = (
+ datetime.fromtimestamp(last_ts, tz=timezone.utc).strftime("%Y-%m-%d")
+ if last_ts > 0
+ else ""
+ )
+ results.append(CrossRepoCoChange(
+ source_repo=src_repo,
+ source_file=src_file,
+ target_repo=tgt_repo,
+ target_file=tgt_file,
+ strength=round(score, 2),
+ frequency=freq,
+ last_date=last_date,
+ ))
+
+ # Sort by strength descending and cap
+ results.sort(key=lambda x: -x.strength)
+ return results[:_MAX_EDGES]
+
+
+# ---------------------------------------------------------------------------
+# Package / manifest dependency detection
+# ---------------------------------------------------------------------------
+
+
+def _resolve_target_repo(
+ relative_ref: str,
+ source_repo_path: Path,
+ repo_paths: dict[str, Path],
+) -> str | None:
+ """Resolve a relative path reference to a repo alias, or None."""
+ try:
+ target_abs = (source_repo_path / relative_ref).resolve()
+ for alias, repo_path in repo_paths.items():
+ if target_abs == repo_path.resolve() or str(target_abs).startswith(
+ str(repo_path.resolve())
+ ):
+ return alias
+ except Exception:
+ pass
+ return None
+
+
+def _scan_package_json(
+ repo_path: Path,
+ repo_paths: dict[str, Path],
+ alias: str,
+) -> list[CrossRepoPackageDep]:
+ """Scan package.json for local file: references to sibling repos."""
+ results: list[CrossRepoPackageDep] = []
+ pkg_json = repo_path / "package.json"
+ if not pkg_json.is_file():
+ return results
+
+ try:
+ data = json.loads(pkg_json.read_text(encoding="utf-8"))
+ except Exception:
+ return results
+
+ for dep_key in ("dependencies", "devDependencies", "peerDependencies"):
+ deps = data.get(dep_key, {})
+ if not isinstance(deps, dict):
+ continue
+ for _name, version in deps.items():
+ if isinstance(version, str) and version.startswith("file:"):
+ rel_path = version[5:] # strip "file:"
+ target = _resolve_target_repo(rel_path, repo_path, repo_paths)
+ if target and target != alias:
+ results.append(CrossRepoPackageDep(
+ source_repo=alias,
+ target_repo=target,
+ source_manifest="package.json",
+ kind="npm_local_path",
+ ))
+
+ # Check workspaces field
+ workspaces = data.get("workspaces", [])
+ if isinstance(workspaces, dict):
+ workspaces = workspaces.get("packages", [])
+ # Workspaces are globs — we just check if they point to sibling repos
+ for ws in workspaces if isinstance(workspaces, list) else []:
+ if isinstance(ws, str) and ".." in ws:
+ target = _resolve_target_repo(ws.rstrip("/*"), repo_path, repo_paths)
+ if target and target != alias:
+ results.append(CrossRepoPackageDep(
+ source_repo=alias,
+ target_repo=target,
+ source_manifest="package.json",
+ kind="npm_workspace",
+ ))
+
+ return results
+
+
+def _scan_pyproject_toml(
+ repo_path: Path,
+ repo_paths: dict[str, Path],
+ alias: str,
+) -> list[CrossRepoPackageDep]:
+ """Scan pyproject.toml for path dependencies."""
+ results: list[CrossRepoPackageDep] = []
+ toml_path = repo_path / "pyproject.toml"
+ if not toml_path.is_file():
+ return results
+
+ try:
+ # Use tomllib (Python 3.11+) or tomli
+ try:
+ import tomllib
+ except ImportError:
+ import tomli as tomllib # type: ignore[no-redef]
+ with open(toml_path, "rb") as f:
+ data = tomllib.load(f)
+ except Exception:
+ return results
+
+ # Poetry path dependencies
+ poetry_deps = (
+ data.get("tool", {}).get("poetry", {}).get("dependencies", {})
+ )
+ for _name, spec in poetry_deps.items() if isinstance(poetry_deps, dict) else []:
+ if isinstance(spec, dict) and "path" in spec:
+ target = _resolve_target_repo(spec["path"], repo_path, repo_paths)
+ if target and target != alias:
+ results.append(CrossRepoPackageDep(
+ source_repo=alias,
+ target_repo=target,
+ source_manifest="pyproject.toml",
+ kind="pip_path",
+ ))
+
+ # PEP 621 dependencies with path (uncommon but possible via tool configs)
+ for group_key in ("dependencies", "optional-dependencies"):
+ group = data.get("project", {}).get(group_key, {})
+ if isinstance(group, dict):
+ for _name, spec in group.items():
+ if isinstance(spec, dict) and "path" in spec:
+ target = _resolve_target_repo(spec["path"], repo_path, repo_paths)
+ if target and target != alias:
+ results.append(CrossRepoPackageDep(
+ source_repo=alias,
+ target_repo=target,
+ source_manifest="pyproject.toml",
+ kind="pip_path",
+ ))
+
+ return results
+
+
+def _scan_cargo_toml(
+ repo_path: Path,
+ repo_paths: dict[str, Path],
+ alias: str,
+) -> list[CrossRepoPackageDep]:
+ """Scan Cargo.toml for path dependencies."""
+ results: list[CrossRepoPackageDep] = []
+ cargo_path = repo_path / "Cargo.toml"
+ if not cargo_path.is_file():
+ return results
+
+ try:
+ try:
+ import tomllib
+ except ImportError:
+ import tomli as tomllib # type: ignore[no-redef]
+ with open(cargo_path, "rb") as f:
+ data = tomllib.load(f)
+ except Exception:
+ return results
+
+ for section in ("dependencies", "dev-dependencies", "build-dependencies"):
+ deps = data.get(section, {})
+ for _name, spec in deps.items():
+ if isinstance(spec, dict) and "path" in spec:
+ target = _resolve_target_repo(spec["path"], repo_path, repo_paths)
+ if target and target != alias:
+ results.append(CrossRepoPackageDep(
+ source_repo=alias,
+ target_repo=target,
+ source_manifest="Cargo.toml",
+ kind="cargo_path",
+ ))
+
+ return results
+
+
+def _scan_go_mod(
+ repo_path: Path,
+ repo_paths: dict[str, Path],
+ alias: str,
+) -> list[CrossRepoPackageDep]:
+ """Scan go.mod for replace directives pointing to sibling repos."""
+ results: list[CrossRepoPackageDep] = []
+ go_mod = repo_path / "go.mod"
+ if not go_mod.is_file():
+ return results
+
+ try:
+ content = go_mod.read_text(encoding="utf-8")
+ except Exception:
+ return results
+
+ # Parse "replace" directives: `replace foo => ../sibling`
+ in_replace_block = False
+ for line in content.splitlines():
+ stripped = line.strip()
+ if stripped.startswith("replace ("):
+ in_replace_block = True
+ continue
+ if in_replace_block and stripped == ")":
+ in_replace_block = False
+ continue
+
+ # Single-line replace or inside block
+ if stripped.startswith("replace ") or in_replace_block:
+ parts = stripped.replace("replace ", "").split("=>")
+ if len(parts) == 2:
+ target_path = parts[1].strip().split()[0] # first token after =>
+ if target_path.startswith("..") or target_path.startswith("./"):
+ target = _resolve_target_repo(target_path, repo_path, repo_paths)
+ if target and target != alias:
+ results.append(CrossRepoPackageDep(
+ source_repo=alias,
+ target_repo=target,
+ source_manifest="go.mod",
+ kind="go_replace",
+ ))
+
+ return results
+
+
+def detect_package_dependencies(
+ repo_paths: dict[str, Path],
+) -> list[CrossRepoPackageDep]:
+ """Scan all repos for manifest-based cross-repo dependencies."""
+ results: list[CrossRepoPackageDep] = []
+ seen: set[tuple[str, str, str]] = set() # (source, target, kind)
+
+ for alias, path in repo_paths.items():
+ for scanner in (_scan_package_json, _scan_pyproject_toml, _scan_cargo_toml, _scan_go_mod):
+ for dep in scanner(path, repo_paths, alias):
+ key = (dep.source_repo, dep.target_repo, dep.kind)
+ if key not in seen:
+ seen.add(key)
+ results.append(dep)
+
+ return results
+
+
+# ---------------------------------------------------------------------------
+# Repo summaries
+# ---------------------------------------------------------------------------
+
+
+def _build_repo_summaries(
+ repo_paths: dict[str, Path],
+ co_changes: list[CrossRepoCoChange],
+ package_deps: list[CrossRepoPackageDep],
+) -> dict[str, dict]:
+ """Build per-repo summary stats."""
+ summaries: dict[str, dict] = {}
+
+ # Count cross-repo edges per repo
+ edge_counts: dict[str, int] = defaultdict(int)
+ for cc in co_changes:
+ edge_counts[cc.source_repo] += 1
+ edge_counts[cc.target_repo] += 1
+ for pd in package_deps:
+ edge_counts[pd.source_repo] += 1
+ edge_counts[pd.target_repo] += 1
+
+ for alias in repo_paths:
+ summaries[alias] = {
+ "cross_repo_edge_count": edge_counts.get(alias, 0),
+ }
+
+ return summaries
+
+
+# ---------------------------------------------------------------------------
+# Persistence
+# ---------------------------------------------------------------------------
+
+
+def save_overlay(overlay: CrossRepoOverlay, workspace_root: Path) -> Path:
+ """Save overlay to ``.repowise-workspace/cross_repo_edges.json``."""
+ data_dir = ensure_workspace_data_dir(workspace_root)
+ out_path = data_dir / CROSS_REPO_EDGES_FILENAME
+ out_path.write_text(
+ json.dumps(overlay.to_dict(), indent=2, ensure_ascii=False),
+ encoding="utf-8",
+ )
+ return out_path
+
+
+def load_overlay(workspace_root: Path) -> CrossRepoOverlay | None:
+ """Load overlay from ``.repowise-workspace/cross_repo_edges.json``.
+
+ Returns ``None`` if the file doesn't exist or is corrupt.
+ """
+ from .config import WORKSPACE_DATA_DIR
+
+ path = workspace_root / WORKSPACE_DATA_DIR / CROSS_REPO_EDGES_FILENAME
+ if not path.is_file():
+ return None
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ return CrossRepoOverlay.from_dict(data)
+ except Exception:
+ _log.warning("Failed to load cross-repo overlay from %s", path, exc_info=True)
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Orchestrator
+# ---------------------------------------------------------------------------
+
+
+async def run_cross_repo_analysis(
+ ws_config: WorkspaceConfig,
+ workspace_root: Path,
+ changed_repos: list[str],
+) -> CrossRepoOverlay:
+ """Full cross-repo analysis pipeline.
+
+ Called from :func:`run_cross_repo_hooks` after workspace update.
+ """
+ # Build repo_paths dict — only include repos that have been indexed
+ # (have a .repowise/ directory). Non-indexed repos must not leak into
+ # cross-repo signals.
+ repo_paths: dict[str, Path] = {}
+ for entry in ws_config.repos:
+ abs_path = (workspace_root / entry.path).resolve()
+ if abs_path.is_dir() and (abs_path / ".repowise").is_dir():
+ repo_paths[entry.alias] = abs_path
+ elif abs_path.is_dir():
+ _log.debug(
+ "Skipping non-indexed repo %r in cross-repo analysis",
+ entry.alias,
+ )
+
+ if len(repo_paths) < 2:
+ _log.debug("Skipping cross-repo analysis — fewer than 2 indexed repos")
+ return CrossRepoOverlay()
+
+ _log.info(
+ "Running cross-repo analysis across %d repos (changed: %s)",
+ len(repo_paths),
+ ", ".join(changed_repos),
+ )
+
+ # Co-change detection (CPU-bound git subprocess calls)
+ import asyncio
+
+ co_changes = await asyncio.to_thread(
+ detect_cross_repo_co_changes, repo_paths
+ )
+
+ # Package dependency detection (file I/O)
+ package_deps = await asyncio.to_thread(
+ detect_package_dependencies, repo_paths
+ )
+
+ # Build summaries
+ repo_summaries = _build_repo_summaries(repo_paths, co_changes, package_deps)
+
+ overlay = CrossRepoOverlay(
+ version=1,
+ generated_at=datetime.now(timezone.utc).isoformat(),
+ co_changes=co_changes,
+ package_deps=package_deps,
+ repo_summaries=repo_summaries,
+ )
+
+ # Persist
+ out_path = save_overlay(overlay, workspace_root)
+ _log.info(
+ "Cross-repo analysis complete: %d co-change edges, %d package deps → %s",
+ len(co_changes),
+ len(package_deps),
+ out_path,
+ )
+
+ return overlay
diff --git a/packages/core/src/repowise/core/workspace/extractors/__init__.py b/packages/core/src/repowise/core/workspace/extractors/__init__.py
new file mode 100644
index 000000000..d2c748d44
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/__init__.py
@@ -0,0 +1,22 @@
+"""Contract extractors — HTTP routes, gRPC services, message topics, service boundaries."""
+
+from __future__ import annotations
+
+from .grpc_extractor import GrpcExtractor
+from .http_extractor import HttpExtractor, normalize_http_path
+from .service_boundary import (
+ ServiceBoundary,
+ assign_service,
+ detect_service_boundaries,
+)
+from .topic_extractor import TopicExtractor
+
+__all__ = [
+ "GrpcExtractor",
+ "HttpExtractor",
+ "ServiceBoundary",
+ "TopicExtractor",
+ "assign_service",
+ "detect_service_boundaries",
+ "normalize_http_path",
+]
diff --git a/packages/core/src/repowise/core/workspace/extractors/grpc_extractor.py b/packages/core/src/repowise/core/workspace/extractors/grpc_extractor.py
new file mode 100644
index 000000000..71d5d0a92
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/grpc_extractor.py
@@ -0,0 +1,319 @@
+"""gRPC contract extraction.
+
+Scans ``.proto`` files for service/rpc declarations (providers) and
+language-specific source files for gRPC server registrations (providers) and
+client stubs (consumers).
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+_log = logging.getLogger("repowise.workspace.extractors.grpc")
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+_BLOCKED_DIRS = frozenset({
+ ".git", "node_modules", "__pycache__", ".venv", "venv",
+ "dist", "build", "target", "vendor", ".next", ".nuxt",
+ ".tox", ".mypy_cache", ".gradle", ".mvn", "out", "bin",
+})
+
+_MAX_FILE_SIZE = 512 * 1024
+
+_PROTO_EXTENSIONS = frozenset({".proto"})
+
+_SOURCE_EXTENSIONS = frozenset({
+ ".go", ".java", ".py", ".ts", ".tsx", ".js", ".jsx",
+})
+
+_ALL_EXTENSIONS = _PROTO_EXTENSIONS | _SOURCE_EXTENSIONS
+
+
+# ---------------------------------------------------------------------------
+# Proto parsing (brace-depth counter)
+# ---------------------------------------------------------------------------
+
+
+def _extract_service_blocks(content: str) -> list[tuple[str, str]]:
+ """Extract ``(service_name, body)`` pairs from a ``.proto`` file.
+
+ Uses brace-depth counting so nested braces in comments, options, or
+ message bodies don't break parsing.
+ """
+ results: list[tuple[str, str]] = []
+ header_re = re.compile(r"service\s+(\w+)\s*\{")
+
+ for header_match in header_re.finditer(content):
+ service_name = header_match.group(1)
+ body_start = header_match.end()
+ depth = 1
+ pos = body_start
+ in_line_comment = False
+ in_block_comment = False
+ while pos < len(content) and depth > 0:
+ ch = content[pos]
+ # Track comment state to ignore braces inside comments
+ if in_line_comment:
+ if ch == "\n":
+ in_line_comment = False
+ elif in_block_comment:
+ if ch == "*" and pos + 1 < len(content) and content[pos + 1] == "/":
+ in_block_comment = False
+ pos += 1 # skip the '/'
+ elif ch == "/" and pos + 1 < len(content):
+ if content[pos + 1] == "/":
+ in_line_comment = True
+ elif content[pos + 1] == "*":
+ in_block_comment = True
+ pos += 1 # skip the '*'
+ elif ch == "{":
+ depth += 1
+ elif ch == "}":
+ depth -= 1
+ pos += 1
+ if depth != 0:
+ continue # incomplete/malformed service block
+ body = content[body_start : pos - 1]
+ results.append((service_name, body))
+
+ return results
+
+
+def _parse_proto_file(content: str) -> tuple[str, list[tuple[str, str, list[str]]]]:
+ """Parse a proto file, returning ``(package, services)``.
+
+ Each service is ``(service_name, full_service_path, [method_names])``.
+ """
+ # Extract package
+ pkg_match = re.search(r"^\s*package\s+([\w.]+)\s*;", content, re.MULTILINE)
+ package = pkg_match.group(1) if pkg_match else ""
+
+ services: list[tuple[str, str, list[str]]] = []
+ rpc_re = re.compile(r"rpc\s+(\w+)\s*\(")
+
+ for svc_name, body in _extract_service_blocks(content):
+ full_path = f"{package}.{svc_name}" if package else svc_name
+ methods = [m.group(1) for m in rpc_re.finditer(body)]
+ services.append((svc_name, full_path, methods))
+
+ return package, services
+
+
+# ---------------------------------------------------------------------------
+# Language-specific patterns
+# ---------------------------------------------------------------------------
+
+# Go providers: pb.RegisterAuthServiceServer(grpcServer, &impl{})
+_GO_PROVIDER_RE = re.compile(r"\.Register(\w+)Server\s*\(")
+# Go consumers: pb.NewAuthServiceClient(conn)
+_GO_CONSUMER_RE = re.compile(r"\.New(\w+)Client\s*\(")
+
+# Java providers: extends AuthServiceGrpc.AuthServiceImplBase
+_JAVA_PROVIDER_RE = re.compile(r"extends\s+(\w+)Grpc\.(\w+)ImplBase")
+# Java @GrpcService annotation
+_JAVA_GRPC_SERVICE_RE = re.compile(r"@GrpcService")
+# Java consumers: AuthServiceGrpc.newBlockingStub(channel)
+_JAVA_CONSUMER_RE = re.compile(r"(\w+)Grpc\.new(?:Blocking|Future)?Stub\s*\(")
+
+# Python providers: add_AuthServiceServicer_to_server(servicer, server)
+_PY_PROVIDER_RE = re.compile(r"add_(\w+?)Servicer_to_server\s*\(")
+# Python consumers: AuthServiceStub(channel)
+_PY_CONSUMER_RE = re.compile(r"(\w+)Stub\s*\(")
+
+# TypeScript providers: @GrpcMethod('AuthService', 'Login')
+_TS_PROVIDER_RE = re.compile(r"@GrpcMethod\s*\(\s*'(\w+)'\s*,\s*'(\w+)'\s*\)")
+
+
+# ---------------------------------------------------------------------------
+# Extractor
+# ---------------------------------------------------------------------------
+
+
+class GrpcExtractor:
+ """Extract gRPC contracts from proto files and language-specific source."""
+
+ def extract(self, repo_path: Path, repo_alias: str = "") -> list[Contract]:
+ from repowise.core.workspace.contracts import Contract
+
+ contracts: list[Contract] = []
+ repo_root = repo_path.resolve()
+
+ for dirpath, dirnames, filenames in os.walk(repo_root):
+ dirnames[:] = [
+ d for d in dirnames
+ if d not in _BLOCKED_DIRS and not d.startswith(".")
+ ]
+ for fname in filenames:
+ fpath = Path(dirpath) / fname
+ suffix = fpath.suffix.lower()
+ if suffix not in _ALL_EXTENSIONS:
+ continue
+ try:
+ if fpath.stat().st_size > _MAX_FILE_SIZE:
+ continue
+ except OSError:
+ continue
+
+ try:
+ content = fpath.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ continue
+
+ rel_path = fpath.relative_to(repo_root).as_posix()
+
+ # --- Proto files → providers ---
+ if suffix in _PROTO_EXTENSIONS:
+ _package, services = _parse_proto_file(content)
+ for _svc_name, full_path, methods in services:
+ for method in methods:
+ contract_id = f"grpc::{full_path}/{method}"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="grpc",
+ role="provider",
+ file_path=rel_path,
+ symbol_name=f"{full_path}/{method}",
+ confidence=0.85,
+ service=None,
+ meta={
+ "package": _package,
+ "service": _svc_name,
+ "method": method,
+ "source": "proto",
+ },
+ ))
+
+ # --- Go ---
+ elif suffix == ".go":
+ for m in _GO_PROVIDER_RE.finditer(content):
+ svc = m.group(1)
+ contract_id = f"grpc::{svc}/*"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="grpc",
+ role="provider",
+ file_path=rel_path,
+ symbol_name=f"go:Register{svc}Server",
+ confidence=0.8,
+ service=None,
+ meta={"service": svc, "source": "go_register"},
+ ))
+
+ for m in _GO_CONSUMER_RE.finditer(content):
+ svc = m.group(1)
+ contract_id = f"grpc::{svc}/*"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="grpc",
+ role="consumer",
+ file_path=rel_path,
+ symbol_name=f"go:New{svc}Client",
+ confidence=0.7,
+ service=None,
+ meta={"service": svc, "source": "go_client"},
+ ))
+
+ # --- Java ---
+ elif suffix == ".java":
+ for m in _JAVA_PROVIDER_RE.finditer(content):
+ svc = m.group(1)
+ contract_id = f"grpc::{svc}/*"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="grpc",
+ role="provider",
+ file_path=rel_path,
+ symbol_name=f"java:extends {svc}Grpc.ImplBase",
+ confidence=0.8,
+ service=None,
+ meta={"service": svc, "source": "java_extends"},
+ ))
+
+ for m in _JAVA_CONSUMER_RE.finditer(content):
+ svc = m.group(1)
+ contract_id = f"grpc::{svc}/*"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="grpc",
+ role="consumer",
+ file_path=rel_path,
+ symbol_name=f"java:{svc}Grpc.newStub",
+ confidence=0.7,
+ service=None,
+ meta={"service": svc, "source": "java_stub"},
+ ))
+
+ # --- Python ---
+ elif suffix == ".py":
+ for m in _PY_PROVIDER_RE.finditer(content):
+ svc = m.group(1)
+ contract_id = f"grpc::{svc}/*"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="grpc",
+ role="provider",
+ file_path=rel_path,
+ symbol_name=f"py:add_{svc}Servicer_to_server",
+ confidence=0.8,
+ service=None,
+ meta={"service": svc, "source": "py_servicer"},
+ ))
+
+ for m in _PY_CONSUMER_RE.finditer(content):
+ svc = m.group(1)
+ # Filter common false positives (Mock*, Test*, Fake* prefixes)
+ svc_lower = svc.lower()
+ if any(svc_lower.startswith(p) for p in ("mock", "test", "fake")):
+ continue
+ contract_id = f"grpc::{svc}/*"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="grpc",
+ role="consumer",
+ file_path=rel_path,
+ symbol_name=f"py:{svc}Stub",
+ confidence=0.7,
+ service=None,
+ meta={"service": svc, "source": "py_stub"},
+ ))
+
+ # --- TypeScript ---
+ elif suffix in (".ts", ".tsx", ".js", ".jsx"):
+ for m in _TS_PROVIDER_RE.finditer(content):
+ svc = m.group(1)
+ method = m.group(2)
+ contract_id = f"grpc::{svc}/{method}"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="grpc",
+ role="provider",
+ file_path=rel_path,
+ symbol_name=f"ts:@GrpcMethod('{svc}', '{method}')",
+ confidence=0.8,
+ service=None,
+ meta={
+ "service": svc,
+ "method": method,
+ "source": "ts_decorator",
+ },
+ ))
+
+ return contracts
diff --git a/packages/core/src/repowise/core/workspace/extractors/http_extractor.py b/packages/core/src/repowise/core/workspace/extractors/http_extractor.py
new file mode 100644
index 000000000..2f00b4687
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http_extractor.py
@@ -0,0 +1,343 @@
+"""HTTP route contract extraction.
+
+Scans source files for route handler declarations (providers) and HTTP client
+calls (consumers). Patterns cover Express, FastAPI, Spring, Laravel, Go,
+fetch, axios, requests, and httpx.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+_log = logging.getLogger("repowise.workspace.extractors.http")
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+_BLOCKED_DIRS = frozenset({
+ ".git", "node_modules", "__pycache__", ".venv", "venv",
+ "dist", "build", "target", "vendor", ".next", ".nuxt",
+ ".tox", ".mypy_cache", ".gradle", ".mvn", "out", "bin",
+})
+
+_MAX_FILE_SIZE = 512 * 1024 # 512 KB
+
+_PROVIDER_EXTENSIONS = frozenset({
+ ".py", ".ts", ".tsx", ".js", ".jsx", ".java", ".php", ".go",
+})
+
+_CONSUMER_EXTENSIONS = frozenset({
+ ".py", ".ts", ".tsx", ".js", ".jsx",
+})
+
+_ALL_EXTENSIONS = _PROVIDER_EXTENSIONS | _CONSUMER_EXTENSIONS
+
+
+# ---------------------------------------------------------------------------
+# Path normalization
+# ---------------------------------------------------------------------------
+
+
+def normalize_http_path(path: str) -> str:
+ """Normalize an HTTP path for matching.
+
+ Steps:
+ 1. Strip whitespace
+ 2. Remove query string
+ 3. Lowercase
+ 4. Strip trailing slash (but keep root ``/``)
+ 5. Unify param styles: ``:param``, ``{param}``, ``[param]`` → ``{param}``
+ """
+ s = path.strip().split("?")[0].lower()
+ if s != "/":
+ s = s.rstrip("/")
+ # Unify Express :param
+ s = re.sub(r":(\w+)", "{param}", s)
+ # Unify Spring/FastAPI {name} → {param}
+ s = re.sub(r"\{[^}]+\}", "{param}", s)
+ # Unify Next.js [name] → {param}
+ s = re.sub(r"\[[^\]]+\]", "{param}", s)
+ # Unify JS template literal ${expr} → {param}
+ s = re.sub(r"\$\{[^}]+\}", "{param}", s)
+ return s or "/"
+
+
+# ---------------------------------------------------------------------------
+# Provider patterns
+# ---------------------------------------------------------------------------
+
+# Each pattern: (compiled_regex, method_group_or_none, path_group, framework)
+# method_group is the capture group index for the HTTP method (1-based), or 0
+# if the method is embedded in the regex match differently.
+
+_METHODS = r"get|post|put|delete|patch"
+_METHODS_UPPER = r"GET|POST|PUT|DELETE|PATCH"
+
+# Express / Node.js: router.get('/path', ...) or app.post('/path', ...)
+# Negative lookbehind for @ to avoid matching FastAPI decorators
+_EXPRESS_RE = re.compile(
+ rf"""(?<!@)(?:router|app)\.({_METHODS})\s*\(\s*['"]([^'"]+)['"]""",
+ re.IGNORECASE,
+)
+
+# FastAPI / Python: @app.get('/path') or @router.post('/path')
+_FASTAPI_RE = re.compile(
+ rf"""@(?:app|router)\.({_METHODS})\s*\(\s*['"]([^'"]+)['"]""",
+ re.IGNORECASE,
+)
+
+# Spring: @GetMapping("/path"), @PostMapping(value="/path"), etc.
+_SPRING_METHOD_RE = re.compile(
+ r"""@(Get|Post|Put|Delete|Patch)Mapping\s*\(\s*(?:value\s*=\s*)?['"]([^'"]+)['"]""",
+ re.IGNORECASE,
+)
+
+# Spring class-level prefix: @RequestMapping("/api/v1")
+_SPRING_CLASS_RE = re.compile(
+ r"""@RequestMapping\s*\(\s*(?:value\s*=\s*)?['"]([^'"]+)['"]""",
+)
+
+# Laravel: Route::get('/path', ...)
+_LARAVEL_RE = re.compile(
+ rf"""Route::({_METHODS})\s*\(\s*['"]([^'"]+)['"]""",
+ re.IGNORECASE,
+)
+
+# Go (gin, echo, chi, net/http): r.GET("/path", ...) or .HandleFunc("/path", ...)
+_GO_ROUTE_RE = re.compile(
+ rf"""\.({_METHODS_UPPER}|Handle|HandleFunc)\s*\(\s*['"]([^'"]+)['"]""",
+)
+
+_PROVIDER_PATTERNS = [
+ (_EXPRESS_RE, "express"),
+ (_FASTAPI_RE, "fastapi"),
+ (_SPRING_METHOD_RE, "spring"),
+ (_LARAVEL_RE, "laravel"),
+ (_GO_ROUTE_RE, "go"),
+]
+
+# ---------------------------------------------------------------------------
+# Consumer patterns
+# ---------------------------------------------------------------------------
+
+# fetch('/api/users') or fetch('/api/users', { method: 'POST' })
+_FETCH_RE = re.compile(
+ r"""fetch\s*\(\s*['"`]([^'"`]+)['"`]""",
+)
+_FETCH_METHOD_RE = re.compile(
+ r"""fetch\s*\(\s*['"`]([^'"`]+)['"`]\s*,\s*\{[^}]*method\s*:\s*['"](\w+)['"]""",
+ re.DOTALL,
+)
+
+# axios.get('/api/users')
+_AXIOS_RE = re.compile(
+ rf"""axios\.({_METHODS})\s*\(\s*['"]([^'"]+)['"]""",
+ re.IGNORECASE,
+)
+
+# requests.get('http://host/api/users') or httpx.post(...)
+_REQUESTS_RE = re.compile(
+ rf"""(?:requests|httpx)\.({_METHODS})\s*\(\s*['"]([^'"]+)['"]""",
+ re.IGNORECASE,
+)
+
+
+# ---------------------------------------------------------------------------
+# Extractor
+# ---------------------------------------------------------------------------
+
+
+def _extract_path_from_url(url: str) -> str:
+ """Extract just the path portion from a URL, stripping scheme and host."""
+ # If it starts with http:// or https://, strip scheme + authority
+ if "://" in url:
+ after_scheme = url.split("://", 1)[1]
+ slash_idx = after_scheme.find("/")
+ if slash_idx >= 0:
+ return after_scheme[slash_idx:]
+ return "/"
+ return url
+
+
+class HttpExtractor:
+ """Extract HTTP route contracts from source files."""
+
+ def extract(self, repo_path: Path, repo_alias: str = "") -> list[Contract]:
+ """Scan all source files in *repo_path* and return Contract instances."""
+ from repowise.core.workspace.contracts import Contract
+
+ contracts: list[Contract] = []
+ repo_root = repo_path.resolve()
+
+ for dirpath, dirnames, filenames in os.walk(repo_root):
+ dirnames[:] = [
+ d for d in dirnames
+ if d not in _BLOCKED_DIRS and not d.startswith(".")
+ ]
+ for fname in filenames:
+ fpath = Path(dirpath) / fname
+ suffix = fpath.suffix.lower()
+ if suffix not in _ALL_EXTENSIONS:
+ continue
+ try:
+ if fpath.stat().st_size > _MAX_FILE_SIZE:
+ continue
+ except OSError:
+ continue
+
+ try:
+ content = fpath.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ continue
+
+ rel_path = fpath.relative_to(repo_root).as_posix()
+
+ # --- Providers ---
+ if suffix in _PROVIDER_EXTENSIONS:
+ # Spring: collect all class-level @RequestMapping positions and prefixes
+ # so each method-level annotation gets the prefix from the nearest
+ # preceding class declaration rather than always the first one in the file.
+ spring_class_mappings: list[tuple[int, str]] = []
+ if suffix == ".java":
+ for cm in _SPRING_CLASS_RE.finditer(content):
+ spring_class_mappings.append((cm.start(), cm.group(1).rstrip("/")))
+
+ for pattern, framework in _PROVIDER_PATTERNS:
+ for match in pattern.finditer(content):
+ method_raw = match.group(1)
+ path_raw = match.group(2)
+
+ # Go Handle/HandleFunc don't carry a method
+ if method_raw in ("Handle", "HandleFunc"):
+ method = "*"
+ else:
+ method = method_raw.upper()
+
+ # Apply Spring class-level prefix: pick the nearest preceding
+ # @RequestMapping (highest start position that is still before
+ # this match).
+ if framework == "spring" and spring_class_mappings:
+ match_pos = match.start()
+ spring_prefix = ""
+ for cls_pos, cls_prefix in spring_class_mappings:
+ if cls_pos < match_pos:
+ spring_prefix = cls_prefix
+ else:
+ break
+ if spring_prefix:
+ path_raw = spring_prefix + "/" + path_raw.lstrip("/")
+
+ norm_path = normalize_http_path(path_raw)
+
+ # Skip paths that look like template variables or empty
+ if not norm_path or norm_path == "/":
+ if not path_raw.strip("/"):
+ continue
+
+ contract_id = f"http::{method}::{norm_path}"
+
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="http",
+ role="provider",
+ file_path=rel_path,
+ symbol_name=f"{framework}:{method} {path_raw}",
+ confidence=0.85,
+ service=None,
+ meta={
+ "method": method,
+ "path": norm_path,
+ "framework": framework,
+ },
+ ))
+
+ # --- Consumers ---
+ if suffix in _CONSUMER_EXTENSIONS:
+ # fetch() with method
+ for match in _FETCH_METHOD_RE.finditer(content):
+ url = match.group(1)
+ method = match.group(2).upper()
+ path = _extract_path_from_url(url)
+ norm_path = normalize_http_path(path)
+ contract_id = f"http::{method}::{norm_path}"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="http",
+ role="consumer",
+ file_path=rel_path,
+ symbol_name=f"fetch:{method} {url}",
+ confidence=0.75,
+ service=None,
+ meta={"method": method, "path": norm_path, "client": "fetch"},
+ ))
+
+ # fetch() without explicit method → GET (but skip if already matched with method)
+ fetch_method_urls = {m.group(1) for m in _FETCH_METHOD_RE.finditer(content)}
+ for match in _FETCH_RE.finditer(content):
+ url = match.group(1)
+ if url in fetch_method_urls:
+ continue
+ path = _extract_path_from_url(url)
+ norm_path = normalize_http_path(path)
+ contract_id = f"http::GET::{norm_path}"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="http",
+ role="consumer",
+ file_path=rel_path,
+ symbol_name=f"fetch:GET {url}",
+ confidence=0.75,
+ service=None,
+ meta={"method": "GET", "path": norm_path, "client": "fetch"},
+ ))
+
+ # axios
+ for match in _AXIOS_RE.finditer(content):
+ method = match.group(1).upper()
+ url = match.group(2)
+ path = _extract_path_from_url(url)
+ norm_path = normalize_http_path(path)
+ contract_id = f"http::{method}::{norm_path}"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="http",
+ role="consumer",
+ file_path=rel_path,
+ symbol_name=f"axios:{method} {url}",
+ confidence=0.75,
+ service=None,
+ meta={"method": method, "path": norm_path, "client": "axios"},
+ ))
+
+ # requests / httpx
+ for match in _REQUESTS_RE.finditer(content):
+ method = match.group(1).upper()
+ url = match.group(2)
+ path = _extract_path_from_url(url)
+ norm_path = normalize_http_path(path)
+ contract_id = f"http::{method}::{norm_path}"
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="http",
+ role="consumer",
+ file_path=rel_path,
+ symbol_name=f"requests:{method} {url}",
+ confidence=0.75,
+ service=None,
+ meta={"method": method, "path": norm_path, "client": "requests"},
+ ))
+
+ return contracts
diff --git a/packages/core/src/repowise/core/workspace/extractors/service_boundary.py b/packages/core/src/repowise/core/workspace/extractors/service_boundary.py
new file mode 100644
index 000000000..3dbd4fd26
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/service_boundary.py
@@ -0,0 +1,167 @@
+"""Service boundary detection for monorepo sub-services.
+
+Walks a repo directory tree looking for marker files (package.json, go.mod,
+Dockerfile, etc.) that indicate independent service boundaries. Used to
+distinguish intra-service calls from inter-service calls when matching
+contracts.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass, field
+from pathlib import Path
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+_SERVICE_MARKERS = frozenset({
+ "package.json",
+ "go.mod",
+ "Dockerfile",
+ "pom.xml",
+ "build.gradle",
+ "build.gradle.kts",
+ "Cargo.toml",
+ "pyproject.toml",
+ "requirements.txt",
+ "mix.exs",
+})
+
+_BLOCKED_DIRS = frozenset({
+ ".git", "node_modules", "__pycache__", ".venv", "venv",
+ "dist", "build", "target", "vendor", ".next", ".nuxt",
+ ".tox", ".mypy_cache", ".gradle", ".mvn", "out", "bin",
+})
+
+_SOURCE_EXTENSIONS = frozenset({
+ ".py", ".ts", ".tsx", ".js", ".jsx", ".java", ".go",
+ ".rs", ".rb", ".php", ".cs", ".kt", ".scala", ".ex", ".exs",
+})
+
+
+# ---------------------------------------------------------------------------
+# Data model
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class ServiceBoundary:
+ """A detected service boundary within a repo."""
+
+ service_path: str # Relative to repo root, POSIX-style
+ service_name: str # Basename of the directory
+ markers: list[str] = field(default_factory=list)
+ confidence: float = 0.75
+
+ def to_dict(self) -> dict:
+ return {
+ "service_path": self.service_path,
+ "service_name": self.service_name,
+ "markers": self.markers,
+ "confidence": self.confidence,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Detection
+# ---------------------------------------------------------------------------
+
+
+def detect_service_boundaries(repo_path: Path) -> list[ServiceBoundary]:
+ """Walk *repo_path* and find directories that look like service roots.
+
+ A directory is a service boundary if it contains at least one marker file
+ AND at least one source file (to avoid flagging config-only dirs).
+ The repo root itself is excluded — it's the default boundary.
+
+ Confidence scoring:
+ - 1 marker → 0.75
+ - 2 markers → 0.90
+ - 3+ markers → 1.00
+ """
+ repo_root = repo_path.resolve()
+ boundaries: list[ServiceBoundary] = []
+
+ for dirpath, dirnames, filenames in os.walk(repo_root):
+ # Prune blocked dirs in-place
+ dirnames[:] = [
+ d for d in dirnames
+ if d not in _BLOCKED_DIRS and not d.startswith(".")
+ ]
+
+ current = Path(dirpath)
+ if current == repo_root:
+ continue # skip repo root itself
+
+ # Check for marker files
+ found_markers = [f for f in filenames if f in _SERVICE_MARKERS]
+ if not found_markers:
+ continue
+
+ # Require at least one source file in this dir (not recursively)
+ has_source = any(
+ Path(f).suffix.lower() in _SOURCE_EXTENSIONS
+ for f in filenames
+ )
+ if not has_source:
+ # Check immediate subdirs for source files
+ try:
+ has_source = any(
+ Path(dirpath, d, f).suffix.lower() in _SOURCE_EXTENSIONS
+ for d in dirnames
+ for f in os.listdir(Path(dirpath, d))
+ if os.path.isfile(Path(dirpath, d, f))
+ ) if dirnames else False
+ except (PermissionError, OSError):
+ has_source = False
+
+ if not has_source:
+ continue
+
+ rel_path = current.relative_to(repo_root).as_posix()
+ marker_count = len(found_markers)
+
+ if marker_count >= 3:
+ confidence = 1.0
+ elif marker_count == 2:
+ confidence = 0.9
+ else:
+ confidence = 0.75
+
+ boundaries.append(ServiceBoundary(
+ service_path=rel_path,
+ service_name=current.name,
+ markers=sorted(found_markers),
+ confidence=confidence,
+ ))
+
+ return boundaries
+
+
+# ---------------------------------------------------------------------------
+# Assignment
+# ---------------------------------------------------------------------------
+
+
+def assign_service(
+ file_path: str,
+ boundaries: list[ServiceBoundary],
+) -> str | None:
+ """Return the service_path of the deepest boundary that is a prefix of *file_path*.
+
+ Uses longest-prefix matching so that ``services/auth/handler.py`` matches
+ ``services/auth`` over ``services``.
+ """
+ normalized = file_path.replace("\\", "/")
+ best: ServiceBoundary | None = None
+ best_length = 0
+
+ for boundary in boundaries:
+ prefix = boundary.service_path + "/"
+ if normalized.startswith(prefix) and len(boundary.service_path) > best_length:
+ best = boundary
+ best_length = len(boundary.service_path)
+
+ return best.service_path if best else None
diff --git a/packages/core/src/repowise/core/workspace/extractors/topic_extractor.py b/packages/core/src/repowise/core/workspace/extractors/topic_extractor.py
new file mode 100644
index 000000000..44338aa0a
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/topic_extractor.py
@@ -0,0 +1,237 @@
+"""Message topic/queue contract extraction.
+
+Scans source files for Kafka, RabbitMQ, and NATS producer (provider) and
+consumer patterns.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+_log = logging.getLogger("repowise.workspace.extractors.topic")
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+_BLOCKED_DIRS = frozenset({
+ ".git", "node_modules", "__pycache__", ".venv", "venv",
+ "dist", "build", "target", "vendor", ".next", ".nuxt",
+ ".tox", ".mypy_cache", ".gradle", ".mvn", "out", "bin",
+})
+
+_MAX_FILE_SIZE = 512 * 1024
+
+_EXTENSIONS = frozenset({
+ ".py", ".ts", ".tsx", ".js", ".jsx", ".java", ".go",
+})
+
+
+# ---------------------------------------------------------------------------
+# Pattern definitions
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class _PatternDef:
+ regex: re.Pattern[str]
+ role: str # "provider" | "consumer"
+ broker: str # "kafka" | "rabbitmq" | "nats"
+ confidence: float
+ topic_group: int # capture group index for topic name
+ label: str # human-readable name
+
+
+# --- Kafka ---
+
+_KAFKA_PATTERNS: list[_PatternDef] = [
+ # Java: @KafkaListener(topics = "orders")
+ _PatternDef(
+ regex=re.compile(r"""@KafkaListener\s*\([^)]*topics?\s*=\s*['"]([^'"]+)['"]"""),
+ role="consumer", broker="kafka", confidence=0.8,
+ topic_group=1, label="@KafkaListener",
+ ),
+ # Java: kafkaTemplate.send("orders", ...)
+ _PatternDef(
+ regex=re.compile(r"""kafkaTemplate\.send\s*\(\s*['"]([^'"]+)['"]"""),
+ role="provider", broker="kafka", confidence=0.8,
+ topic_group=1, label="kafkaTemplate.send",
+ ),
+ # Node: producer.send({ topic: 'orders' })
+ _PatternDef(
+ regex=re.compile(r"""producer\.send\s*\(\s*\{\s*topic\s*:\s*['"]([^'"]+)['"]"""),
+ role="provider", broker="kafka", confidence=0.8,
+ topic_group=1, label="producer.send({topic})",
+ ),
+ # Node: consumer.subscribe({ topic: 'orders' })
+ _PatternDef(
+ regex=re.compile(r"""consumer\.subscribe\s*\(\s*\{\s*topic\s*:\s*['"]([^'"]+)['"]"""),
+ role="consumer", broker="kafka", confidence=0.8,
+ topic_group=1, label="consumer.subscribe({topic})",
+ ),
+ # Python: KafkaConsumer('orders')
+ _PatternDef(
+ regex=re.compile(r"""KafkaConsumer\s*\(\s*['"]([^'"]+)['"]"""),
+ role="consumer", broker="kafka", confidence=0.7,
+ topic_group=1, label="KafkaConsumer",
+ ),
+ # Python: producer.produce('orders')
+ _PatternDef(
+ regex=re.compile(r"""producer\.produce\s*\(\s*['"]([^'"]+)['"]"""),
+ role="provider", broker="kafka", confidence=0.7,
+ topic_group=1, label="producer.produce",
+ ),
+ # Go: ConsumePartition("orders", ...)
+ _PatternDef(
+ regex=re.compile(r"""ConsumePartition\s*\(\s*['"]([^'"]+)['"]"""),
+ role="consumer", broker="kafka", confidence=0.7,
+ topic_group=1, label="ConsumePartition",
+ ),
+]
+
+# --- RabbitMQ ---
+
+_RABBITMQ_PATTERNS: list[_PatternDef] = [
+ # Java: @RabbitListener(queues = "jobs")
+ _PatternDef(
+ regex=re.compile(r"""@RabbitListener\s*\([^)]*queues?\s*=\s*['"]([^'"]+)['"]"""),
+ role="consumer", broker="rabbitmq", confidence=0.8,
+ topic_group=1, label="@RabbitListener",
+ ),
+ # Java: rabbitTemplate.convertAndSend("exchange", ...)
+ _PatternDef(
+ regex=re.compile(r"""rabbitTemplate\.convertAndSend\s*\(\s*['"]([^'"]+)['"]"""),
+ role="provider", broker="rabbitmq", confidence=0.8,
+ topic_group=1, label="rabbitTemplate.convertAndSend",
+ ),
+ # Node: channel.consume("queue", ...)
+ _PatternDef(
+ regex=re.compile(r"""channel\.consume\s*\(\s*['"]([^'"]+)['"]"""),
+ role="consumer", broker="rabbitmq", confidence=0.8,
+ topic_group=1, label="channel.consume",
+ ),
+ # Node: channel.publish("exchange", ...)
+ _PatternDef(
+ regex=re.compile(r"""channel\.publish\s*\(\s*['"]([^'"]+)['"]"""),
+ role="provider", broker="rabbitmq", confidence=0.8,
+ topic_group=1, label="channel.publish",
+ ),
+ # Node: channel.sendToQueue("queue", ...)
+ _PatternDef(
+ regex=re.compile(r"""channel\.sendToQueue\s*\(\s*['"]([^'"]+)['"]"""),
+ role="provider", broker="rabbitmq", confidence=0.8,
+ topic_group=1, label="channel.sendToQueue",
+ ),
+ # Python: channel.basic_consume(queue='jobs')
+ _PatternDef(
+ regex=re.compile(r"""channel\.basic_consume\s*\([^)]*queue\s*=\s*['"]([^'"]+)['"]"""),
+ role="consumer", broker="rabbitmq", confidence=0.7,
+ topic_group=1, label="basic_consume",
+ ),
+ # Python: channel.basic_publish(exchange='events')
+ _PatternDef(
+ regex=re.compile(r"""channel\.basic_publish\s*\([^)]*exchange\s*=\s*['"]([^'"]+)['"]"""),
+ role="provider", broker="rabbitmq", confidence=0.7,
+ topic_group=1, label="basic_publish",
+ ),
+]
+
+# --- NATS ---
+
+_NATS_PATTERNS: list[_PatternDef] = [
+ # Go/Python/Node: nc.Subscribe("events") or nc.subscribe("events")
+ # Requires a NATS-idiomatic variable name (nc, nats, conn, js, sub, client)
+ # to avoid false-positives from RxJS, EventEmitter, custom publishers, etc.
+ _PatternDef(
+ regex=re.compile(r"""(?:nc|nats|conn|js|sub|client)\s*\.\s*(?:Subscribe|subscribe)\s*\(\s*['"]([^'"]+)['"]"""),
+ role="consumer", broker="nats", confidence=0.8,
+ topic_group=1, label="nc.Subscribe",
+ ),
+ # Go/Python/Node: nc.Publish("events") or nc.publish("events")
+ # Requires a NATS-idiomatic variable name to avoid false-positives.
+ _PatternDef(
+ regex=re.compile(r"""(?:nc|nats|conn|js|sub|client)\s*\.\s*(?:Publish|publish)\s*\(\s*['"]([^'"]+)['"]"""),
+ role="provider", broker="nats", confidence=0.8,
+ topic_group=1, label="nc.Publish",
+ ),
+]
+
+_ALL_PATTERNS = _KAFKA_PATTERNS + _RABBITMQ_PATTERNS + _NATS_PATTERNS
+
+
+# ---------------------------------------------------------------------------
+# Extractor
+# ---------------------------------------------------------------------------
+
+
+class TopicExtractor:
+ """Extract message topic/queue contracts from source files."""
+
+ def extract(self, repo_path: Path, repo_alias: str = "") -> list[Contract]:
+ from repowise.core.workspace.contracts import Contract
+
+ contracts: list[Contract] = []
+ repo_root = repo_path.resolve()
+ seen: set[tuple[str, str, str]] = set() # (file, contract_id, role) dedup
+
+ for dirpath, dirnames, filenames in os.walk(repo_root):
+ dirnames[:] = [
+ d for d in dirnames
+ if d not in _BLOCKED_DIRS and not d.startswith(".")
+ ]
+ for fname in filenames:
+ fpath = Path(dirpath) / fname
+ suffix = fpath.suffix.lower()
+ if suffix not in _EXTENSIONS:
+ continue
+ try:
+ if fpath.stat().st_size > _MAX_FILE_SIZE:
+ continue
+ except OSError:
+ continue
+
+ try:
+ content = fpath.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ continue
+
+ rel_path = fpath.relative_to(repo_root).as_posix()
+
+ for pdef in _ALL_PATTERNS:
+ for match in pdef.regex.finditer(content):
+ topic_name = match.group(pdef.topic_group).strip()
+ if not topic_name:
+ continue
+
+ contract_id = f"topic::{topic_name.lower()}"
+
+ # Deduplicate within the same file
+ dedup_key = (rel_path, contract_id, pdef.role)
+ if dedup_key in seen:
+ continue
+ seen.add(dedup_key)
+
+ contracts.append(Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="topic",
+ role=pdef.role,
+ file_path=rel_path,
+ symbol_name=f"{pdef.label}('{topic_name}')",
+ confidence=pdef.confidence,
+ service=None,
+ meta={
+ "topic": topic_name,
+ "broker": pdef.broker,
+ },
+ ))
+
+ return contracts
diff --git a/packages/core/src/repowise/core/workspace/registry.py b/packages/core/src/repowise/core/workspace/registry.py
new file mode 100644
index 000000000..432381e5d
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/registry.py
@@ -0,0 +1,300 @@
+"""Workspace repo registry — manages per-repo database contexts.
+
+Provides ``RepoContext`` (per-repo resources) and ``RepoRegistry``
+(lazy-loading with LRU eviction) for workspace-aware MCP serving.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+_log = logging.getLogger("repowise.workspace.registry")
+
+
+# ---------------------------------------------------------------------------
+# RepoContext — per-repo resource bundle
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class RepoContext:
+ """Holds all resources needed to serve MCP queries for a single repo."""
+
+ alias: str
+ path: Path
+ session_factory: async_sessionmaker[AsyncSession]
+ fts: Any # FullTextSearch
+ vector_store: Any # LanceDB or InMemoryVectorStore
+ decision_store: Any # LanceDB or InMemoryVectorStore
+ vector_store_ready: asyncio.Event = field(default_factory=asyncio.Event)
+ _engine: Any = field(default=None, repr=False) # AsyncEngine, for dispose
+
+
+# ---------------------------------------------------------------------------
+# RepoRegistry — lazy loading + LRU eviction
+# ---------------------------------------------------------------------------
+
+
+class RepoRegistry:
+ """Manages multiple ``RepoContext`` instances for a workspace.
+
+ Loads repo databases lazily on first access. When the number of loaded
+ repos exceeds ``MAX_LOADED``, the least-recently-used context is evicted
+ (engine disposed, stores closed).
+ """
+
+ MAX_LOADED: int = 5
+
+ def __init__(
+ self,
+ workspace_root: Path,
+ ws_config: Any, # WorkspaceConfig
+ embedder_factory: Callable[[], Any] | None = None,
+ ) -> None:
+ self._workspace_root = workspace_root
+ self._ws_config = ws_config
+ self._embedder_factory = embedder_factory
+ self._contexts: dict[str, RepoContext] = {}
+ self._access_order: dict[str, float] = {}
+ self._vs_tasks: dict[str, asyncio.Task[None]] = {}
+
+ # -- Public API --------------------------------------------------------
+
+ @property
+ def workspace_root(self) -> Path:
+ return self._workspace_root
+
+ @property
+ def ws_config(self) -> Any:
+ return self._ws_config
+
+ def get_all_aliases(self) -> list[str]:
+ """Return aliases of all repos in the workspace config."""
+ return [r.alias for r in self._ws_config.repos]
+
+ def get_default_alias(self) -> str:
+ """Return the alias of the default/primary repo."""
+ primary = self._ws_config.get_primary()
+ if primary:
+ return primary.alias
+ if self._ws_config.default_repo:
+ return self._ws_config.default_repo
+ if not self._ws_config.repos:
+ raise RuntimeError("Workspace has no repos configured")
+ return self._ws_config.repos[0].alias
+
+ def resolve_repo_param(self, repo: str | None) -> str | list[str]:
+ """Resolve the ``repo`` tool parameter.
+
+ Returns:
+ A single alias (str) or list of aliases (for ``"all"``).
+
+ Raises:
+ ValueError: if the alias is unknown.
+ """
+ if repo is None:
+ return self.get_default_alias()
+ if repo == "all":
+ return self.get_all_aliases()
+ # Validate alias exists
+ if self._ws_config.get_repo(repo) is None:
+ available = self.get_all_aliases()
+ raise ValueError(
+ f"Unknown repo '{repo}'. Available: {available}"
+ )
+ return repo
+
+ async def get(self, alias: str) -> RepoContext:
+ """Get the ``RepoContext`` for *alias*, loading lazily if needed."""
+ if alias in self._contexts:
+ self._access_order[alias] = time.monotonic()
+ return self._contexts[alias]
+
+ # Evict if at capacity. The default repo is protected from eviction, so
+ # only count non-default contexts against the cap — this prevents the
+ # cap from being silently bypassed when the default is always loaded.
+ default_alias = self.get_default_alias()
+ evictable = [a for a in self._contexts if a != default_alias]
+ if len(evictable) >= self.MAX_LOADED:
+ await self._evict_lru()
+
+ ctx = await self._load_context(alias)
+ self._contexts[alias] = ctx
+ self._access_order[alias] = time.monotonic()
+ return ctx
+
+ async def get_default(self) -> RepoContext:
+ """Shortcut for ``get(default_alias)``."""
+ return await self.get(self.get_default_alias())
+
+ async def close(self) -> None:
+ """Dispose all loaded engines and close stores."""
+ for alias in list(self._contexts):
+ await self._dispose_context(alias)
+ self._contexts.clear()
+ self._access_order.clear()
+
+ # -- Internal ----------------------------------------------------------
+
+ async def _load_context(self, alias: str) -> RepoContext:
+ """Create engine, session factory, FTS, and vector stores for a repo."""
+ entry = self._ws_config.get_repo(alias)
+ if entry is None:
+ raise ValueError(f"No repo with alias '{alias}' in workspace config")
+
+ repo_path = (self._workspace_root / entry.path).resolve()
+ db_path = repo_path / ".repowise" / "wiki.db"
+
+ if not db_path.exists():
+ _log.warning("No wiki.db for repo '%s' at %s", alias, db_path)
+
+ from repowise.core.persistence.database import (
+ get_db_url,
+ init_db,
+ )
+ from repowise.core.persistence.search import FullTextSearch
+ from repowise.core.persistence.vector_store import InMemoryVectorStore
+ from repowise.core.providers.embedding.base import MockEmbedder
+ from sqlalchemy.ext.asyncio import (
+ AsyncSession as _AsyncSession,
+ async_sessionmaker as _async_sessionmaker,
+ create_async_engine,
+ )
+
+ db_url = get_db_url(f"sqlite:///{db_path.as_posix()}")
+
+ engine = create_async_engine(
+ db_url,
+ connect_args={"check_same_thread": False},
+ )
+ await init_db(engine)
+
+ session_factory = _async_sessionmaker(
+ engine, expire_on_commit=False, class_=_AsyncSession,
+ )
+
+ fts = FullTextSearch(engine)
+ await fts.ensure_index()
+
+ # Seed placeholder vector stores
+ embedder = self._embedder_factory() if self._embedder_factory else MockEmbedder()
+ vector_store: Any = InMemoryVectorStore(embedder=embedder)
+ decision_store: Any = InMemoryVectorStore(embedder=embedder)
+
+ vs_ready = asyncio.Event()
+
+ ctx = RepoContext(
+ alias=alias,
+ path=repo_path,
+ session_factory=session_factory,
+ fts=fts,
+ vector_store=vector_store,
+ decision_store=decision_store,
+ vector_store_ready=vs_ready,
+ _engine=engine,
+ )
+
+ # Load real vector stores in background; track task for cancellation on eviction
+ task = asyncio.create_task(
+ self._load_vector_stores(ctx, repo_path, embedder),
+ name=f"vs-load-{alias}",
+ )
+ self._vs_tasks[alias] = task
+
+ return ctx
+
+ async def _load_vector_stores(
+ self,
+ ctx: RepoContext,
+ repo_path: Path,
+ embedder: Any,
+ ) -> None:
+ """Background task: load LanceDB vector stores for a repo."""
+ try:
+ try:
+ await asyncio.to_thread(__import__, "lancedb")
+ from repowise.core.persistence.vector_store import LanceDBVectorStore
+
+ lance_dir = repo_path / ".repowise" / "lancedb"
+ if lance_dir.exists():
+ vs = LanceDBVectorStore(str(lance_dir), embedder=embedder)
+ ds = LanceDBVectorStore(
+ str(lance_dir), embedder=embedder, table_name="decision_records",
+ )
+ await vs._ensure_connected()
+ await ds._ensure_connected()
+ ctx.vector_store = vs
+ ctx.decision_store = ds
+ except ImportError:
+ pass
+ except Exception:
+ _log.warning(
+ "LanceDB load failed for '%s' — using InMemory fallback",
+ ctx.alias,
+ )
+ finally:
+ # Only signal ready if this context is still the active one.
+ # If it was evicted before we finished loading, a fresh context
+ # will have its own event — setting the stale one would leave the
+ # new context's event unset and cause callers to hang forever.
+ if self._contexts.get(ctx.alias) is ctx:
+ ctx.vector_store_ready.set()
+ else:
+ _log.debug(
+ "VS load for '%s' completed after eviction — skipping set()",
+ ctx.alias,
+ )
+ # Remove task reference regardless
+ self._vs_tasks.pop(ctx.alias, None)
+
+ async def _evict_lru(self) -> None:
+ """Evict the least-recently-used context to free resources."""
+ if not self._access_order:
+ return
+ # Find the alias with the oldest access time
+ # Never evict the default repo
+ default_alias = self.get_default_alias()
+ candidates = {
+ a: t for a, t in self._access_order.items()
+ if a != default_alias
+ }
+ if not candidates:
+ return # Only default loaded, can't evict
+
+ lru_alias = min(candidates, key=candidates.get) # type: ignore[arg-type]
+ _log.info("Evicting repo context '%s' (LRU)", lru_alias)
+ await self._dispose_context(lru_alias)
+
+ async def _dispose_context(self, alias: str) -> None:
+ """Dispose engine and close stores for a loaded context."""
+ ctx = self._contexts.pop(alias, None)
+ if ctx is None:
+ return
+ self._access_order.pop(alias, None)
+
+ # Cancel any in-flight background VS-load task so it cannot race with
+ # a fresh context that will be created when this alias is re-accessed.
+ task = self._vs_tasks.pop(alias, None)
+ if task is not None and not task.done():
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception):
+ pass
+
+ try:
+ if ctx._engine is not None:
+ await ctx._engine.dispose()
+ if hasattr(ctx.vector_store, "close"):
+ await ctx.vector_store.close()
+ if hasattr(ctx.decision_store, "close"):
+ await ctx.decision_store.close()
+ except Exception:
+ _log.warning("Error disposing context for '%s'", alias, exc_info=True)
diff --git a/packages/core/src/repowise/core/workspace/scanner.py b/packages/core/src/repowise/core/workspace/scanner.py
new file mode 100644
index 000000000..5f2049203
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/scanner.py
@@ -0,0 +1,227 @@
+"""Workspace repo scanner — discover git repositories in a directory tree.
+
+Pure filesystem module with no CLI, DB, or config dependencies.
+Used by ``repowise init`` to detect multi-repo workspaces.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass, field
+from pathlib import Path
+
+# ---------------------------------------------------------------------------
+# Data models
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class DiscoveredRepo:
+ """A git repository found during workspace scanning."""
+
+ path: Path # Absolute, resolved path to repo root
+ name: str # Directory basename (e.g. "backend")
+ alias: str # Unique short name for workspace config
+ has_repowise: bool # True if .repowise/ already exists
+ is_submodule: bool # True if .git is a file (not a directory)
+
+
+@dataclass
+class ScanResult:
+ """Result of scanning a directory for git repositories."""
+
+ repos: list[DiscoveredRepo]
+ root: Path # The directory that was scanned (absolute)
+ skipped_dirs: list[str] = field(default_factory=list)
+
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+# Directories to never descend into during workspace scanning.
+# Distinct from the ingestion traverser's blocklist — this is for
+# top-level *repo* discovery, not file-level traversal within a repo.
+_SCAN_SKIP_DIRS: frozenset[str] = frozenset(
+ {
+ "node_modules",
+ ".venv",
+ "venv",
+ "__pycache__",
+ ".cache",
+ ".tox",
+ "dist",
+ "build",
+ ".next",
+ "target",
+ ".gradle",
+ "vendor",
+ "coverage",
+ "htmlcov",
+ "site-packages",
+ ".eggs",
+ ".mypy_cache",
+ ".pytest_cache",
+ ".ruff_cache",
+ }
+)
+
+_MAX_SCAN_DEPTH: int = 3
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def scan_for_repos(
+ root: Path,
+ *,
+ max_depth: int = _MAX_SCAN_DEPTH,
+ include_submodules: bool = False,
+) -> ScanResult:
+ """Scan *root* for git repositories up to *max_depth* levels deep.
+
+ Returns a :class:`ScanResult` with discovered repos sorted alphabetically
+ by their path relative to *root*.
+
+ - If *root* itself is a git repo, returns a single-element result.
+ - Stops descending once a ``.git`` boundary is found (no nested repos).
+ - Skips common junk directories (``node_modules``, ``.venv``, etc.).
+ - Submodules (``.git`` is a file) are excluded unless *include_submodules* is True.
+ """
+ root = Path(root).resolve()
+
+ # Check if root itself is a git repo
+ root_is_repo = _is_git_repo(root)
+ root_is_sub = _is_submodule(root) if root_is_repo else False
+
+ # Walk the tree for sub-repos even if root is a git repo — a workspace
+ # can be a git repo that contains other git repos (e.g. non-submodule
+ # nested repos like backend/ and frontend/).
+ found: list[tuple[Path, bool]] = [] # (abs_path, is_submodule)
+ skipped: list[str] = []
+
+ for dirpath_str, dirnames, _filenames in os.walk(root):
+ dirpath = Path(dirpath_str)
+ depth = len(dirpath.relative_to(root).parts)
+
+ if depth >= max_depth:
+ dirnames.clear()
+ continue
+
+ # Prune junk and hidden directories (in-place, so os.walk skips them)
+ _prune_dirs(dirnames, dirpath, skipped)
+
+ # Check remaining children for .git boundaries
+ repos_at_this_level: list[str] = []
+ for dirname in list(dirnames):
+ child = dirpath / dirname
+ if _is_git_repo(child):
+ is_sub = _is_submodule(child)
+ if not is_sub or include_submodules:
+ try:
+ resolved = child.resolve()
+ resolved.relative_to(root)
+ found.append((resolved, is_sub))
+ except (OSError, ValueError):
+ continue # broken symlink or resolved outside root
+ repos_at_this_level.append(dirname)
+
+ # Don't descend into discovered repos
+ for dirname in repos_at_this_level:
+ dirnames.remove(dirname)
+
+ # If root is a git repo and no sub-repos found → single-repo result
+ # If root is a git repo AND sub-repos found → include root in the list
+ if root_is_repo:
+ if not found:
+ # Pure single-repo — no sub-repos
+ if root_is_sub and not include_submodules:
+ return ScanResult(repos=[], root=root)
+ aliases = _generate_aliases([(root, root)])
+ repo = _make_repo(root, root, aliases[root], root_is_sub)
+ return ScanResult(repos=[repo], root=root)
+ # Root + sub-repos → workspace mode; add root to the list
+ if not root_is_sub or include_submodules:
+ found.insert(0, (root, root_is_sub))
+
+ # Sort by relative path for deterministic ordering
+ found.sort(key=lambda item: item[0].relative_to(root).as_posix())
+
+ aliases = _generate_aliases([(p, root) for p, _ in found])
+ repos = [_make_repo(p, root, aliases[p], is_sub) for p, is_sub in found]
+ return ScanResult(repos=repos, root=root, skipped_dirs=skipped)
+
+
+# ---------------------------------------------------------------------------
+# Internal helpers
+# ---------------------------------------------------------------------------
+
+
+def _is_git_repo(path: Path) -> bool:
+ """Check if *path* contains a ``.git`` directory or file."""
+ return (path / ".git").exists()
+
+
+def _is_submodule(path: Path) -> bool:
+ """A submodule has ``.git`` as a file pointing to the parent's modules dir."""
+ return (path / ".git").is_file()
+
+
+def _prune_dirs(
+ dirnames: list[str],
+ parent: Path,
+ skipped: list[str],
+) -> None:
+ """Remove junk and hidden directories from *dirnames* in-place."""
+ to_remove: list[str] = []
+ for d in dirnames:
+ if d == ".git":
+ # Never descend into .git itself, but don't log as skipped
+ to_remove.append(d)
+ elif d in _SCAN_SKIP_DIRS:
+ skipped.append(str(parent / d))
+ to_remove.append(d)
+ elif d.startswith(".") and d != ".repowise":
+ # Skip hidden dirs (except .repowise which we check for has_repowise)
+ to_remove.append(d)
+ for d in to_remove:
+ dirnames.remove(d)
+
+
+def _generate_aliases(repo_root_pairs: list[tuple[Path, Path]]) -> dict[Path, str]:
+ """Generate unique aliases from directory basenames.
+
+ On collision, appends ``-2``, ``-3``, etc.
+ *repo_root_pairs* is a list of ``(abs_repo_path, workspace_root)``.
+ """
+ alias_map: dict[Path, str] = {}
+ used_aliases: dict[str, int] = {} # alias → count of times used
+
+ for repo_path, _root in repo_root_pairs:
+ base = repo_path.name.lower()
+ if base not in used_aliases:
+ used_aliases[base] = 1
+ alias_map[repo_path] = base
+ else:
+ used_aliases[base] += 1
+ alias_map[repo_path] = f"{base}-{used_aliases[base]}"
+
+ return alias_map
+
+
+def _make_repo(
+ abs_path: Path,
+ root: Path,
+ alias: str,
+ is_submodule: bool,
+) -> DiscoveredRepo:
+ """Construct a :class:`DiscoveredRepo` from scan data."""
+ return DiscoveredRepo(
+ path=abs_path,
+ name=abs_path.name,
+ alias=alias,
+ has_repowise=(abs_path / ".repowise").is_dir(),
+ is_submodule=is_submodule,
+ )
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
new file mode 100644
index 000000000..0b1027efc
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/update.py
@@ -0,0 +1,357 @@
+"""Workspace-level update orchestration.
+
+Handles staleness detection, parallel multi-repo updates, and cross-repo
+analysis hooks (Phase 3).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import subprocess
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable
+
+from .config import WorkspaceConfig
+
+_log = logging.getLogger("repowise.workspace.update")
+
+# ---------------------------------------------------------------------------
+# Data models
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class RepoUpdateResult:
+ """Result of updating a single repo within a workspace."""
+
+ alias: str
+ updated: bool # True if an update was performed
+ skipped_reason: str | None = None # "up_to_date", "not_indexed", etc.
+ file_count: int = 0
+ symbol_count: int = 0
+ error: str | None = None
+
+
+# ---------------------------------------------------------------------------
+# Staleness detection
+# ---------------------------------------------------------------------------
+
+
+def get_head_commit(repo_path: Path) -> str | None:
+ """Return the current HEAD commit SHA via git, or ``None``."""
+ try:
+ result = subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=str(repo_path),
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if result.returncode == 0:
+ return result.stdout.strip()
+ except Exception:
+ pass
+ return None
+
+
+def count_commits_between(repo_path: Path, base: str, head: str) -> int:
+ """Return the number of commits between *base* and *head*, or 0 on error."""
+ try:
+ result = subprocess.run(
+ ["git", "rev-list", "--count", f"{base}..{head}"],
+ cwd=str(repo_path),
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if result.returncode == 0:
+ return int(result.stdout.strip())
+ except Exception:
+ pass
+ return 0
+
+
+def check_repo_staleness(
+ repo_path: Path,
+ last_commit: str | None,
+) -> tuple[bool, str | None, int]:
+ """Check if a repo has new commits since *last_commit*.
+
+ Returns ``(is_stale, current_head, commits_behind)``.
+ """
+ current_head = get_head_commit(repo_path)
+ if current_head is None:
+ return False, None, 0
+
+ if last_commit is None:
+ # Never indexed — treat as stale
+ return True, current_head, 0
+
+ if current_head == last_commit:
+ return False, current_head, 0
+
+ behind = count_commits_between(repo_path, last_commit, current_head)
+ return True, current_head, behind
+
+
+# ---------------------------------------------------------------------------
+# Single-repo update (index-only)
+# ---------------------------------------------------------------------------
+
+
+async def update_single_repo_index(
+ repo_path: Path,
+ *,
+ commit_depth: int = 500,
+ exclude_patterns: list[str] | None = None,
+ progress: Any | None = None,
+) -> RepoUpdateResult:
+ """Re-run the ingestion pipeline (index-only) for a single repo.
+
+ This refreshes graph, git stats, dead code, and decisions — everything
+ except wiki pages. Used by workspace update when no LLM provider is set.
+ """
+ from ..pipeline import run_pipeline
+ from ..persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+ from ..persistence.database import resolve_db_url
+ from ..pipeline.persist import persist_pipeline_result
+
+ alias = repo_path.name
+
+ try:
+ result = await run_pipeline(
+ repo_path,
+ commit_depth=commit_depth,
+ exclude_patterns=exclude_patterns,
+ generate_docs=False,
+ progress=progress,
+ )
+
+ # Persist to repo-local DB
+ url = resolve_db_url(repo_path)
+ engine = create_engine(url)
+ await init_db(engine)
+ sf = create_session_factory(engine)
+
+ async with get_session(sf) as session:
+ repo = await upsert_repository(
+ session,
+ name=result.repo_name,
+ local_path=str(repo_path),
+ )
+ await persist_pipeline_result(result, session, repo.id)
+
+ await engine.dispose()
+
+ return RepoUpdateResult(
+ alias=alias,
+ updated=True,
+ file_count=result.file_count,
+ symbol_count=result.symbol_count,
+ )
+ except Exception as exc:
+ return RepoUpdateResult(
+ alias=alias,
+ updated=False,
+ error=str(exc),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Workspace update orchestration
+# ---------------------------------------------------------------------------
+
+_MAX_CONCURRENT_UPDATES = 4
+
+
+async def update_workspace(
+ workspace_root: Path,
+ ws_config: WorkspaceConfig,
+ *,
+ repo_filter: str | None = None,
+ dry_run: bool = False,
+ commit_depth: int = 500,
+ exclude_patterns: list[str] | None = None,
+ on_repo_start: Callable[[str], None] | None = None,
+ on_repo_done: Callable[[RepoUpdateResult], None] | None = None,
+) -> list[RepoUpdateResult]:
+ """Update stale repos in the workspace.
+
+ Args:
+ workspace_root: Path to the workspace root directory.
+ ws_config: Loaded workspace configuration.
+ repo_filter: If set, only update this repo alias.
+ dry_run: If True, detect staleness but don't actually update.
+ commit_depth: Max commits to analyze per file.
+ exclude_patterns: Gitignore-style patterns to exclude.
+ on_repo_start: Called with alias when a repo update begins.
+ on_repo_done: Called with result when a repo update finishes.
+
+ Returns:
+ List of :class:`RepoUpdateResult` for each repo.
+ """
+ results: list[RepoUpdateResult] = []
+ stale_repos: list[tuple[str, Path, str]] = [] # (alias, path, new_head)
+
+ # Step 1: Determine which repos are stale
+ entries = ws_config.repos
+ if repo_filter:
+ entry = ws_config.get_repo(repo_filter)
+ if entry is None:
+ available = ", ".join(ws_config.repo_aliases())
+ raise ValueError(f"Unknown repo '{repo_filter}'. Available: {available}")
+ entries = [entry]
+
+ for entry in entries:
+ abs_path = (workspace_root / entry.path).resolve()
+ if not abs_path.is_dir():
+ results.append(RepoUpdateResult(
+ alias=entry.alias, updated=False, skipped_reason="missing_directory",
+ ))
+ continue
+
+ # Check staleness against stored commit in state.json
+ import json
+ state_path = abs_path / ".repowise" / "state.json"
+ stored_commit = None
+ if state_path.is_file():
+ try:
+ state = json.loads(state_path.read_text(encoding="utf-8"))
+ stored_commit = state.get("last_sync_commit")
+ except Exception:
+ pass
+
+ is_stale, current_head, commits_behind = check_repo_staleness(
+ abs_path, stored_commit,
+ )
+
+ if not is_stale:
+ results.append(RepoUpdateResult(
+ alias=entry.alias, updated=False, skipped_reason="up_to_date",
+ ))
+ continue
+
+ if not (abs_path / ".repowise").is_dir():
+ results.append(RepoUpdateResult(
+ alias=entry.alias, updated=False, skipped_reason="not_indexed",
+ ))
+ continue
+
+ stale_repos.append((entry.alias, abs_path, current_head or ""))
+
+ if dry_run or not stale_repos:
+ return results
+
+ # Step 2: Update stale repos (parallel with concurrency limit)
+ semaphore = asyncio.Semaphore(_MAX_CONCURRENT_UPDATES)
+
+ async def _update_one(alias: str, path: Path, new_head: str) -> RepoUpdateResult:
+ async with semaphore:
+ if on_repo_start:
+ on_repo_start(alias)
+
+ result = await update_single_repo_index(
+ path,
+ commit_depth=commit_depth,
+ exclude_patterns=exclude_patterns,
+ )
+ result.alias = alias
+
+ # Update state.json with new commit
+ if result.updated and new_head:
+ import json as _json
+ state_path = path / ".repowise" / "state.json"
+ state: dict[str, Any] = {}
+ if state_path.is_file():
+ try:
+ state = _json.loads(state_path.read_text(encoding="utf-8"))
+ except Exception:
+ pass
+ state["last_sync_commit"] = new_head
+ state_path.parent.mkdir(parents=True, exist_ok=True)
+ state_path.write_text(
+ _json.dumps(state, indent=2), encoding="utf-8",
+ )
+
+ # Update workspace config entry
+ if result.updated:
+ entry = ws_config.get_repo(alias)
+ if entry is not None:
+ entry.indexed_at = datetime.now(timezone.utc).isoformat()
+ entry.last_commit_at_index = new_head
+
+ if on_repo_done:
+ on_repo_done(result)
+
+ return result
+
+ update_results = await asyncio.gather(
+ *[_update_one(alias, path, head) for alias, path, head in stale_repos],
+ return_exceptions=True,
+ )
+
+ changed_aliases: list[str] = []
+ for r in update_results:
+ if isinstance(r, Exception):
+ results.append(RepoUpdateResult(
+ alias="unknown", updated=False, error=str(r),
+ ))
+ else:
+ results.append(r)
+ if r.updated:
+ changed_aliases.append(r.alias)
+
+ # Step 3: Save workspace config with updated timestamps
+ if changed_aliases:
+ ws_config.save(workspace_root)
+
+ # Step 4: Run cross-repo hooks (Phase 3/4 placeholder)
+ if changed_aliases:
+ await run_cross_repo_hooks(ws_config, workspace_root, changed_aliases)
+
+ return results
+
+
+# ---------------------------------------------------------------------------
+# Cross-repo hooks (Phase 3/4 placeholder)
+# ---------------------------------------------------------------------------
+
+
+async def run_cross_repo_hooks(
+ ws_config: WorkspaceConfig,
+ workspace_root: Path,
+ changed_repos: list[str],
+) -> None:
+ """Run cross-repo analysis after workspace repos are updated.
+
+ Detects cross-repo co-changes (files committed by the same author within
+ a time window across repos) and package/manifest dependencies. Results are
+ persisted to ``.repowise-workspace/cross_repo_edges.json`` and loaded by
+ the MCP server's :class:`CrossRepoEnricher` at startup.
+ """
+ if len(ws_config.repos) < 2:
+ return
+
+ from .cross_repo import run_cross_repo_analysis
+
+ try:
+ await run_cross_repo_analysis(ws_config, workspace_root, changed_repos)
+ except Exception:
+ _log.warning("Cross-repo analysis failed", exc_info=True)
+
+ # Phase 4: Contract extraction
+ from .contracts import run_contract_extraction
+
+ try:
+ await run_contract_extraction(ws_config, workspace_root, changed_repos)
+ except Exception:
+ _log.warning("Contract extraction failed", exc_info=True)
diff --git a/packages/server/README.md b/packages/server/README.md
index 8aafb3ef1..354764baa 100644
--- a/packages/server/README.md
+++ b/packages/server/README.md
@@ -10,10 +10,10 @@ FastAPI REST API, webhook handlers, MCP server, and background job scheduler for
| Component | Description |
|-----------|-------------|
-| **REST API** | FastAPI application with full CRUD for repos, pages, symbols, jobs, git analytics, dead code |
-| **MCP Server** | 10 MCP tools for AI coding assistants (Claude Code, Cursor, Cline) |
-| **Webhooks** | GitHub and GitLab push event handlers — trigger incremental updates automatically |
-| **Scheduler** | APScheduler background jobs — polling fallback, stale page decay, periodic re-sync |
+| **REST API** | FastAPI application with full CRUD for repos, pages (with version history), symbols, jobs, git analytics, dead code, decisions, graph intelligence |
+| **MCP Server** | 16 MCP tools for AI coding assistants (Claude Code, Cursor, Cline) |
+| **Webhooks** | GitHub and GitLab push event handlers — trigger sync jobs automatically on push |
+| **Scheduler** | APScheduler background jobs — polling fallback (auto-syncs diverged repos), stale page detection |
---
@@ -75,8 +75,8 @@ All endpoints are prefixed with `/api/`. When `REPOWISE_API_KEY` is set, every r
| `POST` | `/api/repos` | Register a new repository |
| `GET` | `/api/repos/{id}` | Get repository details and sync state |
| `PATCH` | `/api/repos/{id}` | Update repository settings (name, branch, provider) |
-| `POST` | `/api/repos/{id}/sync` | Trigger incremental sync (equivalent to `repowise update`) |
-| `POST` | `/api/repos/{id}/full-resync` | Trigger full re-generation (equivalent to `repowise init`) |
+| `POST` | `/api/repos/{id}/sync` | Re-index and regenerate only affected pages (graph, git, dead code, decisions + incremental page regen) |
+| `POST` | `/api/repos/{id}/full-resync` | Full re-generation of all pages from scratch (equivalent to `repowise init`) |
### Pages
@@ -110,6 +110,17 @@ Job progress events (`JobProgressEvent`) carry: `event` type, `file` currently b
|--------|------|-------------|
| `GET` | `/api/graph/{repo_id}` | Export dependency graph as nodes + edges (supports language and test filters) |
| `GET` | `/api/graph/{repo_id}/path` | Shortest dependency path between two modules |
+| `GET` | `/api/graph/{repo_id}/modules` | Collapsed directory-level module graph with doc coverage |
+| `GET` | `/api/graph/{repo_id}/ego` | N-hop neighborhood of a given node with git metadata |
+| `GET` | `/api/graph/{repo_id}/entry-points` | Subgraph reachable within 3 hops from entry-point nodes |
+| `GET` | `/api/graph/{repo_id}/dead-nodes` | High-confidence unreachable files with 1-hop neighbors |
+| `GET` | `/api/graph/{repo_id}/hot-files` | Most-committed files with 1-hop outgoing neighbors |
+| `GET` | `/api/graph/{repo_id}/nodes/search` | Full-text search over node IDs |
+| `GET` | `/api/graph/{repo_id}/communities` | List all communities with labels, cohesion scores, member counts |
+| `GET` | `/api/graph/{repo_id}/communities/{id}` | Community detail: members, neighboring communities, cross-edge counts |
+| `GET` | `/api/graph/{repo_id}/metrics` | Graph metrics with percentile ranks for any file or symbol |
+| `GET` | `/api/graph/{repo_id}/callers-callees` | Callers and callees for a symbol, with heritage support |
+| `GET` | `/api/graph/{repo_id}/execution-flows` | Top entry points with BFS call-path traces |
### Git Analytics
@@ -130,6 +141,16 @@ Job progress events (`JobProgressEvent`) carry: `event` type, `file` currently b
| `GET` | `/api/dead-code/{repo_id}/summary` | Summary stats (total findings, deletable lines, by kind) |
| `PATCH` | `/api/dead-code/{id}` | Update a finding's status: `resolved`, `acknowledged`, or `dismissed` |
+### Decisions
+
+| Method | Path | Description |
+|--------|------|-------------|
+| `GET` | `/api/repos/{id}/decisions` | List decision records (supports `status`, `source`, `tag`, `module` filters) |
+| `GET` | `/api/repos/{id}/decisions/health` | Decision health summary — active, proposed, stale counts, ungoverned hotspots |
+| `GET` | `/api/repos/{id}/decisions/{decisionId}` | Get a single decision record with full context |
+| `POST` | `/api/repos/{id}/decisions` | Create a decision record manually |
+| `PATCH` | `/api/repos/{id}/decisions/{decisionId}` | Update decision status (active, deprecated, superseded) |
+
### Search
| Method | Path | Description |
@@ -153,7 +174,7 @@ Job progress events (`JobProgressEvent`) carry: `event` type, `file` currently b
## MCP Server
-repowise exposes 10 MCP tools for AI coding assistants. Start the MCP server via:
+repowise exposes 16 MCP tools for AI coding assistants. Start the MCP server via:
```bash
repowise mcp # stdio transport (Claude Code, Cursor, Cline)
@@ -162,7 +183,7 @@ repowise mcp --transport sse # SSE transport on port 7338
| Tool | What It Answers | When to Call |
|------|----------------|-------------|
-| `get_overview` | Architecture summary, module map, entry points | First call when exploring an unfamiliar codebase |
+| `get_overview` | Architecture summary, module map, entry points, community summary | First call when exploring an unfamiliar codebase |
| `get_context(targets)` | Docs, ownership, history, decisions, freshness for files/modules/symbols | When you need to understand specific code before reading or modifying it |
| `get_risk(targets)` | Hotspot score, dependents, co-change partners, risk summary | Before modifying files — assess what could break |
| `get_why(query?)` | Architectural decisions, rationale, constraints | Before making architectural changes — understand existing intent |
@@ -170,6 +191,14 @@ repowise mcp --transport sse # SSE transport on port 7338
| `get_dependency_path(from, to)` | Connection path between two files/modules | When you need to understand how two things are connected |
| `get_dead_code` | Unused/unreachable code sorted by cleanup impact | Before cleanup tasks |
| `get_architecture_diagram` | Mermaid diagram for repo or module | For documentation or presentation |
+| `get_answer(question)` | One-call RAG with confidence gating and caching | First call on any code question |
+| `get_symbol(symbol_id)` | Source body, signature, docstring for a qualified symbol | When the question names a specific function or class |
+| `annotate_file(target, notes)` | Attach human-authored notes to a wiki page | Adding context that survives re-indexing |
+| `get_callers_callees(symbol_id)` | Callers, callees, and class hierarchy (extends/implements) | Understanding call relationships for any symbol |
+| `get_community(target)` | Community membership, cohesion, neighboring communities | Understanding module boundaries and refactoring safety |
+| `get_graph_metrics(target)` | PageRank/betweenness percentiles, degree, community label | Assessing file or symbol importance in the graph |
+| `get_execution_flows(top_n?)` | Entry point scoring with BFS call-path traces | Understanding how the codebase executes |
+| `update_decision_records(action)` | Create, update, list, or deprecate decision records | After architectural changes |
**Claude Code / Cursor / Cline setup** — add to your MCP config:
@@ -205,7 +234,7 @@ Register the webhook URL with GitHub or GitLab so `repowise update` runs automat
3. Set **Secret token** to the value of `REPOWISE_WEBHOOK_SECRET`
4. Enable **Push events**
-The server verifies HMAC-SHA256 signatures, deduplicates events (stored in the `webhook_events` table), and queues an incremental sync job via the scheduler.
+The server verifies HMAC-SHA256 signatures, deduplicates events (stored in the `webhook_events` table), and launches a background sync job that re-indexes the repo and regenerates only affected wiki pages.
---
@@ -215,9 +244,8 @@ The APScheduler instance manages the following recurring tasks:
| Job | Schedule | Description |
|-----|----------|-------------|
-| Stale page decay | Every 6 hours | Reduces confidence scores on pages whose source hash has changed |
-| Polling fallback | Every 15 minutes | Checks for new commits on repos without webhook integration |
-| Dead code re-analysis | Daily | Re-runs dead code analysis after large syncs |
+| Staleness check | Every 15 minutes | Finds stale/expired wiki pages and logs them for monitoring |
+| Polling fallback | Every 15 minutes | Compares git HEAD against `state.json` for all repos; enqueues and launches sync jobs for any that have diverged (catches missed webhooks) |
---
diff --git a/packages/server/src/repowise/server/__init__.py b/packages/server/src/repowise/server/__init__.py
index 5c0f44901..af5ac956b 100644
--- a/packages/server/src/repowise/server/__init__.py
+++ b/packages/server/src/repowise/server/__init__.py
@@ -7,4 +7,4 @@ Provides:
- Background job scheduler (APScheduler)
"""
-__version__ = "0.2.3"
+__version__ = "0.3.0"
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 14ef79f27..2741ae22d 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -46,6 +46,7 @@ from repowise.server.routers import (
security,
symbols,
webhooks,
+ workspace,
)
from repowise.server.scheduler import setup_scheduler
@@ -81,7 +82,27 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
Shutdown: dispose engine, stop scheduler, close vector store.
"""
# Database
+ # In workspace mode, prefer the primary repo's DB over the global default.
+ # This prevents the global ~/.repowise/wiki.db (which may contain stale
+ # repos from old test runs) from being used as the main DB.
db_url = resolve_db_url()
+ if not os.environ.get("REPOWISE_DB_URL") and not os.environ.get("REPOWISE_DATABASE_URL"):
+ try:
+ from pathlib import Path as _WsPath
+ from repowise.core.workspace.config import find_workspace_root, WorkspaceConfig
+
+ _ws_root = find_workspace_root()
+ if _ws_root is not None:
+ _ws_cfg = WorkspaceConfig.load(_ws_root)
+ _primary = _ws_cfg.get_primary()
+ _primary_path = _ws_root / (_primary.path if _primary else ".")
+ _primary_db = (_primary_path / ".repowise" / "wiki.db").resolve()
+ if _primary_db.exists():
+ db_url = f"sqlite+aiosqlite:///{_primary_db.as_posix()}"
+ logger.info("workspace_primary_db", extra={"db": str(_primary_db)})
+ except Exception:
+ pass # Fall back to default
+
engine = create_engine(db_url)
await init_db(engine)
session_factory = create_session_factory(engine)
@@ -118,18 +139,18 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
embedder = _build_embedder()
vector_store = InMemoryVectorStore(embedder=embedder)
- # Background scheduler
- scheduler = setup_scheduler(session_factory)
- scheduler.start()
-
- # Store on app state
+ # Store on app state (before scheduler, so scheduler can reference app_state)
app.state.engine = engine
app.state.session_factory = session_factory
app.state.fts = fts
app.state.vector_store = vector_store
- app.state.scheduler = scheduler
app.state.background_tasks: set = set() # Strong refs to prevent GC of asyncio tasks
+ # Background scheduler (pass app.state so polling can launch jobs)
+ scheduler = setup_scheduler(session_factory, app_state=app.state)
+ scheduler.start()
+ app.state.scheduler = scheduler
+
# Initialize chat tool state (bridges FastAPI state to MCP tool globals)
from repowise.server.chat_tools import init_tool_state
@@ -139,12 +160,99 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
vector_store=vector_store,
)
+ # Workspace detection — mirrors MCP _server.py:_detect_workspace()
+ app.state.workspace_config = None
+ app.state.workspace_root = None
+ app.state.cross_repo_enricher = None
+ app.state.workspace_sessions = {} # repo_id → session_factory
+ app.state.workspace_engines = [] # engines to dispose on shutdown
+
+ try:
+ from pathlib import Path as _Path
+
+ from repowise.core.workspace.config import (
+ WORKSPACE_DATA_DIR,
+ WorkspaceConfig,
+ find_workspace_root,
+ )
+
+ ws_root = find_workspace_root()
+ if ws_root is not None:
+ ws_config = WorkspaceConfig.load(ws_root)
+ app.state.workspace_config = ws_config
+ app.state.workspace_root = str(ws_root)
+
+ # Create per-repo DB engines so all workspace repos are accessible
+ # via the same REST API (sidebar, repo-specific pages, etc.)
+ import sqlite3 as _sqlite3
+
+ for repo_entry in ws_config.repos:
+ repo_path = (_Path(ws_root) / repo_entry.path).resolve()
+ repo_db = repo_path / ".repowise" / "wiki.db"
+ if not repo_db.exists():
+ continue
+ # Read repo_id from this DB
+ try:
+ conn = _sqlite3.connect(str(repo_db))
+ row = conn.execute("SELECT id FROM repositories LIMIT 1").fetchone()
+ conn.close()
+ if not row:
+ continue
+ repo_id = row[0]
+ except Exception:
+ continue
+
+ # Skip if this is the primary DB we already connected to
+ # (the main engine already serves this repo)
+ db_url_posix = repo_db.as_posix()
+ if db_url and db_url_posix in db_url.replace("\\", "/"):
+ continue
+
+ repo_engine = create_engine(f"sqlite+aiosqlite:///{db_url_posix}")
+ await init_db(repo_engine)
+ repo_sf = create_session_factory(repo_engine)
+ app.state.workspace_sessions[repo_id] = repo_sf
+ app.state.workspace_engines.append(repo_engine)
+
+ if app.state.workspace_sessions:
+ logger.info(
+ "workspace_repo_dbs_loaded",
+ extra={"count": len(app.state.workspace_sessions)},
+ )
+
+ from repowise.core.workspace.contracts import CONTRACTS_FILENAME
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ cross_repo_path = _Path(ws_root) / WORKSPACE_DATA_DIR / "cross_repo_edges.json"
+ contracts_path = _Path(ws_root) / WORKSPACE_DATA_DIR / CONTRACTS_FILENAME
+ enricher = CrossRepoEnricher(cross_repo_path, contracts_path=contracts_path)
+ if enricher.has_data or enricher.has_contract_data:
+ app.state.cross_repo_enricher = enricher
+ logger.info(
+ "repowise_workspace_detected",
+ extra={
+ "repos": len(ws_config.repos),
+ "co_changes": len(getattr(enricher, "_co_changes", [])),
+ "contract_links": len(getattr(enricher, "_contract_links", [])),
+ },
+ )
+ else:
+ logger.info("repowise_workspace_detected", extra={"repos": len(ws_config.repos)})
+ except Exception:
+ logger.debug("Workspace detection skipped", exc_info=True)
+
logger.info("repowise_server_started", extra={"version": __version__})
yield
# Shutdown
scheduler.shutdown(wait=False)
await vector_store.close()
+ # Dispose workspace repo engines first
+ for ws_engine in getattr(app.state, "workspace_engines", []):
+ try:
+ await ws_engine.dispose()
+ except Exception:
+ pass
await engine.dispose()
logger.info("repowise_server_stopped")
@@ -195,5 +303,6 @@ def create_app() -> FastAPI:
app.include_router(security.router)
app.include_router(blast_radius.router)
app.include_router(knowledge_map.router)
+ app.include_router(workspace.router)
return app
diff --git a/packages/server/src/repowise/server/chat_tools.py b/packages/server/src/repowise/server/chat_tools.py
index 53dde5220..2580c5105 100644
--- a/packages/server/src/repowise/server/chat_tools.py
+++ b/packages/server/src/repowise/server/chat_tools.py
@@ -1,6 +1,6 @@
"""Chat tool registry — single source of truth for tool schemas and execution.
-Imports the 10 MCP tool functions directly and exposes them as a callable registry
+Imports the 7 MCP tool functions directly and exposes them as a callable registry
for the agentic chat loop. Also provides OpenAI-format tool definitions for the LLM.
"""
@@ -60,9 +60,13 @@ _TOOL_SCHEMAS: list[dict[str, Any]] = [
"type": "array",
"items": {
"type": "string",
- "enum": ["docs", "ownership", "last_change", "decisions", "freshness"],
+ "enum": [
+ "docs", "full_doc", "ownership", "last_change",
+ "decisions", "freshness", "source", "callers",
+ "callees", "metrics", "community",
+ ],
},
- "description": "Subset of fields to include. Default: all.",
+ "description": "Data blocks to include. Default: docs + freshness.",
},
"repo": {"type": "string", "description": "Repository identifier."},
},
@@ -130,20 +134,6 @@ _TOOL_SCHEMAS: list[dict[str, Any]] = [
},
"artifact_type": "search_results",
},
- {
- "name": "get_dependency_path",
- "description": "Find the shortest dependency path between two files or modules. When no direct path exists, returns visual context: nearest common ancestors, shared neighbors, community analysis, and bridge suggestions.",
- "parameters": {
- "type": "object",
- "properties": {
- "source": {"type": "string", "description": "Source file or module path."},
- "target": {"type": "string", "description": "Target file or module path."},
- "repo": {"type": "string", "description": "Repository identifier."},
- },
- "required": ["source", "target"],
- },
- "artifact_type": "graph",
- },
{
"name": "get_dead_code",
"description": "Get a tiered refactor plan for dead code. Returns findings in high/medium/low confidence tiers with per-directory rollups, ownership hotspots, and impact estimates. Use group_by for rollup views, tier to focus on one band.",
@@ -188,39 +178,14 @@ _TOOL_SCHEMAS: list[dict[str, Any]] = [
},
"artifact_type": "dead_code",
},
- {
- "name": "get_architecture_diagram",
- "description": "Generate a Mermaid architecture diagram for the repo, a module, or a file.",
- "parameters": {
- "type": "object",
- "properties": {
- "scope": {
- "type": "string",
- "description": "Scope: repo, module, or file.",
- "default": "repo",
- },
- "path": {"type": "string", "description": "Required for module/file scope."},
- "diagram_type": {
- "type": "string",
- "description": "Diagram type: auto, flowchart, class, sequence.",
- "default": "auto",
- },
- "repo": {"type": "string", "description": "Repository identifier."},
- },
- "required": [],
- },
- "artifact_type": "diagram",
- },
]
def _build_registry() -> dict[str, ToolDef]:
"""Build the tool registry by importing MCP tool functions."""
from repowise.server.mcp_server import (
- get_architecture_diagram,
get_context,
get_dead_code,
- get_dependency_path,
get_overview,
get_risk,
get_why,
@@ -233,9 +198,7 @@ def _build_registry() -> dict[str, ToolDef]:
"get_risk": get_risk,
"get_why": get_why,
"search_codebase": search_codebase,
- "get_dependency_path": get_dependency_path,
"get_dead_code": get_dead_code,
- "get_architecture_diagram": get_architecture_diagram,
}
registry: dict[str, ToolDef] = {}
diff --git a/packages/server/src/repowise/server/deps.py b/packages/server/src/repowise/server/deps.py
index 6b90dc20a..831b6679b 100644
--- a/packages/server/src/repowise/server/deps.py
+++ b/packages/server/src/repowise/server/deps.py
@@ -37,8 +37,22 @@ if _API_KEY is None and _REPOWISE_HOST in ("0.0.0.0", "::"):
async def get_db_session(request: Request) -> AsyncGenerator[AsyncSession, None]:
- """Yield an async DB session with auto-commit on success, rollback on error."""
+ """Yield an async DB session with auto-commit on success, rollback on error.
+
+ In workspace mode, routes to the correct repo's DB based on the
+ ``repo_id`` path parameter when a matching session factory exists.
+ """
factory = request.app.state.session_factory
+
+ # In workspace mode, check if the request targets a specific repo DB
+ # Check both path params (e.g. /api/repos/{repo_id}/stats) and
+ # query params (e.g. /api/pages?repo_id=xxx) for the repo_id
+ repo_id = request.path_params.get("repo_id") or request.query_params.get("repo_id")
+ if repo_id:
+ ws_sessions = getattr(request.app.state, "workspace_sessions", None)
+ if ws_sessions and repo_id in ws_sessions:
+ factory = ws_sessions[repo_id]
+
async with get_session(factory) as session:
yield session
@@ -53,6 +67,16 @@ async def get_fts(request: Request):
return request.app.state.fts
+async def get_workspace_config(request: Request):
+ """Return WorkspaceConfig from app state, or None in single-repo mode."""
+ return getattr(request.app.state, "workspace_config", None)
+
+
+async def get_cross_repo_enricher(request: Request):
+ """Return CrossRepoEnricher from app state, or None."""
+ return getattr(request.app.state, "cross_repo_enricher", None)
+
+
async def verify_api_key(
auth: str | None = Security(_header_scheme),
) -> None:
diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.py
index 787fd2344..42ef66465 100644
--- a/packages/server/src/repowise/server/job_executor.py
+++ b/packages/server/src/repowise/server/job_executor.py
@@ -195,13 +195,31 @@ async def execute_job(job_id: str, app_state: Any) -> None:
progress=progress,
)
+ # ---- Incremental page regeneration for sync mode ------------------
+ # Sync runs run_pipeline(generate_docs=False) for the full index,
+ # then regenerates only the wiki pages affected by recent changes.
+ # This keeps docs fresh without the cost of a full re-index.
+ incremental_pages: list = []
+ if not is_full_resync and llm_client is not None:
+ incremental_pages = await _incremental_page_regen(
+ Path(repo_path), result, llm_client, config, progress,
+ )
+
# ---- Persist results -----------------------------------------------
async with get_session(session_factory) as session:
await persist_pipeline_result(result, session, repo_id)
+ # Persist incrementally regenerated pages
+ if incremental_pages:
+ from repowise.core.persistence import upsert_page_from_generated
+
+ for page in incremental_pages:
+ await upsert_page_from_generated(session, page, repo_id)
+
# FTS indexing runs after session closes to avoid SQLite write conflicts
- if fts is not None and result.generated_pages:
- for page in result.generated_pages:
+ all_pages = (result.generated_pages or []) + incremental_pages
+ if fts is not None and all_pages:
+ for page in all_pages:
await fts.index(page.page_id, page.title, page.content)
# ---- Mark completed ------------------------------------------------
@@ -210,8 +228,9 @@ async def execute_job(job_id: str, app_state: Any) -> None:
await progress.drain_and_stop()
elapsed = time.monotonic() - start
- total_input = sum(p.input_tokens for p in (result.generated_pages or []))
- total_output = sum(p.output_tokens for p in (result.generated_pages or []))
+ total_input = sum(p.input_tokens for p in all_pages)
+ total_output = sum(p.output_tokens for p in all_pages)
+ pages_generated = len(all_pages)
async with get_session(session_factory) as session:
job = await get_generation_job(session, job_id)
@@ -224,7 +243,7 @@ async def execute_job(job_id: str, app_state: Any) -> None:
"elapsed_seconds": round(elapsed, 1),
"file_count": result.file_count,
"symbol_count": result.symbol_count,
- "pages_generated": len(result.generated_pages) if result.generated_pages else 0,
+ "pages_generated": pages_generated,
}
)
if job is not None:
@@ -234,17 +253,48 @@ async def execute_job(job_id: str, app_state: Any) -> None:
session,
job_id,
"completed",
- completed_pages=len(result.generated_pages) if result.generated_pages else result.file_count,
- total_pages=len(result.generated_pages) if result.generated_pages else result.file_count,
+ completed_pages=pages_generated if pages_generated else result.file_count,
+ total_pages=pages_generated if pages_generated else result.file_count,
)
+ # Update state.json so CLI incremental updates know the new baseline
+ try:
+ _state_path = Path(repo_path) / ".repowise" / "state.json"
+ import subprocess as _sp
+
+ _head_result = _sp.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=repo_path,
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if _head_result.returncode == 0:
+ _head_sha = _head_result.stdout.strip()
+ _state_data: dict = {}
+ if _state_path.is_file():
+ _state_data = json.loads(_state_path.read_text(encoding="utf-8"))
+ _state_data["last_sync_commit"] = _head_sha
+ _state_path.parent.mkdir(parents=True, exist_ok=True)
+ _state_path.write_text(json.dumps(_state_data, indent=2), encoding="utf-8")
+ except Exception:
+ logger.debug("state_json_update_failed", job_id=job_id, exc_info=True)
+
+ # Hot-reload cross-repo enricher if available (workspace mode)
+ try:
+ enricher = getattr(app_state, "cross_repo_enricher", None)
+ if enricher is not None and hasattr(enricher, "reload"):
+ enricher.reload()
+ except Exception:
+ logger.debug("enricher_reload_failed", job_id=job_id, exc_info=True)
+
logger.info(
"job_completed",
job_id=job_id,
elapsed=round(elapsed, 1),
files=result.file_count,
symbols=result.symbol_count,
- pages=len(result.generated_pages) if result.generated_pages else 0,
+ pages=pages_generated,
)
except Exception as exc:
@@ -266,3 +316,107 @@ async def execute_job(job_id: str, app_state: Any) -> None:
)
except Exception:
logger.exception("job_status_update_failed", job_id=job_id)
+
+
+# ---------------------------------------------------------------------------
+# Incremental page regeneration helper
+# ---------------------------------------------------------------------------
+
+
+async def _incremental_page_regen(
+ repo_path: Path,
+ result: Any,
+ llm_client: Any,
+ job_config: dict,
+ progress: Any | None,
+) -> list:
+ """Regenerate only wiki pages affected by recent changes.
+
+ Uses the graph from the just-completed pipeline run + git diff to detect
+ which pages need updating. Returns a list of GeneratedPage objects (may
+ be empty if nothing changed or no base ref is available).
+ """
+ try:
+ # Read base ref from state.json (the commit we last synced to)
+ state_path = repo_path / ".repowise" / "state.json"
+ base_ref: str | None = None
+ if state_path.is_file():
+ state = json.loads(state_path.read_text(encoding="utf-8"))
+ base_ref = state.get("last_sync_commit")
+
+ # Webhook jobs may carry explicit before/after refs
+ if not base_ref:
+ base_ref = job_config.get("before")
+
+ if not base_ref:
+ logger.info("incremental_page_regen_skipped", reason="no_base_ref")
+ return []
+
+ import subprocess as _sp
+
+ head_result = _sp.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=str(repo_path),
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if head_result.returncode != 0:
+ return []
+ head = head_result.stdout.strip()
+
+ if head == base_ref:
+ logger.info("incremental_page_regen_skipped", reason="no_new_commits")
+ return []
+
+ from repowise.core.ingestion import ChangeDetector
+ from repowise.core.ingestion.change_detector import compute_adaptive_budget
+
+ detector = ChangeDetector(repo_path)
+ file_diffs = detector.get_changed_files(base_ref, head)
+ if not file_diffs:
+ return []
+
+ cascade_budget = compute_adaptive_budget(file_diffs, result.file_count)
+ affected = detector.get_affected_pages(file_diffs, result.graph_builder.graph(), cascade_budget)
+
+ if not affected.regenerate:
+ logger.info("incremental_page_regen_skipped", reason="no_affected_pages")
+ return []
+
+ logger.info(
+ "incremental_page_regen_start",
+ changed_files=len(file_diffs),
+ affected_pages=len(affected.regenerate),
+ cascade_budget=cascade_budget,
+ )
+
+ if progress:
+ progress.on_phase_start("generation", len(affected.regenerate))
+
+ # Filter parsed files to only affected ones
+ regen_set = set(affected.regenerate)
+ affected_parsed = [pf for pf in result.parsed_files if pf.file_info.path in regen_set]
+ affected_source = {p: s for p, s in result.source_map.items() if p in regen_set}
+
+ from repowise.core.generation import ContextAssembler, GenerationConfig, PageGenerator
+
+ config = GenerationConfig()
+ assembler = ContextAssembler(config)
+ generator = PageGenerator(llm_client, assembler, config)
+
+ pages = await generator.generate_all(
+ affected_parsed,
+ affected_source,
+ result.graph_builder,
+ result.repo_structure,
+ result.repo_name,
+ git_meta_map=result.git_meta_map,
+ )
+
+ logger.info("incremental_page_regen_done", pages=len(pages))
+ return pages
+
+ except Exception as exc:
+ logger.warning("incremental_page_regen_failed", error=str(exc))
+ return []
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index ac7beb339..438e98266 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -1,4 +1,4 @@
-"""repowise MCP Server — 10 tools for AI coding assistants.
+"""repowise MCP Server — 7 tools for AI coding assistants.
Exposes the full repowise wiki as queryable tools via the MCP protocol.
Supports both stdio transport (Claude Code, Cursor, Cline) and SSE transport
@@ -27,20 +27,15 @@ from repowise.server.mcp_server._server import (
mcp,
run_mcp,
)
-from repowise.server.mcp_server.tool_annotate import annotate_file
+from repowise.server.mcp_server._graph_utils import ( # used by routers/graph.py
+ build_visual_context as _build_visual_context,
+)
from repowise.server.mcp_server.tool_answer import get_answer
from repowise.server.mcp_server.tool_context import get_context
from repowise.server.mcp_server.tool_dead_code import get_dead_code
-from repowise.server.mcp_server.tool_decision_records import update_decision_records
-from repowise.server.mcp_server.tool_dependency import (
- _build_visual_context,
- get_dependency_path,
-)
-from repowise.server.mcp_server.tool_diagram import get_architecture_diagram
from repowise.server.mcp_server.tool_overview import get_overview
from repowise.server.mcp_server.tool_risk import get_risk
from repowise.server.mcp_server.tool_search import search_codebase
-from repowise.server.mcp_server.tool_symbol import get_symbol
from repowise.server.mcp_server.tool_why import get_why
# ---------------------------------------------------------------------------
@@ -63,6 +58,9 @@ _STATE_NAMES = frozenset(
"_fts",
"_repo_path",
"_vector_store_ready",
+ "_registry",
+ "_workspace_root",
+ "_cross_repo_enricher",
}
)
@@ -94,16 +92,12 @@ __all__ = [
"_is_path",
"create_mcp_server",
"get_answer",
- "get_architecture_diagram",
"get_context",
"get_dead_code",
- "get_dependency_path",
"get_overview",
"get_risk",
- "get_symbol",
"get_why",
"mcp",
"run_mcp",
"search_codebase",
- "update_decision_records",
]
diff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.py
new file mode 100644
index 000000000..9179157dc
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py
@@ -0,0 +1,301 @@
+"""Cross-repo enrichment for MCP tool responses.
+
+Loaded once at MCP lifespan start from ``.repowise-workspace/cross_repo_edges.json``.
+Provides O(1) in-memory lookups — never blocks or slows MCP queries.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections import defaultdict
+from pathlib import Path
+from typing import Any
+
+_log = logging.getLogger("repowise.mcp.enrichment")
+
+
+class CrossRepoEnricher:
+ """In-memory lookup for cross-repo signals."""
+
+ def __init__(
+ self,
+ data_path: Path,
+ contracts_path: Path | None = None,
+ ) -> None:
+ self._co_changes: list[dict] = []
+ self._package_deps: list[dict] = []
+ self._repo_summaries: dict[str, dict] = {}
+
+ # Pre-built indexes
+ self._co_change_index: dict[tuple[str, str], list[dict]] = defaultdict(list)
+ self._consumer_index: dict[tuple[str, str], list[dict]] = defaultdict(list)
+ self._package_dep_index: dict[str, list[dict]] = defaultdict(list)
+ self._package_dep_reverse: dict[str, list[str]] = defaultdict(list)
+
+ # Contract indexes (Phase 4)
+ self._contracts: list[dict] = []
+ self._contract_links: list[dict] = []
+ self._contract_provider_index: dict[tuple[str, str], list[dict]] = defaultdict(list)
+ self._contract_consumer_index: dict[tuple[str, str], list[dict]] = defaultdict(list)
+
+ self._data_path = data_path
+ self._contracts_path = contracts_path
+
+ self._load(data_path)
+ if contracts_path is not None:
+ self._load_contracts(contracts_path)
+
+ def _load(self, data_path: Path) -> None:
+ """Parse JSON and build indexes."""
+ if not data_path.is_file():
+ _log.debug("No cross-repo data at %s", data_path)
+ return
+
+ try:
+ data = json.loads(data_path.read_text(encoding="utf-8"))
+ except Exception:
+ _log.warning("Failed to parse cross-repo data at %s", data_path, exc_info=True)
+ return
+
+ self._co_changes = data.get("co_changes", [])
+ self._package_deps = data.get("package_deps", [])
+ self._repo_summaries = data.get("repo_summaries", {})
+
+ # Build co-change index: (repo, file) -> list of partner dicts
+ for cc in self._co_changes:
+ try:
+ src_key = (cc["source_repo"], cc["source_file"])
+ tgt_key = (cc["target_repo"], cc["target_file"])
+ except KeyError:
+ _log.debug("Skipping malformed co-change entry: %s", cc)
+ continue
+
+ partner_for_src = {
+ "repo": cc.get("target_repo", ""),
+ "file": cc.get("target_file", ""),
+ "strength": cc.get("strength", 0),
+ "frequency": cc.get("frequency", 0),
+ "last_date": cc.get("last_date", ""),
+ }
+ partner_for_tgt = {
+ "repo": cc.get("source_repo", ""),
+ "file": cc.get("source_file", ""),
+ "strength": cc.get("strength", 0),
+ "frequency": cc.get("frequency", 0),
+ "last_date": cc.get("last_date", ""),
+ }
+
+ self._co_change_index[src_key].append(partner_for_src)
+ self._co_change_index[tgt_key].append(partner_for_tgt)
+
+ # Consumer index: who is affected BY changes to this file
+ self._consumer_index[src_key].append(partner_for_src)
+ self._consumer_index[tgt_key].append(partner_for_tgt)
+
+ # Sort each index entry by strength descending
+ for key in self._co_change_index:
+ self._co_change_index[key].sort(key=lambda x: -x["strength"])
+ for key in self._consumer_index:
+ self._consumer_index[key].sort(key=lambda x: -x["strength"])
+
+ # Build package dep indexes
+ for pd in self._package_deps:
+ try:
+ src_repo = pd["source_repo"]
+ tgt_repo = pd["target_repo"]
+ except KeyError:
+ _log.debug("Skipping malformed package dep entry: %s", pd)
+ continue
+ self._package_dep_index[src_repo].append({
+ "target_repo": tgt_repo,
+ "source_manifest": pd.get("source_manifest", ""),
+ "kind": pd.get("kind", ""),
+ })
+ # Reverse: who depends on target_repo
+ self._package_dep_reverse[tgt_repo].append(src_repo)
+
+ _log.debug(
+ "Cross-repo enricher loaded: %d co-change edges, %d package deps",
+ len(self._co_changes),
+ len(self._package_deps),
+ )
+
+ def _load_contracts(self, contracts_path: Path) -> None:
+ """Parse ``contracts.json`` and build lookup indexes."""
+ if not contracts_path.is_file():
+ _log.debug("No contract data at %s", contracts_path)
+ return
+
+ try:
+ data = json.loads(contracts_path.read_text(encoding="utf-8"))
+ except Exception:
+ _log.warning(
+ "Failed to parse contract data at %s", contracts_path, exc_info=True
+ )
+ return
+
+ self._contracts = data.get("contracts", [])
+ self._contract_links = data.get("contract_links", [])
+
+ for link in self._contract_links:
+ try:
+ provider_key = (link["provider_repo"], link["provider_file"])
+ consumer_key = (link["consumer_repo"], link["consumer_file"])
+ except KeyError:
+ _log.debug("Skipping malformed contract link: %s", link)
+ continue
+ self._contract_provider_index[provider_key].append(link)
+ self._contract_consumer_index[consumer_key].append(link)
+
+ _log.debug(
+ "Contract enricher loaded: %d contracts, %d links",
+ len(self._contracts),
+ len(self._contract_links),
+ )
+
+ def reload(self) -> None:
+ """Re-read JSON files from disk and rebuild all indexes.
+
+ Call after cross-repo analysis writes new data so the running
+ server serves fresh results without a restart.
+ """
+ # Reset all state
+ self._co_changes = []
+ self._package_deps = []
+ self._repo_summaries = {}
+ self._co_change_index = defaultdict(list)
+ self._consumer_index = defaultdict(list)
+ self._package_dep_index = defaultdict(list)
+ self._package_dep_reverse = defaultdict(list)
+ self._contracts = []
+ self._contract_links = []
+ self._contract_provider_index = defaultdict(list)
+ self._contract_consumer_index = defaultdict(list)
+
+ self._load(self._data_path)
+ if self._contracts_path is not None:
+ self._load_contracts(self._contracts_path)
+
+ _log.info(
+ "Cross-repo enricher reloaded: %d co-change edges, %d package deps, %d contract links",
+ len(self._co_changes),
+ len(self._package_deps),
+ len(self._contract_links),
+ )
+
+ @property
+ def has_data(self) -> bool:
+ """True if any cross-repo signals are available."""
+ return bool(self._co_changes or self._package_deps or self._contract_links)
+
+ @property
+ def has_contract_data(self) -> bool:
+ """True if contract links are available."""
+ return bool(self._contract_links)
+
+ def get_cross_repo_partners(
+ self, repo_alias: str, file_path: str
+ ) -> list[dict]:
+ """Return cross-repo co-change partners for a file.
+
+ Each dict: ``{repo, file, strength, frequency, last_date}``.
+ """
+ return self._co_change_index.get((repo_alias, file_path), [])
+
+ def get_package_deps(self, repo_alias: str) -> list[dict]:
+ """Return package dependencies where *repo_alias* depends on other repos.
+
+ Each dict: ``{target_repo, source_manifest, kind}``.
+ """
+ return self._package_dep_index.get(repo_alias, [])
+
+ def get_repos_depending_on(self, repo_alias: str) -> list[str]:
+ """Return repo aliases that depend on *repo_alias* via package manifests."""
+ return self._package_dep_reverse.get(repo_alias, [])
+
+ def get_cross_repo_summary(self) -> dict:
+ """High-level cross-repo stats for the overview footer."""
+ # Count repo-to-repo connections
+ repo_pairs: dict[tuple[str, str], int] = defaultdict(int)
+ for cc in self._co_changes:
+ pair = tuple(sorted([cc["source_repo"], cc["target_repo"]]))
+ repo_pairs[pair] += 1 # type: ignore[index]
+ for pd in self._package_deps:
+ pair = tuple(sorted([pd["source_repo"], pd["target_repo"]]))
+ repo_pairs[pair] += 1 # type: ignore[index]
+
+ top_connections = sorted(
+ [
+ {"repos": list(pair), "edge_count": count}
+ for pair, count in repo_pairs.items()
+ ],
+ key=lambda x: -x["edge_count"],
+ )[:5]
+
+ return {
+ "co_change_count": len(self._co_changes),
+ "package_dep_count": len(self._package_deps),
+ "top_connections": top_connections,
+ }
+
+ def has_cross_repo_consumers(
+ self, repo_alias: str, file_path: str
+ ) -> list[dict]:
+ """Return files in OTHER repos that co-change with this file.
+
+ Each dict: ``{repo, file, strength}``.
+ """
+ return self._consumer_index.get((repo_alias, file_path), [])
+
+ def get_affected_repos(
+ self, repo_alias: str, file_path: str
+ ) -> list[str]:
+ """Return repo aliases that may be impacted by changes to this file.
+
+ Combines co-change partners + package dep consumers + contract links.
+ """
+ repos: set[str] = set()
+
+ # From co-change partners
+ for partner in self._co_change_index.get((repo_alias, file_path), []):
+ repos.add(partner["repo"])
+
+ # From package deps: repos that depend on this repo
+ for dep_repo in self._package_dep_reverse.get(repo_alias, []):
+ repos.add(dep_repo)
+
+ # From contract links: repos that consume APIs this file provides
+ for link in self._contract_provider_index.get((repo_alias, file_path), []):
+ repos.add(link["consumer_repo"])
+
+ repos.discard(repo_alias)
+ return sorted(repos)
+
+ # ------------------------------------------------------------------
+ # Contract queries (Phase 4)
+ # ------------------------------------------------------------------
+
+ def get_contract_links_as_provider(
+ self, repo_alias: str, file_path: str
+ ) -> list[dict]:
+ """Contract links where this file is the provider (has consumers)."""
+ return self._contract_provider_index.get((repo_alias, file_path), [])
+
+ def get_contract_links_as_consumer(
+ self, repo_alias: str, file_path: str
+ ) -> list[dict]:
+ """Contract links where this file is the consumer (depends on providers)."""
+ return self._contract_consumer_index.get((repo_alias, file_path), [])
+
+ def get_contract_summary(self) -> dict:
+ """High-level contract stats for the overview footer."""
+ by_type: dict[str, int] = defaultdict(int)
+ for c in self._contracts:
+ by_type[c.get("contract_type", "unknown")] += 1
+
+ return {
+ "total_contracts": len(self._contracts),
+ "total_links": len(self._contract_links),
+ "by_type": dict(by_type),
+ }
diff --git a/packages/server/src/repowise/server/mcp_server/_graph_utils.py b/packages/server/src/repowise/server/mcp_server/_graph_utils.py
new file mode 100644
index 000000000..b82e38a6b
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_graph_utils.py
@@ -0,0 +1,268 @@
+"""Shared graph query utilities used by both MCP tools and REST routers.
+
+This module avoids duplicating BFS trace logic and community-meta parsing
+across `tool_flows.py` and `routers/graph.py`.
+"""
+
+from __future__ import annotations
+
+import json
+from collections import deque
+from typing import Any
+
+from repowise.core.persistence.crud import (
+ get_graph_edges_for_node,
+ get_graph_nodes_by_ids,
+)
+from repowise.core.persistence.models import GraphNode
+
+
+def parse_community_meta(node: GraphNode) -> dict[str, Any]:
+ """Safely parse ``community_meta_json`` from a GraphNode."""
+ try:
+ return json.loads(node.community_meta_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ return {}
+
+
+def community_label(node: GraphNode) -> str:
+ """Extract human-readable community label, falling back to 'cluster_N'."""
+ meta = parse_community_meta(node)
+ return meta.get("label") or f"cluster_{node.community_id}"
+
+
+def community_cohesion(node: GraphNode) -> float:
+ """Extract cohesion score from community_meta_json."""
+ meta = parse_community_meta(node)
+ return float(meta.get("cohesion", 0.0) or 0.0)
+
+
+def entry_point_score(node: GraphNode) -> float:
+ """Extract entry_point_score from community_meta_json (symbol nodes only)."""
+ meta = parse_community_meta(node)
+ return float(meta.get("entry_point_score", 0.0) or 0.0)
+
+
+def percentile_rank(value: float, all_values: list[float]) -> int:
+ """Compute the percentile rank (0–100) of *value* within *all_values*."""
+ if not all_values:
+ return 0
+ count_below = sum(1 for v in all_values if v < value)
+ return round(100.0 * count_below / len(all_values))
+
+
+async def bfs_trace(
+ session: Any,
+ repo_id: str,
+ entry_id: str,
+ max_depth: int,
+ node_cache: dict[str, GraphNode] | None = None,
+) -> list[str]:
+ """BFS trace from *entry_id* following ``calls`` edges.
+
+ Returns an ordered list of symbol IDs in the trace. Uses greedy
+ successor ordering (highest confidence first for the primary path)
+ and a visited set for cycle safety.
+ """
+ if node_cache is None:
+ node_cache = {}
+
+ trace: list[str] = [entry_id]
+ visited: set[str] = {entry_id}
+ queue: deque[tuple[str, int]] = deque([(entry_id, 0)])
+
+ while queue:
+ current, depth = queue.popleft()
+ if depth >= max_depth:
+ continue
+
+ edges = await get_graph_edges_for_node(
+ session,
+ repo_id,
+ current,
+ direction="callees",
+ edge_types=["calls"],
+ limit=20,
+ )
+
+ successors: list[tuple[str, float]] = []
+ for e in edges:
+ if e.target_node_id not in visited:
+ successors.append((e.target_node_id, e.confidence or 0.0))
+
+ successors.sort(key=lambda x: -x[1])
+
+ for target_id, _ in successors:
+ if target_id in visited:
+ continue
+ visited.add(target_id)
+ trace.append(target_id)
+ queue.append((target_id, depth + 1))
+
+ return trace
+
+
+async def resolve_trace_communities(
+ session: Any,
+ repo_id: str,
+ trace: list[str],
+ node_cache: dict[str, GraphNode],
+) -> tuple[list[int], bool]:
+ """Resolve community IDs for trace nodes.
+
+ Returns ``(communities_visited, crosses_community)``.
+ """
+ missing = [nid for nid in trace if nid not in node_cache]
+ if missing:
+ batch = await get_graph_nodes_by_ids(session, repo_id, missing)
+ node_cache.update(batch)
+
+ communities_visited: list[int] = []
+ seen: set[int] = set()
+ for nid in trace:
+ n = node_cache.get(nid)
+ cid = n.community_id if n else 0
+ if cid is not None and cid not in seen:
+ seen.add(cid)
+ communities_visited.append(cid)
+
+ return communities_visited, len(communities_visited) > 1
+
+
+def build_visual_context(
+ graph: Any,
+ source: str,
+ target: str,
+ nodes: list,
+ nx: Any,
+) -> dict:
+ """Build diagnostic context when no directed path exists.
+
+ Used by the REST API router (routers/graph.py) for dependency path queries.
+ Moved here from tool_dependency.py to avoid importing the @mcp.tool()-decorated
+ module just for this helper.
+ """
+ node_meta = {n.node_id: n for n in nodes}
+ context: dict[str, Any] = {}
+
+ # --- Reverse path check ---
+ try:
+ rev_path = nx.shortest_path(graph, target, source)
+ context["reverse_path"] = {
+ "exists": True,
+ "path": rev_path,
+ "distance": len(rev_path) - 1,
+ "note": f"A path exists in the reverse direction ({target} -> {source}). "
+ "The dependency flows the other way.",
+ }
+ except nx.NetworkXNoPath:
+ context["reverse_path"] = {"exists": False}
+
+ # --- Nearest common ancestors (via undirected graph) ---
+ undirected = graph.to_undirected()
+ source_reachable = set(nx.single_source_shortest_path_length(undirected, source))
+ target_reachable = set(nx.single_source_shortest_path_length(undirected, target))
+ common = source_reachable & target_reachable
+ common.discard(source)
+ common.discard(target)
+
+ if common:
+ source_dist = nx.single_source_shortest_path_length(undirected, source)
+ target_dist = nx.single_source_shortest_path_length(undirected, target)
+ scored = [(node, source_dist[node] + target_dist[node]) for node in common]
+ scored.sort(key=lambda x: x[1])
+ context["nearest_common_ancestors"] = [
+ {
+ "node": node,
+ "distance_from_source": source_dist[node],
+ "distance_from_target": target_dist[node],
+ }
+ for node, _ in scored[:5]
+ ]
+ else:
+ context["nearest_common_ancestors"] = []
+
+ # --- Shared neighbors (direct) ---
+ source_neighbors = set(graph.predecessors(source)) | set(graph.successors(source))
+ target_neighbors = set(graph.predecessors(target)) | set(graph.successors(target))
+ shared = source_neighbors & target_neighbors
+ context["shared_neighbors"] = sorted(shared) if shared else []
+
+ # --- Community analysis ---
+ src_meta = node_meta.get(source)
+ tgt_meta = node_meta.get(target)
+ src_community = src_meta.community_id if src_meta else None
+ tgt_community = tgt_meta.community_id if tgt_meta else None
+
+ context["community"] = {
+ "source_community": src_community,
+ "target_community": tgt_community,
+ "same_community": src_community is not None and src_community == tgt_community,
+ }
+
+ # --- Bridge suggestions ---
+ if src_community is not None and tgt_community is not None and src_community != tgt_community:
+ bridge_nodes = []
+ nodes_by_community: dict[int, set[str]] = {}
+ for n in nodes:
+ nodes_by_community.setdefault(n.community_id, set()).add(n.node_id)
+
+ src_community_nodes = nodes_by_community.get(src_community, set())
+ tgt_community_nodes = nodes_by_community.get(tgt_community, set())
+
+ for node_id in graph.nodes():
+ neighbors = set(graph.predecessors(node_id)) | set(graph.successors(node_id))
+ touches_src = bool(neighbors & src_community_nodes)
+ touches_tgt = bool(neighbors & tgt_community_nodes)
+ if touches_src and touches_tgt:
+ meta = node_meta.get(node_id)
+ bridge_nodes.append({
+ "node": node_id,
+ "pagerank": meta.pagerank if meta else 0.0,
+ })
+ bridge_nodes.sort(key=lambda x: x["pagerank"], reverse=True)
+ context["bridge_suggestions"] = bridge_nodes[:5]
+ else:
+ context["bridge_suggestions"] = []
+
+ # --- Connectivity summary ---
+ components = list(nx.weakly_connected_components(graph))
+ src_comp = next((c for c in components if source in c), set())
+ tgt_comp = next((c for c in components if target in c), set())
+ actually_disconnected = src_comp != tgt_comp
+
+ if actually_disconnected:
+ context["disconnected"] = True
+ context["source_component_size"] = len(src_comp)
+ context["target_component_size"] = len(tgt_comp)
+ context["suggestion"] = (
+ "These nodes are in completely separate dependency clusters with "
+ "no shared connections. Look for shared configuration files, API "
+ "contracts, or event buses that should bridge them."
+ )
+ else:
+ context["disconnected"] = False
+ if context["nearest_common_ancestors"]:
+ top = context["nearest_common_ancestors"][0]["node"]
+ context["suggestion"] = (
+ f"No direct path, but both nodes connect through '{top}'. "
+ "This shared dependency may be the architectural bridge point."
+ )
+ elif context["shared_neighbors"]:
+ context["suggestion"] = (
+ f"No direct path, but they share neighbor(s): "
+ f"{', '.join(context['shared_neighbors'])}. "
+ "These shared files may serve as the missing link."
+ )
+ elif context["reverse_path"].get("exists"):
+ context["suggestion"] = (
+ "No direct path in this direction, but a reverse path exists. "
+ "The dependency flows the other way."
+ )
+ else:
+ context["suggestion"] = (
+ "These nodes are in the same cluster but have no direct "
+ "or reverse dependency. Check for indirect connections."
+ )
+
+ return context
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index d088f78fe..458f9a6da 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
import os
import os.path
+from pathlib import Path
from typing import Any
from sqlalchemy import select
@@ -13,6 +14,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.persistence.models import (
Repository,
)
+from repowise.server.mcp_server import _state
# ---------------------------------------------------------------------------
# Constants
@@ -85,6 +87,91 @@ def _is_path(query: str) -> bool:
return ext in _CODE_EXTS
+# ---------------------------------------------------------------------------
+# Workspace-aware repo context resolution
+# ---------------------------------------------------------------------------
+
+
+def _is_workspace_mode() -> bool:
+ """Return True if the MCP server is running in workspace mode."""
+ return _state._registry is not None
+
+
+async def _resolve_repo_context(repo: str | None = None) -> Any:
+ """Resolve the per-repo resource context for the given ``repo`` parameter.
+
+ In **single-repo mode** (no registry): returns a lightweight wrapper
+ around the existing ``_state`` globals — zero overhead, full backward
+ compatibility.
+
+ In **workspace mode**: resolves the alias via the registry and returns
+ the matching ``RepoContext``.
+
+ Raises ``ValueError`` for ``repo="all"`` — callers must handle that
+ case explicitly before calling this helper.
+ """
+ from repowise.core.workspace.registry import RepoContext
+
+ registry = _state._registry
+ if registry is None:
+ # Single-repo mode — validate the repo param against the DB if given
+ if repo is not None:
+ from repowise.core.persistence.database import get_session as _get_session
+
+ async with _get_session(_state._session_factory) as session:
+ await _get_repo(session, repo) # raises LookupError if invalid
+
+ return RepoContext(
+ alias="default",
+ path=Path(_state._repo_path) if _state._repo_path else Path.cwd(),
+ session_factory=_state._session_factory,
+ fts=_state._fts,
+ vector_store=_state._vector_store,
+ decision_store=_state._decision_store,
+ vector_store_ready=_state._vector_store_ready or __import__("asyncio").Event(),
+ _engine=None,
+ )
+
+ # Workspace mode — resolve via registry
+ resolved = registry.resolve_repo_param(repo)
+ if isinstance(resolved, list):
+ raise ValueError(
+ "repo='all' must be handled explicitly by each tool. "
+ "Use _resolve_all_contexts() instead."
+ )
+ return await registry.get(resolved)
+
+
+async def _resolve_all_contexts() -> list[Any]:
+ """Return ``RepoContext`` objects for all repos in the workspace.
+
+ In single-repo mode, returns a single-element list wrapping ``_state``.
+ """
+ registry = _state._registry
+ if registry is None:
+ ctx = await _resolve_repo_context(None)
+ return [ctx]
+ contexts = []
+ for alias in registry.get_all_aliases():
+ contexts.append(await registry.get(alias))
+ return contexts
+
+
+def _unsupported_repo_all(tool_name: str) -> dict:
+ """Return an error dict for tools that don't support ``repo='all'``."""
+ registry = _state._registry
+ if registry is not None:
+ available = registry.get_all_aliases()
+ else:
+ available = []
+ return {
+ "error": (
+ f"repo='all' is not supported for {tool_name}. "
+ f"Specify a repo alias instead. Available: {available}"
+ ),
+ }
+
+
# ---------------------------------------------------------------------------
# Origin story & alignment (used by get_context, get_why)
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index 891fa7281..b83cd7e10 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -82,42 +82,22 @@ def build_meta(
return out
-def context_hint(targets: list[str], compact: bool) -> str | None:
+def context_hint(targets: list[str], compact: bool, include: set[str] | None = None) -> str | None:
"""Hint for `get_context` callers.
Conservative: only fires when the call shape suggests the agent could
have used a cheaper tool, AND the suggestion is unambiguously safe.
"""
- if compact:
- # Already in compact mode — don't push further.
- return None
if not targets:
return None
- # Single file target where the agent is likely to follow up with a Read:
- # nudge toward get_symbol so they slice instead of reading the whole file.
- if len(targets) == 1 and "::" not in targets[0] and "/" in targets[0]:
- return (
- "If you only need one function from this file, call "
- "get_symbol(symbol_id='{path}::{name}') to get just that "
- "function body — cheaper than Read.".format(
- path=targets[0], name="<symbol_name>"
- )
- )
+ # If caller requested source and got a large symbol, nudge toward Read with offset
+ if include and "source" in include and len(targets) == 1:
+ return None # source mode provides its own truncation info
return None
def symbol_hint(symbol_id: str, end_line: int, start_line: int) -> str | None:
- """Hint for `get_symbol` callers.
-
- Suggests context_lines expansion only for very small symbols where the
- body alone may be insufficient.
- """
- span = max(end_line - start_line, 0)
- if span < 5:
- return (
- "Small symbol — pass context_lines=10 if you need surrounding "
- "context (imports, sibling defs)."
- )
+ """Hint for source retrieval (kept for backward compat with tool_symbol.py)."""
return None
diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.py
index 6fba31c0a..6233034d4 100644
--- a/packages/server/src/repowise/server/mcp_server/_server.py
+++ b/packages/server/src/repowise/server/mcp_server/_server.py
@@ -120,6 +120,49 @@ async def _load_vector_stores(repo_path: str | None) -> None:
_state._vector_store_ready.set()
+def _detect_workspace(repo_path: str | None):
+ """Check if ``repo_path`` is inside a workspace.
+
+ Returns ``(workspace_root, ws_config, repo_alias)`` or ``(None, None, None)``.
+ """
+ if not repo_path:
+ return None, None, None
+ try:
+ from pathlib import Path as _Path
+
+ from repowise.core.workspace import WorkspaceConfig, find_workspace_root
+
+ ws_root = find_workspace_root(_Path(repo_path))
+ if ws_root is None:
+ return None, None, None
+
+ ws_config = WorkspaceConfig.load(ws_root)
+ if not ws_config.repos:
+ return None, None, None
+
+ # Determine which repo the given path belongs to
+ resolved = _Path(repo_path).resolve()
+ repo_alias = None
+ for entry in ws_config.repos:
+ entry_abs = (ws_root / entry.path).resolve()
+ try:
+ resolved.relative_to(entry_abs)
+ repo_alias = entry.alias
+ break
+ except ValueError:
+ continue
+
+ if repo_alias is None:
+ # Path is inside workspace but doesn't match a repo — use default
+ primary = ws_config.get_primary()
+ repo_alias = primary.alias if primary else ws_config.repos[0].alias
+
+ return ws_root, ws_config, repo_alias
+ except Exception:
+ _log.debug("Workspace detection failed", exc_info=True)
+ return None, None, None
+
+
@asynccontextmanager
async def _lifespan(server: FastMCP):
"""Initialize DB engine, session factory, and FTS synchronously on startup.
@@ -128,6 +171,76 @@ async def _lifespan(server: FastMCP):
the server starts accepting tool calls immediately. search_codebase awaits
_state._vector_store_ready before querying the vector store.
"""
+
+ # --- Workspace detection ------------------------------------------------
+ ws_root, ws_config, ws_repo_alias = _detect_workspace(_state._repo_path)
+
+ if ws_root is not None and ws_config is not None:
+ # Workspace mode — use RepoRegistry for multi-repo serving
+ from pathlib import Path as _Path
+
+ from repowise.core.workspace.registry import RepoRegistry
+
+ # Override default repo to the one the path points at
+ if ws_repo_alias and ws_config.get_repo(ws_repo_alias):
+ ws_config.default_repo = ws_repo_alias
+
+ registry = RepoRegistry(
+ workspace_root=ws_root,
+ ws_config=ws_config,
+ embedder_factory=lambda: _resolve_embedder(),
+ )
+
+ # Eagerly load the default repo so tools work immediately
+ default_ctx = await registry.get_default()
+
+ _state._registry = registry
+ _state._workspace_root = str(ws_root)
+
+ # Alias default repo's resources into _state for backward compat
+ _state._session_factory = default_ctx.session_factory
+ _state._fts = default_ctx.fts
+ _state._vector_store = default_ctx.vector_store
+ _state._decision_store = default_ctx.decision_store
+ _state._vector_store_ready = default_ctx.vector_store_ready
+
+ # Load cross-repo enricher (Phase 3 + 4)
+ try:
+ from repowise.core.workspace.config import WORKSPACE_DATA_DIR
+ from repowise.core.workspace.contracts import CONTRACTS_FILENAME
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ cross_repo_path = ws_root / WORKSPACE_DATA_DIR / "cross_repo_edges.json"
+ contracts_path = ws_root / WORKSPACE_DATA_DIR / CONTRACTS_FILENAME
+ enricher = CrossRepoEnricher(
+ cross_repo_path, contracts_path=contracts_path
+ )
+ if enricher.has_data:
+ _state._cross_repo_enricher = enricher
+ _log.info(
+ "Cross-repo enricher loaded: %d co-change edges, %d package deps, %d contract links",
+ len(enricher._co_changes),
+ len(enricher._package_deps),
+ len(enricher._contract_links),
+ )
+ except Exception:
+ _log.debug("Cross-repo enricher not available", exc_info=True)
+
+ _log.info(
+ "repowise MCP: workspace mode — %d repos, default='%s'",
+ len(ws_config.repos),
+ registry.get_default_alias(),
+ )
+
+ yield
+
+ _state._cross_repo_enricher = None
+ await registry.close()
+ _state._registry = None
+ _state._workspace_root = None
+ return
+
+ # --- Single-repo mode (existing behavior) --------------------------------
configured_db_url = get_configured_db_url()
# When repo path is set and no env override, prefer repo-local DB.
diff --git a/packages/server/src/repowise/server/mcp_server/_state.py b/packages/server/src/repowise/server/mcp_server/_state.py
index 7fa640417..9012d7648 100644
--- a/packages/server/src/repowise/server/mcp_server/_state.py
+++ b/packages/server/src/repowise/server/mcp_server/_state.py
@@ -15,3 +15,8 @@ _repo_path: str | None = None
# Set to an asyncio.Event by _lifespan; signals that vector stores are loaded.
# tool_search awaits this before searching to avoid racing a background load.
_vector_store_ready: asyncio.Event | None = None
+
+# Workspace mode — set by _lifespan when a workspace is detected.
+_registry: Any = None # RepoRegistry | None
+_workspace_root: str | None = None
+_cross_repo_enricher: Any = None # CrossRepoEnricher | None
diff --git a/packages/server/src/repowise/server/mcp_server/tool_annotate.py b/packages/server/src/repowise/server/mcp_server/tool_annotate.py
index ae6a100f5..da734e3f5 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_annotate.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_annotate.py
@@ -10,8 +10,11 @@ from typing import Any
from sqlalchemy import select
from repowise.core.persistence.database import get_session
-from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
from repowise.server.mcp_server._server import mcp
@@ -32,10 +35,14 @@ async def annotate_file(
notes: the note text to attach (empty string to clear).
repo: repository identifier; usually omitted.
"""
+ if repo == "all":
+ return _unsupported_repo_all("annotate_file")
+ ctx = await _resolve_repo_context(repo)
+
from repowise.core.persistence.models import Page
- async with get_session(_state._session_factory) as session:
- await _get_repo(session, repo) # validates repo exists
+ async with get_session(ctx.session_factory) as session:
+ await _get_repo(session) # validates repo exists
# Try file_page first, then module_page
page_id = f"file_page:{target}"
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer.py
index 5bbee83d5..7b3440965 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer.py
@@ -32,8 +32,11 @@ from sqlalchemy import select
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import AnswerCache, Page, WikiSymbol
-from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
from repowise.server.mcp_server._meta import answer_hint as _answer_hint
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._server import mcp
@@ -292,7 +295,7 @@ def _read_signature_from_source(
async def _hydrate_symbols_for_hits(
- session, repo_id: str, hits: list[dict]
+ session, repo_id: str, hits: list[dict], ctx: Any = None,
) -> None:
"""Mutate `hits` in place: attach `symbols` list to top-N file_page hits.
@@ -327,7 +330,7 @@ async def _hydrate_symbols_for_hits(
.order_by(WikiSymbol.file_path, WikiSymbol.start_line)
)
by_file: dict[str, list[dict]] = {}
- repo_root = Path(_state._repo_path) if _state._repo_path else None
+ repo_root = Path(str(ctx.path)) if ctx and ctx.path else None
for row in res.scalars().all():
rich_sig = _read_signature_from_source(
repo_root, row.file_path, row.start_line
@@ -377,7 +380,7 @@ def _split_relational(question: str) -> list[str] | None:
return None
-async def _intersection_boost(question: str, hits: list[dict]) -> None:
+async def _intersection_boost(question: str, hits: list[dict], ctx: Any = None) -> None:
"""For relational questions, boost any hit that appears in both halves
of a split-FTS retrieval. Mutates `hits` in place: adds a multiplicative
bonus to `score` for hits that appear in both subset retrievals.
@@ -387,13 +390,13 @@ async def _intersection_boost(question: str, hits: list[dict]) -> None:
top of either half alone. Independent of repo or domain.
"""
parts = _split_relational(question)
- if parts is None or _state._fts is None:
+ if parts is None or ctx is None or ctx.fts is None:
return
sub_hit_ids: list[set] = []
for sub_q in parts:
try:
sub = await asyncio.wait_for(
- _state._fts.search(sub_q, limit=15), timeout=3.0
+ ctx.fts.search(sub_q, limit=15), timeout=3.0
)
sub_hit_ids.append({h.page_id for h in sub})
except Exception:
@@ -412,7 +415,7 @@ async def _intersection_boost(question: str, hits: list[dict]) -> None:
hits.sort(key=lambda h: h["score"], reverse=True)
-async def _enrich_gated_excerpts(hits: list[dict]) -> None:
+async def _enrich_gated_excerpts(hits: list[dict], ctx: Any = None) -> None:
"""For the gated (low-confidence) return path, fetch real page content
for top hits so the agent has substantive raw material instead of
one-line summaries. Mutates `hits` in place — adds an `excerpt` field.
@@ -427,7 +430,7 @@ async def _enrich_gated_excerpts(hits: list[dict]) -> None:
if not page_ids:
return
try:
- async with get_session(_state._session_factory) as session:
+ async with get_session(ctx.session_factory) as session:
res = await session.execute(
select(Page.id, Page.content_md).where(Page.id.in_(page_ids))
)
@@ -484,24 +487,6 @@ def _rerank_by_coverage(hits: list[dict], question: str) -> list[dict]:
return hits
-def _confidence_from_scores(scores: list[float]) -> str:
- """Map raw FTS scores to a coarse confidence label.
-
- The thresholds are intentionally generous on the low end — when retrieval
- finds *anything* we still let the agent see it, but mark it 'low' so the
- workflow forces verification.
- """
- if not scores:
- return "low"
- top = scores[0]
- gap = top - (scores[1] if len(scores) > 1 else 0.0)
- if top >= 1.0 and gap >= 0.2:
- return "high"
- if top >= 0.5:
- return "medium"
- return "low"
-
-
@mcp.tool()
async def get_answer(
question: str,
@@ -520,7 +505,12 @@ async def get_answer(
scope: optional path prefix to restrict retrieval (e.g. "src/pkg/").
repo: repository identifier; usually omitted.
"""
+ if repo == "all":
+ return _unsupported_repo_all("get_answer")
+
t0 = time.perf_counter()
+ ctx = await _resolve_repo_context(repo)
+
if not question or not question.strip():
return {
"answer": "",
@@ -532,8 +522,8 @@ async def get_answer(
"_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
}
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
repo_id = repository.id
# --- Cache lookup --------------------------------------------------------
@@ -541,7 +531,7 @@ async def get_answer(
# scoped queries are uncommon and including scope would balloon hit rate
# variance. We hash on (repo_id, normalized_question) only.
qhash = _hash_question(question)
- async with get_session(_state._session_factory) as session:
+ async with get_session(ctx.session_factory) as session:
res = await session.execute(
select(AnswerCache).where(
AnswerCache.repository_id == repo_id,
@@ -561,19 +551,19 @@ async def get_answer(
# --- Retrieval (FTS) ---------------------------------------------------
raw_hits: list[Any] = []
- if _state._fts is not None:
+ if ctx.fts is not None:
with contextlib.suppress(Exception):
# Pull a wider candidate set so the term-coverage re-ranker has
# room to push conjunctive matches up the list before we cap to 5.
raw_hits = await asyncio.wait_for(
- _state._fts.search(question, limit=15), timeout=5.0
+ ctx.fts.search(question, limit=15), timeout=5.0
)
# Hydrate hits with target_path + summary from the Page table.
hits: list[dict] = []
if raw_hits:
page_ids = [h.page_id for h in raw_hits]
- async with get_session(_state._session_factory) as session:
+ async with get_session(ctx.session_factory) as session:
res = await session.execute(
select(
Page.id,
@@ -612,7 +602,7 @@ async def get_answer(
# Intersection-retrieval boost for relational questions (multi-entity).
# Pages at the intersection of two split-FTS halves get a 2× bonus.
with contextlib.suppress(Exception):
- await _intersection_boost(question, hits)
+ await _intersection_boost(question, hits, ctx)
# Always cap retrieval hits at 5 for the response payload.
hits = hits[:5]
@@ -622,8 +612,8 @@ async def get_answer(
# classes/functions named in the question.
if hits:
with contextlib.suppress(Exception):
- async with get_session(_state._session_factory) as session:
- await _hydrate_symbols_for_hits(session, repo_id, hits)
+ async with get_session(ctx.session_factory) as session:
+ await _hydrate_symbols_for_hits(session, repo_id, hits, ctx)
fallback_targets = [
h["target_path"] for h in hits if h.get("target_path")
@@ -662,11 +652,20 @@ async def get_answer(
if len(hits) >= 2:
top_score = hits[0].get("score", 0.0)
second_score = hits[1].get("score", 0.0) or 1e-9
- dominant = (top_score / second_score) >= _DOMINANCE_RATIO
+
+ # Two-tier gating: at high retrieval quality (both scores
+ # excellent), close ratios are expected and normal — use an
+ # absolute gap instead. At lower quality, the ratio-based
+ # gate prevents synthesis on genuinely ambiguous retrievals.
+ if top_score >= 3.0:
+ dominant = (top_score - second_score) >= 0.5
+ else:
+ dominant = (top_score / second_score) >= _DOMINANCE_RATIO
+
if not dominant:
# Enrich top hits with substantive excerpts so the agent has
# real material to ground in (not one-line summaries).
- await _enrich_gated_excerpts(hits)
+ await _enrich_gated_excerpts(hits, ctx)
return {
"answer": "",
"citations": [],
@@ -788,7 +787,7 @@ async def get_answer(
# response (we already have the answer in hand).
if answer_text:
with contextlib.suppress(Exception):
- async with get_session(_state._session_factory) as session:
+ async with get_session(ctx.session_factory) as session:
row = AnswerCache(
repository_id=repo_id,
question_hash=qhash,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_callers.py b/packages/server/src/repowise/server/mcp_server/tool_callers.py
new file mode 100644
index 000000000..1f79ff721
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_callers.py
@@ -0,0 +1,225 @@
+"""MCP Tool: get_callers_callees — find who calls a symbol and what it calls.
+
+Provides symbol-level call graph navigation for AI coding assistants.
+Supports call edges, heritage edges (extends/implements), and any other
+edge type stored in the graph. Heritage queries use the same code path
+via the ``edge_types`` parameter — no separate tool needed.
+
+Resolution strategy:
+ 1. Exact match on GraphNode.node_id (the canonical "{path}::{name}" key)
+ 2. Fuzzy match on GraphNode.name column (bare name, e.g. "verify_token")
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from typing import Any
+
+from sqlalchemy import select
+
+from repowise.core.persistence.crud import (
+ get_graph_edges_for_node,
+ get_graph_node,
+ get_graph_nodes_by_ids,
+)
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import GraphNode
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._server import mcp
+
+_DEFAULT_EDGE_TYPES = ["calls"]
+
+
+async def _resolve_symbol_node(
+ session: Any, repo_id: str, symbol_id: str
+) -> GraphNode | None:
+ """Resolve a symbol ID to a GraphNode, with fuzzy fallback."""
+ # 1. Exact match
+ node = await get_graph_node(session, repo_id, symbol_id)
+ if node and node.node_type == "symbol":
+ return node
+
+ # 2. Fuzzy: extract bare name and search
+ bare_name = symbol_id
+ if "::" in symbol_id:
+ bare_name = symbol_id.split("::")[-1]
+ # Try matching by the name column
+ result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "symbol",
+ GraphNode.name == bare_name,
+ )
+ )
+ rows = list(result.scalars().all())
+ if not rows:
+ return None
+
+ # If the symbol_id contains a file path hint, prefer matching file
+ if "::" in symbol_id:
+ file_hint = symbol_id.split("::")[0]
+ for r in rows:
+ if r.file_path == file_hint:
+ return r
+
+ # Return the first match (deterministic: lowest node_id)
+ rows.sort(key=lambda r: r.node_id)
+ return rows[0]
+
+
+def _node_summary(node: GraphNode) -> dict[str, Any]:
+ """Build a compact summary dict for a graph node."""
+ out: dict[str, Any] = {
+ "symbol_id": node.node_id,
+ "name": node.name or node.node_id,
+ "kind": node.kind,
+ "file": node.file_path or node.node_id,
+ }
+ if node.start_line is not None:
+ out["start_line"] = node.start_line
+ if node.signature:
+ out["signature"] = node.signature
+ return out
+
+
+async def get_callers_callees(
+ symbol_id: str,
+ direction: str = "both",
+ edge_types: list[str] | None = None,
+ limit: int = 20,
+ repo: str | None = None,
+) -> dict:
+ """Find who calls a symbol and what it calls. Also works for class hierarchy.
+
+ Use direction="callers" to find what calls/extends this symbol.
+ Use edge_types=["extends","implements"] for class hierarchy queries.
+ Default edge_types is ["calls"].
+
+ Args:
+ symbol_id: "path/to/file.py::FunctionName" format from get_context.
+ direction: "callers", "callees", or "both".
+ edge_types: Filter by edge type. Default ["calls"].
+ limit: Max results per direction (default 20).
+ repo: Usually omitted.
+ """
+ if repo == "all":
+ return _unsupported_repo_all("get_callers_callees")
+ ctx = await _resolve_repo_context(repo)
+
+ t0 = time.perf_counter()
+ if not symbol_id or not symbol_id.strip():
+ return {
+ "symbol_id": symbol_id,
+ "error": "symbol_id is required",
+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
+ }
+
+ if edge_types is None:
+ edge_types = _DEFAULT_EDGE_TYPES
+
+ if direction not in ("callers", "callees", "both"):
+ direction = "both"
+
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ repo_id = repository.id
+
+ # Resolve symbol
+ node = await _resolve_symbol_node(session, repo_id, symbol_id)
+ if node is None:
+ return {
+ "symbol_id": symbol_id,
+ "error": (
+ f"Symbol not found in graph: {symbol_id!r}. Use get_context "
+ "to list available symbols, then try with the exact "
+ "symbol_id from that response."
+ ),
+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
+ }
+
+ # Map direction to CRUD direction param
+ crud_direction = direction
+ if direction == "both":
+ crud_direction = "both"
+
+ edges = await get_graph_edges_for_node(
+ session,
+ repo_id,
+ node.node_id,
+ direction=crud_direction,
+ edge_types=edge_types,
+ limit=limit,
+ )
+
+ # Collect node IDs to hydrate
+ other_ids: list[str] = []
+ for e in edges:
+ if e.source_node_id != node.node_id:
+ other_ids.append(e.source_node_id)
+ if e.target_node_id != node.node_id:
+ other_ids.append(e.target_node_id)
+
+ node_map = await get_graph_nodes_by_ids(session, repo_id, list(set(other_ids)))
+
+ # Build caller/callee lists
+ callers: list[dict[str, Any]] = []
+ callees: list[dict[str, Any]] = []
+
+ for e in edges:
+ is_caller = e.target_node_id == node.node_id
+ other_id = e.source_node_id if is_caller else e.target_node_id
+ other_node = node_map.get(other_id)
+
+ entry: dict[str, Any] = {
+ "symbol_id": other_id,
+ "name": other_node.name if other_node else other_id.split("::")[-1] if "::" in other_id else other_id,
+ "kind": other_node.kind if other_node else None,
+ "file": other_node.file_path if other_node else (other_id.split("::")[0] if "::" in other_id else other_id),
+ "confidence": e.confidence,
+ "edge_type": e.edge_type,
+ }
+ if other_node and other_node.start_line is not None:
+ entry["start_line"] = other_node.start_line
+
+ if is_caller:
+ callers.append(entry)
+ else:
+ callees.append(entry)
+
+ # Sort by confidence DESC, then by name
+ callers.sort(key=lambda x: (-x.get("confidence", 0), x.get("name", "")))
+ callees.sort(key=lambda x: (-x.get("confidence", 0), x.get("name", "")))
+
+ result: dict[str, Any] = {
+ "symbol_id": node.node_id,
+ "symbol": _node_summary(node),
+ }
+
+ if direction in ("callers", "both"):
+ result["callers"] = callers
+ result["caller_count"] = len(callers)
+ if direction in ("callees", "both"):
+ result["callees"] = callees
+ result["callee_count"] = len(callees)
+
+ truncated = (
+ (direction in ("callers", "both") and len(callers) >= limit)
+ or (direction in ("callees", "both") and len(callees) >= limit)
+ )
+ result["truncated"] = truncated
+
+ hint = None
+ if callers or callees:
+ hint = "Use get_symbol(symbol_id) to read the source of any caller/callee."
+ result["_meta"] = _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ hint=hint,
+ )
+ return result
diff --git a/packages/server/src/repowise/server/mcp_server/tool_community.py b/packages/server/src/repowise/server/mcp_server/tool_community.py
new file mode 100644
index 000000000..4934a90d6
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_community.py
@@ -0,0 +1,176 @@
+"""MCP Tool: get_community — explore architectural communities/clusters.
+
+Returns the community a file belongs to, its members, cohesion score,
+label, and neighboring communities. Helps Claude Code understand module
+boundaries, refactoring safety, and architectural coupling.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from typing import Any
+
+from repowise.core.persistence.crud import (
+ get_community_members,
+ get_cross_community_edges,
+ get_graph_node,
+)
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import GraphNode
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._server import mcp
+
+
+def _parse_community_meta(node: GraphNode) -> dict[str, Any]:
+ """Extract label and cohesion from community_meta_json."""
+ try:
+ meta = json.loads(node.community_meta_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ meta = {}
+ return meta
+
+
+async def get_community(
+ target: str,
+ include_members: bool = True,
+ member_limit: int = 30,
+ repo: str | None = None,
+) -> dict:
+ """Show the architectural community/cluster a file belongs to.
+
+ Returns community label, cohesion score, members, and neighboring
+ communities. Useful for understanding module boundaries and
+ refactoring safety.
+
+ Args:
+ target: File path (resolves to its community) or community ID (e.g. "3").
+ include_members: Include member file list (default true).
+ member_limit: Max members to return (default 30).
+ repo: Usually omitted.
+ """
+ if repo == "all":
+ return _unsupported_repo_all("get_community")
+ ctx = await _resolve_repo_context(repo)
+
+ t0 = time.perf_counter()
+ if not target or not target.strip():
+ return {
+ "target": target,
+ "error": "target is required",
+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
+ }
+
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ repo_id = repository.id
+
+ community_id: int | None = None
+ label: str = ""
+ cohesion: float = 0.0
+
+ # Resolve target to community_id
+ if target.strip().isdigit():
+ community_id = int(target.strip())
+ else:
+ node = await get_graph_node(session, repo_id, target)
+ if node is None:
+ return {
+ "target": target,
+ "error": f"Node not found in graph: {target!r}. Check the file path.",
+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
+ }
+ community_id = node.community_id
+ meta = _parse_community_meta(node)
+ label = meta.get("label", "")
+ cohesion = meta.get("cohesion", 0.0)
+
+ if community_id is None:
+ return {
+ "target": target,
+ "error": "Could not resolve community ID",
+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
+ }
+
+ # Get members
+ members_list: list[dict[str, Any]] = []
+ member_count = 0
+ if include_members:
+ members = await get_community_members(
+ session, repo_id, community_id, limit=member_limit
+ )
+ member_count = len(members)
+ for m in members:
+ entry: dict[str, Any] = {
+ "path": m.node_id,
+ "pagerank": round(m.pagerank, 6) if m.pagerank else 0.0,
+ "is_entry_point": m.is_entry_point,
+ }
+ members_list.append(entry)
+
+ # If we haven't found label/cohesion yet (target was a community ID),
+ # grab it from the first member
+ if not label:
+ meta = _parse_community_meta(m)
+ label = meta.get("label", "")
+ cohesion = meta.get("cohesion", 0.0)
+ else:
+ # Still need count
+ members = await get_community_members(
+ session, repo_id, community_id, limit=1000
+ )
+ member_count = len(members)
+ if not label and members:
+ meta = _parse_community_meta(members[0])
+ label = meta.get("label", "")
+ cohesion = meta.get("cohesion", 0.0)
+
+ # Get neighboring communities
+ cross_edges = await get_cross_community_edges(session, repo_id, community_id)
+
+ # Resolve labels for neighbor communities from any member node
+ neighbor_communities: list[dict[str, Any]] = []
+ for ce in cross_edges[:10]: # cap at 10 neighbors
+ neighbor_id = ce["target_community_id"]
+ # Get one member to read the label
+ neighbor_members = await get_community_members(
+ session, repo_id, neighbor_id, limit=1
+ )
+ neighbor_label = ""
+ if neighbor_members:
+ nmeta = _parse_community_meta(neighbor_members[0])
+ neighbor_label = nmeta.get("label", "")
+ neighbor_communities.append({
+ "community_id": neighbor_id,
+ "label": neighbor_label,
+ "cross_edge_count": ce["edge_count"],
+ })
+
+ result: dict[str, Any] = {
+ "target": target,
+ "community_id": community_id,
+ "label": label or f"cluster_{community_id}",
+ "cohesion": round(cohesion, 3),
+ "member_count": member_count,
+ }
+
+ if include_members:
+ result["members"] = members_list
+ result["truncated"] = member_count >= member_limit
+
+ result["neighboring_communities"] = neighbor_communities
+
+ hint = None
+ if neighbor_communities:
+ hint = "Use get_callers_callees on key symbols to understand cross-community coupling."
+ result["_meta"] = _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ hint=hint,
+ )
+ return result
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context.py b/packages/server/src/repowise/server/mcp_server/tool_context.py
index 180aa28b1..76551bf6d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context.py
@@ -1,10 +1,20 @@
-"""MCP Tool 2: get_context — complete context for files, modules, or symbols."""
+"""MCP Tool: get_context — the workhorse tool for files, modules, or symbols.
+
+Absorbs functionality from the former get_symbol, get_callers_callees,
+get_graph_metrics, and get_community tools via the ``include`` parameter:
+ - include=["source"] → symbol source body (replaces get_symbol)
+ - include=["callers"] → who calls this symbol (replaces get_callers_callees)
+ - include=["callees"] → what this symbol calls
+ - include=["metrics"] → PageRank, betweenness, percentiles (replaces get_graph_metrics)
+ - include=["community"]→ community membership + neighbors (replaces get_community)
+"""
from __future__ import annotations
import asyncio
import json
import logging
+from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
@@ -29,6 +39,15 @@ _CHAR_BUDGET = _TOKEN_BUDGET * _CHARS_PER_TOKEN
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.persistence.crud import (
+ get_all_file_metrics,
+ get_community_members,
+ get_cross_community_edges,
+ get_graph_edges_for_node,
+ get_graph_node,
+ get_graph_nodes_by_ids,
+ get_node_degree_counts,
+)
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import (
DecisionRecord,
@@ -40,11 +59,20 @@ from repowise.core.persistence.models import (
WikiSymbol,
)
from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._meta import context_hint as _context_hint
from repowise.server.mcp_server._server import mcp
+# Safety cap for source retrieval (from former get_symbol)
+_MAX_SOURCE_LINES = 400
+# Minimum confidence for call edges to filter false positives
+_MIN_CALL_CONFIDENCE = 0.7
+
def _synthesize_structural_summary(
file_path: str, classes: list[str], functions: list[str]
@@ -76,6 +104,8 @@ async def _resolve_one_target(
target: str,
include: set[str] | None,
compact: bool = False,
+ *,
+ repo_path: str | None = None,
) -> dict:
"""Resolve a single target and return its full context."""
repo_id = repository.id
@@ -92,7 +122,9 @@ async def _resolve_one_target(
target_type = "file"
file_path_for_git = target
else:
- # 2. Try module page
+ # 1b. Normalise directory targets: strip trailing slash and try module
+ clean_target = target.rstrip("/")
+ # 2. Try module page (exact, then cleaned, then partial)
res = await session.execute(
select(Page).where(
Page.repository_id == repo_id,
@@ -101,13 +133,22 @@ async def _resolve_one_target(
)
)
page = res.scalar_one_or_none()
+ if page is None and clean_target != target:
+ res = await session.execute(
+ select(Page).where(
+ Page.repository_id == repo_id,
+ Page.page_type == "module_page",
+ Page.target_path == clean_target,
+ )
+ )
+ page = res.scalar_one_or_none()
if page is None:
# Partial match fallback for modules
res = await session.execute(
select(Page).where(
Page.repository_id == repo_id,
Page.page_type == "module_page",
- Page.target_path.contains(target),
+ Page.target_path.contains(clean_target),
)
)
page = res.scalar_one_or_none()
@@ -189,16 +230,29 @@ async def _resolve_one_target(
# Fallback 3: fuzzy path suggestions — match by filename or partial path.
# Only runs if the prior fallbacks didn't resolve the target.
if target_type is None:
- tail = target.rsplit("/", 1)[-1]
+ # For directory-like targets, suggest files within that directory
+ dir_prefix = clean_target.rstrip("/") + "/"
res = await session.execute(
select(GitMetadata.file_path)
.where(
GitMetadata.repository_id == repo_id,
- GitMetadata.file_path.contains(tail),
+ GitMetadata.file_path.like(f"{dir_prefix}%"),
)
.limit(5)
)
- suggestions = [row[0] for row in res.all() if row[0] != target]
+ suggestions = [row[0] for row in res.all()]
+ if not suggestions:
+ # Fall back to filename / partial path match
+ tail = target.rsplit("/", 1)[-1]
+ res = await session.execute(
+ select(GitMetadata.file_path)
+ .where(
+ GitMetadata.repository_id == repo_id,
+ GitMetadata.file_path.contains(tail),
+ )
+ .limit(5)
+ )
+ suggestions = [row[0] for row in res.all() if row[0] != target]
if suggestions:
return {
"target": target,
@@ -211,7 +265,8 @@ async def _resolve_one_target(
result_data["type"] = target_type
# --- Docs ---
- if include is None or "docs" in include:
+ # "full_doc" implies "docs" — entering the docs block whenever either is requested.
+ if include is None or "docs" in include or "full_doc" in include:
want_full_doc = bool(include and "full_doc" in include)
docs: dict[str, Any] = {}
if target_type == "file":
@@ -292,6 +347,25 @@ async def _resolve_one_target(
importers = res.scalars().all()
docs["imported_by"] = [e.source_node_id for e in importers]
+ # Community info (compact=False only, ~80 bytes)
+ res = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_id == target,
+ )
+ )
+ gn = res.scalar_one_or_none()
+ if gn and gn.community_id is not None:
+ _cmeta: dict[str, Any] = {}
+ try:
+ _cmeta = json.loads(gn.community_meta_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ pass
+ docs["community"] = {
+ "id": gn.community_id,
+ "label": _cmeta.get("label", ""),
+ }
+
elif target_type == "module":
docs["title"] = page.title
docs["summary"] = page.summary or ""
@@ -469,9 +543,327 @@ async def _resolve_one_target(
freshness["is_stale"] = None
result_data["freshness"] = freshness
+ # --- Source (replaces get_symbol) ---
+ if include and "source" in include:
+ await _resolve_source(
+ session, repository, target, target_type, result_data,
+ repo_path=repo_path,
+ )
+
+ # --- Callers / Callees (replaces get_callers_callees) ---
+ want_callers = bool(include and "callers" in include)
+ want_callees = bool(include and "callees" in include)
+ if want_callers or want_callees:
+ await _resolve_call_graph(
+ session, repository, target, target_type, result_data,
+ want_callers=want_callers, want_callees=want_callees,
+ )
+
+ # --- Metrics (replaces get_graph_metrics) ---
+ if include and "metrics" in include:
+ await _resolve_metrics(session, repository, target, result_data)
+
+ # --- Community (replaces get_community) ---
+ if include and "community" in include:
+ await _resolve_community(session, repository, target, result_data)
+
return result_data
+# ---------------------------------------------------------------------------
+# Merged tool helpers (source, callers/callees, metrics, community)
+# ---------------------------------------------------------------------------
+
+
+async def _resolve_source(
+ session: AsyncSession,
+ repository: Repository,
+ target: str,
+ target_type: str | None,
+ result_data: dict[str, Any],
+ *,
+ repo_path: str | None = None,
+) -> None:
+ """Resolve symbol source body and attach to result_data["source"]."""
+ repo_id = repository.id
+
+ # Find the symbol — target could be "path::Name" or a bare name
+ file_path, name = None, None
+ if "::" in target:
+ file_path, _, name = target.partition("::")
+ else:
+ name = target
+
+ # Try exact symbol_id match first
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.symbol_id == target,
+ )
+ )
+ row = res.scalar_one_or_none()
+
+ if row is None and file_path and name:
+ # Try (file_path, qualified_name)
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.file_path == file_path,
+ WikiSymbol.qualified_name == name,
+ )
+ )
+ row = res.scalar_one_or_none()
+
+ if row is None and file_path and name:
+ # Try (file_path, name) — bare name
+ bare = name.split("::")[-1] if "::" in name else name
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.file_path == file_path,
+ WikiSymbol.name == bare,
+ )
+ )
+ row = res.scalar_one_or_none()
+
+ if row is None:
+ result_data["source"] = {"error": f"Symbol not found: {target!r}"}
+ return
+
+ if not repo_path:
+ result_data["source"] = {"error": "MCP server has no repo path configured"}
+ return
+
+ repo_root = Path(repo_path)
+ abs_path = (repo_root / row.file_path).resolve()
+ try:
+ abs_path.relative_to(repo_root.resolve())
+ except ValueError:
+ result_data["source"] = {"error": "Path escape attempt blocked"}
+ return
+
+ try:
+ text = abs_path.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ result_data["source"] = {"error": "Source file could not be read"}
+ return
+
+ lines = text.splitlines()
+ total = len(lines)
+ s = max(1, min(row.start_line, total))
+ e = max(s, min(row.end_line, total))
+
+ span = e - s + 1
+ truncated = False
+ if span > _MAX_SOURCE_LINES:
+ e = s + _MAX_SOURCE_LINES - 1
+ truncated = True
+
+ sliced = "\n".join(lines[s - 1 : e])
+ result_data["source"] = {
+ "body": sliced,
+ "start_line": s,
+ "end_line": e,
+ "language": row.language,
+ "truncated": truncated,
+ }
+
+
+async def _resolve_call_graph(
+ session: AsyncSession,
+ repository: Repository,
+ target: str,
+ target_type: str | None,
+ result_data: dict[str, Any],
+ *,
+ want_callers: bool = False,
+ want_callees: bool = False,
+) -> None:
+ """Resolve callers/callees for a symbol and attach to result_data."""
+ repo_id = repository.id
+ limit = 20
+
+ # Resolve to a graph node (symbol)
+ node = await get_graph_node(session, repo_id, target)
+ if node is None and "::" in target:
+ # Fuzzy: try bare name
+ bare_name = target.split("::")[-1]
+ res = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "symbol",
+ GraphNode.name == bare_name,
+ )
+ )
+ rows = list(res.scalars().all())
+ if rows:
+ file_hint = target.split("::")[0]
+ node = next((r for r in rows if r.file_path == file_hint), rows[0])
+
+ if node is None or node.node_type != "symbol":
+ # For file targets, return empty with explanation — callers/callees is symbol-only
+ if want_callers:
+ result_data["callers"] = []
+ if want_callees:
+ result_data["callees"] = []
+ if node is not None and node.node_type != "symbol":
+ result_data["_call_graph_note"] = (
+ "callers/callees require a symbol target (function/class/method), "
+ f"but '{target}' is a {node.node_type}. Pass a symbol name or file::Symbol."
+ )
+ return
+
+ direction = "both"
+ if want_callers and not want_callees:
+ direction = "callers"
+ elif want_callees and not want_callers:
+ direction = "callees"
+
+ edges = await get_graph_edges_for_node(
+ session, repo_id, node.node_id,
+ direction=direction, edge_types=["calls", "extends", "implements"],
+ limit=limit,
+ )
+
+ # Hydrate other nodes
+ other_ids = list({
+ e.source_node_id if e.target_node_id == node.node_id else e.target_node_id
+ for e in edges
+ })
+ node_map = await get_graph_nodes_by_ids(session, repo_id, other_ids)
+
+ callers: list[dict[str, Any]] = []
+ callees: list[dict[str, Any]] = []
+
+ for e in edges:
+ # Filter out low-confidence edges (false positives from Tier 3 global resolution)
+ if (e.confidence or 0) < _MIN_CALL_CONFIDENCE:
+ continue
+
+ is_caller = e.target_node_id == node.node_id
+ other_id = e.source_node_id if is_caller else e.target_node_id
+ other_node = node_map.get(other_id)
+
+ entry: dict[str, Any] = {
+ "symbol_id": other_id,
+ "name": other_node.name if other_node else (other_id.split("::")[-1] if "::" in other_id else other_id),
+ "kind": other_node.kind if other_node else None,
+ "file": other_node.file_path if other_node else (other_id.split("::")[0] if "::" in other_id else other_id),
+ "confidence": e.confidence,
+ "edge_type": e.edge_type,
+ }
+ if is_caller:
+ callers.append(entry)
+ else:
+ callees.append(entry)
+
+ # Sort by confidence DESC
+ callers.sort(key=lambda x: -(x.get("confidence") or 0))
+ callees.sort(key=lambda x: -(x.get("confidence") or 0))
+
+ if want_callers:
+ result_data["callers"] = callers
+ if want_callees:
+ result_data["callees"] = callees
+
+
+async def _resolve_metrics(
+ session: AsyncSession,
+ repository: Repository,
+ target: str,
+ result_data: dict[str, Any],
+) -> None:
+ """Resolve graph importance metrics and attach to result_data["metrics"]."""
+ repo_id = repository.id
+
+ node = await get_graph_node(session, repo_id, target)
+ if node is None:
+ result_data["metrics"] = None
+ return
+
+ try:
+ meta = json.loads(node.community_meta_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ meta = {}
+
+ degrees = await get_node_degree_counts(session, repo_id, node.node_id)
+
+ # Percentile computation against same-type peers
+ all_nodes = await get_all_file_metrics(session, repo_id)
+ pr_values = [n.pagerank for n in all_nodes if n.pagerank is not None]
+ bt_values = [n.betweenness for n in all_nodes if n.betweenness is not None]
+
+ def _pct(value: float, all_vals: list[float]) -> int:
+ if not all_vals:
+ return 0
+ return round(100 * sum(1 for v in all_vals if v < value) / len(all_vals))
+
+ result_data["metrics"] = {
+ "pagerank": round(node.pagerank or 0.0, 6),
+ "pagerank_percentile": _pct(node.pagerank or 0.0, pr_values),
+ "betweenness": round(node.betweenness or 0.0, 6),
+ "betweenness_percentile": _pct(node.betweenness or 0.0, bt_values),
+ "in_degree": degrees["in_degree"],
+ "out_degree": degrees["out_degree"],
+ "community_id": node.community_id,
+ "community_label": meta.get("label") or None,
+ }
+
+
+async def _resolve_community(
+ session: AsyncSession,
+ repository: Repository,
+ target: str,
+ result_data: dict[str, Any],
+) -> None:
+ """Resolve community membership and attach to result_data["community"]."""
+ repo_id = repository.id
+
+ node = await get_graph_node(session, repo_id, target)
+ if node is None or node.community_id is None:
+ result_data["community"] = None
+ return
+
+ try:
+ meta = json.loads(node.community_meta_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ meta = {}
+
+ label = meta.get("label") or f"cluster_{node.community_id}"
+ cohesion = float(meta.get("cohesion", 0.0) or 0.0)
+
+ # Get top members (cap at 10 for compact output)
+ members = await get_community_members(session, repo_id, node.community_id, limit=10)
+ member_paths = [m.node_id for m in members]
+
+ # Neighboring communities (cap at 5)
+ cross_edges = await get_cross_community_edges(session, repo_id, node.community_id)
+ neighbors: list[dict[str, Any]] = []
+ for ce in cross_edges[:5]:
+ nid = ce["target_community_id"]
+ nm = await get_community_members(session, repo_id, nid, limit=1)
+ nlabel = ""
+ if nm:
+ try:
+ nmeta = json.loads(nm[0].community_meta_json or "{}")
+ nlabel = nmeta.get("label", "")
+ except (json.JSONDecodeError, TypeError):
+ pass
+ neighbors.append({
+ "id": nid,
+ "label": nlabel or f"cluster_{nid}",
+ "cross_edges": ce["edge_count"],
+ })
+
+ result_data["community"] = {
+ "id": node.community_id,
+ "label": label,
+ "cohesion": round(cohesion, 3),
+ "top_members": member_paths,
+ "neighbors": neighbors,
+ }
+
+
def _estimate_tokens(obj: Any) -> int:
"""Cheap upper-bound token estimate for an arbitrary JSON-serialisable object.
@@ -669,20 +1061,39 @@ async def get_context(
compact: bool = True,
repo: str | None = None,
) -> dict:
- """Get a compact navigation index for files/modules/symbols. Batch targets.
+ """Compact context for files, modules, or symbols. Batch multiple targets.
+
+ Default returns title + summary + symbol signatures. Add include options
+ for richer data. Pass all relevant targets in one call.
- Default returns title + summary + symbol signatures (~3× smaller than
- full mode). For full structure block + imported_by + docstrings pass
- compact=False. For the full wiki content_md pass include=["docs","full_doc"].
+ In workspace mode, responses are automatically enriched with cross-repo
+ signals: co-change partners, and API contract links (HTTP routes, gRPC
+ services, message topics consumed/provided by this file).
+
+ Include options:
+ - "docs" (default): wiki summary + symbol signatures
+ - "full_doc": full wiki markdown content
+ - "ownership": primary owner, bus factor, contributor count
+ - "last_change": last commit date and author
+ - "source": symbol source body (for symbol targets like "path::Name")
+ - "callers": who calls this symbol (symbol targets only)
+ - "callees": what this symbol calls (symbol targets only)
+ - "metrics": PageRank, betweenness centrality, percentile ranks
+ - "community": architectural community membership + neighbors
Example: get_context(["src/auth/service.py", "src/auth/middleware.py"])
+ Example: get_context(["src/auth/service.py::verify_token"], include=["source","callers"])
Args:
- targets: file paths, module paths, or symbol names.
- include: ["docs"] (default) | add "full_doc"/"ownership"/"last_change".
+ targets: file paths, module paths, or qualified symbol IDs.
+ include: list of data blocks to include (default: ["docs","freshness"]).
compact: default True (signatures only). False adds structure+imports+docstrings.
repo: usually omitted.
"""
+ if repo == "all":
+ return _unsupported_repo_all("get_context")
+ ctx = await _resolve_repo_context(repo)
+
# Default to docs + freshness when include is omitted. Freshness is
# critical for the agent to detect stale index data. The other blocks
# (ownership/last_change/decisions) are 200–500 bytes each and bloat
@@ -692,12 +1103,15 @@ async def get_context(
import time as _time
_t0 = _time.perf_counter()
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
results = await asyncio.gather(
*[
- _resolve_one_target(session, repository, t, include_set, compact)
+ _resolve_one_target(
+ session, repository, t, include_set, compact,
+ repo_path=str(ctx.path),
+ )
for t in targets
]
)
@@ -706,8 +1120,57 @@ async def get_context(
"targets": {r["target"]: r for r in results},
"_meta": _build_meta(
timing_ms=(_time.perf_counter() - _t0) * 1000,
- hint=_context_hint(targets, compact),
+ hint=_context_hint(targets, compact, include_set),
),
}
+
+ # Cross-repo enrichment (Phase 3 + 4)
+ from repowise.server.mcp_server._helpers import _is_workspace_mode
+
+ enricher = _state._cross_repo_enricher
+ if enricher is not None and enricher.has_data and _is_workspace_mode():
+ for target_key, target_data in response["targets"].items():
+ cross_repo: dict[str, Any] = {}
+
+ partners = enricher.get_cross_repo_partners(ctx.alias, target_key)
+ if partners:
+ cross_repo["co_changes_with"] = [
+ {"repo": p["repo"], "file": p["file"], "strength": p["strength"]}
+ for p in partners[:5]
+ ]
+
+ # Contract links (Phase 4)
+ if enricher.has_contract_data:
+ provider_links = enricher.get_contract_links_as_provider(
+ ctx.alias, target_key
+ )
+ consumer_links = enricher.get_contract_links_as_consumer(
+ ctx.alias, target_key
+ )
+ if provider_links or consumer_links:
+ contracts: dict[str, Any] = {}
+ if provider_links:
+ contracts["consumers"] = [
+ {
+ "consumer_repo": lk["consumer_repo"],
+ "contract_id": lk["contract_id"],
+ "type": lk["contract_type"],
+ }
+ for lk in provider_links[:5]
+ ]
+ if consumer_links:
+ contracts["providers"] = [
+ {
+ "provider_repo": lk["provider_repo"],
+ "contract_id": lk["contract_id"],
+ "type": lk["contract_type"],
+ }
+ for lk in consumer_links[:5]
+ ]
+ cross_repo["contracts"] = contracts
+
+ if cross_repo:
+ target_data["cross_repo"] = cross_repo
+
# Enforce the global token cap. See ``_truncate_to_budget`` for strategy.
return _truncate_to_budget(response)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
index 364b10478..19474c782 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
@@ -13,7 +13,12 @@ from repowise.core.persistence.models import (
GitMetadata,
)
from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _is_workspace_mode,
+ _resolve_all_contexts,
+ _resolve_repo_context,
+)
from repowise.server.mcp_server._server import mcp
@@ -77,8 +82,137 @@ async def get_dead_code(
no_unreachable: Suppress unreachable-file findings (default false).
no_unused_exports: Suppress unused-export findings (default false).
"""
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ # --- repo="all": aggregate dead code across all repos ---
+ if repo == "all":
+ contexts = await _resolve_all_contexts()
+ merged_findings: list[dict] = []
+ total_all = 0
+ total_deletable = 0
+ total_safe = 0
+ merged_by_kind: dict[str, int] = {}
+
+ for ctx in contexts:
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+
+ all_query = select(DeadCodeFinding).where(
+ DeadCodeFinding.repository_id == repository.id,
+ DeadCodeFinding.status == "open",
+ )
+ all_result = await session.execute(all_query)
+ repo_findings = list(all_result.scalars().all())
+
+ finding_paths = list({f.file_path for f in repo_findings})
+ git_meta_map: dict[str, Any] = {}
+ if finding_paths:
+ git_res = await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repository.id,
+ GitMetadata.file_path.in_(finding_paths),
+ )
+ )
+ git_meta_map = {g.file_path: g for g in git_res.scalars().all()}
+
+ # Apply scope-based exclusions
+ _excluded_kinds: set[str] = set()
+ if no_unreachable:
+ _excluded_kinds.add("unreachable_file")
+ if no_unused_exports:
+ _excluded_kinds.add("unused_export")
+ if not include_internals:
+ _excluded_kinds.add("unused_internal")
+ if not include_zombie_packages:
+ _excluded_kinds.add("zombie_package")
+
+ repo_filtered = repo_findings
+ if kind:
+ repo_filtered = [f for f in repo_filtered if f.kind == kind]
+ elif _excluded_kinds:
+ repo_filtered = [f for f in repo_filtered if f.kind not in _excluded_kinds]
+ if safe_only:
+ repo_filtered = [f for f in repo_filtered if f.safe_to_delete]
+ if min_confidence > 0:
+ repo_filtered = [f for f in repo_filtered if f.confidence >= min_confidence]
+ if directory:
+ prefix = directory.rstrip("/") + "/"
+ repo_filtered = [f for f in repo_filtered if f.file_path.startswith(prefix)]
+ if owner:
+ owner_lower = owner.lower()
+ repo_filtered = [
+ f
+ for f in repo_filtered
+ if f.primary_owner and f.primary_owner.lower() == owner_lower
+ ]
+
+ for f in repo_filtered:
+ serialized = _serialize_finding(f, git_meta_map)
+ serialized["repo"] = ctx.alias
+ merged_findings.append(serialized)
+
+ # Accumulate summary stats from unfiltered findings
+ total_all += len(repo_findings)
+ total_deletable += sum(f.lines for f in repo_findings if f.safe_to_delete)
+ total_safe += sum(1 for f in repo_findings if f.safe_to_delete)
+ for f in repo_findings:
+ merged_by_kind[f.kind] = merged_by_kind.get(f.kind, 0) + 1
+
+ # Sort merged findings by confidence descending
+ merged_findings.sort(key=lambda d: (-d["confidence"], -d["lines"]))
+
+ summary = {
+ "total_findings": total_all,
+ "filtered_findings": len(merged_findings),
+ "deletable_lines": total_deletable,
+ "safe_to_delete_count": total_safe,
+ "by_kind": merged_by_kind,
+ }
+
+ # Build pseudo-tiered structure from serialized dicts
+ high = [f for f in merged_findings if f["confidence"] >= 0.8]
+ medium = [f for f in merged_findings if 0.5 <= f["confidence"] < 0.8]
+ low = [f for f in merged_findings if f["confidence"] < 0.5]
+
+ def _tier_from_dicts(items: list[dict], desc: str) -> dict:
+ return {
+ "description": desc,
+ "count": len(items),
+ "lines": sum(f["lines"] for f in items),
+ "safe_count": sum(1 for f in items if f["safe_to_delete"]),
+ "findings": items[:limit],
+ "truncated": len(items) > limit,
+ }
+
+ tiers: dict[str, Any] = {}
+ if tier is None or tier == "high":
+ tiers["high"] = _tier_from_dicts(
+ high,
+ "High confidence (>=0.8): Zero references in the codebase. Safe to delete.",
+ )
+ if tier is None or tier == "medium":
+ tiers["medium"] = _tier_from_dicts(
+ medium,
+ "Medium confidence (0.5-0.8): Likely unused but may have indirect references. Review before deleting.",
+ )
+ if tier is None or tier == "low":
+ tiers["low"] = _tier_from_dicts(
+ low,
+ "Low confidence (<0.5): Potentially used via dynamic imports or reflection. Investigate first.",
+ )
+
+ # Cross-repo confidence adjustment for workspace-wide findings
+ _adjust_dead_code_cross_repo(tiers, None)
+
+ return {
+ "workspace": True,
+ "summary": summary,
+ "tiers": tiers,
+ "impact": _compute_impact(tiers),
+ }
+
+ # --- Single repo path ---
+ ctx = await _resolve_repo_context(repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
# Fetch all open findings for summary computation
all_query = select(DeadCodeFinding).where(
@@ -146,6 +280,9 @@ async def get_dead_code(
"by_kind": by_kind,
}
+ # Cross-repo confidence adjustment (Phase 3)
+ _adjust_dead_code_cross_repo(tiers, ctx.alias)
+
result: dict[str, Any] = {"summary": summary, "tiers": tiers}
# --- Grouping views ---
@@ -160,6 +297,42 @@ async def get_dead_code(
return result
+def _adjust_dead_code_cross_repo(tiers: dict, repo_alias: str | None) -> None:
+ """Reduce confidence for dead code findings that have cross-repo consumers.
+
+ Mutates findings in-place within the tier dicts.
+ """
+ enricher = _state._cross_repo_enricher
+ if enricher is None or not enricher.has_data or not _is_workspace_mode():
+ return
+
+ for tier_data in tiers.values():
+ for finding in tier_data.get("findings", []):
+ alias = finding.get("repo", repo_alias)
+ if not alias:
+ continue
+ file_path = finding.get("file_path", "")
+ consumers = enricher.has_cross_repo_consumers(alias, file_path)
+ if consumers:
+ original = finding["confidence"]
+ finding["confidence"] = round(original * 0.5, 2)
+ consumer_repos = sorted(set(c["repo"] for c in consumers))
+ finding["cross_repo_note"] = (
+ f"Confidence reduced: {len(consumers)} cross-repo consumer(s) "
+ f"in {', '.join(consumer_repos)}."
+ )
+ # Also check if other repos depend on this repo via package deps
+ if alias and finding.get("kind") == "unused_export":
+ depending = enricher.get_repos_depending_on(alias)
+ if depending and not consumers:
+ original = finding["confidence"]
+ finding["confidence"] = round(original * 0.3, 2)
+ finding["cross_repo_note"] = (
+ f"This export may be consumed by: {', '.join(depending)}. "
+ "Verify before deletion."
+ )
+
+
def _find_last_meaningful_change(gm: Any) -> str | None:
"""Find the date of the last feature/fix commit (not style/chore) from git metadata."""
if gm is None:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_decision_records.py b/packages/server/src/repowise/server/mcp_server/tool_decision_records.py
index d9c1dbcb4..fbaada7dd 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_decision_records.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_decision_records.py
@@ -8,8 +8,11 @@ from typing import Any
from repowise.core.persistence import crud
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import DecisionRecord
-from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
from repowise.server.mcp_server._server import mcp
_VALID_ACTIONS = frozenset({"create", "update", "update_status", "delete", "list", "get"})
@@ -111,6 +114,10 @@ async def update_decision_records(
limit: Max results for list (default 50).
offset: Offset for list pagination.
"""
+ if repo == "all":
+ return _unsupported_repo_all("update_decision_records")
+ ctx = await _resolve_repo_context(repo)
+
if action not in _VALID_ACTIONS:
return {
"error": f"Unknown action {action!r}. Valid actions: {', '.join(sorted(_VALID_ACTIONS))}"
@@ -120,8 +127,8 @@ async def update_decision_records(
if action == "create":
if not title:
return {"error": "action 'create' requires 'title'"}
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
rec = await crud.upsert_decision(
session,
repository_id=repository.id,
@@ -144,7 +151,7 @@ async def update_decision_records(
if action == "get":
if not decision_id:
return {"error": "action 'get' requires 'decision_id'"}
- async with get_session(_state._session_factory) as session:
+ async with get_session(ctx.session_factory) as session:
rec = await crud.get_decision(session, decision_id)
if rec is None:
return {"error": f"Decision {decision_id} not found"}
@@ -152,8 +159,8 @@ async def update_decision_records(
# --- list ---
if action == "list":
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
decisions = await crud.list_decisions(
session,
repository.id,
@@ -196,7 +203,7 @@ async def update_decision_records(
fields["tags"] = tags
if not fields:
return {"error": "action 'update' requires at least one field to change"}
- async with get_session(_state._session_factory) as session:
+ async with get_session(ctx.session_factory) as session:
rec = await crud.update_decision_by_id(session, decision_id, **fields)
if rec is None:
return {"error": f"Decision {decision_id} not found"}
@@ -208,7 +215,7 @@ async def update_decision_records(
return {"error": "action 'update_status' requires 'decision_id'"}
if not status:
return {"error": "action 'update_status' requires 'status'"}
- async with get_session(_state._session_factory) as session:
+ async with get_session(ctx.session_factory) as session:
try:
rec = await crud.update_decision_status(
session,
@@ -226,7 +233,7 @@ async def update_decision_records(
if action == "delete":
if not decision_id:
return {"error": "action 'delete' requires 'decision_id'"}
- async with get_session(_state._session_factory) as session:
+ async with get_session(ctx.session_factory) as session:
deleted = await crud.delete_decision(session, decision_id)
if not deleted:
return {"error": f"Decision {decision_id} not found"}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dependency.py b/packages/server/src/repowise/server/mcp_server/tool_dependency.py
index 7b04a876e..1774bcbdd 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dependency.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dependency.py
@@ -13,8 +13,11 @@ from repowise.core.persistence.models import (
GraphEdge,
GraphNode,
)
-from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
from repowise.server.mcp_server._server import mcp
@@ -31,8 +34,12 @@ async def get_dependency_path(source: str, target: str, repo: str | None = None)
target: Target file or module path.
repo: Repository path, name, or ID.
"""
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ if repo == "all":
+ return _unsupported_repo_all("get_dependency_path")
+ ctx = await _resolve_repo_context(repo)
+
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
edge_result = await session.execute(
select(GraphEdge).where(
@@ -88,7 +95,7 @@ async def get_dependency_path(source: str, target: str, repo: str | None = None)
"visual_context": _build_visual_context(graph, source, target, nodes, nx),
}
# Phase 4: check co-change coupling even without import dependency
- async with get_session(_state._session_factory) as session:
+ async with get_session(ctx.session_factory) as session:
src_res = await session.execute(
select(GitMetadata).where(
GitMetadata.repository_id == repository.id,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_diagram.py b/packages/server/src/repowise/server/mcp_server/tool_diagram.py
index b57070555..c9fe672ea 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_diagram.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_diagram.py
@@ -13,8 +13,11 @@ from repowise.core.persistence.models import (
GraphNode,
Page,
)
-from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
from repowise.server.mcp_server._server import mcp
@@ -52,8 +55,12 @@ async def get_architecture_diagram(
show_heat: Annotate nodes with churn heat colors (red=hot, yellow=warm, green=cold).
repo: Repository path, name, or ID.
"""
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ if repo == "all":
+ return _unsupported_repo_all("get_architecture_diagram")
+ ctx = await _resolve_repo_context(repo)
+
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
if scope == "repo":
# Return the architecture diagram page
@@ -179,7 +186,15 @@ async def get_architecture_diagram(
)
seen_nodes.add(tgt)
- lines.append(f" {src} --> {tgt}")
+ # Differentiate arrow style by edge type
+ etype = getattr(e, "edge_type", None) or "imports"
+ if etype == "calls":
+ arrow = "-.->"
+ elif etype in ("extends", "implements"):
+ arrow = "--|>"
+ else:
+ arrow = "-->"
+ lines.append(f" {src} {arrow} {tgt}")
# Apply heat + external classes
if node_classes:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_flows.py b/packages/server/src/repowise/server/mcp_server/tool_flows.py
new file mode 100644
index 000000000..e9f9905e1
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_flows.py
@@ -0,0 +1,130 @@
+"""MCP Tool: get_execution_flows — trace how the codebase executes.
+
+Hybrid approach: reads persisted entry-point scores from community_meta_json,
+then recomputes BFS call-path traces on demand from stored call edges. This
+avoids a dedicated execution_flows table while keeping the expensive scoring
+off the hot path.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+from repowise.core.persistence.crud import (
+ get_graph_node,
+ get_graph_nodes_by_ids,
+ get_top_entry_points,
+)
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import GraphNode
+from repowise.server.mcp_server._graph_utils import (
+ bfs_trace,
+ entry_point_score as _ep_score,
+ resolve_trace_communities,
+)
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._server import mcp
+
+
+async def get_execution_flows(
+ top_n: int = 10,
+ max_depth: int = 8,
+ entry_point: str | None = None,
+ repo: str | None = None,
+) -> dict:
+ """Show how the codebase executes: top entry points and their call traces.
+
+ Returns scored entry points with BFS call-path traces showing which
+ functions are called in sequence and whether the flow crosses
+ community boundaries.
+
+ Args:
+ top_n: Number of top entry points to trace (default 10).
+ max_depth: Max trace depth per flow (default 8).
+ entry_point: Trace from a specific symbol (overrides top_n scoring).
+ repo: Usually omitted.
+ """
+ if repo == "all":
+ return _unsupported_repo_all("get_execution_flows")
+ ctx = await _resolve_repo_context(repo)
+
+ t0 = time.perf_counter()
+
+ # Bound parameters
+ top_n = max(1, min(top_n, 50))
+ max_depth = max(1, min(max_depth, 20))
+
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ repo_id = repository.id
+
+ # Determine entry points
+ entry_nodes: list[tuple[GraphNode, float]] = []
+
+ if entry_point:
+ # Trace from a specific symbol
+ node = await get_graph_node(session, repo_id, entry_point)
+ if node is None:
+ return {
+ "entry_point": entry_point,
+ "error": f"Symbol not found: {entry_point!r}",
+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
+ }
+ entry_nodes = [(node, _ep_score(node))]
+ else:
+ # Top-N scored entry points from DB
+ top_nodes = await get_top_entry_points(
+ session, repo_id, min_score=0.0, limit=top_n
+ )
+ for n in top_nodes:
+ entry_nodes.append((n, _ep_score(n)))
+
+ if not entry_nodes:
+ return {
+ "total_entry_points": 0,
+ "flows": [],
+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
+ }
+
+ # BFS trace from each entry point
+ node_cache: dict[str, GraphNode] = {}
+ flows: list[dict[str, Any]] = []
+
+ for ep_node, ep_score in entry_nodes:
+ trace = await bfs_trace(
+ session, repo_id, ep_node.node_id, max_depth, node_cache
+ )
+
+ communities_visited, crosses = await resolve_trace_communities(
+ session, repo_id, trace, node_cache
+ )
+
+ flows.append({
+ "entry_point": ep_node.node_id,
+ "entry_point_name": ep_node.name or ep_node.node_id.split("::")[-1],
+ "entry_point_score": round(ep_score, 3),
+ "trace": trace,
+ "depth": len(trace) - 1,
+ "crosses_community": crosses,
+ "communities_visited": communities_visited,
+ })
+
+ # Sort by score descending
+ flows.sort(key=lambda f: -f["entry_point_score"])
+
+ result: dict[str, Any] = {
+ "total_entry_points": len(flows),
+ "flows": flows,
+ "_meta": _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ hint="Use get_callers_callees on any trace node for detail.",
+ ),
+ }
+ return result
diff --git a/packages/server/src/repowise/server/mcp_server/tool_metrics.py b/packages/server/src/repowise/server/mcp_server/tool_metrics.py
new file mode 100644
index 000000000..1a8743b70
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_metrics.py
@@ -0,0 +1,131 @@
+"""MCP Tool: get_graph_metrics — importance metrics for a file or symbol.
+
+Returns PageRank, betweenness centrality, community info, degree counts,
+and percentile ranks. Helps Claude Code assess how central/important a
+file or symbol is in the dependency graph.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from typing import Any
+
+from repowise.core.persistence.crud import (
+ get_all_file_metrics,
+ get_graph_node,
+ get_node_degree_counts,
+)
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import GraphNode
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._server import mcp
+
+
+def _percentile_rank(value: float, all_values: list[float]) -> int:
+ """Compute percentile rank (0-100) of *value* within *all_values*."""
+ if not all_values:
+ return 0
+ count_below = sum(1 for v in all_values if v < value)
+ return round(100 * count_below / len(all_values))
+
+
+async def get_graph_metrics(
+ target: str,
+ repo: str | None = None,
+) -> dict:
+ """Get importance metrics for a file or symbol: PageRank, centrality, community.
+
+ Returns raw scores plus percentile ranks across the repo. Helps assess
+ how central/important a file or symbol is in the dependency graph.
+
+ Args:
+ target: File path (e.g. "src/auth/service.py") or symbol ID ("path::Name").
+ repo: Usually omitted.
+ """
+ if repo == "all":
+ return _unsupported_repo_all("get_graph_metrics")
+ ctx = await _resolve_repo_context(repo)
+
+ t0 = time.perf_counter()
+ if not target or not target.strip():
+ return {
+ "target": target,
+ "error": "target is required",
+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
+ }
+
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ repo_id = repository.id
+
+ # Try exact lookup first
+ node = await get_graph_node(session, repo_id, target)
+ if node is None:
+ return {
+ "target": target,
+ "error": (
+ f"Node not found in graph: {target!r}. "
+ "Use get_context to find exact file paths or symbol IDs."
+ ),
+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
+ }
+
+ # Parse community metadata
+ try:
+ meta = json.loads(node.community_meta_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ meta = {}
+
+ community_label = meta.get("label", "")
+ entry_point_score = meta.get("entry_point_score")
+
+ # Degree counts
+ degrees = await get_node_degree_counts(session, repo_id, node.node_id)
+
+ # Percentile computation — compare against same node_type peers
+ all_nodes = await get_all_file_metrics(session, repo_id)
+ pr_values = [n.pagerank for n in all_nodes if n.pagerank is not None]
+ bt_values = [n.betweenness for n in all_nodes if n.betweenness is not None]
+
+ pr_pct = _percentile_rank(node.pagerank or 0.0, pr_values)
+ bt_pct = _percentile_rank(node.betweenness or 0.0, bt_values)
+
+ result: dict[str, Any] = {
+ "target": node.node_id,
+ "node_type": node.node_type,
+ "pagerank": round(node.pagerank or 0.0, 6),
+ "pagerank_percentile": pr_pct,
+ "betweenness": round(node.betweenness or 0.0, 6),
+ "betweenness_percentile": bt_pct,
+ "community_id": node.community_id,
+ "community_label": community_label or None,
+ "is_entry_point": node.is_entry_point,
+ "in_degree": degrees["in_degree"],
+ "out_degree": degrees["out_degree"],
+ }
+
+ if node.node_type == "symbol":
+ result["entry_point_score"] = (
+ round(entry_point_score, 3) if entry_point_score is not None else None
+ )
+ result["kind"] = node.kind
+ result["file"] = node.file_path
+
+ hint = None
+ if node.node_type == "file" and node.community_id is not None:
+ hint = f"Use get_community('{node.node_id}') to see all community members."
+ elif node.node_type == "symbol":
+ hint = f"Use get_callers_callees('{node.node_id}') to explore call relationships."
+
+ result["_meta"] = _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ hint=hint,
+ )
+ return result
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.py
index b5f1179ba..91c7cd4a1 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py
@@ -2,10 +2,11 @@
from __future__ import annotations
+import json
from collections import Counter, defaultdict
from typing import Any
-from sqlalchemy import select
+from sqlalchemy import func as sa_func, select
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import (
@@ -14,9 +15,148 @@ from repowise.core.persistence.models import (
Page,
)
from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _is_workspace_mode,
+ _resolve_all_contexts,
+ _resolve_repo_context,
+)
from repowise.server.mcp_server._server import mcp
-from repowise.server.services.knowledge_map import compute_knowledge_map
+
+
+# ---------------------------------------------------------------------------
+# repo="all" — workspace-level summary
+# ---------------------------------------------------------------------------
+
+
+async def _workspace_overview() -> dict:
+ """Build a concise workspace-level overview across all repos."""
+ contexts = await _resolve_all_contexts()
+ registry = _state._registry
+
+ repos_info: list[dict] = []
+ total_files = 0
+ total_symbols = 0
+
+ for ctx in contexts:
+ async with get_session(ctx.session_factory) as session:
+ repo_obj = await _get_repo(session)
+
+ # One-line summary from repo_overview page
+ ov_result = await session.execute(
+ select(Page.content).where(
+ Page.repository_id == repo_obj.id,
+ Page.page_type == "repo_overview",
+ )
+ )
+ ov_content = ov_result.scalar_one_or_none() or ""
+ summary = ov_content.split("\n")[0].strip("# ").strip()[:200] if ov_content else ""
+
+ # File and symbol counts
+ file_count_res = await session.execute(
+ select(sa_func.count()).select_from(GraphNode).where(
+ GraphNode.repository_id == repo_obj.id,
+ GraphNode.node_type == "file",
+ )
+ )
+ file_count = file_count_res.scalar_one()
+
+ symbol_count_res = await session.execute(
+ select(sa_func.count()).select_from(GraphNode).where(
+ GraphNode.repository_id == repo_obj.id,
+ GraphNode.node_type == "symbol",
+ )
+ )
+ symbol_count = symbol_count_res.scalar_one()
+
+ total_files += file_count
+ total_symbols += symbol_count
+
+ is_default = (
+ registry is not None
+ and ctx.alias == registry.get_default_alias()
+ )
+
+ repos_info.append({
+ "alias": ctx.alias,
+ "path": str(ctx.path),
+ "summary": summary,
+ "file_count": file_count,
+ "symbol_count": symbol_count,
+ "is_default": is_default,
+ })
+
+ # Cross-repo topology (Phase 3 + 4)
+ cross_repo_topology: dict[str, Any] = {}
+ enricher = _state._cross_repo_enricher
+ if enricher is not None and enricher.has_data:
+ cross_repo_topology = enricher.get_cross_repo_summary()
+ if enricher.has_contract_data:
+ cross_repo_topology["contracts"] = enricher.get_contract_summary()
+ # Add per-repo package deps
+ for repo_info in repos_info:
+ deps = enricher.get_package_deps(repo_info["alias"])
+ if deps:
+ repo_info["depends_on"] = sorted(
+ set(d["target_repo"] for d in deps)
+ )
+
+ result: dict[str, Any] = {
+ "workspace": True,
+ "workspace_root": str(registry.workspace_root) if registry else "",
+ "total_repos": len(repos_info),
+ "total_files": total_files,
+ "total_symbols": total_symbols,
+ "repos": repos_info,
+ "hint": (
+ "Use repo='<alias>' to query a specific repo. "
+ "Omit repo to use the default."
+ ),
+ }
+ if cross_repo_topology:
+ result["cross_repo_topology"] = cross_repo_topology
+
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Workspace footer — appended to default-repo overview
+# ---------------------------------------------------------------------------
+
+
+def _build_workspace_footer() -> dict | None:
+ """Build workspace context footer for the default overview."""
+ registry = _state._registry
+ if registry is None:
+ return None
+
+ default_alias = registry.get_default_alias()
+ other_repos = [
+ a for a in registry.get_all_aliases() if a != default_alias
+ ]
+ if not other_repos:
+ return None
+
+ footer: dict[str, Any] = {
+ "workspace_root": str(registry.workspace_root),
+ "default_repo": default_alias,
+ "other_repos": other_repos,
+ "hint": (
+ "This repo is part of a workspace. "
+ f"Other repos: {', '.join(other_repos)}. "
+ "Use repo='<alias>' to query another repo, "
+ "or repo='all' for workspace-wide results."
+ ),
+ }
+
+ # Cross-repo intelligence (Phase 3 + 4)
+ enricher = _state._cross_repo_enricher
+ if enricher is not None and enricher.has_data:
+ footer["cross_repo"] = enricher.get_cross_repo_summary()
+ if enricher.has_contract_data:
+ footer["contract_links"] = enricher.get_contract_summary()
+
+ return footer
@mcp.tool()
@@ -25,11 +165,22 @@ async def get_overview(repo: str | None = None) -> dict:
Best first call when starting to explore an unfamiliar codebase.
+ In workspace mode:
+ - Omit ``repo`` for the default repo overview (includes workspace context,
+ cross-repo co-changes, package dependencies, and API contract links).
+ - Use ``repo="all"`` for a workspace-level summary of all repos including
+ cross-repo topology and contract links (HTTP routes, gRPC services, topics).
+ - Use ``repo="<alias>"`` to query a specific repo.
+
Args:
- repo: Repository path, name, or ID. Omit if only one repo exists.
+ repo: Repository alias, path, or ID. Use ``"all"`` for workspace overview.
"""
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ if repo == "all":
+ return await _workspace_overview()
+
+ ctx = await _resolve_repo_context(repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
# Get repo overview page
result = await session.execute(
@@ -40,15 +191,6 @@ async def get_overview(repo: str | None = None) -> dict:
)
overview_page = result.scalar_one_or_none()
- # Get architecture diagram page
- result = await session.execute(
- select(Page).where(
- Page.repository_id == repository.id,
- Page.page_type == "architecture_diagram",
- )
- )
- arch_page = result.scalar_one_or_none()
-
# Get module pages
result = await session.execute(
select(Page)
@@ -144,56 +286,95 @@ async def get_overview(repo: str | None = None) -> dict:
)[:10]
# knowledge_silos: files where primary owner has > 80% ownership
+ # Filter out boilerplate (migrations, __init__.py, config, lock files)
+ silo_exclude_patterns = (
+ "alembic/versions/", "__init__.py", "migrations/",
+ ".lock", "package-lock", "conftest.py",
+ )
knowledge_silos = [
g.file_path
- for g in all_git
+ for g in sorted(all_git, key=lambda g: -(g.primary_owner_commit_pct or 0.0))
if (g.primary_owner_commit_pct or 0.0) > 0.8
- ][:30] # Cap to keep response size bounded
+ and not any(pat in g.file_path for pat in silo_exclude_patterns)
+ ][:10]
+
+ knowledge_map = {
+ "top_owners": top_owners,
+ "knowledge_silos": knowledge_silos,
+ }
- # onboarding_targets: high-centrality files with least docs
- # pagerank from graph_nodes; doc length from wiki_pages
+ # C. Community summary ---------------------------------------------------
+ community_summary: list[dict[str, Any]] = []
+ # Fetch file nodes for community grouping
+ if not all_git:
node_result = await session.execute(
select(GraphNode).where(
GraphNode.repository_id == repository.id,
- GraphNode.is_test == False, # noqa: E712
+ GraphNode.node_type == "file",
)
)
all_nodes = node_result.scalars().all()
-
- # Build word-count map from wiki_pages (file pages)
- page_result = await session.execute(
- select(Page).where(
- Page.repository_id == repository.id,
- Page.page_type == "file_page",
+ else:
+ node_result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repository.id,
+ GraphNode.is_test == False, # noqa: E712
)
)
- doc_words: dict[str, int] = {
- p.target_path: len(p.content.split()) for p in page_result.scalars().all()
- }
+ all_nodes = node_result.scalars().all()
- onboarding_candidates = [
- {
- "path": n.node_id,
- "pagerank": n.pagerank,
- "doc_words": doc_words.get(n.node_id, 0),
- }
- for n in all_nodes
- if n.pagerank > 0.0
- ]
- # Sort by fewest doc words first (least documented), then by highest pagerank
- onboarding_candidates.sort(key=lambda x: (x["doc_words"], -x["pagerank"]))
- onboarding_targets = [c["path"] for c in onboarding_candidates[:5]]
+ # Group file nodes by community_id
+ community_groups: dict[int, list[GraphNode]] = defaultdict(list)
+ for n in all_nodes:
+ if n.node_type == "file" and n.community_id is not None:
+ community_groups[n.community_id].append(n)
- knowledge_map = {
- "top_owners": top_owners,
- "knowledge_silos": knowledge_silos,
- "onboarding_targets": onboarding_targets,
- }
+ # Sort communities by size descending, take top 10
+ # Skip communities with generic/unhelpful labels
+ generic_labels = {"packages", "src", "lib", "core", "app", ""}
+ for cid, members in sorted(
+ community_groups.items(), key=lambda x: -len(x[1])
+ ):
+ if len(community_summary) >= 10:
+ break
+ label = ""
+ cohesion = 0.0
+ if members:
+ try:
+ meta = json.loads(members[0].community_meta_json or "{}")
+ label = meta.get("label", "")
+ cohesion = meta.get("cohesion", 0.0)
+ except (json.JSONDecodeError, TypeError):
+ pass
- return {
+ # Build a useful label: if the heuristic label is generic,
+ # use the most common directory segment among members
+ display_label = label
+ if not label or label.lower() in generic_labels:
+ # Find dominant specific directory
+ dir_counts: Counter = Counter()
+ for m in members:
+ parts = m.node_id.split("/")
+ # Use the deepest meaningful directory segment
+ for p in reversed(parts[:-1]):
+ if p.lower() not in generic_labels and p not in ("src",):
+ dir_counts[p] += 1
+ break
+ if dir_counts:
+ display_label = dir_counts.most_common(1)[0][0]
+ else:
+ display_label = f"cluster_{cid}"
+
+ community_summary.append({
+ "id": cid,
+ "label": display_label,
+ "size": len(members),
+ "cohesion": round(cohesion, 3),
+ })
+
+ result = {
"title": overview_page.title if overview_page else repository.name,
"content_md": overview_page.content if overview_page else "No overview generated yet.",
- "architecture_diagram_mermaid": arch_page.content if arch_page else None,
"key_modules": [
{
"name": p.title,
@@ -209,4 +390,12 @@ async def get_overview(repo: str | None = None) -> dict:
"entry_points": [n.node_id for n in entry_nodes[:15]],
"git_health": git_health,
"knowledge_map": knowledge_map,
+ "community_summary": community_summary,
}
+
+ # Append workspace context footer when in workspace mode
+ ws_footer = _build_workspace_footer()
+ if ws_footer:
+ result["workspace"] = ws_footer
+
+ return result
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk.py
index fa4812793..968253b68 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py
@@ -21,7 +21,12 @@ from repowise.core.persistence.models import (
Repository,
)
from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _is_workspace_mode,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
from repowise.server.mcp_server._server import mcp
_FIX_PATTERN = re.compile(
@@ -43,7 +48,7 @@ def _derive_change_pattern(categories: dict[str, int]) -> str:
labels = {
"feature": "feature-active",
"refactor": "primarily refactored",
- "fix": "bug-prone",
+ "fix": "fix-heavy",
"dependency": "dependency-churn",
}
return labels.get(dominant, dominant)
@@ -130,22 +135,36 @@ def _compute_impact_surface(
async def _check_test_gap(session: AsyncSession, repo_id: str, target: str) -> bool:
- """Return True if no test file corresponding to *target* exists in graph_nodes."""
+ """Return True if no test file corresponding to *target* exists in graph_nodes.
+
+ Test files themselves (is_test=True) are never considered to have a test gap.
+ """
import os
+ # Test files don't need tests — skip the check entirely
+ node_res = await session.execute(
+ select(GraphNode.is_test).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_id == target,
+ ).limit(1)
+ )
+ row = node_res.scalar_one_or_none()
+ if row is True:
+ return False
+
base = os.path.splitext(os.path.basename(target))[0]
ext = os.path.splitext(target)[1].lstrip(".")
# Build a LIKE pattern broad enough to catch test_<base>, <base>_test, <base>.spec.*
patterns = [f"%test_{base}%", f"%{base}_test%", f"%{base}.spec.{ext}%"]
for pat in patterns:
- row = await session.execute(
+ res = await session.execute(
select(GraphNode).where(
GraphNode.repository_id == repo_id,
GraphNode.is_test == True, # noqa: E712
GraphNode.node_id.like(pat),
).limit(1)
)
- if row.scalar_one_or_none() is not None:
+ if res.scalar_one_or_none() is not None:
return False
return True
@@ -310,6 +329,10 @@ async def _assess_one_target(
if bus_factor == 1 and (meta.commit_count_total or 0) > 20:
bus_note = f", bus factor risk (sole maintainer: {owner})"
+ # NOTE: risk_summary is built here but dependents_count may be updated
+ # later by cross-repo enrichment. We store dep_count now and let the
+ # outer function rebuild the summary after enrichment if needed.
+ result_data["_base_dep_count"] = dep_count
result_data["risk_summary"] = (
f"{target} — hotspot score {hotspot_score:.0%} ({trend}), "
f"{dep_count} dependents, {risk_type}, {change_pattern}, "
@@ -336,6 +359,11 @@ async def get_risk(
- test_gap: bool — True if no test file exists for this file
- security_signals: list of {kind, severity, snippet} from static analysis
+ In workspace mode, includes cross-repo impact: co-change partners from
+ other repos, affected repos, and API contract links (files in other repos
+ that consume HTTP/gRPC/topic contracts provided by this file, or providers
+ this file depends on). Cross-repo consumers increase the dependents count.
+
Plus the top 5 global hotspots for ambient awareness.
Pass ``changed_files`` for PR review / blast radius analysis. When provided,
@@ -354,8 +382,11 @@ async def get_risk(
repo: Repository path, name, or ID.
changed_files: Optional list of files changed in a PR for blast-radius analysis.
"""
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ if repo == "all":
+ return _unsupported_repo_all("get_risk")
+ ctx = await _resolve_repo_context(repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
repo_id = repository.id
# Pre-load edges
@@ -426,6 +457,73 @@ async def get_risk(
analyzer = PRBlastRadiusAnalyzer(session, repo_id)
pr_blast_radius = await analyzer.analyze_files(changed_files)
+ # Cross-repo blast radius enrichment (Phase 3 + 4)
+ enricher = _state._cross_repo_enricher
+ if enricher is not None and enricher.has_data and _is_workspace_mode():
+ for r in results:
+ target = r["target"]
+ cross_partners = enricher.get_cross_repo_partners(ctx.alias, target)
+ affected_repos = enricher.get_affected_repos(ctx.alias, target)
+ if cross_partners or affected_repos:
+ r["cross_repo_impact"] = {
+ "cross_repo_consumers": [
+ {"repo": p["repo"], "file": p["file"], "strength": p["strength"]}
+ for p in cross_partners[:5]
+ ],
+ "affected_repos": affected_repos,
+ }
+ r["dependents_count"] = r.get("dependents_count", 0) + len(cross_partners)
+ # Rebuild risk_summary with updated dependents count
+ if "_base_dep_count" in r:
+ r["risk_summary"] = r["risk_summary"].replace(
+ f"{r['_base_dep_count']} dependents",
+ f"{r['dependents_count']} dependents",
+ )
+
+ # Contract links (Phase 4)
+ if enricher.has_contract_data:
+ provider_links = enricher.get_contract_links_as_provider(
+ ctx.alias, target
+ )
+ consumer_links = enricher.get_contract_links_as_consumer(
+ ctx.alias, target
+ )
+ if provider_links or consumer_links:
+ impact = r.setdefault("cross_repo_impact", {})
+ if provider_links:
+ impact["contract_consumers"] = [
+ {
+ "consumer_repo": lk["consumer_repo"],
+ "consumer_file": lk["consumer_file"],
+ "contract_id": lk["contract_id"],
+ "type": lk["contract_type"],
+ }
+ for lk in provider_links[:5]
+ ]
+ r["dependents_count"] = (
+ r.get("dependents_count", 0) + len(provider_links)
+ )
+ if consumer_links:
+ impact["contract_providers"] = [
+ {
+ "provider_repo": lk["provider_repo"],
+ "provider_file": lk["provider_file"],
+ "contract_id": lk["contract_id"],
+ "type": lk["contract_type"],
+ }
+ for lk in consumer_links[:5]
+ ]
+
+ # Final risk_summary rebuild for any remaining dependents_count updates
+ # (e.g. contract provider links) and cleanup of internal keys.
+ for r in results:
+ base = r.pop("_base_dep_count", None)
+ if base is not None and r.get("dependents_count", base) != base:
+ r["risk_summary"] = r["risk_summary"].replace(
+ f"{base} dependents",
+ f"{r['dependents_count']} dependents",
+ )
+
response: dict = {
"targets": {r["target"]: r for r in results},
"global_hotspots": global_hotspots,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.py
index 4c0087848..8aa9a5e12 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -13,9 +13,78 @@ from repowise.core.persistence.models import (
Page,
)
from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_all_contexts,
+ _resolve_repo_context,
+)
from repowise.server.mcp_server._server import mcp
+# Minimum relevance score below which results are dropped. Prevents
+# returning semantically unrelated pages when the corpus has no real match.
+_MIN_RELEVANCE_SCORE = 0.03
+
+
+async def _search_single_repo(ctx, query: str, limit: int, page_type: str | None):
+ """Run search against a single repo context. Returns list of result dicts."""
+ # Wait for vector store readiness
+ if ctx.vector_store_ready is not None:
+ with contextlib.suppress(TimeoutError):
+ await asyncio.wait_for(ctx.vector_store_ready.wait(), timeout=30.0)
+
+ fetch_limit = limit * 3 if page_type else limit
+ results = []
+ with contextlib.suppress(TimeoutError, Exception):
+ results = await asyncio.wait_for(
+ ctx.vector_store.search(query, limit=fetch_limit),
+ timeout=8.0,
+ )
+ if not results:
+ with contextlib.suppress(Exception):
+ results = await ctx.fts.search(query, limit=fetch_limit)
+
+ output = []
+ for r in results:
+ if page_type and r.page_type != page_type:
+ continue
+ if r.score < _MIN_RELEVANCE_SCORE:
+ continue
+ output.append({
+ "page_id": r.page_id,
+ "title": r.title,
+ "page_type": r.page_type,
+ "snippet": r.snippet,
+ "relevance_score": r.score,
+ })
+
+ return output[:limit]
+
+
+async def _federated_search(query: str, limit: int, page_type: str | None) -> dict:
+ """Search across all repos using Reciprocal Rank Fusion."""
+ contexts = await _resolve_all_contexts()
+ all_results = []
+
+ for ctx in contexts:
+ repo_results = await _search_single_repo(ctx, query, limit, page_type)
+ for rank, item in enumerate(repo_results):
+ item["repo"] = ctx.alias
+ item["rrf_score"] = 1.0 / (rank + 60) # RRF constant k=60
+ all_results.extend(repo_results)
+
+ # Sort by RRF score and take top N
+ all_results.sort(key=lambda x: x.get("rrf_score", 0), reverse=True)
+ output = all_results[:limit]
+
+ # Derive confidence from RRF position
+ if output:
+ max_rrf = max(item.get("rrf_score", 0) for item in output)
+ for item in output:
+ raw = item.get("rrf_score", 0)
+ item["confidence_score"] = round(raw / max_rrf, 2) if max_rrf > 0 else 0.0
+
+ return {"results": output}
+
@mcp.tool()
async def search_codebase(
@@ -27,44 +96,47 @@ async def search_codebase(
"""Semantic search over the wiki. Use when ``get_answer`` did not return
a confident result and you need to discover candidate pages by topic.
+ In workspace mode, use ``repo="all"`` to search across all repos.
+
Args:
query: natural-language search query.
limit: maximum number of results to return (default 5).
page_type: optional filter on page kind (e.g. ``file_page``,
``module_page``, ``symbol_spotlight``).
- repo: repository identifier; usually omitted in single-repo deployments.
+ repo: repository alias, or ``"all"`` for workspace-wide search.
"""
- async with get_session(_state._session_factory) as session:
- # Ensure repo exists
- await _get_repo(session, repo)
-
- # Wait for the background task to finish loading and pre-connecting the
- # vector stores. The task imports lancedb in a thread (avoids blocking
- # the event loop with DLL loading) and calls _ensure_connected() so the
- # first search() call hits a warm connection. Typically completes in
- # under a second for a local LanceDB; 30 s timeout is a hard safety net.
- if _state._vector_store_ready is not None:
+ if repo == "all":
+ return await _federated_search(query, limit, page_type)
+
+ ctx = await _resolve_repo_context(repo)
+
+ async with get_session(ctx.session_factory) as session:
+ # Validate repo exists in DB
+ await _get_repo(session)
+
+ # Wait for vector store readiness
+ if ctx.vector_store_ready is not None:
with contextlib.suppress(TimeoutError):
- await asyncio.wait_for(_state._vector_store_ready.wait(), timeout=30.0)
+ await asyncio.wait_for(ctx.vector_store_ready.wait(), timeout=30.0)
# Try semantic search, fall back to FTS.
- # Over-fetch when filtering by page_type to avoid returning 0 results.
- # 8 s safety-net timeout covers any remaining Gemini API latency.
fetch_limit = limit * 3 if page_type else limit
results = []
with contextlib.suppress(TimeoutError, Exception):
results = await asyncio.wait_for(
- _state._vector_store.search(query, limit=fetch_limit),
+ ctx.vector_store.search(query, limit=fetch_limit),
timeout=8.0,
)
if not results:
with contextlib.suppress(Exception):
- results = await _state._fts.search(query, limit=fetch_limit)
+ results = await ctx.fts.search(query, limit=fetch_limit)
output = []
for r in results:
if page_type and r.page_type != page_type:
continue
+ if r.score < _MIN_RELEVANCE_SCORE:
+ continue
output.append(
{
"page_id": r.page_id,
@@ -80,7 +152,7 @@ async def search_codebase(
# Batch-lookup page target paths for git freshness boost
if output:
page_ids = [item["page_id"] for item in output]
- async with get_session(_state._session_factory) as session:
+ async with get_session(ctx.session_factory) as session:
res = await session.execute(
select(Page.id, Page.target_path).where(Page.id.in_(page_ids))
)
@@ -114,8 +186,6 @@ async def search_codebase(
output.sort(key=lambda x: x.get("relevance_score", 0), reverse=True)
# Derive confidence_score from relative position in the result set.
- # The top result gets 1.0; others are scaled proportionally by their
- # relevance score relative to the best match.
if output:
max_score = max((item.get("relevance_score") or 0) for item in output)
for item in output:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
index 29cd03ba4..49bc29425 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
@@ -37,8 +37,11 @@ from sqlalchemy import select
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import WikiSymbol
-from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._helpers import (
+ _get_repo,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+)
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._meta import symbol_hint as _symbol_hint
from repowise.server.mcp_server._server import mcp
@@ -290,6 +293,10 @@ async def get_symbol(
context_lines: extra source lines before/after (0–50, default 0).
repo: usually omitted.
"""
+ if repo == "all":
+ return _unsupported_repo_all("get_symbol")
+ ctx = await _resolve_repo_context(repo)
+
t0 = time.perf_counter()
if not symbol_id or not symbol_id.strip():
return {
@@ -302,8 +309,8 @@ async def get_symbol(
# defeat the whole point of symbol-level retrieval.
context_lines = max(0, min(50, context_lines))
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
row = await _resolve_symbol(session, repository.id, symbol_id)
if row is None:
@@ -317,14 +324,14 @@ async def get_symbol(
"_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
}
- if not _state._repo_path:
+ if not ctx.path:
return {
"symbol_id": symbol_id,
"error": "MCP server has no repo path configured",
"_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
}
- repo_root = Path(_state._repo_path)
+ repo_root = Path(str(ctx.path))
source, start, end, total = _slice_source(
repo_root, row.file_path, row.start_line, row.end_line, context_lines
)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.py
index ccbd8415a..7467a4710 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -15,12 +15,14 @@ from repowise.core.persistence.models import (
DecisionRecord,
GitMetadata,
)
-from repowise.server.mcp_server import _state
from repowise.server.mcp_server._helpers import (
_build_origin_story,
_compute_alignment,
_get_repo,
_is_path,
+ _resolve_all_contexts,
+ _resolve_repo_context,
+ _unsupported_repo_all,
)
from repowise.server.mcp_server._server import mcp
@@ -49,12 +51,48 @@ async def get_why(
these files are prioritized in results.
repo: Repository path, name, or ID.
"""
+ # --- repo="all": search decisions across ALL repos ---
+ if repo == "all":
+ if not query:
+ return _unsupported_repo_all("get_why (health dashboard)")
+
+ contexts = await _resolve_all_contexts()
+ merged: list[dict] = []
+ for ctx in contexts:
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ res = await session.execute(
+ select(DecisionRecord).where(
+ DecisionRecord.repository_id == repository.id,
+ )
+ )
+ for d in res.scalars().all():
+ text = f"{d.title} {d.decision} {d.rationale} {d.context}".lower()
+ if any(w in text for w in query.lower().split()):
+ merged.append({
+ "repo": ctx.alias,
+ "id": d.id,
+ "title": d.title,
+ "status": d.status,
+ "decision": d.decision,
+ "rationale": d.rationale,
+ "source": d.source,
+ "confidence": d.confidence,
+ })
+ return {
+ "mode": "search",
+ "query": query,
+ "workspace": True,
+ "decisions": merged[:15],
+ }
+
# --- Mode 1: No query → health dashboard ---
if not query:
from repowise.core.persistence.crud import get_decision_health_summary
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ ctx = await _resolve_repo_context(repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
health = await get_decision_health_summary(session, repository.id)
stale = health["stale_decisions"]
@@ -93,8 +131,9 @@ async def get_why(
# --- Mode 2: Path → decisions, origin story, alignment ---
if _is_path(query):
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ ctx = await _resolve_repo_context(repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
res = await session.execute(
select(DecisionRecord).where(
DecisionRecord.repository_id == repository.id,
@@ -163,8 +202,9 @@ async def get_why(
# --- Mode 3: Natural language → target-aware search ---
from repowise.core.persistence.crud import list_decisions as _list_decisions
- async with get_session(_state._session_factory) as session:
- repository = await _get_repo(session, repo)
+ ctx = await _resolve_repo_context(repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
all_decisions = await _list_decisions(
session, repository.id, include_proposed=True, limit=200
)
@@ -223,15 +263,15 @@ async def get_why(
# Semantic search over decision vector store
decision_results = []
with contextlib.suppress(Exception):
- decision_results = await _state._decision_store.search(query, limit=5)
+ decision_results = await ctx.decision_store.search(query, limit=5)
# Semantic search over documentation
doc_results = []
try:
- doc_results = await _state._vector_store.search(query, limit=3)
+ doc_results = await ctx.vector_store.search(query, limit=3)
except Exception:
with contextlib.suppress(Exception):
- doc_results = await _state._fts.search(query, limit=3)
+ doc_results = await ctx.fts.search(query, limit=3)
# Merge keyword matches with semantic results (dedup by ID)
seen_ids: set[str] = set()
@@ -284,7 +324,7 @@ async def get_why(
# If targets provided, include target context
if targets:
- async with get_session(_state._session_factory) as session2:
+ async with get_session(ctx.session_factory) as session2:
# Load all git metadata for cross-file search
all_git_res = await session2.execute(
select(GitMetadata).where(
diff --git a/packages/server/src/repowise/server/routers/graph.py b/packages/server/src/repowise/server/routers/graph.py
index 96ec597d0..bc8e0c4f7 100644
--- a/packages/server/src/repowise/server/routers/graph.py
+++ b/packages/server/src/repowise/server/routers/graph.py
@@ -17,20 +17,39 @@ from repowise.core.persistence.models import (
Page,
)
from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.mcp_server._graph_utils import (
+ bfs_trace,
+ community_cohesion,
+ community_label,
+ entry_point_score as _ep_score,
+ parse_community_meta,
+ percentile_rank,
+ resolve_trace_communities,
+)
from repowise.server.schemas import (
+ CallerCalleeEntry,
+ CallersCalleesResponse,
+ CommunityDetailResponse,
+ CommunityMember,
+ CommunitySummaryItem,
DeadCodeGraphNodeResponse,
DeadCodeGraphResponse,
EgoGraphResponse,
+ ExecutionFlowEntry,
+ ExecutionFlowsResponse,
GitMetadataResponse,
GraphEdgeResponse,
GraphExportResponse,
+ GraphMetricsResponse,
GraphNodeResponse,
HotFilesGraphResponse,
HotFilesNodeResponse,
ModuleEdgeResponse,
ModuleGraphResponse,
ModuleNodeResponse,
+ NeighboringCommunity,
NodeSearchResult,
+ SymbolNodeSummary,
)
router = APIRouter(
@@ -706,3 +725,339 @@ async def dependency_path(
"distance": len(path) - 1,
"explanation": f"Shortest path from {source} to {target} has {len(path) - 1} hops",
}
+
+
+# ---------------------------------------------------------------------------
+# Communities
+# ---------------------------------------------------------------------------
+
+
[email protected]("/{repo_id}/communities", response_model=list[CommunitySummaryItem])
+async def list_communities(
+ repo_id: str,
+ limit: int = Query(20, ge=1, le=100),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> list[CommunitySummaryItem]:
+ """Return top communities by member count with labels and cohesion scores."""
+ repo = await crud.get_repository(session, repo_id)
+ if repo is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+ all_nodes = await crud.get_all_file_metrics(session, repo_id)
+
+ # Group by community_id
+ buckets: dict[int, list[GraphNode]] = {}
+ for n in all_nodes:
+ cid = n.community_id if n.community_id is not None else 0
+ buckets.setdefault(cid, []).append(n)
+
+ items: list[CommunitySummaryItem] = []
+ for cid, members in sorted(buckets.items(), key=lambda kv: -len(kv[1])):
+ # Pick top-pagerank member for label/cohesion extraction
+ top = max(members, key=lambda m: m.pagerank or 0.0)
+ items.append(
+ CommunitySummaryItem(
+ community_id=cid,
+ label=community_label(top),
+ cohesion=community_cohesion(top),
+ member_count=len(members),
+ top_file=top.node_id,
+ )
+ )
+ if len(items) >= limit:
+ break
+
+ return items
+
+
+ "/{repo_id}/communities/{community_id}",
+ response_model=CommunityDetailResponse,
+)
+async def get_community_detail(
+ repo_id: str,
+ community_id: int,
+ include_members: bool = Query(True),
+ member_limit: int = Query(30, ge=1, le=200),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> CommunityDetailResponse:
+ """Return detailed info for a single community."""
+ repo = await crud.get_repository(session, repo_id)
+ if repo is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+ all_members = await crud.get_community_members(
+ session, repo_id, community_id, node_type="file", limit=200
+ )
+ if not all_members:
+ raise HTTPException(status_code=404, detail="Community not found or empty")
+
+ top = max(all_members, key=lambda m: m.pagerank or 0.0)
+ label = community_label(top)
+ cohesion = community_cohesion(top)
+
+ members_out: list[CommunityMember] = []
+ if include_members:
+ for m in all_members[:member_limit]:
+ members_out.append(
+ CommunityMember(
+ path=m.node_id,
+ pagerank=round(m.pagerank or 0.0, 6),
+ is_entry_point=m.is_entry_point,
+ )
+ )
+
+ # Neighboring communities
+ cross_edges = await crud.get_cross_community_edges(session, repo_id, community_id)
+ # Resolve labels for neighbors
+ neighbor_cids = [ce["target_community_id"] for ce in cross_edges]
+ neighbor_labels: dict[int, str] = {}
+ for ncid in neighbor_cids:
+ nbr_members = await crud.get_community_members(
+ session, repo_id, ncid, node_type="file", limit=1
+ )
+ if nbr_members:
+ neighbor_labels[ncid] = community_label(nbr_members[0])
+ else:
+ neighbor_labels[ncid] = f"cluster_{ncid}"
+
+ neighbors = [
+ NeighboringCommunity(
+ community_id=ce["target_community_id"],
+ label=neighbor_labels.get(ce["target_community_id"], ""),
+ cross_edge_count=ce["edge_count"],
+ )
+ for ce in cross_edges[:10]
+ ]
+
+ return CommunityDetailResponse(
+ community_id=community_id,
+ label=label,
+ cohesion=cohesion,
+ member_count=len(all_members),
+ members=members_out,
+ truncated=len(all_members) > member_limit,
+ neighboring_communities=neighbors,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Graph Metrics
+# ---------------------------------------------------------------------------
+
+
[email protected]("/{repo_id}/metrics", response_model=GraphMetricsResponse)
+async def get_graph_metrics(
+ repo_id: str,
+ node_id: str = Query(..., description="File path or symbol_id"),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> GraphMetricsResponse:
+ """Return importance metrics for a file or symbol with percentile ranks."""
+ repo = await crud.get_repository(session, repo_id)
+ if repo is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+ node = await crud.get_graph_node(session, repo_id, node_id)
+ if node is None:
+ raise HTTPException(status_code=404, detail=f"Node not found: {node_id}")
+
+ # Percentiles computed against all file-type nodes
+ all_files = await crud.get_all_file_metrics(session, repo_id)
+ all_pr = [n.pagerank or 0.0 for n in all_files]
+ all_bw = [n.betweenness or 0.0 for n in all_files]
+
+ degrees = await crud.get_node_degree_counts(session, repo_id, node_id)
+ meta = parse_community_meta(node)
+
+ return GraphMetricsResponse(
+ target=node_id,
+ node_type=node.node_type or "file",
+ pagerank=round(node.pagerank or 0.0, 6),
+ pagerank_percentile=percentile_rank(node.pagerank or 0.0, all_pr),
+ betweenness=round(node.betweenness or 0.0, 6),
+ betweenness_percentile=percentile_rank(node.betweenness or 0.0, all_bw),
+ community_id=node.community_id or 0,
+ community_label=meta.get("label") or None,
+ is_entry_point=node.is_entry_point,
+ in_degree=degrees["in_degree"],
+ out_degree=degrees["out_degree"],
+ entry_point_score=meta.get("entry_point_score"),
+ kind=node.kind if node.node_type == "symbol" else None,
+ file=node.file_path if node.node_type == "symbol" else None,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Callers / Callees
+# ---------------------------------------------------------------------------
+
+
[email protected]("/{repo_id}/callers-callees", response_model=CallersCalleesResponse)
+async def get_callers_callees(
+ repo_id: str,
+ symbol_id: str = Query(..., description="Symbol node ID (path::Name)"),
+ direction: str = Query("both", description="callers, callees, or both"),
+ edge_types: str = Query("calls", description="Comma-separated edge types"),
+ limit: int = Query(20, ge=1, le=100),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> CallersCalleesResponse:
+ """Find who calls a symbol and what it calls. Also works for class hierarchy."""
+ repo = await crud.get_repository(session, repo_id)
+ if repo is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+ if direction not in ("callers", "callees", "both"):
+ direction = "both"
+
+ et_list = [t.strip() for t in edge_types.split(",") if t.strip()]
+ if not et_list:
+ et_list = ["calls"]
+
+ # Resolve symbol: exact then fuzzy
+ node = await crud.get_graph_node(session, repo_id, symbol_id)
+ if node is None or node.node_type != "symbol":
+ # Fuzzy: try bare name
+ bare = symbol_id.split("::")[-1] if "::" in symbol_id else symbol_id
+ result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "symbol",
+ GraphNode.name == bare,
+ )
+ )
+ rows = list(result.scalars().all())
+ if not rows:
+ raise HTTPException(status_code=404, detail=f"Symbol not found: {symbol_id}")
+ if "::" in symbol_id:
+ file_hint = symbol_id.split("::")[0]
+ for r in rows:
+ if r.file_path == file_hint:
+ node = r
+ break
+ if node is None or node.node_type != "symbol":
+ rows.sort(key=lambda r: r.node_id)
+ node = rows[0]
+
+ edges = await crud.get_graph_edges_for_node(
+ session, repo_id, node.node_id,
+ direction=direction, edge_types=et_list, limit=limit,
+ )
+
+ # Hydrate connected nodes
+ other_ids: set[str] = set()
+ for e in edges:
+ if e.source_node_id != node.node_id:
+ other_ids.add(e.source_node_id)
+ if e.target_node_id != node.node_id:
+ other_ids.add(e.target_node_id)
+
+ node_map = await crud.get_graph_nodes_by_ids(session, repo_id, list(other_ids))
+
+ callers: list[CallerCalleeEntry] = []
+ callees: list[CallerCalleeEntry] = []
+
+ for e in edges:
+ is_caller = e.target_node_id == node.node_id
+ other_id = e.source_node_id if is_caller else e.target_node_id
+ other = node_map.get(other_id)
+
+ entry = CallerCalleeEntry(
+ symbol_id=other_id,
+ name=other.name if other else (other_id.split("::")[-1] if "::" in other_id else other_id),
+ kind=other.kind if other else "unknown",
+ file=other.file_path if other else (other_id.split("::")[0] if "::" in other_id else other_id),
+ start_line=other.start_line if other else None,
+ edge_type=e.edge_type or "calls",
+ confidence=round(e.confidence or 0.0, 3),
+ )
+
+ if is_caller:
+ callers.append(entry)
+ else:
+ callees.append(entry)
+
+ callers.sort(key=lambda x: (-x.confidence, x.name))
+ callees.sort(key=lambda x: (-x.confidence, x.name))
+
+ return CallersCalleesResponse(
+ symbol_id=node.node_id,
+ symbol=SymbolNodeSummary(
+ symbol_id=node.node_id,
+ name=node.name or node.node_id,
+ kind=node.kind or "unknown",
+ file=node.file_path or node.node_id,
+ start_line=node.start_line,
+ signature=node.signature,
+ ),
+ callers=callers if direction in ("callers", "both") else [],
+ callees=callees if direction in ("callees", "both") else [],
+ caller_count=len(callers),
+ callee_count=len(callees),
+ truncated=(len(callers) >= limit or len(callees) >= limit),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Execution Flows
+# ---------------------------------------------------------------------------
+
+
[email protected]("/{repo_id}/execution-flows", response_model=ExecutionFlowsResponse)
+async def get_execution_flows(
+ repo_id: str,
+ top_n: int = Query(5, ge=1, le=20),
+ max_depth: int = Query(5, ge=1, le=12),
+ entry_point: str | None = Query(None, description="Specific symbol to trace from"),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> ExecutionFlowsResponse:
+ """Return top entry points with BFS call-path traces."""
+ repo = await crud.get_repository(session, repo_id)
+ if repo is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+ entry_nodes: list[tuple[GraphNode, float]] = []
+
+ if entry_point:
+ node = await crud.get_graph_node(session, repo_id, entry_point)
+ if node is None:
+ raise HTTPException(status_code=404, detail=f"Entry point not found: {entry_point}")
+ entry_nodes = [(node, _ep_score(node))]
+ else:
+ top_nodes = await crud.get_top_entry_points(
+ session, repo_id, min_score=0.0, limit=top_n
+ )
+ for n in top_nodes:
+ entry_nodes.append((n, _ep_score(n)))
+
+ if not entry_nodes:
+ return ExecutionFlowsResponse(total_entry_points=0, flows=[])
+
+ node_cache: dict[str, GraphNode] = {}
+ flows: list[ExecutionFlowEntry] = []
+
+ for ep_node, ep_score in entry_nodes:
+ trace = await bfs_trace(
+ session, repo_id, ep_node.node_id, max_depth, node_cache
+ )
+ communities_visited, crosses = await resolve_trace_communities(
+ session, repo_id, trace, node_cache
+ )
+
+ flows.append(
+ ExecutionFlowEntry(
+ entry_point=ep_node.node_id,
+ entry_point_name=ep_node.name or ep_node.node_id.split("::")[-1],
+ entry_point_score=round(ep_score, 3),
+ trace=trace,
+ depth=len(trace) - 1,
+ crosses_community=crosses,
+ communities_visited=communities_visited,
+ )
+ )
+
+ flows.sort(key=lambda f: -f.entry_point_score)
+
+ return ExecutionFlowsResponse(
+ total_entry_points=len(flows),
+ flows=flows,
+ )
diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.py
index bd616ce3e..00cd33fbc 100644
--- a/packages/server/src/repowise/server/routers/repos.py
+++ b/packages/server/src/repowise/server/routers/repos.py
@@ -53,11 +53,37 @@ async def create_repo(
@router.get("", response_model=list[RepoResponse])
async def list_repos(
+ request: Request,
session: AsyncSession = Depends(get_db_session), # noqa: B008
) -> list[RepoResponse]:
- """List all registered repositories."""
+ """List all registered repositories.
+
+ In workspace mode, aggregates repos from the primary DB and all
+ workspace repo DBs so every indexed repo appears in the sidebar.
+ """
result = await session.execute(select(Repository).order_by(Repository.updated_at.desc()))
- repos = result.scalars().all()
+ repos = list(result.scalars().all())
+ seen_ids = {r.id for r in repos}
+
+ # In workspace mode, also fetch repos from other workspace DBs
+ ws_sessions: dict = getattr(request.app.state, "workspace_sessions", {})
+ for repo_id, ws_factory in ws_sessions.items():
+ if repo_id in seen_ids:
+ continue
+ try:
+ async with ws_factory() as ws_session:
+ ws_result = await ws_session.execute(
+ select(Repository).where(Repository.id == repo_id)
+ )
+ ws_repo = ws_result.scalar_one_or_none()
+ if ws_repo:
+ repos.append(ws_repo)
+ seen_ids.add(ws_repo.id)
+ except Exception:
+ pass
+
+ # Sort by updated_at descending
+ repos.sort(key=lambda r: r.updated_at or r.created_at, reverse=True)
return [RepoResponse.from_orm(r) for r in repos]
@@ -141,12 +167,28 @@ async def get_repo_stats(
)
dead_export_count = dead_result.scalar_one() or 0
+ # Compute true freshness score from actual page freshness statuses
+ total_pages_result = await session.execute(
+ select(func.count(Page.id)).where(Page.repository_id == repo_id)
+ )
+ total_pages = total_pages_result.scalar_one() or 0
+
+ fresh_pages_result = await session.execute(
+ select(func.count(Page.id)).where(
+ Page.repository_id == repo_id,
+ Page.freshness_status == "fresh",
+ )
+ )
+ fresh_pages = fresh_pages_result.scalar_one() or 0
+
+ freshness_score = (fresh_pages / total_pages * 100) if total_pages > 0 else doc_coverage_pct
+
return RepoStatsResponse(
file_count=file_count,
symbol_count=symbol_count,
entry_point_count=entry_point_count,
doc_coverage_pct=doc_coverage_pct,
- freshness_score=doc_coverage_pct,
+ freshness_score=freshness_score,
dead_export_count=dead_export_count,
)
diff --git a/packages/server/src/repowise/server/routers/webhooks.py b/packages/server/src/repowise/server/routers/webhooks.py
index 2f5f6b290..cadaede74 100644
--- a/packages/server/src/repowise/server/routers/webhooks.py
+++ b/packages/server/src/repowise/server/routers/webhooks.py
@@ -47,6 +47,25 @@ def _verify_gitlab_token(token_header: str) -> None:
raise HTTPException(status_code=401, detail="Invalid token")
+def _launch_webhook_job(request: Request, job_id: str) -> None:
+ """Launch a webhook-triggered job as a background task."""
+ import asyncio
+
+ from repowise.server.job_executor import execute_job
+
+ task = asyncio.create_task(
+ execute_job(job_id, request.app.state),
+ name=f"webhook-job-{job_id}",
+ )
+ bg_tasks: set = request.app.state.background_tasks
+ bg_tasks.add(task)
+
+ def _on_done(t: asyncio.Task) -> None:
+ bg_tasks.discard(t)
+
+ task.add_done_callback(_on_done)
+
+
@router.post("/github", response_model=WebhookResponse)
async def github_webhook(
request: Request,
@@ -109,6 +128,8 @@ async def github_webhook(
},
)
await crud.mark_webhook_processed(session, event.id, job_id=job.id)
+ await session.commit()
+ _launch_webhook_job(request, job.id)
return WebhookResponse(event_id=event.id)
@@ -165,5 +186,7 @@ async def gitlab_webhook(
},
)
await crud.mark_webhook_processed(session, event.id, job_id=job.id)
+ await session.commit()
+ _launch_webhook_job(request, job.id)
return WebhookResponse(event_id=event.id)
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
new file mode 100644
index 000000000..9b6e4fe75
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -0,0 +1,301 @@
+"""/api/workspace — Workspace intelligence endpoints.
+
+Exposes workspace metadata, cross-repo co-changes, and API contract data
+through REST. All data is read from ``app.state`` (populated at server
+startup from ``.repowise-workspace/`` JSON files) — no DB access needed.
+"""
+
+from __future__ import annotations
+
+import logging
+import sqlite3
+from pathlib import Path
+
+from fastapi import APIRouter, Depends, HTTPException, Query, Request
+
+from repowise.server.deps import (
+ get_cross_repo_enricher,
+ get_workspace_config,
+ verify_api_key,
+)
+from repowise.server.schemas import (
+ WorkspaceCoChangeEntry,
+ WorkspaceCoChangesResponse,
+ WorkspaceContractEntry,
+ WorkspaceContractLinkEntry,
+ WorkspaceContractsResponse,
+ WorkspaceContractSummary,
+ WorkspaceCrossRepoSummary,
+ WorkspaceRepoEntry,
+ WorkspaceResponse,
+)
+
+router = APIRouter(
+ prefix="/api/workspace",
+ tags=["workspace"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
+_log = logging.getLogger("repowise.server.routers.workspace")
+
+
+def _require_workspace(ws_config: object) -> None:
+ """Raise 404 if not in workspace mode."""
+ if ws_config is None:
+ raise HTTPException(status_code=404, detail="Not running in workspace mode")
+
+
+def _query_repo_stats(db_path: Path) -> dict:
+ """Query basic stats from a repo's wiki.db using raw sqlite3.
+
+ Returns a dict with repo_id, file_count, symbol_count, page_count,
+ doc_coverage_pct, hotspot_count. All values default to 0/None on error.
+ """
+ result: dict = {
+ "repo_id": None,
+ "file_count": 0,
+ "symbol_count": 0,
+ "page_count": 0,
+ "doc_coverage_pct": 0.0,
+ "hotspot_count": 0,
+ }
+ if not db_path.exists():
+ return result
+ try:
+ conn = sqlite3.connect(str(db_path))
+ c = conn.cursor()
+
+ # repo id
+ row = c.execute("SELECT id FROM repositories LIMIT 1").fetchone()
+ if row:
+ result["repo_id"] = row[0]
+
+ # file count (graph_nodes)
+ row = c.execute("SELECT COUNT(*) FROM graph_nodes").fetchone()
+ result["file_count"] = row[0] if row else 0
+
+ # symbol count
+ row = c.execute("SELECT COALESCE(SUM(symbol_count), 0) FROM graph_nodes").fetchone()
+ result["symbol_count"] = int(row[0]) if row else 0
+
+ # page count
+ row = c.execute("SELECT COUNT(*) FROM wiki_pages").fetchone()
+ result["page_count"] = row[0] if row else 0
+
+ # doc coverage (avg confidence * 100)
+ row = c.execute("SELECT AVG(confidence) FROM wiki_pages").fetchone()
+ result["doc_coverage_pct"] = round(float(row[0] or 0.0) * 100, 1)
+
+ # hotspot count (git_metadata with churn_percentile >= 90)
+ try:
+ row = c.execute(
+ "SELECT COUNT(*) FROM git_metadata WHERE churn_percentile >= 90"
+ ).fetchone()
+ result["hotspot_count"] = row[0] if row else 0
+ except sqlite3.OperationalError:
+ pass # table or column may not exist
+
+ conn.close()
+ except Exception:
+ _log.debug("Failed to query stats from %s", db_path, exc_info=True)
+ return result
+
+
+# ---------------------------------------------------------------------------
+# GET /api/workspace
+# ---------------------------------------------------------------------------
+
+
[email protected]("", response_model=WorkspaceResponse)
+async def get_workspace(
+ request: Request,
+ ws_config=Depends(get_workspace_config),
+ enricher=Depends(get_cross_repo_enricher),
+):
+ """Workspace metadata and summary statistics.
+
+ Returns ``is_workspace=false`` with empty data in single-repo mode —
+ the web UI uses this for mode detection, so this endpoint never 404s.
+ """
+ if ws_config is None:
+ return WorkspaceResponse(is_workspace=False)
+
+ ws_root = getattr(request.app.state, "workspace_root", None)
+ ws_root_path = Path(ws_root) if ws_root else None
+
+ repo_entries = []
+ for r in ws_config.repos:
+ stats: dict = {}
+ if ws_root_path:
+ repo_path = (ws_root_path / r.path).resolve()
+ db_path = repo_path / ".repowise" / "wiki.db"
+ stats = _query_repo_stats(db_path)
+ repo_entries.append(
+ WorkspaceRepoEntry(
+ alias=r.alias,
+ path=r.path,
+ is_primary=r.is_primary,
+ indexed_at=r.indexed_at,
+ last_commit_at_index=r.last_commit_at_index,
+ **stats,
+ )
+ )
+
+ cross_repo_summary = None
+ contract_summary = None
+
+ if enricher is not None:
+ summary = enricher.get_cross_repo_summary()
+ cross_repo_summary = WorkspaceCrossRepoSummary(**summary)
+ if enricher.has_contract_data:
+ cs = enricher.get_contract_summary()
+ contract_summary = WorkspaceContractSummary(**cs)
+
+ return WorkspaceResponse(
+ is_workspace=True,
+ workspace_root=ws_root,
+ workspace_name=Path(ws_root_path).name if ws_root_path else None,
+ repos=repo_entries,
+ default_repo=ws_config.default_repo,
+ cross_repo_summary=cross_repo_summary,
+ contract_summary=contract_summary,
+ )
+
+
+# ---------------------------------------------------------------------------
+# GET /api/workspace/contracts
+# ---------------------------------------------------------------------------
+
+
[email protected]("/contracts", response_model=WorkspaceContractsResponse)
+async def get_contracts(
+ ws_config=Depends(get_workspace_config),
+ enricher=Depends(get_cross_repo_enricher),
+ contract_type: str | None = Query(None, description="Filter: http, grpc, or topic"),
+ repo: str | None = Query(None, description="Filter by repo alias"),
+ role: str | None = Query(None, description="Filter: provider or consumer"),
+ limit: int = Query(200, ge=1, le=1000),
+ offset: int = Query(0, ge=0),
+):
+ """All detected contracts and matched links with optional filtering."""
+ _require_workspace(ws_config)
+
+ if enricher is None:
+ return WorkspaceContractsResponse(
+ contracts=[], links=[], total_contracts=0, total_links=0,
+ )
+
+ contracts = list(getattr(enricher, "_contracts", []))
+ links = list(getattr(enricher, "_contract_links", []))
+
+ # Apply filters to contracts
+ if contract_type:
+ contracts = [c for c in contracts if c.get("contract_type") == contract_type]
+ links = [lk for lk in links if lk.get("contract_type") == contract_type]
+ if repo:
+ contracts = [c for c in contracts if c.get("repo") == repo]
+ links = [
+ lk for lk in links
+ if lk.get("provider_repo") == repo or lk.get("consumer_repo") == repo
+ ]
+ if role:
+ contracts = [c for c in contracts if c.get("role") == role]
+
+ total_contracts = len(contracts)
+ total_links = len(links)
+
+ # Count by type
+ by_type: dict[str, int] = {}
+ for c in contracts:
+ ct = c.get("contract_type", "unknown")
+ by_type[ct] = by_type.get(ct, 0) + 1
+
+ # Paginate contracts only (links are typically small enough)
+ contracts_page = contracts[offset : offset + limit]
+
+ return WorkspaceContractsResponse(
+ contracts=[
+ WorkspaceContractEntry(
+ contract_id=c.get("contract_id", ""),
+ contract_type=c.get("contract_type", ""),
+ role=c.get("role", ""),
+ repo=c.get("repo", ""),
+ file_path=c.get("file_path", ""),
+ symbol_name=c.get("symbol_name", ""),
+ confidence=c.get("confidence", 0.0),
+ service=c.get("service"),
+ )
+ for c in contracts_page
+ ],
+ links=[
+ WorkspaceContractLinkEntry(
+ contract_id=lk.get("contract_id", ""),
+ contract_type=lk.get("contract_type", ""),
+ match_type=lk.get("match_type", "exact"),
+ confidence=lk.get("confidence", 0.0),
+ provider_repo=lk.get("provider_repo", ""),
+ provider_file=lk.get("provider_file", ""),
+ provider_symbol=lk.get("provider_symbol", ""),
+ consumer_repo=lk.get("consumer_repo", ""),
+ consumer_file=lk.get("consumer_file", ""),
+ consumer_symbol=lk.get("consumer_symbol", ""),
+ )
+ for lk in links
+ ],
+ total_contracts=total_contracts,
+ total_links=total_links,
+ by_type=by_type,
+ )
+
+
+# ---------------------------------------------------------------------------
+# GET /api/workspace/co-changes
+# ---------------------------------------------------------------------------
+
+
[email protected]("/co-changes", response_model=WorkspaceCoChangesResponse)
+async def get_co_changes(
+ ws_config=Depends(get_workspace_config),
+ enricher=Depends(get_cross_repo_enricher),
+ repo: str | None = Query(None, description="Filter by repo alias"),
+ min_strength: float = Query(0.0, ge=0.0, le=1.0),
+ limit: int = Query(50, ge=1, le=500),
+):
+ """Cross-repo co-change pairs, optionally filtered by repo and strength."""
+ _require_workspace(ws_config)
+
+ if enricher is None:
+ return WorkspaceCoChangesResponse(co_changes=[], total=0)
+
+ co_changes = list(getattr(enricher, "_co_changes", []))
+
+ if repo:
+ co_changes = [
+ cc for cc in co_changes
+ if cc.get("source_repo") == repo or cc.get("target_repo") == repo
+ ]
+ if min_strength > 0:
+ co_changes = [cc for cc in co_changes if cc.get("strength", 0) >= min_strength]
+
+ # Sort by strength descending
+ co_changes.sort(key=lambda cc: -cc.get("strength", 0))
+
+ total = len(co_changes)
+ co_changes = co_changes[:limit]
+
+ return WorkspaceCoChangesResponse(
+ co_changes=[
+ WorkspaceCoChangeEntry(
+ source_repo=cc.get("source_repo", ""),
+ source_file=cc.get("source_file", ""),
+ target_repo=cc.get("target_repo", ""),
+ target_file=cc.get("target_file", ""),
+ strength=cc.get("strength", 0.0),
+ frequency=cc.get("frequency", 0),
+ last_date=cc.get("last_date", ""),
+ )
+ for cc in co_changes
+ ],
+ total=total,
+ )
diff --git a/packages/server/src/repowise/server/scheduler.py b/packages/server/src/repowise/server/scheduler.py
index 3faec308d..18c608472 100644
--- a/packages/server/src/repowise/server/scheduler.py
+++ b/packages/server/src/repowise/server/scheduler.py
@@ -7,8 +7,9 @@ Two recurring jobs:
from __future__ import annotations
+import asyncio
import logging
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger
@@ -22,12 +23,17 @@ logger = logging.getLogger(__name__)
def setup_scheduler(
session_factory: async_sessionmaker[AsyncSession],
*,
+ app_state: Any = None,
staleness_interval_minutes: int = 15,
polling_interval_minutes: int = 15,
) -> AsyncIOScheduler:
"""Create and configure the APScheduler instance.
Does NOT start the scheduler — caller must call ``scheduler.start()``.
+
+ Args:
+ app_state: The FastAPI ``app.state`` object, needed to launch
+ background pipeline jobs from the polling fallback.
"""
scheduler = AsyncIOScheduler()
@@ -64,11 +70,21 @@ def setup_scheduler(
logger.exception("staleness_check_failed")
async def polling_fallback() -> None:
- """Check if repos have diverged from their last_sync_commit."""
+ """Check if repos have diverged from their last_sync_commit.
+
+ Enqueues a sync job for any repo whose git HEAD differs from the
+ stored ``last_sync_commit`` in state.json, unless a job is already
+ pending or running.
+ """
+ import json as _json
+ import subprocess
+ from pathlib import Path as _Path
+
from sqlalchemy import select
+ from repowise.core.persistence import crud
from repowise.core.persistence.database import get_session
- from repowise.core.persistence.models import Repository
+ from repowise.core.persistence.models import GenerationJob, Repository
try:
async with get_session(session_factory) as session:
@@ -78,26 +94,80 @@ def setup_scheduler(
for repo in repos:
if not repo.local_path:
continue
- # Compare head_commit with actual git HEAD.
- # This is a lightweight check — full sync is triggered
- # only if commits differ.
- # NOTE: when a full sync is implemented here, pass
- # extra_exclude_patterns=repo.settings.get("exclude_patterns", [])
- # to FileTraverser so user-configured exclusions are respected.
- import json as _json
+ # Read last_sync_commit from state.json
+ state_path = _Path(repo.local_path) / ".repowise" / "state.json"
+ stored_commit = None
+ if state_path.is_file():
+ try:
+ state_data = _json.loads(state_path.read_text(encoding="utf-8"))
+ stored_commit = state_data.get("last_sync_commit")
+ except Exception:
+ pass
+
+ # Get current git HEAD
try:
- _settings = _json.loads(repo.settings_json) if repo.settings_json else {}
+ head_result = subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=repo.local_path,
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if head_result.returncode != 0:
+ continue
+ current_head = head_result.stdout.strip()
except Exception:
- _settings = {}
- logger.debug(
- "polling_check",
+ continue
+
+ if stored_commit and current_head == stored_commit:
+ continue
+
+ # Check no active job already
+ active = await session.execute(
+ select(GenerationJob.id)
+ .where(GenerationJob.repository_id == repo.id)
+ .where(GenerationJob.status.in_(["pending", "running"]))
+ .limit(1)
+ )
+ if active.scalar_one_or_none() is not None:
+ continue
+
+ # Enqueue a sync job
+ await crud.upsert_generation_job(
+ session,
+ repository_id=repo.id,
+ status="pending",
+ config={
+ "mode": "sync",
+ "trigger": "polling_fallback",
+ "before": stored_commit or "",
+ "after": current_head,
+ },
+ )
+ await session.commit()
+
+ logger.info(
+ "polling_sync_enqueued",
extra={
"repo_id": repo.id,
- "head_commit": repo.head_commit,
- "exclude_patterns": _settings.get("exclude_patterns", []),
+ "repo_name": repo.name,
+ "stored": stored_commit,
+ "head": current_head,
},
)
+
+ # Launch the job in the background if app_state is available
+ if app_state is not None:
+ from repowise.server.job_executor import execute_job
+
+ task = asyncio.create_task(
+ execute_job(job.id, app_state),
+ name=f"poll-job-{job.id}",
+ )
+ bg_tasks: set = getattr(app_state, "background_tasks", set())
+ bg_tasks.add(task)
+ task.add_done_callback(bg_tasks.discard)
except Exception:
logger.exception("polling_fallback_failed")
diff --git a/packages/server/src/repowise/server/schemas.py b/packages/server/src/repowise/server/schemas.py
index e99b5aef4..35fe75b22 100644
--- a/packages/server/src/repowise/server/schemas.py
+++ b/packages/server/src/repowise/server/schemas.py
@@ -570,6 +570,102 @@ class HotFilesGraphResponse(BaseModel):
links: list[GraphEdgeResponse]
+# ---------------------------------------------------------------------------
+# Graph Intelligence
+# ---------------------------------------------------------------------------
+
+
+class SymbolNodeSummary(BaseModel):
+ symbol_id: str
+ name: str
+ kind: str
+ file: str
+ start_line: int | None = None
+ signature: str | None = None
+
+
+class CallerCalleeEntry(BaseModel):
+ symbol_id: str
+ name: str
+ kind: str
+ file: str
+ start_line: int | None = None
+ edge_type: str
+ confidence: float
+
+
+class CallersCalleesResponse(BaseModel):
+ symbol_id: str
+ symbol: SymbolNodeSummary
+ callers: list[CallerCalleeEntry]
+ callees: list[CallerCalleeEntry]
+ caller_count: int
+ callee_count: int
+ truncated: bool
+
+
+class CommunityMember(BaseModel):
+ path: str
+ pagerank: float
+ is_entry_point: bool
+
+
+class NeighboringCommunity(BaseModel):
+ community_id: int
+ label: str
+ cross_edge_count: int
+
+
+class CommunityDetailResponse(BaseModel):
+ community_id: int
+ label: str
+ cohesion: float
+ member_count: int
+ members: list[CommunityMember]
+ truncated: bool
+ neighboring_communities: list[NeighboringCommunity]
+
+
+class CommunitySummaryItem(BaseModel):
+ community_id: int
+ label: str
+ cohesion: float
+ member_count: int
+ top_file: str
+
+
+class GraphMetricsResponse(BaseModel):
+ target: str
+ node_type: str
+ pagerank: float
+ pagerank_percentile: int
+ betweenness: float
+ betweenness_percentile: int
+ community_id: int
+ community_label: str | None
+ is_entry_point: bool
+ in_degree: int
+ out_degree: int
+ entry_point_score: float | None = None
+ kind: str | None = None
+ file: str | None = None
+
+
+class ExecutionFlowEntry(BaseModel):
+ entry_point: str
+ entry_point_name: str
+ entry_point_score: float
+ trace: list[str]
+ depth: int
+ crosses_community: bool
+ communities_visited: list[int]
+
+
+class ExecutionFlowsResponse(BaseModel):
+ total_entry_points: int
+ flows: list[ExecutionFlowEntry]
+
+
# ---------------------------------------------------------------------------
# Blast Radius
# ---------------------------------------------------------------------------
@@ -824,3 +920,92 @@ class CostSummaryResponse(BaseModel):
total_input_tokens: int
total_output_tokens: int
since: str | None
+
+
+# ---------------------------------------------------------------------------
+# Workspace
+# ---------------------------------------------------------------------------
+
+
+class WorkspaceRepoEntry(BaseModel):
+ alias: str
+ path: str
+ is_primary: bool = False
+ indexed_at: str | None = None
+ last_commit_at_index: str | None = None
+ # Per-repo stats (populated from each repo's wiki.db)
+ repo_id: str | None = None
+ file_count: int = 0
+ symbol_count: int = 0
+ page_count: int = 0
+ doc_coverage_pct: float = 0.0
+ hotspot_count: int = 0
+
+
+class WorkspaceCrossRepoSummary(BaseModel):
+ co_change_count: int = 0
+ package_dep_count: int = 0
+ top_connections: list[dict] = []
+
+
+class WorkspaceContractSummary(BaseModel):
+ total_contracts: int = 0
+ total_links: int = 0
+ by_type: dict[str, int] = {}
+
+
+class WorkspaceResponse(BaseModel):
+ is_workspace: bool
+ workspace_root: str | None = None
+ workspace_name: str | None = None
+ repos: list[WorkspaceRepoEntry] = []
+ default_repo: str | None = None
+ cross_repo_summary: WorkspaceCrossRepoSummary | None = None
+ contract_summary: WorkspaceContractSummary | None = None
+
+
+class WorkspaceContractEntry(BaseModel):
+ contract_id: str
+ contract_type: str
+ role: str
+ repo: str
+ file_path: str
+ symbol_name: str
+ confidence: float
+ service: str | None = None
+
+
+class WorkspaceContractLinkEntry(BaseModel):
+ contract_id: str
+ contract_type: str
+ match_type: str
+ confidence: float
+ provider_repo: str
+ provider_file: str
+ provider_symbol: str
+ consumer_repo: str
+ consumer_file: str
+ consumer_symbol: str
+
+
+class WorkspaceContractsResponse(BaseModel):
+ contracts: list[WorkspaceContractEntry]
+ links: list[WorkspaceContractLinkEntry]
+ total_contracts: int
+ total_links: int
+ by_type: dict[str, int] = {}
+
+
+class WorkspaceCoChangeEntry(BaseModel):
+ source_repo: str
+ source_file: str
+ target_repo: str
+ target_file: str
+ strength: float
+ frequency: int
+ last_date: str
+
+
+class WorkspaceCoChangesResponse(BaseModel):
+ co_changes: list[WorkspaceCoChangeEntry]
+ total: int
diff --git a/packages/web/README.md b/packages/web/README.md
index 352c2e16b..238990f16 100644
--- a/packages/web/README.md
+++ b/packages/web/README.md
@@ -10,7 +10,9 @@ Next.js 15 frontend for the repowise codebase documentation engine. Provides an
| Styling | Tailwind CSS v4 (CSS-first, no config file), custom design tokens in `globals.css` |
| Components | Radix UI primitives, class-variance-authority for variants |
| Data Fetching | SWR (stale-while-revalidate) with 30s polling, Server-Sent Events for live job progress |
-| Visualization | D3.js (force-directed graphs), Recharts (bar/donut charts), Mermaid (diagrams) |
+| Graph Viz | @xyflow/react (React Flow) with ELK layout (elkjs) |
+| Charts | Recharts (bar/donut charts), D3.js (force-directed minimap, treemap) |
+| Diagrams | Mermaid v11 (embedded in wiki pages) |
| Code Rendering | Shiki (syntax highlighting), next-mdx-remote (wiki content) |
| Search | cmdk command palette (Cmd+K), Fuse.js client-side fuzzy search |
| URL State | nuqs (type-safe URL search params for bookmarkable views) |
@@ -26,29 +28,33 @@ The home page. Shows aggregate stats across all registered repositories (total f
### Repository Overview (`/repos/[id]`)
-Landing page for a single repo. Displays git stats (HEAD commit, branch, contributor count), documentation coverage at a glance, and quick links to all sub-pages. Includes an operations panel for triggering sync and full-resync jobs.
+Landing page for a single repo. Displays health score, git insights (commit activity, churn distribution, bus factor), documentation coverage, and quick links to all sub-pages. Includes a **Graph Intelligence** section with expandable architecture communities (cohesion scores, member lists, neighboring communities) and execution flows panel (entry point scoring, BFS call traces, cross-community classification). Operations panel for triggering sync and full-resync jobs.
### Wiki Pages (`/repos/[id]/wiki/[...slug]`)
The core documentation viewer. Renders AI-generated wiki pages as MDX with:
- Shiki syntax-highlighted code blocks
- Embedded Mermaid diagrams (flowcharts, sequence diagrams, etc.)
-- Auto-generated sticky table of contents from headings
+- Auto-generated sticky table of contents with anchor-linked headings (scroll-to-heading)
- Confidence badge showing freshness (fresh/stale/outdated) with last-updated tooltip
- Git history panel showing the file's change timeline
- Regenerate button to force a fresh AI pass on stale pages
+- Graph intelligence sidebar (XL screens) with PageRank/betweenness percentiles, community label, degree counts, entry point badge
+- Hallucination warnings — surfaces LLM validation findings (symbol references not found in source) as amber banners
+- Version history with diff view — browse previous page versions and compare changes inline
### Dependency Graph (`/repos/[id]/graph`)
-Interactive D3 force-directed graph rendered on HTML Canvas. Supports six view modes:
-- **Module view** — hierarchical module organization
-- **Ego graph** — neighborhood of a selected node with context sidebar
+Interactive React Flow graph with ELK layout engine. Supports five view modes:
+- **Module view** — hierarchical module organization with drill-down
- **Architecture view** — entry point reachability analysis
-- **Dead code view** — highlights unreachable files
+- **Dead code view** — highlights unreachable files with confidence groups
- **Hot files view** — commit activity heatmap overlay
- **Full graph** — complete dependency graph
-Features pan/zoom, a minimap for orientation, a filter panel (by language, node type, edge type), node sizing controls, and a path finder to trace dependency chains between any two files.
+Three color modes: **Language** (per-language coloring), **Community** (Leiden community clusters with real labels from analysis), **Risk** (churn-based).
+
+Features pan/zoom, minimap, path finder for dependency chains, community detail panel (click any node in community mode to see members, cohesion, and neighboring communities with cross-edge counts), and URL param support for deep-linking color modes.
### Search (`/repos/[id]/search`)
@@ -56,7 +62,7 @@ Full-text and semantic search across all wiki pages. Includes a type toggle (FTS
### Symbol Index (`/repos/[id]/symbols`)
-Sortable, filterable table of all extracted symbols (functions, classes, constants, etc.). Filter by kind and language. Click any row to open a detail drawer with the symbol's signature, location, and relationships.
+Sortable, filterable table of all extracted symbols (functions, classes, constants, etc.). Filter by kind and language. Click any row to open a two-panel detail drawer: left side shows the symbol's signature, docstring, and location; right side shows **graph intelligence** — PageRank/betweenness percentile badges, in/out degree, community membership, callers and callees with confidence scoring, and class heritage (extends/implements relationships).
### Documentation Coverage (`/repos/[id]/coverage`)
@@ -74,9 +80,19 @@ Ranked table of high-churn files with churn bar charts and an owner leaderboard.
Tabbed view of dead code findings (unreachable files, unused exports). Supports row-level actions (ignore, mark as false positive), bulk selection, and a trigger to run fresh analysis. Summary bar shows counts by category.
+### Documentation Explorer (`/repos/[id]/docs`)
+
+Split-pane documentation browser (VS Code-style). Left panel is a searchable file tree with type/freshness filters and colored freshness dots. Right panel renders full wiki content with:
+- Mermaid diagram rendering and syntax-highlighted code blocks with copy buttons
+- Graph intelligence sidebar (PageRank/betweenness percentiles, community, callers/callees)
+- Version history browser with LCS-based inline diff view
+- Hallucination warning banners for pages with detected inaccuracies
+- Deep-linkable page selection via URL search params (`?page=...`)
+- Export All (single `.md`) and Download ZIP buttons
+
### Architectural Decisions (`/repos/[id]/decisions`)
-Lists extracted architectural decision records with health metrics. Each decision has a detail page (`/repos/[id]/decisions/[decisionId]`) showing rationale, status, and related code.
+Lists extracted architectural decision records with health metrics. Each decision has a detail page (`/repos/[id]/decisions/[decisionId]`) showing context, rationale, alternatives, and consequences rendered as markdown, with Confirm/Dismiss/Deprecate actions.
### Settings (`/settings` and `/repos/[id]/settings`)
@@ -113,6 +129,10 @@ Organized by domain — `repos.ts`, `pages.ts`, `graph.ts`, `search.ts`, `symbol
| `usePage`, `usePageVersions` | Page content and version history |
| `useSearch` | Debounced search (300ms, min 2 chars) |
| `useGraph` (+ variants) | Graph data with stable caching (no revalidate on focus) |
+| `useCommunities`, `useCommunityDetail` | Community summaries and detail data |
+| `useGraphMetrics` | Per-node PageRank, betweenness, percentiles |
+| `useCallersCallees` | Symbol call graph with confidence and heritage |
+| `useExecutionFlows` | Entry point traces with community crossing |
| `useSSE` | Generic SSE hook with reconnection, exponential backoff, named events |
| `useJob` | Combines SWR polling + SSE streaming for real-time job monitoring |
| `useDebounce` | Generic value debounce |
@@ -123,8 +143,8 @@ Organized by domain — `repos.ts`, `pages.ts`, `graph.ts`, `search.ts`, `symbol
components/
ui/ Radix-based primitives (button, card, dialog, tabs, tooltip, etc.)
layout/ Sidebar, mobile nav
- wiki/ Wiki renderer, code blocks, Mermaid, ToC, confidence badge
- graph/ D3 canvas, filter panel, minimap, tooltip, ego sidebar, path finder
+ wiki/ Wiki renderer (RSC + client), code blocks, Mermaid, ToC, confidence badge, version history with diff
+ graph/ React Flow canvas, toolbar, legend, tooltip, community panel, path finder
search/ Command palette, search bar, result cards
jobs/ Generation progress (SSE), job logs
repos/ Add repo dialog, operations panel, run config form
@@ -132,6 +152,9 @@ components/
dead-code/ Findings table, row actions, summary bar
decisions/ Decisions table, detail view, health widget
git/ Churn bars, contributor charts, hotspot/ownership tables
+ symbols/ Symbol table, symbol drawer, symbol graph panel (metrics + callers)
+ dashboard/ Health ring, attention panel, quick actions, language donut,
+ ownership treemap, community summary grid, execution flows panel
shared/ Stat cards, empty states
```
diff --git a/packages/web/package.json b/packages/web/package.json
index 948690ba3..55f6149a7 100644
--- a/packages/web/package.json
+++ b/packages/web/package.json
@@ -1,6 +1,6 @@
{
"name": "repowise-web",
- "version": "0.1.21",
+ "version": "0.3.0",
"private": true,
"description": "repowise Web UI — Next.js 15 dashboard and wiki viewer",
"scripts": {
diff --git a/packages/web/src/app/layout.tsx b/packages/web/src/app/layout.tsx
index 83b2c7d1f..a7bff3041 100644
--- a/packages/web/src/app/layout.tsx
+++ b/packages/web/src/app/layout.tsx
@@ -8,6 +8,8 @@ import { Sidebar } from "@/components/layout/sidebar";
import { MobileNav } from "@/components/layout/mobile-nav";
import { CommandPalette } from "@/components/search/command-palette";
import { listRepos } from "@/lib/api/repos";
+import { getWorkspace } from "@/lib/api/workspace";
+import type { WorkspaceResponse } from "@/lib/api/types";
import "@/styles/globals.css";
export const metadata: Metadata = {
@@ -23,11 +25,17 @@ export default async function RootLayout({
}: {
children: React.ReactNode;
}) {
- // Fetch repos server-side for the sidebar.
- // Gracefully fall back to empty if the API is unavailable.
+ // Fetch repos + workspace info server-side for the sidebar.
+ // Gracefully fall back to empty/null if the API is unavailable.
let repos: Awaited<ReturnType<typeof listRepos>> = [];
+ let workspace: WorkspaceResponse | null = null;
try {
- repos = await listRepos();
+ const [reposResult, wsResult] = await Promise.allSettled([
+ listRepos(),
+ getWorkspace(),
+ ]);
+ if (reposResult.status === "fulfilled") repos = reposResult.value;
+ if (wsResult.status === "fulfilled") workspace = wsResult.value;
} catch {
// API not available — show empty sidebar
}
@@ -41,15 +49,15 @@ export default async function RootLayout({
<NuqsAdapter>
<TooltipProvider delayDuration={300}>
<div className="flex h-screen overflow-hidden">
- <Sidebar repos={repos} />
+ <Sidebar repos={repos} workspace={workspace} />
<div className="flex flex-1 flex-col min-w-0 overflow-hidden">
- <MobileNav repos={repos} />
+ <MobileNav repos={repos} workspace={workspace} />
<main className="flex-1 overflow-auto min-w-0">
{children}
</main>
</div>
</div>
- <CommandPalette repos={repos} />
+ <CommandPalette repos={repos} workspace={workspace} />
</TooltipProvider>
</NuqsAdapter>
<Toaster
diff --git a/packages/web/src/app/page.tsx b/packages/web/src/app/page.tsx
index e1b30b116..458b2a345 100644
--- a/packages/web/src/app/page.tsx
+++ b/packages/web/src/app/page.tsx
@@ -13,6 +13,7 @@ import {
import { listRepos, getRepoStats } from "@/lib/api/repos";
import { listJobs } from "@/lib/api/jobs";
import { getGitSummary } from "@/lib/api/git";
+import { getWorkspace } from "@/lib/api/workspace";
import type { RepoStatsResponse, GitSummaryResponse } from "@/lib/api/types";
import { StatCard } from "@/components/shared/stat-card";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@@ -27,15 +28,22 @@ export const metadata: Metadata = { title: "Dashboard" };
export const revalidate = 30;
export default async function DashboardPage() {
- const [repos, jobs] = await Promise.allSettled([
+ const [repos, jobs, ws] = await Promise.allSettled([
listRepos(),
listJobs({ limit: 10 }),
+ getWorkspace(),
]);
const repoList = repos.status === "fulfilled" ? repos.value : [];
const jobList = jobs.status === "fulfilled" ? jobs.value : [];
+ const workspace = ws.status === "fulfilled" ? ws.value : null;
- // If there's exactly one repo, go straight to it — no need for a dashboard.
+ // Workspace mode → workspace dashboard
+ if (workspace?.is_workspace) {
+ redirect("/workspace");
+ }
+
+ // Single repo → go straight to its overview
if (repoList.length === 1) {
redirect(`/repos/${repoList[0].id}/overview`);
}
diff --git a/packages/web/src/app/repos/[id]/graph/page.tsx b/packages/web/src/app/repos/[id]/graph/page.tsx
index 7e66a6bfb..0bf6b2646 100644
--- a/packages/web/src/app/repos/[id]/graph/page.tsx
+++ b/packages/web/src/app/repos/[id]/graph/page.tsx
@@ -38,7 +38,7 @@ export default function GraphPage({
);
return (
- <div className="flex flex-col h-screen">
+ <div className="flex flex-col h-full">
{/* Header */}
<div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">
<h1 className="text-lg font-semibold text-[var(--color-text-primary)]">
diff --git a/packages/web/src/app/repos/[id]/hotspots/page.tsx b/packages/web/src/app/repos/[id]/hotspots/page.tsx
index 60e5297f7..9132db781 100644
--- a/packages/web/src/app/repos/[id]/hotspots/page.tsx
+++ b/packages/web/src/app/repos/[id]/hotspots/page.tsx
@@ -5,6 +5,7 @@ import { HotspotTable } from "@/components/git/hotspot-table";
import { ContributorBar } from "@/components/git/contributor-bar";
import { ChurnHistogram } from "@/components/git/churn-histogram";
import { CommitCategoryDonut } from "@/components/git/commit-category-donut";
+import { RiskDistributionChart } from "@/components/git/risk-distribution-chart";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { getHotspots, getGitSummary } from "@/lib/api/git";
import { formatNumber } from "@/lib/utils/format";
@@ -109,6 +110,21 @@ export default async function HotspotsPage({
</div>
)}
+ {/* Risk distribution */}
+ {hotspots.length > 0 && (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm">Risk Distribution</CardTitle>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Composite risk score: churn (40%) + bus factor (35%) + trend (25%)
+ </p>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <RiskDistributionChart hotspots={hotspots} />
+ </CardContent>
+ </Card>
+ )}
+
{/* Table + sidebar */}
<div className="grid grid-cols-1 gap-6 xl:grid-cols-4">
<div className="xl:col-span-3">
diff --git a/packages/web/src/app/repos/[id]/layout.tsx b/packages/web/src/app/repos/[id]/layout.tsx
index 23b447cf9..e158b882b 100644
--- a/packages/web/src/app/repos/[id]/layout.tsx
+++ b/packages/web/src/app/repos/[id]/layout.tsx
@@ -1,6 +1,7 @@
import { redirect } from "next/navigation";
import { getRepo } from "@/lib/api/repos";
import { ActiveJobBanner } from "@/components/dashboard/active-job-banner";
+import { PageTransition } from "@/components/layout/page-transition";
interface RepoLayoutProps {
children: React.ReactNode;
@@ -19,7 +20,7 @@ export default async function RepoLayout({ children, params }: RepoLayoutProps)
return (
<>
<ActiveJobBanner repoId={id} />
- {children}
+ <PageTransition>{children}</PageTransition>
</>
);
}
diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsx
index c8b4414ca..c0ad97938 100644
--- a/packages/web/src/app/repos/[id]/overview/page.tsx
+++ b/packages/web/src/app/repos/[id]/overview/page.tsx
@@ -5,7 +5,7 @@ import { getRepo, getRepoStats } from "@/lib/api/repos";
import { getGitSummary, getHotspots, getOwnership } from "@/lib/api/git";
import { getDeadCodeSummary, listDeadCode } from "@/lib/api/dead-code";
import { listDecisions, getDecisionHealth } from "@/lib/api/decisions";
-import { getGraph, getModuleGraph } from "@/lib/api/graph";
+import { getGraph, getModuleGraph, getCommunities, getExecutionFlows } from "@/lib/api/graph";
import { getProviders } from "@/lib/api/providers";
import { listJobs } from "@/lib/api/jobs";
import { getKnowledgeMap } from "@/lib/api/knowledge-map";
@@ -20,6 +20,9 @@ import { computeHealthScore, buildAttentionItems, aggregateLanguages } from "@/l
import { HotspotsMini } from "@/components/dashboard/hotspots-mini";
import { DecisionsTimeline } from "@/components/dashboard/decisions-timeline";
import { ModuleMinimap } from "@/components/dashboard/module-minimap";
+import { CommunitySummaryGrid } from "@/components/dashboard/community-summary-grid";
+import { ExecutionFlowsPanel } from "@/components/dashboard/execution-flows-panel";
+import { DependencyHeatmap } from "@/components/dashboard/dependency-heatmap";
import { BusFactorPanel } from "@/components/git/bus-factor-panel";
import { ChurnHistogram } from "@/components/git/churn-histogram";
import { CommitCategoryDonut } from "@/components/git/commit-category-donut";
@@ -37,6 +40,8 @@ import type {
DecisionHealthResponse,
GraphExportResponse,
ModuleGraphResponse,
+ CommunitySummaryItem,
+ ExecutionFlowsResponse,
} from "@/lib/api/types";
export const metadata: Metadata = { title: "Overview" };
@@ -61,7 +66,7 @@ export default async function OverviewPage({ params }: Props) {
if (!repo) notFound();
// Fetch all data in parallel — each independently failable
- const [stats, gitSummary, hotspots, ownership, deadCodeSummary, deadCodeSafe, decisions, decisionHealth, graph, moduleGraph, providers, completedJobs, knowledgeMap] =
+ const [stats, gitSummary, hotspots, ownership, deadCodeSummary, deadCodeSafe, decisions, decisionHealth, graph, moduleGraph, providers, completedJobs, knowledgeMap, communities, executionFlows] =
await Promise.all([
safeFetch(() => getRepoStats(id)),
safeFetch(() => getGitSummary(id)),
@@ -76,6 +81,8 @@ export default async function OverviewPage({ params }: Props) {
safeFetch(() => getProviders()),
safeFetch(() => listJobs({ repo_id: id, limit: 20, status: "completed" })),
safeFetch(() => getKnowledgeMap(id)),
+ safeFetch(() => getCommunities(id)),
+ safeFetch(() => getExecutionFlows(id, { top_n: 5, max_depth: 5 })),
]);
// Find timestamps for last sync and last full re-index from completed jobs
@@ -292,13 +299,45 @@ export default async function OverviewPage({ params }: Props) {
);
})()}
- {/* ── Module Architecture Map (full width) ── */}
+ {/* ── Module Architecture Map + Dependency Heatmap ── */}
{moduleGraph && moduleGraph.nodes.length > 0 && (
- <ModuleMinimap
- nodes={moduleGraph.nodes}
- edges={moduleGraph.edges}
- repoId={id}
- />
+ <div className="space-y-4">
+ <ModuleMinimap
+ nodes={moduleGraph.nodes}
+ edges={moduleGraph.edges}
+ repoId={id}
+ />
+ {moduleGraph.nodes.length >= 2 && (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Dependency Heatmap</CardTitle>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Module-to-module dependency density — brighter cells indicate more connections
+ </p>
+ </CardHeader>
+ <CardContent>
+ <DependencyHeatmap moduleGraph={moduleGraph} />
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ )}
+
+ {/* ── Graph Intelligence: Communities & Execution Flows ── */}
+ {((communities && communities.length > 0) || (executionFlows && executionFlows.flows.length > 0)) && (
+ <div className="space-y-4">
+ <h2 className="text-sm font-medium text-[var(--color-text-secondary)] uppercase tracking-wider">
+ Graph Intelligence
+ </h2>
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ {communities && communities.length > 0 && (
+ <CommunitySummaryGrid communities={communities} repoId={id} />
+ )}
+ {executionFlows && executionFlows.flows.length > 0 && (
+ <ExecutionFlowsPanel flows={executionFlows.flows} repoId={id} />
+ )}
+ </div>
+ </div>
)}
{/* ── Knowledge Map ── */}
diff --git a/packages/web/src/app/repos/[id]/ownership/page.tsx b/packages/web/src/app/repos/[id]/ownership/page.tsx
index 48d494fd5..4258a09d3 100644
--- a/packages/web/src/app/repos/[id]/ownership/page.tsx
+++ b/packages/web/src/app/repos/[id]/ownership/page.tsx
@@ -9,6 +9,7 @@ import { OwnershipTable } from "@/components/git/ownership-table";
import { ContributorBar } from "@/components/git/contributor-bar";
import { OwnershipTreemap } from "@/components/git/ownership-treemap";
import { BusFactorPanel } from "@/components/git/bus-factor-panel";
+import { ContributorNetwork } from "@/components/git/contributor-network";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { getOwnership, getGitSummary, getHotspots } from "@/lib/api/git";
@@ -150,6 +151,21 @@ export default function OwnershipPage() {
)}
</div>
+ {/* Contributor Network */}
+ {hotspotData && hotspotData.length > 0 && (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm">Contributor Network</CardTitle>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Contributors linked by shared file ownership — larger nodes own more files
+ </p>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <ContributorNetwork hotspots={hotspotData} />
+ </CardContent>
+ </Card>
+ )}
+
{/* Detail table */}
{loadingEntries ? (
<div className="space-y-2">
diff --git a/packages/web/src/app/repos/[id]/symbols/loading.tsx b/packages/web/src/app/repos/[id]/symbols/loading.tsx
index 2ee853743..181057cc7 100644
--- a/packages/web/src/app/repos/[id]/symbols/loading.tsx
+++ b/packages/web/src/app/repos/[id]/symbols/loading.tsx
@@ -13,13 +13,31 @@ export default function SymbolsLoading() {
<Skeleton className="h-9 w-32" />
<Skeleton className="h-9 w-32" />
</div>
- {/* Table rows */}
- <div className="space-y-px">
- <Skeleton className="h-10 rounded-t-lg" />
- {Array.from({ length: 8 }).map((_, i) => (
- <Skeleton key={i} className="h-12 rounded-none" />
+ {/* Table with header + rows matching content structure */}
+ <div className="rounded-lg border border-[var(--color-border-default)] overflow-hidden">
+ <div className="bg-[var(--color-bg-elevated)] px-4 py-2.5 border-b border-[var(--color-border-default)]">
+ <div className="flex gap-6">
+ <Skeleton className="h-3 w-20" />
+ <Skeleton className="h-3 w-12" />
+ <Skeleton className="h-3 w-10" />
+ <Skeleton className="h-3 w-16 hidden sm:block" />
+ <Skeleton className="h-3 w-24 hidden sm:block" />
+ <Skeleton className="h-3 w-16 hidden sm:block" />
+ </div>
+ </div>
+ {Array.from({ length: 10 }).map((_, i) => (
+ <div
+ key={i}
+ className="flex items-center gap-6 px-4 py-3 border-b border-[var(--color-border-default)] last:border-0"
+ >
+ <Skeleton className="h-1.5 w-16 rounded-full" />
+ <Skeleton className="h-4 w-28" />
+ <Skeleton className="h-5 w-14 rounded-md" />
+ <Skeleton className="h-4 w-16 hidden sm:block" />
+ <Skeleton className="h-4 w-36 hidden sm:block" />
+ <Skeleton className="h-4 w-8 hidden sm:block" />
+ </div>
))}
- <Skeleton className="h-12 rounded-b-lg" />
</div>
</div>
);
diff --git a/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx b/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx
index 207daec00..7d331d71b 100644
--- a/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx
+++ b/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx
@@ -1,8 +1,10 @@
import type { Metadata } from "next";
+import Link from "next/link";
import { notFound } from "next/navigation";
import { getRepo } from "@/lib/api/repos";
import { getPageById, getPageVersions } from "@/lib/api/pages";
import { getGitMetadata } from "@/lib/api/git";
+import { getGraphMetrics } from "@/lib/api/graph";
import { ConfidenceBadge } from "@/components/wiki/confidence-badge";
import { WikiRenderer } from "@/components/wiki/wiki-renderer";
import { TableOfContents } from "@/components/wiki/table-of-contents";
@@ -13,7 +15,8 @@ import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { formatRelativeTime, formatTokens } from "@/lib/utils/format";
import { CoChangeList } from "@/components/git/co-change-list";
-import { Hash, Cpu, StickyNote } from "lucide-react";
+import { Hash, Cpu, StickyNote, Network } from "lucide-react";
+import type { GraphMetricsResponse } from "@/lib/api/types";
interface Props {
params: Promise<{ id: string; slug: string[] }>;
@@ -41,15 +44,18 @@ export default async function WikiPageRoute({ params }: Props) {
notFound();
}
- const [repo, versions, gitMeta] = await Promise.allSettled([
+ const [repo, versions, gitMeta, graphMetricsResult] = await Promise.allSettled([
getRepo(id),
getPageVersions(pageId),
page.target_path ? getGitMetadata(id, page.target_path) : Promise.reject(),
+ page.target_path ? getGraphMetrics(id, page.target_path) : Promise.reject(),
]);
const repoData = repo.status === "fulfilled" ? repo.value : null;
const versionList = versions.status === "fulfilled" ? versions.value : [];
const git = gitMeta.status === "fulfilled" ? gitMeta.value : null;
+ const graphMetrics: GraphMetricsResponse | null =
+ graphMetricsResult.status === "fulfilled" ? graphMetricsResult.value : null;
return (
<div className="flex h-full min-h-0">
@@ -118,6 +124,22 @@ export default async function WikiPageRoute({ params }: Props) {
<article className="prose prose-invert max-w-none leading-relaxed overflow-hidden">
<WikiRenderer content={page.content} />
</article>
+
+ {/* Hallucination warnings */}
+ {Array.isArray(page.metadata?.hallucination_warnings) && (page.metadata.hallucination_warnings as string[]).length > 0 && (
+ <div className="mt-6 rounded-lg border border-amber-400/30 bg-amber-50/5 px-4 py-3">
+ <p className="text-xs font-medium text-amber-400 mb-1.5">
+ Possible inaccuracies detected
+ </p>
+ <ul className="space-y-0.5">
+ {(page.metadata.hallucination_warnings as string[]).map((w, i) => (
+ <li key={i} className="text-xs text-amber-300/80 font-mono">
+ {String(w)}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
</div>
{/* Bottom bar */}
@@ -172,7 +194,48 @@ export default async function WikiPageRoute({ params }: Props) {
</div>
)}
- {/* Co-change partners — now uses the visual bar component */}
+ {/* Graph Intelligence */}
+ {graphMetrics && (
+ <div>
+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">
+ Graph Intelligence
+ </p>
+ <div className="space-y-1.5">
+ {graphMetrics.community_label && (
+ <div className="flex justify-between text-xs">
+ <span className="text-[var(--color-text-tertiary)]">Community</span>
+ <Link
+ href={`/repos/${id}/graph?colorMode=community`}
+ className="text-[var(--color-accent)] hover:underline font-mono text-[11px]"
+ >
+ {graphMetrics.community_label}
+ </Link>
+ </div>
+ )}
+ <div className="flex justify-between text-xs">
+ <span className="text-[var(--color-text-tertiary)]">PageRank</span>
+ <span className={`tabular-nums font-mono text-[11px] ${graphMetrics.pagerank_percentile >= 75 ? "text-green-400" : graphMetrics.pagerank_percentile >= 50 ? "text-yellow-400" : "text-[var(--color-text-secondary)]"}`}>
+ Top {100 - graphMetrics.pagerank_percentile}%
+ </span>
+ </div>
+ <div className="flex justify-between text-xs">
+ <span className="text-[var(--color-text-tertiary)]">Betweenness</span>
+ <span className={`tabular-nums font-mono text-[11px] ${graphMetrics.betweenness_percentile >= 75 ? "text-green-400" : graphMetrics.betweenness_percentile >= 50 ? "text-yellow-400" : "text-[var(--color-text-secondary)]"}`}>
+ Top {100 - graphMetrics.betweenness_percentile}%
+ </span>
+ </div>
+ <div className="flex justify-between text-xs">
+ <span className="text-[var(--color-text-tertiary)]">Degree</span>
+ <span className="text-[var(--color-text-secondary)] tabular-nums font-mono text-[11px]">
+ {graphMetrics.in_degree} in &middot; {graphMetrics.out_degree} out
+ </span>
+ </div>
+ {graphMetrics.is_entry_point && (
+ <Badge variant="accent" className="text-xs">Entry Point</Badge>
+ )}
+ </div>
+ </div>
+ )}
{/* Security findings panel */}
{page.target_path && (
@@ -202,6 +265,14 @@ export default async function WikiPageRoute({ params }: Props) {
<span className="text-[var(--color-text-tertiary)] shrink-0">Level</span>
<span className="text-[var(--color-text-secondary)] tabular-nums">{page.generation_level}</span>
</div>
+ {Array.isArray(page.metadata?.hallucination_warnings) && (page.metadata.hallucination_warnings as string[]).length > 0 && (
+ <div className="flex justify-between gap-2">
+ <span className="text-[var(--color-text-tertiary)] shrink-0">Warnings</span>
+ <Badge variant="stale" className="text-[10px]">
+ {(page.metadata.hallucination_warnings as string[]).length}
+ </Badge>
+ </div>
+ )}
</div>
</div>
</div>
diff --git a/packages/web/src/app/workspace/co-changes/page.tsx b/packages/web/src/app/workspace/co-changes/page.tsx
new file mode 100644
index 000000000..008f229a8
--- /dev/null
+++ b/packages/web/src/app/workspace/co-changes/page.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import { useState } from "react";
+import { GitMerge, Filter } from "lucide-react";
+import { useWorkspaceCoChanges, useWorkspace } from "@/lib/hooks/use-workspace";
+import { CoChangeTable } from "@/components/workspace/co-change-table";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { StatCard } from "@/components/shared/stat-card";
+import { Skeleton } from "@/components/ui/skeleton";
+
+export default function CoChangesPage() {
+ const { workspace } = useWorkspace();
+ const [repo, setRepo] = useState("");
+
+ const { data, isLoading } = useWorkspaceCoChanges({
+ repo: repo || undefined,
+ limit: 100,
+ });
+
+ const repos = workspace?.repos ?? [];
+
+ const selectClass =
+ "rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)] outline-none focus:border-[var(--color-accent-primary)]";
+
+ return (
+ <div className="p-5 sm:p-8 space-y-6 max-w-[1200px]">
+ {/* Header */}
+ <div>
+ <div className="flex items-center gap-2.5 mb-1">
+ <GitMerge className="h-6 w-6 text-[var(--color-accent-primary)]" />
+ <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
+ Co-Changes
+ </h1>
+ </div>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Files across repositories that frequently change together — implicit coupling detected from git history.
+ </p>
+ </div>
+
+ {/* Summary */}
+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-3">
+ <StatCard
+ label="Total Co-Change Pairs"
+ value={data?.total ?? "—"}
+ icon={<GitMerge className="h-4 w-4 text-[var(--color-accent-primary)]" />}
+ />
+ <StatCard
+ label="Repo Pairs"
+ value={
+ data?.co_changes
+ ? new Set(
+ data.co_changes.map((cc) =>
+ [cc.source_repo, cc.target_repo].sort().join("↔"),
+ ),
+ ).size
+ : "—"
+ }
+ icon={<GitMerge className="h-4 w-4 text-purple-400" />}
+ />
+ <StatCard
+ label="Avg Strength"
+ value={
+ data?.co_changes && data.co_changes.length > 0
+ ? `${Math.round(
+ (data.co_changes.reduce((sum, cc) => sum + cc.strength, 0) /
+ data.co_changes.length) *
+ 100,
+ )}%`
+ : "—"
+ }
+ icon={<GitMerge className="h-4 w-4 text-orange-400" />}
+ />
+ </div>
+
+ {/* Filters */}
+ <div className="flex items-center gap-3">
+ <Filter className="h-4 w-4 text-[var(--color-text-tertiary)]" />
+ <span className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ Filter
+ </span>
+ <select
+ value={repo}
+ onChange={(e) => setRepo(e.target.value)}
+ className={selectClass}
+ >
+ <option value="">All Repos</option>
+ {repos.map((r) => (
+ <option key={r.alias} value={r.alias}>
+ {r.alias}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Table */}
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">
+ Co-Change Pairs ({data?.co_changes?.length ?? 0})
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0">
+ {isLoading ? (
+ <div className="space-y-3 py-4">
+ {Array.from({ length: 8 }).map((_, i) => (
+ <Skeleton key={i} className="h-10 w-full" />
+ ))}
+ </div>
+ ) : (
+ <CoChangeTable coChanges={data?.co_changes ?? []} />
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
diff --git a/packages/web/src/app/workspace/contracts/page.tsx b/packages/web/src/app/workspace/contracts/page.tsx
new file mode 100644
index 000000000..7ef75dc2a
--- /dev/null
+++ b/packages/web/src/app/workspace/contracts/page.tsx
@@ -0,0 +1,232 @@
+"use client";
+
+import { useState } from "react";
+import { Link2, Filter } from "lucide-react";
+import { useWorkspaceContracts } from "@/lib/hooks/use-workspace";
+import { useWorkspace } from "@/lib/hooks/use-workspace";
+import { ContractLinksTable } from "@/components/workspace/contract-links-table";
+import { ContractTypeBadge, RoleBadge } from "@/components/workspace/contract-type-badge";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { StatCard } from "@/components/shared/stat-card";
+import { Skeleton } from "@/components/ui/skeleton";
+
+const TYPE_OPTIONS = [
+ { value: "", label: "All Types" },
+ { value: "http", label: "HTTP" },
+ { value: "grpc", label: "gRPC" },
+ { value: "topic", label: "Topic" },
+];
+
+const ROLE_OPTIONS = [
+ { value: "", label: "All Roles" },
+ { value: "provider", label: "Providers" },
+ { value: "consumer", label: "Consumers" },
+];
+
+export default function ContractsPage() {
+ const { workspace } = useWorkspace();
+ const [contractType, setContractType] = useState("");
+ const [repo, setRepo] = useState("");
+ const [role, setRole] = useState("");
+
+ const { data, isLoading } = useWorkspaceContracts({
+ contract_type: contractType || undefined,
+ repo: repo || undefined,
+ role: role || undefined,
+ });
+
+ const repos = workspace?.repos ?? [];
+
+ // Count unmatched contracts (providers with no link, consumers with no link)
+ const linkedContractIds = new Set(
+ (data?.links ?? []).map((l) => l.contract_id),
+ );
+ const unmatchedCount = (data?.contracts ?? []).filter(
+ (c) => !linkedContractIds.has(c.contract_id),
+ ).length;
+
+ const selectClass =
+ "rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)] outline-none focus:border-[var(--color-accent-primary)]";
+
+ return (
+ <div className="p-5 sm:p-8 space-y-6 max-w-[1200px]">
+ {/* Header */}
+ <div>
+ <div className="flex items-center gap-2.5 mb-1">
+ <Link2 className="h-6 w-6 text-[var(--color-accent-primary)]" />
+ <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
+ Contracts
+ </h1>
+ </div>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ HTTP routes, gRPC services, and message topics detected across repositories.
+ </p>
+ </div>
+
+ {/* Summary Stats */}
+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
+ <StatCard
+ label="Total Contracts"
+ value={data?.total_contracts ?? "—"}
+ icon={<Link2 className="h-4 w-4" />}
+ />
+ <StatCard
+ label="Matched Links"
+ value={data?.total_links ?? "—"}
+ icon={<Link2 className="h-4 w-4 text-green-400" />}
+ />
+ <StatCard
+ label="Unmatched"
+ value={isLoading ? "—" : unmatchedCount}
+ description="No matching provider or consumer"
+ icon={<Link2 className="h-4 w-4 text-yellow-400" />}
+ />
+ <StatCard
+ label="By Type"
+ value={
+ data?.by_type
+ ? Object.values(data.by_type).reduce((a, b) => a + b, 0)
+ : "—"
+ }
+ description={
+ data?.by_type
+ ? Object.entries(data.by_type)
+ .map(([k, v]) => `${v} ${k}`)
+ .join(", ")
+ : undefined
+ }
+ icon={<Filter className="h-4 w-4 text-purple-400" />}
+ />
+ </div>
+
+ {/* Filters */}
+ <div className="flex flex-wrap items-center gap-3">
+ <div className="flex items-center gap-2">
+ <Filter className="h-4 w-4 text-[var(--color-text-tertiary)]" />
+ <span className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ Filters
+ </span>
+ </div>
+ <select
+ value={contractType}
+ onChange={(e) => setContractType(e.target.value)}
+ className={selectClass}
+ >
+ {TYPE_OPTIONS.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+ <select
+ value={repo}
+ onChange={(e) => setRepo(e.target.value)}
+ className={selectClass}
+ >
+ <option value="">All Repos</option>
+ {repos.map((r) => (
+ <option key={r.alias} value={r.alias}>
+ {r.alias}
+ </option>
+ ))}
+ </select>
+ <select
+ value={role}
+ onChange={(e) => setRole(e.target.value)}
+ className={selectClass}
+ >
+ {ROLE_OPTIONS.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Contract Links */}
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">
+ Matched Contract Links ({data?.total_links ?? 0})
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0">
+ {isLoading ? (
+ <div className="space-y-3 py-4">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <Skeleton key={i} className="h-10 w-full" />
+ ))}
+ </div>
+ ) : (
+ <ContractLinksTable links={data?.links ?? []} />
+ )}
+ </CardContent>
+ </Card>
+
+ {/* All Contracts */}
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">
+ All Detected Contracts ({data?.total_contracts ?? 0})
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0">
+ {isLoading ? (
+ <div className="space-y-3 py-4">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <Skeleton key={i} className="h-10 w-full" />
+ ))}
+ </div>
+ ) : (data?.contracts ?? []).length === 0 ? (
+ <p className="text-sm text-[var(--color-text-tertiary)] py-4 text-center">
+ No contracts detected.
+ </p>
+ ) : (
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-[var(--color-border-default)] text-left text-xs text-[var(--color-text-tertiary)]">
+ <th className="pb-2 pr-4 font-medium">Contract ID</th>
+ <th className="pb-2 pr-4 font-medium">Type</th>
+ <th className="pb-2 pr-4 font-medium">Role</th>
+ <th className="pb-2 pr-4 font-medium">Repo</th>
+ <th className="pb-2 pr-4 font-medium">File</th>
+ <th className="pb-2 font-medium w-20">Confidence</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-[var(--color-border-default)]">
+ {(data?.contracts ?? []).map((c, i) => (
+ <tr key={i} className="hover:bg-[var(--color-bg-elevated)] transition-colors">
+ <td className="py-2 pr-4">
+ <span className="text-xs font-mono text-[var(--color-text-secondary)] break-all">
+ {c.contract_id}
+ </span>
+ </td>
+ <td className="py-2 pr-4">
+ <ContractTypeBadge type={c.contract_type} />
+ </td>
+ <td className="py-2 pr-4">
+ <RoleBadge role={c.role} />
+ </td>
+ <td className="py-2 pr-4 text-xs font-medium text-[var(--color-text-primary)]">
+ {c.repo}
+ </td>
+ <td className="py-2 pr-4">
+ <span className="text-xs font-mono text-[var(--color-text-tertiary)] truncate block max-w-[200px]">
+ {c.file_path}
+ </span>
+ </td>
+ <td className="py-2 text-xs text-[var(--color-text-tertiary)] tabular-nums">
+ {Math.round(c.confidence * 100)}%
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
diff --git a/packages/web/src/app/workspace/layout.tsx b/packages/web/src/app/workspace/layout.tsx
new file mode 100644
index 000000000..39bc91a65
--- /dev/null
+++ b/packages/web/src/app/workspace/layout.tsx
@@ -0,0 +1,22 @@
+import { redirect } from "next/navigation";
+import { getWorkspace } from "@/lib/api/workspace";
+
+export default async function WorkspaceLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ let isWorkspace = false;
+ try {
+ const ws = await getWorkspace();
+ isWorkspace = ws.is_workspace;
+ } catch {
+ // API unavailable
+ }
+
+ if (!isWorkspace) {
+ redirect("/");
+ }
+
+ return <>{children}</>;
+}
diff --git a/packages/web/src/app/workspace/page.tsx b/packages/web/src/app/workspace/page.tsx
new file mode 100644
index 000000000..dc36f2c09
--- /dev/null
+++ b/packages/web/src/app/workspace/page.tsx
@@ -0,0 +1,212 @@
+import type { Metadata } from "next";
+import Link from "next/link";
+import {
+ Layers,
+ FileText,
+ Code2,
+ BarChart3,
+ Flame,
+ Link2,
+ GitMerge,
+ ArrowRight,
+} from "lucide-react";
+import { getWorkspace, getWorkspaceCoChanges } from "@/lib/api/workspace";
+import { StatCard } from "@/components/shared/stat-card";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { RepoCard } from "@/components/workspace/repo-card";
+import { CrossRepoSummary } from "@/components/workspace/cross-repo-summary";
+import { CoChangeTable } from "@/components/workspace/co-change-table";
+import { ContractTypeBadge } from "@/components/workspace/contract-type-badge";
+import { formatNumber } from "@/lib/utils/format";
+
+export const metadata: Metadata = { title: "Workspace" };
+
+export const revalidate = 30;
+
+async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {
+ try {
+ return await fn();
+ } catch {
+ return null;
+ }
+}
+
+export default async function WorkspaceDashboardPage() {
+ const [workspace, coChanges] = await Promise.all([
+ safeFetch(() => getWorkspace()),
+ safeFetch(() => getWorkspaceCoChanges({ limit: 10 })),
+ ]);
+
+ const wsRepos = workspace?.repos ?? [];
+
+ // Aggregate stats from per-repo data embedded in the workspace response
+ let totalFiles = 0;
+ let totalSymbols = 0;
+ let totalCoveragePctSum = 0;
+ let totalHotspots = 0;
+ let reposWithStats = 0;
+
+ for (const r of wsRepos) {
+ totalFiles += r.file_count;
+ totalSymbols += r.symbol_count;
+ totalCoveragePctSum += r.doc_coverage_pct;
+ totalHotspots += r.hotspot_count;
+ if (r.file_count > 0) reposWithStats++;
+ }
+ const avgCoverage = reposWithStats > 0 ? Math.round(totalCoveragePctSum / reposWithStats) : 0;
+
+ return (
+ <div className="p-5 sm:p-8 space-y-8 max-w-[1200px]">
+ {/* Header */}
+ <div>
+ <div className="flex items-center gap-2.5 mb-1">
+ <Layers className="h-6 w-6 text-[var(--color-accent-primary)]" />
+ <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
+ {workspace?.workspace_name ?? "Workspace"}
+ </h1>
+ </div>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ {workspace?.repos.length ?? 0} repositories
+ {workspace?.workspace_root && (
+ <span className="text-[var(--color-text-tertiary)]">
+ {" "}&middot; {workspace.workspace_root}
+ </span>
+ )}
+ </p>
+ </div>
+
+ {/* Aggregate Stats */}
+ <div className="grid grid-cols-2 gap-4 lg:grid-cols-5">
+ <StatCard
+ label="Total Files"
+ value={formatNumber(totalFiles)}
+ icon={<FileText className="h-4 w-4" />}
+ />
+ <StatCard
+ label="Total Symbols"
+ value={formatNumber(totalSymbols)}
+ icon={<Code2 className="h-4 w-4" />}
+ />
+ <StatCard
+ label="Avg Coverage"
+ value={`${avgCoverage}%`}
+ icon={<BarChart3 className="h-4 w-4" />}
+ />
+ <StatCard
+ label="Hotspots"
+ value={totalHotspots}
+ icon={<Flame className="h-4 w-4 text-orange-400" />}
+ />
+ <StatCard
+ label="Pages"
+ value={formatNumber(wsRepos.reduce((a, r) => a + r.page_count, 0))}
+ icon={<Code2 className="h-4 w-4 text-[var(--color-text-tertiary)]" />}
+ />
+ </div>
+
+ {/* Repo Cards */}
+ <section>
+ <h2 className="text-sm font-medium text-[var(--color-text-primary)] mb-3">
+ Repositories
+ </h2>
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
+ {wsRepos.map((wsRepo) => (
+ <RepoCard
+ key={wsRepo.alias}
+ repoId={wsRepo.repo_id ?? ""}
+ alias={wsRepo.alias}
+ name={wsRepo.alias}
+ path={wsRepo.path}
+ isPrimary={wsRepo.is_primary}
+ stats={wsRepo.file_count > 0 ? {
+ file_count: wsRepo.file_count,
+ symbol_count: wsRepo.symbol_count,
+ doc_coverage_pct: wsRepo.doc_coverage_pct,
+ entry_point_count: 0,
+ freshness_score: 0,
+ dead_export_count: 0,
+ } : null}
+ gitSummary={wsRepo.file_count > 0 ? {
+ total_files: wsRepo.file_count,
+ hotspot_count: wsRepo.hotspot_count,
+ stable_count: 0,
+ average_churn_percentile: 0,
+ top_owners: [],
+ } : null}
+ />
+ ))}
+ </div>
+ </section>
+
+ {/* Cross-Repo Intelligence */}
+ {(workspace?.cross_repo_summary || workspace?.contract_summary) && (
+ <section>
+ <h2 className="text-sm font-medium text-[var(--color-text-primary)] mb-3">
+ Cross-Repo Intelligence
+ </h2>
+ <CrossRepoSummary
+ crossRepo={workspace?.cross_repo_summary ?? null}
+ contracts={workspace?.contract_summary ?? null}
+ />
+
+ {/* Contract type breakdown */}
+ {workspace?.contract_summary && workspace.contract_summary.total_links > 0 && (
+ <Card className="mt-3">
+ <CardHeader className="pb-2">
+ <div className="flex items-center justify-between">
+ <CardTitle className="text-sm font-medium flex items-center gap-2">
+ <Link2 className="h-4 w-4 text-[var(--color-accent-primary)]" />
+ API Contracts
+ </CardTitle>
+ <Link
+ href="/workspace/contracts"
+ className="text-xs text-[var(--color-accent-primary)] hover:underline flex items-center gap-1"
+ >
+ View all <ArrowRight className="h-3 w-3" />
+ </Link>
+ </div>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <div className="flex items-center gap-3">
+ {Object.entries(workspace.contract_summary.by_type).map(([type, count]) => (
+ <div key={type} className="flex items-center gap-1.5">
+ <ContractTypeBadge type={type} />
+ <span className="text-xs text-[var(--color-text-secondary)] tabular-nums">
+ {count}
+ </span>
+ </div>
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+ )}
+ </section>
+ )}
+
+ {/* Top Co-Changes */}
+ {coChanges && coChanges.co_changes.length > 0 && (
+ <section>
+ <Card>
+ <CardHeader className="pb-2">
+ <div className="flex items-center justify-between">
+ <CardTitle className="text-sm font-medium flex items-center gap-2">
+ <GitMerge className="h-4 w-4 text-[var(--color-accent-primary)]" />
+ Top Cross-Repo Co-Changes
+ </CardTitle>
+ <Link
+ href="/workspace/co-changes"
+ className="text-xs text-[var(--color-accent-primary)] hover:underline flex items-center gap-1"
+ >
+ View all <ArrowRight className="h-3 w-3" />
+ </Link>
+ </div>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <CoChangeTable coChanges={coChanges.co_changes} compact />
+ </CardContent>
+ </Card>
+ </section>
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/components/dashboard/community-summary-grid.tsx b/packages/web/src/components/dashboard/community-summary-grid.tsx
new file mode 100644
index 000000000..6dabefb80
--- /dev/null
+++ b/packages/web/src/components/dashboard/community-summary-grid.tsx
@@ -0,0 +1,172 @@
+"use client";
+
+import { useState } from "react";
+import { Network, ChevronRight, ChevronDown, ArrowRight, X } from "lucide-react";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Badge } from "@/components/ui/badge";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { Skeleton } from "@/components/ui/skeleton";
+import { truncatePath } from "@/lib/utils/format";
+import { useCommunityDetail } from "@/lib/hooks/use-graph";
+import { cn } from "@/lib/utils/cn";
+import type { CommunitySummaryItem } from "@/lib/api/types";
+
+const COMMUNITY_COLORS = [
+ "bg-indigo-400", "bg-pink-400", "bg-emerald-400", "bg-amber-400",
+ "bg-blue-400", "bg-purple-400", "bg-rose-400", "bg-teal-400",
+ "bg-orange-400", "bg-cyan-400",
+];
+
+function CommunityDetail({ repoId, communityId, onClose }: { repoId: string; communityId: number; onClose: () => void }) {
+ const { community, isLoading } = useCommunityDetail(repoId, communityId);
+
+ if (isLoading) {
+ return (
+ <div className="p-4 space-y-2">
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="h-3 w-full" />
+ <Skeleton className="h-3 w-3/4" />
+ </div>
+ );
+ }
+
+ if (!community) return null;
+
+ return (
+ <div className="border-t border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/50">
+ <div className="flex items-center justify-between px-4 py-2 border-b border-[var(--color-border-default)]">
+ <span className="text-xs font-medium text-[var(--color-text-primary)]">
+ {community.label} &middot; {community.member_count} files &middot; cohesion {(community.cohesion * 100).toFixed(0)}%
+ </span>
+ <button onClick={onClose} className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]">
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4">
+ {/* Members */}
+ <div>
+ <p className="text-[10px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">
+ Members ({community.member_count})
+ </p>
+ <ScrollArea className="max-h-[200px]">
+ <div className="space-y-1">
+ {community.members.slice(0, 20).map((m) => (
+ <div key={m.path} className="flex items-center justify-between gap-2 py-0.5">
+ <span className="text-[11px] font-mono text-[var(--color-text-secondary)] truncate" title={m.path}>
+ {truncatePath(m.path)}
+ </span>
+ <div className="flex items-center gap-1 shrink-0">
+ {m.is_entry_point && (
+ <Badge variant="accent" className="text-[8px] h-3.5">EP</Badge>
+ )}
+ <span className="text-[9px] font-mono text-[var(--color-text-tertiary)] tabular-nums">
+ {m.pagerank.toFixed(4)}
+ </span>
+ </div>
+ </div>
+ ))}
+ {community.member_count > 20 && (
+ <p className="text-[10px] text-[var(--color-text-tertiary)]">+{community.member_count - 20} more</p>
+ )}
+ </div>
+ </ScrollArea>
+ </div>
+
+ {/* Neighbors */}
+ {community.neighboring_communities.length > 0 && (
+ <div>
+ <p className="text-[10px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">
+ Connected Communities
+ </p>
+ <div className="space-y-1.5">
+ {community.neighboring_communities.map((n) => (
+ <div key={n.community_id} className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-1.5 min-w-0">
+ <ArrowRight className="h-2.5 w-2.5 shrink-0 text-[var(--color-text-tertiary)]" />
+ <span className="text-[11px] text-[var(--color-text-secondary)] truncate">{n.label}</span>
+ </div>
+ <Badge variant="outline" className="text-[9px] h-4 shrink-0">{n.cross_edge_count} edges</Badge>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+interface CommunitySummaryGridProps {
+ communities: CommunitySummaryItem[];
+ repoId: string;
+}
+
+export function CommunitySummaryGrid({ communities, repoId }: CommunitySummaryGridProps) {
+ const [expandedId, setExpandedId] = useState<number | null>(null);
+
+ if (communities.length === 0) return null;
+
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium flex items-center gap-2">
+ <Network className="h-4 w-4" />
+ Architecture Communities ({communities.length})
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="p-0">
+ {/* Community list */}
+ <div className="divide-y divide-[var(--color-border-default)]">
+ {communities.slice(0, 12).map((c, i) => (
+ <div key={c.community_id}>
+ <button
+ onClick={() => setExpandedId(expandedId === c.community_id ? null : c.community_id)}
+ className={cn(
+ "flex items-center gap-3 w-full px-4 py-2.5 text-left hover:bg-[var(--color-bg-elevated)] transition-colors",
+ expandedId === c.community_id && "bg-[var(--color-bg-elevated)]",
+ )}
+ >
+ {/* Color dot */}
+ <span className={cn("w-2.5 h-2.5 rounded-full shrink-0", COMMUNITY_COLORS[i % COMMUNITY_COLORS.length])} />
+
+ {/* Label */}
+ <span className="text-xs font-medium text-[var(--color-text-primary)] truncate min-w-0 flex-1">
+ {c.label}
+ </span>
+
+ {/* File count */}
+ <span className="text-[10px] text-[var(--color-text-tertiary)] tabular-nums shrink-0">
+ {c.member_count} files
+ </span>
+
+ {/* Cohesion mini bar */}
+ <div className="w-12 h-1.5 rounded-full bg-[var(--color-bg-elevated)] overflow-hidden shrink-0">
+ <div
+ className="h-full rounded-full bg-[var(--color-accent)]"
+ style={{ width: `${Math.round(c.cohesion * 100)}%` }}
+ />
+ </div>
+
+ {/* Expand arrow */}
+ {expandedId === c.community_id ? (
+ <ChevronDown className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
+ ) : (
+ <ChevronRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
+ )}
+ </button>
+
+ {/* Detail panel */}
+ {expandedId === c.community_id && (
+ <CommunityDetail
+ repoId={repoId}
+ communityId={c.community_id}
+ onClose={() => setExpandedId(null)}
+ />
+ )}
+ </div>
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/packages/web/src/components/dashboard/dependency-heatmap.tsx b/packages/web/src/components/dashboard/dependency-heatmap.tsx
new file mode 100644
index 000000000..ae94793d5
--- /dev/null
+++ b/packages/web/src/components/dashboard/dependency-heatmap.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+import { useMemo, useRef, useEffect } from "react";
+import type { ModuleGraphResponse } from "@/lib/api/types";
+
+interface DependencyHeatmapProps {
+ moduleGraph: ModuleGraphResponse;
+}
+
+function heatColor(count: number, max: number): string {
+ if (count === 0) return "transparent";
+ const intensity = Math.min(1, count / Math.max(max, 1));
+ if (intensity > 0.7) return `rgba(245, 149, 32, ${0.4 + intensity * 0.5})`;
+ if (intensity > 0.3) return `rgba(245, 149, 32, ${0.15 + intensity * 0.35})`;
+ return `rgba(245, 149, 32, ${0.05 + intensity * 0.15})`;
+}
+
+export function DependencyHeatmap({ moduleGraph }: DependencyHeatmapProps) {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+
+ const { modules, matrix, maxCount } = useMemo(() => {
+ const mods = moduleGraph.nodes
+ .sort((a, b) => b.avg_pagerank - a.avg_pagerank)
+ .slice(0, 20)
+ .map((m) => m.module_id);
+
+ const modIdx = new Map<string, number>();
+ mods.forEach((m, i) => modIdx.set(m, i));
+
+ const mat: number[][] = Array.from({ length: mods.length }, () =>
+ new Array(mods.length).fill(0)
+ );
+
+ let max = 0;
+ for (const e of moduleGraph.edges) {
+ const si = modIdx.get(e.source);
+ const ti = modIdx.get(e.target);
+ if (si !== undefined && ti !== undefined) {
+ mat[si][ti] += e.edge_count;
+ if (mat[si][ti] > max) max = mat[si][ti];
+ }
+ }
+
+ return { modules: mods, matrix: mat, maxCount: max };
+ }, [moduleGraph]);
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas || modules.length === 0) return;
+
+ const size = modules.length;
+ const cellSize = Math.max(14, Math.min(28, Math.floor(300 / size)));
+ const labelWidth = 100;
+ const padding = 4;
+ const totalWidth = labelWidth + size * (cellSize + padding) + padding;
+ const totalHeight = labelWidth + size * (cellSize + padding) + padding;
+
+ canvas.width = totalWidth * 2;
+ canvas.height = totalHeight * 2;
+ canvas.style.width = `${totalWidth}px`;
+ canvas.style.height = `${totalHeight}px`;
+
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+ ctx.scale(2, 2);
+
+ // Clear
+ ctx.clearRect(0, 0, totalWidth, totalHeight);
+
+ // Draw labels (top)
+ ctx.save();
+ ctx.font = "9px var(--font-geist-mono, monospace)";
+ ctx.fillStyle = "var(--color-text-tertiary)";
+ ctx.textAlign = "right";
+ for (let i = 0; i < size; i++) {
+ const label = modules[i].split("/").pop() ?? modules[i];
+ const x = labelWidth + i * (cellSize + padding) + cellSize / 2;
+ ctx.save();
+ ctx.translate(x, labelWidth - 4);
+ ctx.rotate(-Math.PI / 4);
+ ctx.fillText(label.slice(0, 12), 0, 0);
+ ctx.restore();
+ }
+
+ // Draw labels (left)
+ ctx.textAlign = "right";
+ ctx.textBaseline = "middle";
+ for (let i = 0; i < size; i++) {
+ const label = modules[i].split("/").pop() ?? modules[i];
+ const y = labelWidth + i * (cellSize + padding) + cellSize / 2;
+ ctx.fillText(label.slice(0, 12), labelWidth - 6, y);
+ }
+ ctx.restore();
+
+ // Draw cells
+ for (let r = 0; r < size; r++) {
+ for (let c = 0; c < size; c++) {
+ const count = matrix[r][c];
+ const x = labelWidth + c * (cellSize + padding);
+ const y = labelWidth + r * (cellSize + padding);
+
+ if (r === c) {
+ ctx.fillStyle = "rgba(255,255,255,0.03)";
+ } else {
+ ctx.fillStyle = heatColor(count, maxCount);
+ }
+ ctx.beginPath();
+ ctx.roundRect(x, y, cellSize, cellSize, 2);
+ ctx.fill();
+ }
+ }
+ }, [modules, matrix, maxCount]);
+
+ if (modules.length < 2) return null;
+
+ return (
+ <div className="overflow-x-auto">
+ <canvas ref={canvasRef} />
+ </div>
+ );
+}
diff --git a/packages/web/src/components/dashboard/execution-flows-panel.tsx b/packages/web/src/components/dashboard/execution-flows-panel.tsx
new file mode 100644
index 000000000..4a96d29cf
--- /dev/null
+++ b/packages/web/src/components/dashboard/execution-flows-panel.tsx
@@ -0,0 +1,104 @@
+"use client";
+
+import { useState } from "react";
+import { ChevronRight, ChevronDown } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { cn } from "@/lib/utils/cn";
+import type { ExecutionFlowEntry } from "@/lib/api/types";
+
+interface ExecutionFlowsPanelProps {
+ flows: ExecutionFlowEntry[];
+ repoId: string;
+}
+
+function FlowRow({ flow }: { flow: ExecutionFlowEntry }) {
+ const [expanded, setExpanded] = useState(false);
+
+ const scoreColor =
+ flow.entry_point_score >= 0.7
+ ? "text-green-400 bg-green-400/10 border-green-400/20"
+ : flow.entry_point_score >= 0.4
+ ? "text-yellow-400 bg-yellow-400/10 border-yellow-400/20"
+ : "text-[var(--color-text-tertiary)] bg-[var(--color-bg-elevated)] border-[var(--color-border-default)]";
+
+ return (
+ <div className="border-b border-[var(--color-border-default)] last:border-0">
+ <button
+ onClick={() => setExpanded((s) => !s)}
+ className="flex items-center gap-2 w-full px-3 py-2.5 text-left hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ {expanded ? (
+ <ChevronDown className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
+ ) : (
+ <ChevronRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
+ )}
+
+ <span className="text-xs font-mono text-[var(--color-text-primary)] truncate min-w-0 flex-1">
+ {flow.entry_point_name}
+ </span>
+
+ <span className={cn("text-[10px] font-mono px-1.5 py-0.5 rounded border shrink-0", scoreColor)}>
+ {(flow.entry_point_score * 100).toFixed(0)}
+ </span>
+
+ <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0 tabular-nums">
+ {flow.depth} calls
+ </span>
+
+ {flow.crosses_community && (
+ <Badge variant="outline" className="text-[9px] shrink-0 h-4">
+ cross-community
+ </Badge>
+ )}
+ </button>
+
+ {expanded && flow.trace.length > 1 && (
+ <div className="px-3 pb-3 pl-8">
+ <div className="flex flex-wrap items-center gap-1">
+ {flow.trace.slice(0, 12).map((sym, i) => {
+ const name = sym.includes("::") ? sym.split("::").pop() : sym.split("/").pop();
+ return (
+ <span key={i} className="flex items-center gap-1">
+ {i > 0 && (
+ <ChevronRight className="h-2.5 w-2.5 text-[var(--color-text-tertiary)]" />
+ )}
+ <span
+ className="text-[10px] font-mono text-[var(--color-text-secondary)] px-1 py-0.5 rounded bg-[var(--color-bg-elevated)]"
+ title={sym}
+ >
+ {name}
+ </span>
+ </span>
+ );
+ })}
+ {flow.trace.length > 12 && (
+ <span className="text-[10px] text-[var(--color-text-tertiary)]">
+ +{flow.trace.length - 12} more
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function ExecutionFlowsPanel({ flows, repoId }: ExecutionFlowsPanelProps) {
+ if (flows.length === 0) return null;
+
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Execution Flows</CardTitle>
+ </CardHeader>
+ <CardContent className="p-0">
+ <div className="divide-y divide-[var(--color-border-default)]">
+ {flows.slice(0, 8).map((flow) => (
+ <FlowRow key={flow.entry_point} flow={flow} />
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/packages/web/src/components/dashboard/quick-actions.tsx b/packages/web/src/components/dashboard/quick-actions.tsx
index b9ba8de99..1e8c657e5 100644
--- a/packages/web/src/components/dashboard/quick-actions.tsx
+++ b/packages/web/src/components/dashboard/quick-actions.tsx
@@ -88,12 +88,12 @@ const ACTIONS: ActionDef[] = [
{
key: "sync",
label: "Sync",
- description: "Incremental re-index — only changed files",
+ description: "Update everything — only affected pages regenerated",
icon: Zap,
destructive: false,
needsConfirm: true,
confirmTitle: "Sync Repository",
- confirmDescription: "This will re-index changed files and regenerate affected pages.",
+ confirmDescription: "Re-indexes the dependency graph, git metadata, dead code, and decisions. Only wiki pages affected by recent changes are regenerated (minimal LLM cost).",
},
{
key: "resync",
@@ -131,9 +131,11 @@ export function QuickActions({ repoId, repoName, pageCount = 0, modelName = "",
const [pendingAction, setPendingAction] = useState<ActionDef | null>(null);
const [activeJobId, setActiveJobId] = useState<string | null>(null);
+ // Sync regenerates ~10-15% of pages (only affected by changes).
+ // Full resync regenerates all pages.
const estimate = pageCount > 0 && pendingAction?.key !== "dead-code"
? estimateCost(
- pendingAction?.key === "sync" ? Math.ceil(pageCount * 0.15) : pageCount,
+ pendingAction?.key === "sync" ? Math.max(1, Math.ceil(pageCount * 0.1)) : pageCount,
modelName
)
: null;
@@ -248,7 +250,7 @@ export function QuickActions({ repoId, repoName, pageCount = 0, modelName = "",
<div className="grid grid-cols-3 gap-2 text-center">
<div>
<p className="text-sm font-semibold text-[var(--color-text-primary)] tabular-nums">
- {formatNumber(pendingAction.key === "sync" ? Math.ceil(pageCount * 0.15) : pageCount)}
+ {formatNumber(pendingAction.key === "sync" ? Math.max(1, Math.ceil(pageCount * 0.1)) : pageCount)}
</p>
<p className="text-[10px] text-[var(--color-text-tertiary)]">pages</p>
</div>
diff --git a/packages/web/src/components/dead-code/finding-row.tsx b/packages/web/src/components/dead-code/finding-row.tsx
index 2afc13d4f..050b25fd9 100644
--- a/packages/web/src/components/dead-code/finding-row.tsx
+++ b/packages/web/src/components/dead-code/finding-row.tsx
@@ -70,20 +70,20 @@ export function FindingRow({ finding, selected, onToggle, onUpdate }: FindingRow
{formatConfidence(finding.confidence)}
</span>
</td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)]">
+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] hidden md:table-cell">
{finding.primary_owner ?? "—"}
</td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-tertiary)] tabular-nums">
+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-tertiary)] tabular-nums hidden md:table-cell">
{finding.lines}
</td>
- <td className="px-4 py-2.5">
+ <td className="px-4 py-2.5 hidden sm:table-cell">
{finding.safe_to_delete ? (
<Badge variant="fresh">Safe</Badge>
) : (
<Badge variant="default">Review</Badge>
)}
</td>
- <td className="px-4 py-2.5">
+ <td className="px-4 py-2.5 hidden sm:table-cell">
<span
className={cn(
"inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium",
@@ -93,7 +93,7 @@ export function FindingRow({ finding, selected, onToggle, onUpdate }: FindingRow
{finding.status.replace(/_/g, " ")}
</span>
</td>
- <td className="px-4 py-2.5">
+ <td className="px-4 py-2.5 hidden lg:table-cell">
{finding.status === "open" && (
<div className="flex items-center gap-1">
<Button
diff --git a/packages/web/src/components/dead-code/findings-table.tsx b/packages/web/src/components/dead-code/findings-table.tsx
index 1eb25666c..cf0edc389 100644
--- a/packages/web/src/components/dead-code/findings-table.tsx
+++ b/packages/web/src/components/dead-code/findings-table.tsx
@@ -163,7 +163,7 @@ export function FindingsTable({ repoId }: FindingsTableProps) {
/>
) : (
<div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto mt-2">
- <table className="w-full min-w-[560px] text-sm">
+ <table className="w-full text-sm">
<thead>
<tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
<th className="px-4 py-2.5 w-8">
@@ -180,15 +180,15 @@ export function FindingsTable({ repoId }: FindingsTableProps) {
<th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24">
Confidence
</th>
- <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider hidden md:table-cell">
Owner
</th>
- <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-16">
+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-16 hidden md:table-cell">
Lines
</th>
- <th className="px-4 py-2.5 w-20" />
- <th className="px-4 py-2.5 w-24" />
- <th className="px-4 py-2.5 w-36" />
+ <th className="px-4 py-2.5 w-20 hidden sm:table-cell" />
+ <th className="px-4 py-2.5 w-24 hidden sm:table-cell" />
+ <th className="px-4 py-2.5 w-36 hidden lg:table-cell" />
</tr>
</thead>
<tbody>
diff --git a/packages/web/src/components/decisions/decision-detail.tsx b/packages/web/src/components/decisions/decision-detail.tsx
index 0012be346..61b63347c 100644
--- a/packages/web/src/components/decisions/decision-detail.tsx
+++ b/packages/web/src/components/decisions/decision-detail.tsx
@@ -1,6 +1,8 @@
"use client";
import * as React from "react";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
import { Badge } from "@/components/ui/badge";
import { patchDecision } from "@/lib/api/decisions";
import type { DecisionRecordResponse } from "@/lib/api/types";
@@ -166,7 +168,9 @@ function Section({ title, text }: { title: string; text: string }) {
return (
<div>
<h3 className="mb-1 text-sm font-medium text-[var(--color-text-secondary)]">{title}</h3>
- <p className="text-sm text-[var(--color-text-primary)] leading-relaxed">{text}</p>
+ <div className="text-sm text-[var(--color-text-primary)] leading-relaxed prose prose-sm prose-invert max-w-none [&>p]:mb-2 [&>p:last-child]:mb-0">
+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{text}</ReactMarkdown>
+ </div>
</div>
);
}
diff --git a/packages/web/src/components/docs/docs-explorer.tsx b/packages/web/src/components/docs/docs-explorer.tsx
index 5e811eb55..796a289b1 100644
--- a/packages/web/src/components/docs/docs-explorer.tsx
+++ b/packages/web/src/components/docs/docs-explorer.tsx
@@ -1,6 +1,7 @@
"use client";
-import { useState, useCallback } from "react";
+import { useState, useCallback, useEffect } from "react";
+import { useSearchParams, useRouter } from "next/navigation";
import { BookOpen, PanelLeftClose, PanelLeft } from "lucide-react";
import { cn } from "@/lib/utils/cn";
import { usePages } from "@/lib/hooks/use-pages";
@@ -17,10 +18,26 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {
const { pages, isLoading } = usePages(repoId);
const [selectedPage, setSelectedPage] = useState<PageResponse | null>(null);
const [treePanelOpen, setTreePanelOpen] = useState(true);
+ const searchParams = useSearchParams();
+ const router = useRouter();
+
+ // Restore selection from URL on mount / when pages load
+ useEffect(() => {
+ if (pages.length === 0) return;
+ const pageId = searchParams.get("page");
+ if (pageId && !selectedPage) {
+ const match = pages.find((p) => p.id === pageId);
+ if (match) setSelectedPage(match);
+ }
+ }, [pages, searchParams, selectedPage]);
const handleSelectPage = useCallback((page: PageResponse) => {
setSelectedPage(page);
- }, []);
+ // Update URL without full navigation
+ const params = new URLSearchParams(searchParams.toString());
+ params.set("page", page.id);
+ router.replace(`?${params.toString()}`, { scroll: false });
+ }, [searchParams, router]);
if (isLoading) {
return (
diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsx
index b82d530cb..d9d54d965 100644
--- a/packages/web/src/components/docs/docs-viewer.tsx
+++ b/packages/web/src/components/docs/docs-viewer.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import {
FileText,
@@ -13,16 +13,155 @@ import {
ArrowRight,
RefreshCw,
Loader2,
+ PanelRight,
+ PanelRightClose,
+ Network,
+ Activity,
+ GitBranch,
} from "lucide-react";
import { cn } from "@/lib/utils/cn";
-import { ChatMarkdown } from "@/components/chat/chat-markdown";
+import { WikiMarkdown } from "@/components/wiki/wiki-markdown";
+import { VersionHistory } from "@/components/wiki/version-history";
import { ConfidenceBadge } from "@/components/wiki/confidence-badge";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { Skeleton } from "@/components/ui/skeleton";
import { formatRelativeTime, formatTokens } from "@/lib/utils/format";
import { downloadTextFile } from "@/lib/utils/download";
+import { useGraphMetrics, useCallersCallees } from "@/lib/hooks/use-graph";
import type { PageResponse } from "@/lib/api/types";
+function PercentileBar({ value, label }: { value: number; label: string }) {
+ const pct = 100 - value;
+ return (
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] text-[var(--color-text-tertiary)] shrink-0">{label}</span>
+ <div className="flex items-center gap-1.5">
+ <div className="w-16 h-1.5 rounded-full bg-[var(--color-bg-elevated)] overflow-hidden">
+ <div
+ className={cn(
+ "h-full rounded-full",
+ value >= 75 ? "bg-green-400" : value >= 50 ? "bg-yellow-400" : "bg-[var(--color-text-tertiary)]",
+ )}
+ style={{ width: `${value}%` }}
+ />
+ </div>
+ <span className={cn(
+ "text-[10px] font-mono tabular-nums w-10 text-right",
+ value >= 75 ? "text-green-400" : value >= 50 ? "text-yellow-400" : "text-[var(--color-text-tertiary)]",
+ )}>
+ Top {pct}%
+ </span>
+ </div>
+ </div>
+ );
+}
+
+function DocsSidebar({ repoId, targetPath }: { repoId: string; targetPath: string }) {
+ const nodeId = targetPath;
+ const { metrics, isLoading: metricsLoading } = useGraphMetrics(repoId, nodeId);
+ const symbolNodeId = targetPath.includes("::") ? targetPath : null;
+ const { data: callData } = useCallersCallees(repoId, symbolNodeId);
+
+ if (metricsLoading) {
+ return (
+ <div className="space-y-3 p-3">
+ <Skeleton className="h-4 w-20" />
+ <Skeleton className="h-3 w-full" />
+ <Skeleton className="h-3 w-full" />
+ <Skeleton className="h-3 w-3/4" />
+ </div>
+ );
+ }
+
+ if (!metrics) {
+ return (
+ <div className="p-3">
+ <p className="text-[11px] text-[var(--color-text-tertiary)] italic">No graph data available</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4 p-3">
+ {/* Graph Metrics */}
+ <div>
+ <div className="flex items-center gap-1.5 mb-2">
+ <Activity className="h-3 w-3 text-[var(--color-text-tertiary)]" />
+ <span className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ Importance
+ </span>
+ </div>
+ <div className="space-y-2">
+ <PercentileBar value={metrics.pagerank_percentile} label="PageRank" />
+ <PercentileBar value={metrics.betweenness_percentile} label="Centrality" />
+ <div className="flex items-center justify-between">
+ <span className="text-[11px] text-[var(--color-text-tertiary)]">Degree</span>
+ <span className="text-[11px] font-mono text-[var(--color-text-secondary)]">
+ {metrics.in_degree} in &middot; {metrics.out_degree} out
+ </span>
+ </div>
+ {metrics.is_entry_point && (
+ <Badge variant="accent" className="text-[10px]">Entry Point</Badge>
+ )}
+ </div>
+ </div>
+
+ {/* Community */}
+ {metrics.community_label && (
+ <div>
+ <div className="flex items-center gap-1.5 mb-2">
+ <Network className="h-3 w-3 text-[var(--color-text-tertiary)]" />
+ <span className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ Community
+ </span>
+ </div>
+ <Link
+ href={`/repos/${repoId}/graph?colorMode=community`}
+ className="inline-flex items-center gap-1 text-[11px] text-[var(--color-accent)] hover:underline"
+ >
+ {metrics.community_label}
+ <ArrowRight className="h-2.5 w-2.5" />
+ </Link>
+ </div>
+ )}
+
+ {/* Callers/Callees (for symbol pages) */}
+ {callData && (callData.caller_count > 0 || callData.callee_count > 0) && (
+ <div>
+ <div className="flex items-center gap-1.5 mb-2">
+ <GitBranch className="h-3 w-3 text-[var(--color-text-tertiary)]" />
+ <span className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ Call Graph
+ </span>
+ </div>
+ {callData.caller_count > 0 && (
+ <div className="mb-2">
+ <p className="text-[10px] text-[var(--color-text-tertiary)] mb-1">Called by ({callData.caller_count})</p>
+ {callData.callers.slice(0, 5).map((c) => (
+ <p key={c.symbol_id} className="text-[11px] font-mono text-[var(--color-text-secondary)] truncate pl-2" title={c.symbol_id}>
+ {c.name}
+ </p>
+ ))}
+ </div>
+ )}
+ {callData.callee_count > 0 && (
+ <div>
+ <p className="text-[10px] text-[var(--color-text-tertiary)] mb-1">Calls ({callData.callee_count})</p>
+ {callData.callees.slice(0, 5).map((c) => (
+ <p key={c.symbol_id} className="text-[11px] font-mono text-[var(--color-text-secondary)] truncate pl-2" title={c.symbol_id}>
+ {c.name}
+ </p>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
interface DocsViewerProps {
page: PageResponse | null;
repoId: string;
@@ -31,6 +170,7 @@ interface DocsViewerProps {
export function DocsViewer({ page, repoId, isLoading }: DocsViewerProps) {
const scrollRef = useRef<HTMLDivElement>(null);
+ const [sidebarOpen, setSidebarOpen] = useState(true);
// Scroll to top when page changes
useEffect(() => {
@@ -63,94 +203,151 @@ export function DocsViewer({ page, repoId, isLoading }: DocsViewerProps) {
);
}
+ const hasTargetPath = !!page.target_path;
+
return (
- <div className="flex flex-col h-full">
- {/* Sticky header */}
- <div className="sticky top-0 z-10 flex items-center gap-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]/95 backdrop-blur px-4 sm:px-6 py-2.5 flex-wrap sm:flex-nowrap shrink-0">
- {/* Path breadcrumb */}
- <div className="flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] min-w-0 flex-1">
- <span className="font-mono truncate text-[var(--color-text-secondary)]">
- {page.target_path || page.page_type}
- </span>
+ <div className="flex h-full">
+ {/* Main content */}
+ <div className="flex flex-col flex-1 min-w-0">
+ {/* Sticky header */}
+ <div className="sticky top-0 z-10 flex items-center gap-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]/95 backdrop-blur px-4 sm:px-6 py-2.5 flex-wrap sm:flex-nowrap shrink-0">
+ {/* Path breadcrumb */}
+ <div className="flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] min-w-0 flex-1">
+ <span className="font-mono truncate text-[var(--color-text-secondary)]">
+ {page.target_path || page.page_type}
+ </span>
+ </div>
+
+ {/* Confidence */}
+ <ConfidenceBadge
+ score={page.confidence}
+ status={page.freshness_status}
+ showScore
+ />
+
+ {/* Provider */}
+ <Badge variant="outline" className="font-mono text-[10px] hidden sm:flex shrink-0">
+ <Cpu className="h-2.5 w-2.5 mr-1" />
+ <span className="truncate max-w-[100px]">{page.model_name}</span>
+ </Badge>
+
+ {/* Download as markdown */}
+ <button
+ onClick={() => {
+ const filename = (page.target_path || page.title).replace(/\//g, "_") + ".md";
+ const header = `# ${page.title}\n\n> Path: ${page.target_path}\n\n`;
+ downloadTextFile(header + page.content, filename);
+ }}
+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] transition-colors shrink-0"
+ title="Download as Markdown"
+ >
+ <Download className="h-3.5 w-3.5" />
+ </button>
+
+ {/* Open full page link */}
+ <Link
+ href={`/repos/${repoId}/wiki/${encodeURIComponent(page.id)}`}
+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] transition-colors shrink-0"
+ title="Open full page"
+ >
+ <ExternalLink className="h-3.5 w-3.5" />
+ </Link>
+
+ {/* Sidebar toggle */}
+ {hasTargetPath && (
+ <button
+ onClick={() => setSidebarOpen((o) => !o)}
+ className={cn(
+ "transition-colors shrink-0",
+ sidebarOpen
+ ? "text-[var(--color-accent)] hover:text-[var(--color-accent)]"
+ : "text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)]",
+ )}
+ title={sidebarOpen ? "Hide insights" : "Show insights"}
+ >
+ {sidebarOpen ? (
+ <PanelRightClose className="h-3.5 w-3.5" />
+ ) : (
+ <PanelRight className="h-3.5 w-3.5" />
+ )}
+ </button>
+ )}
</div>
- {/* Confidence */}
- <ConfidenceBadge
- score={page.confidence}
- status={page.freshness_status}
- showScore
- />
-
- {/* Provider */}
- <Badge variant="outline" className="font-mono text-[10px] hidden sm:flex shrink-0">
- <Cpu className="h-2.5 w-2.5 mr-1" />
- <span className="truncate max-w-[100px]">{page.model_name}</span>
- </Badge>
-
- {/* Download as markdown */}
- <button
- onClick={() => {
- const filename = (page.target_path || page.title).replace(/\//g, "_") + ".md";
- const header = `# ${page.title}\n\n> Path: ${page.target_path}\n\n`;
- downloadTextFile(header + page.content, filename);
- }}
- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] transition-colors shrink-0"
- title="Download as Markdown"
- >
- <Download className="h-3.5 w-3.5" />
- </button>
-
- {/* Open full page link */}
- <Link
- href={`/repos/${repoId}/wiki/${encodeURIComponent(page.id)}`}
- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] transition-colors shrink-0"
- title="Open full page"
- >
- <ExternalLink className="h-3.5 w-3.5" />
- </Link>
- </div>
+ {/* Content */}
+ <div ref={scrollRef} className="flex-1 overflow-y-auto">
+ <div className="px-4 sm:px-6 py-6 max-w-[768px] mx-auto">
+ {/* Title */}
+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 break-words">
+ {page.title}
+ </h1>
- {/* Content */}
- <div ref={scrollRef} className="flex-1 overflow-y-auto">
- <div className="px-4 sm:px-6 py-6 max-w-[768px] mx-auto">
- {/* Title */}
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 break-words">
- {page.title}
- </h1>
-
- {/* Meta row */}
- <div className="flex items-center gap-3 text-[10px] text-[var(--color-text-tertiary)] mb-6">
- <span className="flex items-center gap-1">
- <Clock className="h-3 w-3" />
- {formatRelativeTime(page.updated_at)}
- </span>
- <span>v{page.version}</span>
- <span className="font-mono">
- {formatTokens(page.input_tokens)} in · {formatTokens(page.output_tokens)} out
- </span>
- </div>
+ {/* Meta row */}
+ <div className="flex items-center gap-3 text-[10px] text-[var(--color-text-tertiary)] mb-6">
+ <span className="flex items-center gap-1">
+ <Clock className="h-3 w-3" />
+ {formatRelativeTime(page.updated_at)}
+ </span>
+ <span>v{page.version}</span>
+ <span className="font-mono">
+ {formatTokens(page.input_tokens)} in · {formatTokens(page.output_tokens)} out
+ </span>
+ </div>
- {/* Human notes */}
- {page.human_notes && (
- <div className="mb-4 rounded-lg border border-[var(--color-border-accent)] bg-[var(--color-accent-blue)]/5 px-4 py-3">
- <div className="flex items-center gap-1.5 mb-1.5">
- <StickyNote className="h-3.5 w-3.5 text-[var(--color-accent-blue)]" />
- <span className="text-xs font-medium text-[var(--color-accent-blue)] uppercase tracking-wider">
- Human Notes
- </span>
+ {/* Human notes */}
+ {page.human_notes && (
+ <div className="mb-4 rounded-lg border border-[var(--color-border-accent)] bg-[var(--color-accent-blue)]/5 px-4 py-3">
+ <div className="flex items-center gap-1.5 mb-1.5">
+ <StickyNote className="h-3.5 w-3.5 text-[var(--color-accent-blue)]" />
+ <span className="text-xs font-medium text-[var(--color-accent-blue)] uppercase tracking-wider">
+ Human Notes
+ </span>
+ </div>
+ <p className="text-sm text-[var(--color-text-secondary)] whitespace-pre-wrap leading-relaxed">
+ {page.human_notes}
+ </p>
</div>
- <p className="text-sm text-[var(--color-text-secondary)] whitespace-pre-wrap leading-relaxed">
- {page.human_notes}
- </p>
+ )}
+
+ {/* Markdown content */}
+ <article className="prose prose-invert max-w-none leading-relaxed overflow-hidden">
+ <WikiMarkdown content={page.content} />
+ </article>
+
+ {/* Version history */}
+ <div className="mt-8">
+ <VersionHistory
+ pageId={page.id}
+ currentVersion={page.version}
+ currentContent={page.content}
+ />
</div>
- )}
- {/* Markdown content */}
- <article className="prose-chat">
- <ChatMarkdown content={page.content} />
- </article>
+ {/* Metadata warnings */}
+ {Array.isArray(page.metadata?.hallucination_warnings) && (page.metadata.hallucination_warnings as string[]).length > 0 && (
+ <div className="mt-4 rounded-lg border border-amber-400/30 bg-amber-50/5 px-4 py-3">
+ <p className="text-xs font-medium text-amber-400 mb-1.5">
+ Possible inaccuracies detected
+ </p>
+ <ul className="space-y-0.5">
+ {(page.metadata.hallucination_warnings as string[]).map((w, i) => (
+ <li key={i} className="text-xs text-amber-300/80 font-mono">
+ {String(w)}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
</div>
</div>
+
+ {/* Right sidebar — Graph Intelligence */}
+ {hasTargetPath && sidebarOpen && (
+ <div className="hidden lg:flex flex-col border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shrink-0 w-[240px] overflow-auto">
+ <DocsSidebar repoId={repoId} targetPath={page.target_path} />
+ </div>
+ )}
</div>
);
}
diff --git a/packages/web/src/components/git/contributor-network.tsx b/packages/web/src/components/git/contributor-network.tsx
new file mode 100644
index 000000000..5ec47cc5d
--- /dev/null
+++ b/packages/web/src/components/git/contributor-network.tsx
@@ -0,0 +1,168 @@
+"use client";
+
+import { useRef, useEffect, useMemo } from "react";
+import * as d3 from "d3-force";
+import type { HotspotResponse } from "@/lib/api/types";
+
+interface ContributorNetworkProps {
+ hotspots: HotspotResponse[];
+}
+
+interface ContributorNode extends d3.SimulationNodeDatum {
+ id: string;
+ fileCount: number;
+ radius: number;
+}
+
+interface ContributorLink extends d3.SimulationLinkDatum<ContributorNode> {
+ sharedFiles: number;
+}
+
+const PALETTE = [
+ "#6366f1", "#ec4899", "#10b981", "#f59e0b", "#3b82f6", "#a855f7",
+ "#14b8a6", "#f97316", "#84cc16", "#06b6d4", "#e11d48", "#8b5cf6",
+];
+
+export function ContributorNetwork({ hotspots }: ContributorNetworkProps) {
+ const svgRef = useRef<SVGSVGElement>(null);
+
+ const { nodes, links } = useMemo(() => {
+ // Build contributor -> files map
+ const ownerFiles = new Map<string, Set<string>>();
+ for (const h of hotspots) {
+ const owner = h.primary_owner;
+ if (!owner) continue;
+ if (!ownerFiles.has(owner)) ownerFiles.set(owner, new Set());
+ ownerFiles.get(owner)!.add(h.file_path);
+ }
+
+ // Build nodes
+ const nodeArr: ContributorNode[] = Array.from(ownerFiles.entries())
+ .map(([id, files]) => ({
+ id,
+ fileCount: files.size,
+ radius: Math.max(6, Math.min(24, Math.sqrt(files.size) * 4)),
+ }))
+ .sort((a, b) => b.fileCount - a.fileCount)
+ .slice(0, 20);
+
+ const nodeIds = new Set(nodeArr.map((n) => n.id));
+
+ // Build links (shared file co-ownership)
+ const linkArr: ContributorLink[] = [];
+ const nodeList = Array.from(nodeIds);
+ for (let i = 0; i < nodeList.length; i++) {
+ for (let j = i + 1; j < nodeList.length; j++) {
+ const a = ownerFiles.get(nodeList[i])!;
+ const b = ownerFiles.get(nodeList[j])!;
+ let shared = 0;
+ for (const f of a) if (b.has(f)) shared++;
+ if (shared > 0) {
+ linkArr.push({ source: nodeList[i], target: nodeList[j], sharedFiles: shared });
+ }
+ }
+ }
+
+ return { nodes: nodeArr, links: linkArr };
+ }, [hotspots]);
+
+ useEffect(() => {
+ const svg = svgRef.current;
+ if (!svg || nodes.length === 0) return;
+
+ const width = svg.clientWidth || 400;
+ const height = svg.clientHeight || 300;
+
+ // Clear
+ while (svg.firstChild) svg.removeChild(svg.firstChild);
+
+ const ns = "http://www.w3.org/2000/svg";
+
+ // Create a group for zoom
+ const g = document.createElementNS(ns, "g");
+ svg.appendChild(g);
+
+ // Reset node positions
+ for (const n of nodes) {
+ n.x = width / 2 + (Math.random() - 0.5) * 100;
+ n.y = height / 2 + (Math.random() - 0.5) * 100;
+ }
+
+ const simulation = d3
+ .forceSimulation(nodes)
+ .force("link", d3.forceLink<ContributorNode, ContributorLink>(links).id((d) => d.id).distance(80).strength(0.3))
+ .force("charge", d3.forceManyBody().strength(-120))
+ .force("center", d3.forceCenter(width / 2, height / 2))
+ .force("collide", d3.forceCollide<ContributorNode>().radius((d) => d.radius + 4));
+
+ // Draw links
+ const linkElements: SVGLineElement[] = links.map((l) => {
+ const line = document.createElementNS(ns, "line");
+ line.setAttribute("stroke", "rgba(255,255,255,0.1)");
+ line.setAttribute("stroke-width", String(Math.max(1, Math.min(4, l.sharedFiles))));
+ g.appendChild(line);
+ return line;
+ });
+
+ // Draw nodes
+ const nodeGroups: SVGGElement[] = nodes.map((n, i) => {
+ const group = document.createElementNS(ns, "g");
+ group.style.cursor = "pointer";
+
+ const circle = document.createElementNS(ns, "circle");
+ circle.setAttribute("r", String(n.radius));
+ circle.setAttribute("fill", PALETTE[i % PALETTE.length]);
+ circle.setAttribute("fill-opacity", "0.8");
+ circle.setAttribute("stroke", PALETTE[i % PALETTE.length]);
+ circle.setAttribute("stroke-opacity", "0.3");
+ circle.setAttribute("stroke-width", "3");
+ group.appendChild(circle);
+
+ const text = document.createElementNS(ns, "text");
+ text.setAttribute("text-anchor", "middle");
+ text.setAttribute("dy", String(n.radius + 12));
+ text.setAttribute("fill", "var(--color-text-secondary)");
+ text.setAttribute("font-size", "9");
+ text.textContent = n.id.length > 15 ? n.id.slice(0, 15) + "…" : n.id;
+ group.appendChild(text);
+
+ const title = document.createElementNS(ns, "title");
+ title.textContent = `${n.id}\n${n.fileCount} files owned`;
+ group.appendChild(title);
+
+ g.appendChild(group);
+ return group;
+ });
+
+ simulation.on("tick", () => {
+ linkElements.forEach((line, i) => {
+ const l = links[i];
+ const s = l.source as ContributorNode;
+ const t = l.target as ContributorNode;
+ line.setAttribute("x1", String(s.x ?? 0));
+ line.setAttribute("y1", String(s.y ?? 0));
+ line.setAttribute("x2", String(t.x ?? 0));
+ line.setAttribute("y2", String(t.y ?? 0));
+ });
+
+ nodeGroups.forEach((group, i) => {
+ const n = nodes[i];
+ group.setAttribute("transform", `translate(${n.x ?? 0}, ${n.y ?? 0})`);
+ });
+ });
+
+ return () => {
+ simulation.stop();
+ };
+ }, [nodes, links]);
+
+ if (nodes.length === 0) return null;
+
+ return (
+ <svg
+ ref={svgRef}
+ className="w-full h-64 md:h-80"
+ style={{ background: "transparent" }}
+ />
+ );
+}
diff --git a/packages/web/src/components/git/hotspot-table.tsx b/packages/web/src/components/git/hotspot-table.tsx
index e22751caf..acebbdad6 100644
--- a/packages/web/src/components/git/hotspot-table.tsx
+++ b/packages/web/src/components/git/hotspot-table.tsx
@@ -106,7 +106,7 @@ export function HotspotTable({ hotspots }: HotspotTableProps) {
placeholder="Search files or owners…"
value={search}
onChange={(e) => setSearch(e.target.value)}
- className="pl-8 h-8 w-56 text-xs"
+ className="pl-8 h-8 w-full sm:w-56 text-xs"
/>
</div>
<div className="flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">
@@ -149,7 +149,7 @@ export function HotspotTable({ hotspots }: HotspotTableProps) {
Commits 90d<SortIcon column="commits" sortKey={sortKey} sortDir={sortDir} />
</th>
<th
- className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-32 cursor-pointer select-none hover:text-[var(--color-text-secondary)]"
+ className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-32 cursor-pointer select-none hover:text-[var(--color-text-secondary)] hidden lg:table-cell"
onClick={() => handleSort("churn")}
>
Churn<SortIcon column="churn" sortKey={sortKey} sortDir={sortDir} />
@@ -161,13 +161,13 @@ export function HotspotTable({ hotspots }: HotspotTableProps) {
>
Trend<SortIcon column="trend" sortKey={sortKey} sortDir={sortDir} />
</th>
- <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-20">
+ <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-20 hidden md:table-cell">
Bus Factor
</th>
- <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24">
+ <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24 hidden lg:table-cell">
Lines ±90d
</th>
- <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider hidden md:table-cell">
Owner
</th>
<th className="px-3 py-2.5 w-20" />
@@ -200,7 +200,7 @@ export function HotspotTable({ hotspots }: HotspotTableProps) {
)}
</span>
</td>
- <td className="px-3 py-2.5">
+ <td className="px-3 py-2.5 hidden lg:table-cell">
<div className="flex items-center gap-2">
<ChurnBar percentile={h.churn_percentile} className="w-16" />
<span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8">
@@ -222,7 +222,7 @@ export function HotspotTable({ hotspots }: HotspotTableProps) {
)}
</span>
</td>
- <td className="px-3 py-2.5">
+ <td className="px-3 py-2.5 hidden md:table-cell">
<span
className={`inline-flex items-center justify-center rounded px-1.5 py-0.5 text-xs font-medium tabular-nums ${
h.bus_factor <= 1
@@ -235,12 +235,12 @@ export function HotspotTable({ hotspots }: HotspotTableProps) {
{h.bus_factor}
</span>
</td>
- <td className="px-3 py-2.5 text-xs tabular-nums">
+ <td className="px-3 py-2.5 text-xs tabular-nums hidden lg:table-cell">
<span className="text-green-400">+{formatLOC(h.lines_added_90d)}</span>
{" "}
<span className="text-red-400">-{formatLOC(h.lines_deleted_90d)}</span>
</td>
- <td className="px-3 py-2.5 text-xs text-[var(--color-text-secondary)]">
+ <td className="px-3 py-2.5 text-xs text-[var(--color-text-secondary)] hidden md:table-cell">
{h.primary_owner ?? "—"}
</td>
<td className="px-3 py-2.5 flex items-center gap-1">
diff --git a/packages/web/src/components/git/risk-distribution-chart.tsx b/packages/web/src/components/git/risk-distribution-chart.tsx
new file mode 100644
index 000000000..94f4f1317
--- /dev/null
+++ b/packages/web/src/components/git/risk-distribution-chart.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import { useMemo } from "react";
+import {
+ BarChart,
+ Bar,
+ XAxis,
+ YAxis,
+ Tooltip,
+ ResponsiveContainer,
+ Cell,
+ ReferenceLine,
+} from "recharts";
+import type { HotspotResponse } from "@/lib/api/types";
+
+interface RiskDistributionChartProps {
+ hotspots: HotspotResponse[];
+}
+
+function computeRiskScore(h: HotspotResponse): number {
+ const churn = h.churn_percentile / 100;
+ const busFactor = h.bus_factor <= 1 ? 1 : h.bus_factor === 2 ? 0.5 : 0;
+ const trend = Math.min(1, (h.temporal_hotspot_score ?? 0) / 10);
+ return Math.round((churn * 0.4 + busFactor * 0.35 + trend * 0.25) * 100);
+}
+
+function riskColor(score: number): string {
+ if (score >= 70) return "#ef4444";
+ if (score >= 45) return "#f59520";
+ if (score >= 25) return "#eab308";
+ return "#22c55e";
+}
+
+export function RiskDistributionChart({ hotspots }: RiskDistributionChartProps) {
+ const data = useMemo(() => {
+ return hotspots
+ .map((h) => ({
+ name: h.file_path.split("/").pop() ?? h.file_path,
+ fullPath: h.file_path,
+ risk: computeRiskScore(h),
+ churn: Math.round(h.churn_percentile),
+ busFactor: h.bus_factor,
+ }))
+ .sort((a, b) => b.risk - a.risk)
+ .slice(0, 30);
+ }, [hotspots]);
+
+ if (data.length === 0) return null;
+
+ const avgRisk = Math.round(data.reduce((s, d) => s + d.risk, 0) / data.length);
+
+ return (
+ <div className="w-full">
+ <ResponsiveContainer width="100%" height={Math.max(200, data.length * 22 + 40)}>
+ <BarChart
+ data={data}
+ layout="vertical"
+ margin={{ top: 5, right: 20, bottom: 5, left: 0 }}
+ barSize={14}
+ >
+ <XAxis
+ type="number"
+ domain={[0, 100]}
+ tick={{ fontSize: 10, fill: "var(--color-text-tertiary)" }}
+ axisLine={false}
+ tickLine={false}
+ />
+ <YAxis
+ type="category"
+ dataKey="name"
+ width={120}
+ tick={{ fontSize: 10, fill: "var(--color-text-secondary)" }}
+ axisLine={false}
+ tickLine={false}
+ />
+ <Tooltip
+ contentStyle={{
+ background: "var(--color-bg-elevated)",
+ border: "1px solid var(--color-border-default)",
+ borderRadius: 8,
+ fontSize: 11,
+ color: "var(--color-text-primary)",
+ }}
+ formatter={(value: number) => [`${value}`, "Risk Score"]}
+ labelFormatter={(label: string) => label}
+ />
+ <ReferenceLine
+ x={avgRisk}
+ stroke="var(--color-text-tertiary)"
+ strokeDasharray="4 4"
+ label={{ value: `avg ${avgRisk}`, position: "top", fontSize: 9, fill: "var(--color-text-tertiary)" }}
+ />
+ <Bar dataKey="risk" radius={[0, 4, 4, 0]}>
+ {data.map((entry, idx) => (
+ <Cell key={idx} fill={riskColor(entry.risk)} fillOpacity={0.85} />
+ ))}
+ </Bar>
+ </BarChart>
+ </ResponsiveContainer>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/graph/edges/dependency-edge.tsx b/packages/web/src/components/graph/edges/dependency-edge.tsx
index 27c7a2ed1..653309152 100644
--- a/packages/web/src/components/graph/edges/dependency-edge.tsx
+++ b/packages/web/src/components/graph/edges/dependency-edge.tsx
@@ -42,7 +42,7 @@ function DependencyEdgeInner({
targetPosition,
});
- const strokeWidth = Math.max(1.5, Math.min(4, 1.5 + Math.sqrt(d.edgeCount) * 0.6));
+ const strokeWidth = Math.max(1, Math.min(6, 1 + Math.sqrt(d.edgeCount) * 0.8));
let stroke: string;
let opacity: number;
@@ -72,17 +72,32 @@ function DependencyEdgeInner({
opacity = 1;
}
+ const tooltip = d.importedNames.length > 0
+ ? d.importedNames.slice(0, 10).join(", ") + (d.importedNames.length > 10 ? ` (+${d.importedNames.length - 10} more)` : "")
+ : `${d.edgeCount} connection${d.edgeCount > 1 ? "s" : ""}`;
+
return (
- <path
- d={edgePath}
- fill="none"
- stroke={stroke}
- strokeWidth={isHoverHighlighted && !isOnPath ? strokeWidth + 0.5 : strokeWidth}
- strokeOpacity={opacity}
- strokeDasharray={dashArray}
- style={{ animation }}
- className="transition-all duration-200"
- />
+ <g>
+ {/* Invisible wider path for easier hover */}
+ <path
+ d={edgePath}
+ fill="none"
+ stroke="transparent"
+ strokeWidth={Math.max(12, strokeWidth + 8)}
+ >
+ <title>{tooltip}</title>
+ </path>
+ <path
+ d={edgePath}
+ fill="none"
+ stroke={stroke}
+ strokeWidth={isHoverHighlighted && !isOnPath ? strokeWidth + 0.5 : strokeWidth}
+ strokeOpacity={opacity}
+ strokeDasharray={dashArray}
+ style={{ animation, pointerEvents: "none" }}
+ className="transition-all duration-200"
+ />
+ </g>
);
}
diff --git a/packages/web/src/components/graph/elk-layout.ts b/packages/web/src/components/graph/elk-layout.ts
index 42a432886..0077ee0ea 100644
--- a/packages/web/src/components/graph/elk-layout.ts
+++ b/packages/web/src/components/graph/elk-layout.ts
@@ -277,12 +277,13 @@ export async function layoutFileGraph(
}
}
- // Add file nodes
+ // Add file nodes (sized by pagerank importance)
for (const n of nodes) {
+ const scale = 1 + Math.min(0.6, n.pagerank * 25);
const elkFileNode: ElkNode = {
id: n.node_id,
- width: FILE_NODE_WIDTH,
- height: FILE_NODE_HEIGHT,
+ width: Math.round(FILE_NODE_WIDTH * scale),
+ height: Math.round(FILE_NODE_HEIGHT * scale),
labels: [{ text: n.node_id.split("/").pop() ?? n.node_id }],
};
const dir = dirOf(n.node_id);
diff --git a/packages/web/src/components/graph/graph-community-panel.tsx b/packages/web/src/components/graph/graph-community-panel.tsx
new file mode 100644
index 000000000..260e74b7b
--- /dev/null
+++ b/packages/web/src/components/graph/graph-community-panel.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+import { X, ArrowRight } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { Skeleton } from "@/components/ui/skeleton";
+import { useCommunityDetail } from "@/lib/hooks/use-graph";
+import { truncatePath } from "@/lib/utils/format";
+
+interface GraphCommunityPanelProps {
+ repoId: string;
+ communityId: number;
+ onClose: () => void;
+}
+
+export function GraphCommunityPanel({
+ repoId,
+ communityId,
+ onClose,
+}: GraphCommunityPanelProps) {
+ const { community, isLoading } = useCommunityDetail(repoId, communityId);
+
+ return (
+ <div className="absolute right-0 top-0 bottom-0 w-full sm:w-[360px] border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] z-10 flex flex-col shadow-lg shadow-black/20">
+ {/* Header */}
+ <div className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border-default)]">
+ <div className="min-w-0">
+ <p className="text-sm font-medium text-[var(--color-text-primary)] truncate">
+ {community?.label ?? `Community ${communityId}`}
+ </p>
+ {community && (
+ <p className="text-[10px] text-[var(--color-text-tertiary)]">
+ {community.member_count} files &middot; cohesion {(community.cohesion * 100).toFixed(0)}%
+ </p>
+ )}
+ </div>
+ <button
+ onClick={onClose}
+ className="p-1 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ <X className="h-4 w-4 text-[var(--color-text-tertiary)]" />
+ </button>
+ </div>
+
+ {/* Content */}
+ {isLoading ? (
+ <div className="p-4 space-y-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-3/4" />
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-2/3" />
+ </div>
+ ) : community ? (
+ <ScrollArea className="flex-1">
+ <div className="p-4 space-y-4">
+ {/* Members */}
+ <div>
+ <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">
+ Members ({community.member_count})
+ </p>
+ <div className="space-y-1">
+ {community.members.map((m) => {
+ const maxPr = community.members[0]?.pagerank || 1;
+ const barWidth = maxPr > 0 ? Math.round((m.pagerank / maxPr) * 100) : 0;
+
+ return (
+ <div
+ key={m.path}
+ className="flex items-center gap-2 py-1 px-1.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ <div className="min-w-0 flex-1">
+ <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate" title={m.path}>
+ {truncatePath(m.path)}
+ </p>
+ </div>
+ {/* PageRank bar */}
+ <div className="w-16 h-1.5 rounded-full bg-[var(--color-bg-elevated)] overflow-hidden shrink-0">
+ <div
+ className="h-full rounded-full bg-[var(--color-accent)]"
+ style={{ width: `${barWidth}%` }}
+ />
+ </div>
+ {m.is_entry_point && (
+ <Badge variant="accent" className="text-[8px] h-3.5 shrink-0">
+ EP
+ </Badge>
+ )}
+ </div>
+ );
+ })}
+ {community.truncated && (
+ <p className="text-[10px] text-[var(--color-text-tertiary)] px-1.5 pt-1">
+ +{community.member_count - community.members.length} more files
+ </p>
+ )}
+ </div>
+ </div>
+
+ {/* Neighboring Communities */}
+ {community.neighboring_communities.length > 0 && (
+ <div>
+ <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">
+ Neighboring Communities
+ </p>
+ <div className="space-y-1">
+ {community.neighboring_communities.map((n) => (
+ <div
+ key={n.community_id}
+ className="flex items-center justify-between gap-2 py-1 px-1.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ <div className="flex items-center gap-1.5 min-w-0">
+ <ArrowRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
+ <span className="text-[11px] text-[var(--color-text-primary)] truncate">
+ {n.label}
+ </span>
+ </div>
+ <Badge variant="outline" className="text-[9px] shrink-0 h-4">
+ {n.cross_edge_count} edges
+ </Badge>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </ScrollArea>
+ ) : (
+ <div className="p-4">
+ <p className="text-xs text-[var(--color-text-tertiary)]">Community not found</p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/components/graph/graph-flow.tsx b/packages/web/src/components/graph/graph-flow.tsx
index f901e1177..4d515eb57 100644
--- a/packages/web/src/components/graph/graph-flow.tsx
+++ b/packages/web/src/components/graph/graph-flow.tsx
@@ -20,8 +20,10 @@ import {
type Node,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
-import { Loader2, ChevronRight, Home } from "lucide-react";
+import { Loader2, ChevronRight, Home, Search } from "lucide-react";
+import Fuse from "fuse.js";
import { Skeleton } from "@/components/ui/skeleton";
+import { Input } from "@/components/ui/input";
import { EmptyState } from "@/components/shared/empty-state";
import {
useModuleGraph,
@@ -29,6 +31,8 @@ import {
useArchitectureGraph,
useDeadCodeGraph,
useHotFilesGraph,
+ useCommunities,
+ useExecutionFlows,
} from "@/lib/hooks/use-graph";
import { ModuleGroupNode } from "./nodes/module-group-node";
import { FileNode } from "./nodes/file-node";
@@ -38,6 +42,7 @@ import { useModuleElkLayout, useFileElkLayout } from "./use-elk-layout";
import { PathFinderPanel } from "./path-finder-panel";
import { GraphToolbar, type ColorMode, type ViewMode } from "./graph-toolbar";
import { GraphLegend } from "./graph-legend";
+import { GraphCommunityPanel } from "./graph-community-panel";
import { GraphContextMenu } from "./graph-context-menu";
import { GraphTooltip } from "./graph-tooltip";
import { languageColor } from "@/lib/utils/confidence";
@@ -53,6 +58,7 @@ export interface GraphContextValue {
connectedNodeIds: Set<string>;
connectedEdgeIds: Set<string>;
selectedNodeId: string | null;
+ searchDimmedNodes: Set<string> | null;
}
export const GraphContext = createContext<GraphContextValue>({
@@ -64,6 +70,7 @@ export const GraphContext = createContext<GraphContextValue>({
connectedNodeIds: new Set(),
connectedEdgeIds: new Set(),
selectedNodeId: null,
+ searchDimmedNodes: null,
});
// ---- Node/Edge types ----
@@ -92,9 +99,16 @@ function GraphFlowInner({
}: GraphFlowInnerProps) {
const reactFlow = useReactFlow();
- // State
+ // State — read initial colorMode from URL if present
const [viewMode, setViewMode] = useState<ViewMode>("module");
- const [colorMode, setColorMode] = useState<ColorMode>("language");
+ const [colorMode, setColorMode] = useState<ColorMode>(() => {
+ if (typeof window !== "undefined") {
+ const params = new URLSearchParams(window.location.search);
+ const cm = params.get("colorMode");
+ if (cm === "community" || cm === "language" || cm === "risk") return cm;
+ }
+ return "language";
+ });
const [hideTests, setHideTests] = useState(false);
const [highlightedPath, setHighlightedPath] = useState<Set<string>>(new Set());
const [highlightedEdges, setHighlightedEdges] = useState<Set<string>>(new Set());
@@ -119,6 +133,14 @@ function GraphFlowInner({
const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
const [selectedNodeScreen, setSelectedNodeScreen] = useState<{ x: number; y: number } | null>(null);
+ // Graph search
+ const [searchQuery, setSearchQuery] = useState("");
+ const [searchDimmedNodes, setSearchDimmedNodes] = useState<Set<string> | null>(null);
+
+ // Execution flow highlighting
+ const [activeFlowIdx, setActiveFlowIdx] = useState<number | null>(null);
+ const [showFlows, setShowFlows] = useState(false);
+
// ---- Data fetching ----
const isModuleView = viewMode === "module";
@@ -143,6 +165,19 @@ function GraphFlowInner({
viewMode === "hotfiles" ? repoId : null,
);
+ // Community data for legend labels and detail panel
+ const { communities } = useCommunities(repoId);
+ const communityLabels = useMemo(() => {
+ if (!communities) return undefined;
+ const m = new Map<number, string>();
+ for (const c of communities) m.set(c.community_id, c.label);
+ return m;
+ }, [communities]);
+ const [communityPanelId, setCommunityPanelId] = useState<number | null>(null);
+
+ // Execution flows data
+ const { flows: executionFlowsData } = useExecutionFlows(repoId, { top_n: 10, max_depth: 6 });
+
// ---- Derived data ----
// When drilled down, re-group nodes as sub-modules at the current prefix
@@ -236,6 +271,74 @@ function GraphFlowInner({
return { connectedNodeIds: nodeIds, connectedEdgeIds: edgeIds };
}, [hoveredNodeId, currentEdges]);
+ // Fuse search index over visible nodes
+ const fuseIndex = useMemo(() => {
+ const items = filteredNodes.map((n) => ({ id: n.id, label: (n.data as { label?: string }).label ?? n.id }));
+ return new Fuse(items, { keys: ["id", "label"], threshold: 0.4 });
+ }, [filteredNodes]);
+
+ // Search: compute dimmed set when query is active
+ useEffect(() => {
+ if (!searchQuery || searchQuery.length < 2) {
+ setSearchDimmedNodes(null);
+ return;
+ }
+ const results = fuseIndex.search(searchQuery);
+ const matchIds = new Set(results.map((r) => r.item.id));
+ const dimmed = new Set<string>();
+ for (const n of filteredNodes) {
+ if (!matchIds.has(n.id)) dimmed.add(n.id);
+ }
+ setSearchDimmedNodes(dimmed);
+
+ // Zoom to matched nodes
+ if (results.length > 0 && results.length <= 20) {
+ const matchedRfNodes = results
+ .map((r) => reactFlow.getNode(r.item.id))
+ .filter(Boolean) as Node[];
+ if (matchedRfNodes.length > 0) {
+ reactFlow.fitView({ nodes: matchedRfNodes, padding: 0.4, duration: 500 });
+ }
+ }
+ }, [searchQuery, fuseIndex, filteredNodes, reactFlow]);
+
+ // Execution flow highlighting
+ useEffect(() => {
+ if (activeFlowIdx === null || !executionFlowsData) {
+ // Don't clear if a manual path is highlighted
+ if (activeFlowIdx === null && showFlows) {
+ setHighlightedPath(new Set());
+ setHighlightedEdges(new Set());
+ }
+ return;
+ }
+ const flow = executionFlowsData.flows[activeFlowIdx];
+ if (!flow) return;
+ const pathSet = new Set(flow.trace);
+ const edgeKeys = new Set<string>();
+ for (let i = 0; i < flow.trace.length - 1; i++) {
+ edgeKeys.add(`${flow.trace[i]}→${flow.trace[i + 1]}`);
+ edgeKeys.add(`${flow.trace[i + 1]}→${flow.trace[i]}`);
+ }
+ setHighlightedPath(pathSet);
+ setHighlightedEdges(edgeKeys);
+
+ // Switch to full view if in module view to show the trace
+ if (viewMode === "module") {
+ setViewMode("full");
+ setModulePath([]);
+ }
+
+ setTimeout(() => {
+ const traceNodes = flow.trace
+ .map((id) => reactFlow.getNode(id))
+ .filter(Boolean) as Node[];
+ if (traceNodes.length > 0) {
+ reactFlow.fitView({ nodes: traceNodes, padding: 0.3, duration: 600 });
+ }
+ }, 800);
+ }, [activeFlowIdx, executionFlowsData]);
+
// Context value
const ctxValue = useMemo<GraphContextValue>(
() => ({
@@ -247,8 +350,9 @@ function GraphFlowInner({
connectedNodeIds,
connectedEdgeIds,
selectedNodeId,
+ searchDimmedNodes,
}),
- [highlightedPath, highlightedEdges, colorMode, hoveredNodeId, connectedNodeIds, connectedEdgeIds, selectedNodeId],
+ [highlightedPath, highlightedEdges, colorMode, hoveredNodeId, connectedNodeIds, connectedEdgeIds, selectedNodeId, searchDimmedNodes],
);
// ---- Handlers ----
@@ -261,6 +365,14 @@ function GraphFlowInner({
setSelectedNodeId(null);
return;
}
+ // In community mode, open community detail panel
+ if (colorMode === "community" && node.type === "fileNode") {
+ const nodeData = node.data as FileNodeData;
+ if (nodeData?.communityId !== undefined) {
+ setCommunityPanelId(nodeData.communityId);
+ }
+ }
+
// Toggle selection — show tooltip on click
const mEvent = event as unknown as React.MouseEvent;
if (selectedNodeId === node.id) {
@@ -271,7 +383,7 @@ function GraphFlowInner({
setSelectedNodeScreen({ x: mEvent.clientX, y: mEvent.clientY });
}
},
- [isModuleView, selectedNodeId],
+ [isModuleView, selectedNodeId, colorMode],
);
const handleNodeMouseEnter: NodeMouseHandler = useCallback(
@@ -549,6 +661,10 @@ function GraphFlowInner({
onFitView={handleFitView}
showPathFinder={showPathFinder}
onTogglePathFinder={() => setShowPathFinder((s) => !s)}
+ showFlows={showFlows}
+ onToggleFlows={() => { setShowFlows((s) => !s); setActiveFlowIdx(null); }}
+ searchQuery={searchQuery}
+ onSearchChange={setSearchQuery}
/>
</div>
@@ -566,6 +682,44 @@ function GraphFlowInner({
</div>
)}
+ {/* Execution Flows Panel */}
+ {showFlows && executionFlowsData && executionFlowsData.flows.length > 0 && (
+ <div className="absolute top-14 right-3 z-10 w-64">
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/95 backdrop-blur-sm shadow-lg shadow-black/20 p-3">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-[11px] font-medium text-[var(--color-text-primary)]">
+ Execution Flows
+ </span>
+ <span className="text-[10px] text-[var(--color-text-tertiary)]">
+ {executionFlowsData.flows.length} entry points
+ </span>
+ </div>
+ <div className="space-y-1 max-h-60 overflow-y-auto">
+ {executionFlowsData.flows.map((flow, idx) => (
+ <button
+ key={flow.entry_point}
+ onClick={() => setActiveFlowIdx(activeFlowIdx === idx ? null : idx)}
+ className={`w-full text-left px-2 py-1.5 rounded-md text-[11px] transition-colors ${
+ activeFlowIdx === idx
+ ? "bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)] hover:text-[var(--color-text-primary)]"
+ }`}
+ >
+ <div className="font-mono truncate">{flow.entry_point_name}</div>
+ <div className="flex items-center gap-2 mt-0.5 text-[10px] text-[var(--color-text-tertiary)]">
+ <span>depth {flow.depth}</span>
+ <span>{flow.trace.length} nodes</span>
+ {flow.crosses_community && (
+ <span className="text-yellow-500">cross-community</span>
+ )}
+ </div>
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+
{/* Legend */}
<div className="absolute bottom-3 left-3 z-10">
<GraphLegend
@@ -573,6 +727,7 @@ function GraphFlowInner({
edgeCount={currentEdges.length}
colorMode={colorMode}
viewMode={viewMode}
+ communityLabels={communityLabels}
/>
</div>
@@ -590,6 +745,15 @@ function GraphFlowInner({
/>
)}
+ {/* Community detail panel */}
+ {communityPanelId !== null && (
+ <GraphCommunityPanel
+ repoId={repoId}
+ communityId={communityPanelId}
+ onClose={() => setCommunityPanelId(null)}
+ />
+ )}
+
{/* Node detail tooltip */}
{selectedNodeId && selectedNodeScreen && (() => {
const rfNode = filteredNodes.find((n) => n.id === selectedNodeId);
diff --git a/packages/web/src/components/graph/graph-legend.tsx b/packages/web/src/components/graph/graph-legend.tsx
index 892836abe..30d1f843c 100644
--- a/packages/web/src/components/graph/graph-legend.tsx
+++ b/packages/web/src/components/graph/graph-legend.tsx
@@ -29,6 +29,7 @@ interface GraphLegendProps {
edgeCount: number;
colorMode: ColorMode;
viewMode: ViewMode;
+ communityLabels?: Map<number, string>;
}
export function GraphLegend({
@@ -36,6 +37,7 @@ export function GraphLegend({
edgeCount,
colorMode,
viewMode,
+ communityLabels,
}: GraphLegendProps) {
const [expanded, setExpanded] = useState(false);
@@ -75,15 +77,27 @@ export function GraphLegend({
))}
{colorMode === "community" &&
- COMMUNITY_SAMPLE.map((c, i) => (
- <div key={i} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
- <span
- className="w-2 h-2 rounded-full shrink-0"
- style={{ background: c.color }}
- />
- <span>{c.label}</span>
- </div>
- ))}
+ (communityLabels && communityLabels.size > 0
+ ? Array.from(communityLabels.entries())
+ .slice(0, 8)
+ .map(([cid, label], i) => (
+ <div key={cid} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span
+ className="w-2 h-2 rounded-full shrink-0"
+ style={{ background: COMMUNITY_SAMPLE[i % COMMUNITY_SAMPLE.length]?.color ?? "#888" }}
+ />
+ <span className="truncate">{label}</span>
+ </div>
+ ))
+ : COMMUNITY_SAMPLE.map((c, i) => (
+ <div key={i} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span
+ className="w-2 h-2 rounded-full shrink-0"
+ style={{ background: c.color }}
+ />
+ <span>{c.label}</span>
+ </div>
+ )))}
{colorMode === "risk" && (
<>
diff --git a/packages/web/src/components/graph/graph-toolbar.tsx b/packages/web/src/components/graph/graph-toolbar.tsx
index e9a4acc16..e8a32dd6a 100644
--- a/packages/web/src/components/graph/graph-toolbar.tsx
+++ b/packages/web/src/components/graph/graph-toolbar.tsx
@@ -12,8 +12,12 @@ import {
Skull,
Flame,
LayoutGrid,
+ Workflow,
+ Search,
+ X,
} from "lucide-react";
import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
export type ColorMode = "language" | "community" | "risk";
export type ViewMode = "module" | "full" | "architecture" | "dead" | "hotfiles";
@@ -28,6 +32,10 @@ interface GraphToolbarProps {
onFitView: () => void;
showPathFinder: boolean;
onTogglePathFinder: () => void;
+ showFlows: boolean;
+ onToggleFlows: () => void;
+ searchQuery: string;
+ onSearchChange: (q: string) => void;
}
const VIEW_MODES: { id: ViewMode; icon: typeof Boxes; label: string }[] = [
@@ -54,6 +62,10 @@ export function GraphToolbar({
onFitView,
showPathFinder,
onTogglePathFinder,
+ showFlows,
+ onToggleFlows,
+ searchQuery,
+ onSearchChange,
}: GraphToolbarProps) {
return (
<div className="flex flex-col gap-1.5 items-end">
@@ -115,6 +127,15 @@ export function GraphToolbar({
>
<Route className="w-3.5 h-3.5" />
</Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={onToggleFlows}
+ className={`h-7 w-7 p-0 ${showFlows ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}
+ title="Execution flows"
+ >
+ <Workflow className="w-3.5 h-3.5" />
+ </Button>
<Button
size="sm"
variant="ghost"
@@ -135,6 +156,25 @@ export function GraphToolbar({
</Button>
</div>
</div>
+
+ {/* Search */}
+ <div className="relative">
+ <div className="flex items-center gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2 py-1 shadow-lg shadow-black/20">
+ <Search className="w-3 h-3 text-[var(--color-text-tertiary)] shrink-0" />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => onSearchChange(e.target.value)}
+ placeholder="Search nodes…"
+ className="bg-transparent text-[11px] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] outline-none w-28 lg:w-40"
+ />
+ {searchQuery && (
+ <button onClick={() => onSearchChange("")} className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]">
+ <X className="w-3 h-3" />
+ </button>
+ )}
+ </div>
+ </div>
</div>
);
}
diff --git a/packages/web/src/components/graph/nodes/file-node.tsx b/packages/web/src/components/graph/nodes/file-node.tsx
index c79105b6c..59a29130f 100644
--- a/packages/web/src/components/graph/nodes/file-node.tsx
+++ b/packages/web/src/components/graph/nodes/file-node.tsx
@@ -27,6 +27,7 @@ function FileNodeInner({ id, data }: NodeProps) {
const isOnPath = ctx.highlightedPath.has(id);
const hasActivePath = ctx.highlightedPath.size > 0;
const isDimmed = hasActivePath && !isOnPath;
+ const isSearchDimmed = ctx.searchDimmedNodes?.has(id) ?? false;
const isSelected = ctx.selectedNodeId === id;
const isHovered = ctx.hoveredNodeId === id;
const hasHover = ctx.hoveredNodeId !== null;
@@ -51,8 +52,10 @@ function FileNodeInner({ id, data }: NodeProps) {
}
// Compute opacity
+ const searchDimmed = isSearchDimmed && !isOnPath && !isSelected;
let opacity = 1;
if (isDimmed) opacity = 0.15;
+ else if (searchDimmed) opacity = 0.12;
else if (isHoverDimmed) opacity = 0.35;
return (
diff --git a/packages/web/src/components/graph/nodes/module-group-node.tsx b/packages/web/src/components/graph/nodes/module-group-node.tsx
index c057dd3d5..a4c41663f 100644
--- a/packages/web/src/components/graph/nodes/module-group-node.tsx
+++ b/packages/web/src/components/graph/nodes/module-group-node.tsx
@@ -48,8 +48,12 @@ function ModuleGroupNodeInner({ id, data }: NodeProps) {
const isConnected = ctx.connectedNodeIds.has(id);
const isHoverDimmed = hasHover && !isConnected && !hasActivePath;
+ const isSearchDimmed = ctx.searchDimmedNodes?.has(id) ?? false;
+ const searchDimmed = isSearchDimmed && !isOnPath && !isSelected;
+
let opacity = 1;
if (isDimmed) opacity = 0.15;
+ else if (searchDimmed) opacity = 0.12;
else if (isHoverDimmed) opacity = 0.35;
return (
diff --git a/packages/web/src/components/layout/mobile-nav.tsx b/packages/web/src/components/layout/mobile-nav.tsx
index 88860a235..64f314cfd 100644
--- a/packages/web/src/components/layout/mobile-nav.tsx
+++ b/packages/web/src/components/layout/mobile-nav.tsx
@@ -24,6 +24,9 @@ import {
ChevronRight,
Circle,
SlidersHorizontal,
+ Layers,
+ Link2,
+ GitMerge,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
@@ -31,7 +34,7 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { AddRepoDialog } from "@/components/repos/add-repo-dialog";
import { cn } from "@/lib/utils/cn";
-import type { RepoResponse } from "@/lib/api/types";
+import type { RepoResponse, WorkspaceResponse } from "@/lib/api/types";
const GLOBAL_NAV = [
{ label: "Dashboard", href: "/", icon: LayoutDashboard },
@@ -56,11 +59,19 @@ function repoNavItems(repoId: string) {
];
}
+const WORKSPACE_NAV = [
+ { label: "Overview", href: "/workspace", icon: Layers },
+ { label: "Contracts", href: "/workspace/contracts", icon: Link2 },
+ { label: "Co-Changes", href: "/workspace/co-changes", icon: GitMerge },
+];
+
interface MobileNavProps {
repos?: RepoResponse[];
+ workspace?: WorkspaceResponse | null;
}
-export function MobileNav({ repos = [] }: MobileNavProps) {
+export function MobileNav({ repos = [], workspace }: MobileNavProps) {
+ const isWorkspace = workspace?.is_workspace ?? false;
const [open, setOpen] = React.useState(false);
const pathname = usePathname();
const [expandedRepos, setExpandedRepos] = React.useState<Set<string>>(new Set());
@@ -140,6 +151,39 @@ export function MobileNav({ repos = [] }: MobileNavProps) {
})}
</nav>
+ {isWorkspace && (
+ <>
+ <Separator className="my-4" />
+ <p className="mb-2 px-2 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Workspace
+ </p>
+ <nav className="space-y-1">
+ {WORKSPACE_NAV.map((item) => {
+ const Icon = item.icon;
+ const isActive =
+ item.href === "/workspace"
+ ? pathname === "/workspace"
+ : pathname.startsWith(`${item.href}`);
+ return (
+ <Link
+ key={item.href}
+ href={item.href}
+ className={cn(
+ "flex items-center gap-2.5 rounded-lg px-2 py-2 text-sm transition-colors",
+ isActive
+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",
+ )}
+ >
+ <Icon className="h-[18px] w-[18px] shrink-0" />
+ {item.label}
+ </Link>
+ );
+ })}
+ </nav>
+ </>
+ )}
+
{repos.length > 0 && (
<>
<Separator className="my-4" />
diff --git a/packages/web/src/components/layout/page-transition.tsx b/packages/web/src/components/layout/page-transition.tsx
new file mode 100644
index 000000000..8b03d5ed1
--- /dev/null
+++ b/packages/web/src/components/layout/page-transition.tsx
@@ -0,0 +1,28 @@
+"use client";
+
+import { usePathname } from "next/navigation";
+import { motion, AnimatePresence } from "framer-motion";
+import type { ReactNode } from "react";
+
+interface PageTransitionProps {
+ children: ReactNode;
+}
+
+export function PageTransition({ children }: PageTransitionProps) {
+ const pathname = usePathname();
+
+ return (
+ <AnimatePresence mode="wait" initial={false}>
+ <motion.div
+ key={pathname}
+ initial={{ opacity: 0, y: 6 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: -4 }}
+ transition={{ duration: 0.15, ease: "easeOut" }}
+ className="h-full"
+ >
+ {children}
+ </motion.div>
+ </AnimatePresence>
+ );
+}
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index eec0d7ad7..1cbe78899 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -24,13 +24,16 @@ import {
ChevronRight,
Circle,
PanelLeft,
+ Layers,
+ Link2,
+ GitMerge,
} from "lucide-react";
import { cn } from "@/lib/utils/cn";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { AddRepoDialog } from "@/components/repos/add-repo-dialog";
-import type { RepoResponse } from "@/lib/api/types";
+import type { RepoResponse, WorkspaceResponse } from "@/lib/api/types";
interface NavItem {
label: string;
@@ -43,6 +46,12 @@ const GLOBAL_NAV: NavItem[] = [
{ label: "Settings", href: "/settings", icon: Settings },
];
+const WORKSPACE_NAV: NavItem[] = [
+ { label: "Overview", href: "/workspace", icon: Layers },
+ { label: "Contracts", href: "/workspace/contracts", icon: Link2 },
+ { label: "Co-Changes", href: "/workspace/co-changes", icon: GitMerge },
+];
+
function repoNavItems(repoId: string): NavItem[] {
return [
@@ -66,9 +75,11 @@ function repoNavItems(repoId: string): NavItem[] {
interface SidebarProps {
repos?: RepoResponse[];
activeRepoId?: string;
+ workspace?: WorkspaceResponse | null;
}
-export function Sidebar({ repos = [], activeRepoId }: SidebarProps) {
+export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {
+ const isWorkspace = workspace?.is_workspace ?? false;
const pathname = usePathname();
const [expandedRepos, setExpandedRepos] = React.useState<Set<string>>(
activeRepoId ? new Set([activeRepoId]) : new Set(),
@@ -128,9 +139,37 @@ export function Sidebar({ repos = [], activeRepoId }: SidebarProps) {
iconOnly={isIconOnly}
/>
))}
-
</nav>
+ {/* Workspace nav — only shown in workspace mode */}
+ {isWorkspace && (
+ <>
+ {!isIconOnly && (
+ <>
+ <Separator className="my-4" />
+ <p className="mb-2 px-2 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Workspace
+ </p>
+ </>
+ )}
+ {isIconOnly && <Separator className="my-4" />}
+ <nav className="space-y-1">
+ {WORKSPACE_NAV.map((item) => (
+ <SidebarNavItem
+ key={item.href}
+ item={item}
+ isActive={
+ item.href === "/workspace"
+ ? pathname === "/workspace"
+ : pathname.startsWith(`${item.href}`)
+ }
+ iconOnly={isIconOnly}
+ />
+ ))}
+ </nav>
+ </>
+ )}
+
{repos.length > 0 && (
<>
{!isIconOnly && (
diff --git a/packages/web/src/components/search/command-palette.tsx b/packages/web/src/components/search/command-palette.tsx
index ac1a9c2c8..2d89b7833 100644
--- a/packages/web/src/components/search/command-palette.tsx
+++ b/packages/web/src/components/search/command-palette.tsx
@@ -3,16 +3,18 @@
import { useEffect, useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { Command } from "cmdk";
-import { Search, LayoutDashboard, Settings, BookOpen } from "lucide-react";
+import { Search, LayoutDashboard, Settings, BookOpen, Layers, Link2, GitMerge } from "lucide-react";
import { useSearch } from "@/lib/hooks/use-search";
import { truncatePath } from "@/lib/utils/format";
-import type { RepoResponse } from "@/lib/api/types";
+import type { RepoResponse, WorkspaceResponse } from "@/lib/api/types";
interface CommandPaletteProps {
repos: RepoResponse[];
+ workspace?: WorkspaceResponse | null;
}
-export function CommandPalette({ repos }: CommandPaletteProps) {
+export function CommandPalette({ repos, workspace }: CommandPaletteProps) {
+ const isWorkspace = workspace?.is_workspace ?? false;
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const router = useRouter();
@@ -92,6 +94,36 @@ export function CommandPalette({ repos }: CommandPaletteProps) {
</Command.Item>
</Command.Group>
+ {/* Workspace */}
+ {isWorkspace && (
+ <Command.Group heading="Workspace" className="px-2 pb-1">
+ <Command.Item
+ value="workspace-overview"
+ onSelect={() => navigate("/workspace")}
+ className="flex items-center gap-2.5 rounded-md px-3 py-2 text-sm text-[var(--color-text-secondary)] cursor-pointer hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] data-[selected=true]:bg-[var(--color-bg-elevated)] data-[selected=true]:text-[var(--color-text-primary)]"
+ >
+ <Layers className="h-4 w-4" />
+ Workspace Overview
+ </Command.Item>
+ <Command.Item
+ value="workspace-contracts"
+ onSelect={() => navigate("/workspace/contracts")}
+ className="flex items-center gap-2.5 rounded-md px-3 py-2 text-sm text-[var(--color-text-secondary)] cursor-pointer hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] data-[selected=true]:bg-[var(--color-bg-elevated)] data-[selected=true]:text-[var(--color-text-primary)]"
+ >
+ <Link2 className="h-4 w-4" />
+ Contracts
+ </Command.Item>
+ <Command.Item
+ value="workspace-co-changes"
+ onSelect={() => navigate("/workspace/co-changes")}
+ className="flex items-center gap-2.5 rounded-md px-3 py-2 text-sm text-[var(--color-text-secondary)] cursor-pointer hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] data-[selected=true]:bg-[var(--color-bg-elevated)] data-[selected=true]:text-[var(--color-text-primary)]"
+ >
+ <GitMerge className="h-4 w-4" />
+ Co-Changes
+ </Command.Item>
+ </Command.Group>
+ )}
+
{/* Repos */}
{repos.length > 0 && (
<Command.Group heading="Repositories" className="px-2 pb-1">
diff --git a/packages/web/src/components/symbols/symbol-drawer.tsx b/packages/web/src/components/symbols/symbol-drawer.tsx
index 1388ebb9b..2028fcd39 100644
--- a/packages/web/src/components/symbols/symbol-drawer.tsx
+++ b/packages/web/src/components/symbols/symbol-drawer.tsx
@@ -9,60 +9,78 @@ import {
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { Separator } from "@/components/ui/separator";
+import { SymbolGraphPanel } from "./symbol-graph-panel";
import type { SymbolResponse } from "@/lib/api/types";
interface SymbolDrawerProps {
symbol: SymbolResponse | null;
+ repoId: string;
onClose: () => void;
}
-export function SymbolDrawer({ symbol, onClose }: SymbolDrawerProps) {
+export function SymbolDrawer({ symbol, repoId, onClose }: SymbolDrawerProps) {
return (
<Dialog open={symbol !== null} onOpenChange={(open) => !open && onClose()}>
- <DialogContent className="max-w-2xl">
+ <DialogContent className="max-w-[90vw] w-[900px] max-h-[85vh] overflow-hidden p-0">
{symbol && (
<>
- <DialogHeader>
- <DialogTitle className="font-mono text-base">{symbol.name}</DialogTitle>
- <DialogDescription className="font-mono text-xs text-[var(--color-text-tertiary)]">
- {symbol.file_path}:{symbol.start_line}
- </DialogDescription>
- </DialogHeader>
-
- <div className="flex flex-wrap gap-1.5 my-1">
- <Badge variant="accent">{symbol.kind}</Badge>
- <Badge variant="outline">{symbol.language}</Badge>
- {symbol.visibility && symbol.visibility !== "public" && (
- <Badge variant="default">{symbol.visibility}</Badge>
- )}
- {symbol.is_async && <Badge variant="default">async</Badge>}
- {symbol.complexity_estimate > 10 && (
- <Badge variant="stale">complexity {symbol.complexity_estimate}</Badge>
- )}
+ <div className="px-6 pt-6 pb-3">
+ <DialogHeader>
+ <DialogTitle className="font-mono text-base">{symbol.name}</DialogTitle>
+ <DialogDescription className="font-mono text-xs text-[var(--color-text-tertiary)]">
+ {symbol.file_path}:{symbol.start_line}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex flex-wrap gap-1.5 mt-2">
+ <Badge variant="accent">{symbol.kind}</Badge>
+ <Badge variant="outline">{symbol.language}</Badge>
+ {symbol.visibility && symbol.visibility !== "public" && (
+ <Badge variant="default">{symbol.visibility}</Badge>
+ )}
+ {symbol.is_async && <Badge variant="default">async</Badge>}
+ {symbol.complexity_estimate > 10 && (
+ <Badge variant="stale">complexity {symbol.complexity_estimate}</Badge>
+ )}
+ </div>
</div>
- <ScrollArea className="max-h-64 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
- <pre className="p-4 text-xs font-mono text-[var(--color-text-primary)] whitespace-pre-wrap break-all">
- <code>{symbol.signature || symbol.name}</code>
- </pre>
- </ScrollArea>
+ <Separator />
- {symbol.docstring && (
- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">
- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1.5">
- Docstring
- </p>
- <p className="text-sm text-[var(--color-text-secondary)] whitespace-pre-wrap">
- {symbol.docstring}
- </p>
- </div>
- )}
+ <div className="flex min-h-0 flex-1 overflow-hidden" style={{ maxHeight: "calc(85vh - 120px)" }}>
+ {/* Left column — existing content */}
+ <ScrollArea className="flex-1 min-w-0">
+ <div className="px-6 py-4 space-y-3">
+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
+ <pre className="p-4 text-xs font-mono text-[var(--color-text-primary)] whitespace-pre-wrap break-all">
+ <code>{symbol.signature || symbol.name}</code>
+ </pre>
+ </div>
+
+ {symbol.docstring && (
+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">
+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1.5">
+ Docstring
+ </p>
+ <p className="text-sm text-[var(--color-text-secondary)] whitespace-pre-wrap">
+ {symbol.docstring}
+ </p>
+ </div>
+ )}
- {symbol.parent_name && (
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Parent: <span className="font-mono text-[var(--color-text-secondary)]">{symbol.parent_name}</span>
- </p>
- )}
+ {symbol.parent_name && (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Parent: <span className="font-mono text-[var(--color-text-secondary)]">{symbol.parent_name}</span>
+ </p>
+ )}
+ </div>
+ </ScrollArea>
+
+ {/* Right column — graph intelligence */}
+ <div className="hidden md:flex flex-col border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-[280px] shrink-0 overflow-hidden">
+ <SymbolGraphPanel repoId={repoId} symbol={symbol} />
+ </div>
+ </div>
</>
)}
</DialogContent>
diff --git a/packages/web/src/components/symbols/symbol-graph-panel.tsx b/packages/web/src/components/symbols/symbol-graph-panel.tsx
new file mode 100644
index 000000000..dbe383ee7
--- /dev/null
+++ b/packages/web/src/components/symbols/symbol-graph-panel.tsx
@@ -0,0 +1,225 @@
+"use client";
+
+import { Badge } from "@/components/ui/badge";
+import { Skeleton } from "@/components/ui/skeleton";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { Separator } from "@/components/ui/separator";
+import { useGraphMetrics, useCallersCallees } from "@/lib/hooks/use-graph";
+import { truncatePath } from "@/lib/utils/format";
+import { cn } from "@/lib/utils/cn";
+import type { SymbolResponse, CallerCalleeEntry } from "@/lib/api/types";
+
+interface SymbolGraphPanelProps {
+ repoId: string;
+ symbol: SymbolResponse;
+}
+
+function PercentileBadge({ value, label }: { value: number; label: string }) {
+ const color =
+ value >= 75
+ ? "text-green-400 bg-green-400/10 border-green-400/20"
+ : value >= 50
+ ? "text-yellow-400 bg-yellow-400/10 border-yellow-400/20"
+ : "text-[var(--color-text-tertiary)] bg-[var(--color-bg-elevated)] border-[var(--color-border-default)]";
+
+ return (
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] text-[var(--color-text-tertiary)]">{label}</span>
+ <span className={cn("text-[11px] font-mono px-1.5 py-0.5 rounded border", color)}>
+ Top {100 - value}%
+ </span>
+ </div>
+ );
+}
+
+function CallerCalleeList({
+ items,
+ label,
+}: {
+ items: CallerCalleeEntry[];
+ label: string;
+}) {
+ if (items.length === 0) {
+ return (
+ <div>
+ <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1.5">
+ {label} (0)
+ </p>
+ <p className="text-[11px] text-[var(--color-text-tertiary)] italic">None found</p>
+ </div>
+ );
+ }
+
+ return (
+ <div>
+ <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1.5">
+ {label} ({items.length})
+ </p>
+ <div className="space-y-1">
+ {items.slice(0, 15).map((item) => (
+ <div
+ key={item.symbol_id}
+ className="flex items-start gap-1.5 py-1 px-1.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ {/* Confidence dot */}
+ <span
+ className={cn(
+ "mt-1.5 w-1.5 h-1.5 rounded-full shrink-0",
+ item.confidence >= 0.9
+ ? "bg-green-400"
+ : item.confidence >= 0.7
+ ? "bg-yellow-400"
+ : "bg-[var(--color-text-tertiary)]",
+ )}
+ />
+ <div className="min-w-0 flex-1">
+ <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate" title={item.symbol_id}>
+ {item.name}
+ </p>
+ <p className="text-[10px] text-[var(--color-text-tertiary)] truncate" title={item.file}>
+ {truncatePath(item.file)}
+ </p>
+ </div>
+ {item.edge_type !== "calls" && (
+ <Badge variant="outline" className="text-[9px] shrink-0 h-4">
+ {item.edge_type}
+ </Badge>
+ )}
+ </div>
+ ))}
+ {items.length > 15 && (
+ <p className="text-[10px] text-[var(--color-text-tertiary)] px-1.5">
+ +{items.length - 15} more
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export function SymbolGraphPanel({ repoId, symbol }: SymbolGraphPanelProps) {
+ const nodeId = `${symbol.file_path}::${symbol.name}`;
+
+ const { metrics, isLoading: metricsLoading } = useGraphMetrics(repoId, nodeId);
+ const { data: callData, isLoading: callsLoading } = useCallersCallees(repoId, nodeId);
+ const { data: heritageData } = useCallersCallees(repoId, nodeId, {
+ edge_types: "extends,implements",
+ });
+
+ const hasHeritage =
+ heritageData && (heritageData.caller_count > 0 || heritageData.callee_count > 0);
+
+ return (
+ <ScrollArea className="h-full">
+ <div className="space-y-4 p-1">
+ {/* Graph Metrics */}
+ <div>
+ <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">
+ Graph Metrics
+ </p>
+ {metricsLoading ? (
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-3/4" />
+ </div>
+ ) : metrics ? (
+ <div className="space-y-1.5">
+ <PercentileBadge value={metrics.pagerank_percentile} label="PageRank" />
+ <PercentileBadge value={metrics.betweenness_percentile} label="Betweenness" />
+
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] text-[var(--color-text-tertiary)]">Degree</span>
+ <span className="text-[11px] font-mono text-[var(--color-text-secondary)]">
+ {metrics.in_degree} in &middot; {metrics.out_degree} out
+ </span>
+ </div>
+
+ {metrics.community_label && (
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] text-[var(--color-text-tertiary)]">Community</span>
+ <Badge variant="outline" className="text-[10px] h-5">
+ {metrics.community_label}
+ </Badge>
+ </div>
+ )}
+
+ {metrics.entry_point_score != null && metrics.entry_point_score > 0 && (
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] text-[var(--color-text-tertiary)]">Entry Point</span>
+ <div className="flex items-center gap-1.5">
+ <div className="w-12 h-1.5 rounded-full bg-[var(--color-bg-elevated)] overflow-hidden">
+ <div
+ className="h-full rounded-full bg-[var(--color-accent)]"
+ style={{ width: `${Math.round(metrics.entry_point_score * 100)}%` }}
+ />
+ </div>
+ <span className="text-[10px] font-mono text-[var(--color-text-secondary)]">
+ {(metrics.entry_point_score * 100).toFixed(0)}%
+ </span>
+ </div>
+ </div>
+ )}
+ </div>
+ ) : (
+ <p className="text-[11px] text-[var(--color-text-tertiary)] italic">
+ Not indexed in graph
+ </p>
+ )}
+ </div>
+
+ <Separator />
+
+ {/* Callers & Callees */}
+ <div>
+ {callsLoading ? (
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-24" />
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-8 w-full" />
+ </div>
+ ) : callData ? (
+ <div className="space-y-3">
+ <CallerCalleeList items={callData.callers} label="Called by" />
+ <CallerCalleeList items={callData.callees} label="Calls" />
+ </div>
+ ) : null}
+ </div>
+
+ {/* Heritage */}
+ {hasHeritage && (
+ <>
+ <Separator />
+ <div>
+ <p className="text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1.5">
+ Heritage
+ </p>
+ {heritageData!.callers.length > 0 && (
+ <div className="mb-2">
+ <p className="text-[10px] text-[var(--color-text-tertiary)] mb-1">Extended/Implemented by:</p>
+ {heritageData!.callers.map((c) => (
+ <p key={c.symbol_id} className="text-[11px] font-mono text-[var(--color-text-primary)] truncate pl-2">
+ {c.name}
+ <span className="text-[var(--color-text-tertiary)] ml-1">({c.edge_type})</span>
+ </p>
+ ))}
+ </div>
+ )}
+ {heritageData!.callees.length > 0 && (
+ <div>
+ <p className="text-[10px] text-[var(--color-text-tertiary)] mb-1">Extends/Implements:</p>
+ {heritageData!.callees.map((c) => (
+ <p key={c.symbol_id} className="text-[11px] font-mono text-[var(--color-text-primary)] truncate pl-2">
+ {c.name}
+ <span className="text-[var(--color-text-tertiary)] ml-1">({c.edge_type})</span>
+ </p>
+ ))}
+ </div>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ </ScrollArea>
+ );
+}
diff --git a/packages/web/src/components/symbols/symbol-table.tsx b/packages/web/src/components/symbols/symbol-table.tsx
index 4a4b2099f..134451595 100644
--- a/packages/web/src/components/symbols/symbol-table.tsx
+++ b/packages/web/src/components/symbols/symbol-table.tsx
@@ -1,8 +1,9 @@
"use client";
-import { useState, useEffect, useCallback } from "react";
+import { useState, useCallback, useMemo } from "react";
import useSWR from "swr";
-import { ChevronUp, ChevronDown, ChevronsUpDown } from "lucide-react";
+import useSWRInfinite from "swr/infinite";
+import { ChevronUp, ChevronDown, ChevronsUpDown, TrendingUp } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
@@ -11,12 +12,13 @@ import { Skeleton } from "@/components/ui/skeleton";
import { EmptyState } from "@/components/shared/empty-state";
import { SymbolDrawer } from "./symbol-drawer";
import { listSymbols } from "@/lib/api/symbols";
+import { getGraph } from "@/lib/api/graph";
import { useDebounce } from "@/lib/hooks/use-debounce";
import { truncatePath } from "@/lib/utils/format";
import { cn } from "@/lib/utils/cn";
-import type { SymbolResponse } from "@/lib/api/types";
+import type { SymbolResponse, GraphExportResponse } from "@/lib/api/types";
-type SortCol = "name" | "kind" | "language" | "complexity_estimate" | "start_line";
+type SortCol = "importance" | "name" | "kind" | "language" | "complexity_estimate" | "start_line";
type SortDir = "asc" | "desc";
const LIMIT = 50;
@@ -37,42 +39,76 @@ function SortIcon({ col, sortCol, sortDir }: { col: SortCol; sortCol: SortCol; s
);
}
+function ImportanceBar({ score }: { score: number }) {
+ const pct = Math.min(100, Math.round(score * 100));
+ const color = pct >= 70 ? "bg-[var(--color-accent-primary)]" : pct >= 40 ? "bg-yellow-500" : "bg-[var(--color-text-tertiary)]";
+ return (
+ <div className="flex items-center gap-1.5">
+ <div className="h-1.5 w-16 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
+ <div className={cn("h-full rounded-full transition-all", color)} style={{ width: `${pct}%` }} />
+ </div>
+ <span className="text-[10px] tabular-nums text-[var(--color-text-tertiary)]">{pct}</span>
+ </div>
+ );
+}
+
export function SymbolTable({ repoId }: SymbolTableProps) {
const [q, setQ] = useState("");
const debouncedQ = useDebounce(q, 300);
const [kind, setKind] = useState("all");
const [language, setLanguage] = useState("all");
- const [offset, setOffset] = useState(0);
- const [items, setItems] = useState<SymbolResponse[]>([]);
- const [sortCol, setSortCol] = useState<SortCol>("name");
- const [sortDir, setSortDir] = useState<SortDir>("asc");
+ const [sortCol, setSortCol] = useState<SortCol>("importance");
+ const [sortDir, setSortDir] = useState<SortDir>("desc");
const [selected, setSelected] = useState<SymbolResponse | null>(null);
- const swrKey = `symbols:${repoId}:${debouncedQ}:${kind}:${language}:${offset}`;
- const { data, isLoading } = useSWR<SymbolResponse[]>(
- swrKey,
- () =>
- listSymbols({
+ // Fetch graph data for pagerank-based importance scoring
+ const { data: graphData } = useSWR<GraphExportResponse>(
+ `graph:${repoId}`,
+ () => getGraph(repoId),
+ { revalidateOnFocus: false, revalidateOnReconnect: false },
+ );
+
+ const pagerankMap = useMemo(() => {
+ if (!graphData) return new Map<string, number>();
+ const m = new Map<string, number>();
+ for (const n of graphData.nodes) m.set(n.node_id, n.pagerank);
+ return m;
+ }, [graphData]);
+
+ const { data, size, setSize, isLoading, isValidating } = useSWRInfinite<SymbolResponse[]>(
+ (pageIndex, previousPageData) => {
+ if (previousPageData && previousPageData.length < LIMIT) return null;
+ return `symbols:${repoId}:${debouncedQ}:${kind}:${language}:${pageIndex}`;
+ },
+ (key) => {
+ const pageIndex = parseInt(key.split(":").pop()!, 10);
+ return listSymbols({
repo_id: repoId,
q: debouncedQ || undefined,
kind: kind !== "all" ? kind : undefined,
language: language !== "all" ? language : undefined,
limit: LIMIT,
- offset,
- }),
- { revalidateOnFocus: false },
+ offset: pageIndex * LIMIT,
+ });
+ },
+ { revalidateOnFocus: false, revalidateFirstPage: false },
);
- useEffect(() => {
- if (!data) return;
- setItems((prev) => (offset === 0 ? data : [...prev, ...data]));
- }, [data, offset]);
+ const items = useMemo(() => (data ? data.flat() : []), [data]);
- // Reset when filters change
- useEffect(() => {
- setOffset(0);
- setItems([]);
- }, [debouncedQ, kind, language]);
+ // Compute importance score per symbol: file pagerank * (1 + log(complexity))
+ const importanceScores = useMemo(() => {
+ const scores = new Map<string, number>();
+ for (const sym of items) {
+ const fileRank = pagerankMap.get(sym.file_path) ?? 0;
+ const complexity = Math.max(1, sym.complexity_estimate);
+ scores.set(sym.id, fileRank * (1 + Math.log(complexity)));
+ }
+ // Normalize to 0-1 range
+ const max = Math.max(...scores.values(), 0.0001);
+ for (const [k, v] of scores) scores.set(k, v / max);
+ return scores;
+ }, [items, pagerankMap]);
const handleSort = useCallback(
(col: SortCol) => {
@@ -80,20 +116,37 @@ export function SymbolTable({ repoId }: SymbolTableProps) {
setSortDir((d) => (d === "asc" ? "desc" : "asc"));
} else {
setSortCol(col);
- setSortDir("asc");
+ setSortDir(col === "importance" ? "desc" : "asc");
}
},
[sortCol],
);
- const sorted = [...items].sort((a, b) => {
- const va = a[sortCol] ?? "";
- const vb = b[sortCol] ?? "";
- const cmp = String(va).localeCompare(String(vb), undefined, { numeric: true });
- return sortDir === "asc" ? cmp : -cmp;
- });
+ const sorted = useMemo(() => {
+ return [...items].sort((a, b) => {
+ if (sortCol === "importance") {
+ const ia = importanceScores.get(a.id) ?? 0;
+ const ib = importanceScores.get(b.id) ?? 0;
+ return sortDir === "asc" ? ia - ib : ib - ia;
+ }
+ const va = a[sortCol] ?? "";
+ const vb = b[sortCol] ?? "";
+ const cmp = String(va).localeCompare(String(vb), undefined, { numeric: true });
+ return sortDir === "asc" ? cmp : -cmp;
+ });
+ }, [items, sortCol, sortDir, importanceScores]);
+
+ const lastPage = data ? data[data.length - 1] : undefined;
+ const hasMore = lastPage?.length === LIMIT;
- const hasMore = data?.length === LIMIT;
+ const columns: Array<{ col: SortCol; label: string; hideOnMobile?: boolean }> = [
+ { col: "importance", label: "Importance" },
+ { col: "name", label: "Name" },
+ { col: "kind", label: "Kind" },
+ { col: "language", label: "Language", hideOnMobile: true },
+ { col: "start_line", label: "File", hideOnMobile: true },
+ { col: "complexity_estimate", label: "Complexity", hideOnMobile: true },
+ ];
return (
<div className="space-y-4">
@@ -153,21 +206,17 @@ export function SymbolTable({ repoId }: SymbolTableProps) {
<table className="w-full text-sm">
<thead>
<tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
- {(
- [
- { col: "name" as SortCol, label: "Name" },
- { col: "kind" as SortCol, label: "Kind" },
- { col: "language" as SortCol, label: "Language" },
- { col: "start_line" as SortCol, label: "File" },
- { col: "complexity_estimate" as SortCol, label: "Complexity" },
- ] as Array<{ col: SortCol; label: string }>
- ).map(({ col, label }) => (
+ {columns.map(({ col, label, hideOnMobile }) => (
<th
key={col}
- className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider cursor-pointer select-none hover:text-[var(--color-text-primary)] transition-colors"
+ className={cn(
+ "px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider cursor-pointer select-none hover:text-[var(--color-text-primary)] transition-colors",
+ hideOnMobile && "hidden sm:table-cell",
+ )}
onClick={() => handleSort(col)}
>
<span className="inline-flex items-center gap-1">
+ {col === "importance" && <TrendingUp className="h-3 w-3" />}
{label}
<SortIcon col={col} sortCol={sortCol} sortDir={sortDir} />
</span>
@@ -182,7 +231,10 @@ export function SymbolTable({ repoId }: SymbolTableProps) {
className="border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0 cursor-pointer"
onClick={() => setSelected(sym)}
>
- <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)]" style={{ maxWidth: 0 }}>
+ <td className="px-4 py-2.5">
+ <ImportanceBar score={importanceScores.get(sym.id) ?? 0} />
+ </td>
+ <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] min-w-0" style={{ maxWidth: 0 }}>
<span className="truncate block" title={sym.qualified_name || sym.name}>{sym.name}</span>
{sym.parent_name && (
<span className="text-[var(--color-text-tertiary)]">.{sym.parent_name}</span>
@@ -191,15 +243,15 @@ export function SymbolTable({ repoId }: SymbolTableProps) {
<td className="px-4 py-2.5">
<Badge variant={sym.kind === "class" ? "accent" : "default"}>{sym.kind}</Badge>
</td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)]">
+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] hidden sm:table-cell">
{sym.language}
</td>
- <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-tertiary)]" style={{ maxWidth: 0 }}>
+ <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-tertiary)] min-w-0 hidden sm:table-cell" style={{ maxWidth: 0 }}>
<span className="block truncate" title={`${sym.file_path}:${sym.start_line}`}>
{truncatePath(sym.file_path)}:{sym.start_line}
</span>
</td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] tabular-nums">
+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] tabular-nums hidden sm:table-cell">
<span
className={cn(
sym.complexity_estimate > 15
@@ -223,17 +275,17 @@ export function SymbolTable({ repoId }: SymbolTableProps) {
<Button
variant="outline"
size="sm"
- onClick={() => setOffset((o) => o + LIMIT)}
- disabled={isLoading}
+ onClick={() => setSize(size + 1)}
+ disabled={isValidating}
>
- {isLoading ? "Loading…" : "Load more"}
+ {isValidating ? "Loading…" : "Load more"}
</Button>
</div>
)}
</>
)}
- <SymbolDrawer symbol={selected} onClose={() => setSelected(null)} />
+ <SymbolDrawer symbol={selected} repoId={repoId} onClose={() => setSelected(null)} />
</div>
);
}
diff --git a/packages/web/src/components/wiki/mermaid-diagram.tsx b/packages/web/src/components/wiki/mermaid-diagram.tsx
index ca6ed9fd6..4111fc823 100644
--- a/packages/web/src/components/wiki/mermaid-diagram.tsx
+++ b/packages/web/src/components/wiki/mermaid-diagram.tsx
@@ -20,7 +20,7 @@ export function MermaidDiagram({ chart }: Props) {
startOnLoad: false,
theme: "dark",
themeVariables: {
- background: "var(--color-bg-surface)",
+ background: "#1a1a2e",
primaryColor: "#5B9CF6",
primaryTextColor: "#e2e8f0",
lineColor: "#334155",
diff --git a/packages/web/src/components/wiki/version-history.tsx b/packages/web/src/components/wiki/version-history.tsx
new file mode 100644
index 000000000..3895c95a3
--- /dev/null
+++ b/packages/web/src/components/wiki/version-history.tsx
@@ -0,0 +1,218 @@
+"use client";
+
+import { useState } from "react";
+import { ChevronDown, ChevronRight, Clock, Diff, ArrowLeft } from "lucide-react";
+import { cn } from "@/lib/utils/cn";
+import { usePageVersions } from "@/lib/hooks/use-page";
+import { Badge } from "@/components/ui/badge";
+import { formatRelativeTime } from "@/lib/utils/format";
+import type { PageVersionResponse } from "@/lib/api/types";
+
+interface VersionHistoryProps {
+ pageId: string;
+ currentVersion: number;
+ currentContent: string;
+}
+
+export function VersionHistory({ pageId, currentVersion, currentContent }: VersionHistoryProps) {
+ const { versions, isLoading } = usePageVersions(pageId);
+ const [expanded, setExpanded] = useState(false);
+ const [selectedVersion, setSelectedVersion] = useState<PageVersionResponse | null>(null);
+ const [showDiff, setShowDiff] = useState(false);
+
+ if (isLoading || versions.length === 0) return null;
+
+ if (selectedVersion) {
+ return (
+ <div className="border border-[var(--color-border-default)] rounded-lg overflow-hidden">
+ {/* Header */}
+ <div className="flex items-center justify-between px-4 py-2 bg-[var(--color-bg-elevated)] border-b border-[var(--color-border-default)]">
+ <button
+ onClick={() => { setSelectedVersion(null); setShowDiff(false); }}
+ className="flex items-center gap-1.5 text-xs text-[var(--color-accent-primary)] hover:underline"
+ >
+ <ArrowLeft className="h-3 w-3" />
+ Back to versions
+ </button>
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ v{selectedVersion.version}
+ </span>
+ <button
+ onClick={() => setShowDiff((d) => !d)}
+ className={cn(
+ "flex items-center gap-1 text-xs px-2 py-0.5 rounded border transition-colors",
+ showDiff
+ ? "bg-[var(--color-accent-primary)]/10 border-[var(--color-accent-primary)]/30 text-[var(--color-accent-primary)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",
+ )}
+ >
+ <Diff className="h-3 w-3" />
+ {showDiff ? "Showing diff" : "Show diff"}
+ </button>
+ </div>
+ </div>
+
+ {/* Content */}
+ <div className="max-h-[500px] overflow-auto p-4">
+ {showDiff ? (
+ <DiffView oldContent={selectedVersion.content} newContent={currentContent} />
+ ) : (
+ <pre className="text-xs font-mono text-[var(--color-text-secondary)] whitespace-pre-wrap leading-relaxed">
+ {selectedVersion.content}
+ </pre>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="border border-[var(--color-border-default)] rounded-lg overflow-hidden">
+ <button
+ onClick={() => setExpanded((e) => !e)}
+ className="flex items-center justify-between w-full px-4 py-2 bg-[var(--color-bg-elevated)] hover:bg-[var(--color-bg-elevated)]/80 transition-colors"
+ >
+ <div className="flex items-center gap-1.5">
+ <Clock className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ <span className="text-xs font-medium text-[var(--color-text-secondary)]">
+ Version History
+ </span>
+ <Badge variant="outline" className="text-[10px] ml-1">
+ {versions.length} versions
+ </Badge>
+ </div>
+ {expanded ? (
+ <ChevronDown className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ ) : (
+ <ChevronRight className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="divide-y divide-[var(--color-border-default)]">
+ {/* Current version */}
+ <div className="flex items-center justify-between px-4 py-2 bg-[var(--color-accent-primary)]/5">
+ <div className="flex items-center gap-2">
+ <span className="text-xs font-mono text-[var(--color-accent-primary)]">
+ v{currentVersion}
+ </span>
+ <Badge variant="accent" className="text-[10px]">current</Badge>
+ </div>
+ </div>
+
+ {/* Previous versions */}
+ {versions.map((v) => (
+ <button
+ key={v.id}
+ onClick={() => setSelectedVersion(v)}
+ className="flex items-center justify-between w-full px-4 py-2 hover:bg-[var(--color-bg-elevated)] transition-colors text-left"
+ >
+ <div className="flex items-center gap-2 min-w-0">
+ <span className="text-xs font-mono text-[var(--color-text-secondary)]">
+ v{v.version}
+ </span>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] font-mono truncate">
+ {v.model_name}
+ </span>
+ </div>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0 ml-2">
+ {formatRelativeTime(v.archived_at)}
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function DiffView({ oldContent, newContent }: { oldContent: string; newContent: string }) {
+ const oldLines = oldContent.split("\n");
+ const newLines = newContent.split("\n");
+
+ // Simple line-by-line diff (LCS-based)
+ const diff = computeLineDiff(oldLines, newLines);
+
+ return (
+ <div className="text-xs font-mono space-y-0">
+ {diff.map((line, i) => (
+ <div
+ key={i}
+ className={cn(
+ "px-2 py-0.5 whitespace-pre-wrap break-all",
+ line.type === "added" && "bg-green-500/10 text-green-400",
+ line.type === "removed" && "bg-red-500/10 text-red-400",
+ line.type === "unchanged" && "text-[var(--color-text-tertiary)]",
+ )}
+ >
+ <span className="inline-block w-4 text-right mr-2 select-none opacity-50">
+ {line.type === "added" ? "+" : line.type === "removed" ? "-" : " "}
+ </span>
+ {line.text}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+interface DiffLine {
+ type: "added" | "removed" | "unchanged";
+ text: string;
+}
+
+function computeLineDiff(oldLines: string[], newLines: string[]): DiffLine[] {
+ // Build LCS table
+ const m = oldLines.length;
+ const n = newLines.length;
+
+ // For very large files, fall back to a simpler approach
+ if (m * n > 500_000) {
+ return simpleDiff(oldLines, newLines);
+ }
+
+ const dp: number[][] = Array.from({ length: m + 1 }, () =>
+ Array(n + 1).fill(0),
+ );
+
+ for (let i = 1; i <= m; i++) {
+ for (let j = 1; j <= n; j++) {
+ if (oldLines[i - 1] === newLines[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ } else {
+ dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
+ }
+ }
+ }
+
+ // Backtrack to produce diff
+ const result: DiffLine[] = [];
+ let i = m;
+ let j = n;
+ while (i > 0 || j > 0) {
+ if (i > 0 && j > 0 && oldLines[i - 1] === newLines[j - 1]) {
+ result.unshift({ type: "unchanged", text: oldLines[i - 1] });
+ i--;
+ j--;
+ } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
+ result.unshift({ type: "added", text: newLines[j - 1] });
+ j--;
+ } else {
+ result.unshift({ type: "removed", text: oldLines[i - 1] });
+ i--;
+ }
+ }
+
+ return result;
+}
+
+function simpleDiff(oldLines: string[], newLines: string[]): DiffLine[] {
+ const result: DiffLine[] = [];
+ for (const line of oldLines) {
+ result.push({ type: "removed", text: line });
+ }
+ for (const line of newLines) {
+ result.push({ type: "added", text: line });
+ }
+ return result;
+}
diff --git a/packages/web/src/components/wiki/wiki-markdown.tsx b/packages/web/src/components/wiki/wiki-markdown.tsx
new file mode 100644
index 000000000..c82be4a78
--- /dev/null
+++ b/packages/web/src/components/wiki/wiki-markdown.tsx
@@ -0,0 +1,206 @@
+"use client";
+
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import type { Components } from "react-markdown";
+import { MermaidDiagram } from "./mermaid-diagram";
+import { useState } from "react";
+import { Copy, Check } from "lucide-react";
+import { cn } from "@/lib/utils/cn";
+
+/**
+ * Client-side wiki markdown renderer with Mermaid diagram support and
+ * heading anchor IDs (for ToC scroll-to-heading).
+ *
+ * This replaces ChatMarkdown in the docs explorer so that Mermaid diagrams
+ * render inline and ToC links work correctly.
+ */
+
+function slugify(text: string): string {
+ return text
+ .toLowerCase()
+ .replace(/[^\w\s-]/g, "")
+ .replace(/\s+/g, "-");
+}
+
+function ClientCodeBlock({ code, language }: { code: string; language: string }) {
+ const [copied, setCopied] = useState(false);
+
+ async function copy() {
+ await navigator.clipboard.writeText(code);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ }
+
+ return (
+ <div className="group relative my-4 rounded-lg border border-[var(--color-border-default)] overflow-hidden">
+ <div className="flex items-center justify-between px-4 py-1.5 bg-[var(--color-bg-elevated)] border-b border-[var(--color-border-default)]">
+ {language && (
+ <span className="text-xs font-mono text-[var(--color-text-tertiary)]">
+ {language}
+ </span>
+ )}
+ <button
+ onClick={copy}
+ className={cn(
+ "ml-auto flex items-center gap-1 text-xs text-[var(--color-text-tertiary)]",
+ "hover:text-[var(--color-text-secondary)] transition-colors",
+ )}
+ aria-label="Copy code"
+ >
+ {copied ? (
+ <>
+ <Check className="h-3.5 w-3.5" />
+ Copied
+ </>
+ ) : (
+ <>
+ <Copy className="h-3.5 w-3.5" />
+ Copy
+ </>
+ )}
+ </button>
+ </div>
+ <pre className="overflow-x-auto p-4 bg-[var(--color-bg-inset)]">
+ <code className="text-xs font-mono text-[var(--color-text-primary)]">
+ {code}
+ </code>
+ </pre>
+ </div>
+ );
+}
+
+const components: Components = {
+ h1: ({ children }) => {
+ const text = typeof children === "string" ? children : extractText(children);
+ const id = slugify(text);
+ return (
+ <h1 id={id} className="mt-8 mb-4 text-xl font-semibold text-[var(--color-text-primary)] first:mt-0 scroll-mt-16">
+ {children}
+ </h1>
+ );
+ },
+ h2: ({ children }) => {
+ const text = typeof children === "string" ? children : extractText(children);
+ const id = slugify(text);
+ return (
+ <h2 id={id} className="mt-6 mb-3 text-lg font-semibold text-[var(--color-text-primary)] scroll-mt-16">
+ {children}
+ </h2>
+ );
+ },
+ h3: ({ children }) => {
+ const text = typeof children === "string" ? children : extractText(children);
+ const id = slugify(text);
+ return (
+ <h3 id={id} className="mt-5 mb-2 text-base font-semibold text-[var(--color-text-primary)] scroll-mt-16">
+ {children}
+ </h3>
+ );
+ },
+ p: ({ children }) => (
+ <p className="mb-4 text-sm leading-7 text-[var(--color-text-secondary)]">
+ {children}
+ </p>
+ ),
+ ul: ({ children }) => (
+ <ul className="mb-4 ml-4 space-y-1 list-disc text-sm text-[var(--color-text-secondary)]">
+ {children}
+ </ul>
+ ),
+ ol: ({ children }) => (
+ <ol className="mb-4 ml-4 space-y-1 list-decimal text-sm text-[var(--color-text-secondary)]">
+ {children}
+ </ol>
+ ),
+ li: ({ children }) => <li className="leading-6">{children}</li>,
+ code: ({ className, children, ...props }) => {
+ const langMatch = className?.match(/language-(\w+)/);
+ const lang = langMatch?.[1];
+ const isBlock = !!lang;
+
+ if (isBlock) {
+ const code = typeof children === "string" ? children : String(children ?? "");
+ const trimmed = code.replace(/\n$/, "");
+
+ if (lang === "mermaid") {
+ return <MermaidDiagram chart={trimmed} />;
+ }
+
+ return <ClientCodeBlock code={trimmed} language={lang} />;
+ }
+
+ return (
+ <code
+ className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs font-mono text-[var(--color-accent-primary)]"
+ {...props}
+ >
+ {children}
+ </code>
+ );
+ },
+ pre: ({ children }) => <>{children}</>,
+ blockquote: ({ children }) => (
+ <blockquote
+ className="my-4 border-l-2 border-[var(--color-accent-primary)] pl-4 text-sm italic text-[var(--color-text-tertiary)]"
+ >
+ {children}
+ </blockquote>
+ ),
+ table: ({ children }) => (
+ <div className="my-4 overflow-x-auto rounded border border-[var(--color-border-default)]">
+ <table className="w-full text-sm">{children}</table>
+ </div>
+ ),
+ thead: ({ children }) => (
+ <thead className="bg-[var(--color-bg-elevated)]">{children}</thead>
+ ),
+ th: ({ children }) => (
+ <th className="px-4 py-2 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ {children}
+ </th>
+ ),
+ td: ({ children }) => (
+ <td className="px-4 py-2 text-sm text-[var(--color-text-secondary)] border-t border-[var(--color-border-default)]">
+ {children}
+ </td>
+ ),
+ hr: () => <hr className="my-6 border-[var(--color-border-default)]" />,
+ a: ({ href, children }) => (
+ <a
+ href={href}
+ className="text-[var(--color-accent-primary)] underline underline-offset-2 hover:opacity-80 transition-opacity"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {children}
+ </a>
+ ),
+ strong: ({ children }) => (
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {children}
+ </strong>
+ ),
+};
+
+function extractText(node: unknown): string {
+ if (typeof node === "string") return node;
+ if (Array.isArray(node)) return node.map(extractText).join("");
+ if (node && typeof node === "object" && "props" in node) {
+ const props = (node as { props?: { children?: unknown } }).props;
+ return extractText(props?.children);
+ }
+ return "";
+}
+
+interface WikiMarkdownProps {
+ content: string;
+}
+
+export function WikiMarkdown({ content }: WikiMarkdownProps) {
+ return (
+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
+ {content}
+ </ReactMarkdown>
+ );
+}
diff --git a/packages/web/src/components/wiki/wiki-renderer.tsx b/packages/web/src/components/wiki/wiki-renderer.tsx
index c61118da3..bc218c4ed 100644
--- a/packages/web/src/components/wiki/wiki-renderer.tsx
+++ b/packages/web/src/components/wiki/wiki-renderer.tsx
@@ -7,18 +7,38 @@ import { MermaidDiagram } from "./mermaid-diagram";
// Custom MDX components
// ---------------------------------------------------------------------------
+function slugify(text: string): string {
+ return text
+ .toLowerCase()
+ .replace(/[^\w\s-]/g, "")
+ .replace(/\s+/g, "-");
+}
+
+function extractText(node: unknown): string {
+ if (typeof node === "string") return node;
+ if (Array.isArray(node)) return node.map(extractText).join("");
+ if (node && typeof node === "object" && "props" in node) {
+ const props = (node as { props?: { children?: unknown } }).props;
+ return extractText(props?.children);
+ }
+ return "";
+}
+
const mdxComponents = {
// Code blocks — pass Shiki-highlighted HTML via a server action wrapper
// The actual Shiki call happens in the pre/code override below.
- h1: (props: React.HTMLAttributes<HTMLHeadingElement>) => (
- <h1 className="mt-8 mb-4 text-xl font-semibold text-[var(--color-text-primary)] first:mt-0" {...props} />
- ),
- h2: (props: React.HTMLAttributes<HTMLHeadingElement>) => (
- <h2 className="mt-6 mb-3 text-lg font-semibold text-[var(--color-text-primary)]" {...props} />
- ),
- h3: (props: React.HTMLAttributes<HTMLHeadingElement>) => (
- <h3 className="mt-5 mb-2 text-base font-semibold text-[var(--color-text-primary)]" {...props} />
- ),
+ h1: (props: React.HTMLAttributes<HTMLHeadingElement>) => {
+ const id = slugify(extractText(props.children));
+ return <h1 id={id} className="mt-8 mb-4 text-xl font-semibold text-[var(--color-text-primary)] first:mt-0 scroll-mt-16" {...props} />;
+ },
+ h2: (props: React.HTMLAttributes<HTMLHeadingElement>) => {
+ const id = slugify(extractText(props.children));
+ return <h2 id={id} className="mt-6 mb-3 text-lg font-semibold text-[var(--color-text-primary)] scroll-mt-16" {...props} />;
+ },
+ h3: (props: React.HTMLAttributes<HTMLHeadingElement>) => {
+ const id = slugify(extractText(props.children));
+ return <h3 id={id} className="mt-5 mb-2 text-base font-semibold text-[var(--color-text-primary)] scroll-mt-16" {...props} />;
+ },
p: (props: React.HTMLAttributes<HTMLParagraphElement>) => (
<p className="mb-4 text-sm leading-7 text-[var(--color-text-secondary)]" {...props} />
),
diff --git a/packages/web/src/components/workspace/co-change-table.tsx b/packages/web/src/components/workspace/co-change-table.tsx
new file mode 100644
index 000000000..4b8f5d87b
--- /dev/null
+++ b/packages/web/src/components/workspace/co-change-table.tsx
@@ -0,0 +1,80 @@
+"use client";
+
+import type { WorkspaceCoChangeEntry } from "@/lib/api/types";
+import { Badge } from "@/components/ui/badge";
+
+interface CoChangeTableProps {
+ coChanges: WorkspaceCoChangeEntry[];
+ compact?: boolean;
+}
+
+export function CoChangeTable({ coChanges, compact }: CoChangeTableProps) {
+ if (coChanges.length === 0) {
+ return (
+ <p className="text-sm text-[var(--color-text-tertiary)] py-4 text-center">
+ No cross-repo co-changes detected.
+ </p>
+ );
+ }
+
+ return (
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-[var(--color-border-default)] text-left text-xs text-[var(--color-text-tertiary)]">
+ <th className="pb-2 pr-4 font-medium">Source</th>
+ <th className="pb-2 pr-4 font-medium">Target</th>
+ <th className="pb-2 pr-4 font-medium w-32">Strength</th>
+ {!compact && <th className="pb-2 pr-4 font-medium">Freq</th>}
+ {!compact && <th className="pb-2 font-medium">Last</th>}
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-[var(--color-border-default)]">
+ {coChanges.map((cc, i) => (
+ <tr key={i} className="hover:bg-[var(--color-bg-elevated)] transition-colors">
+ <td className="py-2 pr-4">
+ <div className="flex flex-col gap-0.5">
+ <Badge variant="default" className="w-fit text-[11px]">{cc.source_repo}</Badge>
+ <span className="text-xs font-mono text-[var(--color-text-secondary)] truncate max-w-[250px]">
+ {cc.source_file}
+ </span>
+ </div>
+ </td>
+ <td className="py-2 pr-4">
+ <div className="flex flex-col gap-0.5">
+ <Badge variant="default" className="w-fit text-[11px]">{cc.target_repo}</Badge>
+ <span className="text-xs font-mono text-[var(--color-text-secondary)] truncate max-w-[250px]">
+ {cc.target_file}
+ </span>
+ </div>
+ </td>
+ <td className="py-2 pr-4">
+ <div className="flex items-center gap-2">
+ <div className="h-1.5 flex-1 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
+ <div
+ className="h-full rounded-full bg-[var(--color-accent-primary)] transition-all"
+ style={{ width: `${Math.round(cc.strength * 100)}%` }}
+ />
+ </div>
+ <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8 text-right">
+ {Math.round(cc.strength * 100)}%
+ </span>
+ </div>
+ </td>
+ {!compact && (
+ <td className="py-2 pr-4 text-xs text-[var(--color-text-secondary)] tabular-nums">
+ {cc.frequency}x
+ </td>
+ )}
+ {!compact && (
+ <td className="py-2 text-xs text-[var(--color-text-tertiary)]">
+ {cc.last_date ? new Date(cc.last_date).toLocaleDateString() : "—"}
+ </td>
+ )}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/workspace/contract-links-table.tsx b/packages/web/src/components/workspace/contract-links-table.tsx
new file mode 100644
index 000000000..cb046f855
--- /dev/null
+++ b/packages/web/src/components/workspace/contract-links-table.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import type { WorkspaceContractLinkEntry } from "@/lib/api/types";
+import { ContractTypeBadge } from "./contract-type-badge";
+
+interface ContractLinksTableProps {
+ links: WorkspaceContractLinkEntry[];
+}
+
+export function ContractLinksTable({ links }: ContractLinksTableProps) {
+ if (links.length === 0) {
+ return (
+ <p className="text-sm text-[var(--color-text-tertiary)] py-4 text-center">
+ No matched contract links.
+ </p>
+ );
+ }
+
+ return (
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-[var(--color-border-default)] text-left text-xs text-[var(--color-text-tertiary)]">
+ <th className="pb-2 pr-4 font-medium">Contract</th>
+ <th className="pb-2 pr-4 font-medium">Type</th>
+ <th className="pb-2 pr-4 font-medium">Provider</th>
+ <th className="pb-2 pr-4 font-medium">Consumer</th>
+ <th className="pb-2 font-medium w-20">Confidence</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-[var(--color-border-default)]">
+ {links.map((link, i) => (
+ <tr key={i} className="hover:bg-[var(--color-bg-elevated)] transition-colors">
+ <td className="py-2 pr-4">
+ <span className="text-xs font-mono text-[var(--color-text-secondary)] break-all">
+ {link.contract_id}
+ </span>
+ </td>
+ <td className="py-2 pr-4">
+ <ContractTypeBadge type={link.contract_type} />
+ </td>
+ <td className="py-2 pr-4">
+ <div className="flex flex-col gap-0.5">
+ <span className="text-xs font-medium text-[var(--color-text-primary)]">
+ {link.provider_repo}
+ </span>
+ <span className="text-xs font-mono text-[var(--color-text-tertiary)] truncate max-w-[200px]">
+ {link.provider_file}
+ </span>
+ </div>
+ </td>
+ <td className="py-2 pr-4">
+ <div className="flex flex-col gap-0.5">
+ <span className="text-xs font-medium text-[var(--color-text-primary)]">
+ {link.consumer_repo}
+ </span>
+ <span className="text-xs font-mono text-[var(--color-text-tertiary)] truncate max-w-[200px]">
+ {link.consumer_file}
+ </span>
+ </div>
+ </td>
+ <td className="py-2">
+ <div className="flex items-center gap-1.5">
+ <div className="h-1.5 w-12 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
+ <div
+ className="h-full rounded-full transition-all"
+ style={{
+ width: `${Math.round(link.confidence * 100)}%`,
+ backgroundColor:
+ link.confidence >= 0.8
+ ? "var(--color-confidence-fresh)"
+ : link.confidence >= 0.6
+ ? "var(--color-confidence-stale)"
+ : "var(--color-confidence-outdated)",
+ }}
+ />
+ </div>
+ <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums">
+ {Math.round(link.confidence * 100)}%
+ </span>
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/workspace/contract-type-badge.tsx b/packages/web/src/components/workspace/contract-type-badge.tsx
new file mode 100644
index 000000000..3f185baf6
--- /dev/null
+++ b/packages/web/src/components/workspace/contract-type-badge.tsx
@@ -0,0 +1,40 @@
+"use client";
+
+import { cn } from "@/lib/utils/cn";
+
+const TYPE_STYLES: Record<string, { bg: string; text: string; label: string }> = {
+ http: { bg: "bg-blue-500/10", text: "text-blue-400", label: "HTTP" },
+ grpc: { bg: "bg-purple-500/10", text: "text-purple-400", label: "gRPC" },
+ topic: { bg: "bg-orange-500/10", text: "text-orange-400", label: "Topic" },
+};
+
+export function ContractTypeBadge({ type }: { type: string }) {
+ const style = TYPE_STYLES[type] ?? { bg: "bg-gray-500/10", text: "text-gray-400", label: type };
+ return (
+ <span
+ className={cn(
+ "inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium",
+ style.bg,
+ style.text,
+ )}
+ >
+ {style.label}
+ </span>
+ );
+}
+
+export function RoleBadge({ role }: { role: string }) {
+ const isProvider = role === "provider";
+ return (
+ <span
+ className={cn(
+ "inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium",
+ isProvider
+ ? "bg-green-500/10 text-green-400"
+ : "bg-yellow-500/10 text-yellow-400",
+ )}
+ >
+ {isProvider ? "Provider" : "Consumer"}
+ </span>
+ );
+}
diff --git a/packages/web/src/components/workspace/cross-repo-summary.tsx b/packages/web/src/components/workspace/cross-repo-summary.tsx
new file mode 100644
index 000000000..6437166e7
--- /dev/null
+++ b/packages/web/src/components/workspace/cross-repo-summary.tsx
@@ -0,0 +1,44 @@
+"use client";
+
+import { Link2, GitMerge, Package } from "lucide-react";
+import type { WorkspaceCrossRepoSummary, WorkspaceContractSummary } from "@/lib/api/types";
+import { StatCard } from "@/components/shared/stat-card";
+
+interface CrossRepoSummaryProps {
+ crossRepo: WorkspaceCrossRepoSummary | null;
+ contracts: WorkspaceContractSummary | null;
+}
+
+export function CrossRepoSummary({ crossRepo, contracts }: CrossRepoSummaryProps) {
+ return (
+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
+ <StatCard
+ label="Co-Change Pairs"
+ value={crossRepo?.co_change_count ?? 0}
+ icon={<GitMerge className="h-4 w-4 text-[var(--color-accent-primary)]" />}
+ />
+ <StatCard
+ label="Package Deps"
+ value={crossRepo?.package_dep_count ?? 0}
+ icon={<Package className="h-4 w-4 text-purple-400" />}
+ />
+ <StatCard
+ label="Contract Links"
+ value={contracts?.total_links ?? 0}
+ icon={<Link2 className="h-4 w-4 text-blue-400" />}
+ />
+ <StatCard
+ label="Contracts Detected"
+ value={contracts?.total_contracts ?? 0}
+ description={
+ contracts?.by_type
+ ? Object.entries(contracts.by_type)
+ .map(([k, v]) => `${v} ${k}`)
+ .join(", ")
+ : undefined
+ }
+ icon={<Link2 className="h-4 w-4 text-orange-400" />}
+ />
+ </div>
+ );
+}
diff --git a/packages/web/src/components/workspace/repo-card.tsx b/packages/web/src/components/workspace/repo-card.tsx
new file mode 100644
index 000000000..21192c347
--- /dev/null
+++ b/packages/web/src/components/workspace/repo-card.tsx
@@ -0,0 +1,81 @@
+import Link from "next/link";
+import { FileText, Flame, BarChart3, ChevronRight } from "lucide-react";
+import type { RepoStatsResponse, GitSummaryResponse } from "@/lib/api/types";
+import { Card, CardContent } from "@/components/ui/card";
+import { Badge } from "@/components/ui/badge";
+
+interface RepoCardProps {
+ repoId: string;
+ alias: string;
+ name: string;
+ path: string;
+ isPrimary: boolean;
+ stats: RepoStatsResponse | null;
+ gitSummary: GitSummaryResponse | null;
+}
+
+export function RepoCard({
+ repoId,
+ alias,
+ name,
+ path,
+ isPrimary,
+ stats,
+ gitSummary,
+}: RepoCardProps) {
+ const card = (
+ <Card className={`group transition-colors ${repoId ? "hover:border-[var(--color-accent-primary)]/30 cursor-pointer" : "opacity-60"}`}>
+ <CardContent className="p-4">
+ <div className="flex items-start justify-between mb-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)] truncate group-hover:text-[var(--color-accent-primary)] transition-colors">
+ {name}
+ </h3>
+ {isPrimary && (
+ <Badge variant="accent" className="text-[10px] shrink-0">
+ default
+ </Badge>
+ )}
+ </div>
+ <p className="text-xs text-[var(--color-text-tertiary)] font-mono mt-0.5 truncate">
+ {alias} &middot; {path}
+ </p>
+ </div>
+ {repoId && (
+ <ChevronRight className="h-4 w-4 text-[var(--color-text-tertiary)] shrink-0 opacity-0 group-hover:opacity-100 transition-opacity mt-0.5" />
+ )}
+ </div>
+
+ <div className="grid grid-cols-3 gap-2">
+ <div className="flex items-center gap-1.5">
+ <FileText className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ <span className="text-xs text-[var(--color-text-secondary)]">
+ {stats?.file_count ?? "—"} files
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <BarChart3 className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ <span className="text-xs text-[var(--color-text-secondary)]">
+ {stats ? `${Math.round(stats.doc_coverage_pct)}% docs` : "—"}
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <Flame className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ <span className="text-xs text-[var(--color-text-secondary)]">
+ {gitSummary?.hotspot_count ?? "—"} hotspots
+ </span>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ );
+
+ if (!repoId) return card;
+
+ return (
+ <Link href={`/repos/${repoId}/overview`}>
+ {card}
+ </Link>
+ );
+}
diff --git a/packages/web/src/lib/api/graph.ts b/packages/web/src/lib/api/graph.ts
index 2d142c1f8..e90638eb1 100644
--- a/packages/web/src/lib/api/graph.ts
+++ b/packages/web/src/lib/api/graph.ts
@@ -1,8 +1,13 @@
import { apiGet } from "./client";
import type {
+ CallersCalleesResponse,
+ CommunityDetailResponse,
+ CommunitySummaryItem,
DeadCodeGraphResponse,
EgoGraphResponse,
+ ExecutionFlowsResponse,
GraphExportResponse,
+ GraphMetricsResponse,
GraphPathResponse,
HotFilesGraphResponse,
ModuleGraphResponse,
@@ -56,3 +61,47 @@ export async function getHotFilesGraph(
): Promise<HotFilesGraphResponse> {
return apiGet<HotFilesGraphResponse>(`/api/graph/${repoId}/hot-files`, { days, limit });
}
+
+// ---------------------------------------------------------------------------
+// Graph Intelligence
+// ---------------------------------------------------------------------------
+
+export async function getCommunities(repoId: string): Promise<CommunitySummaryItem[]> {
+ return apiGet<CommunitySummaryItem[]>(`/api/graph/${repoId}/communities`);
+}
+
+export async function getCommunityDetail(
+ repoId: string,
+ communityId: number,
+ params?: { include_members?: boolean; member_limit?: number },
+): Promise<CommunityDetailResponse> {
+ return apiGet<CommunityDetailResponse>(
+ `/api/graph/${repoId}/communities/${communityId}`,
+ params,
+ );
+}
+
+export async function getGraphMetrics(
+ repoId: string,
+ nodeId: string,
+): Promise<GraphMetricsResponse> {
+ return apiGet<GraphMetricsResponse>(`/api/graph/${repoId}/metrics`, { node_id: nodeId });
+}
+
+export async function getCallersCallees(
+ repoId: string,
+ symbolId: string,
+ params?: { direction?: string; edge_types?: string; limit?: number },
+): Promise<CallersCalleesResponse> {
+ return apiGet<CallersCalleesResponse>(`/api/graph/${repoId}/callers-callees`, {
+ symbol_id: symbolId,
+ ...params,
+ });
+}
+
+export async function getExecutionFlows(
+ repoId: string,
+ params?: { top_n?: number; max_depth?: number; entry_point?: string },
+): Promise<ExecutionFlowsResponse> {
+ return apiGet<ExecutionFlowsResponse>(`/api/graph/${repoId}/execution-flows`, params);
+}
diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.ts
index 9f9fed926..41f7b56f5 100644
--- a/packages/web/src/lib/api/types.ts
+++ b/packages/web/src/lib/api/types.ts
@@ -280,6 +280,101 @@ export interface RepoStatsResponse {
dead_export_count: number;
}
+// ---------------------------------------------------------------------------
+// Graph Intelligence
+// ---------------------------------------------------------------------------
+
+export interface SymbolNodeSummary {
+ symbol_id: string;
+ name: string;
+ kind: string;
+ file: string;
+ start_line?: number | null;
+ signature?: string | null;
+}
+
+export interface CallerCalleeEntry {
+ symbol_id: string;
+ name: string;
+ kind: string;
+ file: string;
+ start_line?: number | null;
+ edge_type: string;
+ confidence: number;
+}
+
+export interface CallersCalleesResponse {
+ symbol_id: string;
+ symbol: SymbolNodeSummary;
+ callers: CallerCalleeEntry[];
+ callees: CallerCalleeEntry[];
+ caller_count: number;
+ callee_count: number;
+ truncated: boolean;
+}
+
+export interface CommunityMember {
+ path: string;
+ pagerank: number;
+ is_entry_point: boolean;
+}
+
+export interface NeighboringCommunity {
+ community_id: number;
+ label: string;
+ cross_edge_count: number;
+}
+
+export interface CommunityDetailResponse {
+ community_id: number;
+ label: string;
+ cohesion: number;
+ member_count: number;
+ members: CommunityMember[];
+ truncated: boolean;
+ neighboring_communities: NeighboringCommunity[];
+}
+
+export interface CommunitySummaryItem {
+ community_id: number;
+ label: string;
+ cohesion: number;
+ member_count: number;
+ top_file: string;
+}
+
+export interface GraphMetricsResponse {
+ target: string;
+ node_type: string;
+ pagerank: number;
+ pagerank_percentile: number;
+ betweenness: number;
+ betweenness_percentile: number;
+ community_id: number;
+ community_label: string | null;
+ is_entry_point: boolean;
+ in_degree: number;
+ out_degree: number;
+ entry_point_score?: number | null;
+ kind?: string | null;
+ file?: string | null;
+}
+
+export interface ExecutionFlowEntry {
+ entry_point: string;
+ entry_point_name: string;
+ entry_point_score: number;
+ trace: string[];
+ depth: number;
+ crosses_community: boolean;
+ communities_visited: number[];
+}
+
+export interface ExecutionFlowsResponse {
+ total_entry_points: number;
+ flows: ExecutionFlowEntry[];
+}
+
// ---------------------------------------------------------------------------
// Git Intelligence
// ---------------------------------------------------------------------------
@@ -531,3 +626,91 @@ export interface ApiError {
detail: string;
status: number;
}
+
+// ---------------------------------------------------------------------------
+// Workspace
+// ---------------------------------------------------------------------------
+
+export interface WorkspaceRepoEntry {
+ alias: string;
+ path: string;
+ is_primary: boolean;
+ indexed_at: string | null;
+ last_commit_at_index: string | null;
+ // Per-repo stats from each repo's wiki.db
+ repo_id: string | null;
+ file_count: number;
+ symbol_count: number;
+ page_count: number;
+ doc_coverage_pct: number;
+ hotspot_count: number;
+}
+
+export interface WorkspaceCrossRepoSummary {
+ co_change_count: number;
+ package_dep_count: number;
+ top_connections: Array<{ repos: string[]; edge_count: number }>;
+}
+
+export interface WorkspaceContractSummary {
+ total_contracts: number;
+ total_links: number;
+ by_type: Record<string, number>;
+}
+
+export interface WorkspaceResponse {
+ is_workspace: boolean;
+ workspace_root: string | null;
+ workspace_name: string | null;
+ repos: WorkspaceRepoEntry[];
+ default_repo: string | null;
+ cross_repo_summary: WorkspaceCrossRepoSummary | null;
+ contract_summary: WorkspaceContractSummary | null;
+}
+
+export interface WorkspaceContractEntry {
+ contract_id: string;
+ contract_type: string;
+ role: string;
+ repo: string;
+ file_path: string;
+ symbol_name: string;
+ confidence: number;
+ service: string | null;
+}
+
+export interface WorkspaceContractLinkEntry {
+ contract_id: string;
+ contract_type: string;
+ match_type: string;
+ confidence: number;
+ provider_repo: string;
+ provider_file: string;
+ provider_symbol: string;
+ consumer_repo: string;
+ consumer_file: string;
+ consumer_symbol: string;
+}
+
+export interface WorkspaceContractsResponse {
+ contracts: WorkspaceContractEntry[];
+ links: WorkspaceContractLinkEntry[];
+ total_contracts: number;
+ total_links: number;
+ by_type: Record<string, number>;
+}
+
+export interface WorkspaceCoChangeEntry {
+ source_repo: string;
+ source_file: string;
+ target_repo: string;
+ target_file: string;
+ strength: number;
+ frequency: number;
+ last_date: string;
+}
+
+export interface WorkspaceCoChangesResponse {
+ co_changes: WorkspaceCoChangeEntry[];
+ total: number;
+}
diff --git a/packages/web/src/lib/api/workspace.ts b/packages/web/src/lib/api/workspace.ts
new file mode 100644
index 000000000..4f24f0206
--- /dev/null
+++ b/packages/web/src/lib/api/workspace.ts
@@ -0,0 +1,38 @@
+import { apiGet } from "./client";
+import type {
+ WorkspaceResponse,
+ WorkspaceContractsResponse,
+ WorkspaceCoChangesResponse,
+} from "./types";
+
+export async function getWorkspace(): Promise<WorkspaceResponse> {
+ return apiGet<WorkspaceResponse>("/api/workspace");
+}
+
+export async function getWorkspaceContracts(opts?: {
+ contract_type?: string;
+ repo?: string;
+ role?: string;
+ limit?: number;
+ offset?: number;
+}): Promise<WorkspaceContractsResponse> {
+ const params: Record<string, string> = {};
+ if (opts?.contract_type) params.contract_type = opts.contract_type;
+ if (opts?.repo) params.repo = opts.repo;
+ if (opts?.role) params.role = opts.role;
+ if (opts?.limit != null) params.limit = String(opts.limit);
+ if (opts?.offset != null) params.offset = String(opts.offset);
+ return apiGet<WorkspaceContractsResponse>("/api/workspace/contracts", params);
+}
+
+export async function getWorkspaceCoChanges(opts?: {
+ repo?: string;
+ min_strength?: number;
+ limit?: number;
+}): Promise<WorkspaceCoChangesResponse> {
+ const params: Record<string, string> = {};
+ if (opts?.repo) params.repo = opts.repo;
+ if (opts?.min_strength != null) params.min_strength = String(opts.min_strength);
+ if (opts?.limit != null) params.limit = String(opts.limit);
+ return apiGet<WorkspaceCoChangesResponse>("/api/workspace/co-changes", params);
+}
diff --git a/packages/web/src/lib/hooks/use-graph.ts b/packages/web/src/lib/hooks/use-graph.ts
index ac1b8232a..a0d30b2c5 100644
--- a/packages/web/src/lib/hooks/use-graph.ts
+++ b/packages/web/src/lib/hooks/use-graph.ts
@@ -3,16 +3,26 @@
import useSWR from "swr";
import {
getArchitectureGraph,
+ getCallersCallees,
+ getCommunities,
+ getCommunityDetail,
getDeadCodeGraph,
getEgoGraph,
+ getExecutionFlows,
getGraph,
+ getGraphMetrics,
getHotFilesGraph,
getModuleGraph,
} from "@/lib/api/graph";
import type {
+ CallersCalleesResponse,
+ CommunityDetailResponse,
+ CommunitySummaryItem,
DeadCodeGraphResponse,
EgoGraphResponse,
+ ExecutionFlowsResponse,
GraphExportResponse,
+ GraphMetricsResponse,
HotFilesGraphResponse,
ModuleGraphResponse,
} from "@/lib/api/types";
@@ -72,3 +82,62 @@ export function useHotFilesGraph(repoId: string | null, days = 30, limit = 25) {
);
return { graph: data, error, isLoading };
}
+
+// ---------------------------------------------------------------------------
+// Graph Intelligence
+// ---------------------------------------------------------------------------
+
+export function useCommunities(repoId: string | null) {
+ const { data, error, isLoading } = useSWR<CommunitySummaryItem[]>(
+ repoId ? `communities:${repoId}` : null,
+ () => getCommunities(repoId!),
+ SWR_OPTS,
+ );
+ return { communities: data, error, isLoading };
+}
+
+export function useCommunityDetail(repoId: string | null, communityId: number | null) {
+ const { data, error, isLoading } = useSWR<CommunityDetailResponse>(
+ repoId && communityId !== null ? `community:${repoId}:${communityId}` : null,
+ () => getCommunityDetail(repoId!, communityId!),
+ SWR_OPTS,
+ );
+ return { community: data, error, isLoading };
+}
+
+export function useGraphMetrics(repoId: string | null, nodeId: string | null) {
+ const { data, error, isLoading } = useSWR<GraphMetricsResponse>(
+ repoId && nodeId ? `metrics:${repoId}:${nodeId}` : null,
+ () => getGraphMetrics(repoId!, nodeId!),
+ SWR_OPTS,
+ );
+ return { metrics: data, error, isLoading };
+}
+
+export function useCallersCallees(
+ repoId: string | null,
+ symbolId: string | null,
+ params?: { direction?: string; edge_types?: string; limit?: number },
+) {
+ const key = repoId && symbolId
+ ? `callers:${repoId}:${symbolId}:${params?.edge_types ?? "calls"}`
+ : null;
+ const { data, error, isLoading } = useSWR<CallersCalleesResponse>(
+ key,
+ () => getCallersCallees(repoId!, symbolId!, params),
+ SWR_OPTS,
+ );
+ return { data, error, isLoading };
+}
+
+export function useExecutionFlows(
+ repoId: string | null,
+ params?: { top_n?: number; max_depth?: number },
+) {
+ const { data, error, isLoading } = useSWR<ExecutionFlowsResponse>(
+ repoId ? `flows:${repoId}:${params?.top_n ?? 5}` : null,
+ () => getExecutionFlows(repoId!, params),
+ SWR_OPTS,
+ );
+ return { flows: data, error, isLoading };
+}
diff --git a/packages/web/src/lib/hooks/use-workspace.ts b/packages/web/src/lib/hooks/use-workspace.ts
new file mode 100644
index 000000000..9412f3065
--- /dev/null
+++ b/packages/web/src/lib/hooks/use-workspace.ts
@@ -0,0 +1,55 @@
+"use client";
+
+import useSWR from "swr";
+import {
+ getWorkspace,
+ getWorkspaceContracts,
+ getWorkspaceCoChanges,
+} from "@/lib/api/workspace";
+import type {
+ WorkspaceResponse,
+ WorkspaceContractsResponse,
+ WorkspaceCoChangesResponse,
+} from "@/lib/api/types";
+
+export function useWorkspace() {
+ const { data, error, isLoading } = useSWR<WorkspaceResponse>(
+ "workspace",
+ () => getWorkspace(),
+ { refreshInterval: 60_000, revalidateOnFocus: false },
+ );
+ return {
+ workspace: data ?? null,
+ isWorkspace: data?.is_workspace ?? false,
+ isLoading,
+ error,
+ };
+}
+
+export function useWorkspaceContracts(opts?: {
+ contract_type?: string;
+ repo?: string;
+ role?: string;
+}) {
+ const key = `workspace:contracts:${JSON.stringify(opts ?? {})}`;
+ const { data, error, isLoading } = useSWR<WorkspaceContractsResponse>(
+ key,
+ () => getWorkspaceContracts(opts),
+ { revalidateOnFocus: false },
+ );
+ return { data: data ?? null, isLoading, error };
+}
+
+export function useWorkspaceCoChanges(opts?: {
+ repo?: string;
+ min_strength?: number;
+ limit?: number;
+}) {
+ const key = `workspace:co-changes:${JSON.stringify(opts ?? {})}`;
+ const { data, error, isLoading } = useSWR<WorkspaceCoChangesResponse>(
+ key,
+ () => getWorkspaceCoChanges(opts),
+ { revalidateOnFocus: false },
+ );
+ return { data: data ?? null, isLoading, error };
+}
diff --git a/pyproject.toml b/pyproject.toml
index 9699d0312..4f2c68875 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "repowise"
-version = "0.2.3"
+version = "0.3.0"
description = "Codebase intelligence for developers and AI — generates and maintains a structured wiki for any codebase"
readme = "README.md"
requires-python = ">=3.11"
@@ -87,6 +87,9 @@ postgres = [
"pgvector>=0.3,<1",
"asyncpg>=0.29,<1",
]
+graph-extra = [
+ "graspologic>=3.4,<4",
+]
dev = [
"pytest>=8,<9",
"pytest-asyncio>=0.23,<1",
@@ -125,11 +128,14 @@ packages = [
"repowise.core.generation.editor_files",
"repowise.core.ingestion",
"repowise.core.ingestion.parsers",
+ "repowise.core.ingestion.dynamic_hints",
"repowise.core.pipeline",
"repowise.core.persistence",
"repowise.core.providers",
"repowise.core.providers.llm",
"repowise.core.providers.embedding",
+ "repowise.core.workspace",
+ "repowise.core.workspace.extractors",
# cli
"repowise.cli",
"repowise.cli.commands",
diff --git a/scripts/validate_quality.py b/scripts/validate_quality.py
new file mode 100644
index 000000000..19a3d5060
--- /dev/null
+++ b/scripts/validate_quality.py
@@ -0,0 +1,195 @@
+"""Validate core pipeline quality improvements.
+
+Run against any repo to check:
+ 1. Call resolution — no cross-language edges, no builtin calls
+ 2. Heritage — no builtin parents (Exception, Object, etc.)
+ 3. Community detection — no generic labels, test/prod separation
+ 4. Execution flows — no demo/test entry points, reasonable depth
+
+Usage:
+ python scripts/validate_quality.py <repo_path>
+ python scripts/validate_quality.py .
+ python scripts/validate_quality.py test-repos/microdot
+"""
+
+from __future__ import annotations
+
+import sys
+from collections import Counter
+from pathlib import Path
+
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+from repowise.core.ingestion.language_data import BUILTIN_CALLS, BUILTIN_PARENTS, get_builtin_calls
+
+
+def main() -> None:
+ repo_path = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
+ print(f"\n{'='*70}")
+ print(f" Validating: {repo_path.name}")
+ print(f"{'='*70}\n")
+
+ # --- Parse ---
+ traverser = FileTraverser(repo_path)
+ parser = ASTParser()
+ parsed_files = []
+ for fi in traverser.traverse():
+ try:
+ pf = parser.parse_file(fi, (repo_path / fi.path).read_bytes())
+ if pf:
+ parsed_files.append(pf)
+ except Exception:
+ pass
+
+ print(f"Parsed {len(parsed_files)} files")
+
+ # --- Check 1: Builtin call filtering ---
+ print(f"\n--- CHECK 1: Builtin Call Filtering ---")
+ total_calls = 0
+ builtin_leaks = []
+ for pf in parsed_files:
+ builtins = get_builtin_calls(pf.file_info.language)
+ for call in pf.calls:
+ total_calls += 1
+ if call.target_name in builtins:
+ builtin_leaks.append(
+ f" {pf.file_info.path}:{call.line} -> {call.target_name}()"
+ )
+ if builtin_leaks:
+ print(f" FAIL: {len(builtin_leaks)} builtin calls leaked through:")
+ for leak in builtin_leaks[:10]:
+ print(leak)
+ else:
+ print(f" PASS: {total_calls} calls extracted, 0 builtins leaked")
+
+ # --- Check 2: Heritage builtin filtering ---
+ print(f"\n--- CHECK 2: Heritage Builtin Filtering ---")
+ total_heritage = 0
+ heritage_leaks = []
+ for pf in parsed_files:
+ parents = BUILTIN_PARENTS.get(pf.file_info.language, frozenset())
+ for h in pf.heritage:
+ total_heritage += 1
+ if h.parent_name in parents:
+ heritage_leaks.append(
+ f" {pf.file_info.path}:{h.line} {h.child_name} -> {h.parent_name}"
+ )
+ if heritage_leaks:
+ print(f" FAIL: {len(heritage_leaks)} builtin parents leaked through:")
+ for leak in heritage_leaks[:10]:
+ print(leak)
+ else:
+ print(f" PASS: {total_heritage} heritage relations, 0 builtin parents leaked")
+
+ # --- Build graph ---
+ builder = GraphBuilder(repo_path)
+ for pf in parsed_files:
+ builder.add_file(pf)
+ graph = builder.build()
+
+ # --- Check 3: Cross-language call edges ---
+ print(f"\n--- CHECK 3: Cross-Language Call Edges ---")
+ cross_lang_edges = []
+ for u, v, d in graph.edges(data=True):
+ if d.get("edge_type") != "calls":
+ continue
+ u_data = graph.nodes.get(u, {})
+ v_data = graph.nodes.get(v, {})
+ u_lang = u_data.get("language")
+ v_lang = v_data.get("language")
+ if u_lang and v_lang and u_lang != v_lang:
+ conf = d.get("confidence", 0)
+ cross_lang_edges.append(f" [{conf:.2f}] {u} -> {v} ({u_lang}->{v_lang})")
+
+ call_edges = sum(1 for _, _, d in graph.edges(data=True) if d.get("edge_type") == "calls")
+ if cross_lang_edges:
+ print(f" WARN: {len(cross_lang_edges)} cross-language call edges (of {call_edges} total):")
+ for edge in cross_lang_edges[:10]:
+ print(edge)
+ else:
+ print(f" PASS: {call_edges} call edges, 0 cross-language")
+
+ # --- Check 4: Community detection quality ---
+ print(f"\n--- CHECK 4: Community Detection ---")
+ cd = builder.community_detection()
+ info = builder.community_info()
+
+ generic_labels = {"packages", "src", "lib", "core", "common", "app", ""}
+ bad_labels = []
+ test_dominated = []
+ for cid, ci in sorted(info.items(), key=lambda x: -x[1].size):
+ if ci.size <= 1:
+ continue
+ if ci.label.lower() in generic_labels or ci.label.startswith("cluster_"):
+ bad_labels.append(f" Community {cid}: label='{ci.label}' size={ci.size}")
+
+ test_count = sum(1 for m in ci.members if "test" in m.lower())
+ prod_count = ci.size - test_count
+ if test_count > prod_count and ci.size > 3:
+ test_dominated.append(
+ f" Community {cid} '{ci.label}': {test_count} test / {prod_count} prod files"
+ )
+
+ total_communities = sum(1 for ci in info.values() if ci.size > 1)
+ print(f" {total_communities} non-singleton communities detected")
+
+ if bad_labels:
+ print(f" WARN: {len(bad_labels)} communities with generic labels:")
+ for bl in bad_labels[:5]:
+ print(bl)
+ else:
+ print(f" PASS: All communities have meaningful labels")
+
+ if test_dominated:
+ print(f" WARN: {len(test_dominated)} test-dominated communities:")
+ for td in test_dominated[:5]:
+ print(td)
+ else:
+ print(f" PASS: No test-dominated communities")
+
+ # Print top 10 communities
+ print(f"\n Top communities:")
+ for cid, ci in sorted(info.items(), key=lambda x: -x[1].size)[:10]:
+ if ci.size <= 1:
+ continue
+ print(f" [{cid}] {ci.label:20s} size={ci.size:3d} cohesion={ci.cohesion:.3f} lang={ci.dominant_language}")
+
+ # --- Check 5: Execution flows ---
+ print(f"\n--- CHECK 5: Execution Flows ---")
+ try:
+ report = builder.execution_flows()
+ if report.flows:
+ print(f" {report.total_entry_points_scored} entry points scored, {report.total_flows} flows traced")
+ for flow in report.flows[:5]:
+ crosses = "CROSSES" if flow.crosses_community else "single"
+ print(f" {flow.entry_point_name:30s} score={flow.entry_point_score:.3f} depth={flow.depth:2d} {crosses} communities={flow.communities_visited}")
+
+ # Check for demo/test entry points
+ bad_entries = [
+ f for f in report.flows
+ if any(x in f.entry_point_id.lower() for x in ("demo", "test", "fixture", "sample", "script"))
+ ]
+ if bad_entries:
+ print(f" WARN: {len(bad_entries)} demo/test/script entry points found")
+ else:
+ print(f" PASS: No demo/test entry points in flows")
+
+ # Check crosses_community
+ crossing = [f for f in report.flows if f.crosses_community]
+ print(f" {len(crossing)}/{len(report.flows)} flows cross community boundaries")
+ else:
+ print(f" No flows detected (may be too few call edges)")
+ except Exception as exc:
+ print(f" ERROR: {exc}")
+
+ # --- Summary ---
+ print(f"\n{'='*70}")
+ issues = len(builtin_leaks) + len(heritage_leaks) + len(cross_lang_edges) + len(bad_labels) + len(test_dominated)
+ if issues == 0:
+ print(" ALL CHECKS PASSED")
+ else:
+ print(f" {issues} issue(s) found — see above")
+ print(f"{'='*70}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/integration/test_ingest_sample_repo.py b/tests/integration/test_ingest_sample_repo.py
index 7c8a5aff6..939f9c4fe 100644
--- a/tests/integration/test_ingest_sample_repo.py
+++ b/tests/integration/test_ingest_sample_repo.py
@@ -213,7 +213,9 @@ class TestIngestSampleRepo:
def test_pagerank_runs(self, ingestion_result) -> None:
builder = ingestion_result["builder"]
pr = builder.pagerank()
- assert len(pr) == ingestion_result["graph"].number_of_nodes()
+ # PageRank operates on the file-level subgraph only
+ file_subgraph = builder.file_subgraph()
+ assert len(pr) == file_subgraph.number_of_nodes()
def test_pagerank_sums_to_one(self, ingestion_result) -> None:
builder = ingestion_result["builder"]
@@ -224,11 +226,115 @@ class TestIngestSampleRepo:
def test_sccs_cover_all_nodes(self, ingestion_result) -> None:
builder = ingestion_result["builder"]
sccs = builder.strongly_connected_components()
- all_nodes = set(ingestion_result["graph"].nodes)
+ # SCCs operate on the file-level subgraph only
+ file_nodes = set(builder.file_subgraph().nodes)
scc_nodes = {n for scc in sccs for n in scc}
- assert scc_nodes == all_nodes
+ assert scc_nodes == file_nodes
def test_betweenness_centrality_runs(self, ingestion_result) -> None:
builder = ingestion_result["builder"]
bc = builder.betweenness_centrality()
- assert len(bc) == ingestion_result["graph"].number_of_nodes()
+ # Betweenness operates on the file-level subgraph only
+ file_subgraph = builder.file_subgraph()
+ assert len(bc) == file_subgraph.number_of_nodes()
+
+ def test_symbol_nodes_exist(self, ingestion_result) -> None:
+ """Verify that the graph contains symbol-level nodes."""
+ graph = ingestion_result["graph"]
+ symbol_nodes = [
+ n for n, d in graph.nodes(data=True) if d.get("node_type") == "symbol"
+ ]
+ assert len(symbol_nodes) > 0, "Graph should contain symbol nodes"
+
+ def test_calls_edges_exist(self, ingestion_result) -> None:
+ """Verify that CALLS edges were resolved between symbol nodes."""
+ graph = ingestion_result["graph"]
+ call_edges = [
+ (u, v) for u, v, d in graph.edges(data=True) if d.get("edge_type") == "calls"
+ ]
+ # The sample repo has functions calling other functions
+ assert len(call_edges) >= 0 # may be 0 for small sample repos
+
+ # ------------------------------------------------------------------
+ # Heritage extraction
+ # ------------------------------------------------------------------
+
+ def test_python_heritage_extracted(self, ingestion_result) -> None:
+ """DivisionByZeroError should have heritage relation to ArithmeticError."""
+ calc_file = next(
+ (
+ p
+ for p in ingestion_result["parsed"]
+ if p.file_info.path.endswith("calculator.py") and "python_pkg" in p.file_info.path
+ ),
+ None,
+ )
+ assert calc_file is not None
+ heritage_names = [(h.child_name, h.parent_name) for h in calc_file.heritage]
+ assert ("DivisionByZeroError", "ArithmeticError") in heritage_names
+
+ def test_python_enum_heritage_extracted(self, ingestion_result) -> None:
+ """Operation should have heritage relation to Enum."""
+ models_file = next(
+ (
+ p
+ for p in ingestion_result["parsed"]
+ if p.file_info.path.endswith("models.py") and "python_pkg" in p.file_info.path
+ ),
+ None,
+ )
+ assert models_file is not None
+ heritage_names = [(h.child_name, h.parent_name) for h in models_file.heritage]
+ # Enum is a Python builtin parent — filtered out by language_data.py
+ assert ("Operation", "Enum") not in heritage_names
+
+ def test_typescript_heritage_extracted(self, ingestion_result) -> None:
+ """Error is a builtin parent — should be filtered out."""
+ client_file = next(
+ (p for p in ingestion_result["parsed"] if p.file_info.path.endswith("client.ts")),
+ None,
+ )
+ assert client_file is not None
+ heritage_names = [(h.child_name, h.parent_name, h.kind) for h in client_file.heritage]
+ # Error is a TS builtin — filtered out by language_data.py
+ assert ("ApiClientError", "Error", "extends") not in heritage_names
+ assert ("ValidationError", "Error", "extends") not in heritage_names
+
+ def test_rust_trait_impl_heritage_extracted(self, ingestion_result) -> None:
+ """Rust std trait impls (Default, Debug, etc.) are filtered as builtins."""
+ calc_file = next(
+ (
+ p
+ for p in ingestion_result["parsed"]
+ if p.file_info.path.endswith("calculator.rs")
+ ),
+ None,
+ )
+ assert calc_file is not None
+ heritage_names = [(h.child_name, h.parent_name, h.kind) for h in calc_file.heritage]
+ # Default is a Rust builtin trait — filtered by language_data.py
+ assert ("Calculator", "Default", "trait_impl") not in heritage_names
+
+ def test_heritage_all_have_valid_kind(self, ingestion_result) -> None:
+ """Every heritage relation must have a valid kind."""
+ valid_kinds = {"extends", "implements", "trait_impl", "mixin"}
+ for p in ingestion_result["parsed"]:
+ for h in p.heritage:
+ assert h.kind in valid_kinds, (
+ f"{p.file_info.path}: invalid heritage kind {h.kind!r}"
+ )
+
+ # ------------------------------------------------------------------
+ # Graph edge types
+ # ------------------------------------------------------------------
+
+ def test_defines_edges_connect_files_to_symbols(self, ingestion_result) -> None:
+ """Verify DEFINES edges link file nodes to their symbols."""
+ graph = ingestion_result["graph"]
+ defines_edges = [
+ (u, v) for u, v, d in graph.edges(data=True) if d.get("edge_type") == "defines"
+ ]
+ assert len(defines_edges) > 0
+ for file_node, sym_node in defines_edges:
+ assert graph.nodes[file_node].get("node_type", "file") == "file"
+ assert graph.nodes[sym_node].get("node_type") == "symbol"
diff --git a/tests/integration/test_mcp.py b/tests/integration/test_mcp.py
index e85d31224..6ad9ebb61 100644
--- a/tests/integration/test_mcp.py
+++ b/tests/integration/test_mcp.py
@@ -376,24 +376,6 @@ async def test_mcp_full_exploration_flow(mcp_env):
assert t["docs"]["file_path"] == "src/data/user_repo.py"
-async def test_mcp_dependency_and_graph_flow(mcp_env):
- """Test dependency path and architecture diagram tools."""
- from repowise.server.mcp_server import (
- get_architecture_diagram,
- get_dependency_path,
- )
-
- # Dependency path from login to models (2 hops)
- path = await get_dependency_path("src/auth/login.py", "src/data/models.py")
- assert path["distance"] == 2
- assert len(path["path"]) == 3
-
- # Architecture diagram
- diagram = await get_architecture_diagram(scope="repo")
- assert "graph TD" in diagram["mermaid_syntax"]
-
-
@pytest.mark.asyncio
async def test_mcp_git_intelligence_flow(mcp_env):
"""Test git intelligence via get_context and get_risk."""
diff --git a/tests/unit/cli/test_workspace_cmd.py b/tests/unit/cli/test_workspace_cmd.py
new file mode 100644
index 000000000..cd99ffa82
--- /dev/null
+++ b/tests/unit/cli/test_workspace_cmd.py
@@ -0,0 +1,454 @@
+"""Unit tests for ``repowise workspace`` command group."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import yaml
+from click.testing import CliRunner
+
+from repowise.cli.main import cli
+
+WORKSPACE_CONFIG_FILENAME = ".repowise-workspace.yaml"
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def runner():
+ return CliRunner()
+
+
+def _write_workspace_config(root: Path, repos: list[dict], default_repo: str | None = None) -> None:
+ """Write a minimal .repowise-workspace.yaml to *root*."""
+ data: dict = {
+ "version": 1,
+ "default_repo": default_repo or (repos[0]["alias"] if repos else None),
+ "repos": repos,
+ }
+ (root / WORKSPACE_CONFIG_FILENAME).write_text(
+ yaml.dump(data, default_flow_style=False),
+ encoding="utf-8",
+ )
+
+
+def _read_workspace_config(root: Path) -> dict:
+ text = (root / WORKSPACE_CONFIG_FILENAME).read_text(encoding="utf-8")
+ return yaml.safe_load(text) or {}
+
+
+def _make_git_repo(path: Path) -> None:
+ """Create a minimal fake git repo at *path*."""
+ path.mkdir(parents=True, exist_ok=True)
+ (path / ".git").mkdir()
+
+
+# ---------------------------------------------------------------------------
+# workspace list
+# ---------------------------------------------------------------------------
+
+
+class TestWorkspaceList:
+ def test_list_shows_repos(self, runner, tmp_path):
+ repo_a = tmp_path / "service-a"
+ repo_b = tmp_path / "service-b"
+ repo_a.mkdir()
+ repo_b.mkdir()
+
+ _write_workspace_config(
+ tmp_path,
+ repos=[
+ {"path": "service-a", "alias": "service-a"},
+ {"path": "service-b", "alias": "service-b"},
+ ],
+ default_repo="service-a",
+ )
+
+ result = runner.invoke(cli, ["workspace", "list", str(tmp_path)])
+ assert result.exit_code == 0
+ assert "service-a" in result.output
+ assert "service-b" in result.output
+
+ def test_list_shows_summary_line(self, runner, tmp_path):
+ repo_a = tmp_path / "repo-a"
+ repo_a.mkdir()
+
+ _write_workspace_config(
+ tmp_path,
+ repos=[{"path": "repo-a", "alias": "repo-a"}],
+ )
+
+ result = runner.invoke(cli, ["workspace", "list", str(tmp_path)])
+ assert result.exit_code == 0
+ # Summary line: "X/Y repos indexed"
+ assert "repos indexed" in result.output
+
+ def test_list_marks_primary_repo(self, runner, tmp_path):
+ repo_a = tmp_path / "main-svc"
+ repo_a.mkdir()
+
+ _write_workspace_config(
+ tmp_path,
+ repos=[{"path": "main-svc", "alias": "main-svc", "is_primary": True}],
+ default_repo="main-svc",
+ )
+
+ result = runner.invoke(cli, ["workspace", "list", str(tmp_path)])
+ assert result.exit_code == 0
+ assert "primary" in result.output
+
+ def test_list_no_workspace_errors(self, runner, tmp_path):
+ result = runner.invoke(cli, ["workspace", "list", str(tmp_path)])
+ # Should exit non-zero or print a helpful error — no workspace found
+ assert result.exit_code != 0 or "No .repowise-workspace.yaml" in result.output
+
+
+# ---------------------------------------------------------------------------
+# workspace add
+# ---------------------------------------------------------------------------
+
+
+class TestWorkspaceAdd:
+ def test_add_new_repo(self, runner, tmp_path):
+ _write_workspace_config(tmp_path, repos=[], default_repo=None)
+ new_repo = tmp_path / "new-service"
+ _make_git_repo(new_repo)
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(
+ cli,
+ ["workspace", "add", str(new_repo)],
+ catch_exceptions=False,
+ )
+
+ assert result.exit_code == 0
+ assert "new-service" in result.output
+
+ cfg = _read_workspace_config(tmp_path)
+ aliases = [r["alias"] for r in cfg.get("repos", [])]
+ assert "new-service" in aliases
+
+ def test_add_with_custom_alias(self, runner, tmp_path):
+ _write_workspace_config(tmp_path, repos=[], default_repo=None)
+ new_repo = tmp_path / "my-long-service-name"
+ _make_git_repo(new_repo)
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(
+ cli,
+ ["workspace", "add", str(new_repo), "--alias", "svc"],
+ catch_exceptions=False,
+ )
+
+ assert result.exit_code == 0
+ cfg = _read_workspace_config(tmp_path)
+ aliases = [r["alias"] for r in cfg.get("repos", [])]
+ assert "svc" in aliases
+
+ def test_add_nonexistent_path_errors(self, runner, tmp_path):
+ _write_workspace_config(tmp_path, repos=[], default_repo=None)
+ bad_path = str(tmp_path / "does-not-exist")
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(cli, ["workspace", "add", bad_path])
+
+ assert result.exit_code != 0
+
+ def test_add_non_git_path_errors(self, runner, tmp_path):
+ _write_workspace_config(tmp_path, repos=[], default_repo=None)
+ plain_dir = tmp_path / "not-a-repo"
+ plain_dir.mkdir()
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(cli, ["workspace", "add", str(plain_dir)])
+
+ assert result.exit_code != 0
+ assert ".git" in result.output
+
+ def test_add_duplicate_alias_errors(self, runner, tmp_path):
+ existing_repo = tmp_path / "svc"
+ existing_repo.mkdir()
+ _write_workspace_config(
+ tmp_path,
+ repos=[{"path": "svc", "alias": "svc"}],
+ )
+ new_repo = tmp_path / "other-svc"
+ _make_git_repo(new_repo)
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(
+ cli,
+ ["workspace", "add", str(new_repo), "--alias", "svc"],
+ )
+
+ assert result.exit_code != 0
+ assert "svc" in result.output
+
+ def test_add_no_workspace_errors(self, runner, tmp_path):
+ # Create a subdirectory that has no workspace config anywhere in its tree
+ isolated = tmp_path / "no-ws"
+ isolated.mkdir()
+ new_repo = isolated / "svc"
+ _make_git_repo(new_repo)
+
+ with runner.isolated_filesystem(temp_dir=str(isolated)):
+ result = runner.invoke(cli, ["workspace", "add", str(new_repo)])
+
+ assert result.exit_code != 0
+
+
+# ---------------------------------------------------------------------------
+# workspace remove
+# ---------------------------------------------------------------------------
+
+
+class TestWorkspaceRemove:
+ def test_remove_existing_repo(self, runner, tmp_path):
+ repo_a = tmp_path / "svc-a"
+ repo_a.mkdir()
+ repo_b = tmp_path / "svc-b"
+ repo_b.mkdir()
+
+ _write_workspace_config(
+ tmp_path,
+ repos=[
+ {"path": "svc-a", "alias": "svc-a"},
+ {"path": "svc-b", "alias": "svc-b"},
+ ],
+ default_repo="svc-a",
+ )
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(
+ cli,
+ ["workspace", "remove", "svc-b"],
+ catch_exceptions=False,
+ )
+
+ assert result.exit_code == 0
+ cfg = _read_workspace_config(tmp_path)
+ aliases = [r["alias"] for r in cfg.get("repos", [])]
+ assert "svc-b" not in aliases
+ assert "svc-a" in aliases
+
+ def test_remove_default_repo_shows_warning(self, runner, tmp_path):
+ repo_a = tmp_path / "svc-a"
+ repo_a.mkdir()
+ repo_b = tmp_path / "svc-b"
+ repo_b.mkdir()
+
+ _write_workspace_config(
+ tmp_path,
+ repos=[
+ {"path": "svc-a", "alias": "svc-a"},
+ {"path": "svc-b", "alias": "svc-b"},
+ ],
+ default_repo="svc-a",
+ )
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(
+ cli,
+ ["workspace", "remove", "svc-a"],
+ catch_exceptions=False,
+ )
+
+ assert result.exit_code == 0
+ # Should mention the reassignment
+ assert "default" in result.output.lower() or "Note" in result.output
+
+ def test_remove_preserves_repowise_dir(self, runner, tmp_path):
+ repo_a = tmp_path / "svc-a"
+ repo_a.mkdir()
+ repowise_dir = repo_a / ".repowise"
+ repowise_dir.mkdir()
+ sentinel = repowise_dir / "wiki.db"
+ sentinel.write_text("data")
+
+ _write_workspace_config(
+ tmp_path,
+ repos=[{"path": "svc-a", "alias": "svc-a"}],
+ )
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ runner.invoke(cli, ["workspace", "remove", "svc-a"])
+
+ # Indexed data must still exist
+ assert sentinel.exists()
+
+ def test_remove_invalid_alias_errors(self, runner, tmp_path):
+ _write_workspace_config(
+ tmp_path,
+ repos=[{"path": "svc-a", "alias": "svc-a"}],
+ )
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(cli, ["workspace", "remove", "no-such-repo"])
+
+ assert result.exit_code != 0
+ assert "no-such-repo" in result.output
+
+ def test_remove_no_workspace_errors(self, runner, tmp_path):
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(cli, ["workspace", "remove", "svc"])
+
+ assert result.exit_code != 0
+
+
+# ---------------------------------------------------------------------------
+# workspace scan
+# ---------------------------------------------------------------------------
+
+
+class TestWorkspaceScan:
+ def test_scan_discovers_new_repos(self, runner, tmp_path):
+ # Workspace exists but has no repos registered
+ _write_workspace_config(tmp_path, repos=[], default_repo=None)
+
+ # Create a git repo inside the workspace root
+ new_repo = tmp_path / "discovered-svc"
+ _make_git_repo(new_repo)
+
+ result = runner.invoke(
+ cli,
+ ["workspace", "scan", str(tmp_path), "--yes"],
+ catch_exceptions=False,
+ )
+
+ assert result.exit_code == 0
+ assert "discovered-svc" in result.output
+
+ cfg = _read_workspace_config(tmp_path)
+ aliases = [r["alias"] for r in cfg.get("repos", [])]
+ assert "discovered-svc" in aliases
+
+ def test_scan_skips_already_registered(self, runner, tmp_path):
+ existing = tmp_path / "existing-svc"
+ _make_git_repo(existing)
+ _write_workspace_config(
+ tmp_path,
+ repos=[{"path": "existing-svc", "alias": "existing-svc"}],
+ )
+
+ result = runner.invoke(
+ cli,
+ ["workspace", "scan", str(tmp_path)],
+ catch_exceptions=False,
+ )
+
+ assert result.exit_code == 0
+ assert "No new repositories" in result.output
+
+ def test_scan_prompts_when_no_yes_flag(self, runner, tmp_path):
+ _write_workspace_config(tmp_path, repos=[], default_repo=None)
+ new_repo = tmp_path / "new-svc"
+ _make_git_repo(new_repo)
+
+ # Answer "n" to the prompt
+ result = runner.invoke(
+ cli,
+ ["workspace", "scan", str(tmp_path)],
+ input="n\n",
+ catch_exceptions=False,
+ )
+
+ assert result.exit_code == 0
+ cfg = _read_workspace_config(tmp_path)
+ aliases = [r["alias"] for r in cfg.get("repos", [])]
+ assert "new-svc" not in aliases
+
+ def test_scan_no_workspace_errors(self, runner, tmp_path):
+ result = runner.invoke(cli, ["workspace", "scan", str(tmp_path)])
+ assert result.exit_code != 0
+
+
+# ---------------------------------------------------------------------------
+# workspace set-default
+# ---------------------------------------------------------------------------
+
+
+class TestWorkspaceSetDefault:
+ def test_set_default_changes_primary(self, runner, tmp_path):
+ _write_workspace_config(
+ tmp_path,
+ repos=[
+ {"path": "svc-a", "alias": "svc-a", "is_primary": True},
+ {"path": "svc-b", "alias": "svc-b"},
+ ],
+ default_repo="svc-a",
+ )
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(
+ cli,
+ ["workspace", "set-default", "svc-b"],
+ catch_exceptions=False,
+ )
+
+ assert result.exit_code == 0
+ assert "svc-b" in result.output
+
+ cfg = _read_workspace_config(tmp_path)
+ assert cfg["default_repo"] == "svc-b"
+
+ # is_primary flag should be set only on svc-b
+ by_alias = {r["alias"]: r for r in cfg["repos"]}
+ assert by_alias["svc-b"].get("is_primary") is True
+ assert not by_alias["svc-a"].get("is_primary", False)
+
+ def test_set_default_invalid_alias_errors(self, runner, tmp_path):
+ _write_workspace_config(
+ tmp_path,
+ repos=[{"path": "svc-a", "alias": "svc-a"}],
+ )
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(cli, ["workspace", "set-default", "nonexistent"])
+
+ assert result.exit_code != 0
+ assert "nonexistent" in result.output
+
+ def test_set_default_no_workspace_errors(self, runner, tmp_path):
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ result = runner.invoke(cli, ["workspace", "set-default", "svc-a"])
+
+ assert result.exit_code != 0
+
+
+# ---------------------------------------------------------------------------
+# Help smoke tests
+# ---------------------------------------------------------------------------
+
+
+class TestWorkspaceHelp:
+ def test_workspace_help(self, runner):
+ result = runner.invoke(cli, ["workspace", "--help"])
+ assert result.exit_code == 0
+ assert "workspace" in result.output
+
+ def test_workspace_list_help(self, runner):
+ result = runner.invoke(cli, ["workspace", "list", "--help"])
+ assert result.exit_code == 0
+
+ def test_workspace_add_help(self, runner):
+ result = runner.invoke(cli, ["workspace", "add", "--help"])
+ assert result.exit_code == 0
+ assert "--alias" in result.output
+ assert "--index" in result.output
+
+ def test_workspace_remove_help(self, runner):
+ result = runner.invoke(cli, ["workspace", "remove", "--help"])
+ assert result.exit_code == 0
+
+ def test_workspace_scan_help(self, runner):
+ result = runner.invoke(cli, ["workspace", "scan", "--help"])
+ assert result.exit_code == 0
+ assert "--yes" in result.output
+
+ def test_workspace_set_default_help(self, runner):
+ result = runner.invoke(cli, ["workspace", "set-default", "--help"])
+ assert result.exit_code == 0
diff --git a/tests/unit/generation/test_workspace_claude_md.py b/tests/unit/generation/test_workspace_claude_md.py
new file mode 100644
index 000000000..b7cc60caa
--- /dev/null
+++ b/tests/unit/generation/test_workspace_claude_md.py
@@ -0,0 +1,397 @@
+"""Unit tests for WorkspaceClaudeMdGenerator and WorkspaceEditorFileData."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.generation.editor_files.claude_md import WorkspaceClaudeMdGenerator
+from repowise.core.generation.editor_files.data import (
+ WorkspaceEditorFileData,
+ WorkspaceRepoSummary,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_repo(
+ alias: str = "backend",
+ is_primary: bool = False,
+ file_count: int = 42,
+ symbol_count: int = 300,
+ hotspot_count: int = 3,
+ entry_points: list[str] | None = None,
+) -> WorkspaceRepoSummary:
+ return WorkspaceRepoSummary(
+ alias=alias,
+ is_primary=is_primary,
+ file_count=file_count,
+ symbol_count=symbol_count,
+ hotspot_count=hotspot_count,
+ entry_points=entry_points or [],
+ )
+
+
+def _make_data(
+ workspace_name: str = "my-workspace",
+ workspace_root: str = "/tmp/my-workspace",
+ repos: list[WorkspaceRepoSummary] | None = None,
+ default_repo: str = "backend",
+ co_changes: list[dict] | None = None,
+ package_deps: list[dict] | None = None,
+ contract_links: list[dict] | None = None,
+ contracts_by_type: dict[str, int] | None = None,
+) -> WorkspaceEditorFileData:
+ return WorkspaceEditorFileData(
+ workspace_name=workspace_name,
+ workspace_root=workspace_root,
+ repos=repos if repos is not None else [_make_repo(is_primary=True)],
+ default_repo=default_repo,
+ co_changes=co_changes or [],
+ package_deps=package_deps or [],
+ contract_links=contract_links or [],
+ contracts_by_type=contracts_by_type or {},
+ )
+
+
+def gen() -> WorkspaceClaudeMdGenerator:
+ return WorkspaceClaudeMdGenerator()
+
+
+# ---------------------------------------------------------------------------
+# Template rendering — basic structure
+# ---------------------------------------------------------------------------
+
+
+def test_render_returns_non_empty_string(gen):
+ result = gen.render(_make_data())
+ assert isinstance(result, str)
+ assert len(result) > 0
+
+
+def test_render_contains_workspace_name(gen):
+ result = gen.render(_make_data(workspace_name="acme-ws"))
+ assert "acme-ws" in result
+
+
+def test_render_contains_repo_alias(gen):
+ repos = [_make_repo(alias="frontend")]
+ result = gen.render(_make_data(repos=repos, default_repo="frontend"))
+ assert "frontend" in result
+
+
+def test_render_contains_repo_table_headers(gen):
+ result = gen.render(_make_data())
+ assert "Files" in result
+ assert "Symbols" in result
+ assert "Hotspots" in result
+
+
+def test_render_contains_file_and_symbol_counts(gen):
+ repos = [_make_repo(alias="svc", file_count=99, symbol_count=512)]
+ result = gen.render(_make_data(repos=repos, default_repo="svc"))
+ assert "99" in result
+ assert "512" in result
+
+
+def test_render_marks_default_repo(gen):
+ repos = [_make_repo(alias="api"), _make_repo(alias="worker")]
+ result = gen.render(_make_data(repos=repos, default_repo="api"))
+ assert "default" in result
+
+
+def test_render_contains_mcp_tools_section(gen):
+ result = gen.render(_make_data())
+ assert "get_overview" in result
+ assert "get_context" in result
+ assert "search_codebase" in result
+
+
+def test_render_contains_workspace_query_note(gen):
+ result = gen.render(_make_data())
+ # The template mentions using repo="all" for workspace-wide queries
+ assert 'repo="all"' in result
+
+
+# ---------------------------------------------------------------------------
+# Template rendering — optional sections
+# ---------------------------------------------------------------------------
+
+
+def test_render_skips_contract_section_when_empty(gen):
+ result = gen.render(_make_data(contract_links=[]))
+ assert "Cross-Repo API Contracts" not in result
+
+
+def test_render_includes_contract_section_when_present(gen):
+ links = [
+ {
+ "provider_repo": "api",
+ "provider_file": "routes/users.py",
+ "consumer_repo": "frontend",
+ "consumer_file": "api/client.ts",
+ "contract_type": "http",
+ "contract_id": "GET::/api/users",
+ }
+ ]
+ result = gen.render(_make_data(contract_links=links))
+ assert "Cross-Repo API Contracts" in result
+ assert "GET::/api/users" in result
+ assert "api" in result
+ assert "frontend" in result
+
+
+def test_render_skips_co_changes_section_when_empty(gen):
+ result = gen.render(_make_data(co_changes=[]))
+ assert "Cross-Repo Co-Changes" not in result
+
+
+def test_render_includes_co_changes_section_when_present(gen):
+ cc = [
+ {
+ "source_repo": "api",
+ "source_file": "models/user.py",
+ "target_repo": "worker",
+ "target_file": "tasks/sync.py",
+ "frequency": 7,
+ }
+ ]
+ result = gen.render(_make_data(co_changes=cc))
+ assert "Cross-Repo Co-Changes" in result
+ assert "models/user.py" in result
+ assert "tasks/sync.py" in result
+ assert "7" in result
+
+
+def test_render_limits_co_changes_to_ten(gen):
+ # Generate 15 co-change entries
+ cc = [
+ {
+ "source_repo": "a",
+ "source_file": f"file_{i}.py",
+ "target_repo": "b",
+ "target_file": f"other_{i}.py",
+ "frequency": i,
+ }
+ for i in range(15)
+ ]
+ result = gen.render(_make_data(co_changes=cc))
+ # Only the first 10 should appear (template uses co_changes[:10])
+ assert result.count("source_repo") == 0 # field names not in output
+ # Count occurrences of "file_" pattern — at most 10
+ import re
+ matches = re.findall(r"file_\d+\.py", result)
+ assert len(matches) <= 10
+
+
+def test_render_skips_package_deps_when_empty(gen):
+ result = gen.render(_make_data(package_deps=[]))
+ assert "Package Dependencies" not in result
+
+
+def test_render_includes_package_deps_when_present(gen):
+ deps = [{"source_repo": "frontend", "target_repo": "shared-lib", "kind": "npm_local_path"}]
+ result = gen.render(_make_data(package_deps=deps))
+ assert "Package Dependencies" in result
+ assert "frontend" in result
+ assert "shared-lib" in result
+ assert "npm_local_path" in result
+
+
+def test_render_includes_entry_points_per_repo(gen):
+ repos = [
+ _make_repo(
+ alias="api",
+ entry_points=["src/api/main.py", "src/api/server.py"],
+ )
+ ]
+ result = gen.render(_make_data(repos=repos, default_repo="api"))
+ assert "src/api/main.py" in result
+ assert "src/api/server.py" in result
+
+
+def test_render_shows_placeholder_when_no_entry_points(gen):
+ repos = [_make_repo(alias="svc", entry_points=[])]
+ result = gen.render(_make_data(repos=repos, default_repo="svc"))
+ assert "No entry points indexed" in result
+
+
+# ---------------------------------------------------------------------------
+# File writing — path and directory
+# ---------------------------------------------------------------------------
+
+
+def test_write_creates_dot_claude_directory(gen, tmp_path):
+ data = _make_data()
+ gen.write(tmp_path, data)
+ assert (tmp_path / ".claude").is_dir()
+
+
+def test_write_creates_claude_md_at_workspace_root(gen, tmp_path):
+ data = _make_data()
+ written = gen.write(tmp_path, data)
+ assert written == tmp_path / ".claude" / "CLAUDE.md"
+ assert written.exists()
+
+
+def test_write_returns_path(gen, tmp_path):
+ result = gen.write(tmp_path, _make_data())
+ assert result == tmp_path / ".claude" / "CLAUDE.md"
+
+
+def test_write_content_contains_markers(gen, tmp_path):
+ gen.write(tmp_path, _make_data())
+ content = (tmp_path / ".claude" / "CLAUDE.md").read_text(encoding="utf-8")
+ assert "<!-- REPOWISE:START" in content
+ assert "<!-- REPOWISE:END -->" in content
+
+
+def test_write_content_contains_user_placeholder_on_new_file(gen, tmp_path):
+ gen.write(tmp_path, _make_data())
+ content = (tmp_path / ".claude" / "CLAUDE.md").read_text(encoding="utf-8")
+ assert "Workspace-level instructions" in content
+
+
+def test_write_creates_parent_dirs_if_missing(gen, tmp_path):
+ deep_root = tmp_path / "a" / "b" / "c"
+ deep_root.mkdir(parents=True)
+ written = gen.write(deep_root, _make_data())
+ assert written.exists()
+
+
+# ---------------------------------------------------------------------------
+# Marker-based merge — preserves user content
+# ---------------------------------------------------------------------------
+
+
+def test_write_preserves_user_content_above_markers(gen, tmp_path):
+ target = tmp_path / ".claude" / "CLAUDE.md"
+ target.parent.mkdir(parents=True, exist_ok=True)
+ marker_start = gen.MARKER_START_FMT.format(tag=gen.marker_tag)
+ marker_end = gen.MARKER_END_FMT.format(tag=gen.marker_tag)
+ old_managed_sentinel = "OLD_MANAGED_CONTENT_SENTINEL_ABC"
+ existing = (
+ "# My workspace notes\n\nDo not erase me!\n\n"
+ f"{marker_start}\n{old_managed_sentinel}\n{marker_end}\n"
+ )
+ target.write_text(existing, encoding="utf-8")
+
+ gen.write(tmp_path, _make_data())
+ new_content = target.read_text(encoding="utf-8")
+
+ assert "Do not erase me!" in new_content
+ assert old_managed_sentinel not in new_content
+ assert "my-workspace" in new_content
+
+
+def test_write_appends_when_no_markers_exist(gen, tmp_path):
+ target = tmp_path / ".claude" / "CLAUDE.md"
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text("# Pre-existing file\n\nUser notes here.\n", encoding="utf-8")
+
+ gen.write(tmp_path, _make_data())
+ content = target.read_text(encoding="utf-8")
+
+ assert "Pre-existing file" in content
+ assert "User notes here." in content
+ assert "<!-- REPOWISE:START" in content
+
+
+def test_write_replaces_only_managed_section(gen, tmp_path):
+ target = tmp_path / ".claude" / "CLAUDE.md"
+ target.parent.mkdir(parents=True, exist_ok=True)
+ marker_start = gen.MARKER_START_FMT.format(tag=gen.marker_tag)
+ marker_end = gen.MARKER_END_FMT.format(tag=gen.marker_tag)
+ old_managed_sentinel = "OLD_MANAGED_CONTENT_SENTINEL_XYZ"
+ target.write_text(
+ f"# Keep this\n\n{marker_start}\n{old_managed_sentinel}\n{marker_end}\n# Also keep this\n",
+ encoding="utf-8",
+ )
+
+ gen.write(tmp_path, _make_data())
+ content = target.read_text(encoding="utf-8")
+
+ assert "Keep this" in content
+ assert old_managed_sentinel not in content
+ assert content.count("<!-- REPOWISE:START") == 1
+ assert content.count("<!-- REPOWISE:END -->") == 1
+
+
+def test_write_is_idempotent(gen, tmp_path):
+ data = _make_data()
+ gen.write(tmp_path, data)
+ first = (tmp_path / ".claude" / "CLAUDE.md").read_text(encoding="utf-8")
+
+ gen.write(tmp_path, data)
+ second = (tmp_path / ".claude" / "CLAUDE.md").read_text(encoding="utf-8")
+
+ assert first == second
+
+
+# ---------------------------------------------------------------------------
+# Edge cases — empty optional fields
+# ---------------------------------------------------------------------------
+
+
+def test_render_with_all_empty_optional_fields_does_not_crash(gen):
+ data = WorkspaceEditorFileData(
+ workspace_name="empty-ws",
+ workspace_root="/tmp/empty-ws",
+ repos=[],
+ default_repo="",
+ co_changes=[],
+ package_deps=[],
+ contract_links=[],
+ contracts_by_type={},
+ )
+ result = gen.render(data)
+ assert isinstance(result, str)
+ assert "empty-ws" in result
+
+
+def test_render_with_single_repo_no_cross_repo_data(gen):
+ data = _make_data(
+ repos=[_make_repo(alias="monolith", is_primary=True)],
+ default_repo="monolith",
+ co_changes=[],
+ package_deps=[],
+ contract_links=[],
+ )
+ result = gen.render(data)
+ assert "monolith" in result
+ assert "Cross-Repo API Contracts" not in result
+ assert "Cross-Repo Co-Changes" not in result
+ assert "Package Dependencies" not in result
+
+
+def test_render_multiple_repos_all_appear_in_table(gen):
+ repos = [
+ _make_repo(alias="api", file_count=10, symbol_count=100),
+ _make_repo(alias="worker", file_count=5, symbol_count=50),
+ _make_repo(alias="frontend", file_count=80, symbol_count=400),
+ ]
+ result = gen.render(_make_data(repos=repos, default_repo="api"))
+ assert "api" in result
+ assert "worker" in result
+ assert "frontend" in result
+
+
+def test_contracts_by_type_shown_when_present(gen):
+ links = [
+ {
+ "provider_repo": "api",
+ "provider_file": "routes.py",
+ "consumer_repo": "mobile",
+ "consumer_file": "client.ts",
+ "contract_type": "http",
+ "contract_id": "GET::/v1/ping",
+ }
+ ]
+ result = gen.render(
+ _make_data(contract_links=links, contracts_by_type={"http": 3, "grpc": 1})
+ )
+ assert "http: 3" in result
+ assert "grpc: 1" in result
diff --git a/tests/unit/server/test_enrichment_contracts.py b/tests/unit/server/test_enrichment_contracts.py
new file mode 100644
index 000000000..4a5349724
--- /dev/null
+++ b/tests/unit/server/test_enrichment_contracts.py
@@ -0,0 +1,134 @@
+"""Tests for CrossRepoEnricher contract loading (Phase 4)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+
+def _write_json(path: Path, data: dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(data), encoding="utf-8")
+
+
+def contracts_json(tmp_path: Path) -> Path:
+ """Write a minimal contracts.json and return its path."""
+ path = tmp_path / "contracts.json"
+ _write_json(path, {
+ "version": 1,
+ "generated_at": "2026-04-12T12:00:00Z",
+ "contracts": [
+ {
+ "repo": "backend",
+ "contract_id": "http::GET::/api/users",
+ "contract_type": "http",
+ "role": "provider",
+ "file_path": "routes.py",
+ "symbol_name": "get_users",
+ "confidence": 0.85,
+ },
+ {
+ "repo": "frontend",
+ "contract_id": "http::GET::/api/users",
+ "contract_type": "http",
+ "role": "consumer",
+ "file_path": "client.ts",
+ "symbol_name": "fetchUsers",
+ "confidence": 0.75,
+ },
+ ],
+ "contract_links": [
+ {
+ "contract_id": "http::GET::/api/users",
+ "contract_type": "http",
+ "match_type": "exact",
+ "confidence": 0.75,
+ "provider_repo": "backend",
+ "provider_file": "routes.py",
+ "provider_symbol": "get_users",
+ "consumer_repo": "frontend",
+ "consumer_file": "client.ts",
+ "consumer_symbol": "fetchUsers",
+ },
+ ],
+ })
+ return path
+
+
+def empty_cross_repo(tmp_path: Path) -> Path:
+ """Empty cross_repo_edges.json (no co-changes or deps)."""
+ path = tmp_path / "cross_repo_edges.json"
+ _write_json(path, {"version": 1, "co_changes": [], "package_deps": []})
+ return path
+
+
+class TestEnricherContractLoading:
+ def test_no_contracts_path(self, empty_cross_repo: Path) -> None:
+ enricher = CrossRepoEnricher(empty_cross_repo)
+ assert enricher.has_contract_data is False
+
+ def test_missing_contracts_file(self, empty_cross_repo: Path, tmp_path: Path) -> None:
+ enricher = CrossRepoEnricher(
+ empty_cross_repo,
+ contracts_path=tmp_path / "nonexistent.json",
+ )
+ assert enricher.has_contract_data is False
+
+ def test_loads_contract_links(
+ self, empty_cross_repo: Path, contracts_json: Path
+ ) -> None:
+ enricher = CrossRepoEnricher(empty_cross_repo, contracts_path=contracts_json)
+ assert enricher.has_contract_data is True
+ assert enricher.has_data is True
+
+ def test_provider_index(
+ self, empty_cross_repo: Path, contracts_json: Path
+ ) -> None:
+ enricher = CrossRepoEnricher(empty_cross_repo, contracts_path=contracts_json)
+ links = enricher.get_contract_links_as_provider("backend", "routes.py")
+ assert len(links) == 1
+ assert links[0]["consumer_repo"] == "frontend"
+
+ def test_consumer_index(
+ self, empty_cross_repo: Path, contracts_json: Path
+ ) -> None:
+ enricher = CrossRepoEnricher(empty_cross_repo, contracts_path=contracts_json)
+ links = enricher.get_contract_links_as_consumer("frontend", "client.ts")
+ assert len(links) == 1
+ assert links[0]["provider_repo"] == "backend"
+
+ def test_missing_file_returns_empty(
+ self, empty_cross_repo: Path, contracts_json: Path
+ ) -> None:
+ enricher = CrossRepoEnricher(empty_cross_repo, contracts_path=contracts_json)
+ assert enricher.get_contract_links_as_provider("backend", "nonexistent.py") == []
+ assert enricher.get_contract_links_as_consumer("frontend", "nonexistent.ts") == []
+
+ def test_contract_summary(
+ self, empty_cross_repo: Path, contracts_json: Path
+ ) -> None:
+ enricher = CrossRepoEnricher(empty_cross_repo, contracts_path=contracts_json)
+ summary = enricher.get_contract_summary()
+ assert summary["total_contracts"] == 2
+ assert summary["total_links"] == 1
+ assert summary["by_type"]["http"] == 2
+
+ def test_affected_repos_includes_contracts(
+ self, empty_cross_repo: Path, contracts_json: Path
+ ) -> None:
+ enricher = CrossRepoEnricher(empty_cross_repo, contracts_path=contracts_json)
+ affected = enricher.get_affected_repos("backend", "routes.py")
+ assert "frontend" in affected
+
+ def test_has_data_with_only_contracts(self, tmp_path: Path, contracts_json: Path) -> None:
+ # No cross_repo_edges.json at all
+ missing_path = tmp_path / "missing_cross_repo.json"
+ enricher = CrossRepoEnricher(missing_path, contracts_path=contracts_json)
+ assert enricher.has_data is True
+ assert enricher.has_contract_data is True
diff --git a/tests/unit/server/test_mcp.py b/tests/unit/server/test_mcp.py
index bd0cb75ee..a35c84bae 100644
--- a/tests/unit/server/test_mcp.py
+++ b/tests/unit/server/test_mcp.py
@@ -563,12 +563,14 @@ async def setup_mcp(factory, fts, vector_store, populated_db):
yield populated_db
- # Reset globals
+ # Reset globals (including workspace state)
mcp_mod._session_factory = None
mcp_mod._fts = None
mcp_mod._vector_store = None
mcp_mod._decision_store = None
mcp_mod._repo_path = None
+ mcp_mod._registry = None
+ mcp_mod._workspace_root = None
# ---- Tool 1: get_overview ----
@@ -581,8 +583,7 @@ async def test_get_overview(setup_mcp):
result = await get_overview()
assert result["title"] == "Test Repo Overview"
assert "comprehensive test" in result["content_md"]
- assert result["architecture_diagram_mermaid"] is not None
- assert "graph TD" in result["architecture_diagram_mermaid"]
+ assert "architecture_diagram_mermaid" not in result # removed: not useful for agents
assert len(result["key_modules"]) == 2
assert any(m["name"] == "Auth Module" for m in result["key_modules"])
assert "src/auth/service.py" in result["entry_points"]
@@ -1101,89 +1102,7 @@ async def test_search_codebase(setup_mcp):
assert len(result["results"]) >= 1
-# ---- Tool 6: get_architecture_diagram ----
-
-
-async def test_get_architecture_diagram_repo(setup_mcp):
- from repowise.server.mcp_server import get_architecture_diagram
-
- result = await get_architecture_diagram(scope="repo")
- assert result["diagram_type"] in ("flowchart", "auto")
- assert "mermaid_syntax" in result
- assert "graph TD" in result["mermaid_syntax"]
-
-
-async def test_get_architecture_diagram_module(setup_mcp):
- from repowise.server.mcp_server import get_architecture_diagram
-
- result = await get_architecture_diagram(scope="module", path="src/auth")
- assert "mermaid_syntax" in result
- assert result["description"]
-
-
-# ---- Tool 7: get_dependency_path ----
-
-
-async def test_get_dependency_path(setup_mcp):
- from repowise.server.mcp_server import get_dependency_path
-
- result = await get_dependency_path("src/auth/service.py", "src/db/models.py")
- assert result["distance"] == 1
- assert len(result["path"]) == 2
-
-
-async def test_get_dependency_path_multi_hop(setup_mcp):
- from repowise.server.mcp_server import get_dependency_path
-
- result = await get_dependency_path("src/auth/middleware.py", "src/db/models.py")
- assert result["distance"] == 2
- assert len(result["path"]) == 3
-
-
-async def test_get_dependency_path_no_path(setup_mcp):
- from repowise.server.mcp_server import get_dependency_path
-
- # Reverse direction — no path from models to middleware
- result = await get_dependency_path("src/db/models.py", "src/auth/middleware.py")
- assert result["distance"] == -1
- assert result["path"] == []
-
- # Visual context should be present
- ctx = result["visual_context"]
- assert ctx is not None
-
- # Reverse path exists (middleware -> service -> models)
- assert ctx["reverse_path"]["exists"] is True
-
- # Nearest common ancestor should be service.py (connects both via undirected)
- ancestors = ctx["nearest_common_ancestors"]
- assert len(ancestors) >= 1
- assert ancestors[0]["node"] == "src/auth/service.py"
-
- # Community analysis — models is community 2, middleware is community 1
- assert ctx["community"]["same_community"] is False
-
- # Not disconnected — they are reachable in undirected graph
- assert ctx["disconnected"] is False
- assert "suggestion" in ctx
-
-
-async def test_get_dependency_path_node_not_found(setup_mcp):
- from repowise.server.mcp_server import get_dependency_path
-
- result = await get_dependency_path("nonexistent.py", "src/auth/service.py")
- assert result["distance"] == -1
- assert result["path"] == []
- assert "not found" in result["explanation"]
-
-
-# ---- Tool 8: get_dead_code ----
+# ---- Tool 6: get_dead_code ----
@pytest.mark.asyncio
@@ -1278,157 +1197,6 @@ async def test_get_dead_code_group_by_owner(setup_mcp):
# ---- MCP config generation ----
-# ---- Tool 9: update_decision_records ----
-
-
-async def test_update_decision_records_create(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(
- action="create",
- title="Use Redis for caching",
- context="Need distributed caching",
- decision="Use Redis as the caching layer",
- rationale="Mature, fast, supports pub/sub",
- alternatives=["Memcached", "In-memory only"],
- consequences=["Requires Redis infrastructure"],
- affected_files=["src/cache/client.py"],
- affected_modules=["src/cache"],
- tags=["performance", "infra"],
- )
- assert result["action"] == "created"
- dec = result["decision"]
- assert dec["title"] == "Use Redis for caching"
- assert dec["source"] == "mcp_tool"
- assert dec["confidence"] == 1.0
- assert dec["status"] == "proposed"
- assert "Memcached" in dec["alternatives"]
-
-
-async def test_update_decision_records_create_missing_title(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(action="create")
- assert "error" in result
- assert "title" in result["error"]
-
-
-async def test_update_decision_records_get(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(action="get", decision_id="dec1")
- assert result["action"] == "get"
- assert result["decision"]["title"] == "Use JWT for authentication"
-
-
-async def test_update_decision_records_get_not_found(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(action="get", decision_id="nonexistent")
- assert "error" in result
- assert "not found" in result["error"]
-
-
-async def test_update_decision_records_list(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(action="list")
- assert result["action"] == "list"
- assert result["count"] >= 2
- titles = {d["title"] for d in result["decisions"]}
- assert "Use JWT for authentication" in titles
- assert "SQLAlchemy as ORM" in titles
-
-
-async def test_update_decision_records_list_with_filter(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(action="list", filter_source="readme_mining")
- assert result["action"] == "list"
- assert all(d["source"] == "readme_mining" for d in result["decisions"])
-
-
-async def test_update_decision_records_update(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(
- action="update",
- decision_id="dec1",
- rationale="Updated: stateless and JWT is industry standard",
- tags=["auth", "security", "api"],
- )
- assert result["action"] == "updated"
- dec = result["decision"]
- assert "industry standard" in dec["rationale"]
- assert "api" in dec["tags"]
- # Other fields should remain unchanged
- assert dec["title"] == "Use JWT for authentication"
-
-
-async def test_update_decision_records_update_no_fields(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(action="update", decision_id="dec1")
- assert "error" in result
- assert "at least one field" in result["error"]
-
-
-async def test_update_decision_records_update_status(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(
- action="update_status", decision_id="dec1", status="active"
- )
- assert result["action"] == "status_updated"
- assert result["decision"]["status"] == "active"
-
-
-async def test_update_decision_records_update_status_deprecate(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(
- action="update_status",
- decision_id="dec1",
- status="superseded",
- superseded_by="dec2",
- )
- assert result["action"] == "status_updated"
- assert result["decision"]["status"] == "superseded"
- assert result["decision"]["superseded_by"] == "dec2"
-
-
-async def test_update_decision_records_delete(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(action="delete", decision_id="dec2")
- assert result["action"] == "deleted"
- assert result["decision_id"] == "dec2"
-
- # Verify it's gone
- get_result = await update_decision_records(action="get", decision_id="dec2")
- assert "error" in get_result
-
-
-async def test_update_decision_records_invalid_action(setup_mcp):
- from repowise.server.mcp_server import update_decision_records
-
- result = await update_decision_records(action="foo")
- assert "error" in result
- assert "Unknown action" in result["error"]
-
-
def test_generate_mcp_config():
from pathlib import Path
diff --git a/tests/unit/server/test_mcp_workspace.py b/tests/unit/server/test_mcp_workspace.py
new file mode 100644
index 000000000..c3038e089
--- /dev/null
+++ b/tests/unit/server/test_mcp_workspace.py
@@ -0,0 +1,603 @@
+"""Tests for workspace-aware MCP tools.
+
+Uses two in-memory SQLite databases (two repos) to test multi-repo routing,
+``repo="all"`` federated queries, and workspace footer in get_overview.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from datetime import UTC, datetime
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.persistence.database import init_db
+from repowise.core.persistence.models import (
+ DeadCodeFinding,
+ DecisionRecord,
+ GraphNode,
+ Page,
+ Repository,
+)
+from repowise.core.persistence.search import FullTextSearch
+from repowise.core.persistence.vector_store import InMemoryVectorStore
+from repowise.core.providers.embedding.base import MockEmbedder
+from repowise.core.workspace.registry import RepoContext, RepoRegistry
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+_NOW = datetime(2026, 4, 12, 10, 0, 0, tzinfo=UTC)
+
+
+async def _make_repo_context(alias: str, repo_path: str, pages: list, extra_models: list | None = None) -> RepoContext:
+ """Create an in-memory RepoContext with test data."""
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+
+ factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+ async with factory() as session:
+ repo = Repository(
+ id=f"repo-{alias}",
+ name=alias,
+ url=f"https://example.com/{alias}",
+ local_path=repo_path,
+ default_branch="main",
+ settings_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ )
+ session.add(repo)
+ for p in pages:
+ session.add(p)
+ for m in (extra_models or []):
+ session.add(m)
+ await session.commit()
+
+ fts = FullTextSearch(engine)
+ await fts.ensure_index()
+
+ embedder = MockEmbedder()
+ vs = InMemoryVectorStore(embedder=embedder)
+ ds = InMemoryVectorStore(embedder=embedder)
+ ready = asyncio.Event()
+ ready.set()
+
+ return RepoContext(
+ alias=alias,
+ path=__import__("pathlib").Path(repo_path),
+ session_factory=factory,
+ fts=fts,
+ vector_store=vs,
+ decision_store=ds,
+ vector_store_ready=ready,
+ _engine=engine,
+ )
+
+
+class _MockRegistry:
+ """Minimal mock RepoRegistry for testing without real workspace files."""
+
+ def __init__(self, contexts: dict[str, RepoContext], default_alias: str):
+ self._contexts = contexts
+ self._default_alias = default_alias
+ self.workspace_root = __import__("pathlib").Path("/tmp/workspace")
+
+ def get_all_aliases(self) -> list[str]:
+ return list(self._contexts.keys())
+
+ def get_default_alias(self) -> str:
+ return self._default_alias
+
+ def resolve_repo_param(self, repo):
+ if repo is None:
+ return self._default_alias
+ if repo == "all":
+ return self.get_all_aliases()
+ if repo not in self._contexts:
+ raise ValueError(f"Unknown repo '{repo}'. Available: {self.get_all_aliases()}")
+ return repo
+
+ async def get(self, alias: str) -> RepoContext:
+ return self._contexts[alias]
+
+ async def get_default(self) -> RepoContext:
+ return self._contexts[self._default_alias]
+
+ async def close(self):
+ for ctx in self._contexts.values():
+ if ctx._engine:
+ await ctx._engine.dispose()
+
+
+async def workspace_mcp():
+ """Set up a two-repo workspace for MCP testing."""
+ import repowise.server.mcp_server as mcp_mod
+
+ # Create two repo contexts with distinct data
+ backend_ctx = await _make_repo_context(
+ "backend",
+ "/tmp/workspace/backend",
+ pages=[
+ Page(
+ id="repo_overview:backend",
+ repository_id="repo-backend",
+ page_type="repo_overview",
+ title="Backend Overview",
+ content="# Backend\n\nThe API backend service.",
+ target_path="backend",
+ source_hash="abc",
+ model_name="mock",
+ provider_name="mock",
+ generation_level=6,
+ confidence=1.0,
+ freshness_status="fresh",
+ metadata_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ ],
+ extra_models=[
+ GraphNode(
+ id="gn-be-1",
+ repository_id="repo-backend",
+ node_id="src/api/server.py",
+ node_type="file",
+ language="python",
+ symbol_count=5,
+ is_entry_point=True,
+ pagerank=0.8,
+ betweenness=0.5,
+ community_id=1,
+ created_at=_NOW,
+ ),
+ DeadCodeFinding(
+ id="dc-be-1",
+ repository_id="repo-backend",
+ file_path="src/old_handler.py",
+ symbol_name="old_handler",
+ kind="unreachable_file",
+ confidence=0.95,
+ safe_to_delete=True,
+ lines=42,
+ reason="No imports found",
+ evidence_json="[]",
+ ),
+ DecisionRecord(
+ id="dec-be-1",
+ repository_id="repo-backend",
+ title="REST over GraphQL",
+ decision="Use REST for all public APIs",
+ rationale="Mobile client simplicity",
+ status="active",
+ source="cli",
+ affected_files_json='["src/api/server.py"]',
+ affected_modules_json='["api"]',
+ ),
+ ],
+ )
+
+ frontend_ctx = await _make_repo_context(
+ "frontend",
+ "/tmp/workspace/frontend",
+ pages=[
+ Page(
+ id="repo_overview:frontend",
+ repository_id="repo-frontend",
+ page_type="repo_overview",
+ title="Frontend Overview",
+ content="# Frontend\n\nThe React web application.",
+ target_path="frontend",
+ source_hash="def",
+ model_name="mock",
+ provider_name="mock",
+ generation_level=6,
+ confidence=1.0,
+ freshness_status="fresh",
+ metadata_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ ],
+ extra_models=[
+ GraphNode(
+ id="gn-fe-1",
+ repository_id="repo-frontend",
+ node_id="src/App.tsx",
+ node_type="file",
+ language="typescript",
+ symbol_count=3,
+ is_entry_point=True,
+ pagerank=0.7,
+ betweenness=0.4,
+ community_id=1,
+ created_at=_NOW,
+ ),
+ DeadCodeFinding(
+ id="dc-fe-1",
+ repository_id="repo-frontend",
+ file_path="src/legacy/utils.ts",
+ symbol_name="formatLegacy",
+ kind="unused_export",
+ confidence=0.80,
+ safe_to_delete=True,
+ lines=15,
+ reason="No imports found",
+ evidence_json="[]",
+ ),
+ DecisionRecord(
+ id="dec-fe-1",
+ repository_id="repo-frontend",
+ title="React over Vue",
+ decision="Use React for all frontend work",
+ rationale="Team expertise and ecosystem",
+ status="active",
+ source="cli",
+ affected_files_json='["src/App.tsx"]',
+ affected_modules_json='["src"]',
+ ),
+ ],
+ )
+
+ registry = _MockRegistry(
+ contexts={"backend": backend_ctx, "frontend": frontend_ctx},
+ default_alias="backend",
+ )
+
+ # Set workspace state
+ mcp_mod._registry = registry
+ mcp_mod._workspace_root = "/tmp/workspace"
+ mcp_mod._session_factory = backend_ctx.session_factory
+ mcp_mod._fts = backend_ctx.fts
+ mcp_mod._vector_store = backend_ctx.vector_store
+ mcp_mod._decision_store = backend_ctx.decision_store
+ mcp_mod._repo_path = "/tmp/workspace/backend"
+ mcp_mod._vector_store_ready = backend_ctx.vector_store_ready
+
+ yield registry
+
+ # Cleanup
+ await registry.close()
+ mcp_mod._registry = None
+ mcp_mod._workspace_root = None
+ mcp_mod._session_factory = None
+ mcp_mod._fts = None
+ mcp_mod._vector_store = None
+ mcp_mod._decision_store = None
+ mcp_mod._repo_path = None
+ mcp_mod._vector_store_ready = None
+ mcp_mod._cross_repo_enricher = None
+
+
+# ---------------------------------------------------------------------------
+# get_overview — workspace footer
+# ---------------------------------------------------------------------------
+
+
+async def test_get_overview_default_includes_workspace_footer(workspace_mcp):
+ from repowise.server.mcp_server import get_overview
+
+ result = await get_overview()
+ assert result["title"] == "Backend Overview"
+ assert "workspace" in result
+ ws = result["workspace"]
+ assert ws["default_repo"] == "backend"
+ assert "frontend" in ws["other_repos"]
+ assert "hint" in ws
+
+
+async def test_get_overview_specific_repo(workspace_mcp):
+ from repowise.server.mcp_server import get_overview
+
+ result = await get_overview(repo="frontend")
+ assert result["title"] == "Frontend Overview"
+ assert "workspace" in result
+
+
+async def test_get_overview_repo_all(workspace_mcp):
+ from repowise.server.mcp_server import get_overview
+
+ result = await get_overview(repo="all")
+ assert result["workspace"] is True
+ assert result["total_repos"] == 2
+ aliases = [r["alias"] for r in result["repos"]]
+ assert "backend" in aliases
+ assert "frontend" in aliases
+ # Default repo should be marked
+ default_repos = [r for r in result["repos"] if r["is_default"]]
+ assert len(default_repos) == 1
+ assert default_repos[0]["alias"] == "backend"
+
+
+# ---------------------------------------------------------------------------
+# search_codebase — federated search
+# ---------------------------------------------------------------------------
+
+
+async def test_search_repo_all_returns_tagged_results(workspace_mcp):
+ from repowise.server.mcp_server import search_codebase
+
+ # FTS search — both repos should be queried
+ result = await search_codebase(query="overview", repo="all")
+ assert "results" in result
+ # Results may be empty with MockEmbedder + FTS on minimal data,
+ # but the function should not error
+
+
+async def test_search_specific_repo(workspace_mcp):
+ from repowise.server.mcp_server import search_codebase
+
+ result = await search_codebase(query="React", repo="frontend")
+ assert "results" in result
+
+
+# ---------------------------------------------------------------------------
+# get_dead_code — workspace-wide
+# ---------------------------------------------------------------------------
+
+
+async def test_get_dead_code_repo_all(workspace_mcp):
+ from repowise.server.mcp_server import get_dead_code
+
+ result = await get_dead_code(repo="all")
+ assert result.get("workspace") is True or "summary" in result
+ # Should aggregate findings from both repos
+ if "summary" in result:
+ assert result["summary"]["total_findings"] >= 2
+
+
+async def test_get_dead_code_specific_repo(workspace_mcp):
+ from repowise.server.mcp_server import get_dead_code
+
+ result = await get_dead_code(repo="backend")
+ assert "summary" in result or "tiers" in result
+
+
+# ---------------------------------------------------------------------------
+# get_why — cross-repo decisions
+# ---------------------------------------------------------------------------
+
+
+async def test_get_why_repo_all(workspace_mcp):
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why(query="REST", repo="all")
+ # Should search across both repos
+ assert isinstance(result, dict)
+
+
+async def test_get_why_specific_repo(workspace_mcp):
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why(query="React", repo="frontend")
+ assert isinstance(result, dict)
+
+
+# ---------------------------------------------------------------------------
+# Unsupported repo="all" tools
+# ---------------------------------------------------------------------------
+
+
+async def test_unsupported_repo_all_get_context(workspace_mcp):
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(targets=["src/api/server.py"], repo="all")
+ assert "error" in result
+ assert "not supported" in result["error"]
+
+
+# ---------------------------------------------------------------------------
+# Invalid repo alias
+# ---------------------------------------------------------------------------
+
+
+async def test_invalid_repo_raises(workspace_mcp):
+ from repowise.server.mcp_server import get_overview
+
+ with pytest.raises(ValueError, match="Unknown repo"):
+ await get_overview(repo="nonexistent")
+
+
+# ---------------------------------------------------------------------------
+# Single-repo mode — no workspace, no regression
+# ---------------------------------------------------------------------------
+
+
+async def test_single_repo_mode_no_workspace():
+ """When _registry is None, tools should use _state globals directly."""
+ import repowise.server.mcp_server as mcp_mod
+
+ # Ensure no registry is set
+ assert mcp_mod._registry is None
+
+ # We can't easily call tools without DB, but verify the helper works
+ from repowise.server.mcp_server._helpers import _is_workspace_mode
+
+ assert _is_workspace_mode() is False
+
+
+# ---------------------------------------------------------------------------
+# Cross-repo enricher
+# ---------------------------------------------------------------------------
+
+
+def enricher_data(tmp_path):
+ """Write a cross_repo_edges.json and return its path."""
+ data = {
+ "version": 1,
+ "generated_at": "2026-04-12T12:00:00Z",
+ "co_changes": [
+ {
+ "source_repo": "backend",
+ "source_file": "src/api/server.py",
+ "target_repo": "frontend",
+ "target_file": "src/api/client.ts",
+ "strength": 4.2,
+ "frequency": 6,
+ "last_date": "2026-04-10",
+ },
+ ],
+ "package_deps": [
+ {
+ "source_repo": "frontend",
+ "target_repo": "backend",
+ "source_manifest": "package.json",
+ "kind": "npm_local_path",
+ },
+ ],
+ "repo_summaries": {
+ "backend": {"cross_repo_edge_count": 1},
+ "frontend": {"cross_repo_edge_count": 1},
+ },
+ }
+ path = tmp_path / "cross_repo_edges.json"
+ path.write_text(json.dumps(data))
+ return path
+
+
+def test_enricher_loads_and_has_data(enricher_data):
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ enricher = CrossRepoEnricher(enricher_data)
+ assert enricher.has_data is True
+
+
+def test_enricher_get_cross_repo_partners(enricher_data):
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ enricher = CrossRepoEnricher(enricher_data)
+ partners = enricher.get_cross_repo_partners("backend", "src/api/server.py")
+ assert len(partners) == 1
+ assert partners[0]["repo"] == "frontend"
+ assert partners[0]["file"] == "src/api/client.ts"
+ assert partners[0]["strength"] == 4.2
+
+
+def test_enricher_bidirectional_index(enricher_data):
+ """Co-change edges should be indexed from both sides."""
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ enricher = CrossRepoEnricher(enricher_data)
+ # Reverse direction
+ partners = enricher.get_cross_repo_partners("frontend", "src/api/client.ts")
+ assert len(partners) == 1
+ assert partners[0]["repo"] == "backend"
+
+
+def test_enricher_get_package_deps(enricher_data):
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ enricher = CrossRepoEnricher(enricher_data)
+ deps = enricher.get_package_deps("frontend")
+ assert len(deps) == 1
+ assert deps[0]["target_repo"] == "backend"
+
+
+def test_enricher_get_repos_depending_on(enricher_data):
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ enricher = CrossRepoEnricher(enricher_data)
+ # frontend depends on backend
+ depending = enricher.get_repos_depending_on("backend")
+ assert "frontend" in depending
+
+
+def test_enricher_has_cross_repo_consumers(enricher_data):
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ enricher = CrossRepoEnricher(enricher_data)
+ consumers = enricher.has_cross_repo_consumers("backend", "src/api/server.py")
+ assert len(consumers) == 1
+ assert consumers[0]["repo"] == "frontend"
+
+
+def test_enricher_get_affected_repos(enricher_data):
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ enricher = CrossRepoEnricher(enricher_data)
+ affected = enricher.get_affected_repos("backend", "src/api/server.py")
+ assert "frontend" in affected
+
+
+def test_enricher_missing_file_returns_empty(enricher_data):
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ enricher = CrossRepoEnricher(enricher_data)
+ assert enricher.get_cross_repo_partners("backend", "nonexistent.py") == []
+ assert enricher.has_cross_repo_consumers("backend", "nonexistent.py") == []
+
+
+def test_enricher_missing_json_has_no_data(tmp_path):
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ enricher = CrossRepoEnricher(tmp_path / "does_not_exist.json")
+ assert enricher.has_data is False
+ assert enricher.get_cross_repo_partners("x", "y") == []
+
+
+def test_enricher_get_cross_repo_summary(enricher_data):
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ enricher = CrossRepoEnricher(enricher_data)
+ summary = enricher.get_cross_repo_summary()
+ assert summary["co_change_count"] == 1
+ assert summary["package_dep_count"] == 1
+ assert len(summary["top_connections"]) >= 1
+
+
+# ---------------------------------------------------------------------------
+# MCP tool enrichment with cross-repo data
+# ---------------------------------------------------------------------------
+
+
+async def workspace_mcp_with_enricher(workspace_mcp, enricher_data):
+ """Extend workspace_mcp with a cross-repo enricher."""
+ import repowise.server.mcp_server as mcp_mod
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ mcp_mod._cross_repo_enricher = CrossRepoEnricher(enricher_data)
+ yield
+ mcp_mod._cross_repo_enricher = None
+
+
+async def test_overview_footer_includes_cross_repo(workspace_mcp_with_enricher):
+ from repowise.server.mcp_server import get_overview
+
+ result = await get_overview()
+ assert "workspace" in result
+ ws = result["workspace"]
+ assert "cross_repo" in ws
+ assert ws["cross_repo"]["co_change_count"] == 1
+
+
+async def test_overview_all_includes_cross_repo_topology(workspace_mcp_with_enricher):
+ from repowise.server.mcp_server import get_overview
+
+ result = await get_overview(repo="all")
+ assert "cross_repo_topology" in result
+ assert result["cross_repo_topology"]["co_change_count"] == 1
diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.py
new file mode 100644
index 000000000..887457ef0
--- /dev/null
+++ b/tests/unit/server/test_workspace_router.py
@@ -0,0 +1,404 @@
+"""Tests for /api/workspace endpoints."""
+
+from __future__ import annotations
+
+import json
+from contextlib import asynccontextmanager
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import pytest
+from fastapi import FastAPI
+from fastapi.responses import JSONResponse
+from httpx import ASGITransport, AsyncClient
+
+from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+from repowise.server.routers import workspace
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def _write_json(path: Path, data: dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(data), encoding="utf-8")
+
+
+def _make_workspace_app(
+ *,
+ ws_config=None,
+ enricher=None,
+ workspace_root: str | None = None,
+) -> FastAPI:
+ """Build a minimal FastAPI app with workspace router + injected state."""
+
+ @asynccontextmanager
+ async def noop_lifespan(app: FastAPI):
+ yield
+
+ app = FastAPI(title="workspace-test", lifespan=noop_lifespan)
+
+ @app.exception_handler(LookupError)
+ async def not_found_handler(request, exc):
+ return JSONResponse(status_code=404, content={"detail": str(exc)})
+
+ app.state.workspace_config = ws_config
+ app.state.cross_repo_enricher = enricher
+ app.state.workspace_root = workspace_root
+
+ app.include_router(workspace.router)
+ return app
+
+
+def _make_ws_config():
+ """Build a fake WorkspaceConfig-like object."""
+ repo1 = MagicMock()
+ repo1.alias = "backend"
+ repo1.path = "./backend"
+ repo1.is_primary = True
+ repo1.indexed_at = "2026-04-12T10:00:00Z"
+ repo1.last_commit_at_index = "abc1234"
+
+ repo2 = MagicMock()
+ repo2.alias = "frontend"
+ repo2.path = "./frontend"
+ repo2.is_primary = False
+ repo2.indexed_at = None
+ repo2.last_commit_at_index = None
+
+ ws_config = MagicMock()
+ ws_config.repos = [repo1, repo2]
+ ws_config.default_repo = "backend"
+ return ws_config
+
+
+def _make_enricher(tmp_path: Path) -> CrossRepoEnricher:
+ """Build a real enricher with sample data."""
+ cross_repo_path = tmp_path / "cross_repo_edges.json"
+ _write_json(cross_repo_path, {
+ "version": 1,
+ "co_changes": [
+ {
+ "source_repo": "backend",
+ "source_file": "api/routes.py",
+ "target_repo": "frontend",
+ "target_file": "src/client.ts",
+ "strength": 0.8,
+ "frequency": 5,
+ "last_date": "2026-04-10",
+ },
+ ],
+ "package_deps": [
+ {
+ "source_repo": "frontend",
+ "target_repo": "backend",
+ "source_manifest": "package.json",
+ "kind": "npm",
+ },
+ ],
+ })
+
+ contracts_path = tmp_path / "contracts.json"
+ _write_json(contracts_path, {
+ "version": 1,
+ "generated_at": "2026-04-12T12:00:00Z",
+ "contracts": [
+ {
+ "repo": "backend",
+ "contract_id": "http::GET::/api/users",
+ "contract_type": "http",
+ "role": "provider",
+ "file_path": "routes.py",
+ "symbol_name": "get_users",
+ "confidence": 0.85,
+ "service": None,
+ },
+ {
+ "repo": "frontend",
+ "contract_id": "http::GET::/api/users",
+ "contract_type": "http",
+ "role": "consumer",
+ "file_path": "client.ts",
+ "symbol_name": "fetchUsers",
+ "confidence": 0.75,
+ "service": None,
+ },
+ {
+ "repo": "backend",
+ "contract_id": "grpc::Auth/Login",
+ "contract_type": "grpc",
+ "role": "provider",
+ "file_path": "auth.py",
+ "symbol_name": "Login",
+ "confidence": 0.85,
+ "service": None,
+ },
+ ],
+ "contract_links": [
+ {
+ "contract_id": "http::GET::/api/users",
+ "contract_type": "http",
+ "match_type": "exact",
+ "confidence": 0.75,
+ "provider_repo": "backend",
+ "provider_file": "routes.py",
+ "provider_symbol": "get_users",
+ "consumer_repo": "frontend",
+ "consumer_file": "client.ts",
+ "consumer_symbol": "fetchUsers",
+ },
+ ],
+ })
+
+ return CrossRepoEnricher(cross_repo_path, contracts_path=contracts_path)
+
+
+# ---------------------------------------------------------------------------
+# Tests — GET /api/workspace
+# ---------------------------------------------------------------------------
+
+
+class TestGetWorkspace:
+ @pytest.mark.asyncio
+ async def test_single_repo_mode(self) -> None:
+ """No workspace config → is_workspace=false."""
+ app = _make_workspace_app()
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["is_workspace"] is False
+ assert data["repos"] == []
+ assert data["default_repo"] is None
+
+ @pytest.mark.asyncio
+ async def test_workspace_mode(self, tmp_path: Path) -> None:
+ """With workspace config → is_workspace=true, repos listed."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(
+ ws_config=ws_config,
+ enricher=enricher,
+ workspace_root="/projects/myworkspace",
+ )
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["is_workspace"] is True
+ assert len(data["repos"]) == 2
+ assert data["repos"][0]["alias"] == "backend"
+ assert data["repos"][0]["is_primary"] is True
+ assert data["default_repo"] == "backend"
+ assert data["workspace_root"] == "/projects/myworkspace"
+
+ @pytest.mark.asyncio
+ async def test_cross_repo_summary(self, tmp_path: Path) -> None:
+ """Enricher data populates cross_repo_summary."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=ws_config, enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace")
+ data = resp.json()
+ assert data["cross_repo_summary"]["co_change_count"] == 1
+ assert data["cross_repo_summary"]["package_dep_count"] == 1
+
+ @pytest.mark.asyncio
+ async def test_contract_summary(self, tmp_path: Path) -> None:
+ """Enricher contract data populates contract_summary."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=ws_config, enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace")
+ data = resp.json()
+ assert data["contract_summary"]["total_contracts"] == 3
+ assert data["contract_summary"]["total_links"] == 1
+ assert data["contract_summary"]["by_type"]["http"] == 2
+
+ @pytest.mark.asyncio
+ async def test_no_enricher(self) -> None:
+ """Workspace config but no enricher → summaries are null."""
+ ws_config = _make_ws_config()
+ app = _make_workspace_app(ws_config=ws_config)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace")
+ data = resp.json()
+ assert data["is_workspace"] is True
+ assert data["cross_repo_summary"] is None
+ assert data["contract_summary"] is None
+
+
+# ---------------------------------------------------------------------------
+# Tests — GET /api/workspace/contracts
+# ---------------------------------------------------------------------------
+
+
+class TestGetContracts:
+ @pytest.mark.asyncio
+ async def test_not_workspace_mode(self) -> None:
+ """404 when not in workspace mode."""
+ app = _make_workspace_app()
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/contracts")
+ assert resp.status_code == 404
+
+ @pytest.mark.asyncio
+ async def test_returns_all(self, tmp_path: Path) -> None:
+ """Returns all contracts and links."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=ws_config, enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/contracts")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["total_contracts"] == 3
+ assert data["total_links"] == 1
+ assert len(data["contracts"]) == 3
+ assert len(data["links"]) == 1
+
+ @pytest.mark.asyncio
+ async def test_filter_by_type(self, tmp_path: Path) -> None:
+ """Filter by contract_type returns only matching."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=ws_config, enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/contracts", params={"contract_type": "grpc"})
+ data = resp.json()
+ assert data["total_contracts"] == 1
+ assert data["contracts"][0]["contract_type"] == "grpc"
+ assert data["total_links"] == 0 # no gRPC links in fixture
+
+ @pytest.mark.asyncio
+ async def test_filter_by_repo(self, tmp_path: Path) -> None:
+ """Filter by repo returns only that repo's contracts."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=ws_config, enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/contracts", params={"repo": "frontend"})
+ data = resp.json()
+ assert data["total_contracts"] == 1
+ assert data["contracts"][0]["repo"] == "frontend"
+
+ @pytest.mark.asyncio
+ async def test_filter_by_role(self, tmp_path: Path) -> None:
+ """Filter by role returns only providers or consumers."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=ws_config, enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/contracts", params={"role": "provider"})
+ data = resp.json()
+ assert data["total_contracts"] == 2
+ assert all(c["role"] == "provider" for c in data["contracts"])
+
+ @pytest.mark.asyncio
+ async def test_no_enricher(self) -> None:
+ """Workspace mode but no enricher → empty response."""
+ ws_config = _make_ws_config()
+ app = _make_workspace_app(ws_config=ws_config)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/contracts")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["total_contracts"] == 0
+ assert data["total_links"] == 0
+
+
+# ---------------------------------------------------------------------------
+# Tests — GET /api/workspace/co-changes
+# ---------------------------------------------------------------------------
+
+
+class TestGetCoChanges:
+ @pytest.mark.asyncio
+ async def test_not_workspace_mode(self) -> None:
+ """404 when not in workspace mode."""
+ app = _make_workspace_app()
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/co-changes")
+ assert resp.status_code == 404
+
+ @pytest.mark.asyncio
+ async def test_returns_all(self, tmp_path: Path) -> None:
+ """Returns co-change pairs."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=ws_config, enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/co-changes")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["total"] == 1
+ assert len(data["co_changes"]) == 1
+ assert data["co_changes"][0]["source_repo"] == "backend"
+ assert data["co_changes"][0]["strength"] == 0.8
+
+ @pytest.mark.asyncio
+ async def test_filter_by_repo(self, tmp_path: Path) -> None:
+ """Filter by repo returns matching pairs."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=ws_config, enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/co-changes", params={"repo": "backend"})
+ data = resp.json()
+ assert data["total"] == 1
+
+ @pytest.mark.asyncio
+ async def test_filter_by_repo_no_match(self, tmp_path: Path) -> None:
+ """Filter by non-existent repo returns empty."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=ws_config, enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/co-changes", params={"repo": "nonexistent"})
+ data = resp.json()
+ assert data["total"] == 0
+ assert data["co_changes"] == []
+
+ @pytest.mark.asyncio
+ async def test_min_strength_filter(self, tmp_path: Path) -> None:
+ """min_strength filter excludes weak pairs."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=ws_config, enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ # Our only co-change has strength 0.8 — filter above it
+ resp = await c.get("/api/workspace/co-changes", params={"min_strength": "0.9"})
+ data = resp.json()
+ assert data["total"] == 0
+
+ @pytest.mark.asyncio
+ async def test_no_enricher(self) -> None:
+ """Workspace mode but no enricher → empty."""
+ ws_config = _make_ws_config()
+ app = _make_workspace_app(ws_config=ws_config)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/co-changes")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["total"] == 0
diff --git a/tests/unit/workspace/__init__.py b/tests/unit/workspace/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/unit/workspace/test_config.py b/tests/unit/workspace/test_config.py
new file mode 100644
index 000000000..e95301e42
--- /dev/null
+++ b/tests/unit/workspace/test_config.py
@@ -0,0 +1,308 @@
+"""Tests for repowise.core.workspace.config — workspace configuration."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.workspace.config import (
+ WORKSPACE_CONFIG_FILENAME,
+ RepoEntry,
+ WorkspaceConfig,
+ find_workspace_root,
+)
+
+
+# ---------------------------------------------------------------------------
+# RepoEntry
+# ---------------------------------------------------------------------------
+
+
+class TestRepoEntry:
+ def test_to_dict_minimal(self) -> None:
+ entry = RepoEntry(path="backend", alias="backend")
+ d = entry.to_dict()
+ assert d == {"path": "backend", "alias": "backend"}
+ assert "is_primary" not in d
+ assert "indexed_at" not in d
+ assert "last_commit_at_index" not in d
+
+ def test_to_dict_with_timestamps(self) -> None:
+ entry = RepoEntry(
+ path="backend",
+ alias="backend",
+ indexed_at="2026-04-12T10:30:00+00:00",
+ last_commit_at_index="abc1234",
+ )
+ d = entry.to_dict()
+ assert d["indexed_at"] == "2026-04-12T10:30:00+00:00"
+ assert d["last_commit_at_index"] == "abc1234"
+
+ def test_from_dict_with_timestamps(self) -> None:
+ entry = RepoEntry.from_dict({
+ "path": "be",
+ "alias": "be",
+ "indexed_at": "2026-04-12T10:30:00+00:00",
+ "last_commit_at_index": "abc1234",
+ })
+ assert entry.indexed_at == "2026-04-12T10:30:00+00:00"
+ assert entry.last_commit_at_index == "abc1234"
+
+ def test_from_dict_backward_compat(self) -> None:
+ """Old YAML without timestamp fields should still load fine."""
+ entry = RepoEntry.from_dict({"path": "lib", "alias": "lib"})
+ assert entry.indexed_at is None
+ assert entry.last_commit_at_index is None
+
+ def test_to_dict_primary(self) -> None:
+ entry = RepoEntry(path="backend", alias="backend", is_primary=True)
+ d = entry.to_dict()
+ assert d["is_primary"] is True
+
+ def test_from_dict(self) -> None:
+ entry = RepoEntry.from_dict({"path": "fe", "alias": "frontend", "is_primary": True})
+ assert entry.path == "fe"
+ assert entry.alias == "frontend"
+ assert entry.is_primary is True
+
+ def test_from_dict_defaults(self) -> None:
+ entry = RepoEntry.from_dict({"path": "lib", "alias": "lib"})
+ assert entry.is_primary is False
+
+
+# ---------------------------------------------------------------------------
+# WorkspaceConfig — serialization
+# ---------------------------------------------------------------------------
+
+
+class TestWorkspaceConfigSerialization:
+ def test_to_dict_structure(self) -> None:
+ config = WorkspaceConfig(
+ version=1,
+ repos=[
+ RepoEntry(path="backend", alias="backend", is_primary=True),
+ RepoEntry(path="frontend", alias="frontend"),
+ ],
+ default_repo="backend",
+ )
+ d = config.to_dict()
+ assert d["version"] == 1
+ assert d["default_repo"] == "backend"
+ assert len(d["repos"]) == 2
+ assert d["repos"][0]["alias"] == "backend"
+
+ def test_from_dict_valid(self) -> None:
+ data = {
+ "version": 1,
+ "default_repo": "be",
+ "repos": [
+ {"path": "be", "alias": "be", "is_primary": True},
+ {"path": "fe", "alias": "fe"},
+ ],
+ }
+ config = WorkspaceConfig.from_dict(data)
+ assert config.version == 1
+ assert config.default_repo == "be"
+ assert len(config.repos) == 2
+
+ def test_from_dict_missing_fields(self) -> None:
+ config = WorkspaceConfig.from_dict({})
+ assert config.version == 1
+ assert config.repos == []
+ assert config.default_repo is None
+
+ def test_save_load_roundtrip(self, tmp_path: Path) -> None:
+ original = WorkspaceConfig(
+ version=1,
+ repos=[
+ RepoEntry(path="backend", alias="backend", is_primary=True),
+ RepoEntry(path="libs/shared", alias="shared"),
+ ],
+ default_repo="backend",
+ )
+ original.save(tmp_path)
+
+ loaded = WorkspaceConfig.load(tmp_path)
+ assert loaded.version == original.version
+ assert loaded.default_repo == original.default_repo
+ assert len(loaded.repos) == len(original.repos)
+ assert loaded.repos[0].path == "backend"
+ assert loaded.repos[0].alias == "backend"
+ assert loaded.repos[0].is_primary is True
+ assert loaded.repos[1].path == "libs/shared"
+ assert loaded.repos[1].alias == "shared"
+ assert loaded.repos[1].is_primary is False
+
+ def test_save_load_roundtrip_with_timestamps(self, tmp_path: Path) -> None:
+ original = WorkspaceConfig(
+ version=1,
+ repos=[
+ RepoEntry(
+ path="backend",
+ alias="backend",
+ is_primary=True,
+ indexed_at="2026-04-12T10:30:00+00:00",
+ last_commit_at_index="abc1234567890",
+ ),
+ RepoEntry(path="frontend", alias="frontend"),
+ ],
+ default_repo="backend",
+ )
+ original.save(tmp_path)
+
+ loaded = WorkspaceConfig.load(tmp_path)
+ assert loaded.repos[0].indexed_at == "2026-04-12T10:30:00+00:00"
+ assert loaded.repos[0].last_commit_at_index == "abc1234567890"
+ assert loaded.repos[1].indexed_at is None
+ assert loaded.repos[1].last_commit_at_index is None
+
+ def test_load_file_not_found(self, tmp_path: Path) -> None:
+ with pytest.raises(FileNotFoundError):
+ WorkspaceConfig.load(tmp_path)
+
+ def test_save_creates_file(self, tmp_path: Path) -> None:
+ config = WorkspaceConfig(repos=[], default_repo=None)
+ path = config.save(tmp_path)
+ assert path.exists()
+ assert path.name == WORKSPACE_CONFIG_FILENAME
+
+ def test_posix_paths_stored(self, tmp_path: Path) -> None:
+ """Paths in YAML should use forward slashes even on Windows."""
+ config = WorkspaceConfig(
+ repos=[RepoEntry(path="libs/shared", alias="shared")],
+ )
+ config.save(tmp_path)
+ text = (tmp_path / WORKSPACE_CONFIG_FILENAME).read_text(encoding="utf-8")
+ assert "libs/shared" in text
+ assert "\\" not in text # no backslashes
+
+
+# ---------------------------------------------------------------------------
+# WorkspaceConfig — query helpers
+# ---------------------------------------------------------------------------
+
+
+class TestWorkspaceConfigQueries:
+ def _make_config(self) -> WorkspaceConfig:
+ return WorkspaceConfig(
+ repos=[
+ RepoEntry(path="backend", alias="backend", is_primary=True),
+ RepoEntry(path="frontend", alias="frontend"),
+ RepoEntry(path="libs/shared", alias="shared"),
+ ],
+ default_repo="backend",
+ )
+
+ def test_get_repo_found(self) -> None:
+ config = self._make_config()
+ repo = config.get_repo("frontend")
+ assert repo is not None
+ assert repo.alias == "frontend"
+
+ def test_get_repo_missing(self) -> None:
+ config = self._make_config()
+ assert config.get_repo("nonexistent") is None
+
+ def test_get_primary(self) -> None:
+ config = self._make_config()
+ primary = config.get_primary()
+ assert primary is not None
+ assert primary.alias == "backend"
+
+ def test_get_primary_fallback_to_first(self) -> None:
+ config = WorkspaceConfig(
+ repos=[RepoEntry(path="a", alias="a"), RepoEntry(path="b", alias="b")],
+ default_repo=None,
+ )
+ primary = config.get_primary()
+ assert primary is not None
+ assert primary.alias == "a"
+
+ def test_get_primary_empty(self) -> None:
+ config = WorkspaceConfig(repos=[])
+ assert config.get_primary() is None
+
+ def test_repo_paths(self, tmp_path: Path) -> None:
+ config = self._make_config()
+ paths = config.repo_paths(tmp_path)
+ assert len(paths) == 3
+ assert all(p.is_absolute() for p in paths)
+ assert paths[0] == (tmp_path / "backend").resolve()
+ assert paths[2] == (tmp_path / "libs" / "shared").resolve()
+
+ def test_repo_aliases(self) -> None:
+ config = self._make_config()
+ assert config.repo_aliases() == ["backend", "frontend", "shared"]
+
+
+# ---------------------------------------------------------------------------
+# WorkspaceConfig — mutation helpers
+# ---------------------------------------------------------------------------
+
+
+class TestWorkspaceConfigMutation:
+ def test_add_repo(self) -> None:
+ config = WorkspaceConfig(repos=[], default_repo=None)
+ config.add_repo(RepoEntry(path="new", alias="new"))
+ assert len(config.repos) == 1
+
+ def test_add_repo_duplicate_alias(self) -> None:
+ config = WorkspaceConfig(
+ repos=[RepoEntry(path="a", alias="myalias")],
+ )
+ with pytest.raises(ValueError, match="already exists"):
+ config.add_repo(RepoEntry(path="b", alias="myalias"))
+
+ def test_remove_repo(self) -> None:
+ config = WorkspaceConfig(
+ repos=[
+ RepoEntry(path="a", alias="a"),
+ RepoEntry(path="b", alias="b"),
+ ],
+ default_repo="a",
+ )
+ removed = config.remove_repo("a")
+ assert removed is not None
+ assert removed.alias == "a"
+ assert len(config.repos) == 1
+ # Default should shift to first remaining repo
+ assert config.default_repo == "b"
+
+ def test_remove_repo_not_found(self) -> None:
+ config = WorkspaceConfig(repos=[])
+ assert config.remove_repo("nope") is None
+
+
+# ---------------------------------------------------------------------------
+# find_workspace_root
+# ---------------------------------------------------------------------------
+
+
+class TestFindWorkspaceRoot:
+ def test_found_at_start(self, tmp_path: Path) -> None:
+ (tmp_path / WORKSPACE_CONFIG_FILENAME).write_text("version: 1")
+ assert find_workspace_root(tmp_path) == tmp_path.resolve()
+
+ def test_found_in_parent(self, tmp_path: Path) -> None:
+ (tmp_path / WORKSPACE_CONFIG_FILENAME).write_text("version: 1")
+ child = tmp_path / "backend" / "src"
+ child.mkdir(parents=True)
+ assert find_workspace_root(child) == tmp_path.resolve()
+
+ def test_not_found(self, tmp_path: Path) -> None:
+ child = tmp_path / "some" / "deep" / "path"
+ child.mkdir(parents=True)
+ # No config file anywhere — should return None (eventually hits fs root)
+ # This test may be slow on deep paths, so we use tmp_path which is shallow
+ result = find_workspace_root(child)
+ assert result is None
+
+ def test_stops_at_correct_level(self, tmp_path: Path) -> None:
+ """Config at one level, deeper path should find it."""
+ ws = tmp_path / "workspace"
+ ws.mkdir()
+ (ws / WORKSPACE_CONFIG_FILENAME).write_text("version: 1")
+ deep = ws / "repo" / "src" / "pkg"
+ deep.mkdir(parents=True)
+ assert find_workspace_root(deep) == ws.resolve()
diff --git a/tests/unit/workspace/test_contract_config.py b/tests/unit/workspace/test_contract_config.py
new file mode 100644
index 000000000..3c2716b33
--- /dev/null
+++ b/tests/unit/workspace/test_contract_config.py
@@ -0,0 +1,131 @@
+"""Tests for ContractConfig and ManualContractLink in workspace config."""
+
+from __future__ import annotations
+
+from repowise.core.workspace.config import (
+ ContractConfig,
+ ManualContractLink,
+ RepoEntry,
+ WorkspaceConfig,
+)
+
+
+class TestContractConfig:
+ def test_default_values(self) -> None:
+ cfg = ContractConfig()
+ assert cfg.detect_http is True
+ assert cfg.detect_grpc is True
+ assert cfg.detect_topics is True
+ assert cfg.manual_links == []
+
+ def test_from_dict_partial_overrides(self) -> None:
+ cfg = ContractConfig.from_dict({"detect_http": False})
+ assert cfg.detect_http is False
+ assert cfg.detect_grpc is True
+ assert cfg.detect_topics is True
+
+ def test_round_trip(self) -> None:
+ cfg = ContractConfig(
+ detect_http=True,
+ detect_grpc=False,
+ detect_topics=True,
+ manual_links=[
+ ManualContractLink(
+ from_repo="worker",
+ to_repo="api",
+ contract_type="http",
+ contract_id="http::GET::/api/jobs",
+ from_role="consumer",
+ ),
+ ],
+ )
+ d = cfg.to_dict()
+ loaded = ContractConfig.from_dict(d)
+ assert loaded.detect_grpc is False
+ assert len(loaded.manual_links) == 1
+ assert loaded.manual_links[0].from_repo == "worker"
+
+
+class TestManualContractLink:
+ def test_from_dict(self) -> None:
+ data = {
+ "from_repo": "frontend",
+ "to_repo": "backend",
+ "contract_type": "http",
+ "contract_id": "http::POST::/api/auth",
+ "from_role": "consumer",
+ }
+ ml = ManualContractLink.from_dict(data)
+ assert ml.from_repo == "frontend"
+ assert ml.to_repo == "backend"
+ assert ml.from_role == "consumer"
+
+ def test_default_role(self) -> None:
+ ml = ManualContractLink.from_dict({
+ "from_repo": "a",
+ "to_repo": "b",
+ "contract_type": "topic",
+ "contract_id": "topic::events",
+ })
+ assert ml.from_role == "consumer"
+
+ def test_round_trip(self) -> None:
+ ml = ManualContractLink(
+ from_repo="a", to_repo="b",
+ contract_type="grpc", contract_id="grpc::Auth/*",
+ from_role="provider",
+ )
+ loaded = ManualContractLink.from_dict(ml.to_dict())
+ assert loaded.from_repo == "a"
+ assert loaded.from_role == "provider"
+
+
+class TestWorkspaceConfigWithContracts:
+ def test_from_dict_no_contracts_key(self) -> None:
+ data = {
+ "version": 1,
+ "repos": [{"path": "api", "alias": "api"}],
+ "default_repo": "api",
+ }
+ cfg = WorkspaceConfig.from_dict(data)
+ assert cfg.contracts.detect_http is True
+ assert cfg.contracts.detect_grpc is True
+
+ def test_from_dict_with_contracts(self) -> None:
+ data = {
+ "version": 1,
+ "repos": [{"path": "api", "alias": "api"}],
+ "default_repo": "api",
+ "contracts": {
+ "detect_http": True,
+ "detect_grpc": False,
+ "detect_topics": True,
+ },
+ }
+ cfg = WorkspaceConfig.from_dict(data)
+ assert cfg.contracts.detect_grpc is False
+
+ def test_round_trip_with_manual_links(self, tmp_path) -> None:
+ cfg = WorkspaceConfig(
+ version=1,
+ repos=[RepoEntry(path="api", alias="api")],
+ default_repo="api",
+ contracts=ContractConfig(
+ detect_http=True,
+ detect_grpc=True,
+ detect_topics=False,
+ manual_links=[
+ ManualContractLink(
+ from_repo="worker",
+ to_repo="api",
+ contract_type="http",
+ contract_id="http::GET::/jobs",
+ ),
+ ],
+ ),
+ )
+ cfg.save(tmp_path)
+ loaded = WorkspaceConfig.load(tmp_path)
+ assert loaded.contracts.detect_topics is False
+ assert len(loaded.contracts.manual_links) == 1
+ assert loaded.contracts.manual_links[0].contract_id == "http::GET::/jobs"
diff --git a/tests/unit/workspace/test_contracts.py b/tests/unit/workspace/test_contracts.py
new file mode 100644
index 000000000..45e5e1fde
--- /dev/null
+++ b/tests/unit/workspace/test_contracts.py
@@ -0,0 +1,659 @@
+"""Tests for contract extraction — HTTP, gRPC, topic extractors, matching, persistence."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.core.workspace.contracts import (
+ CONTRACTS_FILENAME,
+ Contract,
+ ContractLink,
+ ContractStore,
+ load_contract_store,
+ match_contracts,
+ normalize_contract_id,
+ save_contract_store,
+)
+from repowise.core.workspace.extractors.http_extractor import (
+ HttpExtractor,
+ normalize_http_path,
+)
+from repowise.core.workspace.extractors.grpc_extractor import (
+ GrpcExtractor,
+ _extract_service_blocks,
+)
+from repowise.core.workspace.extractors.topic_extractor import TopicExtractor
+from repowise.core.workspace.extractors.service_boundary import (
+ ServiceBoundary,
+ assign_service,
+ detect_service_boundaries,
+)
+
+
+# ---------------------------------------------------------------------------
+# normalize_http_path
+# ---------------------------------------------------------------------------
+
+
+class TestNormalizeHttpPath:
+ def test_express_param(self) -> None:
+ assert normalize_http_path("/api/users/:id") == "/api/users/{param}"
+
+ def test_spring_param(self) -> None:
+ assert normalize_http_path("/api/users/{userId}") == "/api/users/{param}"
+
+ def test_nextjs_param(self) -> None:
+ assert normalize_http_path("/api/users/[id]") == "/api/users/{param}"
+
+ def test_query_string_stripped(self) -> None:
+ assert normalize_http_path("/api/users?page=1") == "/api/users"
+
+ def test_trailing_slash_stripped(self) -> None:
+ assert normalize_http_path("/api/users/") == "/api/users"
+
+ def test_case_lowered(self) -> None:
+ assert normalize_http_path("/Api/Users") == "/api/users"
+
+ def test_multiple_params(self) -> None:
+ assert normalize_http_path("/api/:org/repos/:id") == "/api/{param}/repos/{param}"
+
+ def test_root_path(self) -> None:
+ assert normalize_http_path("/") == "/"
+
+
+# ---------------------------------------------------------------------------
+# HttpExtractor
+# ---------------------------------------------------------------------------
+
+
+class TestHttpExtractor:
+ def _write_file(self, repo: Path, rel: str, content: str) -> None:
+ fpath = repo / rel
+ fpath.parent.mkdir(parents=True, exist_ok=True)
+ fpath.write_text(content, encoding="utf-8")
+
+ def test_express_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "src/routes.js", """
+ const router = require('express').Router();
+ router.get('/api/users', handler);
+ router.post('/api/users', createHandler);
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "backend")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 2
+ ids = {c.contract_id for c in providers}
+ assert "http::GET::/api/users" in ids
+ assert "http::POST::/api/users" in ids
+
+ def test_fastapi_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "main.py", """
+ @app.get("/api/items/{item_id}")
+ async def get_item(item_id: int): ...
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "api")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "http::GET::/api/items/{param}"
+
+ def test_spring_with_class_prefix(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "UserController.java", """
+ @RequestMapping("/api/v1")
+ @RestController
+ public class UserController {
+ @GetMapping("/users")
+ public List<User> list() { ... }
+ }
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "backend")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "http::GET::/api/v1/users"
+
+ def test_spring_multiple_classes_correct_prefix(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "MultiController.java", """
+ @RequestMapping("/api/v1")
+ @RestController
+ public class UserController {
+ @GetMapping("/users")
+ public List<User> list() { ... }
+ }
+
+ @RequestMapping("/internal")
+ @RestController
+ public class AdminController {
+ @PostMapping("/admin")
+ public void doAdmin() { ... }
+ }
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "backend")
+ providers = [c for c in contracts if c.role == "provider"]
+ ids = {c.contract_id for c in providers}
+ assert "http::GET::/api/v1/users" in ids
+ assert "http::POST::/internal/admin" in ids
+ # The inner class prefix must NOT be applied to the first class's methods
+ assert "http::GET::/internal/users" not in ids
+
+ def test_laravel_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "routes/web.php", """
+ Route::delete('/posts/{id}', [PostController::class, 'destroy']);
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "app")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "http::DELETE::/posts/{param}"
+
+ def test_go_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "main.go", """
+ r.GET("/health", healthHandler)
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "svc")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "http::GET::/health"
+
+ def test_fetch_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "src/api.ts", """
+ const users = await fetch('/api/users');
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "frontend")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "http::GET::/api/users"
+
+ def test_fetch_with_method_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "src/api.ts", """
+ await fetch('/api/users', { method: 'POST', body: data });
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "frontend")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "http::POST::/api/users"
+
+ def test_axios_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "src/client.js", """
+ const items = await axios.get('/api/items');
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "frontend")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "http::GET::/api/items"
+
+ def test_requests_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "client.py", """
+ resp = requests.post('http://backend:8000/api/data')
+ """)
+ contracts = HttpExtractor().extract(tmp_path, "worker")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "http::POST::/api/data"
+
+ def test_empty_file(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "empty.py", "")
+ contracts = HttpExtractor().extract(tmp_path, "svc")
+ assert contracts == []
+
+ def test_no_patterns(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "utils.py", "def add(a, b): return a + b")
+ contracts = HttpExtractor().extract(tmp_path, "svc")
+ assert contracts == []
+
+
+# ---------------------------------------------------------------------------
+# GrpcExtractor
+# ---------------------------------------------------------------------------
+
+
+class TestGrpcExtractor:
+ def _write_file(self, repo: Path, rel: str, content: str) -> None:
+ fpath = repo / rel
+ fpath.parent.mkdir(parents=True, exist_ok=True)
+ fpath.write_text(content, encoding="utf-8")
+
+ def test_proto_parsing(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "auth.proto", """
+ syntax = "proto3";
+ package auth;
+
+ service AuthService {
+ rpc Login(LoginRequest) returns (LoginResponse);
+ rpc Logout(LogoutRequest) returns (Empty);
+ }
+ """)
+ contracts = GrpcExtractor().extract(tmp_path, "auth")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 2
+ ids = {c.contract_id for c in providers}
+ assert "grpc::auth.AuthService/Login" in ids
+ assert "grpc::auth.AuthService/Logout" in ids
+
+ def test_proto_multiple_services(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "api.proto", """
+ syntax = "proto3";
+ package api;
+
+ service UserService {
+ rpc GetUser(GetUserReq) returns (User);
+ }
+
+ service OrderService {
+ rpc CreateOrder(CreateOrderReq) returns (Order);
+ }
+ """)
+ contracts = GrpcExtractor().extract(tmp_path, "api")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 2
+
+ def test_proto_nested_braces(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "svc.proto", """
+ syntax = "proto3";
+ package svc;
+
+ service MyService {
+ rpc DoThing(Req) returns (Resp) {
+ option (google.api.http) = {
+ post: "/api/thing"
+ body: "*"
+ };
+ }
+ }
+ """)
+ contracts = GrpcExtractor().extract(tmp_path, "svc")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "grpc::svc.MyService/DoThing"
+
+ def test_go_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "server.go", """
+ pb.RegisterPaymentServer(grpcServer, &impl{})
+ """)
+ contracts = GrpcExtractor().extract(tmp_path, "payment")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "grpc::Payment/*"
+
+ def test_go_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "client.go", """
+ client := pb.NewPaymentClient(conn)
+ """)
+ contracts = GrpcExtractor().extract(tmp_path, "gateway")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "grpc::Payment/*"
+
+ def test_java_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "AuthImpl.java", """
+ @GrpcService
+ public class AuthImpl extends AuthGrpc.AuthImplBase {
+ @Override
+ public void login(LoginRequest req, StreamObserver<LoginReply> resp) {}
+ }
+ """)
+ contracts = GrpcExtractor().extract(tmp_path, "auth")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "grpc::Auth/*"
+
+ def test_java_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "Client.java", """
+ var stub = AuthGrpc.newBlockingStub(channel);
+ """)
+ contracts = GrpcExtractor().extract(tmp_path, "gateway")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "grpc::Auth/*"
+
+ def test_python_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "server.py", """
+ add_GreeterServicer_to_server(GreeterServicer(), server)
+ """)
+ contracts = GrpcExtractor().extract(tmp_path, "greeter")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "grpc::Greeter/*"
+
+ def test_python_consumer_filters_mock(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "test_client.py", """
+ stub = MockGreeterStub(channel)
+ real = GreeterStub(channel)
+ """)
+ contracts = GrpcExtractor().extract(tmp_path, "test")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ # MockGreeterStub should be filtered, only GreeterStub remains
+ assert len(consumers) == 1
+ assert "Greeter" in consumers[0].contract_id
+
+ def test_ts_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "auth.controller.ts", """
+ @GrpcMethod('AuthService', 'Login')
+ login(data: LoginRequest): LoginResponse { ... }
+ """)
+ contracts = GrpcExtractor().extract(tmp_path, "auth")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "grpc::AuthService/Login"
+
+
+# ---------------------------------------------------------------------------
+# TopicExtractor
+# ---------------------------------------------------------------------------
+
+
+class TestTopicExtractor:
+ def _write_file(self, repo: Path, rel: str, content: str) -> None:
+ fpath = repo / rel
+ fpath.parent.mkdir(parents=True, exist_ok=True)
+ fpath.write_text(content, encoding="utf-8")
+
+ def test_kafka_listener_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "Consumer.java", """
+ @KafkaListener(topics = "orders")
+ public void listen(String message) {}
+ """)
+ contracts = TopicExtractor().extract(tmp_path, "worker")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "topic::orders"
+ assert consumers[0].meta["broker"] == "kafka"
+
+ def test_kafka_template_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "Publisher.java", """
+ kafkaTemplate.send("orders", payload);
+ """)
+ contracts = TopicExtractor().extract(tmp_path, "api")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "topic::orders"
+
+ def test_kafka_node_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "producer.js", """
+ await producer.send({ topic: 'payments', messages });
+ """)
+ contracts = TopicExtractor().extract(tmp_path, "svc")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "topic::payments"
+
+ def test_rabbitmq_listener_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "Worker.java", """
+ @RabbitListener(queues = "jobs")
+ public void process(Message msg) {}
+ """)
+ contracts = TopicExtractor().extract(tmp_path, "worker")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "topic::jobs"
+ assert consumers[0].meta["broker"] == "rabbitmq"
+
+ def test_nats_subscribe_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "listener.go", """
+ nc.Subscribe("events.created", handler)
+ """)
+ contracts = TopicExtractor().extract(tmp_path, "svc")
+ consumers = [c for c in contracts if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "topic::events.created"
+ assert consumers[0].meta["broker"] == "nats"
+
+ def test_nats_publish_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "notifier.go", """
+ nc.Publish("events.created", data)
+ """)
+ contracts = TopicExtractor().extract(tmp_path, "notifier")
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "topic::events.created"
+
+ def test_dedup_same_pattern_in_file(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "multi.java", """
+ kafkaTemplate.send("orders", payload1);
+ kafkaTemplate.send("orders", payload2);
+ """)
+ contracts = TopicExtractor().extract(tmp_path, "svc")
+ # Same topic, same role, same file → deduplicated
+ providers = [c for c in contracts if c.role == "provider"]
+ assert len(providers) == 1
+
+
+# ---------------------------------------------------------------------------
+# ServiceBoundary
+# ---------------------------------------------------------------------------
+
+
+class TestServiceBoundary:
+ def test_detects_boundary(self, tmp_path: Path) -> None:
+ svc = tmp_path / "services" / "auth"
+ svc.mkdir(parents=True)
+ (svc / "package.json").write_text("{}")
+ (svc / "handler.ts").write_text("export function login() {}")
+
+ boundaries = detect_service_boundaries(tmp_path)
+ assert len(boundaries) == 1
+ assert boundaries[0].service_path == "services/auth"
+ assert boundaries[0].confidence == 0.75
+
+ def test_root_excluded(self, tmp_path: Path) -> None:
+ (tmp_path / "package.json").write_text("{}")
+ (tmp_path / "app.ts").write_text("console.log('hi')")
+
+ boundaries = detect_service_boundaries(tmp_path)
+ assert len(boundaries) == 0
+
+ def test_confidence_scoring(self, tmp_path: Path) -> None:
+ svc = tmp_path / "svc"
+ svc.mkdir()
+ (svc / "package.json").write_text("{}")
+ (svc / "Dockerfile").write_text("FROM node")
+ (svc / "go.mod").write_text("module svc")
+ (svc / "main.go").write_text("package main")
+
+ boundaries = detect_service_boundaries(tmp_path)
+ assert len(boundaries) == 1
+ assert boundaries[0].confidence == 1.0
+
+ def test_two_marker_confidence(self, tmp_path: Path) -> None:
+ svc = tmp_path / "svc"
+ svc.mkdir()
+ (svc / "package.json").write_text("{}")
+ (svc / "Dockerfile").write_text("FROM node")
+ (svc / "index.ts").write_text("export default {}")
+
+ boundaries = detect_service_boundaries(tmp_path)
+ assert len(boundaries) == 1
+ assert boundaries[0].confidence == 0.9
+
+ def test_nested_services(self, tmp_path: Path) -> None:
+ for name in ("auth", "billing"):
+ svc = tmp_path / "services" / name
+ svc.mkdir(parents=True)
+ (svc / "package.json").write_text("{}")
+ (svc / "index.ts").write_text("export {}")
+
+ boundaries = detect_service_boundaries(tmp_path)
+ assert len(boundaries) == 2
+ paths = {b.service_path for b in boundaries}
+ assert "services/auth" in paths
+ assert "services/billing" in paths
+
+ def test_assign_service_longest_prefix(self) -> None:
+ boundaries = [
+ ServiceBoundary(service_path="services", service_name="services"),
+ ServiceBoundary(service_path="services/auth", service_name="auth"),
+ ]
+ assert assign_service("services/auth/handler.ts", boundaries) == "services/auth"
+
+ def test_assign_service_root_file(self) -> None:
+ boundaries = [
+ ServiceBoundary(service_path="services/auth", service_name="auth"),
+ ]
+ assert assign_service("README.md", boundaries) is None
+
+
+# ---------------------------------------------------------------------------
+# normalize_contract_id
+# ---------------------------------------------------------------------------
+
+
+class TestNormalizeContractId:
+ def test_http_normalizes(self) -> None:
+ assert normalize_contract_id("http::get::/Api/Users") == "http::GET::/api/users"
+
+ def test_http_strips_trailing_slash(self) -> None:
+ assert normalize_contract_id("http::GET::/api/") == "http::GET::/api"
+
+ def test_grpc_preserves_method_case(self) -> None:
+ result = normalize_contract_id("grpc::PKG.Service/GetUser")
+ assert result == "grpc::pkg.service/GetUser"
+
+ def test_topic_lowercases(self) -> None:
+ assert normalize_contract_id("topic::Orders") == "topic::orders"
+
+
+# ---------------------------------------------------------------------------
+# match_contracts
+# ---------------------------------------------------------------------------
+
+
+class TestMatchContracts:
+ def _contract(self, **kwargs) -> Contract:
+ defaults = {
+ "repo": "a",
+ "contract_id": "http::GET::/api",
+ "contract_type": "http",
+ "role": "provider",
+ "file_path": "f.py",
+ "symbol_name": "handler",
+ "confidence": 0.85,
+ "service": None,
+ "meta": {},
+ }
+ defaults.update(kwargs)
+ return Contract(**defaults)
+
+ def test_exact_match_creates_link(self) -> None:
+ contracts = [
+ self._contract(repo="backend", role="provider", contract_id="http::GET::/api/users"),
+ self._contract(repo="frontend", role="consumer", contract_id="http::GET::/api/users", file_path="client.ts"),
+ ]
+ links = match_contracts(contracts)
+ assert len(links) == 1
+ assert links[0].provider_repo == "backend"
+ assert links[0].consumer_repo == "frontend"
+
+ def test_same_repo_same_service_filtered(self) -> None:
+ contracts = [
+ self._contract(repo="mono", role="provider", service="svc-a"),
+ self._contract(repo="mono", role="consumer", service="svc-a", file_path="c.py"),
+ ]
+ links = match_contracts(contracts)
+ assert len(links) == 0
+
+ def test_same_repo_different_service_allowed(self) -> None:
+ contracts = [
+ self._contract(repo="mono", role="provider", service="svc-a"),
+ self._contract(repo="mono", role="consumer", service="svc-b", file_path="c.py"),
+ ]
+ links = match_contracts(contracts)
+ assert len(links) == 1
+
+ def test_http_wildcard_method(self) -> None:
+ contracts = [
+ self._contract(repo="backend", role="provider", contract_id="http::GET::/api/orders"),
+ self._contract(repo="frontend", role="consumer", contract_id="http::*::/api/orders", file_path="c.ts"),
+ ]
+ links = match_contracts(contracts)
+ assert len(links) == 1
+
+ def test_grpc_wildcard_service(self) -> None:
+ contracts = [
+ self._contract(repo="auth", role="provider", contract_id="grpc::auth.AuthService/Login", contract_type="grpc"),
+ self._contract(repo="gateway", role="consumer", contract_id="grpc::auth.AuthService/*", contract_type="grpc", file_path="gw.go"),
+ ]
+ links = match_contracts(contracts)
+ assert len(links) == 1
+
+ def test_no_match(self) -> None:
+ contracts = [
+ self._contract(repo="backend", role="provider", contract_id="http::GET::/api/users"),
+ self._contract(repo="frontend", role="consumer", contract_id="http::GET::/api/orders", file_path="c.ts"),
+ ]
+ links = match_contracts(contracts)
+ assert len(links) == 0
+
+ def test_multiple_consumers_for_one_provider(self) -> None:
+ contracts = [
+ self._contract(repo="backend", role="provider", contract_id="http::GET::/api/users"),
+ self._contract(repo="frontend", role="consumer", contract_id="http::GET::/api/users", file_path="c1.ts"),
+ self._contract(repo="mobile", role="consumer", contract_id="http::GET::/api/users", file_path="c2.ts"),
+ ]
+ links = match_contracts(contracts)
+ assert len(links) == 2
+
+
+# ---------------------------------------------------------------------------
+# ContractStore persistence
+# ---------------------------------------------------------------------------
+
+
+class TestContractStorePersistence:
+ def test_save_and_load_round_trip(self, tmp_path: Path) -> None:
+ store = ContractStore(
+ version=1,
+ generated_at="2026-04-12T12:00:00Z",
+ contracts=[
+ Contract(
+ repo="backend",
+ contract_id="http::GET::/api/users",
+ contract_type="http",
+ role="provider",
+ file_path="routes.py",
+ symbol_name="get_users",
+ confidence=0.85,
+ service=None,
+ meta={"method": "GET"},
+ ),
+ ],
+ contract_links=[
+ ContractLink(
+ contract_id="http::GET::/api/users",
+ contract_type="http",
+ match_type="exact",
+ confidence=0.75,
+ provider_repo="backend",
+ provider_file="routes.py",
+ provider_symbol="get_users",
+ provider_service=None,
+ consumer_repo="frontend",
+ consumer_file="client.ts",
+ consumer_symbol="fetchUsers",
+ consumer_service=None,
+ ),
+ ],
+ )
+ save_contract_store(store, tmp_path)
+ loaded = load_contract_store(tmp_path)
+ assert loaded is not None
+ assert loaded.version == 1
+ assert len(loaded.contracts) == 1
+ assert loaded.contracts[0].contract_id == "http::GET::/api/users"
+ assert len(loaded.contract_links) == 1
+ assert loaded.contract_links[0].provider_repo == "backend"
+
+ def test_load_missing_file_returns_none(self, tmp_path: Path) -> None:
+ assert load_contract_store(tmp_path) is None
+
+ def test_load_corrupt_json_returns_none(self, tmp_path: Path) -> None:
+ data_dir = tmp_path / ".repowise-workspace"
+ data_dir.mkdir()
+ (data_dir / CONTRACTS_FILENAME).write_text("not json!!!")
+ assert load_contract_store(tmp_path) is None
+
+ def test_empty_store_round_trip(self, tmp_path: Path) -> None:
+ store = ContractStore()
+ save_contract_store(store, tmp_path)
+ loaded = load_contract_store(tmp_path)
+ assert loaded is not None
+ assert loaded.contracts == []
+ assert loaded.contract_links == []
diff --git a/tests/unit/workspace/test_cross_repo.py b/tests/unit/workspace/test_cross_repo.py
new file mode 100644
index 000000000..95799b8f4
--- /dev/null
+++ b/tests/unit/workspace/test_cross_repo.py
@@ -0,0 +1,326 @@
+"""Tests for repowise.core.workspace.cross_repo — cross-repo intelligence."""
+
+from __future__ import annotations
+
+import json
+import math
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from repowise.core.workspace.cross_repo import (
+ CROSS_REPO_EDGES_FILENAME,
+ CrossRepoCoChange,
+ CrossRepoOverlay,
+ CrossRepoPackageDep,
+ _GitCommit,
+ _parse_git_log,
+ detect_cross_repo_co_changes,
+ detect_package_dependencies,
+ load_overlay,
+ save_overlay,
+)
+
+
+# ---------------------------------------------------------------------------
+# _parse_git_log
+# ---------------------------------------------------------------------------
+
+
+class TestParseGitLog:
+ def test_parses_standard_output(self, tmp_path: Path) -> None:
+ """Mock subprocess to return a known git log and verify parsing."""
+ fake_output = (
+ "\[email protected]|1712900000\n"
+ "src/app.py\n"
+ "src/utils.py\n"
+ "\[email protected]|1712890000\n"
+ "src/main.py\n"
+ )
+ with patch("subprocess.run") as mock_run:
+ mock_run.return_value = type("R", (), {
+ "returncode": 0, "stdout": fake_output, "stderr": ""
+ })()
+ commits = _parse_git_log(tmp_path)
+
+ assert len(commits) == 2
+ assert commits[0].author_email == "[email protected]"
+ assert commits[0].timestamp == 1712900000
+ assert commits[0].files == ["src/app.py", "src/utils.py"]
+ assert commits[1].author_email == "[email protected]"
+ assert commits[1].files == ["src/main.py"]
+
+ def test_handles_empty_repo(self, tmp_path: Path) -> None:
+ with patch("subprocess.run") as mock_run:
+ mock_run.return_value = type("R", (), {
+ "returncode": 0, "stdout": "", "stderr": ""
+ })()
+ commits = _parse_git_log(tmp_path)
+ assert commits == []
+
+ def test_handles_subprocess_failure(self, tmp_path: Path) -> None:
+ with patch("subprocess.run") as mock_run:
+ mock_run.return_value = type("R", (), {
+ "returncode": 128, "stdout": "", "stderr": "fatal: not a git repo"
+ })()
+ commits = _parse_git_log(tmp_path)
+ assert commits == []
+
+ def test_handles_exception(self, tmp_path: Path) -> None:
+ with patch("subprocess.run", side_effect=OSError("no git")):
+ commits = _parse_git_log(tmp_path)
+ assert commits == []
+
+
+# ---------------------------------------------------------------------------
+# Cross-repo co-change detection
+# ---------------------------------------------------------------------------
+
+
+def _make_commits(alias: str, entries: list[tuple[str, int, list[str]]]) -> list[_GitCommit]:
+ """Helper: build _GitCommit list from (email, ts, files) tuples."""
+ return [_GitCommit(author_email=e, timestamp=ts, files=files)
+ for e, ts, files in entries]
+
+
+class TestCrossRepoCoChanges:
+ def _detect_with_mocked_logs(
+ self, repo_commits: dict[str, list[_GitCommit]], **kwargs
+ ) -> list[CrossRepoCoChange]:
+ """Run detect_cross_repo_co_changes with mocked _parse_git_log."""
+ repo_paths = {alias: Path(f"/fake/{alias}") for alias in repo_commits}
+
+ def fake_parse(repo_path, commit_limit=500):
+ for alias, path in repo_paths.items():
+ if str(repo_path) == str(path):
+ return repo_commits[alias]
+ return []
+
+ with patch("repowise.core.workspace.cross_repo._parse_git_log", side_effect=fake_parse):
+ return detect_cross_repo_co_changes(repo_paths, **kwargs)
+
+ def test_same_author_within_window(self) -> None:
+ """Two repos, same author, commits <24h apart → edges found."""
+ now = int(time.time())
+ results = self._detect_with_mocked_logs({
+ "backend": _make_commits("backend", [
+ ("[email protected]", now - 3600, ["src/api.py"]), # 1 hour ago
+ ]),
+ "frontend": _make_commits("frontend", [
+ ("[email protected]", now - 7200, ["src/client.ts"]), # 2 hours ago
+ ]),
+ }, min_score=0.0)
+ assert len(results) >= 1
+ edge = results[0]
+ assert {edge.source_repo, edge.target_repo} == {"backend", "frontend"}
+
+ def test_different_authors_no_match(self) -> None:
+ """Same timestamps but different authors → no edges."""
+ now = int(time.time())
+ results = self._detect_with_mocked_logs({
+ "backend": _make_commits("backend", [
+ ("[email protected]", now - 3600, ["src/api.py"]),
+ ]),
+ "frontend": _make_commits("frontend", [
+ ("[email protected]", now - 3600, ["src/client.ts"]),
+ ]),
+ }, min_score=0.0)
+ assert len(results) == 0
+
+ def test_outside_time_window(self) -> None:
+ """Same author, commits >24h apart → no edges."""
+ now = int(time.time())
+ results = self._detect_with_mocked_logs({
+ "backend": _make_commits("backend", [
+ ("[email protected]", now, ["src/api.py"]),
+ ]),
+ "frontend": _make_commits("frontend", [
+ ("[email protected]", now - 100000, ["src/client.ts"]), # ~28h ago
+ ]),
+ }, min_score=0.0)
+ assert len(results) == 0
+
+ def test_temporal_decay(self) -> None:
+ """Recent co-changes should have higher strength than old ones."""
+ now = int(time.time())
+ # Recent pair
+ recent = self._detect_with_mocked_logs({
+ "a": _make_commits("a", [("[email protected]", now - 100, ["f1.py"])]),
+ "b": _make_commits("b", [("[email protected]", now - 200, ["f2.py"])]),
+ }, min_score=0.0)
+
+ # Old pair (6 months ago)
+ old = self._detect_with_mocked_logs({
+ "a": _make_commits("a", [("[email protected]", now - 15_000_000, ["f1.py"])]),
+ "b": _make_commits("b", [("[email protected]", now - 15_000_100, ["f2.py"])]),
+ }, min_score=0.0)
+
+ assert recent and old
+ assert recent[0].strength > old[0].strength
+
+ def test_min_score_filter(self) -> None:
+ """Low-strength edges are filtered by min_score."""
+ now = int(time.time())
+ # Very old commit → low weight
+ results = self._detect_with_mocked_logs({
+ "a": _make_commits("a", [("[email protected]", now - 30_000_000, ["f1.py"])]),
+ "b": _make_commits("b", [("[email protected]", now - 30_000_100, ["f2.py"])]),
+ }, min_score=5.0)
+ assert len(results) == 0
+
+ def test_single_repo_returns_empty(self) -> None:
+ """Only one repo → no cross-repo edges."""
+ now = int(time.time())
+ results = self._detect_with_mocked_logs({
+ "only": _make_commits("only", [
+ ("[email protected]", now, ["f1.py", "f2.py"]),
+ ]),
+ })
+ assert results == []
+
+ def test_multiple_files_per_commit(self) -> None:
+ """N files in commit A × M files in commit B = N*M file pairs."""
+ now = int(time.time())
+ results = self._detect_with_mocked_logs({
+ "a": _make_commits("a", [
+ ("[email protected]", now - 100, ["f1.py", "f2.py"]),
+ ]),
+ "b": _make_commits("b", [
+ ("[email protected]", now - 200, ["g1.py", "g2.py", "g3.py"]),
+ ]),
+ }, min_score=0.0)
+ # 2 × 3 = 6 unique file pairs
+ assert len(results) == 6
+
+
+# ---------------------------------------------------------------------------
+# Manifest scanning
+# ---------------------------------------------------------------------------
+
+
+class TestManifestScanning:
+ def test_npm_file_reference(self, tmp_path: Path) -> None:
+ """package.json with file: reference to sibling repo."""
+ backend = tmp_path / "backend"
+ shared = tmp_path / "shared"
+ backend.mkdir()
+ shared.mkdir()
+
+ pkg = {"dependencies": {"@myorg/shared": "file:../shared"}}
+ (backend / "package.json").write_text(json.dumps(pkg))
+
+ repo_paths = {"backend": backend, "shared": shared}
+ deps = detect_package_dependencies(repo_paths)
+ assert len(deps) == 1
+ assert deps[0].source_repo == "backend"
+ assert deps[0].target_repo == "shared"
+ assert deps[0].kind == "npm_local_path"
+
+ def test_cargo_path_dep(self, tmp_path: Path) -> None:
+ """Cargo.toml with path dependency to sibling repo."""
+ app = tmp_path / "app"
+ lib = tmp_path / "lib"
+ app.mkdir()
+ lib.mkdir()
+
+ cargo_content = '[dependencies]\nmylib = { path = "../lib" }\n'
+ (app / "Cargo.toml").write_text(cargo_content)
+
+ # Need tomllib for parsing
+ try:
+ import tomllib # noqa: F401
+ except ImportError:
+ try:
+ import tomli # noqa: F401
+ except ImportError:
+ pytest.skip("No TOML parser available")
+
+ repo_paths = {"app": app, "lib": lib}
+ deps = detect_package_dependencies(repo_paths)
+ assert any(d.kind == "cargo_path" and d.target_repo == "lib" for d in deps)
+
+ def test_go_replace_directive(self, tmp_path: Path) -> None:
+ """go.mod with replace pointing to sibling repo."""
+ svc = tmp_path / "service"
+ proto = tmp_path / "proto"
+ svc.mkdir()
+ proto.mkdir()
+
+ go_mod = "module example.com/service\n\nreplace example.com/proto => ../proto\n"
+ (svc / "go.mod").write_text(go_mod)
+
+ repo_paths = {"service": svc, "proto": proto}
+ deps = detect_package_dependencies(repo_paths)
+ assert any(d.kind == "go_replace" and d.target_repo == "proto" for d in deps)
+
+ def test_no_manifests(self, tmp_path: Path) -> None:
+ """Repo with no manifest files → no deps."""
+ a = tmp_path / "a"
+ b = tmp_path / "b"
+ a.mkdir()
+ b.mkdir()
+ deps = detect_package_dependencies({"a": a, "b": b})
+ assert deps == []
+
+ def test_reference_outside_workspace(self, tmp_path: Path) -> None:
+ """References to dirs not in repo_paths are ignored."""
+ backend = tmp_path / "backend"
+ backend.mkdir()
+ pkg = {"dependencies": {"external": "file:../../outside"}}
+ (backend / "package.json").write_text(json.dumps(pkg))
+
+ deps = detect_package_dependencies({"backend": backend})
+ assert deps == []
+
+
+# ---------------------------------------------------------------------------
+# Overlay persistence
+# ---------------------------------------------------------------------------
+
+
+class TestOverlayPersistence:
+ def test_save_and_load_round_trip(self, tmp_path: Path) -> None:
+ overlay = CrossRepoOverlay(
+ version=1,
+ generated_at="2026-04-12T12:00:00Z",
+ co_changes=[
+ CrossRepoCoChange(
+ source_repo="a", source_file="f1.py",
+ target_repo="b", target_file="f2.py",
+ strength=3.5, frequency=4, last_date="2026-04-10",
+ ),
+ ],
+ package_deps=[
+ CrossRepoPackageDep(
+ source_repo="b", target_repo="a",
+ source_manifest="package.json", kind="npm_local_path",
+ ),
+ ],
+ repo_summaries={"a": {"cross_repo_edge_count": 1}},
+ )
+ save_overlay(overlay, tmp_path)
+ loaded = load_overlay(tmp_path)
+ assert loaded is not None
+ assert loaded.version == 1
+ assert len(loaded.co_changes) == 1
+ assert loaded.co_changes[0].strength == 3.5
+ assert len(loaded.package_deps) == 1
+ assert loaded.package_deps[0].kind == "npm_local_path"
+
+ def test_load_missing_file_returns_none(self, tmp_path: Path) -> None:
+ assert load_overlay(tmp_path) is None
+
+ def test_load_corrupt_json_returns_none(self, tmp_path: Path) -> None:
+ data_dir = tmp_path / ".repowise-workspace"
+ data_dir.mkdir()
+ (data_dir / CROSS_REPO_EDGES_FILENAME).write_text("not json!!!")
+ assert load_overlay(tmp_path) is None
+
+ def test_save_creates_data_dir(self, tmp_path: Path) -> None:
+ overlay = CrossRepoOverlay()
+ path = save_overlay(overlay, tmp_path)
+ assert path.is_file()
+ assert (tmp_path / ".repowise-workspace").is_dir()
diff --git a/tests/unit/workspace/test_registry.py b/tests/unit/workspace/test_registry.py
new file mode 100644
index 000000000..4d27b2a26
--- /dev/null
+++ b/tests/unit/workspace/test_registry.py
@@ -0,0 +1,289 @@
+"""Tests for repowise.core.workspace.registry — RepoRegistry and RepoContext."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.persistence.database import init_db
+from repowise.core.persistence.models import Page, Repository
+from repowise.core.workspace.config import RepoEntry, WorkspaceConfig
+from repowise.core.workspace.registry import RepoContext, RepoRegistry
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+_NOW = datetime(2026, 4, 12, 10, 0, 0, tzinfo=UTC)
+
+
+def _make_workspace(tmp_path: Path, repo_names: list[str], default: str | None = None) -> WorkspaceConfig:
+ """Create repo dirs with .repowise/wiki.db and return a WorkspaceConfig."""
+ entries = []
+ for name in repo_names:
+ repo_dir = tmp_path / name
+ repo_dir.mkdir(parents=True, exist_ok=True)
+ repowise_dir = repo_dir / ".repowise"
+ repowise_dir.mkdir(exist_ok=True)
+ # Create an empty wiki.db — init_db will create tables on first access
+ (repowise_dir / "wiki.db").write_bytes(b"")
+ entries.append(RepoEntry(path=name, alias=name))
+
+ if entries and not default:
+ default = entries[0].alias
+ entries[0].is_primary = True
+
+ config = WorkspaceConfig(
+ version=1,
+ repos=entries,
+ default_repo=default,
+ )
+ config.save(tmp_path)
+ return config
+
+
+async def _seed_repo_db(repo_path: Path, repo_name: str) -> None:
+ """Seed a repo's wiki.db with minimal data for testing."""
+ db_path = repo_path / ".repowise" / "wiki.db"
+ url = f"sqlite+aiosqlite:///{db_path.as_posix()}"
+ engine = create_async_engine(
+ url,
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+
+ factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+ async with factory() as session:
+ repo = Repository(
+ id=f"repo-{repo_name}",
+ name=repo_name,
+ url=f"https://example.com/{repo_name}",
+ local_path=str(repo_path),
+ default_branch="main",
+ settings_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ )
+ session.add(repo)
+ session.add(Page(
+ id=f"repo_overview:{repo_name}",
+ repository_id=repo.id,
+ page_type="repo_overview",
+ title=f"{repo_name} Overview",
+ content=f"# {repo_name}\n\nOverview of {repo_name}.",
+ target_path=repo_name,
+ source_hash="abc",
+ model_name="mock",
+ provider_name="mock",
+ generation_level=6,
+ confidence=1.0,
+ freshness_status="fresh",
+ metadata_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ))
+ await session.commit()
+ await engine.dispose()
+
+
+# ---------------------------------------------------------------------------
+# resolve_repo_param
+# ---------------------------------------------------------------------------
+
+
+class TestResolveRepoParam:
+ def test_none_returns_default(self, tmp_path: Path) -> None:
+ config = _make_workspace(tmp_path, ["backend", "frontend"], default="backend")
+ registry = RepoRegistry(tmp_path, config)
+ assert registry.resolve_repo_param(None) == "backend"
+
+ def test_all_returns_all_aliases(self, tmp_path: Path) -> None:
+ config = _make_workspace(tmp_path, ["backend", "frontend", "shared"])
+ registry = RepoRegistry(tmp_path, config)
+ result = registry.resolve_repo_param("all")
+ assert isinstance(result, list)
+ assert set(result) == {"backend", "frontend", "shared"}
+
+ def test_valid_alias(self, tmp_path: Path) -> None:
+ config = _make_workspace(tmp_path, ["backend", "frontend"])
+ registry = RepoRegistry(tmp_path, config)
+ assert registry.resolve_repo_param("frontend") == "frontend"
+
+ def test_invalid_alias_raises(self, tmp_path: Path) -> None:
+ config = _make_workspace(tmp_path, ["backend", "frontend"])
+ registry = RepoRegistry(tmp_path, config)
+ with pytest.raises(ValueError, match="Unknown repo"):
+ registry.resolve_repo_param("nonexistent")
+
+
+# ---------------------------------------------------------------------------
+# Lazy loading
+# ---------------------------------------------------------------------------
+
+
+class TestLazyLoading:
+ @pytest.mark.asyncio
+ async def test_get_loads_context(self, tmp_path: Path) -> None:
+ config = _make_workspace(tmp_path, ["backend"])
+ await _seed_repo_db(tmp_path / "backend", "backend")
+ registry = RepoRegistry(tmp_path, config)
+
+ ctx = await registry.get("backend")
+ assert isinstance(ctx, RepoContext)
+ assert ctx.alias == "backend"
+ assert ctx.session_factory is not None
+ assert ctx.fts is not None
+
+ await registry.close()
+
+ @pytest.mark.asyncio
+ async def test_get_default(self, tmp_path: Path) -> None:
+ config = _make_workspace(tmp_path, ["backend", "frontend"], default="frontend")
+ await _seed_repo_db(tmp_path / "frontend", "frontend")
+ registry = RepoRegistry(tmp_path, config)
+
+ ctx = await registry.get_default()
+ assert ctx.alias == "frontend"
+
+ await registry.close()
+
+ @pytest.mark.asyncio
+ async def test_same_alias_returns_cached(self, tmp_path: Path) -> None:
+ config = _make_workspace(tmp_path, ["backend"])
+ await _seed_repo_db(tmp_path / "backend", "backend")
+ registry = RepoRegistry(tmp_path, config)
+
+ ctx1 = await registry.get("backend")
+ ctx2 = await registry.get("backend")
+ assert ctx1 is ctx2
+
+ await registry.close()
+
+
+# ---------------------------------------------------------------------------
+# LRU eviction
+# ---------------------------------------------------------------------------
+
+
+class TestLRUEviction:
+ @pytest.mark.asyncio
+ async def test_evicts_at_capacity(self, tmp_path: Path) -> None:
+ # MAX_LOADED caps non-default repos; default is always kept.
+ # With MAX_LOADED=2: at most 2 non-default + 1 default = 3 total.
+ names = ["repo1", "repo2", "repo3", "repo4"]
+ config = _make_workspace(tmp_path, names, default="repo1")
+ for name in names:
+ await _seed_repo_db(tmp_path / name, name)
+
+ registry = RepoRegistry(tmp_path, config)
+ registry.MAX_LOADED = 2
+
+ # Load default + 2 non-default — at capacity (2 non-default)
+ await registry.get("repo1")
+ await registry.get("repo2")
+ await registry.get("repo3")
+ assert len(registry._contexts) == 3
+ non_default = [a for a in registry._contexts if a != "repo1"]
+ assert len(non_default) == 2
+
+ # repo2 is LRU non-default; loading repo4 must evict repo2
+ await registry.get("repo4")
+ assert len(registry._contexts) == 3
+ assert "repo2" not in registry._contexts
+ assert "repo4" in registry._contexts
+
+ await registry.close()
+
+ @pytest.mark.asyncio
+ async def test_cap_not_bypassed_when_default_loaded(self, tmp_path: Path) -> None:
+ """Non-default context count must not exceed MAX_LOADED even when the
+ default repo occupies one of the loaded slots."""
+ names = ["default_repo", "r1", "r2", "r3", "r4"]
+ config = _make_workspace(tmp_path, names, default="default_repo")
+ for name in names:
+ await _seed_repo_db(tmp_path / name, name)
+
+ registry = RepoRegistry(tmp_path, config)
+ registry.MAX_LOADED = 3
+
+ # Load default + MAX_LOADED non-default repos — fills the cap
+ await registry.get("default_repo")
+ await registry.get("r1")
+ await registry.get("r2")
+ await registry.get("r3")
+ # 4 total loaded: default + 3 non-default (exactly at cap)
+ assert len(registry._contexts) == 4
+
+ # Loading one more non-default must evict an existing non-default,
+ # keeping the total non-default count at MAX_LOADED (3).
+ await registry.get("r4")
+ non_default = [a for a in registry._contexts if a != "default_repo"]
+ assert len(non_default) == registry.MAX_LOADED
+ assert "r4" in registry._contexts
+ assert "default_repo" in registry._contexts
+
+ await registry.close()
+
+ @pytest.mark.asyncio
+ async def test_default_never_evicted(self, tmp_path: Path) -> None:
+ # MAX_LOADED=1 caps non-default repos at 1; default is always kept.
+ names = ["default_repo", "other1", "other2", "other3"]
+ config = _make_workspace(tmp_path, names, default="default_repo")
+ for name in names:
+ await _seed_repo_db(tmp_path / name, name)
+
+ registry = RepoRegistry(tmp_path, config)
+ registry.MAX_LOADED = 1
+
+ # Load default + other1 — at capacity (1 non-default)
+ await registry.get("default_repo")
+ await registry.get("other1")
+ assert len(registry._contexts) == 2
+
+ # Load other2 — should evict other1, not default_repo
+ await registry.get("other2")
+ assert "default_repo" in registry._contexts
+ assert "other1" not in registry._contexts
+
+ await registry.close()
+
+
+# ---------------------------------------------------------------------------
+# Close
+# ---------------------------------------------------------------------------
+
+
+class TestClose:
+ @pytest.mark.asyncio
+ async def test_close_disposes_all(self, tmp_path: Path) -> None:
+ config = _make_workspace(tmp_path, ["backend", "frontend"])
+ await _seed_repo_db(tmp_path / "backend", "backend")
+ await _seed_repo_db(tmp_path / "frontend", "frontend")
+ registry = RepoRegistry(tmp_path, config)
+
+ await registry.get("backend")
+ await registry.get("frontend")
+ assert len(registry._contexts) == 2
+
+ await registry.close()
+ assert len(registry._contexts) == 0
+
+
+# ---------------------------------------------------------------------------
+# get_all_aliases
+# ---------------------------------------------------------------------------
+
+
+class TestGetAllAliases:
+ def test_returns_all(self, tmp_path: Path) -> None:
+ config = _make_workspace(tmp_path, ["a", "b", "c"])
+ registry = RepoRegistry(tmp_path, config)
+ assert registry.get_all_aliases() == ["a", "b", "c"]
diff --git a/tests/unit/workspace/test_scanner.py b/tests/unit/workspace/test_scanner.py
new file mode 100644
index 000000000..f7824a3b0
--- /dev/null
+++ b/tests/unit/workspace/test_scanner.py
@@ -0,0 +1,297 @@
+"""Tests for repowise.core.workspace.scanner — repo discovery."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.workspace.scanner import (
+ DiscoveredRepo,
+ ScanResult,
+ _generate_aliases,
+ _is_git_repo,
+ _is_submodule,
+ scan_for_repos,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_repo(tmp_path: Path, rel: str) -> Path:
+ """Create a fake git repo at ``tmp_path / rel`` (with a .git directory)."""
+ p = tmp_path / rel
+ p.mkdir(parents=True, exist_ok=True)
+ (p / ".git").mkdir()
+ return p
+
+
+def _make_submodule(tmp_path: Path, rel: str) -> Path:
+ """Create a fake submodule at ``tmp_path / rel`` (.git is a file)."""
+ p = tmp_path / rel
+ p.mkdir(parents=True, exist_ok=True)
+ (p / ".git").write_text("gitdir: ../.git/modules/sub")
+ return p
+
+
+def _make_indexed_repo(tmp_path: Path, rel: str) -> Path:
+ """Create a fake repo with an existing .repowise/ directory."""
+ p = _make_repo(tmp_path, rel)
+ (p / ".repowise").mkdir()
+ return p
+
+
+# ---------------------------------------------------------------------------
+# scan_for_repos — basic cases
+# ---------------------------------------------------------------------------
+
+
+class TestScanForRepos:
+ def test_empty_dir(self, tmp_path: Path) -> None:
+ result = scan_for_repos(tmp_path)
+ assert result.repos == []
+ assert result.root == tmp_path.resolve()
+
+ def test_single_repo_at_root(self, tmp_path: Path) -> None:
+ (tmp_path / ".git").mkdir()
+ result = scan_for_repos(tmp_path)
+ assert len(result.repos) == 1
+ assert result.repos[0].path == tmp_path.resolve()
+ assert result.repos[0].is_submodule is False
+
+ def test_multiple_repos_at_depth_1(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "backend")
+ _make_repo(tmp_path, "frontend")
+ _make_repo(tmp_path, "shared-libs")
+
+ result = scan_for_repos(tmp_path)
+ aliases = {r.alias for r in result.repos}
+ assert aliases == {"backend", "frontend", "shared-libs"}
+ assert len(result.repos) == 3
+
+ def test_repos_sorted_alphabetically(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "zebra")
+ _make_repo(tmp_path, "alpha")
+ _make_repo(tmp_path, "middle")
+
+ result = scan_for_repos(tmp_path)
+ names = [r.name for r in result.repos]
+ assert names == ["alpha", "middle", "zebra"]
+
+ def test_root_is_repo_with_sub_repos(self, tmp_path: Path) -> None:
+ """When root itself is a git repo AND has sub-repos, all are returned."""
+ (tmp_path / ".git").mkdir() # root is a git repo
+ _make_repo(tmp_path, "backend")
+ _make_repo(tmp_path, "frontend")
+
+ result = scan_for_repos(tmp_path)
+ aliases = {r.alias for r in result.repos}
+ assert len(result.repos) == 3
+ assert tmp_path.name in aliases or "." in aliases or tmp_path.resolve() in {r.path for r in result.repos}
+ assert "backend" in aliases
+ assert "frontend" in aliases
+
+ def test_root_is_repo_no_sub_repos(self, tmp_path: Path) -> None:
+ """When root is a git repo with no sub-repos, single-repo result."""
+ (tmp_path / ".git").mkdir()
+ result = scan_for_repos(tmp_path)
+ assert len(result.repos) == 1
+ assert result.repos[0].path == tmp_path.resolve()
+
+ def test_nested_repos_outer_wins(self, tmp_path: Path) -> None:
+ """If repo A contains repo B, only A is found (B is not descended into)."""
+ outer = _make_repo(tmp_path, "monorepo")
+ # Inner repo would be found if we descended, but we shouldn't
+ (outer / "packages" / "sub").mkdir(parents=True)
+ (outer / "packages" / "sub" / ".git").mkdir()
+
+ result = scan_for_repos(tmp_path)
+ assert len(result.repos) == 1
+ assert result.repos[0].name == "monorepo"
+
+ def test_repos_at_depth_2(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "org/backend")
+ _make_repo(tmp_path, "org/frontend")
+
+ result = scan_for_repos(tmp_path)
+ assert len(result.repos) == 2
+ aliases = {r.alias for r in result.repos}
+ assert aliases == {"backend", "frontend"}
+
+ def test_respects_max_depth(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "a/b/c/deep-repo")
+
+ # Default max_depth=3 should NOT find it (depth of deep-repo is 3,
+ # but we check children at depth 2 which means depth 3 is the boundary)
+ result = scan_for_repos(tmp_path, max_depth=2)
+ assert len(result.repos) == 0
+
+ result = scan_for_repos(tmp_path, max_depth=4)
+ assert len(result.repos) == 1
+
+
+# ---------------------------------------------------------------------------
+# scan_for_repos — skip directories
+# ---------------------------------------------------------------------------
+
+
+class TestScanSkipDirs:
+ def test_skips_node_modules(self, tmp_path: Path) -> None:
+ nm = tmp_path / "node_modules" / "some-pkg"
+ nm.mkdir(parents=True)
+ (nm / ".git").mkdir()
+
+ result = scan_for_repos(tmp_path)
+ assert len(result.repos) == 0
+ assert any("node_modules" in s for s in result.skipped_dirs)
+
+ def test_skips_venv(self, tmp_path: Path) -> None:
+ venv = tmp_path / ".venv" / "lib"
+ venv.mkdir(parents=True)
+
+ result = scan_for_repos(tmp_path)
+ assert len(result.repos) == 0
+
+ def test_skips_hidden_dirs(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, ".hidden-project")
+
+ result = scan_for_repos(tmp_path)
+ assert len(result.repos) == 0
+
+ def test_does_not_skip_repowise_dir(self, tmp_path: Path) -> None:
+ """The .repowise directory itself should not be skipped during scanning."""
+ _make_repo(tmp_path, "myrepo")
+ (tmp_path / "myrepo" / ".repowise").mkdir()
+
+ result = scan_for_repos(tmp_path)
+ assert len(result.repos) == 1
+ assert result.repos[0].has_repowise is True
+
+
+# ---------------------------------------------------------------------------
+# scan_for_repos — submodules
+# ---------------------------------------------------------------------------
+
+
+class TestScanSubmodules:
+ def test_submodule_excluded_by_default(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "main-repo")
+ _make_submodule(tmp_path, "sub-repo")
+
+ result = scan_for_repos(tmp_path)
+ assert len(result.repos) == 1
+ assert result.repos[0].name == "main-repo"
+
+ def test_submodule_included_with_flag(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "main-repo")
+ _make_submodule(tmp_path, "sub-repo")
+
+ result = scan_for_repos(tmp_path, include_submodules=True)
+ assert len(result.repos) == 2
+ sub = next(r for r in result.repos if r.name == "sub-repo")
+ assert sub.is_submodule is True
+
+ def test_submodule_at_root_excluded(self, tmp_path: Path) -> None:
+ """Root itself is a submodule and include_submodules=False."""
+ (tmp_path / ".git").write_text("gitdir: ../.git/modules/x")
+
+ result = scan_for_repos(tmp_path, include_submodules=False)
+ assert len(result.repos) == 0
+
+
+# ---------------------------------------------------------------------------
+# scan_for_repos — metadata
+# ---------------------------------------------------------------------------
+
+
+class TestScanMetadata:
+ def test_has_repowise_detected(self, tmp_path: Path) -> None:
+ _make_indexed_repo(tmp_path, "indexed-repo")
+ _make_repo(tmp_path, "new-repo")
+
+ result = scan_for_repos(tmp_path)
+ indexed = next(r for r in result.repos if r.name == "indexed-repo")
+ new = next(r for r in result.repos if r.name == "new-repo")
+ assert indexed.has_repowise is True
+ assert new.has_repowise is False
+
+ def test_paths_are_absolute(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "myrepo")
+
+ result = scan_for_repos(tmp_path)
+ assert result.repos[0].path.is_absolute()
+ assert result.root.is_absolute()
+
+
+# ---------------------------------------------------------------------------
+# alias generation
+# ---------------------------------------------------------------------------
+
+
+class TestAliasGeneration:
+ def test_unique_names(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "backend")
+ _make_repo(tmp_path, "frontend")
+
+ result = scan_for_repos(tmp_path)
+ aliases = [r.alias for r in result.repos]
+ assert len(set(aliases)) == len(aliases)
+
+ def test_collision_suffixed(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "org1/api")
+ _make_repo(tmp_path, "org2/api")
+
+ result = scan_for_repos(tmp_path)
+ aliases = sorted(r.alias for r in result.repos)
+ assert aliases == ["api", "api-2"]
+
+ def test_triple_collision(self, tmp_path: Path) -> None:
+ _make_repo(tmp_path, "a/svc")
+ _make_repo(tmp_path, "b/svc")
+ _make_repo(tmp_path, "c/svc")
+
+ result = scan_for_repos(tmp_path)
+ aliases = sorted(r.alias for r in result.repos)
+ assert aliases == ["svc", "svc-2", "svc-3"]
+
+
+# ---------------------------------------------------------------------------
+# Helper functions
+# ---------------------------------------------------------------------------
+
+
+class TestHelpers:
+ def test_is_git_repo_dir(self, tmp_path: Path) -> None:
+ (tmp_path / ".git").mkdir()
+ assert _is_git_repo(tmp_path) is True
+
+ def test_is_git_repo_file(self, tmp_path: Path) -> None:
+ (tmp_path / ".git").write_text("gitdir: something")
+ assert _is_git_repo(tmp_path) is True
+
+ def test_is_not_git_repo(self, tmp_path: Path) -> None:
+ assert _is_git_repo(tmp_path) is False
+
+ def test_is_submodule(self, tmp_path: Path) -> None:
+ (tmp_path / ".git").write_text("gitdir: ../.git/modules/x")
+ assert _is_submodule(tmp_path) is True
+
+ def test_is_not_submodule(self, tmp_path: Path) -> None:
+ (tmp_path / ".git").mkdir()
+ assert _is_submodule(tmp_path) is False
+
+ def test_generate_aliases_no_collision(self) -> None:
+ root = Path("/ws")
+ pairs = [(Path("/ws/a"), root), (Path("/ws/b"), root)]
+ aliases = _generate_aliases(pairs)
+ assert aliases == {Path("/ws/a"): "a", Path("/ws/b"): "b"}
+
+ def test_generate_aliases_collision(self) -> None:
+ root = Path("/ws")
+ pairs = [(Path("/ws/x/api"), root), (Path("/ws/y/api"), root)]
+ aliases = _generate_aliases(pairs)
+ assert aliases[Path("/ws/x/api")] == "api"
+ assert aliases[Path("/ws/y/api")] == "api-2"
diff --git a/tests/unit/workspace/test_update.py b/tests/unit/workspace/test_update.py
new file mode 100644
index 000000000..c2c8a4824
--- /dev/null
+++ b/tests/unit/workspace/test_update.py
@@ -0,0 +1,321 @@
+"""Tests for repowise.core.workspace.update — staleness and update orchestration."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from repowise.core.workspace.config import RepoEntry, WorkspaceConfig
+from repowise.core.workspace.update import (
+ RepoUpdateResult,
+ check_repo_staleness,
+ count_commits_between,
+ get_head_commit,
+ run_cross_repo_hooks,
+ update_workspace,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_git_repo(tmp_path: Path, name: str) -> Path:
+ """Create a real git repo with an initial commit."""
+ repo = tmp_path / name
+ repo.mkdir(parents=True)
+ subprocess.run(["git", "init"], cwd=str(repo), capture_output=True)
+ subprocess.run(
+ ["git", "config", "user.email", "[email protected]"],
+ cwd=str(repo), capture_output=True,
+ )
+ subprocess.run(
+ ["git", "config", "user.name", "Test"],
+ cwd=str(repo), capture_output=True,
+ )
+ (repo / "README.md").write_text("hello")
+ subprocess.run(["git", "add", "."], cwd=str(repo), capture_output=True)
+ subprocess.run(
+ ["git", "commit", "-m", "initial"],
+ cwd=str(repo), capture_output=True,
+ )
+ return repo
+
+
+def _add_commit(repo: Path, filename: str = "change.txt", msg: str = "update") -> str:
+ """Add a file and commit. Returns the new commit SHA."""
+ (repo / filename).write_text(f"change-{msg}")
+ subprocess.run(["git", "add", "."], cwd=str(repo), capture_output=True)
+ subprocess.run(["git", "commit", "-m", msg], cwd=str(repo), capture_output=True)
+ result = subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=str(repo), capture_output=True, text=True,
+ )
+ return result.stdout.strip()
+
+
+def _write_state(repo: Path, commit: str | None) -> None:
+ """Write a state.json with the given commit."""
+ state_dir = repo / ".repowise"
+ state_dir.mkdir(parents=True, exist_ok=True)
+ state = {}
+ if commit:
+ state["last_sync_commit"] = commit
+ (state_dir / "state.json").write_text(json.dumps(state), encoding="utf-8")
+
+
+# ---------------------------------------------------------------------------
+# get_head_commit
+# ---------------------------------------------------------------------------
+
+
+class TestGetHeadCommit:
+ def test_returns_sha(self, tmp_path: Path) -> None:
+ repo = _make_git_repo(tmp_path, "myrepo")
+ head = get_head_commit(repo)
+ assert head is not None
+ assert len(head) == 40
+
+ def test_non_git_returns_none(self, tmp_path: Path) -> None:
+ assert get_head_commit(tmp_path) is None
+
+
+# ---------------------------------------------------------------------------
+# check_repo_staleness
+# ---------------------------------------------------------------------------
+
+
+class TestCheckRepoStaleness:
+ def test_same_commit_not_stale(self, tmp_path: Path) -> None:
+ repo = _make_git_repo(tmp_path, "myrepo")
+ head = get_head_commit(repo)
+ is_stale, current, behind = check_repo_staleness(repo, head)
+ assert is_stale is False
+ assert current == head
+ assert behind == 0
+
+ def test_different_commit_stale(self, tmp_path: Path) -> None:
+ repo = _make_git_repo(tmp_path, "myrepo")
+ old_head = get_head_commit(repo)
+ _add_commit(repo, "file1.txt", "second commit")
+ is_stale, current, behind = check_repo_staleness(repo, old_head)
+ assert is_stale is True
+ assert current != old_head
+ assert behind == 1
+
+ def test_no_stored_commit_stale(self, tmp_path: Path) -> None:
+ repo = _make_git_repo(tmp_path, "myrepo")
+ is_stale, current, behind = check_repo_staleness(repo, None)
+ assert is_stale is True
+ assert current is not None
+
+ def test_multiple_commits_behind(self, tmp_path: Path) -> None:
+ repo = _make_git_repo(tmp_path, "myrepo")
+ old_head = get_head_commit(repo)
+ _add_commit(repo, "a.txt", "commit 2")
+ _add_commit(repo, "b.txt", "commit 3")
+ _add_commit(repo, "c.txt", "commit 4")
+ is_stale, current, behind = check_repo_staleness(repo, old_head)
+ assert is_stale is True
+ assert behind == 3
+
+ def test_non_git_dir_not_stale(self, tmp_path: Path) -> None:
+ is_stale, current, behind = check_repo_staleness(tmp_path, "abc123")
+ assert is_stale is False
+ assert current is None
+
+
+# ---------------------------------------------------------------------------
+# count_commits_between
+# ---------------------------------------------------------------------------
+
+
+class TestCountCommitsBetween:
+ def test_counts_correctly(self, tmp_path: Path) -> None:
+ repo = _make_git_repo(tmp_path, "myrepo")
+ old = get_head_commit(repo)
+ _add_commit(repo, "a.txt")
+ _add_commit(repo, "b.txt")
+ new = get_head_commit(repo)
+ assert count_commits_between(repo, old, new) == 2
+
+ def test_zero_when_same(self, tmp_path: Path) -> None:
+ repo = _make_git_repo(tmp_path, "myrepo")
+ head = get_head_commit(repo)
+ assert count_commits_between(repo, head, head) == 0
+
+
+# ---------------------------------------------------------------------------
+# update_workspace
+# ---------------------------------------------------------------------------
+
+
+class TestUpdateWorkspace:
+ def test_skips_up_to_date(self, tmp_path: Path) -> None:
+ """Repos with same HEAD should be skipped."""
+ repo = _make_git_repo(tmp_path, "backend")
+ head = get_head_commit(repo)
+ _write_state(repo, head)
+
+ ws_config = WorkspaceConfig(
+ repos=[RepoEntry(path="backend", alias="backend", last_commit_at_index=head)],
+ default_repo="backend",
+ )
+ ws_config.save(tmp_path)
+
+ async def _run():
+ return await update_workspace(tmp_path, ws_config)
+
+ import asyncio
+ results = asyncio.run(_run())
+ assert len(results) == 1
+ assert results[0].updated is False
+ assert results[0].skipped_reason == "up_to_date"
+
+ def test_detects_stale_repo(self, tmp_path: Path) -> None:
+ """Repos with new commits should be detected as stale."""
+ repo = _make_git_repo(tmp_path, "backend")
+ old_head = get_head_commit(repo)
+ _write_state(repo, old_head)
+ _add_commit(repo, "new_file.txt")
+
+ ws_config = WorkspaceConfig(
+ repos=[RepoEntry(path="backend", alias="backend", last_commit_at_index=old_head)],
+ default_repo="backend",
+ )
+ ws_config.save(tmp_path)
+
+ # Mock update_single_repo_index to avoid running the full pipeline
+ mock_result = RepoUpdateResult(alias="backend", updated=True, file_count=10, symbol_count=50)
+
+ async def _run():
+ with patch(
+ "repowise.core.workspace.update.update_single_repo_index",
+ new_callable=AsyncMock,
+ return_value=mock_result,
+ ):
+ return await update_workspace(tmp_path, ws_config)
+
+ import asyncio
+ results = asyncio.run(_run())
+ updated = [r for r in results if r.updated]
+ assert len(updated) == 1
+ assert updated[0].alias == "backend"
+
+ def test_repo_filter(self, tmp_path: Path) -> None:
+ """--repo flag should only update the specified repo."""
+ repo_a = _make_git_repo(tmp_path, "backend")
+ repo_b = _make_git_repo(tmp_path, "frontend")
+ old_a = get_head_commit(repo_a)
+ old_b = get_head_commit(repo_b)
+ _write_state(repo_a, old_a)
+ _write_state(repo_b, old_b)
+ _add_commit(repo_a, "a.txt")
+ _add_commit(repo_b, "b.txt")
+
+ ws_config = WorkspaceConfig(
+ repos=[
+ RepoEntry(path="backend", alias="backend", last_commit_at_index=old_a),
+ RepoEntry(path="frontend", alias="frontend", last_commit_at_index=old_b),
+ ],
+ default_repo="backend",
+ )
+ ws_config.save(tmp_path)
+
+ mock_result = RepoUpdateResult(alias="backend", updated=True, file_count=5, symbol_count=20)
+
+ async def _run():
+ with patch(
+ "repowise.core.workspace.update.update_single_repo_index",
+ new_callable=AsyncMock,
+ return_value=mock_result,
+ ):
+ return await update_workspace(tmp_path, ws_config, repo_filter="backend")
+
+ import asyncio
+ results = asyncio.run(_run())
+ # Only backend should appear (frontend filtered out)
+ assert len(results) == 1
+ assert results[0].alias == "backend"
+
+ def test_invalid_repo_filter_raises(self, tmp_path: Path) -> None:
+ ws_config = WorkspaceConfig(
+ repos=[RepoEntry(path="backend", alias="backend")],
+ )
+
+ async def _run():
+ return await update_workspace(tmp_path, ws_config, repo_filter="nonexistent")
+
+ import asyncio
+ with pytest.raises(ValueError, match="Unknown repo"):
+ asyncio.run(_run())
+
+ def test_not_indexed_skipped(self, tmp_path: Path) -> None:
+ """Repos without .repowise/ should be skipped."""
+ repo = _make_git_repo(tmp_path, "backend")
+ # No .repowise/ dir, no state.json
+
+ ws_config = WorkspaceConfig(
+ repos=[RepoEntry(path="backend", alias="backend")],
+ )
+
+ async def _run():
+ return await update_workspace(tmp_path, ws_config)
+
+ import asyncio
+ results = asyncio.run(_run())
+ assert len(results) == 1
+ assert results[0].skipped_reason == "not_indexed"
+
+ def test_dry_run(self, tmp_path: Path) -> None:
+ """Dry run should not perform any updates."""
+ repo = _make_git_repo(tmp_path, "backend")
+ old_head = get_head_commit(repo)
+ _write_state(repo, old_head)
+ _add_commit(repo, "new.txt")
+
+ ws_config = WorkspaceConfig(
+ repos=[RepoEntry(path="backend", alias="backend", last_commit_at_index=old_head)],
+ )
+
+ async def _run():
+ return await update_workspace(tmp_path, ws_config, dry_run=True)
+
+ import asyncio
+ results = asyncio.run(_run())
+ # Stale repos detected but not updated
+ updated = [r for r in results if r.updated]
+ assert len(updated) == 0
+
+
+# ---------------------------------------------------------------------------
+# Cross-repo hooks placeholder
+# ---------------------------------------------------------------------------
+
+
+class TestCrossRepoHooks:
+ def test_runs_without_error(self, tmp_path: Path) -> None:
+ """Placeholder hook should be a no-op."""
+ ws_config = WorkspaceConfig(repos=[])
+
+ import asyncio
+ asyncio.run(run_cross_repo_hooks(ws_config, tmp_path, ["backend"]))
+
+
+# ---------------------------------------------------------------------------
+# RepoUpdateResult
+# ---------------------------------------------------------------------------
+
+
+class TestRepoUpdateResult:
+ def test_defaults(self) -> None:
+ r = RepoUpdateResult(alias="test", updated=False)
+ assert r.file_count == 0
+ assert r.symbol_count == 0
+ assert r.error is None
+ assert r.skipped_reason is None
diff --git a/uv.lock b/uv.lock
index 8a7a7711e..d48412f0b 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2,9 +2,12 @@ version = 1
revision = 3
requires-python = ">=3.11"
resolution-markers = [
- "python_full_version >= '3.14'",
+ "python_full_version >= '3.14' and sys_platform == 'win32'",
+ "python_full_version >= '3.14' and sys_platform == 'emscripten'",
+ "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'",
"python_full_version == '3.13.*'",
- "python_full_version < '3.13'",
+ "python_full_version == '3.12.*'",
+ "python_full_version < '3.12'",
]
[manifest]
@@ -212,6 +215,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/38/0e/27be9fdef66e72d64c0cdc3cc2823101b80585f8119b5c112c2e8f5f7dab/anyio-4.12.1-py3-none-any.whl", hash = "sha256:d405828884fc140aa80a3c667b8beed277f1dfedec42ba031bd6ac3db606ab6c", size = 113592, upload-time = "2026-01-06T11:45:19.497Z" },
]
+[[package]]
+name = "anytree"
+version = "2.13.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/bc/a8/eb55fab589c56f9b6be2b3fd6997aa04bb6f3da93b01154ce6fc8e799db2/anytree-2.13.0.tar.gz", hash = "sha256:c9d3aa6825fdd06af7ebb05b4ef291d2db63e62bb1f9b7d9b71354be9d362714", size = 48389, upload-time = "2025-04-08T21:06:30.662Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7b/98/f6aa7fe0783e42be3093d8ef1b0ecdc22c34c0d69640dfb37f56925cb141/anytree-2.13.0-py3-none-any.whl", hash = "sha256:4cbcf10df36b1f1cba131b7e487ff3edafc9d6e932a3c70071b5b768bab901ff", size = 45077, upload-time = "2025-04-08T21:06:29.494Z" },
+]
+
[[package]]
name = "apscheduler"
version = "3.11.2"
@@ -281,6 +293,27 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/3a/2a/7cc015f5b9f5db42b7d48157e23356022889fc354a2813c15934b7cb5c0e/attrs-25.4.0-py3-none-any.whl", hash = "sha256:adcf7e2a1fb3b36ac48d97835bb6d8ade15b8dcce26aba8bf1d14847b57a3373", size = 67615, upload-time = "2025-10-06T13:54:43.17Z" },
]
+[[package]]
+name = "autograd"
+version = "1.8.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/67/1c/3c24ec03c8ba4decc742b1df5a10c52f98c84ca8797757f313e7bdcdf276/autograd-1.8.0.tar.gz", hash = "sha256:107374ded5b09fc8643ac925348c0369e7b0e73bbed9565ffd61b8fd04425683", size = 2562146, upload-time = "2025-05-05T12:49:02.502Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/84/ea/e16f0c423f7d83cf8b79cae9452040fb7b2e020c7439a167ee7c317de448/autograd-1.8.0-py3-none-any.whl", hash = "sha256:4ab9084294f814cf56c280adbe19612546a35574d67c574b04933c7d2ecb7d78", size = 51478, upload-time = "2025-05-05T12:49:00.585Z" },
+]
+
+[[package]]
+name = "beartype"
+version = "0.18.5"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/96/15/4e623478a9628ad4cee2391f19aba0b16c1dd6fedcb2a399f0928097b597/beartype-0.18.5.tar.gz", hash = "sha256:264ddc2f1da9ec94ff639141fbe33d22e12a9f75aa863b83b7046ffff1381927", size = 1193506, upload-time = "2024-04-21T07:25:58.64Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/64/43/7a1259741bd989723272ac7d381a43be932422abcff09a1d9f7ba212cb74/beartype-0.18.5-py3-none-any.whl", hash = "sha256:5301a14f2a9a5540fe47ec6d34d758e9cd8331d36c4760fc7a5499ab86310089", size = 917762, upload-time = "2024-04-21T07:25:55.758Z" },
+]
+
[[package]]
name = "build"
version = "1.4.2"
@@ -484,6 +517,88 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
]
+[[package]]
+name = "contourpy"
+version = "1.3.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/91/2e/c4390a31919d8a78b90e8ecf87cd4b4c4f05a5b48d05ec17db8e5404c6f4/contourpy-1.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:709a48ef9a690e1343202916450bc48b9e51c049b089c7f79a267b46cffcdaa1", size = 288773, upload-time = "2025-07-26T12:01:02.277Z" },
+ { url = "https://files.pythonhosted.org/packages/0d/44/c4b0b6095fef4dc9c420e041799591e3b63e9619e3044f7f4f6c21c0ab24/contourpy-1.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:23416f38bfd74d5d28ab8429cc4d63fa67d5068bd711a85edb1c3fb0c3e2f381", size = 270149, upload-time = "2025-07-26T12:01:04.072Z" },
+ { url = "https://files.pythonhosted.org/packages/30/2e/dd4ced42fefac8470661d7cb7e264808425e6c5d56d175291e93890cce09/contourpy-1.3.3-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:929ddf8c4c7f348e4c0a5a3a714b5c8542ffaa8c22954862a46ca1813b667ee7", size = 329222, upload-time = "2025-07-26T12:01:05.688Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/74/cc6ec2548e3d276c71389ea4802a774b7aa3558223b7bade3f25787fafc2/contourpy-1.3.3-cp311-cp311-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e999574eddae35f1312c2b4b717b7885d4edd6cb46700e04f7f02db454e67c1", size = 377234, upload-time = "2025-07-26T12:01:07.054Z" },
+ { url = "https://files.pythonhosted.org/packages/03/b3/64ef723029f917410f75c09da54254c5f9ea90ef89b143ccadb09df14c15/contourpy-1.3.3-cp311-cp311-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0bf67e0e3f482cb69779dd3061b534eb35ac9b17f163d851e2a547d56dba0a3a", size = 380555, upload-time = "2025-07-26T12:01:08.801Z" },
+ { url = "https://files.pythonhosted.org/packages/5f/4b/6157f24ca425b89fe2eb7e7be642375711ab671135be21e6faa100f7448c/contourpy-1.3.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51e79c1f7470158e838808d4a996fa9bac72c498e93d8ebe5119bc1e6becb0db", size = 355238, upload-time = "2025-07-26T12:01:10.319Z" },
+ { url = "https://files.pythonhosted.org/packages/98/56/f914f0dd678480708a04cfd2206e7c382533249bc5001eb9f58aa693e200/contourpy-1.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:598c3aaece21c503615fd59c92a3598b428b2f01bfb4b8ca9c4edeecc2438620", size = 1326218, upload-time = "2025-07-26T12:01:12.659Z" },
+ { url = "https://files.pythonhosted.org/packages/fb/d7/4a972334a0c971acd5172389671113ae82aa7527073980c38d5868ff1161/contourpy-1.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:322ab1c99b008dad206d406bb61d014cf0174df491ae9d9d0fac6a6fda4f977f", size = 1392867, upload-time = "2025-07-26T12:01:15.533Z" },
+ { url = "https://files.pythonhosted.org/packages/75/3e/f2cc6cd56dc8cff46b1a56232eabc6feea52720083ea71ab15523daab796/contourpy-1.3.3-cp311-cp311-win32.whl", hash = "sha256:fd907ae12cd483cd83e414b12941c632a969171bf90fc937d0c9f268a31cafff", size = 183677, upload-time = "2025-07-26T12:01:17.088Z" },
+ { url = "https://files.pythonhosted.org/packages/98/4b/9bd370b004b5c9d8045c6c33cf65bae018b27aca550a3f657cdc99acdbd8/contourpy-1.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:3519428f6be58431c56581f1694ba8e50626f2dd550af225f82fb5f5814d2a42", size = 225234, upload-time = "2025-07-26T12:01:18.256Z" },
+ { url = "https://files.pythonhosted.org/packages/d9/b6/71771e02c2e004450c12b1120a5f488cad2e4d5b590b1af8bad060360fe4/contourpy-1.3.3-cp311-cp311-win_arm64.whl", hash = "sha256:15ff10bfada4bf92ec8b31c62bf7c1834c244019b4a33095a68000d7075df470", size = 193123, upload-time = "2025-07-26T12:01:19.848Z" },
+ { url = "https://files.pythonhosted.org/packages/be/45/adfee365d9ea3d853550b2e735f9d66366701c65db7855cd07621732ccfc/contourpy-1.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b08a32ea2f8e42cf1d4be3169a98dd4be32bafe4f22b6c4cb4ba810fa9e5d2cb", size = 293419, upload-time = "2025-07-26T12:01:21.16Z" },
+ { url = "https://files.pythonhosted.org/packages/53/3e/405b59cfa13021a56bba395a6b3aca8cec012b45bf177b0eaf7a202cde2c/contourpy-1.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:556dba8fb6f5d8742f2923fe9457dbdd51e1049c4a43fd3986a0b14a1d815fc6", size = 273979, upload-time = "2025-07-26T12:01:22.448Z" },
+ { url = "https://files.pythonhosted.org/packages/d4/1c/a12359b9b2ca3a845e8f7f9ac08bdf776114eb931392fcad91743e2ea17b/contourpy-1.3.3-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92d9abc807cf7d0e047b95ca5d957cf4792fcd04e920ca70d48add15c1a90ea7", size = 332653, upload-time = "2025-07-26T12:01:24.155Z" },
+ { url = "https://files.pythonhosted.org/packages/63/12/897aeebfb475b7748ea67b61e045accdfcf0d971f8a588b67108ed7f5512/contourpy-1.3.3-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b2e8faa0ed68cb29af51edd8e24798bb661eac3bd9f65420c1887b6ca89987c8", size = 379536, upload-time = "2025-07-26T12:01:25.91Z" },
+ { url = "https://files.pythonhosted.org/packages/43/8a/a8c584b82deb248930ce069e71576fc09bd7174bbd35183b7943fb1064fd/contourpy-1.3.3-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:626d60935cf668e70a5ce6ff184fd713e9683fb458898e4249b63be9e28286ea", size = 384397, upload-time = "2025-07-26T12:01:27.152Z" },
+ { url = "https://files.pythonhosted.org/packages/cc/8f/ec6289987824b29529d0dfda0d74a07cec60e54b9c92f3c9da4c0ac732de/contourpy-1.3.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4d00e655fcef08aba35ec9610536bfe90267d7ab5ba944f7032549c55a146da1", size = 362601, upload-time = "2025-07-26T12:01:28.808Z" },
+ { url = "https://files.pythonhosted.org/packages/05/0a/a3fe3be3ee2dceb3e615ebb4df97ae6f3828aa915d3e10549ce016302bd1/contourpy-1.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:451e71b5a7d597379ef572de31eeb909a87246974d960049a9848c3bc6c41bf7", size = 1331288, upload-time = "2025-07-26T12:01:31.198Z" },
+ { url = "https://files.pythonhosted.org/packages/33/1d/acad9bd4e97f13f3e2b18a3977fe1b4a37ecf3d38d815333980c6c72e963/contourpy-1.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:459c1f020cd59fcfe6650180678a9993932d80d44ccde1fa1868977438f0b411", size = 1403386, upload-time = "2025-07-26T12:01:33.947Z" },
+ { url = "https://files.pythonhosted.org/packages/cf/8f/5847f44a7fddf859704217a99a23a4f6417b10e5ab1256a179264561540e/contourpy-1.3.3-cp312-cp312-win32.whl", hash = "sha256:023b44101dfe49d7d53932be418477dba359649246075c996866106da069af69", size = 185018, upload-time = "2025-07-26T12:01:35.64Z" },
+ { url = "https://files.pythonhosted.org/packages/19/e8/6026ed58a64563186a9ee3f29f41261fd1828f527dd93d33b60feca63352/contourpy-1.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:8153b8bfc11e1e4d75bcb0bff1db232f9e10b274e0929de9d608027e0d34ff8b", size = 226567, upload-time = "2025-07-26T12:01:36.804Z" },
+ { url = "https://files.pythonhosted.org/packages/d1/e2/f05240d2c39a1ed228d8328a78b6f44cd695f7ef47beb3e684cf93604f86/contourpy-1.3.3-cp312-cp312-win_arm64.whl", hash = "sha256:07ce5ed73ecdc4a03ffe3e1b3e3c1166db35ae7584be76f65dbbe28a7791b0cc", size = 193655, upload-time = "2025-07-26T12:01:37.999Z" },
+ { url = "https://files.pythonhosted.org/packages/68/35/0167aad910bbdb9599272bd96d01a9ec6852f36b9455cf2ca67bd4cc2d23/contourpy-1.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:177fb367556747a686509d6fef71d221a4b198a3905fe824430e5ea0fda54eb5", size = 293257, upload-time = "2025-07-26T12:01:39.367Z" },
+ { url = "https://files.pythonhosted.org/packages/96/e4/7adcd9c8362745b2210728f209bfbcf7d91ba868a2c5f40d8b58f54c509b/contourpy-1.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d002b6f00d73d69333dac9d0b8d5e84d9724ff9ef044fd63c5986e62b7c9e1b1", size = 274034, upload-time = "2025-07-26T12:01:40.645Z" },
+ { url = "https://files.pythonhosted.org/packages/73/23/90e31ceeed1de63058a02cb04b12f2de4b40e3bef5e082a7c18d9c8ae281/contourpy-1.3.3-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:348ac1f5d4f1d66d3322420f01d42e43122f43616e0f194fc1c9f5d830c5b286", size = 334672, upload-time = "2025-07-26T12:01:41.942Z" },
+ { url = "https://files.pythonhosted.org/packages/ed/93/b43d8acbe67392e659e1d984700e79eb67e2acb2bd7f62012b583a7f1b55/contourpy-1.3.3-cp313-cp313-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:655456777ff65c2c548b7c454af9c6f33f16c8884f11083244b5819cc214f1b5", size = 381234, upload-time = "2025-07-26T12:01:43.499Z" },
+ { url = "https://files.pythonhosted.org/packages/46/3b/bec82a3ea06f66711520f75a40c8fc0b113b2a75edb36aa633eb11c4f50f/contourpy-1.3.3-cp313-cp313-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:644a6853d15b2512d67881586bd03f462c7ab755db95f16f14d7e238f2852c67", size = 385169, upload-time = "2025-07-26T12:01:45.219Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/32/e0f13a1c5b0f8572d0ec6ae2f6c677b7991fafd95da523159c19eff0696a/contourpy-1.3.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4debd64f124ca62069f313a9cb86656ff087786016d76927ae2cf37846b006c9", size = 362859, upload-time = "2025-07-26T12:01:46.519Z" },
+ { url = "https://files.pythonhosted.org/packages/33/71/e2a7945b7de4e58af42d708a219f3b2f4cff7386e6b6ab0a0fa0033c49a9/contourpy-1.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a15459b0f4615b00bbd1e91f1b9e19b7e63aea7483d03d804186f278c0af2659", size = 1332062, upload-time = "2025-07-26T12:01:48.964Z" },
+ { url = "https://files.pythonhosted.org/packages/12/fc/4e87ac754220ccc0e807284f88e943d6d43b43843614f0a8afa469801db0/contourpy-1.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:ca0fdcd73925568ca027e0b17ab07aad764be4706d0a925b89227e447d9737b7", size = 1403932, upload-time = "2025-07-26T12:01:51.979Z" },
+ { url = "https://files.pythonhosted.org/packages/a6/2e/adc197a37443f934594112222ac1aa7dc9a98faf9c3842884df9a9d8751d/contourpy-1.3.3-cp313-cp313-win32.whl", hash = "sha256:b20c7c9a3bf701366556e1b1984ed2d0cedf999903c51311417cf5f591d8c78d", size = 185024, upload-time = "2025-07-26T12:01:53.245Z" },
+ { url = "https://files.pythonhosted.org/packages/18/0b/0098c214843213759692cc638fce7de5c289200a830e5035d1791d7a2338/contourpy-1.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:1cadd8b8969f060ba45ed7c1b714fe69185812ab43bd6b86a9123fe8f99c3263", size = 226578, upload-time = "2025-07-26T12:01:54.422Z" },
+ { url = "https://files.pythonhosted.org/packages/8a/9a/2f6024a0c5995243cd63afdeb3651c984f0d2bc727fd98066d40e141ad73/contourpy-1.3.3-cp313-cp313-win_arm64.whl", hash = "sha256:fd914713266421b7536de2bfa8181aa8c699432b6763a0ea64195ebe28bff6a9", size = 193524, upload-time = "2025-07-26T12:01:55.73Z" },
+ { url = "https://files.pythonhosted.org/packages/c0/b3/f8a1a86bd3298513f500e5b1f5fd92b69896449f6cab6a146a5d52715479/contourpy-1.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:88df9880d507169449d434c293467418b9f6cbe82edd19284aa0409e7fdb933d", size = 306730, upload-time = "2025-07-26T12:01:57.051Z" },
+ { url = "https://files.pythonhosted.org/packages/3f/11/4780db94ae62fc0c2053909b65dc3246bd7cecfc4f8a20d957ad43aa4ad8/contourpy-1.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:d06bb1f751ba5d417047db62bca3c8fde202b8c11fb50742ab3ab962c81e8216", size = 287897, upload-time = "2025-07-26T12:01:58.663Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/15/e59f5f3ffdd6f3d4daa3e47114c53daabcb18574a26c21f03dc9e4e42ff0/contourpy-1.3.3-cp313-cp313t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e4e6b05a45525357e382909a4c1600444e2a45b4795163d3b22669285591c1ae", size = 326751, upload-time = "2025-07-26T12:02:00.343Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/81/03b45cfad088e4770b1dcf72ea78d3802d04200009fb364d18a493857210/contourpy-1.3.3-cp313-cp313t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ab3074b48c4e2cf1a960e6bbeb7f04566bf36b1861d5c9d4d8ac04b82e38ba20", size = 375486, upload-time = "2025-07-26T12:02:02.128Z" },
+ { url = "https://files.pythonhosted.org/packages/0c/ba/49923366492ffbdd4486e970d421b289a670ae8cf539c1ea9a09822b371a/contourpy-1.3.3-cp313-cp313t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6c3d53c796f8647d6deb1abe867daeb66dcc8a97e8455efa729516b997b8ed99", size = 388106, upload-time = "2025-07-26T12:02:03.615Z" },
+ { url = "https://files.pythonhosted.org/packages/9f/52/5b00ea89525f8f143651f9f03a0df371d3cbd2fccd21ca9b768c7a6500c2/contourpy-1.3.3-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50ed930df7289ff2a8d7afeb9603f8289e5704755c7e5c3bbd929c90c817164b", size = 352548, upload-time = "2025-07-26T12:02:05.165Z" },
+ { url = "https://files.pythonhosted.org/packages/32/1d/a209ec1a3a3452d490f6b14dd92e72280c99ae3d1e73da74f8277d4ee08f/contourpy-1.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:4feffb6537d64b84877da813a5c30f1422ea5739566abf0bd18065ac040e120a", size = 1322297, upload-time = "2025-07-26T12:02:07.379Z" },
+ { url = "https://files.pythonhosted.org/packages/bc/9e/46f0e8ebdd884ca0e8877e46a3f4e633f6c9c8c4f3f6e72be3fe075994aa/contourpy-1.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:2b7e9480ffe2b0cd2e787e4df64270e3a0440d9db8dc823312e2c940c167df7e", size = 1391023, upload-time = "2025-07-26T12:02:10.171Z" },
+ { url = "https://files.pythonhosted.org/packages/b9/70/f308384a3ae9cd2209e0849f33c913f658d3326900d0ff5d378d6a1422d2/contourpy-1.3.3-cp313-cp313t-win32.whl", hash = "sha256:283edd842a01e3dcd435b1c5116798d661378d83d36d337b8dde1d16a5fc9ba3", size = 196157, upload-time = "2025-07-26T12:02:11.488Z" },
+ { url = "https://files.pythonhosted.org/packages/b2/dd/880f890a6663b84d9e34a6f88cded89d78f0091e0045a284427cb6b18521/contourpy-1.3.3-cp313-cp313t-win_amd64.whl", hash = "sha256:87acf5963fc2b34825e5b6b048f40e3635dd547f590b04d2ab317c2619ef7ae8", size = 240570, upload-time = "2025-07-26T12:02:12.754Z" },
+ { url = "https://files.pythonhosted.org/packages/80/99/2adc7d8ffead633234817ef8e9a87115c8a11927a94478f6bb3d3f4d4f7d/contourpy-1.3.3-cp313-cp313t-win_arm64.whl", hash = "sha256:3c30273eb2a55024ff31ba7d052dde990d7d8e5450f4bbb6e913558b3d6c2301", size = 199713, upload-time = "2025-07-26T12:02:14.4Z" },
+ { url = "https://files.pythonhosted.org/packages/72/8b/4546f3ab60f78c514ffb7d01a0bd743f90de36f0019d1be84d0a708a580a/contourpy-1.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fde6c716d51c04b1c25d0b90364d0be954624a0ee9d60e23e850e8d48353d07a", size = 292189, upload-time = "2025-07-26T12:02:16.095Z" },
+ { url = "https://files.pythonhosted.org/packages/fd/e1/3542a9cb596cadd76fcef413f19c79216e002623158befe6daa03dbfa88c/contourpy-1.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:cbedb772ed74ff5be440fa8eee9bd49f64f6e3fc09436d9c7d8f1c287b121d77", size = 273251, upload-time = "2025-07-26T12:02:17.524Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/71/f93e1e9471d189f79d0ce2497007731c1e6bf9ef6d1d61b911430c3db4e5/contourpy-1.3.3-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:22e9b1bd7a9b1d652cd77388465dc358dafcd2e217d35552424aa4f996f524f5", size = 335810, upload-time = "2025-07-26T12:02:18.9Z" },
+ { url = "https://files.pythonhosted.org/packages/91/f9/e35f4c1c93f9275d4e38681a80506b5510e9327350c51f8d4a5a724d178c/contourpy-1.3.3-cp314-cp314-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a22738912262aa3e254e4f3cb079a95a67132fc5a063890e224393596902f5a4", size = 382871, upload-time = "2025-07-26T12:02:20.418Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/71/47b512f936f66a0a900d81c396a7e60d73419868fba959c61efed7a8ab46/contourpy-1.3.3-cp314-cp314-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:afe5a512f31ee6bd7d0dda52ec9864c984ca3d66664444f2d72e0dc4eb832e36", size = 386264, upload-time = "2025-07-26T12:02:21.916Z" },
+ { url = "https://files.pythonhosted.org/packages/04/5f/9ff93450ba96b09c7c2b3f81c94de31c89f92292f1380261bd7195bea4ea/contourpy-1.3.3-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f64836de09927cba6f79dcd00fdd7d5329f3fccc633468507079c829ca4db4e3", size = 363819, upload-time = "2025-07-26T12:02:23.759Z" },
+ { url = "https://files.pythonhosted.org/packages/3e/a6/0b185d4cc480ee494945cde102cb0149ae830b5fa17bf855b95f2e70ad13/contourpy-1.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:1fd43c3be4c8e5fd6e4f2baeae35ae18176cf2e5cced681cca908addf1cdd53b", size = 1333650, upload-time = "2025-07-26T12:02:26.181Z" },
+ { url = "https://files.pythonhosted.org/packages/43/d7/afdc95580ca56f30fbcd3060250f66cedbde69b4547028863abd8aa3b47e/contourpy-1.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6afc576f7b33cf00996e5c1102dc2a8f7cc89e39c0b55df93a0b78c1bd992b36", size = 1404833, upload-time = "2025-07-26T12:02:28.782Z" },
+ { url = "https://files.pythonhosted.org/packages/e2/e2/366af18a6d386f41132a48f033cbd2102e9b0cf6345d35ff0826cd984566/contourpy-1.3.3-cp314-cp314-win32.whl", hash = "sha256:66c8a43a4f7b8df8b71ee1840e4211a3c8d93b214b213f590e18a1beca458f7d", size = 189692, upload-time = "2025-07-26T12:02:30.128Z" },
+ { url = "https://files.pythonhosted.org/packages/7d/c2/57f54b03d0f22d4044b8afb9ca0e184f8b1afd57b4f735c2fa70883dc601/contourpy-1.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:cf9022ef053f2694e31d630feaacb21ea24224be1c3ad0520b13d844274614fd", size = 232424, upload-time = "2025-07-26T12:02:31.395Z" },
+ { url = "https://files.pythonhosted.org/packages/18/79/a9416650df9b525737ab521aa181ccc42d56016d2123ddcb7b58e926a42c/contourpy-1.3.3-cp314-cp314-win_arm64.whl", hash = "sha256:95b181891b4c71de4bb404c6621e7e2390745f887f2a026b2d99e92c17892339", size = 198300, upload-time = "2025-07-26T12:02:32.956Z" },
+ { url = "https://files.pythonhosted.org/packages/1f/42/38c159a7d0f2b7b9c04c64ab317042bb6952b713ba875c1681529a2932fe/contourpy-1.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:33c82d0138c0a062380332c861387650c82e4cf1747aaa6938b9b6516762e772", size = 306769, upload-time = "2025-07-26T12:02:34.2Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/6c/26a8205f24bca10974e77460de68d3d7c63e282e23782f1239f226fcae6f/contourpy-1.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ea37e7b45949df430fe649e5de8351c423430046a2af20b1c1961cae3afcda77", size = 287892, upload-time = "2025-07-26T12:02:35.807Z" },
+ { url = "https://files.pythonhosted.org/packages/66/06/8a475c8ab718ebfd7925661747dbb3c3ee9c82ac834ccb3570be49d129f4/contourpy-1.3.3-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d304906ecc71672e9c89e87c4675dc5c2645e1f4269a5063b99b0bb29f232d13", size = 326748, upload-time = "2025-07-26T12:02:37.193Z" },
+ { url = "https://files.pythonhosted.org/packages/b4/a3/c5ca9f010a44c223f098fccd8b158bb1cb287378a31ac141f04730dc49be/contourpy-1.3.3-cp314-cp314t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ca658cd1a680a5c9ea96dc61cdbae1e85c8f25849843aa799dfd3cb370ad4fbe", size = 375554, upload-time = "2025-07-26T12:02:38.894Z" },
+ { url = "https://files.pythonhosted.org/packages/80/5b/68bd33ae63fac658a4145088c1e894405e07584a316738710b636c6d0333/contourpy-1.3.3-cp314-cp314t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ab2fd90904c503739a75b7c8c5c01160130ba67944a7b77bbf36ef8054576e7f", size = 388118, upload-time = "2025-07-26T12:02:40.642Z" },
+ { url = "https://files.pythonhosted.org/packages/40/52/4c285a6435940ae25d7410a6c36bda5145839bc3f0beb20c707cda18b9d2/contourpy-1.3.3-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b7301b89040075c30e5768810bc96a8e8d78085b47d8be6e4c3f5a0b4ed478a0", size = 352555, upload-time = "2025-07-26T12:02:42.25Z" },
+ { url = "https://files.pythonhosted.org/packages/24/ee/3e81e1dd174f5c7fefe50e85d0892de05ca4e26ef1c9a59c2a57e43b865a/contourpy-1.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:2a2a8b627d5cc6b7c41a4beff6c5ad5eb848c88255fda4a8745f7e901b32d8e4", size = 1322295, upload-time = "2025-07-26T12:02:44.668Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/b2/6d913d4d04e14379de429057cd169e5e00f6c2af3bb13e1710bcbdb5da12/contourpy-1.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:fd6ec6be509c787f1caf6b247f0b1ca598bef13f4ddeaa126b7658215529ba0f", size = 1391027, upload-time = "2025-07-26T12:02:47.09Z" },
+ { url = "https://files.pythonhosted.org/packages/93/8a/68a4ec5c55a2971213d29a9374913f7e9f18581945a7a31d1a39b5d2dfe5/contourpy-1.3.3-cp314-cp314t-win32.whl", hash = "sha256:e74a9a0f5e3fff48fb5a7f2fd2b9b70a3fe014a67522f79b7cca4c0c7e43c9ae", size = 202428, upload-time = "2025-07-26T12:02:48.691Z" },
+ { url = "https://files.pythonhosted.org/packages/fa/96/fd9f641ffedc4fa3ace923af73b9d07e869496c9cc7a459103e6e978992f/contourpy-1.3.3-cp314-cp314t-win_amd64.whl", hash = "sha256:13b68d6a62db8eafaebb8039218921399baf6e47bf85006fd8529f2a08ef33fc", size = 250331, upload-time = "2025-07-26T12:02:50.137Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/8c/469afb6465b853afff216f9528ffda78a915ff880ed58813ba4faf4ba0b6/contourpy-1.3.3-cp314-cp314t-win_arm64.whl", hash = "sha256:b7448cb5a725bb1e35ce88771b86fba35ef418952474492cf7c764059933ff8b", size = 203831, upload-time = "2025-07-26T12:02:51.449Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/29/8dcfe16f0107943fa92388c23f6e05cff0ba58058c4c95b00280d4c75a14/contourpy-1.3.3-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:cd5dfcaeb10f7b7f9dc8941717c6c2ade08f587be2226222c12b25f0483ed497", size = 278809, upload-time = "2025-07-26T12:02:52.74Z" },
+ { url = "https://files.pythonhosted.org/packages/85/a9/8b37ef4f7dafeb335daee3c8254645ef5725be4d9c6aa70b50ec46ef2f7e/contourpy-1.3.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:0c1fc238306b35f246d61a1d416a627348b5cf0648648a031e14bb8705fcdfe8", size = 261593, upload-time = "2025-07-26T12:02:54.037Z" },
+ { url = "https://files.pythonhosted.org/packages/0a/59/ebfb8c677c75605cc27f7122c90313fd2f375ff3c8d19a1694bda74aaa63/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70f9aad7de812d6541d29d2bbf8feb22ff7e1c299523db288004e3157ff4674e", size = 302202, upload-time = "2025-07-26T12:02:55.947Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/37/21972a15834d90bfbfb009b9d004779bd5a07a0ec0234e5ba8f64d5736f4/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5ed3657edf08512fc3fe81b510e35c2012fbd3081d2e26160f27ca28affec989", size = 329207, upload-time = "2025-07-26T12:02:57.468Z" },
+ { url = "https://files.pythonhosted.org/packages/0c/58/bd257695f39d05594ca4ad60df5bcb7e32247f9951fd09a9b8edb82d1daa/contourpy-1.3.3-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:3d1a3799d62d45c18bafd41c5fa05120b96a28079f2393af559b843d1a966a77", size = 225315, upload-time = "2025-07-26T12:02:58.801Z" },
+]
+
[[package]]
name = "cryptography"
version = "43.0.3"
@@ -513,6 +628,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/87/5c/3dab83cc4aba1f4b0e733e3f0c3e7d4386440d660ba5b1e3ff995feb734d/cryptography-43.0.3-cp39-abi3-win_amd64.whl", hash = "sha256:0c580952eef9bf68c4747774cde7ec1d85a6e61de97281f2dba83c7d2c806362", size = 3068026, upload-time = "2024-10-18T15:58:11.916Z" },
]
+[[package]]
+name = "cycler"
+version = "0.12.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" },
+]
+
[[package]]
name = "deprecation"
version = "2.1.0"
@@ -620,6 +744,55 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/a4/a5/842ae8f0c08b61d6484b52f99a03510a3a72d23141942d216ebe81fefbce/filelock-3.25.2-py3-none-any.whl", hash = "sha256:ca8afb0da15f229774c9ad1b455ed96e85a81373065fb10446672f64444ddf70", size = 26759, upload-time = "2026-03-11T20:45:37.437Z" },
]
+[[package]]
+name = "fonttools"
+version = "4.62.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/9a/08/7012b00a9a5874311b639c3920270c36ee0c445b69d9989a85e5c92ebcb0/fonttools-4.62.1.tar.gz", hash = "sha256:e54c75fd6041f1122476776880f7c3c3295ffa31962dc6ebe2543c00dca58b5d", size = 3580737, upload-time = "2026-03-13T13:54:25.52Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/88/39/23ff32561ec8d45a4d48578b4d241369d9270dc50926c017570e60893701/fonttools-4.62.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:40975849bac44fb0b9253d77420c6d8b523ac4dcdcefeff6e4d706838a5b80f7", size = 2871039, upload-time = "2026-03-13T13:52:33.127Z" },
+ { url = "https://files.pythonhosted.org/packages/24/7f/66d3f8a9338a9b67fe6e1739f47e1cd5cee78bd3bc1206ef9b0b982289a5/fonttools-4.62.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9dde91633f77fa576879a0c76b1d89de373cae751a98ddf0109d54e173b40f14", size = 2416346, upload-time = "2026-03-13T13:52:35.676Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/53/5276ceba7bff95da7793a07c5284e1da901cf00341ce5e2f3273056c0cca/fonttools-4.62.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6acb4109f8bee00fec985c8c7afb02299e35e9c94b57287f3ea542f28bd0b0a7", size = 5100897, upload-time = "2026-03-13T13:52:38.102Z" },
+ { url = "https://files.pythonhosted.org/packages/cc/a1/40a5c4d8e28b0851d53a8eeeb46fbd73c325a2a9a165f290a5ed90e6c597/fonttools-4.62.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1c5c25671ce8805e0d080e2ffdeca7f1e86778c5cbfbeae86d7f866d8830517b", size = 5071078, upload-time = "2026-03-13T13:52:41.305Z" },
+ { url = "https://files.pythonhosted.org/packages/e3/be/d378fca4c65ea1956fee6d90ace6e861776809cbbc5af22388a090c3c092/fonttools-4.62.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:a5d8825e1140f04e6c99bb7d37a9e31c172f3bc208afbe02175339e699c710e1", size = 5076908, upload-time = "2026-03-13T13:52:44.122Z" },
+ { url = "https://files.pythonhosted.org/packages/f8/d9/ae6a1d0693a4185a84605679c8a1f719a55df87b9c6e8e817bfdd9ef5936/fonttools-4.62.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:268abb1cb221e66c014acc234e872b7870d8b5d4657a83a8f4205094c32d2416", size = 5202275, upload-time = "2026-03-13T13:52:46.591Z" },
+ { url = "https://files.pythonhosted.org/packages/54/6c/af95d9c4efb15cabff22642b608342f2bd67137eea6107202d91b5b03184/fonttools-4.62.1-cp311-cp311-win32.whl", hash = "sha256:942b03094d7edbb99bdf1ae7e9090898cad7bf9030b3d21f33d7072dbcb51a53", size = 2293075, upload-time = "2026-03-13T13:52:48.711Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/97/bf54c5b3f2be34e1f143e6db838dfdc54f2ffa3e68c738934c82f3b2a08d/fonttools-4.62.1-cp311-cp311-win_amd64.whl", hash = "sha256:e8514f4924375f77084e81467e63238b095abda5107620f49421c368a6017ed2", size = 2344593, upload-time = "2026-03-13T13:52:50.725Z" },
+ { url = "https://files.pythonhosted.org/packages/47/d4/dbacced3953544b9a93088cc10ef2b596d348c983d5c67a404fa41ec51ba/fonttools-4.62.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:90365821debbd7db678809c7491ca4acd1e0779b9624cdc6ddaf1f31992bf974", size = 2870219, upload-time = "2026-03-13T13:52:53.664Z" },
+ { url = "https://files.pythonhosted.org/packages/66/9e/a769c8e99b81e5a87ab7e5e7236684de4e96246aae17274e5347d11ebd78/fonttools-4.62.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:12859ff0b47dd20f110804c3e0d0970f7b832f561630cd879969011541a464a9", size = 2414891, upload-time = "2026-03-13T13:52:56.493Z" },
+ { url = "https://files.pythonhosted.org/packages/69/64/f19a9e3911968c37e1e620e14dfc5778299e1474f72f4e57c5ec771d9489/fonttools-4.62.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c125ffa00c3d9003cdaaf7f2c79e6e535628093e14b5de1dccb08859b680936", size = 5033197, upload-time = "2026-03-13T13:52:59.179Z" },
+ { url = "https://files.pythonhosted.org/packages/9b/8a/99c8b3c3888c5c474c08dbfd7c8899786de9604b727fcefb055b42c84bba/fonttools-4.62.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:149f7d84afca659d1a97e39a4778794a2f83bf344c5ee5134e09995086cc2392", size = 4988768, upload-time = "2026-03-13T13:53:02.761Z" },
+ { url = "https://files.pythonhosted.org/packages/d1/c6/0f904540d3e6ab463c1243a0d803504826a11604c72dd58c2949796a1762/fonttools-4.62.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0aa72c43a601cfa9273bb1ae0518f1acadc01ee181a6fc60cd758d7fdadffc04", size = 4971512, upload-time = "2026-03-13T13:53:05.678Z" },
+ { url = "https://files.pythonhosted.org/packages/29/0b/5cbef6588dc9bd6b5c9ad6a4d5a8ca384d0cea089da31711bbeb4f9654a6/fonttools-4.62.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:19177c8d96c7c36359266e571c5173bcee9157b59cfc8cb0153c5673dc5a3a7d", size = 5122723, upload-time = "2026-03-13T13:53:08.662Z" },
+ { url = "https://files.pythonhosted.org/packages/4a/47/b3a5342d381595ef439adec67848bed561ab7fdb1019fa522e82101b7d9c/fonttools-4.62.1-cp312-cp312-win32.whl", hash = "sha256:a24decd24d60744ee8b4679d38e88b8303d86772053afc29b19d23bb8207803c", size = 2281278, upload-time = "2026-03-13T13:53:10.998Z" },
+ { url = "https://files.pythonhosted.org/packages/28/b1/0c2ab56a16f409c6c8a68816e6af707827ad5d629634691ff60a52879792/fonttools-4.62.1-cp312-cp312-win_amd64.whl", hash = "sha256:9e7863e10b3de72376280b515d35b14f5eeed639d1aa7824f4cf06779ec65e42", size = 2331414, upload-time = "2026-03-13T13:53:13.992Z" },
+ { url = "https://files.pythonhosted.org/packages/3b/56/6f389de21c49555553d6a5aeed5ac9767631497ac836c4f076273d15bd72/fonttools-4.62.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:c22b1014017111c401469e3acc5433e6acf6ebcc6aa9efb538a533c800971c79", size = 2865155, upload-time = "2026-03-13T13:53:16.132Z" },
+ { url = "https://files.pythonhosted.org/packages/03/c5/0e3966edd5ec668d41dfe418787726752bc07e2f5fd8c8f208615e61fa89/fonttools-4.62.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:68959f5fc58ed4599b44aad161c2837477d7f35f5f79402d97439974faebfebe", size = 2412802, upload-time = "2026-03-13T13:53:18.878Z" },
+ { url = "https://files.pythonhosted.org/packages/52/94/e6ac4b44026de7786fe46e3bfa0c87e51d5d70a841054065d49cd62bb909/fonttools-4.62.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ef46db46c9447103b8f3ff91e8ba009d5fe181b1920a83757a5762551e32bb68", size = 5013926, upload-time = "2026-03-13T13:53:21.379Z" },
+ { url = "https://files.pythonhosted.org/packages/e2/98/8b1e801939839d405f1f122e7d175cebe9aeb4e114f95bfc45e3152af9a7/fonttools-4.62.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6706d1cb1d5e6251a97ad3c1b9347505c5615c112e66047abbef0f8545fa30d1", size = 4964575, upload-time = "2026-03-13T13:53:23.857Z" },
+ { url = "https://files.pythonhosted.org/packages/46/76/7d051671e938b1881670528fec69cc4044315edd71a229c7fd712eaa5119/fonttools-4.62.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2e7abd2b1e11736f58c1de27819e1955a53267c21732e78243fa2fa2e5c1e069", size = 4953693, upload-time = "2026-03-13T13:53:26.569Z" },
+ { url = "https://files.pythonhosted.org/packages/1f/ae/b41f8628ec0be3c1b934fc12b84f4576a5c646119db4d3bdd76a217c90b5/fonttools-4.62.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:403d28ce06ebfc547fbcb0cb8b7f7cc2f7a2d3e1a67ba9a34b14632df9e080f9", size = 5094920, upload-time = "2026-03-13T13:53:29.329Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/f6/53a1e9469331a23dcc400970a27a4caa3d9f6edbf5baab0260285238b884/fonttools-4.62.1-cp313-cp313-win32.whl", hash = "sha256:93c316e0f5301b2adbe6a5f658634307c096fd5aae60a5b3412e4f3e1728ab24", size = 2279928, upload-time = "2026-03-13T13:53:32.352Z" },
+ { url = "https://files.pythonhosted.org/packages/38/60/35186529de1db3c01f5ad625bde07c1f576305eab6d86bbda4c58445f721/fonttools-4.62.1-cp313-cp313-win_amd64.whl", hash = "sha256:7aa21ff53e28a9c2157acbc44e5b401149d3c9178107130e82d74ceb500e5056", size = 2330514, upload-time = "2026-03-13T13:53:34.991Z" },
+ { url = "https://files.pythonhosted.org/packages/36/f0/2888cdac391807d68d90dcb16ef858ddc1b5309bfc6966195a459dd326e2/fonttools-4.62.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fa1d16210b6b10a826d71bed68dd9ec24a9e218d5a5e2797f37c573e7ec215ca", size = 2864442, upload-time = "2026-03-13T13:53:37.509Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/b2/e521803081f8dc35990816b82da6360fa668a21b44da4b53fc9e77efcd62/fonttools-4.62.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:aa69d10ed420d8121118e628ad47d86e4caa79ba37f968597b958f6cceab7eca", size = 2410901, upload-time = "2026-03-13T13:53:40.55Z" },
+ { url = "https://files.pythonhosted.org/packages/00/a4/8c3511ff06e53110039358dbbdc1a65d72157a054638387aa2ada300a8b8/fonttools-4.62.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bd13b7999d59c5eb1c2b442eb2d0c427cb517a0b7a1f5798fc5c9e003f5ff782", size = 4999608, upload-time = "2026-03-13T13:53:42.798Z" },
+ { url = "https://files.pythonhosted.org/packages/28/63/cd0c3b26afe60995a5295f37c246a93d454023726c3261cfbb3559969bb9/fonttools-4.62.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8d337fdd49a79b0d51c4da87bc38169d21c3abbf0c1aa9367eff5c6656fb6dae", size = 4912726, upload-time = "2026-03-13T13:53:45.405Z" },
+ { url = "https://files.pythonhosted.org/packages/70/b9/ac677cb07c24c685cf34f64e140617d58789d67a3dd524164b63648c6114/fonttools-4.62.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d241cdc4a67b5431c6d7f115fdf63335222414995e3a1df1a41e1182acd4bcc7", size = 4951422, upload-time = "2026-03-13T13:53:48.326Z" },
+ { url = "https://files.pythonhosted.org/packages/e6/10/11c08419a14b85b7ca9a9faca321accccc8842dd9e0b1c8a72908de05945/fonttools-4.62.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:c05557a78f8fa514da0f869556eeda40887a8abc77c76ee3f74cf241778afd5a", size = 5060979, upload-time = "2026-03-13T13:53:51.366Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/3c/12eea4a4cf054e7ab058ed5ceada43b46809fce2bf319017c4d63ae55bb4/fonttools-4.62.1-cp314-cp314-win32.whl", hash = "sha256:49a445d2f544ce4a69338694cad575ba97b9a75fff02720da0882d1a73f12800", size = 2283733, upload-time = "2026-03-13T13:53:53.606Z" },
+ { url = "https://files.pythonhosted.org/packages/6b/67/74b070029043186b5dd13462c958cb7c7f811be0d2e634309d9a1ffb1505/fonttools-4.62.1-cp314-cp314-win_amd64.whl", hash = "sha256:1eecc128c86c552fb963fe846ca4e011b1be053728f798185a1687502f6d398e", size = 2335663, upload-time = "2026-03-13T13:53:56.23Z" },
+ { url = "https://files.pythonhosted.org/packages/42/c5/4d2ed3ca6e33617fc5624467da353337f06e7f637707478903c785bd8e20/fonttools-4.62.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:1596aeaddf7f78e21e68293c011316a25267b3effdaccaf4d59bc9159d681b82", size = 2947288, upload-time = "2026-03-13T13:53:59.397Z" },
+ { url = "https://files.pythonhosted.org/packages/1f/e9/7ab11ddfda48ed0f89b13380e5595ba572619c27077be0b2c447a63ff351/fonttools-4.62.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:8f8fca95d3bb3208f59626a4b0ea6e526ee51f5a8ad5d91821c165903e8d9260", size = 2449023, upload-time = "2026-03-13T13:54:01.642Z" },
+ { url = "https://files.pythonhosted.org/packages/b2/10/a800fa090b5e8819942e54e19b55fc7c21fe14a08757c3aa3ca8db358939/fonttools-4.62.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee91628c08e76f77b533d65feb3fbe6d9dad699f95be51cf0d022db94089cdc4", size = 5137599, upload-time = "2026-03-13T13:54:04.495Z" },
+ { url = "https://files.pythonhosted.org/packages/37/dc/8ccd45033fffd74deb6912fa1ca524643f584b94c87a16036855b498a1ed/fonttools-4.62.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5f37df1cac61d906e7b836abe356bc2f34c99d4477467755c216b72aa3dc748b", size = 4920933, upload-time = "2026-03-13T13:54:07.557Z" },
+ { url = "https://files.pythonhosted.org/packages/99/eb/e618adefb839598d25ac8136cd577925d6c513dc0d931d93b8af956210f0/fonttools-4.62.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:92bb00a947e666169c99b43753c4305fc95a890a60ef3aeb2a6963e07902cc87", size = 5016232, upload-time = "2026-03-13T13:54:10.611Z" },
+ { url = "https://files.pythonhosted.org/packages/d9/5f/9b5c9bfaa8ec82def8d8168c4f13615990d6ce5996fe52bd49bfb5e05134/fonttools-4.62.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:bdfe592802ef939a0e33106ea4a318eeb17822c7ee168c290273cbd5fabd746c", size = 5042987, upload-time = "2026-03-13T13:54:13.569Z" },
+ { url = "https://files.pythonhosted.org/packages/90/aa/dfbbe24c6a6afc5c203d90cc0343e24bcbb09e76d67c4d6eef8c2558d7ba/fonttools-4.62.1-cp314-cp314t-win32.whl", hash = "sha256:b820fcb92d4655513d8402d5b219f94481c4443d825b4372c75a2072aa4b357a", size = 2348021, upload-time = "2026-03-13T13:54:16.98Z" },
+ { url = "https://files.pythonhosted.org/packages/13/6f/ae9c4e4dd417948407b680855c2c7790efb52add6009aaecff1e3bc50e8e/fonttools-4.62.1-cp314-cp314t-win_amd64.whl", hash = "sha256:59b372b4f0e113d3746b88985f1c796e7bf830dd54b28374cd85c2b8acd7583e", size = 2414147, upload-time = "2026-03-13T13:54:19.416Z" },
+ { url = "https://files.pythonhosted.org/packages/fd/ba/56147c165442cc5ba7e82ecf301c9a68353cede498185869e6e02b4c264f/fonttools-4.62.1-py3-none-any.whl", hash = "sha256:7487782e2113861f4ddcc07c3436450659e3caa5e470b27dc2177cade2d8e7fd", size = 1152647, upload-time = "2026-03-13T13:54:22.735Z" },
+]
+
[[package]]
name = "frozenlist"
version = "1.8.0"
@@ -734,6 +907,43 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e6/ab/fb21f4c939bb440104cc2b396d3be1d9b7a9fd3c6c2a53d98c45b3d7c954/fsspec-2026.2.0-py3-none-any.whl", hash = "sha256:98de475b5cb3bd66bedd5c4679e87b4fdfe1a3bf4d707b151b3c07e58c9a2437", size = 202505, upload-time = "2026-02-05T21:50:51.819Z" },
]
+[[package]]
+name = "future"
+version = "1.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a7/b2/4140c69c6a66432916b26158687e821ba631a4c9273c474343badf84d3ba/future-1.0.0.tar.gz", hash = "sha256:bd2968309307861edae1458a4f8a4f3598c03be43b97521076aebf5d94c07b05", size = 1228490, upload-time = "2024-02-21T11:52:38.461Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/da/71/ae30dadffc90b9006d77af76b393cb9dfbfc9629f339fc1574a1c52e6806/future-1.0.0-py3-none-any.whl", hash = "sha256:929292d34f5872e70396626ef385ec22355a1fae8ad29e1a734c3e43f9fbc216", size = 491326, upload-time = "2024-02-21T11:52:35.956Z" },
+]
+
+[[package]]
+name = "gensim"
+version = "4.4.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+ { name = "scipy" },
+ { name = "smart-open" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/1a/80/fe9d2e1ace968041814dbcfce4e8499a643a36c41267fa4b6c4f54cce420/gensim-4.4.0.tar.gz", hash = "sha256:a3f5b626da5518e79a479140361c663089fe7998df8ba52d56e1ded71ac5bdf5", size = 23260095, upload-time = "2025-10-18T02:06:45.962Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/52/7b/81b6c74b32700ee63f6720a60ca0c89ab59b12933257b47572c8af017658/gensim-4.4.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:7590e7313848ca8f3ff064898bcd6ecf6ec71c752cf4d3ec83f7ac992bc7c088", size = 24463159, upload-time = "2025-10-18T01:51:09.7Z" },
+ { url = "https://files.pythonhosted.org/packages/38/7c/18d40f341276a7461962512ca1fb716d5982db57615dfa272f651ecb96d7/gensim-4.4.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:05a027238b5eb544a17afe73ec227d6a7e0c6b4e2108b1131c0b8f291a0e0e2e", size = 24453170, upload-time = "2025-10-18T01:51:58.42Z" },
+ { url = "https://files.pythonhosted.org/packages/68/88/6bd6919d31bdd473472ce1c18c24fcab5869b8b15166a424d11ce33a5eab/gensim-4.4.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7e110e2d3533f5b35239850a96cb2016a586ecd85671d655079b3048332b7169", size = 27760793, upload-time = "2025-10-18T01:52:47.866Z" },
+ { url = "https://files.pythonhosted.org/packages/d9/fa/85531b39c1beb5a4203929ba83d94d886cec40d0fb0bef8ca05fd1cc7a38/gensim-4.4.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:91a7fa5e814e7b1bad4b2dffa8d62c1e55410d5cbdf930714c1997ffb4404db8", size = 27809988, upload-time = "2025-10-18T01:53:36.978Z" },
+ { url = "https://files.pythonhosted.org/packages/10/c3/7e22d6f7d88c4ea6a3a84481f00538252659d285713c3b7e2e1537b0e7e1/gensim-4.4.0-cp311-cp311-win_amd64.whl", hash = "sha256:5e2c1d584d1c7d16b2a0fe7d2f6f59a451422df7b5edb7e3ca46c8e462782127", size = 24396172, upload-time = "2025-10-18T01:54:25.711Z" },
+ { url = "https://files.pythonhosted.org/packages/4f/65/d5285865ca54b93d41ccd8683c2d79952434957c76b411283c7a6c66ca69/gensim-4.4.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0845b2fa039dbea5667fb278b5414e70f6d48fd208ef51f33e84a78444288d8d", size = 24467245, upload-time = "2025-10-18T01:55:09.924Z" },
+ { url = "https://files.pythonhosted.org/packages/32/59/f0ea443cbfb3b06e1d2e060217bb91f954845f6df38cbc9c5468b6c9c638/gensim-4.4.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1853fc5be730f692c444a826041fef9a2fc8d74c73bb59748904b2e3221daa86", size = 24455775, upload-time = "2025-10-18T01:55:52.866Z" },
+ { url = "https://files.pythonhosted.org/packages/f0/b8/9b0ba15756e41ccfdd852f9c65cd2b552f240c201dc3237ad8c178642e80/gensim-4.4.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:23a2a4260f01c8f71bae5dd0e8a01bb247a2c789480c033e0eaba100b0ad4239", size = 27771345, upload-time = "2025-10-18T01:56:41.448Z" },
+ { url = "https://files.pythonhosted.org/packages/97/2c/c29701826c963b04a43d5d7b87573a74040387ab9219e65b10f377d22b5b/gensim-4.4.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4b73ff30af6ddd0d2ddf9473b1eb44603cd79ec14c87d93b75291802b991916c", size = 27864118, upload-time = "2025-10-18T01:57:32.428Z" },
+ { url = "https://files.pythonhosted.org/packages/fd/f2/9ec6863143888bf390cdc5261f6d9e71d79bc95d98fb815679dba478d5f6/gensim-4.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:b3a3f9bc8d4178b01d114e1c58c5ab2333f131c7415fb3d8ec8f1ecfe4c5b544", size = 24400277, upload-time = "2025-10-18T01:58:17.629Z" },
+ { url = "https://files.pythonhosted.org/packages/80/6c/4e522973e07ca491d33cc7829996b9e8c8663a16b3f87f580cbdc2732d97/gensim-4.4.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b8961b7a2bb5190b46bc6cd26c29d5bfea22f99123ed5f506ebd0aaf65996758", size = 24460186, upload-time = "2025-10-18T01:59:01.904Z" },
+ { url = "https://files.pythonhosted.org/packages/cc/6a/593107ee98331128ed20e5d074865587558a0766659be787a40550ab66df/gensim-4.4.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:59d0d29099a76dd97d4563e002f3488a43e51f99d46387025da38007ebfeeff9", size = 24448880, upload-time = "2025-10-18T01:59:46.796Z" },
+ { url = "https://files.pythonhosted.org/packages/d9/ef/1675e1a3a04f7d0293a21082f57f4a6a8bf0a9e387da58b71db648b663de/gensim-4.4.0-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3bec3e6a1ecaa6439b21a3e42ceb0ca67ffabc114b646f89b1aab5fe69a39ffc", size = 27736031, upload-time = "2025-10-18T02:00:36.791Z" },
+ { url = "https://files.pythonhosted.org/packages/b3/b9/ee43ef9c391857232603a9ee281e9c5953f7922d70c98c2296a037d1c0b7/gensim-4.4.0-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9033b18920b7774e68eafacdbd87252ffa29382ec465ddb88bd036e00fc86365", size = 27826360, upload-time = "2025-10-18T02:01:26.166Z" },
+ { url = "https://files.pythonhosted.org/packages/82/f3/4f8f4d478ce69af812c6002b513c5ad3242976923d172dbe5814903be22f/gensim-4.4.0-cp313-cp313-win_amd64.whl", hash = "sha256:6ecb7aed37fb92d24e15a6adbabe693074003263db0fd9ce97c9f4234a9edc1b", size = 24396932, upload-time = "2025-10-18T02:02:11.568Z" },
+]
+
[[package]]
name = "gitdb"
version = "4.0.12"
@@ -797,6 +1007,46 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/84/de/7d3ee9c94b74c3578ea4f88d45e8de9405902f857932334d81e89bce3dfa/google_genai-1.68.0-py3-none-any.whl", hash = "sha256:a1bc9919c0e2ea2907d1e319b65471d3d6d58c54822039a249fe1323e4178d15", size = 750912, upload-time = "2026-03-18T01:03:15.983Z" },
]
+[[package]]
+name = "graspologic"
+version = "3.4.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anytree" },
+ { name = "beartype" },
+ { name = "future" },
+ { name = "gensim" },
+ { name = "graspologic-native" },
+ { name = "hyppo" },
+ { name = "joblib" },
+ { name = "matplotlib" },
+ { name = "networkx" },
+ { name = "numpy" },
+ { name = "pot" },
+ { name = "scikit-learn" },
+ { name = "scipy" },
+ { name = "seaborn" },
+ { name = "statsmodels" },
+ { name = "typing-extensions" },
+ { name = "umap-learn" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/91/bb/0fe2ef85ea775e7b8416b2cf90097aa4b5e0c9c2271d7fe6789bab27d0ca/graspologic-3.4.4.tar.gz", hash = "sha256:79878caf367da3e89046a4ec94291c5b1a5da569f19fdd879d8b45c3563d7110", size = 5134258, upload-time = "2025-09-08T21:44:01.969Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4a/b0/e26eb8fc25f3093ad168fba4101bdcf43258b91672546d20a2b64283845c/graspologic-3.4.4-py3-none-any.whl", hash = "sha256:4ea5cd50f10eaff3fa90f18a8f66b1f5f42c724ac6aeb95e9f081632fc8d2d00", size = 5200993, upload-time = "2025-09-08T21:43:59.843Z" },
+]
+
+[[package]]
+name = "graspologic-native"
+version = "1.2.5"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/25/2d/62b30d89533643ccf4778a18eb023f291b8877b5d85de3342f07b2d363a7/graspologic_native-1.2.5.tar.gz", hash = "sha256:27ea7e01fa44466c0b4cdd678d4561e5d3dc0cb400015683b7ae1386031257a0", size = 2512729, upload-time = "2025-04-02T19:34:22.961Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ae/86/10748f4c474b0c8f6060dd379bb0c4da5d42779244bb13a58656ffb44a03/graspologic_native-1.2.5-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:bf05f2e162ae2a2a8d6e8cfccbe3586d1faa0b808159ff950478348df557c61e", size = 648437, upload-time = "2025-04-02T19:34:16.29Z" },
+ { url = "https://files.pythonhosted.org/packages/42/cc/b75ea35755340bedda29727e5388390c639ea533f55b9249f5ac3003f656/graspologic_native-1.2.5-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4a7fff06ed49c3875cf351bb09a92ae7cbc169ce92dcc4c3439e28e801f822ae", size = 352044, upload-time = "2025-04-02T19:34:18.153Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/55/15e6e4f18bf249b529ac4cd1522b03f5c9ef9284a2f7bfaa1fd1f96464fe/graspologic_native-1.2.5-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:53e7e993e7d70fe0d860773fc62812fbb8cb4ef2d11d8661a1f06f8772593915", size = 364644, upload-time = "2025-04-02T19:34:19.486Z" },
+ { url = "https://files.pythonhosted.org/packages/3b/51/21097af79f3d68626539ab829bdbf6cc42933f020e161972927d916e394c/graspologic_native-1.2.5-cp38-abi3-win_amd64.whl", hash = "sha256:c3ef2172d774083d7e2c8e77daccd218571ddeebeb2c1703cebb1a2cc4c56e07", size = 210438, upload-time = "2025-04-02T19:34:21.139Z" },
+]
+
[[package]]
name = "greenlet"
version = "3.3.2"
@@ -983,6 +1233,26 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/6f/75/ca21955d6117a394a482c7862ce96216239d0e3a53133ae8510727a8bcfa/huggingface_hub-1.7.1-py3-none-any.whl", hash = "sha256:38c6cce7419bbde8caac26a45ed22b0cea24152a8961565d70ec21f88752bfaa", size = 616308, upload-time = "2026-03-13T09:36:06.062Z" },
]
+[[package]]
+name = "hyppo"
+version = "0.5.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "autograd" },
+ { name = "future" },
+ { name = "numba" },
+ { name = "numpy" },
+ { name = "pandas" },
+ { name = "patsy" },
+ { name = "scikit-learn" },
+ { name = "scipy" },
+ { name = "statsmodels" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/dd/a6/0d84fe8486a1447da8bdb8ebb249d525fd8c1d0fe038bceb003c6e0513f9/hyppo-0.5.2.tar.gz", hash = "sha256:4634d15516248a43d25c241ed18beeb79bb3210360f7253693b3f154fe8c9879", size = 125115, upload-time = "2025-05-24T18:33:27.418Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ea/c4/d46858cfac3c0aad314a1fc378beae5c8cac499b677650a34b5a6a3d4328/hyppo-0.5.2-py3-none-any.whl", hash = "sha256:5cc18f9e158fe2cf1804c9a1e979e807118ee89a303f29dc5cb8891d92d44ef3", size = 192272, upload-time = "2025-05-24T18:33:25.904Z" },
+]
+
[[package]]
name = "idna"
version = "3.11"
@@ -1110,6 +1380,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/67/8a/a342b2f0251f3dac4ca17618265d93bf244a2a4d089126e81e4c1056ac50/jiter-0.13.0-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7bb00b6d26db67a05fe3e12c76edc75f32077fb51deed13822dc648fa373bc19", size = 343768, upload-time = "2026-02-02T12:37:55.055Z" },
]
+[[package]]
+name = "joblib"
+version = "1.5.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/41/f2/d34e8b3a08a9cc79a50b2208a93dce981fe615b64d5a4d4abee421d898df/joblib-1.5.3.tar.gz", hash = "sha256:8561a3269e6801106863fd0d6d84bb737be9e7631e33aaed3fb9ce5953688da3", size = 331603, upload-time = "2025-12-15T08:41:46.427Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7b/91/984aca2ec129e2757d1e4e3c81c3fcda9d0f85b74670a094cc443d9ee949/joblib-1.5.3-py3-none-any.whl", hash = "sha256:5fc3c5039fc5ca8c0276333a188bbd59d6b7ab37fe6632daa76bc7f9ec18e713", size = 309071, upload-time = "2025-12-15T08:41:44.973Z" },
+]
+
[[package]]
name = "jsonschema"
version = "4.26.0"
@@ -1137,6 +1416,112 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" },
]
+[[package]]
+name = "kiwisolver"
+version = "1.5.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d0/67/9c61eccb13f0bdca9307614e782fec49ffdde0f7a2314935d489fa93cd9c/kiwisolver-1.5.0.tar.gz", hash = "sha256:d4193f3d9dc3f6f79aaed0e5637f45d98850ebf01f7ca20e69457f3e8946b66a", size = 103482, upload-time = "2026-03-09T13:15:53.382Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/12/dd/a495a9c104be1c476f0386e714252caf2b7eca883915422a64c50b88c6f5/kiwisolver-1.5.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9eed0f7edbb274413b6ee781cca50541c8c0facd3d6fd289779e494340a2b85c", size = 122798, upload-time = "2026-03-09T13:12:58.963Z" },
+ { url = "https://files.pythonhosted.org/packages/11/60/37b4047a2af0cf5ef6d8b4b26e91829ae6fc6a2d1f74524bcb0e7cd28a32/kiwisolver-1.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:3c4923e404d6bcd91b6779c009542e5647fef32e4a5d75e115e3bbac6f2335eb", size = 66216, upload-time = "2026-03-09T13:13:00.155Z" },
+ { url = "https://files.pythonhosted.org/packages/0a/aa/510dc933d87767584abfe03efa445889996c70c2990f6f87c3ebaa0a18c5/kiwisolver-1.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:0df54df7e686afa55e6f21fb86195224a6d9beb71d637e8d7920c95cf0f89aac", size = 63911, upload-time = "2026-03-09T13:13:01.671Z" },
+ { url = "https://files.pythonhosted.org/packages/80/46/bddc13df6c2a40741e0cc7865bb1c9ed4796b6760bd04ce5fae3928ef917/kiwisolver-1.5.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2517e24d7315eb51c10664cdb865195df38ab74456c677df67bb47f12d088a27", size = 1438209, upload-time = "2026-03-09T13:13:03.385Z" },
+ { url = "https://files.pythonhosted.org/packages/fd/d6/76621246f5165e5372f02f5e6f3f48ea336a8f9e96e43997d45b240ed8cd/kiwisolver-1.5.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff710414307fefa903e0d9bdf300972f892c23477829f49504e59834f4195398", size = 1248888, upload-time = "2026-03-09T13:13:05.231Z" },
+ { url = "https://files.pythonhosted.org/packages/b2/c1/31559ec6fb39a5b48035ce29bb63ade628f321785f38c384dee3e2c08bc1/kiwisolver-1.5.0-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6176c1811d9d5a04fa391c490cc44f451e240697a16977f11c6f722efb9041db", size = 1266304, upload-time = "2026-03-09T13:13:06.743Z" },
+ { url = "https://files.pythonhosted.org/packages/5e/ef/1cb8276f2d29cc6a41e0a042f27946ca347d3a4a75acf85d0a16aa6dcc82/kiwisolver-1.5.0-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:50847dca5d197fcbd389c805aa1a1cf32f25d2e7273dc47ab181a517666b68cc", size = 1319650, upload-time = "2026-03-09T13:13:08.607Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/e4/5ba3cecd7ce6236ae4a80f67e5d5531287337d0e1f076ca87a5abe4cd5d0/kiwisolver-1.5.0-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:01808c6d15f4c3e8559595d6d1fe6411c68e4a3822b4b9972b44473b24f4e679", size = 970949, upload-time = "2026-03-09T13:13:10.299Z" },
+ { url = "https://files.pythonhosted.org/packages/5a/69/dc61f7ae9a2f071f26004ced87f078235b5507ab6e5acd78f40365655034/kiwisolver-1.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f1f9f4121ec58628c96baa3de1a55a4e3a333c5102c8e94b64e23bf7b2083309", size = 2199125, upload-time = "2026-03-09T13:13:11.841Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/7b/abbe0f1b5afa85f8d084b73e90e5f801c0939eba16ac2e49af7c61a6c28d/kiwisolver-1.5.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:b7d335370ae48a780c6e6a6bbfa97342f563744c39c35562f3f367665f5c1de2", size = 2293783, upload-time = "2026-03-09T13:13:14.399Z" },
+ { url = "https://files.pythonhosted.org/packages/8a/80/5908ae149d96d81580d604c7f8aefd0e98f4fd728cf172f477e9f2a81744/kiwisolver-1.5.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:800ee55980c18545af444d93fdd60c56b580db5cc54867d8cbf8a1dc0829938c", size = 1960726, upload-time = "2026-03-09T13:13:16.047Z" },
+ { url = "https://files.pythonhosted.org/packages/84/08/a78cb776f8c085b7143142ce479859cfec086bd09ee638a317040b6ef420/kiwisolver-1.5.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:c438f6ca858697c9ab67eb28246c92508af972e114cac34e57a6d4ba17a3ac08", size = 2464738, upload-time = "2026-03-09T13:13:17.897Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/e1/65584da5356ed6cb12c63791a10b208860ac40a83de165cb6a6751a686e3/kiwisolver-1.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:8c63c91f95173f9c2a67c7c526b2cea976828a0e7fced9cdcead2802dc10f8a4", size = 2270718, upload-time = "2026-03-09T13:13:19.421Z" },
+ { url = "https://files.pythonhosted.org/packages/be/6c/28f17390b62b8f2f520e2915095b3c94d88681ecf0041e75389d9667f202/kiwisolver-1.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:beb7f344487cdcb9e1efe4b7a29681b74d34c08f0043a327a74da852a6749e7b", size = 73480, upload-time = "2026-03-09T13:13:20.818Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/0e/2ee5debc4f77a625778fec5501ff3e8036fe361b7ee28ae402a485bb9694/kiwisolver-1.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:ad4ae4ffd1ee9cd11357b4c66b612da9888f4f4daf2f36995eda64bd45370cac", size = 64930, upload-time = "2026-03-09T13:13:21.997Z" },
+ { url = "https://files.pythonhosted.org/packages/4d/b2/818b74ebea34dabe6d0c51cb1c572e046730e64844da6ed646d5298c40ce/kiwisolver-1.5.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:4e9750bc21b886308024f8a54ccb9a2cc38ac9fa813bf4348434e3d54f337ff9", size = 123158, upload-time = "2026-03-09T13:13:23.127Z" },
+ { url = "https://files.pythonhosted.org/packages/bf/d9/405320f8077e8e1c5c4bd6adc45e1e6edf6d727b6da7f2e2533cf58bff71/kiwisolver-1.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:72ec46b7eba5b395e0a7b63025490d3214c11013f4aacb4f5e8d6c3041829588", size = 66388, upload-time = "2026-03-09T13:13:24.765Z" },
+ { url = "https://files.pythonhosted.org/packages/99/9f/795fedf35634f746151ca8839d05681ceb6287fbed6cc1c9bf235f7887c2/kiwisolver-1.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ed3a984b31da7481b103f68776f7128a89ef26ed40f4dc41a2223cda7fb24819", size = 64068, upload-time = "2026-03-09T13:13:25.878Z" },
+ { url = "https://files.pythonhosted.org/packages/c4/13/680c54afe3e65767bed7ec1a15571e1a2f1257128733851ade24abcefbcc/kiwisolver-1.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:bb5136fb5352d3f422df33f0c879a1b0c204004324150cc3b5e3c4f310c9049f", size = 1477934, upload-time = "2026-03-09T13:13:27.166Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/2f/cebfcdb60fd6a9b0f6b47a9337198bcbad6fbe15e68189b7011fd914911f/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b2af221f268f5af85e776a73d62b0845fc8baf8ef0abfae79d29c77d0e776aaf", size = 1278537, upload-time = "2026-03-09T13:13:28.707Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/0d/9b782923aada3fafb1d6b84e13121954515c669b18af0c26e7d21f579855/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b0f172dc8ffaccb8522d7c5d899de00133f2f1ca7b0a49b7da98e901de87bf2d", size = 1296685, upload-time = "2026-03-09T13:13:30.528Z" },
+ { url = "https://files.pythonhosted.org/packages/27/70/83241b6634b04fe44e892688d5208332bde130f38e610c0418f9ede47ded/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6ab8ba9152203feec73758dad83af9a0bbe05001eb4639e547207c40cfb52083", size = 1346024, upload-time = "2026-03-09T13:13:32.818Z" },
+ { url = "https://files.pythonhosted.org/packages/e4/db/30ed226fb271ae1a6431fc0fe0edffb2efe23cadb01e798caeb9f2ceae8f/kiwisolver-1.5.0-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:cdee07c4d7f6d72008d3f73b9bf027f4e11550224c7c50d8df1ae4a37c1402a6", size = 987241, upload-time = "2026-03-09T13:13:34.435Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/bd/c314595208e4c9587652d50959ead9e461995389664e490f4dce7ff0f782/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7c60d3c9b06fb23bd9c6139281ccbdc384297579ae037f08ae90c69f6845c0b1", size = 2227742, upload-time = "2026-03-09T13:13:36.4Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/43/0499cec932d935229b5543d073c2b87c9c22846aab48881e9d8d6e742a2d/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:e315e5ec90d88e140f57696ff85b484ff68bb311e36f2c414aa4286293e6dee0", size = 2323966, upload-time = "2026-03-09T13:13:38.204Z" },
+ { url = "https://files.pythonhosted.org/packages/3d/6f/79b0d760907965acfd9d61826a3d41f8f093c538f55cd2633d3f0db269f6/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:1465387ac63576c3e125e5337a6892b9e99e0627d52317f3ca79e6930d889d15", size = 1977417, upload-time = "2026-03-09T13:13:39.966Z" },
+ { url = "https://files.pythonhosted.org/packages/ab/31/01d0537c41cb75a551a438c3c7a80d0c60d60b81f694dac83dd436aec0d0/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:530a3fd64c87cffa844d4b6b9768774763d9caa299e9b75d8eca6a4423b31314", size = 2491238, upload-time = "2026-03-09T13:13:41.698Z" },
+ { url = "https://files.pythonhosted.org/packages/e4/34/8aefdd0be9cfd00a44509251ba864f5caf2991e36772e61c408007e7f417/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:1d9daea4ea6b9be74fe2f01f7fbade8d6ffab263e781274cffca0dba9be9eec9", size = 2294947, upload-time = "2026-03-09T13:13:43.343Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/cf/0348374369ca588f8fe9c338fae49fa4e16eeb10ffb3d012f23a54578a9e/kiwisolver-1.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:f18c2d9782259a6dc132fdc7a63c168cbc74b35284b6d75c673958982a378384", size = 73569, upload-time = "2026-03-09T13:13:45.792Z" },
+ { url = "https://files.pythonhosted.org/packages/28/26/192b26196e2316e2bd29deef67e37cdf9870d9af8e085e521afff0fed526/kiwisolver-1.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:f7c7553b13f69c1b29a5bde08ddc6d9d0c8bfb84f9ed01c30db25944aeb852a7", size = 64997, upload-time = "2026-03-09T13:13:46.878Z" },
+ { url = "https://files.pythonhosted.org/packages/9d/69/024d6711d5ba575aa65d5538042e99964104e97fa153a9f10bc369182bc2/kiwisolver-1.5.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:fd40bb9cd0891c4c3cb1ddf83f8bbfa15731a248fdc8162669405451e2724b09", size = 123166, upload-time = "2026-03-09T13:13:48.032Z" },
+ { url = "https://files.pythonhosted.org/packages/ce/48/adbb40df306f587054a348831220812b9b1d787aff714cfbc8556e38fccd/kiwisolver-1.5.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:c0e1403fd7c26d77c1f03e096dc58a5c726503fa0db0456678b8668f76f521e3", size = 66395, upload-time = "2026-03-09T13:13:49.365Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/3a/d0a972b34e1c63e2409413104216cd1caa02c5a37cb668d1687d466c1c45/kiwisolver-1.5.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:dda366d548e89a90d88a86c692377d18d8bd64b39c1fb2b92cb31370e2896bbd", size = 64065, upload-time = "2026-03-09T13:13:50.562Z" },
+ { url = "https://files.pythonhosted.org/packages/2b/0a/7b98e1e119878a27ba8618ca1e18b14f992ff1eda40f47bccccf4de44121/kiwisolver-1.5.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:332b4f0145c30b5f5ad9374881133e5aa64320428a57c2c2b61e9d891a51c2f3", size = 1477903, upload-time = "2026-03-09T13:13:52.084Z" },
+ { url = "https://files.pythonhosted.org/packages/18/d8/55638d89ffd27799d5cc3d8aa28e12f4ce7a64d67b285114dbedc8ea4136/kiwisolver-1.5.0-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0c50b89ffd3e1a911c69a1dd3de7173c0cd10b130f56222e57898683841e4f96", size = 1278751, upload-time = "2026-03-09T13:13:54.673Z" },
+ { url = "https://files.pythonhosted.org/packages/b8/97/b4c8d0d18421ecceba20ad8701358453b88e32414e6f6950b5a4bad54e65/kiwisolver-1.5.0-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4db576bb8c3ef9365f8b40fe0f671644de6736ae2c27a2c62d7d8a1b4329f099", size = 1296793, upload-time = "2026-03-09T13:13:56.287Z" },
+ { url = "https://files.pythonhosted.org/packages/c4/10/f862f94b6389d8957448ec9df59450b81bec4abb318805375c401a1e6892/kiwisolver-1.5.0-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0b85aad90cea8ac6797a53b5d5f2e967334fa4d1149f031c4537569972596cb8", size = 1346041, upload-time = "2026-03-09T13:13:58.269Z" },
+ { url = "https://files.pythonhosted.org/packages/a3/6a/f1650af35821eaf09de398ec0bc2aefc8f211f0cda50204c9f1673741ba9/kiwisolver-1.5.0-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:d36ca54cb4c6c4686f7cbb7b817f66f5911c12ddb519450bbe86707155028f87", size = 987292, upload-time = "2026-03-09T13:13:59.871Z" },
+ { url = "https://files.pythonhosted.org/packages/de/19/d7fb82984b9238115fe629c915007be608ebd23dc8629703d917dbfaffd4/kiwisolver-1.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:38f4a703656f493b0ad185211ccfca7f0386120f022066b018eb5296d8613e23", size = 2227865, upload-time = "2026-03-09T13:14:01.401Z" },
+ { url = "https://files.pythonhosted.org/packages/7f/b9/46b7f386589fd222dac9e9de9c956ce5bcefe2ee73b4e79891381dda8654/kiwisolver-1.5.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:3ac2360e93cb41be81121755c6462cff3beaa9967188c866e5fce5cf13170859", size = 2324369, upload-time = "2026-03-09T13:14:02.972Z" },
+ { url = "https://files.pythonhosted.org/packages/92/8b/95e237cf3d9c642960153c769ddcbe278f182c8affb20cecc1cc983e7cc5/kiwisolver-1.5.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:c95cab08d1965db3d84a121f1c7ce7479bdd4072c9b3dafd8fecce48a2e6b902", size = 1977989, upload-time = "2026-03-09T13:14:04.503Z" },
+ { url = "https://files.pythonhosted.org/packages/1b/95/980c9df53501892784997820136c01f62bc1865e31b82b9560f980c0e649/kiwisolver-1.5.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:fc20894c3d21194d8041a28b65622d5b86db786da6e3cfe73f0c762951a61167", size = 2491645, upload-time = "2026-03-09T13:14:06.106Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/32/900647fd0840abebe1561792c6b31e6a7c0e278fc3973d30572a965ca14c/kiwisolver-1.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7a32f72973f0f950c1920475d5c5ea3d971b81b6f0ec53b8d0a956cc965f22e0", size = 2295237, upload-time = "2026-03-09T13:14:08.891Z" },
+ { url = "https://files.pythonhosted.org/packages/be/8a/be60e3bbcf513cc5a50f4a3e88e1dcecebb79c1ad607a7222877becaa101/kiwisolver-1.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:0bf3acf1419fa93064a4c2189ac0b58e3be7872bf6ee6177b0d4c63dc4cea276", size = 73573, upload-time = "2026-03-09T13:14:12.327Z" },
+ { url = "https://files.pythonhosted.org/packages/4d/d2/64be2e429eb4fca7f7e1c52a91b12663aeaf25de3895e5cca0f47ef2a8d0/kiwisolver-1.5.0-cp313-cp313-win_arm64.whl", hash = "sha256:fa8eb9ecdb7efb0b226acec134e0d709e87a909fa4971a54c0c4f6e88635484c", size = 64998, upload-time = "2026-03-09T13:14:13.469Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/69/ce68dd0c85755ae2de490bf015b62f2cea5f6b14ff00a463f9d0774449ff/kiwisolver-1.5.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:db485b3847d182b908b483b2ed133c66d88d49cacf98fd278fadafe11b4478d1", size = 125700, upload-time = "2026-03-09T13:14:14.636Z" },
+ { url = "https://files.pythonhosted.org/packages/74/aa/937aac021cf9d4349990d47eb319309a51355ed1dbdc9c077cdc9224cb11/kiwisolver-1.5.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:be12f931839a3bdfe28b584db0e640a65a8bcbc24560ae3fdb025a449b3d754e", size = 67537, upload-time = "2026-03-09T13:14:15.808Z" },
+ { url = "https://files.pythonhosted.org/packages/ee/20/3a87fbece2c40ad0f6f0aefa93542559159c5f99831d596050e8afae7a9f/kiwisolver-1.5.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:16b85d37c2cbb3253226d26e64663f755d88a03439a9c47df6246b35defbdfb7", size = 65514, upload-time = "2026-03-09T13:14:18.035Z" },
+ { url = "https://files.pythonhosted.org/packages/f0/7f/f943879cda9007c45e1f7dba216d705c3a18d6b35830e488b6c6a4e7cdf0/kiwisolver-1.5.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4432b835675f0ea7414aab3d37d119f7226d24869b7a829caeab49ebda407b0c", size = 1584848, upload-time = "2026-03-09T13:14:19.745Z" },
+ { url = "https://files.pythonhosted.org/packages/37/f8/4d4f85cc1870c127c88d950913370dd76138482161cd07eabbc450deff01/kiwisolver-1.5.0-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b0feb50971481a2cc44d94e88bdb02cdd497618252ae226b8eb1201b957e368", size = 1391542, upload-time = "2026-03-09T13:14:21.54Z" },
+ { url = "https://files.pythonhosted.org/packages/04/0b/65dd2916c84d252b244bd405303220f729e7c17c9d7d33dca6feeff9ffc4/kiwisolver-1.5.0-cp313-cp313t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:56fa888f10d0f367155e76ce849fa1166fc9730d13bd2d65a2aa13b6f5424489", size = 1404447, upload-time = "2026-03-09T13:14:23.205Z" },
+ { url = "https://files.pythonhosted.org/packages/39/5c/2606a373247babce9b1d056c03a04b65f3cf5290a8eac5d7bdead0a17e21/kiwisolver-1.5.0-cp313-cp313t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:940dda65d5e764406b9fb92761cbf462e4e63f712ab60ed98f70552e496f3bf1", size = 1455918, upload-time = "2026-03-09T13:14:24.74Z" },
+ { url = "https://files.pythonhosted.org/packages/d5/d1/c6078b5756670658e9192a2ef11e939c92918833d2745f85cd14a6004bdf/kiwisolver-1.5.0-cp313-cp313t-manylinux_2_39_riscv64.whl", hash = "sha256:89fc958c702ee9a745e4700378f5d23fddbc46ff89e8fdbf5395c24d5c1452a3", size = 1072856, upload-time = "2026-03-09T13:14:26.597Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/c8/7def6ddf16eb2b3741d8b172bdaa9af882b03c78e9b0772975408801fa63/kiwisolver-1.5.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9027d773c4ff81487181a925945743413f6069634d0b122d0b37684ccf4f1e18", size = 2333580, upload-time = "2026-03-09T13:14:28.237Z" },
+ { url = "https://files.pythonhosted.org/packages/9e/87/2ac1fce0eb1e616fcd3c35caa23e665e9b1948bb984f4764790924594128/kiwisolver-1.5.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:5b233ea3e165e43e35dba1d2b8ecc21cf070b45b65ae17dd2747d2713d942021", size = 2423018, upload-time = "2026-03-09T13:14:30.018Z" },
+ { url = "https://files.pythonhosted.org/packages/67/13/c6700ccc6cc218716bfcda4935e4b2997039869b4ad8a94f364c5a3b8e63/kiwisolver-1.5.0-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:ce9bf03dad3b46408c08649c6fbd6ca28a9fce0eb32fdfffa6775a13103b5310", size = 2062804, upload-time = "2026-03-09T13:14:32.888Z" },
+ { url = "https://files.pythonhosted.org/packages/1b/bd/877056304626943ff0f1f44c08f584300c199b887cb3176cd7e34f1515f1/kiwisolver-1.5.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:fc4d3f1fb9ca0ae9f97b095963bc6326f1dbfd3779d6679a1e016b9baaa153d3", size = 2597482, upload-time = "2026-03-09T13:14:34.971Z" },
+ { url = "https://files.pythonhosted.org/packages/75/19/c60626c47bf0f8ac5dcf72c6c98e266d714f2fbbfd50cf6dab5ede3aaa50/kiwisolver-1.5.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:f443b4825c50a51ee68585522ab4a1d1257fac65896f282b4c6763337ac9f5d2", size = 2394328, upload-time = "2026-03-09T13:14:36.816Z" },
+ { url = "https://files.pythonhosted.org/packages/47/84/6a6d5e5bb8273756c27b7d810d47f7ef2f1f9b9fd23c9ee9a3f8c75c9cef/kiwisolver-1.5.0-cp313-cp313t-win_arm64.whl", hash = "sha256:893ff3a711d1b515ba9da14ee090519bad4610ed1962fbe298a434e8c5f8db53", size = 68410, upload-time = "2026-03-09T13:14:38.695Z" },
+ { url = "https://files.pythonhosted.org/packages/e4/d7/060f45052f2a01ad5762c8fdecd6d7a752b43400dc29ff75cd47225a40fd/kiwisolver-1.5.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8df31fe574b8b3993cc61764f40941111b25c2d9fea13d3ce24a49907cd2d615", size = 123231, upload-time = "2026-03-09T13:14:41.323Z" },
+ { url = "https://files.pythonhosted.org/packages/c2/a7/78da680eadd06ff35edef6ef68a1ad273bad3e2a0936c9a885103230aece/kiwisolver-1.5.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:1d49a49ac4cbfb7c1375301cd1ec90169dfeae55ff84710d782260ce77a75a02", size = 66489, upload-time = "2026-03-09T13:14:42.534Z" },
+ { url = "https://files.pythonhosted.org/packages/49/b2/97980f3ad4fae37dd7fe31626e2bf75fbf8bdf5d303950ec1fab39a12da8/kiwisolver-1.5.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:0cbe94b69b819209a62cb27bdfa5dc2a8977d8de2f89dfd97ba4f53ed3af754e", size = 64063, upload-time = "2026-03-09T13:14:44.759Z" },
+ { url = "https://files.pythonhosted.org/packages/e7/f9/b06c934a6aa8bc91f566bd2a214fd04c30506c2d9e2b6b171953216a65b6/kiwisolver-1.5.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:80aa065ffd378ff784822a6d7c3212f2d5f5e9c3589614b5c228b311fd3063ac", size = 1475913, upload-time = "2026-03-09T13:14:46.247Z" },
+ { url = "https://files.pythonhosted.org/packages/6b/f0/f768ae564a710135630672981231320bc403cf9152b5596ec5289de0f106/kiwisolver-1.5.0-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e7f886f47ab881692f278ae901039a234e4025a68e6dfab514263a0b1c4ae05", size = 1282782, upload-time = "2026-03-09T13:14:48.458Z" },
+ { url = "https://files.pythonhosted.org/packages/e2/9f/1de7aad00697325f05238a5f2eafbd487fb637cc27a558b5367a5f37fb7f/kiwisolver-1.5.0-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5060731cc3ed12ca3a8b57acd4aeca5bbc2f49216dd0bec1650a1acd89486bcd", size = 1300815, upload-time = "2026-03-09T13:14:50.721Z" },
+ { url = "https://files.pythonhosted.org/packages/5a/c2/297f25141d2e468e0ce7f7a7b92e0cf8918143a0cbd3422c1ad627e85a06/kiwisolver-1.5.0-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7a4aa69609f40fce3cbc3f87b2061f042eee32f94b8f11db707b66a26461591a", size = 1347925, upload-time = "2026-03-09T13:14:52.304Z" },
+ { url = "https://files.pythonhosted.org/packages/b9/d3/f4c73a02eb41520c47610207b21afa8cdd18fdbf64ffd94674ae21c4812d/kiwisolver-1.5.0-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:d168fda2dbff7b9b5f38e693182d792a938c31db4dac3a80a4888de603c99554", size = 991322, upload-time = "2026-03-09T13:14:54.637Z" },
+ { url = "https://files.pythonhosted.org/packages/7b/46/d3f2efef7732fcda98d22bf4ad5d3d71d545167a852ca710a494f4c15343/kiwisolver-1.5.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:413b820229730d358efd838ecbab79902fe97094565fdc80ddb6b0a18c18a581", size = 2232857, upload-time = "2026-03-09T13:14:56.471Z" },
+ { url = "https://files.pythonhosted.org/packages/3f/ec/2d9756bf2b6d26ae4349b8d3662fb3993f16d80c1f971c179ce862b9dbae/kiwisolver-1.5.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:5124d1ea754509b09e53738ec185584cc609aae4a3b510aaf4ed6aa047ef9303", size = 2329376, upload-time = "2026-03-09T13:14:58.072Z" },
+ { url = "https://files.pythonhosted.org/packages/8f/9f/876a0a0f2260f1bde92e002b3019a5fabc35e0939c7d945e0fa66185eb20/kiwisolver-1.5.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:e4415a8db000bf49a6dd1c478bf70062eaacff0f462b92b0ba68791a905861f9", size = 1982549, upload-time = "2026-03-09T13:14:59.668Z" },
+ { url = "https://files.pythonhosted.org/packages/6c/4f/ba3624dfac23a64d54ac4179832860cb537c1b0af06024936e82ca4154a0/kiwisolver-1.5.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:d618fd27420381a4f6044faa71f46d8bfd911bd077c555f7138ed88729bfbe79", size = 2494680, upload-time = "2026-03-09T13:15:01.364Z" },
+ { url = "https://files.pythonhosted.org/packages/39/b7/97716b190ab98911b20d10bf92eca469121ec483b8ce0edd314f51bc85af/kiwisolver-1.5.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5092eb5b1172947f57d6ea7d89b2f29650414e4293c47707eb499ec07a0ac796", size = 2297905, upload-time = "2026-03-09T13:15:03.925Z" },
+ { url = "https://files.pythonhosted.org/packages/a3/36/4e551e8aa55c9188bca9abb5096805edbf7431072b76e2298e34fd3a3008/kiwisolver-1.5.0-cp314-cp314-win_amd64.whl", hash = "sha256:d76e2d8c75051d58177e762164d2e9ab92886534e3a12e795f103524f221dd8e", size = 75086, upload-time = "2026-03-09T13:15:07.775Z" },
+ { url = "https://files.pythonhosted.org/packages/70/15/9b90f7df0e31a003c71649cf66ef61c3c1b862f48c81007fa2383c8bd8d7/kiwisolver-1.5.0-cp314-cp314-win_arm64.whl", hash = "sha256:fa6248cd194edff41d7ea9425ced8ca3a6f838bfb295f6f1d6e6bb694a8518df", size = 66577, upload-time = "2026-03-09T13:15:09.139Z" },
+ { url = "https://files.pythonhosted.org/packages/17/01/7dc8c5443ff42b38e72731643ed7cf1ed9bf01691ae5cdca98501999ed83/kiwisolver-1.5.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:d1ffeb80b5676463d7a7d56acbe8e37a20ce725570e09549fe738e02ca6b7e1e", size = 125794, upload-time = "2026-03-09T13:15:10.525Z" },
+ { url = "https://files.pythonhosted.org/packages/46/8a/b4ebe46ebaac6a303417fab10c2e165c557ddaff558f9699d302b256bc53/kiwisolver-1.5.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:bc4d8e252f532ab46a1de9349e2d27b91fce46736a9eedaa37beaca66f574ed4", size = 67646, upload-time = "2026-03-09T13:15:12.016Z" },
+ { url = "https://files.pythonhosted.org/packages/60/35/10a844afc5f19d6f567359bf4789e26661755a2f36200d5d1ed8ad0126e5/kiwisolver-1.5.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:6783e069732715ad0c3ce96dbf21dbc2235ab0593f2baf6338101f70371f4028", size = 65511, upload-time = "2026-03-09T13:15:13.311Z" },
+ { url = "https://files.pythonhosted.org/packages/f8/8a/685b297052dd041dcebce8e8787b58923b6e78acc6115a0dc9189011c44b/kiwisolver-1.5.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e7c4c09a490dc4d4a7f8cbee56c606a320f9dc28cf92a7157a39d1ce7676a657", size = 1584858, upload-time = "2026-03-09T13:15:15.103Z" },
+ { url = "https://files.pythonhosted.org/packages/9e/80/04865e3d4638ac5bddec28908916df4a3075b8c6cc101786a96803188b96/kiwisolver-1.5.0-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2a075bd7bd19c70cf67c8badfa36cf7c5d8de3c9ddb8420c51e10d9c50e94920", size = 1392539, upload-time = "2026-03-09T13:15:16.661Z" },
+ { url = "https://files.pythonhosted.org/packages/ba/01/77a19cacc0893fa13fafa46d1bba06fb4dc2360b3292baf4b56d8e067b24/kiwisolver-1.5.0-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bdd3e53429ff02aa319ba59dfe4ceeec345bf46cf180ec2cf6fd5b942e7975e9", size = 1405310, upload-time = "2026-03-09T13:15:18.229Z" },
+ { url = "https://files.pythonhosted.org/packages/53/39/bcaf5d0cca50e604cfa9b4e3ae1d64b50ca1ae5b754122396084599ef903/kiwisolver-1.5.0-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3cdcb35dc9d807259c981a85531048ede628eabcffb3239adf3d17463518992d", size = 1456244, upload-time = "2026-03-09T13:15:20.444Z" },
+ { url = "https://files.pythonhosted.org/packages/d0/7a/72c187abc6975f6978c3e39b7cf67aeb8b3c0a8f9790aa7fd412855e9e1f/kiwisolver-1.5.0-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:70d593af6a6ca332d1df73d519fddb5148edb15cd90d5f0155e3746a6d4fcc65", size = 1073154, upload-time = "2026-03-09T13:15:22.039Z" },
+ { url = "https://files.pythonhosted.org/packages/c7/ca/cf5b25783ebbd59143b4371ed0c8428a278abe68d6d0104b01865b1bbd0f/kiwisolver-1.5.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:377815a8616074cabbf3f53354e1d040c35815a134e01d7614b7692e4bf8acfa", size = 2334377, upload-time = "2026-03-09T13:15:23.741Z" },
+ { url = "https://files.pythonhosted.org/packages/4a/e5/b1f492adc516796e88751282276745340e2a72dcd0d36cf7173e0daf3210/kiwisolver-1.5.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:0255a027391d52944eae1dbb5d4cc5903f57092f3674e8e544cdd2622826b3f0", size = 2425288, upload-time = "2026-03-09T13:15:25.789Z" },
+ { url = "https://files.pythonhosted.org/packages/e6/e5/9b21fbe91a61b8f409d74a26498706e97a48008bfcd1864373d32a6ba31c/kiwisolver-1.5.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:012b1eb16e28718fa782b5e61dc6f2da1f0792ca73bd05d54de6cb9561665fc9", size = 2063158, upload-time = "2026-03-09T13:15:27.63Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/02/83f47986138310f95ea95531f851b2a62227c11cbc3e690ae1374fe49f0f/kiwisolver-1.5.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:0e3aafb33aed7479377e5e9a82e9d4bf87063741fc99fc7ae48b0f16e32bdd6f", size = 2597260, upload-time = "2026-03-09T13:15:29.421Z" },
+ { url = "https://files.pythonhosted.org/packages/07/18/43a5f24608d8c313dd189cf838c8e68d75b115567c6279de7796197cfb6a/kiwisolver-1.5.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:e7a116ae737f0000343218c4edf5bd45893bfeaff0993c0b215d7124c9f77646", size = 2394403, upload-time = "2026-03-09T13:15:31.517Z" },
+ { url = "https://files.pythonhosted.org/packages/3b/b5/98222136d839b8afabcaa943b09bd05888c2d36355b7e448550211d1fca4/kiwisolver-1.5.0-cp314-cp314t-win_amd64.whl", hash = "sha256:1dd9b0b119a350976a6d781e7278ec7aca0b201e1a9e2d23d9804afecb6ca681", size = 79687, upload-time = "2026-03-09T13:15:33.204Z" },
+ { url = "https://files.pythonhosted.org/packages/99/a2/ca7dc962848040befed12732dff6acae7fb3c4f6fc4272b3f6c9a30b8713/kiwisolver-1.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:58f812017cd2985c21fbffb4864d59174d4903dd66fa23815e74bbc7a0e2dd57", size = 70032, upload-time = "2026-03-09T13:15:34.411Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/fa/2910df836372d8761bb6eff7d8bdcb1613b5c2e03f260efe7abe34d388a7/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-macosx_10_13_x86_64.whl", hash = "sha256:5ae8e62c147495b01a0f4765c878e9bfdf843412446a247e28df59936e99e797", size = 130262, upload-time = "2026-03-09T13:15:35.629Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/41/c5f71f9f00aabcc71fee8b7475e3f64747282580c2fe748961ba29b18385/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:f6764a4ccab3078db14a632420930f6186058750df066b8ea2a7106df91d3203", size = 138036, upload-time = "2026-03-09T13:15:36.894Z" },
+ { url = "https://files.pythonhosted.org/packages/fa/06/7399a607f434119c6e1fdc8ec89a8d51ccccadf3341dee4ead6bd14caaf5/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c31c13da98624f957b0fb1b5bae5383b2333c2c3f6793d9825dd5ce79b525cb7", size = 194295, upload-time = "2026-03-09T13:15:38.22Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/91/53255615acd2a1eaca307ede3c90eb550bae9c94581f8c00081b6b1c8f44/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:1f1489f769582498610e015a8ef2d36f28f505ab3096d0e16b4858a9ec214f57", size = 75987, upload-time = "2026-03-09T13:15:39.65Z" },
+ { url = "https://files.pythonhosted.org/packages/e9/eb/5fcbbbf9a0e2c3a35effb88831a483345326bbc3a030a3b5b69aee647f84/kiwisolver-1.5.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:ec4c85dc4b687c7f7f15f553ff26a98bfe8c58f5f7f0ac8905f0ba4c7be60232", size = 59532, upload-time = "2026-03-09T13:15:47.047Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/9b/e17104555bb4db148fd52327feea1e96be4b88e8e008b029002c281a21ab/kiwisolver-1.5.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:12e91c215a96e39f57989c8912ae761286ac5a9584d04030ceb3368a357f017a", size = 57420, upload-time = "2026-03-09T13:15:48.199Z" },
+ { url = "https://files.pythonhosted.org/packages/48/44/2b5b95b7aa39fb2d8d9d956e0f3d5d45aef2ae1d942d4c3ffac2f9cfed1a/kiwisolver-1.5.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:be4a51a55833dc29ab5d7503e7bcb3b3af3402d266018137127450005cdfe737", size = 79892, upload-time = "2026-03-09T13:15:49.694Z" },
+ { url = "https://files.pythonhosted.org/packages/52/7d/7157f9bba6b455cfb4632ed411e199fc8b8977642c2b12082e1bd9e6d173/kiwisolver-1.5.0-pp311-pypy311_pp73-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:daae526907e262de627d8f70058a0f64acc9e2641c164c99c8f594b34a799a16", size = 77603, upload-time = "2026-03-09T13:15:50.945Z" },
+ { url = "https://files.pythonhosted.org/packages/0a/dd/8050c947d435c8d4bc94e3252f4d8bb8a76cfb424f043a8680be637a57f1/kiwisolver-1.5.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:59cd8683f575d96df5bb48f6add94afc055012c29e28124fcae2b63661b9efb1", size = 73558, upload-time = "2026-03-09T13:15:52.112Z" },
+]
+
[[package]]
name = "lance-namespace"
version = "0.6.1"
@@ -1283,6 +1668,34 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/19/2c/a670cc050fcd6f45c6199eb99e259c73aea92edba8d5c2fc1b3686d36217/litellm-1.83.0-py3-none-any.whl", hash = "sha256:88c536d339248f3987571493015784671ba3f193a328e1ea6780dbebaa2094a8", size = 15610306, upload-time = "2026-03-31T05:08:21.987Z" },
]
+[[package]]
+name = "llvmlite"
+version = "0.47.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/01/88/a8952b6d5c21e74cbf158515b779666f692846502623e9e3c39d8e8ba25f/llvmlite-0.47.0.tar.gz", hash = "sha256:62031ce968ec74e95092184d4b0e857e444f8fdff0b8f9213707699570c33ccc", size = 193614, upload-time = "2026-03-31T18:29:53.497Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/34/0b/b9d1911cfefa61399821dfb37f486d83e0f42630a8d12f7194270c417002/llvmlite-0.47.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:74090f0dcfd6f24ebbef3f21f11e38111c4d7e6919b54c4416e1e357c3446b07", size = 37232770, upload-time = "2026-03-31T18:28:26.765Z" },
+ { url = "https://files.pythonhosted.org/packages/46/27/5799b020e4cdfb25a7c951c06a96397c135efcdc21b78d853bbd9c814c7d/llvmlite-0.47.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ca14f02e29134e837982497959a8e2193d6035235de1cb41a9cb2bd6da4eedbb", size = 56275177, upload-time = "2026-03-31T18:28:31.01Z" },
+ { url = "https://files.pythonhosted.org/packages/7e/51/48a53fedf01cb1f3f43ef200be17ebf83c8d9a04018d3783c1a226c342c2/llvmlite-0.47.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:12a69d4bb05f402f30477e21eeabe81911e7c251cecb192bed82cd83c9db10d8", size = 55128631, upload-time = "2026-03-31T18:28:36.046Z" },
+ { url = "https://files.pythonhosted.org/packages/a2/50/59227d06bdc96e23322713c381af4e77420949d8cd8a042c79e0043096cc/llvmlite-0.47.0-cp311-cp311-win_amd64.whl", hash = "sha256:c37d6eb7aaabfa83ab9c2ff5b5cdb95a5e6830403937b2c588b7490724e05327", size = 38138400, upload-time = "2026-03-31T18:28:40.076Z" },
+ { url = "https://files.pythonhosted.org/packages/fa/48/4b7fe0e34c169fa2f12532916133e0b219d2823b540733651b34fdac509a/llvmlite-0.47.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:306a265f408c259067257a732c8e159284334018b4083a9e35f67d19792b164f", size = 37232769, upload-time = "2026-03-31T18:28:43.735Z" },
+ { url = "https://files.pythonhosted.org/packages/e6/4b/e3f2cd17822cf772a4a51a0a8080b0032e6d37b2dbe8cfb724eac4e31c52/llvmlite-0.47.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5853bf26160857c0c2573415ff4efe01c4c651e59e2c55c2a088740acfee51cd", size = 56275178, upload-time = "2026-03-31T18:28:48.342Z" },
+ { url = "https://files.pythonhosted.org/packages/b6/55/a3b4a543185305a9bdf3d9759d53646ed96e55e7dfd43f53e7a421b8fbae/llvmlite-0.47.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:003bcf7fa579e14db59c1a1e113f93ab8a06b56a4be31c7f08264d1d4072d077", size = 55128632, upload-time = "2026-03-31T18:28:52.901Z" },
+ { url = "https://files.pythonhosted.org/packages/2f/f5/d281ae0f79378a5a91f308ea9fdb9f9cc068fddd09629edc0725a5a8fde1/llvmlite-0.47.0-cp312-cp312-win_amd64.whl", hash = "sha256:f3079f25bdc24cd9d27c4b2b5e68f5f60c4fdb7e8ad5ee2b9b006007558f9df7", size = 38138692, upload-time = "2026-03-31T18:28:57.147Z" },
+ { url = "https://files.pythonhosted.org/packages/77/6f/4615353e016799f80fa52ccb270a843c413b22361fadda2589b2922fb9b0/llvmlite-0.47.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:a3c6a735d4e1041808434f9d440faa3d78d9b4af2ee64d05a66f351883b6ceec", size = 37232771, upload-time = "2026-03-31T18:29:01.324Z" },
+ { url = "https://files.pythonhosted.org/packages/31/b8/69f5565f1a280d032525878a86511eebed0645818492feeb169dfb20ae8e/llvmlite-0.47.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2699a74321189e812d476a43d6d7f652f51811e7b5aad9d9bba842a1c7927acb", size = 56275178, upload-time = "2026-03-31T18:29:05.748Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/da/b32cafcb926fb0ce2aa25553bf32cb8764af31438f40e2481df08884c947/llvmlite-0.47.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6c6951e2b29930227963e53ee152441f0e14be92e9d4231852102d986c761e40", size = 55128632, upload-time = "2026-03-31T18:29:11.235Z" },
+ { url = "https://files.pythonhosted.org/packages/46/9f/4898b44e4042c60fafcb1162dfb7014f6f15b1ec19bf29cfea6bf26df90d/llvmlite-0.47.0-cp313-cp313-win_amd64.whl", hash = "sha256:c2e9adf8698d813a9a5efb2d4370caf344dbc1e145019851fee6a6f319ba760e", size = 38138695, upload-time = "2026-03-31T18:29:15.43Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/d4/33c8af00f0bf6f552d74f3a054f648af2c5bc6bece97972f3bfadce4f5ec/llvmlite-0.47.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:de966c626c35c9dff5ae7bf12db25637738d0df83fc370cf793bc94d43d92d14", size = 37232773, upload-time = "2026-03-31T18:29:19.453Z" },
+ { url = "https://files.pythonhosted.org/packages/64/1d/a760e993e0c0ba6db38d46b9f48f6c7dceb8ac838824997fb9e25f97bc04/llvmlite-0.47.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ddbccff2aeaff8670368340a158abefc032fe9b3ccf7d9c496639263d00151aa", size = 56275176, upload-time = "2026-03-31T18:29:24.149Z" },
+ { url = "https://files.pythonhosted.org/packages/84/3b/e679bc3b29127182a7f4aa2d2e9e5bea42adb93fb840484147d59c236299/llvmlite-0.47.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4a7b778a2e144fc64468fb9bf509ac1226c9813a00b4d7afea5d988c4e22fca", size = 55128631, upload-time = "2026-03-31T18:29:29.536Z" },
+ { url = "https://files.pythonhosted.org/packages/be/f7/19e2a09c62809c9e63bbd14ce71fb92c6ff7b7b3045741bb00c781efc3c9/llvmlite-0.47.0-cp314-cp314-win_amd64.whl", hash = "sha256:694e3c2cdc472ed2bd8bd4555ca002eec4310961dd58ef791d508f57b5cc4c94", size = 39153826, upload-time = "2026-03-31T18:29:33.681Z" },
+ { url = "https://files.pythonhosted.org/packages/40/a1/581a8c707b5e80efdbbe1dd94527404d33fe50bceb71f39d5a7e11bd57b7/llvmlite-0.47.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:92ec8a169a20b473c1c54d4695e371bde36489fc1efa3688e11e99beba0abf9c", size = 37232772, upload-time = "2026-03-31T18:29:37.952Z" },
+ { url = "https://files.pythonhosted.org/packages/11/03/16090dd6f74ba2b8b922276047f15962fbeea0a75d5601607edb301ba945/llvmlite-0.47.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:fa1cbd800edd3b20bc141521f7fd45a6185a5b84109aa6855134e81397ffe72b", size = 56275178, upload-time = "2026-03-31T18:29:42.58Z" },
+ { url = "https://files.pythonhosted.org/packages/f5/cb/0abf1dd4c5286a95ffe0c1d8c67aec06b515894a0dd2ac97f5e27b82ab0b/llvmlite-0.47.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f6725179b89f03b17dabe236ff3422cb8291b4c1bf40af152826dfd34e350ae8", size = 55128632, upload-time = "2026-03-31T18:29:46.939Z" },
+ { url = "https://files.pythonhosted.org/packages/4f/79/d3bbab197e86e0ff4f9c07122895b66a3e0d024247fcff7f12c473cb36d9/llvmlite-0.47.0-cp314-cp314t-win_amd64.whl", hash = "sha256:6842cf6f707ec4be3d985a385ad03f72b2d724439e118fcbe99b2929964f0453", size = 39153839, upload-time = "2026-03-31T18:29:51.004Z" },
+]
+
[[package]]
name = "mako"
version = "1.3.10"
@@ -1381,6 +1794,70 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" },
]
+[[package]]
+name = "matplotlib"
+version = "3.10.8"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "contourpy" },
+ { name = "cycler" },
+ { name = "fonttools" },
+ { name = "kiwisolver" },
+ { name = "numpy" },
+ { name = "packaging" },
+ { name = "pillow" },
+ { name = "pyparsing" },
+ { name = "python-dateutil" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/8a/76/d3c6e3a13fe484ebe7718d14e269c9569c4eb0020a968a327acb3b9a8fe6/matplotlib-3.10.8.tar.gz", hash = "sha256:2299372c19d56bcd35cf05a2738308758d32b9eaed2371898d8f5bd33f084aa3", size = 34806269, upload-time = "2025-12-10T22:56:51.155Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f8/86/de7e3a1cdcfc941483af70609edc06b83e7c8a0e0dc9ac325200a3f4d220/matplotlib-3.10.8-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:6be43b667360fef5c754dda5d25a32e6307a03c204f3c0fc5468b78fa87b4160", size = 8251215, upload-time = "2025-12-10T22:55:16.175Z" },
+ { url = "https://files.pythonhosted.org/packages/fd/14/baad3222f424b19ce6ad243c71de1ad9ec6b2e4eb1e458a48fdc6d120401/matplotlib-3.10.8-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a2b336e2d91a3d7006864e0990c83b216fcdca64b5a6484912902cef87313d78", size = 8139625, upload-time = "2025-12-10T22:55:17.712Z" },
+ { url = "https://files.pythonhosted.org/packages/8f/a0/7024215e95d456de5883e6732e708d8187d9753a21d32f8ddb3befc0c445/matplotlib-3.10.8-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:efb30e3baaea72ce5928e32bab719ab4770099079d66726a62b11b1ef7273be4", size = 8712614, upload-time = "2025-12-10T22:55:20.8Z" },
+ { url = "https://files.pythonhosted.org/packages/5a/f4/b8347351da9a5b3f41e26cf547252d861f685c6867d179a7c9d60ad50189/matplotlib-3.10.8-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d56a1efd5bfd61486c8bc968fa18734464556f0fb8e51690f4ac25d85cbbbbc2", size = 9540997, upload-time = "2025-12-10T22:55:23.258Z" },
+ { url = "https://files.pythonhosted.org/packages/9e/c0/c7b914e297efe0bc36917bf216b2acb91044b91e930e878ae12981e461e5/matplotlib-3.10.8-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:238b7ce5717600615c895050239ec955d91f321c209dd110db988500558e70d6", size = 9596825, upload-time = "2025-12-10T22:55:25.217Z" },
+ { url = "https://files.pythonhosted.org/packages/6f/d3/a4bbc01c237ab710a1f22b4da72f4ff6d77eb4c7735ea9811a94ae239067/matplotlib-3.10.8-cp311-cp311-win_amd64.whl", hash = "sha256:18821ace09c763ec93aef5eeff087ee493a24051936d7b9ebcad9662f66501f9", size = 8135090, upload-time = "2025-12-10T22:55:27.162Z" },
+ { url = "https://files.pythonhosted.org/packages/89/dd/a0b6588f102beab33ca6f5218b31725216577b2a24172f327eaf6417d5c9/matplotlib-3.10.8-cp311-cp311-win_arm64.whl", hash = "sha256:bab485bcf8b1c7d2060b4fcb6fc368a9e6f4cd754c9c2fea281f4be21df394a2", size = 8012377, upload-time = "2025-12-10T22:55:29.185Z" },
+ { url = "https://files.pythonhosted.org/packages/9e/67/f997cdcbb514012eb0d10cd2b4b332667997fb5ebe26b8d41d04962fa0e6/matplotlib-3.10.8-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:64fcc24778ca0404ce0cb7b6b77ae1f4c7231cdd60e6778f999ee05cbd581b9a", size = 8260453, upload-time = "2025-12-10T22:55:30.709Z" },
+ { url = "https://files.pythonhosted.org/packages/7e/65/07d5f5c7f7c994f12c768708bd2e17a4f01a2b0f44a1c9eccad872433e2e/matplotlib-3.10.8-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b9a5ca4ac220a0cdd1ba6bcba3608547117d30468fefce49bb26f55c1a3d5c58", size = 8148321, upload-time = "2025-12-10T22:55:33.265Z" },
+ { url = "https://files.pythonhosted.org/packages/3e/f3/c5195b1ae57ef85339fd7285dfb603b22c8b4e79114bae5f4f0fcf688677/matplotlib-3.10.8-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3ab4aabc72de4ff77b3ec33a6d78a68227bf1123465887f9905ba79184a1cc04", size = 8716944, upload-time = "2025-12-10T22:55:34.922Z" },
+ { url = "https://files.pythonhosted.org/packages/00/f9/7638f5cc82ec8a7aa005de48622eecc3ed7c9854b96ba15bd76b7fd27574/matplotlib-3.10.8-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:24d50994d8c5816ddc35411e50a86ab05f575e2530c02752e02538122613371f", size = 9550099, upload-time = "2025-12-10T22:55:36.789Z" },
+ { url = "https://files.pythonhosted.org/packages/57/61/78cd5920d35b29fd2a0fe894de8adf672ff52939d2e9b43cb83cd5ce1bc7/matplotlib-3.10.8-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:99eefd13c0dc3b3c1b4d561c1169e65fe47aab7b8158754d7c084088e2329466", size = 9613040, upload-time = "2025-12-10T22:55:38.715Z" },
+ { url = "https://files.pythonhosted.org/packages/30/4e/c10f171b6e2f44d9e3a2b96efa38b1677439d79c99357600a62cc1e9594e/matplotlib-3.10.8-cp312-cp312-win_amd64.whl", hash = "sha256:dd80ecb295460a5d9d260df63c43f4afbdd832d725a531f008dad1664f458adf", size = 8142717, upload-time = "2025-12-10T22:55:41.103Z" },
+ { url = "https://files.pythonhosted.org/packages/f1/76/934db220026b5fef85f45d51a738b91dea7d70207581063cd9bd8fafcf74/matplotlib-3.10.8-cp312-cp312-win_arm64.whl", hash = "sha256:3c624e43ed56313651bc18a47f838b60d7b8032ed348911c54906b130b20071b", size = 8012751, upload-time = "2025-12-10T22:55:42.684Z" },
+ { url = "https://files.pythonhosted.org/packages/3d/b9/15fd5541ef4f5b9a17eefd379356cf12175fe577424e7b1d80676516031a/matplotlib-3.10.8-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:3f2e409836d7f5ac2f1c013110a4d50b9f7edc26328c108915f9075d7d7a91b6", size = 8261076, upload-time = "2025-12-10T22:55:44.648Z" },
+ { url = "https://files.pythonhosted.org/packages/8d/a0/2ba3473c1b66b9c74dc7107c67e9008cb1782edbe896d4c899d39ae9cf78/matplotlib-3.10.8-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:56271f3dac49a88d7fca5060f004d9d22b865f743a12a23b1e937a0be4818ee1", size = 8148794, upload-time = "2025-12-10T22:55:46.252Z" },
+ { url = "https://files.pythonhosted.org/packages/75/97/a471f1c3eb1fd6f6c24a31a5858f443891d5127e63a7788678d14e249aea/matplotlib-3.10.8-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a0a7f52498f72f13d4a25ea70f35f4cb60642b466cbb0a9be951b5bc3f45a486", size = 8718474, upload-time = "2025-12-10T22:55:47.864Z" },
+ { url = "https://files.pythonhosted.org/packages/01/be/cd478f4b66f48256f42927d0acbcd63a26a893136456cd079c0cc24fbabf/matplotlib-3.10.8-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:646d95230efb9ca614a7a594d4fcacde0ac61d25e37dd51710b36477594963ce", size = 9549637, upload-time = "2025-12-10T22:55:50.048Z" },
+ { url = "https://files.pythonhosted.org/packages/5d/7c/8dc289776eae5109e268c4fb92baf870678dc048a25d4ac903683b86d5bf/matplotlib-3.10.8-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f89c151aab2e2e23cb3fe0acad1e8b82841fd265379c4cecd0f3fcb34c15e0f6", size = 9613678, upload-time = "2025-12-10T22:55:52.21Z" },
+ { url = "https://files.pythonhosted.org/packages/64/40/37612487cc8a437d4dd261b32ca21fe2d79510fe74af74e1f42becb1bdb8/matplotlib-3.10.8-cp313-cp313-win_amd64.whl", hash = "sha256:e8ea3e2d4066083e264e75c829078f9e149fa119d27e19acd503de65e0b13149", size = 8142686, upload-time = "2025-12-10T22:55:54.253Z" },
+ { url = "https://files.pythonhosted.org/packages/66/52/8d8a8730e968185514680c2a6625943f70269509c3dcfc0dcf7d75928cb8/matplotlib-3.10.8-cp313-cp313-win_arm64.whl", hash = "sha256:c108a1d6fa78a50646029cb6d49808ff0fc1330fda87fa6f6250c6b5369b6645", size = 8012917, upload-time = "2025-12-10T22:55:56.268Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/27/51fe26e1062f298af5ef66343d8ef460e090a27fea73036c76c35821df04/matplotlib-3.10.8-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:ad3d9833a64cf48cc4300f2b406c3d0f4f4724a91c0bd5640678a6ba7c102077", size = 8305679, upload-time = "2025-12-10T22:55:57.856Z" },
+ { url = "https://files.pythonhosted.org/packages/2c/1e/4de865bc591ac8e3062e835f42dd7fe7a93168d519557837f0e37513f629/matplotlib-3.10.8-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:eb3823f11823deade26ce3b9f40dcb4a213da7a670013929f31d5f5ed1055b22", size = 8198336, upload-time = "2025-12-10T22:55:59.371Z" },
+ { url = "https://files.pythonhosted.org/packages/c6/cb/2f7b6e75fb4dce87ef91f60cac4f6e34f4c145ab036a22318ec837971300/matplotlib-3.10.8-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d9050fee89a89ed57b4fb2c1bfac9a3d0c57a0d55aed95949eedbc42070fea39", size = 8731653, upload-time = "2025-12-10T22:56:01.032Z" },
+ { url = "https://files.pythonhosted.org/packages/46/b3/bd9c57d6ba670a37ab31fb87ec3e8691b947134b201f881665b28cc039ff/matplotlib-3.10.8-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b44d07310e404ba95f8c25aa5536f154c0a8ec473303535949e52eb71d0a1565", size = 9561356, upload-time = "2025-12-10T22:56:02.95Z" },
+ { url = "https://files.pythonhosted.org/packages/c0/3d/8b94a481456dfc9dfe6e39e93b5ab376e50998cddfd23f4ae3b431708f16/matplotlib-3.10.8-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:0a33deb84c15ede243aead39f77e990469fff93ad1521163305095b77b72ce4a", size = 9614000, upload-time = "2025-12-10T22:56:05.411Z" },
+ { url = "https://files.pythonhosted.org/packages/bd/cd/bc06149fe5585ba800b189a6a654a75f1f127e8aab02fd2be10df7fa500c/matplotlib-3.10.8-cp313-cp313t-win_amd64.whl", hash = "sha256:3a48a78d2786784cc2413e57397981fb45c79e968d99656706018d6e62e57958", size = 8220043, upload-time = "2025-12-10T22:56:07.551Z" },
+ { url = "https://files.pythonhosted.org/packages/e3/de/b22cf255abec916562cc04eef457c13e58a1990048de0c0c3604d082355e/matplotlib-3.10.8-cp313-cp313t-win_arm64.whl", hash = "sha256:15d30132718972c2c074cd14638c7f4592bd98719e2308bccea40e0538bc0cb5", size = 8062075, upload-time = "2025-12-10T22:56:09.178Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/43/9c0ff7a2f11615e516c3b058e1e6e8f9614ddeca53faca06da267c48345d/matplotlib-3.10.8-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:b53285e65d4fa4c86399979e956235deb900be5baa7fc1218ea67fbfaeaadd6f", size = 8262481, upload-time = "2025-12-10T22:56:10.885Z" },
+ { url = "https://files.pythonhosted.org/packages/6f/ca/e8ae28649fcdf039fda5ef554b40a95f50592a3c47e6f7270c9561c12b07/matplotlib-3.10.8-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:32f8dce744be5569bebe789e46727946041199030db8aeb2954d26013a0eb26b", size = 8151473, upload-time = "2025-12-10T22:56:12.377Z" },
+ { url = "https://files.pythonhosted.org/packages/f1/6f/009d129ae70b75e88cbe7e503a12a4c0670e08ed748a902c2568909e9eb5/matplotlib-3.10.8-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4cf267add95b1c88300d96ca837833d4112756045364f5c734a2276038dae27d", size = 9553896, upload-time = "2025-12-10T22:56:14.432Z" },
+ { url = "https://files.pythonhosted.org/packages/f5/26/4221a741eb97967bc1fd5e4c52b9aa5a91b2f4ec05b59f6def4d820f9df9/matplotlib-3.10.8-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2cf5bd12cecf46908f286d7838b2abc6c91cda506c0445b8223a7c19a00df008", size = 9824193, upload-time = "2025-12-10T22:56:16.29Z" },
+ { url = "https://files.pythonhosted.org/packages/1f/f3/3abf75f38605772cf48a9daf5821cd4f563472f38b4b828c6fba6fa6d06e/matplotlib-3.10.8-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:41703cc95688f2516b480f7f339d8851a6035f18e100ee6a32bc0b8536a12a9c", size = 9615444, upload-time = "2025-12-10T22:56:18.155Z" },
+ { url = "https://files.pythonhosted.org/packages/93/a5/de89ac80f10b8dc615807ee1133cd99ac74082581196d4d9590bea10690d/matplotlib-3.10.8-cp314-cp314-win_amd64.whl", hash = "sha256:83d282364ea9f3e52363da262ce32a09dfe241e4080dcedda3c0db059d3c1f11", size = 8272719, upload-time = "2025-12-10T22:56:20.366Z" },
+ { url = "https://files.pythonhosted.org/packages/69/ce/b006495c19ccc0a137b48083168a37bd056392dee02f87dba0472f2797fe/matplotlib-3.10.8-cp314-cp314-win_arm64.whl", hash = "sha256:2c1998e92cd5999e295a731bcb2911c75f597d937341f3030cc24ef2733d78a8", size = 8144205, upload-time = "2025-12-10T22:56:22.239Z" },
+ { url = "https://files.pythonhosted.org/packages/68/d9/b31116a3a855bd313c6fcdb7226926d59b041f26061c6c5b1be66a08c826/matplotlib-3.10.8-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:b5a2b97dbdc7d4f353ebf343744f1d1f1cca8aa8bfddb4262fcf4306c3761d50", size = 8305785, upload-time = "2025-12-10T22:56:24.218Z" },
+ { url = "https://files.pythonhosted.org/packages/1e/90/6effe8103f0272685767ba5f094f453784057072f49b393e3ea178fe70a5/matplotlib-3.10.8-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3f5c3e4da343bba819f0234186b9004faba952cc420fbc522dc4e103c1985908", size = 8198361, upload-time = "2025-12-10T22:56:26.787Z" },
+ { url = "https://files.pythonhosted.org/packages/d7/65/a73188711bea603615fc0baecca1061429ac16940e2385433cc778a9d8e7/matplotlib-3.10.8-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f62550b9a30afde8c1c3ae450e5eb547d579dd69b25c2fc7a1c67f934c1717a", size = 9561357, upload-time = "2025-12-10T22:56:28.953Z" },
+ { url = "https://files.pythonhosted.org/packages/f4/3d/b5c5d5d5be8ce63292567f0e2c43dde9953d3ed86ac2de0a72e93c8f07a1/matplotlib-3.10.8-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:495672de149445ec1b772ff2c9ede9b769e3cb4f0d0aa7fa730d7f59e2d4e1c1", size = 9823610, upload-time = "2025-12-10T22:56:31.455Z" },
+ { url = "https://files.pythonhosted.org/packages/4d/4b/e7beb6bbd49f6bae727a12b270a2654d13c397576d25bd6786e47033300f/matplotlib-3.10.8-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:595ba4d8fe983b88f0eec8c26a241e16d6376fe1979086232f481f8f3f67494c", size = 9614011, upload-time = "2025-12-10T22:56:33.85Z" },
+ { url = "https://files.pythonhosted.org/packages/7c/e6/76f2813d31f032e65f6f797e3f2f6e4aab95b65015924b1c51370395c28a/matplotlib-3.10.8-cp314-cp314t-win_amd64.whl", hash = "sha256:25d380fe8b1dc32cf8f0b1b448470a77afb195438bafdf1d858bfb876f3edf7b", size = 8362801, upload-time = "2025-12-10T22:56:36.107Z" },
+ { url = "https://files.pythonhosted.org/packages/5d/49/d651878698a0b67f23aa28e17f45a6d6dd3d3f933fa29087fa4ce5947b5a/matplotlib-3.10.8-cp314-cp314t-win_arm64.whl", hash = "sha256:113bb52413ea508ce954a02c10ffd0d565f9c3bc7f2eddc27dfe1731e71c7b5f", size = 8192560, upload-time = "2025-12-10T22:56:38.008Z" },
+ { url = "https://files.pythonhosted.org/packages/04/30/3afaa31c757f34b7725ab9d2ba8b48b5e89c2019c003e7d0ead143aabc5a/matplotlib-3.10.8-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:6da7c2ce169267d0d066adcf63758f0604aa6c3eebf67458930f9d9b79ad1db1", size = 8249198, upload-time = "2025-12-10T22:56:45.584Z" },
+ { url = "https://files.pythonhosted.org/packages/48/2f/6334aec331f57485a642a7c8be03cb286f29111ae71c46c38b363230063c/matplotlib-3.10.8-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:9153c3292705be9f9c64498a8872118540c3f4123d1a1c840172edf262c8be4a", size = 8136817, upload-time = "2025-12-10T22:56:47.339Z" },
+ { url = "https://files.pythonhosted.org/packages/73/e4/6d6f14b2a759c622f191b2d67e9075a3f56aaccb3be4bb9bb6890030d0a0/matplotlib-3.10.8-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1ae029229a57cd1e8fe542485f27e7ca7b23aa9e8944ddb4985d0bc444f1eca2", size = 8713867, upload-time = "2025-12-10T22:56:48.954Z" },
+]
+
[[package]]
name = "mcp"
version = "1.26.0"
@@ -1589,83 +2066,60 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9e/c9/b2622292ea83fbb4ec318f5b9ab867d0a28ab43c5717bb85b0a5f6b3b0a4/networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762", size = 2068504, upload-time = "2025-12-08T17:02:38.159Z" },
]
+[[package]]
+name = "numba"
+version = "0.65.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llvmlite" },
+ { name = "numpy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/49/61/7299643b9c18d669e04be7c5bcb64d985070d07553274817b45b049e7bfe/numba-0.65.0.tar.gz", hash = "sha256:edad0d9f6682e93624c00125a471ae4df186175d71fd604c983c377cdc03e68b", size = 2764131, upload-time = "2026-04-01T03:52:01.946Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ba/ce/d67c499703eb5479ce02420e8ccd65c5753d87d2e16d563f152d71405346/numba-0.65.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:28e547d0b18024f19cbaf9de02fc5c145790213d9be8a2c95b43f93ec162b9e4", size = 2680228, upload-time = "2026-04-01T03:51:25.401Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/a7/11e2b24251d57cf41fc9ad83f378d890d61a890e3f8eb6338b39833f67a4/numba-0.65.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:032b0b8e879512cd424d79eed6d772a1399c6387ded184c2cf3cc22c08d750a6", size = 3744674, upload-time = "2026-04-01T03:51:27.311Z" },
+ { url = "https://files.pythonhosted.org/packages/fe/0b/7c63eb742859a6243f42288441f65ac9dac96ea59f409e43b713aafbe867/numba-0.65.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:af143d823624033a128b5950c0aaf9ffc2386dfe954eb757119cf0432335534c", size = 3450620, upload-time = "2026-04-01T03:51:29.092Z" },
+ { url = "https://files.pythonhosted.org/packages/53/ff/1371cbbe955be340a46093a10b61462437e0fadc7a63290473a0e584cb03/numba-0.65.0-cp311-cp311-win_amd64.whl", hash = "sha256:15d159578e59a39df246b83480f78d7794b0fca40153b5684d3849a99c48a0fb", size = 2747081, upload-time = "2026-04-01T03:51:30.785Z" },
+ { url = "https://files.pythonhosted.org/packages/6c/2f/8bd31a1ea43c01ac215283d83aa5f8d5acbe7a36c85b82f1757bfe9ccb31/numba-0.65.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:b27ee4847e1bfb17e9604d100417ee7c1d10f15a6711c6213404b3da13a0b2aa", size = 2680705, upload-time = "2026-04-01T03:51:32.597Z" },
+ { url = "https://files.pythonhosted.org/packages/73/36/88406bd58600cc696417b8e5dd6a056478da808f3eaf48d18e2421e0c2d9/numba-0.65.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a52d92ffd297c10364bce60cd1fcb88f99284ab5df085f2c6bcd1cb33b529a6f", size = 3801411, upload-time = "2026-04-01T03:51:34.321Z" },
+ { url = "https://files.pythonhosted.org/packages/0c/61/ce753a1d7646dd477e16d15e89473703faebb8995d2f71d7ad69a540b565/numba-0.65.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:da8e371e328c06d0010c3d8b44b21858652831b85bcfba78cb22c042e22dbd8e", size = 3501622, upload-time = "2026-04-01T03:51:36.348Z" },
+ { url = "https://files.pythonhosted.org/packages/7d/86/db87a5393f1b1fabef53ac3ba4e6b938bb27e40a04ad7cc512098fcae032/numba-0.65.0-cp312-cp312-win_amd64.whl", hash = "sha256:59bb9f2bb9f1238dfd8e927ba50645c18ae769fef4f3d58ea0ea22a2683b91f5", size = 2749979, upload-time = "2026-04-01T03:51:37.88Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/f8/eee0f1ff456218db036bfc9023995ec1f85a9dc8f2422f1594f6a87829e0/numba-0.65.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:c6334094563a456a695c812e6846288376ca02327cf246cdcc83e1bb27862367", size = 2680679, upload-time = "2026-04-01T03:51:39.491Z" },
+ { url = "https://files.pythonhosted.org/packages/1b/8f/3d116e4b8e92f6abace431afa4b2b944f4d65bdee83af886f5c4b263df95/numba-0.65.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b8a9008411615c69d083d1dcf477f75a5aa727b30beb16e139799e2be945cdfd", size = 3809537, upload-time = "2026-04-01T03:51:41.42Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/2c/6a3ca4128e253cb67affe06deb47688f51ce968f5111e2a06d010e6f1fa6/numba-0.65.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:af96c0cba53664efcb361528b8c75e011a6556c859c7e08424c2715201c6cf7a", size = 3508615, upload-time = "2026-04-01T03:51:43.444Z" },
+ { url = "https://files.pythonhosted.org/packages/96/0e/267f9a36fb282c104a971d7eecb685b411c47dce2a740fe69cf5fc2945d9/numba-0.65.0-cp313-cp313-win_amd64.whl", hash = "sha256:6254e73b9c929dc736a1fbd3d6f5680789709a5067cae1fa7198707385129c04", size = 2749938, upload-time = "2026-04-01T03:51:45.218Z" },
+ { url = "https://files.pythonhosted.org/packages/56/a4/90edb01e9176053578e343d7a7276bc28356741ee67059aed8ed2c1a4e59/numba-0.65.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:ee336b398a6fca51b1f626034de99f50cb1bd87d537a166275158a3cee744b82", size = 2680878, upload-time = "2026-04-01T03:51:46.91Z" },
+ { url = "https://files.pythonhosted.org/packages/24/8d/e12d6ff4b9119db3cbf7b2db1ce257576441bd3c76388c786dea74f20b02/numba-0.65.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:05c0a9fdf75d85f57dee47b719e8d6415707b80aae45d75f63f9dc1b935c29f7", size = 3778456, upload-time = "2026-04-01T03:51:48.552Z" },
+ { url = "https://files.pythonhosted.org/packages/17/89/abcd83e76f6a773276fe76244140671bcc5bf820f6e2ae1a15362ae4c8c9/numba-0.65.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:583680e0e8faf124d362df23b4b593f3221a8996341a63d1b664c122401bec2f", size = 3478464, upload-time = "2026-04-01T03:51:50.527Z" },
+ { url = "https://files.pythonhosted.org/packages/73/5b/fbce55ce3d933afbc7ade04df826853e4a846aaa47d58d2fbb669b8f2d08/numba-0.65.0-cp314-cp314-win_amd64.whl", hash = "sha256:add297d3e1c08dd884f44100152612fa41e66a51d15fdf91307f9dde31d06830", size = 2752012, upload-time = "2026-04-01T03:51:52.691Z" },
+ { url = "https://files.pythonhosted.org/packages/1e/ab/af705f4257d9388fb2fd6d7416573e98b6ca9c786e8b58f02720978557bd/numba-0.65.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:194a243ba53a9157c8538cbb3166ec015d785a8c5d584d06cdd88bee902233c7", size = 2683961, upload-time = "2026-04-01T03:51:54.281Z" },
+ { url = "https://files.pythonhosted.org/packages/ff/e5/8267b0adb0c01b52b553df5062fbbb42c30ed5362d08b85cc913a36f838f/numba-0.65.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c7fa502960f7a2f3f5cb025bc7bff888a3551277b92431bfdc5ba2f11a375749", size = 3816373, upload-time = "2026-04-01T03:51:56.18Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/f5/b8397ca360971669a93706b9274592b6864e4367a37d498fbbcb62aa2d48/numba-0.65.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5046c63f783ca3eb6195f826a50797465e7c4ce811daa17c9bea47e310c9b964", size = 3532782, upload-time = "2026-04-01T03:51:58.387Z" },
+ { url = "https://files.pythonhosted.org/packages/f5/21/1e73fa16bf0393ebb74c5bb208d712152ffdfc84600a8e93a3180317856e/numba-0.65.0-cp314-cp314t-win_amd64.whl", hash = "sha256:46fd679ae4f68c7a5d5721efbd29ecee0b0f3013211591891d79b51bfdf73113", size = 2757611, upload-time = "2026-04-01T03:52:00.083Z" },
+]
+
[[package]]
name = "numpy"
-version = "2.4.3"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/10/8b/c265f4823726ab832de836cdd184d0986dcf94480f81e8739692a7ac7af2/numpy-2.4.3.tar.gz", hash = "sha256:483a201202b73495f00dbc83796c6ae63137a9bdade074f7648b3e32613412dd", size = 20727743, upload-time = "2026-03-09T07:58:53.426Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/f9/51/5093a2df15c4dc19da3f79d1021e891f5dcf1d9d1db6ba38891d5590f3fe/numpy-2.4.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:33b3bf58ee84b172c067f56aeadc7ee9ab6de69c5e800ab5b10295d54c581adb", size = 16957183, upload-time = "2026-03-09T07:55:57.774Z" },
- { url = "https://files.pythonhosted.org/packages/b5/7c/c061f3de0630941073d2598dc271ac2f6cbcf5c83c74a5870fea07488333/numpy-2.4.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8ba7b51e71c05aa1f9bc3641463cd82308eab40ce0d5c7e1fd4038cbf9938147", size = 14968734, upload-time = "2026-03-09T07:56:00.494Z" },
- { url = "https://files.pythonhosted.org/packages/ef/27/d26c85cbcd86b26e4f125b0668e7a7c0542d19dd7d23ee12e87b550e95b5/numpy-2.4.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:a1988292870c7cb9d0ebb4cc96b4d447513a9644801de54606dc7aabf2b7d920", size = 5475288, upload-time = "2026-03-09T07:56:02.857Z" },
- { url = "https://files.pythonhosted.org/packages/2b/09/3c4abbc1dcd8010bf1a611d174c7aa689fc505585ec806111b4406f6f1b1/numpy-2.4.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:23b46bb6d8ecb68b58c09944483c135ae5f0e9b8d8858ece5e4ead783771d2a9", size = 6805253, upload-time = "2026-03-09T07:56:04.53Z" },
- { url = "https://files.pythonhosted.org/packages/21/bc/e7aa3f6817e40c3f517d407742337cbb8e6fc4b83ce0b55ab780c829243b/numpy-2.4.3-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a016db5c5dba78fa8fe9f5d80d6708f9c42ab087a739803c0ac83a43d686a470", size = 15969479, upload-time = "2026-03-09T07:56:06.638Z" },
- { url = "https://files.pythonhosted.org/packages/78/51/9f5d7a41f0b51649ddf2f2320595e15e122a40610b233d51928dd6c92353/numpy-2.4.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:715de7f82e192e8cae5a507a347d97ad17598f8e026152ca97233e3666daaa71", size = 16901035, upload-time = "2026-03-09T07:56:09.405Z" },
- { url = "https://files.pythonhosted.org/packages/64/6e/b221dd847d7181bc5ee4857bfb026182ef69499f9305eb1371cbb1aea626/numpy-2.4.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:2ddb7919366ee468342b91dea2352824c25b55814a987847b6c52003a7c97f15", size = 17325657, upload-time = "2026-03-09T07:56:12.067Z" },
- { url = "https://files.pythonhosted.org/packages/eb/b8/8f3fd2da596e1063964b758b5e3c970aed1949a05200d7e3d46a9d46d643/numpy-2.4.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a315e5234d88067f2d97e1f2ef670a7569df445d55400f1e33d117418d008d52", size = 18635512, upload-time = "2026-03-09T07:56:14.629Z" },
- { url = "https://files.pythonhosted.org/packages/5c/24/2993b775c37e39d2f8ab4125b44337ab0b2ba106c100980b7c274a22bee7/numpy-2.4.3-cp311-cp311-win32.whl", hash = "sha256:2b3f8d2c4589b1a2028d2a770b0fc4d1f332fb5e01521f4de3199a896d158ddd", size = 6238100, upload-time = "2026-03-09T07:56:17.243Z" },
- { url = "https://files.pythonhosted.org/packages/76/1d/edccf27adedb754db7c4511d5eac8b83f004ae948fe2d3509e8b78097d4c/numpy-2.4.3-cp311-cp311-win_amd64.whl", hash = "sha256:77e76d932c49a75617c6d13464e41203cd410956614d0a0e999b25e9e8d27eec", size = 12609816, upload-time = "2026-03-09T07:56:19.089Z" },
- { url = "https://files.pythonhosted.org/packages/92/82/190b99153480076c8dce85f4cfe7d53ea84444145ffa54cb58dcd460d66b/numpy-2.4.3-cp311-cp311-win_arm64.whl", hash = "sha256:eb610595dd91560905c132c709412b512135a60f1851ccbd2c959e136431ff67", size = 10485757, upload-time = "2026-03-09T07:56:21.753Z" },
- { url = "https://files.pythonhosted.org/packages/a9/ed/6388632536f9788cea23a3a1b629f25b43eaacd7d7377e5d6bc7b9deb69b/numpy-2.4.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:61b0cbabbb6126c8df63b9a3a0c4b1f44ebca5e12ff6997b80fcf267fb3150ef", size = 16669628, upload-time = "2026-03-09T07:56:24.252Z" },
- { url = "https://files.pythonhosted.org/packages/74/1b/ee2abfc68e1ce728b2958b6ba831d65c62e1b13ce3017c13943f8f9b5b2e/numpy-2.4.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7395e69ff32526710748f92cd8c9849b361830968ea3e24a676f272653e8983e", size = 14696872, upload-time = "2026-03-09T07:56:26.991Z" },
- { url = "https://files.pythonhosted.org/packages/ba/d1/780400e915ff5638166f11ca9dc2c5815189f3d7cf6f8759a1685e586413/numpy-2.4.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:abdce0f71dcb4a00e4e77f3faf05e4616ceccfe72ccaa07f47ee79cda3b7b0f4", size = 5203489, upload-time = "2026-03-09T07:56:29.414Z" },
- { url = "https://files.pythonhosted.org/packages/0b/bb/baffa907e9da4cc34a6e556d6d90e032f6d7a75ea47968ea92b4858826c4/numpy-2.4.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:48da3a4ee1336454b07497ff7ec83903efa5505792c4e6d9bf83d99dc07a1e18", size = 6550814, upload-time = "2026-03-09T07:56:32.225Z" },
- { url = "https://files.pythonhosted.org/packages/7b/12/8c9f0c6c95f76aeb20fc4a699c33e9f827fa0d0f857747c73bb7b17af945/numpy-2.4.3-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:32e3bef222ad6b052280311d1d60db8e259e4947052c3ae7dd6817451fc8a4c5", size = 15666601, upload-time = "2026-03-09T07:56:34.461Z" },
- { url = "https://files.pythonhosted.org/packages/bd/79/cc665495e4d57d0aa6fbcc0aa57aa82671dfc78fbf95fe733ed86d98f52a/numpy-2.4.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e7dd01a46700b1967487141a66ac1a3cf0dd8ebf1f08db37d46389401512ca97", size = 16621358, upload-time = "2026-03-09T07:56:36.852Z" },
- { url = "https://files.pythonhosted.org/packages/a8/40/b4ecb7224af1065c3539f5ecfff879d090de09608ad1008f02c05c770cb3/numpy-2.4.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:76f0f283506c28b12bba319c0fab98217e9f9b54e6160e9c79e9f7348ba32e9c", size = 17016135, upload-time = "2026-03-09T07:56:39.337Z" },
- { url = "https://files.pythonhosted.org/packages/f7/b1/6a88e888052eed951afed7a142dcdf3b149a030ca59b4c71eef085858e43/numpy-2.4.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:737f630a337364665aba3b5a77e56a68cc42d350edd010c345d65a3efa3addcc", size = 18345816, upload-time = "2026-03-09T07:56:42.31Z" },
- { url = "https://files.pythonhosted.org/packages/f3/8f/103a60c5f8c3d7fc678c19cd7b2476110da689ccb80bc18050efbaeae183/numpy-2.4.3-cp312-cp312-win32.whl", hash = "sha256:26952e18d82a1dbbc2f008d402021baa8d6fc8e84347a2072a25e08b46d698b9", size = 5960132, upload-time = "2026-03-09T07:56:44.851Z" },
- { url = "https://files.pythonhosted.org/packages/d7/7c/f5ee1bf6ed888494978046a809df2882aad35d414b622893322df7286879/numpy-2.4.3-cp312-cp312-win_amd64.whl", hash = "sha256:65f3c2455188f09678355f5cae1f959a06b778bc66d535da07bf2ef20cd319d5", size = 12316144, upload-time = "2026-03-09T07:56:47.057Z" },
- { url = "https://files.pythonhosted.org/packages/71/46/8d1cb3f7a00f2fb6394140e7e6623696e54c6318a9d9691bb4904672cf42/numpy-2.4.3-cp312-cp312-win_arm64.whl", hash = "sha256:2abad5c7fef172b3377502bde47892439bae394a71bc329f31df0fd829b41a9e", size = 10220364, upload-time = "2026-03-09T07:56:49.849Z" },
- { url = "https://files.pythonhosted.org/packages/b6/d0/1fe47a98ce0df229238b77611340aff92d52691bcbc10583303181abf7fc/numpy-2.4.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b346845443716c8e542d54112966383b448f4a3ba5c66409771b8c0889485dd3", size = 16665297, upload-time = "2026-03-09T07:56:52.296Z" },
- { url = "https://files.pythonhosted.org/packages/27/d9/4e7c3f0e68dfa91f21c6fb6cf839bc829ec920688b1ce7ec722b1a6202fb/numpy-2.4.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2629289168f4897a3c4e23dc98d6f1731f0fc0fe52fb9db19f974041e4cc12b9", size = 14691853, upload-time = "2026-03-09T07:56:54.992Z" },
- { url = "https://files.pythonhosted.org/packages/3a/66/bd096b13a87549683812b53ab211e6d413497f84e794fb3c39191948da97/numpy-2.4.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:bb2e3cf95854233799013779216c57e153c1ee67a0bf92138acca0e429aefaee", size = 5198435, upload-time = "2026-03-09T07:56:57.184Z" },
- { url = "https://files.pythonhosted.org/packages/a2/2f/687722910b5a5601de2135c891108f51dfc873d8e43c8ed9f4ebb440b4a2/numpy-2.4.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:7f3408ff897f8ab07a07fbe2823d7aee6ff644c097cc1f90382511fe982f647f", size = 6546347, upload-time = "2026-03-09T07:56:59.531Z" },
- { url = "https://files.pythonhosted.org/packages/bf/ec/7971c4e98d86c564750393fab8d7d83d0a9432a9d78bb8a163a6dc59967a/numpy-2.4.3-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:decb0eb8a53c3b009b0962378065589685d66b23467ef5dac16cbe818afde27f", size = 15664626, upload-time = "2026-03-09T07:57:01.385Z" },
- { url = "https://files.pythonhosted.org/packages/7e/eb/7daecbea84ec935b7fc732e18f532073064a3816f0932a40a17f3349185f/numpy-2.4.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d5f51900414fc9204a0e0da158ba2ac52b75656e7dce7e77fb9f84bfa343b4cc", size = 16608916, upload-time = "2026-03-09T07:57:04.008Z" },
- { url = "https://files.pythonhosted.org/packages/df/58/2a2b4a817ffd7472dca4421d9f0776898b364154e30c95f42195041dc03b/numpy-2.4.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:6bd06731541f89cdc01b261ba2c9e037f1543df7472517836b78dfb15bd6e476", size = 17015824, upload-time = "2026-03-09T07:57:06.347Z" },
- { url = "https://files.pythonhosted.org/packages/4a/ca/627a828d44e78a418c55f82dd4caea8ea4a8ef24e5144d9e71016e52fb40/numpy-2.4.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:22654fe6be0e5206f553a9250762c653d3698e46686eee53b399ab90da59bd92", size = 18334581, upload-time = "2026-03-09T07:57:09.114Z" },
- { url = "https://files.pythonhosted.org/packages/cd/c0/76f93962fc79955fcba30a429b62304332345f22d4daec1cb33653425643/numpy-2.4.3-cp313-cp313-win32.whl", hash = "sha256:d71e379452a2f670ccb689ec801b1218cd3983e253105d6e83780967e899d687", size = 5958618, upload-time = "2026-03-09T07:57:11.432Z" },
- { url = "https://files.pythonhosted.org/packages/b1/3c/88af0040119209b9b5cb59485fa48b76f372c73068dbf9254784b975ac53/numpy-2.4.3-cp313-cp313-win_amd64.whl", hash = "sha256:0a60e17a14d640f49146cb38e3f105f571318db7826d9b6fef7e4dce758faecd", size = 12312824, upload-time = "2026-03-09T07:57:13.586Z" },
- { url = "https://files.pythonhosted.org/packages/58/ce/3d07743aced3d173f877c3ef6a454c2174ba42b584ab0b7e6d99374f51ed/numpy-2.4.3-cp313-cp313-win_arm64.whl", hash = "sha256:c9619741e9da2059cd9c3f206110b97583c7152c1dc9f8aafd4beb450ac1c89d", size = 10221218, upload-time = "2026-03-09T07:57:16.183Z" },
- { url = "https://files.pythonhosted.org/packages/62/09/d96b02a91d09e9d97862f4fc8bfebf5400f567d8eb1fe4b0cc4795679c15/numpy-2.4.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:7aa4e54f6469300ebca1d9eb80acd5253cdfa36f2c03d79a35883687da430875", size = 14819570, upload-time = "2026-03-09T07:57:18.564Z" },
- { url = "https://files.pythonhosted.org/packages/b5/ca/0b1aba3905fdfa3373d523b2b15b19029f4f3031c87f4066bd9d20ef6c6b/numpy-2.4.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:d1b90d840b25874cf5cd20c219af10bac3667db3876d9a495609273ebe679070", size = 5326113, upload-time = "2026-03-09T07:57:21.052Z" },
- { url = "https://files.pythonhosted.org/packages/c0/63/406e0fd32fcaeb94180fd6a4c41e55736d676c54346b7efbce548b94a914/numpy-2.4.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:a749547700de0a20a6718293396ec237bb38218049cfce788e08fcb716e8cf73", size = 6646370, upload-time = "2026-03-09T07:57:22.804Z" },
- { url = "https://files.pythonhosted.org/packages/b6/d0/10f7dc157d4b37af92720a196be6f54f889e90dcd30dce9dc657ed92c257/numpy-2.4.3-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:94f3c4a151a2e529adf49c1d54f0f57ff8f9b233ee4d44af623a81553ab86368", size = 15723499, upload-time = "2026-03-09T07:57:24.693Z" },
- { url = "https://files.pythonhosted.org/packages/66/f1/d1c2bf1161396629701bc284d958dc1efa3a5a542aab83cf11ee6eb4cba5/numpy-2.4.3-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22c31dc07025123aedf7f2db9e91783df13f1776dc52c6b22c620870dc0fab22", size = 16657164, upload-time = "2026-03-09T07:57:27.676Z" },
- { url = "https://files.pythonhosted.org/packages/1a/be/cca19230b740af199ac47331a21c71e7a3d0ba59661350483c1600d28c37/numpy-2.4.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:148d59127ac95979d6f07e4d460f934ebdd6eed641db9c0db6c73026f2b2101a", size = 17081544, upload-time = "2026-03-09T07:57:30.664Z" },
- { url = "https://files.pythonhosted.org/packages/b9/c5/9602b0cbb703a0936fb40f8a95407e8171935b15846de2f0776e08af04c7/numpy-2.4.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:a97cbf7e905c435865c2d939af3d93f99d18eaaa3cabe4256f4304fb51604349", size = 18380290, upload-time = "2026-03-09T07:57:33.763Z" },
- { url = "https://files.pythonhosted.org/packages/ed/81/9f24708953cd30be9ee36ec4778f4b112b45165812f2ada4cc5ea1c1f254/numpy-2.4.3-cp313-cp313t-win32.whl", hash = "sha256:be3b8487d725a77acccc9924f65fd8bce9af7fac8c9820df1049424a2115af6c", size = 6082814, upload-time = "2026-03-09T07:57:36.491Z" },
- { url = "https://files.pythonhosted.org/packages/e2/9e/52f6eaa13e1a799f0ab79066c17f7016a4a8ae0c1aefa58c82b4dab690b4/numpy-2.4.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1ec84fd7c8e652b0f4aaaf2e6e9cc8eaa9b1b80a537e06b2e3a2fb176eedcb26", size = 12452673, upload-time = "2026-03-09T07:57:38.281Z" },
- { url = "https://files.pythonhosted.org/packages/c4/04/b8cece6ead0b30c9fbd99bb835ad7ea0112ac5f39f069788c5558e3b1ab2/numpy-2.4.3-cp313-cp313t-win_arm64.whl", hash = "sha256:120df8c0a81ebbf5b9020c91439fccd85f5e018a927a39f624845be194a2be02", size = 10290907, upload-time = "2026-03-09T07:57:40.747Z" },
- { url = "https://files.pythonhosted.org/packages/70/ae/3936f79adebf8caf81bd7a599b90a561334a658be4dcc7b6329ebf4ee8de/numpy-2.4.3-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:5884ce5c7acfae1e4e1b6fde43797d10aa506074d25b531b4f54bde33c0c31d4", size = 16664563, upload-time = "2026-03-09T07:57:43.817Z" },
- { url = "https://files.pythonhosted.org/packages/9b/62/760f2b55866b496bb1fa7da2a6db076bef908110e568b02fcfc1422e2a3a/numpy-2.4.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:297837823f5bc572c5f9379b0c9f3a3365f08492cbdc33bcc3af174372ebb168", size = 14702161, upload-time = "2026-03-09T07:57:46.169Z" },
- { url = "https://files.pythonhosted.org/packages/32/af/a7a39464e2c0a21526fb4fb76e346fb172ebc92f6d1c7a07c2c139cc17b1/numpy-2.4.3-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:a111698b4a3f8dcbe54c64a7708f049355abd603e619013c346553c1fd4ca90b", size = 5208738, upload-time = "2026-03-09T07:57:48.506Z" },
- { url = "https://files.pythonhosted.org/packages/29/8c/2a0cf86a59558fa078d83805589c2de490f29ed4fb336c14313a161d358a/numpy-2.4.3-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:4bd4741a6a676770e0e97fe9ab2e51de01183df3dcbcec591d26d331a40de950", size = 6543618, upload-time = "2026-03-09T07:57:50.591Z" },
- { url = "https://files.pythonhosted.org/packages/aa/b8/612ce010c0728b1c363fa4ea3aa4c22fe1c5da1de008486f8c2f5cb92fae/numpy-2.4.3-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:54f29b877279d51e210e0c80709ee14ccbbad647810e8f3d375561c45ef613dd", size = 15680676, upload-time = "2026-03-09T07:57:52.34Z" },
- { url = "https://files.pythonhosted.org/packages/a9/7e/4f120ecc54ba26ddf3dc348eeb9eb063f421de65c05fc961941798feea18/numpy-2.4.3-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:679f2a834bae9020f81534671c56fd0cc76dd7e5182f57131478e23d0dc59e24", size = 16613492, upload-time = "2026-03-09T07:57:54.91Z" },
- { url = "https://files.pythonhosted.org/packages/2c/86/1b6020db73be330c4b45d5c6ee4295d59cfeef0e3ea323959d053e5a6909/numpy-2.4.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d84f0f881cb2225c2dfd7f78a10a5645d487a496c6668d6cc39f0f114164f3d0", size = 17031789, upload-time = "2026-03-09T07:57:57.641Z" },
- { url = "https://files.pythonhosted.org/packages/07/3a/3b90463bf41ebc21d1b7e06079f03070334374208c0f9a1f05e4ae8455e7/numpy-2.4.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d213c7e6e8d211888cc359bab7199670a00f5b82c0978b9d1c75baf1eddbeac0", size = 18339941, upload-time = "2026-03-09T07:58:00.577Z" },
- { url = "https://files.pythonhosted.org/packages/a8/74/6d736c4cd962259fd8bae9be27363eb4883a2f9069763747347544c2a487/numpy-2.4.3-cp314-cp314-win32.whl", hash = "sha256:52077feedeff7c76ed7c9f1a0428558e50825347b7545bbb8523da2cd55c547a", size = 6007503, upload-time = "2026-03-09T07:58:03.331Z" },
- { url = "https://files.pythonhosted.org/packages/48/39/c56ef87af669364356bb011922ef0734fc49dad51964568634c72a009488/numpy-2.4.3-cp314-cp314-win_amd64.whl", hash = "sha256:0448e7f9caefb34b4b7dd2b77f21e8906e5d6f0365ad525f9f4f530b13df2afc", size = 12444915, upload-time = "2026-03-09T07:58:06.353Z" },
- { url = "https://files.pythonhosted.org/packages/9d/1f/ab8528e38d295fd349310807496fabb7cf9fe2e1f70b97bc20a483ea9d4a/numpy-2.4.3-cp314-cp314-win_arm64.whl", hash = "sha256:b44fd60341c4d9783039598efadd03617fa28d041fc37d22b62d08f2027fa0e7", size = 10494875, upload-time = "2026-03-09T07:58:08.734Z" },
- { url = "https://files.pythonhosted.org/packages/e6/ef/b7c35e4d5ef141b836658ab21a66d1a573e15b335b1d111d31f26c8ef80f/numpy-2.4.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0a195f4216be9305a73c0e91c9b026a35f2161237cf1c6de9b681637772ea657", size = 14822225, upload-time = "2026-03-09T07:58:11.034Z" },
- { url = "https://files.pythonhosted.org/packages/cd/8d/7730fa9278cf6648639946cc816e7cc89f0d891602584697923375f801ed/numpy-2.4.3-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:cd32fbacb9fd1bf041bf8e89e4576b6f00b895f06d00914820ae06a616bdfef7", size = 5328769, upload-time = "2026-03-09T07:58:13.67Z" },
- { url = "https://files.pythonhosted.org/packages/47/01/d2a137317c958b074d338807c1b6a383406cdf8b8e53b075d804cc3d211d/numpy-2.4.3-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:2e03c05abaee1f672e9d67bc858f300b5ccba1c21397211e8d77d98350972093", size = 6649461, upload-time = "2026-03-09T07:58:15.912Z" },
- { url = "https://files.pythonhosted.org/packages/5c/34/812ce12bc0f00272a4b0ec0d713cd237cb390666eb6206323d1cc9cedbb2/numpy-2.4.3-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7d1ce23cce91fcea443320a9d0ece9b9305d4368875bab09538f7a5b4131938a", size = 15725809, upload-time = "2026-03-09T07:58:17.787Z" },
- { url = "https://files.pythonhosted.org/packages/25/c0/2aed473a4823e905e765fee3dc2cbf504bd3e68ccb1150fbdabd5c39f527/numpy-2.4.3-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c59020932feb24ed49ffd03704fbab89f22aa9c0d4b180ff45542fe8918f5611", size = 16655242, upload-time = "2026-03-09T07:58:20.476Z" },
- { url = "https://files.pythonhosted.org/packages/f2/c8/7e052b2fc87aa0e86de23f20e2c42bd261c624748aa8efd2c78f7bb8d8c6/numpy-2.4.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:9684823a78a6cd6ad7511fc5e25b07947d1d5b5e2812c93fe99d7d4195130720", size = 17080660, upload-time = "2026-03-09T07:58:23.067Z" },
- { url = "https://files.pythonhosted.org/packages/f3/3d/0876746044db2adcb11549f214d104f2e1be00f07a67edbb4e2812094847/numpy-2.4.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0200b25c687033316fb39f0ff4e3e690e8957a2c3c8d22499891ec58c37a3eb5", size = 18380384, upload-time = "2026-03-09T07:58:25.839Z" },
- { url = "https://files.pythonhosted.org/packages/07/12/8160bea39da3335737b10308df4f484235fd297f556745f13092aa039d3b/numpy-2.4.3-cp314-cp314t-win32.whl", hash = "sha256:5e10da9e93247e554bb1d22f8edc51847ddd7dde52d85ce31024c1b4312bfba0", size = 6154547, upload-time = "2026-03-09T07:58:28.289Z" },
- { url = "https://files.pythonhosted.org/packages/42/f3/76534f61f80d74cc9cdf2e570d3d4eeb92c2280a27c39b0aaf471eda7b48/numpy-2.4.3-cp314-cp314t-win_amd64.whl", hash = "sha256:45f003dbdffb997a03da2d1d0cb41fbd24a87507fb41605c0420a3db5bd4667b", size = 12633645, upload-time = "2026-03-09T07:58:30.384Z" },
- { url = "https://files.pythonhosted.org/packages/1f/b6/7c0d4334c15983cec7f92a69e8ce9b1e6f31857e5ee3a413ac424e6bd63d/numpy-2.4.3-cp314-cp314t-win_arm64.whl", hash = "sha256:4d382735cecd7bcf090172489a525cd7d4087bc331f7df9f60ddc9a296cf208e", size = 10565454, upload-time = "2026-03-09T07:58:33.031Z" },
- { url = "https://files.pythonhosted.org/packages/64/e4/4dab9fb43c83719c29241c535d9e07be73bea4bc0c6686c5816d8e1b6689/numpy-2.4.3-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:c6b124bfcafb9e8d3ed09130dbee44848c20b3e758b6bbf006e641778927c028", size = 16834892, upload-time = "2026-03-09T07:58:35.334Z" },
- { url = "https://files.pythonhosted.org/packages/c9/29/f8b6d4af90fed3dfda84ebc0df06c9833d38880c79ce954e5b661758aa31/numpy-2.4.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:76dbb9d4e43c16cf9aa711fcd8de1e2eeb27539dcefb60a1d5e9f12fae1d1ed8", size = 14893070, upload-time = "2026-03-09T07:58:37.7Z" },
- { url = "https://files.pythonhosted.org/packages/9a/04/a19b3c91dbec0a49269407f15d5753673a09832daed40c45e8150e6fa558/numpy-2.4.3-pp311-pypy311_pp73-macosx_14_0_arm64.whl", hash = "sha256:29363fbfa6f8ee855d7569c96ce524845e3d726d6c19b29eceec7dd555dab152", size = 5399609, upload-time = "2026-03-09T07:58:39.853Z" },
- { url = "https://files.pythonhosted.org/packages/79/34/4d73603f5420eab89ea8a67097b31364bf7c30f811d4dd84b1659c7476d9/numpy-2.4.3-pp311-pypy311_pp73-macosx_14_0_x86_64.whl", hash = "sha256:bc71942c789ef415a37f0d4eab90341425a00d538cd0642445d30b41023d3395", size = 6714355, upload-time = "2026-03-09T07:58:42.365Z" },
- { url = "https://files.pythonhosted.org/packages/58/ad/1100d7229bb248394939a12a8074d485b655e8ed44207d328fdd7fcebc7b/numpy-2.4.3-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7e58765ad74dcebd3ef0208a5078fba32dc8ec3578fe84a604432950cd043d79", size = 15800434, upload-time = "2026-03-09T07:58:44.837Z" },
- { url = "https://files.pythonhosted.org/packages/0c/fd/16d710c085d28ba4feaf29ac60c936c9d662e390344f94a6beaa2ac9899b/numpy-2.4.3-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e236dbda4e1d319d681afcbb136c0c4a8e0f1a5c58ceec2adebb547357fe857", size = 16729409, upload-time = "2026-03-09T07:58:47.972Z" },
- { url = "https://files.pythonhosted.org/packages/57/a7/b35835e278c18b85206834b3aa3abe68e77a98769c59233d1f6300284781/numpy-2.4.3-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:4b42639cdde6d24e732ff823a3fa5b701d8acad89c4142bc1d0bd6dc85200ba5", size = 12504685, upload-time = "2026-03-09T07:58:50.525Z" },
+version = "1.26.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/65/6e/09db70a523a96d25e115e71cc56a6f9031e7b8cd166c1ac8438307c14058/numpy-1.26.4.tar.gz", hash = "sha256:2a02aba9ed12e4ac4eb3ea9421c420301a0c6460d9830d74a9df87efa4912010", size = 15786129, upload-time = "2024-02-06T00:26:44.495Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/11/57/baae43d14fe163fa0e4c47f307b6b2511ab8d7d30177c491960504252053/numpy-1.26.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4c66707fabe114439db9068ee468c26bbdf909cac0fb58686a42a24de1760c71", size = 20630554, upload-time = "2024-02-05T23:51:50.149Z" },
+ { url = "https://files.pythonhosted.org/packages/1a/2e/151484f49fd03944c4a3ad9c418ed193cfd02724e138ac8a9505d056c582/numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:edd8b5fe47dab091176d21bb6de568acdd906d1887a4584a15a9a96a1dca06ef", size = 13997127, upload-time = "2024-02-05T23:52:15.314Z" },
+ { url = "https://files.pythonhosted.org/packages/79/ae/7e5b85136806f9dadf4878bf73cf223fe5c2636818ba3ab1c585d0403164/numpy-1.26.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7ab55401287bfec946ced39700c053796e7cc0e3acbef09993a9ad2adba6ca6e", size = 14222994, upload-time = "2024-02-05T23:52:47.569Z" },
+ { url = "https://files.pythonhosted.org/packages/3a/d0/edc009c27b406c4f9cbc79274d6e46d634d139075492ad055e3d68445925/numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:666dbfb6ec68962c033a450943ded891bed2d54e6755e35e5835d63f4f6931d5", size = 18252005, upload-time = "2024-02-05T23:53:15.637Z" },
+ { url = "https://files.pythonhosted.org/packages/09/bf/2b1aaf8f525f2923ff6cfcf134ae5e750e279ac65ebf386c75a0cf6da06a/numpy-1.26.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:96ff0b2ad353d8f990b63294c8986f1ec3cb19d749234014f4e7eb0112ceba5a", size = 13885297, upload-time = "2024-02-05T23:53:42.16Z" },
+ { url = "https://files.pythonhosted.org/packages/df/a0/4e0f14d847cfc2a633a1c8621d00724f3206cfeddeb66d35698c4e2cf3d2/numpy-1.26.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:60dedbb91afcbfdc9bc0b1f3f402804070deed7392c23eb7a7f07fa857868e8a", size = 18093567, upload-time = "2024-02-05T23:54:11.696Z" },
+ { url = "https://files.pythonhosted.org/packages/d2/b7/a734c733286e10a7f1a8ad1ae8c90f2d33bf604a96548e0a4a3a6739b468/numpy-1.26.4-cp311-cp311-win32.whl", hash = "sha256:1af303d6b2210eb850fcf03064d364652b7120803a0b872f5211f5234b399f20", size = 5968812, upload-time = "2024-02-05T23:54:26.453Z" },
+ { url = "https://files.pythonhosted.org/packages/3f/6b/5610004206cf7f8e7ad91c5a85a8c71b2f2f8051a0c0c4d5916b76d6cbb2/numpy-1.26.4-cp311-cp311-win_amd64.whl", hash = "sha256:cd25bcecc4974d09257ffcd1f098ee778f7834c3ad767fe5db785be9a4aa9cb2", size = 15811913, upload-time = "2024-02-05T23:54:53.933Z" },
+ { url = "https://files.pythonhosted.org/packages/95/12/8f2020a8e8b8383ac0177dc9570aad031a3beb12e38847f7129bacd96228/numpy-1.26.4-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:b3ce300f3644fb06443ee2222c2201dd3a89ea6040541412b8fa189341847218", size = 20335901, upload-time = "2024-02-05T23:55:32.801Z" },
+ { url = "https://files.pythonhosted.org/packages/75/5b/ca6c8bd14007e5ca171c7c03102d17b4f4e0ceb53957e8c44343a9546dcc/numpy-1.26.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:03a8c78d01d9781b28a6989f6fa1bb2c4f2d51201cf99d3dd875df6fbd96b23b", size = 13685868, upload-time = "2024-02-05T23:55:56.28Z" },
+ { url = "https://files.pythonhosted.org/packages/79/f8/97f10e6755e2a7d027ca783f63044d5b1bc1ae7acb12afe6a9b4286eac17/numpy-1.26.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9fad7dcb1aac3c7f0584a5a8133e3a43eeb2fe127f47e3632d43d677c66c102b", size = 13925109, upload-time = "2024-02-05T23:56:20.368Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/50/de23fde84e45f5c4fda2488c759b69990fd4512387a8632860f3ac9cd225/numpy-1.26.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:675d61ffbfa78604709862923189bad94014bef562cc35cf61d3a07bba02a7ed", size = 17950613, upload-time = "2024-02-05T23:56:56.054Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/0c/9c603826b6465e82591e05ca230dfc13376da512b25ccd0894709b054ed0/numpy-1.26.4-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:ab47dbe5cc8210f55aa58e4805fe224dac469cde56b9f731a4c098b91917159a", size = 13572172, upload-time = "2024-02-05T23:57:21.56Z" },
+ { url = "https://files.pythonhosted.org/packages/76/8c/2ba3902e1a0fc1c74962ea9bb33a534bb05984ad7ff9515bf8d07527cadd/numpy-1.26.4-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:1dda2e7b4ec9dd512f84935c5f126c8bd8b9f2fc001e9f54af255e8c5f16b0e0", size = 17786643, upload-time = "2024-02-05T23:57:56.585Z" },
+ { url = "https://files.pythonhosted.org/packages/28/4a/46d9e65106879492374999e76eb85f87b15328e06bd1550668f79f7b18c6/numpy-1.26.4-cp312-cp312-win32.whl", hash = "sha256:50193e430acfc1346175fcbdaa28ffec49947a06918b7b92130744e81e640110", size = 5677803, upload-time = "2024-02-05T23:58:08.963Z" },
+ { url = "https://files.pythonhosted.org/packages/16/2e/86f24451c2d530c88daf997cb8d6ac622c1d40d19f5a031ed68a4b73a374/numpy-1.26.4-cp312-cp312-win_amd64.whl", hash = "sha256:08beddf13648eb95f8d867350f6a018a4be2e5ad54c8d8caed89ebca558b2818", size = 15517754, upload-time = "2024-02-05T23:58:36.364Z" },
]
[[package]]
@@ -1705,6 +2159,60 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b7/b9/c538f279a4e237a006a2c98387d081e9eb060d203d8ed34467cc0f0b9b53/packaging-26.0-py3-none-any.whl", hash = "sha256:b36f1fef9334a5588b4166f8bcd26a14e521f2b55e6b9de3aaa80d3ff7a37529", size = 74366, upload-time = "2026-01-21T20:50:37.788Z" },
]
+[[package]]
+name = "pandas"
+version = "2.3.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+ { name = "python-dateutil" },
+ { name = "pytz" },
+ { name = "tzdata" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c1/fa/7ac648108144a095b4fb6aa3de1954689f7af60a14cf25583f4960ecb878/pandas-2.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:602b8615ebcc4a0c1751e71840428ddebeb142ec02c786e8ad6b1ce3c8dec523", size = 11578790, upload-time = "2025-09-29T23:18:30.065Z" },
+ { url = "https://files.pythonhosted.org/packages/9b/35/74442388c6cf008882d4d4bdfc4109be87e9b8b7ccd097ad1e7f006e2e95/pandas-2.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8fe25fc7b623b0ef6b5009149627e34d2a4657e880948ec3c840e9402e5c1b45", size = 10833831, upload-time = "2025-09-29T23:38:56.071Z" },
+ { url = "https://files.pythonhosted.org/packages/fe/e4/de154cbfeee13383ad58d23017da99390b91d73f8c11856f2095e813201b/pandas-2.3.3-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b468d3dad6ff947df92dcb32ede5b7bd41a9b3cceef0a30ed925f6d01fb8fa66", size = 12199267, upload-time = "2025-09-29T23:18:41.627Z" },
+ { url = "https://files.pythonhosted.org/packages/bf/c9/63f8d545568d9ab91476b1818b4741f521646cbdd151c6efebf40d6de6f7/pandas-2.3.3-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b98560e98cb334799c0b07ca7967ac361a47326e9b4e5a7dfb5ab2b1c9d35a1b", size = 12789281, upload-time = "2025-09-29T23:18:56.834Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/00/a5ac8c7a0e67fd1a6059e40aa08fa1c52cc00709077d2300e210c3ce0322/pandas-2.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37b5848ba49824e5c30bedb9c830ab9b7751fd049bc7914533e01c65f79791", size = 13240453, upload-time = "2025-09-29T23:19:09.247Z" },
+ { url = "https://files.pythonhosted.org/packages/27/4d/5c23a5bc7bd209231618dd9e606ce076272c9bc4f12023a70e03a86b4067/pandas-2.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:db4301b2d1f926ae677a751eb2bd0e8c5f5319c9cb3f88b0becbbb0b07b34151", size = 13890361, upload-time = "2025-09-29T23:19:25.342Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/59/712db1d7040520de7a4965df15b774348980e6df45c129b8c64d0dbe74ef/pandas-2.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:f086f6fe114e19d92014a1966f43a3e62285109afe874f067f5abbdcbb10e59c", size = 11348702, upload-time = "2025-09-29T23:19:38.296Z" },
+ { url = "https://files.pythonhosted.org/packages/9c/fb/231d89e8637c808b997d172b18e9d4a4bc7bf31296196c260526055d1ea0/pandas-2.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d21f6d74eb1725c2efaa71a2bfc661a0689579b58e9c0ca58a739ff0b002b53", size = 11597846, upload-time = "2025-09-29T23:19:48.856Z" },
+ { url = "https://files.pythonhosted.org/packages/5c/bd/bf8064d9cfa214294356c2d6702b716d3cf3bb24be59287a6a21e24cae6b/pandas-2.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3fd2f887589c7aa868e02632612ba39acb0b8948faf5cc58f0850e165bd46f35", size = 10729618, upload-time = "2025-09-29T23:39:08.659Z" },
+ { url = "https://files.pythonhosted.org/packages/57/56/cf2dbe1a3f5271370669475ead12ce77c61726ffd19a35546e31aa8edf4e/pandas-2.3.3-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecaf1e12bdc03c86ad4a7ea848d66c685cb6851d807a26aa245ca3d2017a1908", size = 11737212, upload-time = "2025-09-29T23:19:59.765Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/63/cd7d615331b328e287d8233ba9fdf191a9c2d11b6af0c7a59cfcec23de68/pandas-2.3.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b3d11d2fda7eb164ef27ffc14b4fcab16a80e1ce67e9f57e19ec0afaf715ba89", size = 12362693, upload-time = "2025-09-29T23:20:14.098Z" },
+ { url = "https://files.pythonhosted.org/packages/a6/de/8b1895b107277d52f2b42d3a6806e69cfef0d5cf1d0ba343470b9d8e0a04/pandas-2.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a68e15f780eddf2b07d242e17a04aa187a7ee12b40b930bfdd78070556550e98", size = 12771002, upload-time = "2025-09-29T23:20:26.76Z" },
+ { url = "https://files.pythonhosted.org/packages/87/21/84072af3187a677c5893b170ba2c8fbe450a6ff911234916da889b698220/pandas-2.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:371a4ab48e950033bcf52b6527eccb564f52dc826c02afd9a1bc0ab731bba084", size = 13450971, upload-time = "2025-09-29T23:20:41.344Z" },
+ { url = "https://files.pythonhosted.org/packages/86/41/585a168330ff063014880a80d744219dbf1dd7a1c706e75ab3425a987384/pandas-2.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:a16dcec078a01eeef8ee61bf64074b4e524a2a3f4b3be9326420cabe59c4778b", size = 10992722, upload-time = "2025-09-29T23:20:54.139Z" },
+ { url = "https://files.pythonhosted.org/packages/cd/4b/18b035ee18f97c1040d94debd8f2e737000ad70ccc8f5513f4eefad75f4b/pandas-2.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:56851a737e3470de7fa88e6131f41281ed440d29a9268dcbf0002da5ac366713", size = 11544671, upload-time = "2025-09-29T23:21:05.024Z" },
+ { url = "https://files.pythonhosted.org/packages/31/94/72fac03573102779920099bcac1c3b05975c2cb5f01eac609faf34bed1ca/pandas-2.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bdcd9d1167f4885211e401b3036c0c8d9e274eee67ea8d0758a256d60704cfe8", size = 10680807, upload-time = "2025-09-29T23:21:15.979Z" },
+ { url = "https://files.pythonhosted.org/packages/16/87/9472cf4a487d848476865321de18cc8c920b8cab98453ab79dbbc98db63a/pandas-2.3.3-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e32e7cc9af0f1cc15548288a51a3b681cc2a219faa838e995f7dc53dbab1062d", size = 11709872, upload-time = "2025-09-29T23:21:27.165Z" },
+ { url = "https://files.pythonhosted.org/packages/15/07/284f757f63f8a8d69ed4472bfd85122bd086e637bf4ed09de572d575a693/pandas-2.3.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:318d77e0e42a628c04dc56bcef4b40de67918f7041c2b061af1da41dcff670ac", size = 12306371, upload-time = "2025-09-29T23:21:40.532Z" },
+ { url = "https://files.pythonhosted.org/packages/33/81/a3afc88fca4aa925804a27d2676d22dcd2031c2ebe08aabd0ae55b9ff282/pandas-2.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4e0a175408804d566144e170d0476b15d78458795bb18f1304fb94160cabf40c", size = 12765333, upload-time = "2025-09-29T23:21:55.77Z" },
+ { url = "https://files.pythonhosted.org/packages/8d/0f/b4d4ae743a83742f1153464cf1a8ecfafc3ac59722a0b5c8602310cb7158/pandas-2.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:93c2d9ab0fc11822b5eece72ec9587e172f63cff87c00b062f6e37448ced4493", size = 13418120, upload-time = "2025-09-29T23:22:10.109Z" },
+ { url = "https://files.pythonhosted.org/packages/4f/c7/e54682c96a895d0c808453269e0b5928a07a127a15704fedb643e9b0a4c8/pandas-2.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:f8bfc0e12dc78f777f323f55c58649591b2cd0c43534e8355c51d3fede5f4dee", size = 10993991, upload-time = "2025-09-29T23:25:04.889Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/ca/3f8d4f49740799189e1395812f3bf23b5e8fc7c190827d55a610da72ce55/pandas-2.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:75ea25f9529fdec2d2e93a42c523962261e567d250b0013b16210e1d40d7c2e5", size = 12048227, upload-time = "2025-09-29T23:22:24.343Z" },
+ { url = "https://files.pythonhosted.org/packages/0e/5a/f43efec3e8c0cc92c4663ccad372dbdff72b60bdb56b2749f04aa1d07d7e/pandas-2.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:74ecdf1d301e812db96a465a525952f4dde225fdb6d8e5a521d47e1f42041e21", size = 11411056, upload-time = "2025-09-29T23:22:37.762Z" },
+ { url = "https://files.pythonhosted.org/packages/46/b1/85331edfc591208c9d1a63a06baa67b21d332e63b7a591a5ba42a10bb507/pandas-2.3.3-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6435cb949cb34ec11cc9860246ccb2fdc9ecd742c12d3304989017d53f039a78", size = 11645189, upload-time = "2025-09-29T23:22:51.688Z" },
+ { url = "https://files.pythonhosted.org/packages/44/23/78d645adc35d94d1ac4f2a3c4112ab6f5b8999f4898b8cdf01252f8df4a9/pandas-2.3.3-cp313-cp313t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:900f47d8f20860de523a1ac881c4c36d65efcb2eb850e6948140fa781736e110", size = 12121912, upload-time = "2025-09-29T23:23:05.042Z" },
+ { url = "https://files.pythonhosted.org/packages/53/da/d10013df5e6aaef6b425aa0c32e1fc1f3e431e4bcabd420517dceadce354/pandas-2.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:a45c765238e2ed7d7c608fc5bc4a6f88b642f2f01e70c0c23d2224dd21829d86", size = 12712160, upload-time = "2025-09-29T23:23:28.57Z" },
+ { url = "https://files.pythonhosted.org/packages/bd/17/e756653095a083d8a37cbd816cb87148debcfcd920129b25f99dd8d04271/pandas-2.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c4fc4c21971a1a9f4bdb4c73978c7f7256caa3e62b323f70d6cb80db583350bc", size = 13199233, upload-time = "2025-09-29T23:24:24.876Z" },
+ { url = "https://files.pythonhosted.org/packages/04/fd/74903979833db8390b73b3a8a7d30d146d710bd32703724dd9083950386f/pandas-2.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:ee15f284898e7b246df8087fc82b87b01686f98ee67d85a17b7ab44143a3a9a0", size = 11540635, upload-time = "2025-09-29T23:25:52.486Z" },
+ { url = "https://files.pythonhosted.org/packages/21/00/266d6b357ad5e6d3ad55093a7e8efc7dd245f5a842b584db9f30b0f0a287/pandas-2.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1611aedd912e1ff81ff41c745822980c49ce4a7907537be8692c8dbc31924593", size = 10759079, upload-time = "2025-09-29T23:26:33.204Z" },
+ { url = "https://files.pythonhosted.org/packages/ca/05/d01ef80a7a3a12b2f8bbf16daba1e17c98a2f039cbc8e2f77a2c5a63d382/pandas-2.3.3-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d2cefc361461662ac48810cb14365a365ce864afe85ef1f447ff5a1e99ea81c", size = 11814049, upload-time = "2025-09-29T23:27:15.384Z" },
+ { url = "https://files.pythonhosted.org/packages/15/b2/0e62f78c0c5ba7e3d2c5945a82456f4fac76c480940f805e0b97fcbc2f65/pandas-2.3.3-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ee67acbbf05014ea6c763beb097e03cd629961c8a632075eeb34247120abcb4b", size = 12332638, upload-time = "2025-09-29T23:27:51.625Z" },
+ { url = "https://files.pythonhosted.org/packages/c5/33/dd70400631b62b9b29c3c93d2feee1d0964dc2bae2e5ad7a6c73a7f25325/pandas-2.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c46467899aaa4da076d5abc11084634e2d197e9460643dd455ac3db5856b24d6", size = 12886834, upload-time = "2025-09-29T23:28:21.289Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/18/b5d48f55821228d0d2692b34fd5034bb185e854bdb592e9c640f6290e012/pandas-2.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6253c72c6a1d990a410bc7de641d34053364ef8bcd3126f7e7450125887dffe3", size = 13409925, upload-time = "2025-09-29T23:28:58.261Z" },
+ { url = "https://files.pythonhosted.org/packages/a6/3d/124ac75fcd0ecc09b8fdccb0246ef65e35b012030defb0e0eba2cbbbe948/pandas-2.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:1b07204a219b3b7350abaae088f451860223a52cfb8a6c53358e7948735158e5", size = 11109071, upload-time = "2025-09-29T23:32:27.484Z" },
+ { url = "https://files.pythonhosted.org/packages/89/9c/0e21c895c38a157e0faa1fb64587a9226d6dd46452cac4532d80c3c4a244/pandas-2.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:2462b1a365b6109d275250baaae7b760fd25c726aaca0054649286bcfbb3e8ec", size = 12048504, upload-time = "2025-09-29T23:29:31.47Z" },
+ { url = "https://files.pythonhosted.org/packages/d7/82/b69a1c95df796858777b68fbe6a81d37443a33319761d7c652ce77797475/pandas-2.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0242fe9a49aa8b4d78a4fa03acb397a58833ef6199e9aa40a95f027bb3a1b6e7", size = 11410702, upload-time = "2025-09-29T23:29:54.591Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/88/702bde3ba0a94b8c73a0181e05144b10f13f29ebfc2150c3a79062a8195d/pandas-2.3.3-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a21d830e78df0a515db2b3d2f5570610f5e6bd2e27749770e8bb7b524b89b450", size = 11634535, upload-time = "2025-09-29T23:30:21.003Z" },
+ { url = "https://files.pythonhosted.org/packages/a4/1e/1bac1a839d12e6a82ec6cb40cda2edde64a2013a66963293696bbf31fbbb/pandas-2.3.3-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e3ebdb170b5ef78f19bfb71b0dc5dc58775032361fa188e814959b74d726dd5", size = 12121582, upload-time = "2025-09-29T23:30:43.391Z" },
+ { url = "https://files.pythonhosted.org/packages/44/91/483de934193e12a3b1d6ae7c8645d083ff88dec75f46e827562f1e4b4da6/pandas-2.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d051c0e065b94b7a3cea50eb1ec32e912cd96dba41647eb24104b6c6c14c5788", size = 12699963, upload-time = "2025-09-29T23:31:10.009Z" },
+ { url = "https://files.pythonhosted.org/packages/70/44/5191d2e4026f86a2a109053e194d3ba7a31a2d10a9c2348368c63ed4e85a/pandas-2.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3869faf4bd07b3b66a9f462417d0ca3a9df29a9f6abd5d0d0dbab15dac7abe87", size = 13202175, upload-time = "2025-09-29T23:31:59.173Z" },
+]
+
[[package]]
name = "pathspec"
version = "0.12.1"
@@ -1714,6 +2222,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cc/20/ff623b09d963f88bfde16306a54e12ee5ea43e9b597108672ff3a408aad6/pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08", size = 31191, upload-time = "2023-12-10T22:30:43.14Z" },
]
+[[package]]
+name = "patsy"
+version = "1.0.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/be/44/ed13eccdd0519eff265f44b670d46fbb0ec813e2274932dc1c0e48520f7d/patsy-1.0.2.tar.gz", hash = "sha256:cdc995455f6233e90e22de72c37fcadb344e7586fb83f06696f54d92f8ce74c0", size = 399942, upload-time = "2025-10-20T16:17:37.535Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f1/70/ba4b949bdc0490ab78d545459acd7702b211dfccf7eb89bbc1060f52818d/patsy-1.0.2-py2.py3-none-any.whl", hash = "sha256:37bfddbc58fcf0362febb5f54f10743f8b21dd2aa73dec7e7ef59d1b02ae668a", size = 233301, upload-time = "2025-10-20T16:17:36.563Z" },
+]
+
[[package]]
name = "pgvector"
version = "0.4.2"
@@ -1726,6 +2246,93 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/5a/26/6cee8a1ce8c43625ec561aff19df07f9776b7525d9002c86bceb3e0ac970/pgvector-0.4.2-py3-none-any.whl", hash = "sha256:549d45f7a18593783d5eec609ea1684a724ba8405c4cb182a0b2b08aeff04e08", size = 27441, upload-time = "2025-12-05T01:07:16.536Z" },
]
+[[package]]
+name = "pillow"
+version = "12.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/8c/21/c2bcdd5906101a30244eaffc1b6e6ce71a31bd0742a01eb89e660ebfac2d/pillow-12.2.0.tar.gz", hash = "sha256:a830b1a40919539d07806aa58e1b114df53ddd43213d9c8b75847eee6c0182b5", size = 46987819, upload-time = "2026-04-01T14:46:17.687Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/68/e1/748f5663efe6edcfc4e74b2b93edfb9b8b99b67f21a854c3ae416500a2d9/pillow-12.2.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:8be29e59487a79f173507c30ddf57e733a357f67881430449bb32614075a40ab", size = 5354347, upload-time = "2026-04-01T14:42:44.255Z" },
+ { url = "https://files.pythonhosted.org/packages/47/a1/d5ff69e747374c33a3b53b9f98cca7889fce1fd03d79cdc4e1bccc6c5a87/pillow-12.2.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:71cde9a1e1551df7d34a25462fc60325e8a11a82cc2e2f54578e5e9a1e153d65", size = 4695873, upload-time = "2026-04-01T14:42:46.452Z" },
+ { url = "https://files.pythonhosted.org/packages/df/21/e3fbdf54408a973c7f7f89a23b2cb97a7ef30c61ab4142af31eee6aebc88/pillow-12.2.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f490f9368b6fc026f021db16d7ec2fbf7d89e2edb42e8ec09d2c60505f5729c7", size = 6280168, upload-time = "2026-04-01T14:42:49.228Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/f1/00b7278c7dd52b17ad4329153748f87b6756ec195ff786c2bdf12518337d/pillow-12.2.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8bd7903a5f2a4545f6fd5935c90058b89d30045568985a71c79f5fd6edf9b91e", size = 8088188, upload-time = "2026-04-01T14:42:51.735Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/cf/220a5994ef1b10e70e85748b75649d77d506499352be135a4989c957b701/pillow-12.2.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3997232e10d2920a68d25191392e3a4487d8183039e1c74c2297f00ed1c50705", size = 6394401, upload-time = "2026-04-01T14:42:54.343Z" },
+ { url = "https://files.pythonhosted.org/packages/e9/bd/e51a61b1054f09437acfbc2ff9106c30d1eb76bc1453d428399946781253/pillow-12.2.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e74473c875d78b8e9d5da2a70f7099549f9eb37ded4e2f6a463e60125bccd176", size = 7079655, upload-time = "2026-04-01T14:42:56.954Z" },
+ { url = "https://files.pythonhosted.org/packages/6b/3d/45132c57d5fb4b5744567c3817026480ac7fc3ce5d4c47902bc0e7f6f853/pillow-12.2.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:56a3f9c60a13133a98ecff6197af34d7824de9b7b38c3654861a725c970c197b", size = 6503105, upload-time = "2026-04-01T14:42:59.847Z" },
+ { url = "https://files.pythonhosted.org/packages/7d/2e/9df2fc1e82097b1df3dce58dc43286aa01068e918c07574711fcc53e6fb4/pillow-12.2.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:90e6f81de50ad6b534cab6e5aef77ff6e37722b2f5d908686f4a5c9eba17a909", size = 7203402, upload-time = "2026-04-01T14:43:02.664Z" },
+ { url = "https://files.pythonhosted.org/packages/bd/2e/2941e42858ebb67e50ae741473de81c2984e6eff7b397017623c676e2e8d/pillow-12.2.0-cp311-cp311-win32.whl", hash = "sha256:8c984051042858021a54926eb597d6ee3012393ce9c181814115df4c60b9a808", size = 6378149, upload-time = "2026-04-01T14:43:05.274Z" },
+ { url = "https://files.pythonhosted.org/packages/69/42/836b6f3cd7f3e5fa10a1f1a5420447c17966044c8fbf589cc0452d5502db/pillow-12.2.0-cp311-cp311-win_amd64.whl", hash = "sha256:6e6b2a0c538fc200b38ff9eb6628228b77908c319a005815f2dde585a0664b60", size = 7082626, upload-time = "2026-04-01T14:43:08.557Z" },
+ { url = "https://files.pythonhosted.org/packages/c2/88/549194b5d6f1f494b485e493edc6693c0a16f4ada488e5bd974ed1f42fad/pillow-12.2.0-cp311-cp311-win_arm64.whl", hash = "sha256:9a8a34cc89c67a65ea7437ce257cea81a9dad65b29805f3ecee8c8fe8ff25ffe", size = 2463531, upload-time = "2026-04-01T14:43:10.743Z" },
+ { url = "https://files.pythonhosted.org/packages/58/be/7482c8a5ebebbc6470b3eb791812fff7d5e0216c2be3827b30b8bb6603ed/pillow-12.2.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2d192a155bbcec180f8564f693e6fd9bccff5a7af9b32e2e4bf8c9c69dbad6b5", size = 5308279, upload-time = "2026-04-01T14:43:13.246Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/95/0a351b9289c2b5cbde0bacd4a83ebc44023e835490a727b2a3bd60ddc0f4/pillow-12.2.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f3f40b3c5a968281fd507d519e444c35f0ff171237f4fdde090dd60699458421", size = 4695490, upload-time = "2026-04-01T14:43:15.584Z" },
+ { url = "https://files.pythonhosted.org/packages/de/af/4e8e6869cbed569d43c416fad3dc4ecb944cb5d9492defaed89ddd6fe871/pillow-12.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:03e7e372d5240cc23e9f07deca4d775c0817bffc641b01e9c3af208dbd300987", size = 6284462, upload-time = "2026-04-01T14:43:18.268Z" },
+ { url = "https://files.pythonhosted.org/packages/e9/9e/c05e19657fd57841e476be1ab46c4d501bffbadbafdc31a6d665f8b737b6/pillow-12.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b86024e52a1b269467a802258c25521e6d742349d760728092e1bc2d135b4d76", size = 8094744, upload-time = "2026-04-01T14:43:20.716Z" },
+ { url = "https://files.pythonhosted.org/packages/2b/54/1789c455ed10176066b6e7e6da1b01e50e36f94ba584dc68d9eebfe9156d/pillow-12.2.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7371b48c4fa448d20d2714c9a1f775a81155050d383333e0a6c15b1123dda005", size = 6398371, upload-time = "2026-04-01T14:43:23.443Z" },
+ { url = "https://files.pythonhosted.org/packages/43/e3/fdc657359e919462369869f1c9f0e973f353f9a9ee295a39b1fea8ee1a77/pillow-12.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:62f5409336adb0663b7caa0da5c7d9e7bdbaae9ce761d34669420c2a801b2780", size = 7087215, upload-time = "2026-04-01T14:43:26.758Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/f8/2f6825e441d5b1959d2ca5adec984210f1ec086435b0ed5f52c19b3b8a6e/pillow-12.2.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:01afa7cf67f74f09523699b4e88c73fb55c13346d212a59a2db1f86b0a63e8c5", size = 6509783, upload-time = "2026-04-01T14:43:29.56Z" },
+ { url = "https://files.pythonhosted.org/packages/67/f9/029a27095ad20f854f9dba026b3ea6428548316e057e6fc3545409e86651/pillow-12.2.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc3d34d4a8fbec3e88a79b92e5465e0f9b842b628675850d860b8bd300b159f5", size = 7212112, upload-time = "2026-04-01T14:43:32.091Z" },
+ { url = "https://files.pythonhosted.org/packages/be/42/025cfe05d1be22dbfdb4f264fe9de1ccda83f66e4fc3aac94748e784af04/pillow-12.2.0-cp312-cp312-win32.whl", hash = "sha256:58f62cc0f00fd29e64b29f4fd923ffdb3859c9f9e6105bfc37ba1d08994e8940", size = 6378489, upload-time = "2026-04-01T14:43:34.601Z" },
+ { url = "https://files.pythonhosted.org/packages/5d/7b/25a221d2c761c6a8ae21bfa3874988ff2583e19cf8a27bf2fee358df7942/pillow-12.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:7f84204dee22a783350679a0333981df803dac21a0190d706a50475e361c93f5", size = 7084129, upload-time = "2026-04-01T14:43:37.213Z" },
+ { url = "https://files.pythonhosted.org/packages/10/e1/542a474affab20fd4a0f1836cb234e8493519da6b76899e30bcc5d990b8b/pillow-12.2.0-cp312-cp312-win_arm64.whl", hash = "sha256:af73337013e0b3b46f175e79492d96845b16126ddf79c438d7ea7ff27783a414", size = 2463612, upload-time = "2026-04-01T14:43:39.421Z" },
+ { url = "https://files.pythonhosted.org/packages/4a/01/53d10cf0dbad820a8db274d259a37ba50b88b24768ddccec07355382d5ad/pillow-12.2.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:8297651f5b5679c19968abefd6bb84d95fe30ef712eb1b2d9b2d31ca61267f4c", size = 4100837, upload-time = "2026-04-01T14:43:41.506Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/98/f3a6657ecb698c937f6c76ee564882945f29b79bad496abcba0e84659ec5/pillow-12.2.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:50d8520da2a6ce0af445fa6d648c4273c3eeefbc32d7ce049f22e8b5c3daecc2", size = 4176528, upload-time = "2026-04-01T14:43:43.773Z" },
+ { url = "https://files.pythonhosted.org/packages/69/bc/8986948f05e3ea490b8442ea1c1d4d990b24a7e43d8a51b2c7d8b1dced36/pillow-12.2.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:766cef22385fa1091258ad7e6216792b156dc16d8d3fa607e7545b2b72061f1c", size = 3640401, upload-time = "2026-04-01T14:43:45.87Z" },
+ { url = "https://files.pythonhosted.org/packages/34/46/6c717baadcd62bc8ed51d238d521ab651eaa74838291bda1f86fe1f864c9/pillow-12.2.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5d2fd0fa6b5d9d1de415060363433f28da8b1526c1c129020435e186794b3795", size = 5308094, upload-time = "2026-04-01T14:43:48.438Z" },
+ { url = "https://files.pythonhosted.org/packages/71/43/905a14a8b17fdb1ccb58d282454490662d2cb89a6bfec26af6d3520da5ec/pillow-12.2.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:56b25336f502b6ed02e889f4ece894a72612fe885889a6e8c4c80239ff6e5f5f", size = 4695402, upload-time = "2026-04-01T14:43:51.292Z" },
+ { url = "https://files.pythonhosted.org/packages/73/dd/42107efcb777b16fa0393317eac58f5b5cf30e8392e266e76e51cff28c3d/pillow-12.2.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f1c943e96e85df3d3478f7b691f229887e143f81fedab9b20205349ab04d73ed", size = 6280005, upload-time = "2026-04-01T14:43:54.242Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/68/b93e09e5e8549019e61acf49f65b1a8530765a7f812c77a7461bca7e4494/pillow-12.2.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:03f6fab9219220f041c74aeaa2939ff0062bd5c364ba9ce037197f4c6d498cd9", size = 8090669, upload-time = "2026-04-01T14:43:57.335Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/6e/3ccb54ce8ec4ddd1accd2d89004308b7b0b21c4ac3d20fa70af4760a4330/pillow-12.2.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5cdfebd752ec52bf5bb4e35d9c64b40826bc5b40a13df7c3cda20a2c03a0f5ed", size = 6395194, upload-time = "2026-04-01T14:43:59.864Z" },
+ { url = "https://files.pythonhosted.org/packages/67/ee/21d4e8536afd1a328f01b359b4d3997b291ffd35a237c877b331c1c3b71c/pillow-12.2.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eedf4b74eda2b5a4b2b2fb4c006d6295df3bf29e459e198c90ea48e130dc75c3", size = 7082423, upload-time = "2026-04-01T14:44:02.74Z" },
+ { url = "https://files.pythonhosted.org/packages/78/5f/e9f86ab0146464e8c133fe85df987ed9e77e08b29d8d35f9f9f4d6f917ba/pillow-12.2.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:00a2865911330191c0b818c59103b58a5e697cae67042366970a6b6f1b20b7f9", size = 6505667, upload-time = "2026-04-01T14:44:05.381Z" },
+ { url = "https://files.pythonhosted.org/packages/ed/1e/409007f56a2fdce61584fd3acbc2bbc259857d555196cedcadc68c015c82/pillow-12.2.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1e1757442ed87f4912397c6d35a0db6a7b52592156014706f17658ff58bbf795", size = 7208580, upload-time = "2026-04-01T14:44:08.39Z" },
+ { url = "https://files.pythonhosted.org/packages/23/c4/7349421080b12fb35414607b8871e9534546c128a11965fd4a7002ccfbee/pillow-12.2.0-cp313-cp313-win32.whl", hash = "sha256:144748b3af2d1b358d41286056d0003f47cb339b8c43a9ea42f5fea4d8c66b6e", size = 6375896, upload-time = "2026-04-01T14:44:11.197Z" },
+ { url = "https://files.pythonhosted.org/packages/3f/82/8a3739a5e470b3c6cbb1d21d315800d8e16bff503d1f16b03a4ec3212786/pillow-12.2.0-cp313-cp313-win_amd64.whl", hash = "sha256:390ede346628ccc626e5730107cde16c42d3836b89662a115a921f28440e6a3b", size = 7081266, upload-time = "2026-04-01T14:44:13.947Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/25/f968f618a062574294592f668218f8af564830ccebdd1fa6200f598e65c5/pillow-12.2.0-cp313-cp313-win_arm64.whl", hash = "sha256:8023abc91fba39036dbce14a7d6535632f99c0b857807cbbbf21ecc9f4717f06", size = 2463508, upload-time = "2026-04-01T14:44:16.312Z" },
+ { url = "https://files.pythonhosted.org/packages/4d/a4/b342930964e3cb4dce5038ae34b0eab4653334995336cd486c5a8c25a00c/pillow-12.2.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:042db20a421b9bafecc4b84a8b6e444686bd9d836c7fd24542db3e7df7baad9b", size = 5309927, upload-time = "2026-04-01T14:44:18.89Z" },
+ { url = "https://files.pythonhosted.org/packages/9f/de/23198e0a65a9cf06123f5435a5d95cea62a635697f8f03d134d3f3a96151/pillow-12.2.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:dd025009355c926a84a612fecf58bb315a3f6814b17ead51a8e48d3823d9087f", size = 4698624, upload-time = "2026-04-01T14:44:21.115Z" },
+ { url = "https://files.pythonhosted.org/packages/01/a6/1265e977f17d93ea37aa28aa81bad4fa597933879fac2520d24e021c8da3/pillow-12.2.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:88ddbc66737e277852913bd1e07c150cc7bb124539f94c4e2df5344494e0a612", size = 6321252, upload-time = "2026-04-01T14:44:23.663Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/83/5982eb4a285967baa70340320be9f88e57665a387e3a53a7f0db8231a0cd/pillow-12.2.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d362d1878f00c142b7e1a16e6e5e780f02be8195123f164edf7eddd911eefe7c", size = 8126550, upload-time = "2026-04-01T14:44:26.772Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/48/6ffc514adce69f6050d0753b1a18fd920fce8cac87620d5a31231b04bfc5/pillow-12.2.0-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2c727a6d53cb0018aadd8018c2b938376af27914a68a492f59dfcaca650d5eea", size = 6433114, upload-time = "2026-04-01T14:44:29.615Z" },
+ { url = "https://files.pythonhosted.org/packages/36/a3/f9a77144231fb8d40ee27107b4463e205fa4677e2ca2548e14da5cf18dce/pillow-12.2.0-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:efd8c21c98c5cc60653bcb311bef2ce0401642b7ce9d09e03a7da87c878289d4", size = 7115667, upload-time = "2026-04-01T14:44:32.773Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/fc/ac4ee3041e7d5a565e1c4fd72a113f03b6394cc72ab7089d27608f8aaccb/pillow-12.2.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9f08483a632889536b8139663db60f6724bfcb443c96f1b18855860d7d5c0fd4", size = 6538966, upload-time = "2026-04-01T14:44:35.252Z" },
+ { url = "https://files.pythonhosted.org/packages/c0/a8/27fb307055087f3668f6d0a8ccb636e7431d56ed0750e07a60547b1e083e/pillow-12.2.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:dac8d77255a37e81a2efcbd1fc05f1c15ee82200e6c240d7e127e25e365c39ea", size = 7238241, upload-time = "2026-04-01T14:44:37.875Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/4b/926ab182c07fccae9fcb120043464e1ff1564775ec8864f21a0ebce6ac25/pillow-12.2.0-cp313-cp313t-win32.whl", hash = "sha256:ee3120ae9dff32f121610bb08e4313be87e03efeadfc6c0d18f89127e24d0c24", size = 6379592, upload-time = "2026-04-01T14:44:40.336Z" },
+ { url = "https://files.pythonhosted.org/packages/c2/c4/f9e476451a098181b30050cc4c9a3556b64c02cf6497ea421ac047e89e4b/pillow-12.2.0-cp313-cp313t-win_amd64.whl", hash = "sha256:325ca0528c6788d2a6c3d40e3568639398137346c3d6e66bb61db96b96511c98", size = 7085542, upload-time = "2026-04-01T14:44:43.251Z" },
+ { url = "https://files.pythonhosted.org/packages/00/a4/285f12aeacbe2d6dc36c407dfbbe9e96d4a80b0fb710a337f6d2ad978c75/pillow-12.2.0-cp313-cp313t-win_arm64.whl", hash = "sha256:2e5a76d03a6c6dcef67edabda7a52494afa4035021a79c8558e14af25313d453", size = 2465765, upload-time = "2026-04-01T14:44:45.996Z" },
+ { url = "https://files.pythonhosted.org/packages/bf/98/4595daa2365416a86cb0d495248a393dfc84e96d62ad080c8546256cb9c0/pillow-12.2.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:3adc9215e8be0448ed6e814966ecf3d9952f0ea40eb14e89a102b87f450660d8", size = 4100848, upload-time = "2026-04-01T14:44:48.48Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/79/40184d464cf89f6663e18dfcf7ca21aae2491fff1a16127681bf1fa9b8cf/pillow-12.2.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:6a9adfc6d24b10f89588096364cc726174118c62130c817c2837c60cf08a392b", size = 4176515, upload-time = "2026-04-01T14:44:51.353Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/63/703f86fd4c422a9cf722833670f4f71418fb116b2853ff7da722ea43f184/pillow-12.2.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:6a6e67ea2e6feda684ed370f9a1c52e7a243631c025ba42149a2cc5934dec295", size = 3640159, upload-time = "2026-04-01T14:44:53.588Z" },
+ { url = "https://files.pythonhosted.org/packages/71/e0/fb22f797187d0be2270f83500aab851536101b254bfa1eae10795709d283/pillow-12.2.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:2bb4a8d594eacdfc59d9e5ad972aa8afdd48d584ffd5f13a937a664c3e7db0ed", size = 5312185, upload-time = "2026-04-01T14:44:56.039Z" },
+ { url = "https://files.pythonhosted.org/packages/ba/8c/1a9e46228571de18f8e28f16fabdfc20212a5d019f3e3303452b3f0a580d/pillow-12.2.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:80b2da48193b2f33ed0c32c38140f9d3186583ce7d516526d462645fd98660ae", size = 4695386, upload-time = "2026-04-01T14:44:58.663Z" },
+ { url = "https://files.pythonhosted.org/packages/70/62/98f6b7f0c88b9addd0e87c217ded307b36be024d4ff8869a812b241d1345/pillow-12.2.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:22db17c68434de69d8ecfc2fe821569195c0c373b25cccb9cbdacf2c6e53c601", size = 6280384, upload-time = "2026-04-01T14:45:01.5Z" },
+ { url = "https://files.pythonhosted.org/packages/5e/03/688747d2e91cfbe0e64f316cd2e8005698f76ada3130d0194664174fa5de/pillow-12.2.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7b14cc0106cd9aecda615dd6903840a058b4700fcb817687d0ee4fc8b6e389be", size = 8091599, upload-time = "2026-04-01T14:45:04.5Z" },
+ { url = "https://files.pythonhosted.org/packages/f6/35/577e22b936fcdd66537329b33af0b4ccfefaeabd8aec04b266528cddb33c/pillow-12.2.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8cbeb542b2ebc6fcdacabf8aca8c1a97c9b3ad3927d46b8723f9d4f033288a0f", size = 6396021, upload-time = "2026-04-01T14:45:07.117Z" },
+ { url = "https://files.pythonhosted.org/packages/11/8d/d2532ad2a603ca2b93ad9f5135732124e57811d0168155852f37fbce2458/pillow-12.2.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4bfd07bc812fbd20395212969e41931001fd59eb55a60658b0e5710872e95286", size = 7083360, upload-time = "2026-04-01T14:45:09.763Z" },
+ { url = "https://files.pythonhosted.org/packages/5e/26/d325f9f56c7e039034897e7380e9cc202b1e368bfd04d4cbe6a441f02885/pillow-12.2.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:9aba9a17b623ef750a4d11b742cbafffeb48a869821252b30ee21b5e91392c50", size = 6507628, upload-time = "2026-04-01T14:45:12.378Z" },
+ { url = "https://files.pythonhosted.org/packages/5f/f7/769d5632ffb0988f1c5e7660b3e731e30f7f8ec4318e94d0a5d674eb65a4/pillow-12.2.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:deede7c263feb25dba4e82ea23058a235dcc2fe1f6021025dc71f2b618e26104", size = 7209321, upload-time = "2026-04-01T14:45:15.122Z" },
+ { url = "https://files.pythonhosted.org/packages/6a/7a/c253e3c645cd47f1aceea6a8bacdba9991bf45bb7dfe927f7c893e89c93c/pillow-12.2.0-cp314-cp314-win32.whl", hash = "sha256:632ff19b2778e43162304d50da0181ce24ac5bb8180122cbe1bf4673428328c7", size = 6479723, upload-time = "2026-04-01T14:45:17.797Z" },
+ { url = "https://files.pythonhosted.org/packages/cd/8b/601e6566b957ca50e28725cb6c355c59c2c8609751efbecd980db44e0349/pillow-12.2.0-cp314-cp314-win_amd64.whl", hash = "sha256:4e6c62e9d237e9b65fac06857d511e90d8461a32adcc1b9065ea0c0fa3a28150", size = 7217400, upload-time = "2026-04-01T14:45:20.529Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/94/220e46c73065c3e2951bb91c11a1fb636c8c9ad427ac3ce7d7f3359b9b2f/pillow-12.2.0-cp314-cp314-win_arm64.whl", hash = "sha256:b1c1fbd8a5a1af3412a0810d060a78b5136ec0836c8a4ef9aa11807f2a22f4e1", size = 2554835, upload-time = "2026-04-01T14:45:23.162Z" },
+ { url = "https://files.pythonhosted.org/packages/b6/ab/1b426a3974cb0e7da5c29ccff4807871d48110933a57207b5a676cccc155/pillow-12.2.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:57850958fe9c751670e49b2cecf6294acc99e562531f4bd317fa5ddee2068463", size = 5314225, upload-time = "2026-04-01T14:45:25.637Z" },
+ { url = "https://files.pythonhosted.org/packages/19/1e/dce46f371be2438eecfee2a1960ee2a243bbe5e961890146d2dee1ff0f12/pillow-12.2.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:d5d38f1411c0ed9f97bcb49b7bd59b6b7c314e0e27420e34d99d844b9ce3b6f3", size = 4698541, upload-time = "2026-04-01T14:45:28.355Z" },
+ { url = "https://files.pythonhosted.org/packages/55/c3/7fbecf70adb3a0c33b77a300dc52e424dc22ad8cdc06557a2e49523b703d/pillow-12.2.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5c0a9f29ca8e79f09de89293f82fc9b0270bb4af1d58bc98f540cc4aedf03166", size = 6322251, upload-time = "2026-04-01T14:45:30.924Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/3c/7fbc17cfb7e4fe0ef1642e0abc17fc6c94c9f7a16be41498e12e2ba60408/pillow-12.2.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1610dd6c61621ae1cf811bef44d77e149ce3f7b95afe66a4512f8c59f25d9ebe", size = 8127807, upload-time = "2026-04-01T14:45:33.908Z" },
+ { url = "https://files.pythonhosted.org/packages/ff/c3/a8ae14d6defd2e448493ff512fae903b1e9bd40b72efb6ec55ce0048c8ce/pillow-12.2.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0a34329707af4f73cf1782a36cd2289c0368880654a2c11f027bcee9052d35dd", size = 6433935, upload-time = "2026-04-01T14:45:36.623Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/32/2880fb3a074847ac159d8f902cb43278a61e85f681661e7419e6596803ed/pillow-12.2.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e9c4f5b3c546fa3458a29ab22646c1c6c787ea8f5ef51300e5a60300736905e", size = 7116720, upload-time = "2026-04-01T14:45:39.258Z" },
+ { url = "https://files.pythonhosted.org/packages/46/87/495cc9c30e0129501643f24d320076f4cc54f718341df18cc70ec94c44e1/pillow-12.2.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fb043ee2f06b41473269765c2feae53fc2e2fbf96e5e22ca94fb5ad677856f06", size = 6540498, upload-time = "2026-04-01T14:45:41.879Z" },
+ { url = "https://files.pythonhosted.org/packages/18/53/773f5edca692009d883a72211b60fdaf8871cbef075eaa9d577f0a2f989e/pillow-12.2.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f278f034eb75b4e8a13a54a876cc4a5ab39173d2cdd93a638e1b467fc545ac43", size = 7239413, upload-time = "2026-04-01T14:45:44.705Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/e4/4b64a97d71b2a83158134abbb2f5bd3f8a2ea691361282f010998f339ec7/pillow-12.2.0-cp314-cp314t-win32.whl", hash = "sha256:6bb77b2dcb06b20f9f4b4a8454caa581cd4dd0643a08bacf821216a16d9c8354", size = 6482084, upload-time = "2026-04-01T14:45:47.568Z" },
+ { url = "https://files.pythonhosted.org/packages/ba/13/306d275efd3a3453f72114b7431c877d10b1154014c1ebbedd067770d629/pillow-12.2.0-cp314-cp314t-win_amd64.whl", hash = "sha256:6562ace0d3fb5f20ed7290f1f929cae41b25ae29528f2af1722966a0a02e2aa1", size = 7225152, upload-time = "2026-04-01T14:45:50.032Z" },
+ { url = "https://files.pythonhosted.org/packages/ff/6e/cf826fae916b8658848d7b9f38d88da6396895c676e8086fc0988073aaf8/pillow-12.2.0-cp314-cp314t-win_arm64.whl", hash = "sha256:aa88ccfe4e32d362816319ed727a004423aab09c5cea43c01a4b435643fa34eb", size = 2556579, upload-time = "2026-04-01T14:45:52.529Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/b7/2437044fb910f499610356d1352e3423753c98e34f915252aafecc64889f/pillow-12.2.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0538bd5e05efec03ae613fd89c4ce0368ecd2ba239cc25b9f9be7ed426b0af1f", size = 5273969, upload-time = "2026-04-01T14:45:55.538Z" },
+ { url = "https://files.pythonhosted.org/packages/f6/f4/8316e31de11b780f4ac08ef3654a75555e624a98db1056ecb2122d008d5a/pillow-12.2.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:394167b21da716608eac917c60aa9b969421b5dcbbe02ae7f013e7b85811c69d", size = 4659674, upload-time = "2026-04-01T14:45:58.093Z" },
+ { url = "https://files.pythonhosted.org/packages/d4/37/664fca7201f8bb2aa1d20e2c3d5564a62e6ae5111741966c8319ca802361/pillow-12.2.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5d04bfa02cc2d23b497d1e90a0f927070043f6cbf303e738300532379a4b4e0f", size = 5288479, upload-time = "2026-04-01T14:46:01.141Z" },
+ { url = "https://files.pythonhosted.org/packages/49/62/5b0ed78fce87346be7a5cfcfaaad91f6a1f98c26f86bdbafa2066c647ef6/pillow-12.2.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0c838a5125cee37e68edec915651521191cef1e6aa336b855f495766e77a366e", size = 7032230, upload-time = "2026-04-01T14:46:03.874Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/28/ec0fc38107fc32536908034e990c47914c57cd7c5a3ece4d8d8f7ffd7e27/pillow-12.2.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a6c9fa44005fa37a91ebfc95d081e8079757d2e904b27103f4f5fa6f0bf78c0", size = 5355404, upload-time = "2026-04-01T14:46:06.33Z" },
+ { url = "https://files.pythonhosted.org/packages/5e/8b/51b0eddcfa2180d60e41f06bd6d0a62202b20b59c68f5a132e615b75aecf/pillow-12.2.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:25373b66e0dd5905ed63fa3cae13c82fbddf3079f2c8bf15c6fb6a35586324c1", size = 6002215, upload-time = "2026-04-01T14:46:08.83Z" },
+ { url = "https://files.pythonhosted.org/packages/bc/60/5382c03e1970de634027cee8e1b7d39776b778b81812aaf45b694dfe9e28/pillow-12.2.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:bfa9c230d2fe991bed5318a5f119bd6780cda2915cca595393649fc118ab895e", size = 7080946, upload-time = "2026-04-01T14:46:11.734Z" },
+]
+
[[package]]
name = "pluggy"
version = "1.6.0"
@@ -1735,6 +2342,39 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
]
+[[package]]
+name = "pot"
+version = "0.9.6.post1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+ { name = "scipy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/42/8b/5f939eaf1fbeb7ff914fe540d659486951a056e5537b8f454362045b6c72/pot-0.9.6.post1.tar.gz", hash = "sha256:9b6cc14a8daecfe1268268168cf46548f9130976b22b24a9e8ec62a734be6c43", size = 604243, upload-time = "2025-09-22T12:51:14.894Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f6/fc/3f4014bd6713c5b4c8a329b12c52842443b2284f52213a80e697b76b9f20/pot-0.9.6.post1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7fd8482a0262e5c875c05cf52e9c087e7c8bc473ef05d175887ad16e3c0443b7", size = 599499, upload-time = "2025-09-22T12:50:33.796Z" },
+ { url = "https://files.pythonhosted.org/packages/e7/4e/b22b789ee3a81c11c6f39ff08ed6a2e797a2a75a831fae996f4057db4771/pot-0.9.6.post1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c0bfac9daec0095061279a709f52be740e09363a62fe4c7edc843a4a0f6144c6", size = 466484, upload-time = "2025-09-22T12:50:34.973Z" },
+ { url = "https://files.pythonhosted.org/packages/9f/ae/2b35b96562bd72baf6de9583458878738f4508eef70d6fa9dd5867760d6a/pot-0.9.6.post1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:703853f7ba0ae2afed8203ea3478e87ef5f39d55cd75b1a39bb622867d1d5628", size = 453014, upload-time = "2025-09-22T12:50:36.157Z" },
+ { url = "https://files.pythonhosted.org/packages/44/7e/f49d0593338a3b7f2c88c4cd6f1285c084e8ce05d52d42ac6f89f4f7ec0c/pot-0.9.6.post1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:68268b4dd926976cf0604d466a57dff2ca44372e8ae9c879ba1f3d2a51e3be3d", size = 1494875, upload-time = "2025-09-22T12:50:37.903Z" },
+ { url = "https://files.pythonhosted.org/packages/15/91/844c8437caaca6d6a71b38623df75c43642a116d399316adb1d0a9280c85/pot-0.9.6.post1-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c7568ddc957d3a16739bd24f9e07ce655166d27ebbc8786aad692cc5ba5d4c59", size = 1514551, upload-time = "2025-09-22T12:50:39.616Z" },
+ { url = "https://files.pythonhosted.org/packages/ac/de/34a50565c37c0b71725a8075ff1ad2de62213d2e119276b546ef20356ac2/pot-0.9.6.post1-cp311-cp311-win32.whl", hash = "sha256:9649b736ea5dddad3a89d55a4a3bb0078610307ba64cac2efebe6bfcf8cfe785", size = 443490, upload-time = "2025-09-22T12:50:41.162Z" },
+ { url = "https://files.pythonhosted.org/packages/a7/fa/453730c1b10094ab4d2ecd0b5fbfcdfe0305419cf01e32a2d31efd333559/pot-0.9.6.post1-cp311-cp311-win_amd64.whl", hash = "sha256:e161e49a22d5a925993baace4679f4e32fc2ade8f45ad73cf8417e13df5bd337", size = 458509, upload-time = "2025-09-22T12:50:43.597Z" },
+ { url = "https://files.pythonhosted.org/packages/b9/28/13622807461f9f6082a8cd6768f9b4a810bc3a8fda474b81572da94b4d23/pot-0.9.6.post1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:f7c542fc20662e35c24dd82eeff8a737220757434d7f0038664a7322221452f7", size = 599240, upload-time = "2025-09-22T12:50:44.848Z" },
+ { url = "https://files.pythonhosted.org/packages/c6/5c/b4e017560531f53d06798c681b0d0a9488bb8116bc98da9d399a3d096391/pot-0.9.6.post1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c1755516a7354cbd6110ad2e5f341b98b9968240c2f0f67b0ff5e3ebcb3105bd", size = 464695, upload-time = "2025-09-22T12:50:46.341Z" },
+ { url = "https://files.pythonhosted.org/packages/07/9f/57e49b3f7173359741053c5e2766a45dcf649d767c2e967ef93526c9045f/pot-0.9.6.post1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f3207362d3e3b5aaa783f452aa85f66e83edbefb5764f34662860af54ac72ee6", size = 454726, upload-time = "2025-09-22T12:50:47.953Z" },
+ { url = "https://files.pythonhosted.org/packages/30/60/fa72dd6094f7dbe6b38e2c6907af8cd0f18c6bd107e0cf4874deddaba883/pot-0.9.6.post1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:05f6659c5657e6d7e9f98f4a82e0ed64f88e9fce69b2e557416d156343919ba3", size = 1503391, upload-time = "2025-09-22T12:50:49.336Z" },
+ { url = "https://files.pythonhosted.org/packages/2f/3f/cc519c1176116271b6282268a705162fa042c16cc922bc56039445c9d697/pot-0.9.6.post1-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4f1b0148ae17bec0ed12264c6da3a05e13913b716e2a8c9043242b5d8349d8df", size = 1528170, upload-time = "2025-09-22T12:50:50.625Z" },
+ { url = "https://files.pythonhosted.org/packages/f5/01/0132c94404cd0b1b2f21c4a49698db9dcd6107c47c02b22df1ed38206b2a/pot-0.9.6.post1-cp312-cp312-win32.whl", hash = "sha256:571e543cc2b0a462365002203595baf2b89c3d064cce4fce70fd1231e832c21f", size = 440577, upload-time = "2025-09-22T12:50:51.716Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/6d/23229c0e198a4f7fb27750b3ef8497e6ebed23fe531ed64b5194da8b2b02/pot-0.9.6.post1-cp312-cp312-win_amd64.whl", hash = "sha256:b1d8bd9a334c72baa37f9a2b268de5366c23c0f9c9e3d6dc25d150137ec2823c", size = 455404, upload-time = "2025-09-22T12:50:52.956Z" },
+ { url = "https://files.pythonhosted.org/packages/53/17/e4aebb8deef58b0d40ac339d952d12c63559801b50ae43c622d49bebda7e/pot-0.9.6.post1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:659fff750a162f58b52b33a64c4ac358f4ff44e9dff0841052c088e1b6a54430", size = 596485, upload-time = "2025-09-22T12:50:54.309Z" },
+ { url = "https://files.pythonhosted.org/packages/f7/b9/3646c153b13f999ac30112dcf85c5f233af79b0d98c37b52dda9a624c91b/pot-0.9.6.post1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:4f54830e9f9cb78b1ff7abd5c5bf162625ed6aea903241267c64ea9f0fb73ddb", size = 463244, upload-time = "2025-09-22T12:50:56.004Z" },
+ { url = "https://files.pythonhosted.org/packages/53/e9/c7092f7aec8cb32739ad66ba1f1259626546e4893b61b905ce2da3987235/pot-0.9.6.post1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e9fd4b1fafacd37debdb984687ddb26f5c43d1429401847d388a6f1bd1f10e98", size = 453215, upload-time = "2025-09-22T12:50:57.515Z" },
+ { url = "https://files.pythonhosted.org/packages/0c/a1/f0187ab15aa1538ece07b28f3a7938b8592ef01fbe37b1a8f9c2f8f47f4d/pot-0.9.6.post1-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ec097ec0ef8bb93fee8cdb187b6a0a9653613cba7b06bb603247930e2c629cdc", size = 1496245, upload-time = "2025-09-22T12:50:58.848Z" },
+ { url = "https://files.pythonhosted.org/packages/29/fa/85af71553b7e990fc37da8d5f2e7294ec66297e62cba419efeec11518e5a/pot-0.9.6.post1-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:299f11f172908d799793ef18b2bc82452305350d2528d243e255a17876e98a57", size = 1521691, upload-time = "2025-09-22T12:51:00.203Z" },
+ { url = "https://files.pythonhosted.org/packages/19/ae/96b2bce173b3d2d3d0faf8b7362fe79e60e1a6a939c9459b2f7b64e625d8/pot-0.9.6.post1-cp313-cp313-win32.whl", hash = "sha256:8a1d95310faae9c75355d9e2fac8dfac41316a2450061eefc982ee498a687a34", size = 439760, upload-time = "2025-09-22T12:51:01.601Z" },
+ { url = "https://files.pythonhosted.org/packages/f7/b1/8ca34418e7c4a2ec666e2204539577287223c4e78ab80b1c746cedb559c3/pot-0.9.6.post1-cp313-cp313-win_amd64.whl", hash = "sha256:a43e2b61389bd32f5b488da2488999ed55867e95fedb25dd64f9f390e40b4fab", size = 454228, upload-time = "2025-09-22T12:51:03.215Z" },
+]
+
[[package]]
name = "propcache"
version = "0.4.1"
@@ -2063,6 +2703,31 @@ crypto = [
{ name = "cryptography" },
]
+[[package]]
+name = "pynndescent"
+version = "0.6.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "joblib" },
+ { name = "llvmlite" },
+ { name = "numba" },
+ { name = "scikit-learn" },
+ { name = "scipy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/4a/fb/7f58c397fb31666756457ee2ac4c0289ef2daad57f4ae4be8dec12f80b03/pynndescent-0.6.0.tar.gz", hash = "sha256:7ffde0fb5b400741e055a9f7d377e3702e02250616834231f6c209e39aac24f5", size = 2992987, upload-time = "2026-01-08T21:29:58.943Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b2/e6/94145d714402fd5ade00b5661f2d0ab981219e07f7db9bfa16786cdb9c04/pynndescent-0.6.0-py3-none-any.whl", hash = "sha256:dc8c74844e4c7f5cbd1e0cd6909da86fdc789e6ff4997336e344779c3d5538ef", size = 73511, upload-time = "2026-01-08T21:29:57.306Z" },
+]
+
+[[package]]
+name = "pyparsing"
+version = "3.3.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f3/91/9c6ee907786a473bf81c5f53cf703ba0957b23ab84c264080fb5a450416f/pyparsing-3.3.2.tar.gz", hash = "sha256:c777f4d763f140633dcb6d8a3eda953bf7a214dc4eff598413c070bcdc117cbc", size = 6851574, upload-time = "2026-01-21T03:57:59.36Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/10/bd/c038d7cc38edc1aa5bf91ab8068b63d4308c66c4c8bb3cbba7dfbc049f9c/pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d", size = 122781, upload-time = "2026-01-21T03:57:55.912Z" },
+]
+
[[package]]
name = "pyproject-hooks"
version = "1.2.0"
@@ -2142,6 +2807,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/1b/d0/397f9626e711ff749a95d96b7af99b9c566a9bb5129b8e4c10fc4d100304/python_multipart-0.0.22-py3-none-any.whl", hash = "sha256:2b2cd894c83d21bf49d702499531c7bafd057d730c201782048f7945d82de155", size = 24579, upload-time = "2026-01-25T10:15:54.811Z" },
]
+[[package]]
+name = "pytz"
+version = "2026.1.post1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/56/db/b8721d71d945e6a8ac63c0fc900b2067181dbb50805958d4d4661cf7d277/pytz-2026.1.post1.tar.gz", hash = "sha256:3378dde6a0c3d26719182142c56e60c7f9af7e968076f31aae569d72a0358ee1", size = 321088, upload-time = "2026-03-03T07:47:50.683Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/10/99/781fe0c827be2742bcc775efefccb3b048a3a9c6ce9aec0cbf4a101677e5/pytz-2026.1.post1-py2.py3-none-any.whl", hash = "sha256:f2fd16142fda348286a75e1a524be810bb05d444e5a081f37f7affc635035f7a", size = 510489, upload-time = "2026-03-03T07:47:49.167Z" },
+]
+
[[package]]
name = "pywin32"
version = "311"
@@ -2336,7 +3010,7 @@ wheels = [
[[package]]
name = "repowise"
-version = "0.2.2"
+version = "0.2.3"
source = { editable = "." }
dependencies = [
{ name = "aiosqlite" },
@@ -2387,6 +3061,9 @@ dev = [
{ name = "time-machine" },
{ name = "types-networkx" },
]
+graph-extra = [
+ { name = "graspologic" },
+]
postgres = [
{ name = "asyncpg" },
{ name = "pgvector" },
@@ -2418,6 +3095,7 @@ requires-dist = [
{ name = "fastapi", specifier = ">=0.115,<1" },
{ name = "gitpython", specifier = ">=3.1,<4" },
{ name = "google-genai", specifier = ">=1.0,<2" },
+ { name = "graspologic", marker = "extra == 'graph-extra'", specifier = ">=3.4,<4" },
{ name = "httpx", specifier = ">=0.27,<1" },
{ name = "jinja2", specifier = ">=3.1,<4" },
{ name = "lancedb", specifier = ">=0.12,<1" },
@@ -2453,7 +3131,7 @@ requires-dist = [
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.32,<1" },
{ name = "watchdog", specifier = ">=4,<5" },
]
-provides-extras = ["postgres", "dev"]
+provides-extras = ["postgres", "graph-extra", "dev"]
[package.metadata.requires-dev]
dev = [
@@ -2672,6 +3350,56 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/7f/d0/578c47dd68152ddddddf31cd7fc67dc30b7cdf639a86275fda821b0d9d98/ruff-0.15.6-py3-none-win_arm64.whl", hash = "sha256:c34de3dd0b0ba203be50ae70f5910b17188556630e2178fd7d79fc030eb0d837", size = 11060497, upload-time = "2026-03-12T23:05:25.968Z" },
]
+[[package]]
+name = "scikit-learn"
+version = "1.8.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "joblib" },
+ { name = "numpy" },
+ { name = "scipy" },
+ { name = "threadpoolctl" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/0e/d4/40988bf3b8e34feec1d0e6a051446b1f66225f8529b9309becaeef62b6c4/scikit_learn-1.8.0.tar.gz", hash = "sha256:9bccbb3b40e3de10351f8f5068e105d0f4083b1a65fa07b6634fbc401a6287fd", size = 7335585, upload-time = "2025-12-10T07:08:53.618Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c9/92/53ea2181da8ac6bf27170191028aee7251f8f841f8d3edbfdcaf2008fde9/scikit_learn-1.8.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:146b4d36f800c013d267b29168813f7a03a43ecd2895d04861f1240b564421da", size = 8595835, upload-time = "2025-12-10T07:07:39.385Z" },
+ { url = "https://files.pythonhosted.org/packages/01/18/d154dc1638803adf987910cdd07097d9c526663a55666a97c124d09fb96a/scikit_learn-1.8.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:f984ca4b14914e6b4094c5d52a32ea16b49832c03bd17a110f004db3c223e8e1", size = 8080381, upload-time = "2025-12-10T07:07:41.93Z" },
+ { url = "https://files.pythonhosted.org/packages/8a/44/226142fcb7b7101e64fdee5f49dbe6288d4c7af8abf593237b70fca080a4/scikit_learn-1.8.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5e30adb87f0cc81c7690a84f7932dd66be5bac57cfe16b91cb9151683a4a2d3b", size = 8799632, upload-time = "2025-12-10T07:07:43.899Z" },
+ { url = "https://files.pythonhosted.org/packages/36/4d/4a67f30778a45d542bbea5db2dbfa1e9e100bf9ba64aefe34215ba9f11f6/scikit_learn-1.8.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ada8121bcb4dac28d930febc791a69f7cb1673c8495e5eee274190b73a4559c1", size = 9103788, upload-time = "2025-12-10T07:07:45.982Z" },
+ { url = "https://files.pythonhosted.org/packages/89/3c/45c352094cfa60050bcbb967b1faf246b22e93cb459f2f907b600f2ceda5/scikit_learn-1.8.0-cp311-cp311-win_amd64.whl", hash = "sha256:c57b1b610bd1f40ba43970e11ce62821c2e6569e4d74023db19c6b26f246cb3b", size = 8081706, upload-time = "2025-12-10T07:07:48.111Z" },
+ { url = "https://files.pythonhosted.org/packages/3d/46/5416595bb395757f754feb20c3d776553a386b661658fb21b7c814e89efe/scikit_learn-1.8.0-cp311-cp311-win_arm64.whl", hash = "sha256:2838551e011a64e3053ad7618dda9310175f7515f1742fa2d756f7c874c05961", size = 7688451, upload-time = "2025-12-10T07:07:49.873Z" },
+ { url = "https://files.pythonhosted.org/packages/90/74/e6a7cc4b820e95cc38cf36cd74d5aa2b42e8ffc2d21fe5a9a9c45c1c7630/scikit_learn-1.8.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5fb63362b5a7ddab88e52b6dbb47dac3fd7dafeee740dc6c8d8a446ddedade8e", size = 8548242, upload-time = "2025-12-10T07:07:51.568Z" },
+ { url = "https://files.pythonhosted.org/packages/49/d8/9be608c6024d021041c7f0b3928d4749a706f4e2c3832bbede4fb4f58c95/scikit_learn-1.8.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:5025ce924beccb28298246e589c691fe1b8c1c96507e6d27d12c5fadd85bfd76", size = 8079075, upload-time = "2025-12-10T07:07:53.697Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/47/f187b4636ff80cc63f21cd40b7b2d177134acaa10f6bb73746130ee8c2e5/scikit_learn-1.8.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4496bb2cf7a43ce1a2d7524a79e40bc5da45cf598dbf9545b7e8316ccba47bb4", size = 8660492, upload-time = "2025-12-10T07:07:55.574Z" },
+ { url = "https://files.pythonhosted.org/packages/97/74/b7a304feb2b49df9fafa9382d4d09061a96ee9a9449a7cbea7988dda0828/scikit_learn-1.8.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a0bcfe4d0d14aec44921545fd2af2338c7471de9cb701f1da4c9d85906ab847a", size = 8931904, upload-time = "2025-12-10T07:07:57.666Z" },
+ { url = "https://files.pythonhosted.org/packages/9f/c4/0ab22726a04ede56f689476b760f98f8f46607caecff993017ac1b64aa5d/scikit_learn-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:35c007dedb2ffe38fe3ee7d201ebac4a2deccd2408e8621d53067733e3c74809", size = 8019359, upload-time = "2025-12-10T07:07:59.838Z" },
+ { url = "https://files.pythonhosted.org/packages/24/90/344a67811cfd561d7335c1b96ca21455e7e472d281c3c279c4d3f2300236/scikit_learn-1.8.0-cp312-cp312-win_arm64.whl", hash = "sha256:8c497fff237d7b4e07e9ef1a640887fa4fb765647f86fbe00f969ff6280ce2bb", size = 7641898, upload-time = "2025-12-10T07:08:01.36Z" },
+ { url = "https://files.pythonhosted.org/packages/03/aa/e22e0768512ce9255eba34775be2e85c2048da73da1193e841707f8f039c/scikit_learn-1.8.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0d6ae97234d5d7079dc0040990a6f7aeb97cb7fa7e8945f1999a429b23569e0a", size = 8513770, upload-time = "2025-12-10T07:08:03.251Z" },
+ { url = "https://files.pythonhosted.org/packages/58/37/31b83b2594105f61a381fc74ca19e8780ee923be2d496fcd8d2e1147bd99/scikit_learn-1.8.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:edec98c5e7c128328124a029bceb09eda2d526997780fef8d65e9a69eead963e", size = 8044458, upload-time = "2025-12-10T07:08:05.336Z" },
+ { url = "https://files.pythonhosted.org/packages/2d/5a/3f1caed8765f33eabb723596666da4ebbf43d11e96550fb18bdec42b467b/scikit_learn-1.8.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:74b66d8689d52ed04c271e1329f0c61635bcaf5b926db9b12d58914cdc01fe57", size = 8610341, upload-time = "2025-12-10T07:08:07.732Z" },
+ { url = "https://files.pythonhosted.org/packages/38/cf/06896db3f71c75902a8e9943b444a56e727418f6b4b4a90c98c934f51ed4/scikit_learn-1.8.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8fdf95767f989b0cfedb85f7ed8ca215d4be728031f56ff5a519ee1e3276dc2e", size = 8900022, upload-time = "2025-12-10T07:08:09.862Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/f9/9b7563caf3ec8873e17a31401858efab6b39a882daf6c1bfa88879c0aa11/scikit_learn-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:2de443b9373b3b615aec1bb57f9baa6bb3a9bd093f1269ba95c17d870422b271", size = 7989409, upload-time = "2025-12-10T07:08:12.028Z" },
+ { url = "https://files.pythonhosted.org/packages/49/bd/1f4001503650e72c4f6009ac0c4413cb17d2d601cef6f71c0453da2732fc/scikit_learn-1.8.0-cp313-cp313-win_arm64.whl", hash = "sha256:eddde82a035681427cbedded4e6eff5e57fa59216c2e3e90b10b19ab1d0a65c3", size = 7619760, upload-time = "2025-12-10T07:08:13.688Z" },
+ { url = "https://files.pythonhosted.org/packages/d2/7d/a630359fc9dcc95496588c8d8e3245cc8fd81980251079bc09c70d41d951/scikit_learn-1.8.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:7cc267b6108f0a1499a734167282c00c4ebf61328566b55ef262d48e9849c735", size = 8826045, upload-time = "2025-12-10T07:08:15.215Z" },
+ { url = "https://files.pythonhosted.org/packages/cc/56/a0c86f6930cfcd1c7054a2bc417e26960bb88d32444fe7f71d5c2cfae891/scikit_learn-1.8.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:fe1c011a640a9f0791146011dfd3c7d9669785f9fed2b2a5f9e207536cf5c2fd", size = 8420324, upload-time = "2025-12-10T07:08:17.561Z" },
+ { url = "https://files.pythonhosted.org/packages/46/1e/05962ea1cebc1cf3876667ecb14c283ef755bf409993c5946ade3b77e303/scikit_learn-1.8.0-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:72358cce49465d140cc4e7792015bb1f0296a9742d5622c67e31399b75468b9e", size = 8680651, upload-time = "2025-12-10T07:08:19.952Z" },
+ { url = "https://files.pythonhosted.org/packages/fe/56/a85473cd75f200c9759e3a5f0bcab2d116c92a8a02ee08ccd73b870f8bb4/scikit_learn-1.8.0-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:80832434a6cc114f5219211eec13dcbc16c2bac0e31ef64c6d346cde3cf054cb", size = 8925045, upload-time = "2025-12-10T07:08:22.11Z" },
+ { url = "https://files.pythonhosted.org/packages/cc/b7/64d8cfa896c64435ae57f4917a548d7ac7a44762ff9802f75a79b77cb633/scikit_learn-1.8.0-cp313-cp313t-win_amd64.whl", hash = "sha256:ee787491dbfe082d9c3013f01f5991658b0f38aa8177e4cd4bf434c58f551702", size = 8507994, upload-time = "2025-12-10T07:08:23.943Z" },
+ { url = "https://files.pythonhosted.org/packages/5e/37/e192ea709551799379958b4c4771ec507347027bb7c942662c7fbeba31cb/scikit_learn-1.8.0-cp313-cp313t-win_arm64.whl", hash = "sha256:bf97c10a3f5a7543f9b88cbf488d33d175e9146115a451ae34568597ba33dcde", size = 7869518, upload-time = "2025-12-10T07:08:25.71Z" },
+ { url = "https://files.pythonhosted.org/packages/24/05/1af2c186174cc92dcab2233f327336058c077d38f6fe2aceb08e6ab4d509/scikit_learn-1.8.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:c22a2da7a198c28dd1a6e1136f19c830beab7fdca5b3e5c8bba8394f8a5c45b3", size = 8528667, upload-time = "2025-12-10T07:08:27.541Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/25/01c0af38fe969473fb292bba9dc2b8f9b451f3112ff242c647fee3d0dfe7/scikit_learn-1.8.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:6b595b07a03069a2b1740dc08c2299993850ea81cce4fe19b2421e0c970de6b7", size = 8066524, upload-time = "2025-12-10T07:08:29.822Z" },
+ { url = "https://files.pythonhosted.org/packages/be/ce/a0623350aa0b68647333940ee46fe45086c6060ec604874e38e9ab7d8e6c/scikit_learn-1.8.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:29ffc74089f3d5e87dfca4c2c8450f88bdc61b0fc6ed5d267f3988f19a1309f6", size = 8657133, upload-time = "2025-12-10T07:08:31.865Z" },
+ { url = "https://files.pythonhosted.org/packages/b8/cb/861b41341d6f1245e6ca80b1c1a8c4dfce43255b03df034429089ca2a2c5/scikit_learn-1.8.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fb65db5d7531bccf3a4f6bec3462223bea71384e2cda41da0f10b7c292b9e7c4", size = 8923223, upload-time = "2025-12-10T07:08:34.166Z" },
+ { url = "https://files.pythonhosted.org/packages/76/18/a8def8f91b18cd1ba6e05dbe02540168cb24d47e8dcf69e8d00b7da42a08/scikit_learn-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:56079a99c20d230e873ea40753102102734c5953366972a71d5cb39a32bc40c6", size = 8096518, upload-time = "2025-12-10T07:08:36.339Z" },
+ { url = "https://files.pythonhosted.org/packages/d1/77/482076a678458307f0deb44e29891d6022617b2a64c840c725495bee343f/scikit_learn-1.8.0-cp314-cp314-win_arm64.whl", hash = "sha256:3bad7565bc9cf37ce19a7c0d107742b320c1285df7aab1a6e2d28780df167242", size = 7754546, upload-time = "2025-12-10T07:08:38.128Z" },
+ { url = "https://files.pythonhosted.org/packages/2d/d1/ef294ca754826daa043b2a104e59960abfab4cf653891037d19dd5b6f3cf/scikit_learn-1.8.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:4511be56637e46c25721e83d1a9cea9614e7badc7040c4d573d75fbe257d6fd7", size = 8848305, upload-time = "2025-12-10T07:08:41.013Z" },
+ { url = "https://files.pythonhosted.org/packages/5b/e2/b1f8b05138ee813b8e1a4149f2f0d289547e60851fd1bb268886915adbda/scikit_learn-1.8.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:a69525355a641bf8ef136a7fa447672fb54fe8d60cab5538d9eb7c6438543fb9", size = 8432257, upload-time = "2025-12-10T07:08:42.873Z" },
+ { url = "https://files.pythonhosted.org/packages/26/11/c32b2138a85dcb0c99f6afd13a70a951bfdff8a6ab42d8160522542fb647/scikit_learn-1.8.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c2656924ec73e5939c76ac4c8b026fc203b83d8900362eb2599d8aee80e4880f", size = 8678673, upload-time = "2025-12-10T07:08:45.362Z" },
+ { url = "https://files.pythonhosted.org/packages/c7/57/51f2384575bdec454f4fe4e7a919d696c9ebce914590abf3e52d47607ab8/scikit_learn-1.8.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:15fc3b5d19cc2be65404786857f2e13c70c83dd4782676dd6814e3b89dc8f5b9", size = 8922467, upload-time = "2025-12-10T07:08:47.408Z" },
+ { url = "https://files.pythonhosted.org/packages/35/4d/748c9e2872637a57981a04adc038dacaa16ba8ca887b23e34953f0b3f742/scikit_learn-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:00d6f1d66fbcf4eba6e356e1420d33cc06c70a45bb1363cd6f6a8e4ebbbdece2", size = 8774395, upload-time = "2025-12-10T07:08:49.337Z" },
+ { url = "https://files.pythonhosted.org/packages/60/22/d7b2ebe4704a5e50790ba089d5c2ae308ab6bb852719e6c3bd4f04c3a363/scikit_learn-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:f28dd15c6bb0b66ba09728cf09fd8736c304be29409bd8445a080c1280619e8c", size = 8002647, upload-time = "2025-12-10T07:08:51.601Z" },
+]
+
[[package]]
name = "scipy"
version = "1.17.1"
@@ -2743,6 +3471,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/07/39/338d9219c4e87f3e708f18857ecd24d22a0c3094752393319553096b98af/scipy-1.17.1-cp314-cp314t-win_arm64.whl", hash = "sha256:200e1050faffacc162be6a486a984a0497866ec54149a01270adc8a59b7c7d21", size = 25489165, upload-time = "2026-02-23T00:22:29.563Z" },
]
+[[package]]
+name = "seaborn"
+version = "0.13.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "matplotlib" },
+ { name = "numpy" },
+ { name = "pandas" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/86/59/a451d7420a77ab0b98f7affa3a1d78a313d2f7281a57afb1a34bae8ab412/seaborn-0.13.2.tar.gz", hash = "sha256:93e60a40988f4d65e9f4885df477e2fdaff6b73a9ded434c1ab356dd57eefff7", size = 1457696, upload-time = "2024-01-25T13:21:52.551Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/83/11/00d3c3dfc25ad54e731d91449895a79e4bf2384dc3ac01809010ba88f6d5/seaborn-0.13.2-py3-none-any.whl", hash = "sha256:636f8336facf092165e27924f223d3c62ca560b1f2bb5dff7ab7fad265361987", size = 294914, upload-time = "2024-01-25T13:21:49.598Z" },
+]
+
[[package]]
name = "shellingham"
version = "1.5.4"
@@ -2761,6 +3503,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
]
+[[package]]
+name = "smart-open"
+version = "7.5.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "wrapt" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e8/be/a66598b305763861a9ab15ff0f2fbc44e47b1ce7a776797337a4eef37c66/smart_open-7.5.1.tar.gz", hash = "sha256:3f08e16827c4733699e6b2cc40328a3568f900cb12ad9a3ad233ba6c872d9fe7", size = 54034, upload-time = "2026-02-23T11:01:28.979Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5e/ea/dcdecd68acebb49d3fd560473a43499b1635076f7f1ae8641c060fe7ce74/smart_open-7.5.1-py3-none-any.whl", hash = "sha256:3e07cbbd9c8a908bcb8e25d48becf1a5cbb4886fa975e9f34c672ed171df2318", size = 64108, upload-time = "2026-02-23T11:01:27.429Z" },
+]
+
[[package]]
name = "smmap"
version = "5.0.3"
@@ -2863,6 +3617,45 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/81/0d/13d1d239a25cbfb19e740db83143e95c772a1fe10202dda4b76792b114dd/starlette-0.52.1-py3-none-any.whl", hash = "sha256:0029d43eb3d273bc4f83a08720b4912ea4b071087a3b48db01b7c839f7954d74", size = 74272, upload-time = "2026-01-18T13:34:09.188Z" },
]
+[[package]]
+name = "statsmodels"
+version = "0.14.6"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+ { name = "packaging" },
+ { name = "pandas" },
+ { name = "patsy" },
+ { name = "scipy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/0d/81/e8d74b34f85285f7335d30c5e3c2d7c0346997af9f3debf9a0a9a63de184/statsmodels-0.14.6.tar.gz", hash = "sha256:4d17873d3e607d398b85126cd4ed7aad89e4e9d89fc744cdab1af3189a996c2a", size = 20689085, upload-time = "2025-12-05T23:08:39.522Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a9/4d/df4dd089b406accfc3bb5ee53ba29bb3bdf5ae61643f86f8f604baa57656/statsmodels-0.14.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6ad5c2810fc6c684254a7792bf1cbaf1606cdee2a253f8bd259c43135d87cfb4", size = 10121514, upload-time = "2025-12-05T19:28:16.521Z" },
+ { url = "https://files.pythonhosted.org/packages/82/af/ec48daa7f861f993b91a0dcc791d66e1cf56510a235c5cbd2ab991a31d5c/statsmodels-0.14.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:341fa68a7403e10a95c7b6e41134b0da3a7b835ecff1eb266294408535a06eb6", size = 10003346, upload-time = "2025-12-05T19:28:29.568Z" },
+ { url = "https://files.pythonhosted.org/packages/a9/2c/c8f7aa24cd729970728f3f98822fb45149adc216f445a9301e441f7ac760/statsmodels-0.14.6-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bdf1dfe2a3ca56f5529118baf33a13efed2783c528f4a36409b46bbd2d9d48eb", size = 10129872, upload-time = "2025-12-05T23:09:25.724Z" },
+ { url = "https://files.pythonhosted.org/packages/40/c6/9ae8e9b0721e9b6eb5f340c3a0ce8cd7cce4f66e03dd81f80d60f111987f/statsmodels-0.14.6-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a3764ba8195c9baf0925a96da0743ff218067a269f01d155ca3558deed2658ca", size = 10381964, upload-time = "2025-12-05T23:09:41.326Z" },
+ { url = "https://files.pythonhosted.org/packages/28/8c/cf3d30c8c2da78e2ad1f50ade8b7fabec3ff4cdfc56fbc02e097c4577f90/statsmodels-0.14.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9e8d2e519852adb1b420e018f5ac6e6684b2b877478adf7fda2cfdb58f5acb5d", size = 10409611, upload-time = "2025-12-05T23:09:57.131Z" },
+ { url = "https://files.pythonhosted.org/packages/bf/cc/018f14ecb58c6cb89de9d52695740b7d1f5a982aa9ea312483ea3c3d5f77/statsmodels-0.14.6-cp311-cp311-win_amd64.whl", hash = "sha256:2738a00fca51196f5a7d44b06970ace6b8b30289839e4808d656f8a98e35faa7", size = 9580385, upload-time = "2025-12-05T19:28:42.778Z" },
+ { url = "https://files.pythonhosted.org/packages/25/ce/308e5e5da57515dd7cab3ec37ea2d5b8ff50bef1fcc8e6d31456f9fae08e/statsmodels-0.14.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fe76140ae7adc5ff0e60a3f0d56f4fffef484efa803c3efebf2fcd734d72ecb5", size = 10091932, upload-time = "2025-12-05T19:28:55.446Z" },
+ { url = "https://files.pythonhosted.org/packages/05/30/affbabf3c27fb501ec7b5808230c619d4d1a4525c07301074eb4bda92fa9/statsmodels-0.14.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:26d4f0ed3b31f3c86f83a92f5c1f5cbe63fc992cd8915daf28ca49be14463a1c", size = 9997345, upload-time = "2025-12-05T19:29:10.278Z" },
+ { url = "https://files.pythonhosted.org/packages/48/f5/3a73b51e6450c31652c53a8e12e24eac64e3824be816c0c2316e7dbdcb7d/statsmodels-0.14.6-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d8c00a42863e4f4733ac9d078bbfad816249c01451740e6f5053ecc7db6d6368", size = 10058649, upload-time = "2025-12-05T23:10:12.775Z" },
+ { url = "https://files.pythonhosted.org/packages/81/68/dddd76117df2ef14c943c6bbb6618be5c9401280046f4ddfc9fb4596a1b8/statsmodels-0.14.6-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:19b58cf7474aa9e7e3b0771a66537148b2df9b5884fbf156096c0e6c1ff0469d", size = 10339446, upload-time = "2025-12-05T23:10:28.503Z" },
+ { url = "https://files.pythonhosted.org/packages/56/4a/dce451c74c4050535fac1ec0c14b80706d8fc134c9da22db3c8a0ec62c33/statsmodels-0.14.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:81e7dcc5e9587f2567e52deaff5220b175bf2f648951549eae5fc9383b62bc37", size = 10368705, upload-time = "2025-12-05T23:10:44.339Z" },
+ { url = "https://files.pythonhosted.org/packages/60/15/3daba2df40be8b8a9a027d7f54c8dedf24f0d81b96e54b52293f5f7e3418/statsmodels-0.14.6-cp312-cp312-win_amd64.whl", hash = "sha256:b5eb07acd115aa6208b4058211138393a7e6c2cf12b6f213ede10f658f6a714f", size = 9543991, upload-time = "2025-12-05T23:10:58.536Z" },
+ { url = "https://files.pythonhosted.org/packages/81/59/a5aad5b0cc266f5be013db8cde563ac5d2a025e7efc0c328d83b50c72992/statsmodels-0.14.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:47ee7af083623d2091954fa71c7549b8443168f41b7c5dce66510274c50fd73e", size = 10072009, upload-time = "2025-12-05T23:11:14.021Z" },
+ { url = "https://files.pythonhosted.org/packages/53/dd/d8cfa7922fc6dc3c56fa6c59b348ea7de829a94cd73208c6f8202dd33f17/statsmodels-0.14.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:aa60d82e29fcd0a736e86feb63a11d2380322d77a9369a54be8b0965a3985f71", size = 9980018, upload-time = "2025-12-05T23:11:30.907Z" },
+ { url = "https://files.pythonhosted.org/packages/ee/77/0ec96803eba444efd75dba32f2ef88765ae3e8f567d276805391ec2c98c6/statsmodels-0.14.6-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:89ee7d595f5939cc20bf946faedcb5137d975f03ae080f300ebb4398f16a5bd4", size = 10060269, upload-time = "2025-12-05T23:11:46.338Z" },
+ { url = "https://files.pythonhosted.org/packages/10/b9/fd41f1f6af13a1a1212a06bb377b17762feaa6d656947bf666f76300fc05/statsmodels-0.14.6-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:730f3297b26749b216a06e4327fe0be59b8d05f7d594fb6caff4287b69654589", size = 10324155, upload-time = "2025-12-05T23:12:01.805Z" },
+ { url = "https://files.pythonhosted.org/packages/ee/0f/a6900e220abd2c69cd0a07e3ad26c71984be6061415a60e0f17b152ecf08/statsmodels-0.14.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f1c08befa85e93acc992b72a390ddb7bd876190f1360e61d10cf43833463bc9c", size = 10349765, upload-time = "2025-12-05T23:12:18.018Z" },
+ { url = "https://files.pythonhosted.org/packages/98/08/b79f0c614f38e566eebbdcff90c0bcacf3c6ba7a5bbb12183c09c29ca400/statsmodels-0.14.6-cp313-cp313-win_amd64.whl", hash = "sha256:8021271a79f35b842c02a1794465a651a9d06ec2080f76ebc3b7adce77d08233", size = 9540043, upload-time = "2025-12-05T23:12:33.887Z" },
+ { url = "https://files.pythonhosted.org/packages/71/de/09540e870318e0c7b58316561d417be45eff731263b4234fdd2eee3511a8/statsmodels-0.14.6-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:00781869991f8f02ad3610da6627fd26ebe262210287beb59761982a8fa88cae", size = 10069403, upload-time = "2025-12-05T23:12:48.424Z" },
+ { url = "https://files.pythonhosted.org/packages/ab/f0/63c1bfda75dc53cee858006e1f46bd6d6f883853bea1b97949d0087766ca/statsmodels-0.14.6-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:73f305fbf31607b35ce919fae636ab8b80d175328ed38fdc6f354e813b86ee37", size = 9989253, upload-time = "2025-12-05T23:13:05.274Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/98/b0dfb4f542b2033a3341aa5f1bdd97024230a4ad3670c5b0839d54e3dcab/statsmodels-0.14.6-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e443e7077a6e2d3faeea72f5a92c9f12c63722686eb80bb40a0f04e4a7e267ad", size = 10090802, upload-time = "2025-12-05T23:13:20.653Z" },
+ { url = "https://files.pythonhosted.org/packages/34/0e/2408735aca9e764643196212f9069912100151414dd617d39ffc72d77eee/statsmodels-0.14.6-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3414e40c073d725007a6603a18247ab7af3467e1af4a5e5a24e4c27bc26673b4", size = 10337587, upload-time = "2025-12-05T23:13:37.597Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/36/4d44f7035ab3c0b2b6a4c4ebb98dedf36246ccbc1b3e2f51ebcd7ac83abb/statsmodels-0.14.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a518d3f9889ef920116f9fa56d0338069e110f823926356946dae83bc9e33e19", size = 10363350, upload-time = "2025-12-05T23:13:53.08Z" },
+ { url = "https://files.pythonhosted.org/packages/26/33/f1652d0c59fa51de18492ee2345b65372550501ad061daa38f950be390b6/statsmodels-0.14.6-cp314-cp314-win_amd64.whl", hash = "sha256:151b73e29f01fe619dbce7f66d61a356e9d1fe5e906529b78807df9189c37721", size = 9588010, upload-time = "2025-12-05T23:14:07.28Z" },
+]
+
[[package]]
name = "structlog"
version = "24.4.0"
@@ -2881,6 +3674,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d7/c1/eb8f9debc45d3b7918a32ab756658a0904732f75e555402972246b0b8e71/tenacity-9.1.4-py3-none-any.whl", hash = "sha256:6095a360c919085f28c6527de529e76a06ad89b23659fa881ae0649b867a9d55", size = 28926, upload-time = "2026-02-07T10:45:32.24Z" },
]
+[[package]]
+name = "threadpoolctl"
+version = "3.6.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/b7/4d/08c89e34946fce2aec4fbb45c9016efd5f4d7f24af8e5d93296e935631d8/threadpoolctl-3.6.0.tar.gz", hash = "sha256:8ab8b4aa3491d812b623328249fab5302a68d2d71745c8a4c719a2fcaba9f44e", size = 21274, upload-time = "2025-03-13T13:49:23.031Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/32/d5/f9a850d79b0851d1d4ef6456097579a9005b31fea68726a4ae5f2d82ddd9/threadpoolctl-3.6.0-py3-none-any.whl", hash = "sha256:43a0b8fd5a2928500110039e43a5eed8480b918967083ea48dc3ab9f13c4a7fb", size = 18638, upload-time = "2025-03-13T13:49:21.846Z" },
+]
+
[[package]]
name = "tiktoken"
version = "0.12.0"
@@ -3263,6 +4065,23 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c2/14/e2a54fabd4f08cd7af1c07030603c3356b74da07f7cc056e600436edfa17/tzlocal-5.3.1-py3-none-any.whl", hash = "sha256:eb1a66c3ef5847adf7a834f1be0800581b683b5608e74f86ecbcef8ab91bb85d", size = 18026, upload-time = "2025-03-05T21:17:39.857Z" },
]
+[[package]]
+name = "umap-learn"
+version = "0.5.12"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numba" },
+ { name = "numpy" },
+ { name = "pynndescent" },
+ { name = "scikit-learn" },
+ { name = "scipy" },
+ { name = "tqdm" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/02/ee/af4171241117f85c74b5ca6448ea1033cc28d599c13651d67289bacd4083/umap_learn-0.5.12.tar.gz", hash = "sha256:6aff02ecac5f2aad9f3c65ee518d7ae93e1a985ae38721fdcffceee4232c33c7", size = 96672, upload-time = "2026-04-08T20:03:54.012Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1b/98/f63318ccbe75c810011fe9233884c5d348d94d90005de1b79e5f93bef9c0/umap_learn-0.5.12-py3-none-any.whl", hash = "sha256:f2a85d2a2adcb52b541bed9b27a23ca169b56bb1b23283abeebfb8dfb8a42fe5", size = 91849, upload-time = "2026-04-08T20:03:52.561Z" },
+]
+
[[package]]
name = "urllib3"
version = "2.6.3"
@@ -3507,6 +4326,81 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/6f/28/258ebab549c2bf3e64d2b0217b973467394a9cea8c42f70418ca2c5d0d2e/websockets-16.0-py3-none-any.whl", hash = "sha256:1637db62fad1dc833276dded54215f2c7fa46912301a24bd94d45d46a011ceec", size = 171598, upload-time = "2026-01-10T09:23:45.395Z" },
]
+[[package]]
+name = "wrapt"
+version = "2.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/2e/64/925f213fdcbb9baeb1530449ac71a4d57fc361c053d06bf78d0c5c7cd80c/wrapt-2.1.2.tar.gz", hash = "sha256:3996a67eecc2c68fd47b4e3c564405a5777367adfd9b8abb58387b63ee83b21e", size = 81678, upload-time = "2026-03-06T02:53:25.134Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c7/81/60c4471fce95afa5922ca09b88a25f03c93343f759aae0f31fb4412a85c7/wrapt-2.1.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:96159a0ee2b0277d44201c3b5be479a9979cf154e8c82fa5df49586a8e7679bb", size = 60666, upload-time = "2026-03-06T02:52:58.934Z" },
+ { url = "https://files.pythonhosted.org/packages/6b/be/80e80e39e7cb90b006a0eaf11c73ac3a62bbfb3068469aec15cc0bc795de/wrapt-2.1.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:98ba61833a77b747901e9012072f038795de7fc77849f1faa965464f3f87ff2d", size = 61601, upload-time = "2026-03-06T02:53:00.487Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/be/d7c88cd9293c859fc74b232abdc65a229bb953997995d6912fc85af18323/wrapt-2.1.2-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:767c0dbbe76cae2a60dd2b235ac0c87c9cccf4898aef8062e57bead46b5f6894", size = 114057, upload-time = "2026-03-06T02:52:44.08Z" },
+ { url = "https://files.pythonhosted.org/packages/ea/25/36c04602831a4d685d45a93b3abea61eca7fe35dab6c842d6f5d570ef94a/wrapt-2.1.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c691a6bc752c0cc4711cc0c00896fcd0f116abc253609ef64ef930032821842", size = 116099, upload-time = "2026-03-06T02:54:56.74Z" },
+ { url = "https://files.pythonhosted.org/packages/5c/4e/98a6eb417ef551dc277bec1253d5246b25003cf36fdf3913b65cb7657a56/wrapt-2.1.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f3b7d73012ea75aee5844de58c88f44cf62d0d62711e39da5a82824a7c4626a8", size = 112457, upload-time = "2026-03-06T02:53:52.842Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/a6/a6f7186a5297cad8ec53fd7578533b28f795fdf5372368c74bd7e6e9841c/wrapt-2.1.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:577dff354e7acd9d411eaf4bfe76b724c89c89c8fc9b7e127ee28c5f7bcb25b6", size = 115351, upload-time = "2026-03-06T02:53:32.684Z" },
+ { url = "https://files.pythonhosted.org/packages/97/6f/06e66189e721dbebd5cf20e138acc4d1150288ce118462f2fcbff92d38db/wrapt-2.1.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3d7b6fd105f8b24e5bd23ccf41cb1d1099796524bcc6f7fbb8fe576c44befbc9", size = 111748, upload-time = "2026-03-06T02:53:08.455Z" },
+ { url = "https://files.pythonhosted.org/packages/ef/43/4808b86f499a51370fbdbdfa6cb91e9b9169e762716456471b619fca7a70/wrapt-2.1.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:866abdbf4612e0b34764922ef8b1c5668867610a718d3053d59e24a5e5fcfc15", size = 113783, upload-time = "2026-03-06T02:53:02.02Z" },
+ { url = "https://files.pythonhosted.org/packages/91/2c/a3f28b8fa7ac2cefa01cfcaca3471f9b0460608d012b693998cd61ef43df/wrapt-2.1.2-cp311-cp311-win32.whl", hash = "sha256:5a0a0a3a882393095573344075189eb2d566e0fd205a2b6414e9997b1b800a8b", size = 57977, upload-time = "2026-03-06T02:53:27.844Z" },
+ { url = "https://files.pythonhosted.org/packages/3f/c3/2b1c7bd07a27b1db885a2fab469b707bdd35bddf30a113b4917a7e2139d2/wrapt-2.1.2-cp311-cp311-win_amd64.whl", hash = "sha256:64a07a71d2730ba56f11d1a4b91f7817dc79bc134c11516b75d1921a7c6fcda1", size = 60336, upload-time = "2026-03-06T02:54:28.104Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/5c/76ece7b401b088daa6503d6264dd80f9a727df3e6042802de9a223084ea2/wrapt-2.1.2-cp311-cp311-win_arm64.whl", hash = "sha256:b89f095fe98bc12107f82a9f7d570dc83a0870291aeb6b1d7a7d35575f55d98a", size = 58756, upload-time = "2026-03-06T02:53:16.319Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/b6/1db817582c49c7fcbb7df6809d0f515af29d7c2fbf57eb44c36e98fb1492/wrapt-2.1.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ff2aad9c4cda28a8f0653fc2d487596458c2a3f475e56ba02909e950a9efa6a9", size = 61255, upload-time = "2026-03-06T02:52:45.663Z" },
+ { url = "https://files.pythonhosted.org/packages/a2/16/9b02a6b99c09227c93cd4b73acc3678114154ec38da53043c0ddc1fba0dc/wrapt-2.1.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6433ea84e1cfacf32021d2a4ee909554ade7fd392caa6f7c13f1f4bf7b8e8748", size = 61848, upload-time = "2026-03-06T02:53:48.728Z" },
+ { url = "https://files.pythonhosted.org/packages/af/aa/ead46a88f9ec3a432a4832dfedb84092fc35af2d0ba40cd04aea3889f247/wrapt-2.1.2-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:c20b757c268d30d6215916a5fa8461048d023865d888e437fab451139cad6c8e", size = 121433, upload-time = "2026-03-06T02:54:40.328Z" },
+ { url = "https://files.pythonhosted.org/packages/3a/9f/742c7c7cdf58b59085a1ee4b6c37b013f66ac33673a7ef4aaed5e992bc33/wrapt-2.1.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:79847b83eb38e70d93dc392c7c5b587efe65b3e7afcc167aa8abd5d60e8761c8", size = 123013, upload-time = "2026-03-06T02:53:26.58Z" },
+ { url = "https://files.pythonhosted.org/packages/e8/44/2c3dd45d53236b7ed7c646fcf212251dc19e48e599debd3926b52310fafb/wrapt-2.1.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f8fba1bae256186a83d1875b2b1f4e2d1242e8fac0f58ec0d7e41b26967b965c", size = 117326, upload-time = "2026-03-06T02:53:11.547Z" },
+ { url = "https://files.pythonhosted.org/packages/74/e2/b17d66abc26bd96f89dec0ecd0ef03da4a1286e6ff793839ec431b9fae57/wrapt-2.1.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e3d3b35eedcf5f7d022291ecd7533321c4775f7b9cd0050a31a68499ba45757c", size = 121444, upload-time = "2026-03-06T02:54:09.5Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/62/e2977843fdf9f03daf1586a0ff49060b1b2fc7ff85a7ea82b6217c1ae36e/wrapt-2.1.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:6f2c5390460de57fa9582bc8a1b7a6c86e1a41dfad74c5225fc07044c15cc8d1", size = 116237, upload-time = "2026-03-06T02:54:03.884Z" },
+ { url = "https://files.pythonhosted.org/packages/88/dd/27fc67914e68d740bce512f11734aec08696e6b17641fef8867c00c949fc/wrapt-2.1.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7dfa9f2cf65d027b951d05c662cc99ee3bd01f6e4691ed39848a7a5fffc902b2", size = 120563, upload-time = "2026-03-06T02:53:20.412Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/9f/b750b3692ed2ef4705cb305bd68858e73010492b80e43d2a4faa5573cbe7/wrapt-2.1.2-cp312-cp312-win32.whl", hash = "sha256:eba8155747eb2cae4a0b913d9ebd12a1db4d860fc4c829d7578c7b989bd3f2f0", size = 58198, upload-time = "2026-03-06T02:53:37.732Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/b2/feecfe29f28483d888d76a48f03c4c4d8afea944dbee2b0cd3380f9df032/wrapt-2.1.2-cp312-cp312-win_amd64.whl", hash = "sha256:1c51c738d7d9faa0b3601708e7e2eda9bf779e1b601dce6c77411f2a1b324a63", size = 60441, upload-time = "2026-03-06T02:52:47.138Z" },
+ { url = "https://files.pythonhosted.org/packages/44/e1/e328f605d6e208547ea9fd120804fcdec68536ac748987a68c47c606eea8/wrapt-2.1.2-cp312-cp312-win_arm64.whl", hash = "sha256:c8e46ae8e4032792eb2f677dbd0d557170a8e5524d22acc55199f43efedd39bf", size = 58836, upload-time = "2026-03-06T02:53:22.053Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/7a/d936840735c828b38d26a854e85d5338894cda544cb7a85a9d5b8b9c4df7/wrapt-2.1.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:787fd6f4d67befa6fe2abdffcbd3de2d82dfc6fb8a6d850407c53332709d030b", size = 61259, upload-time = "2026-03-06T02:53:41.922Z" },
+ { url = "https://files.pythonhosted.org/packages/5e/88/9a9b9a90ac8ca11c2fdb6a286cb3a1fc7dd774c00ed70929a6434f6bc634/wrapt-2.1.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4bdf26e03e6d0da3f0e9422fd36bcebf7bc0eeb55fdf9c727a09abc6b9fe472e", size = 61851, upload-time = "2026-03-06T02:52:48.672Z" },
+ { url = "https://files.pythonhosted.org/packages/03/a9/5b7d6a16fd6533fed2756900fc8fc923f678179aea62ada6d65c92718c00/wrapt-2.1.2-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:bbac24d879aa22998e87f6b3f481a5216311e7d53c7db87f189a7a0266dafffb", size = 121446, upload-time = "2026-03-06T02:54:14.013Z" },
+ { url = "https://files.pythonhosted.org/packages/45/bb/34c443690c847835cfe9f892be78c533d4f32366ad2888972c094a897e39/wrapt-2.1.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:16997dfb9d67addc2e3f41b62a104341e80cac52f91110dece393923c0ebd5ca", size = 123056, upload-time = "2026-03-06T02:54:10.829Z" },
+ { url = "https://files.pythonhosted.org/packages/93/b9/ff205f391cb708f67f41ea148545f2b53ff543a7ac293b30d178af4d2271/wrapt-2.1.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:162e4e2ba7542da9027821cb6e7c5e068d64f9a10b5f15512ea28e954893a267", size = 117359, upload-time = "2026-03-06T02:53:03.623Z" },
+ { url = "https://files.pythonhosted.org/packages/1f/3d/1ea04d7747825119c3c9a5e0874a40b33594ada92e5649347c457d982805/wrapt-2.1.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f29c827a8d9936ac320746747a016c4bc66ef639f5cd0d32df24f5eacbf9c69f", size = 121479, upload-time = "2026-03-06T02:53:45.844Z" },
+ { url = "https://files.pythonhosted.org/packages/78/cc/ee3a011920c7a023b25e8df26f306b2484a531ab84ca5c96260a73de76c0/wrapt-2.1.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:a9dd9813825f7ecb018c17fd147a01845eb330254dff86d3b5816f20f4d6aaf8", size = 116271, upload-time = "2026-03-06T02:54:46.356Z" },
+ { url = "https://files.pythonhosted.org/packages/98/fd/e5ff7ded41b76d802cf1191288473e850d24ba2e39a6ec540f21ae3b57cb/wrapt-2.1.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6f8dbdd3719e534860d6a78526aafc220e0241f981367018c2875178cf83a413", size = 120573, upload-time = "2026-03-06T02:52:50.163Z" },
+ { url = "https://files.pythonhosted.org/packages/47/c5/242cae3b5b080cd09bacef0591691ba1879739050cc7c801ff35c8886b66/wrapt-2.1.2-cp313-cp313-win32.whl", hash = "sha256:5c35b5d82b16a3bc6e0a04349b606a0582bc29f573786aebe98e0c159bc48db6", size = 58205, upload-time = "2026-03-06T02:53:47.494Z" },
+ { url = "https://files.pythonhosted.org/packages/12/69/c358c61e7a50f290958809b3c61ebe8b3838ea3e070d7aac9814f95a0528/wrapt-2.1.2-cp313-cp313-win_amd64.whl", hash = "sha256:f8bc1c264d8d1cf5b3560a87bbdd31131573eb25f9f9447bb6252b8d4c44a3a1", size = 60452, upload-time = "2026-03-06T02:53:30.038Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/66/c8a6fcfe321295fd8c0ab1bd685b5a01462a9b3aa2f597254462fc2bc975/wrapt-2.1.2-cp313-cp313-win_arm64.whl", hash = "sha256:3beb22f674550d5634642c645aba4c72a2c66fb185ae1aebe1e955fae5a13baf", size = 58842, upload-time = "2026-03-06T02:52:52.114Z" },
+ { url = "https://files.pythonhosted.org/packages/da/55/9c7052c349106e0b3f17ae8db4b23a691a963c334de7f9dbd60f8f74a831/wrapt-2.1.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0fc04bc8664a8bc4c8e00b37b5355cffca2535209fba1abb09ae2b7c76ddf82b", size = 63075, upload-time = "2026-03-06T02:53:19.108Z" },
+ { url = "https://files.pythonhosted.org/packages/09/a8/ce7b4006f7218248dd71b7b2b732d0710845a0e49213b18faef64811ffef/wrapt-2.1.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:a9b9d50c9af998875a1482a038eb05755dfd6fe303a313f6a940bb53a83c3f18", size = 63719, upload-time = "2026-03-06T02:54:33.452Z" },
+ { url = "https://files.pythonhosted.org/packages/e4/e5/2ca472e80b9e2b7a17f106bb8f9df1db11e62101652ce210f66935c6af67/wrapt-2.1.2-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2d3ff4f0024dd224290c0eabf0240f1bfc1f26363431505fb1b0283d3b08f11d", size = 152643, upload-time = "2026-03-06T02:52:42.721Z" },
+ { url = "https://files.pythonhosted.org/packages/36/42/30f0f2cefca9d9cbf6835f544d825064570203c3e70aa873d8ae12e23791/wrapt-2.1.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3278c471f4468ad544a691b31bb856374fbdefb7fee1a152153e64019379f015", size = 158805, upload-time = "2026-03-06T02:54:25.441Z" },
+ { url = "https://files.pythonhosted.org/packages/bb/67/d08672f801f604889dcf58f1a0b424fe3808860ede9e03affc1876b295af/wrapt-2.1.2-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a8914c754d3134a3032601c6984db1c576e6abaf3fc68094bb8ab1379d75ff92", size = 145990, upload-time = "2026-03-06T02:53:57.456Z" },
+ { url = "https://files.pythonhosted.org/packages/68/a7/fd371b02e73babec1de6ade596e8cd9691051058cfdadbfd62a5898f3295/wrapt-2.1.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:ff95d4264e55839be37bafe1536db2ab2de19da6b65f9244f01f332b5286cfbf", size = 155670, upload-time = "2026-03-06T02:54:55.309Z" },
+ { url = "https://files.pythonhosted.org/packages/86/2d/9fe0095dfdb621009f40117dcebf41d7396c2c22dca6eac779f4c007b86c/wrapt-2.1.2-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:76405518ca4e1b76fbb1b9f686cff93aebae03920cc55ceeec48ff9f719c5f67", size = 144357, upload-time = "2026-03-06T02:54:24.092Z" },
+ { url = "https://files.pythonhosted.org/packages/0e/b6/ec7b4a254abbe4cde9fa15c5d2cca4518f6b07d0f1b77d4ee9655e30280e/wrapt-2.1.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c0be8b5a74c5824e9359b53e7e58bef71a729bacc82e16587db1c4ebc91f7c5a", size = 150269, upload-time = "2026-03-06T02:53:31.268Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/6b/2fabe8ebf148f4ee3c782aae86a795cc68ffe7d432ef550f234025ce0cfa/wrapt-2.1.2-cp313-cp313t-win32.whl", hash = "sha256:f01277d9a5fc1862f26f7626da9cf443bebc0abd2f303f41c5e995b15887dabd", size = 59894, upload-time = "2026-03-06T02:54:15.391Z" },
+ { url = "https://files.pythonhosted.org/packages/ca/fb/9ba66fc2dedc936de5f8073c0217b5d4484e966d87723415cc8262c5d9c2/wrapt-2.1.2-cp313-cp313t-win_amd64.whl", hash = "sha256:84ce8f1c2104d2f6daa912b1b5b039f331febfeee74f8042ad4e04992bd95c8f", size = 63197, upload-time = "2026-03-06T02:54:41.943Z" },
+ { url = "https://files.pythonhosted.org/packages/c0/1c/012d7423c95d0e337117723eb8ecf73c622ce15a97847e84cf3f8f26cd7e/wrapt-2.1.2-cp313-cp313t-win_arm64.whl", hash = "sha256:a93cd767e37faeddbe07d8fc4212d5cba660af59bdb0f6372c93faaa13e6e679", size = 60363, upload-time = "2026-03-06T02:54:48.093Z" },
+ { url = "https://files.pythonhosted.org/packages/39/25/e7ea0b417db02bb796182a5316398a75792cd9a22528783d868755e1f669/wrapt-2.1.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:1370e516598854e5b4366e09ce81e08bfe94d42b0fd569b88ec46cc56d9164a9", size = 61418, upload-time = "2026-03-06T02:53:55.706Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/0f/fa539e2f6a770249907757eaeb9a5ff4deb41c026f8466c1c6d799088a9b/wrapt-2.1.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:6de1a3851c27e0bd6a04ca993ea6f80fc53e6c742ee1601f486c08e9f9b900a9", size = 61914, upload-time = "2026-03-06T02:52:53.37Z" },
+ { url = "https://files.pythonhosted.org/packages/53/37/02af1867f5b1441aaeda9c82deed061b7cd1372572ddcd717f6df90b5e93/wrapt-2.1.2-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:de9f1a2bbc5ac7f6012ec24525bdd444765a2ff64b5985ac6e0692144838542e", size = 120417, upload-time = "2026-03-06T02:54:30.74Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/b7/0138a6238c8ba7476c77cf786a807f871672b37f37a422970342308276e7/wrapt-2.1.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:970d57ed83fa040d8b20c52fe74a6ae7e3775ae8cff5efd6a81e06b19078484c", size = 122797, upload-time = "2026-03-06T02:54:51.539Z" },
+ { url = "https://files.pythonhosted.org/packages/e1/ad/819ae558036d6a15b7ed290d5b14e209ca795dd4da9c58e50c067d5927b0/wrapt-2.1.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3969c56e4563c375861c8df14fa55146e81ac11c8db49ea6fb7f2ba58bc1ff9a", size = 117350, upload-time = "2026-03-06T02:54:37.651Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/2d/afc18dc57a4600a6e594f77a9ae09db54f55ba455440a54886694a84c71b/wrapt-2.1.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:57d7c0c980abdc5f1d98b11a2aa3bb159790add80258c717fa49a99921456d90", size = 121223, upload-time = "2026-03-06T02:54:35.221Z" },
+ { url = "https://files.pythonhosted.org/packages/b9/5b/5ec189b22205697bc56eb3b62aed87a1e0423e9c8285d0781c7a83170d15/wrapt-2.1.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:776867878e83130c7a04237010463372e877c1c994d449ca6aaafeab6aab2586", size = 116287, upload-time = "2026-03-06T02:54:19.654Z" },
+ { url = "https://files.pythonhosted.org/packages/f7/2d/f84939a7c9b5e6cdd8a8d0f6a26cabf36a0f7e468b967720e8b0cd2bdf69/wrapt-2.1.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:fab036efe5464ec3291411fabb80a7a39e2dd80bae9bcbeeca5087fdfa891e19", size = 119593, upload-time = "2026-03-06T02:54:16.697Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/fe/ccd22a1263159c4ac811ab9374c061bcb4a702773f6e06e38de5f81a1bdc/wrapt-2.1.2-cp314-cp314-win32.whl", hash = "sha256:e6ed62c82ddf58d001096ae84ce7f833db97ae2263bff31c9b336ba8cfe3f508", size = 58631, upload-time = "2026-03-06T02:53:06.498Z" },
+ { url = "https://files.pythonhosted.org/packages/65/0a/6bd83be7bff2e7efaac7b4ac9748da9d75a34634bbbbc8ad077d527146df/wrapt-2.1.2-cp314-cp314-win_amd64.whl", hash = "sha256:467e7c76315390331c67073073d00662015bb730c566820c9ca9b54e4d67fd04", size = 60875, upload-time = "2026-03-06T02:53:50.252Z" },
+ { url = "https://files.pythonhosted.org/packages/6c/c0/0b3056397fe02ff80e5a5d72d627c11eb885d1ca78e71b1a5c1e8c7d45de/wrapt-2.1.2-cp314-cp314-win_arm64.whl", hash = "sha256:da1f00a557c66225d53b095a97eace0fc5349e3bfda28fa34ffae238978ee575", size = 59164, upload-time = "2026-03-06T02:53:59.128Z" },
+ { url = "https://files.pythonhosted.org/packages/71/ed/5d89c798741993b2371396eb9d4634f009ff1ad8a6c78d366fe2883ea7a6/wrapt-2.1.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:62503ffbc2d3a69891cf29beeaccdb4d5e0a126e2b6a851688d4777e01428dbb", size = 63163, upload-time = "2026-03-06T02:52:54.873Z" },
+ { url = "https://files.pythonhosted.org/packages/c6/8c/05d277d182bf36b0a13d6bd393ed1dec3468a25b59d01fba2dd70fe4d6ae/wrapt-2.1.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c7e6cd120ef837d5b6f860a6ea3745f8763805c418bb2f12eeb1fa6e25f22d22", size = 63723, upload-time = "2026-03-06T02:52:56.374Z" },
+ { url = "https://files.pythonhosted.org/packages/f4/27/6c51ec1eff4413c57e72d6106bb8dec6f0c7cdba6503d78f0fa98767bcc9/wrapt-2.1.2-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3769a77df8e756d65fbc050333f423c01ae012b4f6731aaf70cf2bef61b34596", size = 152652, upload-time = "2026-03-06T02:53:23.79Z" },
+ { url = "https://files.pythonhosted.org/packages/db/4c/d7dd662d6963fc7335bfe29d512b02b71cdfa23eeca7ab3ac74a67505deb/wrapt-2.1.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a76d61a2e851996150ba0f80582dd92a870643fa481f3b3846f229de88caf044", size = 158807, upload-time = "2026-03-06T02:53:35.742Z" },
+ { url = "https://files.pythonhosted.org/packages/b4/4d/1e5eea1a78d539d346765727422976676615814029522c76b87a95f6bcdd/wrapt-2.1.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6f97edc9842cf215312b75fe737ee7c8adda75a89979f8e11558dfff6343cc4b", size = 146061, upload-time = "2026-03-06T02:52:57.574Z" },
+ { url = "https://files.pythonhosted.org/packages/89/bc/62cabea7695cd12a288023251eeefdcb8465056ddaab6227cb78a2de005b/wrapt-2.1.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:4006c351de6d5007aa33a551f600404ba44228a89e833d2fadc5caa5de8edfbf", size = 155667, upload-time = "2026-03-06T02:53:39.422Z" },
+ { url = "https://files.pythonhosted.org/packages/e9/99/6f2888cd68588f24df3a76572c69c2de28287acb9e1972bf0c83ce97dbc1/wrapt-2.1.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:a9372fc3639a878c8e7d87e1556fa209091b0a66e912c611e3f833e2c4202be2", size = 144392, upload-time = "2026-03-06T02:54:22.41Z" },
+ { url = "https://files.pythonhosted.org/packages/40/51/1dfc783a6c57971614c48e361a82ca3b6da9055879952587bc99fe1a7171/wrapt-2.1.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3144b027ff30cbd2fca07c0a87e67011adb717eb5f5bd8496325c17e454257a3", size = 150296, upload-time = "2026-03-06T02:54:07.848Z" },
+ { url = "https://files.pythonhosted.org/packages/6c/38/cbb8b933a0201076c1f64fc42883b0023002bdc14a4964219154e6ff3350/wrapt-2.1.2-cp314-cp314t-win32.whl", hash = "sha256:3b8d15e52e195813efe5db8cec156eebe339aaf84222f4f4f051a6c01f237ed7", size = 60539, upload-time = "2026-03-06T02:54:00.594Z" },
+ { url = "https://files.pythonhosted.org/packages/82/dd/e5176e4b241c9f528402cebb238a36785a628179d7d8b71091154b3e4c9e/wrapt-2.1.2-cp314-cp314t-win_amd64.whl", hash = "sha256:08ffa54146a7559f5b8df4b289b46d963a8e74ed16ba3687f99896101a3990c5", size = 63969, upload-time = "2026-03-06T02:54:39Z" },
+ { url = "https://files.pythonhosted.org/packages/5c/99/79f17046cf67e4a95b9987ea129632ba8bcec0bc81f3fb3d19bdb0bd60cd/wrapt-2.1.2-cp314-cp314t-win_arm64.whl", hash = "sha256:72aaa9d0d8e4ed0e2e98019cea47a21f823c9dd4b43c7b77bba6679ffcca6a00", size = 60554, upload-time = "2026-03-06T02:53:14.132Z" },
+ { url = "https://files.pythonhosted.org/packages/1a/c7/8528ac2dfa2c1e6708f647df7ae144ead13f0a31146f43c7264b4942bf12/wrapt-2.1.2-py3-none-any.whl", hash = "sha256:b8fd6fa2b2c4e7621808f8c62e8317f4aae56e59721ad933bac5239d913cf0e8", size = 43993, upload-time = "2026-03-06T02:53:12.905Z" },
+]
+
[[package]]
name = "yarl"
version = "1.23.0"