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.

Release v0.2.3 — language support, dead code, human notes, export (#73)

Raghav Chamadiyabaa4a8ac7f3d
diff --git a/README.md b/README.md
index 409283f41..9b8b0d3dd 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. Ten MCP tools. One `pip install`.
+Four intelligence layers. Eleven MCP tools. 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. Ten 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 ten 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 eleven precisely designed tools. **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."*
@@ -115,7 +115,7 @@ Add to your Claude Code config (optional, `repowise init` already initializes `.
---
-## Ten MCP tools
+## Eleven 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.
@@ -131,6 +131,7 @@ Most tools are designed around data entities — one module, one file, one symbo
| `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 |
### Tool call comparison — a real task
@@ -274,7 +275,7 @@ repowise dead-code
✗ analytics/v1/tracker.ts file 0.41 recent activity — review first
```
-Conservative by design. `safe_to_delete` requires confidence ≥ 0.70 and excludes dynamically-loaded patterns (`*Plugin`, `*Handler`, `*Adapter`, `*Middleware`). repowise surfaces candidates. Engineers decide.
+Conservative by design. `safe_to_delete` requires confidence ≥ 0.70 and excludes dynamically-loaded patterns (`*Plugin`, `*Handler`, `*Adapter`, `*Middleware`). Dynamic import detection (`importlib.import_module()`, `__import__()`) and framework decorator awareness (Flask/FastAPI/Django routes) further reduce false positives. repowise surfaces candidates. Engineers decide.
---
@@ -317,7 +318,7 @@ 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 | ✅ 10 tools | ❌ | ✅ 3 tools | ✅ | ✅ |
+| MCP server for AI agents | ✅ 11 tools | ❌ | ✅ 3 tools | ✅ | ✅ |
| Auto-generated CLAUDE.md | ✅ | ❌ | ❌ | ❌ | ❌ |
| Doc freshness scoring | ✅ | ❌ | ❌ | ⚠️ staleness only | ❌ |
| Incremental updates on commit | ✅ <30s | ✅ | ❌ | ✅ | ✅ |
@@ -395,6 +396,7 @@ repowise generate-claude-md # regenerate CLAUDE.md
# Utilities
repowise export [PATH] # export wiki as markdown files
+repowise export --full --format json # full export with decisions, dead code, hotspots
repowise doctor # check setup, API keys, store drift
repowise doctor --repair # check and fix detected store mismatches
repowise reindex # rebuild vector store (no LLM calls)
@@ -404,13 +406,15 @@ repowise reindex # rebuild vector store (no LLM calls)
## Supported languages
-**Code:** Python · TypeScript · JavaScript · Go · Rust · Java · C · C++ · Ruby · Kotlin
+| 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 |
+| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · SQL · Terraform | Included in the file tree; special handlers extract endpoints/targets where applicable |
-**Config / contracts:** OpenAPI · Protobuf · GraphQL · Dockerfile · GitHub Actions YAML · Makefile
-
-More languages coming soon — Swift, Scala, PHP, 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. PRs welcome. See [Adding a new language](docs/CONTRIBUTING.md#adding-a-new-language).
+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).
---
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index be5a49218..0ebfe3f3f 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -9,6 +9,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
---
+## [0.2.3] — 2026-04-11
+
+### Added
+- **`annotate_file` MCP tool** — attach human-authored notes to any wiki page. Notes survive LLM-driven re-generation and appear in `get_context` responses and the web UI. Pass an empty string to clear notes.
+- **`repowise export --full`** — full JSON export now includes decision records, dead code findings, git hotspots, and per-page provenance metadata (confidence, freshness, model, provider).
+- **Rust import resolution** — `use crate::`, `super::`, and `self::` imports now resolve to local files via crate root detection (`lib.rs`/`main.rs`). External crates mapped to `external:` nodes.
+- **Go import resolution** — `go.mod` module path parsing enables accurate local vs external package classification. Local imports resolve by suffix matching against the module path.
+- **C/C++ parser improvements** — added captures for `template_declaration`, `type_definition` (typedef struct/enum), `preproc_def` (#define), `preproc_function_def`, and forward declarations.
+- **Go parser** — added `const_spec` and `var_spec` captures for package-level constants and variables.
+- **Rust parser** — added `macro_definition` capture for `macro_rules!` macros.
+- **Dynamic import detection** — dead code analysis now scans for `importlib.import_module()` and `__import__()` calls; files in the same package receive reduced confidence (capped at 0.4).
+- **Framework decorator awareness** — Flask, FastAPI, and Django route/endpoint decorators added to `_FRAMEWORK_DECORATORS`. Decorated functions are never flagged as dead code.
+- **`human_notes` column on wiki pages** — persists across re-indexing. Alembic migration `0014_page_human_notes`.
+- **Decision staleness scoring during ingestion** — `compute_staleness()` now runs during `repowise init`, not just `repowise update`.
+
+### Changed
+- **CLAUDE.md template** — replaced imperative "MUST use" / "CRITICAL" language with advisory framing. Added `indexed_commit` display. Made `update_decision_records` optional ("SHOULD for architectural changes").
+- **`get_context` freshness** — freshness data now included by default instead of requiring explicit `include=["freshness"]`.
+- **`get_answer` docstring** — removed "do NOT verify by Read" instruction. High-confidence note changed to "verify cited file paths exist before acting on them".
+- **Token budget caps** — `get_overview` caps knowledge_silos (30), module_pages (20), entry_points (15). `get_why` caps file_commits (10).
+- **Dead code patterns** — expanded `_DEFAULT_DYNAMIC_PATTERNS` with `*Mixin`, `*Command`, `*_view`, `*_endpoint`, `*_route`, `*_callback`, `*_signal`, `*_task`.
+
+### Docs
+- **README** — tool count updated to 11, `annotate_file` added to MCP tools table, `--full` export flag documented, dynamic import detection noted, comparison table updated.
+- **Supported languages** — tiered table with accurate "What works" descriptions per language.
+- Updated USER_GUIDE.md, ARCHITECTURE.md, and deep-dives.md to reflect all changes.
+
+---
+
## [0.2.2] — 2026-04-11
### Added
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 665eb796a..692fbf2ed 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -315,7 +315,7 @@ 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 (10 tools):**
+**MCP tools exposed (11 tools):**
| Tool | What it does |
|------|-------------|
@@ -329,6 +329,7 @@ This is how you connect repowise to Claude Code, Cursor, Cline, Windsurf, and ot
| `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.
@@ -485,6 +486,7 @@ repowise export [PATH]
|------|-------------|
| `--format` | `markdown` (default), `html`, `json` |
| `--output / -o` | Output directory (default: `.repowise/export`) |
+| `--full` | Include decisions, dead code findings, hotspots, and provenance metadata (JSON format only) |
**Examples:**
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md
index 9025c3cc3..7a394df92 100644
--- a/docs/architecture/ARCHITECTURE.md
+++ b/docs/architecture/ARCHITECTURE.md
@@ -16,7 +16,7 @@ For per-package detail (installation, full API reference, all CLI flags, file ma
|---------|--------|----------------|
| `packages/core` | [`packages/core/README.md`](../packages/core/README.md) | Ingestion, generation, persistence, providers — all key classes with code examples |
| `packages/cli` | [`packages/cli/README.md`](../packages/cli/README.md) | All 10 CLI commands with every flag documented |
-| `packages/server` | [`packages/server/README.md`](../packages/server/README.md) | All REST API endpoints, 10 MCP tools, webhook setup, scheduler jobs |
+| `packages/server` | [`packages/server/README.md`](../packages/server/README.md) | All REST API endpoints, 11 MCP tools, webhook setup, scheduler jobs |
| `packages/web` | [`packages/web/README.md`](../packages/web/README.md) | Every frontend file with purpose — API client, hooks, components, pages |
---
@@ -959,9 +959,10 @@ affected files, modules, tags, and evidence commits. Deduplication key:
### Staleness Tracking
-Decisions have a `staleness_score` (0.0 = fresh, 1.0 = very stale) recomputed on every
-`repowise update`. Staleness rises when affected files receive commits after the decision
-was recorded. Decisions with `staleness_score > 0.5` are flagged as stale.
+Decisions have a `staleness_score` (0.0 = fresh, 1.0 = very stale) computed during
+`repowise init` and recomputed on every `repowise update`. Staleness rises when affected
+files receive commits after the decision was recorded. Decisions with `staleness_score > 0.5`
+are flagged as stale.
### MCP Tools
@@ -1008,7 +1009,7 @@ and supports two transports:
- **stdio** — for Claude Code, Cursor, Cline (add to their MCP config)
- **SSE** — for web-based MCP clients (served on port 7338)
-### Tools (9 total)
+### Tools (11 total)
| Tool | What it answers | When to call |
|------|----------------|-------------|
@@ -1021,6 +1022,9 @@ and supports two transports:
| `get_dependency_path(from, to)` | Connection path between two files/modules in the dependency graph. | When you need to understand how two things are connected. |
| `get_dead_code` | Dead/unused code findings sorted by confidence and cleanup impact. | Before cleanup tasks. |
| `get_architecture_diagram` | Mermaid diagram for repo or specific module. | For documentation or presentation. |
+| `get_answer` | One-call RAG: confidence-gated synthesis with cited answers and question cache. | First call on any code question — collapses search → read → reason. |
+| `get_symbol` | Resolve a qualified symbol id to source body, signature, and docstring. | When the question names a specific class, function, or method. |
+| `annotate_file` | Attach human-authored notes to a wiki page — survives re-indexing. | Adding rationale, known issues, or context the LLM shouldn't overwrite. |
### Auto-generated Config
@@ -1112,7 +1116,7 @@ file, tokens used, estimated cost, estimated time remaining).
repowise includes an interactive chat interface that lets users ask questions about
their codebase and receive answers grounded in the wiki, dependency graph, git
history, and architectural decisions. The chat agent uses whichever LLM provider
-the user has configured and has access to all 10 MCP tools.
+the user has configured and has access to all 11 MCP tools.
See [`docs/CHAT.md`](CHAT.md) for the full technical reference covering the
backend agentic loop, SSE streaming protocol, provider abstraction extensions,
@@ -1123,7 +1127,7 @@ database schema, frontend component architecture, and artifact rendering system.
- **Provider-agnostic** — the chat agent goes through the same provider abstraction
as documentation generation. A `ChatProvider` protocol extends `BaseProvider` with
`stream_chat()` for streaming + tool use without breaking existing callers.
-- **Tool reuse** — the 10 MCP tools are called directly as Python functions (no
+- **Tool reuse** — the 11 MCP tools are called directly as Python functions (no
subprocess round-trip). Tool schemas are defined once in `chat_tools.py` and
fed to both the LLM and the executor.
- **SSE streaming** — `POST /api/repos/{repo_id}/chat/messages` runs the agentic
diff --git a/docs/architecture/deep-dives.md b/docs/architecture/deep-dives.md
index 6e0ad662f..b43f9b683 100644
--- a/docs/architecture/deep-dives.md
+++ b/docs/architecture/deep-dives.md
@@ -43,9 +43,9 @@ For each node in the dependency graph:
**Why in_degree alone isn't enough:**
-Consider `plugin_auth.py`. Nothing imports it directly because the plugin framework loads it dynamically at runtime via `importlib.import_module()`. The graph doesn't capture dynamic imports because they don't appear in the AST as static import statements.
+Consider `plugin_auth.py`. Nothing imports it directly because the plugin framework loads it dynamically at runtime via `importlib.import_module()`. The graph doesn't capture dynamic imports as edges because they don't appear in the AST as static import statements.
-Repowise handles this with multiple layers of filtering:
+Repowise handles this with multiple layers of filtering, including **dynamic import detection** — files in the same package as `importlib.import_module()` or `__import__()` calls automatically get reduced confidence scores:
**Layer 1 — Structural exclusions** (never flagged):
@@ -69,13 +69,33 @@ _DEFAULT_DYNAMIC_PATTERNS = (
"*Handler", # Event handler registration
"*Adapter", # Adapter patterns
"*Middleware", # Middleware chains
+ "*Mixin", # Mixin classes
+ "*Command", # CLI/management commands
"register_*", # Registration functions
"on_*", # Event callbacks
+ "*_view", # Django/Flask views
+ "*_endpoint", # API endpoints
+ "*_route", # Route handlers
+ "*_callback", # Callback functions
+ "*_signal", # Signal handlers
+ "*_task", # Background tasks
)
```
Files matching these patterns aren't marked `safe_to_delete` even if confidence is high, because they're likely loaded dynamically.
+**Layer 2b — Framework decorator awareness:**
+
+Functions decorated with framework-specific route/endpoint decorators are never flagged as dead code:
+
+- Flask: `@app.route`, `@blueprint.route`, `@app.before_request`, `@app.errorhandler`, etc.
+- FastAPI: `@app.get`, `@app.post`, `@router.get`, `@app.on_event`, `@app.middleware`, etc.
+- Django: `@admin.register`, `@receiver`, `@login_required`, etc.
+
+**Layer 2c — Dynamic import detection:**
+
+Files in the same package as `importlib.import_module()` or `__import__()` calls automatically receive a reduced confidence score (capped at 0.4), since they may be loaded dynamically at runtime.
+
**Layer 3 — Confidence scoring with git metadata:**
This is where it gets interesting. A file with zero importers might be dead, or it might be actively used via dynamic loading. Git history helps distinguish:
diff --git a/packages/cli/src/repowise/cli/__init__.py b/packages/cli/src/repowise/cli/__init__.py
index ccc1e3fe1..f53d600ae 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.2"
+__version__ = "0.2.3"
diff --git a/packages/cli/src/repowise/cli/commands/export_cmd.py b/packages/cli/src/repowise/cli/commands/export_cmd.py
index e9f091475..2a37e7b2a 100644
--- a/packages/cli/src/repowise/cli/commands/export_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/export_cmd.py
@@ -33,10 +33,18 @@ from repowise.cli.helpers import (
default=None,
help="Output directory (default: .repowise/export).",
)
+ "--full",
+ "full_export",
+ is_flag=True,
+ default=False,
+ help="Include decisions, dead code, git metadata, and provenance in JSON export.",
+)
def export_command(
path: str | None,
fmt: str,
output_dir: str | None,
+ full_export: bool = False,
) -> None:
"""Export wiki pages to files."""
repo_path = resolve_repo_path(path)
@@ -45,7 +53,9 @@ def export_command(
out = repo_path / ".repowise" / "export" if output_dir is None else Path(output_dir).resolve()
out.mkdir(parents=True, exist_ok=True)
- # Load pages from DB
+ # Load pages (and optionally decisions/dead-code/git) from DB
+ extra_data: dict = {}
+
async def _load_pages():
from repowise.core.persistence import (
create_engine,
@@ -66,6 +76,73 @@ def export_command(
return []
pages = await list_pages(session, repo.id, limit=10000)
+ if full_export and fmt == "json":
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import (
+ DeadCodeFinding,
+ DecisionRecord,
+ GitMetadata,
+ )
+
+ # Decisions
+ dr = await session.execute(
+ select(DecisionRecord).where(
+ DecisionRecord.repository_id == repo.id
+ )
+ )
+ extra_data["decisions"] = [
+ {
+ "title": d.title,
+ "status": d.status,
+ "decision": d.decision,
+ "rationale": d.rationale,
+ "confidence": d.confidence,
+ "staleness_score": d.staleness_score,
+ "source": d.source,
+ "affected_files": json.loads(d.affected_files_json),
+ "created_at": d.created_at.isoformat() if d.created_at else None,
+ }
+ for d in dr.scalars().all()
+ ]
+
+ # Dead code findings
+ dc = await session.execute(
+ select(DeadCodeFinding).where(
+ DeadCodeFinding.repository_id == repo.id
+ )
+ )
+ extra_data["dead_code"] = [
+ {
+ "file_path": f.file_path,
+ "symbol_name": f.symbol_name,
+ "finding_type": f.finding_type,
+ "confidence": f.confidence,
+ "safe_to_delete": f.safe_to_delete,
+ }
+ for f in dc.scalars().all()
+ ]
+
+ # Git metadata (hotspots)
+ gm = await session.execute(
+ select(GitMetadata)
+ .where(
+ GitMetadata.repository_id == repo.id,
+ GitMetadata.is_hotspot == True, # noqa: E712
+ )
+ .limit(50)
+ )
+ extra_data["hotspots"] = [
+ {
+ "file_path": g.file_path,
+ "churn_percentile": g.churn_percentile,
+ "commit_count_90d": g.commit_count_90d,
+ "primary_owner": g.primary_owner_name,
+ "bus_factor": g.bus_factor,
+ }
+ for g in gm.scalars().all()
+ ]
+
await engine.dispose()
return pages
@@ -143,17 +220,27 @@ def export_command(
elif fmt == "json":
data = []
for page in pages:
- data.append(
- {
- "page_id": page.id,
- "page_type": page.page_type,
- "title": page.title,
- "content": page.content,
- "target_path": page.target_path,
- }
- )
+ entry: dict = {
+ "page_id": page.id,
+ "page_type": page.page_type,
+ "title": page.title,
+ "content": page.content,
+ "target_path": page.target_path,
+ }
+ if full_export:
+ entry["confidence"] = page.confidence
+ entry["freshness_status"] = page.freshness_status
+ entry["version"] = page.version
+ entry["model_name"] = getattr(page, "model_name", None)
+ entry["provider_name"] = getattr(page, "provider_name", None)
+ data.append(entry)
progress.advance(task)
+
+ export_obj: dict = {"pages": data}
+ if full_export and extra_data:
+ export_obj.update(extra_data)
+
filepath = out / "wiki_pages.json"
- filepath.write_text(json.dumps(data, indent=2), encoding="utf-8")
+ filepath.write_text(json.dumps(export_obj, indent=2), encoding="utf-8")
console.print(f"[bold green]Exported {len(pages)} pages to {out}[/bold green]")
diff --git a/packages/core/alembic/versions/0014_page_human_notes.py b/packages/core/alembic/versions/0014_page_human_notes.py
new file mode 100644
index 000000000..e3161494b
--- /dev/null
+++ b/packages/core/alembic/versions/0014_page_human_notes.py
@@ -0,0 +1,30 @@
+"""Add human_notes column to wiki_pages for human-in-the-loop annotations.
+
+Allows developers to attach notes, rationale, or context that survives
+LLM-driven regeneration. The column is nullable and preserved on upsert.
+
+Revision ID: 0014
+Revises: 0013
+Create Date: 2026-04-11
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0014"
+down_revision: str | None = "0013"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column("wiki_pages", sa.Column("human_notes", sa.Text(), nullable=True))
+
+
+def downgrade() -> None:
+ op.drop_column("wiki_pages", "human_notes")
diff --git a/packages/core/src/repowise/core/__init__.py b/packages/core/src/repowise/core/__init__.py
index 518e3b035..db3ddfd2e 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.2"
+__version__ = "0.2.3"
diff --git a/packages/core/src/repowise/core/analysis/dead_code.py b/packages/core/src/repowise/core/analysis/dead_code.py
index b1c2d8c37..c01798866 100644
--- a/packages/core/src/repowise/core/analysis/dead_code.py
+++ b/packages/core/src/repowise/core/analysis/dead_code.py
@@ -98,8 +98,26 @@ _NEVER_FLAG_PATTERNS = (
"*vitest.config.*",
)
-# Decorator patterns that indicate framework usage
-_FRAMEWORK_DECORATORS = ("pytest.fixture", "pytest.mark")
+# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)
+_FRAMEWORK_DECORATORS = (
+ "pytest.fixture",
+ "pytest.mark",
+ # Flask
+ "app.route",
+ "blueprint.route",
+ "bp.route",
+ # FastAPI
+ "router.get",
+ "router.post",
+ "router.put",
+ "router.delete",
+ "router.patch",
+ "app.get",
+ "app.post",
+ # Django
+ "admin.register",
+ "receiver",
+)
# Default dynamic patterns (plugins, handlers, etc.)
_DEFAULT_DYNAMIC_PATTERNS = (
@@ -107,8 +125,17 @@ _DEFAULT_DYNAMIC_PATTERNS = (
"*Handler",
"*Adapter",
"*Middleware",
+ "*Mixin",
+ "*Command",
"register_*",
"on_*",
+ # Common route/view patterns
+ "*_view",
+ "*_endpoint",
+ "*_route",
+ "*_callback",
+ "*_signal",
+ "*_task",
)
# Path segments that indicate test fixture / sample data directories.
@@ -141,13 +168,47 @@ class DeadCodeAnalyzer:
All analysis is graph traversal + SQL. No LLM calls.
"""
+ # Patterns in source that indicate dynamic/runtime imports.
+ _DYNAMIC_IMPORT_MARKERS = (
+ "importlib.import_module",
+ "__import__(",
+ "importlib.reload",
+ "pkgutil.iter_modules",
+ )
+
def __init__(
self,
graph: Any, # nx.DiGraph
git_meta_map: dict | None = None,
+ parsed_files: dict | None = None,
) -> None:
self.graph = graph
self.git_meta_map = git_meta_map or {}
+ self._dynamic_import_files = self._find_dynamic_import_files(parsed_files or {})
+
+ @classmethod
+ def _find_dynamic_import_files(cls, parsed_files: dict) -> set[str]:
+ """Return set of file paths that contain dynamic import calls.
+
+ When a repo uses ``importlib.import_module`` or ``__import__``,
+ unreachable modules in the same package may be loaded at runtime.
+ We use this to lower confidence on those findings.
+ """
+ result: set[str] = set()
+ for path, pf in parsed_files.items():
+ try:
+ abs_path = getattr(pf, "file_info", None)
+ if abs_path is None:
+ continue
+ src_path = Path(abs_path.abs_path)
+ if src_path.suffix != ".py":
+ continue
+ source = src_path.read_text(errors="ignore")
+ if any(marker in source for marker in cls._DYNAMIC_IMPORT_MARKERS):
+ result.add(path)
+ except Exception:
+ continue
+ return result
def analyze(self, config: dict | None = None) -> DeadCodeReport:
"""Full analysis. Returns report with all findings."""
@@ -300,6 +361,15 @@ class DeadCodeAnalyzer:
else:
confidence = 0.4
+ # Reduce confidence when dynamic imports exist in the same package —
+ # importlib.import_module / __import__ may load this file at runtime.
+ if self._dynamic_import_files:
+ node_pkg = str(Path(node).parent)
+ for dif in self._dynamic_import_files:
+ if str(Path(dif).parent) == node_pkg:
+ confidence = min(confidence, 0.4)
+ break
+
# safe_to_delete only if confidence >= 0.7 AND not matching dynamic patterns
safe = confidence >= 0.7
if safe and self._matches_dynamic_patterns(node, dynamic_patterns):
@@ -308,6 +378,8 @@ class DeadCodeAnalyzer:
evidence = ["in_degree=0 (no files import this)"]
if commit_90d == 0:
evidence.append("No commits in last 90 days")
+ if self._dynamic_import_files and confidence <= 0.4:
+ evidence.append("Package uses dynamic imports (importlib/__import__)")
return DeadCodeFindingData(
kind=DeadCodeKind.UNREACHABLE_FILE,
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 b0e43cf4f..5761a84b8 100644
--- a/packages/core/src/repowise/core/generation/editor_files/data.py
+++ b/packages/core/src/repowise/core/generation/editor_files/data.py
@@ -44,6 +44,7 @@ class DecisionSummary:
class EditorFileData:
repo_name: str
indexed_at: str # date only: "2026-03-28"
+ indexed_commit: str # short SHA of HEAD at index time, e.g. "a1b2c3d"
architecture_summary: str # 2-4 sentences from repo_overview page
key_modules: list[KeyModule] = field(default_factory=list)
entry_points: list[str] = field(default_factory=list)
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 bd3891cf3..2de6c26a7 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -7,6 +7,7 @@ Uses the existing CRUD layer where possible; raw selects for aggregate queries.
from __future__ import annotations
import re
+import subprocess
from datetime import UTC, datetime
from pathlib import Path
@@ -52,6 +53,7 @@ class EditorFileDataFetcher:
return EditorFileData(
repo_name=repo_name,
indexed_at=datetime.now(UTC).strftime("%Y-%m-%d"),
+ indexed_commit=_get_head_short_sha(self._repo_path),
architecture_summary=await self._get_architecture_summary(),
key_modules=await self._get_key_modules(),
entry_points=await self._get_entry_points(),
@@ -217,6 +219,21 @@ class EditorFileDataFetcher:
# ------------------------------------------------------------------
+def _get_head_short_sha(repo_path: Path) -> str:
+ """Return the short SHA of HEAD, or empty string if not a git repo."""
+ try:
+ result = subprocess.run(
+ ["git", "rev-parse", "--short", "HEAD"],
+ cwd=repo_path,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ return result.stdout.strip() if result.returncode == 0 else ""
+ except Exception:
+ return ""
+
+
def _extract_sentences(text: str, max_sentences: int) -> str:
"""Return up to *max_sentences* sentences from the start of *text*.
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 9f1111194..a25a872f8 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -1,11 +1,11 @@
## IMPORTANT: Codebase Intelligence Instructions for {{ data.repo_name }}
-> **CRITICAL**: This repository is indexed by [Repowise](https://repowise.dev).
-> You MUST use the repowise MCP tools below instead of reading raw source files.
-> They deliver richer context — documentation, ownership, history, decisions —
-> in a single call. Raw `read_file` calls are a last resort only.
+> This repository is indexed by [Repowise](https://repowise.dev).
+> Use the MCP tools below for orientation, discovery, and enriched context
+> (documentation, ownership, history, decisions). **Always verify against
+> actual source files before making changes** — the index may be stale.
-Last indexed: {{ data.indexed_at }}{% if data.avg_confidence %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% endif %}
+Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.indexed_commit }}){% endif %}{% if data.avg_confidence %}. Confidence: {{ (data.avg_confidence * 100) | int }}%.{% endif %}
{% if data.architecture_summary %}
### Architecture
@@ -50,32 +50,30 @@ Last indexed: {{ data.indexed_at }}{% if data.avg_confidence %}. Confidence: {{
### Repowise MCP Tools
-This project has a Repowise MCP server configured. **ALWAYS use these tools before reading source files** — they provide documentation, ownership, architectural decisions, and risk signals in a single call.
+This project has a Repowise MCP server configured. These tools provide documentation, ownership, architectural decisions, and risk signals. Use them for orientation and discovery — then read actual source to verify before editing.
-**MANDATORY workflow:**
+**Recommended workflow:**
-1. **ALWAYS start with `get_overview()`** on any new task to orient yourself.
-2. **MUST call `get_context(targets=["path/to/file.py"])`** before reading or editing any file — faster and richer than reading source directly.
-3. **MUST call `get_risk(targets=["path/to/file.py"])`** before making changes — especially for hotspot files.
-4. Don't know where something lives? Call `search_codebase(query="authentication flow")` — prefer over grep/find.
-5. Need to understand why code is structured a certain way? **MUST call `get_why(query="why JWT over sessions")`** before any architectural change.
-6. **After completing any code changes**, **MUST call `update_decision_records(action="list")`** to review existing decisions, then:
- - Call `update_decision_records(action="create", title="...", decision="...", rationale="...", affected_files=[...])` to record any new architectural decisions you made.
- - Call `update_decision_records(action="update", decision_id="...", ...)` to update existing decisions affected by your changes.
- - Call `update_decision_records(action="update_status", decision_id="...", status="deprecated")` if your changes invalidate an existing decision.
- **This is not optional** — keeping decision records current is a required part of every coding task.
+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")`.
-| Tool | WHEN you MUST use it |
-|------|----------------------|
-| `get_overview()` | **FIRST call on every new task** |
-| `get_context(targets=[...])` | **Before reading or modifying any file** |
-| `get_risk(targets=[...])` | Before changing files — REQUIRED for hotspots |
-| `get_why(query="...")` | Before architectural changes — REQUIRED |
-| `update_decision_records(action=...)` | **After every coding task** — record and update decisions |
-| `search_codebase(query="...")` | When locating code — prefer over grep/find |
+**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/graph.py b/packages/core/src/repowise/core/ingestion/graph.py
index f86b259a0..1869c9a98 100644
--- a/packages/core/src/repowise/core/ingestion/graph.py
+++ b/packages/core/src/repowise/core/ingestion/graph.py
@@ -121,6 +121,7 @@ class GraphBuilder:
self._repo_path: Path | None = Path(repo_path) if repo_path else None
self._compile_commands_cache: dict[str, dict] | None = None
self._tsconfig_resolver: Any | None = None # TsconfigResolver (lazy import)
+ self._go_module_path: str | None = self._read_go_module_path()
def set_tsconfig_resolver(self, resolver: Any) -> None:
"""Attach a :class:`TsconfigResolver` for TS/JS path-alias resolution."""
@@ -538,9 +539,7 @@ class GraphBuilder:
# --- Go ---
if language == "go":
- # Last segment of the import path is the package name
- stem = module_path.rsplit("/", 1)[-1].lower()
- return self._stem_lookup(stem_map, stem)
+ return self._resolve_go_import(module_path, path_set, stem_map)
# --- C / C++ ---
if language in ("cpp", "c"):
@@ -567,10 +566,190 @@ class GraphBuilder:
stem = Path(module_path).stem.lower()
return self._stem_lookup(stem_map, stem)
+ # --- Rust ---
+ if language == "rust":
+ return self._resolve_rust_import(module_path, importer_path, path_set, stem_map)
+
# --- Generic fallback: stem matching ---
stem = Path(module_path).stem.lower()
return self._stem_lookup(stem_map, stem)
+ # ------------------------------------------------------------------
+ # Go module resolution
+ # ------------------------------------------------------------------
+
+ def _read_go_module_path(self) -> str | None:
+ """Read the ``module`` directive from ``go.mod``, if present."""
+ if self._repo_path is None:
+ return None
+ go_mod = self._repo_path / "go.mod"
+ if not go_mod.is_file():
+ return None
+ try:
+ for line in go_mod.read_text(encoding="utf-8", errors="ignore").splitlines():
+ line = line.strip()
+ if line.startswith("module "):
+ return line.split(None, 1)[1].strip()
+ except Exception:
+ pass
+ return None
+
+ def _resolve_go_import(
+ self,
+ module_path: str,
+ path_set: set[str],
+ stem_map: dict[str, str],
+ ) -> str | None:
+ """Resolve a Go import path.
+
+ If ``go.mod`` declares ``module github.com/org/repo``, then an
+ import ``github.com/org/repo/pkg/util`` maps to ``pkg/util/*.go``
+ in the repository. Unmatched imports are classified as external.
+ """
+ # If we know the module path and the import starts with it,
+ # strip the prefix to get the repo-relative package dir.
+ if self._go_module_path and module_path.startswith(self._go_module_path):
+ suffix = module_path[len(self._go_module_path) :]
+ rel_dir = suffix.lstrip("/")
+ # Find any Go file in that directory
+ for p in path_set:
+ if p.endswith(".go"):
+ p_dir = str(Path(p).parent.as_posix())
+ if p_dir == rel_dir or p_dir.endswith(f"/{rel_dir}"):
+ return p
+ # Try stem matching as fallback for the package name
+ pkg_name = rel_dir.rsplit("/", 1)[-1].lower() if rel_dir else ""
+ if pkg_name:
+ result = self._stem_lookup(stem_map, pkg_name)
+ if result:
+ return result
+
+ # No go.mod match — fall back to stem matching on the last segment
+ stem = module_path.rsplit("/", 1)[-1].lower()
+ result = self._stem_lookup(stem_map, stem)
+ if result:
+ return result
+
+ # External package
+ external_key = f"external:{module_path}"
+ if external_key not in self._graph.nodes:
+ self._graph.add_node(
+ external_key, language="external", symbol_count=0, has_error=False
+ )
+ return external_key
+
+ # ------------------------------------------------------------------
+ # Rust import resolution
+ # ------------------------------------------------------------------
+
+ def _resolve_rust_import(
+ self,
+ module_path: str,
+ importer_path: str,
+ path_set: set[str],
+ stem_map: dict[str, str],
+ ) -> str | None:
+ """Resolve a Rust ``use`` path to a repo-relative file.
+
+ Handles ``crate::``, ``self::``, ``super::`` prefixes by mapping
+ them to filesystem paths, then probing for ``<name>.rs`` or
+ ``<name>/mod.rs``. External crates are classified as ``external:``
+ nodes.
+ """
+ parts = module_path.split("::")
+ if not parts:
+ return None
+
+ prefix = parts[0]
+
+ # --- crate:: — resolve from the crate root ---
+ if prefix == "crate":
+ crate_root = self._find_rust_crate_root(importer_path)
+ return self._probe_rust_path(crate_root, parts[1:], path_set)
+
+ # --- self:: — resolve from the current module's directory ---
+ if prefix == "self":
+ importer_dir = str(Path(importer_path).parent.as_posix())
+ return self._probe_rust_path(importer_dir, parts[1:], path_set)
+
+ # --- super:: — resolve from the parent directory ---
+ if prefix == "super":
+ parent_dir = str(Path(importer_path).parent.parent.as_posix())
+ return self._probe_rust_path(parent_dir, parts[1:], path_set)
+
+ # --- External crate (no prefix or unknown crate name) ---
+ # Check if it might be a local module at the crate root first
+ crate_root = self._find_rust_crate_root(importer_path)
+ resolved = self._probe_rust_path(crate_root, parts, path_set)
+ if resolved is not None:
+ return resolved
+
+ # External crate
+ external_key = f"external:{module_path}"
+ if external_key not in self._graph.nodes:
+ self._graph.add_node(
+ external_key, language="external", symbol_count=0, has_error=False
+ )
+ return external_key
+
+ def _find_rust_crate_root(self, importer_path: str) -> str:
+ """Find the ``src/`` directory containing the importer (Rust crate root).
+
+ Walks up from the importer looking for ``lib.rs`` or ``main.rs``
+ siblings, returning the directory containing them. Falls back
+ to the nearest ``src/`` directory.
+ """
+ parts = Path(importer_path).parts
+ for i in range(len(parts) - 1, -1, -1):
+ candidate_dir = Path(*parts[:i]) if i > 0 else Path(".")
+ for root_file in ("lib.rs", "main.rs"):
+ root_path = (candidate_dir / root_file).as_posix()
+ if root_path in self._parsed_files:
+ return candidate_dir.as_posix()
+ if parts[i] == "src" and i > 0:
+ return candidate_dir.as_posix()
+ return Path(importer_path).parent.as_posix()
+
+ @staticmethod
+ def _probe_rust_path(
+ base_dir: str,
+ path_parts: list[str],
+ path_set: set[str],
+ ) -> str | None:
+ """Probe the file system for a Rust module path.
+
+ For ``[\"models\", \"Calculator\"]`` from base ``src/``, tries:
+ - ``src/models.rs`` (module file)
+ - ``src/models/mod.rs`` (directory module)
+ Then recurses into deeper segments. The last segment is often
+ a symbol name (struct/fn), so we try without it too.
+ """
+ if not path_parts:
+ return None
+
+ base = Path(base_dir)
+
+ # Try progressively deeper path segments — the last N segments
+ # may be symbol names rather than module names.
+ for depth in range(len(path_parts), 0, -1):
+ module_parts = path_parts[:depth]
+ # Build the path: base / part1 / part2 / ... / partN-1
+ module_dir = base
+ for p in module_parts[:-1]:
+ module_dir = module_dir / p
+
+ last = module_parts[-1]
+ # Try <dir>/<last>.rs
+ candidate = (module_dir / f"{last}.rs").as_posix()
+ if candidate in path_set:
+ return candidate
+ # Try <dir>/<last>/mod.rs
+ candidate = (module_dir / last / "mod.rs").as_posix()
+ if candidate in path_set:
+ return candidate
+
+ return None
+
# ------------------------------------------------------------------
# Co-change edges (Phase 5.5)
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 8c4e35f36..1e6e88c67 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -246,6 +246,8 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"function_declaration": "function",
"method_declaration": "method",
"type_spec": "struct", # refined in post-processing
+ "const_spec": "variable", # const MaxRetries = 3
+ "var_spec": "variable", # var ErrNotFound = errors.New(...)
},
import_node_types=["import_declaration"],
export_node_types=[],
@@ -264,6 +266,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"const_item": "constant",
"type_item": "type_alias",
"mod_item": "module",
+ "macro_definition": "function", # macro_rules! my_macro { ... }
},
import_node_types=["use_declaration"],
export_node_types=[],
@@ -296,6 +299,11 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"struct_specifier": "struct",
"enum_specifier": "enum",
"namespace_definition": "module",
+ "template_declaration": "class", # template<> class/struct/function
+ "type_definition": "struct", # typedef struct { ... } Name;
+ "preproc_def": "variable", # #define MACRO value
+ "preproc_function_def": "function", # #define MACRO(x) ...
+ "declaration": "function", # forward declarations
},
import_node_types=["preproc_include"],
export_node_types=[],
@@ -309,6 +317,10 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"function_definition": "function",
"struct_specifier": "struct",
"enum_specifier": "enum",
+ "type_definition": "struct", # typedef struct { ... } Name;
+ "preproc_def": "variable", # #define MACRO value
+ "preproc_function_def": "function", # #define MACRO(x) ...
+ "declaration": "function", # forward declarations
},
import_node_types=["preproc_include"],
export_node_types=[],
diff --git a/packages/core/src/repowise/core/ingestion/queries/c.scm b/packages/core/src/repowise/core/ingestion/queries/c.scm
index 8bbc2d100..eb8e36020 100644
--- a/packages/core/src/repowise/core/ingestion/queries/c.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/c.scm
@@ -22,6 +22,37 @@
name: (type_identifier) @symbol.name
) @symbol.def
+; typedef struct { ... } MyType;
+(type_definition
+ type: (struct_specifier)
+ declarator: (type_identifier) @symbol.name
+) @symbol.def
+
+; typedef enum { ... } MyEnum;
+(type_definition
+ type: (enum_specifier)
+ declarator: (type_identifier) @symbol.name
+) @symbol.def
+
+; #define MACRO_NAME ...
+(preproc_def
+ name: (identifier) @symbol.name
+) @symbol.def
+
+; #define FUNC_MACRO(x) ...
+(preproc_function_def
+ name: (identifier) @symbol.name
+ parameters: (preproc_params) @symbol.params
+) @symbol.def
+
+; Forward declarations: void func(int x);
+(declaration
+ declarator: (function_declarator
+ declarator: (identifier) @symbol.name
+ parameters: (parameter_list) @symbol.params
+ )
+) @symbol.def
+
; ---------------------------------------------------------------------------
; Imports (#include directives)
; ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
index da57ec9fe..e03ce803d 100644
--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
@@ -47,6 +47,61 @@
name: (namespace_identifier) @symbol.name
) @symbol.def
+; Template class: template<typename T> class Foo { ... }
+(template_declaration
+ (class_specifier
+ name: (type_identifier) @symbol.name
+ )
+) @symbol.def
+
+; Template struct: template<typename T> struct Bar { ... }
+(template_declaration
+ (struct_specifier
+ name: (type_identifier) @symbol.name
+ )
+) @symbol.def
+
+; Template function: template<typename T> T func(T x) { ... }
+(template_declaration
+ (function_definition
+ declarator: (function_declarator
+ declarator: (identifier) @symbol.name
+ parameters: (parameter_list) @symbol.params
+ )
+ )
+) @symbol.def
+
+; typedef struct { ... } MyType;
+(type_definition
+ type: (struct_specifier)
+ declarator: (type_identifier) @symbol.name
+) @symbol.def
+
+; typedef enum { ... } MyEnum;
+(type_definition
+ type: (enum_specifier)
+ declarator: (type_identifier) @symbol.name
+) @symbol.def
+
+; #define MACRO_NAME ...
+(preproc_def
+ name: (identifier) @symbol.name
+) @symbol.def
+
+; #define FUNC_MACRO(x) ...
+(preproc_function_def
+ name: (identifier) @symbol.name
+ parameters: (preproc_params) @symbol.params
+) @symbol.def
+
+; Forward declarations: void func(int x);
+(declaration
+ declarator: (function_declarator
+ declarator: (identifier) @symbol.name
+ parameters: (parameter_list) @symbol.params
+ )
+) @symbol.def
+
; ---------------------------------------------------------------------------
; Imports (#include directives)
; ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/queries/go.scm b/packages/core/src/repowise/core/ingestion/queries/go.scm
index 432409d04..6ba262a09 100644
--- a/packages/core/src/repowise/core/ingestion/queries/go.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/go.scm
@@ -26,6 +26,16 @@
name: (type_identifier) @symbol.name
) @symbol.def
+; Package-level const: const MaxRetries = 3
+(const_spec
+ name: (identifier) @symbol.name
+) @symbol.def
+
+; Package-level var: var ErrNotFound = errors.New("not found")
+(var_spec
+ name: (identifier) @symbol.name
+) @symbol.def
+
; ---------------------------------------------------------------------------
; Imports
; ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/queries/rust.scm b/packages/core/src/repowise/core/ingestion/queries/rust.scm
index f0367a84d..f332f0f9b 100644
--- a/packages/core/src/repowise/core/ingestion/queries/rust.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/rust.scm
@@ -41,6 +41,11 @@
name: (identifier) @symbol.name
) @symbol.def
+; macro_rules! my_macro { ... }
+(macro_definition
+ name: (identifier) @symbol.name
+) @symbol.def
+
; pub visibility modifier
(function_item
(visibility_modifier) @symbol.modifiers
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 3f035380b..2daeb00ad 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -118,6 +118,8 @@ class Page(Base):
freshness_status: Mapped[str] = mapped_column(String(32), nullable=False, default="fresh")
# JSON-encoded dict (metadata is a reserved SQLAlchemy attribute name)
metadata_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
+ # Developer-authored notes that survive LLM re-generation.
+ human_notes: Mapped[str | None] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index 1765ba53f..70e54dfaa 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -620,7 +620,9 @@ async def _run_dead_code_analysis(
if progress:
progress.on_phase_start("dead_code", None)
- analyzer = DeadCodeAnalyzer(graph_builder.graph(), git_meta_map)
+ analyzer = DeadCodeAnalyzer(
+ graph_builder.graph(), git_meta_map, parsed_files=graph_builder._parsed_files
+ )
report = analyzer.analyze()
if progress:
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 8c702ac60..2b9c517c8 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -47,6 +47,7 @@ async def persist_pipeline_result(
)
from repowise.core.persistence.crud import (
bulk_upsert_decisions,
+ recompute_decision_staleness,
save_dead_code_findings,
upsert_git_metadata_bulk,
)
@@ -142,6 +143,23 @@ async def persist_pipeline_result(
repo_id,
[dataclasses.asdict(d) for d in result.decision_report.decisions],
)
+ # Recompute staleness scores using git metadata.
+ if result.git_metadata_list:
+ try:
+ git_meta_map: dict[str, dict] = {}
+ for gm in result.git_metadata_list:
+ gm_dict = gm if isinstance(gm, dict) else dataclasses.asdict(gm)
+ fp = gm_dict.get("file_path", "")
+ if fp:
+ git_meta_map[fp] = gm_dict
+ if git_meta_map:
+ updated = await recompute_decision_staleness(
+ session, repo_id, git_meta_map
+ )
+ if updated:
+ logger.info("decision_staleness_recomputed", updated=updated)
+ except Exception as _stale_err:
+ logger.debug("staleness_scoring_skipped", error=str(_stale_err))
logger.info(
"pipeline_result_persisted",
diff --git a/packages/server/src/repowise/server/__init__.py b/packages/server/src/repowise/server/__init__.py
index 2a5513f2e..5c0f44901 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.2"
+__version__ = "0.2.3"
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index 99a441b7e..ac7beb339 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -27,6 +27,7 @@ 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.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
diff --git a/packages/server/src/repowise/server/mcp_server/tool_annotate.py b/packages/server/src/repowise/server/mcp_server/tool_annotate.py
new file mode 100644
index 000000000..ae6a100f5
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_annotate.py
@@ -0,0 +1,65 @@
+"""``annotate_file`` — attach human notes to a wiki page.
+
+Notes survive LLM-driven re-generation and appear in ``get_context`` responses.
+"""
+
+from __future__ import annotations
+
+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._server import mcp
+
+
+async def annotate_file(
+ target: str,
+ notes: str,
+ repo: str | None = None,
+) -> dict[str, Any]:
+ """Attach human-authored notes to a file's wiki page.
+
+ Notes persist across re-indexing — use them for rationale, known issues,
+ or context that the LLM shouldn't overwrite. Pass an empty string to
+ clear existing notes.
+
+ Args:
+ target: file path (e.g. "src/auth/service.py").
+ notes: the note text to attach (empty string to clear).
+ repo: repository identifier; usually omitted.
+ """
+ from repowise.core.persistence.models import Page
+
+ async with get_session(_state._session_factory) as session:
+ await _get_repo(session, repo) # validates repo exists
+
+ # Try file_page first, then module_page
+ page_id = f"file_page:{target}"
+ result = await session.execute(select(Page).where(Page.id == page_id))
+ page = result.scalar_one_or_none()
+
+ if page is None:
+ page_id = f"module_page:{target}"
+ result = await session.execute(select(Page).where(Page.id == page_id))
+ page = result.scalar_one_or_none()
+
+ if page is None:
+ return {
+ "status": "error",
+ "message": f"No wiki page found for '{target}'. Run 'repowise init' first.",
+ }
+
+ page.human_notes = notes if notes else None
+ await session.flush()
+
+ action = "cleared" if not notes else "updated"
+ return {
+ "status": "ok",
+ "target": target,
+ "action": action,
+ "human_notes": page.human_notes,
+ }
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 1d3c05379..5bbee83d5 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer.py
@@ -510,10 +510,10 @@ async def get_answer(
) -> dict:
"""One-call RAG: answer a code question. Always your first call.
- Returns {answer, citations, confidence, fallback_targets}. If
- confidence=="high" and the answer names concrete files/symbols, cite it
- directly — do NOT verify by Read. Only fall back to search_codebase +
- get_context if confidence=="low" or the answer is hedged.
+ Returns {answer, citations, confidence, fallback_targets}. High-confidence
+ answers name concrete files/symbols and can be used with less verification.
+ For medium/low confidence, cross-reference with search_codebase + get_context.
+ Always verify cited file paths exist before acting on them.
Args:
question: developer question.
@@ -776,14 +776,12 @@ async def get_answer(
"fallback_targets": fallback_targets,
"retrieval": hits,
}
- # When confidence is high, document what the signal means so the consumer
- # knows it can cite the answer directly without falling back to Read.
+ # When confidence is high, document the signal strength for the consumer.
if confidence == "high":
payload["note"] = (
"High confidence: top retrieval result clearly dominates "
- f"(dominance ratio {_ratio:.2f}x). Cite this answer directly; "
- "no further verification needed unless the question explicitly "
- "requires checking additional files."
+ f"(dominance ratio {_ratio:.2f}x). This answer is likely accurate, "
+ "but verify cited file paths exist before acting on them."
)
# Persist to cache. Best-effort: cache failures must NEVER block the
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 2214b1e88..180aa28b1 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context.py
@@ -220,6 +220,8 @@ async def _resolve_one_target(
docs["summary"] = page.summary or ""
if want_full_doc:
docs["content_md"] = page.content
+ if page.human_notes:
+ docs["human_notes"] = page.human_notes
# Symbols in this file
res = await session.execute(
select(WikiSymbol).where(
@@ -681,11 +683,12 @@ async def get_context(
compact: default True (signatures only). False adds structure+imports+docstrings.
repo: usually omitted.
"""
- # Default to docs-only when include is omitted. The other blocks
- # (ownership/last_change/decisions/freshness) are 200–500 bytes each and
- # bloat every subsequent agent turn via cache replay. Callers that want
- # them must pass include explicitly.
- include_set = set(include) if include else {"docs"}
+ # 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
+ # every subsequent agent turn via cache replay. Callers that want them
+ # must pass include explicitly.
+ include_set = set(include) if include else {"docs", "freshness"}
import time as _time
_t0 = _time.perf_counter()
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 62a346ee9..b5f1179ba 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py
@@ -58,7 +58,7 @@ async def get_overview(repo: str | None = None) -> dict:
)
.order_by(Page.title)
)
- module_pages = result.scalars().all()
+ module_pages = result.scalars().all()[:20] # Cap to keep response bounded
# Get entry point files from graph nodes (exclude tests & fixtures)
result = await session.execute(
@@ -148,7 +148,7 @@ async def get_overview(repo: str | None = None) -> dict:
g.file_path
for g in all_git
if (g.primary_owner_commit_pct or 0.0) > 0.8
- ]
+ ][:30] # Cap to keep response size bounded
# onboarding_targets: high-centrality files with least docs
# pagerank from graph_nodes; doc length from wiki_pages
@@ -206,7 +206,7 @@ async def get_overview(repo: str | None = None) -> dict:
}
for p in module_pages
],
- "entry_points": [n.node_id for n in entry_nodes],
+ "entry_points": [n.node_id for n in entry_nodes[:15]],
"git_health": git_health,
"knowledge_map": knowledge_map,
}
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 c262529be..ccbd8415a 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -387,7 +387,7 @@ async def _git_archaeology_fallback(
}
for c in commits
]
- result["file_commits"] = file_commits
+ result["file_commits"] = file_commits[:10] # Cap to keep response bounded
# --- Layer 2: Cross-file search — other files' commits mentioning this file ---
basename = file_path.rsplit("/", 1)[-1] if "/" in file_path else file_path
diff --git a/packages/server/src/repowise/server/schemas.py b/packages/server/src/repowise/server/schemas.py
index 77f3637a0..e99b5aef4 100644
--- a/packages/server/src/repowise/server/schemas.py
+++ b/packages/server/src/repowise/server/schemas.py
@@ -89,6 +89,7 @@ class PageResponse(BaseModel):
confidence: float
freshness_status: str
metadata: dict
+ human_notes: str | None = None
created_at: datetime
updated_at: datetime
@@ -112,6 +113,7 @@ class PageResponse(BaseModel):
confidence=obj.confidence, # type: ignore[attr-defined]
freshness_status=obj.freshness_status, # type: ignore[attr-defined]
metadata=json.loads(obj.metadata_json), # type: ignore[attr-defined]
+ human_notes=obj.human_notes, # type: ignore[attr-defined]
created_at=obj.created_at, # type: ignore[attr-defined]
updated_at=obj.updated_at, # type: ignore[attr-defined]
)
diff --git a/packages/web/FRONTEND_BUILD_STATUS.md b/packages/web/FRONTEND_BUILD_STATUS.md
deleted file mode 100644
index 069493336..000000000
--- a/packages/web/FRONTEND_BUILD_STATUS.md
+++ /dev/null
@@ -1,608 +0,0 @@
-# repowise Frontend — Build Status & Remaining Work
-
-**Last updated:** 2026-03-20
-**Current state:** Phase 3 complete. All polish, advanced features, responsive layout, loading skeletons, error boundaries, and a11y improvements are implemented.
-
----
-
-## What's Already Done
-
-| Area | Status |
-|------|--------|
-| Next.js 15 scaffold + Tailwind v4 design system | ✅ Complete |
-| All API types (mirrors all 35 backend endpoints) | ✅ Complete |
-| Base API client with auth injection | ✅ Complete |
-| All data hooks (SWR, SSE, debounce, graph) | ✅ Complete |
-| UI component library (Radix: Button, Badge, Card, Dialog, Select, Tabs, Tooltip, ScrollArea…) | ✅ Complete |
-| Sidebar with collapsible repo navigation | ✅ Complete |
-| Dashboard page (stat cards, repo list, recent jobs) | ✅ Complete |
-| Repo overview page (git stats, wiki preview) | ✅ Complete |
-| Wiki page structure (top bar, confidence badge, git panel, metadata) | ✅ Structure only |
-| Wiki page content rendering | ✅ Complete (WikiRenderer, Shiki, Mermaid, TOC, git history panel) |
-| Search page (debounce, type toggle, cmdk command palette) | ✅ Complete |
-| Symbols page (sortable table, filter row, detail drawer, Shiki signatures) | ✅ Complete |
-| Graph page (D3 canvas, zoom/pan, hover tooltips, filter panel, minimap) | ✅ Complete |
-| Coverage page (donut chart, freshness table, per-file regenerate) | ✅ Complete |
-| Ownership page (table, contributor chart, silo badges) | ✅ Complete |
-| Hotspots page (ranked table, churn bars, owner leaderboard) | ✅ Complete |
-| Dead Code page (tabs, row resolve/ack/dismiss, bulk select, analyze button) | ✅ Complete |
-| Settings page (connection, provider, webhook, MCP) | ✅ Complete |
-| Add repository dialog + sidebar button | ✅ Complete |
-| Repo operations panel (sync / full resync + confirm) | ✅ Complete |
-| Real-time job progress (SSE stream, log, elapsed, toasts) | ✅ Complete |
-| MDX rendering (WikiRenderer, CodeBlock, MermaidDiagram, TOC) | ✅ Complete |
-| Regenerate button on wiki page | ✅ Complete |
-| Sonner toast notifications | ✅ Complete |
-
----
-
-## Phase 1 — All Data Pages (COMPLETE)
-
-**Goal:** Every stub page becomes a fully functional data view. Backend data is all available — this phase is pure frontend wiring and visualization.
-
-**Status:** All 7 data pages and their components are fully built. See component file list below.
-
----
-
-### 1.1 Search Page (`/repos/[id]/search`)
-
-Full-featured search with type switching and instant results.
-
-**API:** `GET /api/search?query=&search_type=(semantic|fulltext)&limit=`
-**Returns:** `{ page_id, title, page_type, target_path, score, snippet, search_type }`
-
-**UI to build:**
-- Search input with debounce (already have `useSearch` hook — wire it in)
-- Toggle: `Full-Text` | `Semantic` | `Hybrid` — updates `search_type` param
-- Language filter dropdown (Python / TypeScript / Go / etc.)
-- Result cards: file path, title, match snippet with highlight, score badge, link to wiki page
-- Keyboard shortcut: `cmd+K` / `ctrl+K` — opens a `cmdk` command palette overlay from anywhere in the app (global, mounted in root layout)
-- Empty state when no query / no results
-
-**Component files:**
-- `src/app/repos/[id]/search/page.tsx` — full implementation (client component)
-- `src/components/search/search-bar.tsx` — reusable input + type toggle
-- `src/components/search/search-result-card.tsx` — result row
-- `src/components/search/command-palette.tsx` — `cmdk` global overlay
-
----
-
-### 1.2 Symbols Page (`/repos/[id]/symbols`)
-
-Searchable, filterable, sortable symbol index for a repo.
-
-**API:** `GET /api/symbols?repo_id=&q=&kind=&language=&limit=&offset=`
-**Returns:** `{ id, name, qualified_name, kind, file_path, start_line, signature, language, visibility, is_async, complexity_estimate }`
-
-**UI to build:**
-- Search input (substring search on symbol name, wired to `q` param)
-- Filter row: `Kind` (function / class / method / interface / variable) and `Language` dropdowns
-- Sortable table columns: Name, Kind, File, Language, Lines, Complexity
-- Row click opens a drawer (Radix Dialog) showing:
- - Full signature (syntax-highlighted via Shiki)
- - Docstring if present
- - File path with line number link
- - `kind` and `visibility` badges
-- Pagination — load more or page navigation (API supports `offset`)
-- Summary bar: "X symbols across Y files"
-
-**Component files:**
-- `src/app/repos/[id]/symbols/page.tsx` — full implementation
-- `src/components/symbols/symbol-table.tsx` — sortable table with filter row
-- `src/components/symbols/symbol-drawer.tsx` — detail drawer
-
----
-
-### 1.3 Hotspots Page (`/repos/[id]/hotspots`)
-
-Ranked file list by churn + complexity. Shows where the most risky code lives.
-
-**APIs used:**
-- `GET /api/repos/{id}/hotspots?limit=` → `{ file_path, commit_count_90d, churn_percentile, primary_owner, is_hotspot }`
-- `GET /api/repos/{id}/git-summary` → `{ total_files, hotspot_count, stable_count, average_churn_percentile, top_owners }`
-
-**UI to build:**
-- Summary bar: X hotspots / Y stable files / avg churn percentile
-- Ranked table: Rank, File path, Commits (90d), Churn percentile (progress bar), Owner, Hotspot badge
-- Churn percentile shown as a horizontal `Recharts` bar or colored progress bar (red = high churn)
-- Top owners mini-leaderboard (from git-summary `top_owners`)
-- Click file row → navigate to wiki page for that file (if exists)
-
-**Component files:**
-- `src/app/repos/[id]/hotspots/page.tsx` — full server component
-- `src/components/git/hotspot-table.tsx`
-- `src/components/git/churn-bar.tsx` — inline progress bar with color gradient
-
----
-
-### 1.4 Ownership Page (`/repos/[id]/ownership`)
-
-Code ownership breakdown — who owns what, silo detection.
-
-**APIs used:**
-- `GET /api/repos/{id}/ownership?granularity=module` → `{ module_path, primary_owner, owner_pct, file_count, is_silo }`
-- `GET /api/repos/{id}/git-summary` → top_owners leaderboard
-
-**UI to build:**
-- Toggle: `Module` | `File` granularity (updates `granularity` query param)
-- Ownership table: Module/File, Owner, Ownership%, File Count, Silo badge
- - Silo badge (ownership > 80%) highlighted in yellow with tooltip "Bus factor risk"
- - Ownership % shown as a colored progress bar
-- Contributor sidebar: top 10 owners with file counts and percentage of total
-- `Recharts` horizontal bar chart showing top 5 contributors by file count
-
-**Component files:**
-- `src/app/repos/[id]/ownership/page.tsx` — client component (toggle state)
-- `src/components/git/ownership-table.tsx`
-- `src/components/git/contributor-bar.tsx`
-
----
-
-### 1.5 Coverage Page (`/repos/[id]/coverage`)
-
-Documentation freshness breakdown — how much of the codebase is documented and up to date.
-
-**APIs used:**
-- `GET /api/pages?repo_id=&limit=500` → all pages with `freshness_status`, `confidence`, `target_path`, `page_type`
-- `GET /api/symbols?repo_id=&limit=1` to get total symbol count (from API count header or paginated total)
-
-**Derived metrics (computed client-side):**
-- `fresh` = pages where `freshness_status === "fresh"`
-- `stale` = `freshness_status === "stale"`
-- `outdated` = `freshness_status === "outdated"`
-- Coverage % = total_pages / estimated_file_count × 100
-
-**UI to build:**
-- Big coverage score at top (donut chart via Recharts or large text + confidence bar)
-- Three stat cards: Fresh / Stale / Outdated with counts + percentage
-- Freshness distribution bar (stacked horizontal bar: green/yellow/red)
-- Table: File path, Status badge, Confidence %, Model used, Last generated
- - Filterable by status
-- "Stale files" list with links to wiki pages + "Regenerate" button per row (calls `POST /api/pages/lookup/regenerate?page_id=`)
-
-**Component files:**
-- `src/app/repos/[id]/coverage/page.tsx` — server component with client sub-components
-- `src/components/coverage/coverage-donut.tsx` — Recharts PieChart
-- `src/components/coverage/freshness-table.tsx`
-
----
-
-### 1.6 Dead Code Page (`/repos/[id]/dead-code`)
-
-Unused files, exports, and zombie packages — triage and resolve workflow.
-
-**APIs used:**
-- `GET /api/repos/{id}/dead-code?min_confidence=0.4&status=open&limit=200`
-- `GET /api/repos/{id}/dead-code/summary` → `{ total_findings, by_kind, deletable_lines, confidence_summary }`
-- `POST /api/repos/{id}/dead-code/analyze` → trigger async analysis (202)
-- `PATCH /api/dead-code/{finding_id}` → resolve/dismiss a finding (`status`: acknowledged | resolved | false_positive)
-
-**UI to build:**
-- Summary bar: total findings, deletable lines, breakdown by kind (unreachable_file / unused_export / unused_internal / zombie_package)
-- Three tabs: **Unreachable** | **Unused Exports** | **Zombie Packages** (filters `kind`)
-- Finding table per tab:
- - Columns: File, Symbol, Confidence, Owner, Lines, Safe-to-delete badge, Status
- - Row actions: Resolve / Acknowledge / Mark False Positive (calls `PATCH`)
- - Bulk select + bulk resolve
-- "Analyze" button → calls `POST /analyze` → shows toast "Analysis started"
-- Confidence filter slider (0.4 – 1.0)
-- Safe-only toggle (filters `safe_to_delete=true`)
-
-**Component files:**
-- `src/app/repos/[id]/dead-code/page.tsx` — client component (tabs + row actions)
-- `src/components/dead-code/findings-table.tsx`
-- `src/components/dead-code/finding-row.tsx` — with inline action buttons
-- `src/components/dead-code/summary-bar.tsx`
-
----
-
-### 1.7 Dependency Graph Page (`/repos/[id]/graph`)
-
-D3 force-directed graph of module dependencies.
-
-**API:** `GET /api/graph/{repoId}` → `{ nodes: [{ node_id, node_type, language, symbol_count, pagerank, betweenness, community_id, is_test, is_entry_point }], links: [{ source, target, imported_names }] }`
-
-**UI to build:**
-- D3 force simulation on `<canvas>` (not SVG — 2000+ nodes need canvas performance)
- - Node size = `symbol_count` (capped at 3× base)
- - Node color = language (from `LANGUAGE_COLORS` in `confidence.ts`)
- - Edge color = `--color-edge-imports` / `--color-edge-calls` CSS vars
- - Entry point nodes have a ring indicator
- - Test nodes shown dimmed
-- Zoom + pan (D3 zoom)
-- Hover tooltip: node_id, language, symbol_count, pagerank, community_id
-- Click node → navigate to wiki page for that file (if exists)
-- Filter panel (right side):
- - Language multi-select
- - Hide test files toggle
- - Color-by: Language | Community | Entry Points
- - Size-by: Symbol Count | PageRank | Betweenness
-- Node search (highlights matching nodes)
-- Mini-map (small overview canvas in corner showing full graph, viewport rect)
-
-**Component files:**
-- `src/app/repos/[id]/graph/page.tsx` — thin server wrapper
-- `src/components/graph/graph-canvas.tsx` — `"use client"` D3 canvas component
-- `src/components/graph/graph-filter-panel.tsx` — filter controls
-- `src/components/graph/graph-tooltip.tsx` — hover overlay
-- `src/components/graph/graph-minimap.tsx` — overview canvas
-
----
-
-## Phase 2 — CLI Operations & Full Control from UI (COMPLETE)
-
-**Goal:** Every CLI command (`init`, `update`, `sync`, `dead-code`, `export`, `doctor`, `status`) is triggerable from the UI. All provider/model/API key config is manageable from the Settings page. Real-time job progress via SSE is fully surfaced.
-
-**Estimated files:** ~20 new/modified files
-**New dependencies needed:** `sonner`, `@radix-ui/react-progress`, `@radix-ui/react-switch`, `@radix-ui/react-slider`, `@radix-ui/react-label` — none are installed yet.
-
----
-
-### 2.1 Settings Page (`/settings`)
-
-Central config — everything needed to run repowise is configurable here.
-
-**Sections:**
-
-#### API Connection
-- API server URL (reads/writes `NEXT_PUBLIC_REPOWISE_API_URL` via `.env.local` or just localStorage)
-- API key (stored in `localStorage` as `repowise_api_key` — already read by `client.ts`)
-- "Test connection" button → calls `GET /health` and shows server version + status
-
-#### Default Provider & Model
-- Provider dropdown: `litellm` | `openai` | `anthropic` | `ollama` | `mock`
-- Model text input (e.g., `gemini/gemini-2.0-flash`, `gpt-4.1`, `claude-opus-4-6`)
-- Saved to `localStorage` as `repowise_default_provider` and `repowise_default_model`
-- Used as defaults when triggering init/sync from UI
-
-#### Embedder Config
-- Embedder dropdown: `mock` | `gemini`
-- Embedding dimensions (default 768)
-- Note: "Set REPOWISE_EMBEDDER env var when starting the server"
-- Inline docs explaining when semantic search is active
-
-#### Webhook Config (display only)
-- GitHub webhook URL: `http://your-server:7337/api/webhooks/github`
-- GitLab webhook URL: `http://your-server:7337/api/webhooks/gitlab`
-- Secret env vars to set: `REPOWISE_GITHUB_WEBHOOK_SECRET`, `REPOWISE_GITLAB_WEBHOOK_TOKEN`
-- Copy-to-clipboard buttons
-
-#### MCP Config (display only)
-- Auto-generated MCP config for Claude Code / Cursor / Cline
-- Shows `repowise mcp {repo_path} --transport stdio` command
-- Copy-to-clipboard
-
-**Component files:**
-- `src/app/settings/page.tsx` — full implementation
-- `src/components/settings/connection-section.tsx`
-- `src/components/settings/provider-section.tsx`
-- `src/components/settings/webhook-section.tsx`
-- `src/components/settings/mcp-section.tsx`
-- `src/lib/config.ts` — localStorage read/write helpers for all settings
-
----
-
-### 2.2 Add Repository Dialog
-
-Register a new repo without using the CLI.
-
-**API:** `POST /api/repos` with `{ name, local_path, url?, default_branch?, settings? }`
-
-**UI:**
-- "+ Add Repository" button in sidebar (below repo list) and on empty dashboard
-- Radix Dialog with form:
- - `name` — text input
- - `local_path` — text input (e.g., `C:\Users\ragha\Desktop\interview-coach`)
- - `url` — optional git remote URL
- - `default_branch` — text input (default: `main`)
-- Submit → `POST /api/repos` → mutate SWR cache → sidebar updates
-
-**Component files:**
-- `src/components/repos/add-repo-dialog.tsx` — Dialog with form
-- Update `src/components/layout/sidebar.tsx` — add the "+ Add" button
-
----
-
-### 2.3 Repo Operations Panel
-
-Init, sync, and resync a repo from the UI — the most important CLI feature to expose.
-
-This is a collapsible panel on the repo overview page (`/repos/[id]`), and also accessible from a "Run" button in the sidebar.
-
-**Supported operations:**
-
-| Operation | API | CLI Equivalent |
-|-----------|-----|----------------|
-| Incremental Sync | `POST /api/repos/{id}/sync` | `repowise update` |
-| Full Resync | `POST /api/repos/{id}/full-resync` | `repowise init --force` |
-
-**UI — "Run" panel:**
-- Provider dropdown (defaults to saved settings provider)
-- Model text input (defaults to saved settings model)
-- Options: Skip Tests toggle, Skip Infra toggle, Concurrency slider (1–10)
-- "Sync" button → `POST /api/repos/{id}/sync` with config
-- "Full Resync" button (destructive — confirm dialog first) → `POST /api/repos/{id}/full-resync`
-- After triggering: transition to Job Progress view (see 2.4)
-
-**Component files:**
-- `src/components/repos/operations-panel.tsx` — `"use client"` collapsible form
-- `src/components/repos/run-config-form.tsx` — provider/model/options form (reused in 2.4)
-- Update `src/app/repos/[id]/page.tsx` — embed operations panel
-
----
-
-### 2.4 Real-Time Job Progress
-
-Live SSE stream from `GET /api/jobs/{id}/stream`. Shows file-by-file generation progress.
-
-**SSE Events:**
-- `event: progress` → `{ job_id, status, completed_pages, total_pages, failed_pages, current_level }`
-- `event: done` → same shape, triggers completion state
-- `event: error` → `{ detail }` → show error state
-
-**UI:**
-- `GenerationProgress` component — mounted when a job is running
- - Progress bar: `completed_pages / total_pages`
- - Status text: "Generating level 2 — 47/142 pages"
- - Failed count badge (if > 0)
- - Elapsed time counter
- - Log lines: last 5 progress events shown as scrolling log
- - On `done`: show summary (total pages, tokens, elapsed, failed count)
- - On `error`: show error message with retry option
-- Job list in dashboard auto-refreshes every 5s while any job is running
-- Toast notification (sonner) on job completion/failure
-
-**Component files:**
-- `src/components/jobs/generation-progress.tsx` — `"use client"` SSE-driven component
-- `src/components/jobs/job-log.tsx` — scrolling event log
-- `src/lib/hooks/use-job.ts` — SWR hook for polling job status + SSE stream control
-- Update `src/app/repos/[id]/page.tsx` — show `GenerationProgress` when job is running
-
----
-
-### 2.5 Wiki Page MDX Rendering
-
-Replace plain-text content display with full MDX rendering.
-
-**Tools:** `next-mdx-remote` (server-side compilation), `shiki` (code highlighting), `mermaid` (diagrams)
-
-**Components to build:**
-- `src/components/wiki/wiki-renderer.tsx` — RSC that compiles MDX with `next-mdx-remote/rsc`
- - Custom MDX components: heading levels, code blocks, tables, blockquotes
-- `src/components/wiki/code-block.tsx` — `"use client"` Shiki syntax highlighter
- - Language badge, copy button, line numbers, VSCode Dark+ theme
-- `src/components/wiki/mermaid-diagram.tsx` — `"use client"` lazy Mermaid renderer
- - Dynamic import of `mermaid` to avoid SSR issues
-- `src/components/wiki/table-of-contents.tsx` — extracted from MDX headings, sticky on scroll
-- Update `src/app/repos/[id]/wiki/[...slug]/page.tsx` — swap plain text for `WikiRenderer`
-
----
-
-### 2.6 Regenerate Button on Wiki Page
-
-Allow regenerating a single page from the UI without running the full CLI.
-
-**API:** `POST /api/pages/lookup/regenerate?page_id={page_id}` → `{ job_id, status }`
-
-**UI:**
-- "Regenerate" button in wiki page top bar (spinner while running)
-- On click → POST regenerate → get `job_id` → open `GenerationProgress` in a Dialog
-- On complete → revalidate page data (SWR mutate) → confidence badge updates
-
----
-
-## Phase 3 — Polish, Advanced Features & Full Completeness (COMPLETE)
-
-**Goal:** Production-grade UX. Command palette, advanced graph interactions, responsive layouts, loading states, error boundaries, accessibility, and any remaining gaps.
-
-**Estimated files:** ~25 new/modified files
-
----
-
-### 3.1 Global Command Palette (`cmd+K`)
-
-Instant access to everything from anywhere in the app.
-
-**Library:** `cmdk` (already installed)
-
-**Features:**
-- Sections: Recent Pages, Repos, Quick Actions, Symbols
-- Quick Actions: "Init repo", "Open settings", "View jobs"
-- Repo pages: navigate to any wiki page by typing its title or path
-- Symbol lookup: type a symbol name → navigate to symbol drawer
-- Keyboard: `↑/↓` navigate, `Enter` select, `Esc` close
-- Mounted globally in `layout.tsx`
-
-**Component files:**
-- `src/components/search/command-palette.tsx` — full cmdk implementation
-- Update `src/app/layout.tsx` — mount palette + register `cmd+K` listener
-
----
-
-### 3.2 Advanced Graph Features
-
-Completing the dependency graph from Phase 1 with path-finding and filtering.
-
-**New features:**
-- Shortest path finder: "From" + "To" node inputs → calls `GET /api/graph/{id}/path?from=&to=` → highlights path in orange on the graph canvas
-- Community clustering: color nodes by `community_id` — nodes in same community use the same color family
-- "Focus on file" mode: click a node → dim all non-adjacent nodes, show 1-hop neighborhood
-- Export graph as PNG (canvas `.toDataURL()`)
-
-**Component files:**
-- `src/components/graph/path-finder.tsx` — UI controls for path query
-- Update `src/components/graph/graph-canvas.tsx` — add path highlighting, community colors, focus mode
-
----
-
-### 3.3 Git History Panel on Wiki Pages
-
-Full per-file commit history surfaced in the wiki page context panel.
-
-**API:** `GET /api/repos/{id}/git-metadata?file_path=` → `{ significant_commits, top_authors, co_change_partners, commit_count_90d, churn_percentile }`
-
-**UI:**
-- Recent commits list: SHA (7-char), message (truncated), author, relative date
-- Author avatars (generated from author name initials)
-- Co-change partners: "Often changed with: X, Y, Z" linked to their wiki pages
-- Churn indicator: commit frequency sparkline (last 12 weeks, Recharts LineChart)
-
-**Component files:**
-- `src/components/wiki/git-history-panel.tsx` — full implementation
-- `src/components/wiki/commit-row.tsx`
-- `src/components/wiki/co-change-list.tsx`
-
----
-
-### 3.4 Repo Settings & Danger Zone
-
-Per-repo settings accessible from the repo overview.
-
-**APIs:**
-- `PATCH /api/repos/{id}` → update name, default_branch, settings
-- (No delete endpoint in backend yet — add to Phase 3 wishlist)
-
-**UI (tab on repo overview or separate `/repos/[id]/settings` route):**
-- Repo name (editable)
-- Default branch (editable)
-- Local path (read-only display)
-- Webhook URL display (repo-specific)
-- Danger zone: "Full Resync" (red button, confirm dialog)
-
-**Component files:**
-- `src/app/repos/[id]/settings/page.tsx` — new route
-- `src/components/repos/repo-settings-form.tsx`
-
----
-
-### 3.5 Toast Notification System
-
-Consistent feedback for all async operations.
-
-**Library:** `sonner` (add to dependencies)
-
-**Coverage:**
-- ✅ Job started: "Sync started for {repo}"
-- ✅ Job completed: "Documentation updated — 47 pages"
-- ✅ Job failed: "{error message}" with retry button
-- ✅ Repo added: "Repository registered"
-- ✅ Finding resolved: "Marked as resolved"
-- ✅ Page regenerated: "Page regeneration queued"
-
-**Component files:**
-- `src/components/ui/toaster.tsx` — Sonner Toaster wrapper
-- Update `src/app/layout.tsx` — mount `<Toaster />`
-
----
-
-### 3.6 Loading Skeletons for All Pages
-
-Every data-fetching page needs `loading.tsx` with skeleton placeholders.
-
-**Files to add:**
-- `src/app/loading.tsx` — dashboard skeleton
-- `src/app/repos/[id]/loading.tsx` — repo overview skeleton
-- `src/app/repos/[id]/symbols/loading.tsx`
-- `src/app/repos/[id]/hotspots/loading.tsx`
-- `src/app/repos/[id]/ownership/loading.tsx`
-- `src/app/repos/[id]/dead-code/loading.tsx`
-- `src/app/repos/[id]/coverage/loading.tsx`
-- `src/app/repos/[id]/graph/loading.tsx`
-- `src/app/repos/[id]/search/loading.tsx`
-
-Each skeleton matches the page's layout — no layout shift.
-
----
-
-### 3.7 Error Boundaries
-
-Graceful degradation when API calls fail.
-
-**Files to add:**
-- `src/app/error.tsx` — root error boundary
-- `src/app/repos/[id]/error.tsx` — repo-level error (shows "Repo not found" + back button)
-- `src/components/shared/api-error.tsx` — reusable error display with retry button
-
----
-
-### 3.8 Responsive Layout
-
-Full usability on tablet (768px) and mobile (375px).
-
-**Changes:**
-- Sidebar: collapses to icon rail on tablet, full-screen overlay on mobile
-- Graph page: falls back to table view on mobile (canvas interaction impractical)
-- Symbols/Hotspots/Ownership tables: horizontal scroll on small screens
-- Dead code: card view instead of table on mobile
-
-**Component files:**
-- `src/components/layout/mobile-nav.tsx` — hamburger + sheet sidebar for mobile
-- Update `src/components/layout/sidebar.tsx` — responsive breakpoints
-
----
-
-### 3.9 Keyboard Navigation & Accessibility
-
-Full WCAG 2.1 AA compliance.
-
-**Audit & fix:**
-- All interactive elements reachable by `Tab`
-- Focus rings visible on all buttons/links/inputs
-- `aria-label` on icon-only buttons
-- `role="status"` on loading states
-- `aria-live="polite"` on job progress updates
-- Contrast ratio check on all text/background pairs
-
----
-
-## Dependency Additions Needed
-
-| Package | Phase | Purpose |
-|---------|-------|---------|
-| `sonner` | Phase 2 | Toast notifications |
-| `@radix-ui/react-progress` | Phase 2 | Progress bar component |
-| `@radix-ui/react-switch` | Phase 2 | Toggle switches in settings |
-| `@radix-ui/react-slider` | Phase 2 | Concurrency slider |
-| `@radix-ui/react-label` | Phase 2 | Form labels |
-
-All other dependencies (D3, Recharts, cmdk, next-mdx-remote, shiki, framer-motion) are already installed.
-
----
-
-## Build Order
-
-The recommended build order within each phase:
-
-**Phase 1** (DONE):
-All 7 data pages complete in order: Hotspots → Ownership → Symbols → Dead Code → Coverage → Search → Graph.
-
-**Phase 2** (each step unblocks the next):
-1. `src/lib/config.ts` — settings localStorage helpers (used by everything)
-2. Settings page — foundational, other pages reference saved config
-3. Add Repository dialog — needed before operations panel makes sense
-4. MDX rendering — high-value, independent
-5. Operations panel (init/sync UI) — depends on config helpers for defaults
-6. Job progress component — depends on operations panel triggering jobs
-7. Regenerate button — depends on job progress component
-
-**Phase 3** (independent, can be parallelized):
-- Command palette, advanced graph, git history panel, repo settings, loading skeletons, error boundaries, responsive layout, a11y audit — all independent of each other.
-
----
-
-## Page Completion Tracker
-
-| Page | Phase 1 | Phase 2 | Phase 3 | Done |
-|------|---------|---------|---------|------|
-| `/` Dashboard | — | job progress polling | skeleton + error boundary | |
-| `/repos/[id]` Overview | — | ✅ operations panel | repo settings tab | |
-| `/repos/[id]/wiki/[...slug]` | — | ✅ MDX + regenerate + TOC | symbol hover | |
-| `/repos/[id]/search` | ✅ full search UI | — | — | ✅ |
-| `/repos/[id]/graph` | ✅ D3 canvas | — | path finder + community colors | ✅ (P1) |
-| `/repos/[id]/symbols` | ✅ table + drawer | — | symbol hover card | ✅ (P1) |
-| `/repos/[id]/coverage` | ✅ donut + table | — | skeleton | ✅ (P1) |
-| `/repos/[id]/ownership` | ✅ table + chart | — | skeleton | ✅ (P1) |
-| `/repos/[id]/hotspots` | ✅ table + churn bars | — | skeleton | ✅ (P1) |
-| `/repos/[id]/dead-code` | ✅ tabs + resolve | — | skeleton | ✅ (P1) |
-| `/settings` | — | ✅ full settings | — | ✅ |
-| `/repos/[id]/settings` | — | — | ✅ repo settings | ✅ |
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 7aa20412d..207daec00 100644
--- a/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx
+++ b/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx
@@ -13,7 +13,7 @@ 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 } from "lucide-react";
+import { Hash, Cpu, StickyNote } from "lucide-react";
interface Props {
params: Promise<{ id: string; slug: string[] }>;
@@ -101,6 +101,20 @@ export default async function WikiPageRoute({ params }: Props) {
{page.title}
</h1>
+ {page.human_notes && (
+ <div className="mb-5 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>
+ )}
+
<article className="prose prose-invert max-w-none leading-relaxed overflow-hidden">
<WikiRenderer content={page.content} />
</article>
diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsx
index a6c2ff262..b82d530cb 100644
--- a/packages/web/src/components/docs/docs-viewer.tsx
+++ b/packages/web/src/components/docs/docs-viewer.tsx
@@ -9,6 +9,7 @@ import {
Hash,
ExternalLink,
Download,
+ StickyNote,
ArrowRight,
RefreshCw,
Loader2,
@@ -129,6 +130,21 @@ export function DocsViewer({ page, repoId, isLoading }: DocsViewerProps) {
</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>
+ </div>
+ <p className="text-sm text-[var(--color-text-secondary)] whitespace-pre-wrap leading-relaxed">
+ {page.human_notes}
+ </p>
+ </div>
+ )}
+
{/* Markdown content */}
<article className="prose-chat">
<ChatMarkdown content={page.content} />
diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.ts
index ca759470f..9f9fed926 100644
--- a/packages/web/src/lib/api/types.ts
+++ b/packages/web/src/lib/api/types.ts
@@ -59,6 +59,7 @@ export interface PageResponse {
confidence: number;
freshness_status: string;
metadata: Record<string, unknown>;
+ human_notes: string | null;
created_at: string;
updated_at: string;
}
diff --git a/pyproject.toml b/pyproject.toml
index d41c8364a..9699d0312 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "repowise"
-version = "0.2.2"
+version = "0.2.3"
description = "Codebase intelligence for developers and AI — generates and maintains a structured wiki for any codebase"
readme = "README.md"
requires-python = ">=3.11"
diff --git a/tests/unit/generation/test_editor_file_base.py b/tests/unit/generation/test_editor_file_base.py
index 38c39865e..1004c4a7a 100644
--- a/tests/unit/generation/test_editor_file_base.py
+++ b/tests/unit/generation/test_editor_file_base.py
@@ -23,6 +23,7 @@ def _minimal_data() -> EditorFileData:
return EditorFileData(
repo_name="test-repo",
indexed_at="2026-03-28",
+ indexed_commit="a1b2c3d",
architecture_summary="A test repo.",
)
diff --git a/tests/unit/ingestion/test_graph.py b/tests/unit/ingestion/test_graph.py
index 985bb4cc3..bc36795ad 100644
--- a/tests/unit/ingestion/test_graph.py
+++ b/tests/unit/ingestion/test_graph.py
@@ -720,3 +720,158 @@ class TestCppCompileCommandsResolution:
b.add_file(_cpp("src/main.cpp", imports=[_cinclude("bar.hpp")]))
b.build()
assert b.graph().has_edge("src/main.cpp", "include/bar.hpp")
+
+
+# ---------------------------------------------------------------------------
+# Rust import resolution
+# ---------------------------------------------------------------------------
+
+
+class TestRustImports:
+ def test_crate_import_resolves_to_file(self) -> None:
+ """use crate::models::Calculator -> src/models.rs"""
+ b = GraphBuilder()
+ b.add_file(_parsed("src/lib.rs", language="rust"))
+ b.add_file(_parsed("src/models.rs", language="rust"))
+ b.add_file(
+ _parsed(
+ "src/main.rs",
+ language="rust",
+ imports=[_imp("crate::models::Calculator")],
+ )
+ )
+ b.build()
+ g = b.graph()
+ assert g.has_edge("src/main.rs", "src/models.rs")
+
+ def test_crate_import_resolves_to_mod_rs(self) -> None:
+ """use crate::utils -> src/utils/mod.rs when src/utils.rs doesn't exist."""
+ b = GraphBuilder()
+ b.add_file(_parsed("src/lib.rs", language="rust"))
+ b.add_file(_parsed("src/utils/mod.rs", language="rust"))
+ b.add_file(
+ _parsed(
+ "src/main.rs",
+ language="rust",
+ imports=[_imp("crate::utils")],
+ )
+ )
+ b.build()
+ g = b.graph()
+ assert g.has_edge("src/main.rs", "src/utils/mod.rs")
+
+ def test_super_import(self) -> None:
+ """use super::sibling -> resolves to parent dir's sibling.rs."""
+ b = GraphBuilder()
+ b.add_file(_parsed("src/lib.rs", language="rust"))
+ b.add_file(_parsed("src/sibling.rs", language="rust"))
+ b.add_file(
+ _parsed(
+ "src/sub/child.rs",
+ language="rust",
+ imports=[_imp("super::sibling")],
+ )
+ )
+ b.build()
+ g = b.graph()
+ assert g.has_edge("src/sub/child.rs", "src/sibling.rs")
+
+ def test_self_import(self) -> None:
+ """use self::helper -> resolves to current dir's helper.rs."""
+ b = GraphBuilder()
+ b.add_file(_parsed("src/lib.rs", language="rust"))
+ b.add_file(_parsed("src/utils/helper.rs", language="rust"))
+ b.add_file(
+ _parsed(
+ "src/utils/mod.rs",
+ language="rust",
+ imports=[_imp("self::helper")],
+ )
+ )
+ b.build()
+ g = b.graph()
+ assert g.has_edge("src/utils/mod.rs", "src/utils/helper.rs")
+
+ def test_external_crate(self) -> None:
+ """use serde::Deserialize -> external:serde::Deserialize."""
+ b = GraphBuilder()
+ b.add_file(_parsed("src/lib.rs", language="rust"))
+ b.add_file(
+ _parsed(
+ "src/main.rs",
+ language="rust",
+ imports=[_imp("serde::Deserialize")],
+ )
+ )
+ b.build()
+ g = b.graph()
+ assert any(n.startswith("external:") for n in g.nodes)
+
+ def test_nested_crate_import(self) -> None:
+ """use crate::api::handlers::auth -> src/api/handlers/auth.rs."""
+ b = GraphBuilder()
+ b.add_file(_parsed("src/lib.rs", language="rust"))
+ b.add_file(_parsed("src/api/handlers/auth.rs", language="rust"))
+ b.add_file(
+ _parsed(
+ "src/main.rs",
+ language="rust",
+ imports=[_imp("crate::api::handlers::auth")],
+ )
+ )
+ b.build()
+ g = b.graph()
+ assert g.has_edge("src/main.rs", "src/api/handlers/auth.rs")
+
+
+# ---------------------------------------------------------------------------
+# Go import resolution with go.mod
+# ---------------------------------------------------------------------------
+
+
+class TestGoImports:
+ def test_go_mod_resolves_local_import(self, tmp_path: Path) -> None:
+ """go.mod module path enables resolving internal package imports."""
+ (tmp_path / "go.mod").write_text("module github.com/org/myapp\n\ngo 1.21\n")
+ b = GraphBuilder(repo_path=tmp_path)
+ b.add_file(_parsed("pkg/util/util.go", language="go"))
+ b.add_file(
+ _parsed(
+ "cmd/main.go",
+ language="go",
+ imports=[_imp("github.com/org/myapp/pkg/util")],
+ )
+ )
+ b.build()
+ g = b.graph()
+ assert g.has_edge("cmd/main.go", "pkg/util/util.go")
+
+ def test_go_external_package(self, tmp_path: Path) -> None:
+ """Imports not matching go.mod module path become external: nodes."""
+ (tmp_path / "go.mod").write_text("module github.com/org/myapp\n\ngo 1.21\n")
+ b = GraphBuilder(repo_path=tmp_path)
+ b.add_file(
+ _parsed(
+ "main.go",
+ language="go",
+ imports=[_imp("github.com/gin-gonic/gin")],
+ )
+ )
+ b.build()
+ g = b.graph()
+ assert any(n.startswith("external:") for n in g.nodes)
+
+ def test_go_no_go_mod_falls_back_to_stem(self) -> None:
+ """Without go.mod, Go resolution falls back to stem matching."""
+ b = GraphBuilder()
+ b.add_file(_parsed("calculator/calculator.go", language="go"))
+ b.add_file(
+ _parsed(
+ "main.go",
+ language="go",
+ imports=[_imp("github.com/example/app/calculator")],
+ )
+ )
+ b.build()
+ g = b.graph()
+ assert g.has_edge("main.go", "calculator/calculator.go")
diff --git a/uv.lock b/uv.lock
index 852e71e5e..8a7a7711e 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1262,7 +1262,7 @@ wheels = [
[[package]]
name = "litellm"
-version = "1.80.0"
+version = "1.83.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohttp" },
@@ -1278,9 +1278,9 @@ dependencies = [
{ name = "tiktoken" },
{ name = "tokenizers" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/bd/8c/48d533affdbc6d485b7ad4221cd3b40b8c12f9f5568edfe0be0b11e7b945/litellm-1.80.0.tar.gz", hash = "sha256:eeac733eb6b226f9e5fb020f72fe13a32b3354b001dc62bcf1bc4d9b526d6231", size = 11591976, upload-time = "2025-11-16T00:03:51.812Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/22/92/6ce9737554994ca8e536e5f4f6a87cc7c4774b656c9eb9add071caf7d54b/litellm-1.83.0.tar.gz", hash = "sha256:860bebc76c4bb27b4cf90b4a77acd66dba25aced37e3db98750de8a1766bfb7a", size = 17333062, upload-time = "2026-03-31T05:08:25.331Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/ea/53/aa31e4d057b3746b3c323ca993003d6cf15ef987e7fe7ceb53681695ae87/litellm-1.80.0-py3-none-any.whl", hash = "sha256:fd0009758f4772257048d74bf79bb64318859adb4ea49a8b66fdbc718cd80b6e", size = 10492975, upload-time = "2025-11-16T00:03:49.182Z" },
+ { 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]]
@@ -1670,7 +1670,7 @@ wheels = [
[[package]]
name = "openai"
-version = "1.109.1"
+version = "2.31.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio" },
@@ -1682,9 +1682,9 @@ dependencies = [
{ name = "tqdm" },
{ name = "typing-extensions" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/c6/a1/a303104dc55fc546a3f6914c842d3da471c64eec92043aef8f652eb6c524/openai-1.109.1.tar.gz", hash = "sha256:d173ed8dbca665892a6db099b4a2dfac624f94d20a93f46eb0b56aae940ed869", size = 564133, upload-time = "2025-09-24T13:00:53.075Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/94/fe/64b3d035780b3188f86c4f6f1bc202e7bb74757ef028802112273b9dcacf/openai-2.31.0.tar.gz", hash = "sha256:43ca59a88fc973ad1848d86b98d7fac207e265ebbd1828b5e4bdfc85f79427a5", size = 684772, upload-time = "2026-04-08T21:01:41.797Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/1d/2a/7dd3d207ec669cacc1f186fd856a0f61dbc255d24f6fdc1a6715d6051b0f/openai-1.109.1-py3-none-any.whl", hash = "sha256:6bcaf57086cf59159b8e27447e4e7dd019db5d29a438072fbd49c290c7e65315", size = 948627, upload-time = "2025-09-24T13:00:50.754Z" },
+ { url = "https://files.pythonhosted.org/packages/66/bc/a8f7c3aa03452fedbb9af8be83e959adba96a6b4a35e416faffcc959c568/openai-2.31.0-py3-none-any.whl", hash = "sha256:44e1344d87e56a493d649b17e2fac519d1368cbb0745f59f1957c4c26de50a0a", size = 1153479, upload-time = "2026-04-08T21:01:39.217Z" },
]
[[package]]
@@ -2336,7 +2336,7 @@ wheels = [
[[package]]
name = "repowise"
-version = "0.1.29"
+version = "0.2.2"
source = { editable = "." }
dependencies = [
{ name = "aiosqlite" },
@@ -2421,11 +2421,11 @@ requires-dist = [
{ name = "httpx", specifier = ">=0.27,<1" },
{ name = "jinja2", specifier = ">=3.1,<4" },
{ name = "lancedb", specifier = ">=0.12,<1" },
- { name = "litellm", specifier = ">=1.50,<2" },
+ { name = "litellm", specifier = ">=1.83.0,<2" },
{ name = "mcp", specifier = ">=1.0,<2" },
{ name = "mypy", marker = "extra == 'dev'", specifier = ">=1.11,<2" },
{ name = "networkx", specifier = ">=3.3,<4" },
- { name = "openai", specifier = ">=1.50,<2" },
+ { name = "openai", specifier = ">=1.50,<3" },
{ name = "pathspec", specifier = ">=0.12,<1" },
{ name = "pgvector", marker = "extra == 'postgres'", specifier = ">=0.3,<1" },
{ name = "pydantic", specifier = ">=2.8,<3" },