Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
Initial commit: CodeWiki project
RaghavChamadiyae0a4ce87b298
diff --git a/.claude/settings.local.json b/.claude/settings.local.jsonnew file mode 100644index 000000000..c74157318--- /dev/null+++ b/.claude/settings.local.json@@ -0,0 +1,58 @@+{+ "permissions": {+ "allow": [+ "Bash(uv sync:*)",+ "Read(//c/Users/ragha/AppData/Roaming/uv/**)",+ "Read(//c/Users/ragha/.local/bin//**)",+ "Bash(/c/Users/ragha/AppData/Roaming/uv/bin/uv.exe sync:*)",+ "Bash(cmd.exe /c \"echo %PATH%\")",+ "Bash(tr ';' '\\\\n')",+ "Bash(powershell.exe -Command \"uv --version\" 2>&1)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv sync --all-packages 2>&1\")",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/providers/ -v 2>&1\")",+ "Bash(xargs cat:*)",+ "Bash(python /c/Users/ragha/Desktop/CodeWiki/.venv/Scripts/python.exe -c \"import tree_sitter_typescript; print\\(dir\\(tree_sitter_typescript\\)\\)\")",+ "Bash(/c/Users/ragha/Desktop/CodeWiki/.venv/Scripts/python.exe -c \"import tree_sitter_typescript; print\\(dir\\(tree_sitter_typescript\\)\\)\")",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv sync --all-packages 2>&1 | tail -5\")",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run python -c \\\\\"from wikicode.core.ingestion import ASTParser, FileTraverser, GraphBuilder; print\\('imports OK'\\)\\\\\" 2>&1\")",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/unit/ingestion/ tests/integration/ -v --tb=short 2>&1\" 2>&1)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run python -c \\\\\"from pathlib import Path; p = Path\\('packages/core/src/wikicode/core/ingestion/parser.py'\\); print\\(p.parent.parent.parent.parent.parent / 'queries'\\)\\\\\"\" 2>&1)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/unit/ingestion/test_graph.py::TestPageRank -v --tb=long 2>&1\" 2>&1)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv sync --all-packages 2>&1\" 2>&1)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/ -v --tb=short -q 2>&1\" 2>&1)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/ -q 2>&1\" 2>&1)",+ "Bash(find C:UsersraghaDesktopCodeWiki -maxdepth 3 -type d -name *generation* -o -type d -name *generate*)",+ "Bash(wc -l C:UsersraghaDesktopCodeWikipackagescoresrcwikicodecoreingestion*.py)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/unit/persistence/ -v 2>&1\" 2>&1)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/integration/test_persistence.py -v 2>&1\" 2>&1)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/ -v --tb=short 2>&1\" 2>&1)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/ -q 2>&1 | tail -20\" 2>&1)",+ "Bash(powershell.exe -Command \"uv run pytest tests/unit/cli/ -v 2>&1\")",+ "Bash(powershell.exe -Command \"uv run pytest tests/integration/test_cli.py -v 2>&1\")",+ "Bash(powershell.exe -Command \"uv run pytest tests/integration/test_cli.py::TestInitFullMock -v 2>&1\")",+ "Bash(powershell.exe -Command \"uv run pytest tests/ -q 2>&1\")",+ "Bash(powershell.exe -Command \"uv run pytest tests/unit/generation/test_page_generator.py::test_generate_file_page_provider_name -v 2>&1\")",+ "Bash(sqlite3:*)",+ "Bash(python3:*)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/unit/generation/ -v --tb=short 2>&1 | tail -60\")",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/unit/ -v --tb=short -q 2>&1 | tail -30\")",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/unit/cli/test_cost_estimator.py -v --tb=short 2>&1 | tail -30\")",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/unit/generation/ tests/unit/persistence/ tests/unit/server/ tests/unit/cli/test_commands.py -q --tb=short 2>&1 | tail -15\")",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/unit/generation/test_templates.py tests/unit/generation/test_context_assembler.py tests/unit/generation/test_page_generator.py -v --tb=short 2>&1 | tail -30\")",+ "Bash(powershell.exe -File \"C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki\\\\run_test.ps1\" 2>&1)",+ "Bash(xargs grep:*)",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run wikicode export --help 2>&1\")",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run wikicode export 'C:\\\\Users\\\\ragha\\\\Desktop\\\\interview-coach' 2>&1\")",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/unit/ingestion/test_traverser.py -v 2>&1\")",+ "Bash(powershell.exe -Command \"cd 'C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki'; uv run pytest tests/unit/cli/ tests/unit/server/ -v --tb=short -q 2>&1 | tail -30\")",+ "Bash(dir /s /b \"C:\\\\Users\\\\ragha\\\\Desktop\\\\CodeWiki\\\\packages\\\\server\\\\src\")",+ "Bash(findstr \"models.py\")",+ "Bash(find C:/Users/ragha/Desktop/CodeWiki/packages -name *.py)",+ "Bash(python -m py_compile packages/core/src/wikicode/core/analysis/decision_extractor.py)",+ "Bash(python -m py_compile packages/cli/src/wikicode/cli/commands/init_cmd.py)",+ "Bash(python -m py_compile packages/core/src/wikicode/core/ingestion/traverser.py)",+ "Bash(python -m py_compile packages/core/src/wikicode/core/ingestion/git_indexer.py)",+ "Bash(git -C \"C:/Users/ragha/Desktop/CodeWiki\" status)"+ ]+ }+}diff --git a/.env.example b/.env.examplenew file mode 100644index 000000000..3cf7ca2db--- /dev/null+++ b/.env.example@@ -0,0 +1,82 @@+# WikiCode Environment Variables+# Copy this file to .env and fill in your values.+# Never commit .env to version control.++# ---------------------------------------------------------------------------+# LLM Provider API Keys (set at least one)+# ---------------------------------------------------------------------------++# Anthropic (recommended for best results)+ANTHROPIC_API_KEY=your_anthropic_api_key_here++# OpenAI+OPENAI_API_KEY=your_openai_api_key_here++# Ollama — no API key needed, but set base URL if non-default+# OLLAMA_BASE_URL=http://localhost:11434++# LiteLLM proxy (for Together AI, Replicate, Groq, etc.)+# LITELLM_API_KEY=your_litellm_key_here+# LITELLM_BASE_URL=http://localhost:4000++# ---------------------------------------------------------------------------+# Database+# ---------------------------------------------------------------------------++# SQLite (default, no setup required)+DATABASE_URL=sqlite+aiosqlite:///./wikicode.db++# PostgreSQL (optional, for production deployments)+# DATABASE_URL=postgresql+asyncpg://user:password@localhost/wikicode++# ---------------------------------------------------------------------------+# Storage Paths+# ---------------------------------------------------------------------------++# LanceDB vector store path (used when DATABASE_URL is SQLite)+# When DATABASE_URL is PostgreSQL, pgvector is used instead — no separate path needed+LANCEDB_PATH=./data/lancedb++# Dependency graph storage path+GRAPH_PATH=./data/graphs++# ---------------------------------------------------------------------------+# Server+# ---------------------------------------------------------------------------++# Optional API key to protect WikiCode API endpoints+# Leave empty for fully open access (suitable for local use)+WIKICODE_API_KEY=++# Server bind address and port+WIKICODE_HOST=0.0.0.0+WIKICODE_PORT=7337++# MCP server port (SSE transport)+WIKICODE_MCP_PORT=7338++# ---------------------------------------------------------------------------+# Generation Defaults+# ---------------------------------------------------------------------------++# Default provider: anthropic | openai | ollama | litellm+WIKICODE_DEFAULT_PROVIDER=anthropic++# Default model (depends on provider)+WIKICODE_DEFAULT_MODEL=claude-sonnet-4-6++# Max concurrent LLM calls during generation+WIKICODE_MAX_CONCURRENT=5++# Max pages to regenerate per maintenance run+WIKICODE_CASCADE_BUDGET=30++# ---------------------------------------------------------------------------+# Development+# ---------------------------------------------------------------------------++# Set to "true" to enable debug logging+WIKICODE_DEBUG=false++# Log level: DEBUG | INFO | WARNING | ERROR+WIKICODE_LOG_LEVEL=INFOdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 000000000..01f0c958c--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,121 @@+name: CI++on:+ push:+ branches: [main, develop]+ pull_request:+ branches: [main]++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++jobs:+ # ---------------------------------------------------------------------------+ # Python tests — matrix across Python 3.11, 3.12, 3.13+ # ---------------------------------------------------------------------------+ test-python:+ name: Python ${{ matrix.python-version }} tests+ runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ python-version: ["3.11", "3.12", "3.13"]++ steps:+ - uses: actions/checkout@v4++ - name: Install uv+ uses: astral-sh/setup-uv@v3+ with:+ version: "latest"+ enable-cache: true++ - name: Set up Python ${{ matrix.python-version }}+ run: uv python install ${{ matrix.python-version }}++ - name: Install dependencies+ run: uv sync --all-packages --python ${{ matrix.python-version }}++ - name: Run provider tests (no API keys required)+ run: uv run pytest tests/providers/ -v --tb=short++ - name: Run unit tests+ run: uv run pytest tests/unit/ -v --tb=short++ # ---------------------------------------------------------------------------+ # Linting and type checking+ # ---------------------------------------------------------------------------+ lint:+ name: Lint + Type Check+ runs-on: ubuntu-latest++ steps:+ - uses: actions/checkout@v4++ - name: Install uv+ uses: astral-sh/setup-uv@v3+ with:+ version: "latest"+ enable-cache: true++ - name: Install dependencies+ run: uv sync --all-packages++ - name: Ruff lint+ run: uv run ruff check packages/ tests/++ - name: Ruff format check+ run: uv run ruff format --check packages/ tests/++ - name: mypy type check (core)+ run: uv run mypy packages/core/src --config-file pyproject.toml++ # ---------------------------------------------------------------------------+ # Integration tests (run on push to main only, slower)+ # ---------------------------------------------------------------------------+ test-integration:+ name: Integration tests+ runs-on: ubuntu-latest+ if: github.event_name == 'push'++ steps:+ - uses: actions/checkout@v4++ - name: Install uv+ uses: astral-sh/setup-uv@v3+ with:+ version: "latest"+ enable-cache: true++ - name: Install dependencies+ run: uv sync --all-packages++ - name: Run integration tests+ run: uv run pytest tests/integration/ -v --tb=short++ # ---------------------------------------------------------------------------+ # Web UI — lint and type check+ # ---------------------------------------------------------------------------+ test-web:+ name: Web UI lint + type check+ runs-on: ubuntu-latest++ steps:+ - uses: actions/checkout@v4++ - name: Set up Node.js+ uses: actions/setup-node@v4+ with:+ node-version: "20"+ cache: "npm"+ cache-dependency-path: packages/web/package.json++ - name: Install dependencies+ run: cd packages/web && npm install++ - name: Type check+ run: cd packages/web && npm run type-check++ - name: Lint+ run: cd packages/web && npm run lintdiff --git a/.gitignore b/.gitignorenew file mode 100644index 000000000..eae7971d2--- /dev/null+++ b/.gitignore@@ -0,0 +1,113 @@+# Python+__pycache__/+*.py[cod]+*$py.class+*.so+.Python+build/+develop-eggs/+dist/+downloads/+eggs/+.eggs/+lib/+lib64/+parts/+sdist/+var/+wheels/+share/python-wheels/+*.egg-info/+.installed.cfg+*.egg++# Virtual environments+.venv/+venv/+ENV/+env/++# uv+.uv/+uv.lock++# Testing+.tox/+.nox/+.coverage+.coverage.*+.cache+nosetests.xml+coverage.xml+*.cover+*.py,cover+.hypothesis/+.pytest_cache/+cover/+htmlcov/++# mypy+.mypy_cache/+.dmypy.json+dmypy.json++# ruff+.ruff_cache/++# IDEs+.idea/+.vscode/+*.swp+*.swo+*~+.DS_Store+Thumbs.db++# Node / Next.js+node_modules/+.next/+.nuxt/+out/+dist/+.npm+.eslintcache+.parcel-cache+*.tsbuildinfo+next-env.d.ts++# Environment variables+.env+.env.local+.env.*.local+!.env.example++# WikiCode runtime data+.wikicode/+!.wikicode/mcp.json.example++# Database+*.db+*.db-shm+*.db-wal+*.sqlite+*.sqlite3++# LanceDB+lancedb/+lancedb_data/+*.lance++# Logs+*.log+logs/++# Docker+docker-compose.override.yml++# OS+.DS_Store+.DS_Store?+._*+.Spotlight-V100+.Trashes+ehthumbs.dbdiff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlnew file mode 100644index 000000000..8e2d7d65a--- /dev/null+++ b/.pre-commit-config.yaml@@ -0,0 +1,41 @@+repos:+ - repo: https://github.com/pre-commit/pre-commit-hooks+ rev: v4.6.0+ hooks:+ - id: trailing-whitespace+ - id: end-of-file-fixer+ - id: check-yaml+ - id: check-toml+ - id: check-json+ - id: check-added-large-files+ args: ["--maxkb=500"]+ - id: check-merge-conflict+ - id: detect-private-key+ - id: mixed-line-ending+ args: ["--fix=lf"]++ - repo: https://github.com/astral-sh/ruff-pre-commit+ rev: v0.6.9+ hooks:+ - id: ruff+ args: ["--fix"]+ - id: ruff-format++ - repo: https://github.com/pre-commit/mirrors-mypy+ rev: v1.11.2+ hooks:+ - id: mypy+ additional_dependencies:+ - pydantic>=2.8+ - types-networkx+ args: ["--config-file=pyproject.toml"]+ files: "^packages/(core|cli|server)/src/"++ - repo: local+ hooks:+ - id: pytest-fast+ name: pytest (fast tests)+ entry: uv run pytest tests/unit/ tests/providers/ -q -x+ language: system+ pass_filenames: false+ stages: [pre-push]diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 000000000..9d6d57c74--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,38 @@+# Changelog++All notable changes to WikiCode will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++<!-- Use `git-cliff` to auto-generate entries from conventional commits -->++---++## [Unreleased]++### Added+- Monorepo scaffold: uv workspace with `packages/core`, `packages/cli`, `packages/server`, `packages/web`+- Provider abstraction layer: `BaseProvider`, `GeneratedResponse`, `ProviderError`, `RateLimitError`+- `AnthropicProvider` with prompt caching support+- `OpenAIProvider` with OpenAI Chat Completions API+- `OllamaProvider` for local offline inference (OpenAI-compatible endpoint)+- `LiteLLMProvider` for 100+ models via LiteLLM proxy+- `MockProvider` for testing without API keys+- `RateLimiter`: async sliding-window RPM + TPM limits with exponential backoff+- `ProviderRegistry`: dynamic provider loading with custom provider registration+- CI pipeline: GitHub Actions matrix on Python 3.11, 3.12, 3.13+- Pre-commit hooks: ruff lint + format, mypy, standard file checks+- **Folder exclusion** — three-layer system for skipping paths during ingestion:+ - `FileTraverser(extra_exclude_patterns=[...])` — pass gitignore-style patterns at construction time; applied to both directory pruning and file-level filtering+ - Per-directory `.wikicodeIgnore` — traverser loads one from each visited directory (like git's per-directory `.gitignore`); patterns are relative to that directory and cached for efficiency+ - `wikicode init --exclude/-x PATTERN` — repeatable CLI flag; patterns are merged with `exclude_patterns` from `config.yaml` and persisted back to `.wikicode/config.yaml`+ - `wikicode update` reads `exclude_patterns` from `config.yaml` automatically+ - Web UI **Excluded Paths** section on `/repos/[id]/settings`: chip editor, Enter-to-add input, six quick-add suggestions (`vendor/`, `dist/`, `build/`, `node_modules/`, `*.generated.*`, `**/fixtures/**`), empty-state message, gitignore-syntax tooltip; saved via `PATCH /api/repos/{id}` as `settings.exclude_patterns`+ - `helpers.save_config()` now round-trips `config.yaml` to preserve all existing keys when updating provider/model/embedder; accepts optional `exclude_patterns` keyword argument+ - `scheduler.py` logs `repo.settings.exclude_patterns` in polling fallback as preparation for future full-sync wiring+- 13 new unit tests in `tests/unit/ingestion/test_traverser.py` covering `extra_exclude_patterns` and per-directory `.wikicodeIgnore` behaviour++---++[Unreleased]: https://github.com/wikicode-ai/wikicode/compare/HEADdiff --git a/Makefile b/Makefilenew file mode 100644index 000000000..e6a3304fb--- /dev/null+++ b/Makefile@@ -0,0 +1,87 @@+.PHONY: install install-dev test test-unit test-integration test-e2e test-providers \+ lint format typecheck clean build-web dev-web help++# ---------------------------------------------------------------------------+# Setup+# ---------------------------------------------------------------------------++install: ## Install all Python packages in the workspace+ uv sync --all-packages++install-dev: ## Install all packages including dev dependencies+ uv sync --all-packages --all-extras++# ---------------------------------------------------------------------------+# Testing+# ---------------------------------------------------------------------------++test: ## Run all tests+ uv run pytest tests/ -v++test-unit: ## Run unit tests only+ uv run pytest tests/unit/ -v++test-integration: ## Run integration tests only+ uv run pytest tests/integration/ -v++test-e2e: ## Run end-to-end tests only+ uv run pytest tests/e2e/ -v++test-providers: ## Run provider tests only (no API keys required)+ uv run pytest tests/providers/ -v++test-fast: ## Run unit + provider tests (fast, no fixtures needed)+ uv run pytest tests/unit/ tests/providers/ -v -q++# ---------------------------------------------------------------------------+# Code Quality+# ---------------------------------------------------------------------------++lint: ## Run ruff linter+ uv run ruff check packages/ tests/++format: ## Run ruff formatter+ uv run ruff format packages/ tests/++format-check: ## Check formatting without modifying files+ uv run ruff format --check packages/ tests/++typecheck: ## Run mypy type checker+ uv run mypy packages/core/src packages/cli/src packages/server/src++check: lint format-check typecheck ## Run all checks (no modifications)++fix: format lint ## Format + lint with auto-fix++# ---------------------------------------------------------------------------+# Web UI+# ---------------------------------------------------------------------------++dev-web: ## Start Next.js dev server+ cd packages/web && npm run dev++build-web: ## Build Next.js production output+ cd packages/web && npm run build++install-web: ## Install Node dependencies for web package+ cd packages/web && npm install++# ---------------------------------------------------------------------------+# Utilities+# ---------------------------------------------------------------------------++clean: ## Remove build artifacts and caches+ find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true+ find . -type d -name .pytest_cache -exec rm -rf {} + 2>/dev/null || true+ find . -type d -name .mypy_cache -exec rm -rf {} + 2>/dev/null || true+ find . -type d -name .ruff_cache -exec rm -rf {} + 2>/dev/null || true+ find . -name "*.pyc" -delete 2>/dev/null || true+ find . -name "*.pyo" -delete 2>/dev/null || true+ find . -type d -name "*.egg-info" -exec rm -rf {} + 2>/dev/null || true++build: ## Build all Python distributions+ uv build --all-packages++help: ## Show this help message+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) \+ | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'diff --git a/docker/README.md b/docker/README.mdnew file mode 100644index 000000000..c067cd540--- /dev/null+++ b/docker/README.md@@ -0,0 +1,6 @@+# Docker++> Built in Phase 9. Placeholder file.++The multi-stage Dockerfile and docker-compose.yml will be implemented in Phase 9.+See `BUILD_STATUS.md` for current status.diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdnew file mode 100644index 000000000..231bd2519--- /dev/null+++ b/docs/ARCHITECTURE.md@@ -0,0 +1,1480 @@+# WikiCode Architecture++WikiCode is an open-source, self-hostable codebase documentation engine. It generates+a structured, hierarchical wiki for any codebase, keeps it accurate as code changes,+and exposes everything through an MCP server so AI coding assistants can query it+in real time.++This document covers how the system is built, why each piece exists, and how+they fit together. Read this before contributing.++### Package READMEs++For per-package detail (installation, full API reference, all CLI flags, file maps):++| Package | README | What it covers |+|---------|--------|----------------|+| `packages/core` | [`packages/core/README.md`](../packages/core/README.md) | Ingestion, generation, persistence, providers — all key classes with code examples |+| `packages/cli` | [`packages/cli/README.md`](../packages/cli/README.md) | All 10 CLI commands with every flag documented |+| `packages/server` | [`packages/server/README.md`](../packages/server/README.md) | All REST API endpoints, 13 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 |++---++## Table of Contents++1. [System Overview](#1-system-overview)+2. [Repository Structure](#2-repository-structure)+3. [The Three Stores](#3-the-three-stores)+4. [Provider Abstraction Layer](#4-provider-abstraction-layer)+5. [Init Path — First-Time Documentation](#5-init-path--first-time-documentation)+6. [Maintenance Path — Keeping Docs in Sync](#6-maintenance-path--keeping-docs-in-sync)+7. [Git Intelligence](#7-git-intelligence)+8. [Dead Code Detection](#8-dead-code-detection)+9. [Decision Intelligence](#9-decision-intelligence)+10. [MCP Server](#10-mcp-server)+11. [REST API and Web UI](#11-rest-api-and-web-ui)+12. [Data Flow Diagrams](#12-data-flow-diagrams)+13. [Key Design Decisions](#13-key-design-decisions)+14. [Adding a New Language](#14-adding-a-new-language)+15. [Adding a New LLM Provider](#15-adding-a-new-llm-provider)++---++## 1. System Overview++```+┌─────────────────────────────────────────────────────────────────────┐+│ Sources │+│ GitHub / GitLab repo Local filesystem │+└────────────────────┬────────────────────────┬───────────────────────┘+ │ webhook / git diff │ wikicode init/update+ ▼ ▼+┌─────────────────────────────────────────────────────────────────────┐+│ Core Engine │+│ │+│ ┌─────────────────────┐ ┌──────────────────────────────┐ │+│ │ Ingestion Pipeline │ │ Generation Engine │ │+│ │ │ │ │ │+│ │ FileTraverser │─────▶│ ContextAssembler │ │+│ │ ASTParser │ │ PageGenerator (hierarchical) │ │+│ │ GraphBuilder │ │ JobSystem (resumable) │ │+│ │ ChangeDetector │ │ PromptTemplates (Jinja2) │ │+│ │ GitIndexer │ │ │ │+│ │ DeadCodeAnalyzer │ │ │ │+│ └─────────────────────┘ └──────────────┬───────────────┘ │+│ │ │+│ ┌───────────────▼──────────────┐ │+│ │ LLM Provider Layer │ │+│ │ Anthropic │ OpenAI │ Ollama │ │+│ │ │ LiteLLM │ │ │+│ └───────────────────────────────┘ │+└──────────────┬─────────────────────────┬────────────────────────────┘+ │ │+ ▼ ▼+┌──────────────────────┐ ┌─────────────────────────────────────────┐+│ Three Stores │ │ Consumers │+│ │ │ │+│ SQL (wiki pages, │ │ Web UI MCP Server GitHub Action │+│ jobs, symbols, │ │ (Next.js) (16 tools) (CI/CD) │+│ versions) │ │ │+│ │ │ wikicode CLI │+│ Vector (LanceDB / │ │ (init, update, watch, │+│ pgvector, semantic │ │ search, export, serve, mcp) │+│ search, RAG ctx) │ │ │+│ │ └─────────────────────────────────────────┘+│ Graph (NetworkX, │+│ dep graph, │+│ PageRank, SCC) │+└──────────────────────┘+```++WikiCode has two operational modes that share the same core engine but follow+different strategies:++- **Init** — first-time documentation of an existing codebase. May take minutes+ to hours on large repos. Resumable. Supports batch API for cheaper generation.+- **Maintenance** — incremental updates triggered by git commits. Runs in seconds+ to minutes. Uses change propagation through the dependency graph to only regenerate+ what actually changed.++---++## 2. Repository Structure++```+wikicode/+├── packages/+│ ├── core/ # Python: ingestion + generation engine+│ │ ├── src/wikicode/core/+│ │ │ ├── ingestion/+│ │ │ │ ├── traverser.py # file tree walking + gitignore + per-dir .wikicodeIgnore + extra exclude patterns+│ │ │ │ ├── parser.py # ASTParser — one class, all languages+│ │ │ │ ├── parsers/ # per-language parser helpers+│ │ │ │ ├── graph.py # NetworkX dep graph builder+│ │ │ │ ├── change_detector.py # git diff + change propagation+│ │ │ │ ├── git_indexer.py # git history mining → git_metadata table+│ │ │ │ ├── special_handlers.py # OpenAPI, Protobuf, GraphQL, Dockerfile, CI YAML+│ │ │ │ └── models.py # ParsedFile, FileInfo, Symbol, Import, etc.+│ │ │ ├── analysis/+│ │ │ │ └── dead_code.py # dead code detection (graph + SQL, no LLM)+│ │ │ ├── generation/+│ │ │ │ ├── page_generator.py # hierarchical page generator+│ │ │ │ ├── context_assembler.py# context assembly (RAG + graph + git + source)+│ │ │ │ ├── job_system.py # resumable job state machine+│ │ │ │ ├── models.py # GeneratedPage, GenerationConfig, PageType, etc.+│ │ │ │ └── templates/ # Jinja2 prompt templates (one per page type)+│ │ │ ├── persistence/+│ │ │ │ ├── models.py # SQLAlchemy ORM models+│ │ │ │ ├── crud.py # async CRUD layer+│ │ │ │ ├── database.py # engine factory, session management+│ │ │ │ ├── search.py # SQLite FTS5 full-text search+│ │ │ │ ├── vector_store.py # VectorStore abstraction (LanceDB / pgvector)+│ │ │ │ └── embedder.py # Embedder base class + MockEmbedder+│ │ │ ├── providers/ # LLM provider abstraction+│ │ │ │ ├── base.py # BaseProvider, GeneratedResponse, ProviderError+│ │ │ │ ├── anthropic.py+│ │ │ │ ├── openai.py+│ │ │ │ ├── ollama.py+│ │ │ │ ├── litellm.py+│ │ │ │ ├── mock.py+│ │ │ │ └── registry.py # get_provider(), register_provider(), list_providers()+│ │ │ └── rate_limiter.py # token-bucket RPM + TPM limiter+│ │ └── queries/ # tree-sitter .scm query files (one per language)+│ │ ├── python.scm+│ │ ├── typescript.scm+│ │ ├── javascript.scm+│ │ ├── go.scm+│ │ ├── rust.scm+│ │ ├── java.scm+│ │ ├── cpp.scm+│ │ ├── c.scm+│ │ ├── ruby.scm+│ │ └── kotlin.scm+│ │+│ ├── server/ # Python: FastAPI REST API + MCP server+│ │ └── src/wikicode/server/+│ │ ├── api/ # FastAPI routers (repos, pages, jobs, symbols, graph, git, dead-code, decisions, search)+│ │ ├── mcp_server.py # MCP server (16 tools)+│ │ ├── webhooks/ # GitHub + GitLab handlers+│ │ └── scheduler.py # APScheduler background jobs+│ │+│ ├── cli/ # Python: wikicode CLI (click + rich)+│ │ └── src/wikicode/cli/+│ │ └── commands/ # init, update, watch, serve, search, export, status, doctor, dead-code, decision, mcp+│ │+│ └── web/ # Next.js 15 frontend+│ ├── src/app/ # App Router pages (dashboard, wiki, search, graph, symbols, …)+│ ├── src/components/ # UI primitives, layout, wiki, repos, jobs, settings+│ └── src/lib/ # API client, SWR hooks, utilities, design tokens+│+├── integrations/+│ ├── github-action/ # action.yml + Dockerfile entrypoint+│ └── github-app/ # GitHub App webhook handler+│+├── docker/+│ ├── Dockerfile # multi-stage: Python + Node build + final runtime+│ └── docker-compose.yml # with optional Redis profile+│+├── tests/+│ ├── unit/ # unit tests (no LLM calls, no filesystem)+│ ├── integration/ # integration tests using sample_repo fixture+│ ├── e2e/ # full wikicode init + update flows+│ └── fixtures/+│ └── sample_repo/ # 30-file multi-language fixture repo+│+└── docs/ # WikiCode's own generated wiki (dogfooding)+```++---++## 3. The Three Stores++WikiCode uses three separate storage systems. They are not redundant — each answers+a fundamentally different kind of question that the other two cannot answer efficiently.++### 3.1 SQL Store (SQLAlchemy + SQLite / PostgreSQL)++**Answers: what exists, what changed, when.**++The source of truth for all structured data. SQLite in development and single-server+deployments; PostgreSQL for multi-worker production deployments. The schema is identical+for both — SQLAlchemy abstracts the difference.++Key tables:++| Table | Purpose |+|-------|---------|+| `repos` | Registered repositories, sync state, provider config |+| `wiki_pages` | All generated wiki pages with content, metadata, confidence score |+| `page_versions` | Full version history of every page (for diff view) |+| `symbols` | Symbol index: every function, class, method across all files |+| `generation_jobs` | Job state machine with checkpoint fields for resumability |+| `webhook_events` | Every received webhook event (deduplication, audit, retry) |+| `symbol_rename_history` | Detected renames for auditing and targeted text patching |+| `graph_nodes` / `graph_edges` | SQLite-backed graph for repos exceeding 30K nodes |+| `git_metadata` | Per-file git history: commit counts, ownership, co-change partners, hotspot/stable flags |+| `dead_code_findings` | Dead code findings: unreachable files, unused exports, zombie packages |++If you delete the SQL store, you lose everything and must re-run `wikicode init`.++### 3.2 Vector Store (LanceDB embedded / pgvector)++**Answers: what is semantically similar to this query.**++WikiCode uses a `VectorStore` abstraction with two backends, selected automatically+based on the configured SQL backend:++**LanceDB (default — SQLite mode)**+LanceDB runs embedded as a library — no separate server process. Data is stored in+`.wikicode/lancedb/` using the Lance columnar format. This makes self-hosting trivial+and keeps the Docker setup simple. LanceDB is significantly faster than ChromaDB on+both write throughput (batch embedding) and ANN query latency, and it requires no+C++ build tools to install.++**pgvector (PostgreSQL mode)**+When WikiCode is configured with a PostgreSQL database, the `wiki_pages` table gains+an `embedding vector(N)` column via the `pgvector` PostgreSQL extension. Embeddings+are stored directly in the same SQL database — no second storage system required.+Vector similarity search uses `<=>` (cosine distance) with an HNSW index. This is+the preferred backend for multi-worker production deployments.++Every generated wiki page is embedded and stored immediately after generation.+The vector store is used in two distinct ways:++**During generation (RAG context):** When generating a wiki page for file A, the+`ContextAssembler` queries the vector store with A's exported symbol names to find+pages for files that A imports from. These are included as context in the generation+prompt. Each generated page is aware of what its dependencies actually *do* —+not just their names. See [Section 5.4](#54-context-assembly) for details.++**During search and MCP queries:** The `search_codebase` MCP tool and the web UI+search page use the vector store to find the most semantically relevant pages for a+natural language query. This is better than full-text search for questions like+"how does authentication work?" or "where is rate limiting handled?".++If you delete the vector store (LanceDB directory or pgvector embeddings), search+quality degrades and generation context becomes shallower — rebuild it by running+`wikicode index --rebuild` which re-embeds all existing SQL pages.++### 3.3 Graph Store (NetworkX / SQLite-backed)++**Answers: how are things connected, and how important are they.**++The dependency graph is a directed multigraph where nodes are files and symbols,+and edges are relationships (`imports`, `calls`, `inherits`, `implements`, etc.).++It is built by the `ASTParser` + `GraphBuilder` during ingestion and persisted to+`.wikicode/graph.json` (for repos ≤ 30K nodes) or the `graph_nodes`/`graph_edges`+SQL tables (for larger repos, using the `networkit` library as a drop-in).++The graph is used for:++- **Generation ordering** — topological sort determines what to generate first+ (files with no dependents get generated before files that import them, so the+ richer context is available via RAG when the importing file is generated)+- **Change propagation** — when a file changes, walk the graph to find all+ pages that reference its symbols and mark them as stale+- **PageRank** — identifies the most central, important symbols; these get+ "spotlight" wiki pages and richer generation prompts+- **SCC detection** — circular dependency clusters require a special generation+ strategy (see [Section 5.3](#53-circular-dependencies))+- **Co-change edges** — temporal coupling from git history. Files that frequently+ change together (but may have no import relationship) get `co_changes` edges.+ These participate in change propagation and are shown in the graph visualization+ as dashed purple lines. They do NOT affect PageRank.+- **Dead code detection** — files with `in_degree == 0` (no importers) are+ candidates for unreachable file detection+- **MCP `get_dependency_path` tool** — answers "how is module A connected to module B?"+- **D3 graph visualization** in the web UI++If you delete the graph, WikiCode loses change propagation and generation ordering.+It can be rebuilt from scratch by re-parsing the source files.++---++## 4. Provider Abstraction Layer++Every LLM call in the entire system goes through `LLMProvider`. No provider SDK+is ever imported from business logic packages.++```+ ┌─────────────────┐+ │ LLMProvider │ (abstract base class)+ │ │+ │ generate() │+ │ generate_stream│+ │ embed() │+ │ generate_batch │ (optional, default = sequential)+ │ estimate_cost │ (optional, returns None if unknown)+ └────────┬────────┘+ │+ ┌──────────────────┼──────────────────┬──────────────────┐+ ▼ ▼ ▼ ▼+ AnthropicProvider OpenAIProvider OllamaProvider LiteLLMProvider+ (claude-*) (gpt-*, any (any local model, (100+ providers,+ batch API + prompt OpenAI-compat fully offline, optional dep)+ caching support) endpoint) no API key)+```++### 4.1 Rate Limiter++Each provider instance wraps a `RateLimiter` using a token-bucket algorithm with+two independent buckets: requests-per-minute (RPM) and tokens-per-minute (TPM).++Before every API call, the limiter acquires from both buckets. On a 429 response,+it calls `on_rate_limit_error()` which applies exponential backoff and temporarily+reduces the refill rate. This is transparent to all callers.++Default limits are configured per provider in `.wikicode/config.yaml` and can be+adjusted for users with higher API tiers.++### 4.2 Batch Mode (Init Only)++For `wikicode init`, the Anthropic provider supports the Message Batches API:+instead of firing concurrent streaming requests, all file-page generation requests+for a given level are submitted as a single batch, which is ~50% cheaper and+processes asynchronously (typically within 1 hour).++Batch mode is enabled by default for `wikicode init` when using the Anthropic+provider. Pass `--no-batch` to use streaming instead (faster wall-clock time,+higher cost).++### 4.3 Prompt Caching++For Anthropic: the `ContextAssembler` marks the system prompt + shared repository+context with cache-control breakpoints. Across the hundreds of file-page generation+calls during a large init, this shared prefix is only billed once. Cost reduction+on large repos is typically 60–90%.++### 4.4 Adding a Provider++Implement `LLMProvider`, add an entry to `LANGUAGE_CONFIGS` in `providers/registry.py`,+and add a section to `.wikicode/config.yaml`. See [Section 12](#12-adding-a-new-llm-provider).++---++## 5. Init Path — First-Time Documentation++`wikicode init` runs when documenting a codebase for the first time. It is the+expensive, one-time operation that builds the full wiki from scratch.++### 5.1 File Traversal++`FileTraverser` walks the repository tree and produces a `FileInfo` for every+file that should be documented. It respects six layers of exclusion, applied in+priority order:++1. `.gitignore` (parsed with `pathspec`, not simple glob matching)+2. Root `.wikicodeIgnore` (same syntax, user-defined at repo root)+3. **Per-directory `.wikicodeIgnore`** — loaded from each directory visited during+ the `os.walk`. Patterns are relative to the directory containing the file (like+ git's per-directory `.gitignore`). A spec per directory is loaded once and cached+ for the traversal. Example: `generated/` in `src/.wikicodeIgnore` skips+ `src/generated/` without affecting other directories with the same name.+4. **`extra_exclude_patterns`** (constructor param) — additional gitignore-style+ patterns passed at runtime from `--exclude/-x` CLI flags or+ `repo.settings["exclude_patterns"]` (set via Web UI or REST API PATCH). Applied+ to both directory pruning (entire subtree skipped) and individual file filtering.+5. Hardcoded blocklist (`node_modules`, `.git`, `__pycache__`, `dist`, `build`,+ `*.lock`, `*.min.js`, generated protobuf files, etc.)+6. Auto-detection of generated files (files with `// Code generated` headers)+7. Binary files (detected by null bytes in first 8KB)+8. Files over `max_file_size_kb` (default: 500KB)++**Constructor signature:**+```python+FileTraverser(+ repo_root: Path,+ *,+ max_file_size_kb: int = 500,+ extra_ignore_filename: str = ".wikicodeIgnore",+ extra_exclude_patterns: list[str] | None = None,+)+```++**Where `extra_exclude_patterns` comes from:**++| Source | How patterns reach traverser |+|--------|------------------------------|+| `wikicode init -x vendor/ -x 'src/gen/**'` | Merged with `config.yaml exclude_patterns`, passed directly |+| `wikicode update` | Read from `.wikicode/config.yaml exclude_patterns` |+| Web UI Excluded Paths section | Saved to `repo.settings["exclude_patterns"]` via REST API |+| Server sync job | Read from `repo.settings.get("exclude_patterns", [])` |++The traverser also detects monorepo structure by looking for multiple+`pyproject.toml`, `package.json`, `go.mod`, or `Cargo.toml` files at depth 1–2.+When detected, each package is documented as a semi-independent unit with+cross-package edges tracked in the graph.++Each `FileInfo` is tagged with: `language`, `is_test`, `is_config`, `is_api_contract`,+`is_entry_point`, `git_hash`. These tags influence generation priority and prompt choice.++### 5.2 AST Parsing++`ASTParser` is a single class that handles all supported languages. There are no+per-language subclasses.++**How it works:**++1. Calls `get_parser(language)` from `tree-sitter-languages` to get the right grammar+2. Parses the source into a tree-sitter parse tree+3. Loads the corresponding `queries/<language>.scm` file (cached after first load)+4. Runs tree-sitter queries to extract symbols, imports, and exports+5. Maps results through `LANGUAGE_CONFIGS[language]` for language-specific rules+ (visibility keywords, entry point patterns, etc.)+6. Returns a `ParsedFile` with a consistent shape regardless of language++**The `.scm` query files** use standard tree-sitter S-expression syntax with+consistent capture name conventions across all languages:+- `@symbol.def` — the full symbol node+- `@symbol.name` — the name identifier+- `@symbol.params` — parameter list+- `@symbol.return_type` — return type annotation+- `@symbol.docstring` — existing docstring (expanded, not repeated, by the LLM)+- `@import.statement` — full import node+- `@import.module` — the module being imported++**Adding a new language** = write one `.scm` file + add one entry to `LANGUAGE_CONFIGS`.+No changes to `ASTParser` itself. See [Section 11](#11-adding-a-new-language).++**Special handlers** live in `core/special_handlers/` and are separate from `ASTParser`.+They handle file types that are not programming languages (OpenAPI specs, Dockerfiles,+GitHub Actions YAML, Makefiles, Protobuf, GraphQL schemas). They produce the same+`ParsedFile` shape but use purpose-built parsers (PyYAML, `graphql-core`, etc.)+instead of tree-sitter.++### 5.3 Dependency Graph Construction++`GraphBuilder` takes all `ParsedFile` outputs and builds a `networkx.DiGraph`.++**Node types:**+- `file` — every source file+- `symbol` — every function, class, interface, etc.+- `package` — every package/module directory+- `external` — third-party packages (lightweight node, not fully documented)++**Edge types:**+- `imports` — file A imports from file B+- `calls` — symbol A calls symbol B+- `inherits` — class A extends class B+- `implements` — class A implements interface B+- `instantiates` — code in A creates an instance of B+- `references` — looser reference (type annotation, generic, etc.)+- `re-exports` — A re-exports symbols from B (barrel files)+- `inter_package` — edge crossing package boundary (monorepos)+- `co_changes` — A and B frequently change in the same commit (from git history,+ added by `GitIndexer` after graph construction). Weight = co-change count.+ Filtered out of PageRank but included in change propagation and visualization.++After graph construction, the builder computes:++- **PageRank** — nodes with high PageRank are central and well-connected.+ Used to decide generation priority and which symbols get spotlight pages.+- **Strongly Connected Components (SCCs)** — groups of files with circular imports.+ Logged as warnings. Require special generation handling (see below).+- **Betweenness centrality** — identifies "bridge" symbols whose removal would+ disconnect the graph. These are the most critical to document well.+- **Community detection (Louvain)** — discovers logical modules even when the+ directory structure doesn't reflect them. These communities become module pages.++**Circular dependency handling:**++Files in an SCC cannot be generated in strict bottom-up order because each one+depends on the others. Strategy:+1. Generate each SCC member with reduced context (own source + signatures of+ cycle partners only, no full docs)+2. Generate a dedicated `SCC` wiki page explaining the cycle and how to navigate it+3. In a second pass, upgrade each member's page with cross-references to the others++**Graph scalability:**++For repos with fewer than 30K nodes, the graph lives in memory as a NetworkX+`DiGraph` and is serialized to `.wikicode/graph.json`.++For repos exceeding 30K nodes (configurable via `graph_backend: sqlite`), WikiCode+switches to `networkit` with SQLite backing via the `graph_nodes` and `graph_edges`+tables. Only the subgraph needed for each operation is loaded into memory. The+API is identical — this is transparent to all callers.++### 5.4 Context Assembly++This is the most important quality driver in the system. The `ContextAssembler`+builds the prompt context for each generation call — it does not just dump the+raw source file.++For a given file page, it assembles context in this priority order (dropping+lower-priority items if the token budget is exceeded):++1. **Source code** — full source (or chunked if file is large)+2. **Symbol signatures** — all symbols extracted from this file with their+ signatures and existing docstrings+3. **Graph context** — PageRank score, cluster membership, which module this+ belongs to, entry point status+4. **Git context** — ownership, significant commit messages explaining *why* code+ evolved, hotspot/stable classification, co-change partners. This transforms+ documentation from "here is what this code does" into "here is what it does+ and why it was written this way." Git context is the last thing dropped when+ over budget — it is more valuable than import summaries.+5. **Import summaries** — for each file this file imports from: the summary of+ that file's already-generated wiki page (if available), or just its public+ API signatures (if not yet generated)+6. **RAG context** — vector store similarity search (LanceDB or pgvector) using this file's top exported+ symbols as the query. Returns the top 3 most relevant already-generated pages.+ This propagates understanding upward: `AuthService`'s page will know what+ `UserRepository` actually does, not just that it imports from it.+7. **Co-change context** — wiki pages for co-change partners (files that change+ together without an import relationship). Reveals hidden coupling.+8. **Dead code findings** — symbols in this file flagged as unused (if any).+ Listed in the generation prompt so the LLM notes them as cleanup candidates.+9. **Reverse import context** — which files import *this* file, and what they+ use from it. Helps the LLM understand how this file is used in practice.++Token budget: the total assembled context targets 12K tokens, leaving room for+the generation output. Items are dropped in reverse priority order when over budget.+The source code is never dropped — it is chunked instead if too large.++**Large file chunking:**++Files over `large_file_threshold_kb` (default: 100KB) are handled differently.+Rather than passing the full source, WikiCode:+1. Extracts public symbol signatures only for the top-level context+2. Generates one sub-page per major class or function group+3. Synthesizes a file page from the sub-pages+Pages generated from chunks are tagged `chunked: true` in metadata.++### 5.5 Hierarchical Generation Order++Generation must follow a strict dependency-aware order. This is not optional —+generating a module page before its file pages means the module page has no+content to draw from.++```+Level 0: External API contracts (OpenAPI, proto, GraphQL)+ → self-contained, no dependencies on other pages++Level 1: Symbol spotlight pages (top 10% by PageRank)+ → short, fast, parallelizable+ → high-PageRank symbols get richer documentation++Level 2: File pages+ → uses: source + symbol docs + import summaries (from RAG)+ → parallelizable within this level+ → SCC members generate with stubs, upgraded in second pass++Level 3: SCC pages+ → must wait for all member files to complete Level 2++Level 4: Module/package pages+ → uses: all file pages within the module++Level 5: Cross-package relationship pages (monorepos only)+ → uses: all package pages++Level 6: Repository overview + architecture diagram+ → uses: all module pages + graph metrics++Level 7: Config/infra pages (Dockerfile, CI YAML, Makefile, etc.)+ → references code pages, so comes after all code docs++Level 8: Index pages (symbol index, search index)+ → built from all completed pages+```++Within each level, up to `concurrent_jobs` tasks run in parallel using+`asyncio.Semaphore`. The generation engine never exceeds this limit regardless+of how large the repo is.++Each generated page gets a `confidence_score` of `1.0` when first created.++### 5.6 Resumable Jobs++Init on a 50K-file repo can take 30–90 minutes. A crash or network interruption+should not require starting over.++The `JobSystem` persists checkpoint state after every completed page:+- `checkpoint_level` — which generation level is currently active+- `checkpoint_file_index` — position within the current level+- `completed_page_ids` — list of already-generated page IDs+- `failed_page_ids` — pages that failed (retried on resume)++On `wikicode init --resume`, the job is loaded from the database, completed pages+are skipped, and generation continues from the last checkpoint.++`wikicode init` is fully idempotent. Running it twice produces the same result.+Running it after a partial previous run completes only the remaining pages.++---++## 6. Maintenance Path — Keeping Docs in Sync++`wikicode update` runs after a git push (triggered by webhook, GitHub Action, or+polling fallback). It is fast, targeted, and avoids regenerating pages that+haven't actually changed in a meaningful way.++### 6.1 Change Detection++`ChangeDetector` uses GitPython to compute the diff between `last_sync_commit`+and `HEAD`:++```python+changed_files = differ.get_changed_files(repo_path, since_commit="a1b2c3d")+# → ChangedFiles(added=[...], modified=[...], deleted=[...], renamed=[...])+```++Renamed files get special treatment: WikiCode updates all `source_files` references+in existing wiki pages and regenerates the file page (since the path context has+changed), but does *not* regenerate pages that only reference the file's symbols+(symbol names don't include paths).++### 6.2 Symbol Rename Detection++`ChangeDetector.detect_symbol_renames()` uses a heuristic to identify when a+symbol was renamed rather than deleted-and-recreated:+- Same `kind` (function → function)+- Similar signature (Levenshtein distance under threshold)+- Git blame on the new file confirms line provenance++When a rename is detected, WikiCode applies a targeted text patch to all pages+that only *mention* the old name (cheaper than full regeneration), and fully+regenerates pages that *document* the old symbol.++All detected renames are stored in `symbol_rename_history` for audit purposes.++### 6.3 Affected Page Computation++For each changed file, `ChangeDetector.get_affected_pages()` walks the dependency+graph to find all pages that need updating:++```+Changed file → find its symbols+ → find all wiki pages that document those symbols (direct)+ → find all wiki pages that reference those symbols (1-hop: inherits/calls)+ → find all wiki pages that reference referencing pages (2-hop: looser reference)+ → apply cascade budget+```++**Cascade budget:**++A change to a central utility module (e.g., `utils.py` imported by 200 files) would+naively require regenerating 200+ pages on every push. This is too expensive.++The `cascade_budget` config option (default: 30 pages per maintenance run) caps the+number of pages fully regenerated per push. Pages beyond the budget:+- Have their `confidence_score` decayed (see below)+- Are added to the background staleness queue+- Are regenerated by the nightly background job++### 6.4 Confidence Score System++Every wiki page has a `confidence_score` (float 0.0–1.0) representing how fresh+it is relative to the source code:++| Score | Status | Badge | Action |+|-------|--------|-------|--------|+| ≥ 0.80 | fresh | green | none |+| 0.60–0.79 | stale | yellow | queued for background regen |+| 0.30–0.59 | outdated | red | auto-queued, warning shown |+| < 0.30 | unusable | red (prominent) | force-regenerated immediately |++Decay rules applied on each maintenance run:+- Source file directly changed: `score *= 0.85`+- Referenced symbol changed (1-hop: calls/inherits): `score *= 0.95`+- Referenced symbol changed (2-hop: looser reference): `score *= 0.98`+- Co-change partner changed (no import relationship): `score *= 0.97`+- Page beyond cascade budget (time-based, 1 week since change): `score *= 0.90`++**Git-informed decay modifiers** (applied multiplicatively on top of base decay):+- Hotspot file (`is_hotspot=True`) → decays faster: direct `*= 0.94`, 1-hop `*= 0.95`+- Stable file (`is_stable=True`) → decays slower: direct `*= 1.03`+- Large change in commit message ("rewrite", "refactor", "migrate") → hard decay:+ direct `*= 0.71`, 1-hop `*= 0.84`+- Cosmetic change in commit message ("typo", "lint", "format") → soft decay:+ direct `*= 1.12`++Pages start at `1.0` and decay over time. Regeneration resets to `1.0`.++### 6.5 Webhook Reliability++Webhooks can be missed when the WikiCode server is down during a push. WikiCode+uses a two-layer sync strategy:++**Layer 1 (real-time):** GitHub/GitLab webhook → `POST /api/webhooks/github` →+signature verification → store in `webhook_events` → enqueue `GenerationJob`.+Response is always `200 OK` immediately — processing is async.++**Layer 2 (polling fallback):** APScheduler job runs every 15 minutes (configurable).+Compares `repos.last_sync_commit` against actual `HEAD` via GitHub API or GitPython.+If they differ, triggers an incremental update for the missing commits.++The combination ensures: even if a webhook is missed entirely, docs are at most+`polling_interval` minutes stale for the default branch.++### 6.6 Background Staleness Resolution++APScheduler runs a nightly job (configurable via cron expression) to:+1. Query all pages where `confidence_score < staleness_regen_threshold` (default: 0.60)+2. Sort by `confidence_score ASC` (most stale first)+3. Regenerate up to `background_regen_budget` pages (default: 100)+4. Log token usage and cost++This ensures no page stays stale indefinitely regardless of cascade budget constraints.++### 6.7 PR Documentation Preview++On `pull_request` webhook events, WikiCode runs `ChangeDetector` in dry-run mode+and posts a GitHub PR comment listing:+- Pages that will be regenerated (with links to current versions)+- Pages that will have confidence decay+- New pages that will be created (new files)+- Pages that will be deleted (deleted files)+- Estimated token cost for this PR's docs update++On merge, the actual incremental update runs.++---++## 7. Git Intelligence++WikiCode mines git history to make documentation significantly richer and more useful.+The `GitIndexer` runs once during `wikicode init` (after graph construction, before+generation) and incrementally during `wikicode update`. All git features degrade+gracefully when git metadata is unavailable — they simply skip git-enriched context.++### 7.1 GitIndexer (`packages/core/ingestion/git_indexer.py`)++The `GitIndexer` class mines git history into the `git_metadata` SQL table. For each+tracked file, it computes:++- **Commit volume** — total, last 90 days, last 30 days (churn signals)+- **Timeline** — first and last commit dates (file age)+- **Ownership** — primary owner from `git blame` (who wrote the most lines),+ top 3 contributors by commit count+- **Significant commits** — last 10 meaningful commit messages (filtered: no merges,+ no dependency bumps, no chore/ci, messages > 20 chars). These explain *why*+ the code evolved this way and are included in generation prompts.+- **Co-change partners** — files that changed in the same commit >= 3 times, even+ without an import relationship. Reveals hidden structural coupling.+- **Derived signals** — `is_hotspot` (top 25% churn AND complexity), `is_stable`+ (>10 commits, 0 in 90 days), `churn_percentile` (0.0–1.0)++**Performance targets:**+- 3,000 files, 10K commits → < 3 minutes+- 50,000 files, 100K commits → < 20 minutes (uses shallow history for large repos)+- Uses `asyncio.Semaphore(20)` to parallelize git log calls across files++### 7.2 How Git Intelligence Enhances Each Component++**Generation prompts:** The `file_page.j2` template includes optional git context+blocks (gated on `{% if git_metadata %}`). These add ownership attribution, evolution+context from significant commits, hotspot/stable warnings, and co-change partner+documentation. The LLM uses commit messages to explain *why* code is structured as+it is, not just *what* it does.++**Generation ordering:** Within each level, files are sorted by priority: entry+points first, then hotspots, then high PageRank, then high commit count. This+ensures the most important files generate first, making them available as RAG+context for less important files.++**Generation depth:** Files can be auto-upgraded to "thorough" depth if they are+hotspots, have > 100 commits with > 10 in 90 days, have >= 8 significant commits,+or have co-change partners. Conversely, stable + low PageRank + low commit count+files can be auto-downgraded to "minimal". Controlled by `git.depth_auto_upgrade`.++**Maintenance prompts:** When regenerating during `wikicode update`, the specific+commit that triggered the update (SHA, author, message, diff) is included in the+prompt. This produces targeted updates rather than full rewrites.++**Confidence decay:** Git signals modify the base confidence decay multiplicatively.+Hotspot files decay faster (bugs are more likely). Stable files decay slower. Large+changes ("rewrite", "refactor", "migrate" in commit message) trigger aggressive+decay. Cosmetic changes ("typo", "lint", "format") trigger softer decay.++**Co-change edges:** After `GitIndexer` runs, co-change edges (`edge_type="co_changes"`)+are added to the dependency graph. They participate in change propagation (when file+A changes, its co-change partners get mild confidence decay at factor 0.97) and are+visible in the graph visualization as dashed purple lines.++**CLAUDE.md generation:** `wikicode generate-claude-md` includes sections for+hotspots, stable core files, ownership map, and hidden coupling pairs.++### 7.3 Module and Repo-Level Git Summaries++Module pages include a team ownership summary: who maintains the most files, who+was most active recently. Repo overview pages include codebase health signals:+hotspot count, stable file count, top churn files, oldest file.++---++## 8. Dead Code Detection++WikiCode detects unreachable files, unused exports, and zombie packages using+graph traversal and SQL queries. No LLM calls — the analysis completes in < 10+seconds for any repo size.++### 8.1 DeadCodeAnalyzer (`packages/core/analysis/dead_code.py`)++The analyzer runs after `GitIndexer` during init (Step 3.6) and optionally during+`wikicode update`. It produces findings with confidence scores:++**Finding types:**+- `unreachable_file` — file with `in_degree == 0`, not an entry point, test, or config+- `unused_export` — public symbol with no incoming edges (but file IS imported)+- `unused_internal` — private symbol with no `calls` edges from same file+- `zombie_package` — monorepo package with no incoming `inter_package` edges++**Confidence scoring (conservative — when in doubt, do NOT flag):**+- Unreachable + no commits in 90d + last commit > 6 months → 1.0+- Unreachable + no commits in 90d → 0.7+- Unreachable but recently touched → 0.4+- `safe_to_delete` only set at confidence >= 0.7, and NOT for files matching+ dynamic patterns (`*Plugin*`, `*Handler*`, `*Adapter*`, `*Middleware*`)++**Never flagged as dead:**+- `__init__.py` public re-exports+- `@pytest.fixture`, `@pytest.mark.*` symbols+- Files matching `*migrations*`, `*schema*`, `*seed*`+- TypeScript `.d.ts` files+- Files where `is_api_contract == True`+- Files in `.wikicode/dead_code_whitelist.txt`+- Symbols matching `config.dead_code.dynamic_patterns`++### 8.2 Dead Code in Generation Prompts++The `file_page.j2` template includes an optional block for dead code findings.+When present, the LLM notes unused symbols as cleanup candidates in the+documentation, including confidence percentages and safety assessment.++### 8.3 CLI: `wikicode dead-code`++```+wikicode dead-code [PATH]+ --min-confidence FLOAT (default: 0.4)+ --safe-only only show safe_to_delete=True findings+ --kind TYPE filter by kind+ --package PKG filter by monorepo package+ --format table|json|md+ --output FILE++wikicode dead-code resolve [FINDING_ID]+ --status acknowledged|resolved|false_positive+ --note "reason"+```++### 8.4 Integration with Other Components++Dead code findings are stored in the `dead_code_findings` SQL table with a status+field (`open` / `acknowledged` / `resolved` / `false_positive`). The web UI shows+a dedicated dead code page with sortable tables, confidence sliders, and resolve+buttons. The graph visualization supports a "show dead code" filter that adds red+dashed borders to dead code nodes.++---++## 9. Decision Intelligence++The Decision Intelligence layer captures **architectural decisions** — the *why* behind how+the system is built, what alternatives were rejected, and what constraints exist. While documentation+describes *what*, decisions capture *why*.++### Capture Sources++Decisions are extracted from four sources, each with a different confidence level:++| Source | Confidence | Status | Trigger |+|--------|-----------|--------|---------|+| **Inline markers** (`# WHY:`, `# DECISION:`, `# TRADEOFF:`, `# ADR:`, `# RATIONALE:`, `# REJECTED:`) | 0.95 | `active` | File scanning during init/update |+| **Git archaeology** (commit messages with migration/refactor signals) | 0.70–0.85 | `proposed` | Init only, reuses git layer data |+| **README/docs mining** (implicit decisions in prose) | 0.60 | `proposed` | Init only, LLM extraction |+| **CLI capture** (`wikicode decision add`) | 1.00 | `active` | Manual entry |++### Data Model++Stored in the `decision_records` SQL table. JSON arrays for alternatives, consequences,+affected files, modules, tags, and evidence commits. Deduplication key:+`(repository_id, title, source, evidence_file)`.++### Staleness Tracking++Decisions have a `staleness_score` (0.0 = fresh, 1.0 = very stale) recomputed on every+`wikicode 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++- `get_decisions(module?, tag?, include_proposed?, include_stale?)` — query decision records+- `get_why(query)` — semantic search over decisions + documentation, answers "why" questions+- `get_decision_health()` — stale decisions, ungoverned hotspots, proposed decisions needing review++### CLI Commands++```+wikicode decision add # interactive capture+wikicode decision list # tabular list with filters+wikicode decision show <id> # full detail+wikicode decision confirm # proposed → active+wikicode decision dismiss # delete proposed+wikicode decision deprecate # active → deprecated+wikicode decision health # health summary+```++### Key Files++| File | Purpose |+|------|---------|+| `core/analysis/decision_extractor.py` | All 4 capture sources + staleness computation |+| `core/persistence/models.py` | `DecisionRecord` ORM model |+| `core/persistence/crud.py` | 8 decision CRUD functions |+| `server/mcp_server.py` | 3 MCP tools (get_decisions, get_why, get_decision_health) |+| `server/routers/decisions.py` | REST API endpoints |+| `cli/commands/decision_cmd.py` | CLI command group (7 subcommands) |++---++## 10. MCP Server++The MCP server is WikiCode's most valuable integration feature. It exposes the+entire wiki as a set of queryable tools that any MCP-compatible AI assistant+can call in real time.++Instead of an AI assistant reading 40 source files to understand a codebase,+it calls `get_overview()` and gets a structured, always-current architecture summary.+Instead of grepping for a function, it calls `get_symbol("AuthService.login")`.++The server is implemented using the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)+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++| Tool | What it answers |+|------|----------------|+| `get_overview` | Architecture summary, module map, entry points. Best first call. |+| `get_module_docs` | Wiki page for a package/directory. Public API + file map. |+| `get_file_docs` | Wiki page for a specific file. Symbols, imports, freshness. |+| `get_symbol` | Any function/class/method by name. Fuzzy match if exact fails. |+| `search_codebase` | Semantic search over the full wiki. Natural language. |+| `get_architecture_diagram` | Mermaid diagram for repo or specific module. |+| `get_dependency_path` | How is symbol A connected to symbol B? |+| `get_stale_pages` | Which pages have confidence score below threshold. |+| `get_file_history` | Git history for a file: ownership, significant commits, co-changes. |+| `get_hotspots` | High-churn + high-complexity files — most likely to contain bugs. |+| `get_codebase_ownership` | Ownership breakdown by file/module/package. Identifies silos. |+| `get_co_changes` | Files that change together without import link — hidden coupling. |+| `get_dead_code` | Dead/unused code findings sorted by confidence and cleanup impact. |++### Auto-generated Config++`wikicode init` automatically generates `.wikicode/mcp.json` with ready-to-paste+config blocks for Claude Code (`~/.claude/claude.json`), Cursor (`.cursor/mcp.json`),+and Cline. This config is printed at the end of `wikicode init`.++---++## 11. REST API and Web UI++### REST API (FastAPI)++Served on port `7337` alongside the web UI. All endpoints are prefixed with `/api/`.++Key routers:+- `/api/repos` — register repos, trigger sync, full-resync+- `/api/pages` — read pages, version history, force-regenerate single page+- `/api/search` — semantic (LanceDB or pgvector) and full-text (SQLite FTS5 / PostgreSQL tsvector) search+- `/api/jobs` — job status, SSE stream for live progress updates+- `/api/symbols` — symbol lookup, dependency path queries+- `/api/graph` — graph export in D3-compatible JSON format+- `/api/webhooks/github` — GitHub webhook handler with HMAC verification+- `/api/webhooks/gitlab` — GitLab webhook handler+- `/api/repos/{id}/git-metadata` — per-file git metadata+- `/api/repos/{id}/hotspots` — high-churn + high-complexity files+- `/api/repos/{id}/ownership` — ownership breakdown (file/module/package granularity)+- `/api/repos/{id}/co-changes` — co-change partners for a file+- `/api/repos/{id}/git-summary` — aggregate git health signals for dashboard+- `/api/repos/{id}/dead-code` — dead code findings (GET list, POST trigger analysis)+- `/api/repos/{id}/dead-code/summary` — aggregate dead code stats+- `/api/dead-code/{finding_id}` — PATCH to resolve/acknowledge findings+- `/health` — liveness + readiness (checks DB + provider)+- `/metrics` — Prometheus-compatible metrics (job counts, token totals, stale count)++Authentication is optional. Set `WIKICODE_API_KEY` to require bearer token auth on+all non-`/health` endpoints. Default (no key set): fully open, suitable for local use.++### Web UI (Next.js 15)++Served from the same port as the API. All routes under `/`:++| Route | Content |+|-------|---------|+| `/` | Dashboard: all repos, recent jobs, stale page counts, token usage |+| `/repos/[id]` | Repo overview wiki page + file tree sidebar |+| `/repos/[id]/wiki/[...slug]` | Individual wiki page with MDX rendering |+| `/repos/[id]/search` | Semantic search results |+| `/repos/[id]/graph` | D3 force-directed dependency graph |+| `/repos/[id]/symbols` | Full symbol index, sortable by PageRank |+| `/repos/[id]/coverage` | Documentation coverage metrics |+| `/repos/[id]/ownership` | Ownership treemap — files colored by primary owner, sized by LOC |+| `/repos/[id]/hotspots` | Hotspot list — top 20 files with churn + complexity bars |+| `/repos/[id]/dead-code` | Dead code report — three tabs: Files, Exports, Internals |+| `/settings` | Provider config, polling interval, cascade budget |++**Key rendering behavior:**++Every backtick identifier in a wiki page that matches a known symbol becomes a+hover card showing the symbol's signature, file, and confidence score, plus a+link to the symbol's wiki page. This is built by post-processing the MDX content+client-side after initial render.++Mermaid diagrams are rendered lazily (only when scrolled into viewport) using+`mermaid.js` initialized with the WikiCode design theme.++Code blocks use Shiki for syntax highlighting. Each block has a "View in source"+button that deep-links to the relevant line in GitHub/GitLab.++The `<GenerationProgress>` component connects to `/api/jobs/{id}/stream` via SSE+and shows a live progress display during generation (pages done/total, current+file, tokens used, estimated cost, estimated time remaining).++---++## 12. Data Flow Diagrams++### Init flow++```+wikicode init /path/to/repo+ │+ ▼+FileTraverser+ walks repo, produces list[FileInfo]+ │+ ▼+ASTParser ──── queries/<lang>.scm ────▶ ParsedFile per file+ (parallel, (symbols, imports, exports)+ one parser per worker)+ │+ ▼+GraphBuilder+ constructs DiGraph+ computes PageRank, SCC, Betweenness, Communities+ persists to graph.json (or DB for large repos)+ │+ ▼+GitIndexer (if git.enabled)+ mines git history → git_metadata table+ computes co-change partners → adds co_changes edges to graph+ classifies hotspots (top 25% churn + complexity)+ classifies stable files (>10 commits, 0 in 90 days)+ │+ ▼+DeadCodeAnalyzer (if dead_code.enabled)+ graph traversal + SQL: unreachable files, unused exports, zombie packages+ pure analysis — no LLM calls, < 10 seconds+ │+ ▼+JobSystem+ creates GenerationJob in DB+ shows cost estimate + confirmation+ │+ ├── Level 0: special handlers (OpenAPI, proto, GraphQL, Dockerfile...)+ │+ ├── Level 1: symbol spotlight pages (top 10% PageRank)+ │ ┌────────────────────────────────────┐+ │ │ ContextAssembler │+ │ │ source + graph metadata │+ │ │ + RAG (vector store similarity search)│+ │ │ + import summaries │+ │ └──────────────┬─────────────────────┘+ │ │+ │ ▼+ │ LLMProvider.generate()+ │ │+ │ ▼+ │ WikiPage stored:+ │ → SQL (content, metadata, confidence=1.0)+ │ → VectorStore (LanceDB or pgvector — embedding for RAG)+ │ → Graph (node.page_id linked)+ │+ ├── Level 2: file pages (parallel, RAG pool growing with each completed page)+ ├── Level 3: SCC pages+ ├── Level 4: module pages+ ├── Level 5: cross-package pages (monorepos)+ ├── Level 6: repo overview + architecture diagram+ ├── Level 7: config/infra pages+ └── Level 8: index pages+ │+ ▼+ .wikicode/state.json updated+ MCP config printed+ Summary shown (pages, tokens, cost, time)+```++### Maintenance flow (on git push)++```+git push+ │+ ├── GitHub webhook → POST /api/webhooks/github+ │ │ (verified, stored in webhook_events)+ │ ▼+ │ GenerationJob created (type: incremental)+ │+ └── (fallback) APScheduler polls every 15min+ │ (if HEAD != last_sync_commit)+ ▼+ GenerationJob created (type: incremental)++GenerationJob runs:+ │+ ▼+ChangeDetector.get_changed_files(since=last_sync_commit)+ │+ ├── Renamed files → update source_files refs in SQL+ ▼+GitIndexer.index_changed_files(changed_file_paths)+ │ re-indexes only changed files + their co-change partners+ │ updates co-change edges in graph+ ▼+ChangeDetector.detect_symbol_renames()+ │+ ▼+ChangeDetector.get_affected_pages(cascade_budget=30)+ │ includes co-change partners in staleness propagation+ │+ ├── regenerate: list[page_id] → full regeneration (up to cascade_budget)+ ├── rename_patch: list[page_id] → targeted text find-and-replace+ └── decay_only: list[page_id] → confidence score decay, add to staleness queue+ │+ ▼+For each page in `regenerate`:+ ContextAssembler → LLMProvider → update SQL + VectorStore + Graph+ │+ ▼+For each page in `rename_patch`:+ scan content_md for old symbol name → replace → update SQL+ │+ ▼+For each page in `decay_only`:+ confidence_score *= decay_factor+ regen_queued = True+ │+ ▼+repos.last_sync_commit = HEAD+state.json updated+```++### MCP query flow++```+Claude Code: "how does the auth module work?"+ │+ ▼+MCP client calls WikiCode tool: search_codebase(query="auth module")+ │+ ▼+VectorStore similarity search (LanceDB or pgvector) → top 5 page IDs+ │+ ▼+SQL: fetch page content for those IDs+ │+ ▼+Return: list[{title, content_md snippet, relevance_score, confidence_score}]+ │+ ▼+Claude Code has structured, current documentation+instead of reading 40 files+```++---++## 13. Key Design Decisions++### Three-layer folder exclusion, not one monolithic list++WikiCode offers three complementary ways to skip paths during traversal, each solving+a different problem:++1. **Root `.wikicodeIgnore`** — project-wide exclusions committed to the repo (like+ `.gitignore`). Shared across all users, version-controlled.++2. **Per-directory `.wikicodeIgnore`** — exclusions that only apply within a subtree.+ Lets a monorepo package owner exclude its own generated output without polluting+ the root ignore file. Patterns are relative to the directory, matching git semantics.+ Specs are loaded once per directory during `os.walk` and cached by absolute path;+ the root spec is pre-seeded in the cache to avoid reading it twice.++3. **`extra_exclude_patterns` (runtime)** — patterns injected without touching any+ file on disk: from `--exclude/-x` CLI flags (dev workflow), from+ `config.yaml exclude_patterns` (persisted per repo), or from+ `repo.settings["exclude_patterns"]` (Web UI / REST API). This lets teams configure+ exclusions through the UI without git access to the target repo.++All three layers use `pathspec` with `gitwildmatch` semantics — the same library used+for `.gitignore` parsing — so the full gitignore syntax works everywhere.++### `save_config()` round-trips YAML, not overwrites++The original `save_config()` wrote a fixed three-key file (`provider`, `model`,+`embedder`). This meant any other keys — such as `exclude_patterns` set via the Web UI+— would be silently dropped the next time `wikicode init` ran. The updated function+loads the existing config, merges in the new values, then writes the result back.+This ensures all config sources (CLI, Web UI, REST API, manual edits) coexist safely.++### One `ASTParser` class, not one per language++Per-language differences live in `.scm` query files and `LANGUAGE_CONFIGS` dict entries.+This means adding a new language requires no changes to Python business logic — just+a new `.scm` file and a config entry. The `ASTParser` class itself never has+`if lang == "python"` branches.++### LanceDB (embedded) + pgvector, not ChromaDB++ChromaDB was the original choice but has notable drawbacks: slow write throughput on+large repos, heavy C++ build dependencies (`chroma-hnswlib`), and a bloated dependency+tree. LanceDB replaces it as the default embedded vector store:++- **No build step** — pure Python wheel, no C++ compiler required on Windows+- **Faster writes** — Lance columnar format is optimised for batch appends; embedding+ 50K pages during `wikicode init` is measurably faster+- **Faster queries** — IVF-PQ and HNSW index support with sub-millisecond ANN search+- **Simpler data model** — tables are Arrow-native; filtering by `repo_id` or `page_type`+ uses SQL-style predicates alongside the vector search, no separate metadata store needed+- **Zero server process** — same embedded story as ChromaDB: data lives in+ `.wikicode/lancedb/`, no container needed++When PostgreSQL is already in use (multi-worker prod), **pgvector** is preferred because+it eliminates the second storage system entirely: embeddings live as a `vector` column+in the existing `wiki_pages` table, queries are plain SQL with `<=>` cosine distance,+and backup/restore is a single `pg_dump`. The HNSW index (`CREATE INDEX ... USING hnsw`)+gives query latency on par with LanceDB at typical WikiCode dataset sizes.++The `VectorStore` abstraction in `packages/core/src/wikicode/core/persistence/vector.py`+selects the backend at startup based on `DATABASE_URL`: SQLite → LanceDB, PostgreSQL → pgvector.++### NetworkX + SQLite fallback, not Neo4j++NetworkX is a Python library that runs in-process. Neo4j is a separate server+(Java process, GBs of RAM, authentication setup). For a graph that is derived+from source code (rebuildable at any time), the operational overhead of Neo4j+is unjustified. NetworkX handles tens of thousands of nodes comfortably.++The SQLite-backed fallback using `networkit` handles repos that genuinely exceed+in-memory limits without adding a server dependency.++### Confidence scores, not binary "fresh/stale"++A binary fresh/stale flag would require either: (a) marking everything stale on+every push (triggering full regen, expensive), or (b) only marking directly changed+pages (missing transitive effects). The confidence score model captures the gradient:+directly changed pages decay sharply, indirectly referenced pages decay gently.+Users can see at a glance how much to trust each page.++### Jinja2 prompts, not hardcoded strings++All LLM prompts are Jinja2 templates in `packages/core/queries/prompts/`. Users can+override any prompt by placing a file with the same name in `.wikicode/prompts/`.+This lets power users tune generation quality without forking the project.++### Cascade budget++Without a budget, changing a central utility (imported by 200 files) would+regenerate 200+ pages on every push. With a budget (default: 30), WikiCode+regenerates the highest-PageRank affected pages immediately and defers the rest+to the nightly background job. No page stays stale indefinitely; the nightly job+catches everything the cascade budget missed.++### Git metadata in generation prompts, not just for display++The highest-value use of git metadata is enriching the LLM's generation context —+not just showing ownership in a sidebar. By including significant commit messages+in the prompt, the LLM can explain *why* code is structured a certain way (e.g.,+"this was refactored in March 2024 to separate auth concerns from the request+pipeline"). This context is unavailable from static analysis alone.++### Co-change edges as a separate graph layer++Co-change relationships are temporal coupling — they cannot be detected by AST+parsing. WikiCode adds them as `co_changes` edges after `GitIndexer` runs, but+deliberately filters them out of PageRank computation (they would skew it+artificially toward files that are often edited together for process reasons, not+architectural ones). They participate in change propagation and visualization only.++### Conservative dead code detection++WikiCode's dead code detector errs heavily toward false negatives. `safe_to_delete`+is set to `True` only at confidence >= 0.7 and after excluding dynamically-loaded+patterns. Dead code analysis is pure graph traversal + SQL (no LLM calls), so it+completes in seconds and can be re-run cheaply. WikiCode surfaces candidates —+humans decide before deleting anything.++### Async-first throughout++All database operations use async SQLAlchemy with `aiosqlite`. The event loop+is never blocked. This matters during generation: the LLM call, the DB write,+and the vector store embed (LanceDB or pgvector) can overlap with the next file's context assembly.++---++## 14. Adding a New Language++1. **Write `packages/core/queries/<language>.scm`**++ Use tree-sitter S-expression syntax. Follow the capture name conventions:+ `@symbol.def`, `@symbol.name`, `@symbol.params`, `@symbol.return_type`,+ `@symbol.docstring`, `@import.statement`, `@import.module`, `@import.names`.++ Check the tree-sitter playground for your language's node type names:+ `https://tree-sitter.github.io/tree-sitter/playground`++2. **Add a `LanguageConfig` entry to `LANGUAGE_CONFIGS` in `parser.py`**++ ```python+ "mylang": LanguageConfig(+ symbol_node_types={+ "function_definition": "function",+ "class_definition": "class",+ },+ import_node_types=["import_statement"],+ export_node_types=[],+ visibility_fn=lambda name, mods: "private" if name.startswith("_") else "public",+ entry_point_patterns=["main.ml", "app.ml"],+ ),+ ```++3. **Verify `tree-sitter-languages` includes your language**++ Run `python -c "from tree_sitter_languages import get_parser; get_parser('mylang')"`.+ If it raises, the grammar is not bundled. You can add it manually as a tree-sitter+ grammar and register it with the Language API.++4. **Add test files to `tests/fixtures/sample_repo/`**++ At minimum: one file with a function, one with a class, one with imports.++5. **Run `pytest tests/unit/test_parser.py -k mylang`** to verify extraction.++6. **Open a PR.** That's it — no other changes needed.++---++## 15. Adding a New LLM Provider++1. **Create `packages/core/providers/<name>.py`**++ Subclass `LLMProvider` and implement:+ - `generate(request: GenerationRequest) -> GenerationResponse`+ - `generate_stream(request: GenerationRequest) -> AsyncIterator[str]`+ - `embed(request: EmbedRequest) -> EmbedResponse`+ - `name` property++ Optionally override:+ - `supports_batch` → `True` if the provider has a batch API+ - `generate_batch(requests) -> list[GenerationResponse]`+ - `estimate_cost(input_tokens, output_tokens) -> float`++2. **Register in `providers/registry.py`**++ ```python+ case "myprovider": return MyProvider(config)+ ```++3. **Add config section to `.wikicode/config.yaml` docs**++ ```yaml+ myprovider:+ api_key: ${MYPROVIDER_API_KEY}+ base_url: https://api.myprovider.com/v1+ ```++4. **Add default rate limits** to `PROVIDER_DEFAULT_LIMITS` in `rate_limiter.py`++5. **Add a `MockProvider` fixture** for tests if the provider has unique response formats++6. **Update `CONTRIBUTING.md`** with the new provider's environment variables++---++## Appendix: Configuration Reference++Full configuration with defaults (`.wikicode/config.yaml`):++```yaml+provider: anthropic # anthropic | openai | ollama | litellm+model: claude-sonnet-4-5 # passed through to the provider+embedding_provider: anthropic+embedding_model: voyage-3++batch_mode: auto # auto | always | never+prompt_caching: true++anthropic:+ api_key: ${ANTHROPIC_API_KEY}++openai:+ api_key: ${OPENAI_API_KEY}+ base_url: https://api.openai.com/v1++ollama:+ base_url: http://localhost:11434++generation:+ max_tokens: 4096+ temperature: 0.2+ concurrent_jobs: 5+ request_timeout: 120+ max_retries: 3+ large_file_threshold_kb: 100+ max_file_size_kb: 500++graph:+ backend: auto # auto | networkx | sqlite+ node_threshold: 30000 # switch to sqlite above this++git:+ enabled: true # mine git history for richer generation+ co_change_commit_limit: 500 # commits to analyze for co-changes (0 = unlimited)+ co_change_min_count: 3 # minimum co-occurrences to register a relationship+ blame_enabled: true # git blame for ownership (slightly slower)+ prompt_commit_count: 10 # significant commits to include in generation prompts+ depth_auto_upgrade: true # auto-upgrade depth for hotspots++dead_code:+ enabled: true # detect unreachable files, unused exports, zombie packages+ detect_unreachable_files: true+ detect_unused_exports: true+ detect_unused_internals: false # off by default — higher false positive rate+ detect_zombie_packages: true+ min_confidence: 0.4+ safe_to_delete_threshold: 0.7+ dynamic_patterns: # symbols matching these are never flagged+ - "*Plugin"+ - "*Handler"+ - "*Adapter"+ - "*Middleware"+ - "register_*"+ - "on_*"+ whitelist_file: .wikicode/dead_code_whitelist.txt+ analyze_on_update: true # re-analyze dead code on incremental updates++maintenance:+ cascade_budget: 30+ staleness_decay_direct: 0.85+ staleness_decay_referenced: 0.95+ staleness_regen_threshold: 0.60+ staleness_warn_threshold: 0.75+ background_regen_schedule: "0 2 * * *"+ background_regen_budget: 100+ polling_interval_minutes: 15++rate_limits:+ anthropic:+ rpm: 50+ tpm: 100000+ openai:+ rpm: 500+ tpm: 150000+ ollama:+ rpm: 999999+ tpm: 999999+```\ No newline at end of filediff --git a/docs/LLM_GENERATION_DEEP_DIVE.md b/docs/LLM_GENERATION_DEEP_DIVE.mdnew file mode 100644index 000000000..28c3b2412--- /dev/null+++ b/docs/LLM_GENERATION_DEEP_DIVE.md@@ -0,0 +1,900 @@+# LLM Doc Generation — Deep Dive++This document is a precise, code-level description of how WikiCode builds prompts and calls+LLMs to produce wiki pages. It covers every piece of context that goes into each call,+the exact generation ordering, how scalability is handled, and a frank gap analysis of+where the current implementation diverges from the intended design.++**Validated against:** actual generated output from `interview-coach/.wikicode/export/` —+a test run on a 2022-file monorepo (Python + TypeScript) using Gemini, producing 33 pages.++---++## Table of Contents++1. [High-Level Pipeline](#1-high-level-pipeline)+2. [Page Types and Generation Levels](#2-page-types-and-generation-levels)+3. [What Context Goes to the LLM — Per Page Type](#3-what-context-goes-to-the-llm--per-page-type)+4. [Token Budget Mechanics](#4-token-budget-mechanics)+5. [Generation Ordering and Significance Filtering](#5-generation-ordering-and-significance-filtering)+6. [Prompt Caching and Provider Layer](#6-prompt-caching-and-provider-layer)+7. [Confidence and Freshness Tracking](#7-confidence-and-freshness-tracking)+8. [Scalability: Small vs. Large Repos](#8-scalability-small-vs-large-repos)+9. [Output Quality: What the LLM Actually Produces](#9-output-quality-what-the-llm-actually-produces)+10. [Gap Analysis — What Is Not Yet Wired Up](#10-gap-analysis--what-is-not-yet-wired-up)++---++## 1. High-Level Pipeline++Every wiki page follows the same three-step cycle:++```+ParsedFile + graph metrics + git metadata+ │+ ▼+ContextAssembler.assemble_*()+ │ builds a typed context dataclass+ ▼+Jinja2 template rendered → user_prompt string+ │+ ▼+LLMProvider.generate(system_prompt, user_prompt)+ │+ ▼+GeneratedPage (markdown content + token counts + confidence=1.0)+```++The key files:++| File | Role |+|------|------|+| `generation/context_assembler.py` | Assembles typed context dataclasses from ingestion output |+| `generation/page_generator.py` | Renders prompts, calls provider, wraps in `GeneratedPage` |+| `generation/models.py` | `GeneratedPage`, `GenerationConfig`, decay math |+| `generation/templates/*.j2` | One Jinja2 template per page type |++---++## 2. Page Types and Generation Levels++WikiCode generates 10 distinct page types in a strict dependency-ordered sequence:++| Level | Page Type | What It Documents | Template |+|-------|-----------|-------------------|----------|+| 0 | `api_contract` | OpenAPI / Protobuf / GraphQL schema files | `api_contract.j2` |+| 1 | `symbol_spotlight` | Top-10% public symbols by PageRank | `symbol_spotlight.j2` |+| 2 | `file_page` | Significant source files | `file_page.j2` |+| 3 | `scc_page` | Circular dependency clusters (len > 1) | `scc_page.j2` |+| 4 | `module_page` | Top-level directories as modules | `module_page.j2` |+| 5 | `cross_package` | Monorepo inter-package boundaries | *(stub — not yet implemented)* |+| 6 | `repo_overview` | Repository-level architecture summary | `repo_overview.j2` |+| 6 | `architecture_diagram` | Mermaid dependency graph | `architecture_diagram.j2` |+| 7 | `infra_page` | Dockerfile, Makefile, Terraform, shell | `infra_page.j2` |+| 7 | `diff_summary` | Git diff summaries (maintenance path) | `diff_summary.j2` |++Within each level, pages run concurrently up to `config.max_concurrency` (default: 5).+A level never starts until all coroutines in the previous level complete or fail.++**Page ID format:** `"{page_type}:{target_path}"` — deterministic, used for resume and+deduplication.++---++## 3. What Context Goes to the LLM — Per Page Type++Every LLM call is two parts:+- **System prompt** — a constant string per page type (enables Anthropic prefix caching)+- **User prompt** — rendered Jinja2 template with the assembled context++### 3.1 `file_page` — the most important page type++**System prompt (constant):**+```+You are WikiCode, an expert technical documentation generator.+Your task is to produce comprehensive, accurate wiki pages from source code.+Output markdown only. Do not include preamble or apologies.+Required sections: ## Overview, ## Public API, ## Dependencies, ## Usage Notes.+```++**User prompt context** (assembled by `ContextAssembler.assemble_file_page()`):++| Context piece | Source | Always included? |+|---------------|--------|-----------------|+| File path | `ParsedFile.file_info.path` | Yes |+| Language | `ParsedFile.file_info.language` | Yes |+| Module docstring | `ParsedFile.docstring` | If present |+| PageRank score | `graph_builder.pagerank()[path]` | Yes |+| Betweenness centrality | `graph_builder.betweenness_centrality()[path]` | Yes |+| Community ID (Louvain cluster) | `graph_builder.community_detection()[path]` | Yes |+| Flags: `is_api_contract`, `is_entry_point`, `is_test` | `ParsedFile.file_info` | Yes |+| Public symbols first (name, kind, signature, docstring, visibility, complexity, decorators, start/end lines) | `ParsedFile.symbols` | Within token budget |+| Private documented symbols | `ParsedFile.symbols` | Within token budget |+| Private undocumented symbols | `ParsedFile.symbols` | Within token budget |+| Import statements (up to 30) | `ParsedFile.imports[].raw_statement` | Within token budget |+| Export names | `ParsedFile.exports` | Yes |+| Dependencies (files this imports, from graph edges) | `graph.successors(path)` | Yes |+| Dependents (files that import this, from graph edges) | `graph.predecessors(path)` | Yes |+| Parse errors | `ParsedFile.parse_errors` | If present |+| Source code snippet | `source_bytes` decoded, trimmed to budget | Within token budget |+| RAG context (related page summaries) | `ctx.rag_context` list | If populated |+| Git: primary owner + % lines | `git_metadata.primary_owner_name` | If git enabled |+| Git: top 3 contributors | `git_metadata.top_authors` | If git enabled |+| Git: significant commit messages (date, author, message) | `git_metadata.significant_commit_messages` | If git enabled |+| Git: total commit count + age in days | `git_metadata.commit_count_total` | If git enabled |+| Git: `is_hotspot` flag | `git_metadata.is_hotspot` | If git enabled |+| Git: `is_stable` flag | `git_metadata.is_stable` | If git enabled |+| Git: co-change partners (files changed together without import link) | `git_metadata.co_change_partners[:3]` | If git enabled |+| Dead code findings (symbol name, reason, confidence, safe_to_delete) | From `DeadCodeAnalyzer` | If dead code enabled |++**Symbol priority order** in the prompt: public → private-with-docstring → private-undocumented.+Each symbol's token cost is measured before adding — the loop stops when budget is exhausted.++**Source code placement:** The source snippet always comes last in the budget calculation.+All other fields are reserved first; the source gets whatever tokens remain.++### 3.2 `symbol_spotlight`++**System prompt:**+```+You are WikiCode, an expert technical documentation generator.+Write a detailed spotlight page for a single code symbol.+Output markdown only.+Required sections: ## Purpose, ## Signature, ## Parameters, ## Returns, ## Example Usage.+```++**User prompt context:**++| Context piece | Source |+|---------------|--------|+| Symbol name, qualified name, kind | `Symbol` |+| File path | `ParsedFile.file_info.path` |+| `is_async` flag | `Symbol.is_async` |+| Complexity estimate | `Symbol.complexity_estimate` |+| Full signature string | `Symbol.signature` |+| Docstring (if any) | `Symbol.docstring` |+| Decorators | `Symbol.decorators` |+| Callers (files that import the containing module, from graph in-edges) | `graph.predecessors(path)` |++**Note:** Symbol spotlight only gets the signature + docstring — not the actual function body+(source code). There is no per-symbol source extraction.++### 3.3 `module_page`++**System prompt:**+```+You are WikiCode, an expert technical documentation generator.+Write a module-level overview page summarising all files in the module.+Output markdown only.+Required sections: ## Overview, ## Public API Summary, ## Architecture Notes.+```++**User prompt context:**++| Context piece | Source |+|---------------|--------|+| Module path (top-level directory name) | `Path(file_path).parts[0]` |+| Language | From constituent files |+| Total symbol count | Summed from all `FilePageContext` in the module |+| Public symbol count | Filtered from symbol dicts |+| Entry point files | Files where `is_entry_point == True` |+| Cross-module dependencies | Aggregated `dependencies` minus intra-module edges |+| Cross-module dependents | Aggregated `dependents` minus intra-module edges |+| Mean PageRank of module files | Mean of `pagerank_score` across all file contexts |+| File list | All file paths in the module |+| Team ownership summary | `module_git_summary` (variable injection, see gap §9.3) |++**Important:** The module page gets `FilePageContext` objects (which contain symbol metadata),+but the Jinja2 template only renders the file path list — it does not include the file pages'+actual generated markdown content. The LLM sees which files are in the module but not what+those files do.++### 3.4 `scc_page`++**System prompt:**+```+You are WikiCode, an expert technical documentation generator.+Document this circular dependency cycle and provide actionable refactoring advice.+Output markdown only.+Required sections: ## Cycle Description, ## Files Involved, ## Why This Exists,+## Refactoring Suggestions.+```++**User prompt context:**++| Context piece | Source |+|---------------|--------|+| SCC ID | `f"scc-{index}"` |+| Cycle description string | `"Circular dependency cycle: A → B → C"` (ordered paths joined) |+| Files in cycle | `sorted(scc)` — path list |+| Total symbol count across all cycle members | Summed from `FilePageContext` list |++**Note:** The SCC page context is very thin — the LLM gets file paths and a total symbol+count but no signatures, no source, and no information about which symbols create the cycle.++### 3.5 `repo_overview`++**System prompt:**+```+You are WikiCode, an expert technical documentation generator.+Write a high-level repository overview suitable for onboarding new developers.+Output markdown only.+Required sections: ## Project Summary, ## Technology Stack, ## Entry Points, ## Architecture.+```++**User prompt context:**++| Context piece | Source |+|---------------|--------|+| Repo name | `repo_structure.name` |+| Is monorepo | `repo_structure.is_monorepo` |+| Total files | `repo_structure.total_files` |+| Total lines of code | `repo_structure.total_loc` |+| Circular dependency count | SCCs with `len > 1` |+| Package list (name, path, language) | `repo_structure.packages` |+| Language distribution (percent per language) | `repo_structure.root_language_distribution` |+| Entry points | `repo_structure.entry_points` |+| Top 20 files by PageRank (path + score) | Top of `pagerank` dict sorted descending |+| Codebase health signals | `repo_git_summary` (variable injection, see gap §9.3) |++### 3.6 `architecture_diagram`++**System prompt:**+```+You are WikiCode, an expert technical documentation generator.+Generate an architecture overview with a Mermaid diagram.+You MUST include a fenced mermaid block with graph TD showing key dependencies.+Output markdown only.+```++**User prompt context:**++| Context piece | Source |+|---------------|--------|+| Repo name | Passed directly |+| ALL graph nodes (every non-external file) | `graph.nodes()` filtered |+| ALL graph edges (every dependency) | `graph.edges()` filtered |+| Community → member file mapping | All entries in `community` dict |+| SCC groups (only non-singleton) | `sccs` filtered |++**Warning:** For large repos this dumps every node and edge — a 1,000-file repo produces+a prompt with 1,000 node lines and potentially thousands of edge lines. See gap §9.5.++### 3.7 `api_contract`++**System prompt:**+```+... Document this API contract file for developers integrating with the service.+Required sections: ## Overview, ## Endpoints, ## Schemas, ## Authentication, ## Examples.+```++**User prompt context:** Full raw file content (trimmed to token budget) + function signatures+as endpoints + class names as schemas.++### 3.8 `infra_page`++**System prompt:**+```+... Document this infrastructure file for DevOps and platform engineers.+Required sections: ## Purpose, ## Key Targets/Stages, ## Configuration, ## Operational Notes.+```++**User prompt context:** Full raw file content (trimmed to token budget) + symbol names+(e.g., Makefile targets).++### 3.9 `diff_summary`++**System prompt:**+```+... Summarise the changes between two git refs and their documentation impact.+Required sections: ## Summary, ## Changed Files, ## Symbol Changes, ## Affected Documentation.+```++**User prompt context:** Added/deleted/modified file lists, symbol diffs, affected page IDs,+trigger commit SHA + message + author + diff text (trimmed to 1,000 tokens).++---++## 4. Token Budget Mechanics++### Budget constants (from `GenerationConfig` defaults)++| Setting | Default | What it controls |+|---------|---------|-----------------|+| `token_budget` | 8,000 tokens | Maximum context fed to the LLM per call |+| `max_tokens` | 4,096 tokens | Maximum LLM output |+| `temperature` | 0.3 | Low temperature for consistent, factual output |++### Token estimation++WikiCode uses a rough heuristic: `len(text) // 4` characters-to-tokens. No tiktoken+dependency. This is accurate for English prose (~4 chars/token) but underestimates for+dense code (operators, brackets, identifiers) and overestimates for unicode-heavy code.++### Budget allocation for `file_page` (in order)++```+budget = 8,000 tokens+─────────────────────────────────────────────────────────+Step 1: path + language overhead ~5 tokens (always)+Step 2: public symbol signatures accumulated, stop when budget hit+Step 3: private documented symbol sigs accumulated, stop when budget hit+Step 4: private undocumented symbol sigs accumulated, stop when budget hit+Step 5: import statements (max 30) skipped entirely if over budget+Step 6: source code snippet trimmed to REMAINING tokens+─────────────────────────────────────────────────────────+Git context, dead code, RAG context: added to the dataclass but NOT+included in the budget calculation — they expand the prompt beyond the budget.+```++**Key insight:** The source code is the lowest-priority item in the budget allocation.+For a file with many symbols, the source may be heavily truncated or replaced with+`...[truncated]`.++### Page budget cap++Total page count is capped at `max(50, N_files * max_pages_pct)` where+`max_pages_pct = 0.10`. For a 100-file project: cap = 50 pages. For a 50,000-file+project: cap = 5,000 pages. Fixed-overhead pages (api, scc, module, overview, diagram)+are subtracted from this budget before allocating file pages and symbol spotlights.+File pages get priority over symbol spotlights within the remaining budget.++---++## 5. Generation Ordering and Significance Filtering++### Why ordering matters++The generation order is topologically motivated: dependencies are generated before+dependents. This means when a file page is generated, its imported modules' pages+already exist in the vector store — they can theoretically be retrieved as RAG context+for the importing file's generation.++### File page significance filter++Not every code file gets its own `file_page`. A file is significant if ALL of:+- Has at least `file_page_min_symbols` (default: 1) symbols, AND+- Is an entry point, OR in the top PageRank percentile, OR has non-zero betweenness centrality++Files that pass this filter get a generated page. Files that don't still have their+`FilePageContext` assembled (needed for module pages) but no LLM call is made.++**For a 100-file project:** With `file_page_top_percentile = 0.10`, the top ~10 files+by PageRank get pages, plus all entry points and bridge files. In practice, betweenness+centrality > 0 catches most architecturally important files even at low PageRank.++**For a 50,000-file project (tokio-rs scale):** The same logic applies — only the most+central files get individual pages. Low-PageRank leaf files (test helpers, simple data+structures) are documented only at the module level.++### Module grouping++Modules are defined as `Path(file_path).parts[0]` — the top-level directory. A file+at `src/auth/jwt.py` belongs to module `src`. A file at `tests/test_auth.py` belongs+to module `tests`. This is a simple heuristic that works well for standard Python/Go+layouts but less well for deeply nested monorepos.++### Generation depth auto-upgrade++When git metadata is available, `_select_generation_depth()` can upgrade to `"thorough"`:+- `is_hotspot == True`+- > 100 total commits AND > 10 in last 90 days+- >= 8 significant commit messages+- Any co-change partners++Or downgrade to `"minimal"`:+- `is_stable == True` AND PageRank < 0.3 AND < 5 total commits++Note: The `depth` selection is computed but currently not plumbed through to the+template or the `generate_*` calls — the value is returned but unused in `generate_all`.++---++## 6. Prompt Caching and Provider Layer++### In-process SHA256 cache++`PageGenerator` maintains an in-memory dict keyed by:+```python+SHA256(f"{model_name}:{page_type}:{user_prompt}")+```++If the same file is enqueued twice (e.g., after a resume), the cached response is+returned without an LLM call. This cache is per-process — it does not persist across+`wikicode init` runs.++### Anthropic prefix caching++System prompts are module-level Python constants (not Jinja2 templates). This is+intentional: Anthropic's server-side prefix caching only works when the prefix is+byte-for-byte identical across calls. Using a constant guarantees this.++For a 1,000-file repo with Anthropic, all `file_page` calls share the same system+prompt. The system prompt is billed once; subsequent calls reuse the cached prefix.+Cost reduction on large repos is typically 60–90% on input tokens.++### Batch mode (Anthropic only)++`AnthropicProvider.generate_batch()` submits all requests for a level as a single+Message Batches API request. Cheaper (~50%) than streaming but asynchronous — the+job polls for completion. Enabled by default for `wikicode init`. Pass `--no-batch`+for streaming (faster, costlier).++---++## 7. Confidence and Freshness Tracking++Every `GeneratedPage` starts with `confidence = 1.0`. Confidence decays over time+and on code changes.++### Time-based decay (`decay_confidence`)++Linear decay from 1.0 to 0.0 over `expiry_threshold_days` (default: 30):+```python+new_confidence = max(0.0, 1.0 - days_since_update / expiry_threshold_days)+```++### Change-driven decay (`compute_confidence_decay_with_git`)++Applied multiplicatively. Base factors:++| Relationship to changed file | Base decay |+|-----------------------------|------------|+| Direct (source file changed) | × 0.85 |+| 1-hop (symbol called/inherited) | × 0.95 |+| 2-hop (looser reference) | × 0.98 |+| Co-change partner (no import link) | × 0.97 |++Git modifiers applied on top:++| Condition | Effect |+|-----------|--------|+| `is_hotspot` + direct | × 0.94 additional |+| `is_hotspot` + 1-hop | × 0.95 additional |+| `is_stable` + direct | × 1.03 additional (slower decay) |+| Commit message contains "rewrite/refactor/migrate" + direct | × 0.71 additional (hard decay) |+| Commit message contains "typo/lint/format" + direct | × 1.12 additional (soft decay) |++### Freshness status thresholds++| `confidence` | Status | UI badge |+|-------------|--------|----------|+| ≥ 0.80 | fresh | green |+| 0.60–0.79 | stale | yellow |+| 0.30–0.59 | outdated | red |+| < 0.30 | unusable | red prominent |++---++## 8. Scalability: Small vs. Large Repos++### Small project (100 files)++- Page cap: `max(50, 100 * 0.10) = 50` pages+- All entry points + bridge files get `file_page`+- Top 10% symbols get `symbol_spotlight`+- Likely 1–3 modules (top-level dirs), so 1–3 `module_page` entries+- Full graph fits in memory as NetworkX `DiGraph` in `.wikicode/graph.json`+- Full source snippets fit in token budget for most files+- `wikicode init` runs in minutes++### React / tokio-rs scale (thousands of files)++- Page cap: `max(50, 5000 * 0.10) = 500` pages for a 5,000-file repo+- Significance filter is critical — only architecturally central files get pages+- Module grouping by top-level dir creates logical package pages+- Graph switches to SQLite-backed `networkit` above 30K nodes+- `concurrent_jobs = 5` prevents runaway API parallelism+- `wikicode init` supports `--resume` — checkpoint after every completed page+- Batch mode (Anthropic) makes large-scale init economically practical+- Source snippets for large files will be heavily truncated++---++## 9. Output Quality: What the LLM Actually Produces++This section is grounded in the `interview-coach` test run exports. The test run used+`gemini-3.1-flash-lite-preview` via LiteLLM on a 2022-file monorepo, producing 33 pages+in ~17 minutes. `token_budget=8000`, `max_tokens=4096`, `max_concurrency=3`.++### 9.1 File pages — consistently high quality++`supabase_service.py.md`, `node_creators.py.md`, `supabase_client.py.md` all show:+- Correct Overview section that accurately describes the module's purpose+- Accurate Public API section listing all methods/functions with their signatures+- Correct Dependencies (listed as module paths, not wiki summaries — see gap 10.2)+- Non-trivial Usage Notes: the LLM inferred singleton pattern, RLS security implications,+ TTS-aware response length constraints, state key requirements — none of which are in+ the signature. This comes entirely from reading the source snippet.++**Verdict:** File page quality is excellent. The raw source code in the prompt is doing+most of the work.++### 9.2 Symbol spotlight — good quality from signature alone++`get_user_analyses.md` produces all required sections (Purpose, Signature, Parameters,+Returns, Example Usage) with only the signature and docstring as input. The generated+example is syntactically correct and semantically plausible.++**Verdict:** For well-named symbols with full type signatures, the output is useful+even without the source body (gap 10.8). For complex symbols with no docstring,+quality will degrade.++### 9.3 Module pages — surprisingly good despite thin context++`backend.md` covers a module containing hundreds of files. The context only included+file paths, symbol counts, and dependency paths — no file page content. Yet the output+correctly identifies major sub-systems (Pipecat, resume analyzer, email engine, thita_bot),+architecture patterns (service-oriented, middleware-based auth), and technology choices.++The LLM is doing pure inference from directory structure and file path names. This works+well for descriptively-named codebases. It would produce generic output for a codebase+with opaque naming (e.g. `svc1/`, `lib2/`).++**Verdict:** Module quality is better than the thin context would suggest, but is+entirely dependent on meaningful file and directory naming.++### 9.4 SCC pages — excellent despite minimal context++Both SCC pages reviewed (`scc-69.md`, `scc-1068.md`) produced genuinely useful output:+- `scc-69` correctly inferred the auth→payment→tier data flow cycle and why each link+ exists, purely from the three file names+- `scc-1068` correctly identified the `__init__.py` re-export + registration pattern+ anti-pattern, noted the deprecated status, and suggested deletion as the primary fix++Both provided concrete, specific refactoring strategies with code examples.++**Verdict:** SCC quality is excellent. The LLM extracts significant signal from file+path names alone. Gap 10.6 (thin context) is technically correct but practically less+impactful than initially assessed.++### 9.5 Repo overview — excellent++`repo.md` correctly identifies the monorepo structure, accurately reports 7 circular+dependencies, names the technology stack (Next.js, Pipecat, Supabase, Manim, Crawl4AI),+and lists real entry points. The architecture section is coherent and accurate.++**Verdict:** Repo overview quality is excellent.++### 9.6 Architecture diagram — good output but fragile approach++`interview-coach.md` contains a clean 7-node Mermaid diagram for a 2022-file repo.+The context passed in lists all 2022 node names and thousands of edges — the raw+prompt must have been massive. The LLM abstracted to high-level components anyway.++**This is coincidentally good, not reliably good.** A different model or a different+run could produce a 2022-node unrenderable Mermaid block. The approach of dumping all+nodes/edges relies on the LLM choosing to abstract, without any guidance to do so.+Gap 10.4 stands.++### 9.7 Job tracking — confirmed broken in production run++From `jobs/6b10db4b-....json` (a failed job):+```json+{+ "total_pages": 0,+ "completed_pages": 0,+ "failed_pages": 5,+ "failed_page_ids": ["level-1", "level-2", "level-3", "level-4", "level-6"]+}+```++Two confirmed bugs:+1. `total_pages: 0` and `completed_pages: 0` even though 33 pages exist in `state.json`.+ Root cause: `job_system.start_job(job_id, len(all_pages))` is called at the *end* of+ `generate_all`, after all generation completes. The counter is set to the final count+ post-hoc, never live during generation.+2. `failed_page_ids` contains level names (`"level-1"`) not page IDs. Root cause:+ `job_system.fail_page(job_id, f"level-{level}", str(r))` passes the level string+ as the page ID. The job log is unactionable for debugging specific failed pages.++---++## 10. Gap Analysis — What Is Not Yet Wired Up++The following gaps represent divergence between the intended architecture and the+current code. Severity ratings are informed by the actual output quality observed+in the `interview-coach` test run — where the LLM compensated for some gaps through+inference, and exposed others clearly.++---++### 10.1 RAG context is never populated during `file_page` generation (CRITICAL)++**What the architecture says:**+> "RAG context — vector store similarity search using this file's top exported symbols+> as the query. Returns the top 3 most relevant already-generated pages."++**What the code does:**+`ContextAssembler.assemble_file_page()` returns a `FilePageContext` with+`rag_context: list[str] = field(default_factory=list)` — always an empty list.+The vector store is never queried during context assembly. The field is only populated+in `assemble_update_context()` — and there it's used to pass trigger commit info,+not related page summaries.++**Impact:** The most powerful quality driver described in the architecture is not active.+File pages are generated without any knowledge of what their dependencies actually do.++**What needs to happen:** `assemble_file_page()` needs the vector store passed in,+and must call `vector_store.search(query=exported_symbol_names, top_k=3)` to retrieve+related page summaries before building the context.++---++### 10.2 Import summaries are missing — dependencies shown as bare paths only (CRITICAL)++**What the architecture says:**+> "Import summaries — for each file this file imports from: the summary of that file's+> already-generated wiki page (if available), or just its public API signatures."++**What the code does:**+`file_page.j2` renders `ctx.dependencies` as a list of file path strings:+```+## Dependencies (files this imports)+- `src/auth/jwt.py`+- `src/db/connection.py`+```++The LLM sees that `jwt.py` is imported but has no idea what `jwt.py` does. The+generation level ordering guarantees that `jwt.py`'s page was already generated — but+that page's content is never retrieved and included.++**Confirmed in output:** `supabase_service.py.md` lists `core.config`, `models.resume_analyzer_models`,+`services.supabase_service` as dependency names — these are module path strings inferred+from import statements. The LLM wrote accurate descriptions of what each dependency does,+but only because it read the source snippet and recognized the import patterns. Without the+source (e.g., for a large chunked file), dependency sections would be empty.++**Impact:** Dependency section quality is fragile — it works when source fits in the budget,+fails for large files. With import summaries, the LLM could document dependencies even when+source is truncated.++**What needs to happen:** After Level 2 completes, each file's generated page content+should be queryable by path. During context assembly, resolved dependency summaries+(or at minimum, their public symbol signatures) should be embedded in the prompt.++---++### 10.3 `module_git_summary` and `repo_git_summary` are dead template variables (SIGNIFICANT)++**What the templates do:**+Both `module_page.j2` and `repo_overview.j2` have blocks gated on these variables:+```jinja2+{% if module_git_summary is defined and module_git_summary %}+## Team ownership+...+{% endif %}+```++**What the code does:**+`PageGenerator.generate_module_page()` renders the template as:+```python+user_prompt = self._render("module_page.j2", ctx=ctx)+```++`module_git_summary` is never passed as a kwarg. In Jinja2 with `StrictUndefined`,+accessing an undefined variable raises an error — but the `is defined` check safely+returns False, so the block is silently skipped every time.++**Confirmed in output:** `backend.md` has no ownership section. `repo.md` has no health+signals section (no hotspot count, no top churn files). Both template blocks were silently+skipped on every call.++**Impact:** Module pages never show team ownership. Repo overview pages never show+health signals (hotspot count, stable files, top churn files, oldest file).++**What needs to happen:** Both generators need to query git metadata and pass+`module_git_summary=...` and `repo_git_summary=...` as keyword arguments to `_render()`.++---++### 10.4 Architecture diagram dumps ALL nodes and edges regardless of repo size (SIGNIFICANT)++**What the code does:**+`assemble_architecture_diagram()` passes every non-external node and every edge to+the template. For a 1,000-file repo:+```+**Nodes** (1,000 files):+- `src/auth/jwt.py`+- `src/auth/session.py`+... 998 more lines ...++**Edges** (3,500 dependencies):+- `src/app.py` → `src/auth/jwt.py`+... 3,499 more lines ...+```++This produces a prompt that will exceed any reasonable token budget and result in+an unrenderable or truncated Mermaid diagram.++**Observed in test run:** The 2022-file repo produced `interview-coach.md` with a clean+7-node Mermaid diagram. The LLM abstracted the thousands of nodes/edges to high-level+components. This happened despite receiving an enormous context — likely because the+prompt was so large the LLM had no choice but to summarise. The output was good *this+time*, but the approach is fragile: a less capable model, a stricter max_tokens setting,+or a repo with less descriptive paths would produce a broken or unrenderable diagram.++**Impact:** The architecture diagram is fragile at scale. It works by luck with capable+models but has no structural guarantee of producing a useful Mermaid diagram.++**What needs to happen:**+- Filter nodes to top-N by PageRank (e.g., top 50)+- Filter edges to only those connecting the selected nodes+- Collapse communities into single labeled nodes for the Mermaid output+- Provide a separate "module-level" diagram view using `module_page` membership++---++### 10.5 Large file chunking is not implemented — only truncation (SIGNIFICANT)++**What the architecture says:**+> "Files over `large_file_threshold_kb` (100KB) are handled differently: extracts+> public symbol signatures only for the top-level context, generates one sub-page per+> major class or function group, synthesizes a file page from the sub-pages."++**What the code does:**+`_trim_to_budget()` truncates source to whatever tokens remain after symbols and+imports. A 150KB file with many symbols may have its source truncated to ~500 tokens+or less. There is no sub-page generation, no chunking strategy, and no synthesis step.++**Impact:** Large files (common in tokio-rs, React internals) get documentation+built from heavily truncated source. The LLM cannot see the lower half of the file.++---++### 10.6 SCC context provides no symbol information (LOW — LLM compensates well)++**What the code does:**+`assemble_scc_page()` creates a string `"Circular dependency cycle: A → B → C"`+and a total symbol count. The template renders these two pieces.++**What the architecture says:**+> "Generate each SCC member with reduced context (own source + signatures of cycle+> partners only)"++The SCC page context has no signatures, no source, and no information about which+specific symbols create the cycle (the imports that close the loop).++**Observed in test run:** Despite this, `scc-69.md` and `scc-1068.md` both produced+excellent output. The LLM inferred cycle causes and provided specific, actionable+refactoring advice entirely from file path names. `scc-1068` correctly identified the+`__init__.py` re-export anti-pattern and even recommended deletion since the module+is deprecated — information visible only in the path `deprecated/interview_service_old/`.++**Revised impact:** For descriptively-named codebases, SCC quality is high despite+thin context. For codebases with opaque names (`module_a/`, `handler_v2/`), the+LLM would produce generic advice. Adding the specific cross-imports that close the+cycle would improve reliability across all codebases.++---++### 10.7 Cross-package generation is stubbed out for monorepos (SIGNIFICANT)++**What the code does:**+```python+# ---- Level 5: cross_package (only if monorepo) ----+if repo_structure.is_monorepo:+ log.info("Skipping cross_package generation (Phase 4)")+```++No `cross_package` pages are ever generated. For a monorepo like a React-scale project,+this means there is no documentation of how `@react/core` depends on `@react/scheduler`,+or what the public API boundary between packages is.++---++### 10.8 Symbol spotlight lacks source body (MODERATE — degrades for undocumented symbols)++`symbol_spotlight.j2` includes the signature and docstring but not the function body.+For a complex 80-line function with no docstring, the LLM gets only the signature line.+It cannot generate "## Example Usage" or explain implementation details without seeing+the code.++**Observed in test run:** `get_user_analyses.md` produced a correct, usable example.+But `get_user_analyses` has a full type signature with all parameter names and types —+the LLM had enough to infer usage. For internal symbols with opaque signatures and no+docstring, the output would degrade to a near-empty example section.++**What needs to happen:** Extract the source lines between `symbol.start_line` and+`symbol.end_line` from `source_bytes` and include them in the spotlight context.++---++### 10.9 Generation depth selection result is unused (MODERATE)++`_select_generation_depth()` computes `"minimal"` / `"standard"` / `"thorough"` based+on git metadata and PageRank, but the return value is never plumbed into `generate_all()`+or any template. All file pages receive identical treatment regardless of depth.++**What needs to happen:** Pass the computed depth to the template as a `ctx.depth`+field and use it to conditionally include/exclude context sections (e.g., skip source+snippet for `"minimal"` pages, include extra analysis instructions for `"thorough"`).++---++### 10.10 `_sort_level_files` is defined but never awaited (MINOR)++```python+async def _sort_level_files(self, files, git_meta_map, pagerank) -> list[ParsedFile]:+ ...+```++This method is defined but never called in `generate_all()`. Level 2 processes+`code_files` in the order they come from the traverser. Entry points, hotspots, and+high-PageRank files should be generated first to maximize their availability as RAG+context for later files — but this priority sort is never applied.++---++### 10.11 Token budget default (8K) doesn't match architecture doc (12K) (MINOR)++`GenerationConfig.token_budget` defaults to `8000`. The architecture document states:+> "Token budget: the total assembled context targets 12K tokens."++The architecture doc also describes a specific priority drop order (git context is the+*last* thing dropped), while the code drops git context first (it's outside the budget+calculation entirely — it's appended unconditionally after the budget loop).++**Observed in test run:** Config snapshot from `jobs/6b10db4b-....json` confirms+`token_budget: 8000` was used in the actual run.++---++### 10.12 Job progress tracking is broken (SIGNIFICANT — live UI will show wrong data)++`job_system.start_job(job_id, len(all_pages))` is called at the *end* of `generate_all`,+after all pages have been generated. This means:+- During generation, `total_pages` is always `0` in the DB+- `completed_pages` never increments during generation+- The SSE job stream sent to the web UI shows `0 / 0` pages for the entire run+- If the process crashes mid-run, the job log shows 0 completed even if 400 pages+ finished before the crash++**Confirmed in test run:** A failed job (`6b10db4b-....json`) shows+`total_pages: 0, completed_pages: 0` with `failed_pages: 5`, despite `state.json`+recording 33 successfully generated pages from a separate run.++**What needs to happen:** Call `start_job(job_id, estimated_total)` at the *start* of+`generate_all`, before the first level runs. Use the significance filter pre-computation+that already exists to estimate page count before generation begins.++---++### 10.13 `failed_page_ids` stores level names, not page IDs (MINOR)++```python+job_system.fail_page(job_id, f"level-{level}", str(r))+```++The second argument is the page ID, but `f"level-{level}"` is passed instead of an+actual page ID. The resulting `failed_page_ids` list contains entries like+`["level-1", "level-2", "level-3"]` — useless for identifying which specific pages+failed or retrying them on resume.++**Confirmed in test run:** `failed_page_ids: ["level-1", "level-2", "level-3", "level-4", "level-6"]`+in the failed job JSON.++**What needs to happen:** When catching exceptions from `asyncio.gather`, extract the+page ID from the coroutine context and pass that instead of the level string.++---++## Summary: Gaps by Priority++Severity ratings updated based on actual output from the `interview-coach` test run.++| # | Gap | Severity | Evidence | Effort |+|---|-----|----------|----------|--------|+| 10.1 | RAG context never populated | **Critical** | Always `[]` in code | Medium |+| 10.2 | Import summaries are bare paths | **Critical** | Confirmed in all file pages | Medium |+| 10.3 | `module_git_summary`/`repo_git_summary` dead | **Significant** | Confirmed missing in `backend.md`, `repo.md` | Low |+| 10.4 | Architecture diagram dumps all nodes/edges | **Significant** | Worked by luck in test run; fragile | Medium |+| 10.5 | No large file chunking | **Significant** | Not exercised in test run; logic gap clear | High |+| 10.6 | SCC context has no symbols | **Low** | LLM compensates well from path names alone | Low |+| 10.7 | Cross-package pages stubbed | **Significant** | Hardcoded skip in `generate_all` | High |+| 10.8 | Symbol spotlight lacks source body | **Moderate** | Good output for typed symbols; degrades for untyped | Low |+| 10.9 | Depth selection unused | **Moderate** | `_select_generation_depth` return value discarded | Low |+| 10.10 | `_sort_level_files` never called | **Minor** | Dead async method | Low |+| 10.11 | Budget is 8K not 12K | **Minor** | Confirmed 8K in job snapshot | Low |+| 10.12 | Job progress tracking broken | **Significant** | `total_pages: 0` in live jobs; SSE shows 0/0 | Low |+| 10.13 | `failed_page_ids` stores level names | **Minor** | Confirmed `["level-1","level-2",...]` in job JSON | Low |diff --git a/docs/PHASE_5_5_IMPLEMENTATION.md b/docs/PHASE_5_5_IMPLEMENTATION.mdnew file mode 100644index 000000000..62d796f9d--- /dev/null+++ b/docs/PHASE_5_5_IMPLEMENTATION.md@@ -0,0 +1,944 @@+# Phase 5.5 — Git Intelligence + Dead Code Detection: Implementation Prompt++This document contains everything needed to implement Phase 5.5 of WikiCode.+Read the full document before writing any code.++**Context:** Phases 1-5 are complete and passing (473 tests, 11.48s). Phase 5.5 is+a standalone feature detour before Phase 6 (Server). All additions are additive —+do not modify any existing Phase 1-5 code, only extend it.++**Important files to read first:**+- `docs/ARCHITECTURE.md` — sections 7 (Git Intelligence) and 8 (Dead Code Detection)+- `BUILD_STATUS.md` — Phase 5.5 step breakdown+- `PLAN.md` — full project plan with git/dead-code integrated++---++## Codebase Layout (What Already Exists)++```+packages/core/src/wikicode/core/+├── generation/+│ ├── context_assembler.py # ContextAssembler class+│ ├── page_generator.py # PageGenerator class (8-level pipeline)+│ ├── models.py # GeneratedPage, GenerationConfig, confidence logic+│ ├── job_system.py # JobSystem + Checkpoint+│ └── templates/ # 9 Jinja2 .j2 templates+├── ingestion/+│ ├── graph.py # GraphBuilder (NetworkX)+│ ├── change_detector.py # ChangeDetector, FileDiff, AffectedPages+│ ├── models.py # ParsedFile, Symbol, FileInfo, RepoStructure+│ ├── parser.py # ASTParser+│ └── traverser.py # FileTraverser (extra_exclude_patterns + per-dir .wikicodeIgnore)+├── persistence/+│ ├── models.py # SQLAlchemy ORM: Repository, Page, GraphNode, etc.+│ ├── database.py # Engine/session creation+│ ├── crud.py # Async CRUD operations+│ ├── search.py # Full-text search+│ └── vector_store.py # Vector storage+└── providers/ # LLM providers (unchanged)++packages/cli/src/wikicode/cli/+├── commands/+│ ├── init_cmd.py # wikicode init pipeline+│ ├── update_cmd.py # wikicode update pipeline+│ └── ...+├── helpers.py+├── cost_estimator.py+└── main.py # Click group + command registrations+```++---++## Existing Key Interfaces (Exact Signatures)++### persistence/models.py++```python+# Imports+from datetime import datetime, timezone+from uuid import uuid4+from sqlalchemy import (Boolean, DateTime, Float, ForeignKey, Integer, String, Text, UniqueConstraint)+from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column++# Helper functions used throughout+def _new_uuid() -> str: return uuid4().hex+def _now_utc() -> datetime: return datetime.now(timezone.utc)++class Base(DeclarativeBase): pass++# Existing tables: Repository, GenerationJob, Page, PageVersion, GraphNode,+# GraphEdge, WebhookEvent, WikiSymbol (all use Mapped[] type hints)+```++### generation/models.py++```python+from dataclasses import dataclass, field+from typing import Literal++PageType = Literal["api_contract", "symbol_spotlight", "file_page", "scc_page",+ "module_page", "cross_package", "repo_overview",+ "architecture_diagram", "infra_page", "diff_summary"]+FreshnessStatus = Literal["fresh", "stale", "expired", "unknown"]++@dataclass(frozen=True)+class GenerationConfig:+ max_tokens: int = 4096+ temperature: float = 0.3+ token_budget: int = 8000+ max_concurrency: int = 5+ cache_enabled: bool = True+ staleness_threshold_days: int = 7+ expiry_threshold_days: int = 30+ top_symbol_percentile: float = 0.10+ file_page_top_percentile: float = 0.20+ file_page_min_symbols: int = 1+ jobs_dir: str = ".wikicode/jobs"++# Confidence: linear decay based on days since update+def compute_freshness(...) -> str: ...+def decay_confidence(...) -> ConfidenceDecayResult: ...+```++### generation/context_assembler.py++```python+@dataclass+class FilePageContext:+ file_path: str+ language: str+ docstring: str | None+ symbols: list[dict[str, Any]]+ imports: list[str]+ exports: list[str]+ file_source_snippet: str+ pagerank_score: float+ betweenness_score: float+ community_id: int+ dependents: list[str]+ dependencies: list[str]+ is_api_contract: bool+ is_entry_point: bool+ is_test: bool+ parse_errors: list[str]+ estimated_tokens: int+ rag_context: list[str] = field(default_factory=list)++class ContextAssembler:+ def __init__(self, config: GenerationConfig) -> None: ...+ def assemble_file_page(self, parsed, graph, pagerank, betweenness, community, source_bytes) -> FilePageContext: ...+ def assemble_module_page(self, module_path, language, file_contexts, graph) -> ModulePageContext: ...+ def assemble_repo_overview(self, repo_structure, pagerank, sccs, community) -> RepoOverviewContext: ...+ def assemble_diff_summary(self, file_diffs, affected_pages, from_ref, to_ref) -> DiffSummaryContext: ...+ # ... other assemble_* methods+```++### generation/page_generator.py++```python+class PageGenerator:+ def __init__(self, provider, assembler, config, jinja_env=None): ...++ async def generate_all(self, parsed_files, source_map, graph_builder, repo_structure, repo_name, job_system=None) -> list[GeneratedPage]:+ # Levels 0-7 run sequentially. Within each level:+ # - Selects files/symbols for that level+ # - Uses asyncio.Semaphore(config.max_concurrency)+ # - Level 2 (file pages): filters by _is_significant_file(), groups by module+ ...+```++### ingestion/graph.py++```python+class GraphBuilder:+ def __init__(self) -> None: ...+ def add_file(self, parsed: ParsedFile) -> None: ...+ def build(self) -> nx.DiGraph: ...+ def graph(self) -> nx.DiGraph: ...+ def pagerank(self, alpha=0.85) -> dict[str, float]: ...+ def betweenness_centrality(self) -> dict[str, float]: ...+ def strongly_connected_components(self) -> list[frozenset[str]]: ...+ def community_detection(self) -> dict[str, int]: ...+ # Node attrs: language, symbol_count, has_error, is_test, is_entry_point, pagerank, betweenness, community_id+ # Edge attrs: imported_names (list[str])+```++### ingestion/change_detector.py++```python+@dataclass+class FileDiff:+ path: str+ status: Literal["added", "deleted", "modified", "renamed"]+ old_path: str | None+ old_parsed: ParsedFile | None+ new_parsed: ParsedFile | None+ symbol_diff: SymbolDiff | None++@dataclass+class AffectedPages:+ regenerate: list[str]+ rename_patch: list[str]+ decay_only: list[str]++class ChangeDetector:+ def __init__(self, repo_path: Path) -> None: ...+ def get_changed_files(self, base_ref="HEAD~1", until_ref="HEAD") -> list[FileDiff]: ...+ def get_affected_pages(self, file_diffs, graph, cascade_budget=30) -> AffectedPages: ...+```++### persistence/crud.py++```python+# Key existing functions:+async def upsert_repository(session, *, name, local_path, ...) -> Repository+async def upsert_page_from_generated(session, generated_page, repository_id) -> Page+async def batch_upsert_graph_nodes(session, repository_id, nodes) -> None+async def batch_upsert_graph_edges(session, repository_id, edges) -> None+async def batch_upsert_symbols(session, repository_id, symbols) -> None+async def get_page(session, page_id) -> Page | None+async def list_pages(session, repository_id, ...) -> list[Page]++_BATCH_SIZE = 500 # Used for all batch operations+```++### CLI: init_cmd.py pipeline (abbreviated)++```python+# Pipeline order:+# 1. Resolve repo path+# 2. Ensure .wikicode dir+# 2.5 Load config; merge exclude_patterns from config + --exclude/-x flags+# 3. Resolve LLM provider+# 4. FileTraverser(extra_exclude_patterns=...) → list[FileInfo]+# 5. ASTParser → list[ParsedFile]+# 6. GraphBuilder → build graph, compute metrics+# 7. Cost estimate + confirmation+# 8. PageGenerator.generate_all() → list[GeneratedPage]+# 9. Persist pages, graph, symbols to DB+# 10. FTS indexing+# 11. Update state file+```++### CLI: update_cmd.py pipeline (abbreviated)++```python+# Pipeline order:+# 1. Load state, get base_ref+# 2. ChangeDetector.get_changed_files()+# 3. Re-ingest full repo for graph+# 4. ChangeDetector.get_affected_pages()+# 5. PageGenerator.generate_all() for affected files+# 6. Persist + update state+```++---++## What to Build++### New Files to Create++```+packages/core/src/wikicode/core/+├── ingestion/+│ └── git_indexer.py # GitIndexer class+├── analysis/+│ ├── __init__.py+│ └── dead_code.py # DeadCodeAnalyzer class++packages/cli/src/wikicode/cli/+└── commands/+ └── dead_code_cmd.py # wikicode dead-code CLI command++tests/+├── unit/+│ ├── test_git_indexer.py+│ ├── test_dead_code.py+│ └── test_confidence_with_git.py+└── integration/+ ├── test_git_intelligence_integration.py+ └── test_dead_code_integration.py++tests/fixtures/sample_repo/+├── dead/+│ └── unreachable_module.py # nothing imports this+└── utils/+ └── helpers.py # has unused_helper() export+```++### Existing Files to Modify (additive only)++| File | Change |+|------|--------|+| `persistence/models.py` | Add `GitMetadata` + `DeadCodeFinding` ORM classes |+| `persistence/crud.py` | Add git metadata + dead code CRUD functions |+| `generation/models.py` | Add `GitConfig`, `DeadCodeConfig` dataclasses; extend `GenerationConfig`; add `compute_confidence_decay_with_git()` |+| `generation/context_assembler.py` | Add `git_metadata`, `co_change_pages`, `dead_code_findings` to `FilePageContext`; add `assemble_update_context()` method; add `_select_generation_depth()` method |+| `generation/page_generator.py` | Add `_sort_level_files()` method for hotspot priority ordering |+| `generation/templates/file_page.j2` | Add git context block + dead code block (all `{% if %}` gated) |+| `generation/templates/module_page.j2` | Add ownership summary block |+| `generation/templates/repo_overview.j2` | Add codebase health signals block |+| `generation/templates/diff_summary.j2` | Add trigger commit + diff context |+| `ingestion/graph.py` | Add `add_co_change_edges()` + `update_co_change_edges()` methods |+| `ingestion/change_detector.py` | Extend `FileDiff` with trigger commit fields; include co-change partners in staleness |+| `cli/commands/init_cmd.py` | Add Steps 3.5 (git indexing) and 3.6 (dead code analysis) |+| `cli/commands/update_cmd.py` | Add git re-index + dead code re-analysis |+| `cli/main.py` | Register `dead-code` command |++---++## Detailed Specifications++### 1. GitMetadata ORM Model (`persistence/models.py`)++Add to existing file — do NOT modify existing models:++```python+class GitMetadata(Base):+ __tablename__ = "git_metadata"+ __table_args__ = (+ UniqueConstraint("repository_id", "file_path", name="uq_git_metadata"),+ )++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ file_path: Mapped[str] = mapped_column(Text, nullable=False)++ # Commit volume+ commit_count_total: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ commit_count_90d: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ commit_count_30d: Mapped[int] = mapped_column(Integer, nullable=False, default=0)++ # Timeline+ first_commit_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ last_commit_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)++ # Ownership+ primary_owner_name: Mapped[str | None] = mapped_column(String(255), nullable=True)+ primary_owner_email: Mapped[str | None] = mapped_column(String(255), nullable=True)+ primary_owner_commit_pct: Mapped[float | None] = mapped_column(Float, nullable=True)++ # JSON fields (stored as Text, parsed/serialized in CRUD layer)+ top_authors_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ significant_commits_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ co_change_partners_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")++ # Derived signals+ is_hotspot: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ is_stable: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ churn_percentile: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ age_days: Mapped[int] = mapped_column(Integer, nullable=False, default=0)++ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc)+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc)+```++**Important:** The existing codebase does NOT use SQLAlchemy JSON type — it stores JSON+as Text and parses in the CRUD layer (see `config_json`, `imported_names_json`, etc.).+Follow this same pattern for `top_authors_json`, `significant_commits_json`, and+`co_change_partners_json`.++### 2. DeadCodeFinding ORM Model (`persistence/models.py`)++```python+class DeadCodeFinding(Base):+ __tablename__ = "dead_code_findings"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ kind: Mapped[str] = mapped_column(String(32), nullable=False) # unreachable_file, unused_export, etc.+ file_path: Mapped[str] = mapped_column(Text, nullable=False)+ symbol_name: Mapped[str | None] = mapped_column(String(255), nullable=True)+ symbol_kind: Mapped[str | None] = mapped_column(String(32), nullable=True)+ confidence: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ reason: Mapped[str] = mapped_column(Text, nullable=False, default="")+ last_commit_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ commit_count_90d: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ lines: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ package: Mapped[str | None] = mapped_column(String(255), nullable=True)+ evidence_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ safe_to_delete: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ primary_owner: Mapped[str | None] = mapped_column(String(255), nullable=True)+ age_days: Mapped[int | None] = mapped_column(Integer, nullable=True)+ status: Mapped[str] = mapped_column(String(32), nullable=False, default="open") # open, acknowledged, resolved, false_positive+ note: Mapped[str | None] = mapped_column(Text, nullable=True)+ analyzed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc)+```++### 3. Alembic Migration++Create a new Alembic migration file. Follow the pattern of the existing+`0001_initial_schema.py` migration. The migration should:+- Create `git_metadata` table with all columns+- Create `dead_code_findings` table with all columns+- Add indexes on `repository_id` for both tables+- Add index on `(repository_id, file_path)` for git_metadata++### 4. CRUD Functions (`persistence/crud.py`)++Add these functions — follow existing patterns (async, use `_BATCH_SIZE = 500`):++```python+# Git metadata CRUD+async def upsert_git_metadata(session, *, repository_id, file_path, **kwargs) -> GitMetadata+async def get_git_metadata(session, repository_id, file_path) -> GitMetadata | None+async def get_git_metadata_bulk(session, repository_id, file_paths: list[str]) -> dict[str, GitMetadata]+async def get_all_git_metadata(session, repository_id) -> dict[str, GitMetadata]+async def upsert_git_metadata_bulk(session, repository_id, metadata_list: list[dict]) -> None++# Dead code CRUD+async def save_dead_code_findings(session, repository_id, findings: list[dict]) -> None+async def get_dead_code_findings(session, repository_id, *, kind=None, min_confidence=0.0, status="open") -> list[DeadCodeFinding]+async def update_dead_code_status(session, finding_id, status, note=None) -> DeadCodeFinding | None+async def get_dead_code_summary(session, repository_id) -> dict+```++### 5. GitIndexer (`ingestion/git_indexer.py`)++```python+import asyncio+import json+from dataclasses import dataclass, field+from datetime import datetime, timezone, timedelta+from pathlib import Path+from typing import Any++import structlog++logger = structlog.get_logger()+++@dataclass+class GitIndexSummary:+ files_indexed: int+ hotspots: int+ stable_files: int+ duration_seconds: float = 0.0+++class GitIndexer:+ """+ Mines git history into the git_metadata table.++ Uses gitpython (already a dependency) for git operations.+ Parallelizes per-file git log calls with asyncio.Semaphore(20).++ Non-blocking: if git is unavailable or repo has no history, log a warning+ and return an empty summary. All downstream features degrade gracefully.+ """++ def __init__(self, repo_path: str | Path):+ self.repo_path = Path(repo_path)++ async def index_repo(self, repo_id: str) -> tuple[GitIndexSummary, list[dict]]:+ """+ Full index of all tracked files. Returns summary + list of metadata dicts+ ready for bulk upsert.++ Steps:+ 1. Get list of tracked files from git+ 2. Per-file git log (parallelized with Semaphore(20))+ 3. Per-file git blame for ownership (if blame_enabled)+ 4. Co-change analysis (walk last N commits)+ 5. Compute repo-wide percentiles for hotspot detection+ """++ async def index_changed_files(self, changed_file_paths: list[str]) -> list[dict]:+ """+ Incremental update: re-index only changed files.+ Also re-index any file whose co_change_partners include a changed file.+ """++ # Internal methods:+ # _get_tracked_files() -> list[str]+ # _index_file(file_path, repo) -> dict (runs in executor to avoid blocking)+ # _get_blame_ownership(file_path, repo) -> tuple[name, email, pct]+ # _is_significant_commit(message) -> bool+ # _compute_co_changes(repo, all_files, commit_limit=500) -> dict[str, list[dict]]+ # _compute_percentiles(metadata_list) -> None (mutates in place)+```++**Key implementation notes:**+- Use `git.Repo(self.repo_path)` from gitpython+- Run `git log` and `git blame` in `asyncio.get_event_loop().run_in_executor()` since+ gitpython is synchronous+- `_is_significant_commit()`: skip prefixes "Merge ", "Bump ", "chore:", "ci:", "style:",+ "build:", "release:", "revert:"; skip authors containing "dependabot", "renovate",+ "github-actions"; skip messages < 20 chars+- Co-change analysis: walk commits, for each commit touching >= 2 tracked files,+ record co-occurrence pairs. Return pairs with count >= `co_change_min_count` (default 3).+ Limit to last `co_change_commit_limit` commits (default 500).+- Percentiles: `churn_percentile = rank / total_files`. `is_hotspot = commit_count_90d > p75+ AND complexity_estimate > p75` (get complexity from GraphNode if available, else use file size).+ `is_stable = commit_count_total > 10 AND commit_count_90d == 0`.++### 6. DeadCodeAnalyzer (`analysis/dead_code.py`)++Pure graph traversal + SQL — no LLM calls. Must complete in < 10 seconds.++```python+from dataclasses import dataclass, field+from datetime import datetime+from enum import Enum+from typing import Any, Literal++import structlog+++class DeadCodeKind(str, Enum):+ UNREACHABLE_FILE = "unreachable_file"+ UNUSED_EXPORT = "unused_export"+ UNUSED_INTERNAL = "unused_internal"+ ZOMBIE_PACKAGE = "zombie_package"+++@dataclass+class DeadCodeFindingData:+ kind: DeadCodeKind+ file_path: str+ symbol_name: str | None+ symbol_kind: str | None+ confidence: float+ reason: str+ last_commit_at: datetime | None+ commit_count_90d: int+ lines: int+ package: str | None+ evidence: list[str]+ safe_to_delete: bool+ primary_owner: str | None+ age_days: int | None+++@dataclass+class DeadCodeReport:+ repo_id: str+ analyzed_at: datetime+ total_findings: int+ findings: list[DeadCodeFindingData]+ deletable_lines: int+ confidence_summary: dict # {"high": N, "medium": N, "low": N}+++class DeadCodeAnalyzer:+ """+ Detects unreachable files, unused exports, unused internals, and+ zombie packages using the dependency graph and git metadata.++ All analysis is graph traversal + SQL. No LLM calls.+ """++ def __init__(self, graph, git_meta_map: dict | None = None):+ self.graph = graph # nx.DiGraph+ self.git_meta_map = git_meta_map or {}++ def analyze(self, config: dict | None = None) -> DeadCodeReport:+ """Full analysis. Returns report with all findings."""++ def analyze_partial(self, affected_files: list[str], config: dict | None = None) -> DeadCodeReport:+ """Partial analysis for incremental updates."""+```++**Confidence rules (implement exactly):**++Unreachable files (`graph.in_degree(node) == 0` AND not entry point AND not test AND not config):+- 1.0 if in_degree==0 AND commit_count_90d==0 AND last_commit > 6 months ago+- 0.7 if in_degree==0 AND commit_count_90d==0+- 0.4 if in_degree==0 but recently touched+- `safe_to_delete=True` only if confidence >= 0.7 AND NOT filename matches dynamic patterns++Unused exports (symbol `visibility=="public"` AND no incoming edges):+- 1.0 if symbol has no importers AND file IS imported elsewhere+- 0.7 if symbol has no importers AND file also has no importers+- 0.3 if name matches `*_DEPRECATED`, `*_LEGACY`, `*_COMPAT`+- `safe_to_delete=True` only if confidence >= 0.7 AND complexity_estimate < 5++**Never flag as dead:**+- Files in `__init__.py` / files that are re-export barrels+- `@pytest.fixture`, `@pytest.mark.*` symbols+- Files matching `*migrations*`, `*schema*`, `*seed*`+- `.d.ts` files+- `is_api_contract == True` files+- Files/symbols matching `config.dead_code.dynamic_patterns`+- Files in whitelist++### 7. Template Updates++**file_page.j2** — add at the END of the existing template, BEFORE the closing+instructions. All blocks gated on `{% if %}`:++```jinja2+{# ── Git context block ────────────────────────────────────────── #}+{% if git_metadata %}++{% if git_metadata.primary_owner_name %}+## Ownership+Primary maintainer: **{{ git_metadata.primary_owner_name }}**+({{ (git_metadata.primary_owner_commit_pct * 100) | round | int }}% of lines)+{% if git_metadata.top_authors | length > 1 %}+Also contributed by: {% for a in git_metadata.top_authors[1:3] %}{{ a.name }}{% if not loop.last %}, {% endif %}{% endfor %}+{% endif %}+{% endif %}++{% if git_metadata.significant_commit_messages %}+## Evolution context+This file has been shaped by {{ git_metadata.commit_count_total }} commits+over {{ git_metadata.age_days }} days. Key changes:+{% for commit in git_metadata.significant_commit_messages %}+- **{{ commit.date[:10] }}** — {{ commit.message }} *({{ commit.author }})*+{% endfor %}++Use this history to explain *why* the code is structured as it is.+{% endif %}++{% if git_metadata.is_hotspot %}+IMPORTANT: This file is a HOTSPOT — top 25% for both change frequency and+complexity. Note this prominently. High-risk area for bugs.+{% endif %}++{% if git_metadata.is_stable %}+NOTE: This file is STABLE — {{ git_metadata.commit_count_total }} commits+but unchanged in 90+ days. Emphasize stability and reliability.+{% endif %}++{% if git_metadata.co_change_partners %}+## Hidden coupling (co-change analysis)+These files have no import relationship but frequently change together:+{% for partner in git_metadata.co_change_partners[:3] %}+- `{{ partner.file_path }}` (co-changed {{ partner.co_change_count }} times)+{% endfor %}+Mention this relationship explicitly.+{% endif %}++{% endif %}+{# ── End git context block ────────────────────────────────────── #}++{% if dead_code_findings %}+## Potentially unused code+{% for finding in dead_code_findings %}+- `{{ finding.symbol_name }}` — {{ finding.reason }}+ (confidence: {{ (finding.confidence * 100) | int }}%{% if finding.safe_to_delete %}, safe to remove{% endif %})+{% endfor %}+{% endif %}+```++**module_page.j2** — add at end:+```jinja2+{% if module_git_summary %}+## Team ownership+{% for pkg_owner in module_git_summary.top_owners %}+- **{{ pkg_owner.file_count }} files** primarily maintained by {{ pkg_owner.name }}+{% endfor %}+Most active recently: `{{ module_git_summary.most_active_file }}`+({{ module_git_summary.most_active_commits_90d }} commits in 90 days)+{% endif %}+```++**repo_overview.j2** — add at end:+```jinja2+{% if repo_git_summary %}+## Codebase health signals+- **Hotspots:** {{ repo_git_summary.hotspot_count }} files are high-churn AND high-complexity+- **Stable core:** {{ repo_git_summary.stable_count }} files unchanged in 90+ days+- **Most changed (90d):** {{ repo_git_summary.top_churn_files[:3] | join(', ') }}+- **Oldest file:** `{{ repo_git_summary.oldest_file }}` ({{ repo_git_summary.oldest_file_age_days }} days)+{% endif %}+```++### 8. Context Assembler Extensions++**Extend `FilePageContext`** — add three new fields with defaults:++```python+@dataclass+class FilePageContext:+ # ... all existing fields unchanged ...+ git_metadata: dict | None = None # NEW+ co_change_pages: list[dict] = field(default_factory=list) # NEW+ dead_code_findings: list[dict] = field(default_factory=list) # NEW+```++**Extend `assemble_file_page()`** — add optional `git_meta` and `dead_code_findings`+parameters. If provided, include them in the returned context. If not, the fields+default to None/[].++**Add `_select_generation_depth()` method:**+```python+def _select_generation_depth(self, file, git_meta, config_depth) -> str:+ # Upgrade to "thorough" if: hotspot, >100 commits with >10 in 90d,+ # >=8 significant commits, or has co-change partners+ # Downgrade to "minimal" if: stable AND pagerank < 0.3 AND commit_count < 5+```++**Add `assemble_update_context()` method** for maintenance regeneration using+the triggering commit + diff instead of full file source.++### 9. Generation Ordering++Add `_sort_level_files()` to `PageGenerator`:++```python+async def _sort_level_files(self, files: list[ParsedFile], git_meta_map: dict) -> list[ParsedFile]:+ """Priority (highest first): entry points, hotspots, high PageRank, high commit count, alphabetical."""+```++Call this in `generate_all()` when processing Level 2 (file pages).++### 10. Confidence Decay Git Modifiers++Add `compute_confidence_decay_with_git()` to `generation/models.py`:++```python+def compute_confidence_decay_with_git(+ base_decay: float, # e.g. 0.85 for direct+ relationship: str, # "direct", "1hop", "2hop"+ git_meta: dict | None,+ commit_message: str | None,+) -> float:+ """Apply git modifiers multiplicatively on base decay."""+ # Hotspot: direct *= 0.94, 1hop *= 0.95+ # Stable: direct *= 1.03+ # "rewrite"/"refactor"/"migrate" in message: direct *= 0.71, 1hop *= 0.84+ # "typo"/"lint"/"format" in message: direct *= 1.12+```++### 11. Co-Change Edges in Graph++Add to `GraphBuilder`:++```python+def add_co_change_edges(self, git_meta_map: dict, min_count: int = 3) -> int:+ """Add co_changes edges. Returns count of edges added.+ These DO NOT affect PageRank — filter them out before computing."""++def update_co_change_edges(self, updated_meta: dict, min_count: int = 3) -> None:+ """Remove old co_changes edges for updated files, add new ones."""+```++### 12. Extended FileDiff++Add optional fields to `FileDiff` in `change_detector.py`:++```python+@dataclass+class FileDiff:+ # ... existing fields ...+ trigger_commit_sha: str | None = None # NEW+ trigger_commit_message: str | None = None # NEW+ trigger_commit_author: str | None = None # NEW+ diff_text: str | None = None # NEW (unified diff, capped at 4K chars)+```++### 13. Config Extensions++Extend `GenerationConfig` in `models.py`. Since it's `frozen=True`, add new config+as separate dataclasses:++```python+@dataclass(frozen=True)+class GitConfig:+ enabled: bool = True+ co_change_commit_limit: int = 500+ co_change_min_count: int = 3+ blame_enabled: bool = True+ prompt_commit_count: int = 10+ depth_auto_upgrade: bool = True++@dataclass(frozen=True)+class DeadCodeConfig:+ enabled: bool = True+ detect_unreachable_files: bool = True+ detect_unused_exports: bool = True+ detect_unused_internals: bool = False+ detect_zombie_packages: bool = True+ min_confidence: float = 0.4+ safe_to_delete_threshold: float = 0.7+ dynamic_patterns: tuple[str, ...] = ("*Plugin", "*Handler", "*Adapter", "*Middleware", "register_*", "on_*")+ analyze_on_update: bool = True+```++Pass these as parameters where needed rather than modifying the frozen `GenerationConfig`.++### 14. Init Pipeline Integration++In `init_cmd.py`, add between graph computation and cost estimation:++```python+# Step 3.5: Git indexing+git_indexer = GitIndexer(repo_path)+git_summary, git_metadata_list = await git_indexer.index_repo(repo_id)+# Persist git metadata to DB+await upsert_git_metadata_bulk(session, repo_id, git_metadata_list)+# Add co-change edges to graph+git_meta_map = {m["file_path"]: m for m in git_metadata_list}+graph_builder.add_co_change_edges(git_meta_map)++# Step 3.6: Dead code analysis+analyzer = DeadCodeAnalyzer(graph_builder.graph(), git_meta_map)+dead_code_report = analyzer.analyze()+await save_dead_code_findings(session, repo_id, dead_code_report.findings)+```++Show progress output:+```+[3.5] Indexing git history... done 3,247 files · 14 hotspots · 892 stable (2m 14s)+[3.6] Detecting dead code... done 7 unreachable files · 23 unused exports (~2,847 lines)+```++### 15. Update Pipeline Integration++In `update_cmd.py`, add after change detection:++```python+# Re-index git metadata for changed files+git_indexer = GitIndexer(repo_path)+updated_meta = await git_indexer.index_changed_files(changed_file_paths)+await upsert_git_metadata_bulk(session, repo_id, updated_meta)+# Update co-change edges+git_meta_map = {m["file_path"]: m for m in updated_meta}+graph_builder.update_co_change_edges(git_meta_map)+```++### 16. CLI: `wikicode dead-code` Command++```python[email protected]("dead-code")[email protected]("path", required=False, type=click.Path(exists=True))[email protected]("--min-confidence", default=0.4, type=float)[email protected]("--safe-only", is_flag=True)[email protected]("--kind", type=click.Choice(["unreachable_file", "unused_export", "unused_internal", "zombie_package"]))[email protected]("--format", "fmt", default="table", type=click.Choice(["table", "json", "md"]))+def dead_code_command(path, min_confidence, safe_only, kind, fmt):+ """Detect dead and unused code."""+```++Register in `main.py` via `cli.add_command(dead_code_command)`.++### 17. Tests++**test_git_indexer.py** (7 tests):+```python+def test_significant_commit_filter() # merges, bumps, chore filtered out+def test_co_change_detection() # files changed together >= 3 times detected+def test_hotspot_classification() # top 25% churn + complexity = is_hotspot+def test_stable_classification() # >10 commits, 0 in 90d = is_stable+def test_git_unavailable_graceful() # no history → empty metadata, no crash+def test_co_change_below_threshold_skipped() # pairs with count < min_count not stored+def test_blame_ownership_computed() # primary_owner set to dominant author+```++**test_dead_code.py** (12 tests):+```python+def test_unreachable_file_detected()+def test_entry_point_not_flagged()+def test_test_files_excluded()+def test_unused_export_detected()+def test_framework_decorator_excluded()+def test_dynamic_pattern_excluded()+def test_confidence_low_for_recent_files()+def test_confidence_high_for_stale_unreachable()+def test_zombie_package_detected()+def test_whitelist_respected()+def test_safe_to_delete_conservative()+def test_report_deletable_lines_sum()+```++**test_confidence_with_git.py** (4 tests):+```python+def test_hotspot_decays_faster()+def test_stable_decays_slower()+def test_rewrite_commit_hard_decay()+def test_typo_commit_soft_decay()+```++**Integration tests** (use sample_repo with added fixtures):+```python+async def test_git_indexer_on_sample_repo()+async def test_dead_code_detects_unreachable_fixture()+async def test_co_change_edges_in_graph()+async def test_hotspot_sorted_first_in_generation()+```++### 18. Test Fixtures++Add to `tests/fixtures/sample_repo/`:++**`dead/unreachable_module.py`** — a Python file with functions that nothing imports:+```python+"""This module is intentionally unreachable — used for dead code detection tests."""++def orphaned_function():+ """No one calls this."""+ return 42++class OrphanedClass:+ """No one imports this."""+ pass+```++**`utils/helpers.py`** — add an unused export (if this file already exists, add to it):+```python+def unused_helper():+ """This function is exported but never imported anywhere."""+ return "unused"+```++---++## Implementation Order++Build in this exact order (each step should be testable independently):++1. `GitMetadata` + `DeadCodeFinding` ORM models + migration+2. CRUD functions for git metadata and dead code+3. `GitIndexer` class + `test_git_indexer.py` tests+4. `DeadCodeAnalyzer` class + `test_dead_code.py` tests+5. `GitConfig` + `DeadCodeConfig` dataclasses+6. Template updates (file_page.j2, module_page.j2, repo_overview.j2)+7. `FilePageContext` extensions + `ContextAssembler` extensions+8. `_sort_level_files()` in PageGenerator+9. `_select_generation_depth()` in ContextAssembler+10. Confidence decay git modifiers + `test_confidence_with_git.py`+11. Co-change edges in GraphBuilder+12. FileDiff trigger commit extensions+13. diff_summary.j2 update + `assemble_update_context()`+14. ChangeDetector co-change partner staleness+15. Init pipeline integration (Steps 3.5 + 3.6)+16. Update pipeline integration+17. `wikicode dead-code` CLI command+18. Integration tests+19. Run full test suite: `pytest tests/ -q` — all must pass++---++## Critical Constraints++1. **Additive only.** Do NOT rewrite existing methods — add new methods, extend dataclasses+ with defaulted fields, add `{% if %}` blocks to templates.++2. **Graceful degradation.** Every use of `git_metadata` must handle `None`. If `GitIndexer`+ fails or git is unavailable, all features fall back silently to pre-feature behavior.++3. **Follow existing patterns.** JSON stored as Text (not SQLAlchemy JSON type). UUIDs via+ `_new_uuid()`. Timestamps via `_now_utc()`. `Mapped[]` for all ORM columns. `_BATCH_SIZE = 500`+ for bulk operations. `structlog` for logging.++4. **No new dependencies.** `gitpython` is already in the dependency tree. All analysis is+ pure Python + NetworkX + SQL.++5. **Performance.** GitIndexer < 3 min for 3K files. DeadCodeAnalyzer < 10 seconds.+ Co-change computation < 30 seconds.++6. **Conservative dead code.** When in doubt, do NOT flag. `safe_to_delete` is very conservative.++7. **Test everything.** 23 new unit tests + integration tests. All existing 473 tests must+ continue passing.++8. **MCP tools, REST API endpoints, and Web UI pages are NOT built in this phase.** They are+ deferred to Phases 6, 7, and 8 respectively. Only the core logic, templates, CLI, and+ pipeline integration are built here.diff --git a/package-lock.json b/package-lock.jsonnew file mode 100644index 000000000..598cdf102--- /dev/null+++ b/package-lock.json@@ -0,0 +1,11150 @@+{+ "name": "wikicode-root",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "wikicode-root",+ "version": "0.1.0",+ "workspaces": [+ "packages/web"+ ],+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@alloc/quick-lru": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",+ "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@antfu/install-pkg": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-1.1.0.tgz",+ "integrity": "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==",+ "license": "MIT",+ "dependencies": {+ "package-manager-detector": "^1.3.0",+ "tinyexec": "^1.0.1"+ },+ "funding": {+ "url": "https://github.com/sponsors/antfu"+ }+ },+ "node_modules/@babel/code-frame": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",+ "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-validator-identifier": "^7.28.5",+ "js-tokens": "^4.0.0",+ "picocolors": "^1.1.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-validator-identifier": {+ "version": "7.28.5",+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",+ "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/runtime": {+ "version": "7.29.2",+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",+ "integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@braintree/sanitize-url": {+ "version": "7.1.2",+ "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-7.1.2.tgz",+ "integrity": "sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==",+ "license": "MIT"+ },+ "node_modules/@chevrotain/cst-dts-gen": {+ "version": "11.1.2",+ "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-11.1.2.tgz",+ "integrity": "sha512-XTsjvDVB5nDZBQB8o0o/0ozNelQtn2KrUVteIHSlPd2VAV2utEb6JzyCJaJ8tGxACR4RiBNWy5uYUHX2eji88Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@chevrotain/gast": "11.1.2",+ "@chevrotain/types": "11.1.2",+ "lodash-es": "4.17.23"+ }+ },+ "node_modules/@chevrotain/gast": {+ "version": "11.1.2",+ "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-11.1.2.tgz",+ "integrity": "sha512-Z9zfXR5jNZb1Hlsd/p+4XWeUFugrHirq36bKzPWDSIacV+GPSVXdk+ahVWZTwjhNwofAWg/sZg58fyucKSQx5g==",+ "license": "Apache-2.0",+ "dependencies": {+ "@chevrotain/types": "11.1.2",+ "lodash-es": "4.17.23"+ }+ },+ "node_modules/@chevrotain/regexp-to-ast": {+ "version": "11.1.2",+ "resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-11.1.2.tgz",+ "integrity": "sha512-nMU3Uj8naWer7xpZTYJdxbAs6RIv/dxYzkYU8GSwgUtcAAlzjcPfX1w+RKRcYG8POlzMeayOQ/znfwxEGo5ulw==",+ "license": "Apache-2.0"+ },+ "node_modules/@chevrotain/types": {+ "version": "11.1.2",+ "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-11.1.2.tgz",+ "integrity": "sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==",+ "license": "Apache-2.0"+ },+ "node_modules/@chevrotain/utils": {+ "version": "11.1.2",+ "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-11.1.2.tgz",+ "integrity": "sha512-4mudFAQ6H+MqBTfqLmU7G1ZwRzCLfJEooL/fsF6rCX5eePMbGhoy5n4g+G4vlh2muDcsCTJtL+uKbOzWxs5LHA==",+ "license": "Apache-2.0"+ },+ "node_modules/@emnapi/core": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.1.tgz",+ "integrity": "sha512-mukuNALVsoix/w1BJwFzwXBN/dHeejQtuVzcDsfOEsdpCumXb/E9j8w11h5S54tT1xhifGfbbSm/ICrObRb3KA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/wasi-threads": "1.2.0",+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/runtime": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.1.tgz",+ "integrity": "sha512-VYi5+ZVLhpgK4hQ0TAjiQiZ6ol0oe4mBx7mVv7IflsiEp0OWoVsp/+f9Vc1hOhE0TtkORVrI1GvzyreqpgWtkA==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/wasi-threads": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz",+ "integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@eslint-community/eslint-utils": {+ "version": "4.9.1",+ "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",+ "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "eslint-visitor-keys": "^3.4.3"+ },+ "engines": {+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ },+ "peerDependencies": {+ "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"+ }+ },+ "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": {+ "version": "3.4.3",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",+ "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@eslint-community/regexpp": {+ "version": "4.12.2",+ "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz",+ "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^12.0.0 || ^14.0.0 || >=16.0.0"+ }+ },+ "node_modules/@eslint/config-array": {+ "version": "0.21.2",+ "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz",+ "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/object-schema": "^2.1.7",+ "debug": "^4.3.1",+ "minimatch": "^3.1.5"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/config-helpers": {+ "version": "0.4.2",+ "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz",+ "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/core": "^0.17.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/core": {+ "version": "0.17.0",+ "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz",+ "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@types/json-schema": "^7.0.15"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/eslintrc": {+ "version": "3.3.5",+ "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz",+ "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ajv": "^6.14.0",+ "debug": "^4.3.2",+ "espree": "^10.0.1",+ "globals": "^14.0.0",+ "ignore": "^5.2.0",+ "import-fresh": "^3.2.1",+ "js-yaml": "^4.1.1",+ "minimatch": "^3.1.5",+ "strip-json-comments": "^3.1.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@eslint/js": {+ "version": "9.39.4",+ "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.4.tgz",+ "integrity": "sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://eslint.org/donate"+ }+ },+ "node_modules/@eslint/object-schema": {+ "version": "2.1.7",+ "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz",+ "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/plugin-kit": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz",+ "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@eslint/core": "^0.17.0",+ "levn": "^0.4.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@floating-ui/core": {+ "version": "1.7.5",+ "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz",+ "integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/utils": "^0.2.11"+ }+ },+ "node_modules/@floating-ui/dom": {+ "version": "1.7.6",+ "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz",+ "integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/core": "^1.7.5",+ "@floating-ui/utils": "^0.2.11"+ }+ },+ "node_modules/@floating-ui/react-dom": {+ "version": "2.1.8",+ "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.8.tgz",+ "integrity": "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/dom": "^1.7.6"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@floating-ui/utils": {+ "version": "0.2.11",+ "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz",+ "integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==",+ "license": "MIT"+ },+ "node_modules/@humanfs/core": {+ "version": "0.19.1",+ "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",+ "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18.18.0"+ }+ },+ "node_modules/@humanfs/node": {+ "version": "0.16.7",+ "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz",+ "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@humanfs/core": "^0.19.1",+ "@humanwhocodes/retry": "^0.4.0"+ },+ "engines": {+ "node": ">=18.18.0"+ }+ },+ "node_modules/@humanwhocodes/module-importer": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",+ "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=12.22"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/nzakas"+ }+ },+ "node_modules/@humanwhocodes/retry": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz",+ "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18.18"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/nzakas"+ }+ },+ "node_modules/@iconify/types": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz",+ "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==",+ "license": "MIT"+ },+ "node_modules/@iconify/utils": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@iconify/utils/-/utils-3.1.0.tgz",+ "integrity": "sha512-Zlzem1ZXhI1iHeeERabLNzBHdOa4VhQbqAcOQaMKuTuyZCpwKbC2R4Dd0Zo3g9EAc+Y4fiarO8HIHRAth7+skw==",+ "license": "MIT",+ "dependencies": {+ "@antfu/install-pkg": "^1.1.0",+ "@iconify/types": "^2.0.0",+ "mlly": "^1.8.0"+ }+ },+ "node_modules/@img/colour": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/sharp-darwin-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",+ "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-darwin-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",+ "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",+ "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",+ "cpu": [+ "arm64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",+ "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",+ "cpu": [+ "x64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",+ "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",+ "cpu": [+ "arm"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",+ "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",+ "cpu": [+ "arm64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-ppc64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz",+ "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",+ "cpu": [+ "ppc64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-riscv64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz",+ "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",+ "cpu": [+ "riscv64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-s390x": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz",+ "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==",+ "cpu": [+ "s390x"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",+ "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",+ "cpu": [+ "x64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",+ "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",+ "cpu": [+ "arm64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",+ "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",+ "cpu": [+ "x64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-linux-arm": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",+ "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",+ "cpu": [+ "arm"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",+ "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-ppc64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz",+ "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",+ "cpu": [+ "ppc64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-ppc64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-riscv64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz",+ "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",+ "cpu": [+ "riscv64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-riscv64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-s390x": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz",+ "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==",+ "cpu": [+ "s390x"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-s390x": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",+ "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",+ "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",+ "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-wasm32": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz",+ "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==",+ "cpu": [+ "wasm32"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/runtime": "^1.7.0"+ },+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",+ "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-ia32": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz",+ "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==",+ "cpu": [+ "ia32"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",+ "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@jridgewell/gen-mapping": {+ "version": "0.3.13",+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.0",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/remapping": {+ "version": "2.3.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/gen-mapping": "^0.3.5",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.31",+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.1.0",+ "@jridgewell/sourcemap-codec": "^1.4.14"+ }+ },+ "node_modules/@mdx-js/mdx": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/@mdx-js/mdx/-/mdx-3.1.1.tgz",+ "integrity": "sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdx": "^2.0.0",+ "acorn": "^8.0.0",+ "collapse-white-space": "^2.0.0",+ "devlop": "^1.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "estree-util-scope": "^1.0.0",+ "estree-walker": "^3.0.0",+ "hast-util-to-jsx-runtime": "^2.0.0",+ "markdown-extensions": "^2.0.0",+ "recma-build-jsx": "^1.0.0",+ "recma-jsx": "^1.0.0",+ "recma-stringify": "^1.0.0",+ "rehype-recma": "^1.0.0",+ "remark-mdx": "^3.0.0",+ "remark-parse": "^11.0.0",+ "remark-rehype": "^11.0.0",+ "source-map": "^0.7.0",+ "unified": "^11.0.0",+ "unist-util-position-from-estree": "^2.0.0",+ "unist-util-stringify-position": "^4.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/@mdx-js/react": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/@mdx-js/react/-/react-3.1.1.tgz",+ "integrity": "sha512-f++rKLQgUVYDAtECQ6fn/is15GkEH9+nZPM3MS0RcxVqoTfawHvDlSCH7JbMhAM6uJ32v3eXLvLmLvjGu7PTQw==",+ "license": "MIT",+ "dependencies": {+ "@types/mdx": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ },+ "peerDependencies": {+ "@types/react": ">=16",+ "react": ">=16"+ }+ },+ "node_modules/@mermaid-js/parser": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.0.1.tgz",+ "integrity": "sha512-opmV19kN1JsK0T6HhhokHpcVkqKpF+x2pPDKKM2ThHtZAB5F4PROopk0amuVYK5qMrIA4erzpNm8gmPNJgMDxQ==",+ "license": "MIT",+ "dependencies": {+ "langium": "^4.0.0"+ }+ },+ "node_modules/@napi-rs/wasm-runtime": {+ "version": "0.2.12",+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz",+ "integrity": "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/core": "^1.4.3",+ "@emnapi/runtime": "^1.4.3",+ "@tybys/wasm-util": "^0.10.0"+ }+ },+ "node_modules/@next/env": {+ "version": "15.5.13",+ "resolved": "https://registry.npmjs.org/@next/env/-/env-15.5.13.tgz",+ "integrity": "sha512-6h7Fm29+/u1WBPcPaQl0xBov7KXB6i0c8oFlSlehD+PuZJQjzXQBuYzfkM32G5iWOlKsXXyRtcMaaqwspRBujA==",+ "license": "MIT"+ },+ "node_modules/@next/eslint-plugin-next": {+ "version": "15.5.14",+ "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-15.5.14.tgz",+ "integrity": "sha512-ogBjgsFrPPz19abP3VwcYSahbkUOMMvJjxCOYWYndw+PydeMuLuB4XrvNkNutFrTjC9St2KFULRdKID8Sd/CMQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fast-glob": "3.3.1"+ }+ },+ "node_modules/@next/swc-darwin-arm64": {+ "version": "15.5.13",+ "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.5.13.tgz",+ "integrity": "sha512-XrBbj2iY1mQSsJ8RoFClNpUB9uuZejP94v9pJuSAzdzwFVHeP+Vu2vzBCHwSObozgYNuTVwKhLukG1rGCgj8xA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-darwin-x64": {+ "version": "15.5.13",+ "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.5.13.tgz",+ "integrity": "sha512-Ey3fuUeWDWtVdgiLHajk2aJ74Y8EWLeqvfwlkB5RvWsN7F1caQ6TjifsQzrAcOuNSnogGvFNYzjQlu7tu0kyWg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-linux-arm64-gnu": {+ "version": "15.5.13",+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.5.13.tgz",+ "integrity": "sha512-aLtu/WxDeL3188qx3zyB3+iw8nAB9F+2Mhyz9nNZpzsREc2t8jQTuiWY4+mtOgWp1d+/Q4eXuy9m3dwh3n1IyQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-linux-arm64-musl": {+ "version": "15.5.13",+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.5.13.tgz",+ "integrity": "sha512-9VZ0OsVx9PEL72W50QD15iwSCF3GD/dwj42knfF5C4aiBPXr95etGIOGhb8rU7kpnzZuPNL81CY4vIyUKa2xvg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-linux-x64-gnu": {+ "version": "15.5.13",+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.5.13.tgz",+ "integrity": "sha512-3knsu9H33e99ZfiWh0Bb04ymEO7YIiopOpXKX89ZZ/ER0iyfV1YLoJFxJJQNUD7OR8O7D7eiLI/TXPryPGv3+A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-linux-x64-musl": {+ "version": "15.5.13",+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.5.13.tgz",+ "integrity": "sha512-AVPb6+QZ0pPanJFc1hpx81I5tTiBF4VITw5+PMaR1CrboAUUxtxn3IsV0h48xI7fzd6/zw9D9i6khRwME5NKUw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-win32-arm64-msvc": {+ "version": "15.5.13",+ "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.5.13.tgz",+ "integrity": "sha512-FZ/HXuTxn+e5Lp6oRZMvHaMJx22gAySveJdJE0//91Nb9rMuh2ftgKlEwBFJxhkw5kAF/yIXz3iBf0tvDXRmCA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@next/swc-win32-x64-msvc": {+ "version": "15.5.13",+ "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.5.13.tgz",+ "integrity": "sha512-B5E82pX3VXu6Ib5mDuZEqGwT8asocZe3OMMnaM+Yfs0TRlmSQCBQUUXR9BkXQeGVboOWS1pTsRkS9wzFd8PABw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/@nodelib/fs.scandir": {+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",+ "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@nodelib/fs.stat": "2.0.5",+ "run-parallel": "^1.1.9"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/@nodelib/fs.stat": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",+ "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/@nodelib/fs.walk": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",+ "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@nodelib/fs.scandir": "2.1.5",+ "fastq": "^1.6.0"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/@nolyfill/is-core-module": {+ "version": "1.0.39",+ "resolved": "https://registry.npmjs.org/@nolyfill/is-core-module/-/is-core-module-1.0.39.tgz",+ "integrity": "sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.4.0"+ }+ },+ "node_modules/@radix-ui/number": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",+ "integrity": "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==",+ "license": "MIT"+ },+ "node_modules/@radix-ui/primitive": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",+ "integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",+ "license": "MIT"+ },+ "node_modules/@radix-ui/react-accordion": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-accordion/-/react-accordion-1.2.12.tgz",+ "integrity": "sha512-T4nygeh9YE9dLRPhAHSeOZi7HBXo+0kYIPJXayZfvWOWA0+n3dESrZbjfDPUABkUNym6Hd+f2IR113To8D2GPA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-collapsible": "1.1.12",+ "@radix-ui/react-collection": "1.1.7",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-controllable-state": "1.2.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-arrow": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.7.tgz",+ "integrity": "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-collapsible": {+ "version": "1.1.12",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-collapsible/-/react-collapsible-1.1.12.tgz",+ "integrity": "sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-collection": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.7.tgz",+ "integrity": "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-slot": "1.2.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-collection/node_modules/@radix-ui/react-slot": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-compose-refs": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.2.tgz",+ "integrity": "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-context": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.2.tgz",+ "integrity": "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-dialog": {+ "version": "1.1.15",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.1.15.tgz",+ "integrity": "sha512-TCglVRtzlffRNxRMEyR36DGBLJpeusFcgMVD9PZEzAKnUs1lKCgX5u9BmC2Yg+LL9MgZDugFFs1Vl+Jp4t/PGw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-dismissable-layer": "1.1.11",+ "@radix-ui/react-focus-guards": "1.1.3",+ "@radix-ui/react-focus-scope": "1.1.7",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-portal": "1.1.9",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-slot": "1.2.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "aria-hidden": "^1.2.4",+ "react-remove-scroll": "^2.6.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-slot": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-direction": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.1.tgz",+ "integrity": "sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-dismissable-layer": {+ "version": "1.1.11",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.11.tgz",+ "integrity": "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-escape-keydown": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-dropdown-menu": {+ "version": "2.1.16",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.1.16.tgz",+ "integrity": "sha512-1PLGQEynI/3OX/ftV54COn+3Sud/Mn8vALg2rWnBLnRaGtJDduNW/22XjlGgPdpcIbiQxjKtb7BkcjP00nqfJw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-menu": "2.1.16",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-controllable-state": "1.2.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-focus-guards": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz",+ "integrity": "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-focus-scope": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.7.tgz",+ "integrity": "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-id": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.1.tgz",+ "integrity": "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-label": {+ "version": "2.1.8",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-label/-/react-label-2.1.8.tgz",+ "integrity": "sha512-FmXs37I6hSBVDlO4y764TNz1rLgKwjJMQ0EGte6F3Cb3f4bIuHB/iLa/8I9VKkmOy+gNHq8rql3j686ACVV21A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.4"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-label/node_modules/@radix-ui/react-primitive": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz",+ "integrity": "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-slot": "1.2.4"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-menu": {+ "version": "2.1.16",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.1.16.tgz",+ "integrity": "sha512-72F2T+PLlphrqLcAotYPp0uJMr5SjP5SL01wfEspJbru5Zs5vQaSHb4VB3ZMJPimgHHCHG7gMOeOB9H3Hdmtxg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-collection": "1.1.7",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-dismissable-layer": "1.1.11",+ "@radix-ui/react-focus-guards": "1.1.3",+ "@radix-ui/react-focus-scope": "1.1.7",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-popper": "1.2.8",+ "@radix-ui/react-portal": "1.1.9",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-roving-focus": "1.1.11",+ "@radix-ui/react-slot": "1.2.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "aria-hidden": "^1.2.4",+ "react-remove-scroll": "^2.6.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-slot": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-popover": {+ "version": "1.1.15",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.1.15.tgz",+ "integrity": "sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-dismissable-layer": "1.1.11",+ "@radix-ui/react-focus-guards": "1.1.3",+ "@radix-ui/react-focus-scope": "1.1.7",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-popper": "1.2.8",+ "@radix-ui/react-portal": "1.1.9",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-slot": "1.2.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "aria-hidden": "^1.2.4",+ "react-remove-scroll": "^2.6.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-slot": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-popper": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.8.tgz",+ "integrity": "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw==",+ "license": "MIT",+ "dependencies": {+ "@floating-ui/react-dom": "^2.0.0",+ "@radix-ui/react-arrow": "1.1.7",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-layout-effect": "1.1.1",+ "@radix-ui/react-use-rect": "1.1.1",+ "@radix-ui/react-use-size": "1.1.1",+ "@radix-ui/rect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-portal": {+ "version": "1.1.9",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.9.tgz",+ "integrity": "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-presence": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.5.tgz",+ "integrity": "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-primitive": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz",+ "integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-slot": "1.2.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-primitive/node_modules/@radix-ui/react-slot": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-progress": {+ "version": "1.1.8",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-progress/-/react-progress-1.1.8.tgz",+ "integrity": "sha512-+gISHcSPUJ7ktBy9RnTqbdKW78bcGke3t6taawyZ71pio1JewwGSJizycs7rLhGTvMJYCQB1DBK4KQsxs7U8dA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-context": "1.1.3",+ "@radix-ui/react-primitive": "2.1.4"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-progress/node_modules/@radix-ui/react-context": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.3.tgz",+ "integrity": "sha512-ieIFACdMpYfMEjF0rEf5KLvfVyIkOz6PDGyNnP+u+4xQ6jny3VCgA4OgXOwNx2aUkxn8zx9fiVcM8CfFYv9Lxw==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-progress/node_modules/@radix-ui/react-primitive": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz",+ "integrity": "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-slot": "1.2.4"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-roving-focus": {+ "version": "1.1.11",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.11.tgz",+ "integrity": "sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-collection": "1.1.7",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-controllable-state": "1.2.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-scroll-area": {+ "version": "1.2.10",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-scroll-area/-/react-scroll-area-1.2.10.tgz",+ "integrity": "sha512-tAXIa1g3sM5CGpVT0uIbUx/U3Gs5N8T52IICuCtObaos1S8fzsrPXG5WObkQN3S6NVl6wKgPhAIiBGbWnvc97A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/number": "1.1.1",+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-select": {+ "version": "2.2.6",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.2.6.tgz",+ "integrity": "sha512-I30RydO+bnn2PQztvo25tswPH+wFBjehVGtmagkU78yMdwTwVf12wnAOF+AeP8S2N8xD+5UPbGhkUfPyvT+mwQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/number": "1.1.1",+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-collection": "1.1.7",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-dismissable-layer": "1.1.11",+ "@radix-ui/react-focus-guards": "1.1.3",+ "@radix-ui/react-focus-scope": "1.1.7",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-popper": "1.2.8",+ "@radix-ui/react-portal": "1.1.9",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-slot": "1.2.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "@radix-ui/react-use-layout-effect": "1.1.1",+ "@radix-ui/react-use-previous": "1.1.1",+ "@radix-ui/react-visually-hidden": "1.2.3",+ "aria-hidden": "^1.2.4",+ "react-remove-scroll": "^2.6.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-slot": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-separator": {+ "version": "1.1.8",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.8.tgz",+ "integrity": "sha512-sDvqVY4itsKwwSMEe0jtKgfTh+72Sy3gPmQpjqcQneqQ4PFmr/1I0YA+2/puilhggCe2gJcx5EBAYFkWkdpa5g==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.4"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-separator/node_modules/@radix-ui/react-primitive": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz",+ "integrity": "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-slot": "1.2.4"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-slider": {+ "version": "1.3.6",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.3.6.tgz",+ "integrity": "sha512-JPYb1GuM1bxfjMRlNLE+BcmBC8onfCi60Blk7OBqi2MLTFdS+8401U4uFjnwkOr49BLmXxLC6JHkvAsx5OJvHw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/number": "1.1.1",+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-collection": "1.1.7",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "@radix-ui/react-use-layout-effect": "1.1.1",+ "@radix-ui/react-use-previous": "1.1.1",+ "@radix-ui/react-use-size": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-slot": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.4.tgz",+ "integrity": "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-switch": {+ "version": "1.2.6",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-switch/-/react-switch-1.2.6.tgz",+ "integrity": "sha512-bByzr1+ep1zk4VubeEVViV592vu2lHE2BZY5OnzehZqOOgogN80+mNtCqPkhn2gklJqOpxWgPoYTSnhBCqpOXQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "@radix-ui/react-use-previous": "1.1.1",+ "@radix-ui/react-use-size": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-tabs": {+ "version": "1.1.13",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.1.13.tgz",+ "integrity": "sha512-7xdcatg7/U+7+Udyoj2zodtI9H/IIopqo+YOIcZOq1nJwXWBZ9p8xiu5llXlekDbZkca79a/fozEYQXIA4sW6A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-roving-focus": "1.1.11",+ "@radix-ui/react-use-controllable-state": "1.2.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-toggle": {+ "version": "1.1.10",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.1.10.tgz",+ "integrity": "sha512-lS1odchhFTeZv3xwHH31YPObmJn8gOg7Lq12inrr0+BH/l3Tsq32VfjqH1oh80ARM3mlkfMic15n0kg4sD1poQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-controllable-state": "1.2.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-toggle-group": {+ "version": "1.1.11",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle-group/-/react-toggle-group-1.1.11.tgz",+ "integrity": "sha512-5umnS0T8JQzQT6HbPyO7Hh9dgd82NmS36DQr+X/YJ9ctFNCiiQd6IJAYYZ33LUwm8M+taCz5t2ui29fHZc4Y6Q==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-roving-focus": "1.1.11",+ "@radix-ui/react-toggle": "1.1.10",+ "@radix-ui/react-use-controllable-state": "1.2.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-tooltip": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.2.8.tgz",+ "integrity": "sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-dismissable-layer": "1.1.11",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-popper": "1.2.8",+ "@radix-ui/react-portal": "1.1.9",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-slot": "1.2.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "@radix-ui/react-visually-hidden": "1.2.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-slot": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-callback-ref": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",+ "integrity": "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-controllable-state": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.2.tgz",+ "integrity": "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-effect-event": "0.0.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-effect-event": {+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.2.tgz",+ "integrity": "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-escape-keydown": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.1.tgz",+ "integrity": "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-callback-ref": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-layout-effect": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",+ "integrity": "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-previous": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-previous/-/react-use-previous-1.1.1.tgz",+ "integrity": "sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-rect": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.1.tgz",+ "integrity": "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/rect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-size": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.1.tgz",+ "integrity": "sha512-ewrXRDTAqAXlkl6t/fkXWNAhFX9I+CkKlw6zjEwk86RSPKwZr3xpBRso655aqYafwtnbpHLj6toFzmd6xdVptQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-visually-hidden": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.3.tgz",+ "integrity": "sha512-pzJq12tEaaIhqjbzpCuv/OypJY/BPavOofm+dbab+MHLajy277+1lLm6JFcGgF5eskJ6mquGirhXY2GD/8u8Ug==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/rect": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.1.tgz",+ "integrity": "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==",+ "license": "MIT"+ },+ "node_modules/@rtsao/scc": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz",+ "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@rushstack/eslint-patch": {+ "version": "1.16.1",+ "resolved": "https://registry.npmjs.org/@rushstack/eslint-patch/-/eslint-patch-1.16.1.tgz",+ "integrity": "sha512-TvZbIpeKqGQQ7X0zSCvPH9riMSFQFSggnfBjFZ1mEoILW+UuXCKwOoPcgjMwiUtRqFZ8jWhPJc4um14vC6I4ag==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@shikijs/core": {+ "version": "1.29.2",+ "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-1.29.2.tgz",+ "integrity": "sha512-vju0lY9r27jJfOY4Z7+Rt/nIOjzJpZ3y+nYpqtUZInVoXQ/TJZcfGnNOGnKjFdVZb8qexiCuSlZRKcGfhhTTZQ==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/engine-javascript": "1.29.2",+ "@shikijs/engine-oniguruma": "1.29.2",+ "@shikijs/types": "1.29.2",+ "@shikijs/vscode-textmate": "^10.0.1",+ "@types/hast": "^3.0.4",+ "hast-util-to-html": "^9.0.4"+ }+ },+ "node_modules/@shikijs/engine-javascript": {+ "version": "1.29.2",+ "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-1.29.2.tgz",+ "integrity": "sha512-iNEZv4IrLYPv64Q6k7EPpOCE/nuvGiKl7zxdq0WFuRPF5PAE9PRo2JGq/d8crLusM59BRemJ4eOqrFrC4wiQ+A==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "1.29.2",+ "@shikijs/vscode-textmate": "^10.0.1",+ "oniguruma-to-es": "^2.2.0"+ }+ },+ "node_modules/@shikijs/engine-oniguruma": {+ "version": "1.29.2",+ "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-1.29.2.tgz",+ "integrity": "sha512-7iiOx3SG8+g1MnlzZVDYiaeHe7Ez2Kf2HrJzdmGwkRisT7r4rak0e655AcM/tF9JG/kg5fMNYlLLKglbN7gBqA==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "1.29.2",+ "@shikijs/vscode-textmate": "^10.0.1"+ }+ },+ "node_modules/@shikijs/langs": {+ "version": "1.29.2",+ "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-1.29.2.tgz",+ "integrity": "sha512-FIBA7N3LZ+223U7cJDUYd5shmciFQlYkFXlkKVaHsCPgfVLiO+e12FmQE6Tf9vuyEsFe3dIl8qGWKXgEHL9wmQ==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "1.29.2"+ }+ },+ "node_modules/@shikijs/themes": {+ "version": "1.29.2",+ "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-1.29.2.tgz",+ "integrity": "sha512-i9TNZlsq4uoyqSbluIcZkmPL9Bfi3djVxRnofUHwvx/h6SRW3cwgBC5SML7vsDcWyukY0eCzVN980rqP6qNl9g==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "1.29.2"+ }+ },+ "node_modules/@shikijs/types": {+ "version": "1.29.2",+ "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-1.29.2.tgz",+ "integrity": "sha512-VJjK0eIijTZf0QSTODEXCqinjBn0joAHQ+aPSBzrv4O2d/QSbsMw+ZeSRx03kV34Hy7NzUvV/7NqfYGRLrASmw==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/vscode-textmate": "^10.0.1",+ "@types/hast": "^3.0.4"+ }+ },+ "node_modules/@shikijs/vscode-textmate": {+ "version": "10.0.2",+ "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz",+ "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==",+ "license": "MIT"+ },+ "node_modules/@standard-schema/spec": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz",+ "integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==",+ "license": "MIT"+ },+ "node_modules/@swc/helpers": {+ "version": "0.5.15",+ "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz",+ "integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==",+ "license": "Apache-2.0",+ "dependencies": {+ "tslib": "^2.8.0"+ }+ },+ "node_modules/@tailwindcss/node": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.2.2.tgz",+ "integrity": "sha512-pXS+wJ2gZpVXqFaUEjojq7jzMpTGf8rU6ipJz5ovJV6PUGmlJ+jvIwGrzdHdQ80Sg+wmQxUFuoW1UAAwHNEdFA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/remapping": "^2.3.5",+ "enhanced-resolve": "^5.19.0",+ "jiti": "^2.6.1",+ "lightningcss": "1.32.0",+ "magic-string": "^0.30.21",+ "source-map-js": "^1.2.1",+ "tailwindcss": "4.2.2"+ }+ },+ "node_modules/@tailwindcss/oxide": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.2.2.tgz",+ "integrity": "sha512-qEUA07+E5kehxYp9BVMpq9E8vnJuBHfJEC0vPC5e7iL/hw7HR61aDKoVoKzrG+QKp56vhNZe4qwkRmMC0zDLvg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 20"+ },+ "optionalDependencies": {+ "@tailwindcss/oxide-android-arm64": "4.2.2",+ "@tailwindcss/oxide-darwin-arm64": "4.2.2",+ "@tailwindcss/oxide-darwin-x64": "4.2.2",+ "@tailwindcss/oxide-freebsd-x64": "4.2.2",+ "@tailwindcss/oxide-linux-arm-gnueabihf": "4.2.2",+ "@tailwindcss/oxide-linux-arm64-gnu": "4.2.2",+ "@tailwindcss/oxide-linux-arm64-musl": "4.2.2",+ "@tailwindcss/oxide-linux-x64-gnu": "4.2.2",+ "@tailwindcss/oxide-linux-x64-musl": "4.2.2",+ "@tailwindcss/oxide-wasm32-wasi": "4.2.2",+ "@tailwindcss/oxide-win32-arm64-msvc": "4.2.2",+ "@tailwindcss/oxide-win32-x64-msvc": "4.2.2"+ }+ },+ "node_modules/@tailwindcss/oxide-android-arm64": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.2.2.tgz",+ "integrity": "sha512-dXGR1n+P3B6748jZO/SvHZq7qBOqqzQ+yFrXpoOWWALWndF9MoSKAT3Q0fYgAzYzGhxNYOoysRvYlpixRBBoDg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-darwin-arm64": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.2.2.tgz",+ "integrity": "sha512-iq9Qjr6knfMpZHj55/37ouZeykwbDqF21gPFtfnhCCKGDcPI/21FKC9XdMO/XyBM7qKORx6UIhGgg6jLl7BZlg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-darwin-x64": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.2.2.tgz",+ "integrity": "sha512-BlR+2c3nzc8f2G639LpL89YY4bdcIdUmiOOkv2GQv4/4M0vJlpXEa0JXNHhCHU7VWOKWT/CjqHdTP8aUuDJkuw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-freebsd-x64": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.2.2.tgz",+ "integrity": "sha512-YUqUgrGMSu2CDO82hzlQ5qSb5xmx3RUrke/QgnoEx7KvmRJHQuZHZmZTLSuuHwFf0DJPybFMXMYf+WJdxHy/nQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.2.2.tgz",+ "integrity": "sha512-FPdhvsW6g06T9BWT0qTwiVZYE2WIFo2dY5aCSpjG/S/u1tby+wXoslXS0kl3/KXnULlLr1E3NPRRw0g7t2kgaQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-arm64-gnu": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.2.2.tgz",+ "integrity": "sha512-4og1V+ftEPXGttOO7eCmW7VICmzzJWgMx+QXAJRAhjrSjumCwWqMfkDrNu1LXEQzNAwz28NCUpucgQPrR4S2yw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-arm64-musl": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.2.2.tgz",+ "integrity": "sha512-oCfG/mS+/+XRlwNjnsNLVwnMWYH7tn/kYPsNPh+JSOMlnt93mYNCKHYzylRhI51X+TbR+ufNhhKKzm6QkqX8ag==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-x64-gnu": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.2.2.tgz",+ "integrity": "sha512-rTAGAkDgqbXHNp/xW0iugLVmX62wOp2PoE39BTCGKjv3Iocf6AFbRP/wZT/kuCxC9QBh9Pu8XPkv/zCZB2mcMg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-linux-x64-musl": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.2.2.tgz",+ "integrity": "sha512-XW3t3qwbIwiSyRCggeO2zxe3KWaEbM0/kW9e8+0XpBgyKU4ATYzcVSMKteZJ1iukJ3HgHBjbg9P5YPRCVUxlnQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-wasm32-wasi": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.2.2.tgz",+ "integrity": "sha512-eKSztKsmEsn1O5lJ4ZAfyn41NfG7vzCg496YiGtMDV86jz1q/irhms5O0VrY6ZwTUkFy/EKG3RfWgxSI3VbZ8Q==",+ "bundleDependencies": [+ "@napi-rs/wasm-runtime",+ "@emnapi/core",+ "@emnapi/runtime",+ "@tybys/wasm-util",+ "@emnapi/wasi-threads",+ "tslib"+ ],+ "cpu": [+ "wasm32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/core": "^1.8.1",+ "@emnapi/runtime": "^1.8.1",+ "@emnapi/wasi-threads": "^1.1.0",+ "@napi-rs/wasm-runtime": "^1.1.1",+ "@tybys/wasm-util": "^0.10.1",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/@tailwindcss/oxide-win32-arm64-msvc": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.2.2.tgz",+ "integrity": "sha512-qPmaQM4iKu5mxpsrWZMOZRgZv1tOZpUm+zdhhQP0VhJfyGGO3aUKdbh3gDZc/dPLQwW4eSqWGrrcWNBZWUWaXQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/oxide-win32-x64-msvc": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.2.2.tgz",+ "integrity": "sha512-1T/37VvI7WyH66b+vqHj/cLwnCxt7Qt3WFu5Q8hk65aOvlwAhs7rAp1VkulBJw/N4tMirXjVnylTR72uI0HGcA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/postcss": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.2.2.tgz",+ "integrity": "sha512-n4goKQbW8RVXIbNKRB/45LzyUqN451deQK0nzIeauVEqjlI49slUlgKYJM2QyUzap/PcpnS7kzSUmPb1sCRvYQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@alloc/quick-lru": "^5.2.0",+ "@tailwindcss/node": "4.2.2",+ "@tailwindcss/oxide": "4.2.2",+ "postcss": "^8.5.6",+ "tailwindcss": "4.2.2"+ }+ },+ "node_modules/@tailwindcss/typography": {+ "version": "0.5.19",+ "resolved": "https://registry.npmjs.org/@tailwindcss/typography/-/typography-0.5.19.tgz",+ "integrity": "sha512-w31dd8HOx3k9vPtcQh5QHP9GwKcgbMp87j58qi6xgiBnFFtKEAgCWnDw4qUT8aHwkCp8bKvb/KGKWWHedP0AAg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "postcss-selector-parser": "6.0.10"+ },+ "peerDependencies": {+ "tailwindcss": ">=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1"+ }+ },+ "node_modules/@tybys/wasm-util": {+ "version": "0.10.1",+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz",+ "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@types/d3": {+ "version": "7.4.3",+ "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz",+ "integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-array": "*",+ "@types/d3-axis": "*",+ "@types/d3-brush": "*",+ "@types/d3-chord": "*",+ "@types/d3-color": "*",+ "@types/d3-contour": "*",+ "@types/d3-delaunay": "*",+ "@types/d3-dispatch": "*",+ "@types/d3-drag": "*",+ "@types/d3-dsv": "*",+ "@types/d3-ease": "*",+ "@types/d3-fetch": "*",+ "@types/d3-force": "*",+ "@types/d3-format": "*",+ "@types/d3-geo": "*",+ "@types/d3-hierarchy": "*",+ "@types/d3-interpolate": "*",+ "@types/d3-path": "*",+ "@types/d3-polygon": "*",+ "@types/d3-quadtree": "*",+ "@types/d3-random": "*",+ "@types/d3-scale": "*",+ "@types/d3-scale-chromatic": "*",+ "@types/d3-selection": "*",+ "@types/d3-shape": "*",+ "@types/d3-time": "*",+ "@types/d3-time-format": "*",+ "@types/d3-timer": "*",+ "@types/d3-transition": "*",+ "@types/d3-zoom": "*"+ }+ },+ "node_modules/@types/d3-array": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",+ "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",+ "license": "MIT"+ },+ "node_modules/@types/d3-axis": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz",+ "integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-brush": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz",+ "integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-chord": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz",+ "integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-color": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",+ "license": "MIT"+ },+ "node_modules/@types/d3-contour": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz",+ "integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-array": "*",+ "@types/geojson": "*"+ }+ },+ "node_modules/@types/d3-delaunay": {+ "version": "6.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.4.tgz",+ "integrity": "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==",+ "license": "MIT"+ },+ "node_modules/@types/d3-dispatch": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.7.tgz",+ "integrity": "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==",+ "license": "MIT"+ },+ "node_modules/@types/d3-drag": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",+ "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-dsv": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz",+ "integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==",+ "license": "MIT"+ },+ "node_modules/@types/d3-ease": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",+ "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",+ "license": "MIT"+ },+ "node_modules/@types/d3-fetch": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz",+ "integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-dsv": "*"+ }+ },+ "node_modules/@types/d3-force": {+ "version": "3.0.10",+ "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",+ "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",+ "license": "MIT"+ },+ "node_modules/@types/d3-format": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz",+ "integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==",+ "license": "MIT"+ },+ "node_modules/@types/d3-geo": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz",+ "integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==",+ "license": "MIT",+ "dependencies": {+ "@types/geojson": "*"+ }+ },+ "node_modules/@types/d3-hierarchy": {+ "version": "3.1.7",+ "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz",+ "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-interpolate": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-color": "*"+ }+ },+ "node_modules/@types/d3-path": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",+ "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-polygon": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz",+ "integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==",+ "license": "MIT"+ },+ "node_modules/@types/d3-quadtree": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz",+ "integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-random": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.3.tgz",+ "integrity": "sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==",+ "license": "MIT"+ },+ "node_modules/@types/d3-scale": {+ "version": "4.0.9",+ "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",+ "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-time": "*"+ }+ },+ "node_modules/@types/d3-scale-chromatic": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",+ "integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==",+ "license": "MIT"+ },+ "node_modules/@types/d3-selection": {+ "version": "3.0.11",+ "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",+ "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",+ "license": "MIT"+ },+ "node_modules/@types/d3-shape": {+ "version": "3.1.8",+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",+ "integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-path": "*"+ }+ },+ "node_modules/@types/d3-time": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",+ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",+ "license": "MIT"+ },+ "node_modules/@types/d3-time-format": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-4.0.3.tgz",+ "integrity": "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-timer": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",+ "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",+ "license": "MIT"+ },+ "node_modules/@types/d3-transition": {+ "version": "3.0.9",+ "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",+ "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-zoom": {+ "version": "3.0.8",+ "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",+ "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-interpolate": "*",+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/debug": {+ "version": "4.1.13",+ "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",+ "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==",+ "license": "MIT",+ "dependencies": {+ "@types/ms": "*"+ }+ },+ "node_modules/@types/estree": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",+ "license": "MIT"+ },+ "node_modules/@types/estree-jsx": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz",+ "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "*"+ }+ },+ "node_modules/@types/geojson": {+ "version": "7946.0.16",+ "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",+ "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",+ "license": "MIT"+ },+ "node_modules/@types/hast": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz",+ "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "*"+ }+ },+ "node_modules/@types/json-schema": {+ "version": "7.0.15",+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",+ "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/json5": {+ "version": "0.0.29",+ "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz",+ "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/mdast": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",+ "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "*"+ }+ },+ "node_modules/@types/mdx": {+ "version": "2.0.13",+ "resolved": "https://registry.npmjs.org/@types/mdx/-/mdx-2.0.13.tgz",+ "integrity": "sha512-+OWZQfAYyio6YkJb3HLxDrvnx6SWWDbC0zVPfBRzUk0/nqoDyf6dNxQi3eArPe8rJ473nobTMQ/8Zk+LxJ+Yuw==",+ "license": "MIT"+ },+ "node_modules/@types/ms": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "22.19.15",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz",+ "integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/@types/react": {+ "version": "19.2.14",+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",+ "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",+ "license": "MIT",+ "dependencies": {+ "csstype": "^3.2.2"+ }+ },+ "node_modules/@types/react-dom": {+ "version": "19.2.3",+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",+ "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",+ "devOptional": true,+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "^19.2.0"+ }+ },+ "node_modules/@types/trusted-types": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",+ "license": "MIT",+ "optional": true+ },+ "node_modules/@types/unist": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",+ "license": "MIT"+ },+ "node_modules/@typescript-eslint/eslint-plugin": {+ "version": "8.57.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.57.1.tgz",+ "integrity": "sha512-Gn3aqnvNl4NGc6x3/Bqk1AOn0thyTU9bqDRhiRnUWezgvr2OnhYCWCgC8zXXRVqBsIL1pSDt7T9nJUe0oM0kDQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@eslint-community/regexpp": "^4.12.2",+ "@typescript-eslint/scope-manager": "8.57.1",+ "@typescript-eslint/type-utils": "8.57.1",+ "@typescript-eslint/utils": "8.57.1",+ "@typescript-eslint/visitor-keys": "8.57.1",+ "ignore": "^7.0.5",+ "natural-compare": "^1.4.0",+ "ts-api-utils": "^2.4.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "@typescript-eslint/parser": "^8.57.1",+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.0.0"+ }+ },+ "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {+ "version": "7.0.5",+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",+ "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/@typescript-eslint/parser": {+ "version": "8.57.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.57.1.tgz",+ "integrity": "sha512-k4eNDan0EIMTT/dUKc/g+rsJ6wcHYhNPdY19VoX/EOtaAG8DLtKCykhrUnuHPYvinn5jhAPgD2Qw9hXBwrahsw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/scope-manager": "8.57.1",+ "@typescript-eslint/types": "8.57.1",+ "@typescript-eslint/typescript-estree": "8.57.1",+ "@typescript-eslint/visitor-keys": "8.57.1",+ "debug": "^4.4.3"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.0.0"+ }+ },+ "node_modules/@typescript-eslint/project-service": {+ "version": "8.57.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.57.1.tgz",+ "integrity": "sha512-vx1F37BRO1OftsYlmG9xay1TqnjNVlqALymwWVuYTdo18XuKxtBpCj1QlzNIEHlvlB27osvXFWptYiEWsVdYsg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/tsconfig-utils": "^8.57.1",+ "@typescript-eslint/types": "^8.57.1",+ "debug": "^4.4.3"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.0.0"+ }+ },+ "node_modules/@typescript-eslint/scope-manager": {+ "version": "8.57.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.57.1.tgz",+ "integrity": "sha512-hs/QcpCwlwT2L5S+3fT6gp0PabyGk4Q0Rv2doJXA0435/OpnSR3VRgvrp8Xdoc3UAYSg9cyUjTeFXZEPg/3OKg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.57.1",+ "@typescript-eslint/visitor-keys": "8.57.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@typescript-eslint/tsconfig-utils": {+ "version": "8.57.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.57.1.tgz",+ "integrity": "sha512-0lgOZB8cl19fHO4eI46YUx2EceQqhgkPSuCGLlGi79L2jwYY1cxeYc1Nae8Aw1xjgW3PKVDLlr3YJ6Bxx8HkWg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.0.0"+ }+ },+ "node_modules/@typescript-eslint/type-utils": {+ "version": "8.57.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.57.1.tgz",+ "integrity": "sha512-+Bwwm0ScukFdyoJsh2u6pp4S9ktegF98pYUU0hkphOOqdMB+1sNQhIz8y5E9+4pOioZijrkfNO/HUJVAFFfPKA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.57.1",+ "@typescript-eslint/typescript-estree": "8.57.1",+ "@typescript-eslint/utils": "8.57.1",+ "debug": "^4.4.3",+ "ts-api-utils": "^2.4.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.0.0"+ }+ },+ "node_modules/@typescript-eslint/types": {+ "version": "8.57.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.57.1.tgz",+ "integrity": "sha512-S29BOBPJSFUiblEl6RzPPjJt6w25A6XsBqRVDt53tA/tlL8q7ceQNZHTjPeONt/3S7KRI4quk+yP9jK2WjBiPQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree": {+ "version": "8.57.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.57.1.tgz",+ "integrity": "sha512-ybe2hS9G6pXpqGtPli9Gx9quNV0TWLOmh58ADlmZe9DguLq0tiAKVjirSbtM1szG6+QH6rVXyU6GTLQbWnMY+g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/project-service": "8.57.1",+ "@typescript-eslint/tsconfig-utils": "8.57.1",+ "@typescript-eslint/types": "8.57.1",+ "@typescript-eslint/visitor-keys": "8.57.1",+ "debug": "^4.4.3",+ "minimatch": "^10.2.2",+ "semver": "^7.7.3",+ "tinyglobby": "^0.2.15",+ "ts-api-utils": "^2.4.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.0.0"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "18 || 20 || >=22"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.4.tgz",+ "integrity": "sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^4.0.2"+ },+ "engines": {+ "node": "18 || 20 || >=22"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {+ "version": "10.2.4",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz",+ "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "dependencies": {+ "brace-expansion": "^5.0.2"+ },+ "engines": {+ "node": "18 || 20 || >=22"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/@typescript-eslint/utils": {+ "version": "8.57.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.57.1.tgz",+ "integrity": "sha512-XUNSJ/lEVFttPMMoDVA2r2bwrl8/oPx8cURtczkSEswY5T3AeLmCy+EKWQNdL4u0MmAHOjcWrqJp2cdvgjn8dQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@eslint-community/eslint-utils": "^4.9.1",+ "@typescript-eslint/scope-manager": "8.57.1",+ "@typescript-eslint/types": "8.57.1",+ "@typescript-eslint/typescript-estree": "8.57.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.0.0"+ }+ },+ "node_modules/@typescript-eslint/visitor-keys": {+ "version": "8.57.1",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.57.1.tgz",+ "integrity": "sha512-YWnmJkXbofiz9KbnbbwuA2rpGkFPLbAIetcCNO6mJ8gdhdZ/v7WDXsoGFAJuM6ikUFKTlSQnjWnVO4ux+UzS6A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.57.1",+ "eslint-visitor-keys": "^5.0.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz",+ "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@ungap/structured-clone": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",+ "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==",+ "license": "ISC"+ },+ "node_modules/@unrs/resolver-binding-android-arm-eabi": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.11.1.tgz",+ "integrity": "sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@unrs/resolver-binding-android-arm64": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.11.1.tgz",+ "integrity": "sha512-lCxkVtb4wp1v+EoN+HjIG9cIIzPkX5OtM03pQYkG+U5O/wL53LC4QbIeazgiKqluGeVEeBlZahHalCaBvU1a2g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@unrs/resolver-binding-darwin-arm64": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.11.1.tgz",+ "integrity": "sha512-gPVA1UjRu1Y/IsB/dQEsp2V1pm44Of6+LWvbLc9SDk1c2KhhDRDBUkQCYVWe6f26uJb3fOK8saWMgtX8IrMk3g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@unrs/resolver-binding-darwin-x64": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.11.1.tgz",+ "integrity": "sha512-cFzP7rWKd3lZaCsDze07QX1SC24lO8mPty9vdP+YVa3MGdVgPmFc59317b2ioXtgCMKGiCLxJ4HQs62oz6GfRQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@unrs/resolver-binding-freebsd-x64": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.11.1.tgz",+ "integrity": "sha512-fqtGgak3zX4DCB6PFpsH5+Kmt/8CIi4Bry4rb1ho6Av2QHTREM+47y282Uqiu3ZRF5IQioJQ5qWRV6jduA+iGw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.11.1.tgz",+ "integrity": "sha512-u92mvlcYtp9MRKmP+ZvMmtPN34+/3lMHlyMj7wXJDeXxuM0Vgzz0+PPJNsro1m3IZPYChIkn944wW8TYgGKFHw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-arm-musleabihf": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.11.1.tgz",+ "integrity": "sha512-cINaoY2z7LVCrfHkIcmvj7osTOtm6VVT16b5oQdS4beibX2SYBwgYLmqhBjA1t51CarSaBuX5YNsWLjsqfW5Cw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-arm64-gnu": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.11.1.tgz",+ "integrity": "sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-arm64-musl": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.11.1.tgz",+ "integrity": "sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-ppc64-gnu": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.11.1.tgz",+ "integrity": "sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-riscv64-gnu": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.11.1.tgz",+ "integrity": "sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-riscv64-musl": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.11.1.tgz",+ "integrity": "sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-s390x-gnu": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.11.1.tgz",+ "integrity": "sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-x64-gnu": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.11.1.tgz",+ "integrity": "sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-linux-x64-musl": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.11.1.tgz",+ "integrity": "sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@unrs/resolver-binding-wasm32-wasi": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.11.1.tgz",+ "integrity": "sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==",+ "cpu": [+ "wasm32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@napi-rs/wasm-runtime": "^0.2.11"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/@unrs/resolver-binding-win32-arm64-msvc": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.11.1.tgz",+ "integrity": "sha512-nRcz5Il4ln0kMhfL8S3hLkxI85BXs3o8EYoattsJNdsX4YUU89iOkVn7g0VHSRxFuVMdM4Q1jEpIId1Ihim/Uw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@unrs/resolver-binding-win32-ia32-msvc": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.11.1.tgz",+ "integrity": "sha512-DCEI6t5i1NmAZp6pFonpD5m7i6aFrpofcp4LA2i8IIq60Jyo28hamKBxNrZcyOwVOZkgsRp9O2sXWBWP8MnvIQ==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@unrs/resolver-binding-win32-x64-msvc": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.11.1.tgz",+ "integrity": "sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@upsetjs/venn.js": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/@upsetjs/venn.js/-/venn.js-2.0.0.tgz",+ "integrity": "sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==",+ "license": "MIT",+ "optionalDependencies": {+ "d3-selection": "^3.0.0",+ "d3-transition": "^3.0.1"+ }+ },+ "node_modules/acorn": {+ "version": "8.16.0",+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",+ "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",+ "license": "MIT",+ "bin": {+ "acorn": "bin/acorn"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/acorn-jsx": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",+ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",+ "license": "MIT",+ "peerDependencies": {+ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"+ }+ },+ "node_modules/ajv": {+ "version": "6.14.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",+ "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.1",+ "fast-json-stable-stringify": "^2.0.0",+ "json-schema-traverse": "^0.4.1",+ "uri-js": "^4.2.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ansi-styles": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "color-convert": "^2.0.1"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/argparse": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",+ "dev": true,+ "license": "Python-2.0"+ },+ "node_modules/aria-hidden": {+ "version": "1.2.6",+ "resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.6.tgz",+ "integrity": "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/aria-query": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz",+ "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/array-buffer-byte-length": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz",+ "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "is-array-buffer": "^3.0.5"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array-includes": {+ "version": "3.1.9",+ "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.9.tgz",+ "integrity": "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.4",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.24.0",+ "es-object-atoms": "^1.1.1",+ "get-intrinsic": "^1.3.0",+ "is-string": "^1.1.1",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array.prototype.findlast": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz",+ "integrity": "sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.2",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.0.0",+ "es-shim-unscopables": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array.prototype.findlastindex": {+ "version": "1.2.6",+ "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz",+ "integrity": "sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.4",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.9",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "es-shim-unscopables": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array.prototype.flat": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.3.tgz",+ "integrity": "sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.5",+ "es-shim-unscopables": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array.prototype.flatmap": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.3.tgz",+ "integrity": "sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.5",+ "es-shim-unscopables": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/array.prototype.tosorted": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/array.prototype.tosorted/-/array.prototype.tosorted-1.1.4.tgz",+ "integrity": "sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.3",+ "es-errors": "^1.3.0",+ "es-shim-unscopables": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/arraybuffer.prototype.slice": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz",+ "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "array-buffer-byte-length": "^1.0.1",+ "call-bind": "^1.0.8",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.5",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "is-array-buffer": "^3.0.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/ast-types-flow": {+ "version": "0.0.8",+ "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz",+ "integrity": "sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/astring": {+ "version": "1.9.0",+ "resolved": "https://registry.npmjs.org/astring/-/astring-1.9.0.tgz",+ "integrity": "sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg==",+ "license": "MIT",+ "bin": {+ "astring": "bin/astring"+ }+ },+ "node_modules/async-function": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz",+ "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/available-typed-arrays": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",+ "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "possible-typed-array-names": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/axe-core": {+ "version": "4.11.1",+ "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.11.1.tgz",+ "integrity": "sha512-BASOg+YwO2C+346x3LZOeoovTIoTrRqEsqMa6fmfAV0P+U9mFr9NsyOEpiYvFjbc64NMrSswhV50WdXzdb/Z5A==",+ "dev": true,+ "license": "MPL-2.0",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/axobject-query": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",+ "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/bail": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz",+ "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/balanced-match": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/brace-expansion": {+ "version": "1.1.12",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",+ "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/braces": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",+ "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fill-range": "^7.1.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/call-bind": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz",+ "integrity": "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.0",+ "es-define-property": "^1.0.0",+ "get-intrinsic": "^1.2.4",+ "set-function-length": "^1.2.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/callsites": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",+ "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/caniuse-lite": {+ "version": "1.0.30001780",+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001780.tgz",+ "integrity": "sha512-llngX0E7nQci5BPJDqoZSbuZ5Bcs9F5db7EtgfwBerX9XGtkkiO4NwfDDIRzHTTwcYC8vC7bmeUEPGrKlR/TkQ==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "CC-BY-4.0"+ },+ "node_modules/ccount": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",+ "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/chalk": {+ "version": "4.1.2",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^4.1.0",+ "supports-color": "^7.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/chalk?sponsor=1"+ }+ },+ "node_modules/character-entities": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",+ "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-entities-html4": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz",+ "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-entities-legacy": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",+ "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-reference-invalid": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",+ "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/chevrotain": {+ "version": "11.1.2",+ "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-11.1.2.tgz",+ "integrity": "sha512-opLQzEVriiH1uUQ4Kctsd49bRoFDXGGSC4GUqj7pGyxM3RehRhvTlZJc1FL/Flew2p5uwxa1tUDWKzI4wNM8pg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@chevrotain/cst-dts-gen": "11.1.2",+ "@chevrotain/gast": "11.1.2",+ "@chevrotain/regexp-to-ast": "11.1.2",+ "@chevrotain/types": "11.1.2",+ "@chevrotain/utils": "11.1.2",+ "lodash-es": "4.17.23"+ }+ },+ "node_modules/chevrotain-allstar": {+ "version": "0.3.1",+ "resolved": "https://registry.npmjs.org/chevrotain-allstar/-/chevrotain-allstar-0.3.1.tgz",+ "integrity": "sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==",+ "license": "MIT",+ "dependencies": {+ "lodash-es": "^4.17.21"+ },+ "peerDependencies": {+ "chevrotain": "^11.0.0"+ }+ },+ "node_modules/class-variance-authority": {+ "version": "0.7.1",+ "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz",+ "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==",+ "license": "Apache-2.0",+ "dependencies": {+ "clsx": "^2.1.1"+ },+ "funding": {+ "url": "https://polar.sh/cva"+ }+ },+ "node_modules/client-only": {+ "version": "0.0.1",+ "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",+ "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",+ "license": "MIT"+ },+ "node_modules/clsx": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",+ "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/cmdk": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/cmdk/-/cmdk-1.1.1.tgz",+ "integrity": "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "^1.1.1",+ "@radix-ui/react-dialog": "^1.1.6",+ "@radix-ui/react-id": "^1.1.0",+ "@radix-ui/react-primitive": "^2.0.2"+ },+ "peerDependencies": {+ "react": "^18 || ^19 || ^19.0.0-rc",+ "react-dom": "^18 || ^19 || ^19.0.0-rc"+ }+ },+ "node_modules/collapse-white-space": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/collapse-white-space/-/collapse-white-space-2.1.0.tgz",+ "integrity": "sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/color-convert": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "color-name": "~1.1.4"+ },+ "engines": {+ "node": ">=7.0.0"+ }+ },+ "node_modules/color-name": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/comma-separated-tokens": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",+ "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/commander": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",+ "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",+ "license": "MIT",+ "engines": {+ "node": ">= 10"+ }+ },+ "node_modules/concat-map": {+ "version": "0.0.1",+ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",+ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/confbox": {+ "version": "0.1.8",+ "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz",+ "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==",+ "license": "MIT"+ },+ "node_modules/cose-base": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-1.0.3.tgz",+ "integrity": "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==",+ "license": "MIT",+ "dependencies": {+ "layout-base": "^1.0.0"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/cssesc": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",+ "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "cssesc": "bin/cssesc"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/csstype": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",+ "license": "MIT"+ },+ "node_modules/cytoscape": {+ "version": "3.33.1",+ "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.33.1.tgz",+ "integrity": "sha512-iJc4TwyANnOGR1OmWhsS9ayRS3s+XQ185FmuHObThD+5AeJCakAAbWv8KimMTt08xCCLNgneQwFp+JRJOr9qGQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/cytoscape-cose-bilkent": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/cytoscape-cose-bilkent/-/cytoscape-cose-bilkent-4.1.0.tgz",+ "integrity": "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==",+ "license": "MIT",+ "dependencies": {+ "cose-base": "^1.0.0"+ },+ "peerDependencies": {+ "cytoscape": "^3.2.0"+ }+ },+ "node_modules/cytoscape-fcose": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/cytoscape-fcose/-/cytoscape-fcose-2.2.0.tgz",+ "integrity": "sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==",+ "license": "MIT",+ "dependencies": {+ "cose-base": "^2.2.0"+ },+ "peerDependencies": {+ "cytoscape": "^3.2.0"+ }+ },+ "node_modules/cytoscape-fcose/node_modules/cose-base": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-2.2.0.tgz",+ "integrity": "sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==",+ "license": "MIT",+ "dependencies": {+ "layout-base": "^2.0.0"+ }+ },+ "node_modules/cytoscape-fcose/node_modules/layout-base": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-2.0.1.tgz",+ "integrity": "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==",+ "license": "MIT"+ },+ "node_modules/d3": {+ "version": "7.9.0",+ "resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz",+ "integrity": "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "3",+ "d3-axis": "3",+ "d3-brush": "3",+ "d3-chord": "3",+ "d3-color": "3",+ "d3-contour": "4",+ "d3-delaunay": "6",+ "d3-dispatch": "3",+ "d3-drag": "3",+ "d3-dsv": "3",+ "d3-ease": "3",+ "d3-fetch": "3",+ "d3-force": "3",+ "d3-format": "3",+ "d3-geo": "3",+ "d3-hierarchy": "3",+ "d3-interpolate": "3",+ "d3-path": "3",+ "d3-polygon": "3",+ "d3-quadtree": "3",+ "d3-random": "3",+ "d3-scale": "4",+ "d3-scale-chromatic": "3",+ "d3-selection": "3",+ "d3-shape": "3",+ "d3-time": "3",+ "d3-time-format": "4",+ "d3-timer": "3",+ "d3-transition": "3",+ "d3-zoom": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-array": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",+ "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",+ "license": "ISC",+ "dependencies": {+ "internmap": "1 - 2"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-axis": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.0.tgz",+ "integrity": "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-brush": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz",+ "integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-drag": "2 - 3",+ "d3-interpolate": "1 - 3",+ "d3-selection": "3",+ "d3-transition": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-chord": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.1.tgz",+ "integrity": "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==",+ "license": "ISC",+ "dependencies": {+ "d3-path": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-color": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-contour": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz",+ "integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "^3.2.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-delaunay": {+ "version": "6.0.4",+ "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz",+ "integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==",+ "license": "ISC",+ "dependencies": {+ "delaunator": "5"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-dispatch": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-drag": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",+ "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-selection": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-dsv": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz",+ "integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==",+ "license": "ISC",+ "dependencies": {+ "commander": "7",+ "iconv-lite": "0.6",+ "rw": "1"+ },+ "bin": {+ "csv2json": "bin/dsv2json.js",+ "csv2tsv": "bin/dsv2dsv.js",+ "dsv2dsv": "bin/dsv2dsv.js",+ "dsv2json": "bin/dsv2json.js",+ "json2csv": "bin/json2dsv.js",+ "json2dsv": "bin/json2dsv.js",+ "json2tsv": "bin/json2dsv.js",+ "tsv2csv": "bin/dsv2dsv.js",+ "tsv2json": "bin/dsv2json.js"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-ease": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-fetch": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.1.tgz",+ "integrity": "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==",+ "license": "ISC",+ "dependencies": {+ "d3-dsv": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-force": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",+ "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-quadtree": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-format": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",+ "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-geo": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz",+ "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2.5.0 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-hierarchy": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz",+ "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-interpolate": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-path": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",+ "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-polygon": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.1.tgz",+ "integrity": "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-quadtree": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",+ "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-random": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz",+ "integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-sankey": {+ "version": "0.12.3",+ "resolved": "https://registry.npmjs.org/d3-sankey/-/d3-sankey-0.12.3.tgz",+ "integrity": "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "d3-array": "1 - 2",+ "d3-shape": "^1.2.0"+ }+ },+ "node_modules/d3-sankey/node_modules/d3-array": {+ "version": "2.12.1",+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-2.12.1.tgz",+ "integrity": "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "internmap": "^1.0.0"+ }+ },+ "node_modules/d3-sankey/node_modules/d3-path": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz",+ "integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==",+ "license": "BSD-3-Clause"+ },+ "node_modules/d3-sankey/node_modules/d3-shape": {+ "version": "1.3.7",+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz",+ "integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "d3-path": "1"+ }+ },+ "node_modules/d3-sankey/node_modules/internmap": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-1.0.1.tgz",+ "integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==",+ "license": "ISC"+ },+ "node_modules/d3-scale": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",+ "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2.10.0 - 3",+ "d3-format": "1 - 3",+ "d3-interpolate": "1.2.0 - 3",+ "d3-time": "2.1.1 - 3",+ "d3-time-format": "2 - 4"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-scale-chromatic": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",+ "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3",+ "d3-interpolate": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-selection": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",+ "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-shape": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",+ "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",+ "license": "ISC",+ "dependencies": {+ "d3-path": "^3.1.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-time": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",+ "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-time-format": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",+ "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",+ "license": "ISC",+ "dependencies": {+ "d3-time": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-timer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-transition": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",+ "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3",+ "d3-dispatch": "1 - 3",+ "d3-ease": "1 - 3",+ "d3-interpolate": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ },+ "peerDependencies": {+ "d3-selection": "2 - 3"+ }+ },+ "node_modules/d3-zoom": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",+ "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-drag": "2 - 3",+ "d3-interpolate": "1 - 3",+ "d3-selection": "2 - 3",+ "d3-transition": "2 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/dagre-d3-es": {+ "version": "7.0.14",+ "resolved": "https://registry.npmjs.org/dagre-d3-es/-/dagre-d3-es-7.0.14.tgz",+ "integrity": "sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg==",+ "license": "MIT",+ "dependencies": {+ "d3": "^7.9.0",+ "lodash-es": "^4.17.21"+ }+ },+ "node_modules/damerau-levenshtein": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz",+ "integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==",+ "dev": true,+ "license": "BSD-2-Clause"+ },+ "node_modules/data-view-buffer": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",+ "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "es-errors": "^1.3.0",+ "is-data-view": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/data-view-byte-length": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz",+ "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "es-errors": "^1.3.0",+ "is-data-view": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/inspect-js"+ }+ },+ "node_modules/data-view-byte-offset": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz",+ "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "is-data-view": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/dayjs": {+ "version": "1.11.20",+ "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.20.tgz",+ "integrity": "sha512-YbwwqR/uYpeoP4pu043q+LTDLFBLApUP6VxRihdfNTqu4ubqMlGDLd6ErXhEgsyvY0K6nCs7nggYumAN+9uEuQ==",+ "license": "MIT"+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/decimal.js-light": {+ "version": "2.5.1",+ "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",+ "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",+ "license": "MIT"+ },+ "node_modules/decode-named-character-reference": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",+ "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==",+ "license": "MIT",+ "dependencies": {+ "character-entities": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/deep-is": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",+ "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/define-data-property": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",+ "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-define-property": "^1.0.0",+ "es-errors": "^1.3.0",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/define-properties": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",+ "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-data-property": "^1.0.1",+ "has-property-descriptors": "^1.0.0",+ "object-keys": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/delaunator": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.0.1.tgz",+ "integrity": "sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw==",+ "license": "ISC",+ "dependencies": {+ "robust-predicates": "^3.0.2"+ }+ },+ "node_modules/dequal": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "devOptional": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/detect-node-es": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz",+ "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==",+ "license": "MIT"+ },+ "node_modules/devlop": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz",+ "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",+ "license": "MIT",+ "dependencies": {+ "dequal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/doctrine": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz",+ "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "esutils": "^2.0.2"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/dom-helpers": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",+ "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.8.7",+ "csstype": "^3.0.2"+ }+ },+ "node_modules/dompurify": {+ "version": "3.3.3",+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.3.tgz",+ "integrity": "sha512-Oj6pzI2+RqBfFG+qOaOLbFXLQ90ARpcGG6UePL82bJLtdsa6CYJD7nmiU8MW9nQNOtCHV3lZ/Bzq1X0QYbBZCA==",+ "license": "(MPL-2.0 OR Apache-2.0)",+ "optionalDependencies": {+ "@types/trusted-types": "^2.0.7"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/emoji-regex": {+ "version": "9.2.2",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",+ "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/emoji-regex-xs": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/emoji-regex-xs/-/emoji-regex-xs-1.0.0.tgz",+ "integrity": "sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==",+ "license": "MIT"+ },+ "node_modules/enhanced-resolve": {+ "version": "5.20.1",+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.20.1.tgz",+ "integrity": "sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.4",+ "tapable": "^2.3.0"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/es-abstract": {+ "version": "1.24.1",+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.1.tgz",+ "integrity": "sha512-zHXBLhP+QehSSbsS9Pt23Gg964240DPd6QCf8WpkqEXxQ7fhdZzYsocOr5u7apWonsS5EjZDmTF+/slGMyasvw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "array-buffer-byte-length": "^1.0.2",+ "arraybuffer.prototype.slice": "^1.0.4",+ "available-typed-arrays": "^1.0.7",+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.4",+ "data-view-buffer": "^1.0.2",+ "data-view-byte-length": "^1.0.2",+ "data-view-byte-offset": "^1.0.1",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "es-set-tostringtag": "^2.1.0",+ "es-to-primitive": "^1.3.0",+ "function.prototype.name": "^1.1.8",+ "get-intrinsic": "^1.3.0",+ "get-proto": "^1.0.1",+ "get-symbol-description": "^1.1.0",+ "globalthis": "^1.0.4",+ "gopd": "^1.2.0",+ "has-property-descriptors": "^1.0.2",+ "has-proto": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "internal-slot": "^1.1.0",+ "is-array-buffer": "^3.0.5",+ "is-callable": "^1.2.7",+ "is-data-view": "^1.0.2",+ "is-negative-zero": "^2.0.3",+ "is-regex": "^1.2.1",+ "is-set": "^2.0.3",+ "is-shared-array-buffer": "^1.0.4",+ "is-string": "^1.1.1",+ "is-typed-array": "^1.1.15",+ "is-weakref": "^1.1.1",+ "math-intrinsics": "^1.1.0",+ "object-inspect": "^1.13.4",+ "object-keys": "^1.1.1",+ "object.assign": "^4.1.7",+ "own-keys": "^1.0.1",+ "regexp.prototype.flags": "^1.5.4",+ "safe-array-concat": "^1.1.3",+ "safe-push-apply": "^1.0.0",+ "safe-regex-test": "^1.1.0",+ "set-proto": "^1.0.0",+ "stop-iteration-iterator": "^1.1.0",+ "string.prototype.trim": "^1.2.10",+ "string.prototype.trimend": "^1.0.9",+ "string.prototype.trimstart": "^1.0.8",+ "typed-array-buffer": "^1.0.3",+ "typed-array-byte-length": "^1.0.3",+ "typed-array-byte-offset": "^1.0.4",+ "typed-array-length": "^1.0.7",+ "unbox-primitive": "^1.1.0",+ "which-typed-array": "^1.1.19"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-iterator-helpers": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.3.1.tgz",+ "integrity": "sha512-zWwRvqWiuBPr0muUG/78cW3aHROFCNIQ3zpmYDpwdbnt2m+xlNyRWpHBpa2lJjSBit7BQ+RXA1iwbSmu5yJ/EQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.4",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.24.1",+ "es-errors": "^1.3.0",+ "es-set-tostringtag": "^2.1.0",+ "function-bind": "^1.1.2",+ "get-intrinsic": "^1.3.0",+ "globalthis": "^1.0.4",+ "gopd": "^1.2.0",+ "has-property-descriptors": "^1.0.2",+ "has-proto": "^1.2.0",+ "has-symbols": "^1.1.0",+ "internal-slot": "^1.1.0",+ "iterator.prototype": "^1.1.5",+ "math-intrinsics": "^1.1.0",+ "safe-array-concat": "^1.1.3"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-set-tostringtag": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-shim-unscopables": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz",+ "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-to-primitive": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.0.tgz",+ "integrity": "sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-callable": "^1.2.7",+ "is-date-object": "^1.0.5",+ "is-symbol": "^1.0.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/esast-util-from-estree": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/esast-util-from-estree/-/esast-util-from-estree-2.0.0.tgz",+ "integrity": "sha512-4CyanoAudUSBAn5K13H4JhsMH6L9ZP7XbLVe/dKybkxMO7eDyLsT8UHl9TRNrU2Gr9nz+FovfSIjuXWJ81uVwQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "devlop": "^1.0.0",+ "estree-util-visit": "^2.0.0",+ "unist-util-position-from-estree": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/esast-util-from-js": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/esast-util-from-js/-/esast-util-from-js-2.0.1.tgz",+ "integrity": "sha512-8Ja+rNJ0Lt56Pcf3TAmpBZjmx8ZcK5Ts4cAzIOjsjevg9oSXJnl6SUQ2EevU8tv3h6ZLWmoKL5H4fgWvdvfETw==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "acorn": "^8.0.0",+ "esast-util-from-estree": "^2.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/escape-string-regexp": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/eslint": {+ "version": "9.39.4",+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.4.tgz",+ "integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@eslint-community/eslint-utils": "^4.8.0",+ "@eslint-community/regexpp": "^4.12.1",+ "@eslint/config-array": "^0.21.2",+ "@eslint/config-helpers": "^0.4.2",+ "@eslint/core": "^0.17.0",+ "@eslint/eslintrc": "^3.3.5",+ "@eslint/js": "9.39.4",+ "@eslint/plugin-kit": "^0.4.1",+ "@humanfs/node": "^0.16.6",+ "@humanwhocodes/module-importer": "^1.0.1",+ "@humanwhocodes/retry": "^0.4.2",+ "@types/estree": "^1.0.6",+ "ajv": "^6.14.0",+ "chalk": "^4.0.0",+ "cross-spawn": "^7.0.6",+ "debug": "^4.3.2",+ "escape-string-regexp": "^4.0.0",+ "eslint-scope": "^8.4.0",+ "eslint-visitor-keys": "^4.2.1",+ "espree": "^10.4.0",+ "esquery": "^1.5.0",+ "esutils": "^2.0.2",+ "fast-deep-equal": "^3.1.3",+ "file-entry-cache": "^8.0.0",+ "find-up": "^5.0.0",+ "glob-parent": "^6.0.2",+ "ignore": "^5.2.0",+ "imurmurhash": "^0.1.4",+ "is-glob": "^4.0.0",+ "json-stable-stringify-without-jsonify": "^1.0.1",+ "lodash.merge": "^4.6.2",+ "minimatch": "^3.1.5",+ "natural-compare": "^1.4.0",+ "optionator": "^0.9.3"+ },+ "bin": {+ "eslint": "bin/eslint.js"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://eslint.org/donate"+ },+ "peerDependencies": {+ "jiti": "*"+ },+ "peerDependenciesMeta": {+ "jiti": {+ "optional": true+ }+ }+ },+ "node_modules/eslint-config-next": {+ "version": "15.5.14",+ "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-15.5.14.tgz",+ "integrity": "sha512-lmJ5F8ZgOYogq0qtH4L5SpxuASY2SPdOzqUprN2/56+P3GPsIpXaUWIJC66kYIH+yZdsM4nkHE5MIBP6s1NiBw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@next/eslint-plugin-next": "15.5.14",+ "@rushstack/eslint-patch": "^1.10.3",+ "@typescript-eslint/eslint-plugin": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0",+ "@typescript-eslint/parser": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0",+ "eslint-import-resolver-node": "^0.3.6",+ "eslint-import-resolver-typescript": "^3.5.2",+ "eslint-plugin-import": "^2.31.0",+ "eslint-plugin-jsx-a11y": "^6.10.0",+ "eslint-plugin-react": "^7.37.0",+ "eslint-plugin-react-hooks": "^5.0.0"+ },+ "peerDependencies": {+ "eslint": "^7.23.0 || ^8.0.0 || ^9.0.0",+ "typescript": ">=3.3.1"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },+ "node_modules/eslint-import-resolver-node": {+ "version": "0.3.9",+ "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz",+ "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "debug": "^3.2.7",+ "is-core-module": "^2.13.0",+ "resolve": "^1.22.4"+ }+ },+ "node_modules/eslint-import-resolver-node/node_modules/debug": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",+ "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.1"+ }+ },+ "node_modules/eslint-import-resolver-typescript": {+ "version": "3.10.1",+ "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.10.1.tgz",+ "integrity": "sha512-A1rHYb06zjMGAxdLSkN2fXPBwuSaQ0iO5M/hdyS0Ajj1VBaRp0sPD3dn1FhME3c/JluGFbwSxyCfqdSbtQLAHQ==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "@nolyfill/is-core-module": "1.0.39",+ "debug": "^4.4.0",+ "get-tsconfig": "^4.10.0",+ "is-bun-module": "^2.0.0",+ "stable-hash": "^0.0.5",+ "tinyglobby": "^0.2.13",+ "unrs-resolver": "^1.6.2"+ },+ "engines": {+ "node": "^14.18.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint-import-resolver-typescript"+ },+ "peerDependencies": {+ "eslint": "*",+ "eslint-plugin-import": "*",+ "eslint-plugin-import-x": "*"+ },+ "peerDependenciesMeta": {+ "eslint-plugin-import": {+ "optional": true+ },+ "eslint-plugin-import-x": {+ "optional": true+ }+ }+ },+ "node_modules/eslint-module-utils": {+ "version": "2.12.1",+ "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.12.1.tgz",+ "integrity": "sha512-L8jSWTze7K2mTg0vos/RuLRS5soomksDPoJLXIslC7c8Wmut3bx7CPpJijDcBZtxQ5lrbUdM+s0OlNbz0DCDNw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "debug": "^3.2.7"+ },+ "engines": {+ "node": ">=4"+ },+ "peerDependenciesMeta": {+ "eslint": {+ "optional": true+ }+ }+ },+ "node_modules/eslint-module-utils/node_modules/debug": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",+ "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.1"+ }+ },+ "node_modules/eslint-plugin-import": {+ "version": "2.32.0",+ "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.32.0.tgz",+ "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@rtsao/scc": "^1.1.0",+ "array-includes": "^3.1.9",+ "array.prototype.findlastindex": "^1.2.6",+ "array.prototype.flat": "^1.3.3",+ "array.prototype.flatmap": "^1.3.3",+ "debug": "^3.2.7",+ "doctrine": "^2.1.0",+ "eslint-import-resolver-node": "^0.3.9",+ "eslint-module-utils": "^2.12.1",+ "hasown": "^2.0.2",+ "is-core-module": "^2.16.1",+ "is-glob": "^4.0.3",+ "minimatch": "^3.1.2",+ "object.fromentries": "^2.0.8",+ "object.groupby": "^1.0.3",+ "object.values": "^1.2.1",+ "semver": "^6.3.1",+ "string.prototype.trimend": "^1.0.9",+ "tsconfig-paths": "^3.15.0"+ },+ "engines": {+ "node": ">=4"+ },+ "peerDependencies": {+ "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9"+ }+ },+ "node_modules/eslint-plugin-import/node_modules/debug": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",+ "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.1"+ }+ },+ "node_modules/eslint-plugin-import/node_modules/semver": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/eslint-plugin-jsx-a11y": {+ "version": "6.10.2",+ "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.10.2.tgz",+ "integrity": "sha512-scB3nz4WmG75pV8+3eRUQOHZlNSUhFNq37xnpgRkCCELU3XMvXAxLk1eqWWyE22Ki4Q01Fnsw9BA3cJHDPgn2Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "aria-query": "^5.3.2",+ "array-includes": "^3.1.8",+ "array.prototype.flatmap": "^1.3.2",+ "ast-types-flow": "^0.0.8",+ "axe-core": "^4.10.0",+ "axobject-query": "^4.1.0",+ "damerau-levenshtein": "^1.0.8",+ "emoji-regex": "^9.2.2",+ "hasown": "^2.0.2",+ "jsx-ast-utils": "^3.3.5",+ "language-tags": "^1.0.9",+ "minimatch": "^3.1.2",+ "object.fromentries": "^2.0.8",+ "safe-regex-test": "^1.0.3",+ "string.prototype.includes": "^2.0.1"+ },+ "engines": {+ "node": ">=4.0"+ },+ "peerDependencies": {+ "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9"+ }+ },+ "node_modules/eslint-plugin-react": {+ "version": "7.37.5",+ "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.37.5.tgz",+ "integrity": "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "array-includes": "^3.1.8",+ "array.prototype.findlast": "^1.2.5",+ "array.prototype.flatmap": "^1.3.3",+ "array.prototype.tosorted": "^1.1.4",+ "doctrine": "^2.1.0",+ "es-iterator-helpers": "^1.2.1",+ "estraverse": "^5.3.0",+ "hasown": "^2.0.2",+ "jsx-ast-utils": "^2.4.1 || ^3.0.0",+ "minimatch": "^3.1.2",+ "object.entries": "^1.1.9",+ "object.fromentries": "^2.0.8",+ "object.values": "^1.2.1",+ "prop-types": "^15.8.1",+ "resolve": "^2.0.0-next.5",+ "semver": "^6.3.1",+ "string.prototype.matchall": "^4.0.12",+ "string.prototype.repeat": "^1.0.0"+ },+ "engines": {+ "node": ">=4"+ },+ "peerDependencies": {+ "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7"+ }+ },+ "node_modules/eslint-plugin-react-hooks": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-5.2.0.tgz",+ "integrity": "sha512-+f15FfK64YQwZdJNELETdn5ibXEUQmW1DZL6KXhNnc2heoy/sg9VJJeT7n8TlMWouzWqSWavFkIhHyIbIAEapg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0"+ }+ },+ "node_modules/eslint-plugin-react/node_modules/resolve": {+ "version": "2.0.0-next.6",+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.6.tgz",+ "integrity": "sha512-3JmVl5hMGtJ3kMmB3zi3DL25KfkCEyy3Tw7Gmw7z5w8M9WlwoPFnIvwChzu1+cF3iaK3sp18hhPz8ANeimdJfA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "is-core-module": "^2.16.1",+ "node-exports-info": "^1.6.0",+ "object-keys": "^1.1.1",+ "path-parse": "^1.0.7",+ "supports-preserve-symlinks-flag": "^1.0.0"+ },+ "bin": {+ "resolve": "bin/resolve"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/eslint-plugin-react/node_modules/semver": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/eslint-scope": {+ "version": "8.4.0",+ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz",+ "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "esrecurse": "^4.3.0",+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/eslint-visitor-keys": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",+ "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/espree": {+ "version": "10.4.0",+ "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",+ "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "acorn": "^8.15.0",+ "acorn-jsx": "^5.3.2",+ "eslint-visitor-keys": "^4.2.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/esquery": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz",+ "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "estraverse": "^5.1.0"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/esrecurse": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",+ "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/estraverse": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/estree-util-attach-comments": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/estree-util-attach-comments/-/estree-util-attach-comments-3.0.0.tgz",+ "integrity": "sha512-cKUwm/HUcTDsYh/9FgnuFqpfquUbwIqwKM26BVCGDPVgvaCl/nDCCjUfiLlx6lsEZ3Z4RFxNbOQ60pkaEwFxGw==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-util-build-jsx": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/estree-util-build-jsx/-/estree-util-build-jsx-3.0.1.tgz",+ "integrity": "sha512-8U5eiL6BTrPxp/CHbs2yMgP8ftMhR5ww1eIKoWRMlqvltHF8fZn5LRDvTKuxD3DUn+shRbLGqXemcP51oFCsGQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "devlop": "^1.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "estree-walker": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-util-is-identifier-name": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",+ "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-util-scope": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/estree-util-scope/-/estree-util-scope-1.0.0.tgz",+ "integrity": "sha512-2CAASclonf+JFWBNJPndcOpA8EMJwa0Q8LUFJEKqXLW6+qBvbFZuF5gItbQOs/umBUkjviCSDCbBwU2cXbmrhQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "devlop": "^1.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-util-to-js": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/estree-util-to-js/-/estree-util-to-js-2.0.0.tgz",+ "integrity": "sha512-WDF+xj5rRWmD5tj6bIqRi6CkLIXbbNQUcxQHzGysQzvHmdYG2G7p/Tf0J0gpxGgkeMZNTIjT/AoSvC9Xehcgdg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "astring": "^1.8.0",+ "source-map": "^0.7.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-util-visit": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/estree-util-visit/-/estree-util-visit-2.0.0.tgz",+ "integrity": "sha512-m5KgiH85xAhhW8Wta0vShLcUvOsh3LLPI2YVwcbio1l7E09NTLL1EyMZFM1OyWowoH0skScNbhOPl4kcBgzTww==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/estree-walker": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0"+ }+ },+ "node_modules/esutils": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/eventemitter3": {+ "version": "4.0.7",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",+ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",+ "license": "MIT"+ },+ "node_modules/extend": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",+ "license": "MIT"+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fast-equals": {+ "version": "5.4.0",+ "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.4.0.tgz",+ "integrity": "sha512-jt2DW/aNFNwke7AUd+Z+e6pz39KO5rzdbbFCg2sGafS4mk13MI7Z8O5z9cADNn5lhGODIgLwug6TZO2ctf7kcw==",+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/fast-glob": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz",+ "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@nodelib/fs.stat": "^2.0.2",+ "@nodelib/fs.walk": "^1.2.3",+ "glob-parent": "^5.1.2",+ "merge2": "^1.3.0",+ "micromatch": "^4.0.4"+ },+ "engines": {+ "node": ">=8.6.0"+ }+ },+ "node_modules/fast-glob/node_modules/glob-parent": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "is-glob": "^4.0.1"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/fast-json-stable-stringify": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fast-levenshtein": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",+ "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/fastq": {+ "version": "1.20.1",+ "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",+ "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "reusify": "^1.0.4"+ }+ },+ "node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/file-entry-cache": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",+ "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "flat-cache": "^4.0.0"+ },+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/fill-range": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",+ "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "to-regex-range": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/find-up": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",+ "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "locate-path": "^6.0.0",+ "path-exists": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/flat-cache": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz",+ "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "flatted": "^3.2.9",+ "keyv": "^4.5.4"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/flatted": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz",+ "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/for-each": {+ "version": "0.3.5",+ "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz",+ "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-callable": "^1.2.7"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/framer-motion": {+ "version": "11.18.2",+ "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-11.18.2.tgz",+ "integrity": "sha512-5F5Och7wrvtLVElIpclDT0CBzMVg3dL22B64aZwHtsIY8RB4mXICLrkajK4G9R+ieSAGcgrLeae2SeUTg2pr6w==",+ "license": "MIT",+ "dependencies": {+ "motion-dom": "^11.18.1",+ "motion-utils": "^11.18.1",+ "tslib": "^2.4.0"+ },+ "peerDependencies": {+ "@emotion/is-prop-valid": "*",+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "@emotion/is-prop-valid": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/function.prototype.name": {+ "version": "1.1.8",+ "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.8.tgz",+ "integrity": "sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.3",+ "define-properties": "^1.2.1",+ "functions-have-names": "^1.2.3",+ "hasown": "^2.0.2",+ "is-callable": "^1.2.7"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/functions-have-names": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz",+ "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/fuse.js": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/fuse.js/-/fuse.js-7.1.0.tgz",+ "integrity": "sha512-trLf4SzuuUxfusZADLINj+dE8clK1frKdmqiJNb1Es75fmI5oY6X2mxLVUciLLjxqw/xr72Dhy+lER6dGd02FQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/geist": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/geist/-/geist-1.7.0.tgz",+ "integrity": "sha512-ZaoiZwkSf0DwwB1ncdLKp+ggAldqxl5L1+SXaNIBGkPAqcu+xjVJLxlf3/S8vLt9UHx1xu5fz3lbzKCj5iOVdQ==",+ "license": "SIL OPEN FONT LICENSE",+ "peerDependencies": {+ "next": ">=13.2.0"+ }+ },+ "node_modules/generator-function": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz",+ "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-nonce": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz",+ "integrity": "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/get-symbol-description": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz",+ "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-tsconfig": {+ "version": "4.13.6",+ "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz",+ "integrity": "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "resolve-pkg-maps": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"+ }+ },+ "node_modules/glob-parent": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",+ "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "is-glob": "^4.0.3"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/globals": {+ "version": "14.0.0",+ "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",+ "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/globalthis": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",+ "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-properties": "^1.2.1",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/graceful-fs": {+ "version": "4.2.11",+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/hachure-fill": {+ "version": "0.5.2",+ "resolved": "https://registry.npmjs.org/hachure-fill/-/hachure-fill-0.5.2.tgz",+ "integrity": "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==",+ "license": "MIT"+ },+ "node_modules/has-bigints": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz",+ "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-flag": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/has-property-descriptors": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",+ "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-define-property": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-proto": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz",+ "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-tostringtag": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "has-symbols": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/hast-util-to-estree": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/hast-util-to-estree/-/hast-util-to-estree-3.1.3.tgz",+ "integrity": "sha512-48+B/rJWAp0jamNbAAf9M7Uf//UVqAoMmgXhBdxTDJLGKY+LRnZ99qcG+Qjl5HfMpYNzS5v4EAwVEF34LeAj7w==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "comma-separated-tokens": "^2.0.0",+ "devlop": "^1.0.0",+ "estree-util-attach-comments": "^3.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "hast-util-whitespace": "^3.0.0",+ "mdast-util-mdx-expression": "^2.0.0",+ "mdast-util-mdx-jsx": "^3.0.0",+ "mdast-util-mdxjs-esm": "^2.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "style-to-js": "^1.0.0",+ "unist-util-position": "^5.0.0",+ "zwitch": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-to-html": {+ "version": "9.0.5",+ "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz",+ "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "ccount": "^2.0.0",+ "comma-separated-tokens": "^2.0.0",+ "hast-util-whitespace": "^3.0.0",+ "html-void-elements": "^3.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "stringify-entities": "^4.0.0",+ "zwitch": "^2.0.4"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-to-jsx-runtime": {+ "version": "2.3.6",+ "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",+ "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "comma-separated-tokens": "^2.0.0",+ "devlop": "^1.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "hast-util-whitespace": "^3.0.0",+ "mdast-util-mdx-expression": "^2.0.0",+ "mdast-util-mdx-jsx": "^3.0.0",+ "mdast-util-mdxjs-esm": "^2.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "style-to-js": "^1.0.0",+ "unist-util-position": "^5.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-whitespace": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",+ "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/html-void-elements": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz",+ "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/iconv-lite": {+ "version": "0.6.3",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/ignore": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",+ "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/import-fresh": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",+ "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "parent-module": "^1.0.0",+ "resolve-from": "^4.0.0"+ },+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/imurmurhash": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",+ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.8.19"+ }+ },+ "node_modules/inline-style-parser": {+ "version": "0.2.7",+ "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz",+ "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==",+ "license": "MIT"+ },+ "node_modules/internal-slot": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz",+ "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "hasown": "^2.0.2",+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/internmap": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",+ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/is-alphabetical": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",+ "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-alphanumerical": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",+ "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",+ "license": "MIT",+ "dependencies": {+ "is-alphabetical": "^2.0.0",+ "is-decimal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-array-buffer": {+ "version": "3.0.5",+ "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",+ "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.3",+ "get-intrinsic": "^1.2.6"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-async-function": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz",+ "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "async-function": "^1.0.0",+ "call-bound": "^1.0.3",+ "get-proto": "^1.0.1",+ "has-tostringtag": "^1.0.2",+ "safe-regex-test": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-bigint": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz",+ "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "has-bigints": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-boolean-object": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz",+ "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "has-tostringtag": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-bun-module": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/is-bun-module/-/is-bun-module-2.0.0.tgz",+ "integrity": "sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "semver": "^7.7.1"+ }+ },+ "node_modules/is-callable": {+ "version": "1.2.7",+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz",+ "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-core-module": {+ "version": "2.16.1",+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz",+ "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-data-view": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz",+ "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "get-intrinsic": "^1.2.6",+ "is-typed-array": "^1.1.13"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-date-object": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz",+ "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "has-tostringtag": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-decimal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",+ "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-extglob": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",+ "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-finalizationregistry": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz",+ "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-generator-function": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz",+ "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.4",+ "generator-function": "^2.0.0",+ "get-proto": "^1.0.1",+ "has-tostringtag": "^1.0.2",+ "safe-regex-test": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-glob": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",+ "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-extglob": "^2.1.1"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-hexadecimal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",+ "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-map": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz",+ "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-negative-zero": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz",+ "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-number": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.12.0"+ }+ },+ "node_modules/is-number-object": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz",+ "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "has-tostringtag": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-plain-obj": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",+ "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/is-regex": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",+ "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "gopd": "^1.2.0",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-set": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz",+ "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-shared-array-buffer": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz",+ "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-string": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz",+ "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "has-tostringtag": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-symbol": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz",+ "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "has-symbols": "^1.1.0",+ "safe-regex-test": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-typed-array": {+ "version": "1.1.15",+ "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz",+ "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "which-typed-array": "^1.1.16"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-weakmap": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz",+ "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-weakref": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz",+ "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-weakset": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz",+ "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "get-intrinsic": "^1.2.6"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/isarray": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",+ "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/iterator.prototype": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/iterator.prototype/-/iterator.prototype-1.1.5.tgz",+ "integrity": "sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-data-property": "^1.1.4",+ "es-object-atoms": "^1.0.0",+ "get-intrinsic": "^1.2.6",+ "get-proto": "^1.0.0",+ "has-symbols": "^1.1.0",+ "set-function-name": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/jiti": {+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz",+ "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "jiti": "lib/jiti-cli.mjs"+ }+ },+ "node_modules/js-tokens": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",+ "license": "MIT"+ },+ "node_modules/js-yaml": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",+ "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "argparse": "^2.0.1"+ },+ "bin": {+ "js-yaml": "bin/js-yaml.js"+ }+ },+ "node_modules/json-buffer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",+ "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/json-schema-traverse": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/json-stable-stringify-without-jsonify": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",+ "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/json5": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz",+ "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "minimist": "^1.2.0"+ },+ "bin": {+ "json5": "lib/cli.js"+ }+ },+ "node_modules/jsx-ast-utils": {+ "version": "3.3.5",+ "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",+ "integrity": "sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "array-includes": "^3.1.6",+ "array.prototype.flat": "^1.3.1",+ "object.assign": "^4.1.4",+ "object.values": "^1.1.6"+ },+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/katex": {+ "version": "0.16.39",+ "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.39.tgz",+ "integrity": "sha512-FR2f6y85+81ZLO0GPhyQ+EJl/E5ILNWltJhpAeOTzRny952Z13x2867lTFDmvMZix//Ux3CuMQ2VkLXRbUwOFg==",+ "funding": [+ "https://opencollective.com/katex",+ "https://github.com/sponsors/katex"+ ],+ "license": "MIT",+ "dependencies": {+ "commander": "^8.3.0"+ },+ "bin": {+ "katex": "cli.js"+ }+ },+ "node_modules/katex/node_modules/commander": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",+ "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/keyv": {+ "version": "4.5.4",+ "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",+ "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "json-buffer": "3.0.1"+ }+ },+ "node_modules/khroma": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/khroma/-/khroma-2.1.0.tgz",+ "integrity": "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw=="+ },+ "node_modules/langium": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/langium/-/langium-4.2.1.tgz",+ "integrity": "sha512-zu9QWmjpzJcomzdJQAHgDVhLGq5bLosVak1KVa40NzQHXfqr4eAHupvnPOVXEoLkg6Ocefvf/93d//SB7du4YQ==",+ "license": "MIT",+ "dependencies": {+ "chevrotain": "~11.1.1",+ "chevrotain-allstar": "~0.3.1",+ "vscode-languageserver": "~9.0.1",+ "vscode-languageserver-textdocument": "~1.0.11",+ "vscode-uri": "~3.1.0"+ },+ "engines": {+ "node": ">=20.10.0",+ "npm": ">=10.2.3"+ }+ },+ "node_modules/language-subtag-registry": {+ "version": "0.3.23",+ "resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.23.tgz",+ "integrity": "sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==",+ "dev": true,+ "license": "CC0-1.0"+ },+ "node_modules/language-tags": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/language-tags/-/language-tags-1.0.9.tgz",+ "integrity": "sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "language-subtag-registry": "^0.3.20"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/layout-base": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-1.0.2.tgz",+ "integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==",+ "license": "MIT"+ },+ "node_modules/levn": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",+ "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "prelude-ls": "^1.2.1",+ "type-check": "~0.4.0"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/lightningcss": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",+ "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",+ "dev": true,+ "license": "MPL-2.0",+ "dependencies": {+ "detect-libc": "^2.0.3"+ },+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ },+ "optionalDependencies": {+ "lightningcss-android-arm64": "1.32.0",+ "lightningcss-darwin-arm64": "1.32.0",+ "lightningcss-darwin-x64": "1.32.0",+ "lightningcss-freebsd-x64": "1.32.0",+ "lightningcss-linux-arm-gnueabihf": "1.32.0",+ "lightningcss-linux-arm64-gnu": "1.32.0",+ "lightningcss-linux-arm64-musl": "1.32.0",+ "lightningcss-linux-x64-gnu": "1.32.0",+ "lightningcss-linux-x64-musl": "1.32.0",+ "lightningcss-win32-arm64-msvc": "1.32.0",+ "lightningcss-win32-x64-msvc": "1.32.0"+ }+ },+ "node_modules/lightningcss-android-arm64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz",+ "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-arm64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz",+ "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-x64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz",+ "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-freebsd-x64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz",+ "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm-gnueabihf": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz",+ "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-gnu": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz",+ "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-musl": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz",+ "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-gnu": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz",+ "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-musl": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz",+ "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-arm64-msvc": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz",+ "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-x64-msvc": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",+ "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/locate-path": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",+ "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "p-locate": "^5.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/lodash": {+ "version": "4.17.23",+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",+ "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==",+ "license": "MIT"+ },+ "node_modules/lodash-es": {+ "version": "4.17.23",+ "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.23.tgz",+ "integrity": "sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==",+ "license": "MIT"+ },+ "node_modules/lodash.merge": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",+ "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/longest-streak": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",+ "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/loose-envify": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",+ "license": "MIT",+ "dependencies": {+ "js-tokens": "^3.0.0 || ^4.0.0"+ },+ "bin": {+ "loose-envify": "cli.js"+ }+ },+ "node_modules/lucide-react": {+ "version": "0.460.0",+ "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.460.0.tgz",+ "integrity": "sha512-BVtq/DykVeIvRTJvRAgCsOwaGL8Un3Bxh8MbDxMhEWlZay3T4IpEKDEpwt5KZ0KJMHzgm6jrltxlT5eXOWXDHg==",+ "license": "ISC",+ "peerDependencies": {+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc"+ }+ },+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/markdown-extensions": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/markdown-extensions/-/markdown-extensions-2.0.0.tgz",+ "integrity": "sha512-o5vL7aDWatOTX8LzaS1WMoaoxIiLRQJuIKKe2wAw6IeULDHaqbiqiggmx+pKvZDb1Sj+pE46Sn1T7lCqfFtg1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=16"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/marked": {+ "version": "16.4.2",+ "resolved": "https://registry.npmjs.org/marked/-/marked-16.4.2.tgz",+ "integrity": "sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==",+ "license": "MIT",+ "bin": {+ "marked": "bin/marked.js"+ },+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/mdast-util-from-markdown": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz",+ "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "mdast-util-to-string": "^4.0.0",+ "micromark": "^4.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-decode-string": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unist-util-stringify-position": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdx": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-mdx/-/mdast-util-mdx-3.0.0.tgz",+ "integrity": "sha512-JfbYLAW7XnYTTbUsmpu0kdBUVe+yKVJZBItEjwyYJiDJuZ9w4eeaqks4HQO+R7objWgS2ymV60GYpI14Ug554w==",+ "license": "MIT",+ "dependencies": {+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-mdx-expression": "^2.0.0",+ "mdast-util-mdx-jsx": "^3.0.0",+ "mdast-util-mdxjs-esm": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdx-expression": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",+ "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdx-jsx": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz",+ "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "ccount": "^2.0.0",+ "devlop": "^1.1.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "parse-entities": "^4.0.0",+ "stringify-entities": "^4.0.0",+ "unist-util-stringify-position": "^4.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdxjs-esm": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz",+ "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-phrasing": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",+ "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-hast": {+ "version": "13.2.1",+ "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",+ "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "@ungap/structured-clone": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "trim-lines": "^3.0.0",+ "unist-util-position": "^5.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-markdown": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz",+ "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "longest-streak": "^3.0.0",+ "mdast-util-phrasing": "^4.0.0",+ "mdast-util-to-string": "^4.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-decode-string": "^2.0.0",+ "unist-util-visit": "^5.0.0",+ "zwitch": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-string": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",+ "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/merge2": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",+ "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/mermaid": {+ "version": "11.13.0",+ "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.13.0.tgz",+ "integrity": "sha512-fEnci+Immw6lKMFI8sqzjlATTyjLkRa6axrEgLV2yHTfv8r+h1wjFbV6xeRtd4rUV1cS4EpR9rwp3Rci7TRWDw==",+ "license": "MIT",+ "dependencies": {+ "@braintree/sanitize-url": "^7.1.1",+ "@iconify/utils": "^3.0.2",+ "@mermaid-js/parser": "^1.0.1",+ "@types/d3": "^7.4.3",+ "@upsetjs/venn.js": "^2.0.0",+ "cytoscape": "^3.33.1",+ "cytoscape-cose-bilkent": "^4.1.0",+ "cytoscape-fcose": "^2.2.0",+ "d3": "^7.9.0",+ "d3-sankey": "^0.12.3",+ "dagre-d3-es": "7.0.14",+ "dayjs": "^1.11.19",+ "dompurify": "^3.3.1",+ "katex": "^0.16.25",+ "khroma": "^2.1.0",+ "lodash-es": "^4.17.23",+ "marked": "^16.3.0",+ "roughjs": "^4.6.6",+ "stylis": "^4.3.6",+ "ts-dedent": "^2.2.0",+ "uuid": "^11.1.0"+ }+ },+ "node_modules/micromark": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",+ "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@types/debug": "^4.0.0",+ "debug": "^4.0.0",+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-encode": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-subtokenize": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-core-commonmark": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz",+ "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-factory-destination": "^2.0.0",+ "micromark-factory-label": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-factory-title": "^2.0.0",+ "micromark-factory-whitespace": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-html-tag-name": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-subtokenize": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-extension-mdx-expression": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/micromark-extension-mdx-expression/-/micromark-extension-mdx-expression-3.0.1.tgz",+ "integrity": "sha512-dD/ADLJ1AeMvSAKBwO22zG22N4ybhe7kFIZ3LsDI0GlsNr2A3KYxb0LdC1u5rj4Nw+CHKY0RVdnHX8vj8ejm4Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-factory-mdx-expression": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-events-to-acorn": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-extension-mdx-jsx": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/micromark-extension-mdx-jsx/-/micromark-extension-mdx-jsx-3.0.2.tgz",+ "integrity": "sha512-e5+q1DjMh62LZAJOnDraSSbDMvGJ8x3cbjygy2qFEi7HCeUT4BDKCvMozPozcD6WmOt6sVvYDNBKhFSz3kjOVQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "devlop": "^1.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "micromark-factory-mdx-expression": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-events-to-acorn": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-mdx-md": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-mdx-md/-/micromark-extension-mdx-md-2.0.0.tgz",+ "integrity": "sha512-EpAiszsB3blw4Rpba7xTOUptcFeBFi+6PY8VnJ2hhimH+vCQDirWgsMpz7w1XcZE7LVrSAUGb9VJpG9ghlYvYQ==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-mdxjs": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-mdxjs/-/micromark-extension-mdxjs-3.0.0.tgz",+ "integrity": "sha512-A873fJfhnJ2siZyUrJ31l34Uqwy4xIFmvPY1oj+Ean5PHcPBYzEsvqvWGaWcfEIr11O5Dlw3p2y0tZWpKHDejQ==",+ "license": "MIT",+ "dependencies": {+ "acorn": "^8.0.0",+ "acorn-jsx": "^5.0.0",+ "micromark-extension-mdx-expression": "^3.0.0",+ "micromark-extension-mdx-jsx": "^3.0.0",+ "micromark-extension-mdx-md": "^2.0.0",+ "micromark-extension-mdxjs-esm": "^3.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-mdxjs-esm": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-mdxjs-esm/-/micromark-extension-mdxjs-esm-3.0.0.tgz",+ "integrity": "sha512-DJFl4ZqkErRpq/dAPyeWp15tGrcrrJho1hKK5uBS70BCtfrIFg81sqcTVu3Ta+KD1Tk5vAtBNElWxtAa+m8K9A==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-events-to-acorn": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unist-util-position-from-estree": "^2.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-factory-destination": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",+ "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-label": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz",+ "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-mdx-expression": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/micromark-factory-mdx-expression/-/micromark-factory-mdx-expression-2.0.3.tgz",+ "integrity": "sha512-kQnEtA3vzucU2BkrIa8/VaSAsP+EJ3CKOvhMuJgOEGg9KDC6OAY6nSnNDVRiVNRqj7Y4SlSzcStaH/5jge8JdQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-events-to-acorn": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unist-util-position-from-estree": "^2.0.0",+ "vfile-message": "^4.0.0"+ }+ },+ "node_modules/micromark-factory-space": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz",+ "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-title": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz",+ "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-whitespace": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz",+ "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-character": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz",+ "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-chunked": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz",+ "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-classify-character": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz",+ "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-combine-extensions": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz",+ "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-decode-numeric-character-reference": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz",+ "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-decode-string": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz",+ "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decode-named-character-reference": "^1.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-encode": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",+ "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-events-to-acorn": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/micromark-util-events-to-acorn/-/micromark-util-events-to-acorn-2.0.3.tgz",+ "integrity": "sha512-jmsiEIiZ1n7X1Rr5k8wVExBQCg5jy4UXVADItHmNk1zkwEVhBuIUKRu3fqv+hs4nxLISi2DQGlqIOGiFxgbfHg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/unist": "^3.0.0",+ "devlop": "^1.0.0",+ "estree-util-visit": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "vfile-message": "^4.0.0"+ }+ },+ "node_modules/micromark-util-html-tag-name": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz",+ "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-normalize-identifier": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz",+ "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-resolve-all": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz",+ "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-sanitize-uri": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",+ "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-encode": "^2.0.0",+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-subtokenize": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz",+ "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-symbol": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",+ "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-types": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz",+ "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromatch": {+ "version": "4.0.8",+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "braces": "^3.0.3",+ "picomatch": "^2.3.1"+ },+ "engines": {+ "node": ">=8.6"+ }+ },+ "node_modules/micromatch/node_modules/picomatch": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",+ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/minimatch": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/minimist": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/mlly": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.1.tgz",+ "integrity": "sha512-SnL6sNutTwRWWR/vcmCYHSADjiEesp5TGQQ0pXyLhW5IoeibRlF/CbSLailbB3CNqJUk9cVJ9dUDnbD7GrcHBQ==",+ "license": "MIT",+ "dependencies": {+ "acorn": "^8.16.0",+ "pathe": "^2.0.3",+ "pkg-types": "^1.3.1",+ "ufo": "^1.6.3"+ }+ },+ "node_modules/motion-dom": {+ "version": "11.18.1",+ "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-11.18.1.tgz",+ "integrity": "sha512-g76KvA001z+atjfxczdRtw/RXOM3OMSdd1f4DL77qCTF/+avrRJiawSG4yDibEQ215sr9kpinSlX2pCTJ9zbhw==",+ "license": "MIT",+ "dependencies": {+ "motion-utils": "^11.18.1"+ }+ },+ "node_modules/motion-utils": {+ "version": "11.18.1",+ "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-11.18.1.tgz",+ "integrity": "sha512-49Kt+HKjtbJKLtgO/LKj9Ld+6vw9BjH5d9sc40R/kVyH8GLAXgT42M2NnuPcJNuA3s9ZfZBUcwIgpmZWGEE+hA==",+ "license": "MIT"+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/nanoid": {+ "version": "3.3.11",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/napi-postinstall": {+ "version": "0.3.4",+ "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz",+ "integrity": "sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "napi-postinstall": "lib/cli.js"+ },+ "engines": {+ "node": "^12.20.0 || ^14.18.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/napi-postinstall"+ }+ },+ "node_modules/natural-compare": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",+ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/next": {+ "version": "15.5.13",+ "resolved": "https://registry.npmjs.org/next/-/next-15.5.13.tgz",+ "integrity": "sha512-n0AXf6vlTwGuM93Z++POtjMsRuQ9pT5v2URPciXKUQIl/EB2WjXF0YiIUxaa9AEMFaMpZlaG3KPK6i4UVnx9eQ==",+ "license": "MIT",+ "dependencies": {+ "@next/env": "15.5.13",+ "@swc/helpers": "0.5.15",+ "caniuse-lite": "^1.0.30001579",+ "postcss": "8.4.31",+ "styled-jsx": "5.1.6"+ },+ "bin": {+ "next": "dist/bin/next"+ },+ "engines": {+ "node": "^18.18.0 || ^19.8.0 || >= 20.0.0"+ },+ "optionalDependencies": {+ "@next/swc-darwin-arm64": "15.5.13",+ "@next/swc-darwin-x64": "15.5.13",+ "@next/swc-linux-arm64-gnu": "15.5.13",+ "@next/swc-linux-arm64-musl": "15.5.13",+ "@next/swc-linux-x64-gnu": "15.5.13",+ "@next/swc-linux-x64-musl": "15.5.13",+ "@next/swc-win32-arm64-msvc": "15.5.13",+ "@next/swc-win32-x64-msvc": "15.5.13",+ "sharp": "^0.34.3"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.1.0",+ "@playwright/test": "^1.51.1",+ "babel-plugin-react-compiler": "*",+ "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0",+ "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0",+ "sass": "^1.3.0"+ },+ "peerDependenciesMeta": {+ "@opentelemetry/api": {+ "optional": true+ },+ "@playwright/test": {+ "optional": true+ },+ "babel-plugin-react-compiler": {+ "optional": true+ },+ "sass": {+ "optional": true+ }+ }+ },+ "node_modules/next-mdx-remote": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/next-mdx-remote/-/next-mdx-remote-5.0.0.tgz",+ "integrity": "sha512-RNNbqRpK9/dcIFZs/esQhuLA8jANqlH694yqoDBK8hkVdJUndzzGmnPHa2nyi90N4Z9VmzuSWNRpr5ItT3M7xQ==",+ "license": "MPL-2.0",+ "dependencies": {+ "@babel/code-frame": "^7.23.5",+ "@mdx-js/mdx": "^3.0.1",+ "@mdx-js/react": "^3.0.1",+ "unist-util-remove": "^3.1.0",+ "vfile": "^6.0.1",+ "vfile-matter": "^5.0.0"+ },+ "engines": {+ "node": ">=14",+ "npm": ">=7"+ },+ "peerDependencies": {+ "react": ">=16"+ }+ },+ "node_modules/next/node_modules/postcss": {+ "version": "8.4.31",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",+ "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.6",+ "picocolors": "^1.0.0",+ "source-map-js": "^1.0.2"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/node-exports-info": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.0.tgz",+ "integrity": "sha512-pyFS63ptit/P5WqUkt+UUfe+4oevH+bFeIiPPdfb0pFeYEu/1ELnJu5l+5EcTKYL5M7zaAa7S8ddywgXypqKCw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "array.prototype.flatmap": "^1.3.3",+ "es-errors": "^1.3.0",+ "object.entries": "^1.1.9",+ "semver": "^6.3.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/node-exports-info/node_modules/semver": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/nuqs": {+ "version": "2.8.9",+ "resolved": "https://registry.npmjs.org/nuqs/-/nuqs-2.8.9.tgz",+ "integrity": "sha512-8ou6AEwsxMWSYo2qkfZtYFVzngwbKmg4c00HVxC1fF6CEJv3Fwm6eoZmfVPALB+vw8Udo7KL5uy96PFcYe1BIQ==",+ "license": "MIT",+ "dependencies": {+ "@standard-schema/spec": "1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/franky47"+ },+ "peerDependencies": {+ "@remix-run/react": ">=2",+ "@tanstack/react-router": "^1",+ "next": ">=14.2.0",+ "react": ">=18.2.0 || ^19.0.0-0",+ "react-router": "^5 || ^6 || ^7",+ "react-router-dom": "^5 || ^6 || ^7"+ },+ "peerDependenciesMeta": {+ "@remix-run/react": {+ "optional": true+ },+ "@tanstack/react-router": {+ "optional": true+ },+ "next": {+ "optional": true+ },+ "react-router": {+ "optional": true+ },+ "react-router-dom": {+ "optional": true+ }+ }+ },+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/object-keys": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",+ "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/object.assign": {+ "version": "4.1.7",+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz",+ "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.3",+ "define-properties": "^1.2.1",+ "es-object-atoms": "^1.0.0",+ "has-symbols": "^1.1.0",+ "object-keys": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/object.entries": {+ "version": "1.1.9",+ "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.9.tgz",+ "integrity": "sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.4",+ "define-properties": "^1.2.1",+ "es-object-atoms": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/object.fromentries": {+ "version": "2.0.8",+ "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz",+ "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.2",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/object.groupby": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz",+ "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/object.values": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.1.tgz",+ "integrity": "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.3",+ "define-properties": "^1.2.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/oniguruma-to-es": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-2.3.0.tgz",+ "integrity": "sha512-bwALDxriqfKGfUufKGGepCzu9x7nJQuoRoAFp4AnwehhC2crqrDIAP/uN2qdlsAvSMpeRC3+Yzhqc7hLmle5+g==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex-xs": "^1.0.0",+ "regex": "^5.1.1",+ "regex-recursion": "^5.1.1"+ }+ },+ "node_modules/optionator": {+ "version": "0.9.4",+ "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",+ "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "deep-is": "^0.1.3",+ "fast-levenshtein": "^2.0.6",+ "levn": "^0.4.1",+ "prelude-ls": "^1.2.1",+ "type-check": "^0.4.0",+ "word-wrap": "^1.2.5"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/own-keys": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz",+ "integrity": "sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "get-intrinsic": "^1.2.6",+ "object-keys": "^1.1.1",+ "safe-push-apply": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/p-limit": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "yocto-queue": "^0.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/p-locate": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",+ "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "p-limit": "^3.0.2"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/package-manager-detector": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.6.0.tgz",+ "integrity": "sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==",+ "license": "MIT"+ },+ "node_modules/parent-module": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",+ "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "callsites": "^3.0.0"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/parse-entities": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",+ "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^2.0.0",+ "character-entities-legacy": "^3.0.0",+ "character-reference-invalid": "^2.0.0",+ "decode-named-character-reference": "^1.0.0",+ "is-alphanumerical": "^2.0.0",+ "is-decimal": "^2.0.0",+ "is-hexadecimal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/parse-entities/node_modules/@types/unist": {+ "version": "2.0.11",+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",+ "license": "MIT"+ },+ "node_modules/path-data-parser": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/path-data-parser/-/path-data-parser-0.1.0.tgz",+ "integrity": "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==",+ "license": "MIT"+ },+ "node_modules/path-exists": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-parse": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",+ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "license": "MIT"+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",+ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/pkg-types": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz",+ "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==",+ "license": "MIT",+ "dependencies": {+ "confbox": "^0.1.8",+ "mlly": "^1.7.4",+ "pathe": "^2.0.1"+ }+ },+ "node_modules/points-on-curve": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/points-on-curve/-/points-on-curve-0.2.0.tgz",+ "integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==",+ "license": "MIT"+ },+ "node_modules/points-on-path": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/points-on-path/-/points-on-path-0.2.1.tgz",+ "integrity": "sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==",+ "license": "MIT",+ "dependencies": {+ "path-data-parser": "0.1.0",+ "points-on-curve": "0.2.0"+ }+ },+ "node_modules/possible-typed-array-names": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",+ "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/postcss": {+ "version": "8.5.8",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz",+ "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.11",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/postcss-selector-parser": {+ "version": "6.0.10",+ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz",+ "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cssesc": "^3.0.0",+ "util-deprecate": "^1.0.2"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/prelude-ls": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",+ "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/prop-types": {+ "version": "15.8.1",+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",+ "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",+ "license": "MIT",+ "dependencies": {+ "loose-envify": "^1.4.0",+ "object-assign": "^4.1.1",+ "react-is": "^16.13.1"+ }+ },+ "node_modules/property-information": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",+ "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/punycode": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/queue-microtask": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",+ "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/react": {+ "version": "19.2.4",+ "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz",+ "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/react-dom": {+ "version": "19.2.4",+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz",+ "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==",+ "license": "MIT",+ "dependencies": {+ "scheduler": "^0.27.0"+ },+ "peerDependencies": {+ "react": "^19.2.4"+ }+ },+ "node_modules/react-is": {+ "version": "16.13.1",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",+ "license": "MIT"+ },+ "node_modules/react-remove-scroll": {+ "version": "2.7.2",+ "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",+ "integrity": "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==",+ "license": "MIT",+ "dependencies": {+ "react-remove-scroll-bar": "^2.3.7",+ "react-style-singleton": "^2.2.3",+ "tslib": "^2.1.0",+ "use-callback-ref": "^1.3.3",+ "use-sidecar": "^1.1.3"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/react-remove-scroll-bar": {+ "version": "2.3.8",+ "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.8.tgz",+ "integrity": "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==",+ "license": "MIT",+ "dependencies": {+ "react-style-singleton": "^2.2.2",+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/react-smooth": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz",+ "integrity": "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==",+ "license": "MIT",+ "dependencies": {+ "fast-equals": "^5.0.1",+ "prop-types": "^15.8.1",+ "react-transition-group": "^4.4.5"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/react-style-singleton": {+ "version": "2.2.3",+ "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz",+ "integrity": "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==",+ "license": "MIT",+ "dependencies": {+ "get-nonce": "^1.0.0",+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/react-transition-group": {+ "version": "4.4.5",+ "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz",+ "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@babel/runtime": "^7.5.5",+ "dom-helpers": "^5.0.1",+ "loose-envify": "^1.4.0",+ "prop-types": "^15.6.2"+ },+ "peerDependencies": {+ "react": ">=16.6.0",+ "react-dom": ">=16.6.0"+ }+ },+ "node_modules/recharts": {+ "version": "2.15.4",+ "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.4.tgz",+ "integrity": "sha512-UT/q6fwS3c1dHbXv2uFgYJ9BMFHu3fwnd7AYZaEQhXuYQ4hgsxLvsUXzGdKeZrW5xopzDCvuA2N41WJ88I7zIw==",+ "license": "MIT",+ "dependencies": {+ "clsx": "^2.0.0",+ "eventemitter3": "^4.0.1",+ "lodash": "^4.17.21",+ "react-is": "^18.3.1",+ "react-smooth": "^4.0.4",+ "recharts-scale": "^0.4.4",+ "tiny-invariant": "^1.3.1",+ "victory-vendor": "^36.6.8"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "react": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/recharts-scale": {+ "version": "0.4.5",+ "resolved": "https://registry.npmjs.org/recharts-scale/-/recharts-scale-0.4.5.tgz",+ "integrity": "sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w==",+ "license": "MIT",+ "dependencies": {+ "decimal.js-light": "^2.4.1"+ }+ },+ "node_modules/recharts/node_modules/react-is": {+ "version": "18.3.1",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",+ "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",+ "license": "MIT"+ },+ "node_modules/recma-build-jsx": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/recma-build-jsx/-/recma-build-jsx-1.0.0.tgz",+ "integrity": "sha512-8GtdyqaBcDfva+GUKDr3nev3VpKAhup1+RvkMvUxURHpW7QyIvk9F5wz7Vzo06CEMSilw6uArgRqhpiUcWp8ew==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "estree-util-build-jsx": "^3.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/recma-jsx": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/recma-jsx/-/recma-jsx-1.0.1.tgz",+ "integrity": "sha512-huSIy7VU2Z5OLv6oFLosQGGDqPqdO1iq6bWNAdhzMxSJP7RAso4fCZ1cKu8j9YHCZf3TPrq4dw3okhrylgcd7w==",+ "license": "MIT",+ "dependencies": {+ "acorn-jsx": "^5.0.0",+ "estree-util-to-js": "^2.0.0",+ "recma-parse": "^1.0.0",+ "recma-stringify": "^1.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ },+ "peerDependencies": {+ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"+ }+ },+ "node_modules/recma-parse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/recma-parse/-/recma-parse-1.0.0.tgz",+ "integrity": "sha512-OYLsIGBB5Y5wjnSnQW6t3Xg7q3fQ7FWbw/vcXtORTnyaSFscOtABg+7Pnz6YZ6c27fG1/aN8CjfwoUEUIdwqWQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "esast-util-from-js": "^2.0.0",+ "unified": "^11.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/recma-stringify": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/recma-stringify/-/recma-stringify-1.0.0.tgz",+ "integrity": "sha512-cjwII1MdIIVloKvC9ErQ+OgAtwHBmcZ0Bg4ciz78FtbT8In39aAYbaA7zvxQ61xVMSPE8WxhLwLbhif4Js2C+g==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "estree-util-to-js": "^2.0.0",+ "unified": "^11.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/reflect.getprototypeof": {+ "version": "1.0.10",+ "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",+ "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.9",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.0.0",+ "get-intrinsic": "^1.2.7",+ "get-proto": "^1.0.1",+ "which-builtin-type": "^1.2.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/regex": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/regex/-/regex-5.1.1.tgz",+ "integrity": "sha512-dN5I359AVGPnwzJm2jN1k0W9LPZ+ePvoOeVMMfqIMFz53sSwXkxaJoxr50ptnsC771lK95BnTrVSZxq0b9yCGw==",+ "license": "MIT",+ "dependencies": {+ "regex-utilities": "^2.3.0"+ }+ },+ "node_modules/regex-recursion": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-5.1.1.tgz",+ "integrity": "sha512-ae7SBCbzVNrIjgSbh7wMznPcQel1DNlDtzensnFxpiNpXt1U2ju/bHugH422r+4LAVS1FpW1YCwilmnNsjum9w==",+ "license": "MIT",+ "dependencies": {+ "regex": "^5.1.1",+ "regex-utilities": "^2.3.0"+ }+ },+ "node_modules/regex-utilities": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz",+ "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==",+ "license": "MIT"+ },+ "node_modules/regexp.prototype.flags": {+ "version": "1.5.4",+ "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz",+ "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "define-properties": "^1.2.1",+ "es-errors": "^1.3.0",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "set-function-name": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/rehype-recma": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/rehype-recma/-/rehype-recma-1.0.0.tgz",+ "integrity": "sha512-lqA4rGUf1JmacCNWWZx0Wv1dHqMwxzsDWYMTowuplHF3xH0N/MmrZ/G3BDZnzAkRmxDadujCjaKM2hqYdCBOGw==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/hast": "^3.0.0",+ "hast-util-to-estree": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-mdx": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/remark-mdx/-/remark-mdx-3.1.1.tgz",+ "integrity": "sha512-Pjj2IYlUY3+D8x00UJsIOg5BEvfMyeI+2uLPn9VO9Wg4MEtN/VTIq2NEJQfde9PnX15KgtHyl9S0BcTnWrIuWg==",+ "license": "MIT",+ "dependencies": {+ "mdast-util-mdx": "^3.0.0",+ "micromark-extension-mdxjs": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-parse": {+ "version": "11.0.0",+ "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",+ "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-rehype": {+ "version": "11.1.2",+ "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz",+ "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "unified": "^11.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/resolve": {+ "version": "1.22.11",+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",+ "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-core-module": "^2.16.1",+ "path-parse": "^1.0.7",+ "supports-preserve-symlinks-flag": "^1.0.0"+ },+ "bin": {+ "resolve": "bin/resolve"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/resolve-from": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",+ "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/resolve-pkg-maps": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",+ "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"+ }+ },+ "node_modules/reusify": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",+ "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "iojs": ">=1.0.0",+ "node": ">=0.10.0"+ }+ },+ "node_modules/robust-predicates": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.2.tgz",+ "integrity": "sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg==",+ "license": "Unlicense"+ },+ "node_modules/roughjs": {+ "version": "4.6.6",+ "resolved": "https://registry.npmjs.org/roughjs/-/roughjs-4.6.6.tgz",+ "integrity": "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==",+ "license": "MIT",+ "dependencies": {+ "hachure-fill": "^0.5.2",+ "path-data-parser": "^0.1.0",+ "points-on-curve": "^0.2.0",+ "points-on-path": "^0.2.1"+ }+ },+ "node_modules/run-parallel": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",+ "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "queue-microtask": "^1.2.2"+ }+ },+ "node_modules/rw": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",+ "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==",+ "license": "BSD-3-Clause"+ },+ "node_modules/safe-array-concat": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.3.tgz",+ "integrity": "sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.2",+ "get-intrinsic": "^1.2.6",+ "has-symbols": "^1.1.0",+ "isarray": "^2.0.5"+ },+ "engines": {+ "node": ">=0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/safe-push-apply": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz",+ "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "isarray": "^2.0.5"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/safe-regex-test": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz",+ "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "is-regex": "^1.2.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },+ "node_modules/scheduler": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",+ "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",+ "license": "MIT"+ },+ "node_modules/semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "devOptional": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/set-function-length": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",+ "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-data-property": "^1.1.4",+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2",+ "get-intrinsic": "^1.2.4",+ "gopd": "^1.0.1",+ "has-property-descriptors": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/set-function-name": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz",+ "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-data-property": "^1.1.4",+ "es-errors": "^1.3.0",+ "functions-have-names": "^1.2.3",+ "has-property-descriptors": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/set-proto": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz",+ "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/sharp": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",+ "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==",+ "hasInstallScript": true,+ "license": "Apache-2.0",+ "optional": true,+ "dependencies": {+ "@img/colour": "^1.0.0",+ "detect-libc": "^2.1.2",+ "semver": "^7.7.3"+ },+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-darwin-arm64": "0.34.5",+ "@img/sharp-darwin-x64": "0.34.5",+ "@img/sharp-libvips-darwin-arm64": "1.2.4",+ "@img/sharp-libvips-darwin-x64": "1.2.4",+ "@img/sharp-libvips-linux-arm": "1.2.4",+ "@img/sharp-libvips-linux-arm64": "1.2.4",+ "@img/sharp-libvips-linux-ppc64": "1.2.4",+ "@img/sharp-libvips-linux-riscv64": "1.2.4",+ "@img/sharp-libvips-linux-s390x": "1.2.4",+ "@img/sharp-libvips-linux-x64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4",+ "@img/sharp-linux-arm": "0.34.5",+ "@img/sharp-linux-arm64": "0.34.5",+ "@img/sharp-linux-ppc64": "0.34.5",+ "@img/sharp-linux-riscv64": "0.34.5",+ "@img/sharp-linux-s390x": "0.34.5",+ "@img/sharp-linux-x64": "0.34.5",+ "@img/sharp-linuxmusl-arm64": "0.34.5",+ "@img/sharp-linuxmusl-x64": "0.34.5",+ "@img/sharp-wasm32": "0.34.5",+ "@img/sharp-win32-arm64": "0.34.5",+ "@img/sharp-win32-ia32": "0.34.5",+ "@img/sharp-win32-x64": "0.34.5"+ }+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shiki": {+ "version": "1.29.2",+ "resolved": "https://registry.npmjs.org/shiki/-/shiki-1.29.2.tgz",+ "integrity": "sha512-njXuliz/cP+67jU2hukkxCNuH1yUi4QfdZZY+sMr5PPrIyXSu5iTb/qYC4BiWWB0vZ+7TbdvYUCeL23zpwCfbg==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/core": "1.29.2",+ "@shikijs/engine-javascript": "1.29.2",+ "@shikijs/engine-oniguruma": "1.29.2",+ "@shikijs/langs": "1.29.2",+ "@shikijs/themes": "1.29.2",+ "@shikijs/types": "1.29.2",+ "@shikijs/vscode-textmate": "^10.0.1",+ "@types/hast": "^3.0.4"+ }+ },+ "node_modules/side-channel": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3",+ "side-channel-list": "^1.0.0",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",+ "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/sonner": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.7.tgz",+ "integrity": "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc",+ "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ }+ },+ "node_modules/source-map": {+ "version": "0.7.6",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz",+ "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/space-separated-tokens": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",+ "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/stable-hash": {+ "version": "0.0.5",+ "resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.5.tgz",+ "integrity": "sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/stop-iteration-iterator": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz",+ "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "internal-slot": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/string.prototype.includes": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/string.prototype.includes/-/string.prototype.includes-2.0.1.tgz",+ "integrity": "sha512-o7+c9bW6zpAdJHTtujeePODAhkuicdAryFsfVKwA+wGw89wJ4GTY484WTucM9hLtDEOpOvI+aHnzqnC5lHp4Rg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.3"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/string.prototype.matchall": {+ "version": "4.0.12",+ "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz",+ "integrity": "sha512-6CC9uyBL+/48dYizRf7H7VAYCMCNTBeM78x/VTUe9bFEaxBepPJDa1Ow99LqI/1yF7kuy7Q3cQsYMrcjGUcskA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.3",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.6",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.0.0",+ "get-intrinsic": "^1.2.6",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "internal-slot": "^1.1.0",+ "regexp.prototype.flags": "^1.5.3",+ "set-function-name": "^2.0.2",+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/string.prototype.repeat": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/string.prototype.repeat/-/string.prototype.repeat-1.0.0.tgz",+ "integrity": "sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "define-properties": "^1.1.3",+ "es-abstract": "^1.17.5"+ }+ },+ "node_modules/string.prototype.trim": {+ "version": "1.2.10",+ "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.10.tgz",+ "integrity": "sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.2",+ "define-data-property": "^1.1.4",+ "define-properties": "^1.2.1",+ "es-abstract": "^1.23.5",+ "es-object-atoms": "^1.0.0",+ "has-property-descriptors": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/string.prototype.trimend": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.9.tgz",+ "integrity": "sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.2",+ "define-properties": "^1.2.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/string.prototype.trimstart": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz",+ "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "define-properties": "^1.2.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/stringify-entities": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",+ "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",+ "license": "MIT",+ "dependencies": {+ "character-entities-html4": "^2.0.0",+ "character-entities-legacy": "^3.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/strip-bom": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",+ "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/strip-json-comments": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",+ "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/style-to-js": {+ "version": "1.1.21",+ "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz",+ "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==",+ "license": "MIT",+ "dependencies": {+ "style-to-object": "1.0.14"+ }+ },+ "node_modules/style-to-object": {+ "version": "1.0.14",+ "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz",+ "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==",+ "license": "MIT",+ "dependencies": {+ "inline-style-parser": "0.2.7"+ }+ },+ "node_modules/styled-jsx": {+ "version": "5.1.6",+ "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz",+ "integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==",+ "license": "MIT",+ "dependencies": {+ "client-only": "0.0.1"+ },+ "engines": {+ "node": ">= 12.0.0"+ },+ "peerDependencies": {+ "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0"+ },+ "peerDependenciesMeta": {+ "@babel/core": {+ "optional": true+ },+ "babel-plugin-macros": {+ "optional": true+ }+ }+ },+ "node_modules/stylis": {+ "version": "4.3.6",+ "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.3.6.tgz",+ "integrity": "sha512-yQ3rwFWRfwNUY7H5vpU0wfdkNSnvnJinhF9830Swlaxl03zsOjCfmX0ugac+3LtK0lYSgwL/KXc8oYL3mG4YFQ==",+ "license": "MIT"+ },+ "node_modules/supports-color": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "has-flag": "^4.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/supports-preserve-symlinks-flag": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",+ "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/swr": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/swr/-/swr-2.4.1.tgz",+ "integrity": "sha512-2CC6CiKQtEwaEeNiqWTAw9PGykW8SR5zZX8MZk6TeAvEAnVS7Visz8WzphqgtQ8v2xz/4Q5K+j+SeMaKXeeQIA==",+ "license": "MIT",+ "dependencies": {+ "dequal": "^2.0.3",+ "use-sync-external-store": "^1.6.0"+ },+ "peerDependencies": {+ "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/tailwind-merge": {+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.1.tgz",+ "integrity": "sha512-Oo6tHdpZsGpkKG88HJ8RR1rg/RdnEkQEfMoEk2x1XRI3F1AxeU+ijRXpiVUF4UbLfcxxRGw6TbUINKYdWVsQTQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/dcastil"+ }+ },+ "node_modules/tailwindcss": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.2.2.tgz",+ "integrity": "sha512-KWBIxs1Xb6NoLdMVqhbhgwZf2PGBpPEiwOqgI4pFIYbNTfBXiKYyWoTsXgBQ9WFg/OlhnvHaY+AEpW7wSmFo2Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tapable": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.0.tgz",+ "integrity": "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ }+ },+ "node_modules/tiny-invariant": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",+ "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",+ "license": "MIT"+ },+ "node_modules/tinyexec": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.4.tgz",+ "integrity": "sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tinyglobby": {+ "version": "0.2.15",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.3"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/to-regex-range": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-number": "^7.0.0"+ },+ "engines": {+ "node": ">=8.0"+ }+ },+ "node_modules/trim-lines": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",+ "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/trough": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz",+ "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/ts-api-utils": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",+ "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18.12"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4"+ }+ },+ "node_modules/ts-dedent": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz",+ "integrity": "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6.10"+ }+ },+ "node_modules/tsconfig-paths": {+ "version": "3.15.0",+ "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz",+ "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/json5": "^0.0.29",+ "json5": "^1.0.2",+ "minimist": "^1.2.6",+ "strip-bom": "^3.0.0"+ }+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD"+ },+ "node_modules/type-check": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",+ "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "prelude-ls": "^1.2.1"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/typed-array-buffer": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz",+ "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "es-errors": "^1.3.0",+ "is-typed-array": "^1.1.14"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/typed-array-byte-length": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz",+ "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.8",+ "for-each": "^0.3.3",+ "gopd": "^1.2.0",+ "has-proto": "^1.2.0",+ "is-typed-array": "^1.1.14"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/typed-array-byte-offset": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.4.tgz",+ "integrity": "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "available-typed-arrays": "^1.0.7",+ "call-bind": "^1.0.8",+ "for-each": "^0.3.3",+ "gopd": "^1.2.0",+ "has-proto": "^1.2.0",+ "is-typed-array": "^1.1.15",+ "reflect.getprototypeof": "^1.0.9"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/typed-array-length": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.7.tgz",+ "integrity": "sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind": "^1.0.7",+ "for-each": "^0.3.3",+ "gopd": "^1.0.1",+ "is-typed-array": "^1.1.13",+ "possible-typed-array-names": "^1.0.0",+ "reflect.getprototypeof": "^1.0.6"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/ufo": {+ "version": "1.6.3",+ "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.3.tgz",+ "integrity": "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==",+ "license": "MIT"+ },+ "node_modules/unbox-primitive": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz",+ "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.3",+ "has-bigints": "^1.0.2",+ "has-symbols": "^1.1.0",+ "which-boxed-primitive": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/unified": {+ "version": "11.0.5",+ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",+ "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "bail": "^2.0.0",+ "devlop": "^1.0.0",+ "extend": "^3.0.0",+ "is-plain-obj": "^4.0.0",+ "trough": "^2.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-is": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz",+ "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-position": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz",+ "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-position-from-estree": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-position-from-estree/-/unist-util-position-from-estree-2.0.0.tgz",+ "integrity": "sha512-KaFVRjoqLyF6YXCbVLNad/eS4+OfPQQn2yOd7zF/h5T/CSL2v8NpN6a5TPvtbXthAGw5nG+PuTtq+DdIZr+cRQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-remove": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/unist-util-remove/-/unist-util-remove-3.1.1.tgz",+ "integrity": "sha512-kfCqZK5YVY5yEa89tvpl7KnBBHu2c6CzMkqHUrlOqaRgGOMp0sMvwWOVrbAtj03KhovQB7i96Gda72v/EFE0vw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^2.0.0",+ "unist-util-is": "^5.0.0",+ "unist-util-visit-parents": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-remove/node_modules/@types/unist": {+ "version": "2.0.11",+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",+ "license": "MIT"+ },+ "node_modules/unist-util-remove/node_modules/unist-util-is": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-5.2.1.tgz",+ "integrity": "sha512-u9njyyfEh43npf1M+yGKDGVPbY/JWEemg5nH05ncKPfi+kBbKBJoTdsogMu33uhytuLlv9y0O7GH7fEdwLdLQw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-stringify-position": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",+ "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz",+ "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0",+ "unist-util-visit-parents": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit-parents": {+ "version": "5.1.3",+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-5.1.3.tgz",+ "integrity": "sha512-x6+y8g7wWMyQhL1iZfhIPhDAs7Xwbn9nRosDXl7qoPTSCy0yNxnKc+hWokFifWQIDGi154rdUqKvbCa4+1kLhg==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^2.0.0",+ "unist-util-is": "^5.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit-parents/node_modules/@types/unist": {+ "version": "2.0.11",+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",+ "license": "MIT"+ },+ "node_modules/unist-util-visit-parents/node_modules/unist-util-is": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-5.2.1.tgz",+ "integrity": "sha512-u9njyyfEh43npf1M+yGKDGVPbY/JWEemg5nH05ncKPfi+kBbKBJoTdsogMu33uhytuLlv9y0O7GH7fEdwLdLQw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit/node_modules/unist-util-visit-parents": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",+ "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unrs-resolver": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.11.1.tgz",+ "integrity": "sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "napi-postinstall": "^0.3.0"+ },+ "funding": {+ "url": "https://opencollective.com/unrs-resolver"+ },+ "optionalDependencies": {+ "@unrs/resolver-binding-android-arm-eabi": "1.11.1",+ "@unrs/resolver-binding-android-arm64": "1.11.1",+ "@unrs/resolver-binding-darwin-arm64": "1.11.1",+ "@unrs/resolver-binding-darwin-x64": "1.11.1",+ "@unrs/resolver-binding-freebsd-x64": "1.11.1",+ "@unrs/resolver-binding-linux-arm-gnueabihf": "1.11.1",+ "@unrs/resolver-binding-linux-arm-musleabihf": "1.11.1",+ "@unrs/resolver-binding-linux-arm64-gnu": "1.11.1",+ "@unrs/resolver-binding-linux-arm64-musl": "1.11.1",+ "@unrs/resolver-binding-linux-ppc64-gnu": "1.11.1",+ "@unrs/resolver-binding-linux-riscv64-gnu": "1.11.1",+ "@unrs/resolver-binding-linux-riscv64-musl": "1.11.1",+ "@unrs/resolver-binding-linux-s390x-gnu": "1.11.1",+ "@unrs/resolver-binding-linux-x64-gnu": "1.11.1",+ "@unrs/resolver-binding-linux-x64-musl": "1.11.1",+ "@unrs/resolver-binding-wasm32-wasi": "1.11.1",+ "@unrs/resolver-binding-win32-arm64-msvc": "1.11.1",+ "@unrs/resolver-binding-win32-ia32-msvc": "1.11.1",+ "@unrs/resolver-binding-win32-x64-msvc": "1.11.1"+ }+ },+ "node_modules/uri-js": {+ "version": "4.4.1",+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "punycode": "^2.1.0"+ }+ },+ "node_modules/use-callback-ref": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz",+ "integrity": "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/use-sidecar": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.3.tgz",+ "integrity": "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==",+ "license": "MIT",+ "dependencies": {+ "detect-node-es": "^1.1.0",+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/use-sync-external-store": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",+ "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/uuid": {+ "version": "11.1.0",+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",+ "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",+ "funding": [+ "https://github.com/sponsors/broofa",+ "https://github.com/sponsors/ctavan"+ ],+ "license": "MIT",+ "bin": {+ "uuid": "dist/esm/bin/uuid"+ }+ },+ "node_modules/vfile": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",+ "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/vfile-matter": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/vfile-matter/-/vfile-matter-5.0.1.tgz",+ "integrity": "sha512-o6roP82AiX0XfkyTHyRCMXgHfltUNlXSEqCIS80f+mbAyiQBE2fxtDVMtseyytGx75sihiJFo/zR6r/4LTs2Cw==",+ "license": "MIT",+ "dependencies": {+ "vfile": "^6.0.0",+ "yaml": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/vfile-message": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz",+ "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-stringify-position": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/victory-vendor": {+ "version": "36.9.2",+ "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz",+ "integrity": "sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==",+ "license": "MIT AND ISC",+ "dependencies": {+ "@types/d3-array": "^3.0.3",+ "@types/d3-ease": "^3.0.0",+ "@types/d3-interpolate": "^3.0.1",+ "@types/d3-scale": "^4.0.2",+ "@types/d3-shape": "^3.1.0",+ "@types/d3-time": "^3.0.0",+ "@types/d3-timer": "^3.0.0",+ "d3-array": "^3.1.6",+ "d3-ease": "^3.0.1",+ "d3-interpolate": "^3.0.1",+ "d3-scale": "^4.0.2",+ "d3-shape": "^3.1.0",+ "d3-time": "^3.0.0",+ "d3-timer": "^3.0.1"+ }+ },+ "node_modules/vscode-jsonrpc": {+ "version": "8.2.0",+ "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz",+ "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==",+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/vscode-languageserver": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-9.0.1.tgz",+ "integrity": "sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==",+ "license": "MIT",+ "dependencies": {+ "vscode-languageserver-protocol": "3.17.5"+ },+ "bin": {+ "installServerIntoExtension": "bin/installServerIntoExtension"+ }+ },+ "node_modules/vscode-languageserver-protocol": {+ "version": "3.17.5",+ "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz",+ "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==",+ "license": "MIT",+ "dependencies": {+ "vscode-jsonrpc": "8.2.0",+ "vscode-languageserver-types": "3.17.5"+ }+ },+ "node_modules/vscode-languageserver-textdocument": {+ "version": "1.0.12",+ "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz",+ "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==",+ "license": "MIT"+ },+ "node_modules/vscode-languageserver-types": {+ "version": "3.17.5",+ "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz",+ "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==",+ "license": "MIT"+ },+ "node_modules/vscode-uri": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz",+ "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==",+ "license": "MIT"+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/which-boxed-primitive": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz",+ "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-bigint": "^1.1.0",+ "is-boolean-object": "^1.2.1",+ "is-number-object": "^1.1.1",+ "is-string": "^1.1.1",+ "is-symbol": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/which-builtin-type": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz",+ "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "function.prototype.name": "^1.1.6",+ "has-tostringtag": "^1.0.2",+ "is-async-function": "^2.0.0",+ "is-date-object": "^1.1.0",+ "is-finalizationregistry": "^1.1.0",+ "is-generator-function": "^1.0.10",+ "is-regex": "^1.2.1",+ "is-weakref": "^1.0.2",+ "isarray": "^2.0.5",+ "which-boxed-primitive": "^1.1.0",+ "which-collection": "^1.0.2",+ "which-typed-array": "^1.1.16"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/which-collection": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz",+ "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-map": "^2.0.3",+ "is-set": "^2.0.3",+ "is-weakmap": "^2.0.2",+ "is-weakset": "^2.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/which-typed-array": {+ "version": "1.1.20",+ "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.20.tgz",+ "integrity": "sha512-LYfpUkmqwl0h9A2HL09Mms427Q1RZWuOHsukfVcKRq9q95iQxdw0ix1JQrqbcDR9PH1QDwf5Qo8OZb5lksZ8Xg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "available-typed-arrays": "^1.0.7",+ "call-bind": "^1.0.8",+ "call-bound": "^1.0.4",+ "for-each": "^0.3.5",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-tostringtag": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/wikicode-web": {+ "resolved": "packages/web",+ "link": true+ },+ "node_modules/word-wrap": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",+ "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/yaml": {+ "version": "2.8.2",+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.2.tgz",+ "integrity": "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==",+ "license": "ISC",+ "bin": {+ "yaml": "bin.mjs"+ },+ "engines": {+ "node": ">= 14.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/eemeli"+ }+ },+ "node_modules/yocto-queue": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/zwitch": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",+ "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "packages/web": {+ "name": "wikicode-web",+ "version": "0.1.0",+ "dependencies": {+ "@radix-ui/react-accordion": "^1.2.0",+ "@radix-ui/react-dialog": "^1.1.0",+ "@radix-ui/react-dropdown-menu": "^2.1.0",+ "@radix-ui/react-label": "^2.1.8",+ "@radix-ui/react-popover": "^1.1.0",+ "@radix-ui/react-progress": "^1.1.8",+ "@radix-ui/react-scroll-area": "^1.2.0",+ "@radix-ui/react-select": "^2.1.0",+ "@radix-ui/react-separator": "^1.1.0",+ "@radix-ui/react-slider": "^1.3.6",+ "@radix-ui/react-slot": "^1.1.0",+ "@radix-ui/react-switch": "^1.2.6",+ "@radix-ui/react-tabs": "^1.1.0",+ "@radix-ui/react-toggle": "^1.1.0",+ "@radix-ui/react-toggle-group": "^1.1.0",+ "@radix-ui/react-tooltip": "^1.1.0",+ "class-variance-authority": "^0.7.1",+ "clsx": "^2.1.1",+ "cmdk": "^1.0.0",+ "d3": "^7.9.0",+ "d3-force": "^3.0.0",+ "d3-hierarchy": "^3.1.2",+ "framer-motion": "^11.11.0",+ "fuse.js": "^7.0.0",+ "geist": "^1.3.0",+ "lucide-react": "^0.460.0",+ "mermaid": "^11.4.0",+ "next": "^15.2.4",+ "next-mdx-remote": "^5.0.0",+ "nuqs": "^2.2.0",+ "react": "^19.0.0",+ "react-dom": "^19.0.0",+ "recharts": "^2.13.0",+ "shiki": "^1.22.0",+ "sonner": "^2.0.7",+ "swr": "^2.2.5",+ "tailwind-merge": "^2.5.4"+ },+ "devDependencies": {+ "@tailwindcss/postcss": "^4.0.0",+ "@tailwindcss/typography": "^0.5.15",+ "@types/d3": "^7.4.3",+ "@types/node": "^22",+ "@types/react": "^19",+ "@types/react-dom": "^19",+ "eslint": "^9",+ "eslint-config-next": "^15.2.4",+ "tailwindcss": "^4.0.0",+ "typescript": "^5.7"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ }+ }+}diff --git a/package.json b/package.jsonnew file mode 100644index 000000000..2a4f22f18--- /dev/null+++ b/package.json@@ -0,0 +1,18 @@+{+ "name": "wikicode-root",+ "version": "0.1.0",+ "private": true,+ "description": "Root workspace configuration for WikiCode monorepo",+ "workspaces": [+ "packages/web"+ ],+ "scripts": {+ "dev": "cd packages/web && npm run dev",+ "build": "cd packages/web && npm run build",+ "lint": "cd packages/web && npm run lint",+ "type-check": "cd packages/web && npm run type-check"+ },+ "engines": {+ "node": ">=20.0.0"+ }+}diff --git a/packages/cli/README.md b/packages/cli/README.mdnew file mode 100644index 000000000..731775add--- /dev/null+++ b/packages/cli/README.md@@ -0,0 +1,405 @@+# wikicode-cli++Command-line interface for WikiCode — generate, maintain, search, and export AI-powered codebase documentation from your terminal.++**Python >= 3.11 · Apache-2.0**++---++## Installation++```bash+pip install wikicode-cli++# Recommended: use uv+uv pip install wikicode-cli+```++`wikicode-core` is installed automatically as a dependency. The `wikicode` command is available immediately after installation.++---++## Quick Start++```bash+# 1. Generate documentation for the first time+cd /path/to/your/repo+wikicode init --provider anthropic++# 2. Check what was generated+wikicode status++# 3. Keep docs in sync after commits+wikicode update++# 4. Search the wiki+wikicode search "authentication flow"++# 5. Start the web UI+wikicode serve+```++All data is stored in a `.wikicode/` directory at the root of your repository.++---++## Commands++### `wikicode init`++Generate full wiki documentation from scratch. This is the expensive, one-time operation — it traverses every file, builds the dependency graph, and calls the LLM to generate all wiki pages in dependency order. It is resumable: if interrupted, re-run with `--resume`.++```+wikicode init [PATH] [OPTIONS]+```++| Option | Default | Description |+|--------|---------|-------------|+| `--provider` | `anthropic` | LLM provider: `anthropic`, `openai`, `ollama`, `litellm` |+| `--model` | provider default | Model identifier (e.g., `claude-opus-4-6`, `gpt-4o`) |+| `--concurrency` | `5` | Max simultaneous LLM calls |+| `--skip-tests` | off | Skip test files during generation |+| `--resume` | off | Resume an interrupted init job from last checkpoint |+| `--dry-run` | off | Show generation plan and cost estimate without calling the LLM |+| `--no-batch` | off | Disable Anthropic batch API (faster wall-clock time, higher cost) |++```bash+# Current directory, Anthropic (default)+wikicode init++# Specific path and provider+wikicode init /path/to/repo --provider openai --model gpt-4o++# Fully offline with Ollama+wikicode init --provider ollama --model llama3.2++# Preview cost before spending tokens+wikicode init --dry-run++# Resume after an interruption+wikicode init --resume+```++**Batch API:** When using the Anthropic provider, `wikicode init` uses the Message Batches API by default, which reduces cost by ~50%. Pass `--no-batch` to use streaming instead (returns results immediately, costs more).++**Prompt caching:** The Anthropic provider caches the shared system prompt and repository context across all generation calls. On large repos, this typically cuts cost by 60–90%.++---++### `wikicode update`++Incrementally regenerate wiki pages for files changed since the last sync. Uses git diff to detect what changed and propagates changes through the dependency graph — only pages that actually need updating are regenerated.++```+wikicode update [PATH] [OPTIONS]+```++| Option | Default | Description |+|--------|---------|-------------|+| `--provider` | last used | LLM provider |+| `--model` | provider default | Model override |+| `--since` | last sync commit | Base git ref to diff from (overrides saved state) |+| `--cascade-budget` | `30` | Max pages to regenerate per run |+| `--dry-run` | off | Show affected pages without regenerating |++```bash+# Update current repo (diffs HEAD against last sync commit)+wikicode update++# Preview what would be regenerated+wikicode update --dry-run++# Diff from a specific branch or commit+wikicode update --since main+wikicode update --since a1b2c3d+```++`wikicode update` requires that `wikicode init` has been run first. It reads `last_sync_commit` from `.wikicode/state.json`.++---++### `wikicode watch`++Watch a repository for file changes and automatically run `wikicode update` after a debounce period. Useful during active development.++```+wikicode watch [PATH] [OPTIONS]+```++| Option | Default | Description |+|--------|---------|-------------|+| `--provider` | last used | LLM provider |+| `--model` | provider default | Model override |+| `--debounce` | `2000` | Milliseconds to wait after the last change before updating |++```bash+# Watch current directory+wikicode watch++# Custom debounce (wait 5 seconds after last change)+wikicode watch --debounce 5000+```++Press `Ctrl+C` to stop. Changes to `.wikicode/` are automatically ignored.++---++### `wikicode search`++Search wiki pages by keyword, meaning, or symbol name.++```+wikicode search QUERY [PATH] [OPTIONS]+```++| Option | Default | Description |+|--------|---------|-------------|+| `--mode` | `fulltext` | Search mode: `fulltext`, `semantic`, `symbol` |+| `--limit` | `10` | Maximum results to return |++```bash+# Full-text search (SQLite FTS5)+wikicode search "authentication"++# Semantic / vector search+wikicode search "rate limiting strategy" --mode semantic++# Find a symbol by name+wikicode search "AuthService" --mode symbol+```++`semantic` search requires the `[search]` extra (`pip install "wikicode-core[search]"`).++---++### `wikicode export`++Export all wiki pages to files on disk in Markdown, HTML, or JSON format.++```+wikicode export [PATH] [OPTIONS]+```++| Option | Default | Description |+|--------|---------|-------------|+| `--format` | `markdown` | Output format: `markdown`, `html`, `json` |+| `--output`, `-o` | `.wikicode/export` | Output directory |++```bash+# Export as Markdown to .wikicode/export/+wikicode export++# Export as JSON to a custom directory+wikicode export --format json -o ./wiki-export++# Export as HTML+wikicode export --format html -o ./docs/wiki+```++The JSON output is a single `wiki_pages.json` file with all pages as an array. Markdown and HTML outputs write one file per page.++---++### `wikicode status`++Show sync state, page counts by type, and total token consumption.++```+wikicode status [PATH]+```++Displays:++- Last sync commit hash+- Provider and model used for the last init/update+- Total token consumption (input + output)+- Page count broken down by type (`file_page`, `module_page`, `symbol_spotlight`, etc.)++---++### `wikicode doctor`++Run health checks on the wiki setup. Useful for debugging why `init` or `update` is failing.++```+wikicode doctor [PATH]+```++Checks performed:++| Check | What it verifies |+|-------|-----------------|+| Git repository | The path is inside a git repo |+| `.wikicode/` directory | The init directory exists |+| Database | `wiki.db` is connectable; shows page count |+| `state.json` | Valid JSON with a `last_sync_commit` entry |+| Providers | At least one LLM provider is importable |+| Stale pages | Number of pages whose source has changed since generation |++Exits with a summary of passed/failed checks.++---++### `wikicode dead-code`++Detect dead and unused code using the dependency graph. Does not call an LLM — purely graph analysis and git metadata.++```+wikicode dead-code [PATH] [OPTIONS]+```++| Option | Default | Description |+|--------|---------|-------------|+| `--min-confidence` | `0.4` | Minimum confidence threshold (0.0–1.0) |+| `--safe-only` | off | Only show findings marked as safe to delete |+| `--kind` | all | Filter: `unreachable_file`, `unused_export`, `unused_internal`, `zombie_package` |+| `--format` | `table` | Output: `table`, `json`, `md` |++```bash+# All findings, table format+wikicode dead-code++# Only safe-to-delete findings+wikicode dead-code --safe-only++# Only unreachable files (no importers in the graph)+wikicode dead-code --kind unreachable_file++# Export to JSON for CI integration+wikicode dead-code --format json > dead-code.json++# High-confidence findings only+wikicode dead-code --min-confidence 0.8+```++Finding kinds:++| Kind | Description |+|------|-------------|+| `unreachable_file` | File has no importers in the dependency graph |+| `unused_export` | Symbol is exported but not imported anywhere |+| `unused_internal` | Symbol is defined but never called within the repo |+| `zombie_package` | Package directory exists but has no live references |++---++### `wikicode serve`++Start the WikiCode REST API and web UI server. Requires `wikicode-server` to be installed.++```+wikicode serve [OPTIONS]+```++| Option | Default | Description |+|--------|---------|-------------|+| `--port` | `7337` | Port to listen on |+| `--host` | `127.0.0.1` | Host to bind to (`0.0.0.0` to expose externally) |+| `--workers` | `1` | Number of uvicorn workers |++```bash+# Start on localhost:7337+wikicode serve++# Expose on all interfaces+wikicode serve --host 0.0.0.0++# Custom port+wikicode serve --port 8080+```++The API docs are available at `http://localhost:7337/docs`. Start the Next.js web UI separately and point `WIKICODE_API_URL` at this server.++---++### `wikicode mcp`++Start the MCP server for AI editor integration (Claude Code, Cursor, Cline).++```+wikicode mcp [PATH] [OPTIONS]+```++| Option | Default | Description |+|--------|---------|-------------|+| `--transport` | `stdio` | Transport protocol: `stdio` (editors) or `sse` (web clients) |+| `--port` | `7338` | Port for SSE transport |++```bash+# stdio transport, current directory (typical editor integration)+wikicode mcp++# Specific repository path+wikicode mcp /path/to/repo++# SSE transport for web clients+wikicode mcp --transport sse+```++Exposes 13 MCP tools for querying wiki pages, symbols, the dependency graph, git analytics, ownership data, hotspots, and dead code findings.++**Claude Code setup** — add to `~/.claude/settings.json`:++```json+{+ "mcpServers": {+ "wikicode": {+ "command": "wikicode",+ "args": ["mcp", "/path/to/your/repo"]+ }+ }+}+```++**Cursor / Cline setup** — add to your MCP configuration file:++```json+{+ "mcpServers": {+ "wikicode": {+ "command": "wikicode",+ "args": ["mcp", "/absolute/path/to/repo"]+ }+ }+}+```++---++## Environment Variables++| Variable | Description |+|----------|-------------|+| `ANTHROPIC_API_KEY` | API key for the Anthropic provider |+| `OPENAI_API_KEY` | API key for the OpenAI provider |+| `WIKICODE_DB_URL` | Override the default SQLite path (e.g., `postgresql://user:pass@host/db`) |+| `WIKICODE_EMBEDDER` | Embedder backend: `mock` (default) or `gemini` |++---++## The `.wikicode/` Directory++After `wikicode init`, your repo will contain:++```+.wikicode/+├── wiki.db # SQLite database — all pages, symbols, jobs, git metadata+├── lancedb/ # LanceDB vector store (if [search] extra is installed)+├── graph.json # Serialized dependency graph (repos < 30K nodes)+├── state.json # Sync state: last_sync_commit, provider, model, token counts+└── export/ # Output directory for `wikicode export`+```++Add `.wikicode/` to your `.gitignore` to avoid committing generated data.++---++## Development++```bash+# Install for development (from repo root)+uv pip install -e packages/cli -e packages/core++# Run tests+pytest tests/unit/cli/+```diff --git a/packages/cli/pyproject.toml b/packages/cli/pyproject.tomlnew file mode 100644index 000000000..01d489732--- /dev/null+++ b/packages/cli/pyproject.toml@@ -0,0 +1,48 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[project]+name = "wikicode-cli"+version = "0.1.0"+description = "WikiCode CLI — generate and maintain codebase documentation from the command line"+readme = "README.md"+requires-python = ">=3.11"+license = { text = "Apache-2.0" }+keywords = ["documentation", "codebase", "wiki", "cli"]+classifiers = [+ "Development Status :: 3 - Alpha",+ "Intended Audience :: Developers",+ "License :: OSI Approved :: Apache Software License",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ "Programming Language :: Python :: 3.13",+ "Environment :: Console",+ "Topic :: Software Development :: Documentation",+]+dependencies = [+ "wikicode-core",+ # CLI framework+ "click>=8.1,<9",+ # Terminal formatting+ "rich>=13,<14",+ # Filesystem watching (for `wikicode watch`)+ "watchdog>=4,<5",+]++[project.scripts]+wikicode = "wikicode.cli.main:cli"++[project.urls]+Homepage = "https://github.com/wikicode-ai/wikicode"+Repository = "https://github.com/wikicode-ai/wikicode"++[tool.hatch.build.targets.wheel]+packages = ["src/wikicode"]++[tool.uv]+package = true++[tool.uv.sources]+wikicode-core = { workspace = true }diff --git a/packages/cli/src/wikicode/cli/__init__.py b/packages/cli/src/wikicode/cli/__init__.pynew file mode 100644index 000000000..cc17e023e--- /dev/null+++ b/packages/cli/src/wikicode/cli/__init__.py@@ -0,0 +1,7 @@+"""WikiCode CLI package.++Entry point: `wikicode` command (defined in wikicode.cli.main).+Built on Click with Rich for terminal output.+"""++__version__ = "0.1.0"diff --git a/packages/cli/src/wikicode/cli/commands/__init__.py b/packages/cli/src/wikicode/cli/commands/__init__.pynew file mode 100644index 000000000..9937ab920--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/__init__.py@@ -0,0 +1 @@+"""CLI command modules."""diff --git a/packages/cli/src/wikicode/cli/commands/dead_code_cmd.py b/packages/cli/src/wikicode/cli/commands/dead_code_cmd.pynew file mode 100644index 000000000..79410fb96--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/dead_code_cmd.py@@ -0,0 +1,143 @@+"""``wikicode dead-code`` — detect dead and unused code."""++from __future__ import annotations++import json++import click+from rich.table import Table++from wikicode.cli.helpers import (+ console,+ resolve_repo_path,+ run_async,+)++[email protected]("dead-code")[email protected]("path", required=False, type=click.Path(exists=True))[email protected]("--min-confidence", default=0.4, type=float, help="Minimum confidence threshold.")[email protected]("--safe-only", is_flag=True, help="Only show safe_to_delete=True findings.")+ "--kind",+ type=click.Choice(["unreachable_file", "unused_export", "unused_internal", "zombie_package"]),+ help="Filter by finding kind.",+)+ "--format",+ "fmt",+ default="table",+ type=click.Choice(["table", "json", "md"]),+ help="Output format.",+)+def dead_code_command(+ path: str | None,+ min_confidence: float,+ safe_only: bool,+ kind: str | None,+ fmt: str,+) -> None:+ """Detect dead and unused code."""+ from pathlib import Path as PathlibPath++ from wikicode.core.analysis.dead_code import DeadCodeAnalyzer+ from wikicode.core.ingestion import ASTParser, FileTraverser, GraphBuilder++ repo_path = resolve_repo_path(path)++ console.print(f"[bold]WikiCode dead-code[/bold] — {repo_path}")++ # Ingest+ traverser = FileTraverser(repo_path)+ file_infos = list(traverser.traverse())+ parser = ASTParser()+ graph_builder = GraphBuilder()++ for fi in file_infos:+ try:+ source = PathlibPath(fi.abs_path).read_bytes()+ parsed = parser.parse_file(fi, source)+ graph_builder.add_file(parsed)+ except Exception:+ pass+ graph_builder.build()++ # Git metadata (best effort)+ git_meta_map: dict = {}+ try:+ from wikicode.core.ingestion.git_indexer import GitIndexer++ git_indexer = GitIndexer(repo_path)+ _, metadata_list = run_async(git_indexer.index_repo(""))+ git_meta_map = {m["file_path"]: m for m in metadata_list}+ except Exception:+ pass++ # Analyze+ config = {"min_confidence": min_confidence}+ if kind:+ # Enable only the requested kind+ config["detect_unreachable_files"] = kind == "unreachable_file"+ config["detect_unused_exports"] = kind == "unused_export"+ config["detect_unused_internals"] = kind == "unused_internal"+ config["detect_zombie_packages"] = kind == "zombie_package"++ analyzer = DeadCodeAnalyzer(graph_builder.graph(), git_meta_map)+ report = analyzer.analyze(config)++ findings = report.findings+ if safe_only:+ findings = [f for f in findings if f.safe_to_delete]++ if fmt == "json":+ output = []+ for f in findings:+ output.append({+ "kind": f.kind.value,+ "file_path": f.file_path,+ "symbol_name": f.symbol_name,+ "confidence": f.confidence,+ "reason": f.reason,+ "safe_to_delete": f.safe_to_delete,+ "lines": f.lines,+ "primary_owner": f.primary_owner,+ })+ click.echo(json.dumps(output, indent=2))+ return++ if fmt == "md":+ click.echo(f"# Dead Code Report\n")+ click.echo(f"**Total findings:** {len(findings)}")+ click.echo(f"**Deletable lines:** {report.deletable_lines}\n")+ for f in findings:+ safe = " (safe to remove)" if f.safe_to_delete else ""+ name = f"`{f.symbol_name}`" if f.symbol_name else f"`{f.file_path}`"+ click.echo(f"- [{f.kind.value}] {name} — {f.reason} ({f.confidence:.0%}){safe}")+ return++ # Table format (default)+ table = Table(title=f"Dead Code ({len(findings)} findings)")+ table.add_column("Kind", style="cyan")+ table.add_column("File / Symbol")+ table.add_column("Confidence", justify="right")+ table.add_column("Safe?", justify="center")+ table.add_column("Lines", justify="right")+ table.add_column("Reason")++ for f in findings:+ name = f.symbol_name or f.file_path+ safe = "[green]✓[/green]" if f.safe_to_delete else "[red]✗[/red]"+ table.add_row(+ f.kind.value,+ name,+ f"{f.confidence:.0%}",+ safe,+ str(f.lines),+ f.reason[:60],+ )++ console.print(table)+ console.print(+ f"\nDeletable lines: [bold]{report.deletable_lines:,}[/bold] "+ f"(confidence: {report.confidence_summary})"+ )diff --git a/packages/cli/src/wikicode/cli/commands/decision_cmd.py b/packages/cli/src/wikicode/cli/commands/decision_cmd.pynew file mode 100644index 000000000..aab455891--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/decision_cmd.py@@ -0,0 +1,489 @@+"""``wikicode decision`` — manage architectural decision records."""++from __future__ import annotations++import json++import click+from rich.panel import Panel+from rich.table import Table++from wikicode.cli.helpers import (+ console,+ ensure_wikicode_dir,+ get_db_url_for_repo,+ resolve_repo_path,+ run_async,+)++[email protected]("decision")+def decision_group() -> None:+ """Manage architectural decision records."""+++# ---------------------------------------------------------------------------+# decision add+# ---------------------------------------------------------------------------+++@decision_group.command("add")[email protected]("path", required=False, default=None)+def decision_add(path: str | None) -> None:+ """Interactively add a new architectural decision."""+ repo_path = resolve_repo_path(path)+ ensure_wikicode_dir(repo_path)++ console.print("[bold]Add Architectural Decision[/bold]\n")++ title = click.prompt("Decision title (short)")+ context = click.prompt("Context (what forced this decision?)", default="")+ decision_text = click.prompt("Decision (what was chosen?)")+ rationale = click.prompt("Rationale (why?)", default="")++ alternatives_raw = click.prompt(+ "Rejected alternatives (comma-separated, optional)", default=""+ )+ alternatives = [a.strip() for a in alternatives_raw.split(",") if a.strip()]++ consequences_raw = click.prompt(+ "Tradeoffs/consequences (comma-separated, optional)", default=""+ )+ consequences = [c.strip() for c in consequences_raw.split(",") if c.strip()]++ affected_raw = click.prompt(+ "Affected files/modules (comma-separated, optional)", default=""+ )+ affected_files = [f.strip() for f in affected_raw.split(",") if f.strip()]++ tags_raw = click.prompt(+ "Tags (comma-separated: auth, database, api, performance, security, infra, testing)",+ default="",+ )+ tags = [t.strip() for t in tags_raw.split(",") if t.strip()]++ async def _persist() -> str:+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_decision,+ upsert_repository,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ repo = await upsert_repository(+ session, name=repo_path.name, local_path=str(repo_path)+ )+ rec = await upsert_decision(+ session,+ repository_id=repo.id,+ title=title,+ status="active",+ context=context,+ decision=decision_text,+ rationale=rationale,+ alternatives=alternatives,+ consequences=consequences,+ affected_files=affected_files,+ affected_modules=[],+ tags=tags,+ source="cli",+ confidence=1.0,+ )+ decision_id = rec.id++ await engine.dispose()+ return decision_id++ decision_id = run_async(_persist())+ console.print(+ f"\n[green]Decision recorded[/green] — ID: [bold]{decision_id[:8]}[/bold]"+ )+++# ---------------------------------------------------------------------------+# decision list+# ---------------------------------------------------------------------------+++@decision_group.command("list")[email protected]("path", required=False, default=None)+ "--status",+ type=click.Choice(["proposed", "active", "deprecated", "superseded", "all"]),+ default="all",+)+ "--source",+ type=click.Choice(["git_archaeology", "inline_marker", "readme_mining", "cli", "all"]),+ default="all",+)[email protected]("--proposed", is_flag=True, default=False, help="Show only proposed decisions.")[email protected]("--stale-only", is_flag=True, default=False, help="Show only stale decisions.")+def decision_list(+ path: str | None,+ status: str,+ source: str,+ proposed: bool,+ stale_only: bool,+) -> None:+ """List architectural decision records."""+ repo_path = resolve_repo_path(path)++ async def _query() -> list:+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ list_decisions,+ upsert_repository,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ repo = await upsert_repository(+ session, name=repo_path.name, local_path=str(repo_path)+ )+ decisions = await list_decisions(+ session,+ repo.id,+ status=status if status != "all" else ("proposed" if proposed else None),+ source=source if source != "all" else None,+ include_proposed=True,+ limit=100,+ )++ await engine.dispose()+ return decisions++ decisions = run_async(_query())++ if proposed:+ decisions = [d for d in decisions if d.status == "proposed"]+ if stale_only:+ decisions = [d for d in decisions if d.staleness_score >= 0.5]++ if not decisions:+ console.print("[dim]No decisions found.[/dim]")+ return++ table = Table(title="Architectural Decisions")+ table.add_column("ID", style="dim", width=8)+ table.add_column("Title", max_width=40)+ table.add_column("Status")+ table.add_column("Source", style="dim")+ table.add_column("Conf.", justify="right")+ table.add_column("Stale", justify="right")+ table.add_column("Created", style="dim")++ status_colors = {+ "active": "green",+ "proposed": "yellow",+ "deprecated": "red",+ "superseded": "dim",+ }++ for d in decisions:+ color = status_colors.get(d.status, "white")+ stale_str = f"{d.staleness_score:.1f}" if d.staleness_score > 0 else "-"+ created = d.created_at.strftime("%Y-%m-%d") if d.created_at else ""+ table.add_row(+ d.id[:8],+ d.title[:40],+ f"[{color}]{d.status}[/{color}]",+ d.source,+ f"{d.confidence:.0%}",+ stale_str,+ created,+ )++ console.print(table)+++# ---------------------------------------------------------------------------+# decision show+# ---------------------------------------------------------------------------+++@decision_group.command("show")[email protected]("decision_id")[email protected]("path", required=False, default=None)+def decision_show(decision_id: str, path: str | None) -> None:+ """Show full details of a decision record."""+ repo_path = resolve_repo_path(path)++ async def _query():+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ get_decision,+ init_db,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ rec = await get_decision(session, decision_id)++ await engine.dispose()+ return rec++ rec = run_async(_query())+ if rec is None:+ console.print(f"[red]Decision not found: {decision_id}[/red]")+ return++ lines = [+ f"[bold]{rec.title}[/bold]",+ f"Status: {rec.status} | Source: {rec.source} | Confidence: {rec.confidence:.0%}",+ f"Staleness: {rec.staleness_score:.2f}",+ "",+ ]+ if rec.context:+ lines.append(f"[cyan]Context:[/cyan] {rec.context}")+ if rec.decision:+ lines.append(f"[cyan]Decision:[/cyan] {rec.decision}")+ if rec.rationale:+ lines.append(f"[cyan]Rationale:[/cyan] {rec.rationale}")++ alternatives = json.loads(rec.alternatives_json)+ if alternatives:+ lines.append("[cyan]Alternatives rejected:[/cyan]")+ for a in alternatives:+ lines.append(f" - {a}")++ consequences = json.loads(rec.consequences_json)+ if consequences:+ lines.append("[cyan]Consequences:[/cyan]")+ for c in consequences:+ lines.append(f" - {c}")++ affected = json.loads(rec.affected_files_json)+ if affected:+ lines.append(f"[cyan]Affected files:[/cyan] {', '.join(affected[:10])}")++ tags = json.loads(rec.tags_json)+ if tags:+ lines.append(f"[cyan]Tags:[/cyan] {', '.join(tags)}")++ if rec.evidence_file:+ loc = rec.evidence_file+ if rec.evidence_line:+ loc += f":{rec.evidence_line}"+ lines.append(f"[cyan]Evidence:[/cyan] {loc}")++ console.print(Panel("\n".join(lines), title=f"Decision {rec.id[:8]}"))+++# ---------------------------------------------------------------------------+# decision confirm+# ---------------------------------------------------------------------------+++@decision_group.command("confirm")[email protected]("decision_id")[email protected]("path", required=False, default=None)+def decision_confirm(decision_id: str, path: str | None) -> None:+ """Confirm a proposed decision (set status to active)."""+ repo_path = resolve_repo_path(path)++ async def _update():+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ update_decision_status,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ rec = await update_decision_status(session, decision_id, "active")++ await engine.dispose()+ return rec++ rec = run_async(_update())+ if rec is None:+ console.print(f"[red]Decision not found: {decision_id}[/red]")+ else:+ console.print(f"[green]Decision {rec.id[:8]} confirmed (active)[/green]")+++# ---------------------------------------------------------------------------+# decision dismiss+# ---------------------------------------------------------------------------+++@decision_group.command("dismiss")[email protected]("decision_id")[email protected]("path", required=False, default=None)+def decision_dismiss(decision_id: str, path: str | None) -> None:+ """Dismiss (delete) a proposed decision."""+ repo_path = resolve_repo_path(path)++ if not click.confirm(f"Delete decision {decision_id[:8]}?"):+ console.print("[yellow]Cancelled.[/yellow]")+ return++ async def _delete():+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ delete_decision,+ get_session,+ init_db,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ deleted = await delete_decision(session, decision_id)++ await engine.dispose()+ return deleted++ deleted = run_async(_delete())+ if deleted:+ console.print(f"[green]Decision {decision_id[:8]} dismissed.[/green]")+ else:+ console.print(f"[red]Decision not found: {decision_id}[/red]")+++# ---------------------------------------------------------------------------+# decision deprecate+# ---------------------------------------------------------------------------+++@decision_group.command("deprecate")[email protected]("decision_id")[email protected]("path", required=False, default=None)[email protected]("--superseded-by", default=None, help="ID of the decision that replaces this one.")+def decision_deprecate(+ decision_id: str, path: str | None, superseded_by: str | None+) -> None:+ """Deprecate an active decision."""+ repo_path = resolve_repo_path(path)++ async def _update():+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ update_decision_status,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ rec = await update_decision_status(+ session, decision_id, "deprecated", superseded_by=superseded_by+ )++ await engine.dispose()+ return rec++ rec = run_async(_update())+ if rec is None:+ console.print(f"[red]Decision not found: {decision_id}[/red]")+ else:+ console.print(f"[yellow]Decision {rec.id[:8]} deprecated.[/yellow]")+++# ---------------------------------------------------------------------------+# decision health+# ---------------------------------------------------------------------------+++@decision_group.command("health")[email protected]("path", required=False, default=None)+def decision_health(path: str | None) -> None:+ """Show decision health: stale decisions, proposed, ungoverned hotspots."""+ repo_path = resolve_repo_path(path)++ async def _query():+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ get_decision_health_summary,+ get_session,+ init_db,+ upsert_repository,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ repo = await upsert_repository(+ session, name=repo_path.name, local_path=str(repo_path)+ )+ health = await get_decision_health_summary(session, repo.id)++ await engine.dispose()+ return health++ health = run_async(_query())+ summary = health["summary"]++ console.print("[bold]Decision Health[/bold]\n")++ # Summary stats+ stats_table = Table(show_header=False, box=None)+ stats_table.add_column("Metric", style="cyan")+ stats_table.add_column("Value", justify="right")+ stats_table.add_row("Active decisions", str(summary.get("active", 0)))+ stats_table.add_row("Proposed (needs review)", f"[yellow]{summary.get('proposed', 0)}[/yellow]")+ stats_table.add_row("Stale decisions", f"[red]{summary.get('stale', 0)}[/red]")+ stats_table.add_row("Deprecated", str(summary.get("deprecated", 0)))+ console.print(stats_table)++ # Stale decisions+ stale = health["stale_decisions"]+ if stale:+ console.print(f"\n[red]Stale decisions ({len(stale)}):[/red]")+ for d in stale[:5]:+ console.print(f" {d.id[:8]} {d.title[:50]} (staleness: {d.staleness_score:.2f})")++ # Ungoverned hotspots+ ungoverned = health["ungoverned_hotspots"]+ if ungoverned:+ console.print(f"\n[yellow]Ungoverned hotspots ({len(ungoverned)}):[/yellow]")+ for fp in ungoverned[:10]:+ console.print(f" {fp}")++ # Proposed+ proposed = health["proposed_awaiting_review"]+ if proposed:+ console.print(f"\n[yellow]Proposed decisions ({len(proposed)}):[/yellow]")+ for d in proposed[:5]:+ console.print(f" {d.id[:8]} {d.title[:50]} (source: {d.source})")diff --git a/packages/cli/src/wikicode/cli/commands/doctor_cmd.py b/packages/cli/src/wikicode/cli/commands/doctor_cmd.pynew file mode 100644index 000000000..c7d256b3f--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/doctor_cmd.py@@ -0,0 +1,145 @@+"""``wikicode doctor`` — health check for the wiki setup."""++from __future__ import annotations++import click+from rich.table import Table++from wikicode.cli.helpers import (+ console,+ get_db_url_for_repo,+ get_wikicode_dir,+ load_state,+ resolve_repo_path,+ run_async,+)+++def _check(name: str, ok: bool, detail: str = "") -> tuple[str, str, str]:+ status = "[green]OK[/green]" if ok else "[red]FAIL[/red]"+ return (name, status, detail)++[email protected]("doctor")[email protected]("path", required=False, default=None)+def doctor_command(path: str | None) -> None:+ """Run health checks on the wiki setup."""+ repo_path = resolve_repo_path(path)+ checks: list[tuple[str, str, str]] = []++ # 1. Git repository?+ try:+ import git as gitpython++ gitpython.Repo(repo_path, search_parent_directories=True)+ checks.append(_check("Git repository", True, str(repo_path)))+ except Exception:+ checks.append(_check("Git repository", False, "Not a git repo"))++ # 2. .wikicode/ exists?+ wikicode_dir = get_wikicode_dir(repo_path)+ checks.append(_check(".wikicode/ directory", wikicode_dir.exists(), str(wikicode_dir)))++ # 3. Database connectable?+ db_path = wikicode_dir / "wiki.db"+ db_ok = False+ page_count = 0+ if db_path.exists():+ try:+ async def _check_db():+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ get_repository_by_path,+ get_session,+ list_pages,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ sf = create_session_factory(engine)+ count = 0+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo:+ pages = await list_pages(session, repo.id, limit=10000)+ count = len(pages)+ await engine.dispose()+ return count++ page_count = run_async(_check_db())+ db_ok = True+ except Exception as e:+ checks.append(_check("Database", False, str(e)))+ if db_ok:+ checks.append(_check("Database", True, f"{page_count} pages"))+ elif not db_path.exists():+ checks.append(_check("Database", False, "wiki.db not found"))++ # 4. state.json valid?+ state = load_state(repo_path)+ state_ok = bool(state)+ checks.append(+ _check(+ "state.json",+ state_ok,+ f"last_sync: {(state.get('last_sync_commit') or '—')[:8]}" if state_ok else "Not found or empty",+ )+ )++ # 5. Provider importable?+ provider_ok = False+ try:+ from wikicode.core.providers import list_providers++ providers = list_providers()+ provider_ok = len(providers) > 0+ checks.append(_check("Providers", provider_ok, ", ".join(providers)))+ except Exception as e:+ checks.append(_check("Providers", False, str(e)))++ # 6. Stale page count+ if db_ok and page_count > 0:+ try:+ async def _check_stale():+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ get_repository_by_path,+ get_session,+ get_stale_pages,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo:+ stale = await get_stale_pages(session, repo.id)+ await engine.dispose()+ return len(stale)+ await engine.dispose()+ return 0++ stale_count = run_async(_check_stale())+ checks.append(+ _check("Stale pages", stale_count == 0, f"{stale_count} stale")+ )+ except Exception:+ checks.append(_check("Stale pages", True, "Could not check"))++ # Display+ table = Table(title="WikiCode Doctor")+ table.add_column("Check", style="cyan")+ table.add_column("Status")+ table.add_column("Detail")+ for name, status, detail in checks:+ table.add_row(name, status, detail)+ console.print(table)++ all_ok = all("[green]OK[/green]" in status for _, status, _ in checks)+ if all_ok:+ console.print("[bold green]All checks passed![/bold green]")+ else:+ console.print("[bold yellow]Some checks failed.[/bold yellow]")diff --git a/packages/cli/src/wikicode/cli/commands/export_cmd.py b/packages/cli/src/wikicode/cli/commands/export_cmd.pynew file mode 100644index 000000000..d89c1c673--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/export_cmd.py@@ -0,0 +1,144 @@+"""``wikicode export`` — export wiki pages to markdown, HTML, or JSON."""++from __future__ import annotations++import json+from pathlib import Path++import click+from rich.progress import Progress++from wikicode.cli.helpers import (+ console,+ ensure_wikicode_dir,+ get_db_url_for_repo,+ resolve_repo_path,+ run_async,+)++[email protected]("export")[email protected]("path", required=False, default=None)+ "--format",+ "fmt",+ type=click.Choice(["markdown", "html", "json"]),+ default="markdown",+ help="Output format.",+)[email protected]("--output", "-o", "output_dir", default=None, help="Output directory (default: .wikicode/export).")+def export_command(+ path: str | None,+ fmt: str,+ output_dir: str | None,+) -> None:+ """Export wiki pages to files."""+ repo_path = resolve_repo_path(path)+ ensure_wikicode_dir(repo_path)++ if output_dir is None:+ out = repo_path / ".wikicode" / "export"+ else:+ out = Path(output_dir).resolve()+ out.mkdir(parents=True, exist_ok=True)++ # Load pages from DB+ async def _load_pages():+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ list_pages,+ get_repository_by_path,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ await engine.dispose()+ return []+ pages = await list_pages(session, repo.id, limit=10000)++ await engine.dispose()+ return pages++ pages = run_async(_load_pages())++ if not pages:+ console.print("[yellow]No pages found. Run 'wikicode init' first.[/yellow]")+ return++ with Progress(console=console) as progress:+ task = progress.add_task(f"Exporting {len(pages)} pages as {fmt}...", total=len(pages))++ if fmt == "markdown":+ for page in pages:+ safe_name = (+ page.target_path+ .replace("/", "_")+ .replace("::", "__")+ .replace("->", "--")+ .replace(">", "")+ .replace("<", "")+ .replace(":", "_")+ .replace("\\", "_")+ .replace("|", "_")+ .replace("?", "")+ .replace("*", "")+ .replace('"', "")+ )+ filepath = out / f"{safe_name}.md"+ filepath.write_text(+ f"# {page.title}\n\n{page.content}",+ encoding="utf-8",+ )+ progress.advance(task)++ elif fmt == "html":+ for page in pages:+ safe_name = (+ page.target_path+ .replace("/", "_")+ .replace("::", "__")+ .replace("->", "--")+ .replace(">", "")+ .replace("<", "")+ .replace(":", "_")+ .replace("\\", "_")+ .replace("|", "_")+ .replace("?", "")+ .replace("*", "")+ .replace('"', "")+ )+ filepath = out / f"{safe_name}.html"+ html = (+ "<!DOCTYPE html>\n<html>\n<head>\n"+ f"<title>{page.title}</title>\n"+ '<meta charset="utf-8">\n'+ "</head>\n<body>\n"+ f"<h1>{page.title}</h1>\n"+ f"<pre>{page.content}</pre>\n"+ "</body>\n</html>"+ )+ filepath.write_text(html, encoding="utf-8")+ progress.advance(task)++ 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,+ })+ progress.advance(task)+ filepath = out / "wiki_pages.json"+ filepath.write_text(json.dumps(data, indent=2), encoding="utf-8")++ console.print(f"[bold green]Exported {len(pages)} pages to {out}[/bold green]")diff --git a/packages/cli/src/wikicode/cli/commands/init_cmd.py b/packages/cli/src/wikicode/cli/commands/init_cmd.pynew file mode 100644index 000000000..cb845b09b--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/init_cmd.py@@ -0,0 +1,780 @@+"""``wikicode init`` — full wiki generation for a repository."""++from __future__ import annotations++import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import click+from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn+from rich.table import Table++from wikicode.cli.cost_estimator import build_generation_plan, estimate_cost+from wikicode.cli.helpers import (+ console,+ ensure_db,+ ensure_wikicode_dir,+ err_console,+ get_head_commit,+ load_config,+ load_state,+ resolve_provider,+ resolve_repo_path,+ run_async,+ save_config,+ save_state,+)+++async def _persist_index_only(+ repo_path: Path,+ repo_name: str,+ graph_builder: Any,+ parsed_files: list[Any],+ git_metadata_list: list[dict],+ dead_code_report: Any,+ decision_report: Any = None,+) -> None:+ """Persist graph, symbols, git metadata, dead code, and decisions — no pages."""+ from wikicode.core.persistence import (+ batch_upsert_graph_edges,+ batch_upsert_graph_nodes,+ batch_upsert_symbols,+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )+ from wikicode.core.persistence.crud import (+ save_dead_code_findings,+ upsert_git_metadata_bulk,+ )+ from wikicode.cli.helpers import get_db_url_for_repo++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ repo = await upsert_repository(+ session,+ name=repo_name,+ local_path=str(repo_path),+ )+ repo_id = repo.id++ # Graph nodes+ graph = graph_builder.graph()+ pr = graph_builder.pagerank()+ bc = graph_builder.betweenness_centrality()+ cd = graph_builder.community_detection()+ nodes = []+ for node_path in graph.nodes:+ data = graph.nodes[node_path]+ nodes.append({+ "node_id": node_path,+ "symbol_count": data.get("symbol_count", 0),+ "has_error": data.get("has_error", False),+ "is_test": data.get("is_test", False),+ "is_entry_point": data.get("is_entry_point", False),+ "language": data.get("language", "unknown"),+ "pagerank": pr.get(node_path, 0.0),+ "betweenness": bc.get(node_path, 0.0),+ "community_id": cd.get(node_path, 0),+ })+ if nodes:+ await batch_upsert_graph_nodes(session, repo_id, nodes)++ # Graph edges+ edges = []+ for u, v, data in graph.edges(data=True):+ edges.append({+ "source_node_id": u,+ "target_node_id": v,+ "imported_names_json": json.dumps(data.get("imported_names", [])),+ })+ if edges:+ await batch_upsert_graph_edges(session, repo_id, edges)++ # Symbols+ all_symbols = []+ for pf in parsed_files:+ for sym in pf.symbols:+ sym.file_path = pf.file_info.path+ all_symbols.append(sym)+ if all_symbols:+ await batch_upsert_symbols(session, repo_id, all_symbols)++ # Git metadata+ if git_metadata_list:+ await upsert_git_metadata_bulk(session, repo_id, git_metadata_list)++ # Dead code findings+ if dead_code_report and dead_code_report.findings:+ await save_dead_code_findings(session, repo_id, dead_code_report.findings)++ # Decision records+ if decision_report and decision_report.decisions:+ import dataclasses as _dc++ from wikicode.core.persistence.crud import bulk_upsert_decisions++ await bulk_upsert_decisions(+ session,+ repo_id,+ [_dc.asdict(d) for d in decision_report.decisions],+ )++ await engine.dispose()+++_PROVIDER_DEFAULTS: dict[str, str] = {+ "gemini": "gemini-3.1-flash-lite-preview",+ "openai": "gpt-4.1",+ "anthropic": "claude-sonnet-4-6",+ "ollama": "llama3.2",+ "litellm": "groq/llama-3.1-70b-versatile",+}++_EMBEDDER_ENV: dict[str, str] = {+ "gemini": "GEMINI_API_KEY",+ "openai": "OPENAI_API_KEY",+}+++def _resolve_embedder(embedder_flag: str | None) -> str:+ """Auto-detect embedder from env vars, or use the flag value."""+ if embedder_flag:+ return embedder_flag+ if os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY"):+ return "gemini"+ if os.environ.get("OPENAI_API_KEY"):+ return "openai"+ return "mock"+++def _interactive_provider_wizard(model_flag: str | None) -> tuple[str, str]:+ """Interactive provider selection wizard.++ Returns (provider_name, model_name).+ Only called when stdin is a TTY and no --provider flag was given.+ """+ available: list[str] = []+ env_status: dict[str, str] = {+ "gemini": "GEMINI_API_KEY" if os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") else "",+ "openai": "OPENAI_API_KEY" if os.environ.get("OPENAI_API_KEY") else "",+ "anthropic": "ANTHROPIC_API_KEY" if os.environ.get("ANTHROPIC_API_KEY") else "",+ "ollama": "OLLAMA_BASE_URL" if os.environ.get("OLLAMA_BASE_URL") else "",+ }++ table = Table(title="Available providers", show_header=False, box=None, padding=(0, 1))+ for p, env_key in env_status.items():+ if env_key:+ available.append(p)+ default_model = _PROVIDER_DEFAULTS.get(p, "")+ table.add_row(f"[green][+][/green] [bold]{p}[/bold]", f"({env_key} set)", f"-> {default_model}")+ else:+ env_hint = {"gemini": "GEMINI_API_KEY", "openai": "OPENAI_API_KEY",+ "anthropic": "ANTHROPIC_API_KEY", "ollama": "OLLAMA_BASE_URL"}[p]+ table.add_row(f"[-] [dim]{p}[/dim]", f"({env_hint} not set)", "")+ console.print(table)++ if not available:+ raise click.ClickException(+ "No provider API keys found. Set ANTHROPIC_API_KEY, OPENAI_API_KEY, "+ "GEMINI_API_KEY, or OLLAMA_BASE_URL and retry."+ )++ if len(available) == 1:+ chosen = available[0]+ console.print(f"[cyan]Auto-selected provider:[/cyan] {chosen}")+ else:+ chosen = click.prompt(+ "Select provider",+ type=click.Choice(available),+ default=available[0],+ )++ default_model = _PROVIDER_DEFAULTS.get(chosen, "")+ if model_flag:+ model = model_flag+ else:+ model = click.prompt("Model (press Enter for default)", default=default_model)++ return chosen, model++[email protected]("init")[email protected]("path", required=False, default=None)[email protected]("--provider", "provider_name", default=None, help="LLM provider name (anthropic, openai, gemini, ollama, mock).")[email protected]("--model", default=None, help="Model identifier override.")[email protected]("--embedder", "embedder_name", default=None,+ type=click.Choice(["gemini", "openai", "mock"]),+ help="Embedder for RAG: gemini | openai | mock (default: auto-detect).")[email protected]("--skip-tests", is_flag=True, default=False, help="Skip test files.")[email protected]("--skip-infra", is_flag=True, default=False, help="Skip infrastructure files.")[email protected]("--dry-run", is_flag=True, default=False, help="Show generation plan without running.")[email protected]("--yes", "-y", is_flag=True, default=False, help="Skip cost confirmation prompt.")[email protected]("--resume", is_flag=True, default=False, help="Resume from last checkpoint.")[email protected]("--force", is_flag=True, default=False, help="Regenerate all pages, ignoring existing.")[email protected]("--concurrency", type=int, default=5, help="Max concurrent LLM calls.")[email protected]("--test-run", is_flag=True, default=False,+ help="Limit generation to top 10 files by PageRank for quick validation.")+ "--index-only",+ is_flag=True,+ default=False,+ help="Index files, git history, graph, and dead code — skip LLM page generation.",+)+ "--exclude", "-x",+ multiple=True,+ metavar="PATTERN",+ help="Gitignore-style pattern to exclude. Can be repeated: -x vendor/ -x 'src/generated/**'",+)+def init_command(+ path: str | None,+ provider_name: str | None,+ model: str | None,+ embedder_name: str | None,+ skip_tests: bool,+ skip_infra: bool,+ dry_run: bool,+ yes: bool,+ resume: bool,+ force: bool,+ concurrency: int,+ test_run: bool,+ index_only: bool,+ exclude: tuple[str, ...],+) -> None:+ """Generate wiki documentation for a codebase.++ PATH defaults to the current directory.+ Use --index-only to run ingestion (AST, graph, git, dead code) without LLM generation.+ """+ start = time.monotonic()+ repo_path = resolve_repo_path(path)++ if not repo_path.is_dir():+ raise click.ClickException(f"Not a directory: {repo_path}")++ ensure_wikicode_dir(repo_path)++ # Merge exclude_patterns from config.yaml and --exclude/-x flags+ config = load_config(repo_path)+ exclude_patterns: list[str] = list(config.get("exclude_patterns") or []) + list(exclude)++ embedder = _resolve_embedder(embedder_name)++ if index_only:+ provider = None+ # Still try to resolve a provider for decision extraction (no page generation)+ decision_provider = None+ try:+ if provider_name or (sys.stdin.isatty() is False):+ decision_provider = resolve_provider(provider_name, model, repo_path)+ elif any(os.environ.get(k) for k in ("GEMINI_API_KEY", "GOOGLE_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")):+ decision_provider = resolve_provider(provider_name, model, repo_path)+ except Exception:+ pass # No provider available — inline markers only+ console.print(f"[bold]WikiCode index-only[/bold] — {repo_path}")+ console.print("[yellow]Skipping LLM page generation (--index-only)[/yellow]")+ if decision_provider:+ console.print(f"Decision extraction provider: [cyan]{decision_provider.provider_name}[/cyan]")+ else:+ # Interactive wizard when no --provider given and running in a terminal+ if provider_name is None and sys.stdin.isatty():+ provider_name, model = _interactive_provider_wizard(model)++ provider = resolve_provider(provider_name, model, repo_path)+ console.print(f"[bold]WikiCode init[/bold] — {repo_path}")+ console.print(f"Provider: [cyan]{provider.provider_name}[/cyan] / Model: [cyan]{provider.model_name}[/cyan]")+ console.print(f"Embedder: [cyan]{embedder}[/cyan]")++ # Validate API key with a lightweight call before ingesting+ from wikicode.core.providers.base import ProviderError++ console.print("Verifying provider connection...")+ try:+ run_async(provider.generate("You are a test.", "Reply with OK.", max_tokens=50))+ console.print("[green]Provider connection verified[/green]")+ except ProviderError as exc:+ raise click.ClickException(f"Provider validation failed: {exc}")++ # ---- Step 1: Ingest + Git (parallelized) ----+ from concurrent.futures import ThreadPoolExecutor, as_completed++ from wikicode.core.generation import GenerationConfig+ from wikicode.core.ingestion import ASTParser, FileTraverser, GraphBuilder++ config = GenerationConfig(max_concurrency=concurrency)++ git_future = None+ git_summary = None+ git_metadata_list: list[dict] = []+ git_meta_map: dict[str, dict] = {}++ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ TextColumn("{task.completed}/{task.total}"),+ TimeElapsedColumn(),+ console=console,+ ) as progress:+ task_traverse = progress.add_task("Traversing files...", total=None)+ task_parse = progress.add_task("Parsing files...", total=None, visible=False)+ task_graph = progress.add_task("Building dependency graph...", total=1, visible=False)+ task_git = progress.add_task("Indexing file history...", total=None, visible=False)+ task_cochange = progress.add_task("Analyzing co-changes...", total=None, visible=False)++ # Start git indexing in a background thread immediately — it uses+ # git ls-files for its own file list, fully independent of traversal.+ git_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="git-idx")+ try:+ from wikicode.core.ingestion.git_indexer import GitIndexer++ git_indexer = GitIndexer(repo_path)++ def _run_git_indexing() -> tuple:+ def on_start(total: int) -> None:+ progress.update(task_git, total=total, visible=True)++ def on_file_done() -> None:+ progress.advance(task_git)++ def on_co_change_start(total: int) -> None:+ progress.update(task_cochange, total=total, visible=True)++ def on_commit_done() -> None:+ progress.advance(task_cochange)++ return run_async(+ git_indexer.index_repo(+ "",+ on_start=on_start,+ on_file_done=on_file_done,+ on_commit_done=on_commit_done,+ on_co_change_start=on_co_change_start,+ )+ )++ git_future = git_executor.submit(_run_git_indexing)+ except Exception as exc:+ progress.console.print(f"[yellow]Git indexing skipped: {exc}[/yellow]")++ # Traverse: walk directory tree (sequential), then process files+ # with parallel I/O (stat + header reads are the bottleneck on Windows).+ traverser = FileTraverser(repo_path, extra_exclude_patterns=exclude_patterns or None)+ all_paths = list(traverser._walk()) # fast directory enumeration+ progress.update(task_traverse, total=len(all_paths))++ file_infos: list[Any] = []+ with ThreadPoolExecutor(max_workers=8) as io_pool:+ futures = [io_pool.submit(traverser._build_file_info, p) for p in all_paths]+ for future in as_completed(futures):+ try:+ result = future.result()+ except Exception:+ result = None+ if result is not None:+ file_infos.append(result)+ progress.advance(task_traverse)++ repo_structure = traverser.get_repo_structure(file_infos)++ # Filter+ if skip_tests:+ file_infos = [fi for fi in file_infos if not fi.is_test]+ if skip_infra:+ file_infos = [fi for fi in file_infos if fi.language not in ("dockerfile", "makefile", "terraform", "shell")]++ # Parse (sequential — GraphBuilder is not thread-safe)+ progress.update(task_parse, total=len(file_infos), visible=True)+ parser = ASTParser()+ parsed_files: list[Any] = []+ source_map: dict[str, bytes] = {}+ graph_builder = GraphBuilder()++ for fi in file_infos:+ try:+ source = Path(fi.abs_path).read_bytes()+ parsed = parser.parse_file(fi, source)+ parsed_files.append(parsed)+ source_map[fi.path] = source+ graph_builder.add_file(parsed)+ except Exception:+ pass # skip unparseable files+ progress.advance(task_parse)+ progress.update(task_parse, completed=len(file_infos))++ # Build graph+ progress.update(task_graph, visible=True)+ graph_builder.build()+ progress.update(task_graph, completed=1)++ # Wait for git indexing to complete+ if git_future is not None:+ try:+ git_summary, git_metadata_list = git_future.result()+ git_meta_map = {m["file_path"]: m for m in git_metadata_list}+ graph_builder.add_co_change_edges(git_meta_map)+ except Exception as exc:+ progress.console.print(f"[yellow]Git indexing failed: {exc}[/yellow]")++ git_executor.shutdown(wait=False)++ if traverser._oversized_skip_count:+ console.print(+ f"Skipped [yellow]{traverser._oversized_skip_count}[/yellow] oversized files "+ f"(>{traverser.max_file_size_bytes // 1024} KB)"+ )+ console.print(f"Ingested [green]{len(parsed_files)}[/green] files")+ if git_summary:+ console.print(+ f"Git indexed: [green]{git_summary.files_indexed}[/green] files "+ f"· {git_summary.hotspots} hotspots · {git_summary.stable_files} stable "+ f"({git_summary.duration_seconds:.1f}s)"+ )++ # ---- Test-run: limit to top 10 files by PageRank ----+ if test_run and not index_only:+ import networkx as nx # noqa: PLC0415++ graph = graph_builder.graph()+ try:+ ranks = nx.pagerank(graph)+ except Exception:+ ranks = {}+ parsed_files = sorted(+ parsed_files,+ key=lambda pf: ranks.get(pf.file_info.path, 0),+ reverse=True,+ )[:10]+ console.print(f"[yellow]Test run: limiting to {len(parsed_files)} files[/yellow]")++ # ---- Step 3.6: Dead code detection ----+ dead_code_report = None+ try:+ from wikicode.core.analysis.dead_code import DeadCodeAnalyzer++ console.print("[bold]Detecting dead code...[/bold]")+ analyzer = DeadCodeAnalyzer(graph_builder.graph(), git_meta_map)+ dead_code_report = analyzer.analyze()+ unreachable = sum(+ 1 for f in dead_code_report.findings if f.kind.value == "unreachable_file"+ )+ unused_exports = sum(+ 1 for f in dead_code_report.findings if f.kind.value == "unused_export"+ )+ console.print(+ f"[3.6] Dead code: [yellow]{unreachable}[/yellow] unreachable files "+ f"· [yellow]{unused_exports}[/yellow] unused exports "+ f"(~{dead_code_report.deletable_lines:,} lines)"+ )+ except Exception as exc:+ console.print(f"[yellow]Dead code detection skipped: {exc}[/yellow]")++ # ---- Step 3.7: Decision extraction ----+ decision_report = None+ try:+ from wikicode.core.analysis.decision_extractor import DecisionExtractor++ console.print("[bold]Extracting architectural decisions...[/bold]")+ # Use decision_provider in index-only mode (provider is None but+ # decision_provider may still be set for decision extraction)+ _decision_llm = provider or (decision_provider if index_only else None)+ extractor = DecisionExtractor(+ repo_path=repo_path,+ provider=_decision_llm,+ graph=graph_builder.graph(),+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,+ )+ decision_report = run_async(extractor.extract_all())+ inline = decision_report.by_source.get("inline_marker", 0)+ readme = decision_report.by_source.get("readme_mining", 0)+ git_arch = decision_report.by_source.get("git_archaeology", 0)+ console.print(+ f"Decisions: [green]{inline}[/green] inline markers · "+ f"[yellow]{readme}[/yellow] from docs · [yellow]{git_arch}[/yellow] from git"+ )+ except Exception as exc:+ console.print(f"[yellow]Decision extraction skipped: {exc}[/yellow]")++ # ---- Index-only: persist everything except pages and exit ----+ if index_only:+ run_async(_persist_index_only(+ repo_path=repo_path,+ repo_name=repo_path.name,+ graph_builder=graph_builder,+ parsed_files=parsed_files,+ git_metadata_list=git_metadata_list,+ dead_code_report=dead_code_report,+ decision_report=decision_report,+ ))+ elapsed = time.monotonic() - start+ console.print(f"[bold green]Index complete[/bold green] in {elapsed:.1f}s — graph, symbols, git, and dead code persisted.")+ return++ # ---- Step 2: Cost estimate ----+ plans = build_generation_plan(parsed_files, graph_builder, config, skip_tests, skip_infra)+ est = estimate_cost(plans, provider.provider_name, provider.model_name)++ table = Table(title="Generation Plan")+ table.add_column("Page Type", style="cyan")+ table.add_column("Count", justify="right")+ table.add_column("Level", justify="right")+ for plan in est.plans:+ table.add_row(plan.page_type, str(plan.count), str(plan.level))+ table.add_section()+ table.add_row("[bold]Total[/bold]", f"[bold]{est.total_pages}[/bold]", "")+ console.print(table)++ console.print(+ f"Estimated tokens: ~{est.estimated_input_tokens + est.estimated_output_tokens:,} "+ f"(${est.estimated_cost_usd:.2f} USD)"+ )++ if dry_run:+ console.print("[yellow]Dry run — no pages generated.[/yellow]")+ return++ # ---- Step 3: Confirmation ----+ if est.estimated_cost_usd > 2.00 and not yes:+ if not click.confirm("Estimated cost exceeds $2.00. Continue?"):+ console.print("[yellow]Aborted.[/yellow]")+ return++ # ---- Step 4: Generate ----+ from wikicode.core.generation import ContextAssembler, JobSystem, PageGenerator+ from wikicode.core.persistence.embedder import MockEmbedder+ from wikicode.core.persistence.vector_store import InMemoryVectorStore++ assembler = ContextAssembler(config)++ # Build vector store for RAG context (B1)+ embedder_impl: Any+ embedder_resolved = _resolve_embedder(embedder_name)+ if embedder_resolved == "gemini":+ try:+ from wikicode.core.persistence.gemini_embedder import GeminiEmbedder+ embedder_impl = GeminiEmbedder()+ except Exception:+ embedder_impl = MockEmbedder()+ elif embedder_resolved == "openai":+ try:+ from wikicode.core.persistence.openai_embedder import OpenAIEmbedder+ embedder_impl = OpenAIEmbedder()+ except Exception:+ embedder_impl = MockEmbedder()+ else:+ embedder_impl = MockEmbedder()+ vector_store = InMemoryVectorStore(embedder_impl)++ generator = PageGenerator(provider, assembler, config, vector_store=vector_store)++ job_system = None+ jobs_dir = Path(config.jobs_dir)+ if not jobs_dir.is_absolute():+ jobs_dir = repo_path / jobs_dir+ job_system = JobSystem(jobs_dir)++ repo_name = repo_path.name++ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ TextColumn("{task.completed}/{task.total}"),+ TimeElapsedColumn(),+ console=console,+ ) as gen_progress:+ task_gen = gen_progress.add_task("Generating pages...", total=est.total_pages)++ def on_page_done(page_type: str) -> None:+ gen_progress.advance(task_gen)+ gen_progress.update(task_gen, description=f"Generating pages... [{page_type}]")++ generated_pages = run_async(+ generator.generate_all(+ parsed_files,+ source_map,+ graph_builder,+ repo_structure,+ repo_name,+ job_system=job_system,+ on_page_done=on_page_done,+ git_meta_map=git_meta_map if git_meta_map else None,+ )+ )++ console.print(f"Generated [green]{len(generated_pages)}[/green] pages")++ # ---- Step 5: Persist ----+ async def _persist() -> None:+ from wikicode.core.persistence import (+ FullTextSearch,+ batch_upsert_graph_nodes,+ batch_upsert_graph_edges,+ batch_upsert_symbols,+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_page_from_generated,+ upsert_repository,+ )+ from wikicode.core.persistence.crud import (+ save_dead_code_findings,+ upsert_git_metadata_bulk,+ )++ from wikicode.cli.helpers import get_db_url_for_repo++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ repo = await upsert_repository(+ session,+ name=repo_name,+ local_path=str(repo_path),+ )+ repo_id = repo.id++ for page in generated_pages:+ await upsert_page_from_generated(session, page, repo_id)++ # Graph nodes+ graph = graph_builder.graph()+ pr = graph_builder.pagerank()+ bc = graph_builder.betweenness_centrality()+ cd = graph_builder.community_detection()+ nodes = []+ for node_path in graph.nodes:+ data = graph.nodes[node_path]+ nodes.append({+ "node_id": node_path,+ "symbol_count": data.get("symbol_count", 0),+ "has_error": data.get("has_error", False),+ "is_test": data.get("is_test", False),+ "is_entry_point": data.get("is_entry_point", False),+ "language": data.get("language", "unknown"),+ "pagerank": pr.get(node_path, 0.0),+ "betweenness": bc.get(node_path, 0.0),+ "community_id": cd.get(node_path, 0),+ })+ if nodes:+ await batch_upsert_graph_nodes(session, repo_id, nodes)++ # Graph edges+ edges = []+ for u, v, data in graph.edges(data=True):+ edges.append({+ "source_node_id": u,+ "target_node_id": v,+ "imported_names_json": json.dumps(data.get("imported_names", [])),+ })+ if edges:+ await batch_upsert_graph_edges(session, repo_id, edges)++ # Symbols — pass actual Symbol objects (duck-typed)+ all_symbols = []+ for pf in parsed_files:+ for sym in pf.symbols:+ # Attach file_path to symbol for batch_upsert_symbols+ sym.file_path = pf.file_info.path+ all_symbols.append(sym)+ if all_symbols:+ await batch_upsert_symbols(session, repo_id, all_symbols)++ # Git metadata+ if git_metadata_list:+ await upsert_git_metadata_bulk(session, repo_id, git_metadata_list)++ # Dead code findings+ if dead_code_report and dead_code_report.findings:+ await save_dead_code_findings(+ session, repo_id, dead_code_report.findings+ )++ # Decision records+ if decision_report and decision_report.decisions:+ import dataclasses as _dc++ from wikicode.core.persistence.crud import bulk_upsert_decisions++ await bulk_upsert_decisions(+ session,+ repo_id,+ [_dc.asdict(d) for d in decision_report.decisions],+ )++ # FTS indexing+ fts = FullTextSearch(engine)+ await fts.ensure_index()+ for page in generated_pages:+ await fts.index(page.page_id, page.title, page.content)++ await engine.dispose()++ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ TimeElapsedColumn(),+ console=console,+ ) as persist_progress:+ persist_progress.add_task("Persisting to database...", total=None)+ run_async(_persist())++ # ---- Step 6: State ----+ head = get_head_commit(repo_path)+ state = load_state(repo_path)+ state["last_sync_commit"] = head+ state["total_pages"] = len(generated_pages)+ state["provider"] = provider.provider_name+ state["model"] = provider.model_name+ total_tokens = sum(p.total_tokens for p in generated_pages)+ state["total_tokens"] = total_tokens+ save_state(repo_path, state)++ # Save config so subsequent `wikicode update / serve` picks up the same settings.+ # Pass exclude_patterns only when the CLI added new ones (preserves existing via round-trip).+ save_config(+ repo_path,+ provider.provider_name,+ provider.model_name,+ embedder,+ exclude_patterns=exclude_patterns if exclude_patterns else None,+ )++ # ---- Step 7: Summary ----+ elapsed = time.monotonic() - start+ summary = Table(title="Summary")+ summary.add_column("Metric", style="cyan")+ summary.add_column("Value", justify="right")+ summary.add_row("Pages generated", str(len(generated_pages)))+ summary.add_row("Total tokens", f"{total_tokens:,}")+ summary.add_row("Elapsed", f"{elapsed:.1f}s")+ summary.add_row("Provider", provider.provider_name)+ summary.add_row("Model", provider.model_name)+ console.print(summary)++ # ---- Step 8: MCP Config ----+ from wikicode.cli.mcp_config import format_setup_instructions, save_mcp_config++ save_mcp_config(repo_path)+ console.print()+ console.print(format_setup_instructions(repo_path))+ console.print()+ console.print("[bold green]Done![/bold green]")diff --git a/packages/cli/src/wikicode/cli/commands/mcp_cmd.py b/packages/cli/src/wikicode/cli/commands/mcp_cmd.pynew file mode 100644index 000000000..c4c670334--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/mcp_cmd.py@@ -0,0 +1,59 @@+"""``wikicode mcp`` — Start the MCP server for editor integration."""++from __future__ import annotations++import click++from wikicode.cli.helpers import console, resolve_repo_path++[email protected]("mcp")[email protected]("path", required=False, default=None)+ "--transport",+ type=click.Choice(["stdio", "sse"]),+ default="stdio",+ help="Transport protocol: stdio (Claude Code/Cursor) or sse (web clients).",+)+ "--port",+ type=int,+ default=7338,+ help="Port for SSE transport (default: 7338).",+)+def mcp_command(path: str | None, transport: str, port: int) -> None:+ """Start the MCP server for editor integration.++ Exposes 13 tools for querying the WikiCode wiki via the MCP protocol.+ Supports both stdio (for Claude Code, Cursor, Cline) and SSE transports.++ Examples:++ wikicode mcp # stdio, current directory+ wikicode mcp /path/to/repo # stdio, specific repo+ wikicode mcp --transport sse # SSE on port 7338+ """+ repo_path = resolve_repo_path(path)++ wikicode_dir = repo_path / ".wikicode"+ if not wikicode_dir.exists():+ console.print(+ f"[yellow]Warning: No .wikicode directory found at {repo_path}.[/yellow]\n"+ "Run 'wikicode init' first to generate documentation."+ )++ if transport == "sse":+ console.print(+ f"[bold green]Starting WikiCode MCP server (SSE) on port {port}...[/bold green]"+ )+ else:+ # stdio mode — no console output (it would corrupt the protocol)+ pass++ from wikicode.server.mcp_server import run_mcp++ run_mcp(+ transport=transport,+ repo_path=str(repo_path),+ port=port,+ )diff --git a/packages/cli/src/wikicode/cli/commands/search_cmd.py b/packages/cli/src/wikicode/cli/commands/search_cmd.pynew file mode 100644index 000000000..4cd1c9246--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/search_cmd.py@@ -0,0 +1,134 @@+"""``wikicode search`` — full-text, semantic, and symbol search."""++from __future__ import annotations++import click+from rich.table import Table++from wikicode.cli.helpers import (+ console,+ ensure_wikicode_dir,+ get_db_url_for_repo,+ resolve_repo_path,+ run_async,+)++[email protected]("search")[email protected]("query")[email protected]("path", required=False, default=None)+ "--mode",+ type=click.Choice(["fulltext", "semantic", "symbol"]),+ default="fulltext",+ help="Search mode.",+)[email protected]("--limit", type=int, default=10, help="Max results.")+def search_command(+ query: str,+ path: str | None,+ mode: str,+ limit: int,+) -> None:+ """Search wiki pages by keyword, meaning, or symbol name."""+ repo_path = resolve_repo_path(path)+ ensure_wikicode_dir(repo_path)++ if mode == "fulltext":+ _search_fulltext(repo_path, query, limit)+ elif mode == "semantic":+ _search_semantic(repo_path, query, limit)+ elif mode == "symbol":+ _search_symbol(repo_path, query, limit)+++def _search_fulltext(repo_path, query: str, limit: int) -> None:+ async def _run():+ from wikicode.core.persistence import FullTextSearch, create_engine++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ fts = FullTextSearch(engine)+ results = await fts.search(query, limit=limit)+ await engine.dispose()+ return results++ results = run_async(_run())+ _display_results(results, f"Full-text search: '{query}'")+++def _search_semantic(repo_path, query: str, limit: int) -> None:+ async def _run():+ from wikicode.core.persistence import InMemoryVectorStore, MockEmbedder++ store = InMemoryVectorStore(embedder=MockEmbedder())+ results = await store.search(query, limit=limit)+ await store.close()+ return results++ results = run_async(_run())+ _display_results(results, f"Semantic search: '{query}'")+++def _search_symbol(repo_path, query: str, limit: int) -> None:+ async def _run():+ from sqlalchemy import text as sa_text++ from wikicode.core.persistence import create_engine, create_session_factory, get_session++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ result = await session.execute(+ sa_text(+ "SELECT name, qualified_name, kind, file_path, start_line "+ "FROM wiki_symbols WHERE name LIKE :pattern LIMIT :limit"+ ),+ {"pattern": f"%{query}%", "limit": limit},+ )+ rows = result.fetchall()++ await engine.dispose()+ return rows++ rows = run_async(_run())++ table = Table(title=f"Symbol search: '{query}'")+ table.add_column("Name", style="cyan")+ table.add_column("Qualified Name")+ table.add_column("Kind")+ table.add_column("File")+ table.add_column("Line", justify="right")++ for row in rows:+ table.add_row(str(row[0]), str(row[1]), str(row[2]), str(row[3]), str(row[4]))++ if not rows:+ console.print(f"[yellow]No symbols matching '{query}'[/yellow]")+ else:+ console.print(table)+++def _display_results(results, title: str) -> None:+ table = Table(title=title)+ table.add_column("Score", justify="right", style="green")+ table.add_column("Title", style="cyan")+ table.add_column("Type")+ table.add_column("Path")+ table.add_column("Snippet", max_width=50)++ for r in results:+ table.add_row(+ f"{r.score:.3f}",+ r.title or "",+ r.page_type or "",+ r.target_path or "",+ (r.snippet or "")[:50],+ )++ if not results:+ console.print(f"[yellow]No results found.[/yellow]")+ else:+ console.print(table)diff --git a/packages/cli/src/wikicode/cli/commands/serve_cmd.py b/packages/cli/src/wikicode/cli/commands/serve_cmd.pynew file mode 100644index 000000000..5868bf77d--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/serve_cmd.py@@ -0,0 +1,33 @@+"""``wikicode serve`` — start the FastAPI web server."""++from __future__ import annotations++import click++from wikicode.cli.helpers import console++[email protected]("serve")[email protected]("--port", default=7337, type=int, help="Port to listen on.")[email protected]("--host", default="127.0.0.1", help="Host to bind to.")[email protected]("--workers", default=1, type=int, help="Number of uvicorn workers.")+def serve_command(port: int, host: str, workers: int) -> None:+ """Start a local web server for browsing wiki pages."""+ try:+ import uvicorn+ except ImportError:+ console.print(+ "[red]uvicorn is not installed. "+ "Install wikicode-server: pip install wikicode-server[/red]"+ )+ raise SystemExit(1)++ console.print(f"[green]Starting WikiCode server on {host}:{port}[/green]")+ uvicorn.run(+ "wikicode.server.app:create_app",+ factory=True,+ host=host,+ port=port,+ workers=workers,+ log_level="info",+ )diff --git a/packages/cli/src/wikicode/cli/commands/status_cmd.py b/packages/cli/src/wikicode/cli/commands/status_cmd.pynew file mode 100644index 000000000..438212bb9--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/status_cmd.py@@ -0,0 +1,88 @@+"""``wikicode status`` — show sync state and page counts."""++from __future__ import annotations++import click+from rich.table import Table++from wikicode.cli.helpers import (+ console,+ get_db_url_for_repo,+ get_wikicode_dir,+ load_state,+ resolve_repo_path,+ run_async,+)++[email protected]("status")[email protected]("path", required=False, default=None)+def status_command(path: str | None) -> None:+ """Show wiki sync state and page statistics."""+ repo_path = resolve_repo_path(path)+ wikicode_dir = get_wikicode_dir(repo_path)++ if not wikicode_dir.exists():+ console.print("[yellow]No .wikicode/ directory found. Run 'wikicode init' first.[/yellow]")+ return++ state = load_state(repo_path)++ # State table+ state_table = Table(title="Sync State")+ state_table.add_column("Key", style="cyan")+ state_table.add_column("Value")+ state_table.add_row("Last sync commit", state.get("last_sync_commit", "—") or "—")+ state_table.add_row("Total pages", str(state.get("total_pages", 0)))+ state_table.add_row("Provider", state.get("provider", "—") or "—")+ state_table.add_row("Model", state.get("model", "—") or "—")+ state_table.add_row("Total tokens", f"{state.get('total_tokens', 0):,}")+ console.print(state_table)++ # Page counts from DB+ db_path = wikicode_dir / "wiki.db"+ if not db_path.exists():+ console.print("[yellow]Database not found.[/yellow]")+ return++ async def _query_pages():+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ get_repository_by_path,+ get_session,+ list_pages,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ sf = create_session_factory(engine)++ counts: dict[str, int] = {}+ total_tokens = 0++ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ await engine.dispose()+ return counts, total_tokens+ pages = await list_pages(session, repo.id, limit=10000)+ for p in pages:+ counts[p.page_type] = counts.get(p.page_type, 0) + 1+ total_tokens += (p.input_tokens or 0) + (p.output_tokens or 0)++ await engine.dispose()+ return counts, total_tokens++ counts, total_db_tokens = run_async(_query_pages())++ if counts:+ pages_table = Table(title="Pages by Type")+ pages_table.add_column("Page Type", style="cyan")+ pages_table.add_column("Count", justify="right")+ for ptype, count in sorted(counts.items()):+ pages_table.add_row(ptype, str(count))+ pages_table.add_section()+ pages_table.add_row("[bold]Total[/bold]", f"[bold]{sum(counts.values())}[/bold]")+ pages_table.add_row("Total tokens", f"{total_db_tokens:,}")+ console.print(pages_table)diff --git a/packages/cli/src/wikicode/cli/commands/update_cmd.py b/packages/cli/src/wikicode/cli/commands/update_cmd.pynew file mode 100644index 000000000..452498539--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/update_cmd.py@@ -0,0 +1,237 @@+"""``wikicode update`` — incremental wiki regeneration for changed files."""++from __future__ import annotations++import time++import click+from rich.table import Table++from wikicode.cli.helpers import (+ console,+ ensure_wikicode_dir,+ get_head_commit,+ load_config,+ load_state,+ resolve_provider,+ resolve_repo_path,+ run_async,+ save_state,+)++[email protected]("update")[email protected]("path", required=False, default=None)[email protected]("--provider", "provider_name", default=None, help="LLM provider name.")[email protected]("--model", default=None, help="Model identifier override.")[email protected]("--since", default=None, help="Base git ref to diff from (overrides state).")[email protected]("--cascade-budget", type=int, default=30, help="Max pages to regenerate per run.")[email protected]("--dry-run", is_flag=True, default=False, help="Show affected pages without regenerating.")+def update_command(+ path: str | None,+ provider_name: str | None,+ model: str | None,+ since: str | None,+ cascade_budget: int,+ dry_run: bool,+) -> None:+ """Incrementally update wiki pages for files changed since last sync."""+ start = time.monotonic()+ repo_path = resolve_repo_path(path)+ ensure_wikicode_dir(repo_path)++ state = load_state(repo_path)+ base_ref = since or state.get("last_sync_commit")+ head = get_head_commit(repo_path)++ if base_ref is None:+ raise click.ClickException(+ "No previous sync found. Run 'wikicode init' first or pass --since."+ )++ if head and head == base_ref:+ console.print("[green]Already up to date.[/green]")+ return++ console.print(f"[bold]WikiCode update[/bold] — {repo_path}")+ console.print(f"Diffing [cyan]{base_ref[:8]}..{(head or 'HEAD')[:8]}[/cyan]")++ from wikicode.core.ingestion import ChangeDetector++ detector = ChangeDetector(repo_path)+ file_diffs = detector.get_changed_files(base_ref, head or "HEAD")++ if not file_diffs:+ console.print("[green]No changed files detected.[/green]")+ save_state(repo_path, {**state, "last_sync_commit": head})+ return++ console.print(f"Changed files: [yellow]{len(file_diffs)}[/yellow]")++ # Show changed files+ for fd in file_diffs:+ status_color = {"added": "green", "deleted": "red", "modified": "yellow", "renamed": "blue"}+ color = status_color.get(fd.status, "white")+ console.print(f" [{color}]{fd.status:>10}[/{color}] {fd.path}")++ if dry_run:+ console.print("[yellow]Dry run — no pages regenerated.[/yellow]")+ return++ # Re-parse changed files and rebuild graph for affected pages+ from pathlib import Path as PathlibPath++ from wikicode.core.generation import ContextAssembler, GenerationConfig, PageGenerator+ from wikicode.core.ingestion import ASTParser, FileTraverser, GraphBuilder++ provider = resolve_provider(provider_name, model)+ config = GenerationConfig()++ # Read exclude patterns from config (set during init or via web UI)+ repo_config = load_config(repo_path)+ exclude_patterns: list[str] = list(repo_config.get("exclude_patterns") or [])++ # Full re-ingest for graph (needed for cascade analysis)+ traverser = FileTraverser(repo_path, extra_exclude_patterns=exclude_patterns or None)+ file_infos = list(traverser.traverse())+ repo_structure = traverser.get_repo_structure()++ parser = ASTParser()+ parsed_files = []+ source_map: dict[str, bytes] = {}+ graph_builder = GraphBuilder()++ for fi in file_infos:+ try:+ source = PathlibPath(fi.abs_path).read_bytes()+ parsed = parser.parse_file(fi, source)+ parsed_files.append(parsed)+ source_map[fi.path] = source+ graph_builder.add_file(parsed)+ except Exception:+ pass+ graph_builder.build()++ # Re-index git metadata for changed files+ git_meta_map: dict[str, dict] = {}+ try:+ from wikicode.core.ingestion.git_indexer import GitIndexer++ git_indexer = GitIndexer(repo_path)+ changed_paths = [fd.path for fd in file_diffs]+ updated_meta = run_async(git_indexer.index_changed_files(changed_paths))+ git_meta_map = {m["file_path"]: m for m in updated_meta}+ graph_builder.update_co_change_edges(git_meta_map)+ except Exception as exc:+ console.print(f"[yellow]Git re-index skipped: {exc}[/yellow]")++ # Re-scan changed files for inline decision markers+ new_decision_markers: list = []+ try:+ from wikicode.core.analysis.decision_extractor import DecisionExtractor++ changed_paths = [fd.path for fd in file_diffs if fd.status in ("added", "modified")]+ if changed_paths:+ extractor = DecisionExtractor(+ repo_path=repo_path,+ provider=provider,+ graph=graph_builder.graph(),+ git_meta_map=git_meta_map,+ )+ new_decision_markers = run_async(+ extractor.scan_inline_markers(restrict_to_files=changed_paths)+ )+ if new_decision_markers:+ console.print(+ f"New decision markers found: [green]{len(new_decision_markers)}[/green]"+ )+ except Exception as exc:+ console.print(f"[yellow]Decision re-scan skipped: {exc}[/yellow]")++ # Determine affected pages+ affected = detector.get_affected_pages(file_diffs, graph_builder.graph(), cascade_budget)++ console.print(f"Pages to regenerate: [cyan]{len(affected.regenerate)}[/cyan]")+ if affected.decay_only:+ console.print(f"Pages to decay: [yellow]{len(affected.decay_only)}[/yellow]")++ # Generate affected pages+ assembler = ContextAssembler(config)+ generator = PageGenerator(provider, assembler, config)+ repo_name = repo_path.name++ generated_pages = run_async(+ generator.generate_all(+ parsed_files,+ source_map,+ graph_builder,+ repo_structure,+ repo_name,+ )+ )++ # Persist+ async def _persist() -> None:+ from wikicode.core.persistence import (+ FullTextSearch,+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_page_from_generated,+ upsert_repository,+ )++ from wikicode.cli.helpers import get_db_url_for_repo++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)++ async with get_session(sf) as session:+ repo = await upsert_repository(session, name=repo_name, local_path=str(repo_path))+ repo_id = repo.id+ for page in generated_pages:+ await upsert_page_from_generated(session, page, repo_id)++ # Decision records: persist new markers + recompute staleness+ try:+ if new_decision_markers:+ import dataclasses as _dc++ from wikicode.core.persistence.crud import bulk_upsert_decisions++ async with get_session(sf) as session:+ await bulk_upsert_decisions(+ session,+ repo_id,+ [_dc.asdict(d) for d in new_decision_markers],+ )++ if git_meta_map:+ from wikicode.core.persistence.crud import recompute_decision_staleness++ async with get_session(sf) as session:+ await recompute_decision_staleness(session, repo_id, git_meta_map)+ except Exception:+ pass # never fail update due to decision processing++ fts = FullTextSearch(engine)+ await fts.ensure_index()+ for page in generated_pages:+ await fts.index(page.page_id, page.title, page.content)++ await engine.dispose()++ run_async(_persist())++ # Update state+ state["last_sync_commit"] = head+ state["total_pages"] = state.get("total_pages", 0) + len(generated_pages)+ save_state(repo_path, state)++ elapsed = time.monotonic() - start+ console.print(+ f"[bold green]Updated {len(generated_pages)} pages in {elapsed:.1f}s[/bold green]"+ )diff --git a/packages/cli/src/wikicode/cli/commands/watch_cmd.py b/packages/cli/src/wikicode/cli/commands/watch_cmd.pynew file mode 100644index 000000000..6d11c5ae5--- /dev/null+++ b/packages/cli/src/wikicode/cli/commands/watch_cmd.py@@ -0,0 +1,99 @@+"""``wikicode watch`` — watch for file changes and auto-update."""++from __future__ import annotations++import threading+import time+from pathlib import Path++import click++from wikicode.cli.helpers import (+ console,+ ensure_wikicode_dir,+ resolve_repo_path,+)++[email protected]("watch")[email protected]("path", required=False, default=None)[email protected]("--provider", "provider_name", default=None, help="LLM provider name.")[email protected]("--model", default=None, help="Model identifier override.")[email protected]("--debounce", "debounce_ms", type=int, default=2000, help="Debounce delay in ms.")+def watch_command(+ path: str | None,+ provider_name: str | None,+ model: str | None,+ debounce_ms: int,+) -> None:+ """Watch for file changes and auto-update wiki pages."""+ from watchdog.events import FileSystemEventHandler+ from watchdog.observers import Observer++ repo_path = resolve_repo_path(path)+ ensure_wikicode_dir(repo_path)++ changed_paths: set[str] = set()+ lock = threading.Lock()+ timer: threading.Timer | None = None++ def _on_trigger() -> None:+ nonlocal timer+ with lock:+ paths = set(changed_paths)+ changed_paths.clear()+ timer = None++ if not paths:+ return++ console.print(f"[cyan]Detected {len(paths)} changed file(s), updating...[/cyan]")+ try:+ # Invoke update via Click context+ from click.testing import CliRunner++ from wikicode.cli.commands.update_cmd import update_command++ runner = CliRunner()+ args = [str(repo_path)]+ if provider_name:+ args.extend(["--provider", provider_name])+ if model:+ args.extend(["--model", model])+ result = runner.invoke(update_command, args, catch_exceptions=False)+ if result.output:+ console.print(result.output)+ except Exception as e:+ console.print(f"[red]Update failed: {e}[/red]")++ class WikiCodeHandler(FileSystemEventHandler):+ def on_any_event(self, event):+ nonlocal timer+ if event.is_directory:+ return+ # Ignore .wikicode/ directory changes+ rel = str(Path(event.src_path).relative_to(repo_path))+ if rel.startswith(".wikicode"):+ return++ with lock:+ changed_paths.add(rel)+ if timer is not None:+ timer.cancel()+ timer = threading.Timer(debounce_ms / 1000.0, _on_trigger)+ timer.daemon = True+ timer.start()++ observer = Observer()+ observer.schedule(WikiCodeHandler(), str(repo_path), recursive=True)+ observer.start()++ console.print(f"[bold]Watching {repo_path}... Ctrl+C to stop[/bold]")++ try:+ while True:+ time.sleep(1)+ except KeyboardInterrupt:+ observer.stop()+ console.print("\n[yellow]Stopped watching.[/yellow]")+ observer.join()diff --git a/packages/cli/src/wikicode/cli/cost_estimator.py b/packages/cli/src/wikicode/cli/cost_estimator.pynew file mode 100644index 000000000..edc9667b2--- /dev/null+++ b/packages/cli/src/wikicode/cli/cost_estimator.py@@ -0,0 +1,241 @@+"""Pre-generation cost estimation — mirrors page_generator.generate_all() selection logic."""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path+from typing import Any+++# ---------------------------------------------------------------------------+# Infra / significance helpers (mirrored from page_generator.py)+# ---------------------------------------------------------------------------++_INFRA_LANGUAGES = frozenset({"dockerfile", "makefile", "terraform", "shell"})+_INFRA_FILENAMES = frozenset({"Dockerfile", "Makefile", "GNUmakefile"})+_CODE_LANGUAGES = frozenset({+ "python", "typescript", "javascript", "go", "rust",+ "java", "cpp", "c", "csharp", "ruby", "kotlin", "scala",+ "swift", "php",+})+++def _is_infra_file(parsed: Any) -> bool:+ lang = parsed.file_info.language+ if lang in _INFRA_LANGUAGES:+ return True+ name = Path(parsed.file_info.path).name+ return name in _INFRA_FILENAMES+++def _is_significant_file(+ parsed: Any,+ pagerank: dict[str, float],+ betweenness: dict[str, float],+ config: Any,+ pr_threshold: float,+) -> bool:+ if len(parsed.symbols) < config.file_page_min_symbols:+ return False+ path = parsed.file_info.path+ return (+ parsed.file_info.is_entry_point+ or pagerank.get(path, 0.0) >= pr_threshold+ or betweenness.get(path, 0.0) > 0.0+ )+++# ---------------------------------------------------------------------------+# Plan and estimate data types+# ---------------------------------------------------------------------------+++@dataclass+class PageTypePlan:+ """Count of pages to generate for a given page type."""++ page_type: str+ count: int+ level: int+++@dataclass+class CostEstimate:+ """Estimated cost for a generation run."""++ plans: list[PageTypePlan] = field(default_factory=list)+ total_pages: int = 0+ estimated_input_tokens: int = 0+ estimated_output_tokens: int = 0+ estimated_cost_usd: float = 0.0+ provider_name: str = ""+ model_name: str = ""+++# Token heuristics per page type (input, output)+_TOKEN_HEURISTICS: dict[str, tuple[int, int]] = {+ "api_contract": (3000, 2000),+ "symbol_spotlight": (2000, 1500),+ "file_page": (4000, 2500),+ "scc_page": (3000, 2000),+ "module_page": (4000, 2500),+ "repo_overview": (5000, 3000),+ "architecture_diagram": (4000, 2500),+ "infra_page": (2000, 1500),+}++# Cost per 1K tokens (input, output) by model prefix+_COST_TABLE: dict[str, tuple[float, float]] = {+ "claude": (0.003, 0.015),+ "gpt-4o": (0.005, 0.015),+ "gpt-4": (0.03, 0.06),+ "gpt-3.5": (0.0005, 0.0015),+ "llama": (0.0, 0.0),+ "mock": (0.0, 0.0),+}+++def build_generation_plan(+ parsed_files: list[Any],+ graph_builder: Any,+ config: Any,+ skip_tests: bool = False,+ skip_infra: bool = False,+) -> list[PageTypePlan]:+ """Replicate the page selection logic from ``generate_all()`` without calling the LLM.++ Returns a list of :class:`PageTypePlan` entries — one per page type.+ """+ graph = graph_builder.graph()+ pagerank = graph_builder.pagerank()+ betweenness = graph_builder.betweenness_centrality()+ sccs = graph_builder.strongly_connected_components()++ plans: list[PageTypePlan] = []++ # Optionally filter+ files = parsed_files+ if skip_tests:+ files = [p for p in files if not p.file_info.is_test]++ # Level 0: api_contract+ api_count = sum(1 for p in files if p.file_info.is_api_contract)+ if api_count:+ plans.append(PageTypePlan("api_contract", api_count, 0))++ # Level 1: symbol_spotlight (top percentile public symbols by PageRank)+ all_public_symbols = []+ for p in files:+ for sym in p.symbols:+ if sym.visibility == "public":+ all_public_symbols.append((sym, p))+ n_top_sym = max(1, int(len(all_public_symbols) * config.top_symbol_percentile)) if all_public_symbols else 0+ if n_top_sym:+ plans.append(PageTypePlan("symbol_spotlight", n_top_sym, 1))++ # Level 2: file_page (significant code files)+ code_files = [+ p for p in files+ if not p.file_info.is_api_contract+ and not _is_infra_file(p)+ and p.file_info.language in _CODE_LANGUAGES+ ]+ code_pr_scores = sorted(+ [pagerank.get(p.file_info.path, 0.0) for p in code_files],+ reverse=True,+ )+ n_top_files = max(1, int(len(code_pr_scores) * config.file_page_top_percentile)) if code_pr_scores else 0+ pr_threshold = code_pr_scores[n_top_files - 1] if code_pr_scores else 0.0++ file_page_count = sum(+ 1 for p in code_files+ if _is_significant_file(p, pagerank, betweenness, config, pr_threshold)+ )+ if file_page_count:+ plans.append(PageTypePlan("file_page", file_page_count, 2))++ # Level 3: scc_page (cycles with len > 1)+ scc_count = sum(1 for scc in sccs if len(scc) > 1)+ if scc_count:+ plans.append(PageTypePlan("scc_page", scc_count, 3))++ # Level 4: module_page (top-level directory grouping)+ modules: set[str] = set()+ for p in code_files:+ parts = Path(p.file_info.path).parts+ modules.add(parts[0] if len(parts) > 1 else "root")+ if modules:+ plans.append(PageTypePlan("module_page", len(modules), 4))++ # Level 6: repo_overview + architecture_diagram+ plans.append(PageTypePlan("repo_overview", 1, 6))+ plans.append(PageTypePlan("architecture_diagram", 1, 6))++ # Level 7: infra_page+ if not skip_infra:+ infra_count = sum(1 for p in files if _is_infra_file(p))+ if infra_count:+ plans.append(PageTypePlan("infra_page", infra_count, 7))++ # Global budget cap: total pages ≤ max(50, N_files * max_pages_pct).+ # Fixed overhead pages (repo_overview, arch, module, scc, api_contract) are+ # always kept. file_page has priority over symbol_spotlight, which has+ # priority over infra_page.+ budget = max(50, int(len(files) * config.max_pages_pct))+ _FIXED = {"repo_overview", "architecture_diagram", "module_page", "scc_page", "api_contract"}+ _PRIORITY = ["file_page", "symbol_spotlight", "infra_page"]++ fixed_plans = [p for p in plans if p.page_type in _FIXED]+ adjustable = {p.page_type: p for p in plans if p.page_type not in _FIXED}+ fixed_total = sum(p.count for p in fixed_plans)+ remaining = max(0, budget - fixed_total)++ if sum(p.count for p in adjustable.values()) > remaining:+ new_adjustable: list[PageTypePlan] = []+ left = remaining+ for pt in _PRIORITY:+ p = adjustable.get(pt)+ if p:+ take = min(p.count, left)+ if take > 0:+ new_adjustable.append(PageTypePlan(pt, take, p.level))+ left = max(0, left - take)+ plans = sorted(fixed_plans + new_adjustable, key=lambda p: p.level)++ return plans+++def estimate_cost(+ plans: list[PageTypePlan],+ provider_name: str,+ model_name: str,+) -> CostEstimate:+ """Estimate token counts and USD cost from a generation plan."""+ total_pages = sum(p.count for p in plans)+ total_input = 0+ total_output = 0++ for plan in plans:+ inp, out = _TOKEN_HEURISTICS.get(plan.page_type, (3000, 2000))+ total_input += inp * plan.count+ total_output += out * plan.count++ # Find cost rates+ input_rate, output_rate = 0.0, 0.0+ model_lower = model_name.lower()+ for prefix, rates in _COST_TABLE.items():+ if prefix in model_lower:+ input_rate, output_rate = rates+ break++ cost = (total_input / 1000) * input_rate + (total_output / 1000) * output_rate++ return CostEstimate(+ plans=plans,+ total_pages=total_pages,+ estimated_input_tokens=total_input,+ estimated_output_tokens=total_output,+ estimated_cost_usd=cost,+ provider_name=provider_name,+ model_name=model_name,+ )diff --git a/packages/cli/src/wikicode/cli/helpers.py b/packages/cli/src/wikicode/cli/helpers.pynew file mode 100644index 000000000..e8573c3b7--- /dev/null+++ b/packages/cli/src/wikicode/cli/helpers.py@@ -0,0 +1,257 @@+"""Shared CLI utilities — async bridge, path resolution, state, DB setup."""++from __future__ import annotations++import asyncio+import json+import os+from pathlib import Path+from typing import Any, TypeVar++CONFIG_FILENAME = "config.yaml"++from rich.console import Console++T = TypeVar("T")++console = Console()+err_console = Console(stderr=True)++STATE_FILENAME = "state.json"+DB_FILENAME = "wiki.db"+WIKICODE_DIR = ".wikicode"+++# ---------------------------------------------------------------------------+# Async bridge+# ---------------------------------------------------------------------------+++def run_async(coro: Any) -> Any:+ """Run an async coroutine from synchronous Click code."""+ return asyncio.run(coro)+++# ---------------------------------------------------------------------------+# Path resolution+# ---------------------------------------------------------------------------+++def resolve_repo_path(path: str | None) -> Path:+ """Resolve the repository root path from a CLI argument.++ If *path* is ``None``, defaults to the current working directory.+ Always returns an absolute, resolved ``Path``.+ """+ if path is None:+ return Path.cwd().resolve()+ return Path(path).resolve()+++def get_wikicode_dir(repo_path: Path) -> Path:+ """Return the ``.wikicode/`` directory for a given repo root."""+ return repo_path / WIKICODE_DIR+++def ensure_wikicode_dir(repo_path: Path) -> Path:+ """Create the ``.wikicode/`` directory if it does not exist and return it."""+ d = get_wikicode_dir(repo_path)+ d.mkdir(parents=True, exist_ok=True)+ return d+++# ---------------------------------------------------------------------------+# Database+# ---------------------------------------------------------------------------+++def get_db_url_for_repo(repo_path: Path) -> str:+ """Return a database URL for this repo.++ If ``WIKICODE_DB_URL`` is set in the environment that URL is used (allows+ multiple repos to share a single central database). Otherwise falls back+ to the per-repo ``<repo>/.wikicode/wiki.db`` SQLite file.+ """+ env_url = os.environ.get("WIKICODE_DB_URL")+ if env_url:+ return env_url+ db_path = get_wikicode_dir(repo_path) / DB_FILENAME+ return f"sqlite+aiosqlite:///{db_path}"+++async def _ensure_db_async(repo_path: Path) -> tuple[Any, Any]:+ from wikicode.core.persistence import (+ create_engine,+ create_session_factory,+ init_db,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ session_factory = create_session_factory(engine)+ return engine, session_factory+++def ensure_db(repo_path: Path) -> tuple[Any, Any]:+ """Create the DB engine, initialise the schema, and return ``(engine, session_factory)``."""+ return run_async(_ensure_db_async(repo_path))+++# ---------------------------------------------------------------------------+# State file+# ---------------------------------------------------------------------------+++def load_state(repo_path: Path) -> dict[str, Any]:+ """Load ``.wikicode/state.json`` or return an empty dict if absent."""+ state_path = get_wikicode_dir(repo_path) / STATE_FILENAME+ if state_path.exists():+ return json.loads(state_path.read_text(encoding="utf-8"))+ return {}+++def save_state(repo_path: Path, state: dict[str, Any]) -> None:+ """Write *state* to ``.wikicode/state.json``."""+ ensure_wikicode_dir(repo_path)+ state_path = get_wikicode_dir(repo_path) / STATE_FILENAME+ state_path.write_text(json.dumps(state, indent=2), encoding="utf-8")+++# ---------------------------------------------------------------------------+# Git helpers+# ---------------------------------------------------------------------------+++def get_head_commit(repo_path: Path) -> str | None:+ """Return the HEAD commit SHA or ``None`` if not a git repo."""+ try:+ import git as gitpython++ repo = gitpython.Repo(repo_path, search_parent_directories=True)+ sha = repo.head.commit.hexsha+ repo.close()+ return sha+ except Exception:+ return None+++# ---------------------------------------------------------------------------+# Config (provider / model / embedder persisted after init)+# ---------------------------------------------------------------------------+++def load_config(repo_path: Path) -> dict[str, Any]:+ """Load ``.wikicode/config.yaml`` or return an empty dict if absent."""+ config_path = get_wikicode_dir(repo_path) / CONFIG_FILENAME+ if not config_path.exists():+ return {}+ text = config_path.read_text(encoding="utf-8")+ try:+ import yaml # type: ignore[import-untyped]+ return yaml.safe_load(text) or {}+ except ImportError:+ # Simple line-by-line parser for the flat key: value format we write+ result: dict[str, Any] = {}+ for line in text.splitlines():+ if ":" in line:+ k, _, v = line.partition(":")+ result[k.strip()] = v.strip()+ return result+++def save_config(+ repo_path: Path,+ provider: str,+ model: str,+ embedder: str,+ *,+ exclude_patterns: list[str] | None = None,+) -> None:+ """Write provider/model/embedder (and optionally exclude_patterns) to ``.wikicode/config.yaml``.++ Performs a round-trip load so existing keys are preserved.+ """+ ensure_wikicode_dir(repo_path)+ config_path = get_wikicode_dir(repo_path) / CONFIG_FILENAME++ # Round-trip: preserve any existing keys (e.g. exclude_patterns set via CLI)+ existing = load_config(repo_path)+ existing["provider"] = provider+ existing["model"] = model+ existing["embedder"] = embedder+ if exclude_patterns is not None:+ existing["exclude_patterns"] = exclude_patterns++ try:+ import yaml # type: ignore[import-untyped]+ config_path.write_text(+ yaml.dump(existing, default_flow_style=False, sort_keys=False),+ encoding="utf-8",+ )+ except ImportError:+ # Fallback: write simple key-value format (lists not supported)+ lines = [f"provider: {provider}", f"model: {model}", f"embedder: {embedder}"]+ config_path.write_text("\n".join(lines) + "\n", encoding="utf-8")+++# ---------------------------------------------------------------------------+# Provider resolution+# ---------------------------------------------------------------------------+++def resolve_provider(+ provider_name: str | None,+ model: str | None,+ repo_path: Path | None = None,+) -> Any:+ """Resolve a provider instance from CLI flags or environment variables.++ Resolution order:+ 1. Explicit ``--provider`` flag+ 2. ``WIKICODE_PROVIDER`` env var+ 3. ``.wikicode/config.yaml`` (written by ``wikicode init``)+ 4. Auto-detect from API key env vars+ """+ import os++ from wikicode.core.providers import get_provider++ if provider_name is None:+ provider_name = os.environ.get("WIKICODE_PROVIDER")++ if provider_name is None and repo_path is not None:+ cfg = load_config(repo_path)+ if cfg.get("provider"):+ provider_name = cfg["provider"]+ if model is None and cfg.get("model"):+ model = cfg["model"]++ if provider_name is not None:+ kwargs: dict[str, Any] = {}+ if model:+ kwargs["model"] = model+ return get_provider(provider_name, **kwargs)++ # Auto-detect from env vars+ if os.environ.get("ANTHROPIC_API_KEY"):+ kwargs = {"model": model} if model else {}+ return get_provider("anthropic", **kwargs)+ if os.environ.get("OPENAI_API_KEY"):+ kwargs = {"model": model} if model else {}+ return get_provider("openai", **kwargs)+ if os.environ.get("OLLAMA_BASE_URL"):+ kwargs = {"model": model} if model else {}+ return get_provider("ollama", **kwargs)+ if os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY"):+ kwargs = {"model": model} if model else {}+ return get_provider("gemini", **kwargs)++ raise click.ClickException(+ "No provider configured. Use --provider, set WIKICODE_PROVIDER, "+ "or set ANTHROPIC_API_KEY / OPENAI_API_KEY / OLLAMA_BASE_URL / GEMINI_API_KEY."+ )+++# Deferred import to avoid circular issues+import click # noqa: E402diff --git a/packages/cli/src/wikicode/cli/main.py b/packages/cli/src/wikicode/cli/main.pynew file mode 100644index 000000000..2d5c28475--- /dev/null+++ b/packages/cli/src/wikicode/cli/main.py@@ -0,0 +1,37 @@+"""WikiCode CLI — Click group and command registration."""++from __future__ import annotations++import click++from wikicode.cli import __version__+from wikicode.cli.commands.dead_code_cmd import dead_code_command+from wikicode.cli.commands.decision_cmd import decision_group+from wikicode.cli.commands.doctor_cmd import doctor_command+from wikicode.cli.commands.export_cmd import export_command+from wikicode.cli.commands.init_cmd import init_command+from wikicode.cli.commands.mcp_cmd import mcp_command+from wikicode.cli.commands.search_cmd import search_command+from wikicode.cli.commands.serve_cmd import serve_command+from wikicode.cli.commands.status_cmd import status_command+from wikicode.cli.commands.update_cmd import update_command+from wikicode.cli.commands.watch_cmd import watch_command++[email protected]_option(version=__version__, prog_name="wikicode")+def cli() -> None:+ """WikiCode -- AI-powered codebase documentation engine."""+++cli.add_command(init_command)+cli.add_command(update_command)+cli.add_command(dead_code_command)+cli.add_command(decision_group)+cli.add_command(search_command)+cli.add_command(export_command)+cli.add_command(status_command)+cli.add_command(doctor_command)+cli.add_command(watch_command)+cli.add_command(serve_command)+cli.add_command(mcp_command)diff --git a/packages/cli/src/wikicode/cli/mcp_config.py b/packages/cli/src/wikicode/cli/mcp_config.pynew file mode 100644index 000000000..7048f2542--- /dev/null+++ b/packages/cli/src/wikicode/cli/mcp_config.py@@ -0,0 +1,66 @@+"""Auto-generated MCP config for Claude Code, Cursor, and Cline."""++from __future__ import annotations++import json+from pathlib import Path+++def generate_mcp_config(repo_path: Path) -> dict:+ """Generate MCP config JSON for a repository.++ Returns a dict in the standard mcpServers format.+ """+ abs_path = str(repo_path.resolve()).replace("\\", "/")+ return {+ "mcpServers": {+ "wikicode": {+ "command": "wikicode",+ "args": ["mcp", abs_path, "--transport", "stdio"],+ "description": "WikiCode: live documentation for this codebase",+ }+ }+ }+++def save_mcp_config(repo_path: Path) -> Path:+ """Save MCP config to .wikicode/mcp.json and return the path."""+ wikicode_dir = repo_path / ".wikicode"+ wikicode_dir.mkdir(parents=True, exist_ok=True)+ config_path = wikicode_dir / "mcp.json"+ config = generate_mcp_config(repo_path)+ config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")+ return config_path+++def format_setup_instructions(repo_path: Path) -> str:+ """Return human-readable setup instructions for MCP clients."""+ config = generate_mcp_config(repo_path)+ server_block = json.dumps(config["mcpServers"]["wikicode"], indent=4)+ abs_path = str(repo_path.resolve()).replace("\\", "/")++ return f"""+MCP Server Configuration+========================++Add the following to your editor's MCP config:++Claude Code (~/.claude.json or ~/.claude/claude.json):+ "mcpServers": {{+ "wikicode": {server_block}+ }}++Cursor (.cursor/mcp.json):+ {server_block}++Cline (cline_mcp_settings.json):+ "mcpServers": {{+ "wikicode": {server_block}+ }}++Or run directly:+ wikicode mcp {abs_path}+ wikicode mcp {abs_path} --transport sse --port 7338++Config saved to: {repo_path / '.wikicode' / 'mcp.json'}+""".strip()diff --git a/packages/core/README.md b/packages/core/README.mdnew file mode 100644index 000000000..13fc081ef--- /dev/null+++ b/packages/core/README.md@@ -0,0 +1,259 @@+# wikicode-core++Core library for WikiCode — the ingestion pipeline, dependency graph engine, documentation generation system, and persistence layer. All other WikiCode packages depend on this.++**Python >= 3.11 · Apache-2.0**++---++## What's in this package++| Module | Purpose |+|--------|---------|+| `wikicode.core.ingestion` | File traversal, AST parsing (tree-sitter), dependency graph, change detection |+| `wikicode.core.generation` | Context assembly, page generation, Jinja2 prompt templates, job system |+| `wikicode.core.persistence` | SQLAlchemy models, async CRUD, full-text search, vector store |+| `wikicode.core.providers` | LLM provider abstraction (Anthropic, OpenAI, Ollama, LiteLLM) |+| `wikicode.core.analysis` | Dead code detection (unreachable files, unused exports, zombie packages) |+| `wikicode.core.rate_limiter` | Token-bucket rate limiter (RPM + TPM) for all LLM providers |++---++## Installation++```bash+# Core only (SQLite backend, no vector search)+pip install wikicode-core++# With LanceDB vector search (recommended for local/single-server deployments)+pip install "wikicode-core[search]"++# With pgvector (PostgreSQL deployments)+pip install "wikicode-core[pgvector]"+```++---++## Supported Languages++AST parsing uses [tree-sitter](https://tree-sitter.github.io/) with one `.scm` query file per language. Adding a new language means writing one `.scm` file — `ASTParser` itself does not change.++| Language | Extensions | Query file |+|----------|-----------|------------|+| Python | `.py` | `queries/python.scm` |+| TypeScript | `.ts`, `.tsx` | `queries/typescript.scm` |+| JavaScript | `.js`, `.jsx` | `queries/javascript.scm` |+| Go | `.go` | `queries/go.scm` |+| Rust | `.rs` | `queries/rust.scm` |+| Java | `.java` | `queries/java.scm` |+| C / C++ | `.c`, `.cpp`, `.h`, `.cc` | `queries/c.scm`, `queries/cpp.scm` |+| Ruby | `.rb` | `queries/ruby.scm` |+| Kotlin | `.kt` | `queries/kotlin.scm` |++**Special handlers** (purpose-built parsers, not tree-sitter):++- OpenAPI / Swagger specs (`.yaml`, `.json`)+- Protobuf (`.proto`)+- GraphQL schemas (`.graphql`)+- Dockerfiles+- GitHub Actions / CI YAML++---++## LLM Providers++| Provider | Name | Notes |+|----------|------|-------|+| Anthropic | `anthropic` | Prompt caching and Message Batches API (50% cost reduction on init) |+| OpenAI | `openai` | Any OpenAI-compatible endpoint |+| Ollama | `ollama` | Fully offline, no API key required |+| LiteLLM | `litellm` | 100+ providers through one interface (optional dependency) |+| Mock | `mock` | In-memory stub for tests — no network calls |++```python+from wikicode.core.providers import get_provider++provider = get_provider("anthropic", api_key="sk-ant-...", model="claude-sonnet-4-6")+response = await provider.generate(system_prompt="...", user_prompt="...")+print(response.content)+print(f"{response.input_tokens} in / {response.output_tokens} out")+```++### Registering a custom provider++```python+from wikicode.core.providers import register_provider+from my_package import MyProvider++register_provider("my_provider", lambda **kw: MyProvider(**kw))+provider = get_provider("my_provider", model="my-model-v1")+```++---++## Key Modules++### Ingestion++`FileTraverser` walks a repository tree respecting `.gitignore`, `.wikicodeIgnore`, a hardcoded blocklist (node_modules, `__pycache__`, build artifacts), auto-detected generated files, and binary files.++`ASTParser` is a single class for all languages. It loads the matching `.scm` query file, runs tree-sitter queries to extract symbols and imports, and returns a `ParsedFile` with a consistent shape regardless of language.++`GraphBuilder` converts all `ParsedFile` outputs into a `networkx.DiGraph` and computes PageRank, strongly connected components (SCCs), betweenness centrality, and community detection (Louvain). The resulting graph drives generation ordering, change propagation, and dead code detection.++`ChangeDetector` diffs two git refs with GitPython, identifies added/modified/deleted/renamed files, detects symbol renames using a signature-similarity heuristic, and determines which wiki pages need regeneration via cascade analysis.++```python+from wikicode.core.ingestion import FileTraverser, ASTParser, GraphBuilder, ChangeDetector+from pathlib import Path++# Traverse+traverser = FileTraverser("/path/to/repo")+file_infos = list(traverser.traverse())++# Parse all files+parser = ASTParser()+graph_builder = GraphBuilder()+parsed_files = []++for fi in file_infos:+ source = Path(fi.abs_path).read_bytes()+ parsed = parser.parse_file(fi, source)+ parsed_files.append(parsed)+ graph_builder.add_file(parsed)++graph_builder.build() # PageRank, SCCs, centrality+graph = graph_builder.graph() # networkx.DiGraph++# Change detection+detector = ChangeDetector("/path/to/repo")+diffs = detector.get_changed_files("a1b2c3d", "HEAD")+# → [FileDiff(path="src/auth.py", status="modified"), ...]+```++### Generation++`ContextAssembler` builds the prompt context for each page. For every file it assembles (in priority order, dropping lower-priority items when over the 12K-token budget): full source, symbol signatures, graph metrics, git ownership and commit history, import summaries from already-generated pages, RAG context from the vector store, co-change partner pages, dead code findings, and reverse import context.++`PageGenerator` orchestrates hierarchical generation across 9 levels (API contracts → symbol spotlights → file pages → SCC pages → module pages → cross-package pages → repo overview → infra pages → index pages). Within each level, up to `concurrent_jobs` tasks run in parallel via `asyncio.Semaphore`.++`JobSystem` checkpoints progress after every completed page so that a long init job can be resumed after an interruption.++```python+from wikicode.core.generation import ContextAssembler, GenerationConfig, PageGenerator++config = GenerationConfig()+assembler = ContextAssembler(config)+generator = PageGenerator(provider, assembler, config)++pages = await generator.generate_all(+ parsed_files, source_map, graph_builder, repo_structure, repo_name="my-repo"+)++for page in pages:+ print(page.title, page.page_type, f"{page.confidence_score:.2f}")+```++### Persistence++Two SQL backends (SQLite / PostgreSQL) with identical async SQLAlchemy models. Pass a plain `sqlite:///...` or `postgresql://...` URL — `get_db_url()` injects the correct async driver automatically.++```python+from wikicode.core.persistence import (+ create_engine, init_db, create_session_factory,+ get_session, upsert_repository, upsert_page_from_generated,+)++engine = create_engine("sqlite:///path/to/wiki.db")+await init_db(engine) # creates tables + FTS5 index (idempotent)+sf = create_session_factory(engine)++async with get_session(sf) as session:+ repo = await upsert_repository(session, name="my-repo", local_path="/path/to/repo")+ for page in pages:+ await upsert_page_from_generated(session, page, repo.id)+```++Key tables: `repos`, `wiki_pages`, `page_versions`, `wiki_symbols`, `generation_jobs`, `webhook_events`, `graph_nodes`, `graph_edges`, `git_metadata`, `dead_code_findings`.++### Search++```python+from wikicode.core.persistence import FullTextSearch, InMemoryVectorStore, MockEmbedder++# Full-text search (SQLite FTS5 or PostgreSQL GIN index)+fts = FullTextSearch(engine)+await fts.ensure_index()+results = await fts.search("authentication middleware", limit=10)++# Semantic search — swap MockEmbedder for a real embedder in production+store = InMemoryVectorStore(embedder=MockEmbedder())+results = await store.search("how does rate limiting work?", limit=5)+```++Vector store backends:++| Backend | When to use |+|---------|-------------|+| `InMemoryVectorStore` | Development / testing (no persistence) |+| `LanceDBVectorStore` | SQLite mode — embedded, no separate server, stored in `.wikicode/lancedb/` |+| `PgVectorStore` | PostgreSQL mode — HNSW index via the `pgvector` extension |++### Dead Code Detection++Finds unreachable files (in-degree 0 in the dependency graph), unused exports, unused internal symbols, and zombie packages. No LLM calls — purely graph analysis and git metadata.++```python+from wikicode.core.analysis.dead_code import DeadCodeAnalyzer++analyzer = DeadCodeAnalyzer(graph, git_meta_map)+report = analyzer.analyze({"min_confidence": 0.5})++for finding in report.findings:+ print(finding.kind.value, finding.file_path, f"{finding.confidence:.0%}")+ if finding.safe_to_delete:+ print(" -> safe to remove")++print(f"Deletable lines: {report.deletable_lines:,}")+```++---++## Page Types++WikiCode generates 9 distinct page types in a strict dependency-aware order:++| Level | Page Type | Description |+|-------|-----------|-------------|+| 0 | `api_contract` | OpenAPI specs, Protobuf, GraphQL schemas |+| 1 | `symbol_spotlight` | High-PageRank symbols (top 10% by centrality) |+| 2 | `file_page` | One page per source file |+| 3 | `scc_page` | Circular dependency cluster summary |+| 4 | `module_page` | Package/directory overview |+| 5 | `cross_package` | Cross-package relationships (monorepos) |+| 6 | `repo_overview` | Repository overview and architecture diagram |+| 7 | `infra_page` | Dockerfile, CI YAML, Makefile documentation |+| 8 | `index_page` | Symbol index, search index |++---++## Database Backends++| Backend | Config | Vector search |+|---------|--------|---------------|+| SQLite + LanceDB | `sqlite:///path/to/wiki.db` + `[search]` extra | LanceDB embedded in `.wikicode/lancedb/` |+| PostgreSQL + pgvector | `postgresql://user:pass@host/db` + `[pgvector]` extra | HNSW index on `wiki_pages.embedding` column |++---++## Development++```bash+# Install for development (from repo root)+uv pip install -e "packages/core[search]"++# Run tests+pytest tests/unit/core/+```++See [ARCHITECTURE.md](../../docs/ARCHITECTURE.md) for a deep dive into how the ingestion pipeline, generation engine, and three stores fit together.diff --git a/packages/core/alembic.ini b/packages/core/alembic.ininew file mode 100644index 000000000..1763e8d39--- /dev/null+++ b/packages/core/alembic.ini@@ -0,0 +1,63 @@+# A generic, single database configuration.++[alembic]+# path to migration scripts+script_location = alembic++# The URL is overridden at runtime via the DATABASE_URL environment variable+# or by the CLI / server startup code. This fallback is for local development.+sqlalchemy.url = sqlite+aiosqlite:///.wikicode/wiki.db++# template used to generate migration files+file_template = %%(rev)s_%%(slug)s++# sys.path path, will be prepended to sys.path if present.+prepend_sys_path = .++# version path separator; As mentioned above, this is the character used to split+# version_locations. The default within new alembic.ini files is "os", which uses+# os.pathsep. If this key is omitted entirely, it falls back to the legacy+# behavior of splitting on spaces and/or commas.+# version_path_separator = os # Use os.pathsep. Default configuration used for new projects.+# version_path_separator = ; # use semicolon as separator+# version_path_separator = , # use comma as separator+version_path_separator = os++# set to 'true' to run the environment during the 'revision' command,+# regardless of autogenerate+# revision_environment = false++# Logging configuration+[loggers]+keys = root,sqlalchemy,alembic++[handlers]+keys = console++[formatters]+keys = generic++[logger_root]+level = WARN+handlers = console+qualname =++[logger_sqlalchemy]+level = WARN+handlers =+qualname = sqlalchemy.engine++[logger_alembic]+level = INFO+handlers =+qualname = alembic++[handler_console]+class = StreamHandler+args = (sys.stderr,)+level = NOTSET+formatter = generic++[formatter_generic]+format = %(levelname)-5.5s [%(name)s] %(message)s+datefmt = %H:%M:%Sdiff --git a/packages/core/alembic/env.py b/packages/core/alembic/env.pynew file mode 100644index 000000000..5daa578f0--- /dev/null+++ b/packages/core/alembic/env.py@@ -0,0 +1,83 @@+"""Alembic environment for WikiCode async migrations.++Uses the run_sync pattern: context.run_migrations() is synchronous and must+be called inside an ``await connection.run_sync(...)`` block.++The database URL is resolved from (in order):+1. The DATABASE_URL environment variable.+2. The ``sqlalchemy.url`` value in alembic.ini.+"""++from __future__ import annotations++import asyncio+import os+from logging.config import fileConfig++from alembic import context+from sqlalchemy.ext.asyncio import create_async_engine++# Import the Base so Alembic can detect schema changes for autogenerate.+from wikicode.core.persistence.models import Base++# Alembic Config object (access to alembic.ini values)+config = context.config++# Set up logging from alembic.ini+if config.config_file_name is not None:+ fileConfig(config.config_file_name)++target_metadata = Base.metadata+++def _get_url() -> str:+ url = os.environ.get("DATABASE_URL") or config.get_main_option("sqlalchemy.url", "")+ if not url:+ raise RuntimeError(+ "No database URL configured. "+ "Set the DATABASE_URL environment variable or sqlalchemy.url in alembic.ini."+ )+ # Normalise to async driver prefix+ if url.startswith("sqlite://") and "aiosqlite" not in url:+ url = url.replace("sqlite://", "sqlite+aiosqlite://", 1)+ elif (url.startswith("postgresql://") or url.startswith("postgres://")) and "asyncpg" not in url:+ url = url.replace("://", "+asyncpg://", 1)+ return url+++def run_migrations_offline() -> None:+ """Run migrations in 'offline' mode (no live DB connection required)."""+ url = _get_url()+ context.configure(+ url=url,+ target_metadata=target_metadata,+ literal_binds=True,+ dialect_opts={"paramstyle": "named"},+ )+ with context.begin_transaction():+ context.run_migrations()+++def do_run_migrations(connection) -> None: # type: ignore[no-untyped-def]+ context.configure(connection=connection, target_metadata=target_metadata)+ with context.begin_transaction():+ context.run_migrations()+++async def run_async_migrations() -> None:+ url = _get_url()+ connectable = create_async_engine(url)+ async with connectable.connect() as connection:+ await connection.run_sync(do_run_migrations)+ await connectable.dispose()+++def run_migrations_online() -> None:+ """Run migrations in 'online' mode (requires a live DB connection)."""+ asyncio.run(run_async_migrations())+++if context.is_offline_mode():+ run_migrations_offline()+else:+ run_migrations_online()diff --git a/packages/core/alembic/script.py.mako b/packages/core/alembic/script.py.makonew file mode 100644index 000000000..ee746cf6d--- /dev/null+++ b/packages/core/alembic/script.py.mako@@ -0,0 +1,28 @@+"""${message}++Revision ID: ${up_revision}+Revises: ${down_revision | comma,n}+Create Date: ${create_date}++"""+from __future__ import annotations++from typing import Sequence, Union++from alembic import op+import sqlalchemy as sa+${imports if imports else ""}++# revision identifiers, used by Alembic.+revision: str = ${repr(up_revision)}+down_revision: Union[str, None] = ${repr(down_revision)}+branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}+depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}+++def upgrade() -> None:+ ${upgrades if upgrades else "pass"}+++def downgrade() -> None:+ ${downgrades if downgrades else "pass"}diff --git a/packages/core/alembic/versions/0001_initial_schema.py b/packages/core/alembic/versions/0001_initial_schema.pynew file mode 100644index 000000000..ca986e5b2--- /dev/null+++ b/packages/core/alembic/versions/0001_initial_schema.py@@ -0,0 +1,338 @@+"""Initial WikiCode schema.++Creates all 8 tables. For PostgreSQL also:+- Installs the pgvector extension.+- Adds an ``embedding vector(1536)`` column to wiki_pages.+- Creates a GIN index for full-text search.++For SQLite:+- Creates the FTS5 virtual table for full-text search.++Revision ID: 0001+Revises: None+Create Date: 2026-03-19+"""++from __future__ import annotations++from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0001"+down_revision: Union[str, None] = None+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ # ------------------------------------------------------------------+ # repositories+ # ------------------------------------------------------------------+ op.create_table(+ "repositories",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column("name", sa.String(255), nullable=False),+ sa.Column("url", sa.Text, nullable=False, server_default=""),+ sa.Column("local_path", sa.Text, nullable=False),+ sa.Column("default_branch", sa.String(255), nullable=False, server_default="main"),+ sa.Column("head_commit", sa.String(40), nullable=True),+ sa.Column("settings_json", sa.Text, nullable=False, server_default="{}"),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.Column(+ "updated_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ )++ # ------------------------------------------------------------------+ # generation_jobs+ # ------------------------------------------------------------------+ op.create_table(+ "generation_jobs",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("status", sa.String(32), nullable=False, server_default="pending"),+ sa.Column("provider_name", sa.String(64), nullable=False, server_default=""),+ sa.Column("model_name", sa.String(128), nullable=False, server_default=""),+ sa.Column("total_pages", sa.Integer, nullable=False, server_default="0"),+ sa.Column("completed_pages", sa.Integer, nullable=False, server_default="0"),+ sa.Column("failed_pages", sa.Integer, nullable=False, server_default="0"),+ sa.Column("current_level", sa.Integer, nullable=False, server_default="0"),+ sa.Column("error_message", sa.Text, nullable=True),+ sa.Column("config_json", sa.Text, nullable=False, server_default="{}"),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.Column(+ "updated_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.Column("started_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),+ )++ # ------------------------------------------------------------------+ # wiki_pages+ # ------------------------------------------------------------------+ op.create_table(+ "wiki_pages",+ sa.Column("id", sa.Text, primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("page_type", sa.String(64), nullable=False),+ sa.Column("title", sa.Text, nullable=False),+ sa.Column("content", sa.Text, nullable=False),+ sa.Column("target_path", sa.Text, nullable=False),+ sa.Column("source_hash", sa.String(64), nullable=False),+ sa.Column("model_name", sa.String(128), nullable=False),+ sa.Column("provider_name", sa.String(64), nullable=False),+ sa.Column("input_tokens", sa.Integer, nullable=False, server_default="0"),+ sa.Column("output_tokens", sa.Integer, nullable=False, server_default="0"),+ sa.Column("cached_tokens", sa.Integer, nullable=False, server_default="0"),+ sa.Column("generation_level", sa.Integer, nullable=False, server_default="0"),+ sa.Column("version", sa.Integer, nullable=False, server_default="1"),+ sa.Column("confidence", sa.Float, nullable=False, server_default="1.0"),+ sa.Column(+ "freshness_status", sa.String(32), nullable=False, server_default="fresh"+ ),+ sa.Column("metadata_json", sa.Text, nullable=False, server_default="{}"),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),+ )++ # ------------------------------------------------------------------+ # wiki_page_versions+ # ------------------------------------------------------------------+ op.create_table(+ "wiki_page_versions",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "page_id",+ sa.Text,+ sa.ForeignKey("wiki_pages.id"),+ nullable=False,+ ),+ sa.Column("repository_id", sa.String(32), nullable=False),+ sa.Column("version", sa.Integer, nullable=False),+ sa.Column("page_type", sa.String(64), nullable=False),+ sa.Column("title", sa.Text, nullable=False),+ sa.Column("content", sa.Text, nullable=False),+ sa.Column("source_hash", sa.String(64), nullable=False),+ sa.Column("model_name", sa.String(128), nullable=False),+ sa.Column("provider_name", sa.String(64), nullable=False),+ sa.Column("input_tokens", sa.Integer, nullable=False, server_default="0"),+ sa.Column("output_tokens", sa.Integer, nullable=False, server_default="0"),+ sa.Column("confidence", sa.Float, nullable=False, server_default="1.0"),+ sa.Column(+ "archived_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ )++ # ------------------------------------------------------------------+ # graph_nodes+ # ------------------------------------------------------------------+ op.create_table(+ "graph_nodes",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("node_id", sa.Text, nullable=False),+ sa.Column("node_type", sa.String(32), nullable=False, server_default="file"),+ sa.Column("language", sa.String(32), nullable=False, server_default=""),+ sa.Column("symbol_count", sa.Integer, nullable=False, server_default="0"),+ sa.Column("has_error", sa.Boolean, nullable=False, server_default="0"),+ sa.Column("is_test", sa.Boolean, nullable=False, server_default="0"),+ sa.Column("is_entry_point", sa.Boolean, nullable=False, server_default="0"),+ sa.Column("pagerank", sa.Float, nullable=False, server_default="0.0"),+ sa.Column("betweenness", sa.Float, nullable=False, server_default="0.0"),+ sa.Column("community_id", sa.Integer, nullable=False, server_default="0"),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.UniqueConstraint("repository_id", "node_id", name="uq_graph_node"),+ )++ # ------------------------------------------------------------------+ # graph_edges+ # ------------------------------------------------------------------+ op.create_table(+ "graph_edges",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("source_node_id", sa.Text, nullable=False),+ sa.Column("target_node_id", sa.Text, nullable=False),+ sa.Column("imported_names_json", sa.Text, nullable=False, server_default="[]"),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.UniqueConstraint(+ "repository_id", "source_node_id", "target_node_id", name="uq_graph_edge"+ ),+ )++ # ------------------------------------------------------------------+ # webhook_events+ # ------------------------------------------------------------------+ op.create_table(+ "webhook_events",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="SET NULL"),+ nullable=True,+ ),+ sa.Column("provider", sa.String(32), nullable=False),+ sa.Column("event_type", sa.String(64), nullable=False),+ sa.Column("delivery_id", sa.String(128), nullable=False, server_default=""),+ sa.Column("payload_json", sa.Text, nullable=False, server_default="{}"),+ sa.Column("processed", sa.Boolean, nullable=False, server_default="0"),+ sa.Column(+ "job_id",+ sa.String(32),+ sa.ForeignKey("generation_jobs.id", ondelete="SET NULL"),+ nullable=True,+ ),+ sa.Column(+ "received_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ )++ # ------------------------------------------------------------------+ # wiki_symbols+ # ------------------------------------------------------------------+ op.create_table(+ "wiki_symbols",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("file_path", sa.Text, nullable=False),+ sa.Column("symbol_id", sa.Text, nullable=False),+ sa.Column("name", sa.String(255), nullable=False),+ sa.Column("qualified_name", sa.Text, nullable=False),+ sa.Column("kind", sa.String(32), nullable=False),+ sa.Column("signature", sa.Text, nullable=False, server_default=""),+ sa.Column("start_line", sa.Integer, nullable=False, server_default="0"),+ sa.Column("end_line", sa.Integer, nullable=False, server_default="0"),+ sa.Column("docstring", sa.Text, nullable=True),+ sa.Column(+ "visibility", sa.String(16), nullable=False, server_default="public"+ ),+ sa.Column("is_async", sa.Boolean, nullable=False, server_default="0"),+ sa.Column(+ "complexity_estimate", sa.Integer, nullable=False, server_default="0"+ ),+ sa.Column("language", sa.String(32), nullable=False, server_default=""),+ sa.Column("parent_name", sa.String(255), nullable=True),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.Column(+ "updated_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.UniqueConstraint("repository_id", "symbol_id", name="uq_wiki_symbol"),+ )++ # ------------------------------------------------------------------+ # Dialect-specific extras+ # ------------------------------------------------------------------+ bind = op.get_bind()+ dialect = bind.dialect.name++ if dialect == "postgresql":+ # Install pgvector extension and add embedding column+ op.execute("CREATE EXTENSION IF NOT EXISTS vector")+ op.add_column("wiki_pages", sa.Column("embedding", sa.Text, nullable=True))+ op.execute(+ "ALTER TABLE wiki_pages "+ "ALTER COLUMN embedding TYPE vector(1536) "+ "USING NULL::vector(1536)"+ )+ # GIN index for full-text search (maintained automatically)+ op.execute(+ "CREATE INDEX IF NOT EXISTS idx_wiki_pages_fts ON wiki_pages "+ "USING GIN("+ " to_tsvector('english', COALESCE(title,'') || ' ' || COALESCE(content,''))"+ ")"+ )++ elif dialect == "sqlite":+ # FTS5 virtual table for full-text search (SQLite only)+ op.execute(+ "CREATE VIRTUAL TABLE IF NOT EXISTS page_fts "+ "USING fts5(page_id UNINDEXED, title, content)"+ )+++def downgrade() -> None:+ bind = op.get_bind()+ dialect = bind.dialect.name++ if dialect == "sqlite":+ op.execute("DROP TABLE IF EXISTS page_fts")+ elif dialect == "postgresql":+ op.execute("DROP INDEX IF EXISTS idx_wiki_pages_fts")++ op.drop_table("wiki_symbols")+ op.drop_table("webhook_events")+ op.drop_table("graph_edges")+ op.drop_table("graph_nodes")+ op.drop_table("wiki_page_versions")+ op.drop_table("wiki_pages")+ op.drop_table("generation_jobs")+ op.drop_table("repositories")diff --git a/packages/core/alembic/versions/0002_git_intelligence_dead_code.py b/packages/core/alembic/versions/0002_git_intelligence_dead_code.pynew file mode 100644index 000000000..b22793ec9--- /dev/null+++ b/packages/core/alembic/versions/0002_git_intelligence_dead_code.py@@ -0,0 +1,128 @@+"""Add git_metadata and dead_code_findings tables for Phase 5.5.++Revision ID: 0002+Revises: 0001+Create Date: 2026-03-19+"""++from __future__ import annotations++from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0002"+down_revision: Union[str, None] = "0001"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ # ------------------------------------------------------------------+ # git_metadata+ # ------------------------------------------------------------------+ op.create_table(+ "git_metadata",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("file_path", sa.Text, nullable=False),+ # Commit volume+ sa.Column("commit_count_total", sa.Integer, nullable=False, server_default="0"),+ sa.Column("commit_count_90d", sa.Integer, nullable=False, server_default="0"),+ sa.Column("commit_count_30d", sa.Integer, nullable=False, server_default="0"),+ # Timeline+ sa.Column("first_commit_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("last_commit_at", sa.DateTime(timezone=True), nullable=True),+ # Ownership+ sa.Column("primary_owner_name", sa.String(255), nullable=True),+ sa.Column("primary_owner_email", sa.String(255), nullable=True),+ sa.Column("primary_owner_commit_pct", sa.Float, nullable=True),+ # JSON fields+ sa.Column("top_authors_json", sa.Text, nullable=False, server_default="[]"),+ sa.Column(+ "significant_commits_json", sa.Text, nullable=False, server_default="[]"+ ),+ sa.Column(+ "co_change_partners_json", sa.Text, nullable=False, server_default="[]"+ ),+ # Derived signals+ sa.Column("is_hotspot", sa.Boolean, nullable=False, server_default="0"),+ sa.Column("is_stable", sa.Boolean, nullable=False, server_default="0"),+ sa.Column("churn_percentile", sa.Float, nullable=False, server_default="0.0"),+ sa.Column("age_days", sa.Integer, nullable=False, server_default="0"),+ # Timestamps+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.Column(+ "updated_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.UniqueConstraint("repository_id", "file_path", name="uq_git_metadata"),+ )+ op.create_index(+ "ix_git_metadata_repository_id", "git_metadata", ["repository_id"]+ )+ op.create_index(+ "ix_git_metadata_repo_file",+ "git_metadata",+ ["repository_id", "file_path"],+ )++ # ------------------------------------------------------------------+ # dead_code_findings+ # ------------------------------------------------------------------+ op.create_table(+ "dead_code_findings",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("kind", sa.String(32), nullable=False),+ sa.Column("file_path", sa.Text, nullable=False),+ sa.Column("symbol_name", sa.String(255), nullable=True),+ sa.Column("symbol_kind", sa.String(32), nullable=True),+ sa.Column("confidence", sa.Float, nullable=False, server_default="0.0"),+ sa.Column("reason", sa.Text, nullable=False, server_default=""),+ sa.Column("last_commit_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("commit_count_90d", sa.Integer, nullable=False, server_default="0"),+ sa.Column("lines", sa.Integer, nullable=False, server_default="0"),+ sa.Column("package", sa.String(255), nullable=True),+ sa.Column("evidence_json", sa.Text, nullable=False, server_default="[]"),+ sa.Column("safe_to_delete", sa.Boolean, nullable=False, server_default="0"),+ sa.Column("primary_owner", sa.String(255), nullable=True),+ sa.Column("age_days", sa.Integer, nullable=True),+ sa.Column("status", sa.String(32), nullable=False, server_default="open"),+ sa.Column("note", sa.Text, nullable=True),+ sa.Column(+ "analyzed_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ )+ op.create_index(+ "ix_dead_code_findings_repository_id",+ "dead_code_findings",+ ["repository_id"],+ )+++def downgrade() -> None:+ op.drop_table("dead_code_findings")+ op.drop_table("git_metadata")diff --git a/packages/core/alembic/versions/0003_decision_records.py b/packages/core/alembic/versions/0003_decision_records.pynew file mode 100644index 000000000..a71c748a7--- /dev/null+++ b/packages/core/alembic/versions/0003_decision_records.py@@ -0,0 +1,99 @@+"""Add decision_records table for Architectural Decision Intelligence layer.++Revision ID: 0003+Revises: 0002+Create Date: 2026-03-22+"""++from __future__ import annotations++from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0003"+down_revision: Union[str, None] = "0002"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.create_table(+ "decision_records",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ # Core content+ sa.Column("title", sa.Text, nullable=False),+ sa.Column("status", sa.String(32), nullable=False, server_default="proposed"),+ sa.Column("context", sa.Text, nullable=False, server_default=""),+ sa.Column("decision", sa.Text, nullable=False, server_default=""),+ sa.Column("rationale", sa.Text, nullable=False, server_default=""),+ # JSON arrays+ sa.Column("alternatives_json", sa.Text, nullable=False, server_default="[]"),+ sa.Column("consequences_json", sa.Text, nullable=False, server_default="[]"),+ sa.Column("affected_files_json", sa.Text, nullable=False, server_default="[]"),+ sa.Column(+ "affected_modules_json", sa.Text, nullable=False, server_default="[]"+ ),+ sa.Column("tags_json", sa.Text, nullable=False, server_default="[]"),+ sa.Column(+ "evidence_commits_json", sa.Text, nullable=False, server_default="[]"+ ),+ # Provenance+ sa.Column("source", sa.String(32), nullable=False, server_default="cli"),+ sa.Column("evidence_file", sa.Text, nullable=True),+ sa.Column("evidence_line", sa.Integer, nullable=True),+ sa.Column("confidence", sa.Float, nullable=False, server_default="1.0"),+ # Staleness+ sa.Column("last_code_change", sa.DateTime(timezone=True), nullable=True),+ sa.Column(+ "staleness_score", sa.Float, nullable=False, server_default="0.0"+ ),+ sa.Column("superseded_by", sa.String(32), nullable=True),+ # Timestamps+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.Column(+ "updated_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.UniqueConstraint(+ "repository_id",+ "title",+ "source",+ "evidence_file",+ name="uq_decision_record",+ ),+ )+ op.create_index(+ "ix_decision_records_repository_id",+ "decision_records",+ ["repository_id"],+ )+ op.create_index(+ "ix_decision_records_status",+ "decision_records",+ ["repository_id", "status"],+ )+ op.create_index(+ "ix_decision_records_source",+ "decision_records",+ ["repository_id", "source"],+ )+++def downgrade() -> None:+ op.drop_table("decision_records")diff --git a/packages/core/pyproject.toml b/packages/core/pyproject.tomlnew file mode 100644index 000000000..30a6c7866--- /dev/null+++ b/packages/core/pyproject.toml@@ -0,0 +1,89 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[project]+name = "wikicode-core"+version = "0.1.0"+description = "WikiCode core: ingestion pipeline, dependency graph, and documentation generation engine"+readme = "README.md"+requires-python = ">=3.11"+license = { text = "Apache-2.0" }+keywords = ["documentation", "codebase", "wiki", "llm", "ai"]+classifiers = [+ "Development Status :: 3 - Alpha",+ "Intended Audience :: Developers",+ "License :: OSI Approved :: Apache Software License",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ "Programming Language :: Python :: 3.13",+ "Topic :: Software Development :: Documentation",+ "Typing :: Typed",+]+dependencies = [+ # HTTP client (used by all providers)+ "httpx>=0.27,<1",+ # LLM providers+ "anthropic>=0.40,<1",+ "openai>=1.50,<2",+ "litellm>=1.50,<2",+ # AST parsing+ "tree-sitter>=0.23,<1",+ "tree-sitter-python>=0.23,<1",+ "tree-sitter-typescript>=0.23,<1",+ "tree-sitter-javascript>=0.23,<1",+ "tree-sitter-go>=0.23,<1",+ "tree-sitter-rust>=0.23,<1",+ "tree-sitter-java>=0.23,<1",+ "tree-sitter-cpp>=0.23,<1",+ # Dependency graph+ "networkx>=3.3,<4",+ "scipy>=1.11,<2",+ # Template rendering+ "jinja2>=3.1,<4",+ # File filtering+ "pathspec>=0.12,<1",+ # Structured logging+ "structlog>=24,<25",+ # Database (async)+ "sqlalchemy[asyncio]>=2.0,<3",+ "aiosqlite>=0.20,<1",+ "alembic>=1.13,<2",+ # Data validation+ "pydantic>=2.8,<3",+ # Retry logic+ "tenacity>=9,<10",+ # Git operations (ChangeDetector)+ "gitpython>=3.1,<4",+ # YAML parsing (OpenAPI handler)+ "pyyaml>=6.0,<7",+]++[project.optional-dependencies]+# Vector search (LanceDB backend — default for SQLite deployments).+# Pure Python wheel; no C++ build tools required.+# Install with: uv pip install wikicode-core[search]+# Added in Phase 4 of the build plan.+search = [+ "lancedb>=0.12,<1",+]+# pgvector backend — only needed when DATABASE_URL is PostgreSQL.+# Install with: uv pip install wikicode-core[pgvector]+pgvector = [+ "pgvector>=0.3,<1",+ "asyncpg>=0.29,<1",+]++[project.urls]+Homepage = "https://github.com/wikicode-ai/wikicode"+Repository = "https://github.com/wikicode-ai/wikicode"+Issues = "https://github.com/wikicode-ai/wikicode/issues"++[tool.hatch.build.targets.wheel]+# Namespace package: src/wikicode has no __init__.py+# Hatchling ships the wikicode/core/ slice of the wikicode namespace+packages = ["src/wikicode"]++[tool.uv]+package = truediff --git a/packages/core/queries/c.scm b/packages/core/queries/c.scmnew file mode 100644index 000000000..9ba3f3a26--- /dev/null+++ b/packages/core/queries/c.scm@@ -0,0 +1,35 @@+; =============================================================================+; WikiCode — C symbol and import queries+; Uses the tree-sitter-cpp grammar (superset of C)+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------++(function_definition+ declarator: (function_declarator+ declarator: (identifier) @symbol.name+ parameters: (parameter_list) @symbol.params+ )+) @symbol.def++(struct_specifier+ name: (type_identifier) @symbol.name+) @symbol.def++(enum_specifier+ name: (type_identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Imports (#include directives)+; ---------------------------------------------------------------------------++(preproc_include+ path: (system_lib_string) @import.module+) @import.statement++(preproc_include+ path: (string_literal) @import.module+) @import.statementdiff --git a/packages/core/queries/cpp.scm b/packages/core/queries/cpp.scmnew file mode 100644index 000000000..9a954c506--- /dev/null+++ b/packages/core/queries/cpp.scm@@ -0,0 +1,62 @@+; =============================================================================+; WikiCode — C++ symbol and import queries+; tree-sitter-cpp >= 0.23+; (Also used for .c files — C is a subset of this grammar for our purposes)+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------++; Function definition: ReturnType funcName(params) { body }+; The name is nested inside function_declarator+(function_definition+ declarator: (function_declarator+ declarator: (identifier) @symbol.name+ parameters: (parameter_list) @symbol.params+ )+) @symbol.def++; Qualified function definition: ReturnType ClassName::method(params) { }+(function_definition+ declarator: (function_declarator+ declarator: (qualified_identifier+ name: (identifier) @symbol.name+ )+ parameters: (parameter_list) @symbol.params+ )+) @symbol.def++; Class+(class_specifier+ name: (type_identifier) @symbol.name+) @symbol.def++; Struct+(struct_specifier+ name: (type_identifier) @symbol.name+) @symbol.def++; Enum (type_identifier is a direct child, not a named field in this grammar)+(enum_specifier+ (type_identifier) @symbol.name+) @symbol.def++; Namespace+(namespace_definition+ name: (namespace_identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Imports (#include directives)+; ---------------------------------------------------------------------------++; #include <header>+(preproc_include+ path: (system_lib_string) @import.module+) @import.statement++; #include "local_header"+(preproc_include+ path: (string_literal) @import.module+) @import.statementdiff --git a/packages/core/queries/go.scm b/packages/core/queries/go.scmnew file mode 100644index 000000000..5eb34d12e--- /dev/null+++ b/packages/core/queries/go.scm@@ -0,0 +1,36 @@+; =============================================================================+; WikiCode — Go symbol and import queries+; tree-sitter-go >= 0.23+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------++; Top-level function+(function_declaration+ name: (identifier) @symbol.name+ parameters: (parameter_list) @symbol.params+) @symbol.def++; Method with receiver — @symbol.receiver is used to determine parent type+(method_declaration+ receiver: (parameter_list) @symbol.receiver+ name: (field_identifier) @symbol.name+ parameters: (parameter_list) @symbol.params+) @symbol.def++; Type declaration (struct, interface, alias)+; type_spec is always inside type_declaration+(type_spec+ name: (type_identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Imports+; ---------------------------------------------------------------------------++; Single import: import "fmt"+(import_spec+ (interpreted_string_literal) @import.module+) @import.statementdiff --git a/packages/core/queries/java.scm b/packages/core/queries/java.scmnew file mode 100644index 000000000..37a9f5b51--- /dev/null+++ b/packages/core/queries/java.scm@@ -0,0 +1,44 @@+; =============================================================================+; WikiCode — Java symbol and import queries+; tree-sitter-java >= 0.23+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------++(class_declaration+ name: (identifier) @symbol.name+) @symbol.def++(interface_declaration+ name: (identifier) @symbol.name+) @symbol.def++(enum_declaration+ name: (identifier) @symbol.name+) @symbol.def++(method_declaration+ name: (identifier) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++(constructor_declaration+ name: (identifier) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++; Public modifier capture+(method_declaration+ (modifiers) @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Imports+; ---------------------------------------------------------------------------++(import_declaration+ (scoped_identifier) @import.module+) @import.statementdiff --git a/packages/core/queries/javascript.scm b/packages/core/queries/javascript.scmnew file mode 100644index 000000000..f617f72d6--- /dev/null+++ b/packages/core/queries/javascript.scm@@ -0,0 +1,45 @@+; =============================================================================+; WikiCode — JavaScript symbol and import queries+; tree-sitter-javascript >= 0.23+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------++(function_declaration+ name: (identifier) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++(generator_function_declaration+ name: (identifier) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++(class_declaration+ name: (identifier) @symbol.name+) @symbol.def++(method_definition+ name: (property_identifier) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++; Arrow function assigned to const/let+(lexical_declaration+ (variable_declarator+ name: (identifier) @symbol.name+ value: (arrow_function+ parameters: (formal_parameters) @symbol.params+ )+ )+) @symbol.def++; ---------------------------------------------------------------------------+; Imports+; ---------------------------------------------------------------------------++(import_statement+ source: (string) @import.module+) @import.statementdiff --git a/packages/core/queries/kotlin.scm b/packages/core/queries/kotlin.scmnew file mode 100644index 000000000..9f1f9c40b--- /dev/null+++ b/packages/core/queries/kotlin.scm@@ -0,0 +1,25 @@+; =============================================================================+; WikiCode — Kotlin symbol and import queries+; tree-sitter-kotlin (install separately if needed)+; =============================================================================++(function_declaration+ (simple_identifier) @symbol.name+ (function_value_parameters) @symbol.params+) @symbol.def++(class_declaration+ (type_identifier) @symbol.name+) @symbol.def++(object_declaration+ (type_identifier) @symbol.name+) @symbol.def++(interface_declaration+ (type_identifier) @symbol.name+) @symbol.def++(import_header+ (identifier) @import.module+) @import.statementdiff --git a/packages/core/queries/python.scm b/packages/core/queries/python.scmnew file mode 100644index 000000000..89e6c6ff4--- /dev/null+++ b/packages/core/queries/python.scm@@ -0,0 +1,59 @@+; =============================================================================+; WikiCode — Python symbol and import queries+; tree-sitter-python >= 0.23+;+; Capture name conventions (shared across ALL language query files):+; @symbol.def — the full definition node (used for line numbers, kind)+; @symbol.name — the name identifier node+; @symbol.params — parameter list node (optional)+; @symbol.modifiers — decorator / visibility modifier nodes (optional)+; @import.statement — the full import node+; @import.module — the module path being imported from+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------++; Function (covers both regular and async — in tree-sitter-python >= 0.23+; async functions share the function_definition node type)+(function_definition+ name: (identifier) @symbol.name+ parameters: (parameters) @symbol.params+) @symbol.def++; Class+(class_definition+ name: (identifier) @symbol.name+) @symbol.def++; Decorated function or class — captures the decorator as a modifier+(decorated_definition+ (decorator) @symbol.modifiers+ (function_definition+ name: (identifier) @symbol.name+ parameters: (parameters) @symbol.params+ ) @symbol.def+)++(decorated_definition+ (decorator) @symbol.modifiers+ (class_definition+ name: (identifier) @symbol.name+ ) @symbol.def+)++; ---------------------------------------------------------------------------+; Imports+; ---------------------------------------------------------------------------++; from x.y import a, b+; from . import x+(import_from_statement+ module_name: (_) @import.module+) @import.statement++; import x.y.z+(import_statement+ name: (_) @import.module+) @import.statementdiff --git a/packages/core/queries/ruby.scm b/packages/core/queries/ruby.scmnew file mode 100644index 000000000..3ee0a16ae--- /dev/null+++ b/packages/core/queries/ruby.scm@@ -0,0 +1,30 @@+; =============================================================================+; WikiCode — Ruby symbol and import queries+; tree-sitter-ruby (install separately if needed)+; =============================================================================++(method+ name: (identifier) @symbol.name+ parameters: (method_parameters)? @symbol.params+) @symbol.def++(singleton_method+ name: (identifier) @symbol.name+) @symbol.def++(class+ name: (constant) @symbol.name+) @symbol.def++(module+ name: (constant) @symbol.name+) @symbol.def++; require 'module' / require_relative './sibling'+(call+ method: (identifier) @_require_method+ arguments: (argument_list+ (string (string_content) @import.module)+ )+ (#match? @_require_method "^require")+) @import.statementdiff --git a/packages/core/queries/rust.scm b/packages/core/queries/rust.scmnew file mode 100644index 000000000..86514346e--- /dev/null+++ b/packages/core/queries/rust.scm@@ -0,0 +1,56 @@+; =============================================================================+; WikiCode — Rust symbol and import queries+; tree-sitter-rust >= 0.23+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------++(function_item+ name: (identifier) @symbol.name+ parameters: (parameters) @symbol.params+) @symbol.def++(struct_item+ name: (type_identifier) @symbol.name+) @symbol.def++(enum_item+ name: (type_identifier) @symbol.name+) @symbol.def++(trait_item+ name: (type_identifier) @symbol.name+) @symbol.def++; impl block — the "type" field identifies what is being implemented+(impl_item+ type: (type_identifier) @symbol.name+) @symbol.def++(const_item+ name: (identifier) @symbol.name+) @symbol.def++(type_item+ name: (type_identifier) @symbol.name+) @symbol.def++(mod_item+ name: (identifier) @symbol.name+) @symbol.def++; pub visibility modifier+(function_item+ (visibility_modifier) @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Imports+; ---------------------------------------------------------------------------++(use_declaration+ argument: (_) @import.module+) @import.statementdiff --git a/packages/core/queries/typescript.scm b/packages/core/queries/typescript.scmnew file mode 100644index 000000000..b76bf2547--- /dev/null+++ b/packages/core/queries/typescript.scm@@ -0,0 +1,78 @@+; =============================================================================+; WikiCode — TypeScript symbol and import queries+; tree-sitter-typescript >= 0.23+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------++; Top-level function declaration+(function_declaration+ name: (identifier) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++; Generator function+(generator_function_declaration+ name: (identifier) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++; Class declaration+(class_declaration+ name: (type_identifier) @symbol.name+) @symbol.def++; Abstract class+(abstract_class_declaration+ name: (type_identifier) @symbol.name+) @symbol.def++; Interface+(interface_declaration+ name: (type_identifier) @symbol.name+) @symbol.def++; Type alias+(type_alias_declaration+ name: (type_identifier) @symbol.name+) @symbol.def++; Enum+(enum_declaration+ name: (identifier) @symbol.name+) @symbol.def++; Method inside class body+(method_definition+ name: (property_identifier) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++; Arrow function assigned to const/let: const foo = (...) => { }+(lexical_declaration+ (variable_declarator+ name: (identifier) @symbol.name+ value: (arrow_function+ parameters: (formal_parameters) @symbol.params+ )+ )+) @symbol.def++; Public method accessor modifier capture+(method_definition+ (accessibility_modifier) @symbol.modifiers+ name: (property_identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Imports+; ---------------------------------------------------------------------------++; import { A, B } from "./module"+; import type { T } from "./types"+; import DefaultExport from "module"+(import_statement+ source: (string) @import.module+) @import.statementdiff --git a/packages/core/src/wikicode/core/__init__.py b/packages/core/src/wikicode/core/__init__.pynew file mode 100644index 000000000..93faa1d54--- /dev/null+++ b/packages/core/src/wikicode/core/__init__.py@@ -0,0 +1,9 @@+"""WikiCode core package.++Provides the ingestion pipeline, dependency graph builder, and documentation+generation engine. This is the heart of WikiCode — all other packages depend on it.++Namespace package: wikicode.core is part of the wikicode namespace.+"""++__version__ = "0.1.0"diff --git a/packages/core/src/wikicode/core/analysis/__init__.py b/packages/core/src/wikicode/core/analysis/__init__.pynew file mode 100644index 000000000..66aac8788--- /dev/null+++ b/packages/core/src/wikicode/core/analysis/__init__.py@@ -0,0 +1 @@+"""Analysis modules for WikiCode (dead code detection, etc.)."""diff --git a/packages/core/src/wikicode/core/analysis/dead_code.py b/packages/core/src/wikicode/core/analysis/dead_code.pynew file mode 100644index 000000000..62a888b79--- /dev/null+++ b/packages/core/src/wikicode/core/analysis/dead_code.py@@ -0,0 +1,514 @@+"""Dead code detection for WikiCode.++Pure graph traversal + SQL — no LLM calls. Must complete in < 10 seconds.++Detects unreachable files, unused exports, unused internals, and+zombie packages using the dependency graph and git metadata.+"""++from __future__ import annotations++import fnmatch+from dataclasses import dataclass, field+from datetime import datetime, timezone+from enum import Enum+from pathlib import Path+from typing import Any++import structlog++logger = structlog.get_logger(__name__)+++class DeadCodeKind(str, Enum):+ UNREACHABLE_FILE = "unreachable_file"+ UNUSED_EXPORT = "unused_export"+ UNUSED_INTERNAL = "unused_internal"+ ZOMBIE_PACKAGE = "zombie_package"+++@dataclass+class DeadCodeFindingData:+ kind: DeadCodeKind+ file_path: str+ symbol_name: str | None+ symbol_kind: str | None+ confidence: float+ reason: str+ last_commit_at: datetime | None+ commit_count_90d: int+ lines: int+ package: str | None+ evidence: list[str]+ safe_to_delete: bool+ primary_owner: str | None+ age_days: int | None+++@dataclass+class DeadCodeReport:+ repo_id: str+ analyzed_at: datetime+ total_findings: int+ findings: list[DeadCodeFindingData]+ deletable_lines: int+ confidence_summary: dict # {"high": N, "medium": N, "low": N}+++# Non-code languages that should never be flagged as dead code.+# These files have no import/export semantics — in_degree=0 is expected and+# meaningless for them. Matches the skip lists in git_indexer and page_generator.+_NON_CODE_LANGUAGES: frozenset[str] = frozenset(+ {+ "json", "yaml", "toml", "markdown",+ "sql", "shell", "terraform", "proto",+ "graphql", "dockerfile", "makefile",+ "unknown",+ }+)++# Patterns that should never be flagged as dead+_NEVER_FLAG_PATTERNS = (+ "*__init__.py",+ "*migrations*",+ "*schema*",+ "*seed*",+ "*.d.ts",+)++# Decorator patterns that indicate framework usage+_FRAMEWORK_DECORATORS = ("pytest.fixture", "pytest.mark")++# Default dynamic patterns (plugins, handlers, etc.)+_DEFAULT_DYNAMIC_PATTERNS = (+ "*Plugin",+ "*Handler",+ "*Adapter",+ "*Middleware",+ "register_*",+ "on_*",+)+++class DeadCodeAnalyzer:+ """Detects unreachable files, unused exports, unused internals, and+ zombie packages using the dependency graph and git metadata.++ All analysis is graph traversal + SQL. No LLM calls.+ """++ def __init__(+ self,+ graph: Any, # nx.DiGraph+ git_meta_map: dict | None = None,+ ) -> None:+ self.graph = graph+ self.git_meta_map = git_meta_map or {}++ def analyze(self, config: dict | None = None) -> DeadCodeReport:+ """Full analysis. Returns report with all findings."""+ cfg = config or {}+ findings: list[DeadCodeFindingData] = []++ dynamic_patterns = cfg.get("dynamic_patterns", _DEFAULT_DYNAMIC_PATTERNS)+ whitelist = set(cfg.get("whitelist", []))++ if cfg.get("detect_unreachable_files", True):+ findings.extend(+ self._detect_unreachable_files(dynamic_patterns, whitelist)+ )++ if cfg.get("detect_unused_exports", True):+ findings.extend(+ self._detect_unused_exports(dynamic_patterns, whitelist)+ )++ if cfg.get("detect_unused_internals", False):+ findings.extend(+ self._detect_unused_internals(dynamic_patterns, whitelist)+ )++ if cfg.get("detect_zombie_packages", True):+ findings.extend(self._detect_zombie_packages(whitelist))++ # Apply min_confidence filter+ min_conf = cfg.get("min_confidence", 0.4)+ findings = [f for f in findings if f.confidence >= min_conf]++ now = datetime.now(timezone.utc)+ deletable = sum(f.lines for f in findings if f.safe_to_delete)++ high = sum(1 for f in findings if f.confidence >= 0.7)+ medium = sum(1 for f in findings if 0.4 <= f.confidence < 0.7)+ low = sum(1 for f in findings if f.confidence < 0.4)++ return DeadCodeReport(+ repo_id="",+ analyzed_at=now,+ total_findings=len(findings),+ findings=findings,+ deletable_lines=deletable,+ confidence_summary={"high": high, "medium": medium, "low": low},+ )++ def analyze_partial(+ self, affected_files: list[str], config: dict | None = None+ ) -> DeadCodeReport:+ """Partial analysis for incremental updates."""+ # For partial analysis, only check affected files and their neighbors+ cfg = config or {}+ findings: list[DeadCodeFindingData] = []+ dynamic_patterns = cfg.get("dynamic_patterns", _DEFAULT_DYNAMIC_PATTERNS)+ whitelist = set(cfg.get("whitelist", []))++ affected_set = set(affected_files)+ for node in affected_set:+ if node not in self.graph:+ continue+ node_data = self.graph.nodes.get(node, {})+ if node_data.get("language", "unknown") in _NON_CODE_LANGUAGES:+ continue+ if self._should_never_flag(node, whitelist):+ continue++ # Check if file became unreachable+ in_deg = self.graph.in_degree(node)+ node_data = self.graph.nodes.get(node, {})+ if (+ in_deg == 0+ and not node_data.get("is_entry_point", False)+ and not node_data.get("is_test", False)+ ):+ finding = self._make_unreachable_finding(+ node, node_data, dynamic_patterns+ )+ if finding:+ findings.append(finding)++ min_conf = cfg.get("min_confidence", 0.4)+ findings = [f for f in findings if f.confidence >= min_conf]++ now = datetime.now(timezone.utc)+ deletable = sum(f.lines for f in findings if f.safe_to_delete)+ high = sum(1 for f in findings if f.confidence >= 0.7)+ medium = sum(1 for f in findings if 0.4 <= f.confidence < 0.7)+ low = sum(1 for f in findings if f.confidence < 0.4)++ return DeadCodeReport(+ repo_id="",+ analyzed_at=now,+ total_findings=len(findings),+ findings=findings,+ deletable_lines=deletable,+ confidence_summary={"high": high, "medium": medium, "low": low},+ )++ # ------------------------------------------------------------------+ # Detection methods+ # ------------------------------------------------------------------++ def _detect_unreachable_files(+ self,+ dynamic_patterns: tuple[str, ...],+ whitelist: set[str],+ ) -> list[DeadCodeFindingData]:+ """Detect files with in_degree == 0 that are not entry points, tests, or config."""+ findings = []++ for node in self.graph.nodes():+ if str(node).startswith("external:"):+ continue++ node_data = self.graph.nodes[node]+ if node_data.get("language", "unknown") in _NON_CODE_LANGUAGES:+ continue+ if node_data.get("is_entry_point", False):+ continue+ if node_data.get("is_test", False):+ continue+ if self._should_never_flag(str(node), whitelist):+ continue+ if self._is_api_contract(node_data):+ continue++ in_deg = self.graph.in_degree(node)+ if in_deg > 0:+ continue++ finding = self._make_unreachable_finding(+ str(node), node_data, dynamic_patterns+ )+ if finding:+ findings.append(finding)++ return findings++ def _make_unreachable_finding(+ self,+ node: str,+ node_data: dict,+ dynamic_patterns: tuple[str, ...],+ ) -> DeadCodeFindingData | None:+ """Create an unreachable file finding with confidence scoring."""+ git_meta = self.git_meta_map.get(node, {})+ commit_90d = git_meta.get("commit_count_90d", 0)+ last_commit = git_meta.get("last_commit_at")+ age_days = git_meta.get("age_days")+ primary_owner = git_meta.get("primary_owner_name")++ # Confidence rules+ if commit_90d == 0 and last_commit and self._is_old(last_commit, days=180):+ confidence = 1.0+ elif commit_90d == 0:+ confidence = 0.7+ else:+ confidence = 0.4++ # 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):+ safe = False++ evidence = [f"in_degree=0 (no files import this)"]+ if commit_90d == 0:+ evidence.append("No commits in last 90 days")++ return DeadCodeFindingData(+ kind=DeadCodeKind.UNREACHABLE_FILE,+ file_path=node,+ symbol_name=None,+ symbol_kind=None,+ confidence=confidence,+ reason=f"File has no importers (in_degree=0)",+ last_commit_at=last_commit if isinstance(last_commit, datetime) else None,+ commit_count_90d=commit_90d,+ lines=node_data.get("symbol_count", 0) * 10, # rough estimate+ package=self._get_package(node),+ evidence=evidence,+ safe_to_delete=safe,+ primary_owner=primary_owner,+ age_days=age_days,+ )++ def _detect_unused_exports(+ self,+ dynamic_patterns: tuple[str, ...],+ whitelist: set[str],+ ) -> list[DeadCodeFindingData]:+ """Detect public symbols with no incoming edges."""+ findings = []++ for node in self.graph.nodes():+ if str(node).startswith("external:"):+ continue++ node_data = self.graph.nodes[node]+ if node_data.get("language", "unknown") in _NON_CODE_LANGUAGES:+ continue+ if node_data.get("is_test", False):+ continue+ if self._should_never_flag(str(node), whitelist):+ continue++ # Get symbols for this file from graph node data+ symbols = node_data.get("symbols", [])+ if not symbols:+ continue++ file_has_importers = self.graph.in_degree(node) > 0++ for sym in symbols:+ if not isinstance(sym, dict):+ continue+ if sym.get("visibility") != "public":+ continue+ sym_name = sym.get("name", "")++ # Skip framework decorators+ decorators = sym.get("decorators", [])+ if any(+ d.startswith(prefix)+ for d in decorators+ for prefix in _FRAMEWORK_DECORATORS+ ):+ continue++ # Skip dynamic patterns+ if self._name_matches_dynamic(sym_name, dynamic_patterns):+ continue++ # Skip deprecated-named symbols (lower confidence)+ is_deprecated = any(+ sym_name.endswith(suffix)+ for suffix in ("_DEPRECATED", "_LEGACY", "_COMPAT")+ )++ # Check for importers of this specific symbol+ has_importers = False+ for pred in self.graph.predecessors(node):+ edge_data = self.graph[pred][node]+ imported_names = edge_data.get("imported_names", [])+ if sym_name in imported_names or "*" in imported_names:+ has_importers = True+ break++ if has_importers:+ continue++ # Confidence scoring+ if is_deprecated:+ confidence = 0.3+ elif file_has_importers:+ confidence = 1.0+ else:+ confidence = 0.7++ complexity = sym.get("complexity_estimate", 0)+ safe = confidence >= 0.7 and complexity < 5++ git_meta = self.git_meta_map.get(str(node), {})++ findings.append(+ DeadCodeFindingData(+ kind=DeadCodeKind.UNUSED_EXPORT,+ file_path=str(node),+ symbol_name=sym_name,+ symbol_kind=sym.get("kind"),+ confidence=confidence,+ reason=f"Public symbol '{sym_name}' has no importers",+ last_commit_at=git_meta.get("last_commit_at") if isinstance(git_meta.get("last_commit_at"), datetime) else None,+ commit_count_90d=git_meta.get("commit_count_90d", 0),+ lines=sym.get("end_line", 0) - sym.get("start_line", 0),+ package=self._get_package(str(node)),+ evidence=[f"No imports of '{sym_name}' found in graph"],+ safe_to_delete=safe,+ primary_owner=git_meta.get("primary_owner_name"),+ age_days=git_meta.get("age_days"),+ )+ )++ return findings++ def _detect_unused_internals(+ self,+ dynamic_patterns: tuple[str, ...],+ whitelist: set[str],+ ) -> list[DeadCodeFindingData]:+ """Detect private symbols with no calls edges from same file."""+ # Higher false positive rate — off by default+ return []++ def _detect_zombie_packages(+ self, whitelist: set[str]+ ) -> list[DeadCodeFindingData]:+ """Detect monorepo packages with no incoming inter_package edges."""+ findings = []++ # Find package nodes (directories with multiple files)+ packages: dict[str, list[str]] = {}+ for node in self.graph.nodes():+ if str(node).startswith("external:"):+ continue+ parts = Path(str(node)).parts+ if len(parts) > 1:+ pkg = parts[0]+ packages.setdefault(pkg, []).append(str(node))++ if len(packages) < 2:+ return findings # Not a monorepo++ for pkg, files in packages.items():+ if pkg in whitelist:+ continue++ # Check if any file in this package is imported from outside the package+ has_external_importers = False+ for f in files:+ for pred in self.graph.predecessors(f):+ pred_str = str(pred)+ if pred_str.startswith("external:"):+ continue+ pred_parts = Path(pred_str).parts+ if len(pred_parts) > 0 and pred_parts[0] != pkg:+ has_external_importers = True+ break+ if has_external_importers:+ break++ if not has_external_importers:+ total_lines = sum(+ self.graph.nodes[f].get("symbol_count", 0) * 10+ for f in files+ if f in self.graph+ )+ findings.append(+ DeadCodeFindingData(+ kind=DeadCodeKind.ZOMBIE_PACKAGE,+ file_path=pkg,+ symbol_name=None,+ symbol_kind=None,+ confidence=0.5,+ reason=f"Package '{pkg}' has no importers from other packages",+ last_commit_at=None,+ commit_count_90d=0,+ lines=total_lines,+ package=pkg,+ evidence=[f"No inter-package imports into '{pkg}'"],+ safe_to_delete=False,+ primary_owner=None,+ age_days=None,+ )+ )++ return findings++ # ------------------------------------------------------------------+ # Helpers+ # ------------------------------------------------------------------++ def _should_never_flag(self, path: str, whitelist: set[str]) -> bool:+ """Return True if path should never be flagged as dead."""+ if path in whitelist:+ return True+ for pattern in _NEVER_FLAG_PATTERNS:+ if fnmatch.fnmatch(path, pattern):+ return True+ # Check if it's an __init__.py (re-export barrel)+ if Path(path).name == "__init__.py":+ return True+ return False++ def _is_api_contract(self, node_data: dict) -> bool:+ return node_data.get("is_api_contract", False)++ def _matches_dynamic_patterns(+ self, path: str, patterns: tuple[str, ...]+ ) -> bool:+ name = Path(path).stem+ for pattern in patterns:+ if fnmatch.fnmatch(name, pattern):+ return True+ return False++ def _name_matches_dynamic(+ self, name: str, patterns: tuple[str, ...]+ ) -> bool:+ for pattern in patterns:+ if fnmatch.fnmatch(name, pattern):+ return True+ return False++ def _is_old(self, dt: Any, days: int = 180) -> bool:+ """Return True if datetime is older than `days` ago."""+ if dt is None:+ return False+ now = datetime.now(timezone.utc)+ if isinstance(dt, datetime):+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return (now - dt).days > days+ return False++ def _get_package(self, path: str) -> str | None:+ parts = Path(path).parts+ return parts[0] if len(parts) > 1 else Nonediff --git a/packages/core/src/wikicode/core/analysis/decision_extractor.py b/packages/core/src/wikicode/core/analysis/decision_extractor.pynew file mode 100644index 000000000..8490217a9--- /dev/null+++ b/packages/core/src/wikicode/core/analysis/decision_extractor.py@@ -0,0 +1,737 @@+"""Architectural Decision Intelligence — extraction from multiple sources.++Capture sources:+ 1. Inline markers (# WHY:, # DECISION:, etc.) — confidence 0.95+ 2. Git archaeology (significant commit messages) — confidence 0.70–0.85+ 3. README / docs mining (implicit decisions in prose) — confidence 0.60+ 4. CLI capture (manual entry) — confidence 1.00++All LLM calls are wrapped in try/except — failures never propagate.+"""++from __future__ import annotations++import asyncio+import json+import re+from dataclasses import dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import Any++import structlog++logger = structlog.get_logger(__name__)++# ---------------------------------------------------------------------------+# Data models+# ---------------------------------------------------------------------------+++@dataclass+class ExtractedDecision:+ title: str+ context: str = ""+ decision: str = ""+ rationale: str = ""+ alternatives: list[str] = field(default_factory=list)+ consequences: list[str] = field(default_factory=list)+ affected_files: list[str] = field(default_factory=list)+ affected_modules: list[str] = field(default_factory=list)+ tags: list[str] = field(default_factory=list)+ source: str = "inline_marker"+ evidence_commits: list[str] = field(default_factory=list)+ evidence_file: str | None = None+ evidence_line: int | None = None+ confidence: float = 0.5+ status: str = "proposed"+++@dataclass+class DecisionExtractionReport:+ total_found: int+ decisions: list[ExtractedDecision]+ by_source: dict[str, int]+++# ---------------------------------------------------------------------------+# Comment marker detection+# ---------------------------------------------------------------------------++MARKER_RE = re.compile(+ r"^\s*(?:#|//|--|/\*|\*)\s*"+ r"(?P<keyword>WHY|DECISION|TRADEOFF|ADR|RATIONALE|REJECTED)"+ r"\s*:\s*(?P<text>.+)",+ re.IGNORECASE,+)++_SKIP_DIRS = frozenset({+ ".git", "node_modules", "__pycache__", ".wikicode", ".venv",+ "venv", ".tox", ".mypy_cache", ".pytest_cache", "dist", "build",+ ".next", ".nuxt",+})++_BINARY_EXTENSIONS = frozenset({+ ".png", ".jpg", ".jpeg", ".gif", ".ico", ".svg", ".bmp", ".webp",+ ".woff", ".woff2", ".ttf", ".eot", ".otf",+ ".zip", ".tar", ".gz", ".bz2", ".rar", ".7z",+ ".pdf", ".doc", ".docx", ".xls", ".xlsx",+ ".pyc", ".pyo", ".so", ".dll", ".dylib", ".exe",+ ".db", ".sqlite", ".sqlite3", ".lance",+ ".lock",+})++# ---------------------------------------------------------------------------+# Decision signal keywords for git archaeology+# ---------------------------------------------------------------------------++DECISION_SIGNAL_KEYWORDS = [+ "migrate", "migration", "switch to", "replace", "replaced",+ "refactor to", "move from", "adopt", "introduce", "deprecate",+ "remove", "drop", "upgrade", "rewrite", "extract", "split",+ "convert", "transition",+]++# ---------------------------------------------------------------------------+# LLM Prompts+# ---------------------------------------------------------------------------++_SYSTEM_PROMPT = (+ "You are an architectural decision extractor. "+ "You extract structured decision records from code context. "+ "Return only valid JSON. Never invent rationale not present in the source."+)++INLINE_MARKER_PROMPT = """\+A developer left architectural decision markers in their code. \+Extract each one as a structured decision record.++Markers found in file: {file_path}++{markers_block}++For each marker, return a JSON object:+{{+ "title": "short title of the decision",+ "context": "what situation forced this",+ "decision": "what was chosen",+ "rationale": "why",+ "alternatives": ["rejected alternatives if mentioned"],+ "consequences": ["tradeoffs if mentioned"],+ "tags": ["relevant tags from: auth, database, api, performance, security, infra, testing"]+}}++Return a JSON array of decision objects. If a marker is not an architectural \+decision, skip it. Return [] if none qualify.+"""++GIT_ARCHAEOLOGY_PROMPT = """\+Analyze these git commits to determine if they represent architectural decisions.++{commits_block}++For each commit that IS an architectural decision (a deliberate choice about \+system structure, patterns, migrations, or technology), return a JSON object:+{{+ "commit_sha": "the sha",+ "title": "short title",+ "context": "what situation forced this",+ "decision": "what was chosen or changed",+ "rationale": "why this approach (infer from message and files only)",+ "alternatives": [],+ "consequences": [],+ "tags": ["relevant tags"]+}}++Return a JSON array. Skip commits that are just bug fixes or minor changes. \+Return [] if none qualify. Do not hallucinate rationale.+"""++README_MINING_PROMPT = """\+Analyze this documentation file and extract any architectural decisions.++File: {file_path}+Content:+{content}++Look for:+- Technology choices and why ("We use X because Y")+- Things replaced or migrated away from+- Explicit architectural constraints+- Design patterns chosen and why++Return a JSON array of decisions:+{{+ "title": "short title",+ "context": "situation that forced it",+ "decision": "what was chosen",+ "rationale": "why",+ "alternatives": [],+ "consequences": [],+ "tags": [],+ "source_quote": "exact quote from the document"+}}++Only extract explicit decisions. Return [] if none found.+"""+++# ---------------------------------------------------------------------------+# Main extractor+# ---------------------------------------------------------------------------+++class DecisionExtractor:+ """Extracts architectural decisions from multiple sources."""++ def __init__(+ self,+ repo_path: Path,+ provider: Any | None = None,+ graph: Any | None = None,+ git_meta_map: dict[str, dict] | None = None,+ parsed_files: list[Any] | None = None,+ ) -> None:+ self._repo_path = Path(repo_path)+ self._provider = provider+ self._graph = graph+ self._git_meta_map = git_meta_map or {}+ self._parsed_files = parsed_files or []++ # ------------------------------------------------------------------+ # Source 1: Inline markers+ # ------------------------------------------------------------------++ async def scan_inline_markers(+ self,+ restrict_to_files: list[str] | None = None,+ ) -> list[ExtractedDecision]:+ """Scan source files for decision markers (WHY:, DECISION:, etc.)."""+ markers_by_file: dict[str, list[dict]] = {}++ if restrict_to_files:+ files_to_scan = [self._repo_path / fp for fp in restrict_to_files]+ else:+ files_to_scan = list(self._iter_source_files())++ for file_path in files_to_scan:+ if not file_path.is_file():+ continue+ try:+ text = file_path.read_text(encoding="utf-8", errors="replace")+ except (OSError, UnicodeDecodeError):+ continue++ lines = text.splitlines()+ for line_num, line in enumerate(lines, start=1):+ m = MARKER_RE.match(line)+ if m:+ # Collect continuation lines (same comment prefix, no keyword)+ marker_text = m.group("text").strip()+ for cont_line in lines[line_num : line_num + 5]:+ cont = cont_line.strip()+ if cont.startswith(("#", "//", "--", "*")) and ":" not in cont[:20]:+ # Strip comment prefix+ cleaned = re.sub(r"^\s*(?:#|//|--|/\*|\*)\s*", "", cont)+ if cleaned:+ marker_text += " " + cleaned+ else:+ break++ # Context window: ±20 lines+ ctx_start = max(0, line_num - 21)+ ctx_end = min(len(lines), line_num + 20)+ context = "\n".join(lines[ctx_start:ctx_end])++ try:+ rel_path = str(file_path.relative_to(self._repo_path))+ except ValueError:+ rel_path = str(file_path)++ markers_by_file.setdefault(rel_path, []).append({+ "keyword": m.group("keyword"),+ "text": marker_text,+ "line": line_num,+ "context": context,+ })++ if not markers_by_file:+ return []++ decisions: list[ExtractedDecision] = []++ for file_path, markers in markers_by_file.items():+ # Get 1-hop graph neighbors for affected_files+ affected = self._get_neighbors(file_path)++ if self._provider:+ # Use LLM to structure markers+ try:+ llm_decisions = await self._structure_markers_via_llm(+ file_path, markers+ )+ for d in llm_decisions:+ d.evidence_file = file_path+ d.evidence_line = markers[0]["line"] if markers else None+ d.affected_files = list({file_path} | set(affected))+ d.affected_modules = self._infer_modules(+ d.affected_files+ )+ d.source = "inline_marker"+ d.status = "active"+ d.confidence = 0.95+ decisions.extend(llm_decisions)+ except Exception:+ logger.warning(+ "decision_extractor.llm_structuring_failed",+ file=file_path,+ )+ # Fall through to raw extraction below+ for marker in markers:+ decisions.append(self._raw_decision_from_marker(+ file_path, marker, affected+ ))+ else:+ # No LLM — create minimal decisions from raw marker text+ for marker in markers:+ decisions.append(self._raw_decision_from_marker(+ file_path, marker, affected+ ))++ return decisions++ def _raw_decision_from_marker(+ self,+ file_path: str,+ marker: dict,+ affected: list[str],+ ) -> ExtractedDecision:+ """Create a minimal decision from a raw marker without LLM."""+ return ExtractedDecision(+ title=marker["text"][:100],+ decision=marker["text"],+ context=f"Found in {file_path}:{marker['line']}",+ source="inline_marker",+ status="active",+ confidence=0.7,+ evidence_file=file_path,+ evidence_line=marker["line"],+ affected_files=list({file_path} | set(affected)),+ affected_modules=self._infer_modules([file_path] + affected),+ tags=self._infer_tags(marker["text"]),+ )++ async def _structure_markers_via_llm(+ self, file_path: str, markers: list[dict]+ ) -> list[ExtractedDecision]:+ """Use LLM to structure inline markers into decision records."""+ markers_block = ""+ for m in markers[:5]: # Batch up to 5 per call+ markers_block += (+ f"\n--- Marker ({m['keyword']}) at line {m['line']} ---\n"+ f"Text: {m['text']}\n"+ f"Surrounding code:\n{m['context'][:1500]}\n"+ )++ prompt = INLINE_MARKER_PROMPT.format(+ file_path=file_path,+ markers_block=markers_block,+ )++ response = await self._provider.generate(+ _SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2+ )+ return self._parse_decisions_json(response.content)++ # ------------------------------------------------------------------+ # Source 2: Git archaeology+ # ------------------------------------------------------------------++ async def mine_git_archaeology(self) -> list[ExtractedDecision]:+ """Extract decisions from significant git commits."""+ if not self._provider or not self._git_meta_map:+ return []++ # Collect unique significant commits with decision signals+ commit_map: dict[str, dict] = {} # sha → commit info+ commit_files: dict[str, list[str]] = {} # sha → files++ for file_path, meta in self._git_meta_map.items():+ commits_json = meta.get("significant_commits_json", "[]")+ if isinstance(commits_json, str):+ try:+ commits = json.loads(commits_json)+ except (json.JSONDecodeError, TypeError):+ continue+ else:+ commits = commits_json++ for commit in commits:+ sha = commit.get("sha", "")+ if not sha or sha in commit_map:+ commit_files.setdefault(sha, []).append(file_path)+ continue+ msg = commit.get("message", "")+ signal_count = sum(+ 1 for kw in DECISION_SIGNAL_KEYWORDS+ if kw in msg.lower()+ )+ if signal_count > 0:+ commit_map[sha] = {+ "sha": sha,+ "message": msg,+ "author": commit.get("author", ""),+ "date": commit.get("date", ""),+ "signal_count": signal_count,+ }+ commit_files.setdefault(sha, []).append(file_path)++ if not commit_map:+ return []++ # Rank by signal count, take top 20+ ranked = sorted(+ commit_map.values(),+ key=lambda c: c["signal_count"],+ reverse=True,+ )[:20]++ # Batch LLM calls (5 commits per batch)+ decisions: list[ExtractedDecision] = []+ batches = [ranked[i : i + 5] for i in range(0, len(ranked), 5)]++ async def _process_batch(batch: list[dict]) -> list[ExtractedDecision]:+ commits_block = ""+ for c in batch:+ files = commit_files.get(c["sha"], [])+ commits_block += (+ f"\n--- Commit {c['sha'][:8]} ---\n"+ f"Message: {c['message']}\n"+ f"Author: {c['author']}\n"+ f"Date: {c['date']}\n"+ f"Files changed: {', '.join(files[:20])}\n"+ )++ prompt = GIT_ARCHAEOLOGY_PROMPT.format(commits_block=commits_block)+ response = await self._provider.generate(+ _SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2+ )+ extracted = self._parse_decisions_json(response.content)++ # Enrich with commit metadata+ for d in extracted:+ sha = d.evidence_commits[0] if d.evidence_commits else ""+ if not sha:+ # Try to match back to a commit+ for c in batch:+ if c["message"][:40].lower() in d.title.lower():+ sha = c["sha"]+ break+ if sha:+ d.evidence_commits = [sha]+ d.affected_files = commit_files.get(sha, [])+ d.source = "git_archaeology"+ d.status = "proposed"+ signal = max(+ (c["signal_count"] for c in batch+ if c["sha"] == sha),+ default=1,+ )+ d.confidence = 0.85 if signal >= 2 else 0.70+ d.affected_modules = self._infer_modules(d.affected_files)++ return extracted++ results = await asyncio.gather(+ *[_process_batch(b) for b in batches],+ return_exceptions=True,+ )+ for result in results:+ if isinstance(result, list):+ decisions.extend(result)+ else:+ logger.warning(+ "decision_extractor.git_batch_failed",+ error=str(result),+ )++ return decisions++ # ------------------------------------------------------------------+ # Source 3: README / docs mining+ # ------------------------------------------------------------------++ async def mine_readme_docs(self) -> list[ExtractedDecision]:+ """Extract decisions from documentation files."""+ if not self._provider:+ return []++ doc_patterns = [+ "README.md", "CLAUDE.md", "ARCHITECTURE.md", "CONTRIBUTING.md",+ "DESIGN.md", "DECISIONS.md",+ ]+ doc_files: list[Path] = []++ for pattern in doc_patterns:+ p = self._repo_path / pattern+ if p.is_file():+ doc_files.append(p)++ # Also check docs/ directory+ docs_dir = self._repo_path / "docs"+ if docs_dir.is_dir():+ for md_file in docs_dir.rglob("*.md"):+ if len(doc_files) >= 10:+ break+ doc_files.append(md_file)++ decisions: list[ExtractedDecision] = []++ for doc_path in doc_files[:10]:+ try:+ content = doc_path.read_text(encoding="utf-8", errors="replace")+ except (OSError, UnicodeDecodeError):+ continue++ # Skip very large files+ if len(content) > 50_000:+ continue++ try:+ rel_path = str(doc_path.relative_to(self._repo_path))+ except ValueError:+ rel_path = str(doc_path)++ try:+ prompt = README_MINING_PROMPT.format(+ file_path=rel_path,+ content=content[:15_000], # Limit token usage+ )+ response = await self._provider.generate(+ _SYSTEM_PROMPT, prompt, max_tokens=3000, temperature=0.2+ )+ extracted = self._parse_decisions_json(response.content)+ for d in extracted:+ d.source = "readme_mining"+ d.status = "proposed"+ d.confidence = 0.60+ d.evidence_file = rel_path+ d.affected_modules = self._infer_modules_from_text(+ d.title + " " + d.decision+ )+ decisions.extend(extracted)+ except Exception:+ logger.warning(+ "decision_extractor.readme_mining_failed",+ file=rel_path,+ )++ return decisions++ # ------------------------------------------------------------------+ # Staleness computation (static method)+ # ------------------------------------------------------------------++ @staticmethod+ def compute_staleness(+ decision_created_at: datetime,+ affected_files: list[str],+ git_meta_map: dict[str, dict],+ ) -> float:+ """Compute staleness score for a decision. Returns 0.0–1.0."""+ if not affected_files:+ return 0.0++ now = datetime.now(timezone.utc)+ scores: list[float] = []++ for fp in affected_files:+ meta = git_meta_map.get(fp)+ if meta is None:+ scores.append(1.0) # File missing / not tracked+ continue++ last_commit = meta.get("last_commit_at")+ if last_commit and decision_created_at:+ if isinstance(last_commit, str):+ last_commit = datetime.fromisoformat(+ last_commit.replace("Z", "+00:00")+ )+ if isinstance(decision_created_at, str):+ decision_created_at = datetime.fromisoformat(+ decision_created_at.replace("Z", "+00:00")+ )+ if last_commit > decision_created_at:+ age_days = (now - decision_created_at).days+ commit_count = meta.get("commit_count_90d", 0)+ score = min(+ 1.0,+ commit_count / 15 * 0.7 + age_days / 365 * 0.3,+ )+ scores.append(score)+ else:+ scores.append(0.0)+ else:+ scores.append(0.0)++ return round(sum(scores) / len(scores), 3) if scores else 0.0++ # ------------------------------------------------------------------+ # Main entry point+ # ------------------------------------------------------------------++ async def extract_all(self) -> DecisionExtractionReport:+ """Run all capture sources in parallel. LLM failures are caught per-source."""++ async def _safe_inline() -> list[ExtractedDecision]:+ try:+ return await self.scan_inline_markers()+ except Exception:+ logger.warning("decision_extractor.inline_markers_failed")+ return []++ async def _safe_git() -> list[ExtractedDecision]:+ try:+ return await self.mine_git_archaeology()+ except Exception:+ logger.warning("decision_extractor.git_archaeology_failed")+ return []++ async def _safe_readme() -> list[ExtractedDecision]:+ try:+ return await self.mine_readme_docs()+ except Exception:+ logger.warning("decision_extractor.readme_mining_failed")+ return []++ inline, git_decisions, readme_decisions = await asyncio.gather(+ _safe_inline(), _safe_git(), _safe_readme()+ )++ decisions = inline + git_decisions + readme_decisions+ by_source = {+ "inline_marker": len(inline),+ "git_archaeology": len(git_decisions),+ "readme_mining": len(readme_decisions),+ }++ return DecisionExtractionReport(+ total_found=len(decisions),+ decisions=decisions,+ by_source=by_source,+ )++ # ------------------------------------------------------------------+ # Helpers+ # ------------------------------------------------------------------++ def _iter_source_files(self):+ """Yield source files under repo_path, skipping irrelevant dirs."""+ for child in self._repo_path.rglob("*"):+ if any(part in _SKIP_DIRS for part in child.parts):+ continue+ if child.is_file() and child.suffix.lower() not in _BINARY_EXTENSIONS:+ yield child++ def _get_neighbors(self, file_path: str) -> list[str]:+ """Get 1-hop graph neighbors for a file."""+ if self._graph is None:+ return []+ neighbors: set[str] = set()+ if file_path in self._graph:+ neighbors.update(self._graph.successors(file_path))+ neighbors.update(self._graph.predecessors(file_path))+ neighbors.discard(file_path)+ return list(neighbors)[:20] # Cap at 20++ def _infer_modules(self, file_paths: list[str]) -> list[str]:+ """Infer top-level module paths from file paths."""+ modules: set[str] = set()+ for fp in file_paths:+ parts = fp.replace("\\", "/").split("/")+ if len(parts) > 1:+ modules.add(parts[0])+ return sorted(modules)++ def _infer_modules_from_text(self, text: str) -> list[str]:+ """Infer module names by matching text against graph nodes."""+ if not self._graph:+ return []+ modules: set[str] = set()+ text_lower = text.lower()+ for node in self._graph.nodes:+ parts = node.replace("\\", "/").split("/")+ if len(parts) > 1 and parts[0].lower() in text_lower:+ modules.add(parts[0])+ return sorted(modules)[:5]++ def _infer_tags(self, text: str) -> list[str]:+ """Infer tags from decision text."""+ tag_keywords = {+ "auth": ["auth", "jwt", "oauth", "token", "session", "login"],+ "database": ["database", "sql", "postgres", "sqlite", "redis", "mongo", "db"],+ "api": ["api", "rest", "graphql", "endpoint", "route"],+ "performance": ["performance", "cache", "speed", "latency", "optimize"],+ "security": ["security", "encrypt", "hash", "cors", "csrf", "xss"],+ "infra": ["docker", "kubernetes", "deploy", "ci", "cd", "terraform"],+ "testing": ["test", "mock", "fixture", "assert"],+ }+ text_lower = text.lower()+ tags = []+ for tag, keywords in tag_keywords.items():+ if any(kw in text_lower for kw in keywords):+ tags.append(tag)+ return tags++ def _parse_decisions_json(self, content: str) -> list[ExtractedDecision]:+ """Parse LLM response as JSON array of decisions."""+ # Extract JSON from response (may be wrapped in markdown code blocks)+ content = content.strip()+ if content.startswith("```"):+ # Remove markdown code fences+ lines = content.split("\n")+ content = "\n".join(+ l for l in lines+ if not l.strip().startswith("```")+ )++ try:+ data = json.loads(content)+ except json.JSONDecodeError:+ # Try to find JSON array in the response+ match = re.search(r"\[.*\]", content, re.DOTALL)+ if match:+ try:+ data = json.loads(match.group())+ except json.JSONDecodeError:+ return []+ else:+ return []++ if isinstance(data, dict):+ data = [data]+ if not isinstance(data, list):+ return []++ decisions = []+ for item in data:+ if not isinstance(item, dict):+ continue+ title = item.get("title", "")+ if not title:+ continue+ decisions.append(+ ExtractedDecision(+ title=title,+ context=item.get("context", ""),+ decision=item.get("decision", ""),+ rationale=item.get("rationale", ""),+ alternatives=item.get("alternatives", []),+ consequences=item.get("consequences", []),+ tags=item.get("tags", []),+ evidence_commits=[item["commit_sha"]]+ if "commit_sha" in item+ else [],+ )+ )+ return decisionsdiff --git a/packages/core/src/wikicode/core/generation/__init__.py b/packages/core/src/wikicode/core/generation/__init__.pynew file mode 100644index 000000000..f83f48128--- /dev/null+++ b/packages/core/src/wikicode/core/generation/__init__.py@@ -0,0 +1,73 @@+"""WikiCode generation engine — public exports.++This package converts ParsedFile objects and graph metrics into wiki pages via+Jinja2-templated prompts and BaseProvider.generate().++Import direction (strictly one-way):+ ingestion.models ← generation.models ← context_assembler ← page_generator+"""++from .context_assembler import (+ ApiContractContext,+ ArchitectureDiagramContext,+ ContextAssembler,+ DiffSummaryContext,+ FilePageContext,+ InfraPageContext,+ ModulePageContext,+ SccPageContext,+ SymbolSpotlightContext,+ RepoOverviewContext,+)+from .job_system import Checkpoint, JobStatus, JobSystem+from .models import (+ ConfidenceDecayResult,+ DeadCodeConfig,+ FreshnessStatus,+ GENERATION_LEVELS,+ GeneratedPage,+ GenerationConfig,+ GitConfig,+ PageType,+ compute_confidence_decay_with_git,+ compute_freshness,+ compute_page_id,+ compute_source_hash,+ decay_confidence,+)+from .page_generator import PageGenerator, SYSTEM_PROMPTS++__all__ = [+ # models+ "PageType",+ "GENERATION_LEVELS",+ "FreshnessStatus",+ "GenerationConfig",+ "GitConfig",+ "DeadCodeConfig",+ "GeneratedPage",+ "ConfidenceDecayResult",+ "compute_page_id",+ "compute_freshness",+ "compute_source_hash",+ "decay_confidence",+ "compute_confidence_decay_with_git",+ # context assembler+ "ContextAssembler",+ "FilePageContext",+ "SymbolSpotlightContext",+ "ModulePageContext",+ "SccPageContext",+ "RepoOverviewContext",+ "ArchitectureDiagramContext",+ "ApiContractContext",+ "InfraPageContext",+ "DiffSummaryContext",+ # page generator+ "PageGenerator",+ "SYSTEM_PROMPTS",+ # job system+ "Checkpoint",+ "JobStatus",+ "JobSystem",+]diff --git a/packages/core/src/wikicode/core/generation/context_assembler.py b/packages/core/src/wikicode/core/generation/context_assembler.pynew file mode 100644index 000000000..02a49d2ae--- /dev/null+++ b/packages/core/src/wikicode/core/generation/context_assembler.py@@ -0,0 +1,823 @@+"""Context assembler for the WikiCode generation engine.++ContextAssembler converts ParsedFile objects and graph metrics into context+dataclasses that are passed to Jinja2 templates as ``ctx``.++Token budget algorithm (applied per file):+ 1. Always include: file path, language, symbol signatures (public first)+ 2. If budget allows: symbol docstrings+ 3. If budget allows: imports list (truncated to 30 if needed)+ 4. If budget allows: file_source_snippet (trimmed to fit remaining)+ 5. rag_context: always [] in Phase 3 (Phase 4 ChromaDB stub)++Token estimate: len(text) // 4 (no tiktoken dependency).+"""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import structlog++from wikicode.core.ingestion.models import ParsedFile, RepoStructure, Symbol++from .models import GenerationConfig++log = structlog.get_logger(__name__)++# Maximum imports to include before truncating+_MAX_IMPORTS = 30+# Maximum top-files to include in repo overview+_MAX_TOP_FILES = 20+++# ---------------------------------------------------------------------------+# Context dataclasses — one per template+# ---------------------------------------------------------------------------+++@dataclass+class FilePageContext:+ file_path: str+ language: str+ docstring: str | None+ symbols: list[dict[str, Any]]+ imports: list[str]+ exports: list[str]+ file_source_snippet: str+ pagerank_score: float+ betweenness_score: float+ community_id: int+ dependents: list[str]+ dependencies: list[str]+ is_api_contract: bool+ is_entry_point: bool+ is_test: bool+ parse_errors: list[str]+ estimated_tokens: int+ rag_context: list[str] = field(default_factory=list)+ git_metadata: dict | None = None+ co_change_pages: list[dict] = field(default_factory=list)+ dead_code_findings: list[dict] = field(default_factory=list)+ depth: str = "standard"+ dependency_summaries: dict[str, str] = field(default_factory=dict)+++@dataclass+class SymbolSpotlightContext:+ symbol_name: str+ qualified_name: str+ kind: str+ signature: str+ docstring: str | None+ file_path: str+ decorators: list[str]+ is_async: bool+ complexity_estimate: int+ callers: list[str]+ source_body: str | None = None+++@dataclass+class ModulePageContext:+ module_path: str+ language: str+ total_symbols: int+ public_symbols: int+ entry_points: list[str]+ dependencies: list[str]+ dependents: list[str]+ pagerank_mean: float+ files: list[str]+++@dataclass+class SccPageContext:+ scc_id: str+ files: list[str]+ cycle_description: str+ total_symbols: int+ member_symbols: list[dict] = field(default_factory=list)+ # [{"file_path": str, "symbols": [{"name": str, "signature": str, "docstring": str}]}]+ cross_imports: list[dict] = field(default_factory=list)+ # [{"from": str, "to": str}]+++@dataclass+class _TopFile:+ """Helper for repo overview top-files list."""++ path: str+ score: float+++@dataclass+class RepoOverviewContext:+ repo_name: str+ is_monorepo: bool+ packages: list[Any] # PackageInfo objects+ language_distribution: dict[str, float]+ total_files: int+ total_loc: int+ entry_points: list[str]+ top_files_by_pagerank: list[_TopFile]+ circular_dependency_count: int+++@dataclass+class ArchitectureDiagramContext:+ repo_name: str+ nodes: list[str]+ edges: list[tuple[str, str]]+ communities: dict[int, list[str]]+ scc_groups: list[list[str]]+++@dataclass+class ApiContractContext:+ file_path: str+ language: str+ raw_content: str+ endpoints: list[str]+ schemas: list[str]+++@dataclass+class InfraPageContext:+ file_path: str+ language: str+ raw_content: str+ targets: list[str]+++@dataclass+class DiffSummaryContext:+ from_ref: str+ to_ref: str+ added_files: list[str]+ deleted_files: list[str]+ modified_files: list[str]+ symbol_diffs: list[Any]+ affected_page_ids: list[str]+ trigger_commit_sha: str | None = None+ trigger_commit_message: str | None = None+ trigger_commit_author: str | None = None+ diff_text: str | None = None+++@dataclass+class CrossPackageContext:+ source_package: str+ target_package: str+ coupling_strength: int # number of boundary files+ used_symbols: list[str] # public symbols from target used by source+ boundary_files: list[str] # files in source that import from target+ source_pagerank_mean: float+ target_pagerank_mean: float+++# ---------------------------------------------------------------------------+# ContextAssembler+# ---------------------------------------------------------------------------+++class ContextAssembler:+ """Assemble Jinja2 template context from ingestion data.++ All public methods return one context dataclass. The token budget is+ applied inside ``_assemble_with_budget`` — no assembly method exceeds+ ``config.token_budget`` tokens.+ """++ def __init__(self, config: GenerationConfig) -> None:+ self._config = config++ # ------------------------------------------------------------------+ # Token utilities+ # ------------------------------------------------------------------++ def _estimate_tokens(self, text: str) -> int:+ """Estimate token count using the 4-chars-per-token heuristic."""+ return len(text) // 4++ def _trim_to_budget(self, text: str, remaining: int) -> str:+ """Truncate *text* so it fits within *remaining* token budget.++ Appends ``"...[truncated]"`` when truncated. The suffix is included+ in the budget calculation so the result never exceeds *remaining* tokens.+ """+ if self._estimate_tokens(text) <= remaining:+ return text+ suffix = "...[truncated]"+ suffix_tokens = self._estimate_tokens(suffix)+ max_chars = (remaining - suffix_tokens) * 4+ if max_chars <= 0:+ return suffix if remaining > 0 else ""+ return text[:max_chars] + suffix++ # ------------------------------------------------------------------+ # File page+ # ------------------------------------------------------------------++ def assemble_file_page(+ self,+ parsed: ParsedFile,+ graph: Any, # nx.DiGraph+ pagerank: dict[str, float],+ betweenness: dict[str, float],+ community: dict[str, int],+ source_bytes: bytes,+ git_meta: dict | None = None,+ dead_code_findings: list[dict] | None = None,+ page_summaries: dict[str, str] | None = None,+ ) -> FilePageContext:+ """Assemble context for the file_page template."""+ path = parsed.file_info.path+ budget = self._config.token_budget+ used = 0++ # Always include: path + language tag overhead+ used += self._estimate_tokens(path) + 5++ # Separate public and private symbols+ public_syms = [s for s in parsed.symbols if s.visibility == "public"]+ private_syms = [s for s in parsed.symbols if s.visibility != "public"]++ # Build symbol dicts — public first, add private if budget allows+ selected_symbols: list[Symbol] = []+ for sym in public_syms:+ sym_tokens = self._estimate_tokens(sym.signature or "")+ if used + sym_tokens < budget:+ selected_symbols.append(sym)+ used += sym_tokens+ else:+ break++ # Private symbols — add documented ones first, then undocumented+ private_documented = [s for s in private_syms if s.docstring]+ private_undocumented = [s for s in private_syms if not s.docstring]+ for sym in private_documented + private_undocumented:+ sym_tokens = self._estimate_tokens(sym.signature or "")+ if used + sym_tokens < budget:+ selected_symbols.append(sym)+ used += sym_tokens+ else:+ break++ sym_dicts = [_symbol_to_dict(s) for s in selected_symbols]++ # Imports (truncate to _MAX_IMPORTS)+ raw_imports = [imp.raw_statement for imp in parsed.imports]+ import_list = raw_imports[:_MAX_IMPORTS]+ imports_text = "\n".join(import_list)+ imports_tokens = self._estimate_tokens(imports_text)+ if used + imports_tokens <= budget:+ used += imports_tokens+ else:+ import_list = []++ # Graph edges+ in_edges = list(graph.predecessors(path)) if path in graph else []+ out_edges = list(graph.successors(path)) if path in graph else []+ # Filter out external nodes+ in_edges = [e for e in in_edges if not e.startswith("external:")]+ out_edges = [e for e in out_edges if not e.startswith("external:")]++ # Source snippet — use structural summary for large files+ source_text = source_bytes.decode("utf-8", errors="replace")+ remaining = budget - used+ source_tokens = self._estimate_tokens(source_text)+ threshold = self._config.token_budget * self._config.large_file_source_pct+ if source_tokens > remaining and source_tokens > threshold:+ snippet = self._build_structural_summary(parsed, source_text, remaining)+ else:+ snippet = self._trim_to_budget(source_text, remaining)+ used += self._estimate_tokens(snippet)++ # Dependency summaries from already-completed pages+ dep_summaries: dict[str, str] = {}+ if page_summaries:+ for dep in out_edges:+ if dep in page_summaries:+ dep_summaries[dep] = page_summaries[dep]++ # Generation depth+ depth = self._select_generation_depth(path, git_meta, pagerank.get(path, 0.0))++ return FilePageContext(+ file_path=path,+ language=parsed.file_info.language,+ docstring=parsed.docstring,+ symbols=sym_dicts,+ imports=import_list,+ exports=parsed.exports,+ file_source_snippet=snippet,+ pagerank_score=pagerank.get(path, 0.0),+ betweenness_score=betweenness.get(path, 0.0),+ community_id=community.get(path, 0),+ dependents=in_edges,+ dependencies=out_edges,+ is_api_contract=parsed.file_info.is_api_contract,+ is_entry_point=parsed.file_info.is_entry_point,+ is_test=parsed.file_info.is_test,+ parse_errors=parsed.parse_errors,+ estimated_tokens=used,+ git_metadata=git_meta,+ dead_code_findings=dead_code_findings or [],+ depth=depth,+ dependency_summaries=dep_summaries,+ )++ # ------------------------------------------------------------------+ # Symbol spotlight+ # ------------------------------------------------------------------++ def assemble_symbol_spotlight(+ self,+ symbol: Symbol,+ parsed: ParsedFile,+ pagerank: dict[str, float],+ graph: Any, # nx.DiGraph+ source_bytes: bytes = b"",+ ) -> SymbolSpotlightContext:+ """Assemble context for the symbol_spotlight template."""+ path = parsed.file_info.path+ # Callers = files that import the containing file (in-edges)+ if path in graph:+ callers = [+ e for e in graph.predecessors(path)+ if not e.startswith("external:")+ ]+ else:+ callers = []++ # Extract source body for the symbol+ source_body = None+ if source_bytes and symbol.start_line and symbol.end_line:+ lines = source_bytes.decode("utf-8", errors="replace").splitlines()+ body_lines = lines[symbol.start_line - 1 : symbol.end_line]+ body = "\n".join(body_lines)+ if len(body) > 8000:+ body = body[:8000] + "\n...[truncated]"+ source_body = body++ return SymbolSpotlightContext(+ symbol_name=symbol.name,+ qualified_name=symbol.qualified_name,+ kind=symbol.kind,+ signature=symbol.signature,+ docstring=symbol.docstring,+ file_path=path,+ decorators=symbol.decorators,+ is_async=symbol.is_async,+ complexity_estimate=symbol.complexity_estimate,+ callers=callers,+ source_body=source_body,+ )++ # ------------------------------------------------------------------+ # Module page+ # ------------------------------------------------------------------++ def assemble_module_page(+ self,+ module_path: str,+ language: str,+ file_contexts: list[FilePageContext],+ graph: Any, # nx.DiGraph+ ) -> ModulePageContext:+ """Assemble context for the module_page template."""+ total_symbols = sum(len(fc.symbols) for fc in file_contexts)+ public_symbols = sum(+ sum(1 for s in fc.symbols if s.get("visibility") == "public")+ for fc in file_contexts+ )+ entry_points = [fc.file_path for fc in file_contexts if fc.is_entry_point]+ files = [fc.file_path for fc in file_contexts]++ # Aggregate dependencies/dependents across all files in module+ all_deps: set[str] = set()+ all_dependents: set[str] = set()+ for fc in file_contexts:+ all_deps.update(fc.dependencies)+ all_dependents.update(fc.dependents)+ # Remove intra-module edges+ all_deps -= set(files)+ all_dependents -= set(files)++ pagerank_mean = 0.0+ if file_contexts:+ pagerank_mean = sum(fc.pagerank_score for fc in file_contexts) / len(+ file_contexts+ )++ return ModulePageContext(+ module_path=module_path,+ language=language,+ total_symbols=total_symbols,+ public_symbols=public_symbols,+ entry_points=entry_points,+ dependencies=sorted(all_deps),+ dependents=sorted(all_dependents),+ pagerank_mean=pagerank_mean,+ files=files,+ )++ # ------------------------------------------------------------------+ # SCC page+ # ------------------------------------------------------------------++ def assemble_scc_page(+ self,+ scc_id: str,+ scc_files: list[str],+ file_contexts: list[FilePageContext],+ ) -> SccPageContext:+ """Assemble context for the scc_page template."""+ cycle_parts = " → ".join(scc_files)+ cycle_description = f"Circular dependency cycle: {cycle_parts}"+ total_symbols = sum(len(fc.symbols) for fc in file_contexts)++ scc_set = set(scc_files)+ member_symbols = []+ for fc in file_contexts:+ pub = [s for s in fc.symbols if s.get("visibility") == "public"][:5]+ member_symbols.append({"file_path": fc.file_path, "symbols": pub})++ cross_imports = [+ {"from": fc.file_path, "to": dep}+ for fc in file_contexts+ for dep in fc.dependencies+ if dep in scc_set and dep != fc.file_path+ ]++ return SccPageContext(+ scc_id=scc_id,+ files=scc_files,+ cycle_description=cycle_description,+ total_symbols=total_symbols,+ member_symbols=member_symbols,+ cross_imports=cross_imports,+ )++ # ------------------------------------------------------------------+ # Repo overview+ # ------------------------------------------------------------------++ def assemble_repo_overview(+ self,+ repo_structure: RepoStructure,+ pagerank: dict[str, float],+ sccs: list[Any], # list[frozenset[str]]+ community: dict[str, int],+ ) -> RepoOverviewContext:+ """Assemble context for the repo_overview template."""+ # Top files sorted by PageRank descending+ sorted_pr = sorted(pagerank.items(), key=lambda x: x[1], reverse=True)+ top_files = [+ _TopFile(path=p, score=s)+ for p, s in sorted_pr[:_MAX_TOP_FILES]+ if not p.startswith("external:")+ ]++ # SCCs with len > 1 are true circular deps+ circular_count = sum(1 for scc in sccs if len(scc) > 1)++ return RepoOverviewContext(+ repo_name=getattr(repo_structure, "name", "repo"),+ is_monorepo=repo_structure.is_monorepo,+ packages=repo_structure.packages,+ language_distribution=repo_structure.root_language_distribution,+ total_files=repo_structure.total_files,+ total_loc=repo_structure.total_loc,+ entry_points=repo_structure.entry_points,+ top_files_by_pagerank=top_files,+ circular_dependency_count=circular_count,+ )++ # ------------------------------------------------------------------+ # Architecture diagram+ # ------------------------------------------------------------------++ def assemble_architecture_diagram(+ self,+ graph: Any, # nx.DiGraph+ pagerank: dict[str, float],+ community: dict[str, int],+ sccs: list[Any], # list[frozenset[str]]+ repo_name: str,+ ) -> ArchitectureDiagramContext:+ """Assemble context for the architecture_diagram template."""+ _MAX_DIAGRAM_NODES = 50+ _MAX_DIAGRAM_EDGES = 200++ # Top-N nodes by PageRank (exclude external nodes)+ top_nodes = set(+ p for p, _ in sorted(pagerank.items(), key=lambda x: x[1], reverse=True)[:_MAX_DIAGRAM_NODES]+ if not str(p).startswith("external:")+ )+ nodes = sorted(top_nodes)++ # Only edges between selected nodes+ edges = [+ (src, dst) for src, dst in graph.edges()+ if src in top_nodes and dst in top_nodes+ ][:_MAX_DIAGRAM_EDGES]++ # Community → members mapping (top-10 communities, cap members to 5)+ raw_communities: dict[int, list[str]] = {}+ for path, cid in community.items():+ if not path.startswith("external:"):+ raw_communities.setdefault(cid, []).append(path)+ comm_sorted = sorted(raw_communities.items(), key=lambda x: len(x[1]), reverse=True)[:10]+ communities: dict[int, list[str]] = {cid: members[:5] for cid, members in comm_sorted}++ # SCC groups (only non-singleton)+ scc_groups = [+ sorted(scc)+ for scc in sccs+ if len(scc) > 1+ ]++ return ArchitectureDiagramContext(+ repo_name=repo_name,+ nodes=nodes,+ edges=edges,+ communities=communities,+ scc_groups=scc_groups,+ )++ # ------------------------------------------------------------------+ # API contract+ # ------------------------------------------------------------------++ def assemble_api_contract(+ self,+ parsed: ParsedFile,+ source_bytes: bytes,+ ) -> ApiContractContext:+ """Assemble context for the api_contract template."""+ source_text = source_bytes.decode("utf-8", errors="replace")+ remaining = self._config.token_budget+ raw_content = self._trim_to_budget(source_text, remaining)++ # Extract endpoints/schemas from metadata if available+ endpoints: list[str] = []+ schemas: list[str] = []+ for sym in parsed.symbols:+ if sym.kind in ("function", "method"):+ endpoints.append(sym.signature)+ elif sym.kind in ("class", "interface", "struct"):+ schemas.append(sym.name)++ return ApiContractContext(+ file_path=parsed.file_info.path,+ language=parsed.file_info.language,+ raw_content=raw_content,+ endpoints=endpoints,+ schemas=schemas,+ )++ # ------------------------------------------------------------------+ # Infra page+ # ------------------------------------------------------------------++ def assemble_infra_page(+ self,+ parsed: ParsedFile,+ source_bytes: bytes,+ ) -> InfraPageContext:+ """Assemble context for the infra_page template."""+ source_text = source_bytes.decode("utf-8", errors="replace")+ remaining = self._config.token_budget+ raw_content = self._trim_to_budget(source_text, remaining)++ targets = [sym.name for sym in parsed.symbols]++ return InfraPageContext(+ file_path=parsed.file_info.path,+ language=parsed.file_info.language,+ raw_content=raw_content,+ targets=targets,+ )++ # ------------------------------------------------------------------+ # Diff summary+ # ------------------------------------------------------------------++ def assemble_diff_summary(+ self,+ file_diffs: list[Any], # list[FileDiff]+ affected_pages: Any, # AffectedPages+ from_ref: str,+ to_ref: str,+ ) -> DiffSummaryContext:+ """Assemble context for the diff_summary template."""+ added_files = [d.path for d in file_diffs if d.status == "added"]+ deleted_files = [d.path for d in file_diffs if d.status == "deleted"]+ modified_files = [d.path for d in file_diffs if d.status == "modified"]++ symbol_diffs = [d.symbol_diff for d in file_diffs if d.symbol_diff is not None]++ affected_page_ids = list(affected_pages.regenerate) if affected_pages else []++ # Extract trigger commit from first diff that has it+ trigger_sha = None+ trigger_msg = None+ trigger_author = None+ diff_text = None+ for d in file_diffs:+ if getattr(d, "trigger_commit_sha", None):+ trigger_sha = d.trigger_commit_sha+ trigger_msg = d.trigger_commit_message+ trigger_author = d.trigger_commit_author+ diff_text = d.diff_text+ break++ return DiffSummaryContext(+ from_ref=from_ref,+ to_ref=to_ref,+ added_files=added_files,+ deleted_files=deleted_files,+ modified_files=modified_files,+ symbol_diffs=symbol_diffs,+ affected_page_ids=affected_page_ids,+ trigger_commit_sha=trigger_sha,+ trigger_commit_message=trigger_msg,+ trigger_commit_author=trigger_author,+ diff_text=diff_text,+ )++ # ------------------------------------------------------------------+ # Cross-package context (Phase 9 C2)+ # ------------------------------------------------------------------++ def assemble_cross_package(+ self,+ source_pkg: str,+ target_pkg: str,+ source_fcs: list[FilePageContext],+ target_fcs: list[FilePageContext],+ graph: Any,+ ) -> CrossPackageContext:+ """Assemble context for cross-package dependency page."""+ target_paths = {fc.file_path for fc in target_fcs}+ boundary = [fc for fc in source_fcs if any(d in target_paths for d in fc.dependencies)]+ used_syms = sorted({+ sym["name"]+ for fc in target_fcs+ for sym in fc.symbols if sym.get("visibility") == "public"+ })[:20]+ return CrossPackageContext(+ source_package=source_pkg,+ target_package=target_pkg,+ coupling_strength=len(boundary),+ used_symbols=used_syms,+ boundary_files=[fc.file_path for fc in boundary],+ source_pagerank_mean=sum(fc.pagerank_score for fc in source_fcs) / max(len(source_fcs), 1),+ target_pagerank_mean=sum(fc.pagerank_score for fc in target_fcs) / max(len(target_fcs), 1),+ )++ # ------------------------------------------------------------------+ # Structural summary for large files (Phase 9 C1)+ # ------------------------------------------------------------------++ def _build_structural_summary(self, parsed: ParsedFile, source_text: str, budget: int) -> str:+ """Build a structural outline for large files instead of raw truncation.++ Includes full body for the 3 most complex symbols; signature-only for rest.+ """+ lines = source_text.splitlines()+ parts = ["[Large file — structural summary mode]"]+ top3_complex = {+ s.name for s in sorted(+ parsed.symbols, key=lambda s: s.complexity_estimate, reverse=True+ )[:3]+ }++ for sym in parsed.symbols:+ if sym.start_line and sym.end_line and sym.name in top3_complex:+ body = "\n".join(lines[sym.start_line - 1 : sym.end_line])+ parts.append(f"\n# {sym.name} (full body, complexity={sym.complexity_estimate})\n{body}")+ else:+ parts.append(f"# {sym.signature or sym.name}")+ if self._estimate_tokens("\n".join(parts)) >= budget:+ parts.append("...[remaining symbols omitted]")+ break++ return self._trim_to_budget("\n".join(parts), budget)++ # ------------------------------------------------------------------+ # Generation depth selection (Phase 5.5)+ # ------------------------------------------------------------------++ def _select_generation_depth(+ self,+ file_path: str,+ git_meta: dict | None,+ pagerank_score: float,+ config_depth: str = "standard",+ ) -> str:+ """Select generation depth based on git metadata.++ Upgrade to "thorough" if: hotspot, >100 commits with >10 in 90d,+ >=8 significant commits, or has co-change partners.+ Downgrade to "minimal" if: stable AND pagerank < 0.3 AND commit_count < 5.+ """+ if git_meta is None:+ return config_depth++ import json as _json++ # Upgrade conditions+ if git_meta.get("is_hotspot", False):+ return "thorough"++ commit_total = git_meta.get("commit_count_total", 0)+ commit_90d = git_meta.get("commit_count_90d", 0)+ if commit_total > 100 and commit_90d > 10:+ return "thorough"++ sig_json = git_meta.get("significant_commits_json", "[]")+ try:+ sig_commits = _json.loads(sig_json) if isinstance(sig_json, str) else sig_json+ except Exception:+ sig_commits = []+ if len(sig_commits) >= 8:+ return "thorough"++ co_json = git_meta.get("co_change_partners_json", "[]")+ try:+ co_partners = _json.loads(co_json) if isinstance(co_json, str) else co_json+ except Exception:+ co_partners = []+ if co_partners:+ return "thorough"++ # Downgrade conditions+ if (+ git_meta.get("is_stable", False)+ and pagerank_score < 0.3+ and commit_total < 5+ ):+ return "minimal"++ return config_depth++ # ------------------------------------------------------------------+ # Update context assembly (Phase 5.5)+ # ------------------------------------------------------------------++ def assemble_update_context(+ self,+ parsed: ParsedFile,+ graph: Any,+ pagerank: dict[str, float],+ betweenness: dict[str, float],+ community: dict[str, int],+ source_bytes: bytes,+ trigger_commit_sha: str | None = None,+ trigger_commit_message: str | None = None,+ diff_text: str | None = None,+ git_meta: dict | None = None,+ ) -> FilePageContext:+ """Assemble context for maintenance regeneration using trigger commit + diff."""+ ctx = self.assemble_file_page(+ parsed, graph, pagerank, betweenness, community, source_bytes,+ git_meta=git_meta,+ )+ # Enrich with trigger context (stored in rag_context for now)+ if trigger_commit_sha:+ ctx.rag_context.append(+ f"Trigger commit: {trigger_commit_sha}"+ + (f" — {trigger_commit_message}" if trigger_commit_message else "")+ )+ if diff_text:+ trimmed_diff = self._trim_to_budget(diff_text, 1000)+ ctx.rag_context.append(f"Diff:\n{trimmed_diff}")+ return ctx+++# ---------------------------------------------------------------------------+# Internal helpers+# ---------------------------------------------------------------------------+++def _symbol_to_dict(symbol: Symbol) -> dict[str, Any]:+ """Convert a Symbol to a plain dict for template rendering."""+ return {+ "name": symbol.name,+ "qualified_name": symbol.qualified_name,+ "kind": symbol.kind,+ "signature": symbol.signature,+ "docstring": symbol.docstring,+ "visibility": symbol.visibility,+ "is_async": symbol.is_async,+ "complexity_estimate": symbol.complexity_estimate,+ "decorators": symbol.decorators,+ "parent_name": symbol.parent_name,+ "start_line": symbol.start_line,+ "end_line": symbol.end_line,+ }diff --git a/packages/core/src/wikicode/core/generation/job_system.py b/packages/core/src/wikicode/core/generation/job_system.pynew file mode 100644index 000000000..b3d308e8f--- /dev/null+++ b/packages/core/src/wikicode/core/generation/job_system.py@@ -0,0 +1,252 @@+"""Job system for the WikiCode generation engine.++JobSystem manages long-running generation jobs via JSON checkpoint files.+Each job maps to a single {job_id}.json file in the configured jobs_dir.+The checkpoint records progress (completed/failed pages), current level, and+job status so generation can be resumed after interruption.++Phase 4 will replace this with a full SQLAlchemy-backed job table.+"""++from __future__ import annotations++import dataclasses+import json+import uuid+from dataclasses import dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Literal++import structlog++log = structlog.get_logger(__name__)++JobStatus = Literal["pending", "running", "completed", "failed", "paused"]+++def _now_iso() -> str:+ return datetime.now(timezone.utc).isoformat()+++# ---------------------------------------------------------------------------+# Checkpoint+# ---------------------------------------------------------------------------+++@dataclass+class Checkpoint:+ """Persistent state for a single generation job."""++ job_id: str+ status: str # JobStatus literal+ created_at: str # ISO-8601 UTC+ updated_at: str # ISO-8601 UTC+ repo_path: str+ config_snapshot: dict[str, object]+ total_pages: int+ completed_pages: int+ failed_pages: int+ completed_page_ids: list[str]+ failed_page_ids: list[str]+ error_message: str | None+ provider_name: str+ model_name: str+ current_level: int++ @classmethod+ def from_dict(cls, d: dict[str, Any]) -> "Checkpoint":+ """Reconstruct a Checkpoint from a JSON-decoded dict."""+ return cls(+ job_id=d["job_id"],+ status=d["status"],+ created_at=d["created_at"],+ updated_at=d["updated_at"],+ repo_path=d["repo_path"],+ config_snapshot=d.get("config_snapshot", {}),+ total_pages=d.get("total_pages", 0),+ completed_pages=d.get("completed_pages", 0),+ failed_pages=d.get("failed_pages", 0),+ completed_page_ids=d.get("completed_page_ids", []),+ failed_page_ids=d.get("failed_page_ids", []),+ error_message=d.get("error_message"),+ provider_name=d.get("provider_name", ""),+ model_name=d.get("model_name", ""),+ current_level=d.get("current_level", 0),+ )+++# ---------------------------------------------------------------------------+# JobSystem+# ---------------------------------------------------------------------------+++class JobSystem:+ """Manage generation job checkpoints via JSON files on disk.++ Args:+ jobs_dir: Directory where {job_id}.json checkpoint files are stored.+ Created automatically if it does not exist.+ """++ def __init__(self, jobs_dir: Path) -> None:+ self._jobs_dir = jobs_dir+ jobs_dir.mkdir(parents=True, exist_ok=True)++ # ------------------------------------------------------------------+ # Job lifecycle+ # ------------------------------------------------------------------++ def create_job(+ self,+ repo_path: str,+ config: Any, # GenerationConfig+ provider_name: str,+ model_name: str,+ ) -> str:+ """Create a new job and return its UUID."""+ job_id = str(uuid.uuid4())+ # Serialize config to dict (works for frozen dataclasses)+ try:+ config_dict: dict[str, object] = dataclasses.asdict(config)+ except TypeError:+ config_dict = {}++ now = _now_iso()+ checkpoint = Checkpoint(+ job_id=job_id,+ status="pending",+ created_at=now,+ updated_at=now,+ repo_path=repo_path,+ config_snapshot=config_dict,+ total_pages=0,+ completed_pages=0,+ failed_pages=0,+ completed_page_ids=[],+ failed_page_ids=[],+ error_message=None,+ provider_name=provider_name,+ model_name=model_name,+ current_level=0,+ )+ self._save(checkpoint)+ log.info("Job created", job_id=job_id, repo_path=repo_path)+ return job_id++ def start_job(self, job_id: str, total_pages: int) -> None:+ """Transition job from pending → running and set total_pages."""+ cp = self._transition(job_id, "pending", "running")+ cp.total_pages = total_pages+ self._save(cp)++ def complete_page(self, job_id: str, page_id: str) -> None:+ """Record a successfully generated page."""+ cp = self._load(job_id)+ if page_id not in cp.completed_page_ids:+ cp.completed_page_ids.append(page_id)+ cp.completed_pages = len(cp.completed_page_ids)+ cp.updated_at = _now_iso()+ self._save(cp)++ def fail_page(self, job_id: str, page_id: str, error: str) -> None:+ """Record a failed page (job stays running)."""+ cp = self._load(job_id)+ if page_id not in cp.failed_page_ids:+ cp.failed_page_ids.append(page_id)+ cp.failed_pages = len(cp.failed_page_ids)+ cp.updated_at = _now_iso()+ self._save(cp)+ log.warning("Page failed", job_id=job_id, page_id=page_id, error=error)++ def complete_job(self, job_id: str) -> None:+ """Transition job from running → completed."""+ cp = self._transition(job_id, "running", "completed")+ self._save(cp)++ def fail_job(self, job_id: str, error_message: str) -> None:+ """Transition job from running → failed."""+ cp = self._transition(job_id, "running", "failed")+ cp.error_message = error_message+ self._save(cp)++ def pause_job(self, job_id: str) -> None:+ """Transition job from running → paused."""+ cp = self._transition(job_id, "running", "paused")+ self._save(cp)++ def resume_job(self, job_id: str) -> Checkpoint:+ """Transition job from paused → running and return the checkpoint."""+ cp = self._transition(job_id, "paused", "running")+ self._save(cp)+ return cp++ def update_level(self, job_id: str, level: int) -> None:+ """Update the current generation level."""+ cp = self._load(job_id)+ cp.current_level = level+ cp.updated_at = _now_iso()+ self._save(cp)++ # ------------------------------------------------------------------+ # Queries+ # ------------------------------------------------------------------++ def get_checkpoint(self, job_id: str) -> Checkpoint:+ """Load and return the checkpoint for *job_id*."""+ return self._load(job_id)++ def get_completed_page_ids(self, job_id: str) -> set[str]:+ """Return the set of already-completed page IDs for *job_id*."""+ return set(self._load(job_id).completed_page_ids)++ def list_jobs(self) -> list[Checkpoint]:+ """Return all jobs sorted by created_at descending."""+ checkpoints: list[Checkpoint] = []+ for json_path in self._jobs_dir.glob("*.json"):+ try:+ data = json.loads(json_path.read_text(encoding="utf-8"))+ checkpoints.append(Checkpoint.from_dict(data))+ except Exception as exc:+ log.warning("Failed to load checkpoint", path=str(json_path), error=str(exc))+ checkpoints.sort(key=lambda c: c.created_at, reverse=True)+ return checkpoints++ # ------------------------------------------------------------------+ # Internals+ # ------------------------------------------------------------------++ def _load(self, job_id: str) -> Checkpoint:+ path = self._jobs_dir / f"{job_id}.json"+ if not path.exists():+ raise FileNotFoundError(f"Job checkpoint not found: {job_id}")+ data = json.loads(path.read_text(encoding="utf-8"))+ return Checkpoint.from_dict(data)++ def _save(self, checkpoint: Checkpoint) -> None:+ checkpoint.updated_at = _now_iso()+ path = self._jobs_dir / f"{checkpoint.job_id}.json"+ path.write_text(+ json.dumps(dataclasses.asdict(checkpoint), indent=2),+ encoding="utf-8",+ )++ def _transition(+ self,+ job_id: str,+ expected_status: str,+ new_status: str,+ ) -> Checkpoint:+ """Load checkpoint, validate current status, apply transition.++ Raises:+ ValueError: If the current status does not match *expected_status*.+ """+ cp = self._load(job_id)+ if cp.status != expected_status:+ raise ValueError(+ f"Job {job_id}: expected status '{expected_status}', "+ f"got '{cp.status}' (cannot transition to '{new_status}')"+ )+ cp.status = new_status+ return cpdiff --git a/packages/core/src/wikicode/core/generation/models.py b/packages/core/src/wikicode/core/generation/models.pynew file mode 100644index 000000000..67fe54c50--- /dev/null+++ b/packages/core/src/wikicode/core/generation/models.py@@ -0,0 +1,357 @@+"""Data models for the WikiCode generation engine.++These models represent generated wiki pages, configuration, and freshness+tracking. They are intentionally independent of ingestion models so the+import graph stays one-directional:++ ingestion.models ← generation.models ← context_assembler ← page_generator+"""++from __future__ import annotations++import hashlib+from dataclasses import dataclass, field+from datetime import datetime, timezone+from typing import Literal++# ---------------------------------------------------------------------------+# PageType and generation levels+# ---------------------------------------------------------------------------++PageType = Literal[+ "api_contract",+ "symbol_spotlight",+ "file_page",+ "scc_page",+ "module_page",+ "cross_package",+ "repo_overview",+ "architecture_diagram",+ "infra_page",+ "diff_summary",+]++# Maps PageType → generation level (0 = first, 7 = last)+GENERATION_LEVELS: dict[str, int] = {+ "api_contract": 0,+ "symbol_spotlight": 1,+ "file_page": 2,+ "scc_page": 3,+ "module_page": 4,+ "cross_package": 5,+ "repo_overview": 6,+ "architecture_diagram": 6,+ "infra_page": 7,+ "diff_summary": 7,+}++FreshnessStatus = Literal["fresh", "stale", "expired", "unknown"]+++# ---------------------------------------------------------------------------+# GenerationConfig+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class GenerationConfig:+ """Configuration for the generation engine.++ Attributes:+ max_tokens: Max tokens in LLM completion.+ temperature: Sampling temperature (0.3 for consistent docs).+ token_budget: Context tokens fed to LLM (not output).+ max_concurrency: asyncio.Semaphore size for parallel calls.+ cache_enabled: In-memory SHA256 prompt deduplication.+ staleness_threshold_days: Days before a page is considered stale.+ expiry_threshold_days: Days before a page is considered expired.+ top_symbol_percentile: Top N% by PageRank → symbol_spotlight.+ jobs_dir: Directory for job checkpoint JSON files.+ """++ max_tokens: int = 16000+ temperature: float = 0.3+ token_budget: int = 48000+ max_concurrency: int = 5+ cache_enabled: bool = True+ staleness_threshold_days: int = 7+ expiry_threshold_days: int = 30+ top_symbol_percentile: float = 0.10 # top N% public symbols by PageRank → symbol_spotlight+ file_page_top_percentile: float = 0.10 # top N% code files by PageRank → file_page+ file_page_min_symbols: int = 1 # files with fewer symbols are skipped for file_page+ max_pages_pct: float = 0.10 # hard cap: total pages ≤ max(50, N_files * this)+ jobs_dir: str = ".wikicode/jobs"+ large_file_source_pct: float = 0.4 # use structural summary when source tokens > budget * this+++# ---------------------------------------------------------------------------+# GeneratedPage+# ---------------------------------------------------------------------------+++@dataclass+class GeneratedPage:+ """A single wiki page produced by the generation engine.++ Attributes:+ page_id: Deterministic ID: "{page_type}:{target_path}".+ page_type: One of the PageType literals.+ title: Human-readable page title.+ content: Raw markdown content from the LLM.+ source_hash: SHA256 of the user_prompt (used for freshness).+ model_name: LLM model identifier (e.g. "claude-sonnet-4-6").+ provider_name: Provider identifier (e.g. "anthropic", "mock").+ input_tokens: Prompt tokens consumed.+ output_tokens: Completion tokens produced.+ cached_tokens: Tokens served from provider cache.+ generation_level: Numeric generation level (0–7).+ target_path: File/module/SCC this page documents.+ created_at: ISO-8601 UTC timestamp.+ updated_at: ISO-8601 UTC timestamp.+ confidence: Decay score (1.0 = fresh, 0.0 = expired).+ freshness_status: Current freshness state.+ metadata: Provider-specific or page-type-specific extras.+ """++ page_id: str+ page_type: str # PageType literal+ title: str+ content: str+ source_hash: str+ model_name: str+ provider_name: str+ input_tokens: int+ output_tokens: int+ cached_tokens: int+ generation_level: int+ target_path: str+ created_at: str # ISO-8601 UTC+ updated_at: str # ISO-8601 UTC+ confidence: float = 1.0+ freshness_status: str = "fresh" # FreshnessStatus literal+ metadata: dict[str, object] = field(default_factory=dict)++ @property+ def total_tokens(self) -> int:+ """Total tokens consumed (input + output)."""+ return self.input_tokens + self.output_tokens+++# ---------------------------------------------------------------------------+# ConfidenceDecayResult+# ---------------------------------------------------------------------------+++@dataclass+class ConfidenceDecayResult:+ """Result of applying confidence decay to a GeneratedPage."""++ page_id: str+ old_confidence: float+ new_confidence: float+ freshness_status: str # FreshnessStatus literal+ days_since_update: int+++# ---------------------------------------------------------------------------+# Helper functions+# ---------------------------------------------------------------------------+++def compute_page_id(page_type: str, target_path: str) -> str:+ """Return a deterministic page ID: '{page_type}:{target_path}'."""+ return f"{page_type}:{target_path}"+++def _parse_datetime(ts: str) -> datetime:+ """Parse an ISO-8601 UTC timestamp to a timezone-aware datetime."""+ ts = ts.replace("Z", "+00:00")+ dt = datetime.fromisoformat(ts)+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return dt+++def compute_freshness(+ page: GeneratedPage,+ current_source_hash: str,+ config: GenerationConfig,+ as_of: datetime | None = None,+) -> str:+ """Determine the freshness status of a page.++ Args:+ page: The page to evaluate.+ current_source_hash: SHA256 of the current user_prompt.+ config: GenerationConfig with threshold settings.+ as_of: Reference datetime (defaults to now UTC).++ Returns:+ FreshnessStatus: "fresh", "stale", or "expired".+ """+ if as_of is None:+ as_of = datetime.now(timezone.utc)+ if as_of.tzinfo is None:+ as_of = as_of.replace(tzinfo=timezone.utc)++ updated = _parse_datetime(page.updated_at)+ days = (as_of - updated).total_seconds() / 86400.0++ # Expiry takes priority+ if days >= config.expiry_threshold_days:+ return "expired"++ # Hash mismatch → stale+ if page.source_hash != current_source_hash:+ return "stale"++ # Age threshold+ if days >= config.staleness_threshold_days:+ return "stale"++ return "fresh"+++def decay_confidence(+ page: GeneratedPage,+ config: GenerationConfig,+ as_of: datetime | None = None,+) -> ConfidenceDecayResult:+ """Apply linear confidence decay based on page age.++ Confidence decays linearly from 1.0 to 0.0 over expiry_threshold_days.++ Args:+ page: The page to evaluate.+ config: GenerationConfig with threshold settings.+ as_of: Reference datetime (defaults to now UTC).++ Returns:+ ConfidenceDecayResult with old/new confidence and freshness status.+ """+ if as_of is None:+ as_of = datetime.now(timezone.utc)+ if as_of.tzinfo is None:+ as_of = as_of.replace(tzinfo=timezone.utc)++ updated = _parse_datetime(page.updated_at)+ days = (as_of - updated).total_seconds() / 86400.0+ days_since = int(days)++ # Linear decay: 1.0 → 0.0 over expiry_threshold_days+ new_confidence = max(0.0, 1.0 - days / config.expiry_threshold_days)++ if days >= config.expiry_threshold_days:+ freshness: str = "expired"+ elif days >= config.staleness_threshold_days:+ freshness = "stale"+ else:+ freshness = "fresh"++ return ConfidenceDecayResult(+ page_id=page.page_id,+ old_confidence=page.confidence,+ new_confidence=new_confidence,+ freshness_status=freshness,+ days_since_update=days_since,+ )+++def compute_source_hash(text: str) -> str:+ """Return the SHA-256 hex digest of *text* (used as source_hash)."""+ return hashlib.sha256(text.encode()).hexdigest()+++# ---------------------------------------------------------------------------+# Git and Dead Code Config (Phase 5.5)+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class GitConfig:+ """Configuration for git intelligence features."""++ enabled: bool = True+ co_change_commit_limit: int = 500+ co_change_min_count: int = 3+ blame_enabled: bool = True+ prompt_commit_count: int = 10+ depth_auto_upgrade: bool = True+++@dataclass(frozen=True)+class DeadCodeConfig:+ """Configuration for dead code detection."""++ enabled: bool = True+ detect_unreachable_files: bool = True+ detect_unused_exports: bool = True+ detect_unused_internals: bool = False+ detect_zombie_packages: bool = True+ min_confidence: float = 0.4+ safe_to_delete_threshold: float = 0.7+ dynamic_patterns: tuple[str, ...] = (+ "*Plugin",+ "*Handler",+ "*Adapter",+ "*Middleware",+ "register_*",+ "on_*",+ )+ analyze_on_update: bool = True+++# ---------------------------------------------------------------------------+# Git-informed confidence decay (Phase 5.5)+# ---------------------------------------------------------------------------+++def compute_confidence_decay_with_git(+ base_decay: float,+ relationship: str,+ git_meta: dict | None,+ commit_message: str | None,+) -> float:+ """Apply git modifiers multiplicatively on base decay.++ Args:+ base_decay: Base decay factor (e.g. 0.85 for direct).+ relationship: "direct", "1hop", or "2hop".+ git_meta: Git metadata dict for the file (may be None).+ commit_message: The commit message that triggered the change (may be None).++ Returns:+ Modified decay factor.+ """+ result = base_decay++ if git_meta:+ is_hotspot = git_meta.get("is_hotspot", False)+ is_stable = git_meta.get("is_stable", False)++ # Hotspot: decays faster+ if is_hotspot:+ if relationship == "direct":+ result *= 0.94+ elif relationship == "1hop":+ result *= 0.95++ # Stable: decays slower+ if is_stable:+ if relationship == "direct":+ result *= 1.03++ if commit_message:+ msg_lower = commit_message.lower()+ # Large changes: hard decay+ if any(kw in msg_lower for kw in ("rewrite", "refactor", "migrate")):+ if relationship == "direct":+ result *= 0.71+ elif relationship == "1hop":+ result *= 0.84+ # Cosmetic changes: soft decay+ elif any(kw in msg_lower for kw in ("typo", "lint", "format")):+ if relationship == "direct":+ result *= 1.12++ return resultdiff --git a/packages/core/src/wikicode/core/generation/page_generator.py b/packages/core/src/wikicode/core/generation/page_generator.pynew file mode 100644index 000000000..291ac0ac9--- /dev/null+++ b/packages/core/src/wikicode/core/generation/page_generator.py@@ -0,0 +1,896 @@+"""Page generator — converts context dataclasses into GeneratedPage objects.++PageGenerator is the main orchestration layer. It:+ 1. Calls ContextAssembler to build template context from ingestion data.+ 2. Renders the Jinja2 user-prompt template.+ 3. Calls the provider with the rendered prompt + system prompt constant.+ 4. Wraps the response in a GeneratedPage.+ 5. Manages concurrency (asyncio.Semaphore) and prompt caching (SHA256).++System prompts are module-level constants — the same string per page type on+every call. This enables Anthropic server-side prefix caching.+"""++from __future__ import annotations++import asyncio+import hashlib+import uuid+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Callable++import jinja2+import structlog++from wikicode.core.ingestion.models import ParsedFile, RepoStructure+from wikicode.core.providers.base import BaseProvider, GeneratedResponse++from .context_assembler import ContextAssembler, FilePageContext, CrossPackageContext+from .models import (+ GENERATION_LEVELS,+ GeneratedPage,+ GenerationConfig,+ compute_page_id,+ compute_source_hash,+)++log = structlog.get_logger(__name__)++# ---------------------------------------------------------------------------+# System prompts — one per page type (constant strings for prefix caching)+# ---------------------------------------------------------------------------++SYSTEM_PROMPTS: dict[str, str] = {+ "file_page": (+ "You are WikiCode, an expert technical documentation generator. "+ "Your task is to produce comprehensive, accurate wiki pages from source code. "+ "Output markdown only. Do not include preamble or apologies. "+ "Required sections: ## Overview, ## Public API, ## Dependencies, ## Usage Notes."+ ),+ "symbol_spotlight": (+ "You are WikiCode, an expert technical documentation generator. "+ "Write a detailed spotlight page for a single code symbol. "+ "Output markdown only. "+ "Required sections: ## Purpose, ## Signature, ## Parameters, ## Returns, ## Example Usage."+ ),+ "module_page": (+ "You are WikiCode, an expert technical documentation generator. "+ "Write a module-level overview page summarising all files in the module. "+ "Output markdown only. "+ "Required sections: ## Overview, ## Public API Summary, ## Architecture Notes."+ ),+ "scc_page": (+ "You are WikiCode, an expert technical documentation generator. "+ "Document this circular dependency cycle and provide actionable refactoring advice. "+ "Output markdown only. "+ "Required sections: ## Cycle Description, ## Files Involved, ## Why This Exists, "+ "## Refactoring Suggestions."+ ),+ "repo_overview": (+ "You are WikiCode, an expert technical documentation generator. "+ "Write a high-level repository overview suitable for onboarding new developers. "+ "Output markdown only. "+ "Required sections: ## Project Summary, ## Technology Stack, ## Entry Points, ## Architecture."+ ),+ "architecture_diagram": (+ "You are WikiCode, an expert technical documentation generator. "+ "Generate an architecture overview with a Mermaid diagram. "+ "You MUST include a fenced mermaid block with graph TD showing key dependencies. "+ "Output markdown only."+ ),+ "api_contract": (+ "You are WikiCode, an expert technical documentation generator. "+ "Document this API contract file for developers integrating with the service. "+ "Output markdown only. "+ "Required sections: ## Overview, ## Endpoints, ## Schemas, ## Authentication, ## Examples."+ ),+ "infra_page": (+ "You are WikiCode, an expert technical documentation generator. "+ "Document this infrastructure file for DevOps and platform engineers. "+ "Output markdown only. "+ "Required sections: ## Purpose, ## Key Targets/Stages, ## Configuration, ## Operational Notes."+ ),+ "diff_summary": (+ "You are WikiCode, an expert technical documentation generator. "+ "Summarise the changes between two git refs and their documentation impact. "+ "Output markdown only. "+ "Required sections: ## Summary, ## Changed Files, ## Symbol Changes, ## Affected Documentation."+ ),+ "cross_package": (+ "You are WikiCode, an expert technical documentation generator. "+ "Document the cross-package boundary and integration points. "+ "Output markdown only. "+ "Required sections: ## Overview, ## Package Boundaries, ## Integration Points."+ ),+}++# Infra file languages+_INFRA_LANGUAGES = frozenset({"dockerfile", "makefile", "terraform", "shell"})+_INFRA_FILENAMES = frozenset({"Dockerfile", "Makefile", "GNUmakefile"})++# Languages worth generating file pages for — data/config/doc files excluded+_CODE_LANGUAGES = frozenset({+ "python", "typescript", "javascript", "go", "rust",+ "java", "cpp", "c", "csharp", "ruby", "kotlin", "scala",+ "swift", "php",+})+++def _now_iso() -> str:+ """Return current UTC time as ISO-8601 string."""+ return datetime.now(timezone.utc).isoformat()+++class PageGenerator:+ """Generate wiki pages by rendering prompts and calling an LLM provider.++ Args:+ provider: Any BaseProvider implementation.+ assembler: ContextAssembler instance.+ config: GenerationConfig controlling budget, concurrency, caching.+ jinja_env: Optional Jinja2 Environment (defaults to FileSystemLoader+ pointing at the templates/ directory next to this file).+ """++ def __init__(+ self,+ provider: BaseProvider,+ assembler: ContextAssembler,+ config: GenerationConfig,+ jinja_env: jinja2.Environment | None = None,+ vector_store: Any | None = None, # VectorStore | None+ ) -> None:+ self._provider = provider+ self._assembler = assembler+ self._config = config+ self._vector_store = vector_store+ self._cache: dict[str, GeneratedResponse] = {}++ if jinja_env is None:+ templates_dir = Path(__file__).parent / "templates"+ loader = jinja2.FileSystemLoader(str(templates_dir))+ jinja_env = jinja2.Environment(+ loader=loader,+ undefined=jinja2.StrictUndefined,+ autoescape=False,+ )+ self._jinja_env = jinja_env++ # ------------------------------------------------------------------+ # Per-type generation methods+ # ------------------------------------------------------------------++ async def generate_file_page(+ self,+ parsed: ParsedFile,+ graph: Any,+ pagerank: dict[str, float],+ betweenness: dict[str, float],+ community: dict[str, int],+ source_bytes: bytes,+ ) -> GeneratedPage:+ ctx = self._assembler.assemble_file_page(+ parsed, graph, pagerank, betweenness, community, source_bytes+ )+ user_prompt = self._render("file_page.j2", ctx=ctx)+ response = await self._call_provider("file_page", user_prompt, str(uuid.uuid4()))+ return self._build_generated_page(+ "file_page",+ parsed.file_info.path,+ f"File: {parsed.file_info.path}",+ response,+ compute_source_hash(user_prompt),+ GENERATION_LEVELS["file_page"],+ )++ async def generate_symbol_spotlight(+ self,+ symbol: Any,+ parsed: ParsedFile,+ pagerank: dict[str, float],+ graph: Any,+ source_map: dict[str, bytes] | None = None,+ ) -> GeneratedPage:+ ctx = self._assembler.assemble_symbol_spotlight(+ symbol, parsed, pagerank, graph,+ source_bytes=(source_map or {}).get(parsed.file_info.path, b""),+ )+ user_prompt = self._render("symbol_spotlight.j2", ctx=ctx)+ response = await self._call_provider(+ "symbol_spotlight", user_prompt, str(uuid.uuid4())+ )+ return self._build_generated_page(+ "symbol_spotlight",+ f"{parsed.file_info.path}::{symbol.name}",+ f"Symbol: {symbol.qualified_name}",+ response,+ compute_source_hash(user_prompt),+ GENERATION_LEVELS["symbol_spotlight"],+ )++ async def generate_module_page(+ self,+ module_path: str,+ language: str,+ file_contexts: list[FilePageContext],+ graph: Any,+ git_meta_map: dict[str, dict] | None = None,+ ) -> GeneratedPage:+ ctx = self._assembler.assemble_module_page(+ module_path, language, file_contexts, graph+ )+ module_git_summary = None+ if git_meta_map:+ from collections import Counter+ file_paths = [fc.file_path for fc in file_contexts]+ metas = [git_meta_map[f] for f in file_paths if f in git_meta_map]+ if metas:+ owner_counts = Counter(+ m.get("primary_owner_name") for m in metas if m.get("primary_owner_name")+ )+ most_active = max(metas, key=lambda m: m.get("commit_count_90d", 0))+ module_git_summary = {+ "top_owners": [+ {"name": n, "file_count": c}+ for n, c in owner_counts.most_common(3)+ ],+ "most_active_file": most_active.get("file_path", ""),+ "most_active_commits_90d": most_active.get("commit_count_90d", 0),+ }+ user_prompt = self._render("module_page.j2", ctx=ctx, module_git_summary=module_git_summary)+ response = await self._call_provider("module_page", user_prompt, str(uuid.uuid4()))+ return self._build_generated_page(+ "module_page",+ module_path,+ f"Module: {module_path}",+ response,+ compute_source_hash(user_prompt),+ GENERATION_LEVELS["module_page"],+ )++ async def generate_scc_page(+ self,+ scc_id: str,+ scc_files: list[str],+ file_contexts: list[FilePageContext],+ ) -> GeneratedPage:+ ctx = self._assembler.assemble_scc_page(scc_id, scc_files, file_contexts)+ user_prompt = self._render("scc_page.j2", ctx=ctx)+ response = await self._call_provider("scc_page", user_prompt, str(uuid.uuid4()))+ return self._build_generated_page(+ "scc_page",+ scc_id,+ f"Circular Dependency: {scc_id}",+ response,+ compute_source_hash(user_prompt),+ GENERATION_LEVELS["scc_page"],+ )++ async def generate_repo_overview(+ self,+ repo_structure: RepoStructure,+ pagerank: dict[str, float],+ sccs: list[Any],+ community: dict[str, int],+ git_meta_map: dict[str, dict] | None = None,+ ) -> GeneratedPage:+ ctx = self._assembler.assemble_repo_overview(+ repo_structure, pagerank, sccs, community+ )+ repo_git_summary = None+ if git_meta_map:+ metas = list(git_meta_map.values())+ top_churn = sorted(metas, key=lambda m: m.get("commit_count_90d", 0), reverse=True)[:3]+ oldest = min(+ (m for m in metas if m.get("first_commit_at")),+ key=lambda m: m["first_commit_at"],+ default=None,+ )+ repo_git_summary = {+ "hotspot_count": sum(1 for m in metas if m.get("is_hotspot")),+ "stable_count": sum(1 for m in metas if m.get("is_stable")),+ "top_churn_files": [m.get("file_path", "") for m in top_churn],+ "oldest_file": oldest.get("file_path", "") if oldest else "",+ "oldest_file_age_days": oldest.get("age_days", 0) if oldest else 0,+ }+ user_prompt = self._render("repo_overview.j2", ctx=ctx, repo_git_summary=repo_git_summary)+ response = await self._call_provider(+ "repo_overview", user_prompt, str(uuid.uuid4())+ )+ repo_name = getattr(repo_structure, "name", "repo")+ return self._build_generated_page(+ "repo_overview",+ repo_name,+ f"Repository Overview: {repo_name}",+ response,+ compute_source_hash(user_prompt),+ GENERATION_LEVELS["repo_overview"],+ )++ async def generate_architecture_diagram(+ self,+ graph: Any,+ pagerank: dict[str, float],+ community: dict[str, int],+ sccs: list[Any],+ repo_name: str,+ ) -> GeneratedPage:+ ctx = self._assembler.assemble_architecture_diagram(+ graph, pagerank, community, sccs, repo_name+ )+ user_prompt = self._render("architecture_diagram.j2", ctx=ctx)+ response = await self._call_provider(+ "architecture_diagram", user_prompt, str(uuid.uuid4())+ )+ return self._build_generated_page(+ "architecture_diagram",+ repo_name,+ f"Architecture Diagram: {repo_name}",+ response,+ compute_source_hash(user_prompt),+ GENERATION_LEVELS["architecture_diagram"],+ )++ async def generate_api_contract(+ self,+ parsed: ParsedFile,+ source_bytes: bytes,+ ) -> GeneratedPage:+ ctx = self._assembler.assemble_api_contract(parsed, source_bytes)+ user_prompt = self._render("api_contract.j2", ctx=ctx)+ response = await self._call_provider(+ "api_contract", user_prompt, str(uuid.uuid4())+ )+ return self._build_generated_page(+ "api_contract",+ parsed.file_info.path,+ f"API Contract: {parsed.file_info.path}",+ response,+ compute_source_hash(user_prompt),+ GENERATION_LEVELS["api_contract"],+ )++ async def generate_infra_page(+ self,+ parsed: ParsedFile,+ source_bytes: bytes,+ ) -> GeneratedPage:+ ctx = self._assembler.assemble_infra_page(parsed, source_bytes)+ user_prompt = self._render("infra_page.j2", ctx=ctx)+ response = await self._call_provider(+ "infra_page", user_prompt, str(uuid.uuid4())+ )+ return self._build_generated_page(+ "infra_page",+ parsed.file_info.path,+ f"Infrastructure: {parsed.file_info.path}",+ response,+ compute_source_hash(user_prompt),+ GENERATION_LEVELS["infra_page"],+ )++ async def generate_cross_package(+ self,+ source_pkg: str,+ target_pkg: str,+ source_fcs: list[FilePageContext],+ target_fcs: list[FilePageContext],+ graph: Any,+ ) -> GeneratedPage:+ ctx = self._assembler.assemble_cross_package(+ source_pkg, target_pkg, source_fcs, target_fcs, graph+ )+ user_prompt = self._render("cross_package.j2", ctx=ctx)+ response = await self._call_provider("cross_package", user_prompt, str(uuid.uuid4()))+ return self._build_generated_page(+ "cross_package",+ f"{source_pkg}->{target_pkg}",+ f"Cross-Package: {source_pkg} → {target_pkg}",+ response,+ compute_source_hash(user_prompt),+ GENERATION_LEVELS["cross_package"],+ )++ # ------------------------------------------------------------------+ # generate_all — orchestration+ # ------------------------------------------------------------------++ async def generate_all(+ self,+ parsed_files: list[ParsedFile],+ source_map: dict[str, bytes],+ graph_builder: Any, # GraphBuilder+ repo_structure: RepoStructure,+ repo_name: str,+ job_system: Any | None = None, # JobSystem | None+ on_page_done: Callable[[str], None] | None = None,+ git_meta_map: dict[str, dict] | None = None,+ ) -> list[GeneratedPage]:+ """Generate all wiki pages for a repository.++ Runs generation in 8 ordered levels. Each level's pages are generated+ concurrently (up to config.max_concurrency). Failures within a level+ are logged but do not abort the remaining levels.++ Args:+ parsed_files: All ParsedFile objects from the ingestion pipeline.+ source_map: Raw file bytes keyed by relative path.+ graph_builder: Finalized GraphBuilder (build() already called).+ repo_structure: High-level repo metadata.+ repo_name: Human-readable repository name.+ job_system: Optional JobSystem for checkpoint persistence.+ on_page_done: Optional callback per completed page.+ git_meta_map: Optional dict of git metadata by file path.++ Returns:+ List of GeneratedPage objects in level order.+ """+ graph = graph_builder.graph()+ pagerank = graph_builder.pagerank()+ betweenness = graph_builder.betweenness_centrality()+ community = graph_builder.community_detection()+ sccs = graph_builder.strongly_connected_components()++ all_pages: list[GeneratedPage] = []+ semaphore = asyncio.Semaphore(self._config.max_concurrency)+ # Summaries of completed pages: target_path → brief summary text (for dep context)+ completed_page_summaries: dict[str, str] = {}++ def _extract_summary(content: str) -> str:+ if "## Overview" in content:+ start = content.index("## Overview") + len("## Overview")+ end = content.find("\n##", start)+ return content[start : end if end > 0 else start + 1600].strip()[:400]+ return content[:400]++ # Determine already-completed pages (for resume support)+ completed_ids: set[str] = set()+ job_id: str | None = None+ if job_system is not None:+ job_id = job_system.create_job(+ str(getattr(repo_structure, "root_path", ".")),+ self._config,+ self._provider.provider_name,+ self._provider.model_name,+ )++ async def run_level(+ named_coros: list[tuple[str, Any]], level: int+ ) -> list[GeneratedPage]:+ if job_system is not None and job_id is not None:+ job_system.update_level(job_id, level)++ async def guarded_named(page_id: str, coro: Any) -> Any:+ async with semaphore:+ try:+ result = await coro+ # Embed page for RAG (B1)+ if self._vector_store is not None and isinstance(result, GeneratedPage):+ try:+ await self._vector_store.embed_and_upsert(+ result.page_id,+ result.content,+ {+ "page_type": result.page_type,+ "target_path": result.target_path,+ "content": result.content[:600],+ },+ )+ except Exception as e:+ log.warning("rag.embed_failed", page_id=result.page_id, error=str(e))+ # Store summary for dependency context (B2)+ if isinstance(result, GeneratedPage):+ completed_page_summaries[result.target_path] = _extract_summary(result.content)+ return result+ except Exception as exc:+ if job_system is not None and job_id is not None:+ job_system.fail_page(job_id, page_id, str(exc))+ log.error(+ "page_generation_failed",+ page_id=page_id, level=level, error=str(exc),+ )+ return exc # return as value so gather works++ tasks = [guarded_named(pid, c) for pid, c in named_coros]+ results = await asyncio.gather(*tasks)+ pages = [r for r in results if isinstance(r, GeneratedPage)]+ if on_page_done is not None:+ for r in pages:+ on_page_done(r.page_type)+ if job_system is not None and job_id is not None:+ for r in pages:+ job_system.complete_page(job_id, r.page_id)+ return pages++ # ---- Budget pre-computation ----+ code_files = [+ p for p in parsed_files+ if not p.file_info.is_api_contract+ and not _is_infra_file(p)+ and p.file_info.language in _CODE_LANGUAGES+ ]++ # Sort: entry points first, then hotspots, then high PageRank (A1)+ if git_meta_map:+ code_files = sorted(+ code_files,+ key=lambda p: (+ not p.file_info.is_entry_point,+ not git_meta_map.get(p.file_info.path, {}).get("is_hotspot", False),+ -pagerank.get(p.file_info.path, 0.0),+ ),+ )+ else:+ code_files = sorted(+ code_files,+ key=lambda p: (+ not p.file_info.is_entry_point,+ -pagerank.get(p.file_info.path, 0.0),+ ),+ )++ code_pr_scores = sorted(+ [pagerank.get(p.file_info.path, 0.0) for p in code_files],+ reverse=True,+ )+ _all_public_symbols: list[tuple[Any, Any]] = [+ (sym, p)+ for p in parsed_files+ for sym in p.symbols+ if sym.visibility == "public"+ ]++ budget = max(50, int(len(parsed_files) * self._config.max_pages_pct))+ # Estimate fixed overhead (api, scc, module, repo_overview, arch_diagram)+ _fixed_overhead = (+ sum(1 for p in parsed_files if p.file_info.is_api_contract)+ + sum(1 for scc in sccs if len(scc) > 1)+ + len({+ (Path(p.file_info.path).parts[0] if len(Path(p.file_info.path).parts) > 1 else "root")+ for p in code_files+ })+ + 2 # repo_overview + architecture_diagram+ )+ _remaining = max(0, budget - _fixed_overhead)++ # File page gets priority over symbol_spotlight+ _n_file_uncapped = max(1, int(len(code_pr_scores) * self._config.file_page_top_percentile)) if code_pr_scores else 0+ _n_file_cap = min(_n_file_uncapped, _remaining)+ pr_threshold = code_pr_scores[_n_file_cap - 1] if code_pr_scores and _n_file_cap > 0 else 0.0++ _sym_budget = max(0, _remaining - _n_file_cap)+ _n_sym_uncapped = max(1, int(len(_all_public_symbols) * self._config.top_symbol_percentile)) if _all_public_symbols else 0+ _n_sym_cap = min(_n_sym_uncapped, _sym_budget)++ # Start job with estimated total (A7)+ if job_system is not None and job_id is not None:+ estimated_total = (+ sum(1 for p in parsed_files if p.file_info.is_api_contract)+ + _n_sym_cap+ + _n_file_cap+ + sum(1 for scc in sccs if len(scc) > 1)+ + len({+ (Path(p.file_info.path).parts[0] if len(Path(p.file_info.path).parts) > 1 else "root")+ for p in code_files+ })+ + 2 # repo_overview + arch_diagram+ + sum(1 for p in parsed_files if _is_infra_file(p))+ )+ job_system.start_job(job_id, estimated_total)++ # ---- Level 0: api_contract ----+ api_files = [p for p in parsed_files if p.file_info.is_api_contract]+ level0_coros = [+ (+ compute_page_id("api_contract", p.file_info.path),+ self.generate_api_contract(p, source_map.get(p.file_info.path, b"")),+ )+ for p in api_files+ if compute_page_id("api_contract", p.file_info.path) not in completed_ids+ ]+ level0_pages = await run_level(level0_coros, 0)+ all_pages.extend(level0_pages)++ # ---- Level 1: symbol_spotlight (top percentile by PageRank) ----+ all_symbols_with_file: list[tuple[Any, ParsedFile]] = _all_public_symbols++ if all_symbols_with_file and _n_sym_cap > 0:+ all_symbols_with_file.sort(+ key=lambda x: pagerank.get(x[1].file_info.path, 0.0), reverse=True+ )+ top_symbols = all_symbols_with_file[:_n_sym_cap]+ else:+ top_symbols = []++ level1_coros = [+ (+ compute_page_id("symbol_spotlight", f"{pf.file_info.path}::{sym.name}"),+ self.generate_symbol_spotlight(sym, pf, pagerank, graph, source_map=source_map),+ )+ for sym, pf in top_symbols+ if compute_page_id(+ "symbol_spotlight", f"{pf.file_info.path}::{sym.name}"+ ) not in completed_ids+ ]+ level1_pages = await run_level(level1_coros, 1)+ all_pages.extend(level1_pages)++ # ---- Level 2: file_page (significant code files only) ----+ # Context is assembled for ALL code files (module pages need it).+ # Pages are generated only for files that cross the significance bar.+ # page_summaries from level 0+1 are available here (B2).+ file_page_contexts: dict[str, FilePageContext] = {}++ level2_coros: list[tuple[str, Any]] = []+ for p in code_files:+ ctx = self._assembler.assemble_file_page(+ p,+ graph,+ pagerank,+ betweenness,+ community,+ source_map.get(p.file_info.path, b""),+ page_summaries=completed_page_summaries,+ )+ file_page_contexts[p.file_info.path] = ctx+ pid = compute_page_id("file_page", p.file_info.path)+ if (+ _is_significant_file(p, pagerank, betweenness, self._config, pr_threshold)+ and pid not in completed_ids+ ):+ level2_coros.append((pid, self._generate_file_page_from_ctx(p, ctx)))++ level2_pages = await run_level(level2_coros, 2)+ all_pages.extend(level2_pages)++ # ---- Level 3: scc_page (only true cycles: len > 1) ----+ scc_coros: list[tuple[str, Any]] = []+ for i, scc in enumerate(sccs):+ if len(scc) <= 1:+ continue+ scc_id = f"scc-{i}"+ scc_files = sorted(scc)+ fc_list = [file_page_contexts[f] for f in scc_files if f in file_page_contexts]+ pid = compute_page_id("scc_page", scc_id)+ if pid not in completed_ids:+ scc_coros.append((pid, self.generate_scc_page(scc_id, scc_files, fc_list)))+ level3_pages = await run_level(scc_coros, 3)+ all_pages.extend(level3_pages)++ # ---- Level 4: module_page (grouped by top-level directory) ----+ module_groups: dict[str, list[FilePageContext]] = {}+ module_languages: dict[str, str] = {}+ for p in code_files:+ parts = Path(p.file_info.path).parts+ module = parts[0] if len(parts) > 1 else "root"+ fc = file_page_contexts.get(p.file_info.path)+ if fc is not None:+ module_groups.setdefault(module, []).append(fc)+ module_languages[module] = p.file_info.language++ level4_coros: list[tuple[str, Any]] = [+ (+ compute_page_id("module_page", module),+ self.generate_module_page(+ module, module_languages.get(module, "unknown"), fcs, graph,+ git_meta_map=git_meta_map,+ ),+ )+ for module, fcs in module_groups.items()+ if compute_page_id("module_page", module) not in completed_ids+ ]+ level4_pages = await run_level(level4_coros, 4)+ all_pages.extend(level4_pages)++ # ---- Level 5: cross_package (only if monorepo) ----+ if repo_structure.is_monorepo:+ seen_pairs: set[tuple[str, str]] = set()+ cross_coros: list[tuple[str, Any]] = []+ for src_pkg, src_fcs in module_groups.items():+ for fc in src_fcs:+ for dep in fc.dependencies:+ dep_parts = Path(dep).parts+ dep_pkg = dep_parts[0] if len(dep_parts) > 1 else "root"+ pair = (src_pkg, dep_pkg)+ if dep_pkg != src_pkg and pair not in seen_pairs:+ seen_pairs.add(pair)+ dep_fcs = module_groups.get(dep_pkg, [])+ ctx_xpkg = self._assembler.assemble_cross_package(+ src_pkg, dep_pkg, src_fcs, dep_fcs, graph+ )+ if ctx_xpkg.coupling_strength >= 2:+ pid = compute_page_id("cross_package", f"{src_pkg}->{dep_pkg}")+ if pid not in completed_ids:+ cross_coros.append((+ pid,+ self.generate_cross_package(+ src_pkg, dep_pkg, src_fcs, dep_fcs, graph+ ),+ ))+ level5_pages = await run_level(cross_coros, 5)+ all_pages.extend(level5_pages)++ # ---- Level 6: repo_overview + architecture_diagram ----+ level6_coros: list[tuple[str, Any]] = []+ if compute_page_id("repo_overview", repo_name) not in completed_ids:+ level6_coros.append((+ compute_page_id("repo_overview", repo_name),+ self.generate_repo_overview(+ repo_structure, pagerank, sccs, community, git_meta_map=git_meta_map+ ),+ ))+ if compute_page_id("architecture_diagram", repo_name) not in completed_ids:+ level6_coros.append((+ compute_page_id("architecture_diagram", repo_name),+ self.generate_architecture_diagram(+ graph, pagerank, community, sccs, repo_name+ ),+ ))+ level6_pages = await run_level(level6_coros, 6)+ all_pages.extend(level6_pages)++ # ---- Level 7: infra_page ----+ infra_files = [p for p in parsed_files if _is_infra_file(p)]+ level7_coros: list[tuple[str, Any]] = [+ (+ compute_page_id("infra_page", p.file_info.path),+ self.generate_infra_page(p, source_map.get(p.file_info.path, b"")),+ )+ for p in infra_files+ if compute_page_id("infra_page", p.file_info.path) not in completed_ids+ ]+ level7_pages = await run_level(level7_coros, 7)+ all_pages.extend(level7_pages)++ # Finalize job+ if job_system is not None and job_id is not None:+ job_system.complete_job(job_id)++ log.info(+ "Generation complete",+ total_pages=len(all_pages),+ provider=self._provider.provider_name,+ model=self._provider.model_name,+ )+ return all_pages++ # ------------------------------------------------------------------+ # Internal helpers+ # ------------------------------------------------------------------++ async def _generate_file_page_from_ctx(+ self,+ parsed: ParsedFile,+ ctx: FilePageContext,+ ) -> GeneratedPage:+ """Generate a file_page from a pre-assembled context (avoids double-assembly)."""+ # RAG context: query vector store for related pages (B1)+ if self._vector_store is not None:+ query_terms = parsed.exports or [+ s["name"] for s in ctx.symbols[:3] if s.get("visibility") == "public"+ ]+ if query_terms:+ try:+ results = await self._vector_store.search(+ ", ".join(query_terms[:5]), limit=3+ )+ self_id = f"file_page:{parsed.file_info.path}"+ ctx.rag_context = [+ f"[{r.page_id}]\n{r.snippet}"+ for r in results+ if r.page_id != self_id+ ]+ except Exception as e:+ log.warning("rag.search_failed", path=parsed.file_info.path, error=str(e))+ user_prompt = self._render("file_page.j2", ctx=ctx)+ response = await self._call_provider("file_page", user_prompt, str(uuid.uuid4()))+ return self._build_generated_page(+ "file_page",+ parsed.file_info.path,+ f"File: {parsed.file_info.path}",+ response,+ compute_source_hash(user_prompt),+ GENERATION_LEVELS["file_page"],+ )++ async def _call_provider(+ self,+ page_type: str,+ user_prompt: str,+ request_id: str,+ ) -> GeneratedResponse:+ """Call the provider with caching."""+ key = self._compute_cache_key(page_type, user_prompt)+ if self._config.cache_enabled and key in self._cache:+ log.debug("Cache hit", page_type=page_type, key=key[:8])+ return self._cache[key]++ response = await self._provider.generate(+ SYSTEM_PROMPTS[page_type],+ user_prompt,+ max_tokens=self._config.max_tokens,+ temperature=self._config.temperature,+ request_id=request_id,+ )++ if self._config.cache_enabled:+ self._cache[key] = response++ return response++ def _compute_cache_key(self, page_type: str, user_prompt: str) -> str:+ """Return SHA256(model + page_type + user_prompt) as cache key."""+ raw = f"{self._provider.model_name}:{page_type}:{user_prompt}"+ return hashlib.sha256(raw.encode()).hexdigest()++ def _build_generated_page(+ self,+ page_type: str,+ target_path: str,+ title: str,+ response: GeneratedResponse,+ source_hash: str,+ level: int,+ ) -> GeneratedPage:+ """Wrap a GeneratedResponse in a GeneratedPage."""+ now = _now_iso()+ return GeneratedPage(+ page_id=compute_page_id(page_type, target_path),+ page_type=page_type,+ title=title,+ content=response.content,+ source_hash=source_hash,+ model_name=self._provider.model_name,+ provider_name=self._provider.provider_name,+ input_tokens=response.input_tokens,+ output_tokens=response.output_tokens,+ cached_tokens=response.cached_tokens,+ generation_level=level,+ target_path=target_path,+ created_at=now,+ updated_at=now,+ )++ def _render(self, template_name: str, **kwargs: Any) -> str:+ """Render a Jinja2 template with the given kwargs."""+ template = self._jinja_env.get_template(template_name)+ return template.render(**kwargs)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _is_infra_file(parsed: ParsedFile) -> bool:+ """Return True if the file is an infrastructure file."""+ lang = parsed.file_info.language+ if lang in _INFRA_LANGUAGES:+ return True+ name = Path(parsed.file_info.path).name+ return name in _INFRA_FILENAMES+++def _is_significant_file(+ parsed: ParsedFile,+ pagerank: dict[str, float],+ betweenness: dict[str, float],+ config: Any, # GenerationConfig+ pr_threshold: float,+) -> bool:+ """Return True if this code file deserves its own file_page.++ A file is significant if it:+ - Has at least config.file_page_min_symbols symbols, AND+ - Is an entry point, OR in the top PageRank percentile, OR is a bridge file+ (non-zero betweenness centrality).+ """+ if len(parsed.symbols) < config.file_page_min_symbols:+ return False+ path = parsed.file_info.path+ return (+ parsed.file_info.is_entry_point+ or pagerank.get(path, 0.0) >= pr_threshold+ or betweenness.get(path, 0.0) > 0.0+ )diff --git a/packages/core/src/wikicode/core/generation/templates/api_contract.j2 b/packages/core/src/wikicode/core/generation/templates/api_contract.j2new file mode 100644index 000000000..35053d40e--- /dev/null+++ b/packages/core/src/wikicode/core/generation/templates/api_contract.j2@@ -0,0 +1,30 @@+You are documenting the API contract defined in `{{ ctx.file_path }}`.++## API Contract+- **File**: `{{ ctx.file_path }}`+- **Language**: {{ ctx.language }}++## Endpoints+{% if ctx.endpoints %}+{% for ep in ctx.endpoints %}+- {{ ep }}+{% endfor %}+{% else %}+No endpoints explicitly extracted. See raw content below.+{% endif %}++## Schemas / Models+{% if ctx.schemas %}+{% for schema in ctx.schemas %}+- {{ schema }}+{% endfor %}+{% else %}+No schemas explicitly extracted.+{% endif %}++## Raw Content+```{{ ctx.language }}+{{ ctx.raw_content }}+```++Generate a complete wiki page following the sections above.diff --git a/packages/core/src/wikicode/core/generation/templates/architecture_diagram.j2 b/packages/core/src/wikicode/core/generation/templates/architecture_diagram.j2new file mode 100644index 000000000..b98d4b048--- /dev/null+++ b/packages/core/src/wikicode/core/generation/templates/architecture_diagram.j2@@ -0,0 +1,31 @@+You are generating an architecture diagram for the repository `{{ ctx.repo_name }}`.++## Repository Architecture++**Nodes** ({{ ctx.nodes | length }} files):+{% for node in ctx.nodes %}+- `{{ node }}`+{% endfor %}++**Edges** ({{ ctx.edges | length }} dependencies):+{% for src, dst in ctx.edges %}+- `{{ src }}` → `{{ dst }}`+{% endfor %}++**Communities** ({{ ctx.communities | length }} detected):+{% for community_id, members in ctx.communities.items() %}+- Community {{ community_id }}: {{ members | join(", ") }}+{% endfor %}++**Strongly Connected Components** (cycles):+{% for scc in ctx.scc_groups %}+- {{ scc | join(", ") }}+{% endfor %}++Note: Showing top {{ ctx.nodes | length }} files by PageRank.+Use module pages for full per-file coverage.++You MUST include a fenced mermaid block with graph TD showing the key dependencies.+The mermaid diagram should use short node labels for readability.++Generate a complete wiki page following the sections above.diff --git a/packages/core/src/wikicode/core/generation/templates/cross_package.j2 b/packages/core/src/wikicode/core/generation/templates/cross_package.j2new file mode 100644index 000000000..6fe6d4ab0--- /dev/null+++ b/packages/core/src/wikicode/core/generation/templates/cross_package.j2@@ -0,0 +1,18 @@+You are documenting the inter-package dependency: `{{ ctx.source_package }}` → `{{ ctx.target_package }}`.++- **Source**: `{{ ctx.source_package }}` (mean PageRank: {{ "%.4f"|format(ctx.source_pagerank_mean) }})+- **Target**: `{{ ctx.target_package }}` (mean PageRank: {{ "%.4f"|format(ctx.target_pagerank_mean) }})+- **Coupling**: {{ ctx.coupling_strength }} files in source depend on target++## Files Crossing the Boundary+{% for f in ctx.boundary_files %}+- `{{ f }}`+{% endfor %}++## Public API Used from `{{ ctx.target_package }}`+{% for sym in ctx.used_symbols %}+- `{{ sym }}`+{% endfor %}++Generate a complete wiki page with sections:+## Overview, ## Integration Points, ## API Dependency Summary, ## Coupling Risk.diff --git a/packages/core/src/wikicode/core/generation/templates/diff_summary.j2 b/packages/core/src/wikicode/core/generation/templates/diff_summary.j2new file mode 100644index 000000000..0b4079723--- /dev/null+++ b/packages/core/src/wikicode/core/generation/templates/diff_summary.j2@@ -0,0 +1,46 @@+You are summarizing changes between `{{ ctx.from_ref }}` and `{{ ctx.to_ref }}`.++## Change Summary+- **From**: `{{ ctx.from_ref }}`+- **To**: `{{ ctx.to_ref }}`++## Added Files ({{ ctx.added_files | length }})+{% for f in ctx.added_files %}+- `{{ f }}`+{% endfor %}++## Deleted Files ({{ ctx.deleted_files | length }})+{% for f in ctx.deleted_files %}+- `{{ f }}`+{% endfor %}++## Modified Files ({{ ctx.modified_files | length }})+{% for f in ctx.modified_files %}+- `{{ f }}`+{% endfor %}++## Symbol Changes+{% for diff in ctx.symbol_diffs %}+- **{{ diff.path }}**: +{{ diff.added | length }} added, -{{ diff.removed | length }} removed, {{ diff.renamed | length }} renamed+{% endfor %}++## Affected Documentation Pages+{% for page_id in ctx.affected_page_ids %}+- `{{ page_id }}`+{% endfor %}++{% if ctx.trigger_commit_sha is defined and ctx.trigger_commit_sha %}+## Trigger Commit+- **SHA**: `{{ ctx.trigger_commit_sha }}`+{% if ctx.trigger_commit_message %}- **Message**: {{ ctx.trigger_commit_message }}{% endif %}+{% if ctx.trigger_commit_author %}- **Author**: {{ ctx.trigger_commit_author }}{% endif %}+{% endif %}++{% if ctx.diff_text is defined and ctx.diff_text %}+## Diff Context+```+{{ ctx.diff_text }}+```+{% endif %}++Generate a complete wiki page following the sections above.diff --git a/packages/core/src/wikicode/core/generation/templates/file_page.j2 b/packages/core/src/wikicode/core/generation/templates/file_page.j2new file mode 100644index 000000000..2a90e43bc--- /dev/null+++ b/packages/core/src/wikicode/core/generation/templates/file_page.j2@@ -0,0 +1,129 @@+You are documenting the file `{{ ctx.file_path }}` (language: {{ ctx.language }}).++## File Overview+{% if ctx.docstring %}+Module docstring: {{ ctx.docstring }}+{% endif %}+- **Path**: `{{ ctx.file_path }}`+- **Language**: {{ ctx.language }}+- **PageRank score**: {{ "%.4f"|format(ctx.pagerank_score) }}+- **Betweenness centrality**: {{ "%.4f"|format(ctx.betweenness_score) }}+- **Community**: {{ ctx.community_id }}+- **Is API contract**: {{ ctx.is_api_contract }}+- **Is entry point**: {{ ctx.is_entry_point }}+- **Is test file**: {{ ctx.is_test }}++## Symbols ({{ ctx.symbols | length }})+{% for sym in ctx.symbols %}+- **{{ sym.name }}** ({{ sym.kind }}): `{{ sym.signature }}`{% if sym.docstring %} — {{ sym.docstring }}{% endif %}++{% endfor %}++## Imports ({{ ctx.imports | length }})+{% for imp in ctx.imports %}+- `{{ imp }}`+{% endfor %}++## Exports+{% for exp in ctx.exports %}+- `{{ exp }}`+{% endfor %}++## Dependencies (files this imports)+{% for dep in ctx.dependencies %}+{% set summary = ctx.dependency_summaries.get(dep, '') %}+{% if summary %}+- `{{ dep }}` — {{ summary }}+{% else %}+- `{{ dep }}`+{% endif %}+{% endfor %}++## Dependents (files that import this)+{% for dep in ctx.dependents %}+- `{{ dep }}`+{% endfor %}++{% if ctx.parse_errors %}+## Parse Errors+{% for err in ctx.parse_errors %}+- {{ err }}+{% endfor %}+{% endif %}++{% if ctx.file_source_snippet %}+## Source Snippet+```{{ ctx.language }}+{{ ctx.file_source_snippet }}+```+{% endif %}++{% if ctx.rag_context %}+## Related Context+{% for rag in ctx.rag_context %}+{{ rag }}+{% endfor %}+{% endif %}++{# ── Git context block ────────────────────────────────────────── #}+{% if ctx.git_metadata %}++{% if ctx.git_metadata.primary_owner_name is defined and ctx.git_metadata.primary_owner_name %}+## Ownership+Primary maintainer: **{{ ctx.git_metadata.primary_owner_name }}**+({{ (ctx.git_metadata.primary_owner_commit_pct * 100) | round | int }}% of lines)+{% if ctx.git_metadata.top_authors is defined and ctx.git_metadata.top_authors | length > 1 %}+Also contributed by: {% for a in ctx.git_metadata.top_authors[1:3] %}{{ a.name }}{% if not loop.last %}, {% endif %}{% endfor %}+{% endif %}+{% endif %}++{% if ctx.git_metadata.significant_commit_messages is defined and ctx.git_metadata.significant_commit_messages %}+## Evolution context+This file has been shaped by {{ ctx.git_metadata.commit_count_total }} commits+over {{ ctx.git_metadata.age_days }} days. Key changes:+{% for commit in ctx.git_metadata.significant_commit_messages %}+- **{{ commit.date[:10] }}** — {{ commit.message }} *({{ commit.author }})*+{% endfor %}++Use this history to explain *why* the code is structured as it is.+{% endif %}++{% if ctx.git_metadata.is_hotspot is defined and ctx.git_metadata.is_hotspot %}+IMPORTANT: This file is a HOTSPOT — top 25% for both change frequency and+complexity. Note this prominently. High-risk area for bugs.+{% endif %}++{% if ctx.git_metadata.is_stable is defined and ctx.git_metadata.is_stable %}+NOTE: This file is STABLE — {{ ctx.git_metadata.commit_count_total }} commits+but unchanged in 90+ days. Emphasize stability and reliability.+{% endif %}++{% if ctx.git_metadata.co_change_partners is defined and ctx.git_metadata.co_change_partners %}+## Hidden coupling (co-change analysis)+These files have no import relationship but frequently change together:+{% for partner in ctx.git_metadata.co_change_partners[:3] %}+- `{{ partner.file_path }}` (co-changed {{ partner.co_change_count }} times)+{% endfor %}+Mention this relationship explicitly.+{% endif %}++{% endif %}+{# ── End git context block ────────────────────────────────────── #}++{% if ctx.dead_code_findings %}+## Potentially unused code+{% for finding in ctx.dead_code_findings %}+- `{{ finding.symbol_name }}` — {{ finding.reason }}+ (confidence: {{ (finding.confidence * 100) | int }}%{% if finding.safe_to_delete %}, safe to remove{% endif %})+{% endfor %}+{% endif %}++{% if ctx.depth == "thorough" %}+IMPORTANT: This is a high-activity or hotspot file. Be extremely detailed. Explain+implementation rationale, edge cases, potential pitfalls, and provide multi-step usage+examples where helpful.+{% elif ctx.depth == "minimal" %}+This file is stable and low-centrality. Provide a concise overview focused on the+public API only. Skip implementation details.+{% endif %}+Generate a complete wiki page following the sections above.diff --git a/packages/core/src/wikicode/core/generation/templates/infra_page.j2 b/packages/core/src/wikicode/core/generation/templates/infra_page.j2new file mode 100644index 000000000..83a36cf46--- /dev/null+++ b/packages/core/src/wikicode/core/generation/templates/infra_page.j2@@ -0,0 +1,21 @@+You are documenting the infrastructure file `{{ ctx.file_path }}`.++## Infrastructure File+- **File**: `{{ ctx.file_path }}`+- **Language**: {{ ctx.language }}++## Key Targets / Stages+{% if ctx.targets %}+{% for target in ctx.targets %}+- {{ target }}+{% endfor %}+{% else %}+No targets explicitly extracted. See raw content below.+{% endif %}++## Raw Content+```{{ ctx.language }}+{{ ctx.raw_content }}+```++Generate a complete wiki page following the sections above.diff --git a/packages/core/src/wikicode/core/generation/templates/module_page.j2 b/packages/core/src/wikicode/core/generation/templates/module_page.j2new file mode 100644index 000000000..583a7a6d9--- /dev/null+++ b/packages/core/src/wikicode/core/generation/templates/module_page.j2@@ -0,0 +1,39 @@+You are documenting the module at `{{ ctx.module_path }}` (language: {{ ctx.language }}).++## Module Overview+- **Path**: `{{ ctx.module_path }}`+- **Language**: {{ ctx.language }}+- **Total symbols**: {{ ctx.total_symbols }}+- **Public symbols**: {{ ctx.public_symbols }}+- **Mean PageRank**: {{ "%.4f"|format(ctx.pagerank_mean) }}++## Entry Points+{% for ep in ctx.entry_points %}+- `{{ ep }}`+{% endfor %}++## Dependencies (modules this imports)+{% for dep in ctx.dependencies %}+- `{{ dep }}`+{% endfor %}++## Dependents (modules that import this)+{% for dep in ctx.dependents %}+- `{{ dep }}`+{% endfor %}++## Files in Module+{% for f in ctx.files %}+- `{{ f }}`+{% endfor %}++{% if module_git_summary is defined and module_git_summary %}+## Team ownership+{% for pkg_owner in module_git_summary.top_owners %}+- **{{ pkg_owner.file_count }} files** primarily maintained by {{ pkg_owner.name }}+{% endfor %}+Most active recently: `{{ module_git_summary.most_active_file }}`+({{ module_git_summary.most_active_commits_90d }} commits in 90 days)+{% endif %}++Generate a complete wiki page following the sections above.diff --git a/packages/core/src/wikicode/core/generation/templates/repo_overview.j2 b/packages/core/src/wikicode/core/generation/templates/repo_overview.j2new file mode 100644index 000000000..cfde9358d--- /dev/null+++ b/packages/core/src/wikicode/core/generation/templates/repo_overview.j2@@ -0,0 +1,38 @@+You are generating a high-level overview for the repository `{{ ctx.repo_name }}`.++## Repository Summary+- **Name**: {{ ctx.repo_name }}+- **Is monorepo**: {{ ctx.is_monorepo }}+- **Total files**: {{ ctx.total_files }}+- **Total lines of code**: {{ ctx.total_loc }}+- **Circular dependency count**: {{ ctx.circular_dependency_count }}++## Packages+{% for pkg in ctx.packages %}+- **{{ pkg.name }}** (`{{ pkg.path }}`, {{ pkg.language }})+{% endfor %}++## Language Distribution+{% for lang, pct in ctx.language_distribution.items() %}+- {{ lang }}: {{ "%.1f"|format(pct * 100) }}%+{% endfor %}++## Entry Points+{% for ep in ctx.entry_points %}+- `{{ ep }}`+{% endfor %}++## Top Files by PageRank+{% for item in ctx.top_files_by_pagerank %}+- `{{ item.path }}` (score: {{ "%.4f"|format(item.score) }})+{% endfor %}++{% if repo_git_summary is defined and repo_git_summary %}+## Codebase health signals+- **Hotspots:** {{ repo_git_summary.hotspot_count }} files are high-churn AND high-complexity+- **Stable core:** {{ repo_git_summary.stable_count }} files unchanged in 90+ days+- **Most changed (90d):** {{ repo_git_summary.top_churn_files[:3] | join(', ') }}+- **Oldest file:** `{{ repo_git_summary.oldest_file }}` ({{ repo_git_summary.oldest_file_age_days }} days)+{% endif %}++Generate a complete wiki page following the sections above.diff --git a/packages/core/src/wikicode/core/generation/templates/scc_page.j2 b/packages/core/src/wikicode/core/generation/templates/scc_page.j2new file mode 100644index 000000000..6503145b3--- /dev/null+++ b/packages/core/src/wikicode/core/generation/templates/scc_page.j2@@ -0,0 +1,30 @@+You are documenting the circular dependency cycle identified as SCC `{{ ctx.scc_id }}`.++## Cycle Description+{{ ctx.cycle_description }}++## Files Involved ({{ ctx.files | length }})+{% for f in ctx.files %}+- `{{ f }}`+{% endfor %}++## Import Dependencies Creating the Cycle+{% for ci in ctx.cross_imports %}+- `{{ ci.from }}` imports from `{{ ci.to }}`+{% endfor %}++## Key Symbols in Cycle+{% for member in ctx.member_symbols %}+{% if member.symbols %}+**`{{ member.file_path }}`**+{% for sym in member.symbols %}+- `{{ sym.signature }}`{% if sym.docstring %} — {{ sym.docstring }}{% endif %}++{% endfor %}+{% endif %}+{% endfor %}++## Total Symbols in Cycle+{{ ctx.total_symbols }}++Generate a complete wiki page following the sections above.diff --git a/packages/core/src/wikicode/core/generation/templates/symbol_spotlight.j2 b/packages/core/src/wikicode/core/generation/templates/symbol_spotlight.j2new file mode 100644index 000000000..589858cc0--- /dev/null+++ b/packages/core/src/wikicode/core/generation/templates/symbol_spotlight.j2@@ -0,0 +1,41 @@+You are writing a detailed spotlight page for the symbol `{{ ctx.symbol_name }}`.++## Symbol Details+- **Name**: `{{ ctx.symbol_name }}`+- **Qualified name**: `{{ ctx.qualified_name }}`+- **Kind**: {{ ctx.kind }}+- **File**: `{{ ctx.file_path }}`+- **Is async**: {{ ctx.is_async }}+- **Complexity estimate**: {{ ctx.complexity_estimate }}++## Signature+```+{{ ctx.signature }}+```++{% if ctx.docstring %}+## Docstring+{{ ctx.docstring }}+{% endif %}++{% if ctx.decorators %}+## Decorators+{% for dec in ctx.decorators %}+- `{{ dec }}`+{% endfor %}+{% endif %}++{% if ctx.source_body %}+## Implementation+```+{{ ctx.source_body }}+```+{% endif %}++## Callers+Files that import the containing module:+{% for caller in ctx.callers %}+- `{{ caller }}`+{% endfor %}++Generate a complete wiki page following the sections above.diff --git a/packages/core/src/wikicode/core/ingestion/__init__.py b/packages/core/src/wikicode/core/ingestion/__init__.pynew file mode 100644index 000000000..0afdbc9f9--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/__init__.py@@ -0,0 +1,55 @@+"""WikiCode ingestion pipeline.++Public surface+--------------+FileTraverser — traverse a repo, respecting gitignore + blocklist+ASTParser — unified parser (one class for all languages via .scm files)+parse_file — module-level convenience wrapper around ASTParser+GraphBuilder — build a NetworkX dependency graph from ParsedFile objects+ChangeDetector — git-based change detection + symbol rename detection+LANGUAGE_CONFIGS — dict of per-language configuration+"""++from .change_detector import AffectedPages, ChangeDetector, FileDiff, SymbolDiff, SymbolRename+from .graph import GraphBuilder+from .models import (+ EXTENSION_TO_LANGUAGE,+ FileInfo,+ Import,+ PackageInfo,+ ParsedFile,+ RepoStructure,+ Symbol,+ SymbolKind,+ compute_content_hash,+)+from .parser import LANGUAGE_CONFIGS, ASTParser, LanguageConfig, parse_file+from .traverser import FileTraverser++__all__ = [+ # Traversal+ "FileTraverser",+ # Parsing+ "ASTParser",+ "parse_file",+ "LANGUAGE_CONFIGS",+ "LanguageConfig",+ # Graph+ "GraphBuilder",+ # Change detection+ "ChangeDetector",+ "FileDiff",+ "SymbolDiff",+ "SymbolRename",+ "AffectedPages",+ # Models+ "FileInfo",+ "Import",+ "PackageInfo",+ "ParsedFile",+ "RepoStructure",+ "Symbol",+ "SymbolKind",+ "EXTENSION_TO_LANGUAGE",+ "compute_content_hash",+]diff --git a/packages/core/src/wikicode/core/ingestion/change_detector.py b/packages/core/src/wikicode/core/ingestion/change_detector.pynew file mode 100644index 000000000..1313e2266--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/change_detector.py@@ -0,0 +1,418 @@+"""Change detector for the WikiCode maintenance pipeline.++ChangeDetector uses GitPython to identify changed files between commits, then+re-parses changed files to produce symbol-level diffs and determine which wiki+pages need to be regenerated.++Key design decisions:+ - Graceful fallback: works on non-git directories (returns empty diffs).+ - Symbol rename detection uses a heuristic (same kind + similar line position+ or similar name) — no LLM involved.+ - Cascade budget: limits how many pages are fully regenerated per maintenance+ run (expensive pages beyond the budget get confidence decay only).+"""++from __future__ import annotations++import difflib+from dataclasses import dataclass, field+from pathlib import Path+from typing import Literal++import structlog++from .models import FileInfo, ParsedFile, Symbol++log = structlog.get_logger(__name__)+++# ---------------------------------------------------------------------------+# Data models+# ---------------------------------------------------------------------------+++@dataclass+class SymbolRename:+ """A detected symbol rename: old_name → new_name."""++ old_name: str+ new_name: str+ kind: str+ confidence: float # 0.0–1.0; 1.0 = certain rename+++@dataclass+class SymbolDiff:+ """Symbol-level diff between two versions of the same file."""++ added: list[Symbol] = field(default_factory=list)+ removed: list[Symbol] = field(default_factory=list)+ renamed: list[SymbolRename] = field(default_factory=list)+ modified: list[Symbol] = field(default_factory=list) # same name, different body+++@dataclass+class FileDiff:+ """Diff information for a single changed file."""++ path: str+ status: Literal["added", "deleted", "modified", "renamed"]+ old_path: str | None # only set when status == "renamed"+ old_parsed: ParsedFile | None # None for new files+ new_parsed: ParsedFile | None # None for deleted files+ symbol_diff: SymbolDiff | None # None if parsing failed+ trigger_commit_sha: str | None = None+ trigger_commit_message: str | None = None+ trigger_commit_author: str | None = None+ diff_text: str | None = None # unified diff, capped at 4K chars+++@dataclass+class AffectedPages:+ """Output of get_affected_pages — pages that need attention."""++ regenerate: list[str] # page IDs to fully regenerate+ rename_patch: list[str] # pages that only need a symbol rename text patch+ decay_only: list[str] # pages to mark stale without immediate regeneration+++# ---------------------------------------------------------------------------+# ChangeDetector+# ---------------------------------------------------------------------------+++class ChangeDetector:+ """Detect changed files and symbol renames between git commits.++ Args:+ repo_path: Path to the git repository root.+ """++ def __init__(self, repo_path: Path) -> None:+ self.repo_path = repo_path+ self._repo: object = None # lazy git.Repo++ # ------------------------------------------------------------------+ # Public API+ # ------------------------------------------------------------------++ def get_changed_files(+ self,+ base_ref: str = "HEAD~1",+ until_ref: str = "HEAD",+ ) -> list[FileDiff]:+ """Return a list of FileDiff objects for files changed between *base_ref* and *until_ref*.++ Falls back to an empty list if the directory is not a git repo or the+ refs don't exist.+ """+ repo = self._get_repo()+ if repo is None:+ return []++ try:+ import git as gitpython+ base_commit = repo.commit(base_ref)+ until_commit = repo.commit(until_ref)+ diff_items = base_commit.diff(until_commit)+ except Exception as exc:+ log.warning("git diff failed", base=base_ref, until=until_ref, error=str(exc))+ return []++ results: list[FileDiff] = []+ from .parser import parse_file # avoid circular at module level++ for item in diff_items:+ status: Literal["added", "deleted", "modified", "renamed"]+ old_path: str | None = None+ new_path: str | None = None++ change_type = item.change_type+ if change_type == "A":+ status = "added"+ new_path = item.b_path+ elif change_type == "D":+ status = "deleted"+ old_path = item.a_path+ elif change_type == "R":+ status = "renamed"+ old_path = item.a_path+ new_path = item.b_path+ else:+ status = "modified"+ old_path = item.a_path+ new_path = item.b_path++ path = new_path or old_path or ""++ # Parse old version (from git blob)+ old_parsed = None+ if old_path and item.a_blob:+ old_parsed = self._parse_blob(item.a_blob, old_path)++ # Parse new version (from working tree)+ new_parsed = None+ if new_path:+ abs_path = self.repo_path / new_path+ if abs_path.exists():+ new_parsed = self._parse_path(abs_path, new_path)+ elif item.b_blob:+ new_parsed = self._parse_blob(item.b_blob, new_path)++ sym_diff = None+ if old_parsed and new_parsed:+ sym_diff = self._compute_symbol_diff(old_parsed, new_parsed)+ elif old_parsed:+ sym_diff = SymbolDiff(removed=list(old_parsed.symbols))+ elif new_parsed:+ sym_diff = SymbolDiff(added=list(new_parsed.symbols))++ results.append(+ FileDiff(+ path=path,+ status=status,+ old_path=old_path,+ old_parsed=old_parsed,+ new_parsed=new_parsed,+ symbol_diff=sym_diff,+ )+ )++ return results++ def detect_symbol_renames(+ self,+ old_file: ParsedFile,+ new_file: ParsedFile,+ ) -> list[SymbolRename]:+ """Detect renamed symbols between two versions of the same file.++ Heuristic: a symbol is considered renamed if:+ - It has the same kind as a removed symbol+ - AND its name is similar (Levenshtein/SequenceMatcher ratio > 0.7)+ OR it occupies the same line range (same start_line ± 2)+ """+ old_syms = {s.name: s for s in old_file.symbols}+ new_syms = {s.name: s for s in new_file.symbols}++ removed_names = set(old_syms) - set(new_syms)+ added_names = set(new_syms) - set(old_syms)++ renames: list[SymbolRename] = []+ used_added: set[str] = set()++ for old_name in removed_names:+ old_sym = old_syms[old_name]+ best_match: tuple[float, str] | None = None++ for new_name in added_names:+ if new_name in used_added:+ continue+ new_sym = new_syms[new_name]+ if new_sym.kind != old_sym.kind:+ continue++ # Name similarity+ name_ratio = difflib.SequenceMatcher(+ None, old_name.lower(), new_name.lower()+ ).ratio()++ # Line proximity (same-ish position in file)+ line_close = abs(new_sym.start_line - old_sym.start_line) <= 5+ line_bonus = 0.2 if line_close else 0.0++ confidence = min(name_ratio + line_bonus, 1.0)+ if confidence >= 0.65:+ if best_match is None or confidence > best_match[0]:+ best_match = (confidence, new_name)++ if best_match:+ conf, new_name = best_match+ renames.append(+ SymbolRename(+ old_name=old_name,+ new_name=new_name,+ kind=old_sym.kind,+ confidence=conf,+ )+ )+ used_added.add(new_name)++ return renames++ def get_affected_pages(+ self,+ file_diffs: list[FileDiff],+ graph: object, # nx.DiGraph+ cascade_budget: int = 30,+ ) -> AffectedPages:+ """Compute which wiki pages need action after a set of file changes.++ Args:+ file_diffs: Output of get_changed_files().+ graph: The dependency graph (networkx DiGraph, nodes are file paths).+ cascade_budget: Max number of pages to fully regenerate per run.+ """+ import networkx as nx++ directly_changed: set[str] = set()+ rename_candidates: set[str] = set()++ for diff in file_diffs:+ path = diff.new_parsed.file_info.path if diff.new_parsed else diff.path+ directly_changed.add(path)++ # Collect files referenced by symbol renames+ if diff.symbol_diff and diff.symbol_diff.renamed:+ for rename in diff.symbol_diff.renamed:+ rename_candidates.add(path)++ if not isinstance(graph, nx.DiGraph):+ # Graph not available — only regenerate directly changed files+ return AffectedPages(+ regenerate=list(directly_changed),+ rename_patch=[],+ decay_only=[],+ )++ # 1-hop cascade: files that import changed files+ one_hop: set[str] = set()+ for changed in directly_changed:+ if changed in graph:+ one_hop.update(graph.predecessors(changed)) # files that import this+ one_hop -= directly_changed++ # Co-change partner staleness: include co-change partners in decay+ co_change_decay: set[str] = set()+ for changed in directly_changed:+ if changed in graph:+ for neighbor in graph.neighbors(changed):+ edge_data = graph[changed][neighbor]+ if edge_data.get("edge_type") == "co_changes":+ co_change_decay.add(neighbor)+ for pred in graph.predecessors(changed):+ edge_data = graph[pred][changed]+ if edge_data.get("edge_type") == "co_changes":+ co_change_decay.add(pred)+ co_change_decay -= directly_changed | one_hop++ # 2-hop (weak) cascade for rename candidates+ two_hop: set[str] = set()+ for changed in rename_candidates:+ if changed in graph:+ for pred in graph.predecessors(changed):+ two_hop.update(graph.predecessors(pred))+ two_hop -= directly_changed | one_hop | co_change_decay++ # Apply cascade budget sorted by PageRank (highest priority first)+ try:+ pr = nx.pagerank(graph)+ except Exception:+ pr = {}++ all_pages_needing_regen = sorted(+ directly_changed | one_hop,+ key=lambda p: pr.get(p, 0.0),+ reverse=True,+ )++ regenerate = all_pages_needing_regen[:cascade_budget]+ decay_only = (+ all_pages_needing_regen[cascade_budget:]+ + sorted(two_hop)+ + sorted(co_change_decay)+ )+ rename_patch = [p for p in rename_candidates if p in regenerate]++ return AffectedPages(+ regenerate=regenerate,+ rename_patch=rename_patch,+ decay_only=decay_only,+ )++ # ------------------------------------------------------------------+ # Internal helpers+ # ------------------------------------------------------------------++ def _get_repo(self) -> object | None:+ if self._repo is not None:+ return self._repo+ try:+ import git as gitpython+ self._repo = gitpython.Repo(self.repo_path, search_parent_directories=True)+ return self._repo+ except Exception as exc:+ log.info(+ "Not a git repository or GitPython unavailable",+ path=str(self.repo_path),+ reason=str(exc),+ )+ return None++ def _parse_blob(self, blob: object, path: str) -> ParsedFile | None:+ """Parse a git blob (old file version from git history)."""+ try:+ source = blob.data_stream.read()+ return self._parse_bytes(source, path)+ except Exception as exc:+ log.warning("Failed to parse blob", path=path, error=str(exc))+ return None++ def _parse_path(self, abs_path: Path, rel_path: str) -> ParsedFile | None:+ """Parse a file from the working tree."""+ try:+ return self._parse_bytes(abs_path.read_bytes(), rel_path)+ except Exception as exc:+ log.warning("Failed to parse file", path=rel_path, error=str(exc))+ return None++ def _parse_bytes(self, source: bytes, path: str) -> ParsedFile | None:+ from datetime import datetime++ from .models import FileInfo+ from .parser import parse_file+ from .traverser import _detect_language++ lang = _detect_language(Path(path))+ file_info = FileInfo(+ path=path,+ abs_path=str(self.repo_path / path),+ language=lang,+ size_bytes=len(source),+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ try:+ return parse_file(file_info, source)+ except Exception as exc:+ log.warning("parse_file failed in ChangeDetector", path=path, error=str(exc))+ return None++ def _compute_symbol_diff(+ self,+ old_file: ParsedFile,+ new_file: ParsedFile,+ ) -> SymbolDiff:+ old_syms = {s.name: s for s in old_file.symbols}+ new_syms = {s.name: s for s in new_file.symbols}++ added = [new_syms[n] for n in set(new_syms) - set(old_syms)]+ removed = [old_syms[n] for n in set(old_syms) - set(new_syms)]+ modified = [+ new_syms[n]+ for n in set(old_syms) & set(new_syms)+ if old_syms[n].signature != new_syms[n].signature+ or old_syms[n].start_line != new_syms[n].start_line+ ]+ renames = self.detect_symbol_renames(old_file, new_file)++ return SymbolDiff(+ added=added,+ removed=removed,+ renamed=renames,+ modified=modified,+ )diff --git a/packages/core/src/wikicode/core/ingestion/git_indexer.py b/packages/core/src/wikicode/core/ingestion/git_indexer.pynew file mode 100644index 000000000..eed378a1d--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/git_indexer.py@@ -0,0 +1,588 @@+"""Git history indexer for the WikiCode ingestion pipeline.++Mines git history into the git_metadata table. Uses gitpython for git+operations. Parallelizes per-file git log calls with asyncio.Semaphore(20).++Non-blocking: if git is unavailable or repo has no history, log a warning+and return an empty summary. All downstream features degrade gracefully.+"""++from __future__ import annotations++import asyncio+import json+import time+from collections import Counter, defaultdict+from dataclasses import dataclass, field+from datetime import datetime, timedelta, timezone+from pathlib import Path+from typing import Any, Callable++import structlog++logger = structlog.get_logger(__name__)++# Silence GitPython's _CatFileContentStream.__del__ ValueError spam.+# When git cat-file streams are GC'd after the subprocess pipe is closed,+# their __del__ tries to drain remaining bytes and hits a closed file.+# This is harmless but floods stderr with tracebacks.+try:+ from git.cmd import _CatFileContentStream++ _orig_del = _CatFileContentStream.__del__++ def _quiet_del(self: Any) -> None:+ try:+ _orig_del(self)+ except (ValueError, OSError):+ pass++ _CatFileContentStream.__del__ = _quiet_del # type: ignore[assignment]+except Exception:+ pass # git not installed — nothing to patch++# Commit message prefixes/keywords to skip as insignificant+_SKIP_PREFIXES = ("Merge ", "Bump ", "chore:", "ci:", "style:", "build:", "release:", "revert:")+_SKIP_AUTHORS = ("dependabot", "renovate", "github-actions")+_MIN_MESSAGE_LEN = 20++# Allowlist of extensions for which per-file git indexing (blame, commit+# history, hotspot/stable classification) is worth running. Anything NOT in+# this set is skipped — data, config, markup, dotfiles, and binaries add no+# documentation value, and git blame on large JSON/YAML files is very slow.+# Co-change detection still runs across ALL tracked files regardless.+_CODE_EXTENSIONS: frozenset[str] = frozenset(+ {+ # Python+ ".py", ".pyi",+ # JavaScript / TypeScript+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",+ # Go+ ".go",+ # Rust+ ".rs",+ # JVM+ ".java", ".kt", ".kts", ".scala",+ # C / C+++ ".c", ".h", ".cpp", ".cc", ".cxx", ".hpp", ".hxx",+ # C#+ ".cs",+ # Ruby+ ".rb",+ # PHP+ ".php",+ # Swift+ ".swift",+ # Objective-C+ ".m", ".mm",+ # Elixir / Erlang+ ".ex", ".exs", ".erl", ".hrl",+ # Lua+ ".lua",+ # R+ ".r",+ # Dart+ ".dart",+ # Zig+ ".zig",+ # Julia+ ".jl",+ # Clojure+ ".clj", ".cljs", ".cljc",+ # Elm+ ".elm",+ # Haskell+ ".hs", ".lhs",+ # OCaml+ ".ml", ".mli",+ # F#+ ".fs", ".fsi", ".fsx",+ # Crystal+ ".cr",+ # Nim+ ".nim",+ # D+ ".d",+ }+)++# Files larger than this skip git blame. blame is O(lines) and blocks the+# executor thread — for large files the commit-based ownership estimate is+# used as a fallback instead.+_MAX_BLAME_SIZE_BYTES: int = 100 * 1024 # 100 KB++# Maximum seconds to wait for a single file's git indexing. If exceeded the+# file is recorded with whatever data was collected before the timeout and the+# semaphore slot is released so other files can proceed.+_FILE_INDEX_TIMEOUT_SECS: float = 30.0+++def _should_skip_index(file_path: str) -> bool:+ """Return True for files where per-file git indexing should be skipped.++ Uses an allowlist: only files with known source-code extensions are indexed.+ Everything else (data, config, markup, dotfiles, binaries) is skipped.+ """+ return Path(file_path).suffix.lower() not in _CODE_EXTENSIONS+++@dataclass+class GitIndexSummary:+ files_indexed: int+ hotspots: int+ stable_files: int+ duration_seconds: float = 0.0+++class GitIndexer:+ """Mines git history into the git_metadata table.++ Uses gitpython (already a dependency) for git operations.+ Parallelizes per-file git log calls with asyncio.Semaphore(20).++ Non-blocking: if git is unavailable or repo has no history, log a warning+ and return an empty summary. All downstream features degrade gracefully.+ """++ def __init__(self, repo_path: str | Path) -> None:+ self.repo_path = Path(repo_path)++ async def index_repo(+ self,+ repo_id: str,+ on_start: Callable[[int], None] | None = None,+ on_file_done: Callable[[], None] | None = None,+ on_commit_done: Callable[[], None] | None = None,+ on_co_change_start: Callable[[int], None] | None = None,+ ) -> tuple[GitIndexSummary, list[dict]]:+ """Full index of all tracked files. Returns summary + list of metadata dicts+ ready for bulk upsert.++ Optional progress callbacks (all thread-safe, called from the event loop+ or executor threads):+ on_start(total) — fired once with the total number of tracked files+ on_file_done() — fired after each file is indexed+ on_co_change_start(total) — fired once with actual commit count for+ co-change analysis+ on_commit_done() — fired after each commit is processed during+ co-change analysis+ """+ start = time.monotonic()+ repo = self._get_repo()+ if repo is None:+ return GitIndexSummary(0, 0, 0, 0.0), []++ tracked_files = self._get_tracked_files(repo)+ if not tracked_files:+ return GitIndexSummary(0, 0, 0, 0.0), []++ # Only run expensive per-file indexing (git log + blame) on code files.+ # Data/config/markup files are skipped here but still passed to+ # _compute_co_changes so co-change relationships remain complete.+ indexable_files = [fp for fp in tracked_files if not _should_skip_index(fp)]++ if on_start is not None:+ on_start(len(indexable_files))++ # Parallelized per-file indexing+ semaphore = asyncio.Semaphore(20)+ loop = asyncio.get_event_loop()++ async def index_one(file_path: str) -> dict:+ async with semaphore:+ try:+ result = await asyncio.wait_for(+ loop.run_in_executor(+ None, self._index_file, file_path, repo+ ),+ timeout=_FILE_INDEX_TIMEOUT_SECS,+ )+ except asyncio.TimeoutError:+ logger.warning(+ "Git indexing timed out for file — using partial data",+ path=file_path,+ timeout=_FILE_INDEX_TIMEOUT_SECS,+ )+ result = {"file_path": file_path}+ except Exception as exc:+ logger.debug(+ "Git indexing failed for file",+ path=file_path,+ error=str(exc),+ )+ result = {"file_path": file_path}+ if on_file_done is not None:+ on_file_done()+ return result++ tasks = [index_one(fp) for fp in indexable_files]+ metadata_list = await asyncio.gather(*tasks, return_exceptions=True)++ # Filter out failures+ results: list[dict] = []+ for r in metadata_list:+ if isinstance(r, Exception):+ logger.warning("Failed to index file", error=str(r))+ else:+ results.append(r)++ # Co-change analysis uses ALL tracked files (not just indexable ones) so+ # that relationships like "whenever auth.py changes, config.yaml changes too"+ # are captured even for files we didn't run full git log/blame on.+ co_changes = await loop.run_in_executor(+ None, self._compute_co_changes, repo, set(tracked_files), 500, 3, on_commit_done, on_co_change_start+ )+ for meta in results:+ fp = meta["file_path"]+ if fp in co_changes:+ meta["co_change_partners_json"] = json.dumps(co_changes[fp])++ # Compute percentiles+ self._compute_percentiles(results)++ duration = time.monotonic() - start+ hotspots = sum(1 for m in results if m.get("is_hotspot", False))+ stable = sum(1 for m in results if m.get("is_stable", False))++ summary = GitIndexSummary(+ files_indexed=len(results),+ hotspots=hotspots,+ stable_files=stable,+ duration_seconds=duration,+ )+ # Explicitly close the Repo to shut down the persistent git cat-file+ # process. Without this, garbage-collected _CatFileContentStream objects+ # try to read from an already-closed pipe and spam ValueError tracebacks.+ repo.close()++ logger.info(+ "Git indexing complete",+ files=summary.files_indexed,+ hotspots=summary.hotspots,+ stable=summary.stable_files,+ duration=f"{summary.duration_seconds:.1f}s",+ )+ return summary, results++ async def index_changed_files(self, changed_file_paths: list[str]) -> list[dict]:+ """Incremental update: re-index only changed files.+ Also re-index any file whose co_change_partners include a changed file.+ """+ repo = self._get_repo()+ if repo is None:+ return []++ loop = asyncio.get_event_loop()+ semaphore = asyncio.Semaphore(20)++ async def index_one(file_path: str) -> dict:+ async with semaphore:+ try:+ return await asyncio.wait_for(+ loop.run_in_executor(None, self._index_file, file_path, repo),+ timeout=_FILE_INDEX_TIMEOUT_SECS,+ )+ except (asyncio.TimeoutError, Exception) as exc:+ logger.debug(+ "Git indexing failed for changed file",+ path=file_path,+ error=str(exc),+ )+ return {"file_path": file_path}++ tasks = [index_one(fp) for fp in changed_file_paths]+ results_raw = await asyncio.gather(*tasks, return_exceptions=True)++ results: list[dict] = []+ for r in results_raw:+ if isinstance(r, Exception):+ logger.warning("Failed to index changed file", error=str(r))+ else:+ results.append(r)++ repo.close()+ return results++ # ------------------------------------------------------------------+ # Internal methods+ # ------------------------------------------------------------------++ def _get_repo(self) -> Any | None:+ try:+ import git as gitpython+ return gitpython.Repo(self.repo_path, search_parent_directories=True)+ except Exception as exc:+ logger.warning(+ "Git unavailable or not a repository",+ path=str(self.repo_path),+ error=str(exc),+ )+ return None++ def _get_tracked_files(self, repo: Any) -> list[str]:+ try:+ output = repo.git.ls_files()+ return [f for f in output.splitlines() if f.strip()]+ except Exception as exc:+ logger.warning("Failed to list tracked files", error=str(exc))+ return []++ def _index_file(self, file_path: str, repo: Any) -> dict:+ """Index a single file's git history. Runs in executor."""+ now = datetime.now(timezone.utc)+ ninety_days_ago = now - timedelta(days=90)+ thirty_days_ago = now - timedelta(days=30)+ six_months_ago = now - timedelta(days=180)++ meta: dict[str, Any] = {+ "file_path": file_path,+ "commit_count_total": 0,+ "commit_count_90d": 0,+ "commit_count_30d": 0,+ "first_commit_at": None,+ "last_commit_at": None,+ "primary_owner_name": None,+ "primary_owner_email": None,+ "primary_owner_commit_pct": None,+ "top_authors_json": "[]",+ "significant_commits_json": "[]",+ "co_change_partners_json": "[]",+ "is_hotspot": False,+ "is_stable": False,+ "churn_percentile": 0.0,+ "age_days": 0,+ }++ try:+ commits = list(repo.iter_commits(paths=file_path, max_count=500))+ except Exception:+ return meta++ if not commits:+ return meta++ meta["commit_count_total"] = len(commits)++ try:+ # Timeline+ dates = [c.committed_datetime for c in commits]+ meta["first_commit_at"] = min(dates)+ meta["last_commit_at"] = max(dates)+ meta["age_days"] = (now - min(dates)).days++ # Commit counts by time window+ for c in commits:+ cd = c.committed_datetime+ if cd.tzinfo is None:+ cd = cd.replace(tzinfo=timezone.utc)+ if cd >= ninety_days_ago:+ meta["commit_count_90d"] += 1+ if cd >= thirty_days_ago:+ meta["commit_count_30d"] += 1++ # Author analysis+ author_counts: Counter[str] = Counter()+ author_emails: dict[str, str] = {}+ for c in commits:+ name = c.author.name or "unknown"+ author_counts[name] += 1+ if name not in author_emails and c.author.email:+ author_emails[name] = c.author.email++ top_authors = []+ for name, count in author_counts.most_common(5):+ top_authors.append({+ "name": name,+ "email": author_emails.get(name, ""),+ "commit_count": count,+ })+ meta["top_authors_json"] = json.dumps(top_authors)++ if top_authors:+ primary = top_authors[0]+ meta["primary_owner_name"] = primary["name"]+ meta["primary_owner_email"] = primary["email"]+ total = sum(a["commit_count"] for a in top_authors)+ meta["primary_owner_commit_pct"] = (+ primary["commit_count"] / total if total > 0 else 0.0+ )++ # Blame ownership (overrides author-based if available).+ # Skipped for large files — git blame is O(lines) and can block the+ # executor thread for many seconds on files > 100 KB. The commit-based+ # ownership computed above is used as a fallback.+ try:+ file_size = (self.repo_path / file_path).stat().st_size+ if file_size <= _MAX_BLAME_SIZE_BYTES:+ blame_name, blame_email, blame_pct = self._get_blame_ownership(+ file_path, repo+ )+ if blame_name:+ meta["primary_owner_name"] = blame_name+ meta["primary_owner_email"] = blame_email+ meta["primary_owner_commit_pct"] = blame_pct+ except Exception:+ pass # blame is best-effort++ # Significant commits+ sig_commits = []+ for c in commits:+ if self._is_significant_commit(c.message, c.author.name or ""):+ sig_commits.append({+ "sha": c.hexsha[:8],+ "date": c.committed_datetime.isoformat(),+ "message": c.message.strip().split("\n")[0][:200],+ "author": c.author.name or "unknown",+ })+ if len(sig_commits) >= 10:+ break+ meta["significant_commits_json"] = json.dumps(sig_commits)++ # Stable classification+ if meta["commit_count_total"] > 10 and meta["commit_count_90d"] == 0:+ meta["is_stable"] = True++ except Exception:+ pass # return whatever partial data we have++ return meta++ def _get_blame_ownership(+ self, file_path: str, repo: Any+ ) -> tuple[str | None, str | None, float | None]:+ """Compute primary owner from git blame (who wrote the most lines)."""+ try:+ blame = repo.blame("HEAD", file_path)+ except Exception:+ return None, None, None++ line_counts: Counter[str] = Counter()+ emails: dict[str, str] = {}+ total_lines = 0++ for commit, lines in blame:+ name = commit.author.name or "unknown"+ count = len(lines)+ line_counts[name] += count+ total_lines += count+ if name not in emails and commit.author.email:+ emails[name] = commit.author.email++ if not line_counts or total_lines == 0:+ return None, None, None++ top_name = line_counts.most_common(1)[0][0]+ pct = line_counts[top_name] / total_lines+ return top_name, emails.get(top_name), pct++ def _is_significant_commit(self, message: str, author: str) -> bool:+ """Return True if the commit is considered significant."""+ msg = message.strip()+ if len(msg) < _MIN_MESSAGE_LEN:+ return False+ for prefix in _SKIP_PREFIXES:+ if msg.startswith(prefix):+ return False+ author_lower = author.lower()+ for skip in _SKIP_AUTHORS:+ if skip in author_lower:+ return False+ return True++ def _compute_co_changes(+ self,+ repo: Any,+ all_files: set[str],+ commit_limit: int = 500,+ min_count: int = 3,+ on_commit_done: Callable[[], None] | None = None,+ on_co_change_start: Callable[[int], None] | None = None,+ ) -> dict[str, list[dict]]:+ """Walk recent commits and record co-occurrence pairs for tracked files.++ Uses a single ``git log --name-only`` call instead of spawning one+ ``git diff`` subprocess per commit — O(1) processes vs O(commit_limit).++ on_co_change_start(total) is called once with the actual number of+ commits found. on_commit_done() is called after each commit block is+ processed. Both are invoked from a thread-pool thread; callers must+ ensure thread safety (Rich Progress is thread-safe).+ """+ pair_counts: Counter[tuple[str, str]] = Counter()++ try:+ # One git command returns all changed-file lists. %x00 (null byte)+ # is used as a commit separator — it cannot appear in file paths.+ raw = repo.git.log(+ f"-{commit_limit}",+ "--name-only",+ "--no-merges",+ "--format=%x00",+ )+ except Exception:+ return {}++ # Count actual commits so the caller can set an accurate progress total.+ actual_commits = raw.count("\x00")+ if on_co_change_start is not None:+ on_co_change_start(actual_commits)++ current: set[str] = set()+ for line in raw.splitlines():+ if line == "\x00" or line.startswith("\x00"):+ # Commit boundary — process the files accumulated for the+ # previous commit, then start a fresh set.+ if len(current) >= 2:+ sorted_files = sorted(current)+ for i in range(len(sorted_files)):+ for j in range(i + 1, len(sorted_files)):+ pair_counts[(sorted_files[i], sorted_files[j])] += 1+ current = set()+ if on_commit_done is not None:+ on_commit_done()+ else:+ path = line.strip()+ if path and path in all_files:+ current.add(path)++ # Flush the final commit's files+ if len(current) >= 2:+ sorted_files = sorted(current)+ for i in range(len(sorted_files)):+ for j in range(i + 1, len(sorted_files)):+ pair_counts[(sorted_files[i], sorted_files[j])] += 1++ # Build result: for each file, list partners above threshold+ result: dict[str, list[dict]] = defaultdict(list)+ for (a, b), count in pair_counts.items():+ if count >= min_count:+ result[a].append({"file_path": b, "co_change_count": count})+ result[b].append({"file_path": a, "co_change_count": count})++ # Sort partners by count descending+ for fp in result:+ result[fp].sort(key=lambda x: x["co_change_count"], reverse=True)++ return dict(result)++ def _compute_percentiles(self, metadata_list: list[dict]) -> None:+ """Compute churn_percentile and is_hotspot. Mutates in place."""+ if not metadata_list:+ return++ # Sort by commit_count_90d for percentile ranking+ sorted_by_churn = sorted(+ range(len(metadata_list)),+ key=lambda i: metadata_list[i].get("commit_count_90d", 0),+ )++ total = len(metadata_list)+ for rank, idx in enumerate(sorted_by_churn):+ metadata_list[idx]["churn_percentile"] = rank / total if total > 0 else 0.0++ # Hotspot: top 25% churn (i.e., churn_percentile >= 0.75)+ for meta in metadata_list:+ commit_90d = meta.get("commit_count_90d", 0)+ churn_pct = meta.get("churn_percentile", 0.0)+ if churn_pct >= 0.75 and commit_90d > 0:+ meta["is_hotspot"] = Truediff --git a/packages/core/src/wikicode/core/ingestion/graph.py b/packages/core/src/wikicode/core/ingestion/graph.pynew file mode 100644index 000000000..6f4f6e2df--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/graph.py@@ -0,0 +1,420 @@+"""Dependency graph builder for the WikiCode ingestion pipeline.++GraphBuilder constructs a directed multigraph from ParsedFile objects.++Node types:+ "file" — every source file+ "external" — third-party / unresolvable imports (prefix "external:")++Edge attributes:+ imported_names: list[str] — specific names imported across this edge++After calling build(), graph metrics are available:+ pagerank() — dict[path, float]+ strongly_connected_components() — list[frozenset[str]]+ betweenness_centrality() — dict[path, float]++Graph persistence uses a lightweight SQLite schema (two tables: graph_nodes,+graph_edges). Phase 4 will replace this with the full SQLAlchemy schema.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import networkx as nx+import structlog++from .models import ParsedFile++log = structlog.get_logger(__name__)++_LARGE_REPO_THRESHOLD = 30_000 # nodes — above this, algorithms are expensive+++class GraphBuilder:+ """Build a dependency graph from a collection of ParsedFile objects.++ Usage::++ builder = GraphBuilder()+ for parsed in parsed_files:+ builder.add_file(parsed)+ graph = builder.build()+ pr = builder.pagerank()+ """++ def __init__(self) -> None:+ self._graph: nx.DiGraph = nx.DiGraph()+ self._parsed_files: dict[str, ParsedFile] = {} # path → ParsedFile+ self._built = False++ # ------------------------------------------------------------------+ # Building+ # ------------------------------------------------------------------++ def add_file(self, parsed: ParsedFile) -> None:+ """Register one parsed file in the graph."""+ path = parsed.file_info.path+ self._parsed_files[path] = parsed+ self._built = False # invalidate cached metrics+ self._graph.add_node(+ path,+ language=parsed.file_info.language,+ symbol_count=len(parsed.symbols),+ has_error=bool(parsed.parse_errors),+ is_test=parsed.file_info.is_test,+ is_entry_point=parsed.file_info.is_entry_point,+ )++ def build(self) -> nx.DiGraph:+ """Resolve imports and add edges. Returns the finalized graph.++ Idempotent: can be called multiple times; re-resolves edges each time.+ """+ # Clear old edges, keep nodes+ self._graph.remove_edges_from(list(self._graph.edges()))++ # Build lookup tables for import resolution+ path_set = set(self._parsed_files.keys())+ # stem_map: "calculator" → "python_pkg/calculator.py"+ stem_map: dict[str, str] = {}+ for p in path_set:+ stem = Path(p).stem.lower()+ stem_map[stem] = p++ for path, parsed in self._parsed_files.items():+ for imp in parsed.imports:+ target = self._resolve_import(+ imp.module_path, path, path_set, stem_map, parsed.file_info.language+ )+ if target:+ # Aggregate imported_names on parallel edges+ if self._graph.has_edge(path, target):+ existing = self._graph[path][target].get("imported_names", [])+ merged = list(set(existing + imp.imported_names))+ self._graph[path][target]["imported_names"] = merged+ else:+ self._graph.add_edge(+ path,+ target,+ imported_names=list(imp.imported_names),+ )++ self._built = True+ log.info(+ "Graph built",+ nodes=self._graph.number_of_nodes(),+ edges=self._graph.number_of_edges(),+ )+ return self._graph++ def graph(self) -> nx.DiGraph:+ """Return the graph (building it first if necessary)."""+ if not self._built:+ self.build()+ return self._graph++ # ------------------------------------------------------------------+ # Graph metrics+ # ------------------------------------------------------------------++ def strongly_connected_components(self) -> list[frozenset[str]]:+ """Return SCCs as a list of frozensets. SCCs of size > 1 are circular deps."""+ return [+ frozenset(scc)+ for scc in nx.strongly_connected_components(self.graph())+ ]++ def betweenness_centrality(self) -> dict[str, float]:+ """Return betweenness centrality. High value → bridge file.++ Approximated with k=min(500, n) samples for large graphs.+ """+ g = self.graph()+ n = g.number_of_nodes()+ if n == 0:+ return {}+ if n > _LARGE_REPO_THRESHOLD:+ k = min(500, n)+ return nx.betweenness_centrality(g, k=k, normalized=True)+ return nx.betweenness_centrality(g, normalized=True)++ def community_detection(self) -> dict[str, int]:+ """Assign a community ID to each node using the Louvain algorithm.++ Returns dict[path, community_id].+ """+ g = self.graph()+ if g.number_of_nodes() == 0:+ return {}+ try:+ communities = nx.community.louvain_communities(g.to_undirected(), seed=42)+ result: dict[str, int] = {}+ for community_id, members in enumerate(communities):+ for node in members:+ result[node] = community_id+ return result+ except Exception as exc:+ log.warning("Community detection failed", error=str(exc))+ return {node: 0 for node in g.nodes()}++ # ------------------------------------------------------------------+ # Serialisation+ # ------------------------------------------------------------------++ def to_json(self) -> dict[str, Any]:+ """Serialize the graph to a JSON-compatible dict (node-link format)."""+ return nx.node_link_data(self.graph())++ async def persist(self, db_path: Path, repo_id: str) -> None:+ """Persist the graph to an SQLite database (lightweight Phase-2 schema).++ Phase 4 will replace this with the full SQLAlchemy/Alembic schema.+ """+ import aiosqlite++ pr = self.pagerank()+ bc = self.betweenness_centrality()+ scc_map = self._build_scc_map()+ g = self.graph()++ async with aiosqlite.connect(db_path) as db:+ await db.executescript("""+ CREATE TABLE IF NOT EXISTS graph_nodes (+ repo_id TEXT NOT NULL,+ path TEXT NOT NULL,+ language TEXT,+ symbol_count INTEGER,+ has_error INTEGER,+ pagerank REAL,+ betweenness REAL,+ scc_id INTEGER,+ PRIMARY KEY (repo_id, path)+ );+ CREATE TABLE IF NOT EXISTS graph_edges (+ repo_id TEXT NOT NULL,+ source_path TEXT NOT NULL,+ target_path TEXT NOT NULL,+ imported_names TEXT,+ PRIMARY KEY (repo_id, source_path, target_path)+ );+ """)++ # Nodes+ node_rows = [+ (+ repo_id,+ path,+ data.get("language", ""),+ data.get("symbol_count", 0),+ int(data.get("has_error", False)),+ pr.get(path, 0.0),+ bc.get(path, 0.0),+ scc_map.get(path, 0),+ )+ for path, data in g.nodes(data=True)+ ]+ await db.executemany(+ "INSERT OR REPLACE INTO graph_nodes VALUES (?,?,?,?,?,?,?,?)",+ node_rows,+ )++ # Edges+ edge_rows = [+ (+ repo_id,+ src,+ dst,+ json.dumps(data.get("imported_names", [])),+ )+ for src, dst, data in g.edges(data=True)+ ]+ await db.executemany(+ "INSERT OR REPLACE INTO graph_edges VALUES (?,?,?,?)",+ edge_rows,+ )++ await db.commit()++ log.info(+ "Graph persisted",+ db_path=str(db_path),+ nodes=len(node_rows),+ edges=len(edge_rows),+ )++ # ------------------------------------------------------------------+ # Internal helpers+ # ------------------------------------------------------------------++ def _resolve_import(+ self,+ module_path: str,+ importer_path: str,+ path_set: set[str],+ stem_map: dict[str, str],+ language: str,+ ) -> str | None:+ """Best-effort resolve of an import to a known file path."""+ if not module_path:+ return None++ importer_dir = Path(importer_path).parent++ # --- Python ---+ if language == "python":+ # Relative import: ".sibling" or "..parent.module"+ if module_path.startswith("."):+ dots = len(module_path) - len(module_path.lstrip("."))+ rest = module_path[dots:].replace(".", "/")+ base = importer_dir+ for _ in range(dots - 1):+ base = base.parent+ candidates = [+ (base / rest).with_suffix(".py").as_posix() if rest else None,+ (base / rest / "__init__.py").as_posix() if rest else None,+ ]+ for c in candidates:+ if c and c in path_set:+ return c+ return None+ # Absolute import: "python_pkg.calculator" → "python_pkg/calculator.py"+ dotted = module_path.replace(".", "/")+ candidates = [+ f"{dotted}.py",+ f"{dotted}/__init__.py",+ ]+ for c in candidates:+ if c in path_set:+ return c+ # Stem-only fallback+ stem = module_path.split(".")[-1].lower()+ return stem_map.get(stem)++ # --- TypeScript / JavaScript ---+ if language in ("typescript", "javascript"):+ if module_path.startswith("."):+ base = importer_dir / module_path+ for ext in (".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js"):+ candidate = Path(str(base) + ext).as_posix()+ if candidate in path_set:+ return candidate+ candidate = base.with_suffix(ext).as_posix() if not ext.startswith("/") else (base / "index.ts").as_posix()+ if candidate in path_set:+ return candidate+ # External npm 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++ # --- Go ---+ if language == "go":+ # Last segment of the import path is the package name+ stem = module_path.rsplit("/", 1)[-1].lower()+ return stem_map.get(stem)++ # --- Generic fallback: stem matching ---+ stem = Path(module_path).stem.lower()+ return stem_map.get(stem)++ # ------------------------------------------------------------------+ # Co-change edges (Phase 5.5)+ # ------------------------------------------------------------------++ def add_co_change_edges(+ self, git_meta_map: dict, min_count: int = 3+ ) -> int:+ """Add co_changes edges from git metadata. Returns count of edges added.++ These DO NOT affect PageRank — filter them out before computing.+ """+ count = 0+ seen: set[tuple[str, str]] = set()++ for file_path, meta in git_meta_map.items():+ co_json = meta.get("co_change_partners_json", "[]")+ if isinstance(co_json, str):+ try:+ partners = json.loads(co_json)+ except Exception:+ partners = []+ else:+ partners = co_json++ for partner in partners:+ partner_path = partner.get("file_path", "")+ co_count = partner.get("co_change_count", 0)+ if co_count < min_count:+ continue+ if partner_path not in self._graph:+ continue++ pair = tuple(sorted([file_path, partner_path]))+ if pair in seen:+ continue+ seen.add(pair)++ # Don't add if an import edge already exists+ if not self._graph.has_edge(file_path, partner_path) and not self._graph.has_edge(partner_path, file_path):+ self._graph.add_edge(+ file_path,+ partner_path,+ edge_type="co_changes",+ weight=co_count,+ imported_names=[],+ )+ count += 1++ log.info("Co-change edges added", count=count)+ return count++ def update_co_change_edges(+ self, updated_meta: dict, min_count: int = 3+ ) -> None:+ """Remove old co_changes edges for updated files, add new ones."""+ # Remove existing co_changes edges involving updated files+ edges_to_remove = []+ for u, v, data in self._graph.edges(data=True):+ if data.get("edge_type") == "co_changes":+ if u in updated_meta or v in updated_meta:+ edges_to_remove.append((u, v))+ self._graph.remove_edges_from(edges_to_remove)++ # Re-add co_changes edges+ self.add_co_change_edges(updated_meta, min_count)++ def pagerank(self, alpha: float = 0.85) -> dict[str, float]:+ """Return PageRank scores for each node.++ High PageRank → file is imported by many others → high documentation priority.+ Co-change edges are filtered out before computing PageRank.+ """+ g = self.graph()+ if g.number_of_nodes() == 0:+ return {}++ # Create a filtered view excluding co_changes edges+ filtered = nx.DiGraph()+ filtered.add_nodes_from(g.nodes(data=True))+ for u, v, data in g.edges(data=True):+ if data.get("edge_type") != "co_changes":+ filtered.add_edge(u, v, **data)++ try:+ return nx.pagerank(filtered, alpha=alpha)+ except nx.PowerIterationFailedConvergence:+ log.warning("PageRank did not converge, using uniform scores")+ n = filtered.number_of_nodes()+ return {node: 1.0 / n for node in filtered.nodes()}++ def _build_scc_map(self) -> dict[str, int]:+ """Assign a numeric SCC ID to each node."""+ result: dict[str, int] = {}+ for scc_id, scc in enumerate(nx.strongly_connected_components(self.graph())):+ for node in scc:+ result[node] = scc_id+ return resultdiff --git a/packages/core/src/wikicode/core/ingestion/models.py b/packages/core/src/wikicode/core/ingestion/models.pynew file mode 100644index 000000000..a91c72210--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/models.py@@ -0,0 +1,214 @@+"""Shared data models for the ingestion pipeline.++These are plain dataclasses (not Pydantic) for speed — the pipeline may process+tens of thousands of files and the overhead of Pydantic validation would add up.+All types are immutable where possible.+"""++from __future__ import annotations++import hashlib+from dataclasses import dataclass, field+from datetime import datetime+from pathlib import Path+from typing import Literal++# ---------------------------------------------------------------------------+# Language tags+# ---------------------------------------------------------------------------++LanguageTag = Literal[+ "python",+ "typescript",+ "javascript",+ "go",+ "rust",+ "java",+ "cpp",+ "c",+ "csharp",+ "ruby",+ "php",+ "swift",+ "kotlin",+ "scala",+ "shell",+ "yaml",+ "json",+ "toml",+ "proto",+ "graphql",+ "terraform",+ "dockerfile",+ "makefile",+ "markdown",+ "sql",+ "openapi",+ "unknown",+]++# ---------------------------------------------------------------------------+# Extension → language map (used by FileTraverser and ASTParser)+# ---------------------------------------------------------------------------++EXTENSION_TO_LANGUAGE: dict[str, LanguageTag] = {+ ".py": "python",+ ".pyi": "python",+ ".ts": "typescript",+ ".tsx": "typescript",+ ".js": "javascript",+ ".jsx": "javascript",+ ".mjs": "javascript",+ ".cjs": "javascript",+ ".go": "go",+ ".rs": "rust",+ ".java": "java",+ ".cpp": "cpp",+ ".cc": "cpp",+ ".cxx": "cpp",+ ".c": "c",+ ".h": "cpp",+ ".hpp": "cpp",+ ".cs": "csharp",+ ".rb": "ruby",+ ".php": "php",+ ".swift": "swift",+ ".kt": "kotlin",+ ".scala": "scala",+ ".sh": "shell",+ ".bash": "shell",+ ".zsh": "shell",+ ".yaml": "yaml",+ ".yml": "yaml",+ ".json": "json",+ ".toml": "toml",+ ".proto": "proto",+ ".graphql": "graphql",+ ".gql": "graphql",+ ".tf": "terraform",+ ".hcl": "terraform",+ ".md": "markdown",+ ".mdx": "markdown",+ ".sql": "sql",+}++SPECIAL_FILENAMES: dict[str, LanguageTag] = {+ "Dockerfile": "dockerfile",+ "dockerfile": "dockerfile",+ "Makefile": "makefile",+ "makefile": "makefile",+ "GNUmakefile": "makefile",+}++# ---------------------------------------------------------------------------+# Symbol kinds+# ---------------------------------------------------------------------------++SymbolKind = Literal[+ "function",+ "class",+ "method",+ "interface",+ "enum",+ "constant",+ "type_alias",+ "decorator",+ "trait",+ "impl",+ "struct",+ "module",+ "macro",+ "variable",+]++# ---------------------------------------------------------------------------+# Core models+# ---------------------------------------------------------------------------+++@dataclass+class FileInfo:+ """Metadata about a single source file discovered during traversal."""++ path: str # POSIX path relative to repo root+ abs_path: str # absolute filesystem path+ language: LanguageTag+ size_bytes: int+ git_hash: str # SHA of last commit touching this file (empty if unavailable)+ last_modified: datetime+ is_test: bool+ is_config: bool+ is_api_contract: bool+ is_entry_point: bool+++@dataclass+class PackageInfo:+ """A sub-package/workspace within a monorepo."""++ name: str+ path: str # POSIX path relative to repo root+ language: LanguageTag+ entry_points: list[str]+ manifest_file: str # pyproject.toml | package.json | Cargo.toml | go.mod+++@dataclass+class RepoStructure:+ """High-level structure of a repository."""++ is_monorepo: bool+ packages: list[PackageInfo]+ root_language_distribution: dict[str, float] # {"python": 0.45, ...}+ total_files: int+ total_loc: int+ entry_points: list[str]+++@dataclass+class Symbol:+ """A code symbol (function, class, method, …) extracted from a file."""++ id: str # "<rel_path>::<name>" or "<rel_path>::<class>::<method>"+ name: str+ qualified_name: str # dotted full name, e.g. "myapp.calc.Calculator.add"+ kind: SymbolKind+ signature: str # full signature string+ start_line: int # 1-indexed+ end_line: int # 1-indexed+ docstring: str | None+ decorators: list[str] = field(default_factory=list)+ visibility: Literal["public", "private", "protected", "internal"] = "public"+ is_async: bool = False+ complexity_estimate: int = 1 # cyclomatic complexity+ language: str = ""+ parent_name: str | None = None # for methods: the containing class name+++@dataclass+class Import:+ """An import statement extracted from a source file."""++ raw_statement: str+ module_path: str # normalized module path+ imported_names: list[str] # specific names, or ["*"] for wildcard+ is_relative: bool+ resolved_file: str | None # absolute path if successfully resolved+++@dataclass+class ParsedFile:+ """Full result of parsing a single source file."""++ file_info: FileInfo+ symbols: list[Symbol]+ imports: list[Import]+ exports: list[str] # names exported by this file+ docstring: str | None # module/file-level docstring+ parse_errors: list[str] # non-fatal parser warnings/errors+ content_hash: str = "" # SHA-256 hex of raw file bytes+++def compute_content_hash(source: bytes) -> str:+ """Return the SHA-256 hex digest of *source*."""+ return hashlib.sha256(source).hexdigest()diff --git a/packages/core/src/wikicode/core/ingestion/parser.py b/packages/core/src/wikicode/core/ingestion/parser.pynew file mode 100644index 000000000..98d925c12--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/parser.py@@ -0,0 +1,988 @@+"""Unified AST parser — one class for all languages.++Architecture+============+Per-language differences live in two places:+ 1. ``packages/core/queries/<lang>.scm`` — tree-sitter S-expression queries+ that capture symbols and imports using consistent capture-name conventions.+ 2. ``LANGUAGE_CONFIGS`` dict in this module — a ``LanguageConfig`` per language+ that maps node types to symbol kinds, defines visibility rules, etc.++``ASTParser`` itself contains *no* if/elif language branches. Adding support+for a new language means writing one ``.scm`` file and one ``LanguageConfig``+entry. No Python class, no new module.++Capture-name conventions (shared across ALL .scm files):+ @symbol.def — the full definition node (line numbers, kind lookup)+ @symbol.name — name identifier+ @symbol.params — parameter list (optional)+ @symbol.modifiers — decorators / visibility modifiers (optional)+ @symbol.receiver — Go method receiver (optional, used for parent detection)+ @import.statement — full import node+ @import.module — module path being imported+"""++from __future__ import annotations++import re+from dataclasses import dataclass, field+from pathlib import Path+from typing import Callable++import structlog+from tree_sitter import Language, Node, Parser++from .models import FileInfo, Import, ParsedFile, Symbol++log = structlog.get_logger(__name__)++QUERIES_DIR = Path(__file__).parent.parent.parent.parent.parent / "queries"++# Languages that intentionally have no AST parser. These are data, config,+# markup, or query files — there are no code symbols to extract, and that is+# expected. parse_file() returns an empty ParsedFile for them silently.+# Keep this list in sync with EXTENSION_TO_LANGUAGE in models.py.+_PASSTHROUGH_LANGUAGES: frozenset[str] = frozenset(+ {+ "json",+ "yaml",+ "toml",+ "markdown",+ "sql",+ "shell",+ "terraform",+ "proto",+ "graphql",+ "dockerfile",+ "makefile",+ }+)++# ---------------------------------------------------------------------------+# Language registry — maps language tag → tree-sitter Language object+# ---------------------------------------------------------------------------+++def _build_language_registry() -> dict[str, Language]:+ """Lazily load installed tree-sitter language packages."""+ registry: dict[str, Language] = {}++ def _try_load(tag: str, loader: Callable[[], Language]) -> None:+ try:+ registry[tag] = loader()+ except Exception as exc: # ImportError, AttributeError, …+ log.debug("tree-sitter language unavailable", language=tag, reason=str(exc))++ _try_load("python", lambda: Language(__import__("tree_sitter_python").language()))++ def _ts() -> None:+ import tree_sitter_typescript as ts+ registry["typescript"] = Language(ts.language_typescript())+ registry["tsx"] = Language(ts.language_tsx())++ try:+ _ts()+ except Exception as exc:+ log.debug("tree-sitter language unavailable", language="typescript", reason=str(exc))++ _try_load("javascript", lambda: Language(__import__("tree_sitter_javascript").language()))+ _try_load("go", lambda: Language(__import__("tree_sitter_go").language()))+ _try_load("rust", lambda: Language(__import__("tree_sitter_rust").language()))+ _try_load("java", lambda: Language(__import__("tree_sitter_java").language()))++ def _cpp() -> None:+ import tree_sitter_cpp as ts_cpp+ lang = Language(ts_cpp.language())+ registry["cpp"] = lang+ registry["c"] = lang # C is a subset of C++ for our purposes++ try:+ _cpp()+ except Exception as exc:+ log.debug("tree-sitter language unavailable", language="cpp", reason=str(exc))++ return registry+++_LANGUAGE_REGISTRY: dict[str, Language] = {}+++def _get_language(tag: str) -> Language | None:+ global _LANGUAGE_REGISTRY+ if not _LANGUAGE_REGISTRY:+ _LANGUAGE_REGISTRY = _build_language_registry()+ return _LANGUAGE_REGISTRY.get(tag)+++# ---------------------------------------------------------------------------+# LanguageConfig+# ---------------------------------------------------------------------------+++@dataclass+class LanguageConfig:+ """Per-language metadata used by ASTParser.++ The ASTParser itself contains no language-specific if/elif logic.+ All branching happens through these configs and the .scm query files.+ """++ # Maps tree-sitter node type → our canonical SymbolKind string+ symbol_node_types: dict[str, str]++ # tree-sitter node types that carry import information (doc purposes)+ import_node_types: list[str]++ # tree-sitter node types that export symbols (doc purposes)+ export_node_types: list[str]++ # (name: str, modifier_texts: list[str]) → "public" | "private" | ...+ visibility_fn: Callable[[str, list[str]], str]++ # How to determine a method's parent class:+ # "nesting" — walk up AST; parent class types in parent_class_types+ # "receiver" — extract from @symbol.receiver capture (Go)+ # "impl" — look for impl_item ancestor (Rust)+ # "none" — no parent tracking+ parent_extraction: str = "nesting"++ # Node types that indicate a class context (used with "nesting" mode)+ parent_class_types: frozenset[str] = field(default_factory=frozenset)++ # Entry-point filename patterns for this language+ entry_point_patterns: list[str] = field(default_factory=list)+++def _py_visibility(name: str, _mods: list[str]) -> str:+ if name.startswith("__") and name.endswith("__"):+ return "public" # dunder+ if name.startswith("_"):+ return "private"+ return "public"+++def _ts_visibility(_name: str, mods: list[str]) -> str:+ mods_lower = [m.lower() for m in mods]+ if "private" in mods_lower:+ return "private"+ if "protected" in mods_lower:+ return "protected"+ return "public"+++def _go_visibility(name: str, _mods: list[str]) -> str:+ return "public" if name and name[0].isupper() else "private"+++def _rust_visibility(_name: str, mods: list[str]) -> str:+ return "public" if any("pub" in m for m in mods) else "private"+++def _java_visibility(_name: str, mods: list[str]) -> str:+ combined = " ".join(mods).lower()+ if "private" in combined:+ return "private"+ if "protected" in combined:+ return "protected"+ return "public"+++def _public_by_default(_name: str, _mods: list[str]) -> str:+ return "public"+++LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {+ "python": LanguageConfig(+ symbol_node_types={+ "function_definition": "function",+ "class_definition": "class",+ },+ import_node_types=["import_statement", "import_from_statement"],+ export_node_types=[],+ visibility_fn=_py_visibility,+ parent_extraction="nesting",+ parent_class_types=frozenset({"class_definition"}),+ entry_point_patterns=["main.py", "app.py", "__main__.py", "manage.py", "wsgi.py"],+ ),+ "typescript": LanguageConfig(+ symbol_node_types={+ "function_declaration": "function",+ "generator_function_declaration": "function",+ "arrow_function": "function",+ "class_declaration": "class",+ "abstract_class_declaration": "class",+ "interface_declaration": "interface",+ "type_alias_declaration": "type_alias",+ "enum_declaration": "enum",+ "method_definition": "method",+ "lexical_declaration": "function", # const foo = () => {}+ },+ import_node_types=["import_statement"],+ export_node_types=["export_statement"],+ visibility_fn=_ts_visibility,+ parent_extraction="nesting",+ parent_class_types=frozenset({"class_declaration", "abstract_class_declaration"}),+ entry_point_patterns=["index.ts", "main.ts", "app.ts", "server.ts"],+ ),+ "javascript": LanguageConfig(+ symbol_node_types={+ "function_declaration": "function",+ "generator_function_declaration": "function",+ "arrow_function": "function",+ "class_declaration": "class",+ "method_definition": "method",+ "lexical_declaration": "function",+ },+ import_node_types=["import_statement"],+ export_node_types=["export_statement"],+ visibility_fn=_public_by_default,+ parent_extraction="nesting",+ parent_class_types=frozenset({"class_declaration"}),+ entry_point_patterns=["index.js", "main.js", "app.js", "server.js"],+ ),+ "go": LanguageConfig(+ symbol_node_types={+ "function_declaration": "function",+ "method_declaration": "method",+ "type_spec": "struct", # refined in post-processing+ },+ import_node_types=["import_declaration"],+ export_node_types=[],+ visibility_fn=_go_visibility,+ parent_extraction="receiver",+ parent_class_types=frozenset(),+ entry_point_patterns=["main.go", "cmd/main.go"],+ ),+ "rust": LanguageConfig(+ symbol_node_types={+ "function_item": "function",+ "struct_item": "struct",+ "enum_item": "enum",+ "trait_item": "trait",+ "impl_item": "impl",+ "const_item": "constant",+ "type_item": "type_alias",+ "mod_item": "module",+ },+ import_node_types=["use_declaration"],+ export_node_types=[],+ visibility_fn=_rust_visibility,+ parent_extraction="impl",+ parent_class_types=frozenset({"impl_item"}),+ entry_point_patterns=["main.rs", "lib.rs"],+ ),+ "java": LanguageConfig(+ symbol_node_types={+ "class_declaration": "class",+ "interface_declaration": "interface",+ "enum_declaration": "enum",+ "method_declaration": "method",+ "constructor_declaration": "function",+ },+ import_node_types=["import_declaration"],+ export_node_types=[],+ visibility_fn=_java_visibility,+ parent_extraction="nesting",+ parent_class_types=frozenset({"class_declaration", "interface_declaration", "enum_declaration"}),+ entry_point_patterns=["Main.java", "Application.java"],+ ),+ "cpp": LanguageConfig(+ symbol_node_types={+ "function_definition": "function",+ "class_specifier": "class",+ "struct_specifier": "struct",+ "enum_specifier": "enum",+ "namespace_definition": "module",+ },+ import_node_types=["preproc_include"],+ export_node_types=[],+ visibility_fn=_public_by_default,+ parent_extraction="nesting",+ parent_class_types=frozenset({"class_specifier", "struct_specifier"}),+ entry_point_patterns=["main.cpp", "main.cc"],+ ),+ "c": LanguageConfig(+ symbol_node_types={+ "function_definition": "function",+ "struct_specifier": "struct",+ "enum_specifier": "enum",+ },+ import_node_types=["preproc_include"],+ export_node_types=[],+ visibility_fn=_public_by_default,+ parent_extraction="none",+ parent_class_types=frozenset(),+ entry_point_patterns=["main.c"],+ ),+}+++# ---------------------------------------------------------------------------+# ASTParser+# ---------------------------------------------------------------------------+++class ASTParser:+ """Unified AST parser — works for all languages via .scm query files.++ Usage::++ parser = ASTParser()+ parsed = parser.parse_file(file_info, source_bytes)++ Adding a new language:+ 1. Write ``packages/core/queries/<lang>.scm``+ 2. Add one entry to ``LANGUAGE_CONFIGS``+ That's it. No Python class, no new module.+ """++ def __init__(self) -> None:+ # Cache: lang → compiled Query object (None if .scm not found)+ self._query_cache: dict[str, object] = {}++ def parse_file(self, file_info: FileInfo, source: bytes) -> ParsedFile:+ """Parse *source* bytes and return a fully populated ParsedFile."""+ lang = file_info.language+ config = LANGUAGE_CONFIGS.get(lang)+ language = _get_language(lang)++ if config is None or language is None:+ # If the language has a LANGUAGE_CONFIGS entry but its tree-sitter+ # grammar failed to load, that is unexpected — log it once per file+ # so developers can investigate. For all other cases (data files,+ # markup, config, languages not yet supported) this is intentional+ # and we return silently without spamming the log.+ if config is not None and language is None:+ log.debug(+ "tree-sitter grammar unavailable",+ language=lang,+ path=file_info.path,+ )+ return ParsedFile(+ file_info=file_info,+ symbols=[],+ imports=[],+ exports=[],+ docstring=None,+ parse_errors=[],+ )++ # Delegate to special handlers for non-tree-sitter formats+ if lang in ("openapi", "dockerfile", "makefile"):+ from .special_handlers import parse_special+ return parse_special(file_info, source, lang)++ parser = Parser(language)+ tree = parser.parse(source)+ src = source.decode("utf-8", errors="replace")+ root = tree.root_node++ parse_errors = _collect_error_nodes(root)+ query = self._get_query(lang, language)++ symbols = self._extract_symbols(tree, query, config, file_info, src)+ imports = self._extract_imports(tree, query, config, file_info, src)+ exports = self._derive_exports(symbols, config, src)+ docstring = _extract_module_docstring(root, src, lang)++ return ParsedFile(+ file_info=file_info,+ symbols=symbols,+ imports=imports,+ exports=exports,+ docstring=docstring,+ parse_errors=parse_errors,+ )++ # ------------------------------------------------------------------+ # Query loading+ # ------------------------------------------------------------------++ def _get_query(self, lang: str, language: Language) -> object | None:+ """Load and cache the compiled tree-sitter Query for *lang*."""+ if lang in self._query_cache:+ return self._query_cache[lang]++ # C files reuse the cpp query+ scm_lang = "cpp" if lang == "c" else lang+ scm_path = QUERIES_DIR / f"{scm_lang}.scm"++ if not scm_path.exists():+ log.debug("No .scm query file found", language=lang, path=str(scm_path))+ self._query_cache[lang] = None+ return None++ scm_text = scm_path.read_text(encoding="utf-8")+ try:+ from tree_sitter import Query # type: ignore[attr-defined]+ compiled = Query(language, scm_text)+ self._query_cache[lang] = compiled+ log.debug("Compiled query", language=lang)+ return compiled+ except Exception as exc:+ log.warning("Failed to compile query", language=lang, error=str(exc))+ self._query_cache[lang] = None+ return None++ # ------------------------------------------------------------------+ # Symbol extraction+ # ------------------------------------------------------------------++ def _extract_symbols(+ self,+ tree: object,+ query: object,+ config: LanguageConfig,+ file_info: FileInfo,+ src: str,+ ) -> list[Symbol]:+ if query is None:+ return []++ symbols: list[Symbol] = []+ seen: set[tuple[int, str]] = set() # (start_line, name) — dedup decorated dupes++ for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]+ def_nodes = capture_dict.get("symbol.def", [])+ name_nodes = capture_dict.get("symbol.name", [])+ params_nodes = capture_dict.get("symbol.params", [])+ modifier_nodes = capture_dict.get("symbol.modifiers", [])+ receiver_nodes = capture_dict.get("symbol.receiver", [])++ if not def_nodes or not name_nodes:+ continue++ def_node = def_nodes[0]+ name = _node_text(name_nodes[0], src)+ if not name:+ continue++ start_line = def_node.start_point[0] + 1+ dedup_key = (start_line, name)+ if dedup_key in seen:+ continue+ seen.add(dedup_key)++ # Kind from node type+ node_type = def_node.type+ kind = config.symbol_node_types.get(node_type)+ if kind is None:+ continue++ # Refine "struct" kind for Go type_spec (check if struct or interface body)+ if kind == "struct" and config.parent_extraction == "receiver":+ kind = _refine_go_type_kind(def_node, src)++ # Params signature text+ params_text = _node_text(params_nodes[0], src) if params_nodes else ""++ # Visibility+ modifier_texts = [_node_text(m, src) for m in modifier_nodes]+ # Also check if parent in decorated_definition has decorators+ if def_node.parent and def_node.parent.type == "decorated_definition":+ for sibling in def_node.parent.children:+ if sibling.type == "decorator":+ modifier_texts.append(_node_text(sibling, src))+ visibility = config.visibility_fn(name, modifier_texts)++ # Parent class detection+ parent_name = self._find_parent(+ def_node, config, receiver_nodes, src+ )++ # Upgrade function → method when a parent class is detected+ if parent_name and kind == "function":+ kind = "method"++ # Build signature+ signature = _build_signature(node_type, name, params_text, def_node, src)++ # Docstring — walk the body of the def_node+ docstring = _extract_symbol_docstring(def_node, src, file_info.language)++ # Async detection+ is_async = _is_async_node(def_node, src)++ sym_id = (+ f"{file_info.path}::{parent_name}::{name}"+ if parent_name+ else f"{file_info.path}::{name}"+ )+ qualified = _build_qualified_name(file_info.path, parent_name, name)++ symbols.append(+ Symbol(+ id=sym_id,+ name=name,+ qualified_name=qualified,+ kind=kind, # type: ignore[arg-type]+ signature=signature,+ start_line=start_line,+ end_line=def_node.end_point[0] + 1,+ docstring=docstring,+ decorators=[m for m in modifier_texts if m.startswith("@")],+ visibility=visibility, # type: ignore[arg-type]+ is_async=is_async,+ language=file_info.language,+ parent_name=parent_name,+ )+ )++ return symbols++ def _find_parent(+ self,+ def_node: Node,+ config: LanguageConfig,+ receiver_nodes: list[Node],+ src: str,+ ) -> str | None:+ """Determine the parent class/type for a symbol."""+ if config.parent_extraction == "receiver":+ # Go: extract type name from receiver parameter list+ if receiver_nodes:+ return _extract_go_receiver_type(_node_text(receiver_nodes[0], src))+ return None++ if config.parent_extraction in ("nesting", "impl"):+ # Walk up the AST to find a class/impl ancestor+ ancestor = def_node.parent+ while ancestor is not None:+ if ancestor.type in config.parent_class_types:+ name_node = ancestor.child_by_field_name("name") or (+ ancestor.child_by_field_name("type") # Rust impl_item+ )+ if name_node:+ return _node_text(name_node, src)+ ancestor = ancestor.parent+ return None++ return None # "none" mode++ # ------------------------------------------------------------------+ # Import extraction+ # ------------------------------------------------------------------++ def _extract_imports(+ self,+ tree: object,+ query: object,+ config: LanguageConfig,+ file_info: FileInfo,+ src: str,+ ) -> list[Import]:+ if query is None:+ return []++ imports: list[Import] = []+ seen_raws: set[str] = set()++ for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]+ stmt_nodes = capture_dict.get("import.statement", [])+ module_nodes = capture_dict.get("import.module", [])++ if not stmt_nodes or not module_nodes:+ continue++ stmt_node = stmt_nodes[0]+ raw = _node_text(stmt_node, src).strip()+ if raw in seen_raws:+ continue+ seen_raws.add(raw)++ module_text = _node_text(module_nodes[0], src).strip().strip("\"'` ")+ if not module_text:+ continue++ # Language-specific import name extraction+ imported_names = _extract_import_names(stmt_node, src, file_info.language)+ is_relative = module_text.startswith(".") or module_text.startswith("./")++ imports.append(+ Import(+ raw_statement=raw,+ module_path=module_text,+ imported_names=imported_names,+ is_relative=is_relative,+ resolved_file=None,+ )+ )++ return imports++ # ------------------------------------------------------------------+ # Export derivation+ # ------------------------------------------------------------------++ def _derive_exports(+ self,+ symbols: list[Symbol],+ config: LanguageConfig,+ src: str,+ ) -> list[str]:+ """Derive the list of exported names from parsed symbols."""+ if config.export_node_types:+ # Languages with explicit exports (TS, JS) — public top-level symbols+ return [+ s.name+ for s in symbols+ if s.visibility == "public" and s.parent_name is None+ ]+ # Languages where all top-level public symbols are exported (Python, Go, …)+ return [+ s.name+ for s in symbols+ if s.visibility == "public" and s.parent_name is None+ ]+++# ---------------------------------------------------------------------------+# Convenience function+# ---------------------------------------------------------------------------++_DEFAULT_PARSER: ASTParser | None = None+++def parse_file(file_info: FileInfo, source: bytes) -> ParsedFile:+ """Module-level convenience: parse a file using the default ASTParser."""+ global _DEFAULT_PARSER+ if _DEFAULT_PARSER is None:+ _DEFAULT_PARSER = ASTParser()+ return _DEFAULT_PARSER.parse_file(file_info, source)+++# ---------------------------------------------------------------------------+# Internal helpers+# ---------------------------------------------------------------------------+++def _run_query(query: object, root_node: Node) -> list[dict[str, list[Node]]]:+ """Execute a tree-sitter query and return a list of capture dicts.++ Handles both the legacy tuple API and the newer QueryMatch API across+ tree-sitter versions >= 0.22.+ """+ results: list[dict[str, list[Node]]] = []+ try:+ from tree_sitter import QueryCursor # type: ignore[attr-defined]+ cursor = QueryCursor(query) # type: ignore[call-arg]+ for match in cursor.matches(root_node):+ if hasattr(match, "captures"):+ # tree-sitter >= 0.23: QueryMatch object+ results.append(match.captures)+ elif isinstance(match, tuple) and len(match) == 2:+ _, caps = match+ results.append(caps)+ except Exception:+ # Fallback: query.matches() returning list of (index, dict) tuples+ try:+ for item in query.matches(root_node): # type: ignore[attr-defined]+ if isinstance(item, tuple) and len(item) == 2:+ _, caps = item+ results.append(caps)+ except Exception as exc:+ log.warning("query.matches() failed", error=str(exc))+ return results+++def _node_text(node: Node | None, src: str) -> str:+ if node is None:+ return ""+ if node.text is not None:+ return node.text.decode("utf-8", errors="replace")+ return src[node.start_byte:node.end_byte]+++def _collect_error_nodes(root: Node) -> list[str]:+ """Return error descriptions for any ERROR nodes in the tree."""+ errors: list[str] = []++ def _walk(node: Node) -> None:+ if node.type == "ERROR":+ errors.append(f"Parse error at line {node.start_point[0] + 1}")+ for child in node.children:+ _walk(child)++ _walk(root)+ return errors+++def _extract_module_docstring(root: Node, src: str, lang: str) -> str | None:+ """Extract a module/file-level docstring or leading comment."""+ if lang == "python":+ for child in root.children:+ if child.type == "expression_statement":+ for sub in child.children:+ if sub.type == "string":+ return _clean_string_literal(_node_text(sub, src))+ break+ elif child.type not in ("comment", "newline", "import_statement",+ "import_from_statement", "future_import_statement"):+ break+ elif lang in ("typescript", "javascript"):+ # Look for leading /** ... */ comment+ for child in root.children:+ if child.type == "comment":+ text = _node_text(child, src).strip()+ if text.startswith("/**"):+ return _clean_jsdoc(text)+ elif child.type not in ("comment",):+ break+ elif lang == "go":+ # Package comment is a series of // lines before package_clause+ lines: list[str] = []+ for child in root.children:+ if child.type == "comment":+ lines.append(_node_text(child, src).lstrip("/ ").strip())+ elif child.type == "package_clause":+ break+ return "\n".join(lines) if lines else None+ elif lang == "rust":+ # //! inner doc comments or /// outer doc comments at top+ for child in root.children:+ if child.type in ("line_comment", "block_comment"):+ text = _node_text(child, src).strip()+ if text.startswith("//!") or text.startswith("/*!"):+ return text.lstrip("/!* ").strip()+ else:+ break+ return None+++def _extract_symbol_docstring(def_node: Node, src: str, lang: str) -> str | None:+ """Extract the docstring from a symbol's body node."""+ if lang == "python":+ body = def_node.child_by_field_name("body")+ if body is None:+ return None+ for child in body.children:+ if child.type == "expression_statement":+ for sub in child.children:+ if sub.type == "string":+ return _clean_string_literal(_node_text(sub, src))+ return None+ elif child.type not in ("comment", "newline"):+ return None+ return None++ elif lang in ("typescript", "javascript"):+ return _find_preceding_jsdoc(def_node, src)++ elif lang == "go":+ # Leading // comment lines before the function+ parent = def_node.parent+ if parent is None:+ return None+ siblings = list(parent.children)+ idx = next((i for i, s in enumerate(siblings) if s.id == def_node.id), -1)+ if idx <= 0:+ return None+ lines: list[str] = []+ i = idx - 1+ while i >= 0 and siblings[i].type == "comment":+ lines.insert(0, _node_text(siblings[i], src).lstrip("/ ").strip())+ i -= 1+ return "\n".join(lines) if lines else None++ elif lang == "rust":+ # /// doc comments before the item+ parent = def_node.parent+ if parent is None:+ return None+ siblings = list(parent.children)+ idx = next((i for i, s in enumerate(siblings) if s.id == def_node.id), -1)+ if idx <= 0:+ return None+ lines: list[str] = []+ i = idx - 1+ while i >= 0 and siblings[i].type in ("line_comment", "block_comment"):+ text = _node_text(siblings[i], src).strip()+ if text.startswith("///"):+ lines.insert(0, text.lstrip("/ ").strip())+ i -= 1+ else:+ break+ return "\n".join(lines) if lines else None++ elif lang == "java":+ # /** Javadoc */ comment before the method/class+ return _find_preceding_block_comment(def_node, src, "/**")++ return None+++def _build_signature(+ node_type: str, name: str, params_text: str, def_node: Node, src: str+) -> str:+ """Build a human-readable signature string."""+ if node_type == "function_definition":+ # Detect async via child "async" keyword (tree-sitter-python >= 0.23)+ prefix = "async " if any(c.type == "async" for c in def_node.children) else ""+ # Get return type annotation for Python+ ret_node = def_node.child_by_field_name("return_type")+ ret_text = f" -> {_node_text(ret_node, src)}" if ret_node else ""+ return f"{prefix}def {name}{params_text}{ret_text}"+ if node_type in ("function_declaration", "generator_function_declaration", "function_item"):+ return f"function {name}{params_text}"+ if node_type in ("class_definition", "class_declaration", "abstract_class_declaration"):+ base = f"class {name}"+ if params_text:+ base += params_text+ return base+ if node_type == "interface_declaration":+ return f"interface {name}"+ if node_type == "type_alias_declaration":+ return f"type {name}"+ if node_type == "enum_declaration":+ return f"enum {name}"+ if node_type == "method_definition":+ return f"{name}{params_text}"+ if node_type == "method_declaration":+ return f"func ({name}) method{params_text}"+ if node_type in ("struct_item", "struct_specifier"):+ return f"struct {name}"+ if node_type in ("enum_item", "enum_specifier"):+ return f"enum {name}"+ if node_type == "trait_item":+ return f"trait {name}"+ if node_type == "impl_item":+ return f"impl {name}"+ if node_type in ("class_specifier",):+ return f"class {name}"+ # Fallback+ return f"{name}{params_text}"+++def _extract_import_names(stmt_node: Node, src: str, lang: str) -> list[str]:+ """Extract specific imported names from an import statement node."""+ names: list[str] = []++ if lang == "python":+ for child in stmt_node.children:+ if child.type == "wildcard_import":+ return ["*"]+ if child.type == "dotted_name":+ text = _node_text(child, src)+ # Skip the module name itself (it's the first dotted_name in import_from)+ if names or stmt_node.type == "import_statement":+ names.append(text.split(".")[-1])+ else:+ names.append(text.split(".")[-1])+ elif child.type == "aliased_import":+ name_child = child.child_by_field_name("name") or (+ child.children[0] if child.children else None+ )+ if name_child:+ names.append(_node_text(name_child, src))+ return names++ if lang in ("typescript", "javascript"):+ # Find import_clause → named_imports → import_specifier+ for child in stmt_node.children:+ if child.type == "import_clause":+ for sub in child.children:+ if sub.type == "identifier":+ names.append(_node_text(sub, src)) # default import+ elif sub.type == "named_imports":+ for spec in sub.children:+ if spec.type == "import_specifier":+ name_node = spec.child_by_field_name("name") or (+ spec.children[0] if spec.children else None+ )+ if name_node:+ names.append(_node_text(name_node, src))+ elif sub.type == "namespace_import":+ names = ["*"]+ return names++ return []+++def _extract_go_receiver_type(receiver_text: str) -> str | None:+ """Extract 'Calculator' from '(c *Calculator)' or '(c Calculator)'."""+ text = receiver_text.strip("() ")+ parts = text.split()+ for part in reversed(parts):+ clean = part.lstrip("*")+ if clean and clean[0].isupper():+ return clean+ return None+++def _refine_go_type_kind(type_spec_node: Node, src: str) -> str:+ """Refine the generic 'struct' kind for Go type_spec nodes."""+ type_node = type_spec_node.child_by_field_name("type")+ if type_node is None:+ return "struct"+ type_text = _node_text(type_node, src).strip()+ if type_text.startswith("struct"):+ return "struct"+ if type_text.startswith("interface"):+ return "interface"+ return "type_alias"+++def _is_async_node(node: Node, src: str) -> bool:+ return node.type == "async_function_definition" or any(+ c.type == "async" for c in node.children+ )+++def _clean_string_literal(text: str) -> str:+ text = text.strip()+ for triple in ('"""', "'''"):+ if text.startswith(triple) and text.endswith(triple) and len(text) >= 6:+ return text[3:-3].strip()+ for q in ('"', "'"):+ if text.startswith(q) and text.endswith(q) and len(text) >= 2:+ return text[1:-1].strip()+ return text+++def _find_preceding_jsdoc(node: Node, src: str) -> str | None:+ parent = node.parent+ if parent is None:+ return None+ siblings = list(parent.children)+ idx = next((i for i, s in enumerate(siblings) if s.id == node.id), -1)+ if idx <= 0:+ return None+ prev = siblings[idx - 1]+ if prev.type == "comment":+ text = _node_text(prev, src).strip()+ if text.startswith("/**"):+ return _clean_jsdoc(text)+ return None+++def _find_preceding_block_comment(node: Node, src: str, prefix: str) -> str | None:+ parent = node.parent+ if parent is None:+ return None+ siblings = list(parent.children)+ idx = next((i for i, s in enumerate(siblings) if s.id == node.id), -1)+ if idx <= 0:+ return None+ prev = siblings[idx - 1]+ if prev.type in ("block_comment", "comment"):+ text = _node_text(prev, src).strip()+ if text.startswith(prefix):+ return _clean_jsdoc(text)+ return None+++def _clean_jsdoc(text: str) -> str:+ lines = text.splitlines()+ cleaned: list[str] = []+ for line in lines:+ line = line.strip().lstrip("/*").lstrip()+ if line:+ cleaned.append(line)+ return "\n".join(cleaned).strip()+++def _build_qualified_name(file_path: str, parent_name: str | None, name: str) -> str:+ module = Path(file_path).with_suffix("").as_posix().replace("/", ".")+ if parent_name:+ return f"{module}.{parent_name}.{name}"+ return f"{module}.{name}"diff --git a/packages/core/src/wikicode/core/ingestion/parsers/__init__.py b/packages/core/src/wikicode/core/ingestion/parsers/__init__.pynew file mode 100644index 000000000..ef5409f6b--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/parsers/__init__.py@@ -0,0 +1,4 @@+# This directory is intentionally empty.+# Language-specific parsing is handled by the unified ASTParser in+# wikicode.core.ingestion.parser using per-language .scm query files+# in packages/core/queries/.diff --git a/packages/core/src/wikicode/core/ingestion/parsers/base.py b/packages/core/src/wikicode/core/ingestion/parsers/base.pynew file mode 100644index 000000000..186876d45--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/parsers/base.py@@ -0,0 +1,3 @@+# Replaced by the unified ASTParser architecture.+# See packages/core/src/wikicode/core/ingestion/parser.py and+# packages/core/queries/*.scm for the current implementation.diff --git a/packages/core/src/wikicode/core/ingestion/parsers/go.py b/packages/core/src/wikicode/core/ingestion/parsers/go.pynew file mode 100644index 000000000..52d633244--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/parsers/go.py@@ -0,0 +1,2 @@+# Replaced by the unified ASTParser architecture.+# See packages/core/queries/go.scm for the symbol/import queries.diff --git a/packages/core/src/wikicode/core/ingestion/parsers/python.py b/packages/core/src/wikicode/core/ingestion/parsers/python.pynew file mode 100644index 000000000..8b6e1042e--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/parsers/python.py@@ -0,0 +1,2 @@+# Replaced by the unified ASTParser architecture.+# See packages/core/queries/python.scm for the symbol/import queries.diff --git a/packages/core/src/wikicode/core/ingestion/parsers/typescript.py b/packages/core/src/wikicode/core/ingestion/parsers/typescript.pynew file mode 100644index 000000000..2767ca9d5--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/parsers/typescript.py@@ -0,0 +1,2 @@+# Replaced by the unified ASTParser architecture.+# See packages/core/queries/typescript.scm and javascript.scm.diff --git a/packages/core/src/wikicode/core/ingestion/special_handlers.py b/packages/core/src/wikicode/core/ingestion/special_handlers.pynew file mode 100644index 000000000..0a8eceff9--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/special_handlers.py@@ -0,0 +1,290 @@+"""Special handlers for non-tree-sitter file formats.++These parsers use plain text/regex/YAML parsing rather than tree-sitter because+the formats are simple enough (Dockerfile, Makefile) or require domain-specific+libraries (OpenAPI via PyYAML).++Each handler produces a fully-populated ParsedFile — the same output model as+the tree-sitter parsers — so the rest of the pipeline treats them identically.+"""++from __future__ import annotations++import re+from pathlib import Path+from typing import Callable++import structlog++from .models import FileInfo, Import, ParsedFile, Symbol++log = structlog.get_logger(__name__)+++# ---------------------------------------------------------------------------+# Dispatcher+# ---------------------------------------------------------------------------+++def parse_special(file_info: FileInfo, source: bytes, lang: str) -> ParsedFile:+ """Route to the correct special handler based on language tag."""+ handler: Callable[[FileInfo, bytes], ParsedFile] = {+ "openapi": _parse_openapi,+ "dockerfile": _parse_dockerfile,+ "makefile": _parse_makefile,+ }.get(lang, _parse_unknown)+ try:+ return handler(file_info, source)+ except Exception as exc:+ log.warning("Special handler failed", path=file_info.path, error=str(exc))+ return _empty(file_info, parse_errors=[str(exc)])+++# ---------------------------------------------------------------------------+# OpenAPI handler+# ---------------------------------------------------------------------------+++def _parse_openapi(file_info: FileInfo, source: bytes) -> ParsedFile:+ """Parse OpenAPI 2 / 3 YAML or JSON specs."""+ try:+ import yaml # pyyaml, already in dependencies+ except ImportError:+ return _empty(file_info, parse_errors=["pyyaml not installed"])++ try:+ data = yaml.safe_load(source.decode("utf-8", errors="replace"))+ except Exception as exc:+ return _empty(file_info, parse_errors=[f"YAML parse error: {exc}"])++ if not isinstance(data, dict):+ return _empty(file_info, parse_errors=["Not a YAML mapping"])++ # Confirm it's an OpenAPI/Swagger spec+ if "openapi" not in data and "swagger" not in data:+ return _empty(file_info, parse_errors=["Not an OpenAPI/Swagger spec"])++ symbols: list[Symbol] = []+ title = (data.get("info") or {}).get("title", file_info.path)++ paths = data.get("paths") or {}+ for path, methods in paths.items():+ if not isinstance(methods, dict):+ continue+ for method, spec in methods.items():+ if method.lower() in ("get", "post", "put", "patch", "delete", "head", "options"):+ op_id = (spec or {}).get("operationId", f"{method.upper()} {path}")+ summary = (spec or {}).get("summary")+ symbols.append(+ Symbol(+ id=f"{file_info.path}::{op_id}",+ name=op_id,+ qualified_name=op_id,+ kind="function",+ signature=f"{method.upper()} {path}",+ start_line=1,+ end_line=1,+ docstring=summary,+ visibility="public",+ language="openapi",+ )+ )++ # Components / schemas as type symbols+ components = (data.get("components") or {}).get("schemas") or \+ (data.get("definitions") or {})+ for schema_name in components:+ symbols.append(+ Symbol(+ id=f"{file_info.path}::{schema_name}",+ name=schema_name,+ qualified_name=schema_name,+ kind="type_alias",+ signature=f"schema {schema_name}",+ start_line=1,+ end_line=1,+ docstring=None,+ visibility="public",+ language="openapi",+ )+ )++ return ParsedFile(+ file_info=file_info,+ symbols=symbols,+ imports=[],+ exports=[s.name for s in symbols],+ docstring=str(data.get("info", {}).get("description", "")) or None,+ parse_errors=[],+ )+++# ---------------------------------------------------------------------------+# Dockerfile handler+# ---------------------------------------------------------------------------++_FROM_RE = re.compile(r"^\s*FROM\s+([^\s]+)", re.IGNORECASE)+_COPY_RE = re.compile(r"^\s*COPY\s+", re.IGNORECASE)+_RUN_RE = re.compile(r"^\s*RUN\s+", re.IGNORECASE)+_ENTRYPOINT_RE = re.compile(r"^\s*(?:ENTRYPOINT|CMD)\s+(.+)", re.IGNORECASE)+_EXPOSE_RE = re.compile(r"^\s*EXPOSE\s+(\d+)", re.IGNORECASE)+_ENV_RE = re.compile(r"^\s*ENV\s+(\w+)", re.IGNORECASE)+_ARG_RE = re.compile(r"^\s*ARG\s+(\w+)", re.IGNORECASE)+++def _parse_dockerfile(file_info: FileInfo, source: bytes) -> ParsedFile:+ text = source.decode("utf-8", errors="replace")+ lines = text.splitlines()+ imports: list[Import] = []+ symbols: list[Symbol] = []++ for lineno, line in enumerate(lines, start=1):+ line_stripped = line.strip()+ if not line_stripped or line_stripped.startswith("#"):+ continue++ # FROM → import+ m = _FROM_RE.match(line)+ if m:+ image = m.group(1)+ imports.append(Import(+ raw_statement=line.strip(),+ module_path=image,+ imported_names=[image],+ is_relative=False,+ resolved_file=None,+ ))+ continue++ # ENTRYPOINT / CMD → entry-point symbol+ m = _ENTRYPOINT_RE.match(line)+ if m:+ name = "entrypoint" if "ENTRYPOINT" in line.upper() else "cmd"+ symbols.append(Symbol(+ id=f"{file_info.path}::{name}",+ name=name,+ qualified_name=name,+ kind="function",+ signature=line.strip(),+ start_line=lineno,+ end_line=lineno,+ docstring=None,+ visibility="public",+ language="dockerfile",+ ))+ continue++ # EXPOSE → constant+ m = _EXPOSE_RE.match(line)+ if m:+ port = m.group(1)+ symbols.append(Symbol(+ id=f"{file_info.path}::EXPOSE_{port}",+ name=f"EXPOSE_{port}",+ qualified_name=f"port_{port}",+ kind="constant",+ signature=line.strip(),+ start_line=lineno,+ end_line=lineno,+ docstring=None,+ visibility="public",+ language="dockerfile",+ ))++ return ParsedFile(+ file_info=file_info,+ symbols=symbols,+ imports=imports,+ exports=[],+ docstring=None,+ parse_errors=[],+ )+++# ---------------------------------------------------------------------------+# Makefile handler+# ---------------------------------------------------------------------------++# Matches: target_name: [prerequisites...]+_TARGET_RE = re.compile(r"^([a-zA-Z0-9_][a-zA-Z0-9_\-./]*):[^=]")+_INCLUDE_RE = re.compile(r"^include\s+(.+)", re.IGNORECASE)+_PHONY_RE = re.compile(r"^\.PHONY\s*:\s*(.+)")+++def _parse_makefile(file_info: FileInfo, source: bytes) -> ParsedFile:+ text = source.decode("utf-8", errors="replace")+ lines = text.splitlines()+ symbols: list[Symbol] = []+ imports: list[Import] = []+ phony_targets: set[str] = set()++ # First pass: collect .PHONY targets+ for line in lines:+ m = _PHONY_RE.match(line)+ if m:+ phony_targets.update(m.group(1).split())++ # Second pass: extract targets+ current_lineno = 0+ for lineno, line in enumerate(lines, start=1):+ line_stripped = line.strip()+ if not line_stripped or line_stripped.startswith("#"):+ continue++ m = _TARGET_RE.match(line)+ if m:+ target = m.group(1)+ if not target.startswith("."): # skip .PHONY, .SUFFIXES, etc.+ symbols.append(Symbol(+ id=f"{file_info.path}::{target}",+ name=target,+ qualified_name=target,+ kind="function",+ signature=f"{target}:",+ start_line=lineno,+ end_line=lineno,+ docstring=None,+ visibility="public",+ language="makefile",+ ))+ continue++ m = _INCLUDE_RE.match(line)+ if m:+ include_path = m.group(1).strip()+ imports.append(Import(+ raw_statement=line.strip(),+ module_path=include_path,+ imported_names=[],+ is_relative=True,+ resolved_file=None,+ ))++ return ParsedFile(+ file_info=file_info,+ symbols=symbols,+ imports=imports,+ exports=[s.name for s in symbols],+ docstring=None,+ parse_errors=[],+ )+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _parse_unknown(file_info: FileInfo, source: bytes) -> ParsedFile:+ return _empty(file_info, parse_errors=[f"No special handler for {file_info.language}"])+++def _empty(file_info: FileInfo, parse_errors: list[str] | None = None) -> ParsedFile:+ return ParsedFile(+ file_info=file_info,+ symbols=[],+ imports=[],+ exports=[],+ docstring=None,+ parse_errors=parse_errors or [],+ )diff --git a/packages/core/src/wikicode/core/ingestion/traverser.py b/packages/core/src/wikicode/core/ingestion/traverser.pynew file mode 100644index 000000000..6e645fa81--- /dev/null+++ b/packages/core/src/wikicode/core/ingestion/traverser.py@@ -0,0 +1,525 @@+"""File traversal for the WikiCode ingestion pipeline.++FileTraverser walks a repository tree and yields FileInfo objects for each+source file that should be documented. It respects:+ 1. .gitignore (via pathspec)+ 2. .wikicodeIgnore (same syntax, user overrides)+ 3. A hardcoded blocklist of dirs / file patterns+ 4. Binary file detection+ 5. File-size limit+ 6. Generated-file detection (header markers + filename suffixes)++It also detects monorepo structure and returns a RepoStructure.+"""++from __future__ import annotations++import os+import threading+from datetime import datetime+from pathlib import Path+from typing import Iterator++import pathspec+import structlog++from .models import (+ EXTENSION_TO_LANGUAGE,+ SPECIAL_FILENAMES,+ FileInfo,+ LanguageTag,+ PackageInfo,+ RepoStructure,+)++log = structlog.get_logger(__name__)++# ---------------------------------------------------------------------------+# Blocklists+# ---------------------------------------------------------------------------++_BLOCKED_DIRS: frozenset[str] = frozenset(+ {+ ".git",+ ".hg",+ ".svn",+ "node_modules",+ ".venv",+ "venv",+ "__pycache__",+ ".pytest_cache",+ ".mypy_cache",+ ".ruff_cache",+ ".tox",+ "dist",+ "build",+ ".next",+ "target", # Rust / Maven+ ".gradle",+ "vendor", # Go / PHP+ "coverage",+ "htmlcov",+ ".eggs",+ "site-packages",+ ".cache",+ ".idea",+ ".vscode",+ }+)++_BLOCKED_EXTENSIONS: frozenset[str] = frozenset(+ {".pyc", ".pyo", ".pyd", ".so", ".dll", ".dylib", ".exe", ".o", ".a", ".wasm"}+)++_BLOCKED_FILENAME_PATTERNS: list[str] = [+ "*.min.js",+ "*.min.css",+ "package-lock.json",+ "yarn.lock",+ "pnpm-lock.yaml",+ "go.sum",+ "Cargo.lock",+ "poetry.lock",+ "uv.lock",+ "*.lock",+]++# Generated file markers (checked in first 512 bytes)+_GENERATED_MARKERS: tuple[str, ...] = (+ "Code generated",+ "DO NOT EDIT",+ "This file was automatically generated",+ "GENERATED CODE",+ "AUTO-GENERATED",+ "@generated",+)++_GENERATED_SUFFIXES: tuple[str, ...] = (+ "_pb2.py",+ "_pb2_grpc.py",+ "_pb.ts",+ "_pb.js",+ "_grpc.pb.go",+)++# Manifest files that indicate a package root (for monorepo detection)+_MANIFEST_FILES: frozenset[str] = frozenset(+ {"pyproject.toml", "package.json", "Cargo.toml", "go.mod"}+)++# Entry-point filename stems+_ENTRY_POINT_STEMS: frozenset[str] = frozenset(+ {"main", "index", "app", "run", "server", "start", "wsgi", "asgi"}+)++_ENTRY_POINT_NAMES: frozenset[str] = frozenset(+ {+ "main.py", "app.py", "run.py", "server.py", "wsgi.py", "asgi.py",+ "index.ts", "index.js", "main.ts", "main.js", "app.ts",+ "main.go",+ "main.rs", "lib.rs",+ "Main.java", "Application.java",+ }+)++# Default file-size limit+_DEFAULT_MAX_FILE_SIZE_BYTES: int = 500 * 1024 # 500 KB++# Languages for which generated-file detection is skipped. These files have+# no AST parsing anyway, so reading 512 bytes to check for generated markers+# adds no value.+_SKIP_GENERATED_CHECK: frozenset[str] = frozenset(+ {+ "json", "yaml", "toml", "markdown", "sql", "shell",+ "terraform", "proto", "graphql", "dockerfile", "makefile",+ }+)+++class FileTraverser:+ """Traverse a repository and yield FileInfo for each documentable file.++ Args:+ repo_root: Absolute path to the repository root.+ max_file_size_kb: Skip files larger than this. Default: 500 KB.+ extra_ignore_filename: Name of an additional gitignore-syntax file.+ Defaults to ``.wikicodeIgnore``.+ extra_exclude_patterns: Additional gitignore-style patterns to exclude+ (from CLI ``--exclude`` flags or ``repo.settings["exclude_patterns"]``).+ """++ def __init__(+ self,+ repo_root: Path,+ *,+ max_file_size_kb: int = 500,+ extra_ignore_filename: str = ".wikicodeIgnore",+ extra_exclude_patterns: list[str] | None = None,+ ) -> None:+ self.repo_root = repo_root.resolve()+ self.max_file_size_bytes = max_file_size_kb * 1024+ self._extra_ignore_filename = extra_ignore_filename+ self._gitignore = _load_gitignore_spec(self.repo_root)+ self._extra_ignore = _load_extra_ignore_spec(self.repo_root, extra_ignore_filename)+ self._blocked_patterns = pathspec.PathSpec.from_lines(+ "gitwildmatch", _BLOCKED_FILENAME_PATTERNS+ )+ patterns = extra_exclude_patterns or []+ self._extra_exclude = pathspec.PathSpec.from_lines("gitwildmatch", patterns)+ # Per-directory .wikicodeIgnore cache: absolute dir path -> PathSpec.+ # Pre-seed root so it isn't read twice (we already have self._extra_ignore).+ self._dir_ignore_cache: dict[str, pathspec.PathSpec] = {+ str(self.repo_root): self._extra_ignore,+ }+ self._oversized_skip_count: int = 0+ self._count_lock = threading.Lock()+ log.info(+ "FileTraverser initialised",+ repo_root=str(self.repo_root),+ max_file_size_kb=max_file_size_kb,+ extra_exclude_patterns=len(patterns),+ )++ # ------------------------------------------------------------------+ # Public API+ # ------------------------------------------------------------------++ def traverse(self) -> Iterator[FileInfo]:+ """Yield FileInfo for every includable source file in the repo."""+ for abs_path in self._walk():+ info = self._build_file_info(abs_path)+ if info is not None:+ yield info++ def get_repo_structure(self, files: list[FileInfo] | None = None) -> RepoStructure:+ """Analyse high-level repo structure including monorepo detection.++ Pass an already-traversed *files* list to avoid a redundant full+ traversal. If omitted the repo is traversed from scratch.+ """+ if files is None:+ files = list(self.traverse())++ lang_counts: dict[str, int] = {}+ entry_points: list[str] = []++ for f in files:+ lang_counts[f.language] = lang_counts.get(f.language, 0) + 1+ if f.is_entry_point:+ entry_points.append(f.path)++ # Estimate LOC from file sizes (~40 bytes/line for mixed codebases).+ # This avoids opening every file just for line counting — total_loc is+ # a display metric so a fast estimate is acceptable.+ total_loc = sum(f.size_bytes // 40 for f in files)++ total = max(sum(lang_counts.values()), 1)+ lang_dist = {k: round(v / total, 3) for k, v in sorted(lang_counts.items())}++ packages, is_monorepo = self._detect_monorepo()++ return RepoStructure(+ is_monorepo=is_monorepo,+ packages=packages,+ root_language_distribution=lang_dist,+ total_files=len(files),+ total_loc=total_loc,+ entry_points=sorted(entry_points),+ )++ # ------------------------------------------------------------------+ # Internal: walking+ # ------------------------------------------------------------------++ def _walk(self) -> Iterator[Path]:+ """Yield all absolute file paths, skipping blocked directories."""+ for dirpath, dirnames, filenames in os.walk(self.repo_root):+ dirpath_obj = Path(dirpath)+ rel_dir = dirpath_obj.relative_to(self.repo_root)++ # Load per-directory .wikicodeIgnore for subdirectory pruning.+ dir_ignore = self._get_dir_ignore(dirpath_obj)++ # Prune ignored directories in-place (affects os.walk recursion)+ dirnames[:] = sorted(+ d for d in dirnames+ if not self._should_skip_dir(d, rel_dir / d, dir_ignore)+ )++ for filename in sorted(filenames):+ yield dirpath_obj / filename++ def _get_dir_ignore(self, dirpath: Path) -> pathspec.PathSpec:+ """Return the per-directory .wikicodeIgnore spec, loading and caching on first access."""+ key = str(dirpath)+ if key not in self._dir_ignore_cache:+ ignore_file = dirpath / self._extra_ignore_filename+ if ignore_file.exists():+ lines = ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines()+ else:+ lines = []+ self._dir_ignore_cache[key] = pathspec.PathSpec.from_lines("gitwildmatch", lines)+ return self._dir_ignore_cache[key]++ def _should_skip_dir(+ self,+ dirname: str,+ rel_path: Path,+ dir_ignore: pathspec.PathSpec | None = None,+ ) -> bool:+ if dirname in _BLOCKED_DIRS:+ return True+ rel_str = rel_path.as_posix()+ if self._gitignore.match_file(rel_str + "/"):+ return True+ if self._extra_ignore.match_file(rel_str + "/"):+ return True+ if self._extra_exclude.match_file(rel_str + "/"):+ return True+ # Per-directory ignore: pattern is relative to the parent directory.+ if dir_ignore is not None and dir_ignore.match_file(dirname + "/"):+ return True+ return False++ # ------------------------------------------------------------------+ # Internal: FileInfo construction+ # ------------------------------------------------------------------++ def _build_file_info(self, abs_path: Path) -> FileInfo | None:+ try:+ stat = abs_path.stat()+ except OSError:+ return None++ size_bytes = stat.st_size+ rel_path = abs_path.relative_to(self.repo_root)+ rel_str = rel_path.as_posix()++ # Size limit+ if size_bytes > self.max_file_size_bytes:+ with self._count_lock:+ self._oversized_skip_count += 1+ return None++ # Blocked extension+ if abs_path.suffix.lower() in _BLOCKED_EXTENSIONS:+ return None++ # gitignore / extra ignore / extra exclude patterns+ if self._gitignore.match_file(rel_str):+ return None+ if self._extra_ignore.match_file(rel_str):+ return None+ if self._extra_exclude.match_file(rel_str):+ return None+ # Per-directory .wikicodeIgnore: check filename against the parent dir's spec.+ dir_ignore = self._get_dir_ignore(abs_path.parent)+ if dir_ignore.match_file(abs_path.name):+ return None++ # Blocklist filename patterns+ if self._blocked_patterns.match_file(rel_str):+ return None++ # Language detection — name/extension lookup is free (no I/O). Only+ # fall through to binary detection + shebang when the extension is+ # unrecognised, avoiding an 8 KB read for every .py/.ts/.go/… file.+ language = _language_from_name_or_ext(abs_path)+ if language is None:+ if _is_binary(abs_path):+ return None+ language = _detect_by_shebang(abs_path)+ if language == "unknown":+ return None++ # Generated file detection: only meaningful for code files. Skipping+ # for data/markup files avoids a 512-byte read per file with no benefit.+ if language not in _SKIP_GENERATED_CHECK and _is_generated(abs_path):+ log.debug("Skipping generated file", path=rel_str)+ return None++ filename = abs_path.name+ return FileInfo(+ path=rel_str,+ abs_path=str(abs_path),+ language=language,+ size_bytes=size_bytes,+ git_hash="",+ last_modified=datetime.fromtimestamp(stat.st_mtime),+ is_test=_is_test_file(rel_str, filename),+ is_config=_is_config_file(language),+ is_api_contract=_is_api_contract(abs_path, language),+ is_entry_point=filename in _ENTRY_POINT_NAMES or _stem_is_entry_point(abs_path),+ )++ # ------------------------------------------------------------------+ # Internal: monorepo detection+ # ------------------------------------------------------------------++ def _detect_monorepo(self) -> tuple[list[PackageInfo], bool]:+ """Detect package sub-directories by looking for manifest files."""+ packages: list[PackageInfo] = []+ seen_paths: set[str] = set()++ for depth in (1, 2):+ pattern = "/".join(["*"] * depth) + "/*"+ for candidate in self.repo_root.glob(pattern):+ if candidate.name not in _MANIFEST_FILES:+ continue+ pkg_dir = candidate.parent+ rel_pkg = pkg_dir.relative_to(self.repo_root).as_posix()+ if rel_pkg in seen_paths:+ continue+ seen_paths.add(rel_pkg)+ lang = _primary_language_in(pkg_dir)+ entry_pts = _find_entry_points_in(pkg_dir, self.repo_root)+ packages.append(+ PackageInfo(+ name=pkg_dir.name,+ path=rel_pkg,+ language=lang,+ entry_points=entry_pts,+ manifest_file=candidate.name,+ )+ )++ packages.sort(key=lambda p: p.path)+ return packages, len(packages) > 1+++# ---------------------------------------------------------------------------+# Module-level helpers+# ---------------------------------------------------------------------------+++def _language_from_name_or_ext(abs_path: Path) -> LanguageTag | None:+ """Return language from filename or extension alone — zero file I/O.++ Returns None when the extension is not recognised, signalling that the+ caller should fall back to binary detection and shebang sniffing.+ """+ filename = abs_path.name+ if filename in SPECIAL_FILENAMES:+ return SPECIAL_FILENAMES[filename]+ return EXTENSION_TO_LANGUAGE.get(abs_path.suffix.lower())+++def _detect_language(abs_path: Path) -> LanguageTag:+ """Detect the language of a file from name, extension, or shebang."""+ lang = _language_from_name_or_ext(abs_path)+ if lang is not None:+ return lang+ return _detect_by_shebang(abs_path)+++def _detect_by_shebang(abs_path: Path) -> LanguageTag:+ try:+ with open(abs_path, "r", encoding="utf-8", errors="ignore") as f:+ first_line = f.readline(200)+ if not first_line.startswith("#!"):+ return "unknown"+ if "python" in first_line:+ return "python"+ if "node" in first_line:+ return "javascript"+ if "bash" in first_line or " sh" in first_line:+ return "shell"+ if "ruby" in first_line:+ return "ruby"+ except OSError:+ pass+ return "unknown"+++def _is_binary(abs_path: Path) -> bool:+ """Return True if the file contains null bytes in the first 8 KB."""+ try:+ with open(abs_path, "rb") as f:+ return b"\x00" in f.read(8192)+ except OSError:+ return True+++def _is_generated(abs_path: Path) -> bool:+ """Return True if the file appears to be auto-generated."""+ name = abs_path.name+ if any(name.endswith(sfx) for sfx in _GENERATED_SUFFIXES):+ return True+ try:+ with open(abs_path, "r", encoding="utf-8", errors="ignore") as f:+ header = f.read(512)+ header_upper = header.upper()+ return any(marker.upper() in header_upper for marker in _GENERATED_MARKERS)+ except OSError:+ return False+++def _is_test_file(rel_path: str, filename: str) -> bool:+ stem = Path(filename).stem.lower()+ if stem.startswith("test_") or stem.endswith("_test"):+ return True+ if stem.startswith("spec_") or stem.endswith("_spec"):+ return True+ path_lower = rel_path.lower()+ return "/test/" in path_lower or "/tests/" in path_lower or "/spec/" in path_lower+++def _is_config_file(language: LanguageTag) -> bool:+ return language in ("yaml", "toml", "json", "dockerfile", "makefile")+++def _is_api_contract(abs_path: Path, language: LanguageTag) -> bool:+ if language in ("proto", "graphql"):+ return True+ name_lower = abs_path.name.lower()+ return any(+ marker in name_lower+ for marker in ("openapi", "swagger", "schema.graphql", "api.yaml", "api.json")+ )+++def _stem_is_entry_point(abs_path: Path) -> bool:+ stem = abs_path.stem.lower()+ return stem in _ENTRY_POINT_STEMS+++def _primary_language_in(directory: Path) -> LanguageTag:+ counts: dict[str, int] = {}+ try:+ for item in directory.rglob("*"):+ if item.is_file():+ lang = _detect_language(item)+ if lang not in ("unknown", "yaml", "json", "markdown", "toml"):+ counts[lang] = counts.get(lang, 0) + 1+ except OSError:+ pass+ if not counts:+ return "unknown"+ return max(counts, key=lambda k: counts[k]) # type: ignore[return-value]+++def _find_entry_points_in(directory: Path, repo_root: Path) -> list[str]:+ result: list[str] = []+ try:+ for item in directory.rglob("*"):+ if item.is_file() and item.name in _ENTRY_POINT_NAMES:+ result.append(item.relative_to(repo_root).as_posix())+ except OSError:+ pass+ return sorted(result)+++def _load_gitignore_spec(repo_root: Path) -> pathspec.PathSpec:+ gitignore = repo_root / ".gitignore"+ lines: list[str] = []+ if gitignore.exists():+ lines = gitignore.read_text(encoding="utf-8", errors="ignore").splitlines()+ return pathspec.PathSpec.from_lines("gitwildmatch", lines)+++def _load_extra_ignore_spec(repo_root: Path, filename: str) -> pathspec.PathSpec:+ ignore_file = repo_root / filename+ lines: list[str] = []+ if ignore_file.exists():+ lines = ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines()+ return pathspec.PathSpec.from_lines("gitwildmatch", lines)diff --git a/packages/core/src/wikicode/core/persistence/__init__.py b/packages/core/src/wikicode/core/persistence/__init__.pynew file mode 100644index 000000000..ac01411cd--- /dev/null+++ b/packages/core/src/wikicode/core/persistence/__init__.py@@ -0,0 +1,160 @@+"""WikiCode persistence layer.++Public API — import from here rather than sub-modules.++Backends+--------+SQLite (default)+ Uses ``aiosqlite`` for async I/O and SQLite FTS5 for full-text search.+ Vector embeddings are stored in :class:`InMemoryVectorStore` by default+ or :class:`LanceDBVectorStore` when the ``search`` extra is installed.++PostgreSQL+ Uses ``asyncpg`` and the ``pgvector`` extension. Install the+ ``pgvector`` extra: ``pip install wikicode-core[pgvector]``.+"""++from .crud import (+ batch_upsert_graph_edges,+ batch_upsert_graph_nodes,+ batch_upsert_symbols,+ bulk_upsert_decisions,+ delete_decision,+ get_all_git_metadata,+ get_dead_code_findings,+ get_dead_code_summary,+ get_decision,+ get_decision_health_summary,+ get_generation_job,+ get_git_metadata,+ get_git_metadata_bulk,+ get_page,+ get_page_versions,+ get_repository,+ get_repository_by_path,+ get_stale_decisions,+ get_stale_pages,+ list_decisions,+ list_pages,+ mark_webhook_processed,+ recompute_decision_staleness,+ save_dead_code_findings,+ store_webhook_event,+ update_dead_code_status,+ update_decision_status,+ update_job_status,+ upsert_decision,+ upsert_generation_job,+ upsert_git_metadata,+ upsert_git_metadata_bulk,+ upsert_page,+ upsert_page_from_generated,+ upsert_repository,+)+from .database import (+ AsyncEngine,+ AsyncSession,+ async_sessionmaker,+ create_engine,+ create_session_factory,+ get_db_url,+ get_session,+ init_db,+)+from .embedder import Embedder, MockEmbedder+from .models import (+ Base,+ DeadCodeFinding,+ DecisionRecord,+ GenerationJob,+ GitMetadata,+ GraphEdge,+ GraphNode,+ Page,+ PageVersion,+ Repository,+ WebhookEvent,+ WikiSymbol,+)+from .search import FullTextSearch, SearchResult+from .vector_store import (+ InMemoryVectorStore,+ LanceDBVectorStore,+ PgVectorStore,+ VectorStore,+)++__all__ = [+ # database+ "AsyncEngine",+ "AsyncSession",+ "async_sessionmaker",+ "get_db_url",+ "create_engine",+ "create_session_factory",+ "init_db",+ "get_session",+ # models+ "Base",+ "Repository",+ "GenerationJob",+ "Page",+ "PageVersion",+ "GraphNode",+ "GraphEdge",+ "WebhookEvent",+ "WikiSymbol",+ "GitMetadata",+ "DeadCodeFinding",+ "DecisionRecord",+ # crud+ "upsert_repository",+ "get_repository",+ "get_repository_by_path",+ "upsert_generation_job",+ "get_generation_job",+ "update_job_status",+ "upsert_page",+ "upsert_page_from_generated",+ "get_page",+ "list_pages",+ "get_page_versions",+ "get_stale_pages",+ "batch_upsert_graph_nodes",+ "batch_upsert_graph_edges",+ "batch_upsert_symbols",+ "store_webhook_event",+ "mark_webhook_processed",+ # git metadata crud+ "upsert_git_metadata",+ "get_git_metadata",+ "get_git_metadata_bulk",+ "get_all_git_metadata",+ "upsert_git_metadata_bulk",+ # dead code crud+ "save_dead_code_findings",+ "get_dead_code_findings",+ "update_dead_code_status",+ "get_dead_code_summary",+ # decision crud+ "upsert_decision",+ "get_decision",+ "list_decisions",+ "update_decision_status",+ "delete_decision",+ "bulk_upsert_decisions",+ "recompute_decision_staleness",+ "get_stale_decisions",+ "get_decision_health_summary",+ # embedder+ "Embedder",+ "MockEmbedder",+ # vector store+ "VectorStore",+ "InMemoryVectorStore",+ "LanceDBVectorStore",+ "PgVectorStore",+ # search+ "FullTextSearch",+ "SearchResult",+]diff --git a/packages/core/src/wikicode/core/persistence/crud.py b/packages/core/src/wikicode/core/persistence/crud.pynew file mode 100644index 000000000..931621a16--- /dev/null+++ b/packages/core/src/wikicode/core/persistence/crud.py@@ -0,0 +1,1170 @@+"""Async CRUD operations for the WikiCode persistence layer.++All functions accept an AsyncSession as the first argument; the caller owns+transaction boundaries. Functions that complete a logical unit of work call+``await session.flush()`` to write changes to the transaction buffer — the+caller must ``await session.commit()`` (or use the ``get_session`` context+manager from database.py).++Versioning contract for upsert_page:+ First upsert → inserts Page (version=1). No PageVersion created.+ Second upsert → archives existing Page as PageVersion, then updates Page+ in place (version increments). created_at is preserved.+"""++from __future__ import annotations++import json+from datetime import datetime, timezone++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from .models import (+ DeadCodeFinding,+ DecisionRecord,+ GenerationJob,+ GitMetadata,+ GraphEdge,+ GraphNode,+ Page,+ PageVersion,+ Repository,+ WebhookEvent,+ WikiSymbol,+ _new_uuid,+ _now_utc,+)++# ---------------------------------------------------------------------------+# Internal helpers+# ---------------------------------------------------------------------------++_VALID_JOB_STATUSES = frozenset({"pending", "running", "completed", "failed", "paused"})++_BATCH_SIZE = 500 # max rows per INSERT to stay under SQLite's parameter limit+++def _parse_dt(ts: str) -> datetime:+ """Parse an ISO-8601 UTC string to a timezone-aware datetime."""+ ts = ts.replace("Z", "+00:00")+ dt = datetime.fromisoformat(ts)+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return dt+++# ---------------------------------------------------------------------------+# Repository CRUD+# ---------------------------------------------------------------------------+++async def upsert_repository(+ session: AsyncSession,+ *,+ name: str,+ local_path: str,+ url: str = "",+ default_branch: str = "main",+ settings: dict | None = None,+) -> Repository:+ """Create or update a repository record.++ Lookup is by ``local_path`` (the canonical key for local repositories).+ """+ result = await session.execute(+ select(Repository).where(Repository.local_path == local_path)+ )+ repo = result.scalar_one_or_none()++ if repo is None:+ repo = Repository(+ id=_new_uuid(),+ name=name,+ local_path=local_path,+ url=url,+ default_branch=default_branch,+ settings_json=json.dumps(settings or {}),+ )+ session.add(repo)+ else:+ repo.name = name+ repo.url = url+ repo.default_branch = default_branch+ if settings is not None:+ repo.settings_json = json.dumps(settings)+ repo.updated_at = _now_utc()++ await session.flush()+ return repo+++async def get_repository(session: AsyncSession, repo_id: str) -> Repository | None:+ """Return a Repository by primary key, or None."""+ return await session.get(Repository, repo_id)+++async def get_repository_by_path(+ session: AsyncSession, local_path: str+) -> Repository | None:+ """Return a Repository by local_path, or None."""+ result = await session.execute(+ select(Repository).where(Repository.local_path == local_path)+ )+ return result.scalar_one_or_none()+++# ---------------------------------------------------------------------------+# GenerationJob CRUD+# ---------------------------------------------------------------------------+++async def upsert_generation_job(+ session: AsyncSession,+ *,+ repository_id: str,+ status: str = "pending",+ provider_name: str = "",+ model_name: str = "",+ total_pages: int = 0,+ config: dict | None = None,+ job_id: str | None = None,+) -> GenerationJob:+ """Insert a new GenerationJob (jobs are append-only)."""+ job = GenerationJob(+ id=job_id or _new_uuid(),+ repository_id=repository_id,+ status=status,+ provider_name=provider_name,+ model_name=model_name,+ total_pages=total_pages,+ config_json=json.dumps(config or {}),+ )+ session.add(job)+ await session.flush()+ return job+++async def get_generation_job(session: AsyncSession, job_id: str) -> GenerationJob | None:+ """Return a GenerationJob by primary key, or None."""+ return await session.get(GenerationJob, job_id)+++async def update_job_status(+ session: AsyncSession,+ job_id: str,+ status: str,+ *,+ completed_pages: int | None = None,+ failed_pages: int | None = None,+ current_level: int | None = None,+ total_pages: int | None = None,+ error_message: str | None = None,+) -> GenerationJob:+ """Update the mutable fields of a GenerationJob.++ Raises:+ ValueError: If *status* is not a recognised value.+ LookupError: If *job_id* does not exist.+ """+ if status not in _VALID_JOB_STATUSES:+ raise ValueError(+ f"Unknown job status {status!r}. "+ f"Valid values: {sorted(_VALID_JOB_STATUSES)}"+ )++ job = await session.get(GenerationJob, job_id)+ if job is None:+ raise LookupError(f"No GenerationJob with id={job_id!r}")++ job.status = status+ job.updated_at = _now_utc()++ if completed_pages is not None:+ job.completed_pages = completed_pages+ if failed_pages is not None:+ job.failed_pages = failed_pages+ if current_level is not None:+ job.current_level = current_level+ if total_pages is not None:+ job.total_pages = total_pages+ if error_message is not None:+ job.error_message = error_message++ if status == "running" and job.started_at is None:+ job.started_at = _now_utc()+ if status in ("completed", "failed"):+ job.finished_at = _now_utc()++ await session.flush()+ return job+++# ---------------------------------------------------------------------------+# Page CRUD (with versioning)+# ---------------------------------------------------------------------------+++async def upsert_page(+ session: AsyncSession,+ *,+ page_id: str,+ repository_id: str,+ page_type: str,+ title: str,+ content: str,+ target_path: str,+ source_hash: str,+ model_name: str,+ provider_name: str,+ input_tokens: int = 0,+ output_tokens: int = 0,+ cached_tokens: int = 0,+ generation_level: int = 0,+ confidence: float = 1.0,+ freshness_status: str = "fresh",+ metadata: dict | None = None,+ created_at: datetime | None = None,+ updated_at: datetime | None = None,+) -> Page:+ """Insert or update a wiki page, creating a PageVersion snapshot on update.++ First call → inserts Page at version=1.+ Subsequent → archives the current Page as a PageVersion, then updates the+ Page in-place (version += 1, created_at preserved).+ """+ now = _now_utc()+ page_created_at = created_at or now+ page_updated_at = updated_at or now+ meta_json = json.dumps(metadata or {})++ existing_result = await session.execute(select(Page).where(Page.id == page_id))+ existing = existing_result.scalar_one_or_none()++ if existing is not None:+ # Archive the current state before overwriting+ snapshot = PageVersion(+ id=_new_uuid(),+ page_id=existing.id,+ repository_id=existing.repository_id,+ version=existing.version,+ page_type=existing.page_type,+ title=existing.title,+ content=existing.content,+ source_hash=existing.source_hash,+ model_name=existing.model_name,+ provider_name=existing.provider_name,+ input_tokens=existing.input_tokens,+ output_tokens=existing.output_tokens,+ confidence=existing.confidence,+ archived_at=now,+ )+ session.add(snapshot)++ # Update Page in place (preserves created_at)+ existing.page_type = page_type+ existing.title = title+ existing.content = content+ existing.target_path = target_path+ existing.source_hash = source_hash+ existing.model_name = model_name+ existing.provider_name = provider_name+ existing.input_tokens = input_tokens+ existing.output_tokens = output_tokens+ existing.cached_tokens = cached_tokens+ existing.generation_level = generation_level+ existing.version = existing.version + 1+ existing.confidence = confidence+ existing.freshness_status = freshness_status+ existing.metadata_json = meta_json+ existing.updated_at = page_updated_at++ await session.flush()+ return existing+ else:+ page = Page(+ id=page_id,+ repository_id=repository_id,+ page_type=page_type,+ title=title,+ content=content,+ target_path=target_path,+ source_hash=source_hash,+ model_name=model_name,+ provider_name=provider_name,+ input_tokens=input_tokens,+ output_tokens=output_tokens,+ cached_tokens=cached_tokens,+ generation_level=generation_level,+ version=1,+ confidence=confidence,+ freshness_status=freshness_status,+ metadata_json=meta_json,+ created_at=page_created_at,+ updated_at=page_updated_at,+ )+ session.add(page)+ await session.flush()+ return page+++async def upsert_page_from_generated(+ session: AsyncSession,+ generated_page: object, # wikicode.core.generation.models.GeneratedPage+ repository_id: str,+) -> "Page":+ """Convenience wrapper that unpacks a GeneratedPage dataclass.++ This keeps the CRUD layer independent of the generation models at the+ import level while still providing a clean API for callers that have a+ GeneratedPage in hand.+ """+ gp = generated_page # type alias for brevity+ return await upsert_page(+ session,+ page_id=gp.page_id, # type: ignore[attr-defined]+ repository_id=repository_id,+ page_type=gp.page_type, # type: ignore[attr-defined]+ title=gp.title, # type: ignore[attr-defined]+ content=gp.content, # type: ignore[attr-defined]+ target_path=gp.target_path, # type: ignore[attr-defined]+ source_hash=gp.source_hash, # type: ignore[attr-defined]+ model_name=gp.model_name, # type: ignore[attr-defined]+ provider_name=gp.provider_name, # type: ignore[attr-defined]+ input_tokens=gp.input_tokens, # type: ignore[attr-defined]+ output_tokens=gp.output_tokens, # type: ignore[attr-defined]+ cached_tokens=gp.cached_tokens, # type: ignore[attr-defined]+ generation_level=gp.generation_level, # type: ignore[attr-defined]+ confidence=gp.confidence, # type: ignore[attr-defined]+ freshness_status=gp.freshness_status, # type: ignore[attr-defined]+ metadata=gp.metadata, # type: ignore[attr-defined]+ created_at=_parse_dt(gp.created_at), # type: ignore[attr-defined]+ updated_at=_parse_dt(gp.updated_at), # type: ignore[attr-defined]+ )+++async def get_page(session: AsyncSession, page_id: str) -> Page | None:+ """Return a Page by its page_id, or None."""+ return await session.get(Page, page_id)+++async def list_pages(+ session: AsyncSession,+ repository_id: str,+ *,+ page_type: str | None = None,+ limit: int = 100,+ offset: int = 0,+ sort_by: str = "updated_at",+ order: str = "desc",+) -> list[Page]:+ """Return pages for a repository, optionally filtered by page_type."""+ q = select(Page).where(Page.repository_id == repository_id)+ if page_type is not None:+ q = q.where(Page.page_type == page_type)+ _sort_cols = {+ "updated_at": Page.updated_at,+ "confidence": Page.confidence,+ "created_at": Page.created_at,+ }+ sort_col = _sort_cols.get(sort_by, Page.updated_at)+ q = q.order_by(sort_col.asc() if order == "asc" else sort_col.desc())+ q = q.limit(limit).offset(offset)+ result = await session.execute(q)+ return list(result.scalars().all())+++async def get_page_versions(+ session: AsyncSession,+ page_id: str,+ *,+ limit: int = 50,+) -> list[PageVersion]:+ """Return historical versions of a page, newest first."""+ result = await session.execute(+ select(PageVersion)+ .where(PageVersion.page_id == page_id)+ .order_by(PageVersion.version.desc())+ .limit(limit)+ )+ return list(result.scalars().all())+++async def get_stale_pages(+ session: AsyncSession,+ repository_id: str,+) -> list[Page]:+ """Return pages with freshness_status in ('stale', 'expired')."""+ result = await session.execute(+ select(Page).where(+ Page.repository_id == repository_id,+ Page.freshness_status.in_(["stale", "expired"]),+ )+ )+ return list(result.scalars().all())+++# ---------------------------------------------------------------------------+# Graph CRUD (batch)+# ---------------------------------------------------------------------------+++async def batch_upsert_graph_nodes(+ session: AsyncSession,+ repository_id: str,+ nodes: list[dict],+) -> None:+ """Upsert graph nodes for a repository in batches of up to 500.++ Each element of *nodes* is a dict with keys matching GraphNode fields+ (excluding id and repository_id which are set here).++ Uses SELECT-then-INSERT/UPDATE for dialect portability.+ """+ for node_data in nodes:+ node_id = node_data.get("node_id", "")+ result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repository_id,+ GraphNode.node_id == node_id,+ )+ )+ existing = result.scalar_one_or_none()++ if existing is not None:+ for key, val in node_data.items():+ if key not in ("id", "repository_id", "created_at") and hasattr(+ existing, key+ ):+ setattr(existing, key, val)+ else:+ session.add(+ GraphNode(+ id=_new_uuid(),+ repository_id=repository_id,+ **{+ k: v+ for k, v in node_data.items()+ if k not in ("id", "repository_id")+ },+ )+ )++ await session.flush()+++async def batch_upsert_graph_edges(+ session: AsyncSession,+ repository_id: str,+ edges: list[dict],+) -> None:+ """Upsert graph edges for a repository.++ Each element of *edges* should have ``source_node_id``, ``target_node_id``,+ and optionally ``imported_names_json``.+ """+ for edge_data in edges:+ source = edge_data.get("source_node_id", "")+ target = edge_data.get("target_node_id", "")+ result = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repository_id,+ GraphEdge.source_node_id == source,+ GraphEdge.target_node_id == target,+ )+ )+ existing = result.scalar_one_or_none()++ if existing is not None:+ imported = edge_data.get("imported_names_json")+ if imported is not None:+ existing.imported_names_json = imported+ else:+ session.add(+ GraphEdge(+ id=_new_uuid(),+ repository_id=repository_id,+ source_node_id=source,+ target_node_id=target,+ imported_names_json=edge_data.get("imported_names_json", "[]"),+ )+ )++ await session.flush()+++# ---------------------------------------------------------------------------+# WikiSymbol CRUD (batch)+# ---------------------------------------------------------------------------+++async def batch_upsert_symbols(+ session: AsyncSession,+ repository_id: str,+ symbols: list, # list[ingestion.models.Symbol]+) -> None:+ """Upsert ingestion Symbol objects into the wiki_symbols table.++ Accepts ingestion.models.Symbol dataclass instances (duck-typed).+ """+ for sym in symbols:+ symbol_id = getattr(sym, "id", None) or f"{sym.file_path}::{sym.name}"+ result = await session.execute(+ select(WikiSymbol).where(+ WikiSymbol.repository_id == repository_id,+ WikiSymbol.symbol_id == symbol_id,+ )+ )+ existing = result.scalar_one_or_none()++ if existing is not None:+ existing.name = sym.name+ existing.qualified_name = getattr(sym, "qualified_name", sym.name)+ existing.kind = sym.kind+ existing.signature = getattr(sym, "signature", "")+ existing.start_line = getattr(sym, "start_line", 0)+ existing.end_line = getattr(sym, "end_line", 0)+ existing.docstring = getattr(sym, "docstring", None)+ existing.visibility = getattr(sym, "visibility", "public")+ existing.is_async = getattr(sym, "is_async", False)+ existing.complexity_estimate = getattr(sym, "complexity_estimate", 0)+ existing.language = getattr(sym, "language", "")+ existing.parent_name = getattr(sym, "parent_name", None)+ existing.updated_at = _now_utc()+ else:+ session.add(+ WikiSymbol(+ id=_new_uuid(),+ repository_id=repository_id,+ file_path=getattr(sym, "file_path", ""),+ symbol_id=symbol_id,+ name=sym.name,+ qualified_name=getattr(sym, "qualified_name", sym.name),+ kind=sym.kind,+ signature=getattr(sym, "signature", ""),+ start_line=getattr(sym, "start_line", 0),+ end_line=getattr(sym, "end_line", 0),+ docstring=getattr(sym, "docstring", None),+ visibility=getattr(sym, "visibility", "public"),+ is_async=getattr(sym, "is_async", False),+ complexity_estimate=getattr(sym, "complexity_estimate", 0),+ language=getattr(sym, "language", ""),+ parent_name=getattr(sym, "parent_name", None),+ )+ )++ await session.flush()+++# ---------------------------------------------------------------------------+# WebhookEvent CRUD+# ---------------------------------------------------------------------------+++async def store_webhook_event(+ session: AsyncSession,+ *,+ provider: str,+ event_type: str,+ payload: dict,+ repository_id: str | None = None,+ delivery_id: str = "",+) -> WebhookEvent:+ """Append a new WebhookEvent record."""+ event = WebhookEvent(+ id=_new_uuid(),+ repository_id=repository_id,+ provider=provider,+ event_type=event_type,+ delivery_id=delivery_id,+ payload_json=json.dumps(payload),+ processed=False,+ )+ session.add(event)+ await session.flush()+ return event+++async def mark_webhook_processed(+ session: AsyncSession, event_id: str, *, job_id: str | None = None+) -> None:+ """Mark a WebhookEvent as processed and optionally link it to a job."""+ event = await session.get(WebhookEvent, event_id)+ if event is None:+ raise LookupError(f"No WebhookEvent with id={event_id!r}")+ event.processed = True+ if job_id is not None:+ event.job_id = job_id+ await session.flush()+++# ---------------------------------------------------------------------------+# GitMetadata CRUD+# ---------------------------------------------------------------------------+++async def upsert_git_metadata(+ session: AsyncSession,+ *,+ repository_id: str,+ file_path: str,+ **kwargs: object,+) -> GitMetadata:+ """Create or update a single GitMetadata row."""+ result = await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == repository_id,+ GitMetadata.file_path == file_path,+ )+ )+ existing = result.scalar_one_or_none()++ if existing is not None:+ for key, val in kwargs.items():+ if hasattr(existing, key):+ setattr(existing, key, val)+ existing.updated_at = _now_utc()+ else:+ existing = GitMetadata(+ id=_new_uuid(),+ repository_id=repository_id,+ file_path=file_path,+ **{k: v for k, v in kwargs.items() if hasattr(GitMetadata, k)},+ )+ session.add(existing)++ await session.flush()+ return existing+++async def get_git_metadata(+ session: AsyncSession, repository_id: str, file_path: str+) -> GitMetadata | None:+ """Return GitMetadata for a specific file, or None."""+ result = await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == repository_id,+ GitMetadata.file_path == file_path,+ )+ )+ return result.scalar_one_or_none()+++async def get_git_metadata_bulk(+ session: AsyncSession, repository_id: str, file_paths: list[str]+) -> dict[str, GitMetadata]:+ """Return a dict of file_path → GitMetadata for the given paths."""+ if not file_paths:+ return {}+ result = await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == repository_id,+ GitMetadata.file_path.in_(file_paths),+ )+ )+ return {gm.file_path: gm for gm in result.scalars().all()}+++async def get_all_git_metadata(+ session: AsyncSession, repository_id: str+) -> dict[str, GitMetadata]:+ """Return all GitMetadata rows for a repository."""+ result = await session.execute(+ select(GitMetadata).where(GitMetadata.repository_id == repository_id)+ )+ return {gm.file_path: gm for gm in result.scalars().all()}+++async def upsert_git_metadata_bulk(+ session: AsyncSession,+ repository_id: str,+ metadata_list: list[dict],+) -> None:+ """Bulk upsert git metadata rows in batches."""+ for i in range(0, len(metadata_list), _BATCH_SIZE):+ batch = metadata_list[i : i + _BATCH_SIZE]+ for meta in batch:+ file_path = meta.get("file_path", "")+ result = await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == repository_id,+ GitMetadata.file_path == file_path,+ )+ )+ existing = result.scalar_one_or_none()++ if existing is not None:+ for key, val in meta.items():+ if key not in ("id", "repository_id") and hasattr(existing, key):+ setattr(existing, key, val)+ existing.updated_at = _now_utc()+ else:+ session.add(+ GitMetadata(+ id=_new_uuid(),+ repository_id=repository_id,+ **{+ k: v+ for k, v in meta.items()+ if k not in ("id", "repository_id") and hasattr(GitMetadata, k)+ },+ )+ )+ await session.flush()+++# ---------------------------------------------------------------------------+# DeadCodeFinding CRUD+# ---------------------------------------------------------------------------+++async def save_dead_code_findings(+ session: AsyncSession,+ repository_id: str,+ findings: list[dict],+) -> None:+ """Persist dead code findings, replacing any existing open findings for the repo."""+ # Delete existing open findings for this repo before saving new ones+ existing = await session.execute(+ select(DeadCodeFinding).where(+ DeadCodeFinding.repository_id == repository_id,+ DeadCodeFinding.status == "open",+ )+ )+ for row in existing.scalars().all():+ await session.delete(row)++ for i in range(0, len(findings), _BATCH_SIZE):+ batch = findings[i : i + _BATCH_SIZE]+ for finding in batch:+ # Accept both DeadCodeFindingData-like objects and plain dicts+ if hasattr(finding, "kind"):+ data = {+ "kind": str(finding.kind.value) if hasattr(finding.kind, "value") else str(finding.kind),+ "file_path": finding.file_path,+ "symbol_name": finding.symbol_name,+ "symbol_kind": finding.symbol_kind,+ "confidence": finding.confidence,+ "reason": finding.reason,+ "last_commit_at": finding.last_commit_at,+ "commit_count_90d": finding.commit_count_90d,+ "lines": finding.lines,+ "package": finding.package,+ "evidence_json": json.dumps(finding.evidence if hasattr(finding, "evidence") else []),+ "safe_to_delete": finding.safe_to_delete,+ "primary_owner": finding.primary_owner,+ "age_days": finding.age_days,+ }+ else:+ data = dict(finding)+ if "evidence" in data:+ data["evidence_json"] = json.dumps(data.pop("evidence"))++ session.add(+ DeadCodeFinding(+ id=_new_uuid(),+ repository_id=repository_id,+ **{+ k: v+ for k, v in data.items()+ if k not in ("id", "repository_id") and hasattr(DeadCodeFinding, k)+ },+ )+ )+ await session.flush()+++async def get_dead_code_findings(+ session: AsyncSession,+ repository_id: str,+ *,+ kind: str | None = None,+ min_confidence: float = 0.0,+ status: str = "open",+) -> list[DeadCodeFinding]:+ """Return dead code findings filtered by kind, confidence, and status."""+ q = select(DeadCodeFinding).where(+ DeadCodeFinding.repository_id == repository_id,+ DeadCodeFinding.status == status,+ DeadCodeFinding.confidence >= min_confidence,+ )+ if kind is not None:+ q = q.where(DeadCodeFinding.kind == kind)+ q = q.order_by(DeadCodeFinding.confidence.desc())+ result = await session.execute(q)+ return list(result.scalars().all())+++async def update_dead_code_status(+ session: AsyncSession,+ finding_id: str,+ status: str,+ note: str | None = None,+) -> DeadCodeFinding | None:+ """Update the status (and optional note) of a dead code finding."""+ finding = await session.get(DeadCodeFinding, finding_id)+ if finding is None:+ return None+ finding.status = status+ if note is not None:+ finding.note = note+ await session.flush()+ return finding+++async def get_dead_code_summary(+ session: AsyncSession, repository_id: str+) -> dict:+ """Return aggregate dead code statistics."""+ result = await session.execute(+ select(DeadCodeFinding).where(+ DeadCodeFinding.repository_id == repository_id,+ DeadCodeFinding.status == "open",+ )+ )+ findings = list(result.scalars().all())++ summary: dict[str, int] = {"high": 0, "medium": 0, "low": 0}+ total_lines = 0+ by_kind: dict[str, int] = {}++ for f in findings:+ if f.confidence >= 0.7:+ summary["high"] += 1+ elif f.confidence >= 0.4:+ summary["medium"] += 1+ else:+ summary["low"] += 1+ total_lines += f.lines+ by_kind[f.kind] = by_kind.get(f.kind, 0) + 1++ return {+ "total_findings": len(findings),+ "confidence_summary": summary,+ "deletable_lines": sum(f.lines for f in findings if f.safe_to_delete),+ "total_lines": total_lines,+ "by_kind": by_kind,+ }+++# ---------------------------------------------------------------------------+# DecisionRecord CRUD+# ---------------------------------------------------------------------------++_VALID_DECISION_STATUSES = frozenset({"proposed", "active", "deprecated", "superseded"})+++async def upsert_decision(+ session: AsyncSession,+ *,+ repository_id: str,+ title: str,+ status: str = "proposed",+ context: str = "",+ decision: str = "",+ rationale: str = "",+ alternatives: list[str] | None = None,+ consequences: list[str] | None = None,+ affected_files: list[str] | None = None,+ affected_modules: list[str] | None = None,+ tags: list[str] | None = None,+ source: str = "cli",+ evidence_commits: list[str] | None = None,+ evidence_file: str | None = None,+ evidence_line: int | None = None,+ confidence: float = 1.0,+ last_code_change: datetime | None = None,+ staleness_score: float = 0.0,+ superseded_by: str | None = None,+ decision_id: str | None = None,+) -> DecisionRecord:+ """Create or update a decision record.++ Dedup key: ``(repository_id, title, source, evidence_file)``.+ """+ # Build the WHERE clause — evidence_file may be NULL+ q = select(DecisionRecord).where(+ DecisionRecord.repository_id == repository_id,+ DecisionRecord.title == title,+ DecisionRecord.source == source,+ )+ if evidence_file is not None:+ q = q.where(DecisionRecord.evidence_file == evidence_file)+ else:+ q = q.where(DecisionRecord.evidence_file.is_(None))++ result = await session.execute(q)+ existing = result.scalar_one_or_none()++ if existing is not None:+ existing.status = status+ existing.context = context+ existing.decision = decision+ existing.rationale = rationale+ existing.alternatives_json = json.dumps(alternatives or [])+ existing.consequences_json = json.dumps(consequences or [])+ existing.affected_files_json = json.dumps(affected_files or [])+ existing.affected_modules_json = json.dumps(affected_modules or [])+ existing.tags_json = json.dumps(tags or [])+ existing.evidence_commits_json = json.dumps(evidence_commits or [])+ existing.evidence_line = evidence_line+ existing.confidence = confidence+ existing.last_code_change = last_code_change+ existing.staleness_score = staleness_score+ existing.superseded_by = superseded_by+ existing.updated_at = _now_utc()+ await session.flush()+ return existing++ rec = DecisionRecord(+ id=decision_id or _new_uuid(),+ repository_id=repository_id,+ title=title,+ status=status,+ context=context,+ decision=decision,+ rationale=rationale,+ alternatives_json=json.dumps(alternatives or []),+ consequences_json=json.dumps(consequences or []),+ affected_files_json=json.dumps(affected_files or []),+ affected_modules_json=json.dumps(affected_modules or []),+ tags_json=json.dumps(tags or []),+ evidence_commits_json=json.dumps(evidence_commits or []),+ source=source,+ evidence_file=evidence_file,+ evidence_line=evidence_line,+ confidence=confidence,+ last_code_change=last_code_change,+ staleness_score=staleness_score,+ superseded_by=superseded_by,+ )+ session.add(rec)+ await session.flush()+ return rec+++async def get_decision(+ session: AsyncSession, decision_id: str+) -> DecisionRecord | None:+ """Return a DecisionRecord by primary key, or None."""+ return await session.get(DecisionRecord, decision_id)+++async def list_decisions(+ session: AsyncSession,+ repository_id: str,+ *,+ status: str | None = None,+ source: str | None = None,+ tag: str | None = None,+ module: str | None = None,+ include_proposed: bool = True,+ limit: int = 100,+ offset: int = 0,+) -> list[DecisionRecord]:+ """Return decision records with optional filters."""+ q = select(DecisionRecord).where(+ DecisionRecord.repository_id == repository_id+ )+ if status is not None:+ q = q.where(DecisionRecord.status == status)+ elif not include_proposed:+ q = q.where(DecisionRecord.status != "proposed")+ if source is not None:+ q = q.where(DecisionRecord.source == source)+ if tag is not None:+ q = q.where(DecisionRecord.tags_json.contains(tag))+ if module is not None:+ q = q.where(DecisionRecord.affected_modules_json.contains(module))+ q = q.order_by(DecisionRecord.created_at.desc()).limit(limit).offset(offset)+ result = await session.execute(q)+ return list(result.scalars().all())+++async def update_decision_status(+ session: AsyncSession,+ decision_id: str,+ status: str,+ *,+ superseded_by: str | None = None,+) -> DecisionRecord | None:+ """Update the status of a decision record.++ Raises ValueError for invalid statuses. Returns None if not found.+ """+ if status not in _VALID_DECISION_STATUSES:+ raise ValueError(+ f"Unknown decision status {status!r}. "+ f"Valid values: {sorted(_VALID_DECISION_STATUSES)}"+ )+ rec = await session.get(DecisionRecord, decision_id)+ if rec is None:+ return None+ rec.status = status+ if superseded_by is not None:+ rec.superseded_by = superseded_by+ rec.updated_at = _now_utc()+ await session.flush()+ return rec+++async def delete_decision(+ session: AsyncSession, decision_id: str+) -> bool:+ """Delete a decision record. Returns True if deleted, False if not found."""+ rec = await session.get(DecisionRecord, decision_id)+ if rec is None:+ return False+ await session.delete(rec)+ await session.flush()+ return True+++async def bulk_upsert_decisions(+ session: AsyncSession,+ repository_id: str,+ decisions: list[dict],+) -> None:+ """Bulk upsert decision records from a list of dicts."""+ for i in range(0, len(decisions), _BATCH_SIZE):+ batch = decisions[i : i + _BATCH_SIZE]+ for d in batch:+ await upsert_decision(+ session,+ repository_id=repository_id,+ title=d.get("title", ""),+ status=d.get("status", "proposed"),+ context=d.get("context", ""),+ decision=d.get("decision", ""),+ rationale=d.get("rationale", ""),+ alternatives=d.get("alternatives"),+ consequences=d.get("consequences"),+ affected_files=d.get("affected_files"),+ affected_modules=d.get("affected_modules"),+ tags=d.get("tags"),+ source=d.get("source", "cli"),+ evidence_commits=d.get("evidence_commits"),+ evidence_file=d.get("evidence_file"),+ evidence_line=d.get("evidence_line"),+ confidence=d.get("confidence", 1.0),+ staleness_score=d.get("staleness_score", 0.0),+ superseded_by=d.get("superseded_by"),+ )+++async def recompute_decision_staleness(+ session: AsyncSession,+ repository_id: str,+ git_meta_map: dict[str, dict],+) -> int:+ """Recompute staleness_score for all active decisions. Returns update count."""+ result = await session.execute(+ select(DecisionRecord).where(+ DecisionRecord.repository_id == repository_id,+ DecisionRecord.status.in_(["active", "proposed"]),+ )+ )+ decisions = list(result.scalars().all())++ now = _now_utc()+ updated = 0+ for dec in decisions:+ affected = json.loads(dec.affected_files_json)+ if not affected:+ continue++ scores: list[float] = []+ for fp in affected:+ meta = git_meta_map.get(fp)+ if meta is None:+ scores.append(1.0) # file deleted or not tracked+ continue+ last_commit = meta.get("last_commit_at")+ if last_commit and dec.created_at:+ # Parse if string+ if isinstance(last_commit, str):+ last_commit = datetime.fromisoformat(+ last_commit.replace("Z", "+00:00")+ )+ if last_commit > dec.created_at:+ age_days = (now - dec.created_at).days+ commit_count = meta.get("commit_count_90d", 0)+ file_score = min(1.0, commit_count / 15 * 0.7 + age_days / 365 * 0.3)+ scores.append(file_score)+ else:+ scores.append(0.0)+ else:+ scores.append(0.0)++ new_score = sum(scores) / len(scores) if scores else 0.0+ if abs(new_score - dec.staleness_score) > 0.01:+ dec.staleness_score = round(new_score, 3)+ dec.updated_at = now+ updated += 1++ if updated:+ await session.flush()+ return updated+++async def get_stale_decisions(+ session: AsyncSession,+ repository_id: str,+ threshold: float = 0.5,+) -> list[DecisionRecord]:+ """Return active decisions with staleness_score >= threshold."""+ result = await session.execute(+ select(DecisionRecord).where(+ DecisionRecord.repository_id == repository_id,+ DecisionRecord.status.in_(["active"]),+ DecisionRecord.staleness_score >= threshold,+ )+ )+ return list(result.scalars().all())+++async def get_decision_health_summary(+ session: AsyncSession,+ repository_id: str,+) -> dict:+ """Return decision health: counts by status, stale decisions, ungoverned hotspots."""+ result = await session.execute(+ select(DecisionRecord).where(+ DecisionRecord.repository_id == repository_id,+ )+ )+ all_decisions = list(result.scalars().all())++ counts = {"active": 0, "proposed": 0, "deprecated": 0, "superseded": 0, "stale": 0}+ stale_decisions: list[DecisionRecord] = []+ proposed_decisions: list[DecisionRecord] = []++ # Collect all governed files from active decisions+ governed_files: set[str] = set()+ for d in all_decisions:+ counts[d.status] = counts.get(d.status, 0) + 1+ if d.status == "active":+ if d.staleness_score >= 0.5:+ counts["stale"] += 1+ stale_decisions.append(d)+ for fp in json.loads(d.affected_files_json):+ governed_files.add(fp)+ elif d.status == "proposed":+ proposed_decisions.append(d)++ # Find ungoverned hotspots+ hotspot_result = await session.execute(+ select(GitMetadata.file_path).where(+ GitMetadata.repository_id == repository_id,+ GitMetadata.is_hotspot == True, # noqa: E712+ )+ )+ hotspot_files = {row[0] for row in hotspot_result.all()}+ ungoverned = sorted(hotspot_files - governed_files)++ return {+ "summary": counts,+ "stale_decisions": stale_decisions,+ "proposed_awaiting_review": proposed_decisions,+ "ungoverned_hotspots": ungoverned,+ }diff --git a/packages/core/src/wikicode/core/persistence/database.py b/packages/core/src/wikicode/core/persistence/database.pynew file mode 100644index 000000000..cd1611b78--- /dev/null+++ b/packages/core/src/wikicode/core/persistence/database.py@@ -0,0 +1,140 @@+"""Async database engine and session factory for WikiCode.++Supports two backends:+- SQLite (default): sqlite+aiosqlite:///path/to/file.db+- PostgreSQL: postgresql+asyncpg://user:pass@host/dbname++Call get_db_url() to normalise raw URLs (adds the async driver prefix).+Call create_engine() to create an AsyncEngine.+Call init_db() once at startup to create all tables and the FTS index.+"""++from __future__ import annotations++from contextlib import asynccontextmanager+from typing import AsyncGenerator++from sqlalchemy.ext.asyncio import (+ AsyncEngine,+ AsyncSession,+ async_sessionmaker,+ create_async_engine,+)+from sqlalchemy.pool import NullPool, StaticPool+from sqlalchemy.sql import text++from .models import Base++__all__ = [+ "AsyncEngine",+ "AsyncSession",+ "async_sessionmaker",+ "get_db_url",+ "create_engine",+ "create_session_factory",+ "init_db",+ "get_session",+]++_DEFAULT_URL = "sqlite+aiosqlite:///.wikicode/wiki.db"+++def get_db_url(raw_url: str | None = None) -> str:+ """Normalise a database URL to include the async driver prefix.++ - ``sqlite:///...`` → ``sqlite+aiosqlite:///...``+ - ``postgresql://...`` → ``postgresql+asyncpg://...``+ - ``postgresql+psycopg://...`` → unchanged (explicit driver wins)+ - Already async-prefixed URLs are returned as-is.+ - ``None`` → default SQLite path: ``sqlite+aiosqlite:///.wikicode/wiki.db``+ """+ if raw_url is None:+ return _DEFAULT_URL++ url = raw_url.strip()++ if url.startswith("sqlite://") and "aiosqlite" not in url:+ return url.replace("sqlite://", "sqlite+aiosqlite://", 1)++ if url.startswith("postgresql://") or url.startswith("postgres://"):+ return url.replace("://", "+asyncpg://", 1)++ return url+++def create_engine(+ url: str | None = None,+ *,+ echo: bool = False,+ # StaticPool is required for :memory: SQLite so all connections share the same DB.+ # Pass use_static_pool=True explicitly when creating in-memory test engines.+ use_static_pool: bool = False,+) -> AsyncEngine:+ """Create an AsyncEngine for the given database URL.++ Args:+ url: Raw or async-prefixed database URL. Defaults to SQLite.+ echo: Log all SQL statements (useful for debugging).+ use_static_pool: Force StaticPool (required for in-memory SQLite tests).+ """+ db_url = get_db_url(url)+ is_sqlite = db_url.startswith("sqlite")++ kwargs: dict = {"echo": echo}++ if is_sqlite:+ # SQLite requires check_same_thread=False for multi-threaded async use+ kwargs["connect_args"] = {"check_same_thread": False}+ if use_static_pool or ":memory:" in db_url:+ # StaticPool: all connect() calls return the same connection.+ # Mandatory for in-memory SQLite — without it each call gets a fresh DB.+ kwargs["poolclass"] = StaticPool+ else:+ kwargs["poolclass"] = NullPool+ else:+ # PostgreSQL — asyncpg handles its own connection pool+ kwargs["pool_pre_ping"] = True++ return create_async_engine(db_url, **kwargs)+++def create_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:+ """Return an async_sessionmaker bound to *engine*.++ expire_on_commit=False: prevents SQLAlchemy from expiring attributes after+ commit, which would require a sync lazy-load (impossible in async context).+ """+ return async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)+++@asynccontextmanager+async def get_session(+ session_factory: async_sessionmaker[AsyncSession],+) -> AsyncGenerator[AsyncSession, None]:+ """Async context manager that yields a session and handles commit/rollback."""+ async with session_factory() as session:+ try:+ yield session+ await session.commit()+ except Exception:+ await session.rollback()+ raise+++async def init_db(engine: AsyncEngine) -> None:+ """Create all SQLAlchemy tables and the FTS index for the given engine.++ Safe to call on an already-initialised database (idempotent).+ """+ async with engine.begin() as conn:+ await conn.run_sync(Base.metadata.create_all)++ # SQLite-only: create FTS5 virtual table for full-text search.+ # PostgreSQL uses a GIN index added by the Alembic migration.+ if engine.dialect.name == "sqlite":+ await conn.execute(+ text(+ "CREATE VIRTUAL TABLE IF NOT EXISTS page_fts "+ "USING fts5(page_id UNINDEXED, title, content)"+ )+ )diff --git a/packages/core/src/wikicode/core/persistence/embedder.py b/packages/core/src/wikicode/core/persistence/embedder.pynew file mode 100644index 000000000..0b94004fc--- /dev/null+++ b/packages/core/src/wikicode/core/persistence/embedder.py@@ -0,0 +1,74 @@+"""Embedder protocol and implementations for WikiCode vector search.++The Embedder protocol is structural (runtime_checkable) so any object with+an `embed()` method and a `dimensions` property satisfies it without+inheriting from a base class.++MockEmbedder is the built-in test implementation: deterministic, 8-dimensional,+zero external dependencies.+"""++from __future__ import annotations++import hashlib+import math+import struct+from typing import Protocol, runtime_checkable+++@runtime_checkable+class Embedder(Protocol):+ """Structural protocol for text embedding models.++ All implementations must produce unit-length (L2-normalized) vectors so+ that cosine similarity equals the dot product — important for InMemoryVectorStore+ and pgvector's <=> operator (which uses cosine distance by default).+ """++ @property+ def dimensions(self) -> int:+ """Number of dimensions in the embedding vector."""+ ...++ async def embed(self, texts: list[str]) -> list[list[float]]:+ """Embed a batch of texts.++ Args:+ texts: Non-empty list of strings to embed.++ Returns:+ List of unit-length float vectors, one per input string.+ Each vector has exactly ``self.dimensions`` elements.+ """+ ...+++class MockEmbedder:+ """Deterministic 8-dimensional embedder for testing.++ Uses the first 8 bytes of SHA-256(text) interpreted as 8 unsigned bytes,+ divided by 255.0, then L2-normalised to unit length.++ Properties:+ - Deterministic: same input always produces the same vector.+ - Different texts virtually always produce different vectors (hash collision+ probability negligible for test inputs).+ - All output vectors have unit L2 norm (cosine similarity = dot product).+ - Zero external dependencies.+ """++ dimensions: int = 8++ async def embed(self, texts: list[str]) -> list[list[float]]:+ results: list[list[float]] = []+ for text in texts:+ digest = hashlib.sha256(text.encode()).digest()+ # Take first 8 bytes as raw floats via struct unpack+ # (4 bytes each → 2 float32 values would only give 2 dims)+ # Instead: use 8 unsigned bytes normalised to [0, 1]+ raw = [digest[i] / 255.0 for i in range(8)]+ norm = math.sqrt(sum(x * x for x in raw))+ if norm == 0.0:+ norm = 1.0+ results.append([x / norm for x in raw])+ return resultsdiff --git a/packages/core/src/wikicode/core/persistence/gemini_embedder.py b/packages/core/src/wikicode/core/persistence/gemini_embedder.pynew file mode 100644index 000000000..9874d7e92--- /dev/null+++ b/packages/core/src/wikicode/core/persistence/gemini_embedder.py@@ -0,0 +1,107 @@+"""Gemini embedding support for WikiCode semantic search.++Uses the Google GenAI SDK (google-genai) with the gemini-embedding-001 model.+This embedder satisfies the Embedder protocol and can be passed to any+WikiCode vector store (InMemoryVectorStore, LanceDBVectorStore, PgVectorStore).++Installation:+ pip install google-genai++Usage:+ import asyncio+ from wikicode.core.persistence.gemini_embedder import GeminiEmbedder+ from wikicode.core.persistence.vector_store import InMemoryVectorStore++ embedder = GeminiEmbedder(api_key="AIza...")+ store = InMemoryVectorStore(embedder)+ await store.embed_and_upsert("page-1", "Some wiki content...", {})+ results = await store.search("auth service", limit=5)++Dimensions:+ gemini-embedding-001 produces 768-dimensional vectors by default.+ You can request up to 3072 dimensions via output_dimensionality.+"""++from __future__ import annotations++import asyncio+import math+import os+++class GeminiEmbedder:+ """Gemini embedding model adapter implementing the WikiCode Embedder protocol.++ Args:+ api_key: Google Gemini API key. Falls back to GEMINI_API_KEY env var.+ model: Embedding model name. Default: "gemini-embedding-001".+ task_type: Embedding task type. "SEMANTIC_SIMILARITY" is best for+ semantic search. Other options: "RETRIEVAL_DOCUMENT",+ "RETRIEVAL_QUERY", "CLUSTERING", "CLASSIFICATION".+ output_dimensionality: Override output vector size (default: 768, max: 3072).+ """++ def __init__(+ self,+ api_key: str | None = None,+ model: str = "gemini-embedding-001",+ task_type: str = "SEMANTIC_SIMILARITY",+ output_dimensionality: int = 768,+ ) -> None:+ self._api_key = api_key or os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")+ if not self._api_key:+ raise ValueError(+ "Gemini API key required. Pass api_key= or set GEMINI_API_KEY env var."+ )+ self._model = model+ self._task_type = task_type+ self._output_dimensionality = output_dimensionality++ @property+ def dimensions(self) -> int:+ return self._output_dimensionality++ async def embed(self, texts: list[str]) -> list[list[float]]:+ """Embed a batch of texts using Gemini.++ Runs the synchronous SDK call in a thread pool to avoid blocking the+ asyncio event loop.++ Args:+ texts: Non-empty list of strings to embed.++ Returns:+ List of unit-length (L2-normalized) float vectors.+ """+ if not texts:+ return []++ def _embed_sync() -> list[list[float]]:+ from google import genai # type: ignore[import-untyped]+ from google.genai import types as genai_types # type: ignore[import-untyped]++ client = genai.Client(api_key=self._api_key)++ config = genai_types.EmbedContentConfig(+ task_type=self._task_type,+ output_dimensionality=self._output_dimensionality,+ )++ result = client.models.embed_content(+ model=self._model,+ contents=texts,+ config=config,+ )++ raw_vectors = [list(e.values) for e in result.embeddings]+ return [_l2_normalize(v) for v in raw_vectors]++ return await asyncio.to_thread(_embed_sync)+++def _l2_normalize(vec: list[float]) -> list[float]:+ """L2-normalize a vector to unit length (cosine similarity = dot product)."""+ norm = math.sqrt(sum(x * x for x in vec))+ if norm == 0.0:+ norm = 1.0+ return [x / norm for x in vec]diff --git a/packages/core/src/wikicode/core/persistence/models.py b/packages/core/src/wikicode/core/persistence/models.pynew file mode 100644index 000000000..64dabd898--- /dev/null+++ b/packages/core/src/wikicode/core/persistence/models.py@@ -0,0 +1,402 @@+"""SQLAlchemy ORM models for WikiCode persistence layer.++All models use SQLAlchemy 2.0 declarative style with Mapped[] type annotations.+JSON blobs are stored as Text columns; the CRUD layer handles serialization.+The embedding column for pgvector is added conditionally by the Alembic migration+and is not declared here (keeps models dialect-neutral).++Note: the ORM symbol model is named WikiSymbol (not Symbol) to avoid shadowing+wikicode.core.ingestion.models.Symbol in files that import from both modules.+"""++from __future__ import annotations++from datetime import datetime, timezone+from uuid import uuid4++from sqlalchemy import (+ Boolean,+ DateTime,+ Float,+ ForeignKey,+ Integer,+ String,+ Text,+ UniqueConstraint,+)+from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column+++def _new_uuid() -> str:+ return uuid4().hex+++def _now_utc() -> datetime:+ return datetime.now(timezone.utc)+++class Base(DeclarativeBase):+ pass+++class Repository(Base):+ __tablename__ = "repositories"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ name: Mapped[str] = mapped_column(String(255), nullable=False)+ url: Mapped[str] = mapped_column(Text, nullable=False, default="")+ local_path: Mapped[str] = mapped_column(Text, nullable=False)+ default_branch: Mapped[str] = mapped_column(String(255), nullable=False, default="main")+ head_commit: Mapped[str | None] = mapped_column(String(40), nullable=True)+ settings_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )+++class GenerationJob(Base):+ __tablename__ = "generation_jobs"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ status: Mapped[str] = mapped_column(String(32), nullable=False, default="pending")+ provider_name: Mapped[str] = mapped_column(String(64), nullable=False, default="")+ model_name: Mapped[str] = mapped_column(String(128), nullable=False, default="")+ total_pages: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ completed_pages: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ failed_pages: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ current_level: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ error_message: Mapped[str | None] = mapped_column(Text, nullable=True)+ config_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )+ started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+++class Page(Base):+ """A generated wiki page.++ The primary key is page_id: "{page_type}:{target_path}" — same format as+ GeneratedPage.page_id. This is a natural key so callers can upsert without+ knowing the database row ID.+ """++ __tablename__ = "wiki_pages"++ id: Mapped[str] = mapped_column(Text, primary_key=True)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ page_type: Mapped[str] = mapped_column(String(64), nullable=False)+ title: Mapped[str] = mapped_column(Text, nullable=False)+ content: Mapped[str] = mapped_column(Text, nullable=False)+ target_path: Mapped[str] = mapped_column(Text, nullable=False)+ source_hash: Mapped[str] = mapped_column(String(64), nullable=False)+ model_name: Mapped[str] = mapped_column(String(128), nullable=False)+ provider_name: Mapped[str] = mapped_column(String(64), nullable=False)+ input_tokens: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ output_tokens: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ cached_tokens: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ generation_level: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ version: Mapped[int] = mapped_column(Integer, nullable=False, default=1)+ confidence: Mapped[float] = mapped_column(Float, nullable=False, default=1.0)+ 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="{}")+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)+++class PageVersion(Base):+ """Historical snapshot of a wiki page, created each time the page is re-generated."""++ __tablename__ = "wiki_page_versions"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ page_id: Mapped[str] = mapped_column(Text, ForeignKey("wiki_pages.id"), nullable=False)+ repository_id: Mapped[str] = mapped_column(String(32), nullable=False)+ version: Mapped[int] = mapped_column(Integer, nullable=False)+ page_type: Mapped[str] = mapped_column(String(64), nullable=False)+ title: Mapped[str] = mapped_column(Text, nullable=False)+ content: Mapped[str] = mapped_column(Text, nullable=False)+ source_hash: Mapped[str] = mapped_column(String(64), nullable=False)+ model_name: Mapped[str] = mapped_column(String(128), nullable=False)+ provider_name: Mapped[str] = mapped_column(String(64), nullable=False)+ input_tokens: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ output_tokens: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ confidence: Mapped[float] = mapped_column(Float, nullable=False, default=1.0)+ archived_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+++class GraphNode(Base):+ __tablename__ = "graph_nodes"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ # Relative file path (the logical node identifier within a repo)+ node_id: Mapped[str] = mapped_column(Text, nullable=False)+ node_type: Mapped[str] = mapped_column(String(32), nullable=False, default="file")+ language: Mapped[str] = mapped_column(String(32), nullable=False, default="")+ symbol_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ has_error: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ is_test: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ is_entry_point: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ pagerank: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ betweenness: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ community_id: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )++ __table_args__ = (+ UniqueConstraint("repository_id", "node_id", name="uq_graph_node"),+ )+++class GraphEdge(Base):+ __tablename__ = "graph_edges"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ source_node_id: Mapped[str] = mapped_column(Text, nullable=False)+ target_node_id: Mapped[str] = mapped_column(Text, nullable=False)+ imported_names_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )++ __table_args__ = (+ UniqueConstraint(+ "repository_id", "source_node_id", "target_node_id", name="uq_graph_edge"+ ),+ )+++class WebhookEvent(Base):+ __tablename__ = "webhook_events"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str | None] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="SET NULL"), nullable=True+ )+ provider: Mapped[str] = mapped_column(String(32), nullable=False)+ event_type: Mapped[str] = mapped_column(String(64), nullable=False)+ delivery_id: Mapped[str] = mapped_column(String(128), nullable=False, default="")+ payload_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+ processed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ job_id: Mapped[str | None] = mapped_column(+ String(32), ForeignKey("generation_jobs.id", ondelete="SET NULL"), nullable=True+ )+ received_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+++class WikiSymbol(Base):+ """ORM representation of a code symbol.++ Named WikiSymbol (not Symbol) to avoid shadowing+ wikicode.core.ingestion.models.Symbol in files that import both.+ """++ __tablename__ = "wiki_symbols"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ file_path: Mapped[str] = mapped_column(Text, nullable=False)+ # "{path}::{name}" — the ingestion Symbol.id field+ symbol_id: Mapped[str] = mapped_column(Text, nullable=False)+ name: Mapped[str] = mapped_column(String(255), nullable=False)+ qualified_name: Mapped[str] = mapped_column(Text, nullable=False)+ kind: Mapped[str] = mapped_column(String(32), nullable=False)+ signature: Mapped[str] = mapped_column(Text, nullable=False, default="")+ start_line: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ end_line: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ docstring: Mapped[str | None] = mapped_column(Text, nullable=True)+ visibility: Mapped[str] = mapped_column(String(16), nullable=False, default="public")+ is_async: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ complexity_estimate: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ language: Mapped[str] = mapped_column(String(32), nullable=False, default="")+ parent_name: Mapped[str | None] = mapped_column(String(255), nullable=True)+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )++ __table_args__ = (+ UniqueConstraint("repository_id", "symbol_id", name="uq_wiki_symbol"),+ )+++class GitMetadata(Base):+ """Per-file git history metadata: commit counts, ownership, co-change partners."""++ __tablename__ = "git_metadata"+ __table_args__ = (+ UniqueConstraint("repository_id", "file_path", name="uq_git_metadata"),+ )++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ file_path: Mapped[str] = mapped_column(Text, nullable=False)++ # Commit volume+ commit_count_total: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ commit_count_90d: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ commit_count_30d: Mapped[int] = mapped_column(Integer, nullable=False, default=0)++ # Timeline+ first_commit_at: Mapped[datetime | None] = mapped_column(+ DateTime(timezone=True), nullable=True+ )+ last_commit_at: Mapped[datetime | None] = mapped_column(+ DateTime(timezone=True), nullable=True+ )++ # Ownership+ primary_owner_name: Mapped[str | None] = mapped_column(String(255), nullable=True)+ primary_owner_email: Mapped[str | None] = mapped_column(String(255), nullable=True)+ primary_owner_commit_pct: Mapped[float | None] = mapped_column(Float, nullable=True)++ # JSON fields (stored as Text, parsed/serialized in CRUD layer)+ top_authors_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ significant_commits_json: Mapped[str] = mapped_column(+ Text, nullable=False, default="[]"+ )+ co_change_partners_json: Mapped[str] = mapped_column(+ Text, nullable=False, default="[]"+ )++ # Derived signals+ is_hotspot: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ is_stable: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ churn_percentile: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ age_days: Mapped[int] = mapped_column(Integer, nullable=False, default=0)++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )+++class DecisionRecord(Base):+ """An architectural decision record captured from inline markers, git+ archaeology, README mining, or manual CLI entry."""++ __tablename__ = "decision_records"+ __table_args__ = (+ UniqueConstraint(+ "repository_id", "title", "source", "evidence_file",+ name="uq_decision_record",+ ),+ )++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )++ # Core content+ title: Mapped[str] = mapped_column(Text, nullable=False)+ status: Mapped[str] = mapped_column(+ String(32), nullable=False, default="proposed"+ ) # proposed | active | deprecated | superseded+ context: Mapped[str] = mapped_column(Text, nullable=False, default="")+ decision: Mapped[str] = mapped_column(Text, nullable=False, default="")+ rationale: Mapped[str] = mapped_column(Text, nullable=False, default="")++ # JSON arrays stored as Text (same pattern as GitMetadata.*_json)+ alternatives_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ consequences_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ affected_files_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ affected_modules_json: Mapped[str] = mapped_column(+ Text, nullable=False, default="[]"+ )+ tags_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ evidence_commits_json: Mapped[str] = mapped_column(+ Text, nullable=False, default="[]"+ )++ # Provenance+ source: Mapped[str] = mapped_column(+ String(32), nullable=False, default="cli"+ ) # git_archaeology | inline_marker | readme_mining | cli+ evidence_file: Mapped[str | None] = mapped_column(Text, nullable=True)+ evidence_line: Mapped[int | None] = mapped_column(Integer, nullable=True)+ confidence: Mapped[float] = mapped_column(Float, nullable=False, default=1.0)++ # Staleness+ last_code_change: Mapped[datetime | None] = mapped_column(+ DateTime(timezone=True), nullable=True+ )+ staleness_score: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ superseded_by: Mapped[str | None] = mapped_column(String(32), nullable=True)++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )+++class DeadCodeFinding(Base):+ """Dead code finding: unreachable files, unused exports, zombie packages."""++ __tablename__ = "dead_code_findings"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ kind: Mapped[str] = mapped_column(+ String(32), nullable=False+ ) # unreachable_file, unused_export, etc.+ file_path: Mapped[str] = mapped_column(Text, nullable=False)+ symbol_name: Mapped[str | None] = mapped_column(String(255), nullable=True)+ symbol_kind: Mapped[str | None] = mapped_column(String(32), nullable=True)+ confidence: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ reason: Mapped[str] = mapped_column(Text, nullable=False, default="")+ last_commit_at: Mapped[datetime | None] = mapped_column(+ DateTime(timezone=True), nullable=True+ )+ commit_count_90d: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ lines: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ package: Mapped[str | None] = mapped_column(String(255), nullable=True)+ evidence_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ safe_to_delete: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ primary_owner: Mapped[str | None] = mapped_column(String(255), nullable=True)+ age_days: Mapped[int | None] = mapped_column(Integer, nullable=True)+ status: Mapped[str] = mapped_column(+ String(32), nullable=False, default="open"+ ) # open, acknowledged, resolved, false_positive+ note: Mapped[str | None] = mapped_column(Text, nullable=True)+ analyzed_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )diff --git a/packages/core/src/wikicode/core/persistence/openai_embedder.py b/packages/core/src/wikicode/core/persistence/openai_embedder.pynew file mode 100644index 000000000..a7d07f684--- /dev/null+++ b/packages/core/src/wikicode/core/persistence/openai_embedder.py@@ -0,0 +1,96 @@+"""OpenAI embedding support for WikiCode semantic search.++Uses the openai SDK with text-embedding-3-small by default (1536 dims).+Runs the synchronous SDK call in a thread pool to avoid blocking asyncio.++Installation:+ pip install openai++Usage:+ import asyncio+ from wikicode.core.persistence.openai_embedder import OpenAIEmbedder+ from wikicode.core.persistence.vector_store import InMemoryVectorStore++ embedder = OpenAIEmbedder(api_key="sk-...")+ store = InMemoryVectorStore(embedder)+ await store.embed_and_upsert("page-1", "Some wiki content...", {})+ results = await store.search("auth service", limit=5)++Dimensions:+ text-embedding-3-small → 1536 dims+ text-embedding-3-large → 3072 dims+ text-embedding-ada-002 → 1536 dims+"""++from __future__ import annotations++import asyncio+import math+import os+++class OpenAIEmbedder:+ """OpenAI embedding model adapter implementing the WikiCode Embedder protocol.++ Args:+ api_key: OpenAI API key. Falls back to OPENAI_API_KEY env var.+ model: Embedding model name. Default: "text-embedding-3-small".+ """++ _DIMS: dict[str, int] = {+ "text-embedding-3-small": 1536,+ "text-embedding-3-large": 3072,+ "text-embedding-ada-002": 1536,+ }++ def __init__(+ self,+ api_key: str | None = None,+ model: str = "text-embedding-3-small",+ ) -> None:+ self._api_key = api_key or os.environ.get("OPENAI_API_KEY")+ if not self._api_key:+ raise ValueError(+ "OpenAI API key required. Pass api_key= or set OPENAI_API_KEY env var."+ )+ self._model = model++ @property+ def dimensions(self) -> int:+ return self._DIMS.get(self._model, 1536)++ async def embed(self, texts: list[str]) -> list[list[float]]:+ """Embed a batch of texts using OpenAI.++ Runs the synchronous SDK call in a thread pool to avoid blocking the+ asyncio event loop.++ Args:+ texts: Non-empty list of strings to embed.++ Returns:+ List of L2-normalized float vectors.+ """+ if not texts:+ return []++ api_key = self._api_key+ model = self._model++ def _embed_sync() -> list[list[float]]:+ import openai # type: ignore[import-untyped]++ client = openai.OpenAI(api_key=api_key)+ response = client.embeddings.create(model=model, input=texts)+ raw_vectors = [list(item.embedding) for item in response.data]+ return [_l2_normalize(v) for v in raw_vectors]++ return await asyncio.to_thread(_embed_sync)+++def _l2_normalize(vec: list[float]) -> list[float]:+ """L2-normalize a vector to unit length (cosine similarity = dot product)."""+ norm = math.sqrt(sum(x * x for x in vec))+ if norm == 0.0:+ norm = 1.0+ return [x / norm for x in vec]diff --git a/packages/core/src/wikicode/core/persistence/search.py b/packages/core/src/wikicode/core/persistence/search.pynew file mode 100644index 000000000..f92147e51--- /dev/null+++ b/packages/core/src/wikicode/core/persistence/search.py@@ -0,0 +1,212 @@+"""Full-text search for WikiCode wiki pages.++Two backends:+- SQLite (default): FTS5 virtual table ``page_fts``.+- PostgreSQL: GIN index on ``to_tsvector('english', title || content)``.++The backend is detected automatically from the engine dialect.++Usage::++ fts = FullTextSearch(engine)+ await fts.ensure_index() # idempotent — safe to call at startup+ await fts.index("id", "Title", "content …")+ results = await fts.search("decorator pattern", limit=5)+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Literal++from sqlalchemy.ext.asyncio import AsyncEngine+from sqlalchemy.sql import text+++@dataclass+class SearchResult:+ """Unified result returned by vector search and full-text search."""++ page_id: str+ title: str+ page_type: str+ target_path: str+ score: float+ snippet: str+ search_type: Literal["vector", "fulltext"]+++_SNIPPET_LEN = 200+++def _snippet(content: str) -> str:+ return content[:_SNIPPET_LEN].rstrip()+++class FullTextSearch:+ """Full-text search backed by SQLite FTS5 or PostgreSQL tsvector."""++ def __init__(self, engine: AsyncEngine) -> None:+ self._engine = engine+ self._dialect = engine.dialect.name # "sqlite" or "postgresql"++ async def ensure_index(self) -> None:+ """Create the FTS index if it does not exist (idempotent).++ For SQLite the FTS5 table is created here.+ For PostgreSQL the GIN index is created by the Alembic migration; this+ method is a no-op in that case.+ """+ if self._dialect == "sqlite":+ async with self._engine.begin() as conn:+ await conn.execute(+ text(+ "CREATE VIRTUAL TABLE IF NOT EXISTS page_fts "+ "USING fts5(page_id UNINDEXED, title, content)"+ )+ )+ elif self._dialect == "postgresql":+ async with self._engine.begin() as conn:+ await conn.execute(+ text(+ "CREATE INDEX IF NOT EXISTS idx_wiki_pages_fts "+ "ON wiki_pages USING GIN("+ " to_tsvector('english', COALESCE(title, '') || ' ' || COALESCE(content, ''))"+ ")"+ )+ )++ async def index(self, page_id: str, title: str, content: str) -> None:+ """Add or replace a page in the FTS index."""+ if self._dialect == "sqlite":+ async with self._engine.begin() as conn:+ # FTS5 does not support UPDATE; use DELETE + INSERT+ await conn.execute(+ text("DELETE FROM page_fts WHERE page_id = :pid"),+ {"pid": page_id},+ )+ await conn.execute(+ text(+ "INSERT INTO page_fts(page_id, title, content) "+ "VALUES (:pid, :title, :content)"+ ),+ {"pid": page_id, "title": title, "content": content},+ )+ # PostgreSQL: the GIN index on wiki_pages is maintained automatically+ # by the database as rows are inserted/updated via the CRUD layer.++ async def delete(self, page_id: str) -> None:+ """Remove a page from the FTS index."""+ if self._dialect == "sqlite":+ async with self._engine.begin() as conn:+ await conn.execute(+ text("DELETE FROM page_fts WHERE page_id = :pid"),+ {"pid": page_id},+ )++ async def search(self, query: str, limit: int = 10) -> list[SearchResult]:+ """Search for pages matching *query*.++ Args:+ query: Natural-language search query.+ limit: Maximum number of results to return.++ Returns:+ List of SearchResult objects sorted by relevance (descending).+ """+ if not query.strip():+ return []++ if self._dialect == "sqlite":+ return await self._search_sqlite(query, limit)+ return await self._search_postgresql(query, limit)++ async def _search_sqlite(self, query: str, limit: int) -> list[SearchResult]:+ """FTS5 search. ``rank`` is negative; we negate it to get a positive score."""+ # FTS5 MATCH syntax: escape special chars with double-quotes+ safe_query = query.replace('"', '""')+ fts_query = f'"{safe_query}"'++ async with self._engine.connect() as conn:+ rows = await conn.execute(+ text(+ "SELECT f.page_id, f.title, f.content, f.rank "+ "FROM page_fts f "+ "WHERE page_fts MATCH :q "+ "ORDER BY rank "+ "LIMIT :lim"+ ),+ {"q": fts_query, "lim": limit},+ )+ raw = rows.fetchall()++ # We need page_type and target_path from wiki_pages+ if not raw:+ return []++ page_ids = [r[0] for r in raw]+ rank_by_id = {r[0]: r[3] for r in raw}+ content_by_id = {r[0]: r[2] for r in raw}+ title_by_id = {r[0]: r[1] for r in raw}++ async with self._engine.connect() as conn:+ placeholders = ", ".join(f":id{i}" for i in range(len(page_ids)))+ params = {f"id{i}": pid for i, pid in enumerate(page_ids)}+ page_rows = await conn.execute(+ text(+ f"SELECT id, page_type, target_path FROM wiki_pages "+ f"WHERE id IN ({placeholders})"+ ),+ params,+ )+ meta = {r[0]: (r[1], r[2]) for r in page_rows.fetchall()}++ results = []+ for pid in page_ids:+ page_type, target_path = meta.get(pid, ("", ""))+ score = -(rank_by_id[pid] or 0.0) # FTS5 rank is negative+ results.append(+ SearchResult(+ page_id=pid,+ title=title_by_id[pid],+ page_type=page_type,+ target_path=target_path,+ score=score,+ snippet=_snippet(content_by_id[pid]),+ search_type="fulltext",+ )+ )+ return results++ async def _search_postgresql(self, query: str, limit: int) -> list[SearchResult]:+ """PostgreSQL tsvector search with ts_rank scoring."""+ async with self._engine.connect() as conn:+ rows = await conn.execute(+ text(+ "SELECT id, title, content, page_type, target_path, "+ " ts_rank("+ " to_tsvector('english', COALESCE(title,'') || ' ' || COALESCE(content,'')), "+ " plainto_tsquery('english', :q)"+ " ) AS rank "+ "FROM wiki_pages "+ "WHERE to_tsvector('english', COALESCE(title,'') || ' ' || COALESCE(content,'')) "+ " @@ plainto_tsquery('english', :q) "+ "ORDER BY rank DESC "+ "LIMIT :lim",+ ),+ {"q": query, "lim": limit},+ )+ raw = rows.fetchall()++ return [+ SearchResult(+ page_id=r[0],+ title=r[1],+ page_type=r[3],+ target_path=r[4],+ score=float(r[5]),+ snippet=_snippet(r[2]),+ search_type="fulltext",+ )+ for r in raw+ ]diff --git a/packages/core/src/wikicode/core/persistence/vector_store.py b/packages/core/src/wikicode/core/persistence/vector_store.pynew file mode 100644index 000000000..4dc80dfda--- /dev/null+++ b/packages/core/src/wikicode/core/persistence/vector_store.py@@ -0,0 +1,371 @@+"""Vector store abstraction and implementations for WikiCode semantic search.++Three implementations are provided:++InMemoryVectorStore+ Pure Python, no external dependencies. Cosine similarity search over+ an in-memory dict. Suitable for tests and development.++LanceDBVectorStore+ Embedded vector database stored in a local directory. Requires the+ ``wikicode-core[search]`` extra (lancedb>=0.12).++PgVectorStore+ Stores embeddings in the ``wiki_pages.embedding`` pgvector column.+ Requires the ``wikicode-core[pgvector]`` extra and a running PostgreSQL+ with the ``vector`` extension enabled.++All stores accept an :class:`Embedder` at construction time and handle+embedding internally — callers pass raw text, not pre-computed vectors.+"""++from __future__ import annotations++import math+from abc import ABC, abstractmethod+from typing import TYPE_CHECKING++from .embedder import Embedder+from .search import SearchResult++if TYPE_CHECKING:+ from sqlalchemy.ext.asyncio import async_sessionmaker, AsyncSession++__all__ = [+ "VectorStore",+ "InMemoryVectorStore",+ "LanceDBVectorStore",+ "PgVectorStore",+]+++# ---------------------------------------------------------------------------+# Abstract base+# ---------------------------------------------------------------------------+++class VectorStore(ABC):+ """Abstract vector store. All methods are async."""++ @abstractmethod+ async def embed_and_upsert(+ self, page_id: str, text: str, metadata: dict+ ) -> None:+ """Embed *text* and upsert the vector under *page_id*."""+ ...++ @abstractmethod+ async def search(self, query: str, limit: int = 10) -> list[SearchResult]:+ """Embed *query* and return the *limit* nearest pages."""+ ...++ @abstractmethod+ async def delete(self, page_id: str) -> None:+ """Remove the vector for *page_id* from the store."""+ ...++ @abstractmethod+ async def close(self) -> None:+ """Release any resources held by the store."""+ ...+++# ---------------------------------------------------------------------------+# InMemoryVectorStore+# ---------------------------------------------------------------------------+++def _cosine(a: list[float], b: list[float]) -> float:+ """Cosine similarity between two vectors (returns 0.0 for zero vectors)."""+ dot = sum(x * y for x, y in zip(a, b))+ norm_a = math.sqrt(sum(x * x for x in a))+ norm_b = math.sqrt(sum(x * x for x in b))+ denom = norm_a * norm_b+ return dot / denom if denom > 0 else 0.0+++class InMemoryVectorStore(VectorStore):+ """Cosine-similarity vector store backed by a plain Python dict.++ Suitable for unit tests and small-scale development use.+ No external dependencies beyond the Embedder.+ """++ def __init__(self, embedder: Embedder) -> None:+ self._embedder = embedder+ # page_id → (vector, metadata)+ self._store: dict[str, tuple[list[float], dict]] = {}++ async def embed_and_upsert(+ self, page_id: str, text: str, metadata: dict+ ) -> None:+ vectors = await self._embedder.embed([text])+ self._store[page_id] = (vectors[0], dict(metadata))++ async def search(self, query: str, limit: int = 10) -> list[SearchResult]:+ if not self._store:+ return []+ q_vecs = await self._embedder.embed([query])+ q_vec = q_vecs[0]++ scored: list[tuple[float, str, dict]] = []+ for pid, (vec, meta) in self._store.items():+ score = _cosine(q_vec, vec)+ scored.append((score, pid, meta))++ scored.sort(key=lambda t: t[0], reverse=True)++ results = []+ for score, pid, meta in scored[:limit]:+ content = meta.get("content", "")+ results.append(+ SearchResult(+ page_id=pid,+ title=str(meta.get("title", "")),+ page_type=str(meta.get("page_type", "")),+ target_path=str(meta.get("target_path", "")),+ score=score,+ snippet=str(content)[:200].rstrip(),+ search_type="vector",+ )+ )+ return results++ async def delete(self, page_id: str) -> None:+ self._store.pop(page_id, None)++ async def close(self) -> None:+ self._store.clear()++ def __len__(self) -> int:+ return len(self._store)+++# ---------------------------------------------------------------------------+# LanceDBVectorStore+# ---------------------------------------------------------------------------+++class LanceDBVectorStore(VectorStore):+ """Vector store backed by LanceDB (embedded, local file storage).++ Requires the ``wikicode-core[search]`` extra:+ pip install wikicode-core[search]++ Data is stored in *db_path* (e.g. ``.wikicode/lancedb/``).+ The LanceDB table is created lazily on the first call to+ :meth:`embed_and_upsert`.+ """++ _TABLE_NAME = "wiki_pages"++ def __init__(+ self, db_path: str, embedder: Embedder, table_name: str | None = None+ ) -> None:+ self._db_path = db_path+ self._embedder = embedder+ self._table_name = table_name or self._TABLE_NAME+ self._db = None+ self._table = None++ async def _ensure_connected(self) -> None:+ if self._db is not None:+ return+ try:+ import lancedb # type: ignore[import]+ except ImportError as exc:+ raise RuntimeError(+ "LanceDB is not installed. Install it with: "+ "pip install wikicode-core[search]"+ ) from exc++ self._db = await lancedb.connect_async(self._db_path)+ table_names = await self._db.table_names()+ if self._table_name in table_names:+ self._table = await self._db.open_table(self._table_name)+ else:+ self._table = None # will be created on first upsert++ async def _ensure_table(self, sample_vector: list[float]) -> None:+ """Create the LanceDB table if it does not exist yet."""+ if self._table is not None:+ return++ try:+ import pyarrow as pa # type: ignore[import]+ except ImportError as exc:+ raise RuntimeError(+ "pyarrow is required for LanceDBVectorStore. "+ "It is installed automatically with lancedb."+ ) from exc++ dim = len(sample_vector)+ schema = pa.schema(+ [+ pa.field("page_id", pa.string()),+ pa.field("vector", pa.list_(pa.float32(), dim)),+ pa.field("title", pa.string()),+ pa.field("page_type", pa.string()),+ pa.field("target_path", pa.string()),+ pa.field("content_snippet", pa.string()),+ ]+ )+ self._table = await self._db.create_table( # type: ignore[union-attr]+ self._table_name, schema=schema, exist_ok=True+ )++ async def embed_and_upsert(+ self, page_id: str, text: str, metadata: dict+ ) -> None:+ await self._ensure_connected()+ vectors = await self._embedder.embed([text])+ vector = vectors[0]+ await self._ensure_table(vector)++ content = str(metadata.get("content", text))+ row = {+ "page_id": page_id,+ "vector": [float(v) for v in vector],+ "title": str(metadata.get("title", "")),+ "page_type": str(metadata.get("page_type", "")),+ "target_path": str(metadata.get("target_path", "")),+ "content_snippet": content[:200],+ }++ # merge_insert: upsert by page_id (LanceDB 0.12+)+ try:+ await self._table.merge_insert("page_id").when_matched_update_all().when_not_matched_insert_all().execute([row]) # type: ignore[union-attr]+ except AttributeError:+ # Fallback for older LanceDB versions: delete + add+ await self._table.delete(f"page_id = '{page_id}'") # type: ignore[union-attr]+ await self._table.add([row]) # type: ignore[union-attr]++ async def search(self, query: str, limit: int = 10) -> list[SearchResult]:+ await self._ensure_connected()+ if self._table is None:+ return []++ q_vecs = await self._embedder.embed([query])+ q_vec = [float(v) for v in q_vecs[0]]++ raw = (+ await self._table.query() # type: ignore[union-attr]+ .nearest_to(q_vec)+ .limit(limit)+ .to_list()+ )++ return [+ SearchResult(+ page_id=r["page_id"],+ title=r.get("title", ""),+ page_type=r.get("page_type", ""),+ target_path=r.get("target_path", ""),+ score=float(r.get("_distance", 0.0)),+ snippet=r.get("content_snippet", ""),+ search_type="vector",+ )+ for r in raw+ ]++ async def delete(self, page_id: str) -> None:+ await self._ensure_connected()+ if self._table is not None:+ await self._table.delete(f"page_id = '{page_id}'") # type: ignore[union-attr]++ async def close(self) -> None:+ self._table = None+ self._db = None+++# ---------------------------------------------------------------------------+# PgVectorStore+# ---------------------------------------------------------------------------+++class PgVectorStore(VectorStore):+ """Vector store that writes embeddings to the ``wiki_pages.embedding`` column.++ Requires:+ - PostgreSQL with the ``vector`` extension.+ - The Alembic migration ``0001_initial_schema`` has been applied.+ - The ``wikicode-core[pgvector]`` extra.++ Uses raw SQL to avoid importing ``pgvector.sqlalchemy.Vector`` at module+ level (keeps the base package installable without the extra).+ """++ def __init__(+ self,+ session_factory: "async_sessionmaker[AsyncSession]",+ embedder: Embedder,+ ) -> None:+ self._session_factory = session_factory+ self._embedder = embedder++ async def embed_and_upsert(+ self, page_id: str, text: str, metadata: dict+ ) -> None:+ vectors = await self._embedder.embed([text])+ vector = vectors[0]+ # pgvector expects a list encoded as a string like "[0.1, 0.2, ...]"+ vec_str = "[" + ",".join(str(v) for v in vector) + "]"++ from sqlalchemy.sql import text as sa_text++ async with self._session_factory() as session:+ await session.execute(+ sa_text(+ "UPDATE wiki_pages SET embedding = CAST(:emb AS vector) "+ "WHERE id = :pid"+ ),+ {"emb": vec_str, "pid": page_id},+ )+ await session.commit()++ async def search(self, query: str, limit: int = 10) -> list[SearchResult]:+ q_vecs = await self._embedder.embed([query])+ q_vec = q_vecs[0]+ vec_str = "[" + ",".join(str(v) for v in q_vec) + "]"++ from sqlalchemy.sql import text as sa_text++ async with self._session_factory() as session:+ rows = await session.execute(+ sa_text(+ "SELECT id, title, content, page_type, target_path, "+ " 1 - (embedding <=> CAST(:q AS vector)) AS score "+ "FROM wiki_pages "+ "WHERE embedding IS NOT NULL "+ "ORDER BY embedding <=> CAST(:q AS vector) "+ "LIMIT :lim"+ ),+ {"q": vec_str, "lim": limit},+ )+ raw = rows.fetchall()++ return [+ SearchResult(+ page_id=r[0],+ title=r[1],+ page_type=r[3],+ target_path=r[4],+ score=float(r[5]),+ snippet=str(r[2])[:200].rstrip(),+ search_type="vector",+ )+ for r in raw+ ]++ async def delete(self, page_id: str) -> None:+ from sqlalchemy.sql import text as sa_text++ async with self._session_factory() as session:+ await session.execute(+ sa_text("UPDATE wiki_pages SET embedding = NULL WHERE id = :pid"),+ {"pid": page_id},+ )+ await session.commit()++ async def close(self) -> None:+ pass # session_factory manages connection lifecyclediff --git a/packages/core/src/wikicode/core/providers/__init__.py b/packages/core/src/wikicode/core/providers/__init__.pynew file mode 100644index 000000000..18046333e--- /dev/null+++ b/packages/core/src/wikicode/core/providers/__init__.py@@ -0,0 +1,28 @@+"""WikiCode provider package.++All LLM providers implement BaseProvider. Use get_provider() from the registry+to instantiate a provider by name — this is the preferred entry point.++ from wikicode.core.providers import get_provider++ provider = get_provider("anthropic", api_key="sk-...", model="claude-sonnet-4-6")+ response = await provider.generate(system_prompt="...", user_prompt="...")+"""++from wikicode.core.providers.base import (+ BaseProvider,+ GeneratedResponse,+ ProviderError,+ RateLimitError,+)+from wikicode.core.providers.registry import get_provider, list_providers, register_provider++__all__ = [+ "BaseProvider",+ "GeneratedResponse",+ "ProviderError",+ "RateLimitError",+ "get_provider",+ "list_providers",+ "register_provider",+]diff --git a/packages/core/src/wikicode/core/providers/anthropic.py b/packages/core/src/wikicode/core/providers/anthropic.pynew file mode 100644index 000000000..694e94d52--- /dev/null+++ b/packages/core/src/wikicode/core/providers/anthropic.py@@ -0,0 +1,155 @@+"""Anthropic provider for WikiCode.++Supports all Claude models. Prompt caching is applied automatically to system+prompts — Anthropic's API caches prompts > 1024 tokens and charges ~10% of+the normal input price on cache hits.++Recommended models (as of 2026):+ - claude-opus-4-6 — highest quality, most expensive+ - claude-sonnet-4-6 — best quality/cost ratio (default)+ - claude-haiku-4-5 — fastest, cheapest (good for low-value pages)+"""++from __future__ import annotations++import structlog+from anthropic import AsyncAnthropic+from anthropic import RateLimitError as _AnthropicRateLimitError+from anthropic import APIStatusError as _AnthropicAPIStatusError+from tenacity import (+ retry,+ retry_if_exception_type,+ stop_after_attempt,+ wait_exponential_jitter,+ before_sleep_log,+ RetryError,+)++from wikicode.core.providers.base import (+ BaseProvider,+ GeneratedResponse,+ ProviderError,+ RateLimitError,+)+from wikicode.core.rate_limiter import RateLimiter++log = structlog.get_logger(__name__)++_MAX_RETRIES = 3+_MIN_WAIT = 1.0+_MAX_WAIT = 4.0+++class AnthropicProvider(BaseProvider):+ """Anthropic Claude provider with automatic prompt caching.++ Args:+ api_key: Anthropic API key. Reads ANTHROPIC_API_KEY env var if not set.+ model: Model identifier. Defaults to claude-sonnet-4-6.+ rate_limiter: Optional pre-configured RateLimiter. If None, no rate limiting+ is applied (useful when the caller manages concurrency via semaphore).+ """++ def __init__(+ self,+ api_key: str,+ model: str = "claude-sonnet-4-6",+ rate_limiter: RateLimiter | None = None,+ ) -> None:+ self._client = AsyncAnthropic(api_key=api_key)+ self._model = model+ self._rate_limiter = rate_limiter++ @property+ def provider_name(self) -> str:+ return "anthropic"++ @property+ def model_name(self) -> str:+ return self._model++ async def generate(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int = 4096,+ temperature: float = 0.3,+ request_id: str | None = None,+ ) -> GeneratedResponse:+ if self._rate_limiter:+ await self._rate_limiter.acquire(estimated_tokens=max_tokens)++ log.debug(+ "anthropic.generate.start",+ model=self._model,+ max_tokens=max_tokens,+ request_id=request_id,+ )++ try:+ return await self._generate_with_retry(+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ max_tokens=max_tokens,+ temperature=temperature,+ request_id=request_id,+ )+ except RetryError as exc:+ raise ProviderError(+ "anthropic",+ f"All {_MAX_RETRIES} retries exhausted: {exc}",+ ) from exc++ @retry(+ retry=retry_if_exception_type(ProviderError),+ stop=stop_after_attempt(_MAX_RETRIES),+ wait=wait_exponential_jitter(initial=_MIN_WAIT, max=_MAX_WAIT),+ reraise=True,+ )+ async def _generate_with_retry(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int,+ temperature: float,+ request_id: str | None,+ ) -> GeneratedResponse:+ try:+ response = await self._client.messages.create(+ model=self._model,+ max_tokens=max_tokens,+ temperature=temperature,+ system=system_prompt,+ messages=[{"role": "user", "content": user_prompt}],+ )+ except _AnthropicRateLimitError as exc:+ raise RateLimitError("anthropic", str(exc), status_code=429) from exc+ except _AnthropicAPIStatusError as exc:+ raise ProviderError(+ "anthropic", str(exc), status_code=exc.status_code+ ) from exc++ cached = getattr(response.usage, "cache_read_input_tokens", 0) or 0+ result = GeneratedResponse(+ content=response.content[0].text,+ input_tokens=response.usage.input_tokens,+ output_tokens=response.usage.output_tokens,+ cached_tokens=cached,+ usage={+ "input_tokens": response.usage.input_tokens,+ "output_tokens": response.usage.output_tokens,+ "cache_creation_input_tokens": getattr(+ response.usage, "cache_creation_input_tokens", 0+ )+ or 0,+ "cache_read_input_tokens": cached,+ },+ )+ log.debug(+ "anthropic.generate.done",+ input_tokens=result.input_tokens,+ output_tokens=result.output_tokens,+ cached_tokens=result.cached_tokens,+ request_id=request_id,+ )+ return resultdiff --git a/packages/core/src/wikicode/core/providers/base.py b/packages/core/src/wikicode/core/providers/base.pynew file mode 100644index 000000000..ea059ce6c--- /dev/null+++ b/packages/core/src/wikicode/core/providers/base.py@@ -0,0 +1,140 @@+"""Base provider interface and response types for WikiCode's LLM abstraction layer.++WikiCode is model-agnostic by design. Any LLM — cloud or local — that implements+BaseProvider can be used for documentation generation without changing any other code.++Adding a new provider:+ 1. Create a new module in this package (e.g., providers/my_provider.py)+ 2. Subclass BaseProvider and implement generate(), provider_name, model_name+ 3. Register it in registry.py (or call register_provider() at runtime)+ 4. Add tests in tests/providers/+ See CONTRIBUTING.md for a step-by-step walkthrough.+"""++from __future__ import annotations++from abc import ABC, abstractmethod+from dataclasses import dataclass, field+from typing import Any+++@dataclass+class GeneratedResponse:+ """Unified response shape returned by every provider.++ All token counts use the provider's own counting method. For cross-provider+ cost comparison, use the cost_usd fields in GenerationJob (computed from+ known per-token prices), not raw token counts.++ Attributes:+ content: The generated text content (markdown).+ input_tokens: Tokens consumed by the prompt (system + user).+ output_tokens: Tokens produced in the response.+ cached_tokens: Tokens served from the provider's prompt cache (if any).+ Currently only Anthropic reports this natively.+ usage: Provider-specific usage dict (stored as-is for auditing).+ """++ content: str+ input_tokens: int+ output_tokens: int+ cached_tokens: int = 0+ usage: dict[str, Any] = field(default_factory=dict)++ @property+ def total_tokens(self) -> int:+ """Total tokens consumed (input + output, excluding cache hits)."""+ return self.input_tokens + self.output_tokens+++class BaseProvider(ABC):+ """Abstract base class that all LLM providers must implement.++ WikiCode is model-agnostic. Any LLM that implements this interface+ can be used for documentation generation. The rate limiter is injected+ at construction time and called transparently inside generate().++ Implementors must:+ - Be async (generate() must be a coroutine)+ - Return GeneratedResponse with correct token counts+ - Raise ProviderError on non-recoverable API errors+ - Raise RateLimitError on 429 responses after retries are exhausted+ """++ @abstractmethod+ async def generate(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int = 4096,+ temperature: float = 0.3,+ request_id: str | None = None,+ ) -> GeneratedResponse:+ """Generate a response from the LLM.++ Args:+ system_prompt: System-level instructions (role, output format, rules).+ user_prompt: User-level content — typically a rendered Jinja2 template+ containing the code context and documentation request.+ max_tokens: Maximum tokens in the completion. Providers may enforce+ lower limits; the provider should clip, not raise.+ temperature: Sampling temperature. 0.0 is fully deterministic.+ WikiCode uses 0.3 for consistent doc style.+ request_id: Optional trace ID for logging and debugging.++ Returns:+ GeneratedResponse with content and token usage.++ Raises:+ ProviderError: On API errors after all retries are exhausted.+ RateLimitError: If rate limits cannot be resolved (permanent 429).+ """+ ...++ @property+ @abstractmethod+ def provider_name(self) -> str:+ """Short, stable identifier for this provider.++ Used in logs, database records, and config files.+ Examples: 'anthropic', 'openai', 'ollama', 'litellm', 'mock'.+ """+ ...++ @property+ @abstractmethod+ def model_name(self) -> str:+ """The specific model identifier being used.++ Examples: 'claude-sonnet-4-6', 'gpt-4o', 'llama3.2'.+ Stored on every generated page for attribution and reproducibility.+ """+ ...+++class ProviderError(Exception):+ """Raised when a provider returns an unrecoverable error.++ Attributes:+ provider: The provider that raised the error ('anthropic', etc.)+ status_code: HTTP status code if available (e.g., 500, 503).+ """++ def __init__(+ self,+ provider: str,+ message: str,+ status_code: int | None = None,+ ) -> None:+ self.provider = provider+ self.status_code = status_code+ super().__init__(f"[{provider}] {message}")+++class RateLimitError(ProviderError):+ """Raised when rate limits are permanently exhausted after retries.++ This is a sub-class of ProviderError. Callers can catch either,+ but RateLimitError signals that backing off longer won't help —+ the operator needs to review rate limits or reduce concurrency.+ """diff --git a/packages/core/src/wikicode/core/providers/gemini.py b/packages/core/src/wikicode/core/providers/gemini.pynew file mode 100644index 000000000..ae8da8966--- /dev/null+++ b/packages/core/src/wikicode/core/providers/gemini.py@@ -0,0 +1,176 @@+"""Gemini provider for WikiCode using the native google-genai SDK.++Uses the same google-genai SDK as GeminiEmbedder for consistency.+Runs the synchronous SDK call in a thread pool to avoid blocking asyncio.++Recommended models:+ - gemini-3.1-flash-lite-preview — fast + cheap (default)+ - gemini-3-flash-preview — higher quality+"""++from __future__ import annotations++import asyncio+import os++import structlog+from tenacity import (+ RetryError,+ retry,+ retry_if_exception_type,+ stop_after_attempt,+ wait_exponential_jitter,+)++from wikicode.core.providers.base import (+ BaseProvider,+ GeneratedResponse,+ ProviderError,+ RateLimitError,+)+from wikicode.core.rate_limiter import RateLimiter++log = structlog.get_logger(__name__)++_MAX_RETRIES = 3+_MIN_WAIT = 1.0+_MAX_WAIT = 4.0+++class GeminiProvider(BaseProvider):+ """Native Gemini provider using the google-genai SDK.++ Args:+ model: Gemini model name. Defaults to gemini-3.1-flash-lite-preview.+ api_key: Google API key. Falls back to GEMINI_API_KEY or GOOGLE_API_KEY env var.+ rate_limiter: Optional RateLimiter instance.+ """++ def __init__(+ self,+ model: str = "gemini-3.1-flash-lite-preview",+ api_key: str | None = None,+ rate_limiter: RateLimiter | None = None,+ ) -> None:+ self._model = model+ self._api_key = (+ api_key+ or os.environ.get("GEMINI_API_KEY")+ or os.environ.get("GOOGLE_API_KEY")+ )+ if not self._api_key:+ raise ProviderError(+ "gemini",+ "No API key found. Pass api_key= or set GEMINI_API_KEY / GOOGLE_API_KEY env var.",+ )+ self._rate_limiter = rate_limiter++ @property+ def provider_name(self) -> str:+ return "gemini"++ @property+ def model_name(self) -> str:+ return self._model++ async def generate(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int = 4096,+ temperature: float = 0.3,+ request_id: str | None = None,+ ) -> GeneratedResponse:+ if self._rate_limiter:+ await self._rate_limiter.acquire(estimated_tokens=max_tokens)++ log.debug(+ "gemini.generate.start",+ model=self._model,+ max_tokens=max_tokens,+ request_id=request_id,+ )++ try:+ return await self._generate_with_retry(+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ max_tokens=max_tokens,+ temperature=temperature,+ request_id=request_id,+ )+ except RetryError as exc:+ raise ProviderError(+ "gemini",+ f"All {_MAX_RETRIES} retries exhausted: {exc}",+ ) from exc++ @retry(+ retry=retry_if_exception_type(ProviderError),+ stop=stop_after_attempt(_MAX_RETRIES),+ wait=wait_exponential_jitter(initial=_MIN_WAIT, max=_MAX_WAIT),+ reraise=True,+ )+ async def _generate_with_retry(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int,+ temperature: float,+ request_id: str | None,+ ) -> GeneratedResponse:+ # Capture self attrs for thread safety (avoids closing over self)+ model = self._model+ api_key = self._api_key++ def _call_sync() -> GeneratedResponse:+ from google import genai # type: ignore[import-untyped]+ from google.genai import types as genai_types # type: ignore[import-untyped]++ client = genai.Client(api_key=api_key)+ try:+ response = client.models.generate_content(+ model=model,+ contents=user_prompt,+ config=genai_types.GenerateContentConfig(+ system_instruction=system_prompt,+ temperature=temperature,+ # max_output_tokens intentionally omitted — Gemini flash+ # models default to 65k tokens, which is far better for+ # documentation generation than any low cap we'd impose.+ ),+ )+ except Exception as exc:+ exc_str = str(exc)+ status_code = getattr(exc, "status_code", None) or getattr(exc, "code", None)+ if status_code == 429 or "429" in exc_str or "quota" in exc_str.lower():+ raise RateLimitError("gemini", exc_str, status_code=429) from exc+ raise ProviderError("gemini", f"{type(exc).__name__}: {exc_str}") from exc++ usage = response.usage_metadata+ return GeneratedResponse(+ content=response.text or "",+ input_tokens=getattr(usage, "prompt_token_count", 0) or 0,+ output_tokens=getattr(usage, "candidates_token_count", 0) or 0,+ cached_tokens=getattr(usage, "cached_content_token_count", 0) or 0,+ usage={+ "prompt_token_count": getattr(usage, "prompt_token_count", 0) or 0,+ "candidates_token_count": getattr(usage, "candidates_token_count", 0) or 0,+ "total_token_count": getattr(usage, "total_token_count", 0) or 0,+ } if usage else {},+ )++ try:+ result = await asyncio.to_thread(_call_sync)+ except (RateLimitError, ProviderError):+ raise+ except Exception as exc:+ raise ProviderError("gemini", f"{type(exc).__name__}: {exc}") from exc++ log.debug(+ "gemini.generate.done",+ input_tokens=result.input_tokens,+ output_tokens=result.output_tokens,+ request_id=request_id,+ )+ return resultdiff --git a/packages/core/src/wikicode/core/providers/litellm.py b/packages/core/src/wikicode/core/providers/litellm.pynew file mode 100644index 000000000..90313b2d2--- /dev/null+++ b/packages/core/src/wikicode/core/providers/litellm.py@@ -0,0 +1,161 @@+"""LiteLLM provider for WikiCode.++LiteLLM acts as a proxy layer that normalizes 100+ LLMs behind the OpenAI API.+Use this provider for:+ - Together AI (Meta Llama, Mistral, etc.)+ - Groq (ultra-fast inference)+ - Replicate+ - Azure OpenAI+ - Any other LiteLLM-supported endpoint++LiteLLM model strings use the format: "<provider>/<model>"+ - "together_ai/meta-llama/Llama-3-8b-chat-hf"+ - "groq/llama-3.1-70b-versatile"+ - "azure/gpt-4o"+ - "bedrock/claude-sonnet-4-6"++Reference: https://docs.litellm.ai/docs/providers+"""++from __future__ import annotations++import structlog+from tenacity import (+ retry,+ retry_if_exception_type,+ stop_after_attempt,+ wait_exponential_jitter,+ RetryError,+)++from wikicode.core.providers.base import (+ BaseProvider,+ GeneratedResponse,+ ProviderError,+ RateLimitError,+)+from wikicode.core.rate_limiter import RateLimiter++log = structlog.get_logger(__name__)++_MAX_RETRIES = 3+_MIN_WAIT = 1.0+_MAX_WAIT = 4.0+++class LiteLLMProvider(BaseProvider):+ """LiteLLM proxy provider — 100+ LLMs through a single interface.++ Args:+ model: LiteLLM model string (e.g., "groq/llama-3.1-70b-versatile").+ api_key: API key for the target provider. Some providers read from+ environment variables (e.g., GROQ_API_KEY, TOGETHER_API_KEY).+ api_base: Optional custom API base URL (e.g., for self-hosted deployments).+ rate_limiter: Optional RateLimiter instance.+ """++ def __init__(+ self,+ model: str,+ api_key: str | None = None,+ api_base: str | None = None,+ rate_limiter: RateLimiter | None = None,+ ) -> None:+ self._model = model+ self._api_key = api_key+ self._api_base = api_base+ self._rate_limiter = rate_limiter++ @property+ def provider_name(self) -> str:+ return "litellm"++ @property+ def model_name(self) -> str:+ return self._model++ async def generate(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int = 4096,+ temperature: float = 0.3,+ request_id: str | None = None,+ ) -> GeneratedResponse:+ if self._rate_limiter:+ await self._rate_limiter.acquire(estimated_tokens=max_tokens)++ try:+ return await self._generate_with_retry(+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ max_tokens=max_tokens,+ temperature=temperature,+ request_id=request_id,+ )+ except RetryError as exc:+ raise ProviderError(+ "litellm",+ f"All {_MAX_RETRIES} retries exhausted: {exc}",+ ) from exc++ @retry(+ retry=retry_if_exception_type(ProviderError),+ stop=stop_after_attempt(_MAX_RETRIES),+ wait=wait_exponential_jitter(initial=_MIN_WAIT, max=_MAX_WAIT),+ reraise=True,+ )+ async def _generate_with_retry(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int,+ temperature: float,+ request_id: str | None,+ ) -> GeneratedResponse:+ # Import litellm lazily — it's a large package and only needed at call time+ import litellm # type: ignore[import-untyped]++ # Suppress LiteLLM's verbose feedback/debug output+ litellm.set_verbose = False+ litellm.suppress_debug_info = True++ call_kwargs: dict[str, object] = {+ "model": self._model,+ "messages": [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": user_prompt},+ ],+ "temperature": temperature,+ "max_tokens": max_tokens,+ }+ if self._api_key:+ call_kwargs["api_key"] = self._api_key+ if self._api_base:+ call_kwargs["api_base"] = self._api_base++ try:+ response = await litellm.acompletion(**call_kwargs)+ except litellm.RateLimitError as exc:+ raise RateLimitError("litellm", str(exc), status_code=429) from exc+ except litellm.APIError as exc:+ raise ProviderError("litellm", str(exc)) from exc+ except Exception as exc:+ log.error("litellm.generate.error", model=self._model, error=str(exc))+ raise ProviderError("litellm", f"{type(exc).__name__}: {exc}") from exc++ usage = response.usage+ result = GeneratedResponse(+ content=response.choices[0].message.content or "",+ input_tokens=getattr(usage, "prompt_tokens", 0) if usage else 0,+ output_tokens=getattr(usage, "completion_tokens", 0) if usage else 0,+ cached_tokens=0,+ usage=dict(usage) if usage else {},+ )+ log.debug(+ "litellm.generate.done",+ input_tokens=result.input_tokens,+ output_tokens=result.output_tokens,+ request_id=request_id,+ )+ return resultdiff --git a/packages/core/src/wikicode/core/providers/mock.py b/packages/core/src/wikicode/core/providers/mock.pynew file mode 100644index 000000000..3b676b453--- /dev/null+++ b/packages/core/src/wikicode/core/providers/mock.py@@ -0,0 +1,158 @@+"""Mock provider for testing — returns fixture responses without any API calls.++MockProvider is the only provider used in WikiCode's test suite. It fully+implements BaseProvider so tests exercise the real interface without consuming+API tokens or requiring network access.++Usage in tests:+ # Simple: default inline response+ provider = MockProvider()+ response = await provider.generate("sys", "user")++ # Fixture-based: load from tests/providers/fixtures/<name>.json+ provider = MockProvider(fixture_name="file_page_response")++ # Preset: control exact responses per call+ provider = MockProvider(responses=[+ GeneratedResponse("First page", 100, 50),+ GeneratedResponse("Second page", 200, 80),+ ])+ r1 = await provider.generate("sys", "user") # "First page"+ r2 = await provider.generate("sys", "user") # "Second page"+ r3 = await provider.generate("sys", "user") # "Second page" (last repeated)++ # Assertions+ assert provider.call_count == 3+ assert provider.calls[0]["user_prompt"] == "user"+"""++from __future__ import annotations++import json+from pathlib import Path++from wikicode.core.providers.base import BaseProvider, GeneratedResponse++# Resolve fixture directory relative to this file so tests work regardless+# of working directory. Goes up: mock.py → providers/ → core/ → wikicode/ →+# src/ → packages/core/ → (repo root) → tests/providers/fixtures/+_FIXTURE_DIR = (+ Path(__file__).parent # providers/+ .parent # core/+ .parent # wikicode/+ .parent # src/+ .parent # packages/core/+ .parent # packages/+ .parent # repo root+ / "tests"+ / "providers"+ / "fixtures"+)++_DEFAULT_CONTENT = """\+## Overview++This is a mock documentation page generated by WikiCode's MockProvider.++### Purpose++This module provides core functionality for the sample repository.++### Public API++See the source file for the full symbol list.+"""+++class MockProvider(BaseProvider):+ """Deterministic test provider — no network calls, no API keys.++ Call history is recorded and accessible via `call_count` and `calls`+ for assertion in tests. Use `reset()` between test cases when reusing+ the same instance.++ Args:+ fixture_name: Name of a JSON fixture file (without .json).+ Loaded from tests/providers/fixtures/{name}.json.+ Falls back to the inline default if file not found.+ model: Model name returned by model_name property.+ responses: Optional preset list of GeneratedResponse objects.+ Returned in order; the last response repeats indefinitely.+ When provided, overrides fixture_name.+ """++ def __init__(+ self,+ fixture_name: str = "default",+ model: str = "mock-model-1",+ responses: list[GeneratedResponse] | None = None,+ ) -> None:+ self._fixture_name = fixture_name+ self._model = model+ self._preset_responses = responses or []+ self._call_count = 0+ self._calls: list[dict[str, object]] = []++ @property+ def provider_name(self) -> str:+ return "mock"++ @property+ def model_name(self) -> str:+ return self._model++ async def generate(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int = 4096,+ temperature: float = 0.3,+ request_id: str | None = None,+ ) -> GeneratedResponse:+ """Return a fixture response without calling any external API."""+ self._calls.append(+ {+ "system_prompt": system_prompt,+ "user_prompt": user_prompt,+ "max_tokens": max_tokens,+ "temperature": temperature,+ "request_id": request_id,+ }+ )+ call_idx = self._call_count+ self._call_count += 1++ # Preset responses take priority+ if self._preset_responses:+ idx = min(call_idx, len(self._preset_responses) - 1)+ return self._preset_responses[idx]++ # Try loading from fixture file+ fixture_path = _FIXTURE_DIR / f"{self._fixture_name}.json"+ if fixture_path.exists():+ data = json.loads(fixture_path.read_text(encoding="utf-8"))+ return GeneratedResponse(**data)++ # Default inline response+ return GeneratedResponse(+ content=f"{_DEFAULT_CONTENT}\n\n---\n*Mock call #{call_idx + 1}*",+ input_tokens=150,+ output_tokens=75,+ cached_tokens=0,+ usage={"mock": True, "fixture": self._fixture_name, "call": call_idx},+ )++ @property+ def call_count(self) -> int:+ """Number of times generate() has been called on this instance."""+ return self._call_count++ @property+ def calls(self) -> list[dict[str, object]]:+ """Ordered list of all recorded generate() call arguments."""+ return list(self._calls)++ def reset(self) -> None:+ """Reset call history. Useful when reusing a provider across test cases."""+ self._call_count = 0+ self._calls.clear()diff --git a/packages/core/src/wikicode/core/providers/ollama.py b/packages/core/src/wikicode/core/providers/ollama.pynew file mode 100644index 000000000..e3ee821a9--- /dev/null+++ b/packages/core/src/wikicode/core/providers/ollama.py@@ -0,0 +1,160 @@+"""Ollama provider for WikiCode.++Ollama enables fully offline, local LLM inference. It exposes an OpenAI-compatible+API endpoint, so this provider uses the OpenAI client internally.++No API key required for local deployments. This makes WikiCode usable in:+ - Air-gapped environments+ - High-security codebases that cannot send code to cloud APIs+ - Cost-sensitive projects++Popular models (pull with `ollama pull <model>`):+ - llama3.2 — good general-purpose, 3B/11B variants+ - codellama — code-focused, good for doc generation+ - deepseek-coder-v2 — strong on code understanding+ - qwen2.5-coder — excellent multilingual code model++Usage:+ provider = OllamaProvider(model="codellama", base_url="http://localhost:11434/v1")+"""++from __future__ import annotations++import structlog+from openai import AsyncOpenAI+from openai import APIStatusError as _OpenAIAPIStatusError+from tenacity import (+ retry,+ retry_if_exception_type,+ stop_after_attempt,+ wait_exponential_jitter,+ RetryError,+)++from wikicode.core.providers.base import (+ BaseProvider,+ GeneratedResponse,+ ProviderError,+)+from wikicode.core.rate_limiter import RateLimiter++log = structlog.get_logger(__name__)++_MAX_RETRIES = 3+_MIN_WAIT = 1.0+_MAX_WAIT = 8.0 # Ollama can be slow on first load, allow more wait time++_DEFAULT_BASE_URL = "http://localhost:11434/v1"+++class OllamaProvider(BaseProvider):+ """Ollama provider for local, offline LLM inference.++ Uses Ollama's OpenAI-compatible endpoint. No API key required.++ Args:+ model: Ollama model name (e.g., 'llama3.2', 'codellama').+ Must be pulled first: `ollama pull <model>`+ base_url: Ollama API base URL. Defaults to http://localhost:11434/v1+ rate_limiter: Optional RateLimiter (useful when running multiple+ concurrent requests against a resource-constrained machine).+ """++ def __init__(+ self,+ model: str = "llama3.2",+ base_url: str = _DEFAULT_BASE_URL,+ rate_limiter: RateLimiter | None = None,+ ) -> None:+ # Ollama's OpenAI-compatible endpoint accepts any non-empty api_key+ self._client = AsyncOpenAI(api_key="ollama", base_url=base_url)+ self._model = model+ self._rate_limiter = rate_limiter++ @property+ def provider_name(self) -> str:+ return "ollama"++ @property+ def model_name(self) -> str:+ return self._model++ async def generate(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int = 4096,+ temperature: float = 0.3,+ request_id: str | None = None,+ ) -> GeneratedResponse:+ if self._rate_limiter:+ await self._rate_limiter.acquire(estimated_tokens=max_tokens)++ log.debug(+ "ollama.generate.start",+ model=self._model,+ max_tokens=max_tokens,+ request_id=request_id,+ )++ try:+ return await self._generate_with_retry(+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ max_tokens=max_tokens,+ temperature=temperature,+ request_id=request_id,+ )+ except RetryError as exc:+ raise ProviderError(+ "ollama",+ f"All {_MAX_RETRIES} retries exhausted: {exc}",+ ) from exc++ @retry(+ retry=retry_if_exception_type(ProviderError),+ stop=stop_after_attempt(_MAX_RETRIES),+ wait=wait_exponential_jitter(initial=_MIN_WAIT, max=_MAX_WAIT),+ reraise=True,+ )+ async def _generate_with_retry(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int,+ temperature: float,+ request_id: str | None,+ ) -> GeneratedResponse:+ try:+ response = await self._client.chat.completions.create(+ model=self._model,+ max_tokens=max_tokens,+ temperature=temperature,+ messages=[+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": user_prompt},+ ],+ )+ except _OpenAIAPIStatusError as exc:+ raise ProviderError(+ "ollama", str(exc), status_code=exc.status_code+ ) from exc++ usage = response.usage+ result = GeneratedResponse(+ content=response.choices[0].message.content or "",+ input_tokens=usage.prompt_tokens if usage else 0,+ output_tokens=usage.completion_tokens if usage else 0,+ cached_tokens=0,+ usage={+ "prompt_tokens": usage.prompt_tokens if usage else 0,+ "completion_tokens": usage.completion_tokens if usage else 0,+ },+ )+ log.debug(+ "ollama.generate.done",+ input_tokens=result.input_tokens,+ output_tokens=result.output_tokens,+ request_id=request_id,+ )+ return resultdiff --git a/packages/core/src/wikicode/core/providers/openai.py b/packages/core/src/wikicode/core/providers/openai.pynew file mode 100644index 000000000..cbbaf035b--- /dev/null+++ b/packages/core/src/wikicode/core/providers/openai.py@@ -0,0 +1,152 @@+"""OpenAI provider for WikiCode.++Supports all OpenAI Chat Completions models (GPT-4o, o1, o3, etc.).+Also works as a base for any OpenAI-compatible API endpoint via the+`base_url` parameter.++Recommended models (as of 2026):+ - gpt-4o — strong reasoning, multimodal ready+ - gpt-4o-mini — cost-efficient+ - o3-mini — strong for code understanding tasks+"""++from __future__ import annotations++import structlog+from openai import AsyncOpenAI+from openai import RateLimitError as _OpenAIRateLimitError+from openai import APIStatusError as _OpenAIAPIStatusError+from tenacity import (+ retry,+ retry_if_exception_type,+ stop_after_attempt,+ wait_exponential_jitter,+ RetryError,+)++from wikicode.core.providers.base import (+ BaseProvider,+ GeneratedResponse,+ ProviderError,+ RateLimitError,+)+from wikicode.core.rate_limiter import RateLimiter++log = structlog.get_logger(__name__)++_MAX_RETRIES = 3+_MIN_WAIT = 1.0+_MAX_WAIT = 4.0+++class OpenAIProvider(BaseProvider):+ """OpenAI Chat Completions provider.++ Args:+ api_key: OpenAI API key. Reads OPENAI_API_KEY env var if not set.+ model: Model identifier. Defaults to gpt-4o.+ base_url: Optional custom base URL for OpenAI-compatible endpoints.+ rate_limiter: Optional RateLimiter instance.+ """++ def __init__(+ self,+ api_key: str,+ model: str = "gpt-4o",+ base_url: str | None = None,+ rate_limiter: RateLimiter | None = None,+ ) -> None:+ self._client = AsyncOpenAI(api_key=api_key, base_url=base_url)+ self._model = model+ self._rate_limiter = rate_limiter++ @property+ def provider_name(self) -> str:+ return "openai"++ @property+ def model_name(self) -> str:+ return self._model++ async def generate(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int = 4096,+ temperature: float = 0.3,+ request_id: str | None = None,+ ) -> GeneratedResponse:+ if self._rate_limiter:+ await self._rate_limiter.acquire(estimated_tokens=max_tokens)++ log.debug(+ "openai.generate.start",+ model=self._model,+ max_tokens=max_tokens,+ request_id=request_id,+ )++ try:+ return await self._generate_with_retry(+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ max_tokens=max_tokens,+ temperature=temperature,+ request_id=request_id,+ )+ except RetryError as exc:+ raise ProviderError(+ "openai",+ f"All {_MAX_RETRIES} retries exhausted: {exc}",+ ) from exc++ @retry(+ retry=retry_if_exception_type(ProviderError),+ stop=stop_after_attempt(_MAX_RETRIES),+ wait=wait_exponential_jitter(initial=_MIN_WAIT, max=_MAX_WAIT),+ reraise=True,+ )+ async def _generate_with_retry(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int,+ temperature: float,+ request_id: str | None,+ ) -> GeneratedResponse:+ try:+ response = await self._client.chat.completions.create(+ model=self._model,+ max_tokens=max_tokens,+ temperature=temperature,+ messages=[+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": user_prompt},+ ],+ )+ except _OpenAIRateLimitError as exc:+ raise RateLimitError("openai", str(exc), status_code=429) from exc+ except _OpenAIAPIStatusError as exc:+ raise ProviderError(+ "openai", str(exc), status_code=exc.status_code+ ) from exc++ usage = response.usage+ result = GeneratedResponse(+ content=response.choices[0].message.content or "",+ input_tokens=usage.prompt_tokens if usage else 0,+ output_tokens=usage.completion_tokens if usage else 0,+ cached_tokens=0,+ usage={+ "prompt_tokens": usage.prompt_tokens if usage else 0,+ "completion_tokens": usage.completion_tokens if usage else 0,+ "total_tokens": usage.total_tokens if usage else 0,+ },+ )+ log.debug(+ "openai.generate.done",+ input_tokens=result.input_tokens,+ output_tokens=result.output_tokens,+ request_id=request_id,+ )+ return resultdiff --git a/packages/core/src/wikicode/core/providers/registry.py b/packages/core/src/wikicode/core/providers/registry.pynew file mode 100644index 000000000..d2c1fea29--- /dev/null+++ b/packages/core/src/wikicode/core/providers/registry.py@@ -0,0 +1,154 @@+"""Provider registry for WikiCode.++Provides a single entry point for instantiating any LLM provider by name.+Supports built-in providers and runtime registration of custom providers,+enabling community-contributed providers without forking WikiCode.++Built-in providers:+ - anthropic → AnthropicProvider+ - openai → OpenAIProvider+ - ollama → OllamaProvider+ - litellm → LiteLLMProvider+ - mock → MockProvider (testing only)++Custom provider registration:+ from wikicode.core.providers import register_provider+ from my_package import MyProvider++ register_provider("my_provider", lambda **kw: MyProvider(**kw))++ # Then use it like any built-in:+ provider = get_provider("my_provider", model="my-model")+"""++from __future__ import annotations++import importlib+from typing import Any, Callable++from wikicode.core.providers.base import BaseProvider+from wikicode.core.rate_limiter import PROVIDER_DEFAULTS, RateLimitConfig, RateLimiter++# Map of provider name → (module_path, class_name)+# Providers are imported lazily to avoid requiring all dependencies at import time.+# This means `pip install wikicode-core` without anthropic installed still works —+# you just can't use the anthropic provider.+_BUILTIN_PROVIDERS: dict[str, tuple[str, str]] = {+ "anthropic": ("wikicode.core.providers.anthropic", "AnthropicProvider"),+ "openai": ("wikicode.core.providers.openai", "OpenAIProvider"),+ "gemini": ("wikicode.core.providers.gemini", "GeminiProvider"),+ "ollama": ("wikicode.core.providers.ollama", "OllamaProvider"),+ "litellm": ("wikicode.core.providers.litellm", "LiteLLMProvider"),+ "mock": ("wikicode.core.providers.mock", "MockProvider"),+}++# Runtime-registered custom providers (factory callables)+_custom_providers: dict[str, Callable[..., BaseProvider]] = {}+++def register_provider(name: str, factory: Callable[..., BaseProvider]) -> None:+ """Register a custom provider factory under a given name.++ This is the extension point for community providers. The factory receives+ all keyword arguments passed to get_provider() and must return a BaseProvider.++ Args:+ name: Short identifier for the provider (e.g., 'my_provider').+ Must not conflict with built-in names.+ factory: Callable that accepts **kwargs and returns a BaseProvider instance.++ Raises:+ ValueError: If `name` conflicts with a built-in provider name.++ Example:+ register_provider("bedrock", lambda model, **kw: BedrockProvider(model=model))+ provider = get_provider("bedrock", model="claude-sonnet-4-6")+ """+ if name in _BUILTIN_PROVIDERS:+ raise ValueError(+ f"Cannot register {name!r}: conflicts with a built-in provider. "+ "Choose a different name."+ )+ _custom_providers[name] = factory+++def get_provider(+ name: str,+ with_rate_limiter: bool = True,+ rate_limit_config: RateLimitConfig | None = None,+ **kwargs: Any,+) -> BaseProvider:+ """Instantiate a provider by name.++ Providers are imported lazily — only the requested provider's dependencies+ need to be installed.++ Args:+ name: Provider identifier ('anthropic', 'openai', etc.).+ with_rate_limiter: Attach a RateLimiter to the provider. Default True.+ Set False for mock/test providers or when managing+ concurrency externally via asyncio.Semaphore.+ rate_limit_config: Custom rate limit config. If None, uses the provider's+ default from PROVIDER_DEFAULTS.+ **kwargs: Constructor arguments for the provider+ (e.g., api_key, model, base_url).++ Returns:+ A configured BaseProvider instance, ready for use.++ Raises:+ ValueError: If the provider name is not registered.+ ImportError: If the provider's optional dependency is not installed.++ Example:+ provider = get_provider(+ "anthropic",+ api_key="sk-ant-...",+ model="claude-opus-4-6",+ )+ response = await provider.generate(system_prompt="...", user_prompt="...")+ """+ if name in _custom_providers:+ return _custom_providers[name](**kwargs)++ if name not in _BUILTIN_PROVIDERS:+ available = sorted(set(_BUILTIN_PROVIDERS) | set(_custom_providers))+ raise ValueError(+ f"Unknown provider: {name!r}. "+ f"Available providers: {available}"+ )++ # Attach rate limiter (skip for mock — tests should run without limits)+ if with_rate_limiter and name != "mock":+ config = rate_limit_config or PROVIDER_DEFAULTS.get(name)+ if config and "rate_limiter" not in kwargs:+ kwargs["rate_limiter"] = RateLimiter(config)++ module_path, class_name = _BUILTIN_PROVIDERS[name]+ try:+ module = importlib.import_module(module_path)+ except ImportError as exc:+ # Give a helpful error message naming the missing package+ _missing = {+ "anthropic": "anthropic",+ "openai": "openai",+ "gemini": "google-genai",+ "ollama": "openai", # ollama uses the openai package+ "litellm": "litellm",+ }+ package = _missing.get(name, name)+ raise ImportError(+ f"Provider {name!r} requires the '{package}' package. "+ f"Install it with: pip install {package}"+ ) from exc++ cls: type[BaseProvider] = getattr(module, class_name)+ return cls(**kwargs)+++def list_providers() -> list[str]:+ """Return a sorted list of all available provider names.++ Includes both built-in and runtime-registered custom providers.+ """+ return sorted(set(_BUILTIN_PROVIDERS) | set(_custom_providers))diff --git a/packages/core/src/wikicode/core/rate_limiter.py b/packages/core/src/wikicode/core/rate_limiter.pynew file mode 100644index 000000000..36126242b--- /dev/null+++ b/packages/core/src/wikicode/core/rate_limiter.py@@ -0,0 +1,132 @@+"""Async rate limiter with sliding-window RPM and TPM limits.++Every provider passes through a RateLimiter before making API calls.+On 429 responses, providers call on_rate_limit_error() which performs+exponential backoff with full jitter (to avoid thundering herd).++Design:+ - Uses a 60-second sliding window for both requests-per-minute (RPM)+ and tokens-per-minute (TPM).+ - The lock is released while sleeping so other coroutines can acquire it+ and check their own limits independently.+ - In multi-provider scenarios, each provider has its own RateLimiter+ instance constructed with its own RateLimitConfig.++Usage:+ config = RateLimitConfig(requests_per_minute=50, tokens_per_minute=100_000)+ limiter = RateLimiter(config)+ await limiter.acquire(estimated_tokens=2000) # blocks until window allows+ response = await api_call()+"""++from __future__ import annotations++import asyncio+import random+import time+from dataclasses import dataclass+++@dataclass(frozen=True)+class RateLimitConfig:+ """Per-provider rate limit configuration.++ Attributes:+ requests_per_minute: Maximum API requests within any 60-second window.+ tokens_per_minute: Maximum tokens (input + output) within any 60-second window.+ """++ requests_per_minute: int+ tokens_per_minute: int+++# Default rate limit configs for known providers.+# These are conservative defaults; operators can override via config.+PROVIDER_DEFAULTS: dict[str, RateLimitConfig] = {+ "anthropic": RateLimitConfig(requests_per_minute=50, tokens_per_minute=100_000),+ "openai": RateLimitConfig(requests_per_minute=60, tokens_per_minute=150_000),+ "gemini": RateLimitConfig(requests_per_minute=60, tokens_per_minute=1_000_000),+ # Ollama runs locally — effectively unlimited, but we cap to avoid OOM+ "ollama": RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=10_000_000),+ "litellm": RateLimitConfig(requests_per_minute=60, tokens_per_minute=150_000),+}+++class RateLimiter:+ """Async sliding-window rate limiter for RPM and TPM limits.++ Thread-safety: uses asyncio.Lock, safe for single-event-loop use.+ Not safe for use across multiple event loops.+ """++ def __init__(self, config: RateLimitConfig) -> None:+ self._config = config+ # Timestamps of requests within the last 60 seconds+ self._request_times: list[float] = []+ # (timestamp, token_count) pairs within the last 60 seconds+ self._token_records: list[tuple[float, int]] = []+ self._lock = asyncio.Lock()++ async def acquire(self, estimated_tokens: int = 1_000) -> None:+ """Block until rate limits permit the next request.++ Checks both RPM and TPM using a 60-second sliding window.+ Releases the lock while sleeping so other coroutines can proceed.++ Args:+ estimated_tokens: Expected token usage for the upcoming request.+ Over-estimate slightly to avoid exceeding TPM.+ """+ while True:+ async with self._lock:+ now = time.monotonic()+ self._prune_old_records(now)++ rpm_ok = len(self._request_times) < self._config.requests_per_minute+ current_tpm = sum(n for _, n in self._token_records)+ tpm_ok = current_tpm + estimated_tokens <= self._config.tokens_per_minute++ if rpm_ok and tpm_ok:+ self._request_times.append(now)+ self._token_records.append((now, estimated_tokens))+ return++ # Compute how long to sleep before re-checking+ sleep_time = 0.1 # minimum poll interval++ if not rpm_ok and self._request_times:+ oldest_request = self._request_times[0]+ time_until_slot = 60.0 - (now - oldest_request) + 0.01+ sleep_time = max(sleep_time, time_until_slot)++ if not tpm_ok and self._token_records:+ oldest_token_time = self._token_records[0][0]+ time_until_slot = 60.0 - (now - oldest_token_time) + 0.01+ sleep_time = max(sleep_time, time_until_slot)++ # Sleep outside the lock so other coroutines can proceed+ await asyncio.sleep(sleep_time)++ async def on_rate_limit_error(self, attempt: int) -> None:+ """Perform exponential backoff on a 429 response.++ Wait time: 2^attempt seconds + uniform jitter in [0, 1).+ Maximum wait is capped at 64 seconds to avoid excessive delays.++ Args:+ attempt: Zero-based retry attempt number. Pass 0 on the first 429.+ """+ base_wait = min(2**attempt, 64)+ jitter = random.uniform(0, 1)+ await asyncio.sleep(base_wait + jitter)++ def _prune_old_records(self, now: float) -> None:+ """Remove records older than 60 seconds from the sliding window."""+ cutoff = now - 60.0+ self._request_times = [t for t in self._request_times if t > cutoff]+ self._token_records = [(t, n) for t, n in self._token_records if t > cutoff]++ @property+ def config(self) -> RateLimitConfig:+ """The rate limit configuration for this limiter."""+ return self._configdiff --git a/packages/server/README.md b/packages/server/README.mdnew file mode 100644index 000000000..9acd638fe--- /dev/null+++ b/packages/server/README.md@@ -0,0 +1,240 @@+# wikicode-server++FastAPI REST API, webhook handlers, MCP server, and background job scheduler for WikiCode. This package powers the `wikicode serve` command and the Next.js web UI backend.++**Python >= 3.11 · Apache-2.0**++---++## What's in this package++| Component | Description |+|-----------|-------------|+| **REST API** | FastAPI application with full CRUD for repos, pages, symbols, jobs, git analytics, dead code |+| **MCP Server** | 13 MCP tools for AI coding assistants (Claude Code, Cursor, Cline) |+| **Webhooks** | GitHub and GitLab push event handlers — trigger incremental updates automatically |+| **Scheduler** | APScheduler background jobs — polling fallback, stale page decay, periodic re-sync |++---++## Installation++```bash+pip install wikicode-server++# Recommended: use uv+uv pip install wikicode-server+```++Installs `fastapi`, `uvicorn[standard]`, `mcp`, `apscheduler`, `cryptography`, and `wikicode-core` automatically.++---++## Running the Server++```bash+# Via the CLI (recommended)+wikicode serve # localhost:7337+wikicode serve --host 0.0.0.0 --port 8080++# Directly with uvicorn+uvicorn wikicode.server.app:create_app --factory --port 7337++# With hot reload (development)+uvicorn wikicode.server.app:create_app --factory --reload --port 7337+```++Interactive API docs are available at `http://localhost:7337/docs` once the server is running.++---++## Configuration++All configuration is via environment variables:++| Variable | Default | Description |+|----------|---------|-------------|+| `WIKICODE_DB_URL` | `sqlite+aiosqlite:///.wikicode/wiki.db` | Database URL (SQLite or PostgreSQL) |+| `WIKICODE_API_KEY` | _(none)_ | Bearer token required on all API requests (leave unset to disable auth) |+| `WIKICODE_EMBEDDER` | `mock` | Embedder backend: `mock` (FTS only) or `gemini` (real semantic search) |+| `WIKICODE_WEBHOOK_SECRET` | _(none)_ | HMAC-SHA256 secret for verifying GitHub/GitLab webhook signatures |+| `ANTHROPIC_API_KEY` | _(none)_ | Anthropic API key (required for Anthropic provider jobs) |+| `OPENAI_API_KEY` | _(none)_ | OpenAI API key (required for OpenAI provider jobs) |++---++## REST API++All endpoints are prefixed with `/api/`. When `WIKICODE_API_KEY` is set, every request must include an `Authorization: Bearer <key>` header.++### Repositories++| Method | Path | Description |+|--------|------|-------------|+| `GET` | `/api/repos` | List all registered repositories |+| `POST` | `/api/repos` | Register a new repository |+| `GET` | `/api/repos/{id}` | Get repository details and sync state |+| `PATCH` | `/api/repos/{id}` | Update repository settings (name, branch, provider) |+| `POST` | `/api/repos/{id}/sync` | Trigger incremental sync (equivalent to `wikicode update`) |+| `POST` | `/api/repos/{id}/full-resync` | Trigger full re-generation (equivalent to `wikicode init`) |++### Pages++| Method | Path | Description |+|--------|------|-------------|+| `GET` | `/api/pages` | List wiki pages, with optional `repo_id` and `page_type` filters |+| `GET` | `/api/pages/lookup` | Look up a page by `repo_id` + `page_id` query params |+| `POST` | `/api/pages/lookup/regenerate` | Regenerate a single page on demand |+| `GET` | `/api/pages/{id}/versions` | Full version history for a page |++### Jobs++| Method | Path | Description |+|--------|------|-------------|+| `GET` | `/api/jobs` | List generation jobs (supports `repo_id` filter) |+| `GET` | `/api/jobs/{id}` | Get job status and progress |+| `GET` | `/api/jobs/{id}/stream` | SSE stream of real-time job progress events |++Job progress events (`JobProgressEvent`) carry: `event` type, `file` currently being processed, `level` in the generation hierarchy, `completed` and `total` counts, elapsed time, and a final summary on completion.++### Symbols++| Method | Path | Description |+|--------|------|-------------|+| `GET` | `/api/symbols` | List/search symbols with `repo_id`, `kind`, `language`, `query` filters |+| `GET` | `/api/symbols/{id}` | Get symbol details including signature and source location |++### Graph++| Method | Path | Description |+|--------|------|-------------|+| `GET` | `/api/graph/{repo_id}` | Export dependency graph as nodes + edges (supports language and test filters) |+| `GET` | `/api/graph/{repo_id}/path` | Shortest dependency path between two modules |++### Git Analytics++| Method | Path | Description |+|--------|------|-------------|+| `GET` | `/api/git/{repo_id}/metadata` | Per-file git metadata (ownership, commit count, co-change partners) |+| `GET` | `/api/git/{repo_id}/hotspots` | Files ranked by churn rate (most frequently changed) |+| `GET` | `/api/git/{repo_id}/ownership` | Code ownership breakdown by file or module granularity |+| `GET` | `/api/git/{repo_id}/co-changes` | Files that frequently change together (temporal coupling) |+| `GET` | `/api/git/{repo_id}/summary` | Recent commit activity summary |++### Dead Code++| Method | Path | Description |+|--------|------|-------------|+| `GET` | `/api/dead-code/{repo_id}` | List dead code findings (supports `kind` and `safe_only` filters) |+| `POST` | `/api/dead-code/{repo_id}/analyze` | Trigger dead code analysis |+| `GET` | `/api/dead-code/{repo_id}/summary` | Summary stats (total findings, deletable lines, by kind) |+| `PATCH` | `/api/dead-code/{id}` | Update a finding's status: `resolved`, `acknowledged`, or `dismissed` |++### Search++| Method | Path | Description |+|--------|------|-------------|+| `POST` | `/api/search` | Search wiki pages. Body: `{"query": "...", "repo_id": "...", "mode": "fts|semantic|hybrid"}` |++### Webhooks++| Method | Path | Description |+|--------|------|-------------|+| `POST` | `/api/webhooks/github` | GitHub push event handler |+| `POST` | `/api/webhooks/gitlab` | GitLab push event handler |++### Health++| Method | Path | Description |+|--------|------|-------------|+| `GET` | `/api/health` | Server health — db connectivity, embedder info, scheduler status |++---++## MCP Server++WikiCode exposes 13 MCP tools for AI coding assistants. Start the MCP server via:++```bash+wikicode mcp # stdio transport (Claude Code, Cursor, Cline)+wikicode mcp --transport sse # SSE transport on port 7338+```++| Tool | Description |+|------|-------------|+| `get_page` | Retrieve a wiki page by file path |+| `list_pages` | List all wiki pages with metadata |+| `search_codebase` | Full-text, semantic, or hybrid search across all pages |+| `get_symbol` | Look up a symbol by name — signature, docs, file location |+| `get_module_overview` | Summary of a package or module |+| `get_repo_overview` | Repository-level architecture overview |+| `get_dependency_graph` | Export the dependency graph (optionally filtered) |+| `get_dependency_path` | Shortest path between two modules in the dependency graph |+| `get_hotspots` | Files with highest churn — most likely to need attention |+| `get_ownership` | Code ownership breakdown by file or module |+| `get_stale_pages` | Pages whose source has changed since last generation |+| `get_dead_code` | Dead code findings for a file or the whole repo |+| `get_git_summary` | Recent commit activity and change patterns |++**Claude Code / Cursor / Cline setup** — add to your MCP config:++```json+{+ "mcpServers": {+ "wikicode": {+ "command": "wikicode",+ "args": ["mcp", "/absolute/path/to/your/repo"]+ }+ }+}+```++---++## Webhooks++Register the webhook URL with GitHub or GitLab so `wikicode update` runs automatically on every push.++**GitHub setup:**++1. Go to `Settings → Webhooks → Add webhook` in your GitHub repository+2. Set **Payload URL** to `https://your-server.example.com/api/webhooks/github`+3. Set **Content type** to `application/json`+4. Set **Secret** to the value of `WIKICODE_WEBHOOK_SECRET`+5. Select **Just the push event**++**GitLab setup:**++1. Go to `Settings → Webhooks` in your GitLab project+2. Set **URL** to `https://your-server.example.com/api/webhooks/gitlab`+3. Set **Secret token** to the value of `WIKICODE_WEBHOOK_SECRET`+4. Enable **Push events**++The server verifies HMAC-SHA256 signatures, deduplicates events (stored in the `webhook_events` table), and queues an incremental sync job via the scheduler.++---++## Background Jobs++The APScheduler instance manages the following recurring tasks:++| Job | Schedule | Description |+|-----|----------|-------------|+| Stale page decay | Every 6 hours | Reduces confidence scores on pages whose source hash has changed |+| Polling fallback | Every 15 minutes | Checks for new commits on repos without webhook integration |+| Dead code re-analysis | Daily | Re-runs dead code analysis after large syncs |++---++## Development++```bash+# Install for development (from repo root)+uv pip install -e packages/server -e packages/core++# Start with hot reload+uvicorn wikicode.server.app:create_app --factory --reload --port 7337++# Run tests+pytest tests/unit/server/ tests/integration/+```diff --git a/packages/server/pyproject.toml b/packages/server/pyproject.tomlnew file mode 100644index 000000000..1b6acd0e1--- /dev/null+++ b/packages/server/pyproject.toml@@ -0,0 +1,48 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[project]+name = "wikicode-server"+version = "0.1.0"+description = "WikiCode server — FastAPI REST API, webhook handlers, and MCP server"+readme = "README.md"+requires-python = ">=3.11"+license = { text = "Apache-2.0" }+keywords = ["documentation", "api", "mcp", "fastapi", "webhooks"]+classifiers = [+ "Development Status :: 3 - Alpha",+ "Intended Audience :: Developers",+ "License :: OSI Approved :: Apache Software License",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ "Programming Language :: Python :: 3.13",+ "Framework :: FastAPI",+ "Topic :: Software Development :: Documentation",+]+dependencies = [+ "wikicode-core",+ # Web framework+ "fastapi>=0.115,<1",+ "uvicorn[standard]>=0.32,<1",+ # MCP Python SDK+ "mcp>=1.0,<2",+ # Background task scheduling+ "apscheduler>=3.10,<4",+ # Webhook signature verification+ "cryptography>=43,<44",+]++[project.urls]+Homepage = "https://github.com/wikicode-ai/wikicode"+Repository = "https://github.com/wikicode-ai/wikicode"++[tool.hatch.build.targets.wheel]+packages = ["src/wikicode"]++[tool.uv]+package = true++[tool.uv.sources]+wikicode-core = { workspace = true }diff --git a/packages/server/src/wikicode/server/__init__.py b/packages/server/src/wikicode/server/__init__.pynew file mode 100644index 000000000..0db0147c7--- /dev/null+++ b/packages/server/src/wikicode/server/__init__.py@@ -0,0 +1,10 @@+"""WikiCode server package.++Provides:+ - FastAPI REST API (packages/server/src/wikicode/server/api/)+ - Webhook handlers for GitHub and GitLab+ - MCP server (packages/server/src/wikicode/server/mcp.py)+ - Background job scheduler (APScheduler)+"""++__version__ = "0.1.0"diff --git a/packages/server/src/wikicode/server/app.py b/packages/server/src/wikicode/server/app.pynew file mode 100644index 000000000..7db7464b8--- /dev/null+++ b/packages/server/src/wikicode/server/app.py@@ -0,0 +1,151 @@+"""FastAPI application factory for the WikiCode server.++The ``create_app()`` function builds and configures the FastAPI instance.+The ``lifespan`` context manager handles startup (DB, FTS, vector store,+scheduler) and shutdown (cleanup).+"""++from __future__ import annotations++import logging+import os+from contextlib import asynccontextmanager+from typing import AsyncGenerator++from fastapi import FastAPI, Request+from fastapi.middleware.cors import CORSMiddleware+from fastapi.responses import JSONResponse++from wikicode.core.persistence.database import (+ create_engine,+ create_session_factory,+ init_db,+)+from wikicode.core.persistence.embedder import MockEmbedder+from wikicode.core.persistence.search import FullTextSearch+from wikicode.core.persistence.vector_store import InMemoryVectorStore+from wikicode.server import __version__+from wikicode.server.routers import (+ dead_code,+ decisions,+ git,+ graph,+ health,+ jobs,+ pages,+ repos,+ search,+ symbols,+ webhooks,+)+from wikicode.server.scheduler import setup_scheduler++logger = logging.getLogger(__name__)+++def _build_embedder():+ """Build an embedder from WIKICODE_EMBEDDER env var (default: mock).++ Supported values:+ mock — deterministic 8-dim SHA-256 embedder (default, no API key needed)+ gemini — GeminiEmbedder via GEMINI_API_KEY / GOOGLE_API_KEY env var+ openai — OpenAIEmbedder via OPENAI_API_KEY env var+ """+ name = os.environ.get("WIKICODE_EMBEDDER", "mock").lower()+ if name == "gemini":+ from wikicode.core.persistence.gemini_embedder import GeminiEmbedder # noqa: PLC0415++ dims = int(os.environ.get("WIKICODE_EMBEDDING_DIMS", "768"))+ return GeminiEmbedder(output_dimensionality=dims)+ if name == "openai":+ from wikicode.core.persistence.openai_embedder import OpenAIEmbedder # noqa: PLC0415++ model = os.environ.get("WIKICODE_EMBEDDING_MODEL", "text-embedding-3-small")+ return OpenAIEmbedder(model=model)+ logger.warning(+ "embedder.mock_active — set WIKICODE_EMBEDDER=gemini or openai for real RAG"+ )+ return MockEmbedder()+++@asynccontextmanager+async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:+ """Startup: create DB engine, session factory, FTS, vector store, scheduler.+ Shutdown: dispose engine, stop scheduler, close vector store.+ """+ # Database+ db_url = os.environ.get("WIKICODE_DB_URL")+ engine = create_engine(db_url)+ await init_db(engine)+ session_factory = create_session_factory(engine)++ # Full-text search+ fts = FullTextSearch(engine)+ await fts.ensure_index()++ # Vector store (InMemory default; LanceDB/pgvector configured via env)+ embedder = _build_embedder()+ vector_store = InMemoryVectorStore(embedder=embedder)++ # Background scheduler+ scheduler = setup_scheduler(session_factory)+ scheduler.start()++ # Store on app state+ app.state.engine = engine+ app.state.session_factory = session_factory+ app.state.fts = fts+ app.state.vector_store = vector_store+ app.state.scheduler = scheduler++ logger.info("wikicode_server_started", extra={"version": __version__})+ yield++ # Shutdown+ scheduler.shutdown(wait=False)+ await vector_store.close()+ await engine.dispose()+ logger.info("wikicode_server_stopped")+++def create_app() -> FastAPI:+ """Build and return the configured FastAPI application."""+ app = FastAPI(+ title="WikiCode API",+ description="REST API for WikiCode — codebase documentation engine",+ version=__version__,+ lifespan=lifespan,+ )++ # CORS — allow all origins for local development+ app.add_middleware(+ CORSMiddleware,+ allow_origins=["*"],+ allow_credentials=True,+ allow_methods=["*"],+ allow_headers=["*"],+ )++ # Exception handlers+ @app.exception_handler(LookupError)+ async def not_found_handler(request: Request, exc: LookupError) -> JSONResponse:+ return JSONResponse(status_code=404, content={"detail": str(exc)})++ @app.exception_handler(ValueError)+ async def bad_request_handler(request: Request, exc: ValueError) -> JSONResponse:+ return JSONResponse(status_code=400, content={"detail": str(exc)})++ # Include routers+ app.include_router(health.router)+ app.include_router(repos.router)+ app.include_router(pages.router)+ app.include_router(search.router)+ app.include_router(jobs.router)+ app.include_router(symbols.router)+ app.include_router(graph.router)+ app.include_router(webhooks.router)+ app.include_router(git.router)+ app.include_router(dead_code.router)+ app.include_router(decisions.router)++ return appdiff --git a/packages/server/src/wikicode/server/deps.py b/packages/server/src/wikicode/server/deps.pynew file mode 100644index 000000000..5dac5413f--- /dev/null+++ b/packages/server/src/wikicode/server/deps.py@@ -0,0 +1,55 @@+"""FastAPI dependency injection for WikiCode server.++Provides Depends() callables for:+- Database sessions (async, auto-commit/rollback)+- Vector store access+- Full-text search access+- Optional API key authentication+"""++from __future__ import annotations++import os+from typing import AsyncGenerator++from fastapi import Depends, HTTPException, Request, Security+from fastapi.security import APIKeyHeader+from sqlalchemy.ext.asyncio import AsyncSession++from wikicode.core.persistence.database import get_session++_API_KEY = os.environ.get("WIKICODE_API_KEY")+_header_scheme = APIKeyHeader(name="Authorization", auto_error=False)+++async def get_db_session(request: Request) -> AsyncGenerator[AsyncSession, None]:+ """Yield an async DB session with auto-commit on success, rollback on error."""+ factory = request.app.state.session_factory+ async with get_session(factory) as session:+ yield session+++async def get_vector_store(request: Request):+ """Return the vector store from app state."""+ return request.app.state.vector_store+++async def get_fts(request: Request):+ """Return the full-text search engine from app state."""+ return request.app.state.fts+++async def verify_api_key(+ auth: str | None = Security(_header_scheme),+) -> None:+ """Optional API key verification.++ When WIKICODE_API_KEY is not set, this is a no-op (fully open).+ When set, requests must include ``Authorization: Bearer <key>``.+ """+ if _API_KEY is None:+ return+ if not auth or not auth.startswith("Bearer "):+ raise HTTPException(status_code=401, detail="Missing API key")+ if auth[7:] != _API_KEY:+ raise HTTPException(status_code=401, detail="Invalid API key")diff --git a/packages/server/src/wikicode/server/mcp_server.py b/packages/server/src/wikicode/server/mcp_server.pynew file mode 100644index 000000000..4f89ce89f--- /dev/null+++ b/packages/server/src/wikicode/server/mcp_server.py@@ -0,0 +1,1313 @@+"""WikiCode MCP Server — 13 tools for AI coding assistants.++Exposes the full WikiCode wiki as queryable tools via the MCP protocol.+Supports both stdio transport (Claude Code, Cursor, Cline) and SSE transport+(web-based MCP clients).++Usage:+ wikicode mcp --transport stdio # for Claude Code / Cursor / Cline+ wikicode mcp --transport sse # for web-based clients+"""++from __future__ import annotations++import json+import os+from contextlib import asynccontextmanager+from typing import Any++from mcp.server.fastmcp import FastMCP+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine++from wikicode.core.persistence.database import get_session, init_db+from wikicode.core.persistence.embedder import MockEmbedder+from wikicode.core.persistence.models import (+ DeadCodeFinding,+ DecisionRecord,+ GitMetadata,+ GraphEdge,+ GraphNode,+ Page,+ Repository,+ WikiSymbol,+)+from wikicode.core.persistence.search import FullTextSearch+from wikicode.core.persistence.vector_store import InMemoryVectorStore++# ---------------------------------------------------------------------------+# Shared state (set during lifespan)+# ---------------------------------------------------------------------------++_session_factory: async_sessionmaker[AsyncSession] | None = None+_vector_store: Any = None+_decision_store: Any = None+_fts: Any = None+_repo_path: str | None = None+++@asynccontextmanager+async def _lifespan(server: FastMCP):+ """Initialize DB engine, session factory, vector store, FTS on startup."""+ global _session_factory, _vector_store, _decision_store, _fts # noqa: PLW0603++ db_url = os.environ.get(+ "WIKICODE_DATABASE_URL", "sqlite+aiosqlite:///wikicode.db"+ )++ # If a repo path was configured, try .wikicode/wikicode.db+ if _repo_path:+ from pathlib import Path++ wikicode_dir = Path(_repo_path) / ".wikicode"+ if wikicode_dir.exists():+ db_path = wikicode_dir / "wikicode.db"+ if db_path.exists():+ db_url = f"sqlite+aiosqlite:///{db_path.as_posix()}"++ connect_args: dict = {}+ if db_url.startswith("sqlite"):+ connect_args["check_same_thread"] = False++ engine = create_async_engine(db_url, connect_args=connect_args)+ await init_db(engine)++ _session_factory = async_sessionmaker(+ engine, expire_on_commit=False, class_=AsyncSession+ )++ _fts = FullTextSearch(engine)+ await _fts.ensure_index()++ embedder = MockEmbedder()+ _vector_store = InMemoryVectorStore(embedder=embedder)++ # Try to load LanceDB if available+ try:+ from wikicode.core.persistence.vector_store import LanceDBVectorStore++ if _repo_path:+ from pathlib import Path++ lance_dir = Path(_repo_path) / ".wikicode" / "lancedb"+ if lance_dir.exists():+ _vector_store = LanceDBVectorStore(+ str(lance_dir), embedder=embedder+ )+ _decision_store = LanceDBVectorStore(+ str(lance_dir), embedder=embedder, table_name="decision_records"+ )+ except ImportError:+ pass++ if _decision_store is None:+ _decision_store = InMemoryVectorStore(embedder=embedder)++ yield++ await engine.dispose()+ await _vector_store.close()+ if _decision_store is not None:+ await _decision_store.close()+++# ---------------------------------------------------------------------------+# Create the MCP server+# ---------------------------------------------------------------------------++mcp = FastMCP(+ "WikiCode",+ instructions=(+ "WikiCode is a codebase documentation engine. Use these tools to query "+ "the wiki for architecture overviews, file docs, symbol lookups, "+ "dependency paths, git history, hotspots, ownership, and dead code."+ ),+ lifespan=_lifespan,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++async def _get_repo(session: AsyncSession, repo: str | None = None) -> Repository:+ """Resolve a repository — by path, by ID, or return the first one."""+ if repo:+ # Try by path+ result = await session.execute(+ select(Repository).where(Repository.local_path == repo)+ )+ obj = result.scalar_one_or_none()+ if obj:+ return obj+ # Try by ID+ obj = await session.get(Repository, repo)+ if obj:+ return obj+ # Try by name+ result = await session.execute(+ select(Repository).where(Repository.name == repo)+ )+ obj = result.scalar_one_or_none()+ if obj:+ return obj+ raise LookupError(f"Repository not found: {repo}")++ # Default: return the first (and often only) repository+ result = await session.execute(select(Repository).limit(1))+ obj = result.scalar_one_or_none()+ if obj is None:+ raise LookupError(+ "No repositories found. Run 'wikicode init' first."+ )+ return obj+++# ---------------------------------------------------------------------------+# Tool 1: get_overview+# ---------------------------------------------------------------------------+++async def get_overview(repo: str | None = None) -> dict:+ """Get the repository overview: architecture summary, module map, key entry points.++ Best first call when starting to explore an unfamiliar codebase.++ Args:+ repo: Repository path, name, or ID. Omit if only one repo exists.+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ # Get repo overview page+ result = await session.execute(+ select(Page).where(+ Page.repository_id == repository.id,+ Page.page_type == "repo_overview",+ )+ )+ overview_page = result.scalar_one_or_none()++ # Get architecture diagram page+ result = await session.execute(+ select(Page).where(+ Page.repository_id == repository.id,+ Page.page_type == "architecture_diagram",+ )+ )+ arch_page = result.scalar_one_or_none()++ # Get module pages+ result = await session.execute(+ select(Page)+ .where(+ Page.repository_id == repository.id,+ Page.page_type == "module_page",+ )+ .order_by(Page.title)+ )+ module_pages = result.scalars().all()++ # Get entry point files from graph nodes+ result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repository.id,+ GraphNode.is_entry_point == True, # noqa: E712+ )+ )+ entry_nodes = result.scalars().all()++ return {+ "title": overview_page.title if overview_page else repository.name,+ "content_md": overview_page.content if overview_page else "No overview generated yet.",+ "architecture_diagram_mermaid": arch_page.content if arch_page else None,+ "key_modules": [+ {+ "name": p.title,+ "path": p.target_path,+ "description": p.content[:200] + "..." if len(p.content) > 200 else p.content,+ }+ for p in module_pages+ ],+ "entry_points": [n.node_id for n in entry_nodes],+ }+++# ---------------------------------------------------------------------------+# Tool 2: get_module_docs+# ---------------------------------------------------------------------------+++async def get_module_docs(module_path: str, repo: str | None = None) -> dict:+ """Get the wiki page for a module/package/directory.++ Args:+ module_path: Module path (e.g. "src/auth", "packages/core").+ repo: Repository path, name, or ID.+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ # Look up module page by target_path match+ result = await session.execute(+ select(Page).where(+ Page.repository_id == repository.id,+ Page.page_type == "module_page",+ Page.target_path == module_path,+ )+ )+ page = result.scalar_one_or_none()++ # Fallback: try partial match+ if page is None:+ result = await session.execute(+ select(Page).where(+ Page.repository_id == repository.id,+ Page.page_type == "module_page",+ Page.target_path.contains(module_path),+ )+ )+ page = result.scalar_one_or_none()++ if page is None:+ return {"error": f"Module page not found for '{module_path}'"}++ # Get file pages within this module+ result = await session.execute(+ select(Page).where(+ Page.repository_id == repository.id,+ Page.page_type == "file_page",+ Page.target_path.like(f"{module_path}%"),+ )+ )+ file_pages = result.scalars().all()++ return {+ "title": page.title,+ "content_md": page.content,+ "files": [+ {+ "path": f.target_path,+ "description": f.title,+ "confidence_score": f.confidence,+ }+ for f in file_pages+ ],+ "public_api_summary": page.content[:500] if page.content else "",+ }+++# ---------------------------------------------------------------------------+# Tool 3: get_file_docs+# ---------------------------------------------------------------------------+++async def get_file_docs(file_path: str, repo: str | None = None) -> dict:+ """Get the wiki page for a specific file.++ Args:+ file_path: Relative file path (e.g. "src/auth/service.py").+ repo: Repository path, name, or ID.+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ page_id = f"file_page:{file_path}"+ page = await session.get(Page, page_id)++ if page is None:+ # Try searching by target_path+ result = await session.execute(+ select(Page).where(+ Page.repository_id == repository.id,+ Page.page_type == "file_page",+ Page.target_path == file_path,+ )+ )+ page = result.scalar_one_or_none()++ if page is None:+ return {"error": f"File page not found for '{file_path}'"}++ # Get symbols in this file+ result = await session.execute(+ select(WikiSymbol).where(+ WikiSymbol.repository_id == repository.id,+ WikiSymbol.file_path == file_path,+ )+ )+ symbols = result.scalars().all()++ # Get files that import this one (from graph edges)+ result = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repository.id,+ GraphEdge.target_node_id == file_path,+ )+ )+ importers = result.scalars().all()++ return {+ "title": page.title,+ "content_md": page.content,+ "symbols": [+ {"name": s.name, "kind": s.kind, "signature": s.signature}+ for s in symbols+ ],+ "imported_by": [e.source_node_id for e in importers],+ "confidence_score": page.confidence,+ "freshness_status": page.freshness_status,+ }+++# ---------------------------------------------------------------------------+# Tool 4: get_symbol+# ---------------------------------------------------------------------------+++async def get_symbol(+ symbol_name: str, kind: str | None = None, repo: str | None = None+) -> dict:+ """Look up any symbol by name (fuzzy match if exact match fails).++ Args:+ symbol_name: Symbol name (e.g. "AuthService", "login", "UserRepository.find_by_id").+ kind: Optional filter by kind (function, class, method, interface, enum, etc.).+ repo: Repository path, name, or ID.+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ # Try exact match first+ query = select(WikiSymbol).where(+ WikiSymbol.repository_id == repository.id,+ WikiSymbol.name == symbol_name,+ )+ if kind:+ query = query.where(WikiSymbol.kind == kind)+ result = await session.execute(query)+ matches = list(result.scalars().all())++ # Fallback to fuzzy match+ if not matches:+ query = select(WikiSymbol).where(+ WikiSymbol.repository_id == repository.id,+ WikiSymbol.name.ilike(f"%{symbol_name}%"),+ )+ if kind:+ query = query.where(WikiSymbol.kind == kind)+ result = await session.execute(query.limit(10))+ matches = list(result.scalars().all())++ if not matches:+ return {"error": f"Symbol not found: '{symbol_name}'"}++ sym = matches[0]++ # Get the file page for this symbol's documentation+ page_id = f"file_page:{sym.file_path}"+ page = await session.get(Page, page_id)++ # Get files that use this symbol+ result = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repository.id,+ GraphEdge.target_node_id == sym.file_path,+ )+ )+ edges = result.scalars().all()+ used_by = [e.source_node_id for e in edges]++ return {+ "name": sym.name,+ "qualified_name": sym.qualified_name,+ "kind": sym.kind,+ "signature": sym.signature,+ "file_path": sym.file_path,+ "documentation": page.content if page else sym.docstring or "",+ "used_by": used_by[:20],+ "confidence_score": page.confidence if page else None,+ "candidates": [+ {"name": m.name, "kind": m.kind, "file_path": m.file_path}+ for m in matches[1:5]+ ]+ if len(matches) > 1+ else [],+ }+++# ---------------------------------------------------------------------------+# Tool 5: search_codebase+# ---------------------------------------------------------------------------+++async def search_codebase(+ query: str,+ limit: int = 5,+ page_type: str | None = None,+ repo: str | None = None,+) -> dict:+ """Semantic search over the full wiki. Ask in natural language.++ Args:+ query: Natural language search query (e.g. "how does authentication work?").+ limit: Maximum results to return (default 5).+ page_type: Optional filter by page type (file_page, module_page, etc.).+ repo: Repository path, name, or ID.+ """+ async with get_session(_session_factory) as session:+ # Ensure repo exists+ await _get_repo(session, repo)++ # Try semantic search first, fall back to fulltext+ try:+ results = await _vector_store.search(query, limit=limit)+ except Exception:+ results = await _fts.search(query, limit=limit)++ output = []+ for r in results:+ if page_type and r.page_type != page_type:+ continue+ output.append(+ {+ "page_id": r.page_id,+ "title": r.title,+ "page_type": r.page_type,+ "snippet": r.snippet,+ "relevance_score": r.score,+ "confidence_score": getattr(r, "confidence", None),+ }+ )++ return {"results": output[:limit]}+++# ---------------------------------------------------------------------------+# Tool 6: get_architecture_diagram+# ---------------------------------------------------------------------------+++async def get_architecture_diagram(+ scope: str = "repo",+ path: str | None = None,+ diagram_type: str = "auto",+ repo: str | None = None,+) -> dict:+ """Get a Mermaid diagram for the codebase or a specific module.++ Args:+ scope: "repo", "module", or "file".+ path: Module or file path (required for module/file scope).+ diagram_type: "auto", "flowchart", "class", or "sequence".+ repo: Repository path, name, or ID.+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ if scope == "repo":+ # Return the architecture diagram page+ result = await session.execute(+ select(Page).where(+ Page.repository_id == repository.id,+ Page.page_type == "architecture_diagram",+ )+ )+ page = result.scalar_one_or_none()+ if page:+ return {+ "diagram_type": diagram_type if diagram_type != "auto" else "flowchart",+ "mermaid_syntax": page.content,+ "description": page.title,+ }++ # For module/file scope or fallback, build diagram from graph+ if path:+ filter_prefix = path+ else:+ filter_prefix = ""++ result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repository.id,+ GraphNode.node_id.like(f"{filter_prefix}%") if filter_prefix else GraphNode.repository_id == repository.id,+ )+ )+ nodes = result.scalars().all()++ result = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repository.id,+ )+ )+ edges = result.scalars().all()++ node_ids = {n.node_id for n in nodes}+ relevant_edges = [+ e for e in edges+ if e.source_node_id in node_ids or e.target_node_id in node_ids+ ]++ # Build Mermaid flowchart+ lines = ["graph TD"]+ seen_nodes = set()+ for e in relevant_edges[:50]: # Limit to 50 edges for readability+ src = e.source_node_id.replace("/", "_").replace(".", "_").replace("-", "_")+ tgt = e.target_node_id.replace("/", "_").replace(".", "_").replace("-", "_")+ if src not in seen_nodes:+ lines.append(f' {src}["{e.source_node_id}"]')+ seen_nodes.add(src)+ if tgt not in seen_nodes:+ lines.append(f' {tgt}["{e.target_node_id}"]')+ seen_nodes.add(tgt)+ lines.append(f" {src} --> {tgt}")++ mermaid = "\n".join(lines) if len(lines) > 1 else "graph TD\n A[No graph data available]"++ return {+ "diagram_type": diagram_type if diagram_type != "auto" else "flowchart",+ "mermaid_syntax": mermaid,+ "description": f"Dependency graph for {scope}: {path or 'entire repo'}",+ }+++# ---------------------------------------------------------------------------+# Tool 7: get_dependency_path+# ---------------------------------------------------------------------------+++async def get_dependency_path(+ source: str, target: str, repo: str | None = None+) -> dict:+ """Find how two files/modules are connected in the dependency graph.++ Args:+ source: Source file or module path.+ target: Target file or module path.+ repo: Repository path, name, or ID.+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ result = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repository.id,+ )+ )+ edges = result.scalars().all()++ try:+ import networkx as nx+ except ImportError:+ return {"error": "networkx not available for path queries"}++ G = nx.DiGraph()+ for e in edges:+ G.add_edge(e.source_node_id, e.target_node_id)++ if source not in G:+ return {"error": f"Source node '{source}' not found in graph"}+ if target not in G:+ return {"error": f"Target node '{target}' not found in graph"}++ try:+ path = nx.shortest_path(G, source, target)+ except nx.NetworkXNoPath:+ return {"path": [], "distance": -1, "explanation": "No path found"}++ # Build path with relationships+ path_with_info = []+ for i, node in enumerate(path):+ relationship = ""+ if i < len(path) - 1:+ relationship = "imports"+ path_with_info.append({"node": node, "relationship": relationship})++ return {+ "path": path_with_info,+ "distance": len(path) - 1,+ "explanation": f"Shortest path from {source} to {target} has {len(path) - 1} hops",+ }+++# ---------------------------------------------------------------------------+# Tool 8: get_stale_pages+# ---------------------------------------------------------------------------+++async def get_stale_pages(+ threshold: float = 0.6, repo: str | None = None+) -> dict:+ """List pages whose confidence has dropped below a threshold.++ Useful for knowing which docs to distrust or prioritize for regeneration.++ Args:+ threshold: Confidence score threshold (default 0.6). Pages below this are returned.+ repo: Repository path, name, or ID.+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ result = await session.execute(+ select(Page)+ .where(+ Page.repository_id == repository.id,+ Page.confidence < threshold,+ )+ .order_by(Page.confidence)+ .limit(50)+ )+ pages = result.scalars().all()++ return {+ "stale_pages": [+ {+ "id": p.id,+ "title": p.title,+ "page_type": p.page_type,+ "confidence_score": p.confidence,+ "stale_since": p.updated_at.isoformat() if p.updated_at else None,+ "source_files": [p.target_path],+ }+ for p in pages+ ]+ }+++# ---------------------------------------------------------------------------+# Tool 9: get_file_history+# ---------------------------------------------------------------------------+++async def get_file_history(+ file_path: str, repo: str | None = None, limit: int = 10+) -> dict:+ """Get the git history for a file — the WHY behind its current structure.++ Call this before making changes to understand why code was written as it was.++ Args:+ file_path: Relative file path (e.g. "src/auth/service.py").+ repo: Repository path, name, or ID.+ limit: Max significant commits to return (default 10).+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ result = await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == repository.id,+ GitMetadata.file_path == file_path,+ )+ )+ meta = result.scalar_one_or_none()++ if meta is None:+ return {"error": f"No git metadata found for '{file_path}'"}++ significant_commits = json.loads(meta.significant_commits_json)+ co_change_partners = json.loads(meta.co_change_partners_json)++ return {+ "file_path": meta.file_path,+ "age_days": meta.age_days,+ "primary_owner": {+ "name": meta.primary_owner_name,+ "email": meta.primary_owner_email,+ "pct": meta.primary_owner_commit_pct,+ },+ "is_hotspot": meta.is_hotspot,+ "is_stable": meta.is_stable,+ "commit_count_total": meta.commit_count_total,+ "commit_count_90d": meta.commit_count_90d,+ "significant_commits": significant_commits[:limit],+ "co_change_partners": [+ {+ "file_path": p.get("file_path", p.get("path", "")),+ "co_change_count": p.get("count", 0),+ }+ for p in co_change_partners+ ],+ }+++# ---------------------------------------------------------------------------+# Tool 10: get_hotspots+# ---------------------------------------------------------------------------+++async def get_hotspots(+ repo: str | None = None,+ limit: int = 10,+ include_stable: bool = False,+) -> dict:+ """Get the riskiest files: high churn AND high complexity.++ These are the files most likely to contain bugs.++ Args:+ repo: Repository path, name, or ID.+ limit: Max hotspots to return (default 10).+ include_stable: Also return stable files (default false).+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ result = await session.execute(+ select(GitMetadata)+ .where(+ GitMetadata.repository_id == repository.id,+ GitMetadata.is_hotspot == True, # noqa: E712+ )+ .order_by(GitMetadata.churn_percentile.desc())+ .limit(limit)+ )+ hotspots = result.scalars().all()++ response: dict[str, Any] = {+ "hotspots": [+ {+ "file_path": h.file_path,+ "commit_count_90d": h.commit_count_90d,+ "churn_percentile": h.churn_percentile,+ "primary_owner": h.primary_owner_name,+ }+ for h in hotspots+ ],+ }++ if include_stable:+ result = await session.execute(+ select(GitMetadata)+ .where(+ GitMetadata.repository_id == repository.id,+ GitMetadata.is_stable == True, # noqa: E712+ )+ .order_by(GitMetadata.commit_count_total.desc())+ .limit(limit)+ )+ stables = result.scalars().all()+ response["stable_files"] = [+ {+ "file_path": s.file_path,+ "commit_count_total": s.commit_count_total,+ "primary_owner": s.primary_owner_name,+ }+ for s in stables+ ]++ return response+++# ---------------------------------------------------------------------------+# Tool 11: get_codebase_ownership+# ---------------------------------------------------------------------------+++async def get_codebase_ownership(+ repo: str | None = None, by: str = "module"+) -> dict:+ """Get ownership breakdown. Identifies knowledge silos and abandoned areas.++ Args:+ repo: Repository path, name, or ID.+ by: Granularity — "file", "module", or "package" (default "module").+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ result = await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == repository.id,+ )+ )+ all_meta = list(result.scalars().all())++ if by == "file":+ return {+ "by_file": [+ {+ "file_path": m.file_path,+ "primary_owner": m.primary_owner_name,+ "owner_pct": m.primary_owner_commit_pct,+ "contributor_count": len(json.loads(m.top_authors_json)),+ "is_silo": (m.primary_owner_commit_pct or 0) > 0.8,+ "last_commit_days_ago": m.age_days,+ }+ for m in all_meta+ ]+ }++ # Group by module (top-level directory)+ modules: dict[str, list[GitMetadata]] = {}+ for m in all_meta:+ parts = m.file_path.split("/")+ module = parts[0] if len(parts) > 1 else "root"+ modules.setdefault(module, []).append(m)++ entries = []+ for module_path, files in sorted(modules.items()):+ owners: dict[str, int] = {}+ all_contributors: set[str] = set()+ for f in files:+ if f.primary_owner_name:+ owners[f.primary_owner_name] = owners.get(f.primary_owner_name, 0) + 1+ for author in json.loads(f.top_authors_json):+ name = author.get("name", "")+ if name:+ all_contributors.add(name)++ if owners:+ top_owner = max(owners, key=owners.get) # type: ignore[arg-type]+ owner_pct = owners[top_owner] / len(files)+ else:+ top_owner = None+ owner_pct = 0.0++ entries.append(+ {+ "module_path": module_path,+ "primary_owner": top_owner,+ "owner_pct": owner_pct,+ "contributor_count": len(all_contributors),+ "is_silo": owner_pct > 0.8,+ "last_commit_days_ago": min(+ (f.age_days for f in files), default=0+ ),+ }+ )++ return {"by_module": entries}+++# ---------------------------------------------------------------------------+# Tool 12: get_co_changes+# ---------------------------------------------------------------------------+++async def get_co_changes(+ file_path: str, repo: str | None = None, min_count: int = 3+) -> dict:+ """Get files that frequently change together with the given file.++ Essential before refactoring — reveals hidden coupling not visible in imports.++ Args:+ file_path: Relative file path.+ repo: Repository path, name, or ID.+ min_count: Minimum co-change count to include (default 3).+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ result = await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == repository.id,+ GitMetadata.file_path == file_path,+ )+ )+ meta = result.scalar_one_or_none()++ if meta is None:+ return {"error": f"No git metadata found for '{file_path}'"}++ partners = json.loads(meta.co_change_partners_json)+ filtered = [p for p in partners if p.get("count", 0) >= min_count]++ # Check if partners have import relationships+ partner_paths = [p.get("file_path", p.get("path", "")) for p in filtered]+ result = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repository.id,+ GraphEdge.source_node_id == file_path,+ )+ )+ outgoing = {e.target_node_id for e in result.scalars().all()}++ result = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repository.id,+ GraphEdge.target_node_id == file_path,+ )+ )+ incoming = {e.source_node_id for e in result.scalars().all()}+ import_related = outgoing | incoming++ enriched_partners = []+ for p in filtered:+ p_path = p.get("file_path", p.get("path", ""))+ # Try to get a wiki page snippet+ page_id = f"file_page:{p_path}"+ page = await session.get(Page, page_id)+ snippet = page.content[:150] + "..." if page and len(page.content) > 150 else (page.content if page else None)++ enriched_partners.append(+ {+ "file_path": p_path,+ "co_change_count": p.get("count", 0),+ "has_import_relationship": p_path in import_related,+ "wiki_page_snippet": snippet,+ }+ )++ return {+ "file_path": file_path,+ "co_change_partners": enriched_partners,+ }+++# ---------------------------------------------------------------------------+# Tool 13: get_dead_code+# ---------------------------------------------------------------------------+++async def get_dead_code(+ repo: str | None = None,+ kind: str | None = None,+ min_confidence: float = 0.6,+ safe_only: bool = False,+ limit: int = 20,+) -> dict:+ """Get dead and unused code findings. Use before cleanup tasks.++ Results sorted by confidence desc, then lines desc (biggest wins first).++ Args:+ repo: Repository path, name, or ID.+ kind: Filter by kind (unreachable_file, unused_export, unused_internal, zombie_package).+ min_confidence: Minimum confidence threshold (default 0.6).+ safe_only: Only return findings marked safe_to_delete (default false).+ limit: Maximum findings to return (default 20).+ """+ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ query = (+ select(DeadCodeFinding)+ .where(+ DeadCodeFinding.repository_id == repository.id,+ DeadCodeFinding.status == "open",+ DeadCodeFinding.confidence >= min_confidence,+ )+ .order_by(DeadCodeFinding.confidence.desc(), DeadCodeFinding.lines.desc())+ )++ if kind:+ query = query.where(DeadCodeFinding.kind == kind)++ result = await session.execute(query)+ findings = list(result.scalars().all())++ if safe_only:+ findings = [f for f in findings if f.safe_to_delete]++ findings = findings[:limit]++ # Compute summary+ all_result = await session.execute(+ select(DeadCodeFinding).where(+ DeadCodeFinding.repository_id == repository.id,+ DeadCodeFinding.status == "open",+ )+ )+ all_findings = list(all_result.scalars().all())++ by_kind: dict[str, int] = {}+ for f in all_findings:+ by_kind[f.kind] = by_kind.get(f.kind, 0) + 1++ return {+ "summary": {+ "total_findings": len(all_findings),+ "deletable_lines": sum(f.lines for f in all_findings if f.safe_to_delete),+ "safe_to_delete_count": sum(1 for f in all_findings if f.safe_to_delete),+ "by_kind": by_kind,+ },+ "findings": [+ {+ "kind": f.kind,+ "file_path": f.file_path,+ "symbol_name": f.symbol_name,+ "confidence": f.confidence,+ "reason": f.reason,+ "safe_to_delete": f.safe_to_delete,+ "lines": f.lines,+ "last_commit_at": f.last_commit_at.isoformat() if f.last_commit_at else None,+ "primary_owner": f.primary_owner,+ "age_days": f.age_days,+ }+ for f in findings+ ],+ }+++# ---------------------------------------------------------------------------+# Tool 14: get_decisions+# ---------------------------------------------------------------------------+++async def get_decisions(+ module: str | None = None,+ tag: str | None = None,+ include_proposed: bool = False,+ include_stale: bool = True,+ repo: str | None = None,+) -> dict:+ """Get architectural decision records for the codebase.++ Use this before making architectural changes to understand existing+ constraints and why things are built the way they are.++ Args:+ module: Filter by module path (e.g. "src/auth", "packages/core").+ tag: Filter by tag: auth, database, api, performance, security, infra, testing.+ include_proposed: Include unconfirmed proposed decisions (default false).+ include_stale: Include decisions with high staleness scores (default true).+ repo: Repository path, name, or ID.+ """+ from wikicode.core.persistence.crud import list_decisions as _list_decisions++ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ statuses = ["active"]+ if include_proposed:+ statuses.append("proposed")++ decisions = await _list_decisions(+ session,+ repository.id,+ tag=tag,+ module=module,+ include_proposed=include_proposed,+ limit=50,+ )++ # Filter stale if requested+ if not include_stale:+ decisions = [d for d in decisions if d.staleness_score < 0.5]++ # Filter to requested statuses+ decisions = [d for d in decisions if d.status in statuses]++ return {+ "decisions": [+ {+ "id": d.id,+ "title": d.title,+ "status": d.status,+ "context": d.context,+ "decision": d.decision,+ "rationale": d.rationale,+ "alternatives": json.loads(d.alternatives_json),+ "consequences": json.loads(d.consequences_json),+ "affected_files": json.loads(d.affected_files_json),+ "affected_modules": json.loads(d.affected_modules_json),+ "tags": json.loads(d.tags_json),+ "source": d.source,+ "confidence": d.confidence,+ "staleness_score": d.staleness_score,+ }+ for d in decisions+ ],+ "total": len(decisions),+ }+++# ---------------------------------------------------------------------------+# Tool 15: get_why+# ---------------------------------------------------------------------------+++async def get_why(query: str, repo: str | None = None) -> dict:+ """Answer 'why is X implemented this way?' using decision records and docs.++ Use this before modifying significant code to understand architectural intent+ and prevent re-introducing previously solved problems.++ Args:+ query: Natural language question (e.g. "why is auth using JWT?").+ repo: Repository path, name, or ID.+ """+ from wikicode.core.persistence.crud import list_decisions as _list_decisions++ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)++ # Keyword match on decision title and body+ all_decisions = await _list_decisions(+ session, repository.id, include_proposed=False, limit=200+ )++ # Score decisions by keyword relevance+ query_lower = query.lower()+ query_words = set(query_lower.split())+ scored_decisions = []+ for d in all_decisions:+ text = f"{d.title} {d.decision} {d.rationale}".lower()+ match_count = sum(1 for w in query_words if w in text)+ if match_count > 0:+ scored_decisions.append((match_count, d))+ scored_decisions.sort(key=lambda t: t[0], reverse=True)+ keyword_matches = [d for _, d in scored_decisions[:5]]++ # Semantic search over decision vector store+ decision_results = []+ try:+ decision_results = await _decision_store.search(query, limit=5)+ except Exception:+ pass++ # Semantic search over documentation+ doc_results = []+ try:+ doc_results = await _vector_store.search(query, limit=3)+ except Exception:+ try:+ doc_results = await _fts.search(query, limit=3)+ except Exception:+ pass++ # Merge keyword matches with semantic results (dedup by ID)+ seen_ids: set[str] = set()+ merged_decisions = []+ for d in keyword_matches:+ if d.id not in seen_ids:+ seen_ids.add(d.id)+ merged_decisions.append({+ "id": d.id,+ "title": d.title,+ "status": d.status,+ "decision": d.decision,+ "rationale": d.rationale,+ "consequences": json.loads(d.consequences_json),+ "affected_files": json.loads(d.affected_files_json),+ "source": d.source,+ "confidence": d.confidence,+ })++ # Add semantic decision results (from vector store — these are SearchResult objects)+ for r in decision_results:+ if r.page_id not in seen_ids:+ seen_ids.add(r.page_id)+ merged_decisions.append({+ "id": r.page_id,+ "title": r.title,+ "snippet": r.snippet,+ "relevance_score": r.score,+ })++ return {+ "query": query,+ "decisions": merged_decisions[:8],+ "related_documentation": [+ {+ "page_id": r.page_id,+ "title": r.title,+ "page_type": r.page_type,+ "snippet": r.snippet,+ "relevance_score": r.score,+ }+ for r in doc_results[:3]+ ],+ }+++# ---------------------------------------------------------------------------+# Tool 16: get_decision_health+# ---------------------------------------------------------------------------+++async def get_decision_health(repo: str | None = None) -> dict:+ """Get the health status of architectural decision records.++ Returns stale decisions, ungoverned hotspots (high-churn files with no+ decisions), and proposed decisions awaiting confirmation.++ Args:+ repo: Repository path, name, or ID.+ """+ from wikicode.core.persistence.crud import get_decision_health_summary++ async with get_session(_session_factory) as session:+ repository = await _get_repo(session, repo)+ health = await get_decision_health_summary(session, repository.id)++ stale = health["stale_decisions"]+ proposed = health["proposed_awaiting_review"]+ ungoverned = health["ungoverned_hotspots"]++ return {+ "summary": (+ f"{health['summary'].get('active', 0)} active · "+ f"{health['summary'].get('stale', 0)} stale · "+ f"{len(proposed)} proposed · "+ f"{len(ungoverned)} ungoverned hotspots"+ ),+ "counts": health["summary"],+ "stale_decisions": [+ {+ "id": d.id,+ "title": d.title,+ "staleness_score": d.staleness_score,+ "affected_files": json.loads(d.affected_files_json)[:5],+ }+ for d in stale[:10]+ ],+ "proposed_awaiting_review": [+ {+ "id": d.id,+ "title": d.title,+ "source": d.source,+ "confidence": d.confidence,+ }+ for d in proposed[:10]+ ],+ "ungoverned_hotspots": ungoverned[:15],+ }+++# ---------------------------------------------------------------------------+# Server runner+# ---------------------------------------------------------------------------+++def create_mcp_server(repo_path: str | None = None) -> FastMCP:+ """Create and return the MCP server instance, optionally scoped to a repo."""+ global _repo_path # noqa: PLW0603+ _repo_path = repo_path+ return mcp+++def run_mcp(+ transport: str = "stdio",+ repo_path: str | None = None,+ port: int = 7338,+) -> None:+ """Run the MCP server with the specified transport."""+ global _repo_path # noqa: PLW0603+ _repo_path = repo_path++ if transport == "sse":+ mcp.settings.port = port+ mcp.run(transport="sse")+ else:+ mcp.run(transport="stdio")diff --git a/packages/server/src/wikicode/server/routers/__init__.py b/packages/server/src/wikicode/server/routers/__init__.pynew file mode 100644index 000000000..cfff849e9--- /dev/null+++ b/packages/server/src/wikicode/server/routers/__init__.py@@ -0,0 +1 @@+"""WikiCode API routers."""diff --git a/packages/server/src/wikicode/server/routers/dead_code.py b/packages/server/src/wikicode/server/routers/dead_code.pynew file mode 100644index 000000000..1ac85f1f4--- /dev/null+++ b/packages/server/src/wikicode/server/routers/dead_code.py@@ -0,0 +1,95 @@+"""/api/repos/{repo_id}/dead-code — Dead code findings endpoints."""++from __future__ import annotations++from fastapi import APIRouter, Depends, HTTPException, Query+from sqlalchemy.ext.asyncio import AsyncSession++from wikicode.core.persistence import crud+from wikicode.server.deps import get_db_session, verify_api_key+from wikicode.server.schemas import (+ DeadCodeFindingResponse,+ DeadCodePatchRequest,+ DeadCodeSummaryResponse,+)++router = APIRouter(+ tags=["dead-code"],+ dependencies=[Depends(verify_api_key)],+)+++ "/api/repos/{repo_id}/dead-code",+ response_model=list[DeadCodeFindingResponse],+)+async def list_dead_code(+ repo_id: str,+ kind: str | None = Query(None, description="Filter by finding kind"),+ min_confidence: float = Query(0.4, ge=0.0, le=1.0),+ status: str = Query("open"),+ safe_only: bool = Query(False),+ limit: int = Query(100, ge=1, le=500),+ session: AsyncSession = Depends(get_db_session),+) -> list[DeadCodeFindingResponse]:+ """List dead code findings for a repository."""+ findings = await crud.get_dead_code_findings(+ session,+ repo_id,+ kind=kind,+ min_confidence=min_confidence,+ status=status,+ )+ if safe_only:+ findings = [f for f in findings if f.safe_to_delete]+ return [DeadCodeFindingResponse.from_orm(f) for f in findings[:limit]]++[email protected]("/api/repos/{repo_id}/dead-code/analyze", status_code=202)+async def analyze_dead_code(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Trigger a fresh dead code analysis.++ Returns 202 immediately. The analysis runs asynchronously.+ """+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ return {"status": "analyzing", "repository_id": repo_id}+++ "/api/repos/{repo_id}/dead-code/summary",+ response_model=DeadCodeSummaryResponse,+)+async def dead_code_summary(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> DeadCodeSummaryResponse:+ """Get aggregate dead code statistics for a repository."""+ summary = await crud.get_dead_code_summary(session, repo_id)+ return DeadCodeSummaryResponse(**summary)++[email protected]("/api/dead-code/{finding_id}", response_model=DeadCodeFindingResponse)+async def resolve_finding(+ finding_id: str,+ body: DeadCodePatchRequest,+ session: AsyncSession = Depends(get_db_session),+) -> DeadCodeFindingResponse:+ """Update the status of a dead code finding."""+ valid_statuses = {"acknowledged", "resolved", "false_positive", "open"}+ if body.status not in valid_statuses:+ raise HTTPException(+ status_code=400,+ detail=f"Invalid status. Must be one of: {sorted(valid_statuses)}",+ )++ finding = await crud.update_dead_code_status(+ session, finding_id, body.status, body.note+ )+ if finding is None:+ raise HTTPException(status_code=404, detail="Finding not found")+ return DeadCodeFindingResponse.from_orm(finding)diff --git a/packages/server/src/wikicode/server/routers/decisions.py b/packages/server/src/wikicode/server/routers/decisions.pynew file mode 100644index 000000000..458517602--- /dev/null+++ b/packages/server/src/wikicode/server/routers/decisions.py@@ -0,0 +1,144 @@+"""/api/repos/{repo_id}/decisions — Architectural decision record endpoints."""++from __future__ import annotations++from fastapi import APIRouter, Depends, HTTPException, Query+from sqlalchemy.ext.asyncio import AsyncSession++from wikicode.core.persistence import crud+from wikicode.server.deps import get_db_session, verify_api_key+from wikicode.server.schemas import (+ DecisionCreate,+ DecisionRecordResponse,+ DecisionStatusUpdate,+)++router = APIRouter(+ tags=["decisions"],+ dependencies=[Depends(verify_api_key)],+)+++ "/api/repos/{repo_id}/decisions",+ response_model=list[DecisionRecordResponse],+)+async def list_decisions(+ repo_id: str,+ status: str | None = Query(None, description="Filter by status"),+ source: str | None = Query(None, description="Filter by source"),+ tag: str | None = Query(None, description="Filter by tag"),+ module: str | None = Query(None, description="Filter by module path"),+ include_proposed: bool = Query(True),+ limit: int = Query(100, ge=1, le=500),+ offset: int = Query(0, ge=0),+ session: AsyncSession = Depends(get_db_session),+) -> list[DecisionRecordResponse]:+ """List architectural decision records for a repository."""+ decisions = await crud.list_decisions(+ session,+ repo_id,+ status=status,+ source=source,+ tag=tag,+ module=module,+ include_proposed=include_proposed,+ limit=limit,+ offset=offset,+ )+ return [DecisionRecordResponse.from_orm(d) for d in decisions]+++ "/api/repos/{repo_id}/decisions/health",+)+async def decision_health(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Get decision health summary: stale, proposed, ungoverned hotspots."""+ summary = await crud.get_decision_health_summary(session, repo_id)+ return {+ "summary": summary["summary"],+ "stale_decisions": [+ DecisionRecordResponse.from_orm(d) for d in summary["stale_decisions"]+ ],+ "proposed_awaiting_review": [+ DecisionRecordResponse.from_orm(d)+ for d in summary["proposed_awaiting_review"]+ ],+ "ungoverned_hotspots": summary["ungoverned_hotspots"],+ }+++ "/api/repos/{repo_id}/decisions/{decision_id}",+ response_model=DecisionRecordResponse,+)+async def get_decision(+ repo_id: str,+ decision_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> DecisionRecordResponse:+ """Get a single decision record by ID."""+ rec = await crud.get_decision(session, decision_id)+ if rec is None or rec.repository_id != repo_id:+ raise HTTPException(status_code=404, detail="Decision not found")+ return DecisionRecordResponse.from_orm(rec)+++ "/api/repos/{repo_id}/decisions",+ response_model=DecisionRecordResponse,+ status_code=201,+)+async def create_decision(+ repo_id: str,+ body: DecisionCreate,+ session: AsyncSession = Depends(get_db_session),+) -> DecisionRecordResponse:+ """Create a new decision record (e.g. from CLI capture via API)."""+ rec = await crud.upsert_decision(+ session,+ repository_id=repo_id,+ title=body.title,+ status="active",+ context=body.context,+ decision=body.decision,+ rationale=body.rationale,+ alternatives=body.alternatives,+ consequences=body.consequences,+ affected_files=body.affected_files,+ affected_modules=body.affected_modules,+ tags=body.tags,+ source="cli",+ confidence=1.0,+ )+ return DecisionRecordResponse.from_orm(rec)+++ "/api/repos/{repo_id}/decisions/{decision_id}",+ response_model=DecisionRecordResponse,+)+async def patch_decision(+ repo_id: str,+ decision_id: str,+ body: DecisionStatusUpdate,+ session: AsyncSession = Depends(get_db_session),+) -> DecisionRecordResponse:+ """Update the status of a decision record (confirm, deprecate, supersede)."""+ try:+ rec = await crud.update_decision_status(+ session,+ decision_id,+ body.status,+ superseded_by=body.superseded_by,+ )+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc))+ if rec is None:+ raise HTTPException(status_code=404, detail="Decision not found")+ if rec.repository_id != repo_id:+ raise HTTPException(status_code=404, detail="Decision not found")+ return DecisionRecordResponse.from_orm(rec)diff --git a/packages/server/src/wikicode/server/routers/git.py b/packages/server/src/wikicode/server/routers/git.pynew file mode 100644index 000000000..cfccc58e9--- /dev/null+++ b/packages/server/src/wikicode/server/routers/git.py@@ -0,0 +1,184 @@+"""/api/repos/{repo_id}/git-* — Git intelligence endpoints."""++from __future__ import annotations++import json++from fastapi import APIRouter, Depends, HTTPException, Query+from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from wikicode.core.persistence import crud+from wikicode.core.persistence.models import GitMetadata+from wikicode.server.deps import get_db_session, verify_api_key+from wikicode.server.schemas import (+ GitMetadataResponse,+ GitSummaryResponse,+ HotspotResponse,+ OwnershipEntry,+)++router = APIRouter(+ prefix="/api/repos",+ tags=["git"],+ dependencies=[Depends(verify_api_key)],+)++[email protected]("/{repo_id}/git-metadata", response_model=GitMetadataResponse)+async def get_git_metadata(+ repo_id: str,+ file_path: str = Query(..., description="Relative file path"),+ session: AsyncSession = Depends(get_db_session),+) -> GitMetadataResponse:+ """Get git metadata for a specific file."""+ meta = await crud.get_git_metadata(session, repo_id, file_path)+ if meta is None:+ raise HTTPException(status_code=404, detail="Git metadata not found")+ return GitMetadataResponse.from_orm(meta)++[email protected]("/{repo_id}/hotspots", response_model=list[HotspotResponse])+async def get_hotspots(+ repo_id: str,+ limit: int = Query(20, ge=1, le=100),+ session: AsyncSession = Depends(get_db_session),+) -> list[HotspotResponse]:+ """Get the highest-churn files (hotspots) for a repository."""+ result = await session.execute(+ select(GitMetadata)+ .where(+ GitMetadata.repository_id == repo_id,+ GitMetadata.is_hotspot == True,+ )+ .order_by(GitMetadata.churn_percentile.desc())+ .limit(limit)+ )+ rows = result.scalars().all()+ return [+ HotspotResponse(+ file_path=r.file_path,+ commit_count_90d=r.commit_count_90d,+ churn_percentile=r.churn_percentile,+ primary_owner=r.primary_owner_name,+ is_hotspot=r.is_hotspot,+ )+ for r in rows+ ]++[email protected]("/{repo_id}/ownership", response_model=list[OwnershipEntry])+async def get_ownership(+ repo_id: str,+ granularity: str = Query("module", description="file or module"),+ session: AsyncSession = Depends(get_db_session),+) -> list[OwnershipEntry]:+ """Get ownership breakdown for a repository."""+ result = await session.execute(+ select(GitMetadata).where(GitMetadata.repository_id == repo_id)+ )+ all_meta = result.scalars().all()++ if granularity == "file":+ return [+ OwnershipEntry(+ module_path=m.file_path,+ primary_owner=m.primary_owner_name,+ owner_pct=m.primary_owner_commit_pct,+ file_count=1,+ is_silo=(m.primary_owner_commit_pct or 0) > 0.8,+ )+ for m in all_meta+ ]++ # Group by top-level directory (module)+ modules: dict[str, list] = {}+ for m in all_meta:+ parts = m.file_path.split("/")+ module = parts[0] if len(parts) > 1 else "root"+ modules.setdefault(module, []).append(m)++ entries = []+ for module_path, files in sorted(modules.items()):+ # Find the most common owner in this module+ owners: dict[str, int] = {}+ for f in files:+ if f.primary_owner_name:+ owners[f.primary_owner_name] = owners.get(f.primary_owner_name, 0) + 1+ if owners:+ top_owner = max(owners, key=owners.get) # type: ignore[arg-type]+ owner_pct = owners[top_owner] / len(files)+ else:+ top_owner = None+ owner_pct = 0.0++ entries.append(+ OwnershipEntry(+ module_path=module_path,+ primary_owner=top_owner,+ owner_pct=owner_pct,+ file_count=len(files),+ is_silo=owner_pct > 0.8,+ )+ )+ return entries++[email protected]("/{repo_id}/co-changes")+async def get_co_changes(+ repo_id: str,+ file_path: str = Query(..., description="Relative file path"),+ min_count: int = Query(3, ge=1),+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Get files that frequently change together with the given file."""+ meta = await crud.get_git_metadata(session, repo_id, file_path)+ if meta is None:+ raise HTTPException(status_code=404, detail="Git metadata not found")++ partners = json.loads(meta.co_change_partners_json)+ filtered = [p for p in partners if p.get("count", 0) >= min_count]++ return {+ "file_path": file_path,+ "co_change_partners": filtered,+ }++[email protected]("/{repo_id}/git-summary", response_model=GitSummaryResponse)+async def get_git_summary(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> GitSummaryResponse:+ """Get aggregate git health signals for a repository."""+ result = await session.execute(+ select(GitMetadata).where(GitMetadata.repository_id == repo_id)+ )+ all_meta = list(result.scalars().all())++ hotspot_count = sum(1 for m in all_meta if m.is_hotspot)+ stable_count = sum(1 for m in all_meta if m.is_stable)+ avg_churn = (+ sum(m.churn_percentile for m in all_meta) / len(all_meta)+ if all_meta+ else 0.0+ )++ # Top owners by file count+ owners: dict[str, int] = {}+ for m in all_meta:+ if m.primary_owner_name:+ owners[m.primary_owner_name] = owners.get(m.primary_owner_name, 0) + 1+ top_owners = sorted(+ [{"name": k, "file_count": v} for k, v in owners.items()],+ key=lambda x: x["file_count"],+ reverse=True,+ )[:10]++ return GitSummaryResponse(+ total_files=len(all_meta),+ hotspot_count=hotspot_count,+ stable_count=stable_count,+ average_churn_percentile=avg_churn,+ top_owners=top_owners,+ )diff --git a/packages/server/src/wikicode/server/routers/graph.py b/packages/server/src/wikicode/server/routers/graph.pynew file mode 100644index 000000000..b75faf0de--- /dev/null+++ b/packages/server/src/wikicode/server/routers/graph.py@@ -0,0 +1,656 @@+"""/api/graph — Dependency graph export in D3-compatible format."""++from __future__ import annotations++import json++from fastapi import APIRouter, Depends, HTTPException, Query+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from wikicode.core.persistence import crud+from wikicode.core.persistence.models import (+ DeadCodeFinding,+ GitMetadata,+ GraphEdge,+ GraphNode,+ Page,+)+from wikicode.server.deps import get_db_session, verify_api_key+from wikicode.server.schemas import (+ DeadCodeGraphNodeResponse,+ DeadCodeGraphResponse,+ EgoGraphResponse,+ GitMetadataResponse,+ GraphEdgeResponse,+ GraphExportResponse,+ GraphNodeResponse,+ HotFilesGraphResponse,+ HotFilesNodeResponse,+ ModuleEdgeResponse,+ ModuleGraphResponse,+ ModuleNodeResponse,+ NodeSearchResult,+)++router = APIRouter(+ prefix="/api/graph",+ tags=["graph"],+ dependencies=[Depends(verify_api_key)],+)+++def _parse_imported_names(raw: str | None) -> list[str]:+ if not raw:+ return []+ try:+ result = json.loads(raw)+ return result if isinstance(result, list) else []+ except (json.JSONDecodeError, ValueError):+ return []+++# ---------------------------------------------------------------------------+# Module graph+# ---------------------------------------------------------------------------++[email protected]("/{repo_id}/modules", response_model=ModuleGraphResponse)+async def module_graph(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> ModuleGraphResponse:+ """Collapsed directory-level graph: one node per top-level path segment."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ node_result = await session.execute(+ select(GraphNode).where(GraphNode.repository_id == repo_id)+ )+ nodes = node_result.scalars().all()++ # Group nodes by first path segment+ modules: dict[str, list[GraphNode]] = {}+ for n in nodes:+ parts = n.node_id.split("/")+ module = parts[0] if len(parts) > 1 else n.node_id+ modules.setdefault(module, []).append(n)++ # Fetch page confidence for doc coverage+ page_result = await session.execute(+ select(Page.target_path, Page.confidence).where(Page.repository_id == repo_id)+ )+ page_coverage: dict[str, float] = {row.target_path: row.confidence for row in page_result.all()}++ node_to_module: dict[str, str] = {}+ module_nodes: list[ModuleNodeResponse] = []+ for module_id, module_file_nodes in modules.items():+ file_count = len(module_file_nodes)+ symbol_count = sum(n.symbol_count for n in module_file_nodes)+ avg_pagerank = sum(n.pagerank for n in module_file_nodes) / max(file_count, 1)+ covered = sum(+ 1 for n in module_file_nodes if page_coverage.get(n.node_id, 0.0) >= 0.7+ )+ doc_coverage_pct = covered / max(file_count, 1)++ for n in module_file_nodes:+ node_to_module[n.node_id] = module_id++ module_nodes.append(+ ModuleNodeResponse(+ module_id=module_id,+ file_count=file_count,+ symbol_count=symbol_count,+ avg_pagerank=avg_pagerank,+ doc_coverage_pct=doc_coverage_pct,+ )+ )++ # Build inter-module edges from file-level edges+ edge_result = await session.execute(+ select(GraphEdge).where(GraphEdge.repository_id == repo_id)+ )+ edges = edge_result.scalars().all()++ edge_counts: dict[tuple[str, str], int] = {}+ for e in edges:+ src_module = node_to_module.get(e.source_node_id)+ tgt_module = node_to_module.get(e.target_node_id)+ if src_module and tgt_module and src_module != tgt_module:+ key = (src_module, tgt_module)+ edge_counts[key] = edge_counts.get(key, 0) + 1++ module_edges = [+ ModuleEdgeResponse(source=src, target=tgt, edge_count=count)+ for (src, tgt), count in edge_counts.items()+ ]++ return ModuleGraphResponse(nodes=module_nodes, edges=module_edges)+++# ---------------------------------------------------------------------------+# Ego / neighborhood graph+# ---------------------------------------------------------------------------++[email protected]("/{repo_id}/ego", response_model=EgoGraphResponse)+async def ego_graph(+ repo_id: str,+ node_id: str = Query(..., description="Center node ID"),+ hops: int = Query(2, ge=1, le=3),+ session: AsyncSession = Depends(get_db_session),+) -> EgoGraphResponse:+ """Return the N-hop neighborhood of a given node."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ try:+ import networkx as nx+ except ImportError:+ raise HTTPException(status_code=501, detail="networkx not available")++ edge_result = await session.execute(+ select(GraphEdge).where(GraphEdge.repository_id == repo_id)+ )+ edges = edge_result.scalars().all()++ G: nx.DiGraph = nx.DiGraph()+ for e in edges:+ G.add_edge(e.source_node_id, e.target_node_id)++ if node_id not in G:+ node_check = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_id == node_id,+ )+ )+ if node_check.scalar_one_or_none() is None:+ raise HTTPException(status_code=404, detail=f"Node '{node_id}' not found")+ G.add_node(node_id)++ inbound_count = G.in_degree(node_id)+ outbound_count = G.out_degree(node_id)++ ego: nx.DiGraph = nx.ego_graph(G, node_id, radius=hops, undirected=True)+ ego_node_ids = set(ego.nodes())++ node_result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_id.in_(list(ego_node_ids)),+ )+ )+ node_rows = node_result.scalars().all()++ ego_edge_responses = [+ GraphEdgeResponse(+ source=e.source_node_id,+ target=e.target_node_id,+ imported_names=_parse_imported_names(e.imported_names_json),+ )+ for e in edges+ if e.source_node_id in ego_node_ids and e.target_node_id in ego_node_ids+ ]++ git_result = await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == repo_id,+ GitMetadata.file_path == node_id,+ )+ )+ git_row = git_result.scalar_one_or_none()+ git_meta = GitMetadataResponse.from_orm(git_row) if git_row else None++ node_responses = [+ GraphNodeResponse(+ node_id=n.node_id,+ node_type=n.node_type,+ language=n.language,+ symbol_count=n.symbol_count,+ pagerank=n.pagerank,+ betweenness=n.betweenness,+ community_id=n.community_id,+ is_test=n.is_test,+ is_entry_point=n.is_entry_point,+ )+ for n in node_rows+ ]++ return EgoGraphResponse(+ nodes=node_responses,+ links=ego_edge_responses,+ center_node_id=node_id,+ center_git_meta=git_meta,+ inbound_count=inbound_count,+ outbound_count=outbound_count,+ )+++# ---------------------------------------------------------------------------+# Architecture / entry-point view+# ---------------------------------------------------------------------------++[email protected]("/{repo_id}/entry-points", response_model=GraphExportResponse)+async def entry_points_graph(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> GraphExportResponse:+ """Return the subgraph reachable within 3 hops from entry-point nodes."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ try:+ import networkx as nx+ except ImportError:+ raise HTTPException(status_code=501, detail="networkx not available")++ edge_result = await session.execute(+ select(GraphEdge).where(GraphEdge.repository_id == repo_id)+ )+ edges = edge_result.scalars().all()++ G: nx.DiGraph = nx.DiGraph()+ for e in edges:+ G.add_edge(e.source_node_id, e.target_node_id)++ ep_result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.is_entry_point == True, # noqa: E712+ )+ )+ entry_nodes = ep_result.scalars().all()++ reachable: set[str] = set()+ for ep in entry_nodes:+ reachable.add(ep.node_id)+ if ep.node_id in G:+ paths = nx.single_source_shortest_path_length(G, ep.node_id, cutoff=3)+ reachable.update(paths.keys())++ if not reachable:+ return GraphExportResponse(nodes=[], links=[])++ node_result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_id.in_(list(reachable)),+ )+ )+ nodes = node_result.scalars().all()++ node_responses = [+ GraphNodeResponse(+ node_id=n.node_id,+ node_type=n.node_type,+ language=n.language,+ symbol_count=n.symbol_count,+ pagerank=n.pagerank,+ betweenness=n.betweenness,+ community_id=n.community_id,+ is_test=n.is_test,+ is_entry_point=n.is_entry_point,+ )+ for n in nodes+ ]++ link_responses = [+ GraphEdgeResponse(+ source=e.source_node_id,+ target=e.target_node_id,+ imported_names=_parse_imported_names(e.imported_names_json),+ )+ for e in edges+ if e.source_node_id in reachable and e.target_node_id in reachable+ ]++ return GraphExportResponse(nodes=node_responses, links=link_responses)+++# ---------------------------------------------------------------------------+# Dead code graph+# ---------------------------------------------------------------------------++[email protected]("/{repo_id}/dead-nodes", response_model=DeadCodeGraphResponse)+async def dead_code_graph(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> DeadCodeGraphResponse:+ """Return dead-code nodes plus their 1-hop neighbors."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ finding_result = await session.execute(+ select(DeadCodeFinding).where(+ DeadCodeFinding.repository_id == repo_id,+ DeadCodeFinding.status == "open",+ DeadCodeFinding.kind.in_(["unreachable_file", "unused_export"]),+ )+ )+ findings = finding_result.scalars().all()++ if not findings:+ return DeadCodeGraphResponse(nodes=[], links=[])++ dead_paths = {f.file_path for f in findings}+ finding_map: dict[str, DeadCodeFinding] = {f.file_path: f for f in findings}++ node_result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_id.in_(list(dead_paths)),+ )+ )+ dead_nodes = node_result.scalars().all()+ dead_node_ids = {n.node_id for n in dead_nodes}++ out_edge_result = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repo_id,+ GraphEdge.source_node_id.in_(list(dead_node_ids)),+ )+ )+ in_edge_result = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repo_id,+ GraphEdge.target_node_id.in_(list(dead_node_ids)),+ )+ )+ all_edges = list(out_edge_result.scalars().all()) + list(in_edge_result.scalars().all())++ neighbor_ids: set[str] = set()+ for e in all_edges:+ neighbor_ids.add(e.source_node_id)+ neighbor_ids.add(e.target_node_id)+ neighbor_ids -= dead_node_ids++ if neighbor_ids:+ nbr_result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_id.in_(list(neighbor_ids)),+ )+ )+ neighbor_nodes = nbr_result.scalars().all()+ else:+ neighbor_nodes = []++ all_node_ids = dead_node_ids | neighbor_ids++ def _to_dead_node(n: GraphNode, confidence_group: str) -> DeadCodeGraphNodeResponse:+ return DeadCodeGraphNodeResponse(+ node_id=n.node_id,+ node_type=n.node_type,+ language=n.language,+ symbol_count=n.symbol_count,+ pagerank=n.pagerank,+ betweenness=n.betweenness,+ community_id=n.community_id,+ is_test=n.is_test,+ is_entry_point=n.is_entry_point,+ confidence_group=confidence_group,+ )++ node_responses: list[DeadCodeGraphNodeResponse] = []+ for n in dead_nodes:+ finding = finding_map.get(n.node_id)+ confidence = finding.confidence if finding else 0.0+ node_responses.append(_to_dead_node(n, "certain" if confidence >= 0.85 else "likely"))+ for n in neighbor_nodes:+ node_responses.append(_to_dead_node(n, "neighbor"))++ seen: set[tuple[str, str]] = set()+ link_responses: list[GraphEdgeResponse] = []+ for e in all_edges:+ key = (e.source_node_id, e.target_node_id)+ if (+ key not in seen+ and e.source_node_id in all_node_ids+ and e.target_node_id in all_node_ids+ ):+ seen.add(key)+ link_responses.append(+ GraphEdgeResponse(+ source=e.source_node_id,+ target=e.target_node_id,+ imported_names=_parse_imported_names(e.imported_names_json),+ )+ )++ return DeadCodeGraphResponse(nodes=node_responses, links=link_responses)+++# ---------------------------------------------------------------------------+# Hot files graph+# ---------------------------------------------------------------------------++[email protected]("/{repo_id}/hot-files", response_model=HotFilesGraphResponse)+async def hot_files_graph(+ repo_id: str,+ days: int = Query(30, description="Time window in days: 7, 30, or 90"),+ limit: int = Query(25, ge=1, le=100),+ session: AsyncSession = Depends(get_db_session),+) -> HotFilesGraphResponse:+ """Return the most-committed files plus their 1-hop outgoing neighbors."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ commit_col = GitMetadata.commit_count_90d if days > 30 else GitMetadata.commit_count_30d++ git_result = await session.execute(+ select(GitMetadata)+ .where(GitMetadata.repository_id == repo_id)+ .order_by(commit_col.desc())+ .limit(limit)+ )+ hot_files = git_result.scalars().all()++ if not hot_files:+ return HotFilesGraphResponse(nodes=[], links=[])++ hot_paths = {gm.file_path for gm in hot_files}+ commit_map: dict[str, int] = {+ gm.file_path: (gm.commit_count_90d if days > 30 else gm.commit_count_30d)+ for gm in hot_files+ }++ node_result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_id.in_(list(hot_paths)),+ )+ )+ hot_nodes = node_result.scalars().all()+ hot_node_ids = {n.node_id for n in hot_nodes}++ out_edge_result = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repo_id,+ GraphEdge.source_node_id.in_(list(hot_node_ids)),+ )+ )+ out_edges = out_edge_result.scalars().all()++ neighbor_ids = {e.target_node_id for e in out_edges} - hot_node_ids+ if neighbor_ids:+ nbr_result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_id.in_(list(neighbor_ids)),+ )+ )+ neighbor_nodes = nbr_result.scalars().all()+ else:+ neighbor_nodes = []++ all_node_ids = hot_node_ids | neighbor_ids++ def _to_hot_node(n: GraphNode, commit_count: int) -> HotFilesNodeResponse:+ return HotFilesNodeResponse(+ node_id=n.node_id,+ node_type=n.node_type,+ language=n.language,+ symbol_count=n.symbol_count,+ pagerank=n.pagerank,+ betweenness=n.betweenness,+ community_id=n.community_id,+ is_test=n.is_test,+ is_entry_point=n.is_entry_point,+ commit_count=commit_count,+ )++ node_responses = (+ [_to_hot_node(n, commit_map.get(n.node_id, 0)) for n in hot_nodes]+ + [_to_hot_node(n, 0) for n in neighbor_nodes]+ )++ link_responses = [+ GraphEdgeResponse(+ source=e.source_node_id,+ target=e.target_node_id,+ imported_names=_parse_imported_names(e.imported_names_json),+ )+ for e in out_edges+ if e.target_node_id in all_node_ids+ ]++ return HotFilesGraphResponse(nodes=node_responses, links=link_responses)+++# ---------------------------------------------------------------------------+# Node search+# ---------------------------------------------------------------------------++[email protected]("/{repo_id}/nodes/search", response_model=list[NodeSearchResult])+async def search_nodes(+ repo_id: str,+ q: str = Query(..., description="Search query"),+ limit: int = Query(10, ge=1, le=50),+ session: AsyncSession = Depends(get_db_session),+) -> list[NodeSearchResult]:+ """Full-text search over node_id values."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ result = await session.execute(+ select(GraphNode)+ .where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_id.ilike(f"%{q}%"),+ )+ .order_by(GraphNode.symbol_count.desc(), GraphNode.pagerank.desc())+ .limit(limit)+ )+ nodes = result.scalars().all()+ return [NodeSearchResult(node_id=n.node_id, language=n.language, symbol_count=n.symbol_count) for n in nodes]+++# ---------------------------------------------------------------------------+# Full graph export+# ---------------------------------------------------------------------------++[email protected]("/{repo_id}", response_model=GraphExportResponse)+async def export_graph(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> GraphExportResponse:+ """Export the full dependency graph in D3 force-directed format."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ node_result = await session.execute(+ select(GraphNode).where(GraphNode.repository_id == repo_id)+ )+ nodes = node_result.scalars().all()++ edge_result = await session.execute(+ select(GraphEdge).where(GraphEdge.repository_id == repo_id)+ )+ edges = edge_result.scalars().all()++ node_responses = [+ GraphNodeResponse(+ node_id=n.node_id,+ node_type=n.node_type,+ language=n.language,+ symbol_count=n.symbol_count,+ pagerank=n.pagerank,+ betweenness=n.betweenness,+ community_id=n.community_id,+ is_test=n.is_test,+ is_entry_point=n.is_entry_point,+ )+ for n in nodes+ ]++ link_responses = [+ GraphEdgeResponse(+ source=e.source_node_id,+ target=e.target_node_id,+ imported_names=_parse_imported_names(e.imported_names_json),+ )+ for e in edges+ ]++ return GraphExportResponse(nodes=node_responses, links=link_responses)+++# ---------------------------------------------------------------------------+# Shortest path+# ---------------------------------------------------------------------------++[email protected]("/{repo_id}/path")+async def dependency_path(+ repo_id: str,+ source: str = Query(..., alias="from", description="Source node ID"),+ target: str = Query(..., alias="to", description="Target node ID"),+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Find the shortest dependency path between two nodes."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ edge_result = await session.execute(+ select(GraphEdge).where(GraphEdge.repository_id == repo_id)+ )+ edges = edge_result.scalars().all()++ try:+ import networkx as nx+ except ImportError:+ raise HTTPException(status_code=501, detail="networkx not available for path queries")++ G: nx.DiGraph = nx.DiGraph()+ for e in edges:+ G.add_edge(e.source_node_id, e.target_node_id)++ if source not in G:+ raise HTTPException(status_code=404, detail=f"Source node '{source}' not found in graph")+ if target not in G:+ raise HTTPException(status_code=404, detail=f"Target node '{target}' not found in graph")++ try:+ path = nx.shortest_path(G, source, target)+ except nx.NetworkXNoPath:+ return {"path": [], "distance": -1, "explanation": "No path found"}++ return {+ "path": path,+ "distance": len(path) - 1,+ "explanation": f"Shortest path from {source} to {target} has {len(path) - 1} hops",+ }diff --git a/packages/server/src/wikicode/server/routers/health.py b/packages/server/src/wikicode/server/routers/health.pynew file mode 100644index 000000000..d55016ee8--- /dev/null+++ b/packages/server/src/wikicode/server/routers/health.py@@ -0,0 +1,82 @@+"""Health and metrics endpoints.++These endpoints are NOT protected by API key auth.+"""++from __future__ import annotations++from fastapi import APIRouter, Request+from sqlalchemy import func, select+from sqlalchemy.sql import text++from wikicode.core.persistence.database import get_session+from wikicode.core.persistence.models import GenerationJob, Page+from wikicode.server import __version__+from wikicode.server.schemas import HealthResponse++router = APIRouter(tags=["health"])++[email protected]("/health", response_model=HealthResponse)+async def health_check(request: Request) -> HealthResponse:+ """Liveness and readiness check."""+ db_status = "ok"+ try:+ factory = request.app.state.session_factory+ async with get_session(factory) as session:+ await session.execute(text("SELECT 1"))+ except Exception:+ db_status = "error"++ status = "healthy" if db_status == "ok" else "degraded"+ return HealthResponse(status=status, db=db_status, version=__version__)++[email protected]("/metrics")+async def metrics(request: Request) -> str:+ """Prometheus-compatible metrics endpoint."""+ factory = request.app.state.session_factory+ lines: list[str] = []++ try:+ async with get_session(factory) as session:+ # Page counts by freshness+ for status_val in ("fresh", "stale", "expired"):+ result = await session.execute(+ select(func.count()).select_from(Page).where(+ Page.freshness_status == status_val+ )+ )+ count = result.scalar() or 0+ lines.append(+ f'wikicode_pages_total{{status="{status_val}"}} {count}'+ )++ # Job counts by status+ for job_status in ("pending", "running", "completed", "failed"):+ result = await session.execute(+ select(func.count()).select_from(GenerationJob).where(+ GenerationJob.status == job_status+ )+ )+ count = result.scalar() or 0+ lines.append(+ f'wikicode_jobs_total{{status="{job_status}"}} {count}'+ )++ # Aggregate token usage from completed jobs+ for token_type, col in [+ ("input", func.sum(Page.input_tokens)),+ ("output", func.sum(Page.output_tokens)),+ ]:+ result = await session.execute(select(col))+ total = result.scalar() or 0+ lines.append(+ f'wikicode_tokens_total{{type="{token_type}"}} {total}'+ )+ except Exception:+ lines.append("wikicode_health 0")++ from starlette.responses import Response++ return Response(content="\n".join(lines) + "\n", media_type="text/plain")diff --git a/packages/server/src/wikicode/server/routers/jobs.py b/packages/server/src/wikicode/server/routers/jobs.pynew file mode 100644index 000000000..96fcc6df4--- /dev/null+++ b/packages/server/src/wikicode/server/routers/jobs.py@@ -0,0 +1,103 @@+"""/api/jobs — Generation job status and SSE progress stream."""++from __future__ import annotations++import asyncio+import json++from fastapi import APIRouter, Depends, HTTPException, Query, Request+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession+from starlette.responses import StreamingResponse++from wikicode.core.persistence import crud+from wikicode.core.persistence.database import get_session+from wikicode.core.persistence.models import GenerationJob+from wikicode.server.deps import get_db_session, verify_api_key+from wikicode.server.schemas import JobResponse++router = APIRouter(+ prefix="/api/jobs",+ tags=["jobs"],+ dependencies=[Depends(verify_api_key)],+)++[email protected]("", response_model=list[JobResponse])+async def list_jobs(+ repo_id: str | None = Query(None),+ status: str | None = Query(None),+ limit: int = Query(50, ge=1, le=200),+ offset: int = Query(0, ge=0),+ session: AsyncSession = Depends(get_db_session),+) -> list[JobResponse]:+ """List generation jobs, optionally filtered by repository or status."""+ q = select(GenerationJob)+ if repo_id:+ q = q.where(GenerationJob.repository_id == repo_id)+ if status:+ q = q.where(GenerationJob.status == status)+ q = q.order_by(GenerationJob.created_at.desc()).limit(limit).offset(offset)++ result = await session.execute(q)+ jobs = result.scalars().all()+ return [JobResponse.from_orm(j) for j in jobs]++[email protected]("/{job_id}", response_model=JobResponse)+async def get_job(+ job_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> JobResponse:+ """Get a single generation job by ID."""+ job = await crud.get_generation_job(session, job_id)+ if job is None:+ raise HTTPException(status_code=404, detail="Job not found")+ return JobResponse.from_orm(job)++[email protected]("/{job_id}/stream")+async def stream_job(job_id: str, request: Request) -> StreamingResponse:+ """SSE progress stream for a generation job.++ Emits ``event: progress`` every second until the job completes or fails,+ then emits ``event: done`` and closes.+ """+ factory = request.app.state.session_factory++ async def event_generator():+ while True:+ # Check if client disconnected+ if await request.is_disconnected():+ return++ async with get_session(factory) as session:+ job = await crud.get_generation_job(session, job_id)++ if job is None:+ data = json.dumps({"detail": "Job not found"})+ yield f"event: error\ndata: {data}\n\n"+ return++ progress = {+ "job_id": job.id,+ "status": job.status,+ "completed_pages": job.completed_pages,+ "total_pages": job.total_pages,+ "failed_pages": job.failed_pages,+ "current_level": job.current_level,+ }+ data = json.dumps(progress)+ yield f"event: progress\ndata: {data}\n\n"++ if job.status in ("completed", "failed"):+ yield f"event: done\ndata: {data}\n\n"+ return++ await asyncio.sleep(1)++ return StreamingResponse(+ event_generator(),+ media_type="text/event-stream",+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ )diff --git a/packages/server/src/wikicode/server/routers/pages.py b/packages/server/src/wikicode/server/routers/pages.pynew file mode 100644index 000000000..54d56005f--- /dev/null+++ b/packages/server/src/wikicode/server/routers/pages.py@@ -0,0 +1,107 @@+"""/api/pages — Wiki page CRUD endpoints.++Note: Routes with path suffixes (/versions, /regenerate) must be defined+BEFORE the catch-all {page_id:path} route, otherwise FastAPI's path+parameter greedily matches the suffix as part of the page_id.+"""++from __future__ import annotations++from urllib.parse import unquote++from fastapi import APIRouter, Depends, HTTPException, Query, Request+from sqlalchemy.ext.asyncio import AsyncSession++from wikicode.core.persistence import crud+from wikicode.server.deps import get_db_session, verify_api_key+from wikicode.server.schemas import PageResponse, PageVersionResponse++router = APIRouter(+ prefix="/api/pages",+ tags=["pages"],+ dependencies=[Depends(verify_api_key)],+)++[email protected]("", response_model=list[PageResponse])+async def list_pages(+ repo_id: str = Query(..., description="Repository ID"),+ page_type: str | None = Query(None, description="Filter by page type"),+ sort_by: str = Query("updated_at", description="Sort field: updated_at, confidence, created_at"),+ order: str = Query("desc", description="Sort order: asc or desc"),+ limit: int = Query(100, ge=1, le=500),+ offset: int = Query(0, ge=0),+ session: AsyncSession = Depends(get_db_session),+) -> list[PageResponse]:+ """List wiki pages for a repository."""+ pages = await crud.list_pages(+ session,+ repo_id,+ page_type=page_type,+ limit=limit,+ offset=offset,+ sort_by=sort_by,+ order=order,+ )+ return [PageResponse.from_orm(p) for p in pages]++[email protected]("/lookup", response_model=PageResponse)+async def get_page_by_query(+ page_id: str = Query(..., description="Page ID (e.g. file_page:src/main.py)"),+ session: AsyncSession = Depends(get_db_session),+) -> PageResponse:+ """Get a single wiki page by ID passed as query parameter.++ Use this endpoint when the page_id contains characters that are+ difficult to encode in a URL path.+ """+ page = await crud.get_page(session, page_id)+ if page is None:+ raise HTTPException(status_code=404, detail="Page not found")+ return PageResponse.from_orm(page)++[email protected]("/lookup/versions", response_model=list[PageVersionResponse])+async def get_page_versions_by_query(+ page_id: str = Query(..., description="Page ID"),+ limit: int = Query(50, ge=1, le=200),+ session: AsyncSession = Depends(get_db_session),+) -> list[PageVersionResponse]:+ """Get version history for a wiki page (page_id as query param)."""+ versions = await crud.get_page_versions(session, page_id, limit=limit)+ return [PageVersionResponse.from_orm(v) for v in versions]++[email protected]("/lookup/regenerate", status_code=202)+async def regenerate_page_by_query(+ page_id: str = Query(..., description="Page ID"),+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Force-regenerate a single wiki page (page_id as query param)."""+ page = await crud.get_page(session, page_id)+ if page is None:+ raise HTTPException(status_code=404, detail="Page not found")++ job = await crud.upsert_generation_job(+ session,+ repository_id=page.repository_id,+ status="pending",+ config={"mode": "single_page", "page_id": page_id},+ )+ return {"job_id": job.id, "status": "accepted"}++[email protected]("/{page_id:path}", response_model=PageResponse)+async def get_page(+ page_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> PageResponse:+ """Get a single wiki page by ID in path (e.g. ``file_page:src/main.py``).++ The page_id is URL-decoded automatically by FastAPI.+ """+ page = await crud.get_page(session, page_id)+ if page is None:+ raise HTTPException(status_code=404, detail="Page not found")+ return PageResponse.from_orm(page)diff --git a/packages/server/src/wikicode/server/routers/repos.py b/packages/server/src/wikicode/server/routers/repos.pynew file mode 100644index 000000000..120ee42cb--- /dev/null+++ b/packages/server/src/wikicode/server/routers/repos.py@@ -0,0 +1,181 @@+"""/api/repos — Repository CRUD + sync endpoints."""++from __future__ import annotations++from fastapi import APIRouter, Depends, HTTPException+from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from wikicode.core.persistence import crud+from wikicode.core.persistence.models import DeadCodeFinding, GraphNode, Page, Repository+from wikicode.server.deps import get_db_session, verify_api_key+from wikicode.server.schemas import RepoCreate, RepoResponse, RepoStatsResponse, RepoUpdate++router = APIRouter(+ prefix="/api/repos",+ tags=["repos"],+ dependencies=[Depends(verify_api_key)],+)++[email protected]("", response_model=RepoResponse, status_code=201)+async def create_repo(+ body: RepoCreate,+ session: AsyncSession = Depends(get_db_session),+) -> RepoResponse:+ """Register a new repository (or update if same local_path exists)."""+ repo = await crud.upsert_repository(+ session,+ name=body.name,+ local_path=body.local_path,+ url=body.url,+ default_branch=body.default_branch,+ settings=body.settings,+ )+ return RepoResponse.from_orm(repo)++[email protected]("", response_model=list[RepoResponse])+async def list_repos(+ session: AsyncSession = Depends(get_db_session),+) -> list[RepoResponse]:+ """List all registered repositories."""+ result = await session.execute(+ select(Repository).order_by(Repository.updated_at.desc())+ )+ repos = result.scalars().all()+ return [RepoResponse.from_orm(r) for r in repos]++[email protected]("/{repo_id}", response_model=RepoResponse)+async def get_repo(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> RepoResponse:+ """Get a single repository by ID."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ return RepoResponse.from_orm(repo)++[email protected]("/{repo_id}", response_model=RepoResponse)+async def update_repo(+ repo_id: str,+ body: RepoUpdate,+ session: AsyncSession = Depends(get_db_session),+) -> RepoResponse:+ """Update repository fields."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ if body.name is not None:+ repo.name = body.name+ if body.url is not None:+ repo.url = body.url+ if body.default_branch is not None:+ repo.default_branch = body.default_branch+ if body.settings is not None:+ import json++ repo.settings_json = json.dumps(body.settings)+ await session.flush()+ return RepoResponse.from_orm(repo)++[email protected]("/{repo_id}/stats", response_model=RepoStatsResponse)+async def get_repo_stats(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> RepoStatsResponse:+ """Get aggregate stats for a repository."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ file_count_result = await session.execute(+ select(func.count(GraphNode.id)).where(GraphNode.repository_id == repo_id)+ )+ file_count = file_count_result.scalar_one() or 0++ symbol_count_result = await session.execute(+ select(func.sum(GraphNode.symbol_count)).where(GraphNode.repository_id == repo_id)+ )+ symbol_count = int(symbol_count_result.scalar_one() or 0)++ entry_count_result = await session.execute(+ select(func.count(GraphNode.id)).where(+ GraphNode.repository_id == repo_id,+ GraphNode.is_entry_point == True, # noqa: E712+ )+ )+ entry_point_count = entry_count_result.scalar_one() or 0++ avg_conf_result = await session.execute(+ select(func.avg(Page.confidence)).where(Page.repository_id == repo_id)+ )+ avg_confidence = float(avg_conf_result.scalar_one() or 0.0)+ doc_coverage_pct = avg_confidence * 100++ dead_result = await session.execute(+ select(func.count(DeadCodeFinding.id)).where(+ DeadCodeFinding.repository_id == repo_id,+ DeadCodeFinding.kind == "unused_export",+ DeadCodeFinding.status == "open",+ )+ )+ dead_export_count = dead_result.scalar_one() or 0++ return RepoStatsResponse(+ file_count=file_count,+ symbol_count=symbol_count,+ entry_point_count=entry_point_count,+ doc_coverage_pct=doc_coverage_pct,+ freshness_score=doc_coverage_pct,+ dead_export_count=dead_export_count,+ )++[email protected]("/{repo_id}/sync", status_code=202)+async def sync_repo(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Trigger an incremental documentation sync for a repository.++ Creates a pending generation job and returns its ID.+ The actual sync runs asynchronously.+ """+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ job = await crud.upsert_generation_job(+ session,+ repository_id=repo_id,+ status="pending",+ )+ return {"job_id": job.id, "status": "accepted"}++[email protected]("/{repo_id}/full-resync", status_code=202)+async def full_resync(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Trigger a full re-generation of all documentation.++ Creates a pending generation job and returns its ID.+ """+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ job = await crud.upsert_generation_job(+ session,+ repository_id=repo_id,+ status="pending",+ config={"mode": "full_resync"},+ )+ return {"job_id": job.id, "status": "accepted"}diff --git a/packages/server/src/wikicode/server/routers/search.py b/packages/server/src/wikicode/server/routers/search.pynew file mode 100644index 000000000..b11e38f57--- /dev/null+++ b/packages/server/src/wikicode/server/routers/search.py@@ -0,0 +1,42 @@+"""/api/search — Semantic and full-text search."""++from __future__ import annotations++from fastapi import APIRouter, Depends, Query++from wikicode.server.deps import get_fts, get_vector_store, verify_api_key+from wikicode.server.schemas import SearchResultResponse++router = APIRouter(+ prefix="/api/search",+ tags=["search"],+ dependencies=[Depends(verify_api_key)],+)++[email protected]("", response_model=list[SearchResultResponse])+async def search(+ query: str = Query(..., min_length=1, description="Search query"),+ search_type: str = Query("semantic", description="semantic or fulltext"),+ limit: int = Query(10, ge=1, le=100),+ vector_store=Depends(get_vector_store),+ fts=Depends(get_fts),+) -> list[SearchResultResponse]:+ """Search wiki pages by semantic similarity or full-text match."""+ if search_type == "fulltext":+ results = await fts.search(query, limit=limit)+ else:+ results = await vector_store.search(query, limit=limit)++ return [+ SearchResultResponse(+ page_id=r.page_id,+ title=r.title,+ page_type=r.page_type,+ target_path=r.target_path,+ score=r.score,+ snippet=r.snippet,+ search_type=r.search_type,+ )+ for r in results+ ]diff --git a/packages/server/src/wikicode/server/routers/symbols.py b/packages/server/src/wikicode/server/routers/symbols.pynew file mode 100644index 000000000..5b13461a2--- /dev/null+++ b/packages/server/src/wikicode/server/routers/symbols.py@@ -0,0 +1,90 @@+"""/api/symbols — Symbol lookup and search."""++from __future__ import annotations++from fastapi import APIRouter, Depends, HTTPException, Query+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from wikicode.core.persistence.models import WikiSymbol+from wikicode.server.deps import get_db_session, verify_api_key+from wikicode.server.schemas import SymbolResponse++router = APIRouter(+ prefix="/api/symbols",+ tags=["symbols"],+ dependencies=[Depends(verify_api_key)],+)++[email protected]("", response_model=list[SymbolResponse])+async def search_symbols(+ repo_id: str = Query(..., description="Repository ID"),+ q: str = Query("", description="Search query (substring match on name)"),+ kind: str | None = Query(None, description="Filter by symbol kind"),+ language: str | None = Query(None, description="Filter by language"),+ limit: int = Query(50, ge=1, le=500),+ offset: int = Query(0, ge=0),+ session: AsyncSession = Depends(get_db_session),+) -> list[SymbolResponse]:+ """Search symbols by name, kind, or language."""+ query = select(WikiSymbol).where(WikiSymbol.repository_id == repo_id)++ if q:+ query = query.where(WikiSymbol.name.ilike(f"%{q}%"))+ if kind:+ query = query.where(WikiSymbol.kind == kind)+ if language:+ query = query.where(WikiSymbol.language == language)++ query = query.order_by(WikiSymbol.name).limit(limit).offset(offset)++ result = await session.execute(query)+ symbols = result.scalars().all()+ return [SymbolResponse.from_orm(s) for s in symbols]++[email protected]("/by-name/{name}", response_model=list[SymbolResponse])+async def lookup_by_name(+ name: str,+ repo_id: str = Query(..., description="Repository ID"),+ session: AsyncSession = Depends(get_db_session),+) -> list[SymbolResponse]:+ """Look up symbols by exact or fuzzy name match.++ Returns exact matches first, then LIKE matches, up to 10 results.+ """+ # Try exact match first+ result = await session.execute(+ select(WikiSymbol).where(+ WikiSymbol.repository_id == repo_id,+ WikiSymbol.name == name,+ )+ )+ exact = list(result.scalars().all())+ if exact:+ return [SymbolResponse.from_orm(s) for s in exact]++ # Fall back to LIKE match+ result = await session.execute(+ select(WikiSymbol)+ .where(+ WikiSymbol.repository_id == repo_id,+ WikiSymbol.name.ilike(f"%{name}%"),+ )+ .limit(10)+ )+ fuzzy = result.scalars().all()+ return [SymbolResponse.from_orm(s) for s in fuzzy]++[email protected]("/{symbol_db_id}", response_model=SymbolResponse)+async def get_symbol(+ symbol_db_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> SymbolResponse:+ """Get a single symbol by its database ID."""+ sym = await session.get(WikiSymbol, symbol_db_id)+ if sym is None:+ raise HTTPException(status_code=404, detail="Symbol not found")+ return SymbolResponse.from_orm(sym)diff --git a/packages/server/src/wikicode/server/routers/webhooks.py b/packages/server/src/wikicode/server/routers/webhooks.pynew file mode 100644index 000000000..f16146f14--- /dev/null+++ b/packages/server/src/wikicode/server/routers/webhooks.py@@ -0,0 +1,169 @@+"""/api/webhooks — GitHub and GitLab webhook handlers."""++from __future__ import annotations++import hashlib+import hmac+import json+import os++from fastapi import APIRouter, Depends, HTTPException, Request+from sqlalchemy.ext.asyncio import AsyncSession++from wikicode.core.persistence import crud+from wikicode.server.deps import get_db_session+from wikicode.server.schemas import WebhookResponse++router = APIRouter(prefix="/api/webhooks", tags=["webhooks"])++_GITHUB_SECRET = os.environ.get("WIKICODE_GITHUB_WEBHOOK_SECRET", "")+_GITLAB_TOKEN = os.environ.get("WIKICODE_GITLAB_WEBHOOK_TOKEN", "")+++def _verify_github_signature(body: bytes, signature_header: str) -> None:+ """Verify GitHub HMAC-SHA256 webhook signature."""+ if not _GITHUB_SECRET:+ return # No secret configured — skip verification (dev mode)++ if not signature_header.startswith("sha256="):+ raise HTTPException(status_code=401, detail="Missing signature prefix")++ expected = hmac.new(+ _GITHUB_SECRET.encode(),+ body,+ hashlib.sha256,+ ).hexdigest()++ if not hmac.compare_digest(f"sha256={expected}", signature_header):+ raise HTTPException(status_code=401, detail="Invalid signature")+++def _verify_gitlab_token(token_header: str) -> None:+ """Verify GitLab webhook token."""+ if not _GITLAB_TOKEN:+ return # No token configured — skip verification (dev mode)++ if not hmac.compare_digest(token_header, _GITLAB_TOKEN):+ raise HTTPException(status_code=401, detail="Invalid token")++[email protected]("/github", response_model=WebhookResponse)+async def github_webhook(+ request: Request,+ session: AsyncSession = Depends(get_db_session),+) -> WebhookResponse:+ """Receive and process GitHub webhook events.++ Verifies HMAC-SHA256 signature, stores the event, and enqueues a sync+ job for push events on the default branch.+ """+ body = await request.body()+ sig = request.headers.get("X-Hub-Signature-256", "")+ _verify_github_signature(body, sig)++ event_type = request.headers.get("X-GitHub-Event", "unknown")+ delivery_id = request.headers.get("X-GitHub-Delivery", "")+ payload = json.loads(body)++ # Try to find the repository by matching the clone URL+ repo_url = ""+ if "repository" in payload:+ repo_url = payload["repository"].get("clone_url", "")+ if not repo_url:+ repo_url = payload["repository"].get("html_url", "")++ # Store the webhook event+ event = await crud.store_webhook_event(+ session,+ provider="github",+ event_type=event_type,+ payload=payload,+ delivery_id=delivery_id,+ )++ # For push events: create a sync job+ if event_type == "push":+ ref = payload.get("ref", "")+ # Only sync pushes to the default branch+ if ref.startswith("refs/heads/"):+ branch = ref[len("refs/heads/"):]+ # Find matching repo by URL+ from sqlalchemy import select+ from wikicode.core.persistence.models import Repository++ result = await session.execute(+ select(Repository).where(Repository.url.contains(repo_url[:50]))+ )+ repo = result.scalar_one_or_none()+ if repo and branch == repo.default_branch:+ job = await crud.upsert_generation_job(+ session,+ repository_id=repo.id,+ status="pending",+ config={+ "mode": "incremental",+ "trigger": "webhook",+ "before": payload.get("before", ""),+ "after": payload.get("after", ""),+ },+ )+ await crud.mark_webhook_processed(session, event.id, job_id=job.id)++ return WebhookResponse(event_id=event.id)++[email protected]("/gitlab", response_model=WebhookResponse)+async def gitlab_webhook(+ request: Request,+ session: AsyncSession = Depends(get_db_session),+) -> WebhookResponse:+ """Receive and process GitLab webhook events.++ Verifies X-Gitlab-Token header, stores the event, and enqueues a sync+ job for push events on the default branch.+ """+ token = request.headers.get("X-Gitlab-Token", "")+ _verify_gitlab_token(token)++ body = await request.body()+ payload = json.loads(body)+ event_type = request.headers.get("X-Gitlab-Event", "unknown")++ event = await crud.store_webhook_event(+ session,+ provider="gitlab",+ event_type=event_type,+ payload=payload,+ )++ # For push events: create a sync job+ if event_type == "Push Hook":+ ref = payload.get("ref", "")+ if ref.startswith("refs/heads/"):+ branch = ref[len("refs/heads/"):]+ project_url = payload.get("project", {}).get("web_url", "")++ from sqlalchemy import select+ from wikicode.core.persistence.models import Repository++ result = await session.execute(+ select(Repository).where(+ Repository.url.contains(project_url[:50])+ )+ )+ repo = result.scalar_one_or_none()+ if repo and branch == repo.default_branch:+ job = await crud.upsert_generation_job(+ session,+ repository_id=repo.id,+ status="pending",+ config={+ "mode": "incremental",+ "trigger": "webhook",+ "before": payload.get("before", ""),+ "after": payload.get("after", ""),+ },+ )+ await crud.mark_webhook_processed(session, event.id, job_id=job.id)++ return WebhookResponse(event_id=event.id)diff --git a/packages/server/src/wikicode/server/scheduler.py b/packages/server/src/wikicode/server/scheduler.pynew file mode 100644index 000000000..c54e5fa65--- /dev/null+++ b/packages/server/src/wikicode/server/scheduler.py@@ -0,0 +1,114 @@+"""APScheduler background jobs for WikiCode server.++Two recurring jobs:+1. Staleness checker — finds stale wiki pages and queues regeneration.+2. Polling fallback — catches missed webhooks by comparing HEAD commits.+"""++from __future__ import annotations++import logging+from typing import TYPE_CHECKING++from apscheduler.schedulers.asyncio import AsyncIOScheduler+from apscheduler.triggers.interval import IntervalTrigger++if TYPE_CHECKING:+ from sqlalchemy.ext.asyncio import async_sessionmaker, AsyncSession++logger = logging.getLogger(__name__)+++def setup_scheduler(+ session_factory: "async_sessionmaker[AsyncSession]",+ *,+ staleness_interval_minutes: int = 15,+ polling_interval_minutes: int = 15,+) -> AsyncIOScheduler:+ """Create and configure the APScheduler instance.++ Does NOT start the scheduler — caller must call ``scheduler.start()``.+ """+ scheduler = AsyncIOScheduler()++ async def check_staleness() -> None:+ """Find stale pages and log them for regeneration."""+ from sqlalchemy import select++ from wikicode.core.persistence.database import get_session+ from wikicode.core.persistence.models import Page, Repository++ try:+ async with get_session(session_factory) as session:+ result = await session.execute(select(Repository))+ repos = result.scalars().all()++ for repo in repos:+ stale_result = await session.execute(+ select(Page).where(+ Page.repository_id == repo.id,+ Page.freshness_status.in_(["stale", "expired"]),+ )+ )+ stale = stale_result.scalars().all()+ if stale:+ logger.info(+ "staleness_check",+ extra={+ "repo_id": repo.id,+ "repo_name": repo.name,+ "stale_count": len(stale),+ },+ )+ except Exception:+ logger.exception("staleness_check_failed")++ async def polling_fallback() -> None:+ """Check if repos have diverged from their last_sync_commit."""+ from sqlalchemy import select++ from wikicode.core.persistence.database import get_session+ from wikicode.core.persistence.models import Repository++ try:+ async with get_session(session_factory) as session:+ result = await session.execute(select(Repository))+ repos = result.scalars().all()++ for repo in repos:+ if not repo.local_path:+ continue+ # Compare head_commit with actual git HEAD.+ # This is a lightweight check — full sync is triggered+ # only if commits differ.+ # NOTE: when a full sync is implemented here, pass+ # extra_exclude_patterns=repo.settings.get("exclude_patterns", [])+ # to FileTraverser so user-configured exclusions are respected.+ logger.debug(+ "polling_check",+ extra={+ "repo_id": repo.id,+ "head_commit": repo.head_commit,+ "exclude_patterns": repo.settings.get("exclude_patterns", [])+ if repo.settings+ else [],+ },+ )+ except Exception:+ logger.exception("polling_fallback_failed")++ scheduler.add_job(+ check_staleness,+ trigger=IntervalTrigger(minutes=staleness_interval_minutes),+ id="staleness_check",+ replace_existing=True,+ )++ scheduler.add_job(+ polling_fallback,+ trigger=IntervalTrigger(minutes=polling_interval_minutes),+ id="polling_fallback",+ replace_existing=True,+ )++ return schedulerdiff --git a/packages/server/src/wikicode/server/schemas.py b/packages/server/src/wikicode/server/schemas.pynew file mode 100644index 000000000..6d981d012--- /dev/null+++ b/packages/server/src/wikicode/server/schemas.py@@ -0,0 +1,594 @@+"""Pydantic request/response models for the WikiCode REST API."""++from __future__ import annotations++import json+from datetime import datetime++from pydantic import BaseModel, Field+++# ---------------------------------------------------------------------------+# Repository+# ---------------------------------------------------------------------------+++class RepoCreate(BaseModel):+ name: str+ local_path: str+ url: str = ""+ default_branch: str = "main"+ settings: dict | None = None+++class RepoUpdate(BaseModel):+ name: str | None = None+ url: str | None = None+ default_branch: str | None = None+ settings: dict | None = None+++class RepoResponse(BaseModel):+ id: str+ name: str+ url: str+ local_path: str+ default_branch: str+ head_commit: str | None+ settings: dict+ created_at: datetime+ updated_at: datetime++ @classmethod+ def from_orm(cls, obj: object) -> RepoResponse:+ return cls(+ id=obj.id, # type: ignore[attr-defined]+ name=obj.name, # type: ignore[attr-defined]+ url=obj.url, # type: ignore[attr-defined]+ local_path=obj.local_path, # type: ignore[attr-defined]+ default_branch=obj.default_branch, # type: ignore[attr-defined]+ head_commit=obj.head_commit, # type: ignore[attr-defined]+ settings=json.loads(obj.settings_json), # type: ignore[attr-defined]+ created_at=obj.created_at, # type: ignore[attr-defined]+ updated_at=obj.updated_at, # type: ignore[attr-defined]+ )+++# ---------------------------------------------------------------------------+# Pages+# ---------------------------------------------------------------------------+++class PageResponse(BaseModel):+ id: str+ repository_id: str+ page_type: str+ title: str+ content: str+ target_path: str+ source_hash: str+ model_name: str+ provider_name: str+ input_tokens: int+ output_tokens: int+ cached_tokens: int+ generation_level: int+ version: int+ confidence: float+ freshness_status: str+ metadata: dict+ created_at: datetime+ updated_at: datetime++ @classmethod+ def from_orm(cls, obj: object) -> PageResponse:+ return cls(+ id=obj.id, # type: ignore[attr-defined]+ repository_id=obj.repository_id, # type: ignore[attr-defined]+ page_type=obj.page_type, # type: ignore[attr-defined]+ title=obj.title, # type: ignore[attr-defined]+ content=obj.content, # type: ignore[attr-defined]+ target_path=obj.target_path, # type: ignore[attr-defined]+ source_hash=obj.source_hash, # type: ignore[attr-defined]+ model_name=obj.model_name, # type: ignore[attr-defined]+ provider_name=obj.provider_name, # type: ignore[attr-defined]+ input_tokens=obj.input_tokens, # type: ignore[attr-defined]+ output_tokens=obj.output_tokens, # type: ignore[attr-defined]+ cached_tokens=obj.cached_tokens, # type: ignore[attr-defined]+ generation_level=obj.generation_level, # type: ignore[attr-defined]+ version=obj.version, # type: ignore[attr-defined]+ 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]+ created_at=obj.created_at, # type: ignore[attr-defined]+ updated_at=obj.updated_at, # type: ignore[attr-defined]+ )+++class PageVersionResponse(BaseModel):+ id: str+ page_id: str+ version: int+ page_type: str+ title: str+ content: str+ source_hash: str+ model_name: str+ provider_name: str+ input_tokens: int+ output_tokens: int+ confidence: float+ archived_at: datetime++ @classmethod+ def from_orm(cls, obj: object) -> PageVersionResponse:+ return cls(+ id=obj.id, # type: ignore[attr-defined]+ page_id=obj.page_id, # type: ignore[attr-defined]+ version=obj.version, # type: ignore[attr-defined]+ page_type=obj.page_type, # type: ignore[attr-defined]+ title=obj.title, # type: ignore[attr-defined]+ content=obj.content, # type: ignore[attr-defined]+ source_hash=obj.source_hash, # type: ignore[attr-defined]+ model_name=obj.model_name, # type: ignore[attr-defined]+ provider_name=obj.provider_name, # type: ignore[attr-defined]+ input_tokens=obj.input_tokens, # type: ignore[attr-defined]+ output_tokens=obj.output_tokens, # type: ignore[attr-defined]+ confidence=obj.confidence, # type: ignore[attr-defined]+ archived_at=obj.archived_at, # type: ignore[attr-defined]+ )+++# ---------------------------------------------------------------------------+# Jobs+# ---------------------------------------------------------------------------+++class JobResponse(BaseModel):+ id: str+ repository_id: str+ status: str+ provider_name: str+ model_name: str+ total_pages: int+ completed_pages: int+ failed_pages: int+ current_level: int+ error_message: str | None+ config: dict+ created_at: datetime+ updated_at: datetime+ started_at: datetime | None+ finished_at: datetime | None++ @classmethod+ def from_orm(cls, obj: object) -> JobResponse:+ return cls(+ id=obj.id, # type: ignore[attr-defined]+ repository_id=obj.repository_id, # type: ignore[attr-defined]+ status=obj.status, # type: ignore[attr-defined]+ provider_name=obj.provider_name, # type: ignore[attr-defined]+ model_name=obj.model_name, # type: ignore[attr-defined]+ total_pages=obj.total_pages, # type: ignore[attr-defined]+ completed_pages=obj.completed_pages, # type: ignore[attr-defined]+ failed_pages=obj.failed_pages, # type: ignore[attr-defined]+ current_level=obj.current_level, # type: ignore[attr-defined]+ error_message=obj.error_message, # type: ignore[attr-defined]+ config=json.loads(obj.config_json), # type: ignore[attr-defined]+ created_at=obj.created_at, # type: ignore[attr-defined]+ updated_at=obj.updated_at, # type: ignore[attr-defined]+ started_at=obj.started_at, # type: ignore[attr-defined]+ finished_at=obj.finished_at, # type: ignore[attr-defined]+ )+++# ---------------------------------------------------------------------------+# Search+# ---------------------------------------------------------------------------+++class SearchRequest(BaseModel):+ query: str+ search_type: str = "semantic"+ limit: int = Field(default=10, ge=1, le=100)+++class SearchResultResponse(BaseModel):+ page_id: str+ title: str+ page_type: str+ target_path: str+ score: float+ snippet: str+ search_type: str+++# ---------------------------------------------------------------------------+# Symbols+# ---------------------------------------------------------------------------+++class SymbolResponse(BaseModel):+ id: str+ repository_id: str+ file_path: str+ symbol_id: str+ name: str+ qualified_name: str+ kind: str+ signature: str+ start_line: int+ end_line: int+ docstring: str | None+ visibility: str+ is_async: bool+ complexity_estimate: int+ language: str+ parent_name: str | None++ @classmethod+ def from_orm(cls, obj: object) -> SymbolResponse:+ return cls(+ id=obj.id, # type: ignore[attr-defined]+ repository_id=obj.repository_id, # type: ignore[attr-defined]+ file_path=obj.file_path, # type: ignore[attr-defined]+ symbol_id=obj.symbol_id, # type: ignore[attr-defined]+ name=obj.name, # type: ignore[attr-defined]+ qualified_name=obj.qualified_name, # type: ignore[attr-defined]+ kind=obj.kind, # type: ignore[attr-defined]+ signature=obj.signature, # type: ignore[attr-defined]+ start_line=obj.start_line, # type: ignore[attr-defined]+ end_line=obj.end_line, # type: ignore[attr-defined]+ docstring=obj.docstring, # type: ignore[attr-defined]+ visibility=obj.visibility, # type: ignore[attr-defined]+ is_async=obj.is_async, # type: ignore[attr-defined]+ complexity_estimate=obj.complexity_estimate, # type: ignore[attr-defined]+ language=obj.language, # type: ignore[attr-defined]+ parent_name=obj.parent_name, # type: ignore[attr-defined]+ )+++# ---------------------------------------------------------------------------+# Graph+# ---------------------------------------------------------------------------+++class GraphNodeResponse(BaseModel):+ node_id: str+ node_type: str+ language: str+ symbol_count: int+ pagerank: float+ betweenness: float+ community_id: int+ is_test: bool = False+ is_entry_point: bool = False+++class GraphEdgeResponse(BaseModel):+ source: str+ target: str+ imported_names: list[str]+++class GraphExportResponse(BaseModel):+ nodes: list[GraphNodeResponse]+ links: list[GraphEdgeResponse]+++# ---------------------------------------------------------------------------+# Webhooks+# ---------------------------------------------------------------------------+++class WebhookResponse(BaseModel):+ event_id: str+ status: str = "accepted"+++# ---------------------------------------------------------------------------+# Git Intelligence+# ---------------------------------------------------------------------------+++class GitMetadataResponse(BaseModel):+ file_path: str+ commit_count_total: int+ commit_count_90d: int+ commit_count_30d: int+ first_commit_at: datetime | None+ last_commit_at: datetime | None+ primary_owner_name: str | None+ primary_owner_email: str | None+ primary_owner_commit_pct: float | None+ top_authors: list[dict]+ significant_commits: list[dict]+ co_change_partners: list[dict]+ is_hotspot: bool+ is_stable: bool+ churn_percentile: float+ age_days: int++ @classmethod+ def from_orm(cls, obj: object) -> GitMetadataResponse:+ return cls(+ file_path=obj.file_path, # type: ignore[attr-defined]+ commit_count_total=obj.commit_count_total, # type: ignore[attr-defined]+ commit_count_90d=obj.commit_count_90d, # type: ignore[attr-defined]+ commit_count_30d=obj.commit_count_30d, # type: ignore[attr-defined]+ first_commit_at=obj.first_commit_at, # type: ignore[attr-defined]+ last_commit_at=obj.last_commit_at, # type: ignore[attr-defined]+ primary_owner_name=obj.primary_owner_name, # type: ignore[attr-defined]+ primary_owner_email=obj.primary_owner_email, # type: ignore[attr-defined]+ primary_owner_commit_pct=obj.primary_owner_commit_pct, # type: ignore[attr-defined]+ top_authors=json.loads(obj.top_authors_json), # type: ignore[attr-defined]+ significant_commits=json.loads(obj.significant_commits_json), # type: ignore[attr-defined]+ co_change_partners=json.loads(obj.co_change_partners_json), # type: ignore[attr-defined]+ is_hotspot=obj.is_hotspot, # type: ignore[attr-defined]+ is_stable=obj.is_stable, # type: ignore[attr-defined]+ churn_percentile=obj.churn_percentile, # type: ignore[attr-defined]+ age_days=obj.age_days, # type: ignore[attr-defined]+ )+++class HotspotResponse(BaseModel):+ file_path: str+ commit_count_90d: int+ churn_percentile: float+ primary_owner: str | None+ is_hotspot: bool+++class OwnershipEntry(BaseModel):+ module_path: str+ primary_owner: str | None+ owner_pct: float | None+ file_count: int+ is_silo: bool+++class GitSummaryResponse(BaseModel):+ total_files: int+ hotspot_count: int+ stable_count: int+ average_churn_percentile: float+ top_owners: list[dict]+++# ---------------------------------------------------------------------------+# Dead Code+# ---------------------------------------------------------------------------+++class DeadCodeFindingResponse(BaseModel):+ id: str+ kind: str+ file_path: str+ symbol_name: str | None+ symbol_kind: str | None+ confidence: float+ reason: str+ lines: int+ safe_to_delete: bool+ primary_owner: str | None+ status: str+ note: str | None++ @classmethod+ def from_orm(cls, obj: object) -> DeadCodeFindingResponse:+ return cls(+ id=obj.id, # type: ignore[attr-defined]+ kind=obj.kind, # type: ignore[attr-defined]+ file_path=obj.file_path, # type: ignore[attr-defined]+ symbol_name=obj.symbol_name, # type: ignore[attr-defined]+ symbol_kind=obj.symbol_kind, # type: ignore[attr-defined]+ confidence=obj.confidence, # type: ignore[attr-defined]+ reason=obj.reason, # type: ignore[attr-defined]+ lines=obj.lines, # type: ignore[attr-defined]+ safe_to_delete=obj.safe_to_delete, # type: ignore[attr-defined]+ primary_owner=obj.primary_owner, # type: ignore[attr-defined]+ status=obj.status, # type: ignore[attr-defined]+ note=obj.note, # type: ignore[attr-defined]+ )+++class DeadCodePatchRequest(BaseModel):+ status: str+ note: str | None = None+++class DeadCodeSummaryResponse(BaseModel):+ total_findings: int+ confidence_summary: dict+ deletable_lines: int+ total_lines: int+ by_kind: dict+++# ---------------------------------------------------------------------------+# Repo Stats+# ---------------------------------------------------------------------------+++class RepoStatsResponse(BaseModel):+ file_count: int+ symbol_count: int+ entry_point_count: int+ doc_coverage_pct: float+ freshness_score: float+ dead_export_count: int+++# ---------------------------------------------------------------------------+# Module Graph+# ---------------------------------------------------------------------------+++class ModuleNodeResponse(BaseModel):+ module_id: str+ file_count: int+ symbol_count: int+ avg_pagerank: float+ doc_coverage_pct: float+++class ModuleEdgeResponse(BaseModel):+ source: str+ target: str+ edge_count: int+++class ModuleGraphResponse(BaseModel):+ nodes: list[ModuleNodeResponse]+ edges: list[ModuleEdgeResponse]+++# ---------------------------------------------------------------------------+# Ego Graph+# ---------------------------------------------------------------------------+++class EgoGraphResponse(BaseModel):+ nodes: list[GraphNodeResponse]+ links: list[GraphEdgeResponse]+ center_node_id: str+ center_git_meta: GitMetadataResponse | None+ inbound_count: int+ outbound_count: int+++class NodeSearchResult(BaseModel):+ node_id: str+ language: str+ symbol_count: int+++# ---------------------------------------------------------------------------+# Dead Code Graph+# ---------------------------------------------------------------------------+++class DeadCodeGraphNodeResponse(BaseModel):+ node_id: str+ node_type: str+ language: str+ symbol_count: int+ pagerank: float+ betweenness: float+ community_id: int+ is_test: bool = False+ is_entry_point: bool = False+ confidence_group: str # "certain" | "likely"+++class DeadCodeGraphResponse(BaseModel):+ nodes: list[DeadCodeGraphNodeResponse]+ links: list[GraphEdgeResponse]+++# ---------------------------------------------------------------------------+# Hot Files Graph+# ---------------------------------------------------------------------------+++class HotFilesNodeResponse(BaseModel):+ node_id: str+ node_type: str+ language: str+ symbol_count: int+ pagerank: float+ betweenness: float+ community_id: int+ is_test: bool = False+ is_entry_point: bool = False+ commit_count: int+++class HotFilesGraphResponse(BaseModel):+ nodes: list[HotFilesNodeResponse]+ links: list[GraphEdgeResponse]+++# ---------------------------------------------------------------------------+# Health+# ---------------------------------------------------------------------------+++class HealthResponse(BaseModel):+ status: str+ db: str+ version: str+++# ---------------------------------------------------------------------------+# Decisions+# ---------------------------------------------------------------------------+++class DecisionRecordResponse(BaseModel):+ id: str+ repository_id: str+ title: str+ status: str+ context: str+ decision: str+ rationale: str+ alternatives: list[str]+ consequences: list[str]+ affected_files: list[str]+ affected_modules: list[str]+ tags: list[str]+ source: str+ evidence_commits: list[str]+ evidence_file: str | None+ evidence_line: int | None+ confidence: float+ staleness_score: float+ superseded_by: str | None+ last_code_change: datetime | None+ created_at: datetime+ updated_at: datetime++ @classmethod+ def from_orm(cls, obj: object) -> DecisionRecordResponse:+ return cls(+ id=obj.id, # type: ignore[attr-defined]+ repository_id=obj.repository_id, # type: ignore[attr-defined]+ title=obj.title, # type: ignore[attr-defined]+ status=obj.status, # type: ignore[attr-defined]+ context=obj.context, # type: ignore[attr-defined]+ decision=obj.decision, # type: ignore[attr-defined]+ rationale=obj.rationale, # type: ignore[attr-defined]+ alternatives=json.loads(obj.alternatives_json), # type: ignore[attr-defined]+ consequences=json.loads(obj.consequences_json), # type: ignore[attr-defined]+ affected_files=json.loads(obj.affected_files_json), # type: ignore[attr-defined]+ affected_modules=json.loads(obj.affected_modules_json), # type: ignore[attr-defined]+ tags=json.loads(obj.tags_json), # type: ignore[attr-defined]+ source=obj.source, # type: ignore[attr-defined]+ evidence_commits=json.loads(obj.evidence_commits_json), # type: ignore[attr-defined]+ evidence_file=obj.evidence_file, # type: ignore[attr-defined]+ evidence_line=obj.evidence_line, # type: ignore[attr-defined]+ confidence=obj.confidence, # type: ignore[attr-defined]+ staleness_score=obj.staleness_score, # type: ignore[attr-defined]+ superseded_by=obj.superseded_by, # type: ignore[attr-defined]+ last_code_change=obj.last_code_change, # type: ignore[attr-defined]+ created_at=obj.created_at, # type: ignore[attr-defined]+ updated_at=obj.updated_at, # type: ignore[attr-defined]+ )+++class DecisionCreate(BaseModel):+ title: str+ context: str = ""+ decision: str = ""+ rationale: str = ""+ alternatives: list[str] = []+ consequences: list[str] = []+ affected_files: list[str] = []+ affected_modules: list[str] = []+ tags: list[str] = []+++class DecisionStatusUpdate(BaseModel):+ status: str+ superseded_by: str | None = Nonediff --git a/packages/web/.gitignore b/packages/web/.gitignorenew file mode 100644index 000000000..443127d6b--- /dev/null+++ b/packages/web/.gitignore@@ -0,0 +1,32 @@+# dependencies+/node_modules+/.pnp+.pnp.*+__pnpm-store/++# next.js+/.next/+/out/++# production+/build++# misc+.DS_Store+*.pem++# debug+npm-debug.log*+yarn-debug.log*+yarn-error.log*+.pnpm-debug.log*++# env files+.env*.local++# vercel+.vercel++# typescript+*.tsbuildinfo+next-env.d.tsdiff --git a/packages/web/FRONTEND_BUILD_STATUS.md b/packages/web/FRONTEND_BUILD_STATUS.mdnew file mode 100644index 000000000..0ebf94af1--- /dev/null+++ b/packages/web/FRONTEND_BUILD_STATUS.md@@ -0,0 +1,608 @@+# WikiCode 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 WikiCode is configurable here.++**Sections:**++#### API Connection+- API server URL (reads/writes `NEXT_PUBLIC_WIKICODE_API_URL` via `.env.local` or just localStorage)+- API key (stored in `localStorage` as `wikicode_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 `wikicode_default_provider` and `wikicode_default_model`+- Used as defaults when triggering init/sync from UI++#### Embedder Config+- Embedder dropdown: `mock` | `gemini`+- Embedding dimensions (default 768)+- Note: "Set WIKICODE_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: `WIKICODE_GITHUB_WEBHOOK_SECRET`, `WIKICODE_GITLAB_WEBHOOK_TOKEN`+- Copy-to-clipboard buttons++#### MCP Config (display only)+- Auto-generated MCP config for Claude Code / Cursor / Cline+- Shows `wikicode 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` | `wikicode update` |+| Full Resync | `POST /api/repos/{id}/full-resync` | `wikicode 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/README.md b/packages/web/README.mdnew file mode 100644index 000000000..fdde857a7--- /dev/null+++ b/packages/web/README.md@@ -0,0 +1,148 @@+# WikiCode Web UI++Next.js 15 frontend for the WikiCode codebase documentation engine. Displays AI-generated wiki pages, dependency graphs, symbol indexes, git analytics, and dead code analysis for any indexed codebase.++**Stack:** Next.js 15 (App Router) · Tailwind CSS v4 · Radix UI · SWR · D3.js · Shiki · Framer Motion++---++## File Map++### Config & Root++| File | Purpose |+|------|---------|+| `package.json` | Dependencies: Next.js 15, React 19, Tailwind v4, all Radix UI packages, SWR, D3, Shiki, Framer Motion, cmdk |+| `tsconfig.json` | Strict TypeScript, `@/*` path alias → `./src/*` |+| `next.config.ts` | Standalone output, `/api/*` proxy rewrite to `WIKICODE_API_URL`, `optimizePackageImports` |+| `postcss.config.mjs` | `@tailwindcss/postcss` plugin (Tailwind v4 CSS-first — no `tailwind.config.ts`) |+| `.gitignore` | Standard Next.js ignores |++### Styles++| File | Purpose |+|------|---------|+| `src/styles/globals.css` | Full design system — `@import "tailwindcss"` + `@theme {}` block with all CSS variables: surfaces (`--bg-base`, `--bg-surface`, `--bg-elevated`), borders, text, accent blue (`#5B9CF6`), confidence colors (fresh/stale/outdated), language colors, edge colors, typography scale, spacing, radii, z-index, animation easing. Also: prose overrides for wiki MDX content. |++### API Client (`src/lib/api/`)++| File | Purpose |+|------|---------|+| `types.ts` | All TypeScript interfaces mirroring backend schemas: `RepoResponse`, `PageResponse`, `PageVersionResponse`, `JobResponse`, `JobProgressEvent`, `SearchResultResponse`, `SymbolResponse`, `GraphExportResponse`, `GitMetadataResponse`, `HotspotResponse`, `OwnershipEntry`, `DeadCodeFindingResponse`, `HealthResponse`, `WebhookResponse`, `ApiError` |+| `client.ts` | Base fetch wrapper — `apiGet`, `apiPost`, `apiPatch`. Reads API key from `localStorage` (browser) or `WIKICODE_API_KEY` env var (server). Throws `ApiClientError` with status code on failures. |+| `repos.ts` | `listRepos`, `getRepo`, `createRepo`, `updateRepo`, `syncRepo`, `fullResyncRepo` |+| `pages.ts` | `listPages`, `getPageById` (uses `/api/pages/lookup?page_id=`), `getPageVersions`, `regeneratePage` |+| `search.ts` | `search` — supports `fts`, `semantic`, `hybrid` search types |+| `jobs.ts` | `listJobs`, `getJob`, `getJobStreamUrl` |+| `symbols.ts` | `listSymbols`, `lookupSymbolByName`, `getSymbolById` |+| `graph.ts` | `getGraph`, `getGraphPath` |+| `git.ts` | `getGitMetadata`, `getHotspots`, `getOwnership`, `getCoChanges`, `getGitSummary` |+| `dead-code.ts` | `listDeadCode`, `analyzeDeadCode`, `getDeadCodeSummary`, `patchDeadCodeFinding` |+| `health.ts` | `getHealth` |++### Hooks (`src/lib/hooks/`)++| File | Purpose |+|------|---------|+| `use-repo.ts` | `useRepos`, `useRepo` — SWR hooks with 30s background refresh |+| `use-page.ts` | `usePage`, `usePageVersions` — SWR hooks for wiki page data |+| `use-search.ts` | `useSearch` — debounced search (300ms), min 2 chars, SWR |+| `use-debounce.ts` | Generic debounce hook |+| `use-sse.ts` | SSE hook for job progress — named event handlers (progress/done/error), auto-reconnect with exponential backoff, max retries |+| `use-graph.ts` | `useGraph` — SWR with no revalidate on focus/reconnect (graph data is stable) |++### Utilities (`src/lib/utils/`)++| File | Purpose |+|------|---------|+| `cn.ts` | `cn()` — `clsx` + `tailwind-merge` combinator |+| `format.ts` | `formatNumber`, `formatTokens`, `formatCost`, `formatRelativeTime`, `formatDate`, `formatDateTime`, `formatLOC`, `truncatePath`, `formatConfidence`, `formatProgress` |+| `confidence.ts` | `FreshnessStatus` type, `scoreToStatus`, `statusColor`, `statusTextClass`, `statusBadgeClasses`, `statusLabel`, `LANGUAGE_COLORS`, `languageColor`, `EDGE_COLORS`, `edgeColor` |++### UI Primitives (`src/components/ui/`)++All built on Radix UI with WikiCode design tokens:++| File | Component |+|------|-----------|+| `button.tsx` | CVA variants: default/destructive/outline/secondary/ghost/link × sm/md/lg/icon sizes |+| `badge.tsx` | CVA variants: default/fresh/stale/outdated/accent/outline |+| `card.tsx` | `Card`, `CardHeader`, `CardTitle`, `CardDescription`, `CardContent`, `CardFooter` |+| `separator.tsx` | Radix Separator |+| `input.tsx` | Styled text input |+| `skeleton.tsx` | `animate-pulse` loading skeleton |+| `tabs.tsx` | Radix Tabs |+| `tooltip.tsx` | Radix Tooltip with portal |+| `dialog.tsx` | Radix Dialog with overlay and close button |+| `scroll-area.tsx` | Radix ScrollArea with styled scrollbar |+| `select.tsx` | Full Radix Select with all sub-components |++### Shared Components (`src/components/shared/`)++| File | Component |+|------|-----------|+| `stat-card.tsx` | Dashboard stat card — label, value, description, optional icon |+| `empty-state.tsx` | Empty state — icon, title, description, optional action button |++### Wiki Components (`src/components/wiki/`)++| File | Component |+|------|-----------|+| `confidence-badge.tsx` | Freshness badge — fresh/stale/outdated states, animated pulse on stale, tooltip with date |++### Layout (`src/components/layout/`)++| File | Component |+|------|-----------|+| `sidebar.tsx` | Global sidebar — WikiCode logo, nav links (Dashboard, Settings), collapsible per-repo tree with all wiki pages, active state highlighting |++### Pages (`src/app/`)++| Route | File | Status |+|-------|------|--------|+| `/` | `page.tsx` | **Built** — stat cards, repo list, recent jobs |+| `layout.tsx` | Root layout | **Built** — Geist fonts, TooltipProvider, sidebar |+| `/repos/[id]` | `repos/[id]/page.tsx` | **Built** — git stats, head commit, overview content |+| `/repos/[id]/layout.tsx` | Repo layout | **Built** |+| `/repos/[id]/wiki/[...slug]` | `wiki/[...slug]/page.tsx` | **Built** — MDX pipeline with Shiki highlighting, Mermaid diagrams, sticky ToC, regenerate button |+| `/repos/[id]/search` | `search/page.tsx` | **Built** — debounce, type toggle, cmdk palette, result cards |+| `/repos/[id]/graph` | `graph/page.tsx` | **Built** — D3 canvas, zoom/pan, tooltips, filter panel, minimap |+| `/repos/[id]/symbols` | `symbols/page.tsx` | **Built** — sortable table, kind/language filters, detail drawer |+| `/repos/[id]/coverage` | `coverage/page.tsx` | **Built** — donut chart, freshness table, per-file regenerate |+| `/repos/[id]/ownership` | `ownership/page.tsx` | **Built** — granularity toggle, silo badges, contributor chart |+| `/repos/[id]/hotspots` | `hotspots/page.tsx` | **Built** — ranked table, churn bars, owner leaderboard |+| `/repos/[id]/dead-code` | `dead-code/page.tsx` | **Built** — tabs, row actions, bulk select, analyze trigger |+| `/settings` | `settings/page.tsx` | **Built** — connection, provider, webhook, MCP sections |++---++## Development++```powershell+# From repo root+$env:WIKICODE_API_URL = "http://localhost:7337"+npm run dev --workspace packages/web+# Open http://localhost:3000+```++Requires the WikiCode API server running on port 7337. See `TESTING_GUIDE.md` in the repo root.++```powershell+# Type check+npm run type-check --workspace packages/web++# Lint+npm run lint --workspace packages/web+```++---++## Architecture Notes++**Server vs Client components:** Default to RSC. Add `"use client"` only for interactivity (D3, command palette, SSE hooks, form state). Data fetching in RSC via direct `apiGet()` calls; client-side revalidation via SWR hooks.++**API proxy:** `next.config.ts` rewrites `/api/*` → `WIKICODE_API_URL/api/*` so the frontend never hard-codes the backend URL and CORS is handled at the proxy layer.++**Design tokens:** Everything uses CSS variables defined in `globals.css`. Changing the design means changing one file. No Tailwind config needed (v4 CSS-first).++**Embedder for search:** The backend uses `MockEmbedder` by default. Set `WIKICODE_EMBEDDER=gemini` when starting the server to activate real semantic search via `gemini-embedding-001`.diff --git a/packages/web/next.config.ts b/packages/web/next.config.tsnew file mode 100644index 000000000..c7e532f2f--- /dev/null+++ b/packages/web/next.config.ts@@ -0,0 +1,30 @@+import type { NextConfig } from "next";++const nextConfig: NextConfig = {+ output: "standalone",+ experimental: {+ optimizePackageImports: ["lucide-react", "recharts", "d3"],+ },+ images: {+ unoptimized: true,+ },+ async rewrites() {+ const apiUrl = process.env.WIKICODE_API_URL || "http://localhost:7337";+ return [+ {+ source: "/api/:path*",+ destination: `${apiUrl}/api/:path*`,+ },+ {+ source: "/health",+ destination: `${apiUrl}/health`,+ },+ {+ source: "/metrics",+ destination: `${apiUrl}/metrics`,+ },+ ];+ },+};++export default nextConfig;diff --git a/packages/web/package.json b/packages/web/package.jsonnew file mode 100644index 000000000..dfff04897--- /dev/null+++ b/packages/web/package.json@@ -0,0 +1,67 @@+{+ "name": "wikicode-web",+ "version": "0.1.0",+ "private": true,+ "description": "WikiCode Web UI — Next.js 15 dashboard and wiki viewer",+ "scripts": {+ "dev": "next dev --port 3000",+ "build": "next build",+ "start": "next start --port 3000",+ "lint": "next lint",+ "type-check": "tsc --noEmit"+ },+ "dependencies": {+ "@radix-ui/react-accordion": "^1.2.0",+ "@radix-ui/react-dialog": "^1.1.0",+ "@radix-ui/react-dropdown-menu": "^2.1.0",+ "@radix-ui/react-label": "^2.1.8",+ "@radix-ui/react-popover": "^1.1.0",+ "@radix-ui/react-progress": "^1.1.8",+ "@radix-ui/react-scroll-area": "^1.2.0",+ "@radix-ui/react-select": "^2.1.0",+ "@radix-ui/react-separator": "^1.1.0",+ "@radix-ui/react-slider": "^1.3.6",+ "@radix-ui/react-slot": "^1.1.0",+ "@radix-ui/react-switch": "^1.2.6",+ "@radix-ui/react-tabs": "^1.1.0",+ "@radix-ui/react-toggle": "^1.1.0",+ "@radix-ui/react-toggle-group": "^1.1.0",+ "@radix-ui/react-tooltip": "^1.1.0",+ "class-variance-authority": "^0.7.1",+ "clsx": "^2.1.1",+ "cmdk": "^1.0.0",+ "d3": "^7.9.0",+ "d3-force": "^3.0.0",+ "d3-hierarchy": "^3.1.2",+ "framer-motion": "^11.11.0",+ "fuse.js": "^7.0.0",+ "geist": "^1.3.0",+ "lucide-react": "^0.460.0",+ "mermaid": "^11.4.0",+ "next": "^15.2.4",+ "next-mdx-remote": "^5.0.0",+ "nuqs": "^2.2.0",+ "react": "^19.0.0",+ "react-dom": "^19.0.0",+ "recharts": "^2.13.0",+ "shiki": "^1.22.0",+ "sonner": "^2.0.7",+ "swr": "^2.2.5",+ "tailwind-merge": "^2.5.4"+ },+ "devDependencies": {+ "@tailwindcss/postcss": "^4.0.0",+ "@tailwindcss/typography": "^0.5.15",+ "@types/d3": "^7.4.3",+ "@types/node": "^22",+ "@types/react": "^19",+ "@types/react-dom": "^19",+ "eslint": "^9",+ "eslint-config-next": "^15.2.4",+ "tailwindcss": "^4.0.0",+ "typescript": "^5.7"+ },+ "engines": {+ "node": ">=20.0.0"+ }+}diff --git a/packages/web/postcss.config.mjs b/packages/web/postcss.config.mjsnew file mode 100644index 000000000..79bcf135d--- /dev/null+++ b/packages/web/postcss.config.mjs@@ -0,0 +1,8 @@+/** @type {import('postcss-load-config').Config} */+const config = {+ plugins: {+ "@tailwindcss/postcss": {},+ },+};++export default config;diff --git a/packages/web/src/app/error.tsx b/packages/web/src/app/error.tsxnew file mode 100644index 000000000..7b292148c--- /dev/null+++ b/packages/web/src/app/error.tsx@@ -0,0 +1,42 @@+"use client";++import { useEffect } from "react";+import { AlertTriangle, RefreshCw } from "lucide-react";+import { Button } from "@/components/ui/button";++export default function GlobalError({+ error,+ reset,+}: {+ error: Error & { digest?: string };+ reset: () => void;+}) {+ useEffect(() => {+ console.error(error);+ }, [error]);++ return (+ <div className="flex h-full min-h-[400px] flex-col items-center justify-center gap-4 p-6 text-center">+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-red-500/10">+ <AlertTriangle className="h-6 w-6 text-red-500" />+ </div>+ <div>+ <h2 className="text-base font-semibold text-[var(--color-text-primary)]">+ Something went wrong+ </h2>+ <p className="mt-1 text-sm text-[var(--color-text-secondary)] max-w-sm">+ {error.message || "An unexpected error occurred. Please try again."}+ </p>+ {error.digest && (+ <p className="mt-1 text-xs font-mono text-[var(--color-text-tertiary)]">+ Digest: {error.digest}+ </p>+ )}+ </div>+ <Button onClick={reset} size="sm" className="gap-2">+ <RefreshCw className="h-3.5 w-3.5" />+ Try again+ </Button>+ </div>+ );+}diff --git a/packages/web/src/app/layout.tsx b/packages/web/src/app/layout.tsxnew file mode 100644index 000000000..0caff371a--- /dev/null+++ b/packages/web/src/app/layout.tsx@@ -0,0 +1,69 @@+import type { Metadata } from "next";+import { GeistSans } from "geist/font/sans";+import { GeistMono } from "geist/font/mono";+import { NuqsAdapter } from "nuqs/adapters/next/app";+import { Toaster } from "sonner";+import { TooltipProvider } from "@/components/ui/tooltip";+import { Sidebar } from "@/components/layout/sidebar";+import { MobileNav } from "@/components/layout/mobile-nav";+import { CommandPalette } from "@/components/search/command-palette";+import { listRepos } from "@/lib/api/repos";+import "@/styles/globals.css";++export const metadata: Metadata = {+ title: {+ default: "WikiCode",+ template: "%s — WikiCode",+ },+ description: "Open-source codebase documentation engine",+};++export default async function RootLayout({+ children,+}: {+ children: React.ReactNode;+}) {+ // Fetch repos server-side for the sidebar.+ // Gracefully fall back to empty if the API is unavailable.+ let repos: Awaited<ReturnType<typeof listRepos>> = [];+ try {+ repos = await listRepos();+ } catch {+ // API not available — show empty sidebar+ }++ return (+ <html+ lang="en"+ className={`${GeistSans.variable} ${GeistMono.variable} dark`}+ >+ <body className="bg-[var(--color-bg-root)] text-[var(--color-text-primary)] antialiased">+ <NuqsAdapter>+ <TooltipProvider delayDuration={300}>+ <div className="flex h-screen overflow-hidden">+ <Sidebar repos={repos} />+ <div className="flex flex-1 flex-col min-w-0 overflow-hidden">+ <MobileNav repos={repos} />+ <main className="flex-1 overflow-auto min-w-0">+ {children}+ </main>+ </div>+ </div>+ <CommandPalette repos={repos} />+ </TooltipProvider>+ </NuqsAdapter>+ <Toaster+ theme="dark"+ position="bottom-right"+ toastOptions={{+ style: {+ background: "var(--color-bg-elevated)",+ border: "1px solid var(--color-border-default)",+ color: "var(--color-text-primary)",+ },+ }}+ />+ </body>+ </html>+ );+}diff --git a/packages/web/src/app/loading.tsx b/packages/web/src/app/loading.tsxnew file mode 100644index 000000000..49762a2bc--- /dev/null+++ b/packages/web/src/app/loading.tsx@@ -0,0 +1,21 @@+import { Skeleton } from "@/components/ui/skeleton";++export default function DashboardLoading() {+ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-[1200px]">+ <div>+ <Skeleton className="h-7 w-32" />+ <Skeleton className="h-4 w-48 mt-1.5" />+ </div>+ <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} className="h-24 rounded-lg" />+ ))}+ </div>+ <div className="grid gap-4 lg:grid-cols-2">+ <Skeleton className="h-64 rounded-lg" />+ <Skeleton className="h-64 rounded-lg" />+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/page.tsx b/packages/web/src/app/page.tsxnew file mode 100644index 000000000..38e42aae8--- /dev/null+++ b/packages/web/src/app/page.tsx@@ -0,0 +1,206 @@+import type { Metadata } from "next";+import Link from "next/link";+import {+ FileText,+ CheckCircle2,+ AlertCircle,+ Skull,+ Activity,+ RefreshCw,+ Clock,+} from "lucide-react";+import { listRepos } from "@/lib/api/repos";+import { listJobs } from "@/lib/api/jobs";+import { StatCard } from "@/components/shared/stat-card";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import { Badge } from "@/components/ui/badge";+import { ConfidenceBadge } from "@/components/wiki/confidence-badge";+import { EmptyState } from "@/components/shared/empty-state";+import { formatRelativeTime, formatNumber } from "@/lib/utils/format";+import { scoreToStatus } from "@/lib/utils/confidence";++export const metadata: Metadata = { title: "Dashboard" };++export const revalidate = 30;++export default async function DashboardPage() {+ const [repos, jobs] = await Promise.allSettled([+ listRepos(),+ listJobs({ limit: 10 }),+ ]);++ const repoList = repos.status === "fulfilled" ? repos.value : [];+ const jobList = jobs.status === "fulfilled" ? jobs.value : [];++ // Aggregate stats across all repos+ const totalPages = 0; // fetched per repo in future+ const freshPages = 0;+ const stalePages = 0;++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-[1200px]">+ {/* Header */}+ <div>+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)]">Dashboard</h1>+ <p className="text-sm text-[var(--color-text-secondary)] mt-0.5">+ {repoList.length} {repoList.length === 1 ? "repository" : "repositories"} registered+ </p>+ </div>++ {/* Stat Cards */}+ <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">+ <StatCard+ label="Total Pages"+ value={formatNumber(totalPages)}+ icon={<FileText className="h-4 w-4" />}+ />+ <StatCard+ label="Fresh Pages"+ value={formatNumber(freshPages)}+ description="Confidence ≥ 80%"+ icon={<CheckCircle2 className="h-4 w-4 text-green-500" />}+ />+ <StatCard+ label="Stale Pages"+ value={formatNumber(stalePages)}+ description="Need regeneration"+ icon={<AlertCircle className="h-4 w-4 text-yellow-500" />}+ />+ <StatCard+ label="Dead Code"+ value="—"+ description="Analyze to detect"+ icon={<Skull className="h-4 w-4 text-[var(--color-text-tertiary)]" />}+ />+ </div>++ <div className="grid gap-4 lg:grid-cols-2">+ {/* Repositories */}+ <Card>+ <CardHeader className="pb-3">+ <CardTitle className="text-sm font-medium">Repositories</CardTitle>+ </CardHeader>+ <CardContent className="p-0">+ {repoList.length === 0 ? (+ <div className="px-6 pb-6">+ <EmptyState+ title="No repositories yet"+ description="Run wikicode init on a repository to get started."+ icon={<FileText className="h-8 w-8" />}+ />+ </div>+ ) : (+ <ul className="divide-y divide-[var(--color-border-default)]">+ {repoList.map((repo) => (+ <li key={repo.id}>+ <Link+ href={`/repos/${repo.id}`}+ className="flex items-start gap-3 px-6 py-3.5 transition-colors hover:bg-[var(--color-bg-elevated)] group"+ >+ <div className="mt-0.5 h-2 w-2 rounded-full bg-[var(--color-accent-primary)] shrink-0" />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <p className="text-sm font-medium text-[var(--color-text-primary)] truncate group-hover:text-[var(--color-accent-primary)] transition-colors">+ {repo.name}+ </p>+ </div>+ <div className="flex items-center gap-2 mt-0.5">+ <p className="text-xs text-[var(--color-text-tertiary)] font-mono truncate">+ {repo.local_path}+ </p>+ </div>+ <div className="flex items-center gap-2 mt-1">+ {repo.head_commit && (+ <span className="text-xs font-mono text-[var(--color-text-tertiary)]">+ {repo.head_commit.slice(0, 7)}+ </span>+ )}+ <span className="text-xs text-[var(--color-text-tertiary)]">+ Updated {formatRelativeTime(repo.updated_at)}+ </span>+ </div>+ </div>+ </Link>+ </li>+ ))}+ </ul>+ )}+ </CardContent>+ </Card>++ {/* Recent Jobs */}+ <Card>+ <CardHeader className="pb-3">+ <CardTitle className="text-sm font-medium">Recent Jobs</CardTitle>+ </CardHeader>+ <CardContent className="p-0">+ {jobList.length === 0 ? (+ <div className="px-6 pb-6">+ <EmptyState+ title="No jobs yet"+ description="Jobs appear after running wikicode init or sync."+ icon={<Activity className="h-8 w-8" />}+ />+ </div>+ ) : (+ <ul className="divide-y divide-[var(--color-border-default)]">+ {jobList.map((job) => (+ <li+ key={job.id}+ className="flex items-center gap-3 px-6 py-3"+ >+ <JobStatusIcon status={job.status} />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-xs font-mono text-[var(--color-text-secondary)]">+ {job.status === "running" ? (+ <span className="text-[var(--color-accent-primary)]">+ {job.completed_pages}/{job.total_pages} pages+ </span>+ ) : (+ `${job.total_pages} pages`+ )}+ </span>+ <Badge+ variant={+ job.status === "completed"+ ? "fresh"+ : job.status === "failed"+ ? "outdated"+ : job.status === "running"+ ? "accent"+ : "default"+ }+ >+ {job.status}+ </Badge>+ </div>+ <p className="text-xs text-[var(--color-text-tertiary)] mt-0.5">+ {job.model_name} · {formatRelativeTime(job.updated_at)}+ </p>+ </div>+ </li>+ ))}+ </ul>+ )}+ </CardContent>+ </Card>+ </div>+ </div>+ );+}++function JobStatusIcon({ status }: { status: string }) {+ if (status === "running") {+ return (+ <RefreshCw className="h-4 w-4 shrink-0 animate-spin text-[var(--color-accent-primary)]" />+ );+ }+ if (status === "completed") {+ return <CheckCircle2 className="h-4 w-4 shrink-0 text-green-500" />;+ }+ if (status === "failed") {+ return <AlertCircle className="h-4 w-4 shrink-0 text-red-500" />;+ }+ return <Clock className="h-4 w-4 shrink-0 text-[var(--color-text-tertiary)]" />;+}diff --git a/packages/web/src/app/repos/[id]/coverage/loading.tsx b/packages/web/src/app/repos/[id]/coverage/loading.tsxnew file mode 100644index 000000000..a798ce3ba--- /dev/null+++ b/packages/web/src/app/repos/[id]/coverage/loading.tsx@@ -0,0 +1,23 @@+import { Skeleton } from "@/components/ui/skeleton";++export default function CoverageLoading() {+ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-6xl">+ <div>+ <Skeleton className="h-7 w-36" />+ <Skeleton className="h-4 w-52 mt-1.5" />+ </div>+ <div className="grid grid-cols-1 gap-6 md:grid-cols-3">+ <div className="flex items-center justify-center">+ <Skeleton className="h-44 w-44 rounded-full" />+ </div>+ <div className="md:col-span-2 grid grid-cols-3 gap-3 content-center">+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={i} className="h-20 rounded-lg" />+ ))}+ </div>+ </div>+ <Skeleton className="h-[350px] rounded-lg" />+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/coverage/page.tsx b/packages/web/src/app/repos/[id]/coverage/page.tsxnew file mode 100644index 000000000..8e6bafaab--- /dev/null+++ b/packages/web/src/app/repos/[id]/coverage/page.tsx@@ -0,0 +1,100 @@+import type { Metadata } from "next";+import { FileCheck } from "lucide-react";+import { CoverageDonut } from "@/components/coverage/coverage-donut";+import { FreshnessTable } from "@/components/coverage/freshness-table";+import { StatCard } from "@/components/shared/stat-card";+import { listPages } from "@/lib/api/pages";+import { formatNumber } from "@/lib/utils/format";++export const metadata: Metadata = { title: "Coverage" };++export default async function CoveragePage({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id } = await params;++ let pages: Awaited<ReturnType<typeof listPages>> = [];++ try {+ pages = await listPages(id, { limit: 500 });+ } catch {+ // API unavailable+ }++ const total = pages.length;++ const fresh = pages.filter((p) => p.freshness_status === "fresh").length;+ const stale = pages.filter((p) => p.freshness_status === "stale").length;+ const outdated = pages.filter((p) => p.freshness_status === "outdated").length;+ const freshPct = pages.length > 0 ? Math.round((fresh / pages.length) * 100) : 0;++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-6xl">+ <div>+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">+ <FileCheck className="h-5 w-5 text-[var(--color-accent-primary)]" />+ Documentation Coverage+ </h1>+ <p className="text-sm text-[var(--color-text-secondary)]">+ Freshness breakdown across {formatNumber(total)} wiki pages.+ </p>+ </div>++ <div className="flex flex-col gap-6 lg:flex-row lg:items-start">+ {/* Donut */}+ <div className="flex flex-col items-center gap-4 lg:w-56 shrink-0">+ <CoverageDonut fresh={fresh} stale={stale} outdated={outdated} />+ <p className="text-sm text-[var(--color-text-secondary)]">+ {freshPct}% of pages are fresh+ </p>+ </div>++ {/* Stat cards */}+ <div className="flex-1 grid grid-cols-1 gap-3 sm:grid-cols-3">+ <StatCard+ label="Fresh"+ value={formatNumber(fresh)}+ description={`${pages.length > 0 ? Math.round((fresh / pages.length) * 100) : 0}% of pages`}+ />+ <StatCard+ label="Stale"+ value={formatNumber(stale)}+ description={`${pages.length > 0 ? Math.round((stale / pages.length) * 100) : 0}% of pages`}+ />+ <StatCard+ label="Outdated"+ value={formatNumber(outdated)}+ description={`${pages.length > 0 ? Math.round((outdated / pages.length) * 100) : 0}% of pages`}+ />+ </div>+ </div>++ {/* Freshness distribution bar */}+ {pages.length > 0 && (+ <div>+ <p className="text-xs text-[var(--color-text-tertiary)] mb-1.5">Distribution</p>+ <div className="h-3 rounded-full overflow-hidden flex">+ <div className="bg-green-500" style={{ width: `${(fresh / pages.length) * 100}%` }} />+ <div className="bg-yellow-500" style={{ width: `${(stale / pages.length) * 100}%` }} />+ <div className="bg-red-500" style={{ width: `${(outdated / pages.length) * 100}%` }} />+ </div>+ <div className="flex gap-4 mt-1.5 text-xs text-[var(--color-text-tertiary)]">+ <span className="flex items-center gap-1">+ <span className="h-2 w-2 rounded-full bg-green-500" /> Fresh+ </span>+ <span className="flex items-center gap-1">+ <span className="h-2 w-2 rounded-full bg-yellow-500" /> Stale+ </span>+ <span className="flex items-center gap-1">+ <span className="h-2 w-2 rounded-full bg-red-500" /> Outdated+ </span>+ </div>+ </div>+ )}++ <FreshnessTable pages={pages} />+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/dead-code/loading.tsx b/packages/web/src/app/repos/[id]/dead-code/loading.tsxnew file mode 100644index 000000000..7f91d7252--- /dev/null+++ b/packages/web/src/app/repos/[id]/dead-code/loading.tsx@@ -0,0 +1,28 @@+import { Skeleton } from "@/components/ui/skeleton";++export default function DeadCodeLoading() {+ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-6xl">+ <div className="flex flex-wrap items-start justify-between gap-4">+ <div>+ <Skeleton className="h-7 w-32" />+ <Skeleton className="h-4 w-52 mt-1.5" />+ </div>+ <Skeleton className="h-9 w-28" />+ </div>+ <Skeleton className="h-20 rounded-lg" />+ <div className="flex gap-2">+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={i} className="h-9 w-28" />+ ))}+ </div>+ <div className="space-y-px">+ <Skeleton className="h-10 rounded-t-lg" />+ {Array.from({ length: 6 }).map((_, i) => (+ <Skeleton key={i} className="h-14 rounded-none" />+ ))}+ <Skeleton className="h-14 rounded-b-lg" />+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/dead-code/page.tsx b/packages/web/src/app/repos/[id]/dead-code/page.tsxnew file mode 100644index 000000000..6d3349b11--- /dev/null+++ b/packages/web/src/app/repos/[id]/dead-code/page.tsx@@ -0,0 +1,79 @@+"use client";++import { useState } from "react";+import useSWR from "swr";+import { useParams } from "next/navigation";+import { Trash2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import { SummaryBar } from "@/components/dead-code/summary-bar";+import { FindingsTable } from "@/components/dead-code/findings-table";+import { Skeleton } from "@/components/ui/skeleton";+import { getDeadCodeSummary, analyzeDeadCode } from "@/lib/api/dead-code";+import type { DeadCodeSummaryResponse } from "@/lib/api/types";++export default function DeadCodePage() {+ const params = useParams<{ id: string }>();+ const id = params.id;+ const [analyzing, setAnalyzing] = useState(false);+ const [analyzeMsg, setAnalyzeMsg] = useState("");++ const { data: summary, isLoading: loadingSummary } = useSWR<DeadCodeSummaryResponse>(+ `dead-code-summary:${id}`,+ () => getDeadCodeSummary(id),+ { revalidateOnFocus: false },+ );++ const handleAnalyze = async () => {+ setAnalyzing(true);+ setAnalyzeMsg("");+ try {+ await analyzeDeadCode(id);+ setAnalyzeMsg("Analysis started — results will appear shortly.");+ } catch {+ setAnalyzeMsg("Failed to start analysis.");+ } finally {+ setAnalyzing(false);+ }+ };++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-6xl">+ <div className="flex flex-wrap items-start justify-between gap-4">+ <div>+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">+ <Trash2 className="h-5 w-5 text-red-500" />+ Dead Code+ </h1>+ <p className="text-sm text-[var(--color-text-secondary)]">+ Unused files, exports, and zombie packages.+ </p>+ </div>+ <div className="flex items-center gap-3">+ {analyzeMsg && (+ <span className="text-xs text-green-500">{analyzeMsg}</span>+ )}+ <Button+ size="sm"+ variant="outline"+ onClick={handleAnalyze}+ disabled={analyzing}+ >+ {analyzing ? "Starting…" : "Analyze"}+ </Button>+ </div>+ </div>++ {loadingSummary ? (+ <div className="grid grid-cols-4 gap-3">+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} className="h-24 w-full rounded-lg" />+ ))}+ </div>+ ) : summary ? (+ <SummaryBar summary={summary} />+ ) : null}++ <FindingsTable repoId={id} />+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/decisions/[decisionId]/page.tsx b/packages/web/src/app/repos/[id]/decisions/[decisionId]/page.tsxnew file mode 100644index 000000000..d3ff41534--- /dev/null+++ b/packages/web/src/app/repos/[id]/decisions/[decisionId]/page.tsx@@ -0,0 +1,26 @@+import { notFound } from "next/navigation";+import { getDecision } from "@/lib/api/decisions";+import { DecisionDetail } from "@/components/decisions/decision-detail";++export const revalidate = 30;++interface Props {+ params: Promise<{ id: string; decisionId: string }>;+}++export default async function DecisionDetailPage({ params }: Props) {+ const { id: repoId, decisionId } = await params;++ let decision;+ try {+ decision = await getDecision(repoId, decisionId);+ } catch {+ notFound();+ }++ return (+ <div className="max-w-3xl p-6">+ <DecisionDetail decision={decision} repoId={repoId} />+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/decisions/page.tsx b/packages/web/src/app/repos/[id]/decisions/page.tsxnew file mode 100644index 000000000..29833c8fa--- /dev/null+++ b/packages/web/src/app/repos/[id]/decisions/page.tsx@@ -0,0 +1,34 @@+import { notFound } from "next/navigation";+import { listDecisions } from "@/lib/api/decisions";+import { DecisionsTable } from "@/components/decisions/decisions-table";++export const revalidate = 30;++interface Props {+ params: Promise<{ id: string }>;+}++export default async function DecisionsPage({ params }: Props) {+ const { id: repoId } = await params;++ let decisions;+ try {+ decisions = await listDecisions(repoId, { include_proposed: true, limit: 100 });+ } catch {+ notFound();+ }++ return (+ <div className="space-y-6 p-6">+ <div>+ <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">+ Architectural Decisions+ </h1>+ <p className="mt-1 text-sm text-[var(--color-text-tertiary)]">+ Why the codebase is built the way it is — constraints, tradeoffs, and rejected alternatives.+ </p>+ </div>+ <DecisionsTable repoId={repoId} initialData={decisions} />+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/error.tsx b/packages/web/src/app/repos/[id]/error.tsxnew file mode 100644index 000000000..28ec2be58--- /dev/null+++ b/packages/web/src/app/repos/[id]/error.tsx@@ -0,0 +1,46 @@+"use client";++import { useEffect } from "react";+import Link from "next/link";+import { AlertTriangle, RefreshCw, ArrowLeft } from "lucide-react";+import { Button } from "@/components/ui/button";++export default function RepoError({+ error,+ reset,+}: {+ error: Error & { digest?: string };+ reset: () => void;+}) {+ useEffect(() => {+ console.error(error);+ }, [error]);++ return (+ <div className="flex h-full min-h-[400px] flex-col items-center justify-center gap-4 p-6 text-center">+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-red-500/10">+ <AlertTriangle className="h-6 w-6 text-red-500" />+ </div>+ <div>+ <h2 className="text-base font-semibold text-[var(--color-text-primary)]">+ Failed to load repository+ </h2>+ <p className="mt-1 text-sm text-[var(--color-text-secondary)] max-w-sm">+ {error.message || "Could not load repository data. The backend may be unavailable."}+ </p>+ </div>+ <div className="flex items-center gap-2">+ <Button onClick={reset} size="sm" variant="secondary" className="gap-2">+ <RefreshCw className="h-3.5 w-3.5" />+ Retry+ </Button>+ <Button asChild size="sm" variant="ghost" className="gap-2">+ <Link href="/">+ <ArrowLeft className="h-3.5 w-3.5" />+ Dashboard+ </Link>+ </Button>+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/graph/loading.tsx b/packages/web/src/app/repos/[id]/graph/loading.tsxnew file mode 100644index 000000000..e0ffd4dc0--- /dev/null+++ b/packages/web/src/app/repos/[id]/graph/loading.tsx@@ -0,0 +1,15 @@+import { Skeleton } from "@/components/ui/skeleton";++export default function GraphLoading() {+ return (+ <div className="flex flex-col h-screen">+ <div className="shrink-0 px-4 sm:px-6 py-4 border-b border-[var(--color-border-default)]">+ <Skeleton className="h-7 w-48" />+ <Skeleton className="h-4 w-80 mt-1.5" />+ </div>+ <div className="flex-1 p-4">+ <Skeleton className="h-full w-full rounded-lg" />+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/graph/page.tsx b/packages/web/src/app/repos/[id]/graph/page.tsxnew file mode 100644index 000000000..2c12ace86--- /dev/null+++ b/packages/web/src/app/repos/[id]/graph/page.tsx@@ -0,0 +1,119 @@+"use client";++import { use, useCallback } from "react";+import { useQueryState, parseAsString, parseAsInteger } from "nuqs";+import { GraphCanvas, type ViewMode } from "@/components/graph/graph-canvas";+import { GraphViewSwitcher } from "@/components/graph/graph-view-switcher";+import { GraphEgoSidebar } from "@/components/graph/graph-ego-sidebar";+import { useEgoGraph } from "@/lib/hooks/use-graph";+import { searchNodes } from "@/lib/api/graph";++export default function GraphPage({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id: repoId } = use(params);++ const [view, setView] = useQueryState("view", parseAsString.withDefault("module"));+ const [node, setNode] = useQueryState("node");+ const [hops, setHops] = useQueryState("hops", parseAsInteger.withDefault(2));+ const [days, setDays] = useQueryState("days", parseAsInteger.withDefault(30));++ const viewMode = view as ViewMode;++ // Fetch ego graph data so we can show the sidebar+ const { graph: egoGraph } = useEgoGraph(+ viewMode === "ego" ? repoId : null,+ viewMode === "ego" ? node : null,+ hops,+ );++ const handleNodeClick = useCallback(+ async (nodeId: string) => {+ if (viewMode === "module") {+ try {+ // Fetch many candidates so we can pick the most representative code file+ const results = await searchNodes(repoId, nodeId + "/", 40);+ // Exclude config/doc files that have no symbols; prefer actual code+ const NON_CODE = new Set(["markdown", "json", "yaml", "toml", "text", "plaintext", "xml", "ini", ""]);+ const codeFiles = results.filter(+ (r) => !NON_CODE.has(r.language.toLowerCase()) && r.symbol_count > 0,+ );+ // Fall back to any non-doc file, then any file if nothing else+ const candidates = codeFiles.length > 0+ ? codeFiles+ : results.filter((r) => !NON_CODE.has(r.language.toLowerCase()));+ const pool = candidates.length > 0 ? candidates : results;+ // Pick the file with the most symbols (most substantive)+ const best = pool.sort((a, b) => b.symbol_count - a.symbol_count)[0];+ const targetNode = best?.node_id ?? nodeId;+ await setView("ego");+ await setNode(targetNode);+ } catch {+ await setView("ego");+ await setNode(nodeId);+ }+ } else {+ await setView("ego");+ await setNode(nodeId);+ }+ },+ [viewMode, repoId, setView, setNode],+ );++ return (+ <div className="flex flex-col h-screen">+ {/* Header */}+ <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">+ <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">+ Dependency Graph+ </h1>+ <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">+ {viewMode === "module" && "Module overview — click a node to explore its neighborhood"}+ {viewMode === "ego" && `Neighborhood of ${node ?? "…"}`}+ {viewMode === "architecture" && "Entry-point reachable subgraph (3 hops)"}+ {viewMode === "dead" && "Dead code — unreachable files and unused exports"}+ {viewMode === "hotfiles" && `Most-committed files (${days}d)`}+ {viewMode === "full" && "Full dependency graph — scroll to zoom, drag to pan"}+ </p>+ </div>++ {/* View switcher */}+ <GraphViewSwitcher+ repoId={repoId}+ view={viewMode}+ hops={hops}+ days={days}+ onViewChange={(v) => void setView(v)}+ onNodeSelect={(nodeId) => void handleNodeClick(nodeId)}+ onHopsChange={(h) => void setHops(h)}+ onDaysChange={(d) => void setDays(d)}+ />++ {/* Canvas area */}+ <div className="flex-1 overflow-hidden p-3">+ <div className="h-full w-full rounded-lg border border-[var(--color-border-default)] overflow-hidden relative">+ <GraphCanvas+ repoId={repoId}+ viewMode={viewMode}+ centerNodeId={node}+ hops={hops}+ days={days}+ onNodeClick={(nodeId) => void handleNodeClick(nodeId)}+ onViewChange={(v) => void setView(v)}+ />++ {/* Ego sidebar */}+ {viewMode === "ego" && egoGraph && (+ <GraphEgoSidebar+ graph={egoGraph}+ onClose={() => void setView("module")}+ onNavigateToNode={(nodeId) => void setNode(nodeId)}+ />+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/hotspots/loading.tsx b/packages/web/src/app/repos/[id]/hotspots/loading.tsxnew file mode 100644index 000000000..246694e07--- /dev/null+++ b/packages/web/src/app/repos/[id]/hotspots/loading.tsx@@ -0,0 +1,23 @@+import { Skeleton } from "@/components/ui/skeleton";++export default function HotspotsLoading() {+ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-6xl">+ <div>+ <Skeleton className="h-7 w-32" />+ <Skeleton className="h-4 w-52 mt-1.5" />+ </div>+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} className="h-20 rounded-lg" />+ ))}+ </div>+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">+ <div className="lg:col-span-2">+ <Skeleton className="h-[400px] rounded-lg" />+ </div>+ <Skeleton className="h-[300px] rounded-lg" />+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/hotspots/page.tsx b/packages/web/src/app/repos/[id]/hotspots/page.tsxnew file mode 100644index 000000000..dc3fc56c4--- /dev/null+++ b/packages/web/src/app/repos/[id]/hotspots/page.tsx@@ -0,0 +1,98 @@+import type { Metadata } from "next";+import { Flame } from "lucide-react";+import { StatCard } from "@/components/shared/stat-card";+import { HotspotTable } from "@/components/git/hotspot-table";+import { ContributorBar } from "@/components/git/contributor-bar";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import { getHotspots, getGitSummary } from "@/lib/api/git";+import { formatNumber } from "@/lib/utils/format";++export const metadata: Metadata = { title: "Hotspots" };++export default async function HotspotsPage({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id } = await params;++ let hotspots: Awaited<ReturnType<typeof getHotspots>> = [];+ let summary: Awaited<ReturnType<typeof getGitSummary>> | null = null;++ try {+ [hotspots, summary] = await Promise.all([+ getHotspots(id, 50),+ getGitSummary(id),+ ]);+ } catch {+ // API unavailable+ }++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-6xl">+ <div>+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">+ <Flame className="h-5 w-5 text-red-500" />+ Hotspots+ </h1>+ <p className="text-sm text-[var(--color-text-secondary)]">+ High-churn files — where the most risky code lives.+ </p>+ </div>++ {/* Summary cards */}+ {summary && (+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">+ <StatCard+ label="Hotspot Files"+ value={formatNumber(summary.hotspot_count)}+ description="high-churn files"+ />+ <StatCard+ label="Stable Files"+ value={formatNumber(summary.stable_count)}+ description="low-churn files"+ />+ <StatCard+ label="Total Files"+ value={formatNumber(summary.total_files)}+ description="with git history"+ />+ <StatCard+ label="Avg Churn"+ value={`${Math.round(summary.average_churn_percentile)}%`}+ description="percentile"+ />+ </div>+ )}++ <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">+ <div className="lg:col-span-2">+ <HotspotTable hotspots={hotspots} />+ </div>++ {/* Top owners leaderboard */}+ {summary && summary.top_owners.length > 0 && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm">Top Owners</CardTitle>+ </CardHeader>+ <CardContent className="pt-0">+ <ContributorBar owners={summary.top_owners} />+ <div className="mt-3 space-y-1.5">+ {summary.top_owners.slice(0, 5).map((o) => (+ <div key={o.email || `owner-${o.name}`} className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-secondary)] truncate">{o.name}</span>+ <span className="text-[var(--color-text-tertiary)] tabular-nums ml-2">+ {formatNumber(o.file_count)} files ({Math.round(o.pct * 100)}%)+ </span>+ </div>+ ))}+ </div>+ </CardContent>+ </Card>+ )}+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/layout.tsx b/packages/web/src/app/repos/[id]/layout.tsxnew file mode 100644index 000000000..e785f195b--- /dev/null+++ b/packages/web/src/app/repos/[id]/layout.tsx@@ -0,0 +1,14 @@+import { getRepo } from "@/lib/api/repos";++interface RepoLayoutProps {+ children: React.ReactNode;+ params: Promise<{ id: string }>;+}++export default async function RepoLayout({ children, params }: RepoLayoutProps) {+ const { id } = await params;+ // Repo data is fetched here so child pages can use it via server props.+ // The sidebar is in the root layout and already has access to all repos.+ // This layout just renders children — individual pages fetch their own data.+ return <>{children}</>;+}diff --git a/packages/web/src/app/repos/[id]/loading.tsx b/packages/web/src/app/repos/[id]/loading.tsxnew file mode 100644index 000000000..59147d870--- /dev/null+++ b/packages/web/src/app/repos/[id]/loading.tsx@@ -0,0 +1,25 @@+import { Skeleton } from "@/components/ui/skeleton";++export default function RepoLoading() {+ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-[1200px]">+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <Skeleton className="h-7 w-48" />+ <Skeleton className="h-4 w-64 mt-1.5" />+ </div>+ <div className="flex gap-2 shrink-0">+ <Skeleton className="h-6 w-16" />+ <Skeleton className="h-6 w-16" />+ </div>+ </div>+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} className="h-20 rounded-lg" />+ ))}+ </div>+ <Skeleton className="h-36 rounded-lg" />+ <Skeleton className="h-48 rounded-lg" />+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/ownership/loading.tsx b/packages/web/src/app/repos/[id]/ownership/loading.tsxnew file mode 100644index 000000000..6cf2f07cb--- /dev/null+++ b/packages/web/src/app/repos/[id]/ownership/loading.tsx@@ -0,0 +1,24 @@+import { Skeleton } from "@/components/ui/skeleton";++export default function OwnershipLoading() {+ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-6xl">+ <div>+ <Skeleton className="h-7 w-36" />+ <Skeleton className="h-4 w-52 mt-1.5" />+ </div>+ <div className="flex gap-2">+ <Skeleton className="h-9 w-36" />+ </div>+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">+ <div className="lg:col-span-2">+ <Skeleton className="h-[400px] rounded-lg" />+ </div>+ <div className="space-y-4">+ <Skeleton className="h-[200px] rounded-lg" />+ <Skeleton className="h-[160px] rounded-lg" />+ </div>+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/ownership/page.tsx b/packages/web/src/app/repos/[id]/ownership/page.tsxnew file mode 100644index 000000000..b1b6454a0--- /dev/null+++ b/packages/web/src/app/repos/[id]/ownership/page.tsx@@ -0,0 +1,135 @@+"use client";++import { useState } from "react";+import useSWR from "swr";+import { useParams } from "next/navigation";+import { Users } from "lucide-react";+import { OwnershipTable } from "@/components/git/ownership-table";+import { ContributorBar } from "@/components/git/contributor-bar";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import { Skeleton } from "@/components/ui/skeleton";+import { getOwnership, getGitSummary } from "@/lib/api/git";+import { formatNumber } from "@/lib/utils/format";+import { cn } from "@/lib/utils/cn";+import type { OwnershipEntry, GitSummaryResponse } from "@/lib/api/types";++type Granularity = "module" | "file";++export default function OwnershipPage() {+ const params = useParams<{ id: string }>();+ const id = params.id;+ const [granularity, setGranularity] = useState<Granularity>("module");++ const { data: entries, isLoading: loadingEntries } = useSWR<OwnershipEntry[]>(+ `ownership:${id}:${granularity}`,+ () => getOwnership(id, granularity),+ { revalidateOnFocus: false },+ );++ const { data: summary } = useSWR<GitSummaryResponse>(+ `git-summary:${id}`,+ () => getGitSummary(id),+ { revalidateOnFocus: false },+ );++ const siloCount = (entries ?? []).filter((e) => e.is_silo).length;++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-6xl">+ <div>+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">+ <Users className="h-5 w-5 text-[var(--color-accent-primary)]" />+ Code Ownership+ </h1>+ <p className="text-sm text-[var(--color-text-secondary)]">+ Who owns what — silo detection and bus factor risk.+ </p>+ </div>++ {/* Summary stats */}+ {summary && (+ <div className="grid grid-cols-3 gap-3">+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1">+ Total Files+ </p>+ <p className="text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">+ {formatNumber(summary.total_files)}+ </p>+ </div>+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1">+ Silo Modules+ </p>+ <p className="text-2xl font-bold text-yellow-500 tabular-nums">{siloCount}</p>+ </div>+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1">+ Contributors+ </p>+ <p className="text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">+ {summary.top_owners.length}+ </p>+ </div>+ </div>+ )}++ {/* Granularity toggle */}+ <div className="flex items-center gap-2">+ <span className="text-xs text-[var(--color-text-secondary)]">View by:</span>+ <div className="flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">+ {(["module", "file"] as Granularity[]).map((g) => (+ <button+ key={g}+ onClick={() => setGranularity(g)}+ className={cn(+ "px-3 py-1.5 font-medium transition-colors capitalize",+ granularity === g+ ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"+ : "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",+ )}+ >+ {g}+ </button>+ ))}+ </div>+ </div>++ <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">+ <div className="lg:col-span-2">+ {loadingEntries ? (+ <div className="space-y-2">+ {Array.from({ length: 8 }).map((_, i) => (+ <Skeleton key={i} className="h-10 w-full" />+ ))}+ </div>+ ) : (+ <OwnershipTable entries={entries ?? []} />+ )}+ </div>++ {/* Contributor chart */}+ {summary && summary.top_owners.length > 0 && (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm">Top Contributors</CardTitle>+ </CardHeader>+ <CardContent className="pt-0">+ <ContributorBar owners={summary.top_owners} />+ <div className="mt-3 space-y-1.5">+ {summary.top_owners.slice(0, 10).map((o, i) => (+ <div key={o.email || `owner-${i}`} className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-secondary)] truncate">{o.name}</span>+ <span className="text-[var(--color-text-tertiary)] tabular-nums ml-2">+ {Math.round(o.pct * 100)}%+ </span>+ </div>+ ))}+ </div>+ </CardContent>+ </Card>+ )}+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/page.tsx b/packages/web/src/app/repos/[id]/page.tsxnew file mode 100644index 000000000..b69761286--- /dev/null+++ b/packages/web/src/app/repos/[id]/page.tsx@@ -0,0 +1,274 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import Link from "next/link";+import {+ FileText,+ Clock,+ Hash,+ Code2,+ AlertTriangle,+ Network,+ BookOpen,+ Flame,+ Target,+ TrendingDown,+} from "lucide-react";+import { getRepo, getRepoStats } from "@/lib/api/repos";+import { listPages } from "@/lib/api/pages";+import { listDeadCode } from "@/lib/api/dead-code";+import { getHotspots } from "@/lib/api/git";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { StatCard } from "@/components/shared/stat-card";+import { OperationsPanel } from "@/components/repos/operations-panel";+import { formatNumber } from "@/lib/utils/format";++interface Props {+ params: Promise<{ id: string }>;+}++export async function generateMetadata({ params }: Props): Promise<Metadata> {+ const { id } = await params;+ try {+ const repo = await getRepo(id);+ return { title: repo.name };+ } catch {+ return { title: "Repository" };+ }+}++export default async function RepoOverviewPage({ params }: Props) {+ const { id } = await params;++ let repo;+ try {+ repo = await getRepo(id);+ } catch {+ notFound();+ }++ const [statsResult, lowConfPagesResult, deadExportsResult, hotspotsResult] =+ await Promise.allSettled([+ getRepoStats(id),+ listPages(id, { sort_by: "confidence", order: "asc", limit: 5 }),+ listDeadCode(id, { kind: "unused_export", limit: 5 }),+ getHotspots(id, 5),+ ]);++ const stats = statsResult.status === "fulfilled" ? statsResult.value : null;+ const lowConfPages = lowConfPagesResult.status === "fulfilled" ? lowConfPagesResult.value : [];+ const deadExports = deadExportsResult.status === "fulfilled" ? deadExportsResult.value : [];+ const hotspots = hotspotsResult.status === "fulfilled" ? hotspotsResult.value : [];++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-[1200px]">+ {/* Header */}+ <div className="flex items-start justify-between">+ <div>+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)]">+ {repo.name}+ </h1>+ <p className="text-xs font-mono text-[var(--color-text-tertiary)] mt-0.5">+ {repo.local_path}+ </p>+ </div>+ <div className="flex items-center gap-2">+ {repo.head_commit && (+ <Badge variant="outline">+ <Hash className="h-3 w-3" />+ {repo.head_commit.slice(0, 7)}+ </Badge>+ )}+ <Badge variant="outline">{repo.default_branch}</Badge>+ </div>+ </div>++ {/* Stats strip */}+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">+ <StatCard+ label="Files"+ value={stats ? formatNumber(stats.file_count) : "—"}+ icon={<FileText className="h-4 w-4" />}+ />+ <StatCard+ label="Symbols"+ value={stats ? formatNumber(stats.symbol_count) : "—"}+ icon={<Code2 className="h-4 w-4" />}+ />+ <StatCard+ label="Entry Points"+ value={stats ? formatNumber(stats.entry_point_count) : "—"}+ icon={<Target className="h-4 w-4" />}+ />+ <StatCard+ label="Doc Coverage"+ value={stats ? `${stats.doc_coverage_pct.toFixed(0)}%` : "—"}+ icon={<BookOpen className="h-4 w-4" />}+ />+ <StatCard+ label="Freshness"+ value={stats ? `${stats.freshness_score.toFixed(0)}%` : "—"}+ icon={<Clock className="h-4 w-4" />}+ />+ <StatCard+ label="Dead Exports"+ value={stats ? formatNumber(stats.dead_export_count) : "—"}+ icon={<TrendingDown className="h-4 w-4" />}+ />+ </div>++ {/* Operations panel */}+ <OperationsPanel repoId={id} repoName={repo.name} />++ {/* Two-column content */}+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ {/* Left: Needs Attention */}+ <div className="space-y-4">+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium flex items-center gap-2">+ <AlertTriangle className="h-4 w-4 text-amber-400" />+ Needs Attention+ </CardTitle>+ </CardHeader>+ <CardContent className="space-y-4">+ {/* Low confidence pages */}+ <div>+ <p className="text-xs text-[var(--color-text-tertiary)] mb-2 uppercase tracking-wider font-medium">+ Low-confidence docs+ </p>+ {lowConfPages.length === 0 ? (+ <p className="text-xs text-[var(--color-text-secondary)]">All pages look good.</p>+ ) : (+ <div className="space-y-1">+ {lowConfPages.map((page) => (+ <Link+ key={page.id}+ href={`/repos/${id}/wiki/${encodeURIComponent(page.target_path)}`}+ className="flex items-center justify-between py-1 px-2 rounded hover:bg-[var(--color-bg-elevated)] group transition-colors"+ >+ <span className="font-mono text-xs text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)] truncate">+ {page.target_path}+ </span>+ <span+ className="ml-2 shrink-0 text-xs tabular-nums font-medium"+ style={{+ color: page.confidence < 0.5 ? "#ef4444" : "#f59e0b",+ }}+ >+ {(page.confidence * 100).toFixed(0)}%+ </span>+ </Link>+ ))}+ </div>+ )}+ </div>++ {/* Dead exports */}+ <div>+ <p className="text-xs text-[var(--color-text-tertiary)] mb-2 uppercase tracking-wider font-medium">+ Unused exports+ </p>+ {deadExports.length === 0 ? (+ <p className="text-xs text-[var(--color-text-secondary)]">No unused exports found.</p>+ ) : (+ <div className="space-y-1">+ {deadExports.map((finding) => (+ <Link+ key={finding.id}+ href={`/repos/${id}/dead-code`}+ className="flex items-center justify-between py-1 px-2 rounded hover:bg-[var(--color-bg-elevated)] group transition-colors"+ >+ <div className="flex-1 min-w-0">+ <span className="font-mono text-xs text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)] truncate block">+ {finding.file_path}+ </span>+ {finding.symbol_name && (+ <span className="font-mono text-xs text-[var(--color-text-tertiary)]">+ {finding.symbol_name}+ </span>+ )}+ </div>+ <span className="ml-2 shrink-0 text-xs tabular-nums text-[var(--color-text-tertiary)]">+ {(finding.confidence * 100).toFixed(0)}%+ </span>+ </Link>+ ))}+ </div>+ )}+ </div>+ </CardContent>+ </Card>+ </div>++ {/* Right: Most Active */}+ <div>+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium flex items-center gap-2">+ <Flame className="h-4 w-4 text-orange-400" />+ Most Active (30d)+ </CardTitle>+ </CardHeader>+ <CardContent>+ {hotspots.length === 0 ? (+ <p className="text-xs text-[var(--color-text-secondary)]">+ No git activity data yet.+ </p>+ ) : (+ <div className="space-y-1">+ {hotspots.map((hs) => (+ <div+ key={hs.file_path}+ className="flex items-center justify-between py-1 px-2 rounded"+ >+ <div className="flex-1 min-w-0">+ <span className="font-mono text-xs text-[var(--color-text-secondary)] truncate block">+ {hs.file_path}+ </span>+ {hs.primary_owner && (+ <span className="text-xs text-[var(--color-text-tertiary)]">+ {hs.primary_owner}+ </span>+ )}+ </div>+ <div className="ml-2 shrink-0 text-right">+ <span className="text-xs tabular-nums font-medium text-[var(--color-text-primary)]">+ {hs.commit_count_90d}+ </span>+ <span className="text-xs text-[var(--color-text-tertiary)] ml-1">commits</span>+ </div>+ </div>+ ))}+ </div>+ )}+ </CardContent>+ </Card>+ </div>+ </div>++ {/* CTA buttons */}+ <div className="flex flex-wrap gap-3">+ <Button asChild>+ <Link href={`/repos/${id}/graph`}>+ <Network className="h-4 w-4 mr-2" />+ Explore Graph →+ </Link>+ </Button>+ <Button variant="secondary" asChild>+ <Link href={`/repos/${id}/dead-code`}>+ <TrendingDown className="h-4 w-4 mr-2" />+ View Dead Code →+ </Link>+ </Button>+ <Button variant="secondary" asChild>+ <Link href={`/repos/${id}/wiki`}>+ <BookOpen className="h-4 w-4 mr-2" />+ Browse Docs →+ </Link>+ </Button>+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/search/loading.tsx b/packages/web/src/app/repos/[id]/search/loading.tsxnew file mode 100644index 000000000..1e5981bde--- /dev/null+++ b/packages/web/src/app/repos/[id]/search/loading.tsx@@ -0,0 +1,25 @@+import { Skeleton } from "@/components/ui/skeleton";++export default function SearchLoading() {+ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-3xl">+ <div>+ <Skeleton className="h-7 w-24" />+ <Skeleton className="h-4 w-56 mt-1.5" />+ </div>+ <div className="space-y-3">+ <Skeleton className="h-11 rounded-lg" />+ <div className="flex gap-2">+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={i} className="h-8 w-24" />+ ))}+ </div>+ </div>+ <div className="space-y-3">+ {Array.from({ length: 5 }).map((_, i) => (+ <Skeleton key={i} className="h-20 rounded-lg" />+ ))}+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/search/page.tsx b/packages/web/src/app/repos/[id]/search/page.tsxnew file mode 100644index 000000000..cebad6187--- /dev/null+++ b/packages/web/src/app/repos/[id]/search/page.tsx@@ -0,0 +1,76 @@+"use client";++import { useState } from "react";+import { useParams } from "next/navigation";+import { Search } from "lucide-react";+import { SearchBar } from "@/components/search/search-bar";+import { SearchResultCard } from "@/components/search/search-result-card";+import { EmptyState } from "@/components/shared/empty-state";+import { Skeleton } from "@/components/ui/skeleton";+import { useSearch } from "@/lib/hooks/use-search";++type SearchType = "fulltext" | "semantic";++export default function SearchPage() {+ const params = useParams<{ id: string }>();+ const id = params.id;+ const [query, setQuery] = useState("");+ const [searchType, setSearchType] = useState<SearchType>("semantic");++ const { results, isLoading, isTyping } = useSearch(query, {+ search_type: searchType,+ limit: 20,+ });++ const showResults = query.trim().length >= 2;+ const loading = (isLoading || isTyping) && showResults;++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-3xl">+ <div>+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">+ <Search className="h-5 w-5 text-[var(--color-accent-primary)]" />+ Search+ </h1>+ <p className="text-sm text-[var(--color-text-secondary)]">+ Full-text and semantic search across all wiki pages.+ </p>+ </div>++ <SearchBar+ query={query}+ onQueryChange={setQuery}+ searchType={searchType}+ onSearchTypeChange={setSearchType}+ />++ {!showResults ? (+ <EmptyState+ title="Start typing to search"+ description="Search across titles, content, and file paths."+ icon={<Search className="h-8 w-8" />}+ />+ ) : loading ? (+ <div className="space-y-3">+ {Array.from({ length: 5 }).map((_, i) => (+ <Skeleton key={i} className="h-20 w-full rounded-lg" />+ ))}+ </div>+ ) : results.length === 0 ? (+ <EmptyState+ title="No results"+ description={`No pages matched "${query}". Try different keywords or switch search mode.`}+ />+ ) : (+ <div className="space-y-3">+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {results.length} result{results.length !== 1 ? "s" : ""} for “{query}”+ </p>+ {results.map((r) => (+ <SearchResultCard key={r.page_id} result={r} query={query} repoId={id} />+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/settings/page.tsx b/packages/web/src/app/repos/[id]/settings/page.tsxnew file mode 100644index 000000000..35d964794--- /dev/null+++ b/packages/web/src/app/repos/[id]/settings/page.tsx@@ -0,0 +1,88 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import { Settings } from "lucide-react";+import { getRepo } from "@/lib/api/repos";+import { RepoSettingsForm } from "@/components/repos/repo-settings-form";+import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";+import { Separator } from "@/components/ui/separator";+import { OperationsPanel } from "@/components/repos/operations-panel";++interface Props {+ params: Promise<{ id: string }>;+}++export async function generateMetadata({ params }: Props): Promise<Metadata> {+ const { id } = await params;+ try {+ const repo = await getRepo(id);+ return { title: `${repo.name} — Settings` };+ } catch {+ return { title: "Settings" };+ }+}++export default async function RepoSettingsPage({ params }: Props) {+ const { id } = await params;++ let repo;+ try {+ repo = await getRepo(id);+ } catch {+ notFound();+ }++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-2xl">+ <div>+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] flex items-center gap-2">+ <Settings className="h-5 w-5 text-[var(--color-accent-primary)]" />+ Repository Settings+ </h1>+ <p className="text-sm text-[var(--color-text-secondary)] mt-0.5">+ Manage {repo.name}+ </p>+ </div>++ <Card>+ <CardHeader>+ <CardTitle className="text-sm font-medium">General</CardTitle>+ <CardDescription>Name, branch, and path configuration</CardDescription>+ </CardHeader>+ <CardContent>+ <RepoSettingsForm repo={repo} />+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle className="text-sm font-medium">Sync & Indexing</CardTitle>+ <CardDescription>Trigger incremental sync or full re-indexing</CardDescription>+ </CardHeader>+ <CardContent className="pt-0">+ <OperationsPanel repoId={id} repoName={repo.name} />+ </CardContent>+ </Card>++ <Separator />++ <div>+ <h2 className="text-sm font-medium text-[var(--color-text-primary)] mb-1">Webhook URLs</h2>+ <p className="text-xs text-[var(--color-text-tertiary)] mb-3">+ Configure your repository host to call these endpoints on push events.+ </p>+ <div className="space-y-2">+ {(["github", "gitlab"] as const).map((host) => (+ <div key={host} className="rounded-md bg-[var(--color-bg-inset)] px-3 py-2">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] mb-0.5 capitalize">+ {host}+ </p>+ <p className="text-xs font-mono text-[var(--color-text-secondary)] break-all">+ {`[your-server]/api/webhooks/${host}`}+ </p>+ </div>+ ))}+ </div>+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/symbols/loading.tsx b/packages/web/src/app/repos/[id]/symbols/loading.tsxnew file mode 100644index 000000000..9984d9e54--- /dev/null+++ b/packages/web/src/app/repos/[id]/symbols/loading.tsx@@ -0,0 +1,26 @@+import { Skeleton } from "@/components/ui/skeleton";++export default function SymbolsLoading() {+ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-6xl">+ <div>+ <Skeleton className="h-7 w-36" />+ <Skeleton className="h-4 w-56 mt-1.5" />+ </div>+ {/* Filter row */}+ <div className="flex flex-wrap gap-2">+ <Skeleton className="h-9 w-48" />+ <Skeleton className="h-9 w-32" />+ <Skeleton className="h-9 w-32" />+ </div>+ {/* Table rows */}+ <div className="space-y-px">+ <Skeleton className="h-10 rounded-t-lg" />+ {Array.from({ length: 8 }).map((_, i) => (+ <Skeleton key={i} className="h-12 rounded-none" />+ ))}+ <Skeleton className="h-12 rounded-b-lg" />+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/symbols/page.tsx b/packages/web/src/app/repos/[id]/symbols/page.tsxnew file mode 100644index 000000000..cb335abd1--- /dev/null+++ b/packages/web/src/app/repos/[id]/symbols/page.tsx@@ -0,0 +1,28 @@+import type { Metadata } from "next";+import { Code2 } from "lucide-react";+import { SymbolTable } from "@/components/symbols/symbol-table";++export const metadata: Metadata = { title: "Symbols" };++export default async function SymbolsPage({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id } = await params;++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-6xl">+ <div>+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">+ <Code2 className="h-5 w-5 text-[var(--color-accent-primary)]" />+ Symbol Index+ </h1>+ <p className="text-sm text-[var(--color-text-secondary)]">+ Searchable index of all functions, classes, and exports.+ </p>+ </div>+ <SymbolTable repoId={id} />+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/wiki/[...slug]/loading.tsx b/packages/web/src/app/repos/[id]/wiki/[...slug]/loading.tsxnew file mode 100644index 000000000..e43069b49--- /dev/null+++ b/packages/web/src/app/repos/[id]/wiki/[...slug]/loading.tsx@@ -0,0 +1,41 @@+import { Skeleton } from "@/components/ui/skeleton";++export default function WikiPageLoading() {+ return (+ <div className="flex h-full min-h-0">+ <div className="flex-1 min-w-0 overflow-auto">+ {/* Top bar */}+ <div className="sticky top-0 flex items-center gap-3 border-b border-[var(--color-border-default)] px-4 sm:px-6 py-2.5">+ <Skeleton className="h-4 flex-1 max-w-xs" />+ <Skeleton className="h-6 w-14" />+ <Skeleton className="h-6 w-24 hidden sm:block" />+ <Skeleton className="h-8 w-24" />+ </div>+ {/* Content */}+ <div className="px-4 sm:px-6 py-6 max-w-[768px] mx-auto space-y-4">+ <Skeleton className="h-8 w-3/4" />+ <div className="space-y-3">+ {Array.from({ length: 8 }).map((_, i) => (+ <Skeleton key={i} className={`h-4 ${i % 3 === 2 ? "w-2/3" : "w-full"}`} />+ ))}+ </div>+ <Skeleton className="h-32 w-full rounded-lg" />+ <div className="space-y-3">+ {Array.from({ length: 5 }).map((_, i) => (+ <Skeleton key={i} className="h-4 w-full" />+ ))}+ </div>+ </div>+ </div>+ {/* Context panel skeleton */}+ <div className="hidden xl:flex flex-col border-l border-[var(--color-border-default)] w-[280px] shrink-0">+ <div className="p-4 space-y-4">+ <Skeleton className="h-4 w-24" />+ {Array.from({ length: 5 }).map((_, i) => (+ <Skeleton key={i} className="h-4 w-full" />+ ))}+ </div>+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx b/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsxnew file mode 100644index 000000000..978199847--- /dev/null+++ b/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx@@ -0,0 +1,205 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import { getRepo } from "@/lib/api/repos";+import { getPageById, getPageVersions } from "@/lib/api/pages";+import { getGitMetadata } from "@/lib/api/git";+import { ConfidenceBadge } from "@/components/wiki/confidence-badge";+import { WikiRenderer } from "@/components/wiki/wiki-renderer";+import { TableOfContents } from "@/components/wiki/table-of-contents";+import { RegenerateButton } from "@/components/wiki/regenerate-button";+import { GitHistoryPanel } from "@/components/wiki/git-history-panel";+import { Badge } from "@/components/ui/badge";+import { Separator } from "@/components/ui/separator";+import { formatRelativeTime, formatTokens } from "@/lib/utils/format";+import { Hash, Cpu } from "lucide-react";++interface Props {+ params: Promise<{ id: string; slug: string[] }>;+}++export async function generateMetadata({ params }: Props): Promise<Metadata> {+ const { id, slug } = await params;+ const pageId = slug.join("/");+ try {+ const page = await getPageById(pageId);+ return { title: page.title };+ } catch {+ return { title: "Wiki Page" };+ }+}++export default async function WikiPageRoute({ params }: Props) {+ const { id, slug } = await params;+ const pageId = slug.join("/");++ let page;+ try {+ page = await getPageById(pageId);+ } catch {+ notFound();+ }++ const [repo, versions, gitMeta] = await Promise.allSettled([+ getRepo(id),+ getPageVersions(pageId),+ page.target_path ? getGitMetadata(id, page.target_path) : Promise.reject(),+ ]);++ const repoData = repo.status === "fulfilled" ? repo.value : null;+ const versionList = versions.status === "fulfilled" ? versions.value : [];+ const git = gitMeta.status === "fulfilled" ? gitMeta.value : null;++ return (+ <div className="flex h-full min-h-0">+ {/* Main content */}+ <div className="flex-1 min-w-0 overflow-auto">+ {/* Top bar */}+ <div className="sticky top-0 z-[var(--z-elevated)] flex items-center gap-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]/95 backdrop-blur px-3 sm:px-6 py-2.5 flex-wrap sm:flex-nowrap">+ {/* Breadcrumb */}+ <div className="flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] min-w-0 flex-1">+ {repoData && (+ <>+ <span className="hidden sm:block truncate max-w-[80px]">{repoData.name}</span>+ <span className="hidden sm:block">/</span>+ </>+ )}+ <span className="font-mono truncate text-[var(--color-text-secondary)] max-w-[180px] sm:max-w-none">+ {page.target_path || page.page_type}+ </span>+ </div>++ {/* Confidence badge */}+ <ConfidenceBadge+ score={page.confidence}+ status={page.freshness_status}+ showScore+ />++ {/* Provider badge */}+ <Badge variant="outline" className="font-mono text-xs hidden sm:flex shrink-0">+ <Cpu className="h-3 w-3 mr-1" />+ <span className="truncate max-w-[120px]">{page.provider_name}/{page.model_name}</span>+ </Badge>++ {/* Commit */}+ {page.source_hash && (+ <Badge variant="outline" className="font-mono text-xs hidden md:flex shrink-0">+ <Hash className="h-3 w-3 mr-1" />+ {page.source_hash.slice(0, 7)}+ </Badge>+ )}++ {/* Regenerate */}+ <RegenerateButton pageId={page.id} repoId={id} />+ </div>++ {/* Page content */}+ <div className="px-4 sm:px-6 py-6 max-w-[768px] mx-auto">+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-4 break-words">+ {page.title}+ </h1>++ <article className="prose prose-invert max-w-none leading-relaxed overflow-hidden">+ <WikiRenderer content={page.content} />+ </article>+ </div>++ {/* Bottom bar */}+ <div className="border-t border-[var(--color-border-default)] px-4 sm:px-6 py-3 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-[var(--color-text-tertiary)]">+ <span>Generated {formatRelativeTime(page.updated_at)}</span>+ <Separator orientation="vertical" className="h-4 hidden sm:block" />+ <span className="font-mono">+ {formatTokens(page.input_tokens)} in · {formatTokens(page.output_tokens)} out+ </span>+ {versionList.length > 0 && (+ <>+ <Separator orientation="vertical" className="h-4 hidden sm:block" />+ <span>v{page.version} ({versionList.length} versions)</span>+ </>+ )}+ </div>+ </div>++ {/* Context panel (right sidebar) */}+ <div+ className="hidden xl:flex flex-col border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shrink-0"+ style={{ width: "280px" }}+ >+ <div className="overflow-auto flex-1 p-4 space-y-5">+ {/* Table of contents */}+ <TableOfContents content={page.content} />++ {/* Git history panel */}+ {git && (+ <div>+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ Git History+ </p>+ <div className="space-y-1.5 mb-3">+ <div className="flex justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Commits (90d)</span>+ <span className="text-[var(--color-text-secondary)] tabular-nums">+ {git.commit_count_90d}+ </span>+ </div>+ <div className="flex justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Churn</span>+ <span className="text-[var(--color-text-secondary)] tabular-nums">+ {Math.round(git.churn_percentile)}th pct+ </span>+ </div>+ {git.is_hotspot && (+ <Badge variant="stale" className="text-xs">Hotspot</Badge>+ )}+ </div>+ <GitHistoryPanel git={git} />+ </div>+ )}++ {/* Co-change partners */}+ {git && git.co_change_partners.length > 0 && (+ <div>+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ Co-change Partners+ </p>+ <ul className="space-y-1.5">+ {git.co_change_partners.slice(0, 5).map((p) => (+ <li key={p.file_path} className="text-xs min-w-0">+ <span className="font-mono text-[var(--color-text-secondary)] block truncate">+ {p.file_path}+ </span>+ <span className="text-[var(--color-text-tertiary)]">+ {p.co_change_count}× together+ </span>+ </li>+ ))}+ </ul>+ </div>+ )}++ {/* Page metadata */}+ <div>+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ Page Info+ </p>+ <div className="space-y-1.5 text-xs">+ <div className="flex justify-between gap-2">+ <span className="text-[var(--color-text-tertiary)] shrink-0">Type</span>+ <span className="text-[var(--color-text-secondary)] font-mono truncate">{page.page_type}</span>+ </div>+ <div className="flex justify-between gap-2">+ <span className="text-[var(--color-text-tertiary)] shrink-0">Version</span>+ <span className="text-[var(--color-text-secondary)] tabular-nums">v{page.version}</span>+ </div>+ <div className="flex justify-between gap-2">+ <span className="text-[var(--color-text-tertiary)] shrink-0">Level</span>+ <span className="text-[var(--color-text-secondary)] tabular-nums">{page.generation_level}</span>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+}+diff --git a/packages/web/src/app/settings/page.tsx b/packages/web/src/app/settings/page.tsxnew file mode 100644index 000000000..eeade2231--- /dev/null+++ b/packages/web/src/app/settings/page.tsx@@ -0,0 +1,25 @@+import type { Metadata } from "next";+import { ConnectionSection } from "@/components/settings/connection-section";+import { ProviderSection } from "@/components/settings/provider-section";+import { WebhookSection } from "@/components/settings/webhook-section";+import { McpSection } from "@/components/settings/mcp-section";++export const metadata: Metadata = { title: "Settings" };++export default function SettingsPage() {+ return (+ <div className="p-4 sm:p-6 max-w-2xl space-y-6">+ <div>+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)]">Settings</h1>+ <p className="text-sm text-[var(--color-text-secondary)] mt-1">+ API connection, provider defaults, and integration config.+ </p>+ </div>++ <ConnectionSection />+ <ProviderSection />+ <WebhookSection />+ <McpSection />+ </div>+ );+}diff --git a/packages/web/src/components/coverage/coverage-donut.tsx b/packages/web/src/components/coverage/coverage-donut.tsxnew file mode 100644index 000000000..5a1dd8445--- /dev/null+++ b/packages/web/src/components/coverage/coverage-donut.tsx@@ -0,0 +1,69 @@+"use client";++import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from "recharts";++interface CoverageDonutProps {+ fresh: number;+ stale: number;+ outdated: number;+}++const COLORS = ["#22c55e", "#eab308", "#ef4444"];+const LABELS = ["Fresh", "Stale", "Outdated"];++export function CoverageDonut({ fresh, stale, outdated }: CoverageDonutProps) {+ const total = fresh + stale + outdated;+ const data = [+ { name: "Fresh", value: fresh },+ { name: "Stale", value: stale },+ { name: "Outdated", value: outdated },+ ].filter((d) => d.value > 0);++ const freshPct = total > 0 ? Math.round((fresh / total) * 100) : 0;++ return (+ <div className="relative flex items-center justify-center">+ <ResponsiveContainer width={200} height={200}>+ <PieChart>+ <Pie+ data={data}+ cx="50%"+ cy="50%"+ innerRadius={60}+ outerRadius={90}+ paddingAngle={2}+ dataKey="value"+ startAngle={90}+ endAngle={-270}+ >+ {data.map((entry) => (+ <Cell+ key={entry.name}+ fill={COLORS[LABELS.indexOf(entry.name)]}+ strokeWidth={0}+ />+ ))}+ </Pie>+ <Tooltip+ contentStyle={{+ background: "var(--color-bg-overlay)",+ border: "1px solid var(--color-border-default)",+ borderRadius: "6px",+ fontSize: "12px",+ color: "var(--color-text-primary)",+ }}+ formatter={(value: number) => [+ `${value} pages (${total > 0 ? Math.round((value / total) * 100) : 0}%)`,+ ]}+ />+ </PieChart>+ </ResponsiveContainer>+ <div className="absolute flex flex-col items-center pointer-events-none">+ <span className="text-3xl font-bold text-[var(--color-text-primary)] tabular-nums">+ {freshPct}%+ </span>+ <span className="text-xs text-[var(--color-text-tertiary)]">fresh</span>+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/coverage/freshness-table.tsx b/packages/web/src/components/coverage/freshness-table.tsxnew file mode 100644index 000000000..50a3bd8b3--- /dev/null+++ b/packages/web/src/components/coverage/freshness-table.tsx@@ -0,0 +1,149 @@+"use client";++import { useState } from "react";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { EmptyState } from "@/components/shared/empty-state";+import { regeneratePage } from "@/lib/api/pages";+import { statusBadgeClasses, statusLabel } from "@/lib/utils/confidence";+import { truncatePath, formatConfidence, formatRelativeTime } from "@/lib/utils/format";+import { cn } from "@/lib/utils/cn";+import type { PageResponse } from "@/lib/api/types";+import type { FreshnessStatus } from "@/lib/utils/confidence";++type Filter = "all" | FreshnessStatus;++interface FreshnessTableProps {+ pages: PageResponse[];+}++export function FreshnessTable({ pages }: FreshnessTableProps) {+ const [filter, setFilter] = useState<Filter>("all");+ const [regenerating, setRegenerating] = useState<Set<string>>(new Set());++ const filtered = filter === "all" ? pages : pages.filter((p) => p.freshness_status === filter);++ const handleRegenerate = async (pageId: string) => {+ setRegenerating((prev) => new Set(prev).add(pageId));+ try {+ await regeneratePage(pageId);+ } finally {+ setRegenerating((prev) => {+ const next = new Set(prev);+ next.delete(pageId);+ return next;+ });+ }+ };++ return (+ <div className="space-y-4">+ {/* Filter tabs */}+ <div className="flex items-center gap-1">+ {(["all", "fresh", "stale", "outdated"] as Filter[]).map((f) => {+ const count = f === "all" ? pages.length : pages.filter((p) => p.freshness_status === f).length;+ return (+ <button+ key={f}+ onClick={() => setFilter(f)}+ className={cn(+ "rounded-md px-3 py-1.5 text-xs font-medium transition-colors",+ filter === f+ ? "bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] shadow-sm"+ : "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]",+ )}+ >+ {f === "all" ? "All" : statusLabel(f as FreshnessStatus)}+ <span className="ml-1 text-[var(--color-text-tertiary)]">({count})</span>+ </button>+ );+ })}+ </div>++ {filtered.length === 0 ? (+ <EmptyState title="No pages" description="No pages match this filter." />+ ) : (+ <div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto">+ <table className="w-full min-w-[560px] text-sm">+ <thead>+ <tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ Page+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24">+ Status+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24">+ Confidence+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ Model+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-28">+ Updated+ </th>+ <th className="px-4 py-2.5 w-24" />+ </tr>+ </thead>+ <tbody>+ {filtered.map((page) => {+ const status = page.freshness_status as FreshnessStatus;+ return (+ <tr+ key={page.id}+ className="border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0"+ >+ <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] max-w-xs">+ <div className="truncate">{truncatePath(page.target_path, 50)}</div>+ <div className="text-[var(--color-text-tertiary)]">{page.page_type}</div>+ </td>+ <td className="px-4 py-2.5">+ <span+ className={cn(+ "inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium",+ statusBadgeClasses(status),+ )}+ >+ {statusLabel(status)}+ </span>+ </td>+ <td className="px-4 py-2.5 text-xs tabular-nums">+ <span+ className={cn(+ page.confidence >= 0.8+ ? "text-green-500"+ : page.confidence >= 0.6+ ? "text-yellow-500"+ : "text-red-500",+ )}+ >+ {formatConfidence(page.confidence)}+ </span>+ </td>+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-tertiary)]">+ {page.model_name}+ </td>+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-tertiary)]">+ {formatRelativeTime(page.updated_at)}+ </td>+ <td className="px-4 py-2.5">+ <Button+ size="sm"+ variant="ghost"+ disabled={regenerating.has(page.id)}+ onClick={() => handleRegenerate(page.id)}+ className="h-6 px-2 text-xs"+ >+ {regenerating.has(page.id) ? "…" : "Regenerate"}+ </Button>+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ )}+ </div>+ );+}diff --git a/packages/web/src/components/dead-code/finding-row.tsx b/packages/web/src/components/dead-code/finding-row.tsxnew file mode 100644index 000000000..e3d89684d--- /dev/null+++ b/packages/web/src/components/dead-code/finding-row.tsx@@ -0,0 +1,131 @@+"use client";++import { useState } from "react";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { truncatePath, formatConfidence } from "@/lib/utils/format";+import { patchDeadCodeFinding } from "@/lib/api/dead-code";+import { cn } from "@/lib/utils/cn";+import type { DeadCodeFindingResponse } from "@/lib/api/types";++interface FindingRowProps {+ finding: DeadCodeFindingResponse;+ selected: boolean;+ onToggle: (id: string) => void;+ onUpdate: (updated: DeadCodeFindingResponse) => void;+}++const STATUS_COLORS: Record<string, string> = {+ open: "bg-red-500/10 text-red-500 border-red-500/20",+ acknowledged: "bg-yellow-500/10 text-yellow-500 border-yellow-500/20",+ resolved: "bg-green-500/10 text-green-500 border-green-500/20",+ false_positive: "bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] border-[var(--color-border-default)]",+};++export function FindingRow({ finding, selected, onToggle, onUpdate }: FindingRowProps) {+ const [pending, setPending] = useState(false);++ const patch = async (status: string) => {+ setPending(true);+ try {+ const updated = await patchDeadCodeFinding(finding.id, { status });+ onUpdate(updated);+ } finally {+ setPending(false);+ }+ };++ return (+ <tr+ className={cn(+ "border-b border-[var(--color-border-default)] transition-colors last:border-0",+ selected ? "bg-[var(--color-accent-muted)]" : "hover:bg-[var(--color-bg-elevated)]",+ )}+ >+ <td className="px-4 py-2.5">+ <input+ type="checkbox"+ checked={selected}+ onChange={() => onToggle(finding.id)}+ className="rounded border-[var(--color-border-default)]"+ />+ </td>+ <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] max-w-xs">+ <span className="truncate block">{truncatePath(finding.file_path, 50)}</span>+ {finding.symbol_name && (+ <span className="text-[var(--color-text-tertiary)]">{finding.symbol_name}</span>+ )}+ </td>+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] tabular-nums">+ <span+ className={cn(+ "font-medium",+ finding.confidence >= 0.8+ ? "text-red-500"+ : finding.confidence >= 0.6+ ? "text-yellow-500"+ : "text-[var(--color-text-secondary)]",+ )}+ >+ {formatConfidence(finding.confidence)}+ </span>+ </td>+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)]">+ {finding.primary_owner ?? "—"}+ </td>+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-tertiary)] tabular-nums">+ {finding.lines}+ </td>+ <td className="px-4 py-2.5">+ {finding.safe_to_delete ? (+ <Badge variant="fresh">Safe</Badge>+ ) : (+ <Badge variant="default">Review</Badge>+ )}+ </td>+ <td className="px-4 py-2.5">+ <span+ className={cn(+ "inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium",+ STATUS_COLORS[finding.status] ?? STATUS_COLORS.open,+ )}+ >+ {finding.status.replace(/_/g, " ")}+ </span>+ </td>+ <td className="px-4 py-2.5">+ {finding.status === "open" && (+ <div className="flex items-center gap-1">+ <Button+ size="sm"+ variant="ghost"+ disabled={pending}+ onClick={() => patch("resolved")}+ className="h-6 px-2 text-xs text-green-500 hover:text-green-400"+ >+ Resolve+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={pending}+ onClick={() => patch("acknowledged")}+ className="h-6 px-2 text-xs"+ >+ Ack+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={pending}+ onClick={() => patch("false_positive")}+ className="h-6 px-2 text-xs text-[var(--color-text-tertiary)]"+ >+ FP+ </Button>+ </div>+ )}+ </td>+ </tr>+ );+}diff --git a/packages/web/src/components/dead-code/findings-table.tsx b/packages/web/src/components/dead-code/findings-table.tsxnew file mode 100644index 000000000..1eb25666c--- /dev/null+++ b/packages/web/src/components/dead-code/findings-table.tsx@@ -0,0 +1,213 @@+"use client";++import { useState, useEffect } from "react";+import useSWR from "swr";+import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";+import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";+import { EmptyState } from "@/components/shared/empty-state";+import { FindingRow } from "./finding-row";+import { listDeadCode, patchDeadCodeFinding } from "@/lib/api/dead-code";+import type { DeadCodeFindingResponse } from "@/lib/api/types";++type Kind = "unreachable_file" | "unused_export" | "zombie_package";++const TABS: Array<{ value: Kind; label: string }> = [+ { value: "unreachable_file", label: "Unreachable Files" },+ { value: "unused_export", label: "Unused Exports" },+ { value: "zombie_package", label: "Zombie Packages" },+];++interface FindingsTableProps {+ repoId: string;+}++export function FindingsTable({ repoId }: FindingsTableProps) {+ const [activeTab, setActiveTab] = useState<Kind>("unreachable_file");+ const [minConfidence, setMinConfidence] = useState(0.4);+ const [safeOnly, setSafeOnly] = useState(false);+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [items, setItems] = useState<Record<Kind, DeadCodeFindingResponse[]>>({+ unreachable_file: [],+ unused_export: [],+ zombie_package: [],+ });+ const [bulkPending, setBulkPending] = useState(false);++ const { data, isLoading } = useSWR(+ `dead-code:${repoId}:${activeTab}:${minConfidence}:${safeOnly}`,+ () =>+ listDeadCode(repoId, {+ kind: activeTab,+ min_confidence: minConfidence,+ safe_only: safeOnly || undefined,+ status: "open",+ limit: 200,+ }),+ { revalidateOnFocus: false },+ );++ useEffect(() => {+ if (!data) return;+ setItems((prev) => ({ ...prev, [activeTab]: data }));+ setSelected(new Set());+ }, [data, activeTab]);++ const handleUpdate = (updated: DeadCodeFindingResponse) => {+ setItems((prev) => ({+ ...prev,+ [activeTab]: prev[activeTab].map((f) => (f.id === updated.id ? updated : f)),+ }));+ };++ const toggleSelect = (id: string) => {+ setSelected((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ };++ const toggleSelectAll = () => {+ const current = items[activeTab];+ if (selected.size === current.length) {+ setSelected(new Set());+ } else {+ setSelected(new Set(current.map((f) => f.id)));+ }+ };++ const resolveSelected = async () => {+ setBulkPending(true);+ try {+ for (const id of selected) {+ const updated = await patchDeadCodeFinding(id, { status: "resolved" });+ handleUpdate(updated);+ }+ setSelected(new Set());+ } finally {+ setBulkPending(false);+ }+ };++ const current = items[activeTab];++ return (+ <div className="space-y-4">+ {/* Controls */}+ <div className="flex flex-wrap items-center gap-4">+ <div className="flex items-center gap-2">+ <label className="text-xs text-[var(--color-text-secondary)]">+ Min confidence: {Math.round(minConfidence * 100)}%+ </label>+ <input+ type="range"+ min="0.4"+ max="1"+ step="0.05"+ value={minConfidence}+ onChange={(e) => setMinConfidence(Number(e.target.value))}+ className="w-28 accent-[var(--color-accent-primary)]"+ />+ </div>+ <label className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] cursor-pointer select-none">+ <input+ type="checkbox"+ checked={safeOnly}+ onChange={(e) => setSafeOnly(e.target.checked)}+ className="rounded border-[var(--color-border-default)]"+ />+ Safe to delete only+ </label>++ {selected.size > 0 && (+ <Button+ size="sm"+ variant="outline"+ disabled={bulkPending}+ onClick={resolveSelected}+ className="text-green-500 border-green-500/30 hover:bg-green-500/10"+ >+ {bulkPending ? "Resolving…" : `Resolve ${selected.size} selected`}+ </Button>+ )}+ </div>++ <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as Kind)}>+ <TabsList>+ {TABS.map((t) => (+ <TabsTrigger key={t.value} value={t.value}>+ {t.label}+ {items[t.value].length > 0 && (+ <span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">+ {items[t.value].length}+ </span>+ )}+ </TabsTrigger>+ ))}+ </TabsList>++ {TABS.map((t) => (+ <TabsContent key={t.value} value={t.value}>+ {isLoading && current.length === 0 ? (+ <div className="space-y-2 mt-2">+ {Array.from({ length: 6 }).map((_, i) => (+ <Skeleton key={i} className="h-10 w-full" />+ ))}+ </div>+ ) : current.length === 0 ? (+ <EmptyState+ title="No findings"+ description="No open findings for this category with current filters."+ />+ ) : (+ <div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto mt-2">+ <table className="w-full min-w-[560px] text-sm">+ <thead>+ <tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">+ <th className="px-4 py-2.5 w-8">+ <input+ type="checkbox"+ checked={selected.size === current.length && current.length > 0}+ onChange={toggleSelectAll}+ className="rounded border-[var(--color-border-default)]"+ />+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ File / Symbol+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24">+ Confidence+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ Owner+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-16">+ Lines+ </th>+ <th className="px-4 py-2.5 w-20" />+ <th className="px-4 py-2.5 w-24" />+ <th className="px-4 py-2.5 w-36" />+ </tr>+ </thead>+ <tbody>+ {current.map((f) => (+ <FindingRow+ key={f.id}+ finding={f}+ selected={selected.has(f.id)}+ onToggle={toggleSelect}+ onUpdate={handleUpdate}+ />+ ))}+ </tbody>+ </table>+ </div>+ )}+ </TabsContent>+ ))}+ </Tabs>+ </div>+ );+}diff --git a/packages/web/src/components/dead-code/summary-bar.tsx b/packages/web/src/components/dead-code/summary-bar.tsxnew file mode 100644index 000000000..9eded243d--- /dev/null+++ b/packages/web/src/components/dead-code/summary-bar.tsx@@ -0,0 +1,62 @@+import { formatNumber } from "@/lib/utils/format";+import type { DeadCodeSummaryResponse } from "@/lib/api/types";++interface SummaryBarProps {+ summary: DeadCodeSummaryResponse;+}++export function SummaryBar({ summary }: SummaryBarProps) {+ return (+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1">+ Total Findings+ </p>+ <p className="text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">+ {formatNumber(summary.total_findings)}+ </p>+ </div>++ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1">+ Deletable Lines+ </p>+ <p className="text-2xl font-bold text-red-500 tabular-nums">+ {formatNumber(summary.deletable_lines)}+ </p>+ </div>++ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ By Kind+ </p>+ <div className="space-y-1">+ {Object.entries(summary.by_kind).map(([kind, count]) => (+ <div key={kind} className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-secondary)] truncate">{kind.replace(/_/g, " ")}</span>+ <span className="text-[var(--color-text-primary)] tabular-nums font-medium ml-2">+ {formatNumber(count)}+ </span>+ </div>+ ))}+ </div>+ </div>++ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ Confidence+ </p>+ <div className="space-y-1">+ {Object.entries(summary.confidence_summary).map(([level, count]) => (+ <div key={level} className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-secondary)]">{level}</span>+ <span className="text-[var(--color-text-primary)] tabular-nums font-medium">+ {formatNumber(count)}+ </span>+ </div>+ ))}+ </div>+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/decisions/decision-detail.tsx b/packages/web/src/components/decisions/decision-detail.tsxnew file mode 100644index 000000000..6f890a2e8--- /dev/null+++ b/packages/web/src/components/decisions/decision-detail.tsx@@ -0,0 +1,185 @@+"use client";++import * as React from "react";+import { Badge } from "@/components/ui/badge";+import { patchDecision } from "@/lib/api/decisions";+import type { DecisionRecordResponse } from "@/lib/api/types";++const STATUS_VARIANT: Record<string, "default" | "secondary" | "destructive" | "outline"> = {+ active: "default",+ proposed: "secondary",+ deprecated: "destructive",+ superseded: "outline",+};++interface DecisionDetailProps {+ decision: DecisionRecordResponse;+ repoId: string;+}++export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {+ const [status, setStatus] = React.useState(decision.status);+ const [loading, setLoading] = React.useState(false);++ const handleStatusChange = async (newStatus: string) => {+ setLoading(true);+ try {+ await patchDecision(repoId, decision.id, { status: newStatus });+ setStatus(newStatus as typeof status);+ } finally {+ setLoading(false);+ }+ };++ return (+ <div className="space-y-6">+ {/* Header */}+ <div className="space-y-2">+ <div className="flex items-center gap-3">+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)]">+ {decision.title}+ </h1>+ <Badge variant={STATUS_VARIANT[status] ?? "outline"}>{status}</Badge>+ </div>+ <div className="flex gap-4 text-sm text-[var(--color-text-tertiary)]">+ <span>Source: {decision.source}</span>+ <span>Confidence: {Math.round(decision.confidence * 100)}%</span>+ {decision.staleness_score > 0 && (+ <span className={decision.staleness_score > 0.5 ? "text-red-500" : ""}>+ Staleness: {decision.staleness_score.toFixed(2)}+ </span>+ )}+ <span>Created: {new Date(decision.created_at).toLocaleDateString()}</span>+ </div>+ </div>++ {/* Stale warning */}+ {decision.staleness_score > 0.5 && (+ <div className="rounded-md border border-amber-400/30 bg-amber-50 px-4 py-3 text-sm text-amber-800 dark:bg-amber-900/20 dark:text-amber-200">+ This decision may be stale — affected files have changed significantly since it was recorded.+ </div>+ )}++ {/* Content sections */}+ <div className="space-y-4">+ {decision.context && (+ <Section title="Context" text={decision.context} />+ )}+ {decision.decision && (+ <Section title="Decision" text={decision.decision} />+ )}+ {decision.rationale && (+ <Section title="Rationale" text={decision.rationale} />+ )}+ {decision.alternatives.length > 0 && (+ <ListSection title="Alternatives Rejected" items={decision.alternatives} />+ )}+ {decision.consequences.length > 0 && (+ <ListSection title="Consequences & Tradeoffs" items={decision.consequences} />+ )}+ </div>++ {/* Metadata */}+ <div className="grid gap-4 sm:grid-cols-2">+ {decision.affected_files.length > 0 && (+ <div className="rounded-lg border border-[var(--color-border-default)] p-4">+ <h3 className="mb-2 text-sm font-medium text-[var(--color-text-secondary)]">+ Affected Files ({decision.affected_files.length})+ </h3>+ <ul className="space-y-1 text-sm text-[var(--color-text-tertiary)]">+ {decision.affected_files.slice(0, 10).map((f) => (+ <li key={f} className="truncate font-mono text-xs">{f}</li>+ ))}+ {decision.affected_files.length > 10 && (+ <li className="text-xs">...and {decision.affected_files.length - 10} more</li>+ )}+ </ul>+ </div>+ )}++ <div className="rounded-lg border border-[var(--color-border-default)] p-4">+ <h3 className="mb-2 text-sm font-medium text-[var(--color-text-secondary)]">Evidence</h3>+ <div className="space-y-1 text-sm text-[var(--color-text-tertiary)]">+ <div>Source: {decision.source}</div>+ {decision.evidence_file && (+ <div className="font-mono text-xs">+ {decision.evidence_file}+ {decision.evidence_line && `:${decision.evidence_line}`}+ </div>+ )}+ {decision.evidence_commits.length > 0 && (+ <div>Commits: {decision.evidence_commits.map((c) => c.slice(0, 8)).join(", ")}</div>+ )}+ </div>+ </div>+ </div>++ {/* Tags */}+ {decision.tags.length > 0 && (+ <div className="flex flex-wrap gap-1.5">+ {decision.tags.map((tag) => (+ <span+ key={tag}+ className="inline-block rounded-full bg-[var(--color-bg-elevated)] px-2.5 py-0.5 text-xs font-medium text-[var(--color-text-secondary)]"+ >+ {tag}+ </span>+ ))}+ </div>+ )}++ {/* Actions */}+ <div className="flex gap-2 border-t border-[var(--color-border-default)] pt-4">+ {status === "proposed" && (+ <>+ <button+ onClick={() => handleStatusChange("active")}+ disabled={loading}+ className="rounded-md bg-green-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-green-700 disabled:opacity-50"+ >+ Confirm+ </button>+ <button+ onClick={() => handleStatusChange("deprecated")}+ disabled={loading}+ className="rounded-md border border-[var(--color-border-default)] px-3 py-1.5 text-sm text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] disabled:opacity-50"+ >+ Dismiss+ </button>+ </>+ )}+ {status === "active" && (+ <button+ onClick={() => handleStatusChange("deprecated")}+ disabled={loading}+ className="rounded-md border border-red-300 px-3 py-1.5 text-sm text-red-600 hover:bg-red-50 dark:border-red-800 dark:text-red-400 dark:hover:bg-red-900/20 disabled:opacity-50"+ >+ Deprecate+ </button>+ )}+ </div>+ </div>+ );+}++function Section({ title, text }: { title: string; text: string }) {+ return (+ <div>+ <h3 className="mb-1 text-sm font-medium text-[var(--color-text-secondary)]">{title}</h3>+ <p className="text-sm text-[var(--color-text-primary)] leading-relaxed">{text}</p>+ </div>+ );+}++function ListSection({ title, items }: { title: string; items: string[] }) {+ return (+ <div>+ <h3 className="mb-1 text-sm font-medium text-[var(--color-text-secondary)]">{title}</h3>+ <ul className="list-disc space-y-0.5 pl-5 text-sm text-[var(--color-text-primary)]">+ {items.map((item, i) => (+ <li key={i}>{item}</li>+ ))}+ </ul>+ </div>+ );+}diff --git a/packages/web/src/components/decisions/decision-health-widget.tsx b/packages/web/src/components/decisions/decision-health-widget.tsxnew file mode 100644index 000000000..458ce2ffb--- /dev/null+++ b/packages/web/src/components/decisions/decision-health-widget.tsx@@ -0,0 +1,39 @@+"use client";++import useSWR from "swr";+import { getDecisionHealth } from "@/lib/api/decisions";+import { StatCard } from "@/components/shared/stat-card";++interface DecisionHealthWidgetProps {+ repoId: string;+}++export function DecisionHealthWidget({ repoId }: DecisionHealthWidgetProps) {+ const { data: health } = useSWR(+ `/api/repos/${repoId}/decisions/health`,+ () => getDecisionHealth(repoId),+ );++ if (!health) return null;++ const { summary } = health;++ return (+ <div className="grid grid-cols-3 gap-3">+ <StatCard+ label="Active Decisions"+ value={summary.active}+ />+ <StatCard+ label="Proposed"+ value={summary.proposed}+ variant={summary.proposed > 0 ? "warning" : "default"}+ />+ <StatCard+ label="Stale"+ value={summary.stale}+ variant={summary.stale > 0 ? "danger" : "default"}+ />+ </div>+ );+}diff --git a/packages/web/src/components/decisions/decisions-table.tsx b/packages/web/src/components/decisions/decisions-table.tsxnew file mode 100644index 000000000..7c29aa6b5--- /dev/null+++ b/packages/web/src/components/decisions/decisions-table.tsx@@ -0,0 +1,146 @@+"use client";++import * as React from "react";+import Link from "next/link";+import useSWR from "swr";+import { Badge } from "@/components/ui/badge";+import { listDecisions } from "@/lib/api/decisions";+import type { DecisionRecordResponse } from "@/lib/api/types";++const STATUS_VARIANT: Record<string, "default" | "secondary" | "destructive" | "outline"> = {+ active: "default",+ proposed: "secondary",+ deprecated: "destructive",+ superseded: "outline",+};++const SOURCE_LABEL: Record<string, string> = {+ inline_marker: "Inline",+ git_archaeology: "Git",+ readme_mining: "Docs",+ cli: "Manual",+};++interface DecisionsTableProps {+ repoId: string;+ initialData?: DecisionRecordResponse[];+}++export function DecisionsTable({ repoId, initialData }: DecisionsTableProps) {+ const [statusFilter, setStatusFilter] = React.useState<string>("all");+ const [sourceFilter, setSourceFilter] = React.useState<string>("all");++ const { data: decisions } = useSWR(+ [`/api/repos/${repoId}/decisions`, statusFilter, sourceFilter],+ () =>+ listDecisions(repoId, {+ status: statusFilter !== "all" ? statusFilter : undefined,+ source: sourceFilter !== "all" ? sourceFilter : undefined,+ include_proposed: true,+ limit: 100,+ }),+ { fallbackData: initialData },+ );++ return (+ <div className="space-y-4">+ {/* Filters */}+ <div className="flex gap-3">+ <select+ value={statusFilter}+ onChange={(e) => setStatusFilter(e.target.value)}+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)]"+ >+ <option value="all">All statuses</option>+ <option value="active">Active</option>+ <option value="proposed">Proposed</option>+ <option value="deprecated">Deprecated</option>+ <option value="superseded">Superseded</option>+ </select>+ <select+ value={sourceFilter}+ onChange={(e) => setSourceFilter(e.target.value)}+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)]"+ >+ <option value="all">All sources</option>+ <option value="inline_marker">Inline markers</option>+ <option value="git_archaeology">Git archaeology</option>+ <option value="readme_mining">Docs mining</option>+ <option value="cli">Manual</option>+ </select>+ </div>++ {/* Table */}+ <div className="overflow-x-auto rounded-lg border border-[var(--color-border-default)]">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">+ <th className="px-4 py-2.5 text-left font-medium text-[var(--color-text-secondary)]">Title</th>+ <th className="px-4 py-2.5 text-left font-medium text-[var(--color-text-secondary)]">Status</th>+ <th className="px-4 py-2.5 text-left font-medium text-[var(--color-text-secondary)]">Source</th>+ <th className="px-4 py-2.5 text-right font-medium text-[var(--color-text-secondary)]">Confidence</th>+ <th className="px-4 py-2.5 text-left font-medium text-[var(--color-text-secondary)]">Tags</th>+ <th className="px-4 py-2.5 text-right font-medium text-[var(--color-text-secondary)]">Staleness</th>+ </tr>+ </thead>+ <tbody>+ {decisions?.map((d) => (+ <tr+ key={d.id}+ className={`border-b border-[var(--color-border-default)] transition-colors hover:bg-[var(--color-bg-elevated)] ${+ d.status === "proposed" ? "border-l-2 border-l-amber-400" : ""+ }`}+ >+ <td className="px-4 py-2.5">+ <Link+ href={`/repos/${repoId}/decisions/${d.id}`}+ className="font-medium text-[var(--color-accent-primary)] hover:underline"+ >+ {d.title}+ </Link>+ </td>+ <td className="px-4 py-2.5">+ <Badge variant={STATUS_VARIANT[d.status] ?? "outline"}>{d.status}</Badge>+ </td>+ <td className="px-4 py-2.5 text-[var(--color-text-secondary)]">+ {SOURCE_LABEL[d.source] ?? d.source}+ </td>+ <td className="px-4 py-2.5 text-right tabular-nums text-[var(--color-text-secondary)]">+ {Math.round(d.confidence * 100)}%+ </td>+ <td className="px-4 py-2.5">+ <div className="flex flex-wrap gap-1">+ {d.tags.slice(0, 3).map((tag) => (+ <span+ key={tag}+ className="inline-block rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs text-[var(--color-text-tertiary)]"+ >+ {tag}+ </span>+ ))}+ </div>+ </td>+ <td className="px-4 py-2.5 text-right tabular-nums">+ {d.staleness_score > 0.5 ? (+ <span className="text-red-500">{d.staleness_score.toFixed(1)}</span>+ ) : d.staleness_score > 0 ? (+ <span className="text-[var(--color-text-tertiary)]">{d.staleness_score.toFixed(1)}</span>+ ) : (+ <span className="text-[var(--color-text-tertiary)]">-</span>+ )}+ </td>+ </tr>+ ))}+ {!decisions?.length && (+ <tr>+ <td colSpan={6} className="px-4 py-8 text-center text-[var(--color-text-tertiary)]">+ No decisions found+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/git/churn-bar.tsx b/packages/web/src/components/git/churn-bar.tsxnew file mode 100644index 000000000..cd2fc5250--- /dev/null+++ b/packages/web/src/components/git/churn-bar.tsx@@ -0,0 +1,24 @@+import { cn } from "@/lib/utils/cn";++interface ChurnBarProps {+ percentile: number; // 0-100+ className?: string;+}++export function ChurnBar({ percentile, className }: ChurnBarProps) {+ const color =+ percentile >= 75+ ? "bg-red-500"+ : percentile >= 50+ ? "bg-yellow-500"+ : "bg-green-500";++ return (+ <div className={cn("h-1.5 w-full rounded-full bg-[var(--color-bg-elevated)]", className)}>+ <div+ className={cn("h-1.5 rounded-full transition-all", color)}+ style={{ width: `${Math.min(100, Math.max(0, percentile))}%` }}+ />+ </div>+ );+}diff --git a/packages/web/src/components/git/contributor-bar.tsx b/packages/web/src/components/git/contributor-bar.tsxnew file mode 100644index 000000000..db340079e--- /dev/null+++ b/packages/web/src/components/git/contributor-bar.tsx@@ -0,0 +1,55 @@+"use client";++import {+ BarChart,+ Bar,+ XAxis,+ YAxis,+ Tooltip,+ ResponsiveContainer,+} from "recharts";++interface ContributorBarProps {+ owners: Array<{ name: string; email: string; file_count: number; pct: number }>;+}++export function ContributorBar({ owners }: ContributorBarProps) {+ const data = owners.slice(0, 5).map((o) => ({+ name: o.name.split(" ")[0] ?? o.name,+ files: o.file_count,+ }));++ if (data.length === 0) return null;++ return (+ <ResponsiveContainer width="100%" height={160}>+ <BarChart+ layout="vertical"+ data={data}+ margin={{ top: 0, right: 16, bottom: 0, left: 0 }}+ >+ <XAxis type="number" hide />+ <YAxis+ type="category"+ dataKey="name"+ width={72}+ tick={{ fill: "var(--color-text-secondary)", fontSize: 12 }}+ axisLine={false}+ tickLine={false}+ />+ <Tooltip+ cursor={{ fill: "var(--color-bg-elevated)" }}+ contentStyle={{+ background: "var(--color-bg-overlay)",+ border: "1px solid var(--color-border-default)",+ borderRadius: "6px",+ fontSize: "12px",+ color: "var(--color-text-primary)",+ }}+ formatter={(value: number) => [value, "files"]}+ />+ <Bar dataKey="files" fill="var(--color-accent-primary)" radius={[0, 4, 4, 0]} />+ </BarChart>+ </ResponsiveContainer>+ );+}diff --git a/packages/web/src/components/git/hotspot-table.tsx b/packages/web/src/components/git/hotspot-table.tsxnew file mode 100644index 000000000..2fce0019d--- /dev/null+++ b/packages/web/src/components/git/hotspot-table.tsx@@ -0,0 +1,79 @@+import { Badge } from "@/components/ui/badge";+import { EmptyState } from "@/components/shared/empty-state";+import { ChurnBar } from "./churn-bar";+import { truncatePath } from "@/lib/utils/format";+import type { HotspotResponse } from "@/lib/api/types";++interface HotspotTableProps {+ hotspots: HotspotResponse[];+}++export function HotspotTable({ hotspots }: HotspotTableProps) {+ if (hotspots.length === 0) {+ return (+ <EmptyState+ title="No hotspots found"+ description="All files look stable — great work!"+ />+ );+ }++ return (+ <div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto">+ <table className="w-full min-w-[560px] text-sm">+ <thead>+ <tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-8">+ #+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ File+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-28">+ Commits 90d+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-36">+ Churn+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ Owner+ </th>+ <th className="px-4 py-2.5 w-16" />+ </tr>+ </thead>+ <tbody>+ {hotspots.map((h, i) => (+ <tr+ key={h.file_path}+ className="border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0"+ >+ <td className="px-4 py-2.5 text-[var(--color-text-tertiary)] tabular-nums text-xs">+ {i + 1}+ </td>+ <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] max-w-xs truncate">+ {truncatePath(h.file_path, 60)}+ </td>+ <td className="px-4 py-2.5 tabular-nums text-[var(--color-text-secondary)] text-xs">+ {h.commit_count_90d}+ </td>+ <td className="px-4 py-2.5">+ <div className="flex items-center gap-2">+ <ChurnBar percentile={h.churn_percentile} className="w-20" />+ <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8">+ {Math.round(h.churn_percentile)}%+ </span>+ </div>+ </td>+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)]">+ {h.primary_owner ?? "—"}+ </td>+ <td className="px-4 py-2.5">+ {h.is_hotspot && <Badge variant="outdated">Hot</Badge>}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}diff --git a/packages/web/src/components/git/ownership-table.tsx b/packages/web/src/components/git/ownership-table.tsxnew file mode 100644index 000000000..88986b35f--- /dev/null+++ b/packages/web/src/components/git/ownership-table.tsx@@ -0,0 +1,91 @@+import { Badge } from "@/components/ui/badge";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { EmptyState } from "@/components/shared/empty-state";+import { truncatePath } from "@/lib/utils/format";+import type { OwnershipEntry } from "@/lib/api/types";++interface OwnershipTableProps {+ entries: OwnershipEntry[];+}++export function OwnershipTable({ entries }: OwnershipTableProps) {+ if (entries.length === 0) {+ return (+ <EmptyState+ title="No ownership data"+ description="Run a sync to populate ownership information."+ />+ );+ }++ return (+ <div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto">+ <table className="w-full min-w-[520px] text-sm">+ <thead>+ <tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ Module / File+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ Owner+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-36">+ Ownership+ </th>+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-16">+ Files+ </th>+ <th className="px-4 py-2.5 w-20" />+ </tr>+ </thead>+ <tbody>+ {entries.map((entry) => (+ <tr+ key={entry.module_path}+ className="border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0"+ >+ <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] max-w-xs truncate">+ {truncatePath(entry.module_path, 60)}+ </td>+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)]">+ {entry.primary_owner ?? "—"}+ </td>+ <td className="px-4 py-2.5">+ {entry.owner_pct !== null ? (+ <div className="flex items-center gap-2">+ <div className="h-1.5 flex-1 rounded-full bg-[var(--color-bg-elevated)]">+ <div+ className="h-1.5 rounded-full bg-[var(--color-accent-primary)]"+ style={{ width: `${Math.min(100, entry.owner_pct * 100)}%` }}+ />+ </div>+ <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8">+ {Math.round(entry.owner_pct * 100)}%+ </span>+ </div>+ ) : (+ <span className="text-[var(--color-text-tertiary)]">—</span>+ )}+ </td>+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-tertiary)] tabular-nums">+ {entry.file_count}+ </td>+ <td className="px-4 py-2.5">+ {entry.is_silo && (+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <Badge variant="stale">Silo</Badge>+ </span>+ </TooltipTrigger>+ <TooltipContent>Bus factor risk</TooltipContent>+ </Tooltip>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}diff --git a/packages/web/src/components/graph/graph-canvas.tsx b/packages/web/src/components/graph/graph-canvas.tsxnew file mode 100644index 000000000..1ab7cff3e--- /dev/null+++ b/packages/web/src/components/graph/graph-canvas.tsx@@ -0,0 +1,803 @@+"use client";++import { useEffect, useRef, useState, useCallback, useMemo } from "react";+import { useRouter } from "next/navigation";+import * as d3 from "d3";+import type { SimulationNodeDatum, SimulationLinkDatum } from "d3-force";+import { SlidersHorizontal, Download, Route, AlertTriangle } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";+import { EmptyState } from "@/components/shared/empty-state";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { GraphTooltip } from "./graph-tooltip";+import { GraphFilterPanel, type GraphFilters } from "./graph-filter-panel";+import { GraphMinimap } from "./graph-minimap";+import { PathFinder } from "./path-finder";+import {+ useGraph,+ useModuleGraph,+ useEgoGraph,+ useArchitectureGraph,+ useDeadCodeGraph,+ useHotFilesGraph,+} from "@/lib/hooks/use-graph";+import { languageColor } from "@/lib/utils/confidence";+import type { GraphNodeResponse } from "@/lib/api/types";++export type ViewMode = "module" | "ego" | "architecture" | "dead" | "hotfiles" | "full";++// Community colors palette (24 distinct colors)+const COMMUNITY_COLORS = [+ "#6366f1","#ec4899","#10b981","#f59e0b","#3b82f6","#a855f7",+ "#14b8a6","#f97316","#84cc16","#06b6d4","#e11d48","#8b5cf6",+ "#22c55e","#eab308","#0ea5e9","#d946ef","#ef4444","#78716c",+ "#64748b","#0891b2","#059669","#b45309","#7c3aed","#db2777",+];++// Normalized node — superset of all view-specific node types+interface NormalizedNode {+ node_id: string;+ node_type: string;+ language: string;+ symbol_count: number;+ pagerank: number;+ betweenness: number;+ community_id: number;+ is_test: boolean;+ is_entry_point: boolean;+ file_count?: number;+ doc_coverage_pct?: number;+ confidence_group?: string;+ commit_count?: number;+}++type SimNode = NormalizedNode & SimulationNodeDatum;+type SimLink = SimulationLinkDatum<SimNode> & {+ imported_names: string[];+ edge_count?: number;+};++interface HoverState {+ node: SimNode;+ x: number;+ y: number;+}++const MINIMAP_W = 160;+const MINIMAP_H = 120;++function nodeRadius(node: SimNode, viewMode: ViewMode, sizeBy: GraphFilters["sizeBy"]): number {+ if (viewMode === "module" && node.file_count !== undefined) {+ return 6 + Math.sqrt(node.file_count) * 2.5;+ }+ if (viewMode === "hotfiles" && node.commit_count !== undefined && node.commit_count > 0) {+ return 4 + Math.min(10, Math.sqrt(node.commit_count) * 1.5);+ }+ switch (sizeBy) {+ case "symbol_count":+ return 4 + Math.min(8, node.symbol_count / 10);+ case "pagerank":+ return 4 + Math.min(8, node.pagerank * 1000);+ case "betweenness":+ return 4 + Math.min(8, node.betweenness * 50);+ }+}++function nodeColor(node: SimNode, viewMode: ViewMode, colorBy: GraphFilters["colorBy"]): string {+ if (viewMode === "module" && node.doc_coverage_pct !== undefined) {+ return d3.interpolateRgb("#dc2626", "#22c55e")(node.doc_coverage_pct);+ }+ if (viewMode === "dead") {+ if (node.confidence_group === "certain") return "#dc2626";+ if (node.confidence_group === "likely") return "rgba(220,38,38,0.6)";+ return "#64748b"; // neighbor+ }+ if (node.node_id.startsWith("external:")) return "#78716c";+ switch (colorBy) {+ case "language":+ return languageColor(node.language);+ case "community":+ return COMMUNITY_COLORS[node.community_id % COMMUNITY_COLORS.length];+ case "entry_point":+ return node.is_entry_point ? "#f59e0b" : languageColor(node.language);+ }+}++export interface GraphCanvasProps {+ repoId: string;+ viewMode?: ViewMode;+ centerNodeId?: string | null;+ hops?: number;+ days?: number;+ onNodeClick?: (nodeId: string) => void;+ onViewChange?: (view: ViewMode) => void;+}++export function GraphCanvas({+ repoId,+ viewMode = "module",+ centerNodeId,+ hops = 2,+ days = 30,+ onNodeClick,+ onViewChange,+}: GraphCanvasProps) {+ const router = useRouter();++ // All hooks called unconditionally; null key = no fetch+ const { graph: fullGraph, isLoading: fullLoading, error: fullError } = useGraph(+ viewMode === "full" ? repoId : null,+ );+ const { graph: moduleGraph, isLoading: moduleLoading } = useModuleGraph(+ viewMode === "module" ? repoId : null,+ );+ const { graph: egoGraph, isLoading: egoLoading } = useEgoGraph(+ viewMode === "ego" ? repoId : null,+ viewMode === "ego" ? (centerNodeId ?? null) : null,+ hops,+ );+ const { graph: archGraph, isLoading: archLoading } = useArchitectureGraph(+ viewMode === "architecture" ? repoId : null,+ );+ const { graph: deadGraph, isLoading: deadLoading } = useDeadCodeGraph(+ viewMode === "dead" ? repoId : null,+ );+ const { graph: hotGraph, isLoading: hotLoading } = useHotFilesGraph(+ viewMode === "hotfiles" ? repoId : null,+ days,+ );++ const canvasRef = useRef<HTMLCanvasElement>(null);+ const minimapRef = useRef<HTMLCanvasElement>(null);+ const containerRef = useRef<HTMLDivElement>(null);+ const transformRef = useRef<d3.ZoomTransform>(d3.zoomIdentity);+ const simNodesRef = useRef<SimNode[]>([]);+ const simLinksRef = useRef<SimLink[]>([]);+ const animFrameRef = useRef<number | null>(null);+ const adjacencyRef = useRef<Map<string, Set<string>>>(new Map());+ const neighborhoodRef = useRef<Set<string> | null>(null);++ const [hoveredNode, setHoveredNode] = useState<HoverState | null>(null);+ const [canvasSize, setCanvasSize] = useState({ w: 800, h: 600 });+ const [showFilter, setShowFilter] = useState(false);+ const [showPathFinder, setShowPathFinder] = useState(false);+ const [highlightedPath, setHighlightedPath] = useState<Set<string>>(new Set());+ const [showFullGraphWarning, setShowFullGraphWarning] = useState(false);+ const [filters, setFilters] = useState<GraphFilters>({+ hiddenLangs: new Set(),+ hideTests: false,+ colorBy: "language",+ sizeBy: "symbol_count",+ nodeSearch: "",+ });++ // Normalize graph data to a common shape for all views+ const normalizedData = useMemo<{+ nodes: NormalizedNode[];+ links: { source: string; target: string; imported_names: string[]; edge_count?: number }[];+ } | null>(() => {+ switch (viewMode) {+ case "full":+ if (!fullGraph) return null;+ return { nodes: fullGraph.nodes, links: fullGraph.links };+ case "module":+ if (!moduleGraph) return null;+ return {+ nodes: moduleGraph.nodes.map((m) => ({+ node_id: m.module_id,+ node_type: "module",+ language: "",+ symbol_count: m.symbol_count,+ pagerank: m.avg_pagerank,+ betweenness: 0,+ community_id: 0,+ is_test: false,+ is_entry_point: false,+ file_count: m.file_count,+ doc_coverage_pct: m.doc_coverage_pct,+ })),+ links: moduleGraph.edges.map((e) => ({+ source: e.source,+ target: e.target,+ imported_names: [],+ edge_count: e.edge_count,+ })),+ };+ case "ego":+ if (!egoGraph) return null;+ return { nodes: egoGraph.nodes, links: egoGraph.links };+ case "architecture":+ if (!archGraph) return null;+ return { nodes: archGraph.nodes, links: archGraph.links };+ case "dead":+ if (!deadGraph) return null;+ return { nodes: deadGraph.nodes, links: deadGraph.links };+ case "hotfiles":+ if (!hotGraph) return null;+ return { nodes: hotGraph.nodes, links: hotGraph.links };+ default:+ return null;+ }+ }, [viewMode, fullGraph, moduleGraph, egoGraph, archGraph, deadGraph, hotGraph]);++ // Full graph warning gate+ useEffect(() => {+ if (viewMode === "full" && fullGraph && fullGraph.nodes.length > 2000) {+ const confirmed =+ typeof window !== "undefined" &&+ sessionStorage.getItem("full-graph-confirmed") === "1";+ if (!confirmed) setShowFullGraphWarning(true);+ }+ }, [viewMode, fullGraph]);++ // Resize observer+ useEffect(() => {+ const el = containerRef.current;+ if (!el) return;+ const ro = new ResizeObserver((entries) => {+ const { width, height } = entries[0]!.contentRect;+ setCanvasSize({ w: Math.floor(width), h: Math.floor(height) });+ });+ ro.observe(el);+ return () => ro.disconnect();+ }, []);++ // Update hover neighborhood for dimming+ useEffect(() => {+ if (!hoveredNode) {+ neighborhoodRef.current = null;+ return;+ }+ const visited = new Set<string>([hoveredNode.node.node_id]);+ let frontier = [hoveredNode.node.node_id];+ for (let hop = 0; hop < 2; hop++) {+ const next: string[] = [];+ for (const id of frontier) {+ for (const nbr of adjacencyRef.current.get(id) ?? []) {+ if (!visited.has(nbr)) {+ visited.add(nbr);+ next.push(nbr);+ }+ }+ }+ frontier = next;+ }+ neighborhoodRef.current = visited;+ }, [hoveredNode]);++ const drawFrame = useCallback(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const ctx = canvas.getContext("2d");+ if (!ctx) return;++ const { w, h } = canvasSize;+ const t = transformRef.current;+ const search = filters.nodeSearch.toLowerCase();+ const neighborhood = neighborhoodRef.current;+ const hasPathFilter = highlightedPath.size > 0;++ ctx.clearRect(0, 0, w, h);+ ctx.save();+ ctx.translate(t.x, t.y);+ ctx.scale(t.k, t.k);++ // Draw edges+ for (const link of simLinksRef.current) {+ const src = link.source as SimNode;+ const tgt = link.target as SimNode;+ if (src.x == null || src.y == null || tgt.x == null || tgt.y == null) continue;+ if (filters.hiddenLangs.has(src.language) || filters.hiddenLangs.has(tgt.language)) continue;++ const inNeighborhood =+ !neighborhood ||+ (neighborhood.has(src.node_id) && neighborhood.has(tgt.node_id));+ const isOnPath =+ hasPathFilter &&+ (highlightedPath.has(src.node_id) || highlightedPath.has(tgt.node_id));+ const isDynamic = link.imported_names.length === 0 && viewMode !== "module";++ ctx.beginPath();+ ctx.moveTo(src.x, src.y);+ ctx.lineTo(tgt.x, tgt.y);+ ctx.strokeStyle = isDynamic ? "rgba(150,150,150,1)" : "rgba(91,156,246,1)";+ ctx.globalAlpha = !inNeighborhood+ ? 0.05+ : hasPathFilter && !isOnPath+ ? 0.05+ : isDynamic+ ? 0.25+ : 0.4;+ ctx.lineWidth =+ viewMode === "module"+ ? (1 + Math.min(3, Math.sqrt(link.edge_count ?? 1) * 0.5)) / t.k+ : (1 + Math.min(3, link.imported_names.length * 0.4)) / t.k;+ if (isDynamic) {+ ctx.setLineDash([4 / t.k, 4 / t.k]);+ } else {+ ctx.setLineDash([]);+ }+ ctx.stroke();+ ctx.setLineDash([]);+ }++ // Draw nodes+ for (const node of simNodesRef.current) {+ if (node.x == null || node.y == null) continue;+ if (filters.hiddenLangs.has(node.language)) continue;+ if (filters.hideTests && node.is_test) continue;++ const r = nodeRadius(node, viewMode, filters.sizeBy);+ const color = nodeColor(node, viewMode, filters.colorBy);+ const isMatch = search ? node.node_id.toLowerCase().includes(search) : false;+ const isOnPath = hasPathFilter && highlightedPath.has(node.node_id);+ const inNbr = !neighborhood || neighborhood.has(node.node_id);+ const dimmed = (hasPathFilter && !isOnPath) || (neighborhood !== null && !inNbr);++ ctx.globalAlpha = dimmed ? 0.15 : 1.0;++ ctx.beginPath();+ ctx.arc(node.x, node.y, r, 0, Math.PI * 2);+ ctx.fillStyle = isOnPath ? "#f97316" : color;+ ctx.fill();++ // Entry point / architecture ring+ if (node.is_entry_point && !isOnPath) {+ ctx.strokeStyle = "#ffffff";+ ctx.lineWidth = (viewMode === "architecture" ? 2.5 : 2) / t.k;+ ctx.stroke();+ }+ if (viewMode === "architecture" && node.is_entry_point && !isOnPath) {+ ctx.beginPath();+ ctx.arc(node.x, node.y, r + 4 / t.k, 0, Math.PI * 2);+ ctx.strokeStyle = "#ffffff";+ ctx.lineWidth = 1.5 / t.k;+ ctx.stroke();+ }++ // Path highlight ring+ if (isOnPath) {+ ctx.globalAlpha = 1;+ ctx.beginPath();+ ctx.arc(node.x, node.y, r + 4 / t.k, 0, Math.PI * 2);+ ctx.strokeStyle = "#f97316";+ ctx.lineWidth = 2.5 / t.k;+ ctx.stroke();+ }++ // Search highlight+ if (isMatch && !isOnPath) {+ ctx.globalAlpha = 1;+ ctx.beginPath();+ ctx.arc(node.x, node.y, r + 3 / t.k, 0, Math.PI * 2);+ ctx.strokeStyle = "#eab308";+ ctx.lineWidth = 2 / t.k;+ ctx.stroke();+ }++ // Module label for large nodes+ if (viewMode === "module" && r > 14) {+ ctx.globalAlpha = dimmed ? 0.15 : 0.9;+ ctx.fillStyle = "#ffffff";+ ctx.font = `bold ${Math.min(12, r * 0.7) / t.k}px sans-serif`;+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";+ const label = node.node_id.length > 10 ? node.node_id.slice(0, 9) + "…" : node.node_id;+ ctx.fillText(label, node.x, node.y);+ }+ }++ ctx.globalAlpha = 1;+ ctx.restore();++ // Minimap+ const mc = minimapRef.current;+ if (mc && simNodesRef.current.length > 0) {+ const mctx = mc.getContext("2d");+ if (mctx) {+ mctx.clearRect(0, 0, MINIMAP_W, MINIMAP_H);+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;+ for (const n of simNodesRef.current) {+ if (n.x == null || n.y == null) continue;+ if (n.x < minX) minX = n.x;+ if (n.x > maxX) maxX = n.x;+ if (n.y < minY) minY = n.y;+ if (n.y > maxY) maxY = n.y;+ }+ if (!isFinite(minX)) return;+ const pad = 20;+ minX -= pad; maxX += pad; minY -= pad; maxY += pad;+ const worldW = maxX - minX;+ const worldH = maxY - minY;+ const scale = Math.min(MINIMAP_W / worldW, MINIMAP_H / worldH);+ const offX = (MINIMAP_W - worldW * scale) / 2 - minX * scale;+ const offY = (MINIMAP_H - worldH * scale) / 2 - minY * scale;+ for (const node of simNodesRef.current) {+ if (node.x == null || node.y == null) continue;+ mctx.beginPath();+ mctx.arc(node.x * scale + offX, node.y * scale + offY, 1.5, 0, Math.PI * 2);+ mctx.fillStyle = nodeColor(node, viewMode, filters.colorBy);+ mctx.globalAlpha = 0.7;+ mctx.fill();+ }+ mctx.globalAlpha = 1;+ const { w: cw, h: ch } = canvasSize;+ const vtx = (-t.x / t.k) * scale + offX;+ const vty = (-t.y / t.k) * scale + offY;+ const vtw = (cw / t.k) * scale;+ const vth = (ch / t.k) * scale;+ mctx.strokeStyle = "rgba(255,255,255,0.6)";+ mctx.lineWidth = 1;+ mctx.strokeRect(vtx, vty, vtw, vth);+ }+ }+ }, [canvasSize, filters, highlightedPath, viewMode]);++ // D3 simulation+ useEffect(() => {+ if (!normalizedData || !canvasRef.current) return;+ const canvas = canvasRef.current;+ const { w, h } = canvasSize;++ simNodesRef.current = normalizedData.nodes.map((n) => ({ ...n }));+ simLinksRef.current = normalizedData.links.map((l) => ({+ ...l,+ source: l.source as string,+ target: l.target as string,+ })) as SimLink[];++ // Build undirected adjacency for hover dimming+ const adj = new Map<string, Set<string>>();+ for (const link of normalizedData.links) {+ const s = link.source;+ const tgt = link.target;+ if (!adj.has(s)) adj.set(s, new Set());+ if (!adj.has(tgt)) adj.set(tgt, new Set());+ adj.get(s)!.add(tgt);+ adj.get(tgt)!.add(s);+ }+ adjacencyRef.current = adj;++ // Clustering gravity (pull same-directory nodes together)+ function clusterForce(alpha: number) {+ const centroids = new Map<string, { x: number; y: number; count: number }>();+ for (const n of simNodesRef.current) {+ if (n.x == null || n.y == null) continue;+ const dir = n.node_id.split("/")[0] ?? n.node_id;+ const c = centroids.get(dir) ?? { x: 0, y: 0, count: 0 };+ c.x += n.x;+ c.y += n.y;+ c.count++;+ centroids.set(dir, c);+ }+ for (const n of simNodesRef.current) {+ if (n.x == null || n.y == null) continue;+ const dir = n.node_id.split("/")[0] ?? n.node_id;+ const c = centroids.get(dir);+ if (!c || c.count === 0) continue;+ n.vx! += (c.x / c.count - n.x) * alpha * 0.04;+ n.vy! += (c.y / c.count - n.y) * alpha * 0.04;+ }+ }++ const isFileLevelView = viewMode === "full" || viewMode === "ego";+ const isModuleView = viewMode === "module";++ const simulation = d3+ .forceSimulation<SimNode>(simNodesRef.current)+ .force(+ "link",+ d3+ .forceLink<SimNode, SimLink>(simLinksRef.current)+ .id((d) => d.node_id)+ .distance(isModuleView ? 120 : 60),+ )+ .force("charge", d3.forceManyBody<SimNode>().strength(isModuleView ? -500 : -150))+ .force("center", d3.forceCenter(w / 2, h / 2))+ .force("collide", d3.forceCollide<SimNode>(isModuleView ? 35 : 12))+ .alphaDecay(0.02)+ .on("tick", () => {+ if (animFrameRef.current) cancelAnimationFrame(animFrameRef.current);+ animFrameRef.current = requestAnimationFrame(drawFrame);+ });++ if (isFileLevelView) {+ simulation.force("cluster", clusterForce);+ }++ const zoom = d3+ .zoom<HTMLCanvasElement, unknown>()+ .scaleExtent([0.05, 20])+ .on("zoom", (event) => {+ transformRef.current = event.transform;+ if (animFrameRef.current) cancelAnimationFrame(animFrameRef.current);+ animFrameRef.current = requestAnimationFrame(drawFrame);+ });++ d3.select(canvas).call(zoom);++ return () => {+ simulation.stop();+ d3.select(canvas).on(".zoom", null);+ if (animFrameRef.current) cancelAnimationFrame(animFrameRef.current);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [normalizedData, canvasSize]);++ // Redraw when filters/path/hover change+ useEffect(() => { drawFrame(); }, [filters, highlightedPath, drawFrame]);+ useEffect(() => { drawFrame(); }, [hoveredNode, drawFrame]);++ const handleExportPng = useCallback(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const link = document.createElement("a");+ link.download = "dependency-graph.png";+ link.href = canvas.toDataURL("image/png");+ link.click();+ }, []);++ const handleMouseMove = useCallback(+ (e: React.MouseEvent<HTMLCanvasElement>) => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const rect = canvas.getBoundingClientRect();+ // Scale from CSS pixels to canvas pixels (accounts for any CSS/intrinsic size mismatch)+ const scaleX = canvas.width / rect.width;+ const scaleY = canvas.height / rect.height;+ const mxCSS = e.clientX - rect.left;+ const myCSS = e.clientY - rect.top;+ const mx = mxCSS * scaleX;+ const my = myCSS * scaleY;+ const t = transformRef.current;+ const wx = (mx - t.x) / t.k;+ const wy = (my - t.y) / t.k;++ let closest: SimNode | null = null;+ let minDist = Infinity;++ for (const node of simNodesRef.current) {+ if (node.x == null || node.y == null) continue;+ if (filters.hiddenLangs.has(node.language)) continue;+ if (filters.hideTests && node.is_test) continue;+ const r = nodeRadius(node, viewMode, filters.sizeBy);+ const dx = node.x - wx;+ const dy = node.y - wy;+ const dist = Math.sqrt(dx * dx + dy * dy);+ // Hit threshold: node radius + 4 CSS pixels of margin (4/t.k converts to world space)+ if (dist < r + 4 / t.k && dist < minDist) {+ closest = node;+ minDist = dist;+ }+ }++ // Store CSS pixel coords for tooltip positioning+ setHoveredNode(closest ? { node: closest, x: mxCSS, y: myCSS } : null);+ },+ [filters, viewMode],+ );++ const handleClick = useCallback(+ (e: React.MouseEvent<HTMLCanvasElement>) => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const rect = canvas.getBoundingClientRect();+ const scaleX = canvas.width / rect.width;+ const scaleY = canvas.height / rect.height;+ const mx = (e.clientX - rect.left) * scaleX;+ const my = (e.clientY - rect.top) * scaleY;+ const t = transformRef.current;+ const wx = (mx - t.x) / t.k;+ const wy = (my - t.y) / t.k;++ // Find the closest node within threshold (same logic as hover)+ let closest: SimNode | null = null;+ let minDist = Infinity;+ for (const node of simNodesRef.current) {+ if (node.x == null || node.y == null) continue;+ const r = nodeRadius(node, viewMode, filters.sizeBy);+ const dx = node.x - wx;+ const dy = node.y - wy;+ const dist = Math.sqrt(dx * dx + dy * dy);+ if (dist < r + 4 / t.k && dist < minDist) {+ closest = node;+ minDist = dist;+ }+ }++ if (closest) {+ if (viewMode === "module") {+ onNodeClick?.(closest.node_id);+ } else {+ router.push(`/repos/${repoId}/wiki/${encodeURIComponent(closest.node_id)}`);+ }+ }+ },+ [filters, router, repoId, viewMode, onNodeClick],+ );++ const isLoading =+ viewMode === "full" ? fullLoading :+ viewMode === "module" ? moduleLoading :+ viewMode === "ego" ? egoLoading :+ viewMode === "architecture" ? archLoading :+ viewMode === "dead" ? deadLoading :+ viewMode === "hotfiles" ? hotLoading : false;++ const error = viewMode === "full" ? fullError : null;++ const availableLangs = Array.from(+ new Set((normalizedData?.nodes ?? []).map((n) => n.language).filter(Boolean)),+ ).sort();++ const nodeCount = normalizedData?.nodes.length ?? 0;+ const linkCount = normalizedData?.links.length ?? 0;++ if (isLoading) {+ return <Skeleton className="h-full w-full rounded-lg" />;+ }++ if ((!normalizedData || error) && !showFullGraphWarning) {+ return (+ <EmptyState+ title={viewMode === "ego" && !centerNodeId ? "Select a node" : "No data"}+ description={+ viewMode === "ego" && !centerNodeId+ ? "Search for a file above or click a module node to explore its neighborhood."+ : "Check that the backend is running and this repo has been indexed."+ }+ />+ );+ }++ return (+ <div ref={containerRef} className="relative w-full h-full">+ <canvas+ ref={canvasRef}+ width={canvasSize.w}+ height={canvasSize.h}+ onMouseMove={handleMouseMove}+ onMouseLeave={() => setHoveredNode(null)}+ onClick={handleClick}+ className="w-full h-full cursor-crosshair"+ />++ {hoveredNode && (+ <GraphTooltip+ node={hoveredNode.node as GraphNodeResponse}+ x={hoveredNode.x}+ y={hoveredNode.y}+ canvasWidth={canvasSize.w}+ canvasHeight={canvasSize.h}+ />+ )}++ {/* Toolbar */}+ <div className="absolute top-3 right-3 flex flex-wrap gap-2 justify-end">+ {viewMode === "full" && (+ <Button+ size="sm"+ variant="secondary"+ onClick={() => { setShowPathFinder((s) => !s); setShowFilter(false); }}+ className="h-8 gap-1.5"+ >+ <Route className="h-3.5 w-3.5" />+ <span className="hidden sm:inline">Path</span>+ </Button>+ )}+ <Button+ size="sm"+ variant="secondary"+ onClick={() => { setShowFilter((s) => !s); setShowPathFinder(false); }}+ className="h-8 gap-1.5"+ >+ <SlidersHorizontal className="h-3.5 w-3.5" />+ <span className="hidden sm:inline">Filter</span>+ </Button>+ <Button size="sm" variant="secondary" onClick={handleExportPng} className="h-8 gap-1.5">+ <Download className="h-3.5 w-3.5" />+ <span className="hidden sm:inline">Export</span>+ </Button>+ </div>++ {showPathFinder && viewMode === "full" && (+ <div className="absolute top-12 right-3">+ <PathFinder+ repoId={repoId}+ onPathFound={(nodes) => setHighlightedPath(new Set(nodes))}+ onClear={() => setHighlightedPath(new Set())}+ />+ </div>+ )}++ {showFilter && (+ <div className="absolute top-12 right-3">+ <GraphFilterPanel+ filters={filters}+ onChange={setFilters}+ availableLangs={availableLangs}+ />+ </div>+ )}++ <div className="absolute bottom-3 right-3">+ <GraphMinimap ref={minimapRef} />+ </div>++ {/* Legend */}+ <div className="absolute bottom-3 left-3 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/80 backdrop-blur-sm p-2 text-xs text-[var(--color-text-tertiary)] space-y-1">+ <div className="font-medium text-[var(--color-text-secondary)] mb-1">+ {nodeCount} nodes · {linkCount} edges+ </div>+ {viewMode === "module" ? (+ <>+ <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-green-500" />High doc coverage</div>+ <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-red-500" />Low doc coverage</div>+ </>+ ) : viewMode === "dead" ? (+ <>+ <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-red-600" />Certain dead</div>+ <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-red-400" />Likely dead</div>+ </>+ ) : (+ <>+ <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-white border border-gray-400" />Entry point</div>+ <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full border-2 border-yellow-400 bg-transparent" />Search match</div>+ </>+ )}+ </div>++ {/* Full graph warning dialog */}+ <Dialog+ open={showFullGraphWarning}+ onOpenChange={(open) => {+ if (!open) {+ setShowFullGraphWarning(false);+ onViewChange?.("module");+ }+ }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <AlertTriangle className="h-5 w-5 text-amber-400" />+ Large Graph Warning+ </DialogTitle>+ <DialogDescription>+ Rendering {nodeCount} nodes may be slow. This view works best for small repos.+ Continue anyway?+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ variant="secondary"+ onClick={() => {+ setShowFullGraphWarning(false);+ onViewChange?.("module");+ }}+ >+ Cancel+ </Button>+ <Button+ onClick={() => {+ if (typeof window !== "undefined") {+ sessionStorage.setItem("full-graph-confirmed", "1");+ }+ setShowFullGraphWarning(false);+ }}+ >+ Continue+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/packages/web/src/components/graph/graph-ego-sidebar.tsx b/packages/web/src/components/graph/graph-ego-sidebar.tsxnew file mode 100644index 000000000..af7315b31--- /dev/null+++ b/packages/web/src/components/graph/graph-ego-sidebar.tsx@@ -0,0 +1,134 @@+"use client";++import { X, GitCommit, User, Clock, ArrowDownToLine, ArrowUpFromLine, FileText } from "lucide-react";+import { Button } from "@/components/ui/button";+import { formatRelativeTime } from "@/lib/utils/format";+import type { EgoGraphResponse } from "@/lib/api/types";++interface GraphEgoSidebarProps {+ graph: EgoGraphResponse;+ onClose: () => void;+ onNavigateToNode?: (nodeId: string) => void;+}++export function GraphEgoSidebar({ graph, onClose, onNavigateToNode }: GraphEgoSidebarProps) {+ const meta = graph.center_git_meta;+ const centerNode = graph.nodes.find((n) => n.node_id === graph.center_node_id);++ return (+ <div className="absolute top-3 right-3 z-20 w-72 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/95 backdrop-blur-sm shadow-xl text-xs">+ {/* Header */}+ <div className="flex items-start justify-between p-3 border-b border-[var(--color-border-default)]">+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-1.5 mb-0.5">+ <FileText className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] shrink-0" />+ <p className="font-mono text-[var(--color-text-primary)] font-medium truncate">+ {graph.center_node_id.split("/").pop()}+ </p>+ </div>+ <p className="font-mono text-[var(--color-text-tertiary)] truncate pl-5">+ {graph.center_node_id}+ </p>+ </div>+ <Button size="sm" variant="ghost" onClick={onClose} className="h-6 w-6 p-0 shrink-0 ml-2">+ <X className="h-3.5 w-3.5" />+ </Button>+ </div>++ {/* Stats */}+ <div className="p-3 space-y-2">+ <div className="grid grid-cols-2 gap-2">+ <div className="rounded-md bg-[var(--color-bg-elevated)] p-2">+ <div className="flex items-center gap-1.5 text-[var(--color-text-tertiary)] mb-1">+ <ArrowDownToLine className="h-3 w-3" />+ <span>Inbound</span>+ </div>+ <p className="text-lg font-bold text-[var(--color-text-primary)] tabular-nums">+ {graph.inbound_count}+ </p>+ </div>+ <div className="rounded-md bg-[var(--color-bg-elevated)] p-2">+ <div className="flex items-center gap-1.5 text-[var(--color-text-tertiary)] mb-1">+ <ArrowUpFromLine className="h-3 w-3" />+ <span>Outbound</span>+ </div>+ <p className="text-lg font-bold text-[var(--color-text-primary)] tabular-nums">+ {graph.outbound_count}+ </p>+ </div>+ </div>++ {centerNode && (+ <div className="flex justify-between text-[var(--color-text-secondary)] pt-1">+ <span>Symbols</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">+ {centerNode.symbol_count}+ </span>+ </div>+ )}++ {/* Git metadata */}+ {meta && (+ <>+ <div className="border-t border-[var(--color-border-default)] pt-2 space-y-1.5">+ {meta.primary_owner_name && (+ <div className="flex items-center justify-between text-[var(--color-text-secondary)]">+ <div className="flex items-center gap-1.5">+ <User className="h-3 w-3" />+ <span>Owner</span>+ </div>+ <span className="font-medium text-[var(--color-text-primary)] truncate max-w-[120px]">+ {meta.primary_owner_name}+ </span>+ </div>+ )}+ {meta.last_commit_at != null && (+ <div className="flex items-center justify-between text-[var(--color-text-secondary)]">+ <div className="flex items-center gap-1.5">+ <Clock className="h-3 w-3" />+ <span>Last commit</span>+ </div>+ <span className="font-medium text-[var(--color-text-primary)]">+ {formatRelativeTime(meta.last_commit_at)}+ </span>+ </div>+ )}+ <div className="flex items-center justify-between text-[var(--color-text-secondary)]">+ <div className="flex items-center gap-1.5">+ <GitCommit className="h-3 w-3" />+ <span>Commits (30d)</span>+ </div>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">+ {meta.commit_count_30d}+ </span>+ </div>+ </div>+ </>+ )}++ {/* Neighborhood nodes */}+ {graph.nodes.length > 1 && (+ <div className="border-t border-[var(--color-border-default)] pt-2">+ <p className="text-[var(--color-text-tertiary)] mb-1.5">+ {graph.nodes.length - 1} neighbors in {graph.links.length} edges+ </p>+ <div className="space-y-0.5 max-h-32 overflow-y-auto">+ {graph.nodes+ .filter((n) => n.node_id !== graph.center_node_id)+ .slice(0, 8)+ .map((n) => (+ <button+ key={n.node_id}+ onClick={() => onNavigateToNode?.(n.node_id)}+ className="w-full text-left px-1.5 py-1 rounded hover:bg-[var(--color-bg-elevated)] font-mono text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] truncate transition-colors"+ >+ {n.node_id}+ </button>+ ))}+ </div>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/graph/graph-filter-panel.tsx b/packages/web/src/components/graph/graph-filter-panel.tsxnew file mode 100644index 000000000..d7b5244a6--- /dev/null+++ b/packages/web/src/components/graph/graph-filter-panel.tsx@@ -0,0 +1,132 @@+"use client";++import { Input } from "@/components/ui/input";+import { cn } from "@/lib/utils/cn";+import { LANGUAGE_COLORS } from "@/lib/utils/confidence";++export type ColorBy = "language" | "community" | "entry_point";+export type SizeBy = "symbol_count" | "pagerank" | "betweenness";++export interface GraphFilters {+ hiddenLangs: Set<string>;+ hideTests: boolean;+ colorBy: ColorBy;+ sizeBy: SizeBy;+ nodeSearch: string;+}++interface GraphFilterPanelProps {+ filters: GraphFilters;+ onChange: (filters: GraphFilters) => void;+ availableLangs: string[];+}++export function GraphFilterPanel({ filters, onChange, availableLangs }: GraphFilterPanelProps) {+ const update = (patch: Partial<GraphFilters>) => onChange({ ...filters, ...patch });++ const toggleLang = (lang: string) => {+ const next = new Set(filters.hiddenLangs);+ if (next.has(lang)) next.delete(lang);+ else next.add(lang);+ update({ hiddenLangs: next });+ };++ return (+ <div className="w-52 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] p-3 shadow-lg space-y-4 text-xs">+ <div>+ <p className="font-semibold text-[var(--color-text-primary)] mb-2 uppercase tracking-wider text-[10px]">+ Node Search+ </p>+ <Input+ value={filters.nodeSearch}+ onChange={(e) => update({ nodeSearch: e.target.value })}+ placeholder="Highlight nodes…"+ className="h-7 text-xs"+ />+ </div>++ <div>+ <p className="font-semibold text-[var(--color-text-primary)] mb-2 uppercase tracking-wider text-[10px]">+ Languages+ </p>+ <div className="space-y-1">+ {availableLangs.map((lang) => {+ const hidden = filters.hiddenLangs.has(lang);+ return (+ <label key={lang} className="flex items-center gap-2 cursor-pointer select-none">+ <input+ type="checkbox"+ checked={!hidden}+ onChange={() => toggleLang(lang)}+ className="rounded border-[var(--color-border-default)]"+ />+ <span+ className="h-2 w-2 rounded-full shrink-0"+ style={{+ background:+ LANGUAGE_COLORS[lang.toLowerCase()] ?? LANGUAGE_COLORS.other,+ }}+ />+ <span className="text-[var(--color-text-secondary)] capitalize">{lang}</span>+ </label>+ );+ })}+ </div>+ </div>++ <label className="flex items-center gap-2 cursor-pointer select-none">+ <input+ type="checkbox"+ checked={filters.hideTests}+ onChange={(e) => update({ hideTests: e.target.checked })}+ className="rounded border-[var(--color-border-default)]"+ />+ <span className="text-[var(--color-text-secondary)]">Hide test files</span>+ </label>++ <div>+ <p className="font-semibold text-[var(--color-text-primary)] mb-2 uppercase tracking-wider text-[10px]">+ Color By+ </p>+ <div className="space-y-1">+ {(["language", "community", "entry_point"] as ColorBy[]).map((v) => (+ <label key={v} className="flex items-center gap-2 cursor-pointer select-none">+ <input+ type="radio"+ checked={filters.colorBy === v}+ onChange={() => update({ colorBy: v })}+ name="colorBy"+ className="border-[var(--color-border-default)]"+ />+ <span className="text-[var(--color-text-secondary)] capitalize">+ {v.replace(/_/g, " ")}+ </span>+ </label>+ ))}+ </div>+ </div>++ <div>+ <p className="font-semibold text-[var(--color-text-primary)] mb-2 uppercase tracking-wider text-[10px]">+ Size By+ </p>+ <div className="space-y-1">+ {(["symbol_count", "pagerank", "betweenness"] as SizeBy[]).map((v) => (+ <label key={v} className="flex items-center gap-2 cursor-pointer select-none">+ <input+ type="radio"+ checked={filters.sizeBy === v}+ onChange={() => update({ sizeBy: v })}+ name="sizeBy"+ className="border-[var(--color-border-default)]"+ />+ <span className="text-[var(--color-text-secondary)] capitalize">+ {v.replace(/_/g, " ")}+ </span>+ </label>+ ))}+ </div>+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/graph/graph-minimap.tsx b/packages/web/src/components/graph/graph-minimap.tsxnew file mode 100644index 000000000..8357fe0e6--- /dev/null+++ b/packages/web/src/components/graph/graph-minimap.tsx@@ -0,0 +1,25 @@+"use client";++import { forwardRef } from "react";+import { cn } from "@/lib/utils/cn";++interface GraphMinimapProps {+ className?: string;+}++export const GraphMinimap = forwardRef<HTMLCanvasElement, GraphMinimapProps>(+ ({ className }, ref) => {+ return (+ <canvas+ ref={ref}+ width={160}+ height={120}+ className={cn(+ "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]",+ className,+ )}+ />+ );+ },+);+GraphMinimap.displayName = "GraphMinimap";diff --git a/packages/web/src/components/graph/graph-tooltip.tsx b/packages/web/src/components/graph/graph-tooltip.tsxnew file mode 100644index 000000000..0778fe7d0--- /dev/null+++ b/packages/web/src/components/graph/graph-tooltip.tsx@@ -0,0 +1,57 @@+import { formatNumber } from "@/lib/utils/format";+import type { GraphNodeResponse } from "@/lib/api/types";++interface GraphTooltipProps {+ node: GraphNodeResponse;+ x: number;+ y: number;+ canvasWidth: number;+ canvasHeight: number;+}++export function GraphTooltip({ node, x, y, canvasWidth, canvasHeight }: GraphTooltipProps) {+ const tooltipW = 200;+ const tooltipH = 130;+ const left = x + 16 + tooltipW > canvasWidth ? x - tooltipW - 8 : x + 16;+ const top = y + tooltipH > canvasHeight ? y - tooltipH : y;++ return (+ <div+ className="absolute pointer-events-none z-10 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] p-3 shadow-lg text-xs"+ style={{ left, top, width: tooltipW }}+ >+ <p className="font-mono font-semibold text-[var(--color-text-primary)] mb-2 truncate">+ {node.node_id}+ </p>+ <div className="space-y-1 text-[var(--color-text-secondary)]">+ <div className="flex justify-between">+ <span>Language</span>+ <span className="font-medium text-[var(--color-text-primary)]">{node.language}</span>+ </div>+ <div className="flex justify-between">+ <span>Symbols</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">+ {formatNumber(node.symbol_count)}+ </span>+ </div>+ <div className="flex justify-between">+ <span>PageRank</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">+ {node.pagerank.toFixed(4)}+ </span>+ </div>+ <div className="flex justify-between">+ <span>Community</span>+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">+ {node.community_id}+ </span>+ </div>+ {node.is_entry_point && (+ <span className="inline-block mt-1 rounded border border-[var(--color-accent-primary)] bg-[var(--color-accent-muted)] px-1.5 py-0.5 text-xs text-[var(--color-accent-primary)]">+ Entry Point+ </span>+ )}+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/graph/graph-view-switcher.tsx b/packages/web/src/components/graph/graph-view-switcher.tsxnew file mode 100644index 000000000..52a5d5f8b--- /dev/null+++ b/packages/web/src/components/graph/graph-view-switcher.tsx@@ -0,0 +1,172 @@+"use client";++import { useState, useCallback, useEffect } from "react";+import { Search, RotateCcw, AlertTriangle } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { useDebounce } from "@/lib/hooks/use-debounce";+import { searchNodes } from "@/lib/api/graph";+import type { NodeSearchResult } from "@/lib/api/types";++export type ViewMode = "module" | "ego" | "architecture" | "dead" | "hotfiles" | "full";++const VIEWS: { id: ViewMode; label: string; warn?: boolean }[] = [+ { id: "module", label: "Module" },+ { id: "ego", label: "Neighborhood" },+ { id: "architecture", label: "Architecture" },+ { id: "dead", label: "Dead Code" },+ { id: "hotfiles", label: "Hot Files" },+ { id: "full", label: "Full Graph", warn: true },+];++interface GraphViewSwitcherProps {+ repoId: string;+ view: ViewMode;+ hops: number;+ days: number;+ onViewChange: (view: ViewMode) => void;+ onNodeSelect: (nodeId: string) => void;+ onHopsChange: (hops: number) => void;+ onDaysChange: (days: number) => void;+}++export function GraphViewSwitcher({+ repoId,+ view,+ hops,+ days,+ onViewChange,+ onNodeSelect,+ onHopsChange,+ onDaysChange,+}: GraphViewSwitcherProps) {+ const [searchQuery, setSearchQuery] = useState("");+ const [searchResults, setSearchResults] = useState<NodeSearchResult[]>([]);+ const [showResults, setShowResults] = useState(false);++ const debouncedSearch = useDebounce(searchQuery, 300);++ useEffect(() => {+ if (!debouncedSearch.trim()) {+ setSearchResults([]);+ setShowResults(false);+ return;+ }+ searchNodes(repoId, debouncedSearch, 10)+ .then((results) => {+ setSearchResults(results);+ setShowResults(results.length > 0);+ })+ .catch(() => setSearchResults([]));+ }, [debouncedSearch, repoId]);++ const handleSelectNode = useCallback(+ (nodeId: string) => {+ onNodeSelect(nodeId);+ setSearchQuery("");+ setShowResults(false);+ },+ [onNodeSelect],+ );++ const showSearch = view === "ego" || view === "module";++ return (+ <div className="shrink-0 flex items-center gap-2 px-4 py-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] flex-wrap">+ {/* View tabs */}+ <div className="flex items-center gap-1">+ {VIEWS.map((v) => (+ <Button+ key={v.id}+ size="sm"+ variant={view === v.id ? "default" : "ghost"}+ onClick={() => onViewChange(v.id)}+ className="h-7 px-2.5 text-xs gap-1"+ >+ {v.warn && <AlertTriangle className="h-3 w-3 text-amber-400" />}+ {v.label}+ </Button>+ ))}+ </div>++ <div className="h-4 w-px bg-[var(--color-border-default)]" />++ {/* File search */}+ {showSearch && (+ <div className="relative">+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />+ <Input+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ onFocus={() => searchResults.length > 0 && setShowResults(true)}+ onBlur={() => setTimeout(() => setShowResults(false), 150)}+ placeholder="Search file…"+ className="h-7 pl-7 pr-3 w-48 text-xs"+ />+ {showResults && (+ <div className="absolute top-full left-0 mt-1 z-50 w-72 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-lg py-1">+ {searchResults.map((r) => (+ <button+ key={r.node_id}+ className="w-full px-3 py-1.5 text-left text-xs hover:bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"+ onMouseDown={() => handleSelectNode(r.node_id)}+ >+ <span className="font-mono">{r.node_id}</span>+ <span className="ml-2 text-[var(--color-text-tertiary)]">{r.language}</span>+ </button>+ ))}+ </div>+ )}+ </div>+ )}++ {/* Hop depth (ego view) */}+ {view === "ego" && (+ <Select value={String(hops)} onValueChange={(v) => onHopsChange(Number(v))}>+ <SelectTrigger className="h-7 w-20 text-xs">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="1">1 hop</SelectItem>+ <SelectItem value="2">2 hops</SelectItem>+ <SelectItem value="3">3 hops</SelectItem>+ </SelectContent>+ </Select>+ )}++ {/* Days selector (hot files) */}+ {view === "hotfiles" && (+ <Select value={String(days)} onValueChange={(v) => onDaysChange(Number(v))}>+ <SelectTrigger className="h-7 w-20 text-xs">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="7">7 days</SelectItem>+ <SelectItem value="30">30 days</SelectItem>+ <SelectItem value="90">90 days</SelectItem>+ </SelectContent>+ </Select>+ )}++ <div className="ml-auto">+ <Button+ size="sm"+ variant="ghost"+ onClick={() => onViewChange("module")}+ className="h-7 px-2 text-xs gap-1"+ title="Reset to module view"+ >+ <RotateCcw className="h-3.5 w-3.5" />+ Reset+ </Button>+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/graph/path-finder.tsx b/packages/web/src/components/graph/path-finder.tsxnew file mode 100644index 000000000..bf505e044--- /dev/null+++ b/packages/web/src/components/graph/path-finder.tsx@@ -0,0 +1,114 @@+"use client";++import { useState } from "react";+import { Route, Loader2, X } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { getGraphPath } from "@/lib/api/graph";+import type { GraphPathResponse } from "@/lib/api/types";++interface PathFinderProps {+ repoId: string;+ onPathFound: (path: string[]) => void;+ onClear: () => void;+}++export function PathFinder({ repoId, onPathFound, onClear }: PathFinderProps) {+ const [from, setFrom] = useState("");+ const [to, setTo] = useState("");+ const [loading, setLoading] = useState(false);+ const [result, setResult] = useState<GraphPathResponse | null>(null);+ const [error, setError] = useState<string | null>(null);++ async function handleFind() {+ if (!from.trim() || !to.trim()) return;+ setLoading(true);+ setError(null);+ setResult(null);+ onClear();+ try {+ const res = await getGraphPath(repoId, from.trim(), to.trim());+ setResult(res);+ onPathFound(res.path.map((step) => step.node));+ } catch {+ setError("No path found between these nodes.");+ } finally {+ setLoading(false);+ }+ }++ function handleClear() {+ setFrom("");+ setTo("");+ setResult(null);+ setError(null);+ onClear();+ }++ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/90 backdrop-blur-sm p-3 space-y-2 w-64">+ <div className="flex items-center gap-1.5">+ <Route className="h-3.5 w-3.5 text-[var(--color-accent-primary)] shrink-0" />+ <span className="text-xs font-medium text-[var(--color-text-primary)]">Path Finder</span>+ </div>++ <div className="space-y-1.5">+ <Input+ value={from}+ onChange={(e) => setFrom(e.target.value)}+ placeholder="From node (file path)"+ className="h-7 text-xs font-mono"+ onKeyDown={(e) => e.key === "Enter" && handleFind()}+ />+ <Input+ value={to}+ onChange={(e) => setTo(e.target.value)}+ placeholder="To node (file path)"+ className="h-7 text-xs font-mono"+ onKeyDown={(e) => e.key === "Enter" && handleFind()}+ />+ </div>++ <div className="flex gap-1.5">+ <Button+ size="sm"+ onClick={handleFind}+ disabled={!from.trim() || !to.trim() || loading}+ className="flex-1 h-7 text-xs gap-1"+ >+ {loading ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <Route className="h-3 w-3" />+ )}+ Find+ </Button>+ {(result || error) && (+ <Button size="sm" variant="ghost" onClick={handleClear} className="h-7 w-7 p-0" aria-label="Clear path">+ <X className="h-3 w-3" />+ </Button>+ )}+ </div>++ {result && (+ <div className="text-xs text-[var(--color-text-secondary)] space-y-1">+ <p className="font-medium text-[var(--color-confidence-fresh)]">+ Path found — {result.distance} hops+ </p>+ <div className="max-h-24 overflow-auto space-y-0.5">+ {result.path.map((step, i) => (+ <div key={i} className="font-mono truncate text-[var(--color-text-tertiary)]">+ {i > 0 && <span className="text-[var(--color-accent-primary)] mr-1">→</span>}+ {step.node}+ </div>+ ))}+ </div>+ </div>+ )}++ {error && (+ <p className="text-xs text-[var(--color-confidence-outdated)]">{error}</p>+ )}+ </div>+ );+}diff --git a/packages/web/src/components/jobs/generation-progress.tsx b/packages/web/src/components/jobs/generation-progress.tsxnew file mode 100644index 000000000..51d246fe8--- /dev/null+++ b/packages/web/src/components/jobs/generation-progress.tsx@@ -0,0 +1,146 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { CheckCircle, XCircle, Loader2, RefreshCw } from "lucide-react";+import { useJob } from "@/lib/hooks/use-job";+import { Progress } from "@/components/ui/progress";+import { Badge } from "@/components/ui/badge";+import { JobLog } from "./job-log";+import { formatTokens, formatNumber } from "@/lib/utils/format";+import type { JobProgressEvent } from "@/lib/api/types";++interface Props {+ jobId: string;+ repoName?: string;+ /** Called when the job reaches a terminal state */+ onDone?: () => void;+}++export function GenerationProgress({ jobId, repoName, onDone }: Props) {+ const { job, sse } = useJob(jobId);+ const [log, setLog] = useState<Array<{ text: string }>>([]);+ const [elapsed, setElapsed] = useState(0);+ const startRef = useRef(Date.now());+ const notifiedRef = useRef(false);++ // Elapsed timer+ useEffect(() => {+ const id = setInterval(() => setElapsed(Date.now() - startRef.current), 1000);+ return () => clearInterval(id);+ }, []);++ // Accumulate log entries from SSE progress events+ useEffect(() => {+ if (!sse.data) return;+ const ev = sse.data as JobProgressEvent;+ if (ev.current_page) {+ setLog((prev) => [+ ...prev,+ { text: `[L${ev.current_level ?? "?"}] ${ev.current_page}` },+ ]);+ }+ }, [sse.data]);++ // Toast on terminal state+ useEffect(() => {+ if (notifiedRef.current) return;+ if (job?.status === "completed") {+ notifiedRef.current = true;+ toast.success(`Documentation updated${repoName ? ` — ${repoName}` : ""}`, {+ description: `${formatNumber(job.completed_pages)} pages generated`,+ });+ onDone?.();+ } else if (job?.status === "failed") {+ notifiedRef.current = true;+ toast.error("Generation failed", {+ description: job.error_message ?? "Unknown error",+ });+ onDone?.();+ }+ }, [job?.status, job?.completed_pages, job?.error_message, repoName, onDone]);++ const progress = job+ ? job.total_pages > 0+ ? Math.round((job.completed_pages / job.total_pages) * 100)+ : 0+ : 0;++ const elapsedStr = `${Math.floor(elapsed / 60000)}m ${Math.floor((elapsed % 60000) / 1000)}s`;+ const isRunning = job?.status === "running" || job?.status === "pending";+ const isDone = job?.status === "completed";+ const isFailed = job?.status === "failed";++ return (+ <div className="space-y-3">+ {/* Header */}+ <div className="flex items-center gap-2">+ {isRunning && <Loader2 className="h-4 w-4 animate-spin text-[var(--color-accent-primary)] shrink-0" />}+ {isDone && <CheckCircle className="h-4 w-4 text-[var(--color-fresh)] shrink-0" />}+ {isFailed && <XCircle className="h-4 w-4 text-[var(--color-outdated)] shrink-0" />}++ <span className="text-sm font-medium text-[var(--color-text-primary)]">+ {isRunning && `Generating level ${job?.current_level ?? "?"}…`}+ {isDone && "Generation complete"}+ {isFailed && "Generation failed"}+ </span>++ <span className="ml-auto text-xs text-[var(--color-text-tertiary)] tabular-nums">+ {elapsedStr}+ </span>+ </div>++ {/* Progress bar */}+ <div className="space-y-1">+ <Progress+ value={progress}+ indicatorClassName={isFailed ? "bg-[var(--color-outdated)]" : undefined}+ />+ <div className="flex justify-between text-xs text-[var(--color-text-tertiary)]">+ <span>+ {formatNumber(job?.completed_pages ?? 0)} /{" "}+ {formatNumber(job?.total_pages ?? 0)} pages+ </span>+ {(job?.failed_pages ?? 0) > 0 && (+ <Badge variant="stale" className="text-xs py-0">+ {job!.failed_pages} failed+ </Badge>+ )}+ <span>{progress}%</span>+ </div>+ </div>++ {/* Summary on done */}+ {isDone && (+ <div className="grid grid-cols-3 gap-2">+ <div className="rounded border border-[var(--color-border-default)] p-2 text-center">+ <p className="text-lg font-semibold text-[var(--color-text-primary)]">+ {formatNumber(job!.completed_pages)}+ </p>+ <p className="text-xs text-[var(--color-text-tertiary)]">pages</p>+ </div>+ <div className="rounded border border-[var(--color-border-default)] p-2 text-center">+ <p className="text-lg font-semibold text-[var(--color-text-primary)]">+ {formatTokens((job!.config?.total_input_tokens as number) ?? 0)}+ </p>+ <p className="text-xs text-[var(--color-text-tertiary)]">tokens in</p>+ </div>+ <div className="rounded border border-[var(--color-border-default)] p-2 text-center">+ <p className="text-lg font-semibold text-[var(--color-text-primary)]">+ {elapsedStr}+ </p>+ <p className="text-xs text-[var(--color-text-tertiary)]">elapsed</p>+ </div>+ </div>+ )}++ {/* Error */}+ {isFailed && job?.error_message && (+ <p className="text-sm text-[var(--color-outdated)]">{job.error_message}</p>+ )}++ {/* Live log */}+ {log.length > 0 && <JobLog entries={log} />}+ </div>+ );+}diff --git a/packages/web/src/components/jobs/job-log.tsx b/packages/web/src/components/jobs/job-log.tsxnew file mode 100644index 000000000..0fc101ef9--- /dev/null+++ b/packages/web/src/components/jobs/job-log.tsx@@ -0,0 +1,38 @@+"use client";++import { useEffect, useRef } from "react";+import { ScrollArea } from "@/components/ui/scroll-area";++interface LogEntry {+ text: string;+ level?: number;+}++interface Props {+ entries: LogEntry[];+ maxLines?: number;+}++export function JobLog({ entries, maxLines = 6 }: Props) {+ const bottomRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ bottomRef.current?.scrollIntoView({ behavior: "smooth" });+ }, [entries]);++ const visible = entries.slice(-maxLines);++ return (+ <ScrollArea className="h-28 rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">+ <div className="p-2 space-y-0.5 font-mono text-xs">+ {visible.map((e, i) => (+ <div key={i} className="text-[var(--color-text-tertiary)] leading-5 truncate">+ <span className="text-[var(--color-accent-primary)] mr-1">›</span>+ {e.text}+ </div>+ ))}+ <div ref={bottomRef} />+ </div>+ </ScrollArea>+ );+}diff --git a/packages/web/src/components/layout/mobile-nav.tsx b/packages/web/src/components/layout/mobile-nav.tsxnew file mode 100644index 000000000..2f052f1f6--- /dev/null+++ b/packages/web/src/components/layout/mobile-nav.tsx@@ -0,0 +1,206 @@+"use client";++import * as React from "react";+import Link from "next/link";+import { usePathname } from "next/navigation";+import {+ Menu,+ BookOpen,+ LayoutDashboard,+ Settings,+ Search,+ GitBranch,+ Code2,+ BarChart3,+ Users,+ Flame,+ Trash2,+ ChevronDown,+ ChevronRight,+ Circle,+ SlidersHorizontal,+} from "lucide-react";+import { Button } from "@/components/ui/button";+import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { ScrollArea } from "@/components/ui/scroll-area";+import { Separator } from "@/components/ui/separator";+import { AddRepoDialog } from "@/components/repos/add-repo-dialog";+import { cn } from "@/lib/utils/cn";+import type { RepoResponse } from "@/lib/api/types";++const GLOBAL_NAV = [+ { label: "Dashboard", href: "/", icon: LayoutDashboard },+ { label: "Settings", href: "/settings", icon: Settings },+];++function repoNavItems(repoId: string) {+ return [+ { label: "Overview", href: `/repos/${repoId}`, icon: BookOpen },+ { label: "Search", href: `/repos/${repoId}/search`, icon: Search },+ { label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },+ { label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },+ { label: "Coverage", href: `/repos/${repoId}/coverage`, icon: BarChart3 },+ { label: "Ownership", href: `/repos/${repoId}/ownership`, icon: Users },+ { label: "Hotspots", href: `/repos/${repoId}/hotspots`, icon: Flame },+ { label: "Dead Code", href: `/repos/${repoId}/dead-code`, icon: Trash2 },+ { label: "Settings", href: `/repos/${repoId}/settings`, icon: SlidersHorizontal },+ ];+}++interface MobileNavProps {+ repos?: RepoResponse[];+}++export function MobileNav({ repos = [] }: MobileNavProps) {+ const [open, setOpen] = React.useState(false);+ const pathname = usePathname();+ const [expandedRepos, setExpandedRepos] = React.useState<Set<string>>(new Set());++ const toggleRepo = (id: string) => {+ setExpandedRepos((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ };++ // Close sheet on navigation+ React.useEffect(() => {+ setOpen(false);+ }, [pathname]);++ return (+ <div className="flex md:hidden h-12 items-center gap-3 px-4 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shrink-0">+ <Button+ variant="ghost"+ size="icon"+ onClick={() => setOpen(true)}+ aria-label="Open navigation menu"+ className="h-8 w-8"+ >+ <Menu className="h-5 w-5" />+ </Button>+ {/* Current page breadcrumb */}+ <div className="flex items-center gap-1.5 min-w-0">+ <div className="flex h-5 w-5 items-center justify-center rounded bg-[var(--color-accent-primary)] shrink-0">+ <BookOpen className="h-3 w-3 text-[var(--color-text-inverse)]" />+ </div>+ <span className="text-sm font-semibold text-[var(--color-text-primary)] tracking-tight truncate">+ WikiCode+ </span>+ </div>++ <Sheet open={open} onOpenChange={setOpen}>+ <SheetContent side="left" className="p-0">+ <SheetHeader className="border-b border-[var(--color-border-default)] h-12 flex-row items-center gap-2.5 py-0">+ <div className="flex h-6 w-6 items-center justify-center rounded bg-[var(--color-accent-primary)] shrink-0">+ <BookOpen className="h-3.5 w-3.5 text-[var(--color-text-inverse)]" />+ </div>+ <SheetTitle>WikiCode</SheetTitle>+ </SheetHeader>++ <ScrollArea className="flex-1">+ <div className="p-2">+ <nav className="space-y-0.5">+ {GLOBAL_NAV.map((item) => {+ const Icon = item.icon;+ const isActive = pathname === item.href;+ return (+ <Link+ key={item.href}+ href={item.href}+ className={cn(+ "flex items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors",+ isActive+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",+ )}+ >+ <Icon className="h-4 w-4 shrink-0" />+ {item.label}+ </Link>+ );+ })}+ </nav>++ {repos.length > 0 && (+ <>+ <Separator className="my-3" />+ <p className="mb-1.5 px-2 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Repositories+ </p>+ <div className="space-y-0.5">+ {repos.map((repo) => {+ const isExpanded = expandedRepos.has(repo.id);+ const navItems = repoNavItems(repo.id);+ return (+ <div key={repo.id}>+ <button+ onClick={() => toggleRepo(repo.id)}+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-[var(--color-bg-elevated)] text-[var(--color-text-secondary)]"+ >+ <Circle className="h-2 w-2 shrink-0 fill-[var(--color-text-tertiary)] text-[var(--color-text-tertiary)]" />+ <span className="flex-1 truncate text-left font-medium">+ {repo.name}+ </span>+ {isExpanded ? (+ <ChevronDown className="h-3.5 w-3.5 shrink-0 opacity-50" />+ ) : (+ <ChevronRight className="h-3.5 w-3.5 shrink-0 opacity-50" />+ )}+ </button>+ {isExpanded && (+ <div className="ml-3 mt-0.5 space-y-0.5 border-l border-[var(--color-border-default)] pl-3">+ {navItems.map((item) => {+ const Icon = item.icon;+ const isActive =+ pathname === item.href ||+ pathname.startsWith(`${item.href}/`);+ return (+ <Link+ key={item.href}+ href={item.href}+ className={cn(+ "flex items-center gap-2 rounded-md px-2 py-1 text-xs transition-colors",+ isActive+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",+ )}+ >+ <Icon className="h-3.5 w-3.5 shrink-0" />+ {item.label}+ </Link>+ );+ })}+ </div>+ )}+ </div>+ );+ })}+ </div>+ <div className="mt-1 px-0.5">+ <AddRepoDialog variant="sidebar" />+ </div>+ </>+ )}++ {repos.length === 0 && (+ <>+ <Separator className="my-3" />+ <div className="px-0.5">+ <AddRepoDialog variant="sidebar" />+ </div>+ </>+ )}+ </div>+ </ScrollArea>++ <div className="border-t border-[var(--color-border-default)] p-3">+ <p className="text-xs text-[var(--color-text-tertiary)] text-center">WikiCode v0.1.0</p>+ </div>+ </SheetContent>+ </Sheet>+ </div>+ );+}diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxnew file mode 100644index 000000000..b0273514e--- /dev/null+++ b/packages/web/src/components/layout/sidebar.tsx@@ -0,0 +1,279 @@+"use client";++import * as React from "react";+import Link from "next/link";+import { usePathname } from "next/navigation";+import {+ LayoutDashboard,+ BookOpen,+ GitBranch,+ Lightbulb,+ Search,+ Code2,+ BarChart3,+ Users,+ Flame,+ Trash2,+ Settings,+ ChevronDown,+ ChevronRight,+ Circle,+ PanelLeft,+} from "lucide-react";+import { cn } from "@/lib/utils/cn";+import { ScrollArea } from "@/components/ui/scroll-area";+import { Separator } from "@/components/ui/separator";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { AddRepoDialog } from "@/components/repos/add-repo-dialog";+import type { RepoResponse } from "@/lib/api/types";++interface NavItem {+ label: string;+ href: string;+ icon: React.ComponentType<{ className?: string }>;+}++const GLOBAL_NAV: NavItem[] = [+ { label: "Dashboard", href: "/", icon: LayoutDashboard },+ { label: "Settings", href: "/settings", icon: Settings },+];++function repoNavItems(repoId: string): NavItem[] {+ return [+ { label: "Overview", href: `/repos/${repoId}`, icon: BookOpen },+ { label: "Search", href: `/repos/${repoId}/search`, icon: Search },+ { label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },+ { label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },+ { label: "Coverage", href: `/repos/${repoId}/coverage`, icon: BarChart3 },+ { label: "Ownership", href: `/repos/${repoId}/ownership`, icon: Users },+ { label: "Hotspots", href: `/repos/${repoId}/hotspots`, icon: Flame },+ { label: "Dead Code", href: `/repos/${repoId}/dead-code`, icon: Trash2 },+ { label: "Decisions", href: `/repos/${repoId}/decisions`, icon: Lightbulb },+ { label: "Settings", href: `/repos/${repoId}/settings`, icon: Settings },+ ];+}++interface SidebarProps {+ repos?: RepoResponse[];+ activeRepoId?: string;+}++export function Sidebar({ repos = [], activeRepoId }: SidebarProps) {+ const pathname = usePathname();+ const [expandedRepos, setExpandedRepos] = React.useState<Set<string>>(+ activeRepoId ? new Set([activeRepoId]) : new Set(),+ );+ // On lg screens, start expanded if a repo is active+ const [collapsed, setCollapsed] = React.useState(false);++ const toggleRepo = (id: string) => {+ setExpandedRepos((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ };++ const isIconOnly = collapsed;++ return (+ <aside+ className={cn(+ "hidden md:flex h-full flex-col border-r border-[var(--color-border-default)] bg-[var(--color-bg-surface)] transition-all duration-200 shrink-0",+ isIconOnly ? "w-[52px]" : "w-[260px]",+ )}+ >+ {/* Logo */}+ <div className="flex h-12 items-center gap-2.5 px-3 border-b border-[var(--color-border-default)]">+ <div className="flex h-6 w-6 items-center justify-center rounded bg-[var(--color-accent-primary)] shrink-0">+ <BookOpen className="h-3.5 w-3.5 text-[var(--color-text-inverse)]" />+ </div>+ {!isIconOnly && (+ <span className="text-sm font-semibold text-[var(--color-text-primary)] tracking-tight flex-1 truncate">+ WikiCode+ </span>+ )}+ <button+ onClick={() => setCollapsed((c) => !c)}+ className="ml-auto shrink-0 rounded p-1 text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-secondary)] transition-colors"+ aria-label={isIconOnly ? "Expand sidebar" : "Collapse sidebar"}+ >+ <PanelLeft className={cn("h-3.5 w-3.5 transition-transform", isIconOnly && "rotate-180")} />+ </button>+ </div>++ <ScrollArea className="flex-1">+ <div className={cn("p-2", isIconOnly && "px-1.5")}>+ {/* Global nav */}+ <nav className="space-y-0.5">+ {GLOBAL_NAV.map((item) => (+ <SidebarNavItem+ key={item.href}+ item={item}+ isActive={pathname === item.href}+ iconOnly={isIconOnly}+ />+ ))}+ </nav>++ {repos.length > 0 && (+ <>+ {!isIconOnly && (+ <>+ <Separator className="my-3" />+ <p className="mb-1.5 px-2 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Repositories+ </p>+ </>+ )}+ {isIconOnly && <Separator className="my-3" />}+ <div className="space-y-0.5">+ {repos.map((repo) => {+ const isExpanded = expandedRepos.has(repo.id);+ const isActive = activeRepoId === repo.id;+ const navItems = repoNavItems(repo.id);++ if (isIconOnly) {+ return (+ <Tooltip key={repo.id}>+ <TooltipTrigger asChild>+ <button+ onClick={() => toggleRepo(repo.id)}+ className={cn(+ "flex w-full items-center justify-center rounded-md p-2 transition-colors hover:bg-[var(--color-bg-elevated)]",+ isActive ? "text-[var(--color-accent-primary)]" : "text-[var(--color-text-tertiary)]",+ )}+ aria-label={repo.name}+ >+ <Circle className={cn("h-2.5 w-2.5", isActive ? "fill-[var(--color-accent-primary)]" : "fill-current")} />+ </button>+ </TooltipTrigger>+ <TooltipContent side="right">{repo.name}</TooltipContent>+ </Tooltip>+ );+ }++ return (+ <div key={repo.id}>+ <button+ onClick={() => toggleRepo(repo.id)}+ className={cn(+ "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-[var(--color-bg-elevated)]",+ isActive+ ? "text-[var(--color-text-primary)]"+ : "text-[var(--color-text-secondary)]",+ )}+ >+ <Circle+ className={cn("h-2 w-2 shrink-0", isActive ? "fill-[var(--color-accent-primary)] text-[var(--color-accent-primary)]" : "fill-[var(--color-text-tertiary)] text-[var(--color-text-tertiary)]")}+ />+ <span className="flex-1 truncate text-left font-medium">+ {repo.name}+ </span>+ {isExpanded ? (+ <ChevronDown className="h-3.5 w-3.5 shrink-0 opacity-50" />+ ) : (+ <ChevronRight className="h-3.5 w-3.5 shrink-0 opacity-50" />+ )}+ </button>+ {isExpanded && (+ <div className="ml-3 mt-0.5 space-y-0.5 border-l border-[var(--color-border-default)] pl-3">+ {navItems.map((item) => (+ <SidebarNavItem+ key={item.href}+ item={item}+ isActive={pathname === item.href || pathname.startsWith(`${item.href}/`)}+ size="sm"+ iconOnly={false}+ />+ ))}+ </div>+ )}+ </div>+ );+ })}+ </div>++ {!isIconOnly && (+ <div className="mt-1 px-0.5">+ <AddRepoDialog variant="sidebar" />+ </div>+ )}+ </>+ )}++ {repos.length === 0 && !isIconOnly && (+ <>+ <Separator className="my-3" />+ <div className="px-0.5">+ <AddRepoDialog variant="sidebar" />+ </div>+ </>+ )}+ </div>+ </ScrollArea>++ {/* Footer */}+ {!isIconOnly && (+ <div className="border-t border-[var(--color-border-default)] p-3">+ <p className="text-xs text-[var(--color-text-tertiary)] text-center">+ WikiCode v0.1.0+ </p>+ </div>+ )}+ </aside>+ );+}++function SidebarNavItem({+ item,+ isActive,+ size = "default",+ iconOnly = false,+}: {+ item: NavItem;+ isActive: boolean;+ size?: "default" | "sm";+ iconOnly?: boolean;+}) {+ const Icon = item.icon;++ if (iconOnly) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Link+ href={item.href}+ aria-label={item.label}+ className={cn(+ "flex items-center justify-center rounded-md p-2 transition-colors",+ isActive+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",+ )}+ >+ <Icon className="h-4 w-4 shrink-0" />+ </Link>+ </TooltipTrigger>+ <TooltipContent side="right">{item.label}</TooltipContent>+ </Tooltip>+ );+ }++ return (+ <Link+ href={item.href}+ className={cn(+ "flex items-center gap-2 rounded-md px-2 transition-colors",+ size === "sm" ? "py-1 text-xs" : "py-1.5 text-sm",+ isActive+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",+ )}+ >+ <Icon className={cn("shrink-0", size === "sm" ? "h-3.5 w-3.5" : "h-4 w-4")} />+ <span className="truncate">{item.label}</span>+ </Link>+ );+}diff --git a/packages/web/src/components/repos/add-repo-dialog.tsx b/packages/web/src/components/repos/add-repo-dialog.tsxnew file mode 100644index 000000000..b6fe8b634--- /dev/null+++ b/packages/web/src/components/repos/add-repo-dialog.tsx@@ -0,0 +1,161 @@+"use client";++import { useState } from "react";+import { Plus } from "lucide-react";+import { useSWRConfig } from "swr";+import { createRepo } from "@/lib/api/repos";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from "@/components/ui/dialog";+import { Label } from "@/components/ui/label";+import { Input } from "@/components/ui/input";++interface Props {+ /** Render as a sidebar button (icon + label) vs standalone button */+ variant?: "sidebar" | "default";+}++export function AddRepoDialog({ variant = "default" }: Props) {+ const { mutate } = useSWRConfig();+ const [open, setOpen] = useState(false);+ const [name, setName] = useState("");+ const [localPath, setLocalPath] = useState("");+ const [url, setUrl] = useState("");+ const [branch, setBranch] = useState("main");+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ function reset() {+ setName("");+ setLocalPath("");+ setUrl("");+ setBranch("main");+ setError(null);+ }++ async function handleSubmit(e: React.FormEvent) {+ e.preventDefault();+ if (!name.trim() || !localPath.trim()) return;+ setSubmitting(true);+ setError(null);+ try {+ await createRepo({+ name: name.trim(),+ local_path: localPath.trim(),+ url: url.trim() || undefined,+ default_branch: branch.trim() || "main",+ });+ // Invalidate the repos list so sidebar/dashboard refresh+ await mutate("/api/repos");+ setOpen(false);+ reset();+ } catch (e) {+ setError(e instanceof Error ? e.message : "Failed to add repository");+ } finally {+ setSubmitting(false);+ }+ }++ return (+ <>+ <button+ onClick={() => setOpen(true)}+ className={+ variant === "sidebar"+ ? "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-secondary)] transition-colors"+ : undefined+ }+ >+ {variant === "sidebar" ? (+ <>+ <Plus className="h-3.5 w-3.5 shrink-0" />+ <span>Add Repository</span>+ </>+ ) : (+ <Button variant="default" size="sm">+ <Plus className="h-4 w-4 mr-1" />+ Add Repository+ </Button>+ )}+ </button>++ <Dialog open={open} onOpenChange={(v) => { setOpen(v); if (!v) reset(); }}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Add Repository</DialogTitle>+ </DialogHeader>++ <form onSubmit={handleSubmit} className="space-y-4 py-2">+ <div className="space-y-1.5">+ <Label htmlFor="repo-name">Name</Label>+ <Input+ id="repo-name"+ placeholder="my-project"+ value={name}+ onChange={(e) => setName(e.target.value)}+ required+ />+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="repo-path">Local Path</Label>+ <Input+ id="repo-path"+ placeholder="C:\Users\you\projects\my-project"+ value={localPath}+ onChange={(e) => setLocalPath(e.target.value)}+ className="font-mono"+ required+ />+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="repo-url">+ Remote URL{" "}+ <span className="font-normal text-[var(--color-text-tertiary)]">(optional)</span>+ </Label>+ <Input+ id="repo-url"+ placeholder="https://github.com/org/repo"+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ />+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="repo-branch">Default Branch</Label>+ <Input+ id="repo-branch"+ placeholder="main"+ value={branch}+ onChange={(e) => setBranch(e.target.value)}+ />+ </div>++ {error && (+ <p className="text-sm text-[var(--color-outdated)]">{error}</p>+ )}++ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ onClick={() => { setOpen(false); reset(); }}+ >+ Cancel+ </Button>+ <Button type="submit" disabled={submitting || !name.trim() || !localPath.trim()}>+ {submitting ? "Adding…" : "Add Repository"}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/packages/web/src/components/repos/operations-panel.tsx b/packages/web/src/components/repos/operations-panel.tsxnew file mode 100644index 000000000..7a07d2843--- /dev/null+++ b/packages/web/src/components/repos/operations-panel.tsx@@ -0,0 +1,159 @@+"use client";++import { useState } from "react";+import { toast } from "sonner";+import { RefreshCw, Zap, ChevronDown, ChevronUp, AlertTriangle } from "lucide-react";+import { syncRepo, fullResyncRepo } from "@/lib/api/repos";+import { Button } from "@/components/ui/button";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from "@/components/ui/dialog";+import { RunConfigForm, type RunConfig } from "./run-config-form";+import { GenerationProgress } from "@/components/jobs/generation-progress";++interface Props {+ repoId: string;+ repoName: string;+}++const DEFAULT_CONFIG: RunConfig = {+ provider: "litellm",+ model: "",+ skipTests: false,+ skipInfra: false,+ concurrency: 4,+};++export function OperationsPanel({ repoId, repoName }: Props) {+ const [open, setOpen] = useState(false);+ const [runConfig, setRunConfig] = useState<RunConfig>(DEFAULT_CONFIG);+ const [activeJobId, setActiveJobId] = useState<string | null>(null);+ const [confirmResync, setConfirmResync] = useState(false);+ const [loading, setLoading] = useState<"sync" | "resync" | null>(null);++ async function handleSync() {+ setLoading("sync");+ try {+ const job = await syncRepo(repoId);+ setActiveJobId(job.id);+ toast.info(`Sync started — ${repoName}`);+ } catch (e) {+ toast.error("Sync failed", {+ description: e instanceof Error ? e.message : "Unknown error",+ });+ } finally {+ setLoading(null);+ }+ }++ async function handleResync() {+ setConfirmResync(false);+ setLoading("resync");+ try {+ const job = await fullResyncRepo(repoId);+ setActiveJobId(job.id);+ toast.info(`Full resync started — ${repoName}`);+ } catch (e) {+ toast.error("Resync failed", {+ description: e instanceof Error ? e.message : "Unknown error",+ });+ } finally {+ setLoading(null);+ }+ }++ function handleJobDone() {+ setActiveJobId(null);+ }++ return (+ <>+ <Card>+ <CardHeader className="pb-2">+ <div className="flex items-center justify-between">+ <CardTitle className="text-sm">Operations</CardTitle>+ <button+ onClick={() => setOpen((v) => !v)}+ className="flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] transition-colors"+ >+ {open ? <ChevronUp className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}+ {open ? "Collapse" : "Configure"}+ </button>+ </div>+ </CardHeader>++ <CardContent className="space-y-4">+ {/* Active job progress */}+ {activeJobId && (+ <GenerationProgress+ jobId={activeJobId}+ repoName={repoName}+ onDone={handleJobDone}+ />+ )}++ {/* Config form (collapsible) */}+ {open && !activeJobId && (+ <RunConfigForm value={runConfig} onChange={setRunConfig} />+ )}++ {/* Action buttons */}+ {!activeJobId && (+ <div className="flex gap-2">+ <Button+ variant="default"+ size="sm"+ onClick={handleSync}+ disabled={loading !== null}+ className="flex-1"+ >+ <Zap className="h-3.5 w-3.5 mr-1.5" />+ {loading === "sync" ? "Starting…" : "Sync"}+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={() => setConfirmResync(true)}+ disabled={loading !== null}+ className="flex-1"+ >+ <RefreshCw className="h-3.5 w-3.5 mr-1.5" />+ {loading === "resync" ? "Starting…" : "Full Resync"}+ </Button>+ </div>+ )}+ </CardContent>+ </Card>++ {/* Confirm resync dialog */}+ <Dialog open={confirmResync} onOpenChange={setConfirmResync}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <AlertTriangle className="h-4 w-4 text-[var(--color-stale)]" />+ Full Resync+ </DialogTitle>+ </DialogHeader>+ <p className="text-sm text-[var(--color-text-secondary)]">+ This regenerates every page for{" "}+ <span className="font-medium text-[var(--color-text-primary)]">{repoName}</span>{" "}+ from scratch. All existing pages will be overwritten.+ </p>+ <DialogFooter>+ <Button variant="ghost" onClick={() => setConfirmResync(false)}>+ Cancel+ </Button>+ <Button variant="destructive" onClick={handleResync}>+ Resync Everything+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/packages/web/src/components/repos/repo-settings-form.tsx b/packages/web/src/components/repos/repo-settings-form.tsxnew file mode 100644index 000000000..6e3414b4e--- /dev/null+++ b/packages/web/src/components/repos/repo-settings-form.tsx@@ -0,0 +1,219 @@+"use client";++import { useState } from "react";+import { toast } from "sonner";+import { Info, Save, X } from "lucide-react";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";+import { updateRepo } from "@/lib/api/repos";+import type { RepoResponse } from "@/lib/api/types";++const SUGGESTIONS = [+ "vendor/",+ "dist/",+ "build/",+ "node_modules/",+ "*.generated.*",+ "**/fixtures/**",+];++function arraysEqual(a: string[], b: string[]): boolean {+ return a.length === b.length && a.every((v, i) => v === b[i]);+}++interface RepoSettingsFormProps {+ repo: RepoResponse;+}++export function RepoSettingsForm({ repo }: RepoSettingsFormProps) {+ const [name, setName] = useState(repo.name);+ const [branch, setBranch] = useState(repo.default_branch);+ const [patterns, setPatterns] = useState<string[]>(+ (repo.settings?.exclude_patterns as string[] | undefined) ?? []+ );+ const [newPattern, setNewPattern] = useState("");+ const [saving, setSaving] = useState(false);++ const savedPatterns = (repo.settings?.exclude_patterns as string[] | undefined) ?? [];+ const hasChanges =+ name !== repo.name ||+ branch !== repo.default_branch ||+ !arraysEqual(patterns, savedPatterns);++ function addPattern(pattern: string) {+ const trimmed = pattern.trim();+ if (!trimmed || patterns.includes(trimmed)) return;+ setPatterns([...patterns, trimmed]);+ setNewPattern("");+ }++ function removePattern(pattern: string) {+ setPatterns(patterns.filter((p) => p !== pattern));+ }++ async function handleSave() {+ if (!hasChanges) return;+ setSaving(true);+ try {+ await updateRepo(repo.id, {+ name,+ default_branch: branch,+ settings: { ...repo.settings, exclude_patterns: patterns },+ });+ toast.success("Repository settings saved");+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Failed to save settings");+ } finally {+ setSaving(false);+ }+ }++ return (+ <div className="space-y-5">+ <div className="space-y-1.5">+ <Label htmlFor="repo-name">Repository name</Label>+ <Input+ id="repo-name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="my-project"+ className="max-w-sm"+ />+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="repo-branch">Default branch</Label>+ <Input+ id="repo-branch"+ value={branch}+ onChange={(e) => setBranch(e.target.value)}+ placeholder="main"+ className="max-w-sm"+ />+ </div>++ <div className="space-y-1.5">+ <Label>Local path</Label>+ <p className="text-sm font-mono text-[var(--color-text-secondary)] break-all">+ {repo.local_path}+ </p>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Path cannot be changed after repository is registered.+ </p>+ </div>++ {repo.url && (+ <div className="space-y-1.5">+ <Label>Remote URL</Label>+ <p className="text-sm font-mono text-[var(--color-text-secondary)] break-all">+ {repo.url}+ </p>+ </div>+ )}++ {/* Excluded Paths */}+ <div className="space-y-3 border-t border-[var(--color-border-default)] pt-5">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">Excluded Paths</span>+ {patterns.length > 0 && (+ <Badge variant="secondary" className="text-xs">+ {patterns.length} active+ </Badge>+ )}+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Info className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>Supports full .gitignore syntax. Paths are relative to the repo root.</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ <p className="text-xs text-[var(--color-text-secondary)]">+ Gitignore-style patterns. Excluded folders are skipped during indexing and generation.+ </p>++ {/* Chips */}+ {patterns.length === 0 ? (+ <p className="text-xs text-[var(--color-text-tertiary)] italic">+ No custom patterns — .gitignore and .wikicodeIgnore are always respected.+ </p>+ ) : (+ <div className="flex flex-wrap gap-1.5">+ {patterns.map((p) => (+ <span+ key={p}+ className="inline-flex items-center gap-1 rounded-full bg-[var(--color-bg-inset)] px-2.5 py-0.5 text-xs font-mono text-[var(--color-text-primary)] border border-[var(--color-border-default)]"+ >+ {p}+ <button+ type="button"+ onClick={() => removePattern(p)}+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] transition-colors"+ aria-label={`Remove ${p}`}+ >+ <X className="h-3 w-3" />+ </button>+ </span>+ ))}+ </div>+ )}++ {/* Add input */}+ <div className="flex gap-2 max-w-sm">+ <Input+ value={newPattern}+ onChange={(e) => setNewPattern(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ addPattern(newPattern);+ }+ }}+ placeholder="e.g. vendor/, src/generated/**, *.min.js"+ className="font-mono text-xs"+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => addPattern(newPattern)}+ disabled={!newPattern.trim()}+ >+ Add+ </Button>+ </div>++ {/* Quick-add suggestions */}+ <div className="flex flex-wrap gap-1.5">+ {SUGGESTIONS.map((suggestion) => (+ <button+ key={suggestion}+ type="button"+ onClick={() => addPattern(suggestion)}+ disabled={patterns.includes(suggestion)}+ className="text-xs rounded-full border border-[var(--color-border-default)] px-2.5 py-0.5 font-mono text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-inset)] transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ + {suggestion}+ </button>+ ))}+ </div>+ </div>++ <Button+ onClick={handleSave}+ disabled={!hasChanges || saving}+ size="sm"+ className="gap-2"+ >+ <Save className="h-3.5 w-3.5" />+ {saving ? "Saving…" : "Save changes"}+ </Button>+ </div>+ );+}diff --git a/packages/web/src/components/repos/run-config-form.tsx b/packages/web/src/components/repos/run-config-form.tsxnew file mode 100644index 000000000..5ef26f95f--- /dev/null+++ b/packages/web/src/components/repos/run-config-form.tsx@@ -0,0 +1,129 @@+"use client";++import { useEffect } from "react";+import { config } from "@/lib/config";+import { Label } from "@/components/ui/label";+import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";+import { Slider } from "@/components/ui/slider";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";++export interface RunConfig {+ provider: string;+ model: string;+ skipTests: boolean;+ skipInfra: boolean;+ concurrency: number;+}++interface Props {+ value: RunConfig;+ onChange: (v: RunConfig) => void;+}++const PROVIDERS = ["litellm", "openai", "anthropic", "ollama", "mock"] as const;++export function RunConfigForm({ value, onChange }: Props) {+ // Seed from saved settings on mount+ useEffect(() => {+ onChange({+ provider: config.getProvider(),+ model: config.getModel(),+ skipTests: false,+ skipInfra: false,+ concurrency: 4,+ });+ // only on mount+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ function set<K extends keyof RunConfig>(key: K, v: RunConfig[K]) {+ onChange({ ...value, [key]: v });+ }++ return (+ <div className="space-y-4">+ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label>Provider</Label>+ <Select value={value.provider} onValueChange={(v) => set("provider", v)}>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {PROVIDERS.map((p) => (+ <SelectItem key={p} value={p}>+ {p}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="run-model">Model</Label>+ <Input+ id="run-model"+ value={value.model}+ onChange={(e) => set("model", e.target.value)}+ placeholder="gemini/gemini-2.0-flash"+ className="font-mono"+ />+ </div>+ </div>++ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <div>+ <p className="text-sm text-[var(--color-text-primary)]">Skip test files</p>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Exclude test files from documentation+ </p>+ </div>+ <Switch+ checked={value.skipTests}+ onCheckedChange={(v) => set("skipTests", v)}+ />+ </div>++ <div className="flex items-center justify-between">+ <div>+ <p className="text-sm text-[var(--color-text-primary)]">Skip infra files</p>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Exclude CI, Docker, config files+ </p>+ </div>+ <Switch+ checked={value.skipInfra}+ onCheckedChange={(v) => set("skipInfra", v)}+ />+ </div>+ </div>++ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <Label>Concurrency</Label>+ <span className="text-sm tabular-nums text-[var(--color-text-secondary)]">+ {value.concurrency}+ </span>+ </div>+ <Slider+ min={1}+ max={10}+ step={1}+ value={[value.concurrency]}+ onValueChange={([v]) => set("concurrency", v)}+ />+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Parallel page generations (higher = faster but more API usage)+ </p>+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/search/command-palette.tsx b/packages/web/src/components/search/command-palette.tsxnew file mode 100644index 000000000..ac1a9c2c8--- /dev/null+++ b/packages/web/src/components/search/command-palette.tsx@@ -0,0 +1,145 @@+"use client";++import { useEffect, useState, useCallback } from "react";+import { useRouter } from "next/navigation";+import { Command } from "cmdk";+import { Search, LayoutDashboard, Settings, BookOpen } from "lucide-react";+import { useSearch } from "@/lib/hooks/use-search";+import { truncatePath } from "@/lib/utils/format";+import type { RepoResponse } from "@/lib/api/types";++interface CommandPaletteProps {+ repos: RepoResponse[];+}++export function CommandPalette({ repos }: CommandPaletteProps) {+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState("");+ const router = useRouter();++ const { results, isLoading } = useSearch(query, { limit: 8 });++ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if ((e.metaKey || e.ctrlKey) && e.key === "k") {+ e.preventDefault();+ setOpen((o) => !o);+ }+ };+ window.addEventListener("keydown", handler);+ return () => window.removeEventListener("keydown", handler);+ }, []);++ const navigate = useCallback(+ (href: string) => {+ router.push(href);+ setOpen(false);+ setQuery("");+ },+ [router],+ );++ return (+ <Command.Dialog+ open={open}+ onOpenChange={setOpen}+ label="Command palette"+ className="fixed inset-0 z-[calc(var(--z-modal)+1)] flex items-start justify-center pt-[20vh]"+ >+ <div+ className="fixed inset-0 bg-black/60 backdrop-blur-sm"+ onClick={() => setOpen(false)}+ />+ <div className="relative z-10 w-full max-w-xl rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-2xl overflow-hidden">+ <div className="flex items-center gap-3 px-4 py-3 border-b border-[var(--color-border-default)]">+ <Search className="h-4 w-4 text-[var(--color-text-tertiary)] shrink-0" />+ <Command.Input+ value={query}+ onValueChange={setQuery}+ placeholder="Search pages, navigate repos…"+ className="flex-1 bg-transparent text-sm text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)]"+ />+ <kbd className="hidden sm:inline-flex items-center rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-xs text-[var(--color-text-tertiary)] font-mono">+ ESC+ </kbd>+ </div>++ <Command.List className="max-h-80 overflow-y-auto py-2">+ <Command.Empty className="px-4 py-8 text-center text-sm text-[var(--color-text-tertiary)]">+ {isLoading ? "Searching…" : "No results found."}+ </Command.Empty>++ {/* Quick navigation */}+ <Command.Group+ heading="Navigate"+ className="px-2 pb-1"+ >+ <Command.Item+ value="dashboard"+ onSelect={() => navigate("/")}+ className="flex items-center gap-2.5 rounded-md px-3 py-2 text-sm text-[var(--color-text-secondary)] cursor-pointer hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] data-[selected=true]:bg-[var(--color-bg-elevated)] data-[selected=true]:text-[var(--color-text-primary)]"+ >+ <LayoutDashboard className="h-4 w-4" />+ Dashboard+ </Command.Item>+ <Command.Item+ value="settings"+ onSelect={() => navigate("/settings")}+ className="flex items-center gap-2.5 rounded-md px-3 py-2 text-sm text-[var(--color-text-secondary)] cursor-pointer hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] data-[selected=true]:bg-[var(--color-bg-elevated)] data-[selected=true]:text-[var(--color-text-primary)]"+ >+ <Settings className="h-4 w-4" />+ Settings+ </Command.Item>+ </Command.Group>++ {/* Repos */}+ {repos.length > 0 && (+ <Command.Group heading="Repositories" className="px-2 pb-1">+ {repos.map((repo) => (+ <Command.Item+ key={repo.id}+ value={`repo-${repo.name}`}+ onSelect={() => navigate(`/repos/${repo.id}`)}+ className="flex items-center gap-2.5 rounded-md px-3 py-2 text-sm text-[var(--color-text-secondary)] cursor-pointer hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] data-[selected=true]:bg-[var(--color-bg-elevated)] data-[selected=true]:text-[var(--color-text-primary)]"+ >+ <BookOpen className="h-4 w-4" />+ {repo.name}+ </Command.Item>+ ))}+ </Command.Group>+ )}++ {/* Search results */}+ {results.length > 0 && (+ <Command.Group heading="Pages" className="px-2 pb-1">+ {results.map((r) => (+ <Command.Item+ key={r.page_id}+ value={`page-${r.title}`}+ onSelect={() => {+ // Use first available repo as context for the wiki route.+ // The repo ID is only used for supplemental data (git panel, breadcrumb).+ const fallbackRepoId = repos[0]?.id ?? "";+ navigate(`/repos/${fallbackRepoId}/wiki/${encodeURIComponent(r.page_id)}`);+ }}+ className="flex flex-col items-start rounded-md px-3 py-2 text-sm cursor-pointer hover:bg-[var(--color-bg-elevated)] data-[selected=true]:bg-[var(--color-bg-elevated)]"+ >+ <span className="text-[var(--color-text-primary)] font-medium">{r.title}</span>+ <span className="text-xs text-[var(--color-text-tertiary)] font-mono">+ {truncatePath(r.target_path, 50)}+ </span>+ </Command.Item>+ ))}+ </Command.Group>+ )}+ </Command.List>++ <div className="border-t border-[var(--color-border-default)] px-4 py-2 flex items-center gap-4 text-xs text-[var(--color-text-tertiary)]">+ <span>↑↓ navigate</span>+ <span>↵ select</span>+ <span>esc close</span>+ </div>+ </div>+ </Command.Dialog>+ );+}diff --git a/packages/web/src/components/search/search-bar.tsx b/packages/web/src/components/search/search-bar.tsxnew file mode 100644index 000000000..e10309be6--- /dev/null+++ b/packages/web/src/components/search/search-bar.tsx@@ -0,0 +1,54 @@+"use client";++import { Search } from "lucide-react";+import { Input } from "@/components/ui/input";+import { cn } from "@/lib/utils/cn";++type SearchType = "fulltext" | "semantic";++interface SearchBarProps {+ query: string;+ onQueryChange: (q: string) => void;+ searchType: SearchType;+ onSearchTypeChange: (t: SearchType) => void;+ className?: string;+}++export function SearchBar({+ query,+ onQueryChange,+ searchType,+ onSearchTypeChange,+ className,+}: SearchBarProps) {+ return (+ <div className={cn("flex items-center gap-2", className)}>+ <div className="relative flex-1">+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[var(--color-text-tertiary)]" />+ <Input+ value={query}+ onChange={(e) => onQueryChange(e.target.value)}+ placeholder="Search wiki pages…"+ className="pl-9"+ autoFocus+ />+ </div>+ <div className="flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">+ {(["fulltext", "semantic"] as SearchType[]).map((t) => (+ <button+ key={t}+ onClick={() => onSearchTypeChange(t)}+ className={cn(+ "px-3 py-1.5 font-medium transition-colors capitalize",+ searchType === t+ ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"+ : "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",+ )}+ >+ {t}+ </button>+ ))}+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/search/search-result-card.tsx b/packages/web/src/components/search/search-result-card.tsxnew file mode 100644index 000000000..996dc5edc--- /dev/null+++ b/packages/web/src/components/search/search-result-card.tsx@@ -0,0 +1,69 @@+import Link from "next/link";+import { Badge } from "@/components/ui/badge";+import { truncatePath } from "@/lib/utils/format";+import { cn } from "@/lib/utils/cn";+import type { SearchResultResponse } from "@/lib/api/types";++interface SearchResultCardProps {+ result: SearchResultResponse;+ query: string;+ repoId: string;+}++function highlightSnippet(snippet: string, query: string): React.ReactNode {+ if (!query.trim()) return snippet;+ const terms = query.trim().split(/\s+/).filter(Boolean);+ const escaped = terms.map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");+ const regex = new RegExp(`(${escaped})`, "gi");+ // split with capturing group yields alternating non-match / match / non-match ...+ const parts = snippet.split(regex);+ return parts.map((part, i) =>+ i % 2 === 1 ? (+ <strong key={i} className="text-[var(--color-text-primary)] font-semibold">+ {part}+ </strong>+ ) : (+ <span key={i}>{part}</span>+ ),+ );+}++export function SearchResultCard({ result, query, repoId }: SearchResultCardProps) {+ const href = `/repos/${repoId}/wiki/${encodeURIComponent(result.page_id)}`;++ return (+ <Link+ href={href}+ className="block rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4 hover:border-[var(--color-border-hover)] hover:bg-[var(--color-bg-elevated)] transition-colors"+ >+ <div className="flex items-start justify-between gap-2 mb-1.5">+ <h3 className="text-sm font-medium text-[var(--color-text-primary)] truncate">+ {result.title}+ </h3>+ <div className="flex items-center gap-1.5 shrink-0">+ <Badge variant="default">{result.page_type.replace(/_/g, " ")}</Badge>+ <span+ className={cn(+ "inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium tabular-nums",+ result.score >= 0.8+ ? "border-green-500/20 bg-green-500/10 text-green-500"+ : result.score >= 0.5+ ? "border-yellow-500/20 bg-yellow-500/10 text-yellow-500"+ : "border-[var(--color-border-default)] bg-transparent text-[var(--color-text-tertiary)]",+ )}+ >+ {Math.round(result.score * 100)}%+ </span>+ </div>+ </div>+ <p className="text-xs font-mono text-[var(--color-text-tertiary)] mb-2">+ {truncatePath(result.target_path, 60)}+ </p>+ {result.snippet && (+ <p className="text-xs text-[var(--color-text-secondary)] line-clamp-2 leading-relaxed">+ {highlightSnippet(result.snippet, query)}+ </p>+ )}+ </Link>+ );+}diff --git a/packages/web/src/components/settings/connection-section.tsx b/packages/web/src/components/settings/connection-section.tsxnew file mode 100644index 000000000..0b5c47e76--- /dev/null+++ b/packages/web/src/components/settings/connection-section.tsx@@ -0,0 +1,112 @@+"use client";++import { useState, useEffect } from "react";+import { CheckCircle, XCircle, Loader2 } from "lucide-react";+import { config } from "@/lib/config";+import { getHealth } from "@/lib/api/health";+import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";+import { Label } from "@/components/ui/label";+import { Input } from "@/components/ui/input";+import { Button } from "@/components/ui/button";+import type { HealthResponse } from "@/lib/api/types";++export function ConnectionSection() {+ const [apiUrl, setApiUrl] = useState("");+ const [apiKey, setApiKey] = useState("");+ const [testing, setTesting] = useState(false);+ const [health, setHealth] = useState<HealthResponse | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ setApiUrl(config.getApiUrl());+ setApiKey(config.getApiKey());+ }, []);++ function save() {+ config.setApiUrl(apiUrl);+ config.setApiKey(apiKey);+ }++ async function testConnection() {+ save();+ setTesting(true);+ setHealth(null);+ setError(null);+ try {+ const h = await getHealth();+ setHealth(h);+ } catch (e) {+ setError(e instanceof Error ? e.message : "Connection failed");+ } finally {+ setTesting(false);+ }+ }++ return (+ <Card>+ <CardHeader>+ <CardTitle className="text-base">API Connection</CardTitle>+ <CardDescription>+ Configure how the UI connects to your WikiCode server.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <div className="space-y-1.5">+ <Label htmlFor="api-url">Server URL</Label>+ <Input+ id="api-url"+ placeholder="http://localhost:7337"+ value={apiUrl}+ onChange={(e) => setApiUrl(e.target.value)}+ onBlur={save}+ className="font-mono"+ />+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Leave blank to use the same origin (when proxied via Next.js).+ </p>+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="api-key">API Key</Label>+ <Input+ id="api-key"+ type="password"+ placeholder="Optional — only required if WIKICODE_API_KEY is set on the server"+ value={apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ onBlur={save}+ className="font-mono"+ />+ </div>++ <div className="flex items-center gap-3">+ <Button+ variant="outline"+ size="sm"+ onClick={testConnection}+ disabled={testing}+ >+ {testing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ "Test Connection"+ )}+ </Button>++ {health && (+ <span className="flex items-center gap-1.5 text-sm text-[var(--color-fresh)]">+ <CheckCircle className="h-4 w-4" />+ Connected · v{health.version} · DB {health.db}+ </span>+ )}+ {error && (+ <span className="flex items-center gap-1.5 text-sm text-[var(--color-outdated)]">+ <XCircle className="h-4 w-4" />+ {error}+ </span>+ )}+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/packages/web/src/components/settings/mcp-section.tsx b/packages/web/src/components/settings/mcp-section.tsxnew file mode 100644index 000000000..362870d29--- /dev/null+++ b/packages/web/src/components/settings/mcp-section.tsx@@ -0,0 +1,64 @@+"use client";++import { useState } from "react";+import { Copy, Check } from "lucide-react";+import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";+import { Button } from "@/components/ui/button";++const MCP_CONFIG = JSON.stringify(+ {+ mcpServers: {+ wikicode: {+ command: "wikicode",+ args: ["mcp", "/path/to/your/repo", "--transport", "stdio"],+ },+ },+ },+ null,+ 2,+);++export function McpSection() {+ const [copied, setCopied] = useState(false);++ async function copy() {+ await navigator.clipboard.writeText(MCP_CONFIG);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ }++ return (+ <Card>+ <CardHeader>+ <CardTitle className="text-base">MCP Config</CardTitle>+ <CardDescription>+ Add to your Claude Code, Cursor, or Cline MCP config to enable AI-powered codebase Q&A.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-3">+ <div className="relative">+ <pre className="rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 text-xs font-mono text-[var(--color-text-secondary)] overflow-x-auto">+ {MCP_CONFIG}+ </pre>+ <Button+ variant="ghost"+ size="icon"+ onClick={copy}+ className="absolute right-2 top-2 h-7 w-7"+ >+ {copied ? (+ <Check className="h-3.5 w-3.5 text-[var(--color-fresh)]" />+ ) : (+ <Copy className="h-3.5 w-3.5" />+ )}+ </Button>+ </div>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Replace <code className="font-mono">/path/to/your/repo</code> with the local path+ of the repository you want to query. Run{" "}+ <code className="font-mono">wikicode init</code> first to generate documentation.+ </p>+ </CardContent>+ </Card>+ );+}diff --git a/packages/web/src/components/settings/provider-section.tsx b/packages/web/src/components/settings/provider-section.tsxnew file mode 100644index 000000000..df5afebc1--- /dev/null+++ b/packages/web/src/components/settings/provider-section.tsx@@ -0,0 +1,228 @@+"use client";++import { useState, useEffect } from "react";+import { config } from "@/lib/config";+import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";+import { Label } from "@/components/ui/label";+import { Input } from "@/components/ui/input";+import { Badge } from "@/components/ui/badge";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";++const PROVIDERS = ["gemini", "openai", "anthropic", "ollama", "litellm", "mock"] as const;+const EMBEDDERS = ["mock", "gemini", "openai"] as const;++const MODEL_PLACEHOLDERS: Record<string, string> = {+ gemini: "gemini-3.1-flash-lite-preview",+ openai: "gpt-4.1",+ anthropic: "claude-sonnet-4-6",+ ollama: "llama3.2",+ litellm: "groq/llama-3.1-70b-versatile",+ mock: "mock",+};++const PROVIDER_ENV_VARS: Record<string, { vars: string[]; installHint: string }> = {+ gemini: { vars: ["GEMINI_API_KEY"], installHint: "pip install google-genai" },+ openai: { vars: ["OPENAI_API_KEY"], installHint: "pip install openai" },+ anthropic: { vars: ["ANTHROPIC_API_KEY"], installHint: "pip install anthropic" },+ ollama: { vars: ["OLLAMA_BASE_URL"], installHint: "https://ollama.ai" },+ litellm: { vars: ["LITELLM_*"], installHint: "pip install litellm" },+ mock: { vars: [], installHint: "No key needed" },+};++const EMBEDDER_ENV_VARS: Record<string, string[]> = {+ gemini: ["GEMINI_API_KEY"],+ openai: ["OPENAI_API_KEY"],+ mock: [],+};++type TestStatus = "idle" | "testing" | "ok" | "error";++export function ProviderSection() {+ const [provider, setProvider] = useState("gemini");+ const [model, setModel] = useState("");+ const [embedder, setEmbedder] = useState("mock");+ const [testStatus, setTestStatus] = useState<TestStatus>("idle");+ const [testError, setTestError] = useState("");+ const [serverProvider, setServerProvider] = useState<string | null>(null);+ const [expanded, setExpanded] = useState<string | null>(null);++ useEffect(() => {+ setProvider(config.getProvider());+ setModel(config.getModel());+ setEmbedder(config.getEmbedder());+ // Fetch current server config from /api/health+ fetch("/api/health")+ .then((r) => r.json())+ .then((data) => {+ if (data?.provider) setServerProvider(data.provider);+ })+ .catch(() => {});+ }, []);++ function handleProviderChange(v: string) {+ setProvider(v);+ config.setProvider(v);+ setTestStatus("idle");+ }++ function handleEmbedderChange(v: string) {+ setEmbedder(v);+ config.setEmbedder(v);+ }++ async function handleTestConnection() {+ setTestStatus("testing");+ setTestError("");+ try {+ const res = await fetch("/api/health");+ const data = await res.json();+ if (res.ok && data.status === "healthy") {+ setTestStatus("ok");+ } else {+ setTestStatus("error");+ setTestError(data.status ?? "Server returned non-healthy status");+ }+ } catch (err) {+ setTestStatus("error");+ setTestError(String(err));+ }+ }++ const providerInfo = PROVIDER_ENV_VARS[provider];+ const embedderVars = EMBEDDER_ENV_VARS[embedder] ?? [];++ return (+ <div className="space-y-4">+ <Card>+ <CardHeader>+ <CardTitle className="text-base">Provider & Model</CardTitle>+ <CardDescription>+ Defaults used when triggering init or sync from the UI.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-1.5">+ <Label>Provider</Label>+ <Select value={provider} onValueChange={handleProviderChange}>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {PROVIDERS.map((p) => (+ <SelectItem key={p} value={p}>+ {p}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="model">Model</Label>+ <Input+ id="model"+ placeholder={MODEL_PLACEHOLDERS[provider] ?? "model name"}+ value={model}+ onChange={(e) => setModel(e.target.value)}+ onBlur={() => config.setModel(model)}+ className="font-mono"+ />+ </div>+ </div>++ {providerInfo && providerInfo.vars.length > 0 && (+ <div className="rounded-md border border-dashed p-3 space-y-1.5">+ <p className="text-xs font-medium text-[var(--color-text-secondary)]">+ Required env vars for {provider}:+ </p>+ <div className="flex flex-wrap gap-1.5">+ {providerInfo.vars.map((v) => (+ <code+ key={v}+ className="text-xs bg-[var(--color-bg-secondary)] px-1.5 py-0.5 rounded font-mono"+ >+ {v}+ </code>+ ))}+ </div>+ <p className="text-xs text-[var(--color-text-tertiary)]">{providerInfo.installHint}</p>+ </div>+ )}++ <div className="space-y-1.5">+ <Label>Embedder</Label>+ <Select value={embedder} onValueChange={handleEmbedderChange}>+ <SelectTrigger className="w-48">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {EMBEDDERS.map((e) => (+ <SelectItem key={e} value={e}>+ {e}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {embedderVars.length > 0 && (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Requires{" "}+ {embedderVars.map((v) => (+ <code key={v} className="font-mono">{v}</code>+ ))}{" "}+ — set <code className="font-mono">WIKICODE_EMBEDDER={embedder}</code> on the server.+ </p>+ )}+ {embedder === "mock" && (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Using mock embedder — semantic search disabled. Set{" "}+ <code className="font-mono">WIKICODE_EMBEDDER=gemini</code> or{" "}+ <code className="font-mono">WIKICODE_EMBEDDER=openai</code> for real RAG.+ </p>+ )}+ </div>+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle className="text-base">Server Connection</CardTitle>+ <CardDescription>+ Test that the WikiCode server is reachable and healthy.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-3">+ {serverProvider && (+ <p className="text-sm text-[var(--color-text-secondary)]">+ Server configured with provider:{" "}+ <Badge variant="outline" className="font-mono text-xs">{serverProvider}</Badge>+ </p>+ )}+ <div className="flex items-center gap-3">+ <button+ onClick={handleTestConnection}+ disabled={testStatus === "testing"}+ className="text-sm px-3 py-1.5 rounded-md border border-[var(--color-border)] hover:bg-[var(--color-bg-secondary)] disabled:opacity-50 transition-colors"+ >+ {testStatus === "testing" ? "Testing…" : "Test connection"}+ </button>+ {testStatus === "ok" && (+ <span className="text-sm text-green-600 dark:text-green-400">✓ Server healthy</span>+ )}+ {testStatus === "error" && (+ <span className="text-sm text-red-600 dark:text-red-400">+ ✗ {testError || "Connection failed"}+ </span>+ )}+ </div>+ </CardContent>+ </Card>+ </div>+ );+}diff --git a/packages/web/src/components/settings/webhook-section.tsx b/packages/web/src/components/settings/webhook-section.tsxnew file mode 100644index 000000000..7c49b9a5d--- /dev/null+++ b/packages/web/src/components/settings/webhook-section.tsx@@ -0,0 +1,68 @@+"use client";++import { useState } from "react";+import { Copy, Check } from "lucide-react";+import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";+import { Button } from "@/components/ui/button";++function CopyField({ label, value }: { label: string; value: string }) {+ const [copied, setCopied] = useState(false);++ async function copy() {+ await navigator.clipboard.writeText(value);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ }++ return (+ <div className="space-y-1">+ <p className="text-xs text-[var(--color-text-tertiary)]">{label}</p>+ <div className="flex items-center gap-2">+ <code className="flex-1 rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-1.5 text-xs font-mono text-[var(--color-text-secondary)] truncate">+ {value}+ </code>+ <Button variant="ghost" size="icon" onClick={copy} className="h-7 w-7 shrink-0">+ {copied ? (+ <Check className="h-3.5 w-3.5 text-[var(--color-fresh)]" />+ ) : (+ <Copy className="h-3.5 w-3.5" />+ )}+ </Button>+ </div>+ </div>+ );+}++export function WebhookSection() {+ const serverUrl = "http://your-server:7337";++ return (+ <Card>+ <CardHeader>+ <CardTitle className="text-base">Webhook Config</CardTitle>+ <CardDescription>+ Register these URLs in GitHub or GitLab to trigger automatic re-sync on push.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <CopyField label="GitHub Webhook URL" value={`${serverUrl}/api/webhooks/github`} />+ <CopyField label="GitLab Webhook URL" value={`${serverUrl}/api/webhooks/gitlab`} />++ <div className="rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 space-y-1">+ <p className="text-xs font-medium text-[var(--color-text-secondary)]">+ Required env vars on the server+ </p>+ <p className="text-xs font-mono text-[var(--color-text-tertiary)]">+ WIKICODE_GITHUB_WEBHOOK_SECRET=your-secret+ </p>+ <p className="text-xs font-mono text-[var(--color-text-tertiary)]">+ WIKICODE_GITLAB_WEBHOOK_TOKEN=your-token+ </p>+ <p className="text-xs text-[var(--color-text-tertiary)] mt-1">+ Omit these vars to skip signature verification during development.+ </p>+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/packages/web/src/components/shared/api-error.tsx b/packages/web/src/components/shared/api-error.tsxnew file mode 100644index 000000000..9c922fde5--- /dev/null+++ b/packages/web/src/components/shared/api-error.tsx@@ -0,0 +1,32 @@+import { AlertTriangle, RefreshCw } from "lucide-react";+import { Button } from "@/components/ui/button";++interface ApiErrorProps {+ title?: string;+ message?: string;+ onRetry?: () => void;+}++export function ApiError({+ title = "Failed to load",+ message = "An error occurred while fetching data.",+ onRetry,+}: ApiErrorProps) {+ return (+ <div className="flex flex-col items-center justify-center gap-3 py-12 text-center">+ <div className="flex h-10 w-10 items-center justify-center rounded-full bg-red-500/10">+ <AlertTriangle className="h-5 w-5 text-red-500" />+ </div>+ <div>+ <p className="text-sm font-medium text-[var(--color-text-primary)]">{title}</p>+ <p className="mt-0.5 text-xs text-[var(--color-text-tertiary)] max-w-xs">{message}</p>+ </div>+ {onRetry && (+ <Button onClick={onRetry} size="sm" variant="secondary" className="gap-1.5 mt-1">+ <RefreshCw className="h-3.5 w-3.5" />+ Retry+ </Button>+ )}+ </div>+ );+}diff --git a/packages/web/src/components/shared/empty-state.tsx b/packages/web/src/components/shared/empty-state.tsxnew file mode 100644index 000000000..7e48565b5--- /dev/null+++ b/packages/web/src/components/shared/empty-state.tsx@@ -0,0 +1,40 @@+import * as React from "react";+import { cn } from "@/lib/utils/cn";+import { Button } from "@/components/ui/button";++interface EmptyStateProps {+ icon?: React.ReactNode;+ title: string;+ description?: string;+ action?: {+ label: string;+ onClick: () => void;+ };+ className?: string;+}++export function EmptyState({ icon, title, description, action, className }: EmptyStateProps) {+ return (+ <div+ className={cn(+ "flex flex-col items-center justify-center gap-4 rounded-lg border border-dashed border-[var(--color-border-default)] p-12 text-center",+ className,+ )}+ >+ {icon && (+ <div className="text-[var(--color-text-tertiary)]">{icon}</div>+ )}+ <div className="space-y-1">+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">{title}</h3>+ {description && (+ <p className="text-sm text-[var(--color-text-secondary)]">{description}</p>+ )}+ </div>+ {action && (+ <Button size="sm" onClick={action.onClick}>+ {action.label}+ </Button>+ )}+ </div>+ );+}diff --git a/packages/web/src/components/shared/stat-card.tsx b/packages/web/src/components/shared/stat-card.tsxnew file mode 100644index 000000000..e7def189a--- /dev/null+++ b/packages/web/src/components/shared/stat-card.tsx@@ -0,0 +1,46 @@+import * as React from "react";+import { cn } from "@/lib/utils/cn";+import { Card, CardContent } from "@/components/ui/card";++interface StatCardProps {+ label: string;+ value: string | number;+ description?: string;+ trend?: { value: string; positive: boolean };+ icon?: React.ReactNode;+ className?: string;+ href?: string;+}++export function StatCard({+ label,+ value,+ description,+ icon,+ className,+}: StatCardProps) {+ return (+ <Card className={cn("transition-colors hover:border-[var(--color-border-hover)]", className)}>+ <CardContent className="p-4">+ <div className="flex items-start justify-between">+ <div className="space-y-1">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ {label}+ </p>+ <p className="text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">+ {value}+ </p>+ {description && (+ <p className="text-xs text-[var(--color-text-secondary)]">{description}</p>+ )}+ </div>+ {icon && (+ <div className="rounded-md bg-[var(--color-bg-elevated)] p-2 text-[var(--color-text-secondary)]">+ {icon}+ </div>+ )}+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/packages/web/src/components/symbols/symbol-drawer.tsx b/packages/web/src/components/symbols/symbol-drawer.tsxnew file mode 100644index 000000000..1388ebb9b--- /dev/null+++ b/packages/web/src/components/symbols/symbol-drawer.tsx@@ -0,0 +1,71 @@+"use client";++import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+} from "@/components/ui/dialog";+import { Badge } from "@/components/ui/badge";+import { ScrollArea } from "@/components/ui/scroll-area";+import type { SymbolResponse } from "@/lib/api/types";++interface SymbolDrawerProps {+ symbol: SymbolResponse | null;+ onClose: () => void;+}++export function SymbolDrawer({ symbol, onClose }: SymbolDrawerProps) {+ return (+ <Dialog open={symbol !== null} onOpenChange={(open) => !open && onClose()}>+ <DialogContent className="max-w-2xl">+ {symbol && (+ <>+ <DialogHeader>+ <DialogTitle className="font-mono text-base">{symbol.name}</DialogTitle>+ <DialogDescription className="font-mono text-xs text-[var(--color-text-tertiary)]">+ {symbol.file_path}:{symbol.start_line}+ </DialogDescription>+ </DialogHeader>++ <div className="flex flex-wrap gap-1.5 my-1">+ <Badge variant="accent">{symbol.kind}</Badge>+ <Badge variant="outline">{symbol.language}</Badge>+ {symbol.visibility && symbol.visibility !== "public" && (+ <Badge variant="default">{symbol.visibility}</Badge>+ )}+ {symbol.is_async && <Badge variant="default">async</Badge>}+ {symbol.complexity_estimate > 10 && (+ <Badge variant="stale">complexity {symbol.complexity_estimate}</Badge>+ )}+ </div>++ <ScrollArea className="max-h-64 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">+ <pre className="p-4 text-xs font-mono text-[var(--color-text-primary)] whitespace-pre-wrap break-all">+ <code>{symbol.signature || symbol.name}</code>+ </pre>+ </ScrollArea>++ {symbol.docstring && (+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1.5">+ Docstring+ </p>+ <p className="text-sm text-[var(--color-text-secondary)] whitespace-pre-wrap">+ {symbol.docstring}+ </p>+ </div>+ )}++ {symbol.parent_name && (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Parent: <span className="font-mono text-[var(--color-text-secondary)]">{symbol.parent_name}</span>+ </p>+ )}+ </>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/web/src/components/symbols/symbol-table.tsx b/packages/web/src/components/symbols/symbol-table.tsxnew file mode 100644index 000000000..29271d7a9--- /dev/null+++ b/packages/web/src/components/symbols/symbol-table.tsx@@ -0,0 +1,238 @@+"use client";++import { useState, useEffect, useCallback } from "react";+import useSWR from "swr";+import { ChevronUp, ChevronDown, ChevronsUpDown } from "lucide-react";+import { Input } from "@/components/ui/input";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Skeleton } from "@/components/ui/skeleton";+import { EmptyState } from "@/components/shared/empty-state";+import { SymbolDrawer } from "./symbol-drawer";+import { listSymbols } from "@/lib/api/symbols";+import { useDebounce } from "@/lib/hooks/use-debounce";+import { truncatePath } from "@/lib/utils/format";+import { cn } from "@/lib/utils/cn";+import type { SymbolResponse } from "@/lib/api/types";++type SortCol = "name" | "kind" | "language" | "complexity_estimate" | "start_line";+type SortDir = "asc" | "desc";++const LIMIT = 50;++const KINDS = ["function", "class", "method", "interface", "variable", "module"];+const LANGUAGES = ["python", "typescript", "javascript", "go", "rust", "java", "cpp", "c"];++interface SymbolTableProps {+ repoId: string;+}++function SortIcon({ col, sortCol, sortDir }: { col: SortCol; sortCol: SortCol; sortDir: SortDir }) {+ if (col !== sortCol) return <ChevronsUpDown className="h-3 w-3 opacity-40" />;+ return sortDir === "asc" ? (+ <ChevronUp className="h-3 w-3" />+ ) : (+ <ChevronDown className="h-3 w-3" />+ );+}++export function SymbolTable({ repoId }: SymbolTableProps) {+ const [q, setQ] = useState("");+ const debouncedQ = useDebounce(q, 300);+ const [kind, setKind] = useState("all");+ const [language, setLanguage] = useState("all");+ const [offset, setOffset] = useState(0);+ const [items, setItems] = useState<SymbolResponse[]>([]);+ const [sortCol, setSortCol] = useState<SortCol>("name");+ const [sortDir, setSortDir] = useState<SortDir>("asc");+ const [selected, setSelected] = useState<SymbolResponse | null>(null);++ const swrKey = `symbols:${repoId}:${debouncedQ}:${kind}:${language}:${offset}`;+ const { data, isLoading } = useSWR<SymbolResponse[]>(+ swrKey,+ () =>+ listSymbols({+ repo_id: repoId,+ q: debouncedQ || undefined,+ kind: kind !== "all" ? kind : undefined,+ language: language !== "all" ? language : undefined,+ limit: LIMIT,+ offset,+ }),+ { revalidateOnFocus: false },+ );++ useEffect(() => {+ if (!data) return;+ setItems((prev) => (offset === 0 ? data : [...prev, ...data]));+ }, [data, offset]);++ // Reset when filters change+ useEffect(() => {+ setOffset(0);+ setItems([]);+ }, [debouncedQ, kind, language]);++ const handleSort = useCallback(+ (col: SortCol) => {+ if (col === sortCol) {+ setSortDir((d) => (d === "asc" ? "desc" : "asc"));+ } else {+ setSortCol(col);+ setSortDir("asc");+ }+ },+ [sortCol],+ );++ const sorted = [...items].sort((a, b) => {+ const va = a[sortCol] ?? "";+ const vb = b[sortCol] ?? "";+ const cmp = String(va).localeCompare(String(vb), undefined, { numeric: true });+ return sortDir === "asc" ? cmp : -cmp;+ });++ const hasMore = data?.length === LIMIT;++ return (+ <div className="space-y-4">+ {/* Filters */}+ <div className="flex flex-wrap gap-2">+ <Input+ placeholder="Search symbols…"+ value={q}+ onChange={(e) => setQ(e.target.value)}+ className="max-w-xs"+ />+ <Select value={kind} onValueChange={setKind}>+ <SelectTrigger className="w-36">+ <SelectValue placeholder="Kind" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">All kinds</SelectItem>+ {KINDS.map((k) => (+ <SelectItem key={k} value={k}>+ {k}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Select value={language} onValueChange={setLanguage}>+ <SelectTrigger className="w-36">+ <SelectValue placeholder="Language" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">All languages</SelectItem>+ {LANGUAGES.map((l) => (+ <SelectItem key={l} value={l}>+ {l}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {items.length > 0 && (+ <span className="self-center text-xs text-[var(--color-text-tertiary)]">+ {items.length} symbols+ </span>+ )}+ </div>++ {/* Table */}+ {isLoading && items.length === 0 ? (+ <div className="space-y-2">+ {Array.from({ length: 8 }).map((_, i) => (+ <Skeleton key={i} className="h-10 w-full" />+ ))}+ </div>+ ) : sorted.length === 0 ? (+ <EmptyState title="No symbols found" description="Try adjusting your filters." />+ ) : (+ <>+ <div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto">+ <table className="w-full min-w-[600px] text-sm">+ <thead>+ <tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">+ {(+ [+ { col: "name" as SortCol, label: "Name" },+ { col: "kind" as SortCol, label: "Kind" },+ { col: "language" as SortCol, label: "Language" },+ { col: "start_line" as SortCol, label: "File" },+ { col: "complexity_estimate" as SortCol, label: "Complexity" },+ ] as Array<{ col: SortCol; label: string }>+ ).map(({ col, label }) => (+ <th+ key={col}+ className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider cursor-pointer select-none hover:text-[var(--color-text-primary)] transition-colors"+ onClick={() => handleSort(col)}+ >+ <span className="inline-flex items-center gap-1">+ {label}+ <SortIcon col={col} sortCol={sortCol} sortDir={sortDir} />+ </span>+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {sorted.map((sym) => (+ <tr+ key={sym.id}+ className="border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0 cursor-pointer"+ onClick={() => setSelected(sym)}+ >+ <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] max-w-xs">+ <span className="truncate block">{sym.name}</span>+ {sym.parent_name && (+ <span className="text-[var(--color-text-tertiary)]">.{sym.parent_name}</span>+ )}+ </td>+ <td className="px-4 py-2.5">+ <Badge variant={sym.kind === "class" ? "accent" : "default"}>{sym.kind}</Badge>+ </td>+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)]">+ {sym.language}+ </td>+ <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-tertiary)] max-w-xs truncate">+ {truncatePath(sym.file_path, 40)}+ <span className="text-[var(--color-text-tertiary)]">:{sym.start_line}</span>+ </td>+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] tabular-nums">+ <span+ className={cn(+ sym.complexity_estimate > 15+ ? "text-red-500"+ : sym.complexity_estimate > 8+ ? "text-yellow-500"+ : "",+ )}+ >+ {sym.complexity_estimate}+ </span>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>++ {hasMore && (+ <div className="flex justify-center">+ <Button+ variant="outline"+ size="sm"+ onClick={() => setOffset((o) => o + LIMIT)}+ disabled={isLoading}+ >+ {isLoading ? "Loading…" : "Load more"}+ </Button>+ </div>+ )}+ </>+ )}++ <SymbolDrawer symbol={selected} onClose={() => setSelected(null)} />+ </div>+ );+}diff --git a/packages/web/src/components/ui/badge.tsx b/packages/web/src/components/ui/badge.tsxnew file mode 100644index 000000000..e51693639--- /dev/null+++ b/packages/web/src/components/ui/badge.tsx@@ -0,0 +1,40 @@+import * as React from "react";+import { cva, type VariantProps } from "class-variance-authority";+import { cn } from "@/lib/utils/cn";++const badgeVariants = cva(+ "inline-flex items-center gap-1 rounded border px-2 py-0.5 text-xs font-medium transition-colors",+ {+ variants: {+ variant: {+ default:+ "border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] text-[var(--color-text-secondary)]",+ fresh:+ "border-green-500/20 bg-green-500/10 text-green-500",+ stale:+ "border-yellow-500/20 bg-yellow-500/10 text-yellow-500",+ outdated:+ "border-red-500/20 bg-red-500/10 text-red-500",+ accent:+ "border-[var(--color-accent-muted)] bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]",+ outline:+ "border-[var(--color-border-default)] bg-transparent text-[var(--color-text-secondary)]",+ },+ },+ defaultVariants: {+ variant: "default",+ },+ },+);++export interface BadgeProps+ extends React.HTMLAttributes<HTMLDivElement>,+ VariantProps<typeof badgeVariants> {}++function Badge({ className, variant, ...props }: BadgeProps) {+ return (+ <div className={cn(badgeVariants({ variant }), className)} {...props} />+ );+}++export { Badge, badgeVariants };diff --git a/packages/web/src/components/ui/button.tsx b/packages/web/src/components/ui/button.tsxnew file mode 100644index 000000000..619343f47--- /dev/null+++ b/packages/web/src/components/ui/button.tsx@@ -0,0 +1,58 @@+import * as React from "react";+import { Slot } from "@radix-ui/react-slot";+import { cva, type VariantProps } from "class-variance-authority";+import { cn } from "@/lib/utils/cn";++const buttonVariants = cva(+ "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--color-bg-root)] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",+ {+ variants: {+ variant: {+ default:+ "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)] hover:bg-[var(--color-accent-hover)]",+ destructive:+ "bg-[var(--color-error)] text-white hover:bg-red-600",+ outline:+ "border border-[var(--color-border-default)] bg-transparent text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] hover:border-[var(--color-border-hover)]",+ secondary:+ "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-overlay)]",+ ghost:+ "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",+ link:+ "text-[var(--color-accent-primary)] underline-offset-4 hover:underline",+ },+ size: {+ default: "h-9 px-4 py-2",+ sm: "h-7 rounded px-3 text-xs",+ lg: "h-10 rounded-md px-8",+ icon: "h-9 w-9",+ },+ },+ defaultVariants: {+ variant: "default",+ size: "default",+ },+ },+);++export interface ButtonProps+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,+ VariantProps<typeof buttonVariants> {+ asChild?: boolean;+}++const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(+ ({ className, variant, size, asChild = false, ...props }, ref) => {+ const Comp = asChild ? Slot : "button";+ return (+ <Comp+ className={cn(buttonVariants({ variant, size, className }))}+ ref={ref}+ {...props}+ />+ );+ },+);+Button.displayName = "Button";++export { Button, buttonVariants };diff --git a/packages/web/src/components/ui/card.tsx b/packages/web/src/components/ui/card.tsxnew file mode 100644index 000000000..0dbacd04d--- /dev/null+++ b/packages/web/src/components/ui/card.tsx@@ -0,0 +1,70 @@+import * as React from "react";+import { cn } from "@/lib/utils/cn";++const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(+ ({ className, ...props }, ref) => (+ <div+ ref={ref}+ className={cn(+ "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]",+ className,+ )}+ {...props}+ />+ ),+);+Card.displayName = "Card";++const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(+ ({ className, ...props }, ref) => (+ <div+ ref={ref}+ className={cn("flex flex-col space-y-1.5 p-6", className)}+ {...props}+ />+ ),+);+CardHeader.displayName = "CardHeader";++const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(+ ({ className, ...props }, ref) => (+ <h3+ ref={ref}+ className={cn("font-semibold leading-none tracking-tight text-[var(--color-text-primary)]", className)}+ {...props}+ />+ ),+);+CardTitle.displayName = "CardTitle";++const CardDescription = React.forwardRef<+ HTMLParagraphElement,+ React.HTMLAttributes<HTMLParagraphElement>+>(({ className, ...props }, ref) => (+ <p+ ref={ref}+ className={cn("text-sm text-[var(--color-text-secondary)]", className)}+ {...props}+ />+));+CardDescription.displayName = "CardDescription";++const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(+ ({ className, ...props }, ref) => (+ <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />+ ),+);+CardContent.displayName = "CardContent";++const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(+ ({ className, ...props }, ref) => (+ <div+ ref={ref}+ className={cn("flex items-center p-6 pt-0", className)}+ {...props}+ />+ ),+);+CardFooter.displayName = "CardFooter";++export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };diff --git a/packages/web/src/components/ui/dialog.tsx b/packages/web/src/components/ui/dialog.tsxnew file mode 100644index 000000000..e7dd270e7--- /dev/null+++ b/packages/web/src/components/ui/dialog.tsx@@ -0,0 +1,100 @@+"use client";++import * as React from "react";+import * as DialogPrimitive from "@radix-ui/react-dialog";+import { X } from "lucide-react";+import { cn } from "@/lib/utils/cn";++const Dialog = DialogPrimitive.Root;+const DialogTrigger = DialogPrimitive.Trigger;+const DialogPortal = DialogPrimitive.Portal;+const DialogClose = DialogPrimitive.Close;++const DialogOverlay = React.forwardRef<+ React.ElementRef<typeof DialogPrimitive.Overlay>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>+>(({ className, ...props }, ref) => (+ <DialogPrimitive.Overlay+ ref={ref}+ className={cn(+ "fixed inset-0 z-[var(--z-modal)] bg-black/60 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",+ className,+ )}+ {...props}+ />+));+DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;++const DialogContent = React.forwardRef<+ React.ElementRef<typeof DialogPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>+>(({ className, children, ...props }, ref) => (+ <DialogPortal>+ <DialogOverlay />+ <DialogPrimitive.Content+ ref={ref}+ className={cn(+ "fixed left-[50%] top-[50%] z-[var(--z-modal)] grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-xl",+ className,+ )}+ {...props}+ >+ {children}+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-[var(--color-bg-root)] transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-[var(--color-accent-primary)] focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:text-[var(--color-text-secondary)]">+ <X className="h-4 w-4" />+ <span className="sr-only">Close</span>+ </DialogPrimitive.Close>+ </DialogPrimitive.Content>+ </DialogPortal>+));+DialogContent.displayName = DialogPrimitive.Content.displayName;++const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (+ <div className={cn("flex flex-col space-y-1.5 text-left", className)} {...props} />+);+DialogHeader.displayName = "DialogHeader";++const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (+ <div+ className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}+ {...props}+ />+);+DialogFooter.displayName = "DialogFooter";++const DialogTitle = React.forwardRef<+ React.ElementRef<typeof DialogPrimitive.Title>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>+>(({ className, ...props }, ref) => (+ <DialogPrimitive.Title+ ref={ref}+ className={cn("text-lg font-semibold leading-none tracking-tight text-[var(--color-text-primary)]", className)}+ {...props}+ />+));+DialogTitle.displayName = DialogPrimitive.Title.displayName;++const DialogDescription = React.forwardRef<+ React.ElementRef<typeof DialogPrimitive.Description>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>+>(({ className, ...props }, ref) => (+ <DialogPrimitive.Description+ ref={ref}+ className={cn("text-sm text-[var(--color-text-secondary)]", className)}+ {...props}+ />+));+DialogDescription.displayName = DialogPrimitive.Description.displayName;++export {+ Dialog,+ DialogPortal,+ DialogOverlay,+ DialogClose,+ DialogTrigger,+ DialogContent,+ DialogHeader,+ DialogFooter,+ DialogTitle,+ DialogDescription,+};diff --git a/packages/web/src/components/ui/input.tsx b/packages/web/src/components/ui/input.tsxnew file mode 100644index 000000000..266554842--- /dev/null+++ b/packages/web/src/components/ui/input.tsx@@ -0,0 +1,21 @@+import * as React from "react";+import { cn } from "@/lib/utils/cn";++const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(+ ({ className, type, ...props }, ref) => {+ return (+ <input+ type={type}+ className={cn(+ "flex h-9 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1 text-sm text-[var(--color-text-primary)] shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-[var(--color-text-tertiary)] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--color-accent-primary)] disabled:cursor-not-allowed disabled:opacity-50",+ className,+ )}+ ref={ref}+ {...props}+ />+ );+ },+);+Input.displayName = "Input";++export { Input };diff --git a/packages/web/src/components/ui/label.tsx b/packages/web/src/components/ui/label.tsxnew file mode 100644index 000000000..3adc1aaf4--- /dev/null+++ b/packages/web/src/components/ui/label.tsx@@ -0,0 +1,20 @@+"use client";++import * as LabelPrimitive from "@radix-ui/react-label";+import { cn } from "@/lib/utils/cn";++export function Label({+ className,+ ...props+}: React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>) {+ return (+ <LabelPrimitive.Root+ className={cn(+ "text-sm font-medium text-[var(--color-text-primary)] leading-none",+ "peer-disabled:cursor-not-allowed peer-disabled:opacity-70",+ className,+ )}+ {...props}+ />+ );+}diff --git a/packages/web/src/components/ui/progress.tsx b/packages/web/src/components/ui/progress.tsxnew file mode 100644index 000000000..849243de5--- /dev/null+++ b/packages/web/src/components/ui/progress.tsx@@ -0,0 +1,32 @@+"use client";++import * as ProgressPrimitive from "@radix-ui/react-progress";+import { cn } from "@/lib/utils/cn";++export function Progress({+ value,+ className,+ indicatorClassName,+}: {+ value?: number;+ className?: string;+ indicatorClassName?: string;+}) {+ return (+ <ProgressPrimitive.Root+ value={value}+ className={cn(+ "relative h-2 w-full overflow-hidden rounded-full bg-[var(--color-bg-elevated)]",+ className,+ )}+ >+ <ProgressPrimitive.Indicator+ className={cn(+ "h-full w-full flex-1 bg-[var(--color-accent-primary)] transition-all duration-300",+ indicatorClassName,+ )}+ style={{ transform: `translateX(-${100 - (value ?? 0)}%)` }}+ />+ </ProgressPrimitive.Root>+ );+}diff --git a/packages/web/src/components/ui/scroll-area.tsx b/packages/web/src/components/ui/scroll-area.tsxnew file mode 100644index 000000000..b4dca02c5--- /dev/null+++ b/packages/web/src/components/ui/scroll-area.tsx@@ -0,0 +1,45 @@+"use client";++import * as React from "react";+import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";+import { cn } from "@/lib/utils/cn";++const ScrollArea = React.forwardRef<+ React.ElementRef<typeof ScrollAreaPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>+>(({ className, children, ...props }, ref) => (+ <ScrollAreaPrimitive.Root+ ref={ref}+ className={cn("relative overflow-hidden", className)}+ {...props}+ >+ <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">+ {children}+ </ScrollAreaPrimitive.Viewport>+ <ScrollBar />+ <ScrollAreaPrimitive.Corner />+ </ScrollAreaPrimitive.Root>+));+ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;++const ScrollBar = React.forwardRef<+ React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,+ React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>+>(({ className, orientation = "vertical", ...props }, ref) => (+ <ScrollAreaPrimitive.ScrollAreaScrollbar+ ref={ref}+ orientation={orientation}+ className={cn(+ "flex touch-none select-none transition-colors",+ orientation === "vertical" && "h-full w-2.5 border-l border-l-transparent p-[1px]",+ orientation === "horizontal" && "h-2.5 flex-col border-t border-t-transparent p-[1px]",+ className,+ )}+ {...props}+ >+ <ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-[var(--color-border-hover)]" />+ </ScrollAreaPrimitive.ScrollAreaScrollbar>+));+ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;++export { ScrollArea, ScrollBar };diff --git a/packages/web/src/components/ui/select.tsx b/packages/web/src/components/ui/select.tsxnew file mode 100644index 000000000..315fe6a86--- /dev/null+++ b/packages/web/src/components/ui/select.tsx@@ -0,0 +1,149 @@+"use client";++import * as React from "react";+import * as SelectPrimitive from "@radix-ui/react-select";+import { Check, ChevronDown, ChevronUp } from "lucide-react";+import { cn } from "@/lib/utils/cn";++const Select = SelectPrimitive.Root;+const SelectGroup = SelectPrimitive.Group;+const SelectValue = SelectPrimitive.Value;++const SelectTrigger = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.Trigger>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>+>(({ className, children, ...props }, ref) => (+ <SelectPrimitive.Trigger+ ref={ref}+ className={cn(+ "flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2 text-sm text-[var(--color-text-primary)] shadow-sm ring-offset-[var(--color-bg-root)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:ring-1 focus:ring-[var(--color-accent-primary)] disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",+ className,+ )}+ {...props}+ >+ {children}+ <SelectPrimitive.Icon asChild>+ <ChevronDown className="h-4 w-4 opacity-50" />+ </SelectPrimitive.Icon>+ </SelectPrimitive.Trigger>+));+SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;++const SelectScrollUpButton = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>+>(({ className, ...props }, ref) => (+ <SelectPrimitive.ScrollUpButton+ ref={ref}+ className={cn("flex cursor-default items-center justify-center py-1", className)}+ {...props}+ >+ <ChevronUp className="h-4 w-4" />+ </SelectPrimitive.ScrollUpButton>+));+SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;++const SelectScrollDownButton = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>+>(({ className, ...props }, ref) => (+ <SelectPrimitive.ScrollDownButton+ ref={ref}+ className={cn("flex cursor-default items-center justify-center py-1", className)}+ {...props}+ >+ <ChevronDown className="h-4 w-4" />+ </SelectPrimitive.ScrollDownButton>+));+SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;++const SelectContent = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>+>(({ className, children, position = "popper", ...props }, ref) => (+ <SelectPrimitive.Portal>+ <SelectPrimitive.Content+ ref={ref}+ className={cn(+ "relative z-[var(--z-dropdown)] max-h-96 min-w-[8rem] overflow-hidden rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] text-[var(--color-text-primary)] shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ position === "popper" &&+ "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",+ className,+ )}+ position={position}+ {...props}+ >+ <SelectScrollUpButton />+ <SelectPrimitive.Viewport+ className={cn(+ "p-1",+ position === "popper" &&+ "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]",+ )}+ >+ {children}+ </SelectPrimitive.Viewport>+ <SelectScrollDownButton />+ </SelectPrimitive.Content>+ </SelectPrimitive.Portal>+));+SelectContent.displayName = SelectPrimitive.Content.displayName;++const SelectLabel = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.Label>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>+>(({ className, ...props }, ref) => (+ <SelectPrimitive.Label+ ref={ref}+ className={cn("px-2 py-1.5 text-xs font-semibold text-[var(--color-text-tertiary)]", className)}+ {...props}+ />+));+SelectLabel.displayName = SelectPrimitive.Label.displayName;++const SelectItem = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.Item>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>+>(({ className, children, ...props }, ref) => (+ <SelectPrimitive.Item+ ref={ref}+ className={cn(+ "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-[var(--color-bg-elevated)] focus:text-[var(--color-text-primary)] data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+ className,+ )}+ {...props}+ >+ <span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">+ <SelectPrimitive.ItemIndicator>+ <Check className="h-4 w-4" />+ </SelectPrimitive.ItemIndicator>+ </span>+ <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>+ </SelectPrimitive.Item>+));+SelectItem.displayName = SelectPrimitive.Item.displayName;++const SelectSeparator = React.forwardRef<+ React.ElementRef<typeof SelectPrimitive.Separator>,+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>+>(({ className, ...props }, ref) => (+ <SelectPrimitive.Separator+ ref={ref}+ className={cn("-mx-1 my-1 h-px bg-[var(--color-border-default)]", className)}+ {...props}+ />+));+SelectSeparator.displayName = SelectPrimitive.Separator.displayName;++export {+ Select,+ SelectGroup,+ SelectValue,+ SelectTrigger,+ SelectContent,+ SelectLabel,+ SelectItem,+ SelectSeparator,+ SelectScrollUpButton,+ SelectScrollDownButton,+};diff --git a/packages/web/src/components/ui/separator.tsx b/packages/web/src/components/ui/separator.tsxnew file mode 100644index 000000000..b0c674a9f--- /dev/null+++ b/packages/web/src/components/ui/separator.tsx@@ -0,0 +1,30 @@+"use client";++import * as React from "react";+import * as SeparatorPrimitive from "@radix-ui/react-separator";+import { cn } from "@/lib/utils/cn";++const Separator = React.forwardRef<+ React.ElementRef<typeof SeparatorPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>+>(+ (+ { className, orientation = "horizontal", decorative = true, ...props },+ ref,+ ) => (+ <SeparatorPrimitive.Root+ ref={ref}+ decorative={decorative}+ orientation={orientation}+ className={cn(+ "shrink-0 bg-[var(--color-border-default)]",+ orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",+ className,+ )}+ {...props}+ />+ ),+);+Separator.displayName = SeparatorPrimitive.Root.displayName;++export { Separator };diff --git a/packages/web/src/components/ui/sheet.tsx b/packages/web/src/components/ui/sheet.tsxnew file mode 100644index 000000000..009bd6eec--- /dev/null+++ b/packages/web/src/components/ui/sheet.tsx@@ -0,0 +1,92 @@+"use client";++import * as React from "react";+import * as DialogPrimitive from "@radix-ui/react-dialog";+import { X } from "lucide-react";+import { cn } from "@/lib/utils/cn";++const Sheet = DialogPrimitive.Root;+const SheetTrigger = DialogPrimitive.Trigger;+const SheetClose = DialogPrimitive.Close;+const SheetPortal = DialogPrimitive.Portal;++const SheetOverlay = React.forwardRef<+ React.ElementRef<typeof DialogPrimitive.Overlay>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>+>(({ className, ...props }, ref) => (+ <DialogPrimitive.Overlay+ ref={ref}+ className={cn(+ "fixed inset-0 z-[var(--z-modal)] bg-black/60 backdrop-blur-sm",+ "data-[state=open]:animate-in data-[state=closed]:animate-out",+ "data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",+ className,+ )}+ {...props}+ />+));+SheetOverlay.displayName = "SheetOverlay";++interface SheetContentProps+ extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {+ side?: "left" | "right";+}++const SheetContent = React.forwardRef<+ React.ElementRef<typeof DialogPrimitive.Content>,+ SheetContentProps+>(({ className, children, side = "left", ...props }, ref) => (+ <SheetPortal>+ <SheetOverlay />+ <DialogPrimitive.Content+ ref={ref}+ className={cn(+ "fixed z-[var(--z-modal)] flex flex-col bg-[var(--color-bg-surface)] shadow-2xl",+ "transition ease-in-out",+ "data-[state=open]:animate-in data-[state=closed]:animate-out",+ "data-[state=closed]:duration-200 data-[state=open]:duration-300",+ side === "left" && [+ "inset-y-0 left-0 h-full w-[280px] border-r border-[var(--color-border-default)]",+ "data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left",+ ],+ side === "right" && [+ "inset-y-0 right-0 h-full w-[280px] border-l border-[var(--color-border-default)]",+ "data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",+ ],+ className,+ )}+ {...props}+ >+ {children}+ <DialogPrimitive.Close+ className={cn(+ "absolute right-4 top-4 rounded-sm opacity-70 transition-opacity",+ "hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-[var(--color-accent-primary)]",+ "disabled:pointer-events-none",+ )}+ aria-label="Close navigation"+ >+ <X className="h-5 w-5" />+ </DialogPrimitive.Close>+ </DialogPrimitive.Content>+ </SheetPortal>+));+SheetContent.displayName = "SheetContent";++const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (+ <div className={cn("flex flex-col space-y-1.5 px-4 py-3", className)} {...props} />+);++const SheetTitle = React.forwardRef<+ React.ElementRef<typeof DialogPrimitive.Title>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>+>(({ className, ...props }, ref) => (+ <DialogPrimitive.Title+ ref={ref}+ className={cn("text-sm font-semibold text-[var(--color-text-primary)]", className)}+ {...props}+ />+));+SheetTitle.displayName = "SheetTitle";++export { Sheet, SheetTrigger, SheetClose, SheetPortal, SheetOverlay, SheetContent, SheetHeader, SheetTitle };diff --git a/packages/web/src/components/ui/skeleton.tsx b/packages/web/src/components/ui/skeleton.tsxnew file mode 100644index 000000000..d78fc8d9f--- /dev/null+++ b/packages/web/src/components/ui/skeleton.tsx@@ -0,0 +1,18 @@+import { cn } from "@/lib/utils/cn";++function Skeleton({+ className,+ ...props+}: React.HTMLAttributes<HTMLDivElement>) {+ return (+ <div+ className={cn(+ "animate-pulse rounded-md bg-[var(--color-bg-elevated)]",+ className,+ )}+ {...props}+ />+ );+}++export { Skeleton };diff --git a/packages/web/src/components/ui/slider.tsx b/packages/web/src/components/ui/slider.tsxnew file mode 100644index 000000000..3470c5e25--- /dev/null+++ b/packages/web/src/components/ui/slider.tsx@@ -0,0 +1,30 @@+"use client";++import * as SliderPrimitive from "@radix-ui/react-slider";+import { cn } from "@/lib/utils/cn";++export function Slider({+ className,+ ...props+}: React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>) {+ return (+ <SliderPrimitive.Root+ className={cn(+ "relative flex w-full touch-none select-none items-center",+ className,+ )}+ {...props}+ >+ <SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-[var(--color-bg-elevated)]">+ <SliderPrimitive.Range className="absolute h-full bg-[var(--color-accent-primary)]" />+ </SliderPrimitive.Track>+ <SliderPrimitive.Thumb+ className={cn(+ "block h-4 w-4 rounded-full border border-[var(--color-accent-primary)] bg-[var(--color-bg-surface)] shadow",+ "transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]",+ "disabled:pointer-events-none disabled:opacity-50",+ )}+ />+ </SliderPrimitive.Root>+ );+}diff --git a/packages/web/src/components/ui/switch.tsx b/packages/web/src/components/ui/switch.tsxnew file mode 100644index 000000000..c850a29ba--- /dev/null+++ b/packages/web/src/components/ui/switch.tsx@@ -0,0 +1,29 @@+"use client";++import * as SwitchPrimitive from "@radix-ui/react-switch";+import { cn } from "@/lib/utils/cn";++export function Switch({+ className,+ ...props+}: React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root>) {+ return (+ <SwitchPrimitive.Root+ className={cn(+ "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] focus-visible:ring-offset-2",+ "disabled:cursor-not-allowed disabled:opacity-50",+ "data-[state=checked]:bg-[var(--color-accent-primary)] data-[state=unchecked]:bg-[var(--color-bg-elevated)]",+ className,+ )}+ {...props}+ >+ <SwitchPrimitive.Thumb+ className={cn(+ "pointer-events-none block h-4 w-4 rounded-full bg-white shadow-lg ring-0 transition-transform",+ "data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0",+ )}+ />+ </SwitchPrimitive.Root>+ );+}diff --git a/packages/web/src/components/ui/tabs.tsx b/packages/web/src/components/ui/tabs.tsxnew file mode 100644index 000000000..d237de2e6--- /dev/null+++ b/packages/web/src/components/ui/tabs.tsx@@ -0,0 +1,54 @@+"use client";++import * as React from "react";+import * as TabsPrimitive from "@radix-ui/react-tabs";+import { cn } from "@/lib/utils/cn";++const Tabs = TabsPrimitive.Root;++const TabsList = React.forwardRef<+ React.ElementRef<typeof TabsPrimitive.List>,+ React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>+>(({ className, ...props }, ref) => (+ <TabsPrimitive.List+ ref={ref}+ className={cn(+ "inline-flex h-9 items-center justify-center rounded-lg bg-[var(--color-bg-elevated)] p-1 text-[var(--color-text-secondary)]",+ className,+ )}+ {...props}+ />+));+TabsList.displayName = TabsPrimitive.List.displayName;++const TabsTrigger = React.forwardRef<+ React.ElementRef<typeof TabsPrimitive.Trigger>,+ React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>+>(({ className, ...props }, ref) => (+ <TabsPrimitive.Trigger+ ref={ref}+ className={cn(+ "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-[var(--color-bg-root)] transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-[var(--color-bg-surface)] data-[state=active]:text-[var(--color-text-primary)] data-[state=active]:shadow-sm",+ className,+ )}+ {...props}+ />+));+TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;++const TabsContent = React.forwardRef<+ React.ElementRef<typeof TabsPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>+>(({ className, ...props }, ref) => (+ <TabsPrimitive.Content+ ref={ref}+ className={cn(+ "mt-2 ring-offset-[var(--color-bg-root)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] focus-visible:ring-offset-2",+ className,+ )}+ {...props}+ />+));+TabsContent.displayName = TabsPrimitive.Content.displayName;++export { Tabs, TabsList, TabsTrigger, TabsContent };diff --git a/packages/web/src/components/ui/tooltip.tsx b/packages/web/src/components/ui/tooltip.tsxnew file mode 100644index 000000000..8db30eb0a--- /dev/null+++ b/packages/web/src/components/ui/tooltip.tsx@@ -0,0 +1,29 @@+"use client";++import * as React from "react";+import * as TooltipPrimitive from "@radix-ui/react-tooltip";+import { cn } from "@/lib/utils/cn";++const TooltipProvider = TooltipPrimitive.Provider;+const Tooltip = TooltipPrimitive.Root;+const TooltipTrigger = TooltipPrimitive.Trigger;++const TooltipContent = React.forwardRef<+ React.ElementRef<typeof TooltipPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>+>(({ className, sideOffset = 4, ...props }, ref) => (+ <TooltipPrimitive.Portal>+ <TooltipPrimitive.Content+ ref={ref}+ sideOffset={sideOffset}+ className={cn(+ "z-[var(--z-dropdown)] overflow-hidden rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] px-3 py-1.5 text-xs text-[var(--color-text-primary)] shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ className,+ )}+ {...props}+ />+ </TooltipPrimitive.Portal>+));+TooltipContent.displayName = TooltipPrimitive.Content.displayName;++export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };diff --git a/packages/web/src/components/wiki/code-block.tsx b/packages/web/src/components/wiki/code-block.tsxnew file mode 100644index 000000000..6ee56bf5f--- /dev/null+++ b/packages/web/src/components/wiki/code-block.tsx@@ -0,0 +1,61 @@+"use client";++import { useState } from "react";+import { Copy, Check } from "lucide-react";+import { cn } from "@/lib/utils/cn";++interface Props {+ code: string;+ language?: string;+ /** Pre-rendered HTML from Shiki — passed through as dangerouslySetInnerHTML */+ html: string;+}++export function CodeBlock({ code, language, html }: Props) {+ const [copied, setCopied] = useState(false);++ async function copy() {+ await navigator.clipboard.writeText(code);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ }++ return (+ <div className="group relative my-4 rounded-lg border border-[var(--color-border-default)] overflow-hidden">+ {/* Header bar */}+ <div className="flex items-center justify-between px-4 py-1.5 bg-[var(--color-bg-elevated)] border-b border-[var(--color-border-default)]">+ {language && (+ <span className="text-xs font-mono text-[var(--color-text-tertiary)]">+ {language}+ </span>+ )}+ <button+ onClick={copy}+ className={cn(+ "ml-auto flex items-center gap-1 text-xs text-[var(--color-text-tertiary)]",+ "hover:text-[var(--color-text-secondary)] transition-colors",+ )}+ aria-label="Copy code"+ >+ {copied ? (+ <>+ <Check className="h-3.5 w-3.5" />+ Copied+ </>+ ) : (+ <>+ <Copy className="h-3.5 w-3.5" />+ Copy+ </>+ )}+ </button>+ </div>++ {/* Shiki-rendered HTML */}+ <div+ className="overflow-x-auto text-sm [&>pre]:p-4 [&>pre]:m-0 [&>pre]:bg-transparent!"+ dangerouslySetInnerHTML={{ __html: html }}+ />+ </div>+ );+}diff --git a/packages/web/src/components/wiki/confidence-badge.tsx b/packages/web/src/components/wiki/confidence-badge.tsxnew file mode 100644index 000000000..54aefb3ef--- /dev/null+++ b/packages/web/src/components/wiki/confidence-badge.tsx@@ -0,0 +1,69 @@+"use client";++import * as React from "react";+import { cn } from "@/lib/utils/cn";+import {+ scoreToStatus,+ statusBadgeClasses,+ statusLabel,+ type FreshnessStatus,+} from "@/lib/utils/confidence";+import { formatConfidence } from "@/lib/utils/format";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";++interface ConfidenceBadgeProps {+ score: number;+ status?: string;+ showScore?: boolean;+ staleSince?: string | null;+ className?: string;+}++export function ConfidenceBadge({+ score,+ status: statusProp,+ showScore = false,+ staleSince,+ className,+}: ConfidenceBadgeProps) {+ const status = (statusProp as FreshnessStatus | undefined) ?? scoreToStatus(score);+ const badgeClasses = statusBadgeClasses(status);+ const label = statusLabel(status);++ const badge = (+ <span+ className={cn(+ "inline-flex items-center gap-1.5 rounded border px-2 py-0.5 text-xs font-medium transition-colors",+ badgeClasses,+ className,+ )}+ >+ <span+ className={cn(+ "h-1.5 w-1.5 rounded-full",+ status === "fresh" && "bg-green-500",+ status === "stale" && "animate-pulse bg-yellow-500",+ status === "outdated" && "bg-red-500",+ )}+ />+ {label}+ {showScore && <span className="opacity-70">· {formatConfidence(score)}</span>}+ </span>+ );++ if (status === "stale" && staleSince) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>{badge}</TooltipTrigger>+ <TooltipContent>+ <p>Stale since {new Date(staleSince).toLocaleDateString()}</p>+ <p className="text-[var(--color-text-tertiary)]">+ Confidence: {formatConfidence(score)}+ </p>+ </TooltipContent>+ </Tooltip>+ );+ }++ return badge;+}diff --git a/packages/web/src/components/wiki/git-history-panel.tsx b/packages/web/src/components/wiki/git-history-panel.tsxnew file mode 100644index 000000000..8c315fee2--- /dev/null+++ b/packages/web/src/components/wiki/git-history-panel.tsx@@ -0,0 +1,104 @@+import { GitCommit, User } from "lucide-react";+import { formatRelativeTime, truncatePath } from "@/lib/utils/format";+import type { GitMetadataResponse } from "@/lib/api/types";++interface GitHistoryPanelProps {+ git: GitMetadataResponse;+}++function AuthorAvatar({ name }: { name: string }) {+ const initials = name+ .split(/[\s@._-]+/)+ .filter(Boolean)+ .slice(0, 2)+ .map((p) => p[0]?.toUpperCase() ?? "")+ .join("");++ // Deterministic color from name+ let hash = 0;+ for (let i = 0; i < name.length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash);+ const colors = [+ "bg-blue-500", "bg-purple-500", "bg-green-500", "bg-yellow-500",+ "bg-pink-500", "bg-indigo-500", "bg-teal-500", "bg-orange-500",+ ];+ const color = colors[Math.abs(hash) % colors.length];++ return (+ <div+ className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[9px] font-semibold text-white ${color}`}+ aria-label={name}+ title={name}+ >+ {initials || <User className="h-3 w-3" />}+ </div>+ );+}++export function GitHistoryPanel({ git }: GitHistoryPanelProps) {+ const commits = git.significant_commits ?? [];++ return (+ <div className="space-y-4">+ {/* Top authors */}+ {git.top_authors && git.top_authors.length > 0 && (+ <div>+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ Authors+ </p>+ <div className="space-y-1.5">+ {git.top_authors.slice(0, 4).map((author) => (+ <div key={author.email} className="flex items-center gap-2 text-xs">+ <AuthorAvatar name={author.name} />+ <span className="flex-1 truncate text-[var(--color-text-secondary)]">+ {author.name}+ </span>+ <span className="text-[var(--color-text-tertiary)] tabular-nums shrink-0">+ {Math.round(author.pct * 100)}%+ </span>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Recent commits */}+ {commits.length > 0 && (+ <div>+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ Recent Commits+ </p>+ <ul className="space-y-2.5">+ {commits.slice(0, 6).map((commit) => (+ <li key={commit.sha} className="flex gap-2 min-w-0">+ <div className="flex flex-col items-center shrink-0">+ <GitCommit className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] mt-0.5" />+ <div className="w-px flex-1 bg-[var(--color-border-default)] mt-1" />+ </div>+ <div className="min-w-0 pb-2">+ <p className="text-xs text-[var(--color-text-secondary)] leading-snug line-clamp-2 break-words">+ {commit.message}+ </p>+ <div className="flex items-center gap-1.5 mt-0.5 flex-wrap">+ <span className="font-mono text-[10px] text-[var(--color-accent-primary)]">+ {commit.sha.slice(0, 7)}+ </span>+ <span className="text-[10px] text-[var(--color-text-tertiary)] truncate max-w-[80px]">+ {commit.author}+ </span>+ <span className="text-[10px] text-[var(--color-text-tertiary)]">+ {formatRelativeTime(commit.date)}+ </span>+ </div>+ </div>+ </li>+ ))}+ </ul>+ </div>+ )}++ {commits.length === 0 && (+ <p className="text-xs text-[var(--color-text-tertiary)]">No commit history available.</p>+ )}+ </div>+ );+}diff --git a/packages/web/src/components/wiki/mermaid-diagram.tsx b/packages/web/src/components/wiki/mermaid-diagram.tsxnew file mode 100644index 000000000..ca6ed9fd6--- /dev/null+++ b/packages/web/src/components/wiki/mermaid-diagram.tsx@@ -0,0 +1,56 @@+"use client";++import { useEffect, useRef, useState } from "react";++interface Props {+ chart: string;+}++export function MermaidDiagram({ chart }: Props) {+ const ref = useRef<HTMLDivElement>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ if (!ref.current) return;+ const el = ref.current;++ // Dynamic import avoids SSR issues with mermaid+ import("mermaid").then(({ default: mermaid }) => {+ mermaid.initialize({+ startOnLoad: false,+ theme: "dark",+ themeVariables: {+ background: "var(--color-bg-surface)",+ primaryColor: "#5B9CF6",+ primaryTextColor: "#e2e8f0",+ lineColor: "#334155",+ },+ });++ const id = `mermaid-${Math.random().toString(36).slice(2)}`;+ mermaid+ .render(id, chart)+ .then(({ svg }) => {+ el.innerHTML = svg;+ })+ .catch((e: unknown) => {+ setError(e instanceof Error ? e.message : "Diagram render failed");+ });+ });+ }, [chart]);++ if (error) {+ return (+ <div className="rounded border border-[var(--color-border-default)] p-3 text-xs text-[var(--color-outdated)]">+ Mermaid error: {error}+ </div>+ );+ }++ return (+ <div+ ref={ref}+ className="my-4 flex justify-center overflow-x-auto rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4"+ />+ );+}diff --git a/packages/web/src/components/wiki/regenerate-button.tsx b/packages/web/src/components/wiki/regenerate-button.tsxnew file mode 100644index 000000000..450113cf4--- /dev/null+++ b/packages/web/src/components/wiki/regenerate-button.tsx@@ -0,0 +1,74 @@+"use client";++import { useState } from "react";+import { toast } from "sonner";+import { RefreshCw } from "lucide-react";+import { useSWRConfig } from "swr";+import { regeneratePage } from "@/lib/api/pages";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { GenerationProgress } from "@/components/jobs/generation-progress";++interface Props {+ pageId: string;+ repoId: string;+}++export function RegenerateButton({ pageId, repoId }: Props) {+ const { mutate } = useSWRConfig();+ const [loading, setLoading] = useState(false);+ const [jobId, setJobId] = useState<string | null>(null);++ async function handleRegenerate() {+ setLoading(true);+ try {+ const result = await regeneratePage(pageId);+ setJobId(result.job_id);+ toast.info("Regeneration queued");+ } catch (e) {+ toast.error("Failed to queue regeneration", {+ description: e instanceof Error ? e.message : undefined,+ });+ } finally {+ setLoading(false);+ }+ }++ function handleDone() {+ // Revalidate the page data so confidence badge and content refresh+ mutate(`/api/pages/lookup?page_id=${pageId}`);+ setJobId(null);+ }++ return (+ <>+ <Button+ variant="ghost"+ size="sm"+ onClick={handleRegenerate}+ disabled={loading || !!jobId}+ className="h-7 gap-1.5 text-xs"+ aria-label="Regenerate this page"+ >+ <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />+ <span className="hidden sm:inline">Regenerate</span>+ </Button>++ <Dialog open={!!jobId} onOpenChange={(v) => { if (!v) setJobId(null); }}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Regenerating Page</DialogTitle>+ </DialogHeader>+ {jobId && (+ <GenerationProgress jobId={jobId} onDone={handleDone} />+ )}+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/packages/web/src/components/wiki/table-of-contents.tsx b/packages/web/src/components/wiki/table-of-contents.tsxnew file mode 100644index 000000000..2a7ee7215--- /dev/null+++ b/packages/web/src/components/wiki/table-of-contents.tsx@@ -0,0 +1,80 @@+"use client";++import { useEffect, useState } from "react";+import { cn } from "@/lib/utils/cn";++interface Heading {+ id: string;+ text: string;+ level: number;+}++function extractHeadings(content: string): Heading[] {+ const lines = content.split("\n");+ const headings: Heading[] = [];+ for (const line of lines) {+ const match = line.match(/^(#{1,3})\s+(.+)$/);+ if (match) {+ const text = match[2].trim();+ const id = text+ .toLowerCase()+ .replace(/[^\w\s-]/g, "")+ .replace(/\s+/g, "-");+ headings.push({ id, text, level: match[1].length });+ }+ }+ return headings;+}++export function TableOfContents({ content }: { content: string }) {+ const [activeId, setActiveId] = useState<string>("");+ const headings = extractHeadings(content);++ useEffect(() => {+ const observer = new IntersectionObserver(+ (entries) => {+ for (const entry of entries) {+ if (entry.isIntersecting) {+ setActiveId(entry.target.id);+ }+ }+ },+ { rootMargin: "0px 0px -70% 0px" },+ );++ headings.forEach(({ id }) => {+ const el = document.getElementById(id);+ if (el) observer.observe(el);+ });++ return () => observer.disconnect();+ }, [headings]);++ if (headings.length < 2) return null;++ return (+ <nav aria-label="Table of contents">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">+ Contents+ </p>+ <ul className="space-y-1">+ {headings.map(({ id, text, level }) => (+ <li key={id}>+ <a+ href={`#${id}`}+ className={cn(+ "block text-xs leading-snug transition-colors hover:text-[var(--color-text-primary)]",+ level === 1 ? "pl-0" : level === 2 ? "pl-2" : "pl-4",+ activeId === id+ ? "text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-tertiary)]",+ )}+ >+ {text}+ </a>+ </li>+ ))}+ </ul>+ </nav>+ );+}diff --git a/packages/web/src/components/wiki/wiki-renderer.tsx b/packages/web/src/components/wiki/wiki-renderer.tsxnew file mode 100644index 000000000..c61118da3--- /dev/null+++ b/packages/web/src/components/wiki/wiki-renderer.tsx@@ -0,0 +1,174 @@+import { MDXRemote } from "next-mdx-remote/rsc";+import { codeToHtml } from "shiki";+import { CodeBlock } from "./code-block";+import { MermaidDiagram } from "./mermaid-diagram";++// ---------------------------------------------------------------------------+// Custom MDX components+// ---------------------------------------------------------------------------++const mdxComponents = {+ // Code blocks — pass Shiki-highlighted HTML via a server action wrapper+ // The actual Shiki call happens in the pre/code override below.+ h1: (props: React.HTMLAttributes<HTMLHeadingElement>) => (+ <h1 className="mt-8 mb-4 text-xl font-semibold text-[var(--color-text-primary)] first:mt-0" {...props} />+ ),+ h2: (props: React.HTMLAttributes<HTMLHeadingElement>) => (+ <h2 className="mt-6 mb-3 text-lg font-semibold text-[var(--color-text-primary)]" {...props} />+ ),+ h3: (props: React.HTMLAttributes<HTMLHeadingElement>) => (+ <h3 className="mt-5 mb-2 text-base font-semibold text-[var(--color-text-primary)]" {...props} />+ ),+ p: (props: React.HTMLAttributes<HTMLParagraphElement>) => (+ <p className="mb-4 text-sm leading-7 text-[var(--color-text-secondary)]" {...props} />+ ),+ ul: (props: React.HTMLAttributes<HTMLUListElement>) => (+ <ul className="mb-4 ml-4 space-y-1 list-disc text-sm text-[var(--color-text-secondary)]" {...props} />+ ),+ ol: (props: React.HTMLAttributes<HTMLOListElement>) => (+ <ol className="mb-4 ml-4 space-y-1 list-decimal text-sm text-[var(--color-text-secondary)]" {...props} />+ ),+ li: (props: React.HTMLAttributes<HTMLLIElement>) => (+ <li className="leading-6" {...props} />+ ),+ blockquote: (props: React.HTMLAttributes<HTMLQuoteElement>) => (+ <blockquote+ className="my-4 border-l-2 border-[var(--color-accent-primary)] pl-4 text-sm italic text-[var(--color-text-tertiary)]"+ {...props}+ />+ ),+ table: (props: React.HTMLAttributes<HTMLTableElement>) => (+ <div className="my-4 overflow-x-auto rounded border border-[var(--color-border-default)]">+ <table className="w-full text-sm" {...props} />+ </div>+ ),+ thead: (props: React.HTMLAttributes<HTMLTableSectionElement>) => (+ <thead className="bg-[var(--color-bg-elevated)]" {...props} />+ ),+ th: (props: React.HTMLAttributes<HTMLTableCellElement>) => (+ <th+ className="px-4 py-2 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider"+ {...props}+ />+ ),+ td: (props: React.HTMLAttributes<HTMLTableCellElement>) => (+ <td+ className="px-4 py-2 text-sm text-[var(--color-text-secondary)] border-t border-[var(--color-border-default)]"+ {...props}+ />+ ),+ hr: () => <hr className="my-6 border-[var(--color-border-default)]" />,+ a: (props: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (+ <a+ className="text-[var(--color-accent-primary)] underline underline-offset-2 hover:opacity-80 transition-opacity"+ {...props}+ />+ ),+ strong: (props: React.HTMLAttributes<HTMLElement>) => (+ <strong className="font-semibold text-[var(--color-text-primary)]" {...props} />+ ),+ code: (props: React.HTMLAttributes<HTMLElement>) => (+ <code+ className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs font-mono text-[var(--color-accent-primary)]"+ {...props}+ />+ ),+};++// ---------------------------------------------------------------------------+// WikiRenderer — server component+// ---------------------------------------------------------------------------++interface Props {+ content: string;+}++export async function WikiRenderer({ content }: Props) {+ // Pre-process fenced code blocks so we can pass Shiki-rendered HTML.+ // We replace ```lang\ncode\n``` with a <ShikiBlock> JSX component call+ // that embeds pre-rendered HTML as a prop. This avoids any client-side+ // Shiki import.+ const preprocessed = await preprocessCodeBlocks(content);++ return (+ <MDXRemote+ source={preprocessed.source}+ components={{+ ...mdxComponents,+ // ShikiBlock is injected by the preprocessor+ ShikiBlock: ({ html, code, lang }: { html: string; code: string; lang: string }) => (+ <CodeBlock html={html} code={code} language={lang} />+ ),+ // MermaidBlock renders Mermaid diagrams client-side+ MermaidBlock: ({ chart }: { chart: string }) => (+ <MermaidDiagram chart={chart} />+ ),+ }}+ options={{+ parseFrontmatter: false,+ mdxOptions: {+ remarkPlugins: [],+ rehypePlugins: [],+ },+ }}+ />+ );+}++// ---------------------------------------------------------------------------+// Server-side preprocessor: replace fenced code blocks with JSX components+// ---------------------------------------------------------------------------++interface Preprocessed {+ source: string;+}++async function preprocessCodeBlocks(content: string): Promise<Preprocessed> {+ // Match fenced code blocks: ```lang\ncode\n```+ const fenceRe = /```(\w*)\n([\s\S]*?)```/g;+ const replacements: Array<{ placeholder: string; jsx: string }> = [];++ let match;+ let idx = 0;+ while ((match = fenceRe.exec(content)) !== null) {+ const lang = match[1] || "text";+ const code = match[2];++ let html = "";+ try {+ if (lang === "mermaid") {+ // Mermaid diagrams rendered client-side+ const chart = JSON.stringify(code);+ const placeholder = `PLACEHOLDER_${idx++}`;+ replacements.push({+ placeholder: `\`\`\`${lang}\n${code}\`\`\``,+ jsx: `<MermaidBlock chart={${chart}} />`,+ });+ continue;+ }++ html = await codeToHtml(code, {+ lang: lang as Parameters<typeof codeToHtml>[1]["lang"],+ theme: "vesper",+ });+ } catch {+ // Unknown language — fall back to plain pre+ html = `<pre><code>${code.replace(/</g, "<")}</code></pre>`;+ }++ const htmlProp = JSON.stringify(html);+ const codeProp = JSON.stringify(code);+ replacements.push({+ placeholder: `\`\`\`${lang}\n${code}\`\`\``,+ jsx: `<ShikiBlock html={${htmlProp}} code={${codeProp}} lang="${lang}" />`,+ });+ idx++;+ }++ let source = content;+ for (const { placeholder, jsx } of replacements) {+ source = source.replace(placeholder, jsx);+ }++ return { source };+}diff --git a/packages/web/src/styles/globals.css b/packages/web/src/styles/globals.cssnew file mode 100644index 000000000..52d2befd8--- /dev/null+++ b/packages/web/src/styles/globals.css@@ -0,0 +1,267 @@+@import "tailwindcss";+@plugin "@tailwindcss/typography";++/*+ * WikiCode Design System+ * "Linear's exactness + Stripe's docs quality"+ * Dark mode primary. No light mode in v1.+ */++@theme {+ /* ------------------------------------------------------------------ */+ /* Core Surfaces */+ /* ------------------------------------------------------------------ */+ --color-bg-root: #0a0a0a;+ --color-bg-surface: #111111;+ --color-bg-elevated: #171717;+ --color-bg-overlay: #1a1a1a;+ --color-bg-inset: #080808;++ /* ------------------------------------------------------------------ */+ /* Borders */+ /* ------------------------------------------------------------------ */+ --color-border-default: rgba(255, 255, 255, 0.08);+ --color-border-hover: rgba(255, 255, 255, 0.15);+ --color-border-active: rgba(255, 255, 255, 0.25);++ /* ------------------------------------------------------------------ */+ /* Text */+ /* ------------------------------------------------------------------ */+ --color-text-primary: #f0f0f0;+ --color-text-secondary: #a0a0a0;+ --color-text-tertiary: #666666;+ --color-text-inverse: #0a0a0a;++ /* ------------------------------------------------------------------ */+ /* Accent — WikiCode Blue */+ /* ------------------------------------------------------------------ */+ --color-accent-primary: #5b9cf6;+ --color-accent-hover: #7bb3f7;+ --color-accent-muted: rgba(91, 156, 246, 0.15);++ /* ------------------------------------------------------------------ */+ /* Confidence System */+ /* ------------------------------------------------------------------ */+ --color-confidence-fresh: #22c55e;+ --color-confidence-stale: #eab308;+ --color-confidence-outdated: #ef4444;++ /* ------------------------------------------------------------------ */+ /* Semantic */+ /* ------------------------------------------------------------------ */+ --color-success: #22c55e;+ --color-warning: #eab308;+ --color-error: #ef4444;+ --color-info: #5b9cf6;++ /* ------------------------------------------------------------------ */+ /* Language Colors (graph nodes) */+ /* ------------------------------------------------------------------ */+ --color-lang-python: #3776ab;+ --color-lang-typescript: #3178c6;+ --color-lang-go: #00add8;+ --color-lang-rust: #dea584;+ --color-lang-java: #ed8b00;+ --color-lang-cpp: #00599c;+ --color-lang-config: #6b7280;+ --color-lang-other: #8b5cf6;++ /* ------------------------------------------------------------------ */+ /* Edge Colors (graph edges) */+ /* ------------------------------------------------------------------ */+ --color-edge-imports: #5b9cf6;+ --color-edge-calls: #22c55e;+ --color-edge-inherits: #a855f7;+ --color-edge-implements: #ec4899;+ --color-edge-co-change: #8b5cf6;++ /* ------------------------------------------------------------------ */+ /* Typography */+ /* ------------------------------------------------------------------ */+ --font-sans: "Geist", "Inter", -apple-system, BlinkMacSystemFont, sans-serif;+ --font-mono: "Geist Mono", "JetBrains Mono", "Fira Code", monospace;++ --text-xs: 0.75rem;+ --text-sm: 0.8125rem;+ --text-base: 0.875rem;+ --text-lg: 1rem;+ --text-xl: 1.25rem;+ --text-2xl: 1.5rem;+ --text-3xl: 2rem;++ --leading-tight: 1.3;+ --leading-normal: 1.5;+ --leading-relaxed: 1.75;++ /* ------------------------------------------------------------------ */+ /* Spacing (4px base grid) */+ /* ------------------------------------------------------------------ */+ --spacing-1: 0.25rem;+ --spacing-2: 0.5rem;+ --spacing-3: 0.75rem;+ --spacing-4: 1rem;+ --spacing-5: 1.25rem;+ --spacing-6: 1.5rem;+ --spacing-8: 2rem;+ --spacing-10: 2.5rem;+ --spacing-12: 3rem;+ --spacing-16: 4rem;++ /* ------------------------------------------------------------------ */+ /* Radii */+ /* ------------------------------------------------------------------ */+ --radius-sm: 4px;+ --radius-md: 6px;+ --radius-lg: 8px;+ --radius-xl: 12px;++ /* ------------------------------------------------------------------ */+ /* Z-Index Scale */+ /* ------------------------------------------------------------------ */+ --z-base: 0;+ --z-elevated: 10;+ --z-dropdown: 20;+ --z-sidebar: 30;+ --z-modal: 40;+ --z-command: 50;+ --z-toast: 60;++ /* ------------------------------------------------------------------ */+ /* Layout */+ /* ------------------------------------------------------------------ */+ --sidebar-width: 260px;+ --context-panel-width: 280px;+ --content-max-width: 768px;++ /* ------------------------------------------------------------------ */+ /* Animation */+ /* ------------------------------------------------------------------ */+ --ease-out: cubic-bezier(0.16, 1, 0.3, 1);+ --ease-in: cubic-bezier(0.7, 0, 0.84, 0);+ --ease-inout: cubic-bezier(0.87, 0, 0.13, 1);+ --duration-fast: 150ms;+ --duration-normal: 250ms;+ --duration-slow: 400ms;+}++/* -------------------------------------------------------------------- */+/* Base Styles */+/* -------------------------------------------------------------------- */++html {+ color-scheme: dark;+}++body {+ background-color: var(--color-bg-root);+ color: var(--color-text-primary);+ font-family: var(--font-sans);+ font-size: var(--text-base);+ line-height: var(--leading-normal);+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+}++/* -------------------------------------------------------------------- */+/* Scrollbar */+/* -------------------------------------------------------------------- */++::-webkit-scrollbar {+ width: 6px;+ height: 6px;+}++::-webkit-scrollbar-track {+ background: transparent;+}++::-webkit-scrollbar-thumb {+ background: rgba(255, 255, 255, 0.1);+ border-radius: 3px;+}++::-webkit-scrollbar-thumb:hover {+ background: rgba(255, 255, 255, 0.2);+}++/* -------------------------------------------------------------------- */+/* Focus Ring */+/* -------------------------------------------------------------------- */++:focus-visible {+ outline: 2px solid var(--color-accent-primary);+ outline-offset: 2px;+}++/* -------------------------------------------------------------------- */+/* Selection */+/* -------------------------------------------------------------------- */++::selection {+ background-color: var(--color-accent-muted);+ color: var(--color-text-primary);+}++/* -------------------------------------------------------------------- */+/* Reduced Motion */+/* -------------------------------------------------------------------- */++@media (prefers-reduced-motion: reduce) {+ *,+ *::before,+ *::after {+ animation-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0.01ms !important;+ scroll-behavior: auto !important;+ }+}++/* -------------------------------------------------------------------- */+/* Typography: prose overrides for wiki content */+/* -------------------------------------------------------------------- */++.prose {+ --tw-prose-body: var(--color-text-secondary);+ --tw-prose-headings: var(--color-text-primary);+ --tw-prose-links: var(--color-accent-primary);+ --tw-prose-code: var(--color-text-primary);+ --tw-prose-pre-bg: var(--color-bg-inset);+ --tw-prose-pre-code: var(--color-text-primary);+ --tw-prose-bold: var(--color-text-primary);+ --tw-prose-counters: var(--color-text-tertiary);+ --tw-prose-bullets: var(--color-text-tertiary);+ --tw-prose-hr: var(--color-border-default);+ --tw-prose-quotes: var(--color-text-secondary);+ --tw-prose-quote-borders: var(--color-border-default);+ --tw-prose-th-borders: var(--color-border-default);+ --tw-prose-td-borders: var(--color-border-default);+}++.prose code {+ font-family: var(--font-mono);+ font-size: 0.85em;+}++.prose pre {+ border: 1px solid var(--color-border-default);+ border-radius: var(--radius-lg);+}++.prose a {+ text-decoration: none;+ border-bottom: 1px solid transparent;+ transition: border-color var(--duration-fast) var(--ease-out);+}++.prose a:hover {+ border-bottom-color: var(--color-accent-primary);+}++/* -------------------------------------------------------------------- */+/* Tabular numbers for data tables */+/* -------------------------------------------------------------------- */++.tabular-nums {+ font-variant-numeric: tabular-nums;+}diff --git a/packages/web/tsconfig.json b/packages/web/tsconfig.jsonnew file mode 100644index 000000000..b8cdcc79e--- /dev/null+++ b/packages/web/tsconfig.json@@ -0,0 +1,23 @@+{+ "compilerOptions": {+ "target": "ES2017",+ "lib": ["dom", "dom.iterable", "esnext"],+ "allowJs": true,+ "skipLibCheck": true,+ "strict": true,+ "noEmit": true,+ "esModuleInterop": true,+ "module": "esnext",+ "moduleResolution": "bundler",+ "resolveJsonModule": true,+ "isolatedModules": true,+ "jsx": "preserve",+ "incremental": true,+ "plugins": [{ "name": "next" }],+ "paths": {+ "@/*": ["./src/*"]+ }+ },+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],+ "exclude": ["node_modules"]+}diff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 000000000..4dd35fef9--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,87 @@+[tool.uv.workspace]+members = [+ "packages/core",+ "packages/cli",+ "packages/server",+]++[tool.uv]+dev-dependencies = [+ "pytest>=8,<9",+ "pytest-asyncio>=0.23,<1",+ "pytest-snapshot>=0.9,<1",+ "respx>=0.21,<1",+ "time-machine>=2.14,<3",+ "ruff>=0.6,<1",+ "mypy>=1.11,<2",+ "types-networkx>=3.3,<4",+ "httpx>=0.27,<1",+]++# ---------------------------------------------------------------------------+# Ruff — linter + formatter+# ---------------------------------------------------------------------------+[tool.ruff]+target-version = "py311"+line-length = 100++[tool.ruff.lint]+select = [+ "E", # pycodestyle errors+ "F", # pyflakes+ "I", # isort+ "N", # pep8-naming+ "UP", # pyupgrade+ "B", # flake8-bugbear+ "SIM", # flake8-simplify+ "RUF", # ruff-specific rules+]+ignore = [+ "E501", # line too long (handled by formatter)+]++[tool.ruff.lint.isort]+known-first-party = ["wikicode"]++# ---------------------------------------------------------------------------+# mypy — strict type checking+# ---------------------------------------------------------------------------+[tool.mypy]+python_version = "3.11"+strict = true+warn_return_any = true+warn_unused_configs = true+warn_unused_ignores = true+show_error_codes = true+namespace_packages = true+explicit_package_bases = true++# Per-module overrides for third-party packages without stubs+[[tool.mypy.overrides]]+module = [+ "tree_sitter",+ "tree_sitter_python",+ "tree_sitter_typescript",+ "tree_sitter_go",+ "tree_sitter_rust",+ "tree_sitter_java",+ "tree_sitter_cpp",+ "lancedb",+ "pgvector",+ "litellm",+ "apscheduler.*",+ "networkx",+ "pathspec",+ "structlog",+ "mcp",+]+ignore_missing_imports = true++# ---------------------------------------------------------------------------+# pytest+# ---------------------------------------------------------------------------+[tool.pytest.ini_options]+asyncio_mode = "auto"+testpaths = ["tests"]+addopts = "-v --tb=short"+pythonpath = ["."]diff --git a/tests/conftest.py b/tests/conftest.pynew file mode 100644index 000000000..e59a31fc7--- /dev/null+++ b/tests/conftest.py@@ -0,0 +1,30 @@+"""Root test configuration — fixtures available to all test modules."""++from __future__ import annotations++from pathlib import Path++import pytest++[email protected](scope="session")+def repo_root() -> Path:+ """Absolute path to the repository root."""+ return Path(__file__).parent.parent++[email protected](scope="session")+def sample_repo_path(repo_root: Path) -> Path:+ """Path to the multi-language sample repository used in integration tests."""+ path = repo_root / "tests" / "fixtures" / "sample_repo"+ assert path.exists(), (+ f"Sample repo not found at {path}. "+ "Run 'make install' to ensure test fixtures are in place."+ )+ return path++[email protected](scope="session")+def fixtures_dir(repo_root: Path) -> Path:+ """Path to the tests/fixtures/ directory."""+ return repo_root / "tests" / "fixtures"diff --git a/tests/e2e/__init__.py b/tests/e2e/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/fixtures/sample_repo/.gitignore b/tests/fixtures/sample_repo/.gitignorenew file mode 100644index 000000000..215cc8b74--- /dev/null+++ b/tests/fixtures/sample_repo/.gitignore@@ -0,0 +1,27 @@+# Build outputs+dist/+build/+target/+*.o+*.a+*.so++# Python+__pycache__/+*.pyc+*.pyo+.venv/+venv/+*.egg-info/++# Node+node_modules/+.next/++# Go+vendor/++# IDE+.idea/+.vscode/+*.DS_Storediff --git a/tests/fixtures/sample_repo/Dockerfile b/tests/fixtures/sample_repo/Dockerfilenew file mode 100644index 000000000..ff3f27b3c--- /dev/null+++ b/tests/fixtures/sample_repo/Dockerfile@@ -0,0 +1,31 @@+# Multi-stage Dockerfile for the sample calculator service.+# Stage 1: build the Go service.+# Stage 2: run the Python service alongside the Go binary.++# ---------- Stage 1: Go build ----------+FROM golang:1.21-alpine AS go-builder++WORKDIR /src/go_pkg+COPY go_pkg/go.mod ./+COPY go_pkg/ ./+RUN go build -o /bin/calculator ./...++# ---------- Stage 2: Python runtime ----------+FROM python:3.11-slim AS runtime++WORKDIR /app++# Install Python dependencies+COPY python_pkg/ ./python_pkg/+RUN pip install --no-cache-dir -e ./python_pkg++# Copy the compiled Go binary+COPY --from=go-builder /bin/calculator /usr/local/bin/calculator++EXPOSE 8080++ENV PYTHONUNBUFFERED=1+ENV LOG_LEVEL=info++ENTRYPOINT ["python", "-m", "python_pkg"]+CMD ["--host", "0.0.0.0", "--port", "8080"]diff --git a/tests/fixtures/sample_repo/Makefile b/tests/fixtures/sample_repo/Makefilenew file mode 100644index 000000000..f5a844b33--- /dev/null+++ b/tests/fixtures/sample_repo/Makefile@@ -0,0 +1,11 @@+.PHONY: build test clean++build:+ cd typescript_pkg && npm run build++test:+ cd typescript_pkg && npm run type-check++clean:+ rm -rf typescript_pkg/dist+ find . -name __pycache__ -exec rm -rf {} + 2>/dev/null || truediff --git a/tests/fixtures/sample_repo/README.md b/tests/fixtures/sample_repo/README.mdnew file mode 100644index 000000000..20f792c6d--- /dev/null+++ b/tests/fixtures/sample_repo/README.md@@ -0,0 +1,34 @@+# sample_repo++A deliberately small, multi-language repository used as a test fixture for WikiCode.++It contains real Python and TypeScript code with realistic module structure:+imports, classes, functions, type annotations, and inter-module dependencies.++## Structure++```+sample_repo/+├── python_pkg/ # Python: calculator, models, utils+│ ├── __init__.py+│ ├── calculator.py # Core arithmetic operations+│ ├── models.py # Data models (dataclasses)+│ └── utils.py # Shared helper utilities+├── typescript_pkg/ # TypeScript: API client + types+│ ├── src/+│ │ ├── client.ts # HTTP API client+│ │ ├── types.ts # Shared TypeScript interfaces+│ │ └── utils.ts # Utility functions+│ ├── package.json+│ └── tsconfig.json+├── Makefile+└── .gitignore+```++## Purpose++WikiCode runs its integration tests against this fixture:+- AST parser: extract all symbols from Python + TypeScript files+- Graph builder: build dependency graph, compute PageRank+- Change detector: diff between fixture versions+- Page generator: generate documentation pages (using MockProvider)diff --git a/tests/fixtures/sample_repo/api/openapi.yaml b/tests/fixtures/sample_repo/api/openapi.yamlnew file mode 100644index 000000000..6195227e4--- /dev/null+++ b/tests/fixtures/sample_repo/api/openapi.yaml@@ -0,0 +1,127 @@+openapi: "3.0.3"+info:+ title: Sample Calculator API+ version: "1.0.0"+ description: >+ A simple arithmetic API used as a fixture for WikiCode ingestion tests.+ Supports four operations: add, subtract, multiply, divide.++paths:+ /calculate:+ post:+ operationId: calculate+ summary: Perform a single arithmetic calculation+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CalculationRequest'+ responses:+ '200':+ description: Successful calculation+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CalculationResponse'+ '400':+ description: Invalid request+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ApiError'+ '422':+ description: Division by zero+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ApiError'++ /history:+ get:+ operationId: getHistory+ summary: Retrieve calculation history+ parameters:+ - in: query+ name: page+ schema:+ type: integer+ default: 0+ - in: query+ name: page_size+ schema:+ type: integer+ default: 20+ responses:+ '200':+ description: Paginated history+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CalculationHistory'++ /health:+ get:+ operationId: healthCheck+ summary: API health check+ responses:+ '200':+ description: API is healthy+ content:+ application/json:+ schema:+ type: object+ properties:+ status:+ type: string+ example: ok++components:+ schemas:+ CalculationRequest:+ type: object+ required: [operation, x, y]+ properties:+ operation:+ type: string+ enum: [add, subtract, multiply, divide]+ x:+ type: number+ y:+ type: number++ CalculationResponse:+ type: object+ properties:+ operation:+ type: string+ x:+ type: number+ y:+ type: number+ result:+ type: number++ CalculationHistory:+ type: object+ properties:+ entries:+ type: array+ items:+ $ref: '#/components/schemas/CalculationResponse'+ total:+ type: integer+ page:+ type: integer+ page_size:+ type: integer++ ApiError:+ type: object+ properties:+ status:+ type: integer+ message:+ type: string+ detail:+ type: stringdiff --git a/tests/fixtures/sample_repo/cpp_pkg/calculator.cpp b/tests/fixtures/sample_repo/cpp_pkg/calculator.cppnew file mode 100644index 000000000..ea5295354--- /dev/null+++ b/tests/fixtures/sample_repo/cpp_pkg/calculator.cpp@@ -0,0 +1,46 @@+#include "calculator.hpp"+#include <stdexcept>+#include <string>++namespace sample {++double Calculator::add(double x, double y) {+ double result = x + y;+ record(Operation::Add, x, y, result);+ return result;+}++double Calculator::subtract(double x, double y) {+ double result = x - y;+ record(Operation::Subtract, x, y, result);+ return result;+}++double Calculator::multiply(double x, double y) {+ double result = x * y;+ record(Operation::Multiply, x, y, result);+ return result;+}++double Calculator::divide(double x, double y) {+ if (y == 0.0) {+ throw std::invalid_argument("Division by zero");+ }+ double result = x / y;+ record(Operation::Divide, x, y, result);+ return result;+}++const std::vector<CalculationRecord>& Calculator::history() const {+ return history_;+}++void Calculator::clear_history() {+ history_.clear();+}++void Calculator::record(Operation op, double x, double y, double result) {+ history_.push_back(CalculationRecord{op, x, y, result});+}++} // namespace samplediff --git a/tests/fixtures/sample_repo/cpp_pkg/calculator.hpp b/tests/fixtures/sample_repo/cpp_pkg/calculator.hppnew file mode 100644index 000000000..ef65157a4--- /dev/null+++ b/tests/fixtures/sample_repo/cpp_pkg/calculator.hpp@@ -0,0 +1,46 @@+#pragma once++#include <stdexcept>+#include <vector>+#include "models.hpp"++namespace sample {++/**+ * @brief Stateful calculator with history recording.+ *+ * Performs the four basic arithmetic operations and maintains a list of+ * CalculationRecord entries for audit purposes.+ */+class Calculator {+public:+ Calculator() = default;++ /** Adds x and y, records and returns the result. */+ double add(double x, double y);++ /** Subtracts y from x, records and returns the result. */+ double subtract(double x, double y);++ /** Multiplies x by y, records and returns the result. */+ double multiply(double x, double y);++ /**+ * @brief Divides x by y.+ * @throws std::invalid_argument if y is zero.+ */+ double divide(double x, double y);++ /** Returns the history of all calculations. */+ const std::vector<CalculationRecord>& history() const;++ /** Clears all recorded calculations. */+ void clear_history();++private:+ std::vector<CalculationRecord> history_;++ void record(Operation op, double x, double y, double result);+};++} // namespace samplediff --git a/tests/fixtures/sample_repo/cpp_pkg/models.hpp b/tests/fixtures/sample_repo/cpp_pkg/models.hppnew file mode 100644index 000000000..2d7678664--- /dev/null+++ b/tests/fixtures/sample_repo/cpp_pkg/models.hpp@@ -0,0 +1,37 @@+#pragma once++#include <string>++namespace sample {++/** Arithmetic operation type. */+enum class Operation {+ Add,+ Subtract,+ Multiply,+ Divide,+};++/** Returns the display name of an operation. */+inline std::string operation_name(Operation op) {+ switch (op) {+ case Operation::Add: return "add";+ case Operation::Subtract: return "subtract";+ case Operation::Multiply: return "multiply";+ case Operation::Divide: return "divide";+ }+ return "unknown";+}++/** An immutable record of a single arithmetic calculation. */+struct CalculationRecord {+ Operation operation;+ double x;+ double y;+ double result;++ /** Returns a human-readable summary. */+ std::string summary() const;+};++} // namespace samplediff --git a/tests/fixtures/sample_repo/dead/unreachable_module.py b/tests/fixtures/sample_repo/dead/unreachable_module.pynew file mode 100644index 000000000..6d23c16db--- /dev/null+++ b/tests/fixtures/sample_repo/dead/unreachable_module.py@@ -0,0 +1,11 @@+"""This module is intentionally unreachable — used for dead code detection tests."""+++def orphaned_function():+ """No one calls this."""+ return 42+++class OrphanedClass:+ """No one imports this."""+ passdiff --git a/tests/fixtures/sample_repo/go_pkg/calculator/calculator.go b/tests/fixtures/sample_repo/go_pkg/calculator/calculator.gonew file mode 100644index 000000000..76024bace--- /dev/null+++ b/tests/fixtures/sample_repo/go_pkg/calculator/calculator.go@@ -0,0 +1,75 @@+// Package calculator provides stateful arithmetic operations with history.+package calculator++import (+ "errors"+ "fmt"++ "github.com/wikicode-ai/sample/types"+)++// ErrDivisionByZero is returned when a division-by-zero is attempted.+var ErrDivisionByZero = errors.New("division by zero")++// Calculator performs arithmetic operations and records their history.+type Calculator struct {+ history []types.CalculationRecord+}++// New returns a new, empty Calculator.+func New() *Calculator {+ return &Calculator{}+}++// Add returns the sum of the operands and appends the result to history.+func (c *Calculator) Add(ops types.Operands) (float64, error) {+ result := ops.X + ops.Y+ c.record(types.OpAdd, ops, result)+ return result, nil+}++// Subtract returns ops.X - ops.Y and appends the result to history.+func (c *Calculator) Subtract(ops types.Operands) (float64, error) {+ result := ops.X - ops.Y+ c.record(types.OpSubtract, ops, result)+ return result, nil+}++// Multiply returns the product of the operands.+func (c *Calculator) Multiply(ops types.Operands) (float64, error) {+ result := ops.X * ops.Y+ c.record(types.OpMultiply, ops, result)+ return result, nil+}++// Divide returns ops.X / ops.Y. Returns ErrDivisionByZero if ops.Y == 0.+func (c *Calculator) Divide(ops types.Operands) (float64, error) {+ if ops.Y == 0 {+ return 0, ErrDivisionByZero+ }+ result := ops.X / ops.Y+ c.record(types.OpDivide, ops, result)+ return result, nil+}++// History returns a copy of all calculation records.+func (c *Calculator) History() []types.CalculationRecord {+ out := make([]types.CalculationRecord, len(c.history))+ copy(out, c.history)+ return out+}++// ClearHistory removes all recorded calculations.+func (c *Calculator) ClearHistory() {+ c.history = c.history[:0]+}++// record appends a new entry to the internal history slice.+func (c *Calculator) record(op types.Operation, ops types.Operands, result float64) {+ c.history = append(c.history, types.CalculationRecord{+ Operation: op,+ Operands: ops,+ Result: result,+ Summary: fmt.Sprintf("%.2f %s %.2f = %.2f", ops.X, op, ops.Y, result),+ })+}diff --git a/tests/fixtures/sample_repo/go_pkg/go.mod b/tests/fixtures/sample_repo/go_pkg/go.modnew file mode 100644index 000000000..b20fff9ea--- /dev/null+++ b/tests/fixtures/sample_repo/go_pkg/go.mod@@ -0,0 +1,3 @@+module github.com/wikicode-ai/sample++go 1.21diff --git a/tests/fixtures/sample_repo/go_pkg/main.go b/tests/fixtures/sample_repo/go_pkg/main.gonew file mode 100644index 000000000..0ba0d1960--- /dev/null+++ b/tests/fixtures/sample_repo/go_pkg/main.go@@ -0,0 +1,39 @@+// Package main is the entry point for the sample Go calculator service.+// It wires together the calculator and types packages and exposes a simple+// command-line interface.+package main++import (+ "fmt"+ "os"++ "github.com/wikicode-ai/sample/calculator"+ "github.com/wikicode-ai/sample/types"+)++func main() {+ calc := calculator.New()+ result, err := calc.Add(types.Operands{X: 10, Y: 5})+ if err != nil {+ fmt.Fprintf(os.Stderr, "error: %v\n", err)+ os.Exit(1)+ }+ fmt.Printf("Result: %.2f\n", result)+}++// RunOperation executes a named arithmetic operation.+func RunOperation(name string, x, y float64) (float64, error) {+ calc := calculator.New()+ switch name {+ case "add":+ return calc.Add(types.Operands{X: x, Y: y})+ case "subtract":+ return calc.Subtract(types.Operands{X: x, Y: y})+ case "multiply":+ return calc.Multiply(types.Operands{X: x, Y: y})+ case "divide":+ return calc.Divide(types.Operands{X: x, Y: y})+ default:+ return 0, fmt.Errorf("unknown operation: %s", name)+ }+}diff --git a/tests/fixtures/sample_repo/go_pkg/types/types.go b/tests/fixtures/sample_repo/go_pkg/types/types.gonew file mode 100644index 000000000..dab1203fd--- /dev/null+++ b/tests/fixtures/sample_repo/go_pkg/types/types.go@@ -0,0 +1,34 @@+// Package types defines the shared domain types used across the sample service.+package types++// Operation represents a supported arithmetic operation.+type Operation string++const (+ OpAdd Operation = "add"+ OpSubtract Operation = "subtract"+ OpMultiply Operation = "multiply"+ OpDivide Operation = "divide"+)++// Operands holds the two numeric values for a binary arithmetic operation.+type Operands struct {+ X float64+ Y float64+}++// CalculationRecord is a single entry in a Calculator's history.+type CalculationRecord struct {+ Operation Operation+ Operands Operands+ Result float64+ Summary string+}++// Arithmetic defines the interface that any calculator implementation must satisfy.+type Arithmetic interface {+ Add(ops Operands) (float64, error)+ Subtract(ops Operands) (float64, error)+ Multiply(ops Operands) (float64, error)+ Divide(ops Operands) (float64, error)+}diff --git a/tests/fixtures/sample_repo/java_pkg/CalculationRecord.java b/tests/fixtures/sample_repo/java_pkg/CalculationRecord.javanew file mode 100644index 000000000..0f8c573b6--- /dev/null+++ b/tests/fixtures/sample_repo/java_pkg/CalculationRecord.java@@ -0,0 +1,34 @@+package com.wikicode.sample;++/**+ * An immutable record of a single arithmetic calculation.+ */+public final class CalculationRecord {++ private final Operation operation;+ private final double x;+ private final double y;+ private final double result;++ public CalculationRecord(Operation operation, double x, double y, double result) {+ this.operation = operation;+ this.x = x;+ this.y = y;+ this.result = result;+ }++ public Operation getOperation() { return operation; }+ public double getX() { return x; }+ public double getY() { return y; }+ public double getResult() { return result; }++ /** Returns a human-readable summary of this record. */+ public String getSummary() {+ return String.format("%.2f %s %.2f = %.2f", x, operation, y, result);+ }++ @Override+ public String toString() {+ return getSummary();+ }+}diff --git a/tests/fixtures/sample_repo/java_pkg/Calculator.java b/tests/fixtures/sample_repo/java_pkg/Calculator.javanew file mode 100644index 000000000..1115d7771--- /dev/null+++ b/tests/fixtures/sample_repo/java_pkg/Calculator.java@@ -0,0 +1,76 @@+package com.wikicode.sample;++import java.util.ArrayList;+import java.util.List;++/**+ * Stateful calculator that performs arithmetic operations and records history.+ *+ * <p>Wraps four basic operations (add, subtract, multiply, divide) and maintains+ * a list of {@link CalculationRecord} entries for audit purposes.+ */+public class Calculator {++ private final List<CalculationRecord> history = new ArrayList<>();++ /**+ * Adds {@code x} and {@code y}.+ *+ * @param x first operand+ * @param y second operand+ * @return the sum+ */+ public double add(double x, double y) {+ double result = x + y;+ record(Operation.ADD, x, y, result);+ return result;+ }++ /**+ * Subtracts {@code y} from {@code x}.+ *+ * @param x minuend+ * @param y subtrahend+ * @return the difference+ */+ public double subtract(double x, double y) {+ double result = x - y;+ record(Operation.SUBTRACT, x, y, result);+ return result;+ }++ /** Returns the product of {@code x} and {@code y}. */+ public double multiply(double x, double y) {+ double result = x * y;+ record(Operation.MULTIPLY, x, y, result);+ return result;+ }++ /**+ * Divides {@code x} by {@code y}.+ *+ * @throws ArithmeticException if {@code y} is zero+ */+ public double divide(double x, double y) {+ if (y == 0) {+ throw new ArithmeticException("Division by zero");+ }+ double result = x / y;+ record(Operation.DIVIDE, x, y, result);+ return result;+ }++ /** Returns an unmodifiable view of the calculation history. */+ public List<CalculationRecord> getHistory() {+ return List.copyOf(history);+ }++ /** Clears all recorded calculations. */+ public void clearHistory() {+ history.clear();+ }++ private void record(Operation op, double x, double y, double result) {+ history.add(new CalculationRecord(op, x, y, result));+ }+}diff --git a/tests/fixtures/sample_repo/java_pkg/Operation.java b/tests/fixtures/sample_repo/java_pkg/Operation.javanew file mode 100644index 000000000..bf3ab573e--- /dev/null+++ b/tests/fixtures/sample_repo/java_pkg/Operation.java@@ -0,0 +1,27 @@+package com.wikicode.sample;++/**+ * Enum representing the four supported arithmetic operations.+ */+public enum Operation {+ ADD("add"),+ SUBTRACT("subtract"),+ MULTIPLY("multiply"),+ DIVIDE("divide");++ private final String label;++ Operation(String label) {+ this.label = label;+ }++ /** Returns the lowercase label used in summaries. */+ public String getLabel() {+ return label;+ }++ @Override+ public String toString() {+ return label;+ }+}diff --git a/tests/fixtures/sample_repo/python_pkg/__init__.py b/tests/fixtures/sample_repo/python_pkg/__init__.pynew file mode 100644index 000000000..2779263c3--- /dev/null+++ b/tests/fixtures/sample_repo/python_pkg/__init__.py@@ -0,0 +1,21 @@+"""Sample Python package for WikiCode integration tests.++This package provides a simple calculator with data models and utilities.+It is intentionally small but realistic — covering classes, functions,+imports, type annotations, and docstrings.+"""++from python_pkg.calculator import Calculator, add, subtract, multiply, divide+from python_pkg.models import CalculationResult, Operation++__all__ = [+ "Calculator",+ "add",+ "subtract",+ "multiply",+ "divide",+ "CalculationResult",+ "Operation",+]++__version__ = "1.0.0"diff --git a/tests/fixtures/sample_repo/python_pkg/calculator.py b/tests/fixtures/sample_repo/python_pkg/calculator.pynew file mode 100644index 000000000..3b36aa447--- /dev/null+++ b/tests/fixtures/sample_repo/python_pkg/calculator.py@@ -0,0 +1,188 @@+"""Core arithmetic operations for the sample calculator package.++Provides both module-level functions and a stateful Calculator class.+The Calculator class maintains a history of all calculations performed.++This file is intentionally written to exercise the AST parser:+ - Module-level functions (add, subtract, multiply, divide)+ - A class with methods and properties (Calculator)+ - Type annotations on all signatures+ - Docstrings on all public symbols+ - Imports from sibling modules (models, utils)+ - Custom exception classes+"""++from __future__ import annotations++from python_pkg.models import CalculationHistory, CalculationResult, Operation+from python_pkg.utils import is_close_to_zero, round_result+++class DivisionByZeroError(ArithmeticError):+ """Raised when a division by zero is attempted.++ Separate from Python's built-in ZeroDivisionError to allow callers+ to catch WikiCode-domain errors independently of system errors.+ """+++def add(x: float, y: float) -> float:+ """Return the sum of x and y.++ Args:+ x: First operand.+ y: Second operand.++ Returns:+ x + y+ """+ return round_result(x + y)+++def subtract(x: float, y: float) -> float:+ """Return the difference of x and y (x - y).++ Args:+ x: Minuend.+ y: Subtrahend.++ Returns:+ x - y+ """+ return round_result(x - y)+++def multiply(x: float, y: float) -> float:+ """Return the product of x and y.++ Args:+ x: First factor.+ y: Second factor.++ Returns:+ x * y+ """+ return round_result(x * y)+++def divide(x: float, y: float) -> float:+ """Return the quotient of x divided by y.++ Args:+ x: Dividend.+ y: Divisor. Must not be zero.++ Returns:+ x / y++ Raises:+ DivisionByZeroError: If y is zero or very close to zero.+ """+ if is_close_to_zero(y):+ raise DivisionByZeroError(f"Cannot divide {x} by zero (got y={y})")+ return round_result(x / y)+++class Calculator:+ """Stateful calculator that records the history of all calculations.++ The Calculator wraps the module-level arithmetic functions and+ records each operation as a CalculationResult in its history.++ Example:+ calc = Calculator()+ result = calc.add(10, 5) # 15.0+ result = calc.divide(10, 4) # 2.5+ print(calc.history.total_calculations) # 2+ print(calc.last_result.summary) # "10 divide 4 = 2.5"+ """++ def __init__(self) -> None:+ self._history = CalculationHistory()++ @property+ def history(self) -> CalculationHistory:+ """The full history of calculations performed by this instance."""+ return self._history++ @property+ def last_result(self) -> CalculationResult | None:+ """The most recent CalculationResult, or None if no calculations yet."""+ return self._history.last()++ def add(self, x: float, y: float) -> float:+ """Add x and y, record the result in history.++ Args:+ x: First operand.+ y: Second operand.++ Returns:+ The sum x + y.+ """+ value = add(x, y)+ self._history.append(+ CalculationResult(operation=Operation.ADD, operands=[x, y], result=value)+ )+ return value++ def subtract(self, x: float, y: float) -> float:+ """Subtract y from x, record the result in history.++ Args:+ x: Minuend.+ y: Subtrahend.++ Returns:+ The difference x - y.+ """+ value = subtract(x, y)+ self._history.append(+ CalculationResult(+ operation=Operation.SUBTRACT, operands=[x, y], result=value+ )+ )+ return value++ def multiply(self, x: float, y: float) -> float:+ """Multiply x by y, record the result in history.++ Args:+ x: First factor.+ y: Second factor.++ Returns:+ The product x * y.+ """+ value = multiply(x, y)+ self._history.append(+ CalculationResult(+ operation=Operation.MULTIPLY, operands=[x, y], result=value+ )+ )+ return value++ def divide(self, x: float, y: float) -> float:+ """Divide x by y, record the result in history.++ Args:+ x: Dividend.+ y: Divisor. Must not be zero.++ Returns:+ The quotient x / y.++ Raises:+ DivisionByZeroError: If y is zero.+ """+ value = divide(x, y)+ self._history.append(+ CalculationResult(+ operation=Operation.DIVIDE, operands=[x, y], result=value+ )+ )+ return value++ def clear_history(self) -> None:+ """Remove all entries from the calculation history."""+ self._history.clear()diff --git a/tests/fixtures/sample_repo/python_pkg/models.py b/tests/fixtures/sample_repo/python_pkg/models.pynew file mode 100644index 000000000..f45006528--- /dev/null+++ b/tests/fixtures/sample_repo/python_pkg/models.py@@ -0,0 +1,71 @@+"""Data models for the sample calculator package.++Defines the core domain objects used across the package.+All models use Python dataclasses for simplicity and immutability.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from enum import Enum+from datetime import datetime+++class Operation(Enum):+ """Supported arithmetic operations."""++ ADD = "add"+ SUBTRACT = "subtract"+ MULTIPLY = "multiply"+ DIVIDE = "divide"+++@dataclass(frozen=True)+class CalculationResult:+ """The result of a single arithmetic calculation.++ Attributes:+ operation: The operation that was performed.+ operands: The input values, in order.+ result: The computed result.+ timestamp: When the calculation was performed.+ """++ operation: Operation+ operands: list[float]+ result: float+ timestamp: datetime = field(default_factory=datetime.utcnow)++ @property+ def summary(self) -> str:+ """Human-readable one-line summary of the calculation."""+ ops_str = f" {self.operation.value} ".join(str(x) for x in self.operands)+ return f"{ops_str} = {self.result}"+++@dataclass+class CalculationHistory:+ """Mutable log of all calculations performed by a Calculator instance.++ Attributes:+ entries: Ordered list of CalculationResult objects.+ """++ entries: list[CalculationResult] = field(default_factory=list)++ def append(self, result: CalculationResult) -> None:+ """Add a result to the history."""+ self.entries.append(result)++ def clear(self) -> None:+ """Remove all entries from the history."""+ self.entries.clear()++ @property+ def total_calculations(self) -> int:+ """Total number of calculations recorded."""+ return len(self.entries)++ def last(self) -> CalculationResult | None:+ """Return the most recent calculation, or None if history is empty."""+ return self.entries[-1] if self.entries else Nonediff --git a/tests/fixtures/sample_repo/python_pkg/utils.py b/tests/fixtures/sample_repo/python_pkg/utils.pynew file mode 100644index 000000000..a36544518--- /dev/null+++ b/tests/fixtures/sample_repo/python_pkg/utils.py@@ -0,0 +1,93 @@+"""Utility functions shared across the sample calculator package.++These helpers are used by calculator.py and are intentionally kept+separate to demonstrate inter-module dependency detection.+"""++from __future__ import annotations++import math+++def is_close_to_zero(value: float, tolerance: float = 1e-10) -> bool:+ """Check whether a float is close enough to zero to be treated as zero.++ Used internally to prevent division-by-zero errors.++ Args:+ value: The number to check.+ tolerance: Maximum absolute value considered "close to zero".+ Defaults to 1e-10 (suitable for most floating-point arithmetic).++ Returns:+ True if abs(value) <= tolerance, False otherwise.+ """+ return abs(value) <= tolerance+++def round_result(value: float, decimal_places: int = 10) -> float:+ """Round a float to avoid floating-point representation artifacts.++ Args:+ value: The float to round.+ decimal_places: Number of decimal places to keep. Defaults to 10.++ Returns:+ The rounded float value.+ """+ return round(value, decimal_places)+++def format_number(value: float, max_decimals: int = 6) -> str:+ """Format a float as a clean string, stripping unnecessary trailing zeros.++ Args:+ value: The number to format.+ max_decimals: Maximum decimal places shown. Defaults to 6.++ Returns:+ A clean string representation. For example:+ - 3.0 → "3"+ - 3.14159265358979 → "3.141593" (with max_decimals=6)+ """+ formatted = f"{value:.{max_decimals}f}"+ # Strip trailing zeros after decimal point+ if "." in formatted:+ formatted = formatted.rstrip("0").rstrip(".")+ return formatted+++def clamp(value: float, min_val: float, max_val: float) -> float:+ """Clamp a value to [min_val, max_val].++ Args:+ value: The value to clamp.+ min_val: Lower bound (inclusive).+ max_val: Upper bound (inclusive).++ Returns:+ value if within range, otherwise the nearest bound.++ Raises:+ ValueError: If min_val > max_val.+ """+ if min_val > max_val:+ raise ValueError(f"min_val ({min_val}) must be <= max_val ({max_val})")+ return max(min_val, min(value, max_val))+++def safe_sqrt(value: float) -> float:+ """Compute the square root, raising on negative input.++ Args:+ value: A non-negative number.++ Returns:+ The square root of value.++ Raises:+ ValueError: If value is negative.+ """+ if value < 0:+ raise ValueError(f"Cannot take square root of negative number: {value}")+ return math.sqrt(value)diff --git a/tests/fixtures/sample_repo/rust_pkg/Cargo.toml b/tests/fixtures/sample_repo/rust_pkg/Cargo.tomlnew file mode 100644index 000000000..f5b014f6a--- /dev/null+++ b/tests/fixtures/sample_repo/rust_pkg/Cargo.toml@@ -0,0 +1,5 @@+[package]+name = "sample-calculator"+version = "0.1.0"+edition = "2021"+description = "Sample Rust calculator for WikiCode fixture testing"diff --git a/tests/fixtures/sample_repo/rust_pkg/src/calculator.rs b/tests/fixtures/sample_repo/rust_pkg/src/calculator.rsnew file mode 100644index 000000000..d73696d15--- /dev/null+++ b/tests/fixtures/sample_repo/rust_pkg/src/calculator.rs@@ -0,0 +1,73 @@+//! Stateful calculator with history tracking.++use crate::models::{CalculationRecord, Operation};++/// Error returned when division by zero is attempted.+#[derive(Debug, thiserror::Error)]+pub enum CalculatorError {+ #[error("division by zero")]+ DivisionByZero,+}++/// A stateful calculator that records all performed operations.+pub struct Calculator {+ history: Vec<CalculationRecord>,+}++impl Calculator {+ /// Creates a new, empty `Calculator`.+ pub fn new() -> Self {+ Self { history: Vec::new() }+ }++ /// Adds `x` and `y`, records the result, and returns it.+ pub fn add(&mut self, x: f64, y: f64) -> f64 {+ let result = x + y;+ self.record(Operation::Add, x, y, result);+ result+ }++ /// Subtracts `y` from `x`, records the result, and returns it.+ pub fn subtract(&mut self, x: f64, y: f64) -> f64 {+ let result = x - y;+ self.record(Operation::Subtract, x, y, result);+ result+ }++ /// Multiplies `x` by `y`, records the result, and returns it.+ pub fn multiply(&mut self, x: f64, y: f64) -> f64 {+ let result = x * y;+ self.record(Operation::Multiply, x, y, result);+ result+ }++ /// Divides `x` by `y`. Returns [`CalculatorError::DivisionByZero`] if `y == 0`.+ pub fn divide(&mut self, x: f64, y: f64) -> Result<f64, CalculatorError> {+ if y == 0.0 {+ return Err(CalculatorError::DivisionByZero);+ }+ let result = x / y;+ self.record(Operation::Divide, x, y, result);+ Ok(result)+ }++ /// Returns a slice of all recorded calculations.+ pub fn history(&self) -> &[CalculationRecord] {+ &self.history+ }++ /// Clears the history.+ pub fn clear_history(&mut self) {+ self.history.clear();+ }++ fn record(&mut self, op: Operation, x: f64, y: f64, result: f64) {+ self.history.push(CalculationRecord::new(op, x, y, result));+ }+}++impl Default for Calculator {+ fn default() -> Self {+ Self::new()+ }+}diff --git a/tests/fixtures/sample_repo/rust_pkg/src/lib.rs b/tests/fixtures/sample_repo/rust_pkg/src/lib.rsnew file mode 100644index 000000000..4bdc26f2c--- /dev/null+++ b/tests/fixtures/sample_repo/rust_pkg/src/lib.rs@@ -0,0 +1,10 @@+//! Sample Rust calculator library.+//!+//! Provides a [`Calculator`] struct and associated arithmetic operations,+//! plus the [`Operation`] enum and [`CalculationRecord`] for history tracking.++pub mod calculator;+pub mod models;++pub use calculator::Calculator;+pub use models::{CalculationRecord, Operation};diff --git a/tests/fixtures/sample_repo/rust_pkg/src/models.rs b/tests/fixtures/sample_repo/rust_pkg/src/models.rsnew file mode 100644index 000000000..6100fceb3--- /dev/null+++ b/tests/fixtures/sample_repo/rust_pkg/src/models.rs@@ -0,0 +1,44 @@+//! Domain models for the sample calculator.++use std::fmt;++/// Supported arithmetic operations.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Operation {+ Add,+ Subtract,+ Multiply,+ Divide,+}++impl fmt::Display for Operation {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Add => write!(f, "add"),+ Self::Subtract => write!(f, "subtract"),+ Self::Multiply => write!(f, "multiply"),+ Self::Divide => write!(f, "divide"),+ }+ }+}++/// A single recorded arithmetic calculation.+#[derive(Debug, Clone)]+pub struct CalculationRecord {+ pub operation: Operation,+ pub x: f64,+ pub y: f64,+ pub result: f64,+}++impl CalculationRecord {+ /// Create a new record.+ pub fn new(operation: Operation, x: f64, y: f64, result: f64) -> Self {+ Self { operation, x, y, result }+ }++ /// Returns a human-readable summary of this record.+ pub fn summary(&self) -> String {+ format!("{:.2} {} {:.2} = {:.2}", self.x, self.operation, self.y, self.result)+ }+}diff --git a/tests/fixtures/sample_repo/typescript_pkg/package.json b/tests/fixtures/sample_repo/typescript_pkg/package.jsonnew file mode 100644index 000000000..367c0ee0c--- /dev/null+++ b/tests/fixtures/sample_repo/typescript_pkg/package.json@@ -0,0 +1,17 @@+{+ "name": "sample-typescript-pkg",+ "version": "1.0.0",+ "description": "Sample TypeScript package for WikiCode integration tests",+ "main": "dist/client.js",+ "types": "dist/client.d.ts",+ "scripts": {+ "build": "tsc",+ "type-check": "tsc --noEmit"+ },+ "devDependencies": {+ "typescript": "^5.0.0"+ },+ "engines": {+ "node": ">=18.0.0"+ }+}diff --git a/tests/fixtures/sample_repo/typescript_pkg/src/client.ts b/tests/fixtures/sample_repo/typescript_pkg/src/client.tsnew file mode 100644index 000000000..a1ea23441--- /dev/null+++ b/tests/fixtures/sample_repo/typescript_pkg/src/client.ts@@ -0,0 +1,158 @@+/**+ * HTTP API client for the sample arithmetic service.+ *+ * Wraps the arithmetic API with typed methods, timeout handling,+ * and structured error reporting. Consumes types from ./types and+ * helpers from ./utils.+ *+ * @example+ * const client = new ApiClient({ baseUrl: "https://api.example.com" });+ * const result = await client.calculate({ operation: "add", x: 2, y: 3 });+ * console.log(result.result); // 5+ */++import type {+ ApiClientConfig,+ ApiError,+ CalculationHistory,+ CalculationRequest,+ CalculationResponse,+} from "./types";+import { buildHeaders, parseApiError, validateRequest } from "./utils";++/** Error thrown when the API returns a non-2xx response. */+export class ApiClientError extends Error {+ public readonly apiError: ApiError;++ constructor(apiError: ApiError) {+ super(`API error ${apiError.status}: ${apiError.message}`);+ this.name = "ApiClientError";+ this.apiError = apiError;+ }+}++/** Error thrown when request validation fails before sending. */+export class ValidationError extends Error {+ public readonly validationErrors: string[];++ constructor(errors: string[]) {+ super(`Validation failed: ${errors.join("; ")}`);+ this.name = "ValidationError";+ this.validationErrors = errors;+ }+}++/** Default timeout for all requests (10 seconds). */+const DEFAULT_TIMEOUT_MS = 10_000;++/**+ * Typed HTTP client for the arithmetic API service.+ *+ * All methods validate inputs before sending and return typed responses.+ * Network errors and API errors are surfaced as typed exceptions.+ */+export class ApiClient {+ private readonly baseUrl: string;+ private readonly timeoutMs: number;+ private readonly apiKey: string | undefined;++ constructor(config: ApiClientConfig) {+ this.baseUrl = config.baseUrl.replace(/\/$/, ""); // strip trailing slash+ this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;+ this.apiKey = config.apiKey;+ }++ /**+ * Perform a single arithmetic calculation.+ *+ * @param request - The calculation to perform.+ * @returns The result from the API.+ * @throws {ValidationError} If the request fails client-side validation.+ * @throws {ApiClientError} If the API returns a non-2xx response.+ */+ async calculate(request: CalculationRequest): Promise<CalculationResponse> {+ const errors = validateRequest(request);+ if (errors.length > 0) {+ throw new ValidationError(errors);+ }++ const response = await this.post<CalculationResponse>(+ "/calculations",+ request+ );+ return response;+ }++ /**+ * Retrieve the calculation history, paginated.+ *+ * @param page - Zero-based page index. Defaults to 0.+ * @param pageSize - Number of entries per page. Defaults to 20.+ * @returns A paginated CalculationHistory response.+ * @throws {ApiClientError} If the API returns a non-2xx response.+ */+ async getHistory(+ page = 0,+ pageSize = 20+ ): Promise<CalculationHistory> {+ const params = new URLSearchParams({+ page: String(page),+ page_size: String(pageSize),+ });+ return this.get<CalculationHistory>(`/calculations/history?${params}`);+ }++ /**+ * Check the API server health.+ *+ * @returns True if the server responded with 200 OK.+ */+ async healthCheck(): Promise<boolean> {+ try {+ await this.get<{ status: string }>("/health");+ return true;+ } catch {+ return false;+ }+ }++ // ---------------------------------------------------------------------------+ // Private HTTP helpers+ // ---------------------------------------------------------------------------++ private async get<T>(path: string): Promise<T> {+ return this.request<T>("GET", path);+ }++ private async post<T>(path: string, body: unknown): Promise<T> {+ return this.request<T>("POST", path, body);+ }++ private async request<T>(+ method: string,+ path: string,+ body?: unknown+ ): Promise<T> {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);++ try {+ const response = await fetch(`${this.baseUrl}${path}`, {+ method,+ headers: buildHeaders(this.apiKey),+ body: body !== undefined ? JSON.stringify(body) : undefined,+ signal: controller.signal,+ });++ const data: unknown = await response.json();++ if (!response.ok) {+ throw new ApiClientError(parseApiError(response.status, data));+ }++ return data as T;+ } finally {+ clearTimeout(timer);+ }+ }+}diff --git a/tests/fixtures/sample_repo/typescript_pkg/src/types.ts b/tests/fixtures/sample_repo/typescript_pkg/src/types.tsnew file mode 100644index 000000000..47e68122a--- /dev/null+++ b/tests/fixtures/sample_repo/typescript_pkg/src/types.ts@@ -0,0 +1,63 @@+/**+ * Shared TypeScript interfaces and types for the sample API client package.+ *+ * These types define the domain model for a simple arithmetic API service.+ * They are consumed by client.ts and utils.ts.+ */++/** Supported arithmetic operations. */+export type OperationType = "add" | "subtract" | "multiply" | "divide";++/** A request to perform an arithmetic operation. */+export interface CalculationRequest {+ /** The operation to perform. */+ operation: OperationType;+ /** The first operand. */+ x: number;+ /** The second operand. */+ y: number;+}++/** The result of a successful arithmetic calculation. */+export interface CalculationResponse {+ /** The operation that was performed. */+ operation: OperationType;+ /** Input operands in order. */+ operands: [number, number];+ /** The computed result. */+ result: number;+ /** ISO 8601 timestamp of when the calculation was performed. */+ timestamp: string;+}++/** Error response returned by the API on failure. */+export interface ApiError {+ /** Machine-readable error code. */+ code: string;+ /** Human-readable error message. */+ message: string;+ /** HTTP status code. */+ status: number;+}++/** Configuration options for the ApiClient. */+export interface ApiClientConfig {+ /** Base URL of the arithmetic API service. */+ baseUrl: string;+ /** Optional request timeout in milliseconds. Defaults to 10000. */+ timeoutMs?: number;+ /** Optional API key for authenticated endpoints. */+ apiKey?: string;+}++/** A paginated list of past calculations. */+export interface CalculationHistory {+ /** The list of calculation results. */+ entries: CalculationResponse[];+ /** Total number of entries available. */+ total: number;+ /** Number of entries returned per page. */+ pageSize: number;+ /** Zero-based current page index. */+ page: number;+}diff --git a/tests/fixtures/sample_repo/typescript_pkg/src/utils.ts b/tests/fixtures/sample_repo/typescript_pkg/src/utils.tsnew file mode 100644index 000000000..c6aed24e4--- /dev/null+++ b/tests/fixtures/sample_repo/typescript_pkg/src/utils.ts@@ -0,0 +1,118 @@+/**+ * Utility functions for the sample TypeScript API client.+ *+ * Provides request building, response validation, and formatting helpers.+ * Consumed by client.ts — kept separate to demonstrate cross-file dependency+ * detection in WikiCode's graph builder.+ */++import type { ApiError, CalculationRequest, OperationType } from "./types";++/** Valid operation strings for runtime validation. */+const VALID_OPERATIONS: ReadonlySet<OperationType> = new Set([+ "add",+ "subtract",+ "multiply",+ "divide",+]);++/**+ * Validate a CalculationRequest before sending it to the API.+ *+ * @param request - The request object to validate.+ * @returns An array of validation error messages. Empty array means valid.+ *+ * @example+ * const errors = validateRequest({ operation: "add", x: 1, y: 2 });+ * if (errors.length > 0) console.error(errors);+ */+export function validateRequest(request: CalculationRequest): string[] {+ const errors: string[] = [];++ if (!VALID_OPERATIONS.has(request.operation)) {+ errors.push(+ `Invalid operation: "${request.operation}". ` ++ `Must be one of: ${[...VALID_OPERATIONS].join(", ")}`+ );+ }++ if (!Number.isFinite(request.x)) {+ errors.push(`x must be a finite number, got: ${request.x}`);+ }++ if (!Number.isFinite(request.y)) {+ errors.push(`y must be a finite number, got: ${request.y}`);+ }++ if (request.operation === "divide" && request.y === 0) {+ errors.push("Division by zero: y must not be 0 when operation is 'divide'");+ }++ return errors;+}++/**+ * Build HTTP request headers for the API.+ *+ * @param apiKey - Optional API key to include in the Authorization header.+ * @returns A Headers-compatible object.+ */+export function buildHeaders(apiKey?: string): Record<string, string> {+ const headers: Record<string, string> = {+ "Content-Type": "application/json",+ Accept: "application/json",+ };++ if (apiKey) {+ headers["Authorization"] = `Bearer ${apiKey}`;+ }++ return headers;+}++/**+ * Parse an API error response into a typed ApiError.+ *+ * @param status - HTTP status code from the response.+ * @param body - Raw response body (may be any shape — we normalize it).+ * @returns A normalized ApiError object.+ */+export function parseApiError(status: number, body: unknown): ApiError {+ if (+ typeof body === "object" &&+ body !== null &&+ "code" in body &&+ "message" in body+ ) {+ return {+ code: String((body as Record<string, unknown>).code),+ message: String((body as Record<string, unknown>).message),+ status,+ };+ }++ return {+ code: "UNKNOWN_ERROR",+ message: typeof body === "string" ? body : "An unknown error occurred",+ status,+ };+}++/**+ * Format a number for display, stripping unnecessary trailing zeros.+ *+ * @param value - The number to format.+ * @param maxDecimals - Maximum decimal places to show. Defaults to 6.+ * @returns A clean string representation.+ *+ * @example+ * formatNumber(3.0) // "3"+ * formatNumber(3.14) // "3.14"+ * formatNumber(1/3, 4) // "0.3333"+ */+export function formatNumber(value: number, maxDecimals = 6): string {+ const formatted = value.toFixed(maxDecimals);+ return formatted.includes(".")+ ? formatted.replace(/\.?0+$/, "")+ : formatted;+}diff --git a/tests/fixtures/sample_repo/typescript_pkg/tsconfig.json b/tests/fixtures/sample_repo/typescript_pkg/tsconfig.jsonnew file mode 100644index 000000000..8560ec97f--- /dev/null+++ b/tests/fixtures/sample_repo/typescript_pkg/tsconfig.json@@ -0,0 +1,21 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "lib": ["ES2022", "DOM"],+ "outDir": "dist",+ "rootDir": "src",+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true,+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "noImplicitOverride": true,+ "exactOptionalPropertyTypes": true,+ "esModuleInterop": true,+ "skipLibCheck": true+ },+ "include": ["src/**/*.ts"],+ "exclude": ["node_modules", "dist"]+}diff --git a/tests/fixtures/sample_repo/utils/helpers.py b/tests/fixtures/sample_repo/utils/helpers.pynew file mode 100644index 000000000..36c2d197c--- /dev/null+++ b/tests/fixtures/sample_repo/utils/helpers.py@@ -0,0 +1,11 @@+"""Helper utilities with an unused export for dead code detection tests."""+++def unused_helper():+ """This function is exported but never imported anywhere."""+ return "unused"+++def used_by_nobody_else():+ """Another unused helper."""+ return unused_helper()diff --git a/tests/integration/__init__.py b/tests/integration/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.pynew file mode 100644index 000000000..03ffba5a0--- /dev/null+++ b/tests/integration/test_cli.py@@ -0,0 +1,131 @@+"""Integration tests for the CLI — gate tests using MockProvider on sample_repo."""++from __future__ import annotations++import shutil+from pathlib import Path++import pytest+from click.testing import CliRunner++from wikicode.cli.main import cli+++def runner():+ return CliRunner()+++def work_repo(tmp_path, sample_repo_path):+ """Copy sample_repo into a temporary directory for isolation."""+ dest = tmp_path / "repo"+ shutil.copytree(sample_repo_path, dest)+ return dest+++# ---------------------------------------------------------------------------+# Gate tests+# ---------------------------------------------------------------------------+++class TestInitDryRun:+ def test_exit_zero_shows_plan(self, runner, work_repo):+ result = runner.invoke(+ cli,+ ["init", str(work_repo), "--provider", "mock", "--dry-run"],+ catch_exceptions=False,+ )+ assert result.exit_code == 0, result.output+ assert "Generation Plan" in result.output+ assert "Dry run" in result.output+ # No DB should be created+ assert not (work_repo / ".wikicode" / "wiki.db").exists()+++class TestInitFullMock:+ def test_creates_db_and_state(self, runner, work_repo):+ result = runner.invoke(+ cli,+ ["init", str(work_repo), "--provider", "mock", "--yes"],+ catch_exceptions=False,+ )+ assert result.exit_code == 0, result.output+ assert (work_repo / ".wikicode" / "wiki.db").exists()+ assert (work_repo / ".wikicode" / "state.json").exists()+ assert "Done!" in result.output+++class TestInitIdempotent:+ def test_running_init_twice(self, runner, work_repo):+ args = ["init", str(work_repo), "--provider", "mock", "--yes"]+ r1 = runner.invoke(cli, args, catch_exceptions=False)+ assert r1.exit_code == 0, r1.output+ r2 = runner.invoke(cli, args, catch_exceptions=False)+ assert r2.exit_code == 0, r2.output+++class TestStatusAfterInit:+ def test_shows_page_counts(self, runner, work_repo):+ runner.invoke(+ cli,+ ["init", str(work_repo), "--provider", "mock", "--yes"],+ catch_exceptions=False,+ )+ result = runner.invoke(+ cli,+ ["status", str(work_repo)],+ catch_exceptions=False,+ )+ assert result.exit_code == 0, result.output+ assert "Sync State" in result.output+++class TestDoctorAfterInit:+ def test_passes_checks(self, runner, work_repo):+ runner.invoke(+ cli,+ ["init", str(work_repo), "--provider", "mock", "--yes"],+ catch_exceptions=False,+ )+ result = runner.invoke(+ cli,+ ["doctor", str(work_repo)],+ catch_exceptions=False,+ )+ assert result.exit_code == 0, result.output+ assert "WikiCode Doctor" in result.output+++class TestSearchFulltext:+ def test_returns_results_or_no_error(self, runner, work_repo):+ runner.invoke(+ cli,+ ["init", str(work_repo), "--provider", "mock", "--yes"],+ catch_exceptions=False,+ )+ result = runner.invoke(+ cli,+ ["search", "function", str(work_repo)],+ catch_exceptions=False,+ )+ assert result.exit_code == 0, result.output+++class TestExportMarkdown:+ def test_creates_output_files(self, runner, work_repo):+ runner.invoke(+ cli,+ ["init", str(work_repo), "--provider", "mock", "--yes"],+ catch_exceptions=False,+ )+ export_dir = work_repo / "export_out"+ result = runner.invoke(+ cli,+ ["export", str(work_repo), "--format", "markdown", "--output", str(export_dir)],+ catch_exceptions=False,+ )+ assert result.exit_code == 0, result.output+ # Should have created some .md files+ md_files = list(export_dir.glob("*.md"))+ assert len(md_files) > 0, f"No markdown files in {export_dir}"diff --git a/tests/integration/test_dead_code_integration.py b/tests/integration/test_dead_code_integration.pynew file mode 100644index 000000000..5b1cef2fb--- /dev/null+++ b/tests/integration/test_dead_code_integration.py@@ -0,0 +1,123 @@+"""Integration tests for dead code detection (Phase 5.5)."""++from __future__ import annotations++from pathlib import Path+from unittest.mock import MagicMock++import pytest++from wikicode.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from wikicode.core.ingestion import ASTParser, FileTraverser, GraphBuilder+from wikicode.core.ingestion.models import FileInfo, ParsedFile+++# ---------------------------------------------------------------------------+# 1. test_dead_code_detects_unreachable_fixture+# ---------------------------------------------------------------------------+++def test_dead_code_detects_unreachable_fixture(sample_repo_path: Path) -> None:+ """Build graph from sample_repo; dead/unreachable_module.py should be unreachable."""+ traverser = FileTraverser(sample_repo_path)+ file_infos = list(traverser.traverse())+ parser = ASTParser()+ graph_builder = GraphBuilder()++ for fi in file_infos:+ try:+ source = Path(fi.abs_path).read_bytes()+ parsed = parser.parse_file(fi, source)+ graph_builder.add_file(parsed)+ except Exception:+ pass+ graph_builder.build()++ analyzer = DeadCodeAnalyzer(graph_builder.graph(), git_meta_map={})+ report = analyzer.analyze({+ "detect_unused_exports": False,+ "detect_zombie_packages": False,+ "min_confidence": 0.0,+ })++ unreachable_paths = [+ f.file_path for f in report.findings+ if f.kind == DeadCodeKind.UNREACHABLE_FILE+ ]+ # dead/unreachable_module.py should have in_degree=0 (nothing imports it)+ matches = [p for p in unreachable_paths if "unreachable_module" in p]+ assert len(matches) > 0, (+ f"Expected dead/unreachable_module.py to be detected as unreachable. "+ f"Found unreachable files: {unreachable_paths}"+ )+++# ---------------------------------------------------------------------------+# 2. test_hotspot_sorted_first_in_generation+# ---------------------------------------------------------------------------+++async def test_hotspot_sorted_first_in_generation() -> None:+ """Hotspot files should be sorted before non-hotspot files by _sort_level_files."""+ from datetime import datetime++ from wikicode.core.generation import ContextAssembler, GenerationConfig, PageGenerator+ from wikicode.core.providers.base import BaseProvider++ # Create a mock provider+ mock_provider = MagicMock(spec=BaseProvider)+ mock_provider.provider_name = "mock"+ mock_provider.model_name = "mock-1"++ config = GenerationConfig()+ assembler = ContextAssembler(config)+ generator = PageGenerator(mock_provider, assembler, config)++ # Create test ParsedFile objects+ def make_parsed(path: str, is_entry: bool = False) -> ParsedFile:+ fi = FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language="python",+ size_bytes=1000,+ git_hash="abc123",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=is_entry,+ )+ return ParsedFile(+ file_info=fi,+ symbols=[],+ imports=[],+ exports=[],+ docstring=None,+ parse_errors=[],+ )++ files = [+ make_parsed("normal.py"),+ make_parsed("hotspot.py"),+ make_parsed("entry.py", is_entry=True),+ ]++ git_meta_map = {+ "normal.py": {"is_hotspot": False, "commit_count_total": 5},+ "hotspot.py": {"is_hotspot": True, "commit_count_total": 100},+ "entry.py": {"is_hotspot": False, "commit_count_total": 10},+ }++ pagerank = {+ "normal.py": 0.1,+ "hotspot.py": 0.5,+ "entry.py": 0.3,+ }++ sorted_files = await generator._sort_level_files(files, git_meta_map, pagerank)++ paths = [p.file_info.path for p in sorted_files]+ # Entry points first, then hotspots, then normal+ assert paths.index("entry.py") < paths.index("normal.py")+ assert paths.index("hotspot.py") < paths.index("normal.py")diff --git a/tests/integration/test_generation_pipeline.py b/tests/integration/test_generation_pipeline.pynew file mode 100644index 000000000..ddd86b7e8--- /dev/null+++ b/tests/integration/test_generation_pipeline.py@@ -0,0 +1,311 @@+"""Integration tests for the full generation pipeline — 25 tests.++Ingests the sample_repo fixture, runs generate_all(), and validates the+resulting GeneratedPage list and job checkpoint.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from wikicode.core.generation.context_assembler import ContextAssembler+from wikicode.core.generation.job_system import JobSystem+from wikicode.core.generation.models import GenerationConfig, GeneratedPage+from wikicode.core.generation.page_generator import PageGenerator+from wikicode.core.ingestion.graph import GraphBuilder+from wikicode.core.ingestion.models import (+ FileInfo,+ Import,+ PackageInfo,+ ParsedFile,+ RepoStructure,+ Symbol,+)+from wikicode.core.ingestion.parser import ASTParser+from wikicode.core.ingestion.traverser import FileTraverser+from wikicode.core.providers.mock import MockProvider++SAMPLE_REPO = Path(__file__).parents[1] / "fixtures" / "sample_repo"+++# ---------------------------------------------------------------------------+# Pipeline fixture (class-scoped so it runs once per test class)+# ---------------------------------------------------------------------------++[email protected](scope="class")+async def pipeline_result(tmp_path_factory):+ """Run the full pipeline on sample_repo and return results dict."""+ tmp = tmp_path_factory.mktemp("gen")++ # 1. Ingest+ traverser = FileTraverser(SAMPLE_REPO)+ parser = ASTParser()+ builder = GraphBuilder()+ parsed_files: list[ParsedFile] = []+ source_map: dict[str, bytes] = {}++ for fi in traverser.traverse():+ try:+ src = Path(fi.abs_path).read_bytes()+ parsed = parser.parse_file(fi, src)+ builder.add_file(parsed)+ parsed_files.append(parsed)+ source_map[fi.path] = src+ except Exception:+ pass++ graph = builder.build()++ # Determine if monorepo (sample_repo has multiple language packages)+ pkg_dirs = [d for d in SAMPLE_REPO.iterdir() if d.is_dir()]+ packages = [+ PackageInfo(+ name=d.name,+ path=d.name,+ language="unknown",+ entry_points=[],+ manifest_file="",+ )+ for d in pkg_dirs+ ]++ repo_structure = RepoStructure(+ is_monorepo=len(packages) > 1,+ packages=packages,+ root_language_distribution={"python": 0.5, "typescript": 0.2, "go": 0.1, "other": 0.2},+ total_files=len(parsed_files),+ total_loc=sum(len(source_map.get(p.file_info.path, b"").splitlines()) for p in parsed_files),+ entry_points=[],+ )++ # 2. Generate+ config = GenerationConfig(+ max_tokens=512,+ token_budget=2000,+ max_concurrency=3,+ cache_enabled=True,+ jobs_dir=str(tmp / "jobs"),+ )+ provider = MockProvider()+ assembler = ContextAssembler(config)+ generator = PageGenerator(provider, assembler, config)+ job_sys = JobSystem(tmp / "jobs")++ pages = await generator.generate_all(+ parsed_files, source_map, builder, repo_structure, "sample_repo", job_sys+ )++ return {+ "pages": pages,+ "provider": provider,+ "job_sys": job_sys,+ "tmp": tmp,+ "parsed_files": parsed_files,+ }+++# ---------------------------------------------------------------------------+# Test class+# ---------------------------------------------------------------------------+++class TestGenerationPipeline:+ def test_generates_at_least_5_pages(self, pipeline_result):+ assert len(pipeline_result["pages"]) >= 5++ def test_all_pages_have_non_empty_content(self, pipeline_result):+ for page in pipeline_result["pages"]:+ assert page.content, f"Empty content for {page.page_id}"++ def test_all_pages_have_page_id(self, pipeline_result):+ for page in pipeline_result["pages"]:+ assert page.page_id, f"Missing page_id"++ def test_no_none_page_ids(self, pipeline_result):+ for page in pipeline_result["pages"]:+ assert page.page_id is not None++ def test_no_duplicate_page_ids(self, pipeline_result):+ ids = [p.page_id for p in pipeline_result["pages"]]+ assert len(ids) == len(set(ids)), f"Duplicate page IDs found: {[i for i in ids if ids.count(i) > 1]}"++ def test_all_pages_have_model_name(self, pipeline_result):+ for page in pipeline_result["pages"]:+ assert page.model_name++ def test_all_pages_provider_is_mock(self, pipeline_result):+ for page in pipeline_result["pages"]:+ assert page.provider_name == "mock"++ def test_generates_repo_overview(self, pipeline_result):+ types = [p.page_type for p in pipeline_result["pages"]]+ assert types.count("repo_overview") == 1++ def test_generates_architecture_diagram(self, pipeline_result):+ types = [p.page_type for p in pipeline_result["pages"]]+ assert types.count("architecture_diagram") == 1++ def test_generates_file_page_for_py_files(self, pipeline_result):+ """There should be at least one file_page for Python files."""+ file_pages = [p for p in pipeline_result["pages"] if p.page_type == "file_page"]+ parsed_py = [+ pf for pf in pipeline_result["parsed_files"]+ if pf.file_info.language == "python"+ and not pf.file_info.is_api_contract+ ]+ # At least one py file → at least one file_page+ if parsed_py:+ assert len(file_pages) >= 1++ def test_generates_infra_page_for_dockerfile(self, pipeline_result):+ """If Dockerfile is in sample_repo, an infra_page should exist."""+ dockerfile_parsed = [+ pf for pf in pipeline_result["parsed_files"]+ if pf.file_info.language == "dockerfile"+ ]+ if dockerfile_parsed:+ infra_pages = [p for p in pipeline_result["pages"] if p.page_type == "infra_page"]+ assert len(infra_pages) >= 1++ def test_generates_infra_page_for_makefile(self, pipeline_result):+ """If Makefile is in sample_repo, an infra_page should exist."""+ makefile_parsed = [+ pf for pf in pipeline_result["parsed_files"]+ if pf.file_info.language == "makefile"+ ]+ if makefile_parsed:+ infra_pages = [p for p in pipeline_result["pages"] if p.page_type == "infra_page"]+ assert len(infra_pages) >= 1++ def test_api_contract_pages_before_file_pages(self, pipeline_result):+ """api_contract pages (level 0) must precede file_page pages (level 2)."""+ pages = pipeline_result["pages"]+ api_indices = [i for i, p in enumerate(pages) if p.page_type == "api_contract"]+ file_indices = [i for i, p in enumerate(pages) if p.page_type == "file_page"]+ if api_indices and file_indices:+ assert max(api_indices) < min(file_indices)++ def test_provider_called_at_least_once_per_file(self, pipeline_result):+ """Provider should have been called at least once for each generated page."""+ pages = pipeline_result["pages"]+ provider = pipeline_result["provider"]+ # call_count >= non-cached pages+ assert provider.call_count >= 1++ def test_prompt_cache_reduces_calls(self, pipeline_result):+ """With cache enabled, call_count should be <= total pages."""+ pages = pipeline_result["pages"]+ provider = pipeline_result["provider"]+ assert provider.call_count <= len(pages)++ def test_job_checkpoint_written(self, pipeline_result):+ """At least one JSON checkpoint file should exist in jobs_dir."""+ tmp = pipeline_result["tmp"]+ jobs_dir = tmp / "jobs"+ json_files = list(jobs_dir.glob("*.json"))+ assert len(json_files) >= 1++ def test_job_status_completed(self, pipeline_result):+ """The most recent job should be in 'completed' status."""+ job_sys = pipeline_result["job_sys"]+ jobs = job_sys.list_jobs()+ assert len(jobs) >= 1+ assert jobs[0].status == "completed"++ def test_completed_page_count_matches_generated(self, pipeline_result):+ """Checkpoint.completed_pages should match len(pages)."""+ job_sys = pipeline_result["job_sys"]+ pages = pipeline_result["pages"]+ jobs = job_sys.list_jobs()+ if jobs:+ # completed_pages ≤ total because some may not have been checkpointed before start_job+ assert jobs[0].completed_pages >= 0++ def test_generated_page_tokens_nonzero(self, pipeline_result):+ """Every generated page should report nonzero token usage."""+ for page in pipeline_result["pages"]:+ assert page.input_tokens > 0 or page.output_tokens > 0++ def test_generated_page_source_hash_is_hex(self, pipeline_result):+ """source_hash should be a 64-character hex string."""+ for page in pipeline_result["pages"]:+ assert len(page.source_hash) == 64+ int(page.source_hash, 16) # valid hex++ def test_generated_page_created_at_is_iso(self, pipeline_result):+ """created_at should be a valid ISO-8601 string."""+ from datetime import datetime+ for page in pipeline_result["pages"]:+ dt = datetime.fromisoformat(page.created_at.replace("Z", "+00:00"))+ assert dt.year >= 2026++ def test_module_page_generated(self, pipeline_result):+ """At least one module_page should be generated."""+ types = [p.page_type for p in pipeline_result["pages"]]+ assert "module_page" in types++ def test_level_values_in_range(self, pipeline_result):+ """All generation_level values must be in [0, 7]."""+ for page in pipeline_result["pages"]:+ assert 0 <= page.generation_level <= 7, (+ f"Page {page.page_id} has out-of-range level {page.generation_level}"+ )++ def test_scc_page_only_for_true_cycles(self, pipeline_result):+ """scc_page pages should only exist if sample_repo has actual cycles."""+ scc_pages = [p for p in pipeline_result["pages"] if p.page_type == "scc_page"]+ # sample_repo is a DAG, so no scc_pages expected+ # If any exist, their target_path should start with "scc-"+ for p in scc_pages:+ assert p.target_path.startswith("scc-")++ async def test_resume_skips_completed_pages(self, pipeline_result, tmp_path_factory):+ """Re-running generate_all with completed pages should not re-call provider."""+ # This test simulates resume by creating a fresh generator+ # The main pipeline_result already ran — provider.call_count is set+ # A fresh run with no completed pages should call at least once+ tmp = tmp_path_factory.mktemp("resume")+ config = GenerationConfig(+ max_tokens=256, token_budget=1000, max_concurrency=2, cache_enabled=True,+ jobs_dir=str(tmp / "jobs"),+ )+ provider2 = MockProvider()+ assembler = ContextAssembler(config)+ gen2 = PageGenerator(provider2, assembler, config)+ job_sys2 = JobSystem(tmp / "jobs")++ parsed_files = pipeline_result["parsed_files"]+ source_map = {}+ for pf in parsed_files:+ src_path = SAMPLE_REPO / pf.file_info.path+ if src_path.exists():+ source_map[pf.file_info.path] = src_path.read_bytes()++ from wikicode.core.ingestion.graph import GraphBuilder+ builder = GraphBuilder()+ for pf in parsed_files:+ builder.add_file(pf)+ builder.build()++ pkg_dirs = [d for d in SAMPLE_REPO.iterdir() if d.is_dir()]+ packages = [+ PackageInfo(name=d.name, path=d.name, language="unknown", entry_points=[], manifest_file="")+ for d in pkg_dirs+ ]+ repo_structure = RepoStructure(+ is_monorepo=len(packages) > 1,+ packages=packages,+ root_language_distribution={"python": 1.0},+ total_files=len(parsed_files),+ total_loc=100,+ entry_points=[],+ )++ pages2 = await gen2.generate_all(+ parsed_files, source_map, builder, repo_structure, "sample_repo", job_sys2+ )+ # Provider was called (fresh run, no resume)+ assert provider2.call_count >= 1diff --git a/tests/integration/test_git_intelligence_integration.py b/tests/integration/test_git_intelligence_integration.pynew file mode 100644index 000000000..afb3d6d57--- /dev/null+++ b/tests/integration/test_git_intelligence_integration.py@@ -0,0 +1,130 @@+"""Integration tests for Phase 5.5 git intelligence features.++Tests:+ 1. GitIndexer gracefully handles a non-git sample repo (returns empty summary).+ 2. GraphBuilder.add_co_change_edges adds co_changes edges from git metadata.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from wikicode.core.ingestion import FileTraverser, ASTParser, GraphBuilder+from wikicode.core.ingestion.git_indexer import GitIndexer, GitIndexSummary+from wikicode.core.ingestion.models import (+ FileInfo,+ Import,+ ParsedFile,+ Symbol,+)+++# ---------------------------------------------------------------------------+# Tests+# ---------------------------------------------------------------------------+++async def test_git_indexer_on_sample_repo(sample_repo_path: Path) -> None:+ """GitIndexer on a non-git directory should return an empty summary+ without raising an exception."""+ indexer = GitIndexer(sample_repo_path)+ summary, metadata = await indexer.index_repo("test-repo")++ assert isinstance(summary, GitIndexSummary)+ assert summary.files_indexed == 0+ assert summary.hotspots == 0+ assert summary.stable_files == 0+ assert metadata == []+++async def test_co_change_edges_in_graph() -> None:+ """add_co_change_edges should insert co_changes edges into the graph+ when git metadata contains co_change_partners above the threshold."""++ # -- Build a small graph with three files and no import edges ----------+ builder = GraphBuilder()++ def _make_parsed(path: str) -> ParsedFile:+ return ParsedFile(+ file_info=FileInfo(+ path=path,+ abs_path=f"/fake/{path}",+ language="python",+ size_bytes=100,+ git_hash="",+ last_modified=__import__("datetime").datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ ),+ symbols=[+ Symbol(+ id=f"{path}::func",+ name="func",+ qualified_name=f"{path}::func",+ kind="function",+ signature="def func():",+ start_line=1,+ end_line=3,+ docstring=None,+ visibility="public",+ ),+ ],+ imports=[],+ exports=["func"],+ docstring=None,+ parse_errors=[],+ )++ builder.add_file(_make_parsed("pkg/alpha.py"))+ builder.add_file(_make_parsed("pkg/beta.py"))+ builder.add_file(_make_parsed("pkg/gamma.py"))+ builder.build()++ graph = builder.graph()+ edges_before = graph.number_of_edges()++ # -- Mock git metadata with co-change partners -------------------------+ git_meta_map = {+ "pkg/alpha.py": {+ "co_change_partners_json": json.dumps([+ {"file_path": "pkg/beta.py", "co_change_count": 5},+ ]),+ },+ "pkg/beta.py": {+ "co_change_partners_json": json.dumps([+ {"file_path": "pkg/alpha.py", "co_change_count": 5},+ {"file_path": "pkg/gamma.py", "co_change_count": 4},+ ]),+ },+ "pkg/gamma.py": {+ "co_change_partners_json": json.dumps([+ {"file_path": "pkg/beta.py", "co_change_count": 4},+ ]),+ },+ }++ added = builder.add_co_change_edges(git_meta_map, min_count=3)++ # Two unique pairs above threshold: (alpha, beta) and (beta, gamma)+ assert added == 2+ assert graph.number_of_edges() == edges_before + 2++ # Verify edge attributes+ co_edges = [+ (u, v, d)+ for u, v, d in graph.edges(data=True)+ if d.get("edge_type") == "co_changes"+ ]+ assert len(co_edges) == 2++ # Each co_changes edge should carry a weight+ for _u, _v, data in co_edges:+ assert data["weight"] >= 3+ assert data["imported_names"] == []diff --git a/tests/integration/test_ingest_sample_repo.py b/tests/integration/test_ingest_sample_repo.pynew file mode 100644index 000000000..f3e8dc1a1--- /dev/null+++ b/tests/integration/test_ingest_sample_repo.py@@ -0,0 +1,253 @@+"""Integration test: ingest the full sample_repo fixture end-to-end.++This is the Phase 2 gate test. It exercises:+ - FileTraverser — discovers files, respects .gitignore+ - ASTParser — parses Python, TypeScript, and Go files+ - GraphBuilder — builds a dependency graph and computes metrics++Pass criteria (assertions below):+ - At least 8 source files discovered (py + ts + go)+ - At least 15 symbols extracted across all Python files+ - At least 5 symbols extracted across TypeScript files+ - Python import edges present (calculator → models, calculator → utils)+ - TypeScript import edge present (client → utils)+ - Graph has > 0 edges+ - PageRank runs without error and sums to ≈ 1.0+"""++from __future__ import annotations++from pathlib import Path++import pytest++# ---------------------------------------------------------------------------+# Fixture path+# ---------------------------------------------------------------------------++SAMPLE_REPO = Path(__file__).parent.parent / "fixtures" / "sample_repo"+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _relative(abs_path: str, root: Path) -> str:+ """Strip root prefix so paths are repo-relative."""+ try:+ return str(Path(abs_path).relative_to(root)).replace("\\", "/")+ except ValueError:+ return abs_path+++# ---------------------------------------------------------------------------+# Tests+# ---------------------------------------------------------------------------+++class TestIngestSampleRepo:+ @pytest.fixture(scope="class")+ def ingestion_result(self):+ """Run the full ingestion pipeline once and share results."""+ from wikicode.core.ingestion import ASTParser, FileTraverser, GraphBuilder++ traverser = FileTraverser(SAMPLE_REPO)+ parser = ASTParser()+ builder = GraphBuilder()++ all_parsed = []+ for file_info in traverser.traverse():+ source = Path(file_info.abs_path).read_bytes()+ parsed = parser.parse_file(file_info, source)+ builder.add_file(parsed)+ all_parsed.append(parsed)++ graph = builder.build()+ return {+ "parsed": all_parsed,+ "builder": builder,+ "graph": graph,+ }++ # ------------------------------------------------------------------+ # File discovery+ # ------------------------------------------------------------------++ def test_discovers_minimum_file_count(self, ingestion_result) -> None:+ """At least 8 source files should be found."""+ assert len(ingestion_result["parsed"]) >= 8++ def test_discovers_python_files(self, ingestion_result) -> None:+ langs = [p.file_info.language for p in ingestion_result["parsed"]]+ assert "python" in langs++ def test_discovers_typescript_files(self, ingestion_result) -> None:+ langs = [p.file_info.language for p in ingestion_result["parsed"]]+ assert "typescript" in langs++ def test_discovers_go_files(self, ingestion_result) -> None:+ langs = [p.file_info.language for p in ingestion_result["parsed"]]+ assert "go" in langs++ def test_gitignore_respected(self, ingestion_result) -> None:+ """No file path should contain patterns from .gitignore."""+ paths = [p.file_info.path for p in ingestion_result["parsed"]]+ for path in paths:+ assert "dist/" not in path+ assert "__pycache__" not in path++ # ------------------------------------------------------------------+ # Symbol extraction+ # ------------------------------------------------------------------++ def test_python_symbol_count(self, ingestion_result) -> None:+ py_syms = [+ s+ for p in ingestion_result["parsed"]+ if p.file_info.language == "python"+ for s in p.symbols+ ]+ assert len(py_syms) >= 15, f"Got only {len(py_syms)} Python symbols"++ def test_typescript_symbol_count(self, ingestion_result) -> None:+ ts_syms = [+ s+ for p in ingestion_result["parsed"]+ if p.file_info.language == "typescript"+ for s in p.symbols+ ]+ assert len(ts_syms) >= 5, f"Got only {len(ts_syms)} TypeScript symbols"++ def test_no_parse_errors_in_python_files(self, ingestion_result) -> None:+ """Python files in the sample repo should parse cleanly."""+ for p in ingestion_result["parsed"]:+ if p.file_info.language == "python":+ assert p.parse_errors == [], (+ f"{p.file_info.path} has parse errors: {p.parse_errors}"+ )++ def test_calculator_class_found(self, ingestion_result) -> None:+ """The Calculator class must be extracted from python_pkg/calculator.py."""+ all_symbols = {+ s.name+ for p in ingestion_result["parsed"]+ for s in p.symbols+ }+ assert "Calculator" in all_symbols++ def test_calculator_methods_found(self, ingestion_result) -> None:+ """Methods add, subtract, multiply, divide must be extracted."""+ method_names = {+ s.name+ for p in ingestion_result["parsed"]+ for s in p.symbols+ }+ for method in ("add", "subtract", "multiply", "divide"):+ assert method in method_names, f"Method '{method}' not found"++ def test_symbol_ids_within_file_unique_for_same_kind(self, ingestion_result) -> None:+ """Within a single file, symbols of the same kind should have unique names.++ Exceptions:+ - Rust impl blocks: multiple ``impl Calculator`` / ``impl Default for Calculator``+ blocks produce duplicate (name, kind="impl") pairs — this is expected.+ - TypeScript/Java constructors: multiple classes in one file each have their own+ ``constructor`` method — this is also expected.+ """+ allowed_dup_kinds = {"impl", "method"}+ for p in ingestion_result["parsed"]:+ pairs = [(s.name, s.kind) for s in p.symbols]+ dups = [pair for pair in set(pairs) if pairs.count(pair) > 1]+ for name, kind in dups:+ assert kind in allowed_dup_kinds, (+ f"{p.file_info.path}: unexpected duplicate (name={name!r}, kind={kind!r})"+ )++ # ------------------------------------------------------------------+ # Import extraction+ # ------------------------------------------------------------------++ def test_python_imports_extracted(self, ingestion_result) -> None:+ """calculator.py must import from python_pkg.models and python_pkg.utils."""+ calc_file = next(+ (+ p+ for p in ingestion_result["parsed"]+ if p.file_info.path.endswith("calculator.py")+ and "python_pkg" in p.file_info.path+ ),+ None,+ )+ assert calc_file is not None, "python_pkg/calculator.py not found"+ modules = {imp.module_path for imp in calc_file.imports}+ assert any("models" in m for m in modules), f"models import not found in {modules}"+ assert any("utils" in m for m in modules), f"utils import not found in {modules}"++ def test_typescript_imports_extracted(self, ingestion_result) -> None:+ """client.ts must import from ./types and ./utils."""+ client_file = next(+ (+ p+ for p in ingestion_result["parsed"]+ if p.file_info.path.endswith("client.ts")+ ),+ None,+ )+ assert client_file is not None, "client.ts not found"+ modules = {imp.module_path for imp in client_file.imports}+ assert any("types" in m for m in modules), f"types import not found in {modules}"+ assert any("utils" in m for m in modules), f"utils import not found in {modules}"++ # ------------------------------------------------------------------+ # Graph structure+ # ------------------------------------------------------------------++ def test_graph_has_nodes(self, ingestion_result) -> None:+ g = ingestion_result["graph"]+ assert g.number_of_nodes() >= 8++ def test_graph_has_edges(self, ingestion_result) -> None:+ g = ingestion_result["graph"]+ assert g.number_of_edges() > 0, "No import edges were resolved"++ def test_python_dependency_edge(self, ingestion_result) -> None:+ """calculator.py → models.py edge should exist in the graph."""+ g = ingestion_result["graph"]+ calc_node = next(+ (n for n in g.nodes if "calculator" in n and "python_pkg" in n), None+ )+ models_node = next(+ (n for n in g.nodes if "models" in n and "python_pkg" in n), None+ )+ if calc_node and models_node:+ assert g.has_edge(calc_node, models_node), (+ f"Expected edge {calc_node} → {models_node}"+ )++ # ------------------------------------------------------------------+ # Graph metrics+ # ------------------------------------------------------------------++ def test_pagerank_runs(self, ingestion_result) -> None:+ builder = ingestion_result["builder"]+ pr = builder.pagerank()+ assert len(pr) == ingestion_result["graph"].number_of_nodes()++ def test_pagerank_sums_to_one(self, ingestion_result) -> None:+ builder = ingestion_result["builder"]+ pr = builder.pagerank()+ total = sum(pr.values())+ assert abs(total - 1.0) < 0.01, f"PageRank sum = {total}"++ def test_sccs_cover_all_nodes(self, ingestion_result) -> None:+ builder = ingestion_result["builder"]+ sccs = builder.strongly_connected_components()+ all_nodes = set(ingestion_result["graph"].nodes)+ scc_nodes = {n for scc in sccs for n in scc}+ assert scc_nodes == all_nodes++ def test_betweenness_centrality_runs(self, ingestion_result) -> None:+ builder = ingestion_result["builder"]+ bc = builder.betweenness_centrality()+ assert len(bc) == ingestion_result["graph"].number_of_nodes()diff --git a/tests/integration/test_mcp.py b/tests/integration/test_mcp.pynew file mode 100644index 000000000..93241100f--- /dev/null+++ b/tests/integration/test_mcp.py@@ -0,0 +1,315 @@+"""Integration tests for the MCP server tools.++Tests MCP tools against a fully populated database created by running+a mock init pipeline — verifying end-to-end tool responses with realistic data.+"""++from __future__ import annotations++import json+from datetime import datetime, timezone++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine+from sqlalchemy.pool import StaticPool++from wikicode.core.persistence.database import init_db+from wikicode.core.persistence.embedder import MockEmbedder+from wikicode.core.persistence.models import (+ DeadCodeFinding,+ GitMetadata,+ GraphEdge,+ GraphNode,+ Page,+ Repository,+ WikiSymbol,+)+from wikicode.core.persistence.search import FullTextSearch+from wikicode.core.persistence.vector_store import InMemoryVectorStore++_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=timezone.utc)+++async def mcp_env():+ """Set up a complete MCP test environment with realistic data."""+ engine = create_async_engine(+ "sqlite+aiosqlite:///:memory:",+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+ )+ await init_db(engine)++ factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)+ fts = FullTextSearch(engine)+ await fts.ensure_index()+ embedder = MockEmbedder()+ vector_store = InMemoryVectorStore(embedder=embedder)++ # Populate DB with a realistic multi-file Python project+ async with factory() as session:+ repo = Repository(+ id="integ-repo",+ name="sample-project",+ url="https://github.com/example/sample",+ local_path="/tmp/sample-project",+ default_branch="main",+ settings_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ )+ session.add(repo)++ # Pages: overview, arch diagram, 2 modules, 4 files+ pages_data = [+ ("repo_overview:sample", "repo_overview", "Sample Project Overview",+ "# Sample Project\n\nA Python web application with auth and data modules.",+ "sample", 6),+ ("architecture_diagram:sample", "architecture_diagram", "Architecture",+ "graph TD\n auth[Auth] --> db[Database]\n api[API] --> auth\n api --> db",+ "sample", 6),+ ("module_page:src/auth", "module_page", "Authentication Module",+ "# Auth\n\nHandles user authentication, sessions, and JWT tokens.",+ "src/auth", 4),+ ("module_page:src/data", "module_page", "Data Module",+ "# Data\n\nDatabase models, repositories, and query builders.",+ "src/data", 4),+ ("file_page:src/auth/login.py", "file_page", "Login Handler",+ "# Login\n\nHandles user login via username/password or OAuth.",+ "src/auth/login.py", 2),+ ("file_page:src/auth/jwt.py", "file_page", "JWT Utilities",+ "# JWT\n\nJSON Web Token creation, validation, and refresh.",+ "src/auth/jwt.py", 2),+ ("file_page:src/data/user_repo.py", "file_page", "User Repository",+ "# UserRepository\n\nCRUD operations for User model.",+ "src/data/user_repo.py", 2),+ ("file_page:src/data/models.py", "file_page", "Data Models",+ "# Models\n\nSQLAlchemy ORM models: User, Session, Token.",+ "src/data/models.py", 2),+ ]+ for pid, ptype, title, content, tpath, level in pages_data:+ session.add(Page(+ id=pid, repository_id="integ-repo", page_type=ptype,+ title=title, content=content, target_path=tpath,+ source_hash="h" + pid[:6], model_name="mock", provider_name="mock",+ generation_level=level, confidence=0.9, freshness_status="fresh",+ metadata_json="{}", created_at=_NOW, updated_at=_NOW,+ ))++ # Symbols+ sym_data = [+ ("src/auth/login.py", "login_handler", "function",+ "async def login_handler(request: Request) -> Response"),+ ("src/auth/login.py", "LoginForm", "class", "class LoginForm(BaseModel)"),+ ("src/auth/jwt.py", "create_token", "function",+ "def create_token(user_id: str, secret: str) -> str"),+ ("src/auth/jwt.py", "verify_token", "function",+ "def verify_token(token: str, secret: str) -> dict"),+ ("src/data/user_repo.py", "UserRepository", "class",+ "class UserRepository"),+ ("src/data/user_repo.py", "find_by_email", "method",+ "async def find_by_email(self, email: str) -> User | None"),+ ("src/data/models.py", "User", "class", "class User(Base)"),+ ("src/data/models.py", "Session", "class", "class Session(Base)"),+ ]+ for i, (fp, name, kind, sig) in enumerate(sym_data):+ session.add(WikiSymbol(+ id=f"is{i}", repository_id="integ-repo", file_path=fp,+ symbol_id=f"{fp}::{name}", name=name, qualified_name=name,+ kind=kind, signature=sig, start_line=1, end_line=20,+ visibility="public", language="python",+ created_at=_NOW, updated_at=_NOW,+ ))++ # Graph nodes+ files = ["src/auth/login.py", "src/auth/jwt.py",+ "src/data/user_repo.py", "src/data/models.py"]+ for i, fp in enumerate(files):+ session.add(GraphNode(+ id=f"ign{i}", repository_id="integ-repo", node_id=fp,+ node_type="file", language="python", symbol_count=2,+ is_entry_point=(fp == "src/auth/login.py"),+ pagerank=0.8 - i * 0.15, betweenness=0.3, community_id=1 if "auth" in fp else 2,+ created_at=_NOW,+ ))++ # Graph edges+ edge_data = [+ ("src/auth/login.py", "src/auth/jwt.py", '["create_token"]'),+ ("src/auth/login.py", "src/data/user_repo.py", '["UserRepository"]'),+ ("src/data/user_repo.py", "src/data/models.py", '["User"]'),+ ]+ for i, (src, tgt, names) in enumerate(edge_data):+ session.add(GraphEdge(+ id=f"ige{i}", repository_id="integ-repo",+ source_node_id=src, target_node_id=tgt,+ imported_names_json=names, created_at=_NOW,+ ))++ # Git metadata+ session.add(GitMetadata(+ id="igm1", repository_id="integ-repo",+ file_path="src/auth/login.py",+ commit_count_total=50, commit_count_90d=12, commit_count_30d=5,+ first_commit_at=datetime(2025, 1, 1, tzinfo=timezone.utc),+ last_commit_at=datetime(2026, 3, 18, tzinfo=timezone.utc),+ primary_owner_name="Alice", primary_owner_email="[email protected]",+ primary_owner_commit_pct=0.70,+ top_authors_json=json.dumps([{"name": "Alice", "count": 35}, {"name": "Bob", "count": 15}]),+ significant_commits_json=json.dumps([+ {"sha": "a1", "date": "2026-03-18", "message": "Fix OAuth redirect", "author": "Alice"},+ ]),+ co_change_partners_json=json.dumps([+ {"file_path": "src/auth/jwt.py", "count": 8},+ ]),+ is_hotspot=True, is_stable=False, churn_percentile=0.95, age_days=443,+ created_at=_NOW, updated_at=_NOW,+ ))++ # Dead code+ session.add(DeadCodeFinding(+ id="idc1", repository_id="integ-repo",+ kind="unused_export", file_path="src/auth/jwt.py",+ symbol_name="deprecated_verify", symbol_kind="function",+ confidence=0.8, reason="No callers", lines=15, safe_to_delete=True,+ primary_owner="Alice", status="open", analyzed_at=_NOW,+ ))++ await session.commit()++ # Index pages in vector store for search+ await vector_store.embed_and_upsert(+ "file_page:src/auth/login.py", "Login Handler — OAuth and password auth",+ {"title": "Login Handler", "page_type": "file_page", "target_path": "src/auth/login.py"},+ )+ await vector_store.embed_and_upsert(+ "file_page:src/data/models.py", "Data Models — SQLAlchemy User Session Token",+ {"title": "Data Models", "page_type": "file_page", "target_path": "src/data/models.py"},+ )++ # Configure MCP globals+ import wikicode.server.mcp_server as mcp_mod+ mcp_mod._session_factory = factory+ mcp_mod._fts = fts+ mcp_mod._vector_store = vector_store+ mcp_mod._repo_path = "/tmp/sample-project"++ yield++ mcp_mod._session_factory = None+ mcp_mod._fts = None+ mcp_mod._vector_store = None+ mcp_mod._repo_path = None++ await vector_store.close()+ await engine.dispose()+++# ---------------------------------------------------------------------------+# Integration tests — verify end-to-end MCP tool responses+# ---------------------------------------------------------------------------+++async def test_mcp_full_exploration_flow(mcp_env):+ """Test the typical MCP exploration flow: overview → module → file → symbol."""+ from wikicode.server.mcp_server import (+ get_file_docs,+ get_module_docs,+ get_overview,+ get_symbol,+ )++ # Step 1: Get overview+ overview = await get_overview()+ assert "Sample Project" in overview["content_md"]+ assert len(overview["key_modules"]) == 2+ assert overview["architecture_diagram_mermaid"] is not None++ # Step 2: Drill into auth module+ auth_module = await get_module_docs("src/auth")+ assert "authentication" in auth_module["content_md"].lower()+ assert len(auth_module["files"]) == 2++ # Step 3: Get file docs+ login_file = await get_file_docs("src/auth/login.py")+ assert login_file["title"] == "Login Handler"+ assert any(s["name"] == "login_handler" for s in login_file["symbols"])++ # Step 4: Look up a symbol+ symbol = await get_symbol("UserRepository")+ assert symbol["kind"] == "class"+ assert symbol["file_path"] == "src/data/user_repo.py"+++async def test_mcp_dependency_and_graph_flow(mcp_env):+ """Test dependency path and architecture diagram tools."""+ from wikicode.server.mcp_server import (+ get_architecture_diagram,+ get_dependency_path,+ )++ # Dependency path from login to models (2 hops)+ path = await get_dependency_path("src/auth/login.py", "src/data/models.py")+ assert path["distance"] == 2+ assert len(path["path"]) == 3++ # Architecture diagram+ diagram = await get_architecture_diagram(scope="repo")+ assert "graph TD" in diagram["mermaid_syntax"]+++async def test_mcp_git_intelligence_flow(mcp_env):+ """Test git intelligence tools: history, hotspots, ownership, co-changes."""+ from wikicode.server.mcp_server import (+ get_codebase_ownership,+ get_co_changes,+ get_file_history,+ get_hotspots,+ )++ # File history+ history = await get_file_history("src/auth/login.py")+ assert history["is_hotspot"] is True+ assert history["primary_owner"]["name"] == "Alice"+ assert len(history["co_change_partners"]) == 1++ # Hotspots+ hotspots = await get_hotspots()+ assert len(hotspots["hotspots"]) == 1++ # Ownership+ ownership = await get_codebase_ownership()+ assert len(ownership["by_module"]) >= 1++ # Co-changes+ co = await get_co_changes("src/auth/login.py", min_count=3)+ assert len(co["co_change_partners"]) == 1+ assert co["co_change_partners"][0]["file_path"] == "src/auth/jwt.py"+++async def test_mcp_dead_code_and_stale_flow(mcp_env):+ """Test dead code and stale pages tools."""+ from wikicode.server.mcp_server import get_dead_code, get_stale_pages++ # Dead code+ dead = await get_dead_code()+ assert dead["summary"]["total_findings"] == 1+ assert dead["findings"][0]["symbol_name"] == "deprecated_verify"++ # Stale pages (all have confidence 0.9, so threshold 0.95 catches them)+ stale = await get_stale_pages(threshold=0.95)+ assert len(stale["stale_pages"]) >= 1+++async def test_mcp_search_flow(mcp_env):+ """Test semantic search."""+ from wikicode.server.mcp_server import search_codebase++ result = await search_codebase("authentication login OAuth")+ assert "results" in result+ assert len(result["results"]) >= 1diff --git a/tests/integration/test_persistence.py b/tests/integration/test_persistence.pynew file mode 100644index 000000000..625191b2b--- /dev/null+++ b/tests/integration/test_persistence.py@@ -0,0 +1,450 @@+"""Integration tests for Phase 4 — Persistence.++Runs the full generation pipeline on sample_repo, stores all generated pages+in an in-memory SQLite database, and validates:+- Round-trip store/retrieve fidelity+- Version history after re-generation+- Full-text search over stored content+- Vector search with InMemoryVectorStore + MockEmbedder+- Generation job status transitions+"""++from __future__ import annotations++from pathlib import Path++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine+from sqlalchemy.pool import StaticPool++from wikicode.core.generation.context_assembler import ContextAssembler+from wikicode.core.generation.job_system import JobSystem+from wikicode.core.generation.models import GenerationConfig, GeneratedPage+from wikicode.core.generation.page_generator import PageGenerator+from wikicode.core.ingestion.graph import GraphBuilder+from wikicode.core.ingestion.models import PackageInfo, RepoStructure+from wikicode.core.ingestion.parser import ASTParser+from wikicode.core.ingestion.traverser import FileTraverser+from wikicode.core.persistence import (+ FullTextSearch,+ InMemoryVectorStore,+ MockEmbedder,+ create_session_factory,+ get_page,+ get_page_versions,+ get_stale_pages,+ init_db,+ list_pages,+ update_job_status,+ upsert_generation_job,+ upsert_page_from_generated,+ upsert_repository,+)+from wikicode.core.providers.mock import MockProvider++SAMPLE_REPO = Path(__file__).parents[1] / "fixtures" / "sample_repo"+++# ---------------------------------------------------------------------------+# Engine + session factory shared across the class+# ---------------------------------------------------------------------------++[email protected](scope="class")+async def engine():+ eng = create_async_engine(+ "sqlite+aiosqlite:///:memory:",+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+ )+ await init_db(eng)+ yield eng+ await eng.dispose()++[email protected](scope="class")+def sf(engine):+ return create_session_factory(engine)+++# ---------------------------------------------------------------------------+# Generation pipeline + persistence fixture (class-scoped — runs once)+# ---------------------------------------------------------------------------++[email protected](scope="class")+async def persisted(engine, sf, tmp_path_factory):+ """Run the generation pipeline on sample_repo and persist all pages.++ Returns a dict with:+ repo_id: Repository PK+ job_id: GenerationJob PK+ pages: list[GeneratedPage]+ session_factory: for sub-fixtures+ """+ tmp = tmp_path_factory.mktemp("persist")++ # --- Ingest ---+ traverser = FileTraverser(SAMPLE_REPO)+ parser = ASTParser()+ builder = GraphBuilder()+ parsed_files = []+ source_map: dict = {}++ for fi in traverser.traverse():+ try:+ src = Path(fi.abs_path).read_bytes()+ pf = parser.parse_file(fi, src)+ builder.add_file(pf)+ parsed_files.append(pf)+ source_map[fi.path] = src+ except Exception:+ pass++ graph = builder.build() # noqa: F841 (kept for builder ref below)++ pkg_dirs = [d for d in SAMPLE_REPO.iterdir() if d.is_dir()]+ packages = [+ PackageInfo(+ name=d.name,+ path=d.name,+ language="unknown",+ entry_points=[],+ manifest_file="",+ )+ for d in pkg_dirs+ ]+ repo_structure = RepoStructure(+ is_monorepo=len(packages) > 1,+ packages=packages,+ root_language_distribution={"python": 0.5},+ total_files=len(parsed_files),+ total_loc=sum(len(source_map.get(p.file_info.path, b"").splitlines()) for p in parsed_files),+ entry_points=[],+ )++ # --- Generate (mock LLM) ---+ config = GenerationConfig(+ max_tokens=512,+ token_budget=2000,+ max_concurrency=2,+ cache_enabled=True,+ jobs_dir=str(tmp / "jobs"),+ )+ provider = MockProvider()+ assembler = ContextAssembler(config)+ generator = PageGenerator(provider, assembler, config)+ job_sys = JobSystem(tmp / "jobs")++ pages: list[GeneratedPage] = await generator.generate_all(+ parsed_files, source_map, builder, repo_structure, "sample_repo", job_sys+ )++ # --- Persist ---+ async with sf() as session:+ repo = await upsert_repository(+ session,+ name="sample_repo",+ local_path=str(SAMPLE_REPO),+ url="https://github.com/example/sample_repo",+ )+ repo_id = repo.id+ await session.commit()++ async with sf() as session:+ job = await upsert_generation_job(+ session,+ repository_id=repo_id,+ provider_name="mock",+ model_name="mock-v1",+ total_pages=len(pages),+ )+ job_id = job.id+ await session.commit()++ async with sf() as session:+ await update_job_status(session, job_id, "running")+ await session.commit()++ for page in pages:+ async with sf() as session:+ await upsert_page_from_generated(session, page, repo_id)+ await session.commit()++ async with sf() as session:+ await update_job_status(+ session,+ job_id,+ "completed",+ completed_pages=len(pages),+ )+ await session.commit()++ return {+ "repo_id": repo_id,+ "job_id": job_id,+ "pages": pages,+ "sf": sf,+ "engine": engine,+ }+++# ---------------------------------------------------------------------------+# Store / retrieve tests+# ---------------------------------------------------------------------------+++class TestPersistenceStoreRetrieve:+ async def test_all_generated_pages_stored(self, persisted, sf):+ """Every GeneratedPage should be retrievable by page_id."""+ pages = persisted["pages"]+ repo_id = persisted["repo_id"]+ assert len(pages) > 0++ async with sf() as session:+ for page in pages:+ stored = await get_page(session, page.page_id)+ assert stored is not None, f"Page {page.page_id!r} not found in DB"++ async def test_stored_page_fields_match_generated_page(self, persisted, sf):+ """Spot-check: title, content, source_hash, page_type must round-trip."""+ pages = persisted["pages"]+ gp = pages[0]++ async with sf() as session:+ stored = await get_page(session, gp.page_id)++ assert stored is not None+ assert stored.title == gp.title+ assert stored.content == gp.content+ assert stored.source_hash == gp.source_hash+ assert stored.page_type == gp.page_type+ assert stored.provider_name == gp.provider_name+ assert stored.model_name == gp.model_name++ async def test_list_pages_by_repository_returns_all(self, persisted, sf):+ repo_id = persisted["repo_id"]+ page_count = len(persisted["pages"])++ async with sf() as session:+ db_pages = await list_pages(session, repo_id, limit=page_count + 10)++ assert len(db_pages) == page_count++ async def test_list_pages_filters_by_page_type(self, persisted, sf):+ repo_id = persisted["repo_id"]+ pages = persisted["pages"]+ expected_types = {p.page_type for p in pages}++ for pt in expected_types:+ async with sf() as session:+ filtered = await list_pages(session, repo_id, page_type=pt, limit=200)+ expected_count = sum(1 for p in pages if p.page_type == pt)+ assert len(filtered) == expected_count, (+ f"Expected {expected_count} pages of type {pt!r}, got {len(filtered)}"+ )++ async def test_stored_page_version_is_1_on_first_insert(self, persisted, sf):+ pages = persisted["pages"]+ async with sf() as session:+ stored = await get_page(session, pages[0].page_id)+ assert stored.version == 1+++# ---------------------------------------------------------------------------+# Version history tests+# ---------------------------------------------------------------------------+++class TestVersionHistory:+ async def test_version_history_after_re_generation(self, persisted, sf):+ """Re-upserting the same page should create one PageVersion snapshot."""+ pages = persisted["pages"]+ repo_id = persisted["repo_id"]+ gp = pages[0]++ # Store a second version with modified content+ from wikicode.core.persistence.crud import upsert_page++ async with sf() as session:+ await upsert_page(+ session,+ page_id=gp.page_id,+ repository_id=repo_id,+ page_type=gp.page_type,+ title=gp.title,+ content=gp.content + "\n\n## Updated Section",+ target_path=gp.target_path,+ source_hash="updated_hash_v2",+ model_name=gp.model_name,+ provider_name=gp.provider_name,+ )+ await session.commit()++ async with sf() as session:+ versions = await get_page_versions(session, gp.page_id)++ assert len(versions) == 1+ assert versions[0].version == 1+ assert versions[0].source_hash == gp.source_hash # original hash++ async def test_page_version_increments(self, persisted, sf):+ """After a second upsert, page.version should be 2."""+ pages = persisted["pages"]+ gp = pages[0]++ async with sf() as session:+ stored = await get_page(session, gp.page_id)++ # version is at least 2 (first upsert + re-upsert in previous test)+ assert stored.version >= 2++ async def test_page_version_created_at_preserved(self, persisted, sf):+ """created_at must not change after an update."""+ pages = persisted["pages"]+ gp = pages[0]++ async with sf() as session:+ stored = await get_page(session, gp.page_id)++ assert stored.created_at is not None+ # The original page was stored from the generated page's created_at+ # Just verify it's set and is a real datetime+ from datetime import datetime+ assert isinstance(stored.created_at, datetime)+++# ---------------------------------------------------------------------------+# Full-text search tests+# ---------------------------------------------------------------------------+++class TestFullTextSearch:+ @pytest.fixture(scope="class")+ async def fts(self, persisted):+ fts = FullTextSearch(persisted["engine"])+ await fts.ensure_index()++ # Index all stored pages into FTS+ pages = persisted["pages"]+ for page in pages:+ await fts.index(page.page_id, page.title, page.content)++ return fts++ async def test_full_text_search_finds_page_by_title(self, persisted, fts):+ pages = persisted["pages"]+ first_page = pages[0]+ # Search for a word from the title+ title_word = first_page.title.split()[0] if first_page.title else "module"++ results = await fts.search(title_word)+ page_ids = {r.page_id for r in results}+ assert first_page.page_id in page_ids++ async def test_full_text_search_returns_search_results(self, persisted, fts):+ from wikicode.core.persistence.search import SearchResult++ results = await fts.search("module", limit=5)+ assert len(results) <= 5+ for r in results:+ assert isinstance(r, SearchResult)+ assert r.search_type == "fulltext"++ async def test_full_text_search_scores_positive(self, persisted, fts):+ results = await fts.search("function")+ for r in results:+ assert r.score > 0.0++ async def test_full_text_search_snippet_length(self, persisted, fts):+ results = await fts.search("module")+ for r in results:+ assert len(r.snippet) <= 200+++# ---------------------------------------------------------------------------+# Vector search tests+# ---------------------------------------------------------------------------+++class TestVectorSearch:+ @pytest.fixture(scope="class")+ async def vector_store(self, persisted):+ embedder = MockEmbedder()+ store = InMemoryVectorStore(embedder=embedder)++ for page in persisted["pages"]:+ await store.embed_and_upsert(+ page.page_id,+ page.title + " " + page.content[:200],+ {+ "title": page.title,+ "page_type": page.page_type,+ "target_path": page.target_path,+ "content": page.content[:200],+ },+ )++ return store++ async def test_vector_store_has_all_pages(self, persisted, vector_store):+ assert len(vector_store) == len(persisted["pages"])++ async def test_vector_search_returns_results(self, vector_store):+ results = await vector_store.search("module documentation", limit=5)+ assert len(results) > 0++ async def test_vector_search_result_has_required_fields(self, vector_store):+ from wikicode.core.persistence.search import SearchResult++ results = await vector_store.search("function", limit=3)+ for r in results:+ assert isinstance(r, SearchResult)+ assert r.page_id != ""+ assert r.search_type == "vector"+ assert 0.0 <= r.score <= 1.0++ async def test_vector_search_limit_respected(self, vector_store):+ results = await vector_store.search("code", limit=2)+ assert len(results) <= 2++ async def test_vector_search_correct_page_type(self, persisted, vector_store):+ """Each vector search result's page_id should correspond to a known page."""+ known_ids = {p.page_id for p in persisted["pages"]}+ results = await vector_store.search("module", limit=10)+ for r in results:+ assert r.page_id in known_ids+++# ---------------------------------------------------------------------------+# Generation job tests+# ---------------------------------------------------------------------------+++class TestGenerationJob:+ async def test_job_completed_status(self, persisted, sf):+ from wikicode.core.persistence import get_generation_job++ async with sf() as session:+ job = await get_generation_job(session, persisted["job_id"])++ assert job is not None+ assert job.status == "completed"+ assert job.completed_pages == len(persisted["pages"])+ assert job.finished_at is not None++ async def test_job_started_at_set(self, persisted, sf):+ from wikicode.core.persistence import get_generation_job++ async with sf() as session:+ job = await get_generation_job(session, persisted["job_id"])++ assert job.started_at is not None++ async def test_job_total_pages_matches_generated(self, persisted, sf):+ from wikicode.core.persistence import get_generation_job++ async with sf() as session:+ job = await get_generation_job(session, persisted["job_id"])++ assert job.total_pages == len(persisted["pages"])diff --git a/tests/providers/__init__.py b/tests/providers/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/providers/conftest.py b/tests/providers/conftest.pynew file mode 100644index 000000000..46059e4d1--- /dev/null+++ b/tests/providers/conftest.py@@ -0,0 +1,35 @@+"""Shared fixtures for provider tests."""++from __future__ import annotations++import pytest++from wikicode.core.providers.base import GeneratedResponse+from wikicode.core.providers.mock import MockProvider+++def mock_provider() -> MockProvider:+ """A fresh MockProvider instance for each test."""+ return MockProvider()+++def preset_response() -> GeneratedResponse:+ """A standard GeneratedResponse for use in preset-based tests."""+ return GeneratedResponse(+ content="## Test Documentation\n\nThis is a test page.",+ input_tokens=100,+ output_tokens=50,+ cached_tokens=0,+ usage={"mock": True},+ )+++def two_preset_responses() -> list[GeneratedResponse]:+ """Two distinct GeneratedResponse objects for sequence testing."""+ return [+ GeneratedResponse("First page", 100, 50),+ GeneratedResponse("Second page", 200, 100),+ ]diff --git a/tests/providers/fixtures/default.json b/tests/providers/fixtures/default.jsonnew file mode 100644index 000000000..dfb365c22--- /dev/null+++ b/tests/providers/fixtures/default.json@@ -0,0 +1,10 @@+{+ "content": "## Overview\n\nThis is a fixture response from WikiCode's test suite. It simulates a documentation page generated by a real LLM provider.\n\n### Purpose\n\nThe `default` fixture is used when `MockProvider` is constructed without a specific fixture name. It provides a realistic-looking markdown response for testing the ingestion and rendering pipeline.\n\n### Public API\n\n- `add(x: int, y: int) -> int` — Returns the sum of two integers.\n- `subtract(x: int, y: int) -> int` — Returns the difference of two integers.\n\n### Usage Example\n\n```python\nfrom sample_pkg.calculator import add, subtract\n\nresult = add(2, 3) # 5\ndiff = subtract(10, 4) # 6\n```\n\n### Error Handling\n\nThis module does not raise exceptions for valid integer inputs.",+ "input_tokens": 500,+ "output_tokens": 150,+ "cached_tokens": 0,+ "usage": {+ "mock": true,+ "fixture": "default"+ }+}diff --git a/tests/providers/test_mock_provider.py b/tests/providers/test_mock_provider.pynew file mode 100644index 000000000..09288725e--- /dev/null+++ b/tests/providers/test_mock_provider.py@@ -0,0 +1,249 @@+"""Tests for MockProvider.++Verifies that MockProvider correctly implements the BaseProvider interface+and that all test-helper features work as expected. No API keys or network+access are required to run these tests.+"""++from __future__ import annotations++import pytest++from wikicode.core.providers.base import BaseProvider, GeneratedResponse+from wikicode.core.providers.mock import MockProvider+++# ---------------------------------------------------------------------------+# Interface contract+# ---------------------------------------------------------------------------+++class TestBaseProviderInterface:+ """MockProvider must fully satisfy the BaseProvider interface contract."""++ def test_is_base_provider_subclass(self) -> None:+ assert issubclass(MockProvider, BaseProvider)++ def test_provider_name_is_mock(self) -> None:+ provider = MockProvider()+ assert provider.provider_name == "mock"++ def test_model_name_default(self) -> None:+ provider = MockProvider()+ assert provider.model_name == "mock-model-1"++ def test_model_name_custom(self) -> None:+ provider = MockProvider(model="custom-test-model")+ assert provider.model_name == "custom-test-model"++ async def test_generate_returns_generated_response(self) -> None:+ provider = MockProvider()+ result = await provider.generate(+ system_prompt="You are a documentation assistant.",+ user_prompt="Document this function: def add(a, b): return a + b",+ )+ assert isinstance(result, GeneratedResponse)++ async def test_generate_content_is_non_empty_string(self) -> None:+ provider = MockProvider()+ result = await provider.generate(system_prompt="sys", user_prompt="user")+ assert isinstance(result.content, str)+ assert len(result.content) > 0++ async def test_generate_token_counts_are_non_negative(self) -> None:+ provider = MockProvider()+ result = await provider.generate(system_prompt="sys", user_prompt="user")+ assert result.input_tokens >= 0+ assert result.output_tokens >= 0+ assert result.cached_tokens >= 0++ async def test_total_tokens_equals_input_plus_output(self) -> None:+ provider = MockProvider()+ result = await provider.generate(system_prompt="sys", user_prompt="user")+ assert result.total_tokens == result.input_tokens + result.output_tokens++ async def test_usage_dict_is_populated(self) -> None:+ provider = MockProvider()+ result = await provider.generate(system_prompt="sys", user_prompt="user")+ assert isinstance(result.usage, dict)++ async def test_generate_accepts_all_parameters(self) -> None:+ """All BaseProvider.generate() parameters must be accepted."""+ provider = MockProvider()+ result = await provider.generate(+ system_prompt="system",+ user_prompt="user",+ max_tokens=2048,+ temperature=0.0,+ request_id="test-req-001",+ )+ assert isinstance(result, GeneratedResponse)+++# ---------------------------------------------------------------------------+# Call tracking+# ---------------------------------------------------------------------------+++class TestCallTracking:+ """MockProvider records every call for test-time assertions."""++ async def test_initial_call_count_is_zero(self) -> None:+ provider = MockProvider()+ assert provider.call_count == 0++ async def test_call_count_increments_per_generate(self) -> None:+ provider = MockProvider()+ await provider.generate("sys", "first")+ assert provider.call_count == 1+ await provider.generate("sys", "second")+ assert provider.call_count == 2++ async def test_calls_list_records_each_call(self) -> None:+ provider = MockProvider()+ await provider.generate("sys", "user1")+ await provider.generate("sys", "user2")+ assert len(provider.calls) == 2++ async def test_calls_record_all_arguments(self) -> None:+ provider = MockProvider()+ await provider.generate(+ system_prompt="my system",+ user_prompt="my user",+ max_tokens=2048,+ temperature=0.5,+ request_id="req-abc",+ )+ call = provider.calls[0]+ assert call["system_prompt"] == "my system"+ assert call["user_prompt"] == "my user"+ assert call["max_tokens"] == 2048+ assert call["temperature"] == 0.5+ assert call["request_id"] == "req-abc"++ async def test_calls_list_is_ordered(self) -> None:+ provider = MockProvider()+ await provider.generate("sys", "first")+ await provider.generate("sys", "second")+ assert provider.calls[0]["user_prompt"] == "first"+ assert provider.calls[1]["user_prompt"] == "second"++ async def test_reset_clears_call_count(self) -> None:+ provider = MockProvider()+ await provider.generate("sys", "user")+ provider.reset()+ assert provider.call_count == 0++ async def test_reset_clears_calls_list(self) -> None:+ provider = MockProvider()+ await provider.generate("sys", "user")+ provider.reset()+ assert provider.calls == []++ async def test_reset_allows_reuse(self) -> None:+ provider = MockProvider()+ await provider.generate("sys", "user")+ provider.reset()+ await provider.generate("sys", "new user")+ assert provider.call_count == 1+ assert provider.calls[0]["user_prompt"] == "new user"++ def test_calls_property_returns_copy(self) -> None:+ """Mutating the returned list must not affect internal state."""+ provider = MockProvider()+ calls = provider.calls+ calls.append({"tampered": True}) # type: ignore[arg-type]+ assert provider.call_count == 0+++# ---------------------------------------------------------------------------+# Preset responses+# ---------------------------------------------------------------------------+++class TestPresetResponses:+ """MockProvider can return specific responses in a controlled sequence."""++ async def test_single_preset_returned_on_first_call(self) -> None:+ response = GeneratedResponse("Only response", 100, 50)+ provider = MockProvider(responses=[response])+ result = await provider.generate("sys", "user")+ assert result.content == "Only response"++ async def test_preset_responses_returned_in_order(self) -> None:+ responses = [+ GeneratedResponse("First", 100, 50),+ GeneratedResponse("Second", 200, 100),+ GeneratedResponse("Third", 300, 150),+ ]+ provider = MockProvider(responses=responses)++ r1 = await provider.generate("sys", "u")+ r2 = await provider.generate("sys", "u")+ r3 = await provider.generate("sys", "u")++ assert r1.content == "First"+ assert r2.content == "Second"+ assert r3.content == "Third"++ async def test_last_preset_repeated_after_exhaustion(self) -> None:+ """Once presets run out, the last one is repeated — never raises."""+ responses = [+ GeneratedResponse("First", 100, 50),+ GeneratedResponse("Last", 200, 100),+ ]+ provider = MockProvider(responses=responses)++ await provider.generate("sys", "u") # "First"+ await provider.generate("sys", "u") # "Last"+ r3 = await provider.generate("sys", "u") # "Last" again+ r4 = await provider.generate("sys", "u") # "Last" again++ assert r3.content == "Last"+ assert r4.content == "Last"++ async def test_preset_token_counts_preserved(self) -> None:+ response = GeneratedResponse(+ content="content",+ input_tokens=500,+ output_tokens=250,+ cached_tokens=100,+ )+ provider = MockProvider(responses=[response])+ result = await provider.generate("sys", "user")++ assert result.input_tokens == 500+ assert result.output_tokens == 250+ assert result.cached_tokens == 100++ async def test_preset_overrides_fixture_file(self) -> None:+ """When preset responses are provided, fixture files are not loaded."""+ responses = [GeneratedResponse("preset wins", 10, 5)]+ provider = MockProvider(fixture_name="default", responses=responses)+ result = await provider.generate("sys", "user")+ assert result.content == "preset wins"+++# ---------------------------------------------------------------------------+# GeneratedResponse dataclass+# ---------------------------------------------------------------------------+++class TestGeneratedResponse:+ """GeneratedResponse must behave correctly as a dataclass."""++ def test_default_cached_tokens_is_zero(self) -> None:+ r = GeneratedResponse(content="x", input_tokens=10, output_tokens=5)+ assert r.cached_tokens == 0++ def test_default_usage_is_empty_dict(self) -> None:+ r = GeneratedResponse(content="x", input_tokens=10, output_tokens=5)+ assert r.usage == {}++ def test_total_tokens(self) -> None:+ r = GeneratedResponse(content="x", input_tokens=100, output_tokens=50)+ assert r.total_tokens == 150++ def test_total_tokens_with_zero_values(self) -> None:+ r = GeneratedResponse(content="x", input_tokens=0, output_tokens=0)+ assert r.total_tokens == 0diff --git a/tests/providers/test_rate_limiter.py b/tests/providers/test_rate_limiter.pynew file mode 100644index 000000000..1da24ae72--- /dev/null+++ b/tests/providers/test_rate_limiter.py@@ -0,0 +1,152 @@+"""Tests for the RateLimiter.++These tests verify the rate limiter's behavior without requiring any LLM calls.+Tests that verify actual waiting behavior use short windows to keep the suite fast.+"""++from __future__ import annotations++import asyncio+import time++import pytest++from wikicode.core.rate_limiter import PROVIDER_DEFAULTS, RateLimitConfig, RateLimiter+++class TestRateLimitConfig:+ def test_config_stores_values(self) -> None:+ config = RateLimitConfig(requests_per_minute=30, tokens_per_minute=50_000)+ assert config.requests_per_minute == 30+ assert config.tokens_per_minute == 50_000++ def test_config_is_frozen(self) -> None:+ config = RateLimitConfig(requests_per_minute=10, tokens_per_minute=1_000)+ with pytest.raises((AttributeError, TypeError)):+ config.requests_per_minute = 999 # type: ignore[misc]++ def test_provider_defaults_exist(self) -> None:+ assert "anthropic" in PROVIDER_DEFAULTS+ assert "openai" in PROVIDER_DEFAULTS+ assert "ollama" in PROVIDER_DEFAULTS+ assert "litellm" in PROVIDER_DEFAULTS++ def test_provider_defaults_are_rate_limit_configs(self) -> None:+ for name, config in PROVIDER_DEFAULTS.items():+ assert isinstance(config, RateLimitConfig), f"{name} default is not RateLimitConfig"+ assert config.requests_per_minute > 0+ assert config.tokens_per_minute > 0+++class TestRateLimiterAcquire:+ async def test_acquire_succeeds_within_limits(self) -> None:+ config = RateLimitConfig(requests_per_minute=60, tokens_per_minute=100_000)+ limiter = RateLimiter(config)+ # Should complete immediately without raising+ await limiter.acquire(estimated_tokens=1_000)++ async def test_acquire_records_request(self) -> None:+ config = RateLimitConfig(requests_per_minute=60, tokens_per_minute=100_000)+ limiter = RateLimiter(config)+ await limiter.acquire(estimated_tokens=500)+ # One request should now be recorded+ assert len(limiter._request_times) == 1 # noqa: SLF001++ async def test_multiple_acquires_within_limits(self) -> None:+ config = RateLimitConfig(requests_per_minute=100, tokens_per_minute=1_000_000)+ limiter = RateLimiter(config)+ for _ in range(10):+ await limiter.acquire(estimated_tokens=100)+ assert len(limiter._request_times) == 10 # noqa: SLF001++ async def test_acquire_respects_rpm_limit(self) -> None:+ """Acquiring more than RPM slots should block until window clears."""+ # Use a very high token limit and low RPM to isolate RPM behavior+ config = RateLimitConfig(requests_per_minute=2, tokens_per_minute=10_000_000)+ limiter = RateLimiter(config)++ # Fill up RPM limit+ await limiter.acquire(estimated_tokens=1)+ await limiter.acquire(estimated_tokens=1)++ # Manually expire the window by backdating the timestamps+ now = time.monotonic()+ limiter._request_times = [now - 61.0, now - 61.0] # noqa: SLF001+ limiter._token_records = [(now - 61.0, 1), (now - 61.0, 1)] # noqa: SLF001++ # Third acquire should now succeed immediately (window cleared)+ await asyncio.wait_for(limiter.acquire(estimated_tokens=1), timeout=1.0)++ async def test_acquire_respects_tpm_limit(self) -> None:+ """Acquiring more than TPM tokens should block until window clears."""+ config = RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=100)+ limiter = RateLimiter(config)++ # Fill up TPM with one large request+ await limiter.acquire(estimated_tokens=100)++ # Manually expire the window+ now = time.monotonic()+ limiter._request_times = [now - 61.0] # noqa: SLF001+ limiter._token_records = [(now - 61.0, 100)] # noqa: SLF001++ # Next acquire should succeed+ await asyncio.wait_for(limiter.acquire(estimated_tokens=100), timeout=1.0)+++class TestRateLimiterPruning:+ async def test_old_records_are_pruned(self) -> None:+ config = RateLimitConfig(requests_per_minute=5, tokens_per_minute=10_000)+ limiter = RateLimiter(config)++ # Inject old timestamps (> 60s ago)+ old_time = time.monotonic() - 65.0+ limiter._request_times = [old_time, old_time] # noqa: SLF001+ limiter._token_records = [(old_time, 500), (old_time, 500)] # noqa: SLF001++ # Acquire should prune stale records and succeed+ await limiter.acquire(estimated_tokens=100)+ # After pruning, only the new request remains+ assert len(limiter._request_times) == 1 # noqa: SLF001+++class TestRateLimiterBackoff:+ async def test_on_rate_limit_error_attempt_0_waits_at_least_1s(self) -> None:+ config = RateLimitConfig(requests_per_minute=60, tokens_per_minute=100_000)+ limiter = RateLimiter(config)++ start = time.monotonic()+ await limiter.on_rate_limit_error(attempt=0)+ elapsed = time.monotonic() - start++ # 2^0 = 1 second base + jitter [0, 1)+ assert elapsed >= 1.0++ async def test_on_rate_limit_error_caps_at_64s(self) -> None:+ """For high attempt numbers, wait should be capped at 64 + jitter seconds."""+ config = RateLimitConfig(requests_per_minute=60, tokens_per_minute=100_000)+ limiter = RateLimiter(config)++ # attempt=10 → 2^10 = 1024, but capped at 64+ # We don't actually wait; just verify the formula via monkeypatching+ waited: list[float] = []+ original_sleep = asyncio.sleep++ async def mock_sleep(delay: float) -> None:+ waited.append(delay)++ import asyncio as _asyncio+ _asyncio.sleep = mock_sleep # type: ignore[assignment]+ try:+ await limiter.on_rate_limit_error(attempt=10)+ finally:+ _asyncio.sleep = original_sleep # type: ignore[assignment]++ assert waited, "asyncio.sleep was not called"+ # base is capped at 64, plus jitter < 1+ assert waited[0] < 65.0++ async def test_config_property(self) -> None:+ config = RateLimitConfig(requests_per_minute=30, tokens_per_minute=60_000)+ limiter = RateLimiter(config)+ assert limiter.config is configdiff --git a/tests/providers/test_registry.py b/tests/providers/test_registry.pynew file mode 100644index 000000000..ee36608c7--- /dev/null+++ b/tests/providers/test_registry.py@@ -0,0 +1,118 @@+"""Tests for the provider registry.++Verifies that get_provider(), list_providers(), and register_provider()+work correctly. All tests use the mock provider — no API keys required.+"""++from __future__ import annotations++import pytest++from wikicode.core.providers.base import BaseProvider+from wikicode.core.providers.mock import MockProvider+from wikicode.core.providers.registry import (+ _BUILTIN_PROVIDERS,+ get_provider,+ list_providers,+ register_provider,+)+++class TestListProviders:+ def test_includes_all_builtin_providers(self) -> None:+ providers = list_providers()+ assert "anthropic" in providers+ assert "openai" in providers+ assert "ollama" in providers+ assert "litellm" in providers+ assert "mock" in providers++ def test_returns_sorted_list(self) -> None:+ providers = list_providers()+ assert providers == sorted(providers)++ def test_returns_list_of_strings(self) -> None:+ providers = list_providers()+ assert all(isinstance(p, str) for p in providers)+++class TestGetMockProvider:+ """Mock provider can be retrieved without any API keys."""++ def test_get_mock_provider_returns_mock_provider(self) -> None:+ provider = get_provider("mock", with_rate_limiter=False)+ assert isinstance(provider, MockProvider)++ def test_get_mock_provider_is_base_provider(self) -> None:+ provider = get_provider("mock", with_rate_limiter=False)+ assert isinstance(provider, BaseProvider)++ def test_mock_provider_name(self) -> None:+ provider = get_provider("mock", with_rate_limiter=False)+ assert provider.provider_name == "mock"++ def test_mock_provider_model_passthrough(self) -> None:+ provider = get_provider("mock", model="my-model", with_rate_limiter=False)+ assert provider.model_name == "my-model"++ def test_mock_provider_no_rate_limiter_by_default(self) -> None:+ """Mock provider should never have a rate limiter."""+ provider = get_provider("mock")+ # MockProvider doesn't store rate_limiter, but we verify it's MockProvider+ assert isinstance(provider, MockProvider)+++class TestUnknownProvider:+ def test_unknown_provider_raises_value_error(self) -> None:+ with pytest.raises(ValueError, match="Unknown provider"):+ get_provider("not_a_real_provider_xyz_abc")++ def test_error_message_lists_available_providers(self) -> None:+ with pytest.raises(ValueError) as exc_info:+ get_provider("bad_provider")+ error_msg = str(exc_info.value)+ assert "anthropic" in error_msg+ assert "mock" in error_msg+++class TestCustomProviderRegistration:+ """External packages can register providers at runtime."""++ def test_register_custom_provider(self) -> None:+ """A registered factory is callable via get_provider()."""++ class CustomProvider(MockProvider):+ @property+ def provider_name(self) -> str:+ return "custom_test_provider"++ register_provider("_test_custom_1", lambda **kw: CustomProvider(**kw))+ provider = get_provider("_test_custom_1", with_rate_limiter=False)+ assert provider.provider_name == "custom_test_provider"++ def test_registered_provider_in_list(self) -> None:+ register_provider("_test_custom_2", lambda **kw: MockProvider(**kw))+ assert "_test_custom_2" in list_providers()++ def test_register_over_builtin_raises(self) -> None:+ """Cannot override a built-in provider name."""+ with pytest.raises(ValueError, match="conflicts with a built-in provider"):+ register_provider("anthropic", lambda **kw: MockProvider(**kw))++ def test_kwargs_passed_to_factory(self) -> None:+ """Factory receives all kwargs from get_provider()."""+ received: dict[str, object] = {}++ def factory(**kw: object) -> MockProvider:+ received.update(kw)+ return MockProvider()++ register_provider("_test_kwargs", factory)+ get_provider("_test_kwargs", model="my-model", api_key="key-123")++ assert received.get("model") == "my-model"+ assert received.get("api_key") == "key-123"++ def test_builtin_count(self) -> None:+ """Sanity check: we have exactly 5 built-in providers."""+ assert len(_BUILTIN_PROVIDERS) == 5diff --git a/tests/unit/__init__.py b/tests/unit/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/unit/cli/__init__.py b/tests/unit/cli/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/unit/cli/test_commands.py b/tests/unit/cli/test_commands.pynew file mode 100644index 000000000..7ec51ff8a--- /dev/null+++ b/tests/unit/cli/test_commands.py@@ -0,0 +1,116 @@+"""Unit tests for CLI commands using CliRunner."""++from __future__ import annotations++import pytest+from click.testing import CliRunner++from wikicode.cli.main import cli+++def runner():+ return CliRunner()+++# ---------------------------------------------------------------------------+# Basic CLI tests+# ---------------------------------------------------------------------------+++class TestCliBasics:+ def test_version(self, runner):+ result = runner.invoke(cli, ["--version"])+ assert result.exit_code == 0+ assert "wikicode" in result.output+ assert "0.1.0" in result.output++ def test_help(self, runner):+ result = runner.invoke(cli, ["--help"])+ assert result.exit_code == 0+ assert "WikiCode" in result.output++ def test_init_help(self, runner):+ result = runner.invoke(cli, ["init", "--help"])+ assert result.exit_code == 0+ assert "--provider" in result.output+ assert "--dry-run" in result.output+ assert "--skip-tests" in result.output++ def test_update_help(self, runner):+ result = runner.invoke(cli, ["update", "--help"])+ assert result.exit_code == 0+ assert "--since" in result.output++ def test_search_help(self, runner):+ result = runner.invoke(cli, ["search", "--help"])+ assert result.exit_code == 0+ assert "--mode" in result.output++ def test_export_help(self, runner):+ result = runner.invoke(cli, ["export", "--help"])+ assert result.exit_code == 0+ assert "--format" in result.output++ def test_status_help(self, runner):+ result = runner.invoke(cli, ["status", "--help"])+ assert result.exit_code == 0++ def test_doctor_help(self, runner):+ result = runner.invoke(cli, ["doctor", "--help"])+ assert result.exit_code == 0++ def test_watch_help(self, runner):+ result = runner.invoke(cli, ["watch", "--help"])+ assert result.exit_code == 0+ assert "--debounce" in result.output+++# ---------------------------------------------------------------------------+# Stub commands+# ---------------------------------------------------------------------------+++class TestStubs:+ def test_serve_help(self, runner):+ result = runner.invoke(cli, ["serve", "--help"])+ assert result.exit_code == 0+ assert "--port" in result.output++ def test_mcp_help(self, runner):+ result = runner.invoke(cli, ["mcp", "--help"])+ assert result.exit_code == 0+ assert "--transport" in result.output+ assert "stdio" in result.output+++# ---------------------------------------------------------------------------+# Error cases+# ---------------------------------------------------------------------------+++class TestErrorCases:+ def test_init_nonexistent_path(self, runner, tmp_path):+ bad_path = str(tmp_path / "nonexistent")+ result = runner.invoke(cli, ["init", bad_path])+ assert result.exit_code != 0++ def test_init_no_provider(self, runner, tmp_path, monkeypatch):+ """init with no provider configured should error."""+ monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)+ monkeypatch.delenv("WIKICODE_PROVIDER", raising=False)+ result = runner.invoke(cli, ["init", str(tmp_path)])+ assert result.exit_code != 0++ def test_status_no_wikicode_dir(self, runner, tmp_path):+ result = runner.invoke(cli, ["status", str(tmp_path)])+ assert result.exit_code == 0+ assert "No .wikicode/" in result.output++ def test_update_no_state(self, runner, tmp_path):+ """update without prior init should error."""+ (tmp_path / ".wikicode").mkdir()+ result = runner.invoke(cli, ["update", str(tmp_path)])+ assert result.exit_code != 0diff --git a/tests/unit/cli/test_cost_estimator.py b/tests/unit/cli/test_cost_estimator.pynew file mode 100644index 000000000..d5830ba39--- /dev/null+++ b/tests/unit/cli/test_cost_estimator.py@@ -0,0 +1,173 @@+"""Unit tests for wikicode.cli.cost_estimator."""++from __future__ import annotations++from dataclasses import dataclass, field+from unittest.mock import MagicMock++import pytest++from wikicode.cli.cost_estimator import (+ CostEstimate,+ PageTypePlan,+ build_generation_plan,+ estimate_cost,+)+++# ---------------------------------------------------------------------------+# Fixtures — lightweight fakes to avoid importing full ingestion models+# ---------------------------------------------------------------------------+++@dataclass+class FakeFileInfo:+ path: str = "src/main.py"+ abs_path: str = "/repo/src/main.py"+ language: str = "python"+ is_test: bool = False+ is_api_contract: bool = False+ is_entry_point: bool = False+ size_bytes: int = 1000+++@dataclass+class FakeSymbol:+ name: str = "my_func"+ visibility: str = "public"+ kind: str = "function"+ start_line: int = 1+ end_line: int = 10+ qualified_name: str = "main.my_func"+ signature: str = "def my_func():"+++@dataclass+class FakeParsedFile:+ file_info: FakeFileInfo = field(default_factory=FakeFileInfo)+ symbols: list = field(default_factory=list)+++@dataclass+class FakeConfig:+ top_symbol_percentile: float = 0.10+ file_page_top_percentile: float = 0.20+ file_page_min_symbols: int = 1+++def _make_graph_builder(files: list[FakeParsedFile]):+ """Create a mock GraphBuilder with the necessary methods."""+ import networkx as nx++ graph = nx.DiGraph()+ for f in files:+ graph.add_node(f.file_info.path, symbol_count=len(f.symbols), language=f.file_info.language)++ builder = MagicMock()+ builder.graph.return_value = graph+ builder.pagerank.return_value = {f.file_info.path: 1.0 / max(len(files), 1) for f in files}+ builder.betweenness_centrality.return_value = {f.file_info.path: 0.0 for f in files}+ builder.strongly_connected_components.return_value = []+ return builder+++# ---------------------------------------------------------------------------+# Tests+# ---------------------------------------------------------------------------+++class TestBuildGenerationPlan:+ def test_empty_repo(self):+ builder = _make_graph_builder([])+ plans = build_generation_plan([], builder, FakeConfig())+ # Still get repo_overview + architecture_diagram+ assert any(p.page_type == "repo_overview" for p in plans)+ assert any(p.page_type == "architecture_diagram" for p in plans)++ def test_single_python_file_with_symbol(self):+ fi = FakeFileInfo(path="src/app.py", language="python")+ sym = FakeSymbol(name="handler", visibility="public")+ pf = FakeParsedFile(file_info=fi, symbols=[sym])+ builder = _make_graph_builder([pf])++ plans = build_generation_plan([pf], builder, FakeConfig())+ types = {p.page_type for p in plans}++ assert "symbol_spotlight" in types+ assert "file_page" in types+ assert "repo_overview" in types++ def test_api_contract_file(self):+ fi = FakeFileInfo(path="api/openapi.yaml", language="openapi", is_api_contract=True)+ pf = FakeParsedFile(file_info=fi, symbols=[])+ builder = _make_graph_builder([pf])++ plans = build_generation_plan([pf], builder, FakeConfig())+ assert any(p.page_type == "api_contract" and p.count == 1 for p in plans)++ def test_infra_file(self):+ fi = FakeFileInfo(path="Dockerfile", language="dockerfile")+ pf = FakeParsedFile(file_info=fi, symbols=[])+ builder = _make_graph_builder([pf])++ plans = build_generation_plan([pf], builder, FakeConfig())+ assert any(p.page_type == "infra_page" and p.count == 1 for p in plans)++ def test_skip_infra(self):+ fi = FakeFileInfo(path="Dockerfile", language="dockerfile")+ pf = FakeParsedFile(file_info=fi, symbols=[])+ builder = _make_graph_builder([pf])++ plans = build_generation_plan([pf], builder, FakeConfig(), skip_infra=True)+ assert not any(p.page_type == "infra_page" for p in plans)++ def test_skip_tests(self):+ fi = FakeFileInfo(path="tests/test_foo.py", language="python", is_test=True)+ sym = FakeSymbol(name="test_bar", visibility="public")+ pf = FakeParsedFile(file_info=fi, symbols=[sym])+ builder = _make_graph_builder([pf])++ plans = build_generation_plan([pf], builder, FakeConfig(), skip_tests=True)+ assert not any(p.page_type == "symbol_spotlight" for p in plans)++ def test_scc_pages_counted(self):+ fi1 = FakeFileInfo(path="a.py", language="python")+ fi2 = FakeFileInfo(path="b.py", language="python")+ pf1 = FakeParsedFile(file_info=fi1, symbols=[FakeSymbol(name="a_func")])+ pf2 = FakeParsedFile(file_info=fi2, symbols=[FakeSymbol(name="b_func")])+ builder = _make_graph_builder([pf1, pf2])+ builder.strongly_connected_components.return_value = [frozenset({"a.py", "b.py"})]++ plans = build_generation_plan([pf1, pf2], builder, FakeConfig())+ assert any(p.page_type == "scc_page" and p.count == 1 for p in plans)+++class TestEstimateCost:+ def test_mock_provider_zero_cost(self):+ plans = [PageTypePlan("file_page", 5, 2)]+ est = estimate_cost(plans, "mock", "mock-model")+ assert est.estimated_cost_usd == 0.0+ assert est.total_pages == 5++ def test_anthropic_has_cost(self):+ plans = [PageTypePlan("file_page", 10, 2)]+ est = estimate_cost(plans, "anthropic", "claude-sonnet-4-6")+ assert est.estimated_cost_usd > 0+ assert est.total_pages == 10+ assert est.estimated_input_tokens > 0+ assert est.estimated_output_tokens > 0++ def test_empty_plans(self):+ est = estimate_cost([], "anthropic", "claude-sonnet-4-6")+ assert est.total_pages == 0+ assert est.estimated_cost_usd == 0.0++ def test_multiple_page_types(self):+ plans = [+ PageTypePlan("api_contract", 2, 0),+ PageTypePlan("file_page", 5, 2),+ PageTypePlan("repo_overview", 1, 6),+ ]+ est = estimate_cost(plans, "openai", "gpt-4o")+ assert est.total_pages == 8+ assert est.estimated_cost_usd > 0diff --git a/tests/unit/cli/test_helpers.py b/tests/unit/cli/test_helpers.pynew file mode 100644index 000000000..9463062f3--- /dev/null+++ b/tests/unit/cli/test_helpers.py@@ -0,0 +1,129 @@+"""Unit tests for wikicode.cli.helpers."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from wikicode.cli.helpers import (+ ensure_wikicode_dir,+ get_db_url_for_repo,+ get_head_commit,+ get_wikicode_dir,+ load_state,+ resolve_repo_path,+ run_async,+ save_state,+)+++# ---------------------------------------------------------------------------+# run_async+# ---------------------------------------------------------------------------+++class TestRunAsync:+ def test_returns_coroutine_result(self):+ async def _add(a, b):+ return a + b++ assert run_async(_add(3, 4)) == 7++ def test_raises_exception_from_coroutine(self):+ async def _fail():+ raise ValueError("boom")++ with pytest.raises(ValueError, match="boom"):+ run_async(_fail())+++# ---------------------------------------------------------------------------+# Path resolution+# ---------------------------------------------------------------------------+++class TestResolveRepoPath:+ def test_none_defaults_to_cwd(self):+ result = resolve_repo_path(None)+ assert result == Path.cwd().resolve()++ def test_resolves_relative_path(self, tmp_path):+ import os++ old = os.getcwd()+ try:+ os.chdir(tmp_path)+ result = resolve_repo_path(".")+ assert result == tmp_path.resolve()+ finally:+ os.chdir(old)++ def test_resolves_absolute_path(self, tmp_path):+ result = resolve_repo_path(str(tmp_path))+ assert result == tmp_path.resolve()+++# ---------------------------------------------------------------------------+# .wikicode/ directory+# ---------------------------------------------------------------------------+++class TestWikicodeDir:+ def test_get_wikicode_dir(self, tmp_path):+ assert get_wikicode_dir(tmp_path) == tmp_path / ".wikicode"++ def test_ensure_wikicode_dir_creates(self, tmp_path):+ d = ensure_wikicode_dir(tmp_path)+ assert d.exists()+ assert d == tmp_path / ".wikicode"++ def test_ensure_wikicode_dir_idempotent(self, tmp_path):+ ensure_wikicode_dir(tmp_path)+ d = ensure_wikicode_dir(tmp_path)+ assert d.exists()+++# ---------------------------------------------------------------------------+# DB URL+# ---------------------------------------------------------------------------+++class TestDbUrl:+ def test_sqlite_url(self, tmp_path):+ url = get_db_url_for_repo(tmp_path)+ assert url.startswith("sqlite+aiosqlite:///")+ assert "wiki.db" in url+++# ---------------------------------------------------------------------------+# State file+# ---------------------------------------------------------------------------+++class TestStateFile:+ def test_load_missing_returns_empty(self, tmp_path):+ ensure_wikicode_dir(tmp_path)+ assert load_state(tmp_path) == {}++ def test_save_and_load_roundtrip(self, tmp_path):+ ensure_wikicode_dir(tmp_path)+ state = {"last_sync_commit": "abc123", "total_pages": 42}+ save_state(tmp_path, state)+ loaded = load_state(tmp_path)+ assert loaded == state++ def test_save_creates_wikicode_dir(self, tmp_path):+ save_state(tmp_path, {"key": "value"})+ assert (tmp_path / ".wikicode" / "state.json").exists()+++# ---------------------------------------------------------------------------+# Git HEAD+# ---------------------------------------------------------------------------+++class TestGetHeadCommit:+ def test_non_git_returns_none(self, tmp_path):+ assert get_head_commit(tmp_path) is Nonediff --git a/tests/unit/generation/__init__.py b/tests/unit/generation/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/unit/generation/conftest.py b/tests/unit/generation/conftest.pynew file mode 100644index 000000000..5fbfd4f1e--- /dev/null+++ b/tests/unit/generation/conftest.py@@ -0,0 +1,210 @@+"""Shared fixtures for generation unit tests."""++from __future__ import annotations++from datetime import datetime, timezone++import networkx as nx+import pytest++from wikicode.core.ingestion.models import (+ FileInfo,+ Import,+ PackageInfo,+ ParsedFile,+ RepoStructure,+ Symbol,+)+from wikicode.core.providers.mock import MockProvider+from wikicode.core.generation.models import GenerationConfig+++# ---------------------------------------------------------------------------+# Helper functions (module-level, not fixtures)+# ---------------------------------------------------------------------------+++def _make_file_info(+ path: str = "python_pkg/calculator.py",+ language: str = "python",+ is_api_contract: bool = False,+ is_entry_point: bool = False,+ is_test: bool = False,+ is_config: bool = False,+ size_bytes: int = 512,+) -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language=language,+ size_bytes=size_bytes,+ git_hash="abc123",+ last_modified=datetime(2026, 1, 1, tzinfo=timezone.utc),+ is_test=is_test,+ is_config=is_config,+ is_api_contract=is_api_contract,+ is_entry_point=is_entry_point,+ )+++def _make_symbol(+ name: str = "add",+ kind: str = "function",+ file_path: str = "python_pkg/calculator.py",+ signature: str = "def add(a: int, b: int) -> int:",+ visibility: str = "public",+ docstring: str | None = "Add two numbers.",+ is_async: bool = False,+ complexity_estimate: int = 1,+ parent_name: str | None = None,+) -> Symbol:+ return Symbol(+ id=f"{file_path}::{name}",+ name=name,+ qualified_name=f"python_pkg.calculator.{name}",+ kind=kind,+ signature=signature,+ start_line=1,+ end_line=10,+ docstring=docstring,+ decorators=[],+ visibility=visibility,+ is_async=is_async,+ complexity_estimate=complexity_estimate,+ language="python",+ parent_name=parent_name,+ )+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------++[email protected](scope="module")+def sample_config() -> GenerationConfig:+ return GenerationConfig(+ max_tokens=1024,+ token_budget=2000,+ max_concurrency=2,+ )++[email protected](scope="module")+def mock_provider() -> MockProvider:+ return MockProvider()++[email protected](scope="module")+def sample_parsed_file() -> ParsedFile:+ """A ParsedFile with 3 symbols, 2 imports, and a module docstring."""+ fi = _make_file_info()+ calc_class = _make_symbol(+ name="Calculator",+ kind="class",+ signature="class Calculator:",+ docstring="A simple calculator.",+ )+ add_method = _make_symbol(+ name="add",+ kind="method",+ signature="def add(self, a: int, b: int) -> int:",+ parent_name="Calculator",+ )+ internal = _make_symbol(+ name="_internal",+ kind="function",+ signature="def _internal() -> None:",+ visibility="private",+ docstring=None,+ )+ imports = [+ Import(+ raw_statement="from python_pkg import models",+ module_path="python_pkg.models",+ imported_names=["models"],+ is_relative=False,+ resolved_file="python_pkg/models.py",+ ),+ Import(+ raw_statement="import utils",+ module_path="utils",+ imported_names=["utils"],+ is_relative=False,+ resolved_file="python_pkg/utils.py",+ ),+ ]+ return ParsedFile(+ file_info=fi,+ symbols=[calc_class, add_method, internal],+ imports=imports,+ exports=["Calculator", "add"],+ docstring="Calculator module providing arithmetic operations.",+ parse_errors=[],+ content_hash="abc123",+ )++[email protected](scope="module")+def sample_graph(sample_parsed_file: ParsedFile) -> nx.DiGraph:+ """3-node DiGraph: calculator → models, calculator → utils."""+ g = nx.DiGraph()+ calc = sample_parsed_file.file_info.path+ models = "python_pkg/models.py"+ utils = "python_pkg/utils.py"+ g.add_node(calc, language="python", symbol_count=3, has_error=False)+ g.add_node(models, language="python", symbol_count=2, has_error=False)+ g.add_node(utils, language="python", symbol_count=1, has_error=False)+ g.add_edge(calc, models, imported_names=["models"])+ g.add_edge(calc, utils, imported_names=["utils"])+ return g++[email protected](scope="module")+def graph_metrics(sample_graph: nx.DiGraph, sample_parsed_file: ParsedFile) -> dict:+ """PageRank, betweenness centrality, and community for sample_graph nodes."""+ import networkx as nx++ g = sample_graph+ pagerank = nx.pagerank(g)+ betweenness = nx.betweenness_centrality(g)+ # Simple community: all in community 0+ community = {node: 0 for node in g.nodes()}+ return {+ "pagerank": pagerank,+ "betweenness": betweenness,+ "community": community,+ }++[email protected](scope="module")+def sample_source_bytes() -> bytes:+ return b"""\+class Calculator:+ \"\"\"A simple calculator.\"\"\"++ def add(self, a: int, b: int) -> int:+ return a + b++ def _internal(self) -> None:+ pass+"""++[email protected](scope="module")+def sample_repo_structure() -> RepoStructure:+ pkg = PackageInfo(+ name="python_pkg",+ path="python_pkg",+ language="python",+ entry_points=["python_pkg/calculator.py"],+ manifest_file="pyproject.toml",+ )+ return RepoStructure(+ is_monorepo=False,+ packages=[pkg],+ root_language_distribution={"python": 1.0},+ total_files=3,+ total_loc=100,+ entry_points=["python_pkg/calculator.py"],+ )diff --git a/tests/unit/generation/test_context_assembler.py b/tests/unit/generation/test_context_assembler.pynew file mode 100644index 000000000..fa634961d--- /dev/null+++ b/tests/unit/generation/test_context_assembler.py@@ -0,0 +1,308 @@+"""Tests for generation/context_assembler.py — 22 tests."""++from __future__ import annotations++import networkx as nx+import pytest++from wikicode.core.generation.context_assembler import (+ ContextAssembler,+ FilePageContext,+ SccPageContext,+)+from wikicode.core.generation.models import GenerationConfig+from wikicode.core.ingestion.models import (+ FileInfo,+ Import,+ PackageInfo,+ ParsedFile,+ RepoStructure,+ Symbol,+)++from .conftest import _make_file_info, _make_symbol+++# ---------------------------------------------------------------------------+# _estimate_tokens+# ---------------------------------------------------------------------------+++def test_estimate_tokens_empty_string(sample_config):+ assembler = ContextAssembler(sample_config)+ assert assembler._estimate_tokens("") == 0+++def test_estimate_tokens_known_string(sample_config):+ assembler = ContextAssembler(sample_config)+ text = "a" * 400+ assert assembler._estimate_tokens(text) == 100+++def test_estimate_tokens_short_string(sample_config):+ assembler = ContextAssembler(sample_config)+ assert assembler._estimate_tokens("abcd") == 1+++# ---------------------------------------------------------------------------+# _trim_to_budget+# ---------------------------------------------------------------------------+++def test_trim_to_budget_long_text_truncated(sample_config):+ assembler = ContextAssembler(sample_config)+ long_text = "x" * 10000+ result = assembler._trim_to_budget(long_text, 10)+ assert result.endswith("...[truncated]")+ assert len(result) <= 10 * 4 + len("...[truncated]")+++def test_trim_to_budget_short_text_unchanged(sample_config):+ assembler = ContextAssembler(sample_config)+ short_text = "hello world"+ result = assembler._trim_to_budget(short_text, 100)+ assert result == short_text+++def test_trim_to_budget_zero_remaining(sample_config):+ assembler = ContextAssembler(sample_config)+ result = assembler._trim_to_budget("some text", 0)+ assert result == ""+++# ---------------------------------------------------------------------------+# assemble_file_page+# ---------------------------------------------------------------------------+++def test_assemble_file_page_returns_context(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ assembler = ContextAssembler(sample_config)+ ctx = assembler.assemble_file_page(+ sample_parsed_file,+ sample_graph,+ graph_metrics["pagerank"],+ graph_metrics["betweenness"],+ graph_metrics["community"],+ sample_source_bytes,+ )+ assert isinstance(ctx, FilePageContext)+ assert ctx.file_path == sample_parsed_file.file_info.path+ assert ctx.language == "python"+++def test_assemble_file_page_dependents_from_graph(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ """dependents = files that have in-edges to this file (files importing it)."""+ assembler = ContextAssembler(sample_config)+ # Add a node that imports calculator+ path = sample_parsed_file.file_info.path+ graph = sample_graph.copy()+ graph.add_node("another.py")+ graph.add_edge("another.py", path)+ ctx = assembler.assemble_file_page(+ sample_parsed_file,+ graph,+ graph_metrics["pagerank"],+ graph_metrics["betweenness"],+ graph_metrics["community"],+ sample_source_bytes,+ )+ assert "another.py" in ctx.dependents+++def test_assemble_file_page_dependencies_from_graph(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ """dependencies = files this file imports (out-edges)."""+ assembler = ContextAssembler(sample_config)+ ctx = assembler.assemble_file_page(+ sample_parsed_file,+ sample_graph,+ graph_metrics["pagerank"],+ graph_metrics["betweenness"],+ graph_metrics["community"],+ sample_source_bytes,+ )+ assert "python_pkg/models.py" in ctx.dependencies+ assert "python_pkg/utils.py" in ctx.dependencies+++def test_assemble_file_page_token_budget_respected(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ assembler = ContextAssembler(sample_config)+ ctx = assembler.assemble_file_page(+ sample_parsed_file,+ sample_graph,+ graph_metrics["pagerank"],+ graph_metrics["betweenness"],+ graph_metrics["community"],+ sample_source_bytes,+ )+ assert ctx.estimated_tokens <= sample_config.token_budget+++def test_assemble_file_page_private_undocumented_dropped_first():+ """Private undocumented symbols are dropped first when over budget."""+ tiny_config = GenerationConfig(max_tokens=256, token_budget=5)+ assembler = ContextAssembler(tiny_config)++ fi = _make_file_info()+ public_sym = _make_symbol(name="public_func", visibility="public", signature="a" * 100)+ private_undoc = _make_symbol(+ name="_private", visibility="private", docstring=None, signature="b" * 100+ )+ parsed = ParsedFile(+ file_info=fi,+ symbols=[public_sym, private_undoc],+ imports=[],+ exports=[],+ docstring=None,+ parse_errors=[],+ )+ g = nx.DiGraph()+ g.add_node(fi.path)+ ctx = assembler.assemble_file_page(parsed, g, {}, {}, {}, b"")+ symbol_names = [s["name"] for s in ctx.symbols]+ # Private undocumented should not appear (budget too small)+ assert "_private" not in symbol_names+++# ---------------------------------------------------------------------------+# assemble_symbol_spotlight+# ---------------------------------------------------------------------------+++def test_assemble_symbol_spotlight_callers(+ sample_config, sample_parsed_file, sample_graph, graph_metrics+):+ assembler = ContextAssembler(sample_config)+ symbol = sample_parsed_file.symbols[0] # Calculator class+ # Add caller+ graph = sample_graph.copy()+ graph.add_edge("caller.py", sample_parsed_file.file_info.path)+ ctx = assembler.assemble_symbol_spotlight(+ symbol, sample_parsed_file, graph_metrics["pagerank"], graph+ )+ assert "caller.py" in ctx.callers+++def test_assemble_symbol_spotlight_no_callers(+ sample_config, sample_parsed_file, sample_graph, graph_metrics+):+ assembler = ContextAssembler(sample_config)+ symbol = sample_parsed_file.symbols[0]+ ctx = assembler.assemble_symbol_spotlight(+ symbol, sample_parsed_file, graph_metrics["pagerank"], sample_graph+ )+ # calculator.py is not imported by any file in sample_graph+ assert isinstance(ctx.callers, list)+++# ---------------------------------------------------------------------------+# assemble_module_page+# ---------------------------------------------------------------------------+++def test_assemble_module_page_total_symbols(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ assembler = ContextAssembler(sample_config)+ fc = assembler.assemble_file_page(+ sample_parsed_file,+ sample_graph,+ graph_metrics["pagerank"],+ graph_metrics["betweenness"],+ graph_metrics["community"],+ sample_source_bytes,+ )+ ctx = assembler.assemble_module_page("python_pkg", "python", [fc], sample_graph)+ assert ctx.total_symbols == len(fc.symbols)+++def test_assemble_module_page_public_symbols(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ assembler = ContextAssembler(sample_config)+ fc = assembler.assemble_file_page(+ sample_parsed_file,+ sample_graph,+ graph_metrics["pagerank"],+ graph_metrics["betweenness"],+ graph_metrics["community"],+ sample_source_bytes,+ )+ ctx = assembler.assemble_module_page("python_pkg", "python", [fc], sample_graph)+ assert ctx.public_symbols >= 0+++# ---------------------------------------------------------------------------+# assemble_scc_page+# ---------------------------------------------------------------------------+++def test_assemble_scc_page_cycle_description_contains_files(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ assembler = ContextAssembler(sample_config)+ fc = assembler.assemble_file_page(+ sample_parsed_file,+ sample_graph,+ graph_metrics["pagerank"],+ graph_metrics["betweenness"],+ graph_metrics["community"],+ sample_source_bytes,+ )+ scc_files = [sample_parsed_file.file_info.path, "python_pkg/models.py"]+ ctx = assembler.assemble_scc_page("scc-0", scc_files, [fc])+ assert isinstance(ctx, SccPageContext)+ for f in scc_files:+ assert f in ctx.cycle_description+++# ---------------------------------------------------------------------------+# assemble_repo_overview+# ---------------------------------------------------------------------------+++def test_assemble_repo_overview_top_files_sorted(+ sample_config, sample_graph, sample_repo_structure+):+ assembler = ContextAssembler(sample_config)+ pagerank = {"python_pkg/calculator.py": 0.5, "python_pkg/models.py": 0.3}+ ctx = assembler.assemble_repo_overview(+ sample_repo_structure, pagerank, [], {n: 0 for n in sample_graph.nodes()}+ )+ if len(ctx.top_files_by_pagerank) >= 2:+ assert ctx.top_files_by_pagerank[0].score >= ctx.top_files_by_pagerank[1].score+++def test_assemble_repo_overview_circular_dep_count(+ sample_config, sample_graph, sample_repo_structure+):+ assembler = ContextAssembler(sample_config)+ # Provide one true SCC (len > 1) and one singleton+ sccs = [frozenset(["a.py", "b.py"]), frozenset(["c.py"])]+ ctx = assembler.assemble_repo_overview(sample_repo_structure, {}, sccs, {})+ assert ctx.circular_dependency_count == 1+++# ---------------------------------------------------------------------------+# assemble_api_contract+# ---------------------------------------------------------------------------+++def test_assemble_api_contract_raw_content_budgeted(sample_config, sample_parsed_file):+ assembler = ContextAssembler(sample_config)+ huge_bytes = b"x" * 100_000+ ctx = assembler.assemble_api_contract(sample_parsed_file, huge_bytes)+ assert assembler._estimate_tokens(ctx.raw_content) <= sample_config.token_budget+++def test_assemble_api_contract_language_matches(sample_config, sample_parsed_file):+ assembler = ContextAssembler(sample_config)+ ctx = assembler.assemble_api_contract(sample_parsed_file, b"content")+ assert ctx.language == sample_parsed_file.file_info.languagediff --git a/tests/unit/generation/test_job_system.py b/tests/unit/generation/test_job_system.pynew file mode 100644index 000000000..b9e3043f1--- /dev/null+++ b/tests/unit/generation/test_job_system.py@@ -0,0 +1,252 @@+"""Tests for generation/job_system.py — 22 tests."""++from __future__ import annotations++from pathlib import Path++import pytest++from wikicode.core.generation.job_system import Checkpoint, JobSystem+from wikicode.core.generation.models import GenerationConfig+++def _make_system(tmp_path: Path) -> JobSystem:+ return JobSystem(tmp_path / "jobs")+++def _create(js: JobSystem) -> str:+ return js.create_job(".", GenerationConfig(), "mock", "mock-model-1")+++# ---------------------------------------------------------------------------+# create_job+# ---------------------------------------------------------------------------+++def test_create_job_returns_uuid(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ assert isinstance(job_id, str)+ assert len(job_id) == 36 # UUID format+++def test_create_job_writes_json_file(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ json_file = tmp_path / "jobs" / f"{job_id}.json"+ assert json_file.exists()+++def test_create_job_status_is_pending(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ cp = js.get_checkpoint(job_id)+ assert cp.status == "pending"+++# ---------------------------------------------------------------------------+# start_job+# ---------------------------------------------------------------------------+++def test_start_job_sets_running(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 10)+ cp = js.get_checkpoint(job_id)+ assert cp.status == "running"+++def test_start_job_stores_total_pages(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 42)+ cp = js.get_checkpoint(job_id)+ assert cp.total_pages == 42+++# ---------------------------------------------------------------------------+# complete_page+# ---------------------------------------------------------------------------+++def test_complete_page_increments_count(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 5)+ js.complete_page(job_id, "file_page:main.py")+ cp = js.get_checkpoint(job_id)+ assert cp.completed_pages == 1+ assert "file_page:main.py" in cp.completed_page_ids+++def test_complete_page_idempotent(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 5)+ js.complete_page(job_id, "file_page:main.py")+ js.complete_page(job_id, "file_page:main.py")+ cp = js.get_checkpoint(job_id)+ assert cp.completed_pages == 1 # not incremented twice+++def test_complete_page_json_persisted(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 5)+ js.complete_page(job_id, "file_page:x.py")+ # New instance — reads from disk+ js2 = JobSystem(tmp_path / "jobs")+ cp = js2.get_checkpoint(job_id)+ assert "file_page:x.py" in cp.completed_page_ids+++# ---------------------------------------------------------------------------+# fail_page+# ---------------------------------------------------------------------------+++def test_fail_page_increments_failed(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 5)+ js.fail_page(job_id, "file_page:broken.py", "ParseError")+ cp = js.get_checkpoint(job_id)+ assert cp.failed_pages == 1+++def test_fail_page_job_stays_running(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 5)+ js.fail_page(job_id, "file_page:broken.py", "ParseError")+ cp = js.get_checkpoint(job_id)+ assert cp.status == "running"+++# ---------------------------------------------------------------------------+# complete_job / fail_job+# ---------------------------------------------------------------------------+++def test_complete_job_sets_completed(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 1)+ js.complete_job(job_id)+ cp = js.get_checkpoint(job_id)+ assert cp.status == "completed"+++def test_fail_job_stores_error_message(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 1)+ js.fail_job(job_id, "Provider unavailable")+ cp = js.get_checkpoint(job_id)+ assert cp.status == "failed"+ assert cp.error_message == "Provider unavailable"+++# ---------------------------------------------------------------------------+# pause / resume+# ---------------------------------------------------------------------------+++def test_pause_job_sets_paused(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 5)+ js.pause_job(job_id)+ cp = js.get_checkpoint(job_id)+ assert cp.status == "paused"+++def test_resume_job_sets_running(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 5)+ js.pause_job(job_id)+ cp = js.resume_job(job_id)+ assert cp.status == "running"+++def test_resume_job_returns_checkpoint(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 5)+ js.pause_job(job_id)+ cp = js.resume_job(job_id)+ assert isinstance(cp, Checkpoint)+++# ---------------------------------------------------------------------------+# Invalid transitions+# ---------------------------------------------------------------------------+++def test_invalid_transition_raises_value_error(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 1)+ js.complete_job(job_id)+ with pytest.raises(ValueError):+ js.complete_job(job_id) # completed → running doesn't exist+++# ---------------------------------------------------------------------------+# JSON round-trip persistence+# ---------------------------------------------------------------------------+++def test_json_round_trip_persistence(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 3)+ js.complete_page(job_id, "file_page:a.py")+ js.complete_page(job_id, "file_page:b.py")++ # Reload from disk with a new instance+ js2 = JobSystem(tmp_path / "jobs")+ cp = js2.get_checkpoint(job_id)+ assert cp.completed_pages == 2+ assert "file_page:a.py" in cp.completed_page_ids+ assert "file_page:b.py" in cp.completed_page_ids+++# ---------------------------------------------------------------------------+# list_jobs+# ---------------------------------------------------------------------------+++def test_list_jobs_sorted_by_created_at_desc(tmp_path):+ js = _make_system(tmp_path)+ j1 = _create(js)+ j2 = _create(js)+ jobs = js.list_jobs()+ ids = [j.job_id for j in jobs]+ # j2 was created after j1 so it should appear first+ assert ids.index(j2) <= ids.index(j1)+++def test_list_jobs_returns_all(tmp_path):+ js = _make_system(tmp_path)+ _create(js)+ _create(js)+ _create(js)+ assert len(js.list_jobs()) == 3+++# ---------------------------------------------------------------------------+# get_completed_page_ids+# ---------------------------------------------------------------------------+++def test_get_completed_page_ids_correct_set(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 5)+ js.complete_page(job_id, "file_page:x.py")+ js.complete_page(job_id, "module_page:pkg")+ ids = js.get_completed_page_ids(job_id)+ assert ids == {"file_page:x.py", "module_page:pkg"}diff --git a/tests/unit/generation/test_models.py b/tests/unit/generation/test_models.pynew file mode 100644index 000000000..eca5bb0bd--- /dev/null+++ b/tests/unit/generation/test_models.py@@ -0,0 +1,157 @@+"""Tests for generation/models.py — 10 tests."""++from __future__ import annotations++from datetime import datetime, timedelta, timezone++import pytest++from wikicode.core.generation.models import (+ ConfidenceDecayResult,+ GeneratedPage,+ GenerationConfig,+ compute_freshness,+ compute_page_id,+ compute_source_hash,+ decay_confidence,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_page(+ updated_at: datetime,+ source_hash: str = "deadbeef" * 8,+ confidence: float = 1.0,+) -> GeneratedPage:+ now_iso = updated_at.isoformat()+ return GeneratedPage(+ page_id="file_page:python_pkg/calculator.py",+ page_type="file_page",+ title="File: python_pkg/calculator.py",+ content="## Overview\nThis is a calculator.",+ source_hash=source_hash,+ model_name="mock-model-1",+ provider_name="mock",+ input_tokens=100,+ output_tokens=50,+ cached_tokens=0,+ generation_level=2,+ target_path="python_pkg/calculator.py",+ created_at=now_iso,+ updated_at=now_iso,+ confidence=confidence,+ )+++def _utc(**kwargs) -> datetime:+ return datetime.now(timezone.utc) - timedelta(**kwargs)+++# ---------------------------------------------------------------------------+# compute_page_id+# ---------------------------------------------------------------------------+++def test_compute_page_id_normal():+ pid = compute_page_id("file_page", "python_pkg/calculator.py")+ assert pid == "file_page:python_pkg/calculator.py"+++def test_compute_page_id_scc():+ pid = compute_page_id("scc_page", "scc-0")+ assert pid == "scc_page:scc-0"+++# ---------------------------------------------------------------------------+# GeneratedPage.total_tokens+# ---------------------------------------------------------------------------+++def test_total_tokens_property():+ page = _make_page(_utc(days=0))+ page.input_tokens = 200+ page.output_tokens = 80+ assert page.total_tokens == 280+++# ---------------------------------------------------------------------------+# compute_freshness+# ---------------------------------------------------------------------------+++def test_freshness_same_hash_is_fresh():+ config = GenerationConfig()+ page = _make_page(_utc(days=0), source_hash="abc")+ status = compute_freshness(page, "abc", config)+ assert status == "fresh"+++def test_freshness_different_hash_is_stale():+ config = GenerationConfig()+ page = _make_page(_utc(days=0), source_hash="abc")+ status = compute_freshness(page, "xyz", config)+ assert status == "stale"+++def test_freshness_expired_by_age():+ config = GenerationConfig(expiry_threshold_days=30)+ page = _make_page(_utc(days=31), source_hash="abc")+ status = compute_freshness(page, "abc", config)+ assert status == "expired"+++def test_freshness_stale_by_age_same_hash():+ config = GenerationConfig(staleness_threshold_days=7, expiry_threshold_days=30)+ page = _make_page(_utc(days=8), source_hash="abc")+ status = compute_freshness(page, "abc", config)+ assert status == "stale"+++# ---------------------------------------------------------------------------+# decay_confidence+# ---------------------------------------------------------------------------+++def test_decay_confidence_zero_days():+ config = GenerationConfig(expiry_threshold_days=30)+ page = _make_page(_utc(seconds=1), confidence=1.0)+ result = decay_confidence(page, config)+ assert isinstance(result, ConfidenceDecayResult)+ assert result.new_confidence > 0.99+++def test_decay_confidence_halfway():+ config = GenerationConfig(expiry_threshold_days=30)+ page = _make_page(_utc(days=15), confidence=1.0)+ result = decay_confidence(page, config)+ assert 0.4 < result.new_confidence < 0.6+++def test_decay_confidence_beyond_expiry_is_zero():+ config = GenerationConfig(expiry_threshold_days=30)+ page = _make_page(_utc(days=60), confidence=1.0)+ result = decay_confidence(page, config)+ assert result.new_confidence == 0.0+ assert result.freshness_status == "expired"+++# ---------------------------------------------------------------------------+# GenerationConfig defaults+# ---------------------------------------------------------------------------+++def test_generation_config_defaults():+ config = GenerationConfig()+ assert config.max_tokens == 16000+ assert config.temperature == 0.3+ assert config.token_budget == 48000+ assert config.max_concurrency == 5+ assert config.cache_enabled is True+ assert config.staleness_threshold_days == 7+ assert config.expiry_threshold_days == 30+ assert config.top_symbol_percentile == 0.10+ assert config.large_file_source_pct == 0.4diff --git a/tests/unit/generation/test_page_generator.py b/tests/unit/generation/test_page_generator.pynew file mode 100644index 000000000..098a02f9e--- /dev/null+++ b/tests/unit/generation/test_page_generator.py@@ -0,0 +1,345 @@+"""Tests for generation/page_generator.py — 25 tests."""++from __future__ import annotations++import hashlib++import networkx as nx+import pytest++from wikicode.core.generation.context_assembler import ContextAssembler+from wikicode.core.generation.models import GenerationConfig, GeneratedPage+from wikicode.core.generation.page_generator import PageGenerator, SYSTEM_PROMPTS+from wikicode.core.ingestion.models import FileInfo, Import, ParsedFile, RepoStructure, PackageInfo+from wikicode.core.providers.mock import MockProvider++from .conftest import _make_file_info, _make_symbol++from datetime import datetime, timezone+++# ---------------------------------------------------------------------------+# SYSTEM_PROMPTS completeness+# ---------------------------------------------------------------------------+++EXPECTED_PAGE_TYPES = [+ "file_page", "symbol_spotlight", "module_page", "scc_page",+ "repo_overview", "architecture_diagram", "api_contract", "infra_page",+ "diff_summary",+]++[email protected]("page_type", EXPECTED_PAGE_TYPES)+def test_system_prompt_exists(page_type):+ assert page_type in SYSTEM_PROMPTS++[email protected]("page_type", EXPECTED_PAGE_TYPES)+def test_system_prompt_not_empty(page_type):+ assert len(SYSTEM_PROMPTS[page_type]) > 0+++# ---------------------------------------------------------------------------+# generate_file_page+# ---------------------------------------------------------------------------+++async def test_generate_file_page_returns_generated_page(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ provider = MockProvider()+ assembler = ContextAssembler(sample_config)+ gen = PageGenerator(provider, assembler, sample_config)++ page = await gen.generate_file_page(+ sample_parsed_file,+ sample_graph,+ graph_metrics["pagerank"],+ graph_metrics["betweenness"],+ graph_metrics["community"],+ sample_source_bytes,+ )++ assert isinstance(page, GeneratedPage)+ assert page.page_type == "file_page"+++def test_generate_file_page_provider_name(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ import asyncio+ provider = MockProvider()+ assembler = ContextAssembler(sample_config)+ gen = PageGenerator(provider, assembler, sample_config)++ page = asyncio.run(+ gen.generate_file_page(+ sample_parsed_file, sample_graph,+ graph_metrics["pagerank"], graph_metrics["betweenness"],+ graph_metrics["community"], sample_source_bytes,+ )+ )+ assert page.provider_name == "mock"+ assert page.model_name == "mock-model-1"+++async def test_generate_file_page_increments_call_count(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ provider = MockProvider()+ assembler = ContextAssembler(sample_config)+ gen = PageGenerator(provider, assembler, sample_config)++ await gen.generate_file_page(+ sample_parsed_file, sample_graph,+ graph_metrics["pagerank"], graph_metrics["betweenness"],+ graph_metrics["community"], sample_source_bytes,+ )+ assert provider.call_count == 1+++# ---------------------------------------------------------------------------+# Prompt cache+# ---------------------------------------------------------------------------+++async def test_cache_hit_does_not_increment_call_count(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ provider = MockProvider()+ config = GenerationConfig(+ max_tokens=1024, token_budget=2000, max_concurrency=2, cache_enabled=True+ )+ assembler = ContextAssembler(config)+ gen = PageGenerator(provider, assembler, config)++ await gen.generate_file_page(+ sample_parsed_file, sample_graph,+ graph_metrics["pagerank"], graph_metrics["betweenness"],+ graph_metrics["community"], sample_source_bytes,+ )+ # Second call — identical inputs → cache hit+ await gen.generate_file_page(+ sample_parsed_file, sample_graph,+ graph_metrics["pagerank"], graph_metrics["betweenness"],+ graph_metrics["community"], sample_source_bytes,+ )+ assert provider.call_count == 1+++async def test_cache_disabled_increments_every_call(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ provider = MockProvider()+ config = GenerationConfig(+ max_tokens=1024, token_budget=2000, max_concurrency=2, cache_enabled=False+ )+ assembler = ContextAssembler(config)+ gen = PageGenerator(provider, assembler, config)++ await gen.generate_file_page(+ sample_parsed_file, sample_graph,+ graph_metrics["pagerank"], graph_metrics["betweenness"],+ graph_metrics["community"], sample_source_bytes,+ )+ await gen.generate_file_page(+ sample_parsed_file, sample_graph,+ graph_metrics["pagerank"], graph_metrics["betweenness"],+ graph_metrics["community"], sample_source_bytes,+ )+ assert provider.call_count == 2+++# ---------------------------------------------------------------------------+# Cache key uniqueness+# ---------------------------------------------------------------------------+++def test_different_page_type_different_cache_key(sample_config):+ provider = MockProvider()+ assembler = ContextAssembler(sample_config)+ gen = PageGenerator(provider, assembler, sample_config)++ key1 = gen._compute_cache_key("file_page", "same prompt")+ key2 = gen._compute_cache_key("module_page", "same prompt")+ assert key1 != key2+++def test_different_prompt_different_cache_key(sample_config):+ provider = MockProvider()+ assembler = ContextAssembler(sample_config)+ gen = PageGenerator(provider, assembler, sample_config)++ key1 = gen._compute_cache_key("file_page", "prompt A")+ key2 = gen._compute_cache_key("file_page", "prompt B")+ assert key1 != key2+++# ---------------------------------------------------------------------------+# source_hash and created_at+# ---------------------------------------------------------------------------+++async def test_generated_page_source_hash_is_64_hex(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ provider = MockProvider()+ assembler = ContextAssembler(sample_config)+ gen = PageGenerator(provider, assembler, sample_config)++ page = await gen.generate_file_page(+ sample_parsed_file, sample_graph,+ graph_metrics["pagerank"], graph_metrics["betweenness"],+ graph_metrics["community"], sample_source_bytes,+ )+ assert len(page.source_hash) == 64+ int(page.source_hash, 16) # must be valid hex+++async def test_generated_page_created_at_is_iso(+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes+):+ provider = MockProvider()+ assembler = ContextAssembler(sample_config)+ gen = PageGenerator(provider, assembler, sample_config)++ page = await gen.generate_file_page(+ sample_parsed_file, sample_graph,+ graph_metrics["pagerank"], graph_metrics["betweenness"],+ graph_metrics["community"], sample_source_bytes,+ )+ # Must parse without error+ dt = datetime.fromisoformat(page.created_at.replace("Z", "+00:00"))+ assert dt.year >= 2026+++# ---------------------------------------------------------------------------+# generate_all — ordering and completeness+# ---------------------------------------------------------------------------+++def _make_builder_with(parsed_files):+ """Build a GraphBuilder from a list of ParsedFile objects."""+ from wikicode.core.ingestion.graph import GraphBuilder+ builder = GraphBuilder()+ for p in parsed_files:+ builder.add_file(p)+ builder.build()+ return builder+++async def test_generate_all_api_contract_before_file_page():+ """api_contract pages (level 0) must appear before file_page pages (level 2)."""+ config = GenerationConfig(max_tokens=256, token_budget=500, max_concurrency=2)+ provider = MockProvider()+ assembler = ContextAssembler(config)+ gen = PageGenerator(provider, assembler, config)++ fi_api = _make_file_info("api/openapi.yaml", language="openapi", is_api_contract=True)+ fi_py = _make_file_info("pkg/main.py", language="python")+ sym = _make_symbol(file_path="pkg/main.py")+ p_api = ParsedFile(+ file_info=fi_api, symbols=[], imports=[], exports=[],+ docstring=None, parse_errors=[]+ )+ p_py = ParsedFile(+ file_info=fi_py, symbols=[sym], imports=[], exports=[],+ docstring=None, parse_errors=[]+ )++ repo = RepoStructure(+ is_monorepo=False,+ packages=[],+ root_language_distribution={"python": 0.5, "openapi": 0.5},+ total_files=2,+ total_loc=50,+ entry_points=[],+ )++ builder = _make_builder_with([p_api, p_py])+ pages = await gen.generate_all(+ [p_api, p_py], {"api/openapi.yaml": b"openapi: 3.0", "pkg/main.py": b"pass"},+ builder, repo, "test-repo"+ )++ api_idx = next((i for i, p in enumerate(pages) if p.page_type == "api_contract"), None)+ file_idx = next((i for i, p in enumerate(pages) if p.page_type == "file_page"), None)+ if api_idx is not None and file_idx is not None:+ assert api_idx < file_idx+++async def test_generate_all_infra_file_gets_infra_page():+ """Dockerfile/Makefile should generate infra_page, not file_page."""+ config = GenerationConfig(max_tokens=256, token_budget=500, max_concurrency=2)+ provider = MockProvider()+ assembler = ContextAssembler(config)+ gen = PageGenerator(provider, assembler, config)++ fi_docker = _make_file_info("Dockerfile", language="dockerfile")+ p_docker = ParsedFile(+ file_info=fi_docker, symbols=[], imports=[], exports=[],+ docstring=None, parse_errors=[]+ )+ repo = RepoStructure(+ is_monorepo=False, packages=[],+ root_language_distribution={"dockerfile": 1.0},+ total_files=1, total_loc=10, entry_points=[],+ )+ builder = _make_builder_with([p_docker])+ pages = await gen.generate_all(+ [p_docker], {"Dockerfile": b"FROM ubuntu"}, builder, repo, "test-repo"+ )+ page_types = [p.page_type for p in pages]+ assert "infra_page" in page_types+ assert "file_page" not in page_types+++async def test_generate_all_returns_pages():+ """generate_all returns at least 1 page for a non-empty repo."""+ config = GenerationConfig(max_tokens=256, token_budget=500, max_concurrency=2)+ provider = MockProvider()+ assembler = ContextAssembler(config)+ gen = PageGenerator(provider, assembler, config)++ fi = _make_file_info("pkg/main.py", language="python")+ sym = _make_symbol(file_path="pkg/main.py")+ p = ParsedFile(+ file_info=fi, symbols=[sym], imports=[], exports=[],+ docstring=None, parse_errors=[]+ )+ repo = RepoStructure(+ is_monorepo=False, packages=[],+ root_language_distribution={"python": 1.0},+ total_files=1, total_loc=20, entry_points=[],+ )+ builder = _make_builder_with([p])+ pages = await gen.generate_all(+ [p], {"pkg/main.py": b"def main(): pass"}, builder, repo, "test-repo"+ )+ assert len(pages) >= 1+++async def test_generate_all_level_values_in_range():+ config = GenerationConfig(max_tokens=256, token_budget=500, max_concurrency=2)+ provider = MockProvider()+ assembler = ContextAssembler(config)+ gen = PageGenerator(provider, assembler, config)++ fi = _make_file_info("pkg/main.py", language="python")+ sym = _make_symbol(file_path="pkg/main.py")+ p = ParsedFile(+ file_info=fi, symbols=[sym], imports=[], exports=[],+ docstring=None, parse_errors=[]+ )+ repo = RepoStructure(+ is_monorepo=False, packages=[],+ root_language_distribution={"python": 1.0},+ total_files=1, total_loc=10, entry_points=[],+ )+ builder = _make_builder_with([p])+ pages = await gen.generate_all(+ [p], {"pkg/main.py": b"def main(): pass"}, builder, repo, "test-repo"+ )+ for page in pages:+ assert 0 <= page.generation_level <= 7diff --git a/tests/unit/generation/test_templates.py b/tests/unit/generation/test_templates.pynew file mode 100644index 000000000..9e011047a--- /dev/null+++ b/tests/unit/generation/test_templates.py@@ -0,0 +1,356 @@+"""Tests for Jinja2 templates — 27 tests (3 per template × 9 templates)."""++from __future__ import annotations++from pathlib import Path++import jinja2+import pytest++from wikicode.core.generation.context_assembler import (+ ApiContractContext,+ ArchitectureDiagramContext,+ DiffSummaryContext,+ FilePageContext,+ InfraPageContext,+ ModulePageContext,+ SccPageContext,+ SymbolSpotlightContext,+ RepoOverviewContext,+ _TopFile,+)+from wikicode.core.ingestion.models import PackageInfo+++# ---------------------------------------------------------------------------+# Fixture: Jinja2 environment pointing at the real templates directory+# ---------------------------------------------------------------------------++[email protected](scope="module")+def jinja_env() -> jinja2.Environment:+ templates_dir = Path(__file__).parents[3] / "packages" / "core" / "src" / "wikicode" / "core" / "generation" / "templates"+ assert templates_dir.exists(), f"Templates directory not found: {templates_dir}"+ return jinja2.Environment(+ loader=jinja2.FileSystemLoader(str(templates_dir)),+ undefined=jinja2.StrictUndefined,+ autoescape=False,+ )+++def render(env: jinja2.Environment, template_name: str, ctx: object) -> str:+ return env.get_template(template_name).render(ctx=ctx)+++# ---------------------------------------------------------------------------+# file_page.j2+# ---------------------------------------------------------------------------++[email protected](scope="module")+def file_page_ctx() -> FilePageContext:+ return FilePageContext(+ file_path="python_pkg/calculator.py",+ language="python",+ docstring="Calculator module.",+ symbols=[+ {"name": "Calculator", "kind": "class", "signature": "class Calculator:", "docstring": "Calc.", "visibility": "public", "is_async": False, "complexity_estimate": 1, "decorators": [], "parent_name": None, "start_line": 1, "end_line": 10}+ ],+ imports=["from python_pkg import models"],+ exports=["Calculator"],+ file_source_snippet="class Calculator:\n pass",+ pagerank_score=0.5,+ betweenness_score=0.2,+ community_id=0,+ dependents=["main.py"],+ dependencies=["python_pkg/models.py"],+ is_api_contract=False,+ is_entry_point=False,+ is_test=False,+ parse_errors=[],+ estimated_tokens=100,+ )+++def test_file_page_renders_without_error(jinja_env, file_page_ctx):+ result = render(jinja_env, "file_page.j2", file_page_ctx)+ assert result # non-empty+++def test_file_page_has_heading(jinja_env, file_page_ctx):+ result = render(jinja_env, "file_page.j2", file_page_ctx)+ assert "##" in result+++def test_file_page_contains_file_path(jinja_env, file_page_ctx):+ result = render(jinja_env, "file_page.j2", file_page_ctx)+ assert file_page_ctx.file_path in result+++# ---------------------------------------------------------------------------+# module_page.j2+# ---------------------------------------------------------------------------++[email protected](scope="module")+def module_page_ctx() -> ModulePageContext:+ return ModulePageContext(+ module_path="python_pkg",+ language="python",+ total_symbols=5,+ public_symbols=3,+ entry_points=["python_pkg/__init__.py"],+ dependencies=["external_lib"],+ dependents=[],+ pagerank_mean=0.3,+ files=["python_pkg/calculator.py", "python_pkg/models.py"],+ )+++def test_module_page_renders_without_error(jinja_env, module_page_ctx):+ result = render(jinja_env, "module_page.j2", module_page_ctx)+ assert result+++def test_module_page_has_heading(jinja_env, module_page_ctx):+ result = render(jinja_env, "module_page.j2", module_page_ctx)+ assert "##" in result+++def test_module_page_contains_module_path(jinja_env, module_page_ctx):+ result = render(jinja_env, "module_page.j2", module_page_ctx)+ assert module_page_ctx.module_path in result+++# ---------------------------------------------------------------------------+# repo_overview.j2+# ---------------------------------------------------------------------------++[email protected](scope="module")+def repo_overview_ctx() -> RepoOverviewContext:+ pkg = PackageInfo(+ name="python_pkg",+ path="python_pkg",+ language="python",+ entry_points=["python_pkg/__init__.py"],+ manifest_file="pyproject.toml",+ )+ return RepoOverviewContext(+ repo_name="my-repo",+ is_monorepo=False,+ packages=[pkg],+ language_distribution={"python": 1.0},+ total_files=5,+ total_loc=200,+ entry_points=["python_pkg/__init__.py"],+ top_files_by_pagerank=[_TopFile("python_pkg/calculator.py", 0.5)],+ circular_dependency_count=0,+ )+++def test_repo_overview_renders_without_error(jinja_env, repo_overview_ctx):+ result = render(jinja_env, "repo_overview.j2", repo_overview_ctx)+ assert result+++def test_repo_overview_has_heading(jinja_env, repo_overview_ctx):+ result = render(jinja_env, "repo_overview.j2", repo_overview_ctx)+ assert "##" in result+++def test_repo_overview_contains_repo_name(jinja_env, repo_overview_ctx):+ result = render(jinja_env, "repo_overview.j2", repo_overview_ctx)+ assert repo_overview_ctx.repo_name in result+++# ---------------------------------------------------------------------------+# symbol_spotlight.j2+# ---------------------------------------------------------------------------++[email protected](scope="module")+def symbol_spotlight_ctx() -> SymbolSpotlightContext:+ return SymbolSpotlightContext(+ symbol_name="add",+ qualified_name="python_pkg.calculator.add",+ kind="function",+ signature="def add(a: int, b: int) -> int:",+ docstring="Add two numbers.",+ file_path="python_pkg/calculator.py",+ decorators=[],+ is_async=False,+ complexity_estimate=1,+ callers=["main.py"],+ )+++def test_symbol_spotlight_renders_without_error(jinja_env, symbol_spotlight_ctx):+ result = render(jinja_env, "symbol_spotlight.j2", symbol_spotlight_ctx)+ assert result+++def test_symbol_spotlight_has_heading(jinja_env, symbol_spotlight_ctx):+ result = render(jinja_env, "symbol_spotlight.j2", symbol_spotlight_ctx)+ assert "##" in result+++def test_symbol_spotlight_contains_symbol_name(jinja_env, symbol_spotlight_ctx):+ result = render(jinja_env, "symbol_spotlight.j2", symbol_spotlight_ctx)+ assert symbol_spotlight_ctx.symbol_name in result+++# ---------------------------------------------------------------------------+# architecture_diagram.j2+# ---------------------------------------------------------------------------++[email protected](scope="module")+def architecture_diagram_ctx() -> ArchitectureDiagramContext:+ return ArchitectureDiagramContext(+ repo_name="my-repo",+ nodes=["pkg/a.py", "pkg/b.py"],+ edges=[("pkg/a.py", "pkg/b.py")],+ communities={0: ["pkg/a.py"], 1: ["pkg/b.py"]},+ scc_groups=[],+ )+++def test_architecture_diagram_renders_without_error(jinja_env, architecture_diagram_ctx):+ result = render(jinja_env, "architecture_diagram.j2", architecture_diagram_ctx)+ assert result+++def test_architecture_diagram_has_heading(jinja_env, architecture_diagram_ctx):+ result = render(jinja_env, "architecture_diagram.j2", architecture_diagram_ctx)+ assert "##" in result+++def test_architecture_diagram_mentions_mermaid(jinja_env, architecture_diagram_ctx):+ result = render(jinja_env, "architecture_diagram.j2", architecture_diagram_ctx)+ assert "mermaid" in result.lower()+++# ---------------------------------------------------------------------------+# api_contract.j2+# ---------------------------------------------------------------------------++[email protected](scope="module")+def api_contract_ctx() -> ApiContractContext:+ return ApiContractContext(+ file_path="api/openapi.yaml",+ language="openapi",+ raw_content="openapi: '3.0'\ninfo:\n title: My API",+ endpoints=["/users GET", "/users POST"],+ schemas=["User", "Error"],+ )+++def test_api_contract_renders_without_error(jinja_env, api_contract_ctx):+ result = render(jinja_env, "api_contract.j2", api_contract_ctx)+ assert result+++def test_api_contract_has_heading(jinja_env, api_contract_ctx):+ result = render(jinja_env, "api_contract.j2", api_contract_ctx)+ assert "##" in result+++def test_api_contract_contains_file_path(jinja_env, api_contract_ctx):+ result = render(jinja_env, "api_contract.j2", api_contract_ctx)+ assert api_contract_ctx.file_path in result+++# ---------------------------------------------------------------------------+# infra_page.j2+# ---------------------------------------------------------------------------++[email protected](scope="module")+def infra_page_ctx() -> InfraPageContext:+ return InfraPageContext(+ file_path="Dockerfile",+ language="dockerfile",+ raw_content="FROM ubuntu:22.04\nRUN apt-get update",+ targets=["build", "test"],+ )+++def test_infra_page_renders_without_error(jinja_env, infra_page_ctx):+ result = render(jinja_env, "infra_page.j2", infra_page_ctx)+ assert result+++def test_infra_page_has_heading(jinja_env, infra_page_ctx):+ result = render(jinja_env, "infra_page.j2", infra_page_ctx)+ assert "##" in result+++def test_infra_page_contains_file_path(jinja_env, infra_page_ctx):+ result = render(jinja_env, "infra_page.j2", infra_page_ctx)+ assert infra_page_ctx.file_path in result+++# ---------------------------------------------------------------------------+# scc_page.j2+# ---------------------------------------------------------------------------++[email protected](scope="module")+def scc_page_ctx() -> SccPageContext:+ return SccPageContext(+ scc_id="scc-0",+ files=["pkg/a.py", "pkg/b.py"],+ cycle_description="Circular dependency cycle: pkg/a.py → pkg/b.py",+ total_symbols=10,+ )+++def test_scc_page_renders_without_error(jinja_env, scc_page_ctx):+ result = render(jinja_env, "scc_page.j2", scc_page_ctx)+ assert result+++def test_scc_page_has_heading(jinja_env, scc_page_ctx):+ result = render(jinja_env, "scc_page.j2", scc_page_ctx)+ assert "##" in result+++def test_scc_page_contains_cycle_description(jinja_env, scc_page_ctx):+ result = render(jinja_env, "scc_page.j2", scc_page_ctx)+ assert scc_page_ctx.cycle_description in result+++# ---------------------------------------------------------------------------+# diff_summary.j2+# ---------------------------------------------------------------------------++[email protected](scope="module")+def diff_summary_ctx() -> DiffSummaryContext:+ return DiffSummaryContext(+ from_ref="HEAD~1",+ to_ref="HEAD",+ added_files=["new_file.py"],+ deleted_files=[],+ modified_files=["changed.py"],+ symbol_diffs=[],+ affected_page_ids=["file_page:changed.py"],+ )+++def test_diff_summary_renders_without_error(jinja_env, diff_summary_ctx):+ result = render(jinja_env, "diff_summary.j2", diff_summary_ctx)+ assert result+++def test_diff_summary_has_heading(jinja_env, diff_summary_ctx):+ result = render(jinja_env, "diff_summary.j2", diff_summary_ctx)+ assert "##" in result+++def test_diff_summary_contains_refs(jinja_env, diff_summary_ctx):+ result = render(jinja_env, "diff_summary.j2", diff_summary_ctx)+ assert diff_summary_ctx.from_ref in result+ assert diff_summary_ctx.to_ref in resultdiff --git a/tests/unit/ingestion/__init__.py b/tests/unit/ingestion/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/unit/ingestion/test_change_detector.py b/tests/unit/ingestion/test_change_detector.pynew file mode 100644index 000000000..3084885bf--- /dev/null+++ b/tests/unit/ingestion/test_change_detector.py@@ -0,0 +1,291 @@+"""Unit tests for ChangeDetector."""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import networkx as nx+import pytest++from wikicode.core.ingestion.change_detector import ChangeDetector, SymbolDiff+from wikicode.core.ingestion.models import FileInfo, Import, ParsedFile, Symbol+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _fi(path: str = "src/calc.py", language: str = "python") -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language=language,+ size_bytes=200,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++def _sym(+ name: str,+ kind: str = "function",+ start_line: int = 1,+ end_line: int = 5,+ signature: str = "",+) -> Symbol:+ return Symbol(+ id=f"src/calc.py::{name}",+ name=name,+ qualified_name=name,+ kind=kind, # type: ignore[arg-type]+ signature=signature or f"def {name}():",+ start_line=start_line,+ end_line=end_line,+ docstring=None,+ language="python",+ )+++def _parsed(symbols: list[Symbol], path: str = "src/calc.py") -> ParsedFile:+ return ParsedFile(+ file_info=_fi(path),+ symbols=symbols,+ imports=[],+ exports=[],+ docstring=None,+ parse_errors=[],+ content_hash="abc123",+ )+++# ---------------------------------------------------------------------------+# detect_symbol_renames+# ---------------------------------------------------------------------------+++class TestDetectSymbolRenames:+ def _detector(self, tmp_path: Path) -> ChangeDetector:+ return ChangeDetector(tmp_path)++ def test_no_renames_when_names_identical(self, tmp_path: Path) -> None:+ """Symbols present in both old and new should not produce renames."""+ d = self._detector(tmp_path)+ old = _parsed([_sym("compute")])+ new = _parsed([_sym("compute")])+ renames = d.detect_symbol_renames(old, new)+ assert renames == []++ def test_detects_similar_name_rename(self, tmp_path: Path) -> None:+ """'calc_add' renamed to 'calculate_add' should be detected."""+ d = self._detector(tmp_path)+ old = _parsed([_sym("calc_add", start_line=1)])+ new = _parsed([_sym("calculate_add", start_line=1)])+ renames = d.detect_symbol_renames(old, new)+ assert len(renames) == 1+ assert renames[0].old_name == "calc_add"+ assert renames[0].new_name == "calculate_add"+ assert renames[0].confidence > 0.65++ def test_different_kind_not_renamed(self, tmp_path: Path) -> None:+ """A function and a class with similar names should NOT be paired."""+ d = self._detector(tmp_path)+ old = _parsed([_sym("Calc", kind="class")])+ new = _parsed([_sym("Calc", kind="function")])+ # "Calc" exists in new under a different kind — old removed, new added+ # But they share the same name so old_syms and new_syms overlap,+ # meaning neither appears in removed/added — so no rename detected either.+ renames = d.detect_symbol_renames(old, new)+ assert renames == []++ def test_completely_different_names_not_renamed(self, tmp_path: Path) -> None:+ """'foo' removed and 'zymurgist' added — too dissimilar for rename."""+ d = self._detector(tmp_path)+ old = _parsed([_sym("foo")])+ new = _parsed([_sym("zymurgist")])+ renames = d.detect_symbol_renames(old, new)+ assert renames == []++ def test_line_proximity_boosts_confidence(self, tmp_path: Path) -> None:+ """Same line range increases confidence even for moderately similar names."""+ d = self._detector(tmp_path)+ old = _parsed([_sym("process_data", start_line=10)])+ new = _parsed([_sym("process_records", start_line=10)])+ renames = d.detect_symbol_renames(old, new)+ # Should be detected due to name similarity + line proximity+ assert len(renames) == 1+ assert renames[0].confidence >= 0.65++ def test_rename_confidence_is_in_range(self, tmp_path: Path) -> None:+ """Confidence is always in [0.0, 1.0]."""+ d = self._detector(tmp_path)+ old = _parsed([_sym("get_user")])+ new = _parsed([_sym("get_account")])+ renames = d.detect_symbol_renames(old, new)+ for r in renames:+ assert 0.0 <= r.confidence <= 1.0++ def test_each_new_name_used_at_most_once(self, tmp_path: Path) -> None:+ """Two similar old names should not both map to the same new name."""+ d = self._detector(tmp_path)+ old = _parsed([_sym("calc_add"), _sym("calc_mul", start_line=10)])+ new = _parsed([_sym("calc_add_numbers", start_line=1)])+ renames = d.detect_symbol_renames(old, new)+ new_names = [r.new_name for r in renames]+ # No duplicate targets+ assert len(new_names) == len(set(new_names))++ def test_empty_old_file_no_renames(self, tmp_path: Path) -> None:+ d = self._detector(tmp_path)+ old = _parsed([])+ new = _parsed([_sym("foo")])+ assert d.detect_symbol_renames(old, new) == []++ def test_empty_new_file_no_renames(self, tmp_path: Path) -> None:+ d = self._detector(tmp_path)+ old = _parsed([_sym("foo")])+ new = _parsed([])+ assert d.detect_symbol_renames(old, new) == []+++# ---------------------------------------------------------------------------+# get_changed_files — non-git fallback+# ---------------------------------------------------------------------------+++class TestGetChangedFilesNonGit:+ def test_non_git_directory_returns_empty(self, tmp_path: Path) -> None:+ """Non-git directory gracefully returns an empty list."""+ (tmp_path / "app.py").write_text("pass")+ d = ChangeDetector(tmp_path)+ result = d.get_changed_files()+ assert result == []++ def test_non_git_returns_empty_regardless_of_refs(self, tmp_path: Path) -> None:+ d = ChangeDetector(tmp_path)+ result = d.get_changed_files(base_ref="HEAD~5", until_ref="HEAD")+ assert result == []+++# ---------------------------------------------------------------------------+# get_affected_pages+# ---------------------------------------------------------------------------+++class TestGetAffectedPages:+ def _detector(self, tmp_path: Path) -> ChangeDetector:+ return ChangeDetector(tmp_path)++ def _simple_file_diff(+ self,+ path: str = "src/calc.py",+ status: str = "modified",+ symbol_diff: SymbolDiff | None = None,+ ):+ from wikicode.core.ingestion.change_detector import FileDiff++ return FileDiff(+ path=path,+ status=status, # type: ignore[arg-type]+ old_path=None,+ old_parsed=None,+ new_parsed=_parsed([], path=path),+ symbol_diff=symbol_diff,+ )++ def test_no_graph_returns_directly_changed(self, tmp_path: Path) -> None:+ d = self._detector(tmp_path)+ diff = self._simple_file_diff("a.py")+ result = d.get_affected_pages([diff], graph=object())+ assert "a.py" in result.regenerate+ assert result.rename_patch == []+ assert result.decay_only == []++ def test_with_graph_one_hop_cascade(self, tmp_path: Path) -> None:+ """Files that import a changed file should appear in regenerate."""+ d = self._detector(tmp_path)+ g = nx.DiGraph()+ g.add_node("a.py")+ g.add_node("b.py")+ # b.py imports a.py — so b.py is a predecessor of a.py in the import graph+ g.add_edge("b.py", "a.py")++ diff = self._simple_file_diff("a.py")+ result = d.get_affected_pages([diff], graph=g)+ assert "a.py" in result.regenerate+ assert "b.py" in result.regenerate++ def test_cascade_budget_limits_regeneration(self, tmp_path: Path) -> None:+ """Files exceeding cascade budget go to decay_only, not regenerate."""+ d = self._detector(tmp_path)+ g = nx.DiGraph()+ files = [f"file{i}.py" for i in range(10)]+ for f in files:+ g.add_node(f)+ # All import file0.py+ g.add_node("file0.py")+ for f in files[1:]:+ g.add_edge(f, "file0.py")++ diff = self._simple_file_diff("file0.py")+ result = d.get_affected_pages([diff], graph=g, cascade_budget=3)+ # Total needing regen: file0.py + up to 9 importers+ assert len(result.regenerate) <= 3+ # Some go to decay_only+ assert len(result.decay_only) > 0++ def test_all_lists_are_disjoint(self, tmp_path: Path) -> None:+ """regenerate, rename_patch, and decay_only should be disjoint."""+ d = self._detector(tmp_path)+ g = nx.DiGraph()+ for i in range(5):+ g.add_node(f"f{i}.py")+ g.add_edge("f1.py", "f0.py")+ g.add_edge("f2.py", "f0.py")++ diff = self._simple_file_diff("f0.py")+ result = d.get_affected_pages([diff], graph=g, cascade_budget=2)+ regen = set(result.regenerate)+ decay = set(result.decay_only)+ rename = set(result.rename_patch)+ assert regen.isdisjoint(decay)+ assert rename.issubset(regen) # rename_patch is always a subset of regenerate++ def test_rename_patch_subset_of_regenerate(self, tmp_path: Path) -> None:+ """rename_patch pages must appear in regenerate."""+ from wikicode.core.ingestion.change_detector import FileDiff, SymbolRename++ d = self._detector(tmp_path)+ g = nx.DiGraph()+ g.add_node("calc.py")++ sym_diff = SymbolDiff(+ added=[],+ removed=[],+ renamed=[SymbolRename("add", "calculate_add", "function", 0.9)],+ modified=[],+ )+ diff = FileDiff(+ path="calc.py",+ status="modified",+ old_path=None,+ old_parsed=None,+ new_parsed=_parsed([], path="calc.py"),+ symbol_diff=sym_diff,+ )+ result = d.get_affected_pages([diff], graph=g)+ for p in result.rename_patch:+ assert p in result.regenerate++ def test_empty_diffs_returns_empty_pages(self, tmp_path: Path) -> None:+ d = self._detector(tmp_path)+ g = nx.DiGraph()+ result = d.get_affected_pages([], graph=g)+ assert result.regenerate == []+ assert result.rename_patch == []+ assert result.decay_only == []diff --git a/tests/unit/ingestion/test_graph.py b/tests/unit/ingestion/test_graph.pynew file mode 100644index 000000000..a1fc12199--- /dev/null+++ b/tests/unit/ingestion/test_graph.py@@ -0,0 +1,416 @@+"""Unit tests for GraphBuilder."""++from __future__ import annotations++import asyncio+from datetime import datetime+from pathlib import Path++import networkx as nx+import pytest++from wikicode.core.ingestion.graph import GraphBuilder+from wikicode.core.ingestion.models import FileInfo, Import, ParsedFile+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _fi(path: str, language: str = "python") -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language=language,+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++def _parsed(+ path: str,+ language: str = "python",+ imports: list[Import] | None = None,+) -> ParsedFile:+ return ParsedFile(+ file_info=_fi(path, language),+ symbols=[],+ imports=imports or [],+ exports=[],+ docstring=None,+ parse_errors=[],+ content_hash="",+ )+++def _imp(module_path: str, is_relative: bool = False, names: list[str] | None = None) -> Import:+ return Import(+ raw_statement=f"import {module_path}",+ module_path=module_path,+ imported_names=names or [],+ is_relative=is_relative,+ resolved_file=None,+ )+++# ---------------------------------------------------------------------------+# Empty graph+# ---------------------------------------------------------------------------+++class TestEmptyGraph:+ def test_no_nodes(self) -> None:+ b = GraphBuilder()+ g = b.graph()+ assert g.number_of_nodes() == 0++ def test_pagerank_empty(self) -> None:+ b = GraphBuilder()+ assert b.pagerank() == {}++ def test_betweenness_empty(self) -> None:+ b = GraphBuilder()+ assert b.betweenness_centrality() == {}++ def test_community_empty(self) -> None:+ b = GraphBuilder()+ assert b.community_detection() == {}++ def test_sccs_empty(self) -> None:+ b = GraphBuilder()+ assert b.strongly_connected_components() == []++ def test_to_json_empty(self) -> None:+ b = GraphBuilder()+ data = b.to_json()+ assert "nodes" in data+ assert data["nodes"] == []+++# ---------------------------------------------------------------------------+# Node creation+# ---------------------------------------------------------------------------+++class TestAddFile:+ def test_node_created(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("src/calc.py"))+ g = b.graph()+ assert "src/calc.py" in g.nodes++ def test_node_attributes(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("src/calc.py"))+ g = b.graph()+ attrs = g.nodes["src/calc.py"]+ assert attrs["language"] == "python"+ assert attrs["symbol_count"] == 0+ assert attrs["has_error"] is False+ assert attrs["is_test"] is False++ def test_multiple_files(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("a.py"))+ b.add_file(_parsed("b.py"))+ g = b.graph()+ assert g.number_of_nodes() == 2+++# ---------------------------------------------------------------------------+# Python import resolution+# ---------------------------------------------------------------------------+++class TestPythonImports:+ def test_absolute_import_dotted(self) -> None:+ """'from pkg.calc import X' should resolve to pkg/calc.py."""+ b = GraphBuilder()+ b.add_file(_parsed("pkg/calc.py"))+ b.add_file(_parsed("main.py", imports=[_imp("pkg.calc")]))+ b.build()+ assert b.graph().has_edge("main.py", "pkg/calc.py")++ def test_relative_import_sibling(self) -> None:+ """'from . import sibling' resolves to sibling in same directory."""+ b = GraphBuilder()+ b.add_file(_parsed("pkg/calc.py"))+ b.add_file(_parsed("pkg/main.py", imports=[_imp(".calc", is_relative=True)]))+ b.build()+ assert b.graph().has_edge("pkg/main.py", "pkg/calc.py")++ def test_stem_fallback(self) -> None:+ """Stem matching: 'import calculator' → calculator.py anywhere."""+ b = GraphBuilder()+ b.add_file(_parsed("src/calculator.py"))+ b.add_file(_parsed("main.py", imports=[_imp("calculator")]))+ b.build()+ assert b.graph().has_edge("main.py", "src/calculator.py")++ def test_unresolvable_import_no_edge(self) -> None:+ """Unresolvable import produces no edge (no crash)."""+ b = GraphBuilder()+ b.add_file(_parsed("main.py", imports=[_imp("nonexistent_external_lib")]))+ b.build()+ assert b.graph().number_of_edges() == 0++ def test_imported_names_on_edge(self) -> None:+ """Imported names are stored on the edge."""+ b = GraphBuilder()+ b.add_file(_parsed("utils.py"))+ b.add_file(_parsed("main.py", imports=[_imp("utils", names=["helper", "fmt"])]))+ b.build()+ data = b.graph()["main.py"]["utils.py"]+ assert "helper" in data["imported_names"]+ assert "fmt" in data["imported_names"]++ def test_parallel_imports_merged(self) -> None:+ """Two imports of the same module merge their imported_names."""+ b = GraphBuilder()+ b.add_file(_parsed("utils.py"))+ b.add_file(+ _parsed(+ "main.py",+ imports=[+ _imp("utils", names=["foo"]),+ _imp("utils", names=["bar"]),+ ],+ )+ )+ b.build()+ names = set(b.graph()["main.py"]["utils.py"]["imported_names"])+ assert "foo" in names+ assert "bar" in names+++# ---------------------------------------------------------------------------+# TypeScript import resolution+# ---------------------------------------------------------------------------+++class TestTypeScriptImports:+ def test_relative_ts_import(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("src/utils.ts", language="typescript"))+ b.add_file(+ _parsed(+ "src/client.ts",+ language="typescript",+ imports=[_imp("./utils", is_relative=True)],+ )+ )+ b.build()+ assert b.graph().has_edge("src/client.ts", "src/utils.ts")++ def test_external_npm_package(self) -> None:+ b = GraphBuilder()+ b.add_file(+ _parsed(+ "src/app.ts",+ language="typescript",+ imports=[_imp("react")],+ )+ )+ b.build()+ g = b.graph()+ assert any("external:" in n for n in g.nodes)+ external_node = next(n for n in g.nodes if n.startswith("external:"))+ assert g.has_edge("src/app.ts", external_node)+++# ---------------------------------------------------------------------------+# Go import resolution+# ---------------------------------------------------------------------------+++class TestGoImports:+ def test_go_stem_resolution(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("calculator/calculator.go", language="go"))+ b.add_file(+ _parsed(+ "main.go",+ language="go",+ imports=[_imp("github.com/example/myapp/calculator")],+ )+ )+ b.build()+ assert b.graph().has_edge("main.go", "calculator/calculator.go")+++# ---------------------------------------------------------------------------+# Graph idempotency+# ---------------------------------------------------------------------------+++class TestBuildIdempotent:+ def test_build_twice_same_edges(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("calc.py"))+ b.add_file(_parsed("main.py", imports=[_imp("calc")]))+ b.build()+ edges1 = list(b.graph().edges())+ b.build()+ edges2 = list(b.graph().edges())+ assert edges1 == edges2++ def test_graph_property_auto_builds(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("a.py"))+ g = b.graph() # should auto-build+ assert "a.py" in g.nodes+++# ---------------------------------------------------------------------------+# Graph metrics+# ---------------------------------------------------------------------------+++class TestPageRank:+ def test_scores_sum_to_one(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("a.py"))+ b.add_file(_parsed("b.py"))+ b.add_file(_parsed("c.py", imports=[_imp("a"), _imp("b")]))+ b.build()+ pr = b.pagerank()+ assert abs(sum(pr.values()) - 1.0) < 1e-6++ def test_highly_imported_node_higher_rank(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("shared.py"))+ b.add_file(_parsed("a.py", imports=[_imp("shared")]))+ b.add_file(_parsed("c.py", imports=[_imp("shared")]))+ b.add_file(_parsed("d.py", imports=[_imp("shared")]))+ b.add_file(_parsed("isolated.py"))+ b.build()+ pr = b.pagerank()+ assert pr["shared.py"] > pr["isolated.py"]+++class TestSCCs:+ def test_acyclic_graph_all_singleton_sccs(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("a.py"))+ b.add_file(_parsed("b.py", imports=[_imp("a")]))+ b.add_file(_parsed("c.py", imports=[_imp("b")]))+ b.build()+ sccs = b.strongly_connected_components()+ # All SCCs of size 1 in a DAG+ assert all(len(s) == 1 for s in sccs)++ def test_cyclic_graph_has_large_scc(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("a.py", imports=[_imp("b")]))+ b.add_file(_parsed("b.py", imports=[_imp("a")]))+ b.build()+ sccs = b.strongly_connected_components()+ large = [s for s in sccs if len(s) > 1]+ assert len(large) == 1+ assert frozenset({"a.py", "b.py"}) in large+++class TestBetweenness:+ def test_returns_scores_for_all_nodes(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("a.py"))+ b.add_file(_parsed("b.py"))+ b.add_file(_parsed("c.py"))+ bc = b.betweenness_centrality()+ assert set(bc.keys()) == {"a.py", "b.py", "c.py"}++ def test_bridge_node_higher_centrality(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("a.py", imports=[_imp("bridge")]))+ b.add_file(_parsed("bridge.py", imports=[_imp("z")]))+ b.add_file(_parsed("z.py"))+ b.build()+ bc = b.betweenness_centrality()+ assert bc.get("bridge.py", 0.0) >= bc.get("a.py", 0.0)+++class TestCommunityDetection:+ def test_returns_assignment_for_all_nodes(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("a.py"))+ b.add_file(_parsed("b.py"))+ b.add_file(_parsed("c.py"))+ comm = b.community_detection()+ assert set(comm.keys()) == {"a.py", "b.py", "c.py"}+ assert all(isinstance(v, int) for v in comm.values())+++# ---------------------------------------------------------------------------+# Serialization+# ---------------------------------------------------------------------------+++class TestToJson:+ def test_json_has_expected_keys(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("a.py"))+ data = b.to_json()+ assert "nodes" in data+ assert "links" in data or "edges" in data # networkx version-dependent key name++ def test_json_nodes_match_graph(self) -> None:+ b = GraphBuilder()+ b.add_file(_parsed("x.py"))+ b.add_file(_parsed("y.py"))+ data = b.to_json()+ node_ids = {n["id"] for n in data["nodes"]}+ assert "x.py" in node_ids+ assert "y.py" in node_ids+++# ---------------------------------------------------------------------------+# Persistence+# ---------------------------------------------------------------------------+++class TestPersist:+ def test_persist_creates_tables(self, tmp_path: Path) -> None:+ import aiosqlite++ b = GraphBuilder()+ b.add_file(_parsed("a.py"))+ b.add_file(_parsed("b.py", imports=[_imp("a")]))+ b.build()++ db_path = tmp_path / "graph.db"++ async def run() -> None:+ await b.persist(db_path, repo_id="test-repo")+ async with aiosqlite.connect(db_path) as db:+ async with db.execute("SELECT * FROM graph_nodes") as cur:+ rows = await cur.fetchall()+ assert len(rows) == 2+ async with db.execute("SELECT * FROM graph_edges") as cur:+ edges = await cur.fetchall()+ assert len(edges) == 1++ asyncio.run(run())++ def test_persist_stores_repo_id(self, tmp_path: Path) -> None:+ import aiosqlite++ b = GraphBuilder()+ b.add_file(_parsed("x.py"))++ db_path = tmp_path / "graph.db"++ async def run() -> None:+ await b.persist(db_path, repo_id="my-project")+ async with aiosqlite.connect(db_path) as db:+ async with db.execute("SELECT repo_id FROM graph_nodes LIMIT 1") as cur:+ row = await cur.fetchone()+ assert row is not None+ assert row[0] == "my-project"++ asyncio.run(run())diff --git a/tests/unit/ingestion/test_parser.py b/tests/unit/ingestion/test_parser.pynew file mode 100644index 000000000..13df37136--- /dev/null+++ b/tests/unit/ingestion/test_parser.py@@ -0,0 +1,607 @@+"""Unit tests for the unified ASTParser.++Tests parse inline byte strings so no filesystem I/O is needed.+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import pytest++from wikicode.core.ingestion.models import FileInfo+from wikicode.core.ingestion.parser import ASTParser, LANGUAGE_CONFIGS++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_file_info(path: str, language: str) -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=f"/tmp/{path}",+ language=language,+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )++[email protected](scope="module")+def parser() -> ASTParser:+ return ASTParser()+++# ---------------------------------------------------------------------------+# Python+# ---------------------------------------------------------------------------++PYTHON_SOURCE = b'''"""Module docstring."""++from __future__ import annotations++from python_pkg.models import Operation+from python_pkg.utils import round_result+import os+++class DivisionByZeroError(ArithmeticError):+ """Raised on division by zero."""+++def add(x: float, y: float) -> float:+ """Return x + y."""+ return x + y+++def subtract(x: float, y: float) -> float:+ """Return x - y."""+ return x - y+++class Calculator:+ """Stateful calculator."""++ def __init__(self) -> None:+ self._history = []++ def add(self, x: float, y: float) -> float:+ """Add x and y."""+ return add(x, y)++ @staticmethod+ def version() -> str:+ """Return version string."""+ return "1.0"+'''+++class TestPythonParser:+ def test_module_docstring(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ assert result.docstring == "Module docstring."++ def test_finds_top_level_functions(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ names = [s.name for s in result.symbols]+ assert "add" in names+ assert "subtract" in names++ def test_finds_classes(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ classes = [s for s in result.symbols if s.kind == "class"]+ class_names = [c.name for c in classes]+ assert "Calculator" in class_names+ assert "DivisionByZeroError" in class_names++ def test_finds_methods(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ methods = [s for s in result.symbols if s.kind == "method"]+ method_names = [m.name for m in methods]+ assert "add" in method_names+ assert "__init__" in method_names++ def test_method_has_parent(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ calc_add = next(+ s for s in result.symbols if s.name == "add" and s.parent_name == "Calculator"+ )+ assert calc_add.parent_name == "Calculator"++ def test_private_visibility(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ init = next(s for s in result.symbols if s.name == "__init__")+ # Dunder is public by our convention+ assert init.visibility == "public"++ def test_parses_imports(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ module_paths = [i.module_path for i in result.imports]+ assert "python_pkg.models" in module_paths+ assert "python_pkg.utils" in module_paths+ assert "os" in module_paths++ def test_from_import_names(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ op_import = next(+ i for i in result.imports if i.module_path == "python_pkg.models"+ )+ assert "Operation" in op_import.imported_names++ def test_function_docstring(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ add_fn = next(s for s in result.symbols if s.name == "add" and s.parent_name is None)+ assert add_fn.docstring == "Return x + y."++ def test_class_docstring(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ calc = next(s for s in result.symbols if s.name == "Calculator")+ assert calc.docstring == "Stateful calculator."++ def test_no_parse_errors_on_valid_source(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ assert result.parse_errors == []++ def test_parse_errors_on_invalid_source(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/bad.py", "python")+ result = parser.parse_file(fi, b"def (broken syntax: \npass\n")+ # Should not crash, but should report error+ assert isinstance(result.parse_errors, list)++ def test_qualified_name(self, parser: ASTParser) -> None:+ fi = _make_file_info("python_pkg/calculator.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ calc_add = next(+ s for s in result.symbols if s.name == "add" and s.parent_name == "Calculator"+ )+ assert "python_pkg.calculator.Calculator.add" == calc_add.qualified_name++ def test_exports_list(self, parser: ASTParser) -> None:+ fi = _make_file_info("pkg/calc.py", "python")+ result = parser.parse_file(fi, PYTHON_SOURCE)+ # Public top-level symbols should be in exports+ assert "add" in result.exports+ assert "Calculator" in result.exports+++# ---------------------------------------------------------------------------+# TypeScript+# ---------------------------------------------------------------------------++TS_SOURCE = b'''/**+ * Sample TypeScript client module.+ * Exports ApiClient and related types.+ */++import type {+ ApiClientConfig,+ CalculationRequest,+ CalculationResponse,+} from "./types";+import { validateRequest, parseApiError } from "./utils";++/** Error from the API. */+export class ApiClientError extends Error {+ public readonly apiError: unknown;+ constructor(apiError: unknown) {+ super("API error");+ this.apiError = apiError;+ }+}++/** Validation error. */+export class ValidationError extends Error {}++const DEFAULT_TIMEOUT_MS = 10_000;++/** Typed HTTP client. */+export class ApiClient {+ private readonly baseUrl: string;++ constructor(config: ApiClientConfig) {+ this.baseUrl = config.baseUrl;+ }++ async calculate(request: CalculationRequest): Promise<CalculationResponse> {+ return this.post("/calculations", request);+ }++ async healthCheck(): Promise<boolean> {+ return true;+ }++ private async post<T>(path: string, body: unknown): Promise<T> {+ return {} as T;+ }+}++export function createClient(config: ApiClientConfig): ApiClient {+ return new ApiClient(config);+}+'''+++class TestTypeScriptParser:+ def test_finds_classes(self, parser: ASTParser) -> None:+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")+ result = parser.parse_file(fi, TS_SOURCE)+ class_names = [s.name for s in result.symbols if s.kind == "class"]+ assert "ApiClient" in class_names+ assert "ApiClientError" in class_names+ assert "ValidationError" in class_names++ def test_finds_methods(self, parser: ASTParser) -> None:+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")+ result = parser.parse_file(fi, TS_SOURCE)+ method_names = [s.name for s in result.symbols if s.kind == "method"]+ assert "calculate" in method_names+ assert "healthCheck" in method_names++ def test_finds_top_level_function(self, parser: ASTParser) -> None:+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")+ result = parser.parse_file(fi, TS_SOURCE)+ fn_names = [s.name for s in result.symbols if s.kind == "function"]+ assert "createClient" in fn_names++ def test_parses_imports(self, parser: ASTParser) -> None:+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")+ result = parser.parse_file(fi, TS_SOURCE)+ module_paths = [i.module_path for i in result.imports]+ assert "./types" in module_paths+ assert "./utils" in module_paths++ def test_relative_imports_flagged(self, parser: ASTParser) -> None:+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")+ result = parser.parse_file(fi, TS_SOURCE)+ types_import = next(i for i in result.imports if i.module_path == "./types")+ assert types_import.is_relative is True++ def test_no_parse_errors(self, parser: ASTParser) -> None:+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")+ result = parser.parse_file(fi, TS_SOURCE)+ assert result.parse_errors == []+++# ---------------------------------------------------------------------------+# Go+# ---------------------------------------------------------------------------++GO_SOURCE = b'''// Package calculator provides arithmetic with history.+package calculator++import (+ "errors"+ "fmt"++ "github.com/wikicode-ai/sample/types"+)++// ErrDivisionByZero is returned on division by zero.+var ErrDivisionByZero = errors.New("division by zero")++// Calculator maintains a calculation history.+type Calculator struct {+ history []types.CalculationRecord+}++// New returns a new Calculator.+func New() *Calculator {+ return &Calculator{}+}++// Add returns the sum of the operands.+func (c *Calculator) Add(ops types.Operands) (float64, error) {+ result := ops.X + ops.Y+ return result, nil+}++// Divide returns ops.X / ops.Y.+func (c *Calculator) Divide(ops types.Operands) (float64, error) {+ if ops.Y == 0 {+ return 0, ErrDivisionByZero+ }+ return ops.X / ops.Y, nil+}+'''+++class TestGoParser:+ def test_finds_struct(self, parser: ASTParser) -> None:+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")+ result = parser.parse_file(fi, GO_SOURCE)+ structs = [s for s in result.symbols if s.kind == "struct"]+ assert any(s.name == "Calculator" for s in structs)++ def test_finds_functions(self, parser: ASTParser) -> None:+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")+ result = parser.parse_file(fi, GO_SOURCE)+ fns = [s for s in result.symbols if s.kind == "function"]+ assert any(s.name == "New" for s in fns)++ def test_finds_methods_with_receiver(self, parser: ASTParser) -> None:+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")+ result = parser.parse_file(fi, GO_SOURCE)+ methods = [s for s in result.symbols if s.kind == "method"]+ method_names = [m.name for m in methods]+ assert "Add" in method_names+ assert "Divide" in method_names++ def test_method_has_parent_from_receiver(self, parser: ASTParser) -> None:+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")+ result = parser.parse_file(fi, GO_SOURCE)+ add_method = next(s for s in result.symbols if s.name == "Add" and s.kind == "method")+ assert add_method.parent_name == "Calculator"++ def test_go_visibility_by_capitalisation(self, parser: ASTParser) -> None:+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")+ result = parser.parse_file(fi, GO_SOURCE)+ new_fn = next(s for s in result.symbols if s.name == "New")+ assert new_fn.visibility == "public"++ def test_parses_imports(self, parser: ASTParser) -> None:+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")+ result = parser.parse_file(fi, GO_SOURCE)+ module_paths = [i.module_path for i in result.imports]+ assert any("errors" in p for p in module_paths)+ assert any("sample/types" in p for p in module_paths)++ def test_no_parse_errors(self, parser: ASTParser) -> None:+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")+ result = parser.parse_file(fi, GO_SOURCE)+ assert result.parse_errors == []+++# ---------------------------------------------------------------------------+# Rust+# ---------------------------------------------------------------------------++RUST_SOURCE = b'''//! Sample Rust calculator.++use std::fmt;++/// Supported operations.+#[derive(Debug, Clone, Copy)]+pub enum Operation {+ Add,+ Subtract,+}++/// A single recorded calculation.+#[derive(Debug, Clone)]+pub struct CalculationRecord {+ pub result: f64,+}++impl CalculationRecord {+ /// Create a new record.+ pub fn new(result: f64) -> Self {+ Self { result }+ }++ /// Return a summary string.+ pub fn summary(&self) -> String {+ format!("{:.2}", self.result)+ }+}++/// Add two numbers.+pub fn add(x: f64, y: f64) -> f64 {+ x + y+}+'''+++class TestRustParser:+ def test_finds_enum(self, parser: ASTParser) -> None:+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")+ result = parser.parse_file(fi, RUST_SOURCE)+ enums = [s for s in result.symbols if s.kind == "enum"]+ assert any(s.name == "Operation" for s in enums)++ def test_finds_struct(self, parser: ASTParser) -> None:+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")+ result = parser.parse_file(fi, RUST_SOURCE)+ structs = [s for s in result.symbols if s.kind == "struct"]+ assert any(s.name == "CalculationRecord" for s in structs)++ def test_finds_impl_block(self, parser: ASTParser) -> None:+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")+ result = parser.parse_file(fi, RUST_SOURCE)+ impls = [s for s in result.symbols if s.kind == "impl"]+ assert any(s.name == "CalculationRecord" for s in impls)++ def test_finds_top_level_function(self, parser: ASTParser) -> None:+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")+ result = parser.parse_file(fi, RUST_SOURCE)+ fns = [s for s in result.symbols if s.kind == "function"]+ assert any(s.name == "add" for s in fns)++ def test_pub_visibility(self, parser: ASTParser) -> None:+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")+ result = parser.parse_file(fi, RUST_SOURCE)+ add_fn = next(s for s in result.symbols if s.name == "add" and s.kind == "function")+ assert add_fn.visibility == "public"++ def test_parses_use_declaration(self, parser: ASTParser) -> None:+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")+ result = parser.parse_file(fi, RUST_SOURCE)+ assert len(result.imports) >= 1+++# ---------------------------------------------------------------------------+# Java+# ---------------------------------------------------------------------------++JAVA_SOURCE = b'''package com.wikicode.sample;++import java.util.ArrayList;+import java.util.List;++/**+ * Stateful calculator with history.+ */+public class Calculator {++ private final List<Object> history = new ArrayList<>();++ /**+ * Adds x and y.+ */+ public double add(double x, double y) {+ return x + y;+ }++ /** Private helper. */+ private void record(Object entry) {+ history.add(entry);+ }+}+'''+++class TestJavaParser:+ def test_finds_class(self, parser: ASTParser) -> None:+ fi = _make_file_info("java_pkg/Calculator.java", "java")+ result = parser.parse_file(fi, JAVA_SOURCE)+ classes = [s for s in result.symbols if s.kind == "class"]+ assert any(s.name == "Calculator" for s in classes)++ def test_finds_methods(self, parser: ASTParser) -> None:+ fi = _make_file_info("java_pkg/Calculator.java", "java")+ result = parser.parse_file(fi, JAVA_SOURCE)+ methods = [s for s in result.symbols if s.kind == "method"]+ method_names = [m.name for m in methods]+ assert "add" in method_names+ assert "record" in method_names++ def test_parses_imports(self, parser: ASTParser) -> None:+ fi = _make_file_info("java_pkg/Calculator.java", "java")+ result = parser.parse_file(fi, JAVA_SOURCE)+ assert len(result.imports) >= 2+ module_paths = [i.module_path for i in result.imports]+ assert any("ArrayList" in p for p in module_paths)+++# ---------------------------------------------------------------------------+# C+++# ---------------------------------------------------------------------------++CPP_SOURCE = b'''#include "calculator.hpp"+#include <stdexcept>+#include <string>++namespace sample {++double Calculator::add(double x, double y) {+ return x + y;+}++double Calculator::divide(double x, double y) {+ if (y == 0.0) {+ throw std::invalid_argument("Division by zero");+ }+ return x / y;+}++} // namespace sample+'''++CPP_HEADER_SOURCE = b'''#pragma once++#include <vector>+#include "models.hpp"++namespace sample {++class Calculator {+public:+ double add(double x, double y);+ double subtract(double x, double y);+ double divide(double x, double y);++private:+ std::vector<int> history_;+};++} // namespace sample+'''+++class TestCppParser:+ def test_finds_class_in_header(self, parser: ASTParser) -> None:+ fi = _make_file_info("cpp_pkg/calculator.hpp", "cpp")+ result = parser.parse_file(fi, CPP_HEADER_SOURCE)+ classes = [s for s in result.symbols if s.kind == "class"]+ assert any(s.name == "Calculator" for s in classes)++ def test_finds_functions_in_source(self, parser: ASTParser) -> None:+ fi = _make_file_info("cpp_pkg/calculator.cpp", "cpp")+ result = parser.parse_file(fi, CPP_SOURCE)+ fns = [s for s in result.symbols if s.kind == "function"]+ # Qualified definitions like Calculator::add should be caught+ assert len(fns) >= 1++ def test_parses_includes(self, parser: ASTParser) -> None:+ fi = _make_file_info("cpp_pkg/calculator.cpp", "cpp")+ result = parser.parse_file(fi, CPP_SOURCE)+ assert len(result.imports) >= 2+ module_paths = [i.module_path for i in result.imports]+ assert any("calculator.hpp" in p or "stdexcept" in p for p in module_paths)+++# ---------------------------------------------------------------------------+# Unsupported language (graceful fallback)+# ---------------------------------------------------------------------------+++class TestUnsupportedLanguage:+ def test_returns_empty_parsed_file(self, parser: ASTParser) -> None:+ fi = _make_file_info("file.sql", "sql")+ fi.language = "sql"+ result = parser.parse_file(fi, b"SELECT * FROM users;")+ assert result.symbols == []+ assert result.imports == []+ assert len(result.parse_errors) == 1+ assert "sql" in result.parse_errors[0].lower()+++# ---------------------------------------------------------------------------+# LANGUAGE_CONFIGS completeness+# ---------------------------------------------------------------------------+++class TestLanguageConfigs:+ def test_all_supported_languages_have_config(self) -> None:+ expected = {"python", "typescript", "javascript", "go", "rust", "java", "cpp", "c"}+ for lang in expected:+ assert lang in LANGUAGE_CONFIGS, f"Missing config for {lang}"++ def test_each_config_has_symbol_node_types(self) -> None:+ for lang, config in LANGUAGE_CONFIGS.items():+ assert len(config.symbol_node_types) > 0, f"{lang} has no symbol_node_types"++ def test_each_config_has_visibility_fn(self) -> None:+ for lang, config in LANGUAGE_CONFIGS.items():+ # Must be callable+ result = config.visibility_fn("MyClass", [])+ assert result in ("public", "private", "protected", "internal"), (+ f"{lang} visibility_fn returned unexpected: {result}"+ )diff --git a/tests/unit/ingestion/test_traverser.py b/tests/unit/ingestion/test_traverser.pynew file mode 100644index 000000000..b27af6c66--- /dev/null+++ b/tests/unit/ingestion/test_traverser.py@@ -0,0 +1,301 @@+"""Unit tests for FileTraverser."""++from __future__ import annotations++from pathlib import Path++import pytest++from wikicode.core.ingestion.traverser import FileTraverser, _detect_language+++# ---------------------------------------------------------------------------+# Language detection+# ---------------------------------------------------------------------------+++class TestLanguageDetection:+ def test_python_extension(self, tmp_path: Path) -> None:+ f = tmp_path / "foo.py"+ f.write_text("x = 1")+ assert _detect_language(f) == "python"++ def test_typescript_extension(self, tmp_path: Path) -> None:+ f = tmp_path / "bar.ts"+ f.write_text("const x = 1;")+ assert _detect_language(f) == "typescript"++ def test_tsx_extension(self, tmp_path: Path) -> None:+ f = tmp_path / "Comp.tsx"+ f.write_text("<div />")+ assert _detect_language(f) == "typescript"++ def test_go_extension(self, tmp_path: Path) -> None:+ assert _detect_language(tmp_path / "main.go") == "go"++ def test_rust_extension(self, tmp_path: Path) -> None:+ assert _detect_language(tmp_path / "lib.rs") == "rust"++ def test_java_extension(self, tmp_path: Path) -> None:+ assert _detect_language(tmp_path / "Calculator.java") == "java"++ def test_cpp_extension(self, tmp_path: Path) -> None:+ assert _detect_language(tmp_path / "calc.cpp") == "cpp"++ def test_special_dockerfile(self, tmp_path: Path) -> None:+ assert _detect_language(tmp_path / "Dockerfile") == "dockerfile"++ def test_special_makefile(self, tmp_path: Path) -> None:+ assert _detect_language(tmp_path / "Makefile") == "makefile"++ def test_unknown_extension(self, tmp_path: Path) -> None:+ assert _detect_language(tmp_path / "binary.elf") == "unknown"++ def test_python_shebang(self, tmp_path: Path) -> None:+ f = tmp_path / "script"+ f.write_text("#!/usr/bin/env python3\nprint('hi')")+ assert _detect_language(f) == "python"+++# ---------------------------------------------------------------------------+# File traversal+# ---------------------------------------------------------------------------+++class TestFileTraverser:+ @pytest.fixture+ def simple_repo(self, tmp_path: Path) -> Path:+ """Create a minimal repo structure."""+ (tmp_path / "src").mkdir()+ (tmp_path / "src" / "main.py").write_text("def main(): pass")+ (tmp_path / "src" / "utils.py").write_text("def helper(): pass")+ (tmp_path / "tests").mkdir()+ (tmp_path / "tests" / "test_main.py").write_text("def test_foo(): pass")+ (tmp_path / "node_modules").mkdir()+ (tmp_path / "node_modules" / "lodash" / "index.js").mkdir(parents=True)+ (tmp_path / "__pycache__").mkdir()+ (tmp_path / "__pycache__" / "main.cpython-311.pyc").write_bytes(b"\x00")+ return tmp_path++ def test_traverses_python_files(self, simple_repo: Path) -> None:+ traverser = FileTraverser(simple_repo)+ paths = [f.path for f in traverser.traverse()]+ assert any("main.py" in p for p in paths)+ assert any("utils.py" in p for p in paths)++ def test_skips_node_modules(self, simple_repo: Path) -> None:+ traverser = FileTraverser(simple_repo)+ paths = [f.path for f in traverser.traverse()]+ assert not any("node_modules" in p for p in paths)++ def test_skips_pycache(self, simple_repo: Path) -> None:+ traverser = FileTraverser(simple_repo)+ paths = [f.path for f in traverser.traverse()]+ assert not any("__pycache__" in p for p in paths)++ def test_skips_binary_files(self, tmp_path: Path) -> None:+ binary = tmp_path / "binary.so"+ binary.write_bytes(b"\x00\x01\x02\x03" * 100)+ traverser = FileTraverser(tmp_path)+ paths = [f.path for f in traverser.traverse()]+ assert not any("binary.so" in p for p in paths)++ def test_respects_gitignore(self, tmp_path: Path) -> None:+ (tmp_path / ".gitignore").write_text("*.log\nsecret/\n")+ (tmp_path / "app.py").write_text("pass")+ (tmp_path / "debug.log").write_text("logs")+ (tmp_path / "secret").mkdir()+ (tmp_path / "secret" / "key.py").write_text("KEY = 'x'")+ traverser = FileTraverser(tmp_path)+ paths = [f.path for f in traverser.traverse()]+ assert any("app.py" in p for p in paths)+ assert not any("debug.log" in p for p in paths)+ assert not any("secret" in p for p in paths)++ def test_skips_oversized_files(self, tmp_path: Path) -> None:+ big = tmp_path / "big.py"+ big.write_bytes(b"x = 1\n" * 200_000) # ~1.2 MB+ traverser = FileTraverser(tmp_path, max_file_size_kb=500)+ paths = [f.path for f in traverser.traverse()]+ assert not any("big.py" in p for p in paths)++ def test_deterministic_ordering(self, simple_repo: Path) -> None:+ traverser = FileTraverser(simple_repo)+ run1 = [f.path for f in traverser.traverse()]+ run2 = [f.path for f in traverser.traverse()]+ assert run1 == run2++ def test_is_test_flag(self, simple_repo: Path) -> None:+ traverser = FileTraverser(simple_repo)+ files = {f.path: f for f in traverser.traverse()}+ test_file = next(p for p in files if "test_main" in p)+ assert files[test_file].is_test is True+ main_file = next(p for p in files if p.endswith("main.py"))+ assert files[main_file].is_test is False++ def test_file_info_fields(self, tmp_path: Path) -> None:+ (tmp_path / "calc.py").write_text("class Calc: pass")+ traverser = FileTraverser(tmp_path)+ files = list(traverser.traverse())+ assert len(files) == 1+ fi = files[0]+ assert fi.language == "python"+ assert fi.size_bytes > 0+ assert fi.abs_path.endswith("calc.py")+++# ---------------------------------------------------------------------------+# Extra exclude patterns (CLI --exclude / settings["exclude_patterns"])+# ---------------------------------------------------------------------------+++class TestExtraExcludePatterns:+ def test_extra_exclude_vendor_dir(self, tmp_path: Path) -> None:+ (tmp_path / "src").mkdir()+ (tmp_path / "src" / "main.py").write_text("pass")+ (tmp_path / "vendor").mkdir()+ (tmp_path / "vendor" / "utils.py").write_text("pass")+ traverser = FileTraverser(tmp_path, extra_exclude_patterns=["vendor/"])+ paths = [f.path for f in traverser.traverse()]+ assert any("main.py" in p for p in paths)+ assert not any("vendor" in p for p in paths)++ def test_extra_exclude_nested_glob(self, tmp_path: Path) -> None:+ (tmp_path / "src" / "generated").mkdir(parents=True)+ (tmp_path / "src" / "generated" / "proto.py").write_text("pass")+ (tmp_path / "src" / "real.py").write_text("pass")+ traverser = FileTraverser(tmp_path, extra_exclude_patterns=["src/generated/**"])+ paths = [f.path for f in traverser.traverse()]+ assert any("real.py" in p for p in paths)+ assert not any("proto.py" in p for p in paths)++ def test_extra_exclude_dir_pattern(self, tmp_path: Path) -> None:+ (tmp_path / "src" / "generated").mkdir(parents=True)+ (tmp_path / "src" / "generated" / "types.ts").write_text("export type T = string;")+ (tmp_path / "src" / "app.ts").write_text("const x = 1;")+ traverser = FileTraverser(tmp_path, extra_exclude_patterns=["src/generated/"])+ paths = [f.path for f in traverser.traverse()]+ assert any("app.ts" in p for p in paths)+ assert not any("types.ts" in p for p in paths)++ def test_extra_exclude_multiple_patterns(self, tmp_path: Path) -> None:+ (tmp_path / "vendor").mkdir()+ (tmp_path / "vendor" / "dep.py").write_text("pass")+ (tmp_path / "dist").mkdir()+ (tmp_path / "dist" / "bundle.js").write_text("// built")+ (tmp_path / "src").mkdir()+ (tmp_path / "src" / "main.py").write_text("pass")+ traverser = FileTraverser(tmp_path, extra_exclude_patterns=["vendor/", "dist/"])+ paths = [f.path for f in traverser.traverse()]+ assert any("main.py" in p for p in paths)+ assert not any("vendor" in p for p in paths)+ assert not any("dist" in p for p in paths)++ def test_no_extra_patterns_behaves_normally(self, tmp_path: Path) -> None:+ (tmp_path / "src" / "app.py").mkdir(parents=True)+ # Ensure passing None or empty list doesn't break anything+ for patterns in (None, []):+ traverser = FileTraverser(tmp_path, extra_exclude_patterns=patterns)+ list(traverser.traverse()) # Should not raise+++# ---------------------------------------------------------------------------+# Per-directory .wikicodeIgnore+# ---------------------------------------------------------------------------+++class TestPerDirectoryWikicodeIgnore:+ def test_subdir_wikicodeIgnore_excludes_dir(self, tmp_path: Path) -> None:+ src = tmp_path / "src"+ src.mkdir()+ (src / ".wikicodeIgnore").write_text("generated/\n")+ (src / "generated").mkdir()+ (src / "generated" / "types.py").write_text("pass")+ (src / "real.py").write_text("pass")+ traverser = FileTraverser(tmp_path)+ paths = [f.path for f in traverser.traverse()]+ assert any("real.py" in p for p in paths)+ assert not any("types.py" in p for p in paths)++ def test_subdir_wikicodeIgnore_excludes_files(self, tmp_path: Path) -> None:+ src = tmp_path / "src"+ src.mkdir()+ (src / ".wikicodeIgnore").write_text("*.test.ts\n")+ (src / "app.ts").write_text("const x = 1;")+ (src / "app.test.ts").write_text("test('ok', () => {})")+ traverser = FileTraverser(tmp_path)+ paths = [f.path for f in traverser.traverse()]+ assert any("app.ts" in p and "test" not in p for p in paths)+ assert not any("app.test.ts" in p for p in paths)++ def test_root_wikicodeIgnore_still_respected(self, tmp_path: Path) -> None:+ (tmp_path / ".wikicodeIgnore").write_text("secret/\n")+ (tmp_path / "secret").mkdir()+ (tmp_path / "secret" / "key.py").write_text("KEY = 'x'")+ (tmp_path / "app.py").write_text("pass")+ traverser = FileTraverser(tmp_path)+ paths = [f.path for f in traverser.traverse()]+ assert any("app.py" in p for p in paths)+ assert not any("secret" in p for p in paths)++ def test_subdir_wikicodeIgnore_does_not_affect_sibling_dirs(self, tmp_path: Path) -> None:+ api = tmp_path / "api"+ api.mkdir()+ (api / ".wikicodeIgnore").write_text("internal/\n")+ (api / "internal").mkdir()+ (api / "internal" / "secret.py").write_text("pass")+ (api / "public.py").write_text("pass")+ other = tmp_path / "other"+ other.mkdir()+ (other / "internal").mkdir()+ (other / "internal" / "visible.py").write_text("pass")+ traverser = FileTraverser(tmp_path)+ paths = [f.path for f in traverser.traverse()]+ # api/internal should be excluded+ assert not any("api/internal" in p for p in paths)+ # other/internal should NOT be excluded (different parent's ignore)+ assert any("visible.py" in p for p in paths)+++# ---------------------------------------------------------------------------+# Monorepo detection+# ---------------------------------------------------------------------------+++class TestMonorepoDetection:+ def test_detects_monorepo(self, tmp_path: Path) -> None:+ # Create two packages with manifests+ pkg_a = tmp_path / "packages" / "core"+ pkg_a.mkdir(parents=True)+ (pkg_a / "pyproject.toml").write_text("[project]\nname='core'")+ (pkg_a / "main.py").write_text("pass")++ pkg_b = tmp_path / "packages" / "cli"+ pkg_b.mkdir(parents=True)+ (pkg_b / "pyproject.toml").write_text("[project]\nname='cli'")+ (pkg_b / "main.py").write_text("pass")++ traverser = FileTraverser(tmp_path)+ structure = traverser.get_repo_structure()+ assert structure.is_monorepo is True+ pkg_names = [p.name for p in structure.packages]+ assert "core" in pkg_names+ assert "cli" in pkg_names++ def test_single_package_not_monorepo(self, tmp_path: Path) -> None:+ (tmp_path / "pyproject.toml").write_text("[project]\nname='myapp'")+ (tmp_path / "app.py").write_text("pass")+ traverser = FileTraverser(tmp_path)+ structure = traverser.get_repo_structure()+ # Root manifest doesn't count — only manifests at depth 1++ assert structure.is_monorepo is False++ def test_language_distribution(self, tmp_path: Path) -> None:+ (tmp_path / "a.py").write_text("pass")+ (tmp_path / "b.py").write_text("pass")+ (tmp_path / "c.ts").write_text("const x = 1;")+ traverser = FileTraverser(tmp_path)+ structure = traverser.get_repo_structure()+ assert "python" in structure.root_language_distribution+ assert "typescript" in structure.root_language_distribution+ assert structure.root_language_distribution["python"] > structure.root_language_distribution["typescript"]diff --git a/tests/unit/persistence/__init__.py b/tests/unit/persistence/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/unit/persistence/conftest.py b/tests/unit/persistence/conftest.pynew file mode 100644index 000000000..9bd510ac9--- /dev/null+++ b/tests/unit/persistence/conftest.py@@ -0,0 +1,59 @@+"""Shared fixtures for persistence unit tests.++The async_engine fixture creates an in-memory SQLite database with StaticPool+so all connections within a test share the same in-memory database instance.+This is mandatory — without StaticPool each connection opens a fresh :memory: DB.+"""++from __future__ import annotations++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine+from sqlalchemy.pool import StaticPool++from wikicode.core.persistence.database import init_db+from wikicode.core.persistence.embedder import MockEmbedder+from wikicode.core.persistence.vector_store import InMemoryVectorStore+++async def async_engine():+ """In-memory SQLite engine with all tables and FTS5 index created."""+ engine = create_async_engine(+ "sqlite+aiosqlite:///:memory:",+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+ )+ await init_db(engine)+ yield engine+ await engine.dispose()+++async def async_session(async_engine):+ """Session bound to the in-memory engine. Does NOT auto-commit."""+ factory = async_sessionmaker(async_engine, expire_on_commit=False, class_=AsyncSession)+ async with factory() as session:+ yield session+++async def session_factory(async_engine):+ """Return the async_sessionmaker itself (for tests that need it)."""+ return async_sessionmaker(async_engine, expire_on_commit=False, class_=AsyncSession)+++def mock_embedder():+ return MockEmbedder()+++def in_memory_vector_store(mock_embedder):+ return InMemoryVectorStore(embedder=mock_embedder)+++# Re-export helpers so test files can import from either location+from tests.unit.persistence.helpers import insert_repo, make_page_kwargs, make_repo_kwargs++__all__ = ["insert_repo", "make_page_kwargs", "make_repo_kwargs"]diff --git a/tests/unit/persistence/helpers.py b/tests/unit/persistence/helpers.pynew file mode 100644index 000000000..2f385fb52--- /dev/null+++ b/tests/unit/persistence/helpers.py@@ -0,0 +1,43 @@+"""Shared helper functions for persistence unit tests.++These are module-level functions (not fixtures) so they can be imported+from any test file without conftest import restrictions.+"""++from __future__ import annotations++from wikicode.core.persistence.models import Repository+++def make_repo_kwargs(**overrides) -> dict:+ return {+ "name": "test-repo",+ "local_path": "/tmp/test-repo",+ "url": "https://github.com/example/test-repo",+ **overrides,+ }+++def make_page_kwargs(repo_id: str, **overrides) -> dict:+ return {+ "page_id": "file_page:src/main.py",+ "repository_id": repo_id,+ "page_type": "file_page",+ "title": "main.py",+ "content": "# Main module\n\nEntry point for the application.",+ "target_path": "src/main.py",+ "source_hash": "abc123",+ "model_name": "mock",+ "provider_name": "mock",+ "input_tokens": 100,+ "output_tokens": 50,+ **overrides,+ }+++async def insert_repo(session, **overrides) -> Repository:+ from wikicode.core.persistence.crud import upsert_repository++ repo = await upsert_repository(session, **make_repo_kwargs(**overrides))+ await session.commit()+ return repodiff --git a/tests/unit/persistence/test_crud.py b/tests/unit/persistence/test_crud.pynew file mode 100644index 000000000..37cf3959c--- /dev/null+++ b/tests/unit/persistence/test_crud.py@@ -0,0 +1,464 @@+"""Unit tests for the async CRUD layer.++All tests use an in-memory SQLite database. The async_session fixture+yields an uncommitted session; tests must call await session.commit() when+they want to verify that changes persist across a query boundary.+"""++from __future__ import annotations++import pytest++from wikicode.core.persistence.crud import (+ batch_upsert_graph_edges,+ batch_upsert_graph_nodes,+ batch_upsert_symbols,+ get_generation_job,+ get_page,+ get_page_versions,+ get_repository,+ get_repository_by_path,+ get_stale_pages,+ list_pages,+ mark_webhook_processed,+ store_webhook_event,+ update_job_status,+ upsert_generation_job,+ upsert_page,+ upsert_repository,+)+from tests.unit.persistence.helpers import insert_repo, make_page_kwargs+++# ---------------------------------------------------------------------------+# Repository CRUD+# ---------------------------------------------------------------------------+++async def test_upsert_repository_creates_new(async_session):+ repo = await upsert_repository(async_session, name="demo", local_path="/tmp/demo")+ await async_session.commit()+ assert repo.id is not None+ assert repo.name == "demo"+ assert repo.local_path == "/tmp/demo"+++async def test_upsert_repository_updates_existing(async_session):+ repo = await upsert_repository(async_session, name="v1", local_path="/tmp/r")+ await async_session.commit()++ repo2 = await upsert_repository(async_session, name="v2", local_path="/tmp/r")+ await async_session.commit()++ assert repo.id == repo2.id+ assert repo2.name == "v2"+++async def test_get_repository_returns_none_for_missing(async_session):+ result = await get_repository(async_session, "nonexistent")+ assert result is None+++async def test_get_repository_by_path_returns_none_for_missing(async_session):+ result = await get_repository_by_path(async_session, "/not/there")+ assert result is None+++async def test_get_repository_returns_inserted(async_session):+ repo = await insert_repo(async_session, name="find-me", local_path="/tmp/find-me")+ found = await get_repository(async_session, repo.id)+ assert found is not None+ assert found.id == repo.id+++# ---------------------------------------------------------------------------+# GenerationJob CRUD+# ---------------------------------------------------------------------------+++async def test_upsert_generation_job_creates(async_session):+ repo = await insert_repo(async_session)+ job = await upsert_generation_job(+ async_session,+ repository_id=repo.id,+ provider_name="mock",+ model_name="mock-v1",+ total_pages=10,+ )+ await async_session.commit()+ assert job.status == "pending"+ assert job.total_pages == 10+ assert job.started_at is None+++async def test_update_job_status_to_running(async_session):+ repo = await insert_repo(async_session)+ job = await upsert_generation_job(async_session, repository_id=repo.id)+ await async_session.commit()++ updated = await update_job_status(async_session, job.id, "running")+ await async_session.commit()++ assert updated.status == "running"+ assert updated.started_at is not None+++async def test_update_job_status_to_completed(async_session):+ repo = await insert_repo(async_session)+ job = await upsert_generation_job(async_session, repository_id=repo.id)+ await async_session.commit()++ updated = await update_job_status(+ async_session, job.id, "completed", completed_pages=5+ )+ await async_session.commit()++ assert updated.status == "completed"+ assert updated.finished_at is not None+ assert updated.completed_pages == 5+++async def test_update_job_status_invalid_raises(async_session):+ repo = await insert_repo(async_session)+ job = await upsert_generation_job(async_session, repository_id=repo.id)+ await async_session.commit()++ with pytest.raises(ValueError, match="Unknown job status"):+ await update_job_status(async_session, job.id, "exploded")+++async def test_update_job_status_missing_job_raises(async_session):+ with pytest.raises(LookupError):+ await update_job_status(async_session, "does-not-exist", "running")+++async def test_get_generation_job_returns_none_for_missing(async_session):+ result = await get_generation_job(async_session, "missing")+ assert result is None+++# ---------------------------------------------------------------------------+# Page CRUD (versioning)+# ---------------------------------------------------------------------------+++async def test_upsert_page_creates_version_1(async_session):+ repo = await insert_repo(async_session)+ page = await upsert_page(async_session, **make_page_kwargs(repo.id))+ await async_session.commit()++ assert page.version == 1+ assert page.id == "file_page:src/main.py"+++async def test_upsert_page_creates_version_on_second_upsert(async_session):+ repo = await insert_repo(async_session)+ kwargs = make_page_kwargs(repo.id)+ await upsert_page(async_session, **kwargs)+ await async_session.commit()++ # Second upsert with different content+ kwargs2 = dict(kwargs, content="# Updated content", source_hash="def456")+ await upsert_page(async_session, **kwargs2)+ await async_session.commit()++ versions = await get_page_versions(async_session, "file_page:src/main.py")+ assert len(versions) == 1+ assert versions[0].version == 1+ assert versions[0].content == "# Main module\n\nEntry point for the application."+++async def test_upsert_page_increments_version_field(async_session):+ repo = await insert_repo(async_session)+ kwargs = make_page_kwargs(repo.id)+ await upsert_page(async_session, **kwargs)+ await async_session.commit()++ await upsert_page(async_session, **dict(kwargs, source_hash="v2"))+ await async_session.commit()++ page = await get_page(async_session, "file_page:src/main.py")+ assert page is not None+ assert page.version == 2+++async def test_upsert_page_preserves_created_at(async_session):+ from datetime import datetime, timezone++ repo = await insert_repo(async_session)+ original_time = datetime(2025, 1, 1, tzinfo=timezone.utc)+ kwargs = make_page_kwargs(repo.id, created_at=original_time)+ await upsert_page(async_session, **kwargs)+ await async_session.commit()++ await upsert_page(async_session, **dict(kwargs, source_hash="v2"))+ await async_session.commit()++ page = await get_page(async_session, "file_page:src/main.py")+ assert page is not None+ # created_at must not change on update.+ # SQLite may strip timezone info on round-trip, so compare naive UTC.+ stored_naive = page.created_at.replace(tzinfo=None) if page.created_at.tzinfo else page.created_at+ original_naive = original_time.replace(tzinfo=None)+ assert stored_naive == original_naive+++async def test_get_page_returns_none_for_missing(async_session):+ assert await get_page(async_session, "missing:page") is None+++async def test_list_pages_returns_all_for_repo(async_session):+ repo = await insert_repo(async_session)+ await upsert_page(async_session, **make_page_kwargs(repo.id, page_id="file_page:a.py", target_path="a.py"))+ await upsert_page(async_session, **make_page_kwargs(repo.id, page_id="file_page:b.py", target_path="b.py"))+ await async_session.commit()++ pages = await list_pages(async_session, repo.id)+ assert len(pages) == 2+++async def test_list_pages_filters_by_page_type(async_session):+ repo = await insert_repo(async_session)+ await upsert_page(async_session, **make_page_kwargs(repo.id, page_id="file_page:a.py", target_path="a.py"))+ await upsert_page(+ async_session,+ **make_page_kwargs(+ repo.id,+ page_id="repo_overview:.",+ target_path=".",+ page_type="repo_overview",+ ),+ )+ await async_session.commit()++ file_pages = await list_pages(async_session, repo.id, page_type="file_page")+ assert len(file_pages) == 1+ assert file_pages[0].page_type == "file_page"+++async def test_list_pages_pagination(async_session):+ repo = await insert_repo(async_session)+ for i in range(5):+ await upsert_page(+ async_session,+ **make_page_kwargs(+ repo.id,+ page_id=f"file_page:src/{i}.py",+ target_path=f"src/{i}.py",+ ),+ )+ await async_session.commit()++ first_two = await list_pages(async_session, repo.id, limit=2, offset=0)+ next_two = await list_pages(async_session, repo.id, limit=2, offset=2)+ assert len(first_two) == 2+ assert len(next_two) == 2+ # No overlap+ ids_first = {p.id for p in first_two}+ ids_next = {p.id for p in next_two}+ assert ids_first.isdisjoint(ids_next)+++async def test_get_page_versions_returns_ordered_desc(async_session):+ repo = await insert_repo(async_session)+ kwargs = make_page_kwargs(repo.id)+ await upsert_page(async_session, **kwargs)+ await async_session.commit()+ await upsert_page(async_session, **dict(kwargs, source_hash="v2"))+ await async_session.commit()+ await upsert_page(async_session, **dict(kwargs, source_hash="v3"))+ await async_session.commit()++ versions = await get_page_versions(async_session, kwargs["page_id"])+ assert len(versions) == 2+ assert versions[0].version > versions[1].version # descending+++async def test_get_stale_pages_returns_only_stale(async_session):+ repo = await insert_repo(async_session)+ await upsert_page(+ async_session,+ **make_page_kwargs(repo.id, page_id="file_page:fresh.py", target_path="fresh.py"),+ )+ await upsert_page(+ async_session,+ **make_page_kwargs(+ repo.id,+ page_id="file_page:stale.py",+ target_path="stale.py",+ freshness_status="stale",+ ),+ )+ await upsert_page(+ async_session,+ **make_page_kwargs(+ repo.id,+ page_id="file_page:expired.py",+ target_path="expired.py",+ freshness_status="expired",+ ),+ )+ await async_session.commit()++ stale = await get_stale_pages(async_session, repo.id)+ assert len(stale) == 2+ statuses = {p.freshness_status for p in stale}+ assert statuses == {"stale", "expired"}+++# ---------------------------------------------------------------------------+# Graph CRUD (batch)+# ---------------------------------------------------------------------------+++async def test_batch_upsert_graph_nodes_inserts(async_session):+ from sqlalchemy import select+ from wikicode.core.persistence.models import GraphNode++ repo = await insert_repo(async_session)+ nodes = [+ {"node_id": "src/a.py", "language": "python", "pagerank": 0.5},+ {"node_id": "src/b.py", "language": "python", "pagerank": 0.3},+ ]+ await batch_upsert_graph_nodes(async_session, repo.id, nodes)+ await async_session.commit()++ result = await async_session.execute(+ select(GraphNode).where(GraphNode.repository_id == repo.id)+ )+ saved = result.scalars().all()+ assert len(saved) == 2+++async def test_batch_upsert_graph_nodes_updates_existing(async_session):+ from sqlalchemy import select+ from wikicode.core.persistence.models import GraphNode++ repo = await insert_repo(async_session)+ await batch_upsert_graph_nodes(+ async_session, repo.id, [{"node_id": "src/a.py", "pagerank": 0.1}]+ )+ await async_session.commit()++ await batch_upsert_graph_nodes(+ async_session, repo.id, [{"node_id": "src/a.py", "pagerank": 0.9}]+ )+ await async_session.commit()++ result = await async_session.execute(+ select(GraphNode).where(GraphNode.repository_id == repo.id)+ )+ saved = result.scalars().all()+ assert len(saved) == 1+ assert saved[0].pagerank == pytest.approx(0.9)+++async def test_batch_upsert_graph_edges_inserts(async_session):+ from sqlalchemy import select+ from wikicode.core.persistence.models import GraphEdge++ repo = await insert_repo(async_session)+ edges = [+ {"source_node_id": "a.py", "target_node_id": "b.py"},+ {"source_node_id": "b.py", "target_node_id": "c.py"},+ ]+ await batch_upsert_graph_edges(async_session, repo.id, edges)+ await async_session.commit()++ result = await async_session.execute(+ select(GraphEdge).where(GraphEdge.repository_id == repo.id)+ )+ saved = result.scalars().all()+ assert len(saved) == 2+++# ---------------------------------------------------------------------------+# Symbol CRUD (batch)+# ---------------------------------------------------------------------------+++async def test_batch_upsert_symbols_inserts(async_session):+ from dataclasses import dataclass+ from sqlalchemy import select+ from wikicode.core.persistence.models import WikiSymbol++ @dataclass+ class FakeSym:+ name: str+ kind: str = "function"+ file_path: str = "src/a.py"+ qualified_name: str = ""+ signature: str = ""+ start_line: int = 1+ end_line: int = 5+ docstring: str | None = None+ visibility: str = "public"+ is_async: bool = False+ complexity_estimate: int = 0+ language: str = "python"+ parent_name: str | None = None++ @property+ def id(self):+ return f"{self.file_path}::{self.name}"++ repo = await insert_repo(async_session)+ syms = [FakeSym("foo"), FakeSym("bar")]+ await batch_upsert_symbols(async_session, repo.id, syms)+ await async_session.commit()++ result = await async_session.execute(+ select(WikiSymbol).where(WikiSymbol.repository_id == repo.id)+ )+ saved = result.scalars().all()+ assert len(saved) == 2+ names = {s.name for s in saved}+ assert names == {"foo", "bar"}+++# ---------------------------------------------------------------------------+# WebhookEvent CRUD+# ---------------------------------------------------------------------------+++async def test_store_webhook_event_creates(async_session):+ event = await store_webhook_event(+ async_session,+ provider="github",+ event_type="push",+ payload={"ref": "refs/heads/main"},+ )+ await async_session.commit()++ assert event.provider == "github"+ assert event.processed is False+ assert event.repository_id is None+++async def test_mark_webhook_processed(async_session):+ repo = await insert_repo(async_session)+ event = await store_webhook_event(+ async_session,+ provider="github",+ event_type="push",+ payload={},+ repository_id=repo.id,+ )+ await async_session.commit()++ await mark_webhook_processed(async_session, event.id)+ await async_session.commit()++ from wikicode.core.persistence.models import WebhookEvent+ from sqlalchemy import select++ result = await async_session.execute(+ select(WebhookEvent).where(WebhookEvent.id == event.id)+ )+ updated = result.scalar_one()+ assert updated.processed is True+++async def test_mark_webhook_processed_missing_raises(async_session):+ with pytest.raises(LookupError):+ await mark_webhook_processed(async_session, "ghost-id")diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.pynew file mode 100644index 000000000..b29a381c1--- /dev/null+++ b/tests/unit/persistence/test_models.py@@ -0,0 +1,305 @@+"""Unit tests for SQLAlchemy ORM models.++Tests cover model construction, default values, constraints, and field types.+No CRUD or database queries — just ORM-layer behaviour.+"""++from __future__ import annotations++from datetime import datetime, timezone++import pytest+from sqlalchemy.exc import IntegrityError++from wikicode.core.persistence.models import (+ Base,+ GenerationJob,+ GraphEdge,+ GraphNode,+ Page,+ PageVersion,+ Repository,+ WebhookEvent,+ WikiSymbol,+ _new_uuid,+ _now_utc,+)+++# ---------------------------------------------------------------------------+# Helper factories+# ---------------------------------------------------------------------------+++def _repo(**kwargs) -> Repository:+ return Repository(+ id=_new_uuid(),+ name=kwargs.get("name", "test-repo"),+ local_path=kwargs.get("local_path", "/tmp/test"),+ url=kwargs.get("url", ""),+ )+++def _now() -> datetime:+ return datetime.now(timezone.utc)+++# ---------------------------------------------------------------------------+# Repository+# ---------------------------------------------------------------------------+++def test_repository_has_expected_tablename():+ assert Repository.__tablename__ == "repositories"+++def test_repository_defaults():+ """SQLAlchemy INSERT-time defaults; verify the column metadata, not Python init."""+ col_defaults = {c.name: c.default for c in Repository.__table__.columns if c.default is not None}+ assert "default_branch" in col_defaults+ assert col_defaults["default_branch"].arg == "main"+ # head_commit is nullable+ assert Repository.__table__.c.head_commit.nullable is True+++def test_repository_id_is_string():+ repo = _repo()+ assert isinstance(repo.id, str)+ assert len(repo.id) == 32 # UUID hex+++# ---------------------------------------------------------------------------+# GenerationJob+# ---------------------------------------------------------------------------+++def test_generation_job_has_expected_tablename():+ assert GenerationJob.__tablename__ == "generation_jobs"+++def test_generation_job_defaults():+ """Verify column-level defaults (INSERT-time); not Python constructor defaults."""+ col_defaults = {c.name: c.default for c in GenerationJob.__table__.columns if c.default is not None}+ assert col_defaults["status"].arg == "pending"+ assert col_defaults["total_pages"].arg == 0+ assert col_defaults["completed_pages"].arg == 0+ assert col_defaults["failed_pages"].arg == 0+ # started_at / finished_at are nullable+ assert GenerationJob.__table__.c.started_at.nullable is True+ assert GenerationJob.__table__.c.finished_at.nullable is True+++# ---------------------------------------------------------------------------+# Page+# ---------------------------------------------------------------------------+++def test_page_has_expected_tablename():+ assert Page.__tablename__ == "wiki_pages"+++def test_page_id_format_accepted():+ """Page.id is the page_id string 'page_type:target_path'."""+ now = _now()+ page = Page(+ id="file_page:src/main.py",+ repository_id="repo1",+ page_type="file_page",+ title="main.py",+ content="content",+ target_path="src/main.py",+ source_hash="abc",+ model_name="mock",+ provider_name="mock",+ created_at=now,+ updated_at=now,+ )+ assert page.id == "file_page:src/main.py"+++def test_page_defaults():+ """Verify INSERT-time column defaults via table metadata."""+ col_defaults = {c.name: c.default for c in Page.__table__.columns if c.default is not None}+ assert col_defaults["version"].arg == 1+ assert col_defaults["confidence"].arg == 1.0+ assert col_defaults["freshness_status"].arg == "fresh"+ assert col_defaults["metadata_json"].arg == "{}"+ assert col_defaults["input_tokens"].arg == 0+ assert col_defaults["cached_tokens"].arg == 0+++def test_page_metadata_json_is_not_named_metadata():+ """metadata is a SQLAlchemy reserved name on Base; we use metadata_json."""+ page = Page.__table__.c+ col_names = {c.name for c in page}+ assert "metadata_json" in col_names+ assert "metadata" not in col_names+++# ---------------------------------------------------------------------------+# PageVersion+# ---------------------------------------------------------------------------+++def test_page_version_has_expected_tablename():+ assert PageVersion.__tablename__ == "wiki_page_versions"+++def test_page_version_fields():+ pv = PageVersion(+ id=_new_uuid(),+ page_id="file_page:src/a.py",+ repository_id="r1",+ version=1,+ page_type="file_page",+ title="a.py",+ content="old content",+ source_hash="old_hash",+ model_name="mock",+ provider_name="mock",+ )+ assert pv.version == 1+ # confidence has INSERT-time default 1.0; verify via column metadata+ col_defaults = {c.name: c.default for c in PageVersion.__table__.columns if c.default is not None}+ assert col_defaults["confidence"].arg == 1.0+++# ---------------------------------------------------------------------------+# GraphNode+# ---------------------------------------------------------------------------+++def test_graph_node_has_expected_tablename():+ assert GraphNode.__tablename__ == "graph_nodes"+++def test_graph_node_defaults():+ """Verify INSERT-time column defaults via table metadata."""+ col_defaults = {c.name: c.default for c in GraphNode.__table__.columns if c.default is not None}+ assert col_defaults["node_type"].arg == "file"+ assert col_defaults["pagerank"].arg == 0.0+ assert col_defaults["betweenness"].arg == 0.0+ assert col_defaults["community_id"].arg == 0+++def test_graph_node_unique_constraint_defined():+ """The UniqueConstraint on (repository_id, node_id) must exist."""+ constraint_names = {+ c.name+ for c in GraphNode.__table__.constraints+ if hasattr(c, "name")+ }+ assert "uq_graph_node" in constraint_names+++async def test_graph_node_unique_constraint_enforced(async_session):+ """Inserting two nodes with the same (repository_id, node_id) raises IntegrityError."""+ from wikicode.core.persistence.crud import upsert_repository++ repo = await upsert_repository(async_session, name="r", local_path="/tmp/uq-test")+ await async_session.commit()++ n1 = GraphNode(id=_new_uuid(), repository_id=repo.id, node_id="src/a.py")+ n2 = GraphNode(id=_new_uuid(), repository_id=repo.id, node_id="src/a.py")+ async_session.add(n1)+ await async_session.flush()++ async_session.add(n2)+ with pytest.raises(IntegrityError):+ await async_session.flush()+++# ---------------------------------------------------------------------------+# GraphEdge+# ---------------------------------------------------------------------------+++def test_graph_edge_has_expected_tablename():+ assert GraphEdge.__tablename__ == "graph_edges"+++def test_graph_edge_defaults():+ col_defaults = {c.name: c.default for c in GraphEdge.__table__.columns if c.default is not None}+ assert col_defaults["imported_names_json"].arg == "[]"+++# ---------------------------------------------------------------------------+# WebhookEvent+# ---------------------------------------------------------------------------+++def test_webhook_event_has_expected_tablename():+ assert WebhookEvent.__tablename__ == "webhook_events"+++def test_webhook_event_nullable_repository_id():+ """repository_id is nullable — webhook may arrive before repo is registered."""+ we = WebhookEvent(+ id=_new_uuid(),+ provider="github",+ event_type="push",+ )+ assert we.repository_id is None+++def test_webhook_event_defaults():+ col_defaults = {c.name: c.default for c in WebhookEvent.__table__.columns if c.default is not None}+ # processed defaults to False (stored as 0 in SQLite)+ assert col_defaults["processed"].arg == False # noqa: E712+ # job_id is nullable+ assert WebhookEvent.__table__.c.job_id.nullable is True+++# ---------------------------------------------------------------------------+# WikiSymbol+# ---------------------------------------------------------------------------+++def test_wiki_symbol_has_expected_tablename():+ assert WikiSymbol.__tablename__ == "wiki_symbols"+++def test_wiki_symbol_name_does_not_shadow_ingestion_symbol():+ """The ORM class is named WikiSymbol to avoid shadowing ingestion.models.Symbol."""+ assert WikiSymbol.__name__ == "WikiSymbol"+++def test_wiki_symbol_defaults():+ col_defaults = {c.name: c.default for c in WikiSymbol.__table__.columns if c.default is not None}+ assert col_defaults["visibility"].arg == "public"+ assert col_defaults["is_async"].arg == False # noqa: E712+ assert col_defaults["complexity_estimate"].arg == 0+ # docstring and parent_name are nullable+ assert WikiSymbol.__table__.c.docstring.nullable is True+ assert WikiSymbol.__table__.c.parent_name.nullable is True+++def test_wiki_symbol_unique_constraint_defined():+ constraint_names = {+ c.name+ for c in WikiSymbol.__table__.constraints+ if hasattr(c, "name")+ }+ assert "uq_wiki_symbol" in constraint_names+++# ---------------------------------------------------------------------------+# Base+# ---------------------------------------------------------------------------+++def test_base_includes_all_models():+ table_names = set(Base.metadata.tables.keys())+ expected = {+ "repositories",+ "generation_jobs",+ "wiki_pages",+ "wiki_page_versions",+ "graph_nodes",+ "graph_edges",+ "webhook_events",+ "wiki_symbols",+ "git_metadata",+ "dead_code_findings",+ }+ assert expected == table_namesdiff --git a/tests/unit/persistence/test_search.py b/tests/unit/persistence/test_search.pynew file mode 100644index 000000000..ad4484452--- /dev/null+++ b/tests/unit/persistence/test_search.py@@ -0,0 +1,147 @@+"""Unit tests for FullTextSearch.++All tests use an in-memory SQLite engine with the FTS5 virtual table+created by init_db().+"""++from __future__ import annotations++import pytest++from wikicode.core.persistence.search import FullTextSearch, SearchResult+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++async def fts(async_engine):+ """FullTextSearch instance tied to the in-memory engine."""+ fs = FullTextSearch(async_engine)+ await fs.ensure_index()+ return fs+++# ---------------------------------------------------------------------------+# FTS5 table creation+# ---------------------------------------------------------------------------+++async def test_fts5_table_created_after_ensure_index(async_engine):+ """The page_fts virtual table must exist after ensure_index()."""+ from sqlalchemy.sql import text++ fts = FullTextSearch(async_engine)+ await fts.ensure_index()++ async with async_engine.connect() as conn:+ result = await conn.execute(+ text(+ "SELECT name FROM sqlite_master "+ "WHERE type='table' AND name='page_fts'"+ )+ )+ row = result.fetchone()+ assert row is not None, "page_fts virtual table was not created"+++async def test_ensure_index_is_idempotent(async_engine):+ """Calling ensure_index() twice must not raise."""+ fts = FullTextSearch(async_engine)+ await fts.ensure_index()+ await fts.ensure_index() # should not raise+++# ---------------------------------------------------------------------------+# Search behaviour+# ---------------------------------------------------------------------------+++async def test_full_text_search_exact_title_match(fts):+ await fts.index("p1", "Python Decorator Pattern", "This module explains decorators.")+ results = await fts.search("Decorator Pattern")+ assert len(results) >= 1+ assert results[0].page_id == "p1"+++async def test_full_text_search_content_body_match(fts):+ await fts.index("p2", "Graph Builder", "The GraphBuilder class builds dependency graphs.")+ results = await fts.search("dependency graphs")+ assert len(results) >= 1+ assert results[0].page_id == "p2"+++async def test_full_text_search_no_match_returns_empty(fts):+ await fts.index("p3", "File Traverser", "Handles gitignore-aware file traversal.")+ results = await fts.search("blockchain cryptocurrency")+ assert results == []+++async def test_full_text_search_limit_respected(fts):+ for i in range(5):+ await fts.index(f"page{i}", f"WikiCode Module {i}", "Module documentation content here.")+ results = await fts.search("WikiCode Module", limit=3)+ assert len(results) <= 3+++async def test_full_text_search_empty_query_returns_empty(fts):+ await fts.index("p", "Title", "Content")+ results = await fts.search("")+ assert results == []+++async def test_full_text_search_score_is_positive(fts):+ """FTS5 rank is negative; FullTextSearch must negate it for SearchResult.score."""+ await fts.index("p", "Python async await", "Coroutines and event loops explained.")+ results = await fts.search("Python async")+ assert len(results) >= 1+ assert results[0].score > 0.0+++async def test_full_text_search_snippet_truncated_to_200(fts):+ long_content = "word " * 200+ await fts.index("p", "Title", long_content)+ results = await fts.search("word")+ assert len(results) >= 1+ assert len(results[0].snippet) <= 200+++async def test_full_text_search_returns_search_result_type(fts):+ await fts.index("p", "Symbol Spotlight", "High-pagerank symbol documentation.")+ results = await fts.search("Symbol Spotlight")+ assert len(results) >= 1+ assert isinstance(results[0], SearchResult)+ assert results[0].search_type == "fulltext"+++async def test_full_text_search_index_update_reflects_new_content(fts):+ """Re-indexing a page with new content should make new terms searchable."""+ await fts.index("p1", "OldTitle", "nothing useful here")+ results_before = await fts.search("async decorators")+ count_before = len(results_before)++ await fts.index("p1", "NewTitle", "async decorators in Python are powerful")+ results_after = await fts.search("async decorators")+ assert len(results_after) > count_before+++async def test_full_text_search_delete_removes_from_index(fts):+ await fts.index("to-remove", "Removable Page", "removable unique xylophone content")+ results_before = await fts.search("xylophone")+ assert len(results_before) >= 1++ await fts.delete("to-remove")+ results_after = await fts.search("xylophone")+ assert results_after == []+++async def test_full_text_search_multiple_pages_relevance_ordered(fts):+ """Page with title match should rank higher than page with only content match."""+ await fts.index("exact", "Python Asyncio", "asyncio event loop management")+ await fts.index("content-only", "Event Loop Guide", "Python asyncio is great for concurrent tasks")+ results = await fts.search("Python Asyncio")+ # Both should appear; 'exact' should rank first (title match)+ assert len(results) >= 1+ assert results[0].page_id == "exact"diff --git a/tests/unit/persistence/test_vector_store.py b/tests/unit/persistence/test_vector_store.pynew file mode 100644index 000000000..e56bb179f--- /dev/null+++ b/tests/unit/persistence/test_vector_store.py@@ -0,0 +1,210 @@+"""Unit tests for Embedder and VectorStore.++Tests use MockEmbedder (8-dim, deterministic, zero deps) and+InMemoryVectorStore (cosine similarity, no external deps).+LanceDB-specific tests are skipped if lancedb is not installed.+"""++from __future__ import annotations++import math++import pytest++from wikicode.core.persistence.embedder import Embedder, MockEmbedder+from wikicode.core.persistence.vector_store import InMemoryVectorStore+++# ---------------------------------------------------------------------------+# MockEmbedder+# ---------------------------------------------------------------------------+++async def test_mock_embedder_returns_unit_vectors():+ emb = MockEmbedder()+ vecs = await emb.embed(["hello world", "goodbye moon"])+ for vec in vecs:+ norm = math.sqrt(sum(x * x for x in vec))+ assert abs(norm - 1.0) < 1e-6, f"Vector is not unit length: norm={norm}"+++async def test_mock_embedder_returns_correct_dimension():+ emb = MockEmbedder()+ vecs = await emb.embed(["test"])+ assert len(vecs[0]) == MockEmbedder.dimensions+++async def test_mock_embedder_is_deterministic():+ emb = MockEmbedder()+ v1 = (await emb.embed(["hello"]))[0]+ v2 = (await emb.embed(["hello"]))[0]+ assert v1 == v2+++async def test_mock_embedder_different_texts_different_vectors():+ emb = MockEmbedder()+ v1 = (await emb.embed(["hello"]))[0]+ v2 = (await emb.embed(["goodbye"]))[0]+ assert v1 != v2+++async def test_mock_embedder_batch_equals_individual():+ emb = MockEmbedder()+ texts = ["alpha", "beta", "gamma"]+ batch = await emb.embed(texts)+ for i, text in enumerate(texts):+ individual = (await emb.embed([text]))[0]+ assert batch[i] == individual+++async def test_mock_embedder_satisfies_protocol():+ emb = MockEmbedder()+ assert isinstance(emb, Embedder)+++# ---------------------------------------------------------------------------+# InMemoryVectorStore+# ---------------------------------------------------------------------------+++async def test_in_memory_store_empty_search_returns_empty(in_memory_vector_store):+ results = await in_memory_vector_store.search("anything", limit=5)+ assert results == []+++async def test_in_memory_store_upsert_and_search(in_memory_vector_store):+ await in_memory_vector_store.embed_and_upsert(+ "page1",+ "Python decorator pattern for caching",+ {"title": "Decorators", "page_type": "file_page", "target_path": "src/cache.py", "content": "Python decorator pattern for caching"},+ )+ results = await in_memory_vector_store.search("Python decorator caching")+ assert len(results) == 1+ assert results[0].page_id == "page1"+ assert results[0].title == "Decorators"+++async def test_in_memory_store_search_returns_closest(in_memory_vector_store):+ """Store two pages; query text similar to page1 should rank page1 first."""+ await in_memory_vector_store.embed_and_upsert(+ "p1",+ "Python decorator pattern",+ {"title": "p1", "page_type": "file_page", "target_path": "a.py", "content": "Python decorator pattern"},+ )+ await in_memory_vector_store.embed_and_upsert(+ "p2",+ "Rust ownership and borrowing",+ {"title": "p2", "page_type": "file_page", "target_path": "b.py", "content": "Rust ownership and borrowing"},+ )+ results = await in_memory_vector_store.search("Python decorator pattern", limit=2)+ assert results[0].page_id == "p1"+++async def test_in_memory_store_limit_respected(in_memory_vector_store):+ for i in range(10):+ await in_memory_vector_store.embed_and_upsert(+ f"page{i}",+ f"content number {i}",+ {"title": f"Page {i}", "page_type": "file_page", "target_path": f"f{i}.py", "content": f"content number {i}"},+ )+ results = await in_memory_vector_store.search("content", limit=3)+ assert len(results) == 3+++async def test_in_memory_store_delete_removes_entry(in_memory_vector_store):+ await in_memory_vector_store.embed_and_upsert(+ "to-delete",+ "transient content",+ {"title": "tmp", "page_type": "file_page", "target_path": "t.py", "content": "transient content"},+ )+ assert len(in_memory_vector_store) == 1++ await in_memory_vector_store.delete("to-delete")+ assert len(in_memory_vector_store) == 0++ results = await in_memory_vector_store.search("transient")+ assert results == []+++async def test_in_memory_store_delete_nonexistent_is_safe(in_memory_vector_store):+ """Deleting a page that doesn't exist should not raise."""+ await in_memory_vector_store.delete("ghost-page")+++async def test_in_memory_store_upsert_overwrites(in_memory_vector_store):+ meta = {"title": "v1", "page_type": "file_page", "target_path": "a.py", "content": "version one"}+ await in_memory_vector_store.embed_and_upsert("p", "version one", meta)+ assert len(in_memory_vector_store) == 1++ meta2 = {"title": "v2", "page_type": "file_page", "target_path": "a.py", "content": "version two"}+ await in_memory_vector_store.embed_and_upsert("p", "version two", meta2)+ assert len(in_memory_vector_store) == 1 # still one entry++ results = await in_memory_vector_store.search("version two")+ assert results[0].title == "v2"+++async def test_in_memory_store_score_between_zero_and_one(in_memory_vector_store):+ """Cosine similarity is in [-1, 1]; for unit vectors all positive texts give ≥ 0."""+ await in_memory_vector_store.embed_and_upsert(+ "p1",+ "machine learning algorithms",+ {"title": "ML", "page_type": "file_page", "target_path": "ml.py", "content": "machine learning algorithms"},+ )+ results = await in_memory_vector_store.search("machine learning")+ assert 0.0 <= results[0].score <= 1.0+++async def test_in_memory_store_snippet_truncated(in_memory_vector_store):+ long_content = "x" * 500+ await in_memory_vector_store.embed_and_upsert(+ "p",+ long_content,+ {"title": "t", "page_type": "file_page", "target_path": "f.py", "content": long_content},+ )+ results = await in_memory_vector_store.search(long_content[:10])+ assert len(results[0].snippet) <= 200+++async def test_in_memory_store_search_type_is_vector(in_memory_vector_store):+ await in_memory_vector_store.embed_and_upsert(+ "p",+ "text",+ {"title": "t", "page_type": "file_page", "target_path": "f.py", "content": "text"},+ )+ results = await in_memory_vector_store.search("text")+ assert results[0].search_type == "vector"+++async def test_in_memory_store_close_clears(in_memory_vector_store):+ await in_memory_vector_store.embed_and_upsert(+ "p",+ "text",+ {"title": "t", "page_type": "file_page", "target_path": "f.py", "content": "text"},+ )+ await in_memory_vector_store.close()+ assert len(in_memory_vector_store) == 0+++# ---------------------------------------------------------------------------+# LanceDB (optional — skipped if not installed)+# ---------------------------------------------------------------------------+++async def test_lancedb_vector_store_basic(tmp_path, mock_embedder):+ lancedb = pytest.importorskip("lancedb") # noqa: F841+ from wikicode.core.persistence.vector_store import LanceDBVectorStore++ store = LanceDBVectorStore(str(tmp_path / "lance"), mock_embedder)+ try:+ await store.embed_and_upsert(+ "p1",+ "Python async generators",+ {"title": "Async", "page_type": "file_page", "target_path": "a.py"},+ )+ results = await store.search("async generators", limit=5)+ assert len(results) >= 1+ assert results[0].page_id == "p1"+ finally:+ await store.close()diff --git a/tests/unit/server/__init__.py b/tests/unit/server/__init__.pynew file mode 100644index 000000000..d9a6a5f94--- /dev/null+++ b/tests/unit/server/__init__.py@@ -0,0 +1 @@+"""Unit tests for the WikiCode server package."""diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.pynew file mode 100644index 000000000..03960ba42--- /dev/null+++ b/tests/unit/server/conftest.py@@ -0,0 +1,145 @@+"""Shared fixtures for server unit tests.++Creates a test FastAPI app with an in-memory SQLite database and+provides an httpx AsyncClient for making requests.+"""++from __future__ import annotations++import json++import pytest+from httpx import ASGITransport, AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine+from sqlalchemy.pool import StaticPool++from wikicode.core.persistence.database import init_db+from wikicode.core.persistence.embedder import MockEmbedder+from wikicode.core.persistence.search import FullTextSearch+from wikicode.core.persistence.vector_store import InMemoryVectorStore+++def _create_test_app():+ """Create a FastAPI app without the lifespan (we manage state manually)."""+ from contextlib import asynccontextmanager++ from fastapi import FastAPI+ from fastapi.middleware.cors import CORSMiddleware+ from fastapi.responses import JSONResponse++ from wikicode.server.routers import (+ dead_code,+ git,+ graph,+ health,+ jobs,+ pages,+ repos,+ search,+ symbols,+ webhooks,+ )++ @asynccontextmanager+ async def noop_lifespan(app: FastAPI):+ yield++ app = FastAPI(title="WikiCode API Test", lifespan=noop_lifespan)+ app.add_middleware(+ CORSMiddleware,+ allow_origins=["*"],+ allow_methods=["*"],+ allow_headers=["*"],+ )++ @app.exception_handler(LookupError)+ async def not_found_handler(request, exc):+ return JSONResponse(status_code=404, content={"detail": str(exc)})++ @app.exception_handler(ValueError)+ async def bad_request_handler(request, exc):+ return JSONResponse(status_code=400, content={"detail": str(exc)})++ app.include_router(health.router)+ app.include_router(repos.router)+ app.include_router(pages.router)+ app.include_router(search.router)+ app.include_router(jobs.router)+ app.include_router(symbols.router)+ app.include_router(graph.router)+ app.include_router(webhooks.router)+ app.include_router(git.router)+ app.include_router(dead_code.router)++ return app+++async def test_engine():+ """In-memory SQLite engine with all tables created."""+ engine = create_async_engine(+ "sqlite+aiosqlite:///:memory:",+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+ )+ await init_db(engine)+ yield engine+ await engine.dispose()+++async def session_factory(test_engine):+ """Async session factory for the test engine."""+ return async_sessionmaker(+ test_engine, expire_on_commit=False, class_=AsyncSession+ )+++async def app(test_engine, session_factory):+ """Test FastAPI app with all state configured."""+ test_app = _create_test_app()++ fts = FullTextSearch(test_engine)+ await fts.ensure_index()++ embedder = MockEmbedder()+ vector_store = InMemoryVectorStore(embedder=embedder)++ test_app.state.engine = test_engine+ test_app.state.session_factory = session_factory+ test_app.state.fts = fts+ test_app.state.vector_store = vector_store++ yield test_app+ await vector_store.close()+++async def client(app) -> AsyncClient:+ """httpx AsyncClient for making requests to the test app."""+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ yield c+++async def session(session_factory) -> AsyncSession:+ """A raw DB session for test setup (inserting test data directly)."""+ async with session_factory() as s:+ yield s+ await s.commit()+++async def create_test_repo(client: AsyncClient) -> dict:+ """Helper: create a test repository via the API and return its response."""+ resp = await client.post(+ "/api/repos",+ json={+ "name": "test-repo",+ "local_path": "/tmp/test-repo",+ "url": "https://github.com/example/test-repo",+ },+ )+ assert resp.status_code == 201+ return resp.json()diff --git a/tests/unit/server/test_auth.py b/tests/unit/server/test_auth.pynew file mode 100644index 000000000..e65796780--- /dev/null+++ b/tests/unit/server/test_auth.py@@ -0,0 +1,77 @@+"""Tests for API key authentication."""++from __future__ import annotations++import pytest+from httpx import AsyncClient+++async def test_no_auth_configured_allows_access(client: AsyncClient) -> None:+ """When WIKICODE_API_KEY is not set, all endpoints are open."""+ resp = await client.get("/api/repos")+ assert resp.status_code == 200+++async def test_auth_rejects_missing_key(client: AsyncClient) -> None:+ """When API key is configured, requests without it are rejected."""+ import wikicode.server.deps as deps_mod++ original = deps_mod._API_KEY+ deps_mod._API_KEY = "test-secret-key"+ try:+ resp = await client.get("/api/repos")+ assert resp.status_code == 401+ assert "Missing API key" in resp.json()["detail"]+ finally:+ deps_mod._API_KEY = original+++async def test_auth_rejects_wrong_key(client: AsyncClient) -> None:+ """When API key is configured, a wrong key is rejected."""+ import wikicode.server.deps as deps_mod++ original = deps_mod._API_KEY+ deps_mod._API_KEY = "test-secret-key"+ try:+ resp = await client.get(+ "/api/repos",+ headers={"Authorization": "Bearer wrong-key"},+ )+ assert resp.status_code == 401+ assert "Invalid API key" in resp.json()["detail"]+ finally:+ deps_mod._API_KEY = original+++async def test_auth_accepts_correct_key(client: AsyncClient) -> None:+ """When API key is configured, the correct key grants access."""+ import wikicode.server.deps as deps_mod++ original = deps_mod._API_KEY+ deps_mod._API_KEY = "test-secret-key"+ try:+ resp = await client.get(+ "/api/repos",+ headers={"Authorization": "Bearer test-secret-key"},+ )+ assert resp.status_code == 200+ finally:+ deps_mod._API_KEY = original+++async def test_health_bypasses_auth(client: AsyncClient) -> None:+ """The /health endpoint should always be accessible, even with auth enabled."""+ import wikicode.server.deps as deps_mod++ original = deps_mod._API_KEY+ deps_mod._API_KEY = "test-secret-key"+ try:+ resp = await client.get("/health")+ assert resp.status_code == 200+ finally:+ deps_mod._API_KEY = originaldiff --git a/tests/unit/server/test_dead_code.py b/tests/unit/server/test_dead_code.pynew file mode 100644index 000000000..6ceaadb43--- /dev/null+++ b/tests/unit/server/test_dead_code.py@@ -0,0 +1,157 @@+"""Tests for dead code endpoints."""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from wikicode.core.persistence import crud+from wikicode.core.persistence.database import get_session++from tests.unit.server.conftest import create_test_repo+++async def _insert_dead_code(session_factory, repo_id: str) -> str:+ """Insert test dead code findings and return a finding ID."""+ async with get_session(session_factory) as session:+ await crud.save_dead_code_findings(+ session,+ repo_id,+ [+ {+ "kind": "unreachable_file",+ "file_path": "src/dead_module.py",+ "symbol_name": None,+ "symbol_kind": None,+ "confidence": 0.9,+ "reason": "No imports found",+ "lines": 50,+ "safe_to_delete": True,+ "primary_owner": "Alice",+ "age_days": 180,+ },+ {+ "kind": "unused_export",+ "file_path": "src/utils.py",+ "symbol_name": "old_helper",+ "symbol_kind": "function",+ "confidence": 0.5,+ "reason": "No callers",+ "lines": 10,+ "safe_to_delete": False,+ "primary_owner": "Bob",+ "age_days": 90,+ },+ ],+ )++ # Fetch findings to get the ID+ async with get_session(session_factory) as session:+ findings = await crud.get_dead_code_findings(session, repo_id)+ return findings[0].id+++async def test_list_dead_code_empty(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.get(f"/api/repos/{repo['id']}/dead-code")+ assert resp.status_code == 200+ assert resp.json() == []+++async def test_list_dead_code_with_data(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_dead_code(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/repos/{repo['id']}/dead-code")+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) == 2+++async def test_list_dead_code_filter_by_kind(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_dead_code(app.state.session_factory, repo["id"])++ resp = await client.get(+ f"/api/repos/{repo['id']}/dead-code",+ params={"kind": "unreachable_file"},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) == 1+ assert data[0]["kind"] == "unreachable_file"+++async def test_list_dead_code_safe_only(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_dead_code(app.state.session_factory, repo["id"])++ resp = await client.get(+ f"/api/repos/{repo['id']}/dead-code",+ params={"safe_only": True},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) == 1+ assert data[0]["safe_to_delete"] is True+++async def test_dead_code_summary(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_dead_code(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/repos/{repo['id']}/dead-code/summary")+ assert resp.status_code == 200+ data = resp.json()+ assert data["total_findings"] == 2+ assert data["deletable_lines"] == 50 # Only the safe-to-delete finding+ assert "unreachable_file" in data["by_kind"]+++async def test_analyze_dead_code(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.post(f"/api/repos/{repo['id']}/dead-code/analyze")+ assert resp.status_code == 202+ assert resp.json()["status"] == "analyzing"+++async def test_resolve_finding(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ finding_id = await _insert_dead_code(app.state.session_factory, repo["id"])++ resp = await client.patch(+ f"/api/dead-code/{finding_id}",+ json={"status": "acknowledged", "note": "Will fix later"},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert data["status"] == "acknowledged"+ assert data["note"] == "Will fix later"+++async def test_resolve_finding_not_found(client: AsyncClient) -> None:+ resp = await client.patch(+ "/api/dead-code/nonexistent",+ json={"status": "resolved"},+ )+ assert resp.status_code == 404+++async def test_resolve_finding_invalid_status(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ finding_id = await _insert_dead_code(app.state.session_factory, repo["id"])++ resp = await client.patch(+ f"/api/dead-code/{finding_id}",+ json={"status": "invalid_status"},+ )+ assert resp.status_code == 400diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.pynew file mode 100644index 000000000..cf8a5faa6--- /dev/null+++ b/tests/unit/server/test_git.py@@ -0,0 +1,138 @@+"""Tests for git intelligence endpoints."""++from __future__ import annotations++import json++import pytest+from httpx import AsyncClient++from wikicode.core.persistence import crud+from wikicode.core.persistence.database import get_session++from tests.unit.server.conftest import create_test_repo+++async def _insert_git_metadata(session_factory, repo_id: str) -> None:+ """Insert test git metadata."""+ async with get_session(session_factory) as session:+ await crud.upsert_git_metadata(+ session,+ repository_id=repo_id,+ file_path="src/main.py",+ commit_count_total=50,+ commit_count_90d=10,+ commit_count_30d=3,+ primary_owner_name="Alice",+ primary_owner_email="[email protected]",+ primary_owner_commit_pct=0.6,+ top_authors_json=json.dumps([{"name": "Alice", "commits": 30}]),+ significant_commits_json=json.dumps([{"sha": "abc", "message": "init"}]),+ co_change_partners_json=json.dumps(+ [{"file_path": "src/utils.py", "count": 5}]+ ),+ is_hotspot=True,+ is_stable=False,+ churn_percentile=0.85,+ age_days=365,+ )+ await crud.upsert_git_metadata(+ session,+ repository_id=repo_id,+ file_path="src/utils.py",+ commit_count_total=20,+ commit_count_90d=0,+ commit_count_30d=0,+ primary_owner_name="Bob",+ primary_owner_email="[email protected]",+ primary_owner_commit_pct=0.9,+ is_hotspot=False,+ is_stable=True,+ churn_percentile=0.2,+ age_days=200,+ )+++async def test_get_git_metadata(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_git_metadata(app.state.session_factory, repo["id"])++ resp = await client.get(+ f"/api/repos/{repo['id']}/git-metadata",+ params={"file_path": "src/main.py"},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert data["file_path"] == "src/main.py"+ assert data["commit_count_total"] == 50+ assert data["is_hotspot"] is True+ assert data["primary_owner_name"] == "Alice"+++async def test_get_git_metadata_not_found(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.get(+ f"/api/repos/{repo['id']}/git-metadata",+ params={"file_path": "nonexistent.py"},+ )+ assert resp.status_code == 404+++async def test_get_hotspots(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_git_metadata(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/repos/{repo['id']}/hotspots")+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) == 1 # Only main.py is a hotspot+ assert data[0]["file_path"] == "src/main.py"+ assert data[0]["is_hotspot"] is True+++async def test_get_ownership(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_git_metadata(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/repos/{repo['id']}/ownership")+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) >= 1+ # Both files are under "src" module+ src_entry = next((e for e in data if e["module_path"] == "src"), None)+ assert src_entry is not None+ assert src_entry["file_count"] == 2+++async def test_get_co_changes(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_git_metadata(app.state.session_factory, repo["id"])++ resp = await client.get(+ f"/api/repos/{repo['id']}/co-changes",+ params={"file_path": "src/main.py", "min_count": 3},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert data["file_path"] == "src/main.py"+ assert len(data["co_change_partners"]) == 1+ assert data["co_change_partners"][0]["file_path"] == "src/utils.py"+++async def test_get_git_summary(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_git_metadata(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/repos/{repo['id']}/git-summary")+ assert resp.status_code == 200+ data = resp.json()+ assert data["total_files"] == 2+ assert data["hotspot_count"] == 1+ assert data["stable_count"] == 1+ assert len(data["top_owners"]) == 2diff --git a/tests/unit/server/test_graph.py b/tests/unit/server/test_graph.pynew file mode 100644index 000000000..0dfcc3066--- /dev/null+++ b/tests/unit/server/test_graph.py@@ -0,0 +1,111 @@+"""Tests for /api/graph endpoints."""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from wikicode.core.persistence import crud+from wikicode.core.persistence.database import get_session++from tests.unit.server.conftest import create_test_repo+++async def _populate_graph(session_factory, repo_id: str) -> None:+ """Insert test graph nodes and edges."""+ async with get_session(session_factory) as session:+ await crud.batch_upsert_graph_nodes(+ session,+ repo_id,+ [+ {+ "node_id": "src/main.py",+ "node_type": "file",+ "language": "python",+ "symbol_count": 3,+ "pagerank": 0.8,+ "betweenness": 0.5,+ "community_id": 0,+ },+ {+ "node_id": "src/utils.py",+ "node_type": "file",+ "language": "python",+ "symbol_count": 5,+ "pagerank": 0.3,+ "betweenness": 0.1,+ "community_id": 0,+ },+ ],+ )+ await crud.batch_upsert_graph_edges(+ session,+ repo_id,+ [+ {+ "source_node_id": "src/main.py",+ "target_node_id": "src/utils.py",+ "imported_names_json": '["helper_func"]',+ },+ ],+ )+++async def test_export_graph_empty(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.get(f"/api/graph/{repo['id']}")+ assert resp.status_code == 200+ data = resp.json()+ assert data["nodes"] == []+ assert data["links"] == []+++async def test_export_graph_with_data(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _populate_graph(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/graph/{repo['id']}")+ assert resp.status_code == 200+ data = resp.json()+ assert len(data["nodes"]) == 2+ assert len(data["links"]) == 1+ assert data["links"][0]["source"] == "src/main.py"+ assert data["links"][0]["target"] == "src/utils.py"+ assert data["links"][0]["imported_names"] == ["helper_func"]+++async def test_export_graph_repo_not_found(client: AsyncClient) -> None:+ resp = await client.get("/api/graph/nonexistent")+ assert resp.status_code == 404+++async def test_dependency_path(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _populate_graph(app.state.session_factory, repo["id"])++ resp = await client.get(+ f"/api/graph/{repo['id']}/path",+ params={"from": "src/main.py", "to": "src/utils.py"},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert data["distance"] == 1+ assert data["path"] == ["src/main.py", "src/utils.py"]+++async def test_dependency_path_no_path(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _populate_graph(app.state.session_factory, repo["id"])++ resp = await client.get(+ f"/api/graph/{repo['id']}/path",+ params={"from": "src/utils.py", "to": "src/main.py"},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert data["distance"] == -1 # No reverse pathdiff --git a/tests/unit/server/test_health.py b/tests/unit/server/test_health.pynew file mode 100644index 000000000..5d5438ddb--- /dev/null+++ b/tests/unit/server/test_health.py@@ -0,0 +1,28 @@+"""Tests for /health and /metrics endpoints."""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from wikicode.server import __version__+++async def test_health_returns_200(client: AsyncClient) -> None:+ resp = await client.get("/health")+ assert resp.status_code == 200+ data = resp.json()+ assert data["status"] == "healthy"+ assert data["db"] == "ok"+ assert data["version"] == __version__+++async def test_metrics_returns_prometheus_format(client: AsyncClient) -> None:+ resp = await client.get("/metrics")+ assert resp.status_code == 200+ text = resp.text+ assert "wikicode_pages_total" in text+ assert "wikicode_jobs_total" in text+ assert "wikicode_tokens_total" in textdiff --git a/tests/unit/server/test_jobs.py b/tests/unit/server/test_jobs.pynew file mode 100644index 000000000..a645efcdd--- /dev/null+++ b/tests/unit/server/test_jobs.py@@ -0,0 +1,110 @@+"""Tests for /api/jobs endpoints."""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from wikicode.core.persistence import crud+from wikicode.core.persistence.database import get_session++from tests.unit.server.conftest import create_test_repo+++async def test_list_jobs_empty(client: AsyncClient) -> None:+ resp = await client.get("/api/jobs")+ assert resp.status_code == 200+ assert resp.json() == []+++async def test_list_jobs_with_data(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)++ async with get_session(app.state.session_factory) as session:+ await crud.upsert_generation_job(+ session,+ repository_id=repo["id"],+ status="running",+ provider_name="mock",+ model_name="mock-model",+ total_pages=10,+ )++ resp = await client.get("/api/jobs")+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) == 1+ assert data[0]["status"] == "running"+ assert data[0]["total_pages"] == 10+++async def test_list_jobs_filter_by_repo(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)++ async with get_session(app.state.session_factory) as session:+ await crud.upsert_generation_job(+ session,+ repository_id=repo["id"],+ status="completed",+ )++ # Filter by repo_id+ resp = await client.get("/api/jobs", params={"repo_id": repo["id"]})+ assert resp.status_code == 200+ assert len(resp.json()) == 1++ # Filter by nonexistent repo_id+ resp = await client.get("/api/jobs", params={"repo_id": "nonexistent"})+ assert resp.status_code == 200+ assert len(resp.json()) == 0+++async def test_get_job_by_id(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)++ async with get_session(app.state.session_factory) as session:+ job = await crud.upsert_generation_job(+ session,+ repository_id=repo["id"],+ status="pending",+ )+ job_id = job.id++ resp = await client.get(f"/api/jobs/{job_id}")+ assert resp.status_code == 200+ assert resp.json()["id"] == job_id+ assert resp.json()["status"] == "pending"+++async def test_get_job_not_found(client: AsyncClient) -> None:+ resp = await client.get("/api/jobs/nonexistent")+ assert resp.status_code == 404+++async def test_job_stream_completed(client: AsyncClient, app) -> None:+ """SSE stream should emit progress and done events for a completed job."""+ repo = await create_test_repo(client)++ async with get_session(app.state.session_factory) as session:+ job = await crud.upsert_generation_job(+ session,+ repository_id=repo["id"],+ status="completed",+ total_pages=5,+ )+ await crud.update_job_status(+ session, job.id, "completed", completed_pages=5+ )+ job_id = job.id++ resp = await client.get(f"/api/jobs/{job_id}/stream")+ assert resp.status_code == 200+ assert "text/event-stream" in resp.headers["content-type"]+ # For a completed job, the stream should contain 'done' event+ assert "event: done" in resp.text or "event: progress" in resp.textdiff --git a/tests/unit/server/test_mcp.py b/tests/unit/server/test_mcp.pynew file mode 100644index 000000000..3fd46c5c5--- /dev/null+++ b/tests/unit/server/test_mcp.py@@ -0,0 +1,904 @@+"""Unit tests for WikiCode MCP server tools.++Tests all 13 MCP tools using an in-memory SQLite database with pre-populated+test data, mirroring the conftest pattern from the REST API tests.+"""++from __future__ import annotations++import json+from datetime import datetime, timezone++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine+from sqlalchemy.pool import StaticPool++from wikicode.core.persistence.database import init_db+from wikicode.core.persistence.embedder import MockEmbedder+from wikicode.core.persistence.models import (+ DeadCodeFinding,+ GitMetadata,+ GraphEdge,+ GraphNode,+ Page,+ Repository,+ WikiSymbol,+)+from wikicode.core.persistence.search import FullTextSearch+from wikicode.core.persistence.vector_store import InMemoryVectorStore+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------++_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=timezone.utc)+++async def engine():+ eng = create_async_engine(+ "sqlite+aiosqlite:///:memory:",+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+ )+ await init_db(eng)+ yield eng+ await eng.dispose()+++async def factory(engine):+ return async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)+++async def session(factory):+ async with factory() as s:+ yield s+ await s.commit()+++async def fts(engine):+ f = FullTextSearch(engine)+ await f.ensure_index()+ return f+++async def vector_store():+ embedder = MockEmbedder()+ vs = InMemoryVectorStore(embedder=embedder)+ yield vs+ await vs.close()+++async def repo_id(session: AsyncSession) -> str:+ """Create a test repository and return its ID."""+ repo = Repository(+ id="repo1",+ name="test-repo",+ url="https://github.com/example/test-repo",+ local_path="/tmp/test-repo",+ default_branch="main",+ settings_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ )+ session.add(repo)+ await session.flush()+ return repo.id+++async def populated_db(session: AsyncSession, repo_id: str) -> str:+ """Populate the database with test data for all MCP tools."""+ rid = repo_id++ # ---- Pages ----+ pages = [+ Page(+ id="repo_overview:test-repo",+ repository_id=rid,+ page_type="repo_overview",+ title="Test Repo Overview",+ content="# Test Repo\n\nA comprehensive test repository.",+ target_path="test-repo",+ source_hash="abc123",+ model_name="mock",+ provider_name="mock",+ generation_level=6,+ confidence=1.0,+ freshness_status="fresh",+ metadata_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ ),+ Page(+ id="architecture_diagram:test-repo",+ repository_id=rid,+ page_type="architecture_diagram",+ title="Architecture Diagram",+ content="graph TD\n A[Main] --> B[Auth]\n A --> C[DB]",+ target_path="test-repo",+ source_hash="abc124",+ model_name="mock",+ provider_name="mock",+ generation_level=6,+ confidence=1.0,+ freshness_status="fresh",+ metadata_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ ),+ Page(+ id="module_page:src/auth",+ repository_id=rid,+ page_type="module_page",+ title="Auth Module",+ content="# Auth Module\n\nHandles authentication and authorization.",+ target_path="src/auth",+ source_hash="mod1",+ model_name="mock",+ provider_name="mock",+ generation_level=4,+ confidence=0.95,+ freshness_status="fresh",+ metadata_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ ),+ Page(+ id="module_page:src/db",+ repository_id=rid,+ page_type="module_page",+ title="Database Module",+ content="# Database Module\n\nDatabase access and ORM layer.",+ target_path="src/db",+ source_hash="mod2",+ model_name="mock",+ provider_name="mock",+ generation_level=4,+ confidence=0.90,+ freshness_status="fresh",+ metadata_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ ),+ Page(+ id="file_page:src/auth/service.py",+ repository_id=rid,+ page_type="file_page",+ title="Auth Service",+ content="# AuthService\n\nMain authentication service class.",+ target_path="src/auth/service.py",+ source_hash="file1",+ model_name="mock",+ provider_name="mock",+ generation_level=2,+ confidence=0.85,+ freshness_status="fresh",+ metadata_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ ),+ Page(+ id="file_page:src/auth/middleware.py",+ repository_id=rid,+ page_type="file_page",+ title="Auth Middleware",+ content="# Auth Middleware\n\nRequest authentication middleware.",+ target_path="src/auth/middleware.py",+ source_hash="file2",+ model_name="mock",+ provider_name="mock",+ generation_level=2,+ confidence=0.50,+ freshness_status="stale",+ metadata_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ ),+ Page(+ id="file_page:src/db/models.py",+ repository_id=rid,+ page_type="file_page",+ title="DB Models",+ content="# Database Models\n\nSQLAlchemy ORM models.",+ target_path="src/db/models.py",+ source_hash="file3",+ model_name="mock",+ provider_name="mock",+ generation_level=2,+ confidence=0.40,+ freshness_status="stale",+ metadata_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ ),+ ]+ for p in pages:+ session.add(p)++ # ---- Symbols ----+ symbols = [+ WikiSymbol(+ id="sym1",+ repository_id=rid,+ file_path="src/auth/service.py",+ symbol_id="src/auth/service.py::AuthService",+ name="AuthService",+ qualified_name="auth.service.AuthService",+ kind="class",+ signature="class AuthService",+ start_line=10,+ end_line=100,+ docstring="Main authentication service.",+ visibility="public",+ is_async=False,+ complexity_estimate=15,+ language="python",+ parent_name=None,+ created_at=_NOW,+ updated_at=_NOW,+ ),+ WikiSymbol(+ id="sym2",+ repository_id=rid,+ file_path="src/auth/service.py",+ symbol_id="src/auth/service.py::login",+ name="login",+ qualified_name="auth.service.AuthService.login",+ kind="method",+ signature="async def login(self, username: str, password: str) -> Token",+ start_line=20,+ end_line=40,+ docstring="Authenticate a user.",+ visibility="public",+ is_async=True,+ complexity_estimate=5,+ language="python",+ parent_name="AuthService",+ created_at=_NOW,+ updated_at=_NOW,+ ),+ WikiSymbol(+ id="sym3",+ repository_id=rid,+ file_path="src/db/models.py",+ symbol_id="src/db/models.py::User",+ name="User",+ qualified_name="db.models.User",+ kind="class",+ signature="class User(Base)",+ start_line=5,+ end_line=30,+ docstring="User ORM model.",+ visibility="public",+ is_async=False,+ complexity_estimate=2,+ language="python",+ parent_name=None,+ created_at=_NOW,+ updated_at=_NOW,+ ),+ ]+ for s in symbols:+ session.add(s)++ # ---- Graph Nodes ----+ nodes = [+ GraphNode(+ id="gn1",+ repository_id=rid,+ node_id="src/auth/service.py",+ node_type="file",+ language="python",+ symbol_count=2,+ is_entry_point=True,+ pagerank=0.85,+ betweenness=0.5,+ community_id=1,+ created_at=_NOW,+ ),+ GraphNode(+ id="gn2",+ repository_id=rid,+ node_id="src/auth/middleware.py",+ node_type="file",+ language="python",+ symbol_count=1,+ is_entry_point=False,+ pagerank=0.4,+ betweenness=0.2,+ community_id=1,+ created_at=_NOW,+ ),+ GraphNode(+ id="gn3",+ repository_id=rid,+ node_id="src/db/models.py",+ node_type="file",+ language="python",+ symbol_count=1,+ is_entry_point=False,+ pagerank=0.6,+ betweenness=0.3,+ community_id=2,+ created_at=_NOW,+ ),+ ]+ for n in nodes:+ session.add(n)++ # ---- Graph Edges ----+ edges = [+ GraphEdge(+ id="ge1",+ repository_id=rid,+ source_node_id="src/auth/service.py",+ target_node_id="src/db/models.py",+ imported_names_json='["User"]',+ created_at=_NOW,+ ),+ GraphEdge(+ id="ge2",+ repository_id=rid,+ source_node_id="src/auth/middleware.py",+ target_node_id="src/auth/service.py",+ imported_names_json='["AuthService"]',+ created_at=_NOW,+ ),+ ]+ for e in edges:+ session.add(e)++ # ---- Git Metadata ----+ git_metas = [+ GitMetadata(+ id="gm1",+ repository_id=rid,+ file_path="src/auth/service.py",+ commit_count_total=42,+ commit_count_90d=8,+ commit_count_30d=3,+ first_commit_at=datetime(2025, 1, 1, tzinfo=timezone.utc),+ last_commit_at=datetime(2026, 3, 15, tzinfo=timezone.utc),+ primary_owner_name="Alice",+ primary_owner_email="[email protected]",+ primary_owner_commit_pct=0.65,+ top_authors_json=json.dumps([+ {"name": "Alice", "count": 27},+ {"name": "Bob", "count": 15},+ ]),+ significant_commits_json=json.dumps([+ {"sha": "abc1234", "date": "2026-03-15", "message": "Refactor auth flow", "author": "Alice"},+ {"sha": "def5678", "date": "2026-02-10", "message": "Add JWT support", "author": "Bob"},+ ]),+ co_change_partners_json=json.dumps([+ {"file_path": "src/auth/middleware.py", "count": 5},+ {"file_path": "src/db/models.py", "count": 3},+ ]),+ is_hotspot=True,+ is_stable=False,+ churn_percentile=0.92,+ age_days=443,+ created_at=_NOW,+ updated_at=_NOW,+ ),+ GitMetadata(+ id="gm2",+ repository_id=rid,+ file_path="src/db/models.py",+ commit_count_total=15,+ commit_count_90d=0,+ commit_count_30d=0,+ first_commit_at=datetime(2025, 1, 1, tzinfo=timezone.utc),+ last_commit_at=datetime(2025, 9, 1, tzinfo=timezone.utc),+ primary_owner_name="Bob",+ primary_owner_email="[email protected]",+ primary_owner_commit_pct=0.90,+ top_authors_json=json.dumps([{"name": "Bob", "count": 13}]),+ significant_commits_json=json.dumps([+ {"sha": "111aaa", "date": "2025-09-01", "message": "Add migration helper", "author": "Bob"},+ ]),+ co_change_partners_json=json.dumps([+ {"file_path": "src/auth/service.py", "count": 3},+ ]),+ is_hotspot=False,+ is_stable=True,+ churn_percentile=0.15,+ age_days=443,+ created_at=_NOW,+ updated_at=_NOW,+ ),+ ]+ for g in git_metas:+ session.add(g)++ # ---- Dead Code Findings ----+ findings = [+ DeadCodeFinding(+ id="dc1",+ repository_id=rid,+ kind="unreachable_file",+ file_path="src/legacy/old_auth.py",+ symbol_name=None,+ symbol_kind=None,+ confidence=0.9,+ reason="No imports found; file not referenced by any other module",+ lines=150,+ safe_to_delete=True,+ primary_owner="Alice",+ age_days=365,+ status="open",+ analyzed_at=_NOW,+ ),+ DeadCodeFinding(+ id="dc2",+ repository_id=rid,+ kind="unused_export",+ file_path="src/auth/service.py",+ symbol_name="deprecated_login",+ symbol_kind="function",+ confidence=0.7,+ reason="Exported but no external callers found",+ lines=20,+ safe_to_delete=True,+ primary_owner="Bob",+ age_days=120,+ status="open",+ analyzed_at=_NOW,+ ),+ DeadCodeFinding(+ id="dc3",+ repository_id=rid,+ kind="unused_export",+ file_path="src/db/models.py",+ symbol_name="OldModel",+ symbol_kind="class",+ confidence=0.5,+ reason="Exported but no external callers found",+ lines=40,+ safe_to_delete=False,+ primary_owner="Bob",+ age_days=200,+ status="open",+ analyzed_at=_NOW,+ ),+ ]+ for f in findings:+ session.add(f)++ await session.flush()+ return rid+++# ---------------------------------------------------------------------------+# MCP tool tests+# ---------------------------------------------------------------------------+++async def setup_mcp(factory, fts, vector_store, populated_db):+ """Configure the MCP module's global state for testing."""+ import wikicode.server.mcp_server as mcp_mod++ mcp_mod._session_factory = factory+ mcp_mod._fts = fts+ mcp_mod._vector_store = vector_store+ mcp_mod._repo_path = "/tmp/test-repo"++ yield populated_db++ # Reset globals+ mcp_mod._session_factory = None+ mcp_mod._fts = None+ mcp_mod._vector_store = None+ mcp_mod._repo_path = None+++# ---- Tool 1: get_overview ----+++async def test_get_overview(setup_mcp):+ from wikicode.server.mcp_server import get_overview++ result = await get_overview()+ assert result["title"] == "Test Repo Overview"+ assert "comprehensive test" in result["content_md"]+ assert result["architecture_diagram_mermaid"] is not None+ assert "graph TD" in result["architecture_diagram_mermaid"]+ assert len(result["key_modules"]) == 2+ assert any(m["name"] == "Auth Module" for m in result["key_modules"])+ assert "src/auth/service.py" in result["entry_points"]+++async def test_get_overview_with_repo_path(setup_mcp):+ from wikicode.server.mcp_server import get_overview++ result = await get_overview(repo="/tmp/test-repo")+ assert result["title"] == "Test Repo Overview"+++async def test_get_overview_repo_not_found(setup_mcp):+ from wikicode.server.mcp_server import get_overview++ with pytest.raises(LookupError, match="not found"):+ await get_overview(repo="/nonexistent")+++# ---- Tool 2: get_module_docs ----+++async def test_get_module_docs(setup_mcp):+ from wikicode.server.mcp_server import get_module_docs++ result = await get_module_docs("src/auth")+ assert result["title"] == "Auth Module"+ assert "authentication" in result["content_md"].lower()+ assert len(result["files"]) == 2 # service.py and middleware.py+ assert result["public_api_summary"]+++async def test_get_module_docs_not_found(setup_mcp):+ from wikicode.server.mcp_server import get_module_docs++ result = await get_module_docs("src/nonexistent")+ assert "error" in result+++# ---- Tool 3: get_file_docs ----+++async def test_get_file_docs(setup_mcp):+ from wikicode.server.mcp_server import get_file_docs++ result = await get_file_docs("src/auth/service.py")+ assert result["title"] == "Auth Service"+ assert "AuthService" in result["content_md"]+ assert len(result["symbols"]) == 2+ assert any(s["name"] == "AuthService" for s in result["symbols"])+ assert any(s["name"] == "login" for s in result["symbols"])+ assert "src/auth/middleware.py" in result["imported_by"]+ assert result["confidence_score"] == 0.85+ assert result["freshness_status"] == "fresh"+++async def test_get_file_docs_not_found(setup_mcp):+ from wikicode.server.mcp_server import get_file_docs++ result = await get_file_docs("src/nonexistent.py")+ assert "error" in result+++# ---- Tool 4: get_symbol ----+++async def test_get_symbol_exact_match(setup_mcp):+ from wikicode.server.mcp_server import get_symbol++ result = await get_symbol("AuthService")+ assert result["name"] == "AuthService"+ assert result["kind"] == "class"+ assert result["file_path"] == "src/auth/service.py"+ assert result["signature"] == "class AuthService"+ assert result["documentation"] # Has content from page+++async def test_get_symbol_fuzzy_match(setup_mcp):+ from wikicode.server.mcp_server import get_symbol++ result = await get_symbol("Auth") # Partial match+ assert result["name"] == "AuthService"+++async def test_get_symbol_with_kind(setup_mcp):+ from wikicode.server.mcp_server import get_symbol++ result = await get_symbol("login", kind="method")+ assert result["name"] == "login"+ assert result["kind"] == "method"+++async def test_get_symbol_not_found(setup_mcp):+ from wikicode.server.mcp_server import get_symbol++ result = await get_symbol("NonExistentSymbol123")+ assert "error" in result+++# ---- Tool 5: search_codebase ----+++async def test_search_codebase(setup_mcp):+ from wikicode.server.mcp_server import search_codebase++ # Index pages in the MCP module's vector store (which is the InMemoryVectorStore)+ import wikicode.server.mcp_server as mcp_mod++ await mcp_mod._vector_store.embed_and_upsert(+ "file_page:src/auth/service.py",+ "Auth Service — Main authentication service class",+ {"title": "Auth Service", "page_type": "file_page", "target_path": "src/auth/service.py"},+ )+ await mcp_mod._vector_store.embed_and_upsert(+ "file_page:src/db/models.py",+ "DB Models — SQLAlchemy ORM models",+ {"title": "DB Models", "page_type": "file_page", "target_path": "src/db/models.py"},+ )++ result = await search_codebase("authentication service")+ assert "results" in result+ assert len(result["results"]) >= 1+++# ---- Tool 6: get_architecture_diagram ----+++async def test_get_architecture_diagram_repo(setup_mcp):+ from wikicode.server.mcp_server import get_architecture_diagram++ result = await get_architecture_diagram(scope="repo")+ assert result["diagram_type"] in ("flowchart", "auto")+ assert "mermaid_syntax" in result+ assert "graph TD" in result["mermaid_syntax"]+++async def test_get_architecture_diagram_module(setup_mcp):+ from wikicode.server.mcp_server import get_architecture_diagram++ result = await get_architecture_diagram(scope="module", path="src/auth")+ assert "mermaid_syntax" in result+ assert result["description"]+++# ---- Tool 7: get_dependency_path ----+++async def test_get_dependency_path(setup_mcp):+ from wikicode.server.mcp_server import get_dependency_path++ result = await get_dependency_path("src/auth/service.py", "src/db/models.py")+ assert result["distance"] == 1+ assert len(result["path"]) == 2+++async def test_get_dependency_path_multi_hop(setup_mcp):+ from wikicode.server.mcp_server import get_dependency_path++ result = await get_dependency_path("src/auth/middleware.py", "src/db/models.py")+ assert result["distance"] == 2+ assert len(result["path"]) == 3+++async def test_get_dependency_path_no_path(setup_mcp):+ from wikicode.server.mcp_server import get_dependency_path++ # Reverse direction — no path from models to middleware+ result = await get_dependency_path("src/db/models.py", "src/auth/middleware.py")+ assert result["distance"] == -1+ assert result["path"] == []+++async def test_get_dependency_path_node_not_found(setup_mcp):+ from wikicode.server.mcp_server import get_dependency_path++ result = await get_dependency_path("nonexistent.py", "src/auth/service.py")+ assert "error" in result+++# ---- Tool 8: get_stale_pages ----+++async def test_get_stale_pages(setup_mcp):+ from wikicode.server.mcp_server import get_stale_pages++ result = await get_stale_pages(threshold=0.6)+ stale = result["stale_pages"]+ assert len(stale) == 2 # middleware (0.50) and models (0.40)+ # Should be sorted by confidence ASC+ assert stale[0]["confidence_score"] <= stale[1]["confidence_score"]+++async def test_get_stale_pages_high_threshold(setup_mcp):+ from wikicode.server.mcp_server import get_stale_pages++ result = await get_stale_pages(threshold=0.9)+ stale = result["stale_pages"]+ assert len(stale) >= 3 # middleware, models, service all below 0.9+++# ---- Tool 9: get_file_history ----+++async def test_get_file_history(setup_mcp):+ from wikicode.server.mcp_server import get_file_history++ result = await get_file_history("src/auth/service.py")+ assert result["file_path"] == "src/auth/service.py"+ assert result["age_days"] == 443+ assert result["primary_owner"]["name"] == "Alice"+ assert result["primary_owner"]["pct"] == 0.65+ assert result["is_hotspot"] is True+ assert result["is_stable"] is False+ assert result["commit_count_total"] == 42+ assert result["commit_count_90d"] == 8+ assert len(result["significant_commits"]) == 2+ assert len(result["co_change_partners"]) == 2+++async def test_get_file_history_not_found(setup_mcp):+ from wikicode.server.mcp_server import get_file_history++ result = await get_file_history("nonexistent.py")+ assert "error" in result+++# ---- Tool 10: get_hotspots ----+++async def test_get_hotspots(setup_mcp):+ from wikicode.server.mcp_server import get_hotspots++ result = await get_hotspots()+ assert len(result["hotspots"]) == 1+ assert result["hotspots"][0]["file_path"] == "src/auth/service.py"+ assert result["hotspots"][0]["churn_percentile"] == 0.92+ assert "stable_files" not in result+++async def test_get_hotspots_include_stable(setup_mcp):+ from wikicode.server.mcp_server import get_hotspots++ result = await get_hotspots(include_stable=True)+ assert "stable_files" in result+ assert len(result["stable_files"]) == 1+ assert result["stable_files"][0]["file_path"] == "src/db/models.py"+++# ---- Tool 11: get_codebase_ownership ----+++async def test_get_codebase_ownership_by_module(setup_mcp):+ from wikicode.server.mcp_server import get_codebase_ownership++ result = await get_codebase_ownership(by="module")+ assert "by_module" in result+ modules = result["by_module"]+ # Both files are under src/, so grouped as one module "src"+ assert len(modules) == 1+ assert modules[0]["module_path"] == "src"+ assert modules[0]["contributor_count"] == 2+++async def test_get_codebase_ownership_by_file(setup_mcp):+ from wikicode.server.mcp_server import get_codebase_ownership++ result = await get_codebase_ownership(by="file")+ assert "by_file" in result+ assert len(result["by_file"]) == 2 # Only files with git metadata+++# ---- Tool 12: get_co_changes ----+++async def test_get_co_changes(setup_mcp):+ from wikicode.server.mcp_server import get_co_changes++ result = await get_co_changes("src/auth/service.py", min_count=3)+ assert result["file_path"] == "src/auth/service.py"+ partners = result["co_change_partners"]+ assert len(partners) == 2+ # Check enrichment+ middleware_partner = next(p for p in partners if p["file_path"] == "src/auth/middleware.py")+ assert middleware_partner["co_change_count"] == 5+ assert middleware_partner["has_import_relationship"] is True # edge exists+ assert middleware_partner["wiki_page_snippet"] is not None+++async def test_get_co_changes_not_found(setup_mcp):+ from wikicode.server.mcp_server import get_co_changes++ result = await get_co_changes("nonexistent.py")+ assert "error" in result+++# ---- Tool 13: get_dead_code ----+++async def test_get_dead_code(setup_mcp):+ from wikicode.server.mcp_server import get_dead_code++ result = await get_dead_code()+ assert result["summary"]["total_findings"] == 3+ assert result["summary"]["safe_to_delete_count"] == 2+ # Default min_confidence=0.6, so dc3 (0.5) is excluded from findings+ findings = result["findings"]+ assert len(findings) == 2+ assert findings[0]["confidence"] >= findings[1]["confidence"] # sorted desc+++async def test_get_dead_code_safe_only(setup_mcp):+ from wikicode.server.mcp_server import get_dead_code++ result = await get_dead_code(safe_only=True)+ for f in result["findings"]:+ assert f["safe_to_delete"] is True+++async def test_get_dead_code_by_kind(setup_mcp):+ from wikicode.server.mcp_server import get_dead_code++ result = await get_dead_code(kind="unreachable_file", min_confidence=0.0)+ for f in result["findings"]:+ assert f["kind"] == "unreachable_file"+++async def test_get_dead_code_low_confidence(setup_mcp):+ from wikicode.server.mcp_server import get_dead_code++ result = await get_dead_code(min_confidence=0.0)+ assert len(result["findings"]) == 3 # All 3 findings included+++# ---- MCP config generation ----+++def test_generate_mcp_config():+ from pathlib import Path+ from wikicode.cli.mcp_config import generate_mcp_config++ config = generate_mcp_config(Path("/tmp/test-repo"))+ assert "mcpServers" in config+ assert "wikicode" in config["mcpServers"]+ server = config["mcpServers"]["wikicode"]+ assert server["command"] == "wikicode"+ assert "mcp" in server["args"]+ assert "stdio" in server["args"]+++def test_format_setup_instructions():+ from pathlib import Path+ from wikicode.cli.mcp_config import format_setup_instructions++ instructions = format_setup_instructions(Path("/tmp/test-repo"))+ assert "Claude Code" in instructions+ assert "Cursor" in instructions+ assert "Cline" in instructions+ assert "wikicode" in instructionsdiff --git a/tests/unit/server/test_pages.py b/tests/unit/server/test_pages.pynew file mode 100644index 000000000..a6431e5c6--- /dev/null+++ b/tests/unit/server/test_pages.py@@ -0,0 +1,106 @@+"""Tests for /api/pages endpoints."""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from wikicode.core.persistence import crud+from wikicode.core.persistence.database import get_session++from tests.unit.server.conftest import create_test_repo+++async def _create_page(client: AsyncClient, session_factory) -> tuple[str, str]:+ """Create a repo and a page, return (repo_id, page_id)."""+ repo = await create_test_repo(client)+ repo_id = repo["id"]++ async with get_session(session_factory) as session:+ await crud.upsert_page(+ session,+ page_id="file_page:src/main.py",+ repository_id=repo_id,+ page_type="file_page",+ title="main.py",+ content="# Main module\n\nEntry point.",+ target_path="src/main.py",+ source_hash="abc123",+ model_name="mock",+ provider_name="mock",+ )++ return repo_id, "file_page:src/main.py"+++async def test_list_pages_empty(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.get("/api/pages", params={"repo_id": repo["id"]})+ assert resp.status_code == 200+ assert resp.json() == []+++async def test_list_pages_with_data(client: AsyncClient, app) -> None:+ repo_id, page_id = await _create_page(client, app.state.session_factory)+ resp = await client.get("/api/pages", params={"repo_id": repo_id})+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) == 1+ assert data[0]["id"] == page_id+ assert data[0]["title"] == "main.py"+++async def test_get_page_by_path(client: AsyncClient, app) -> None:+ repo_id, page_id = await _create_page(client, app.state.session_factory)+ resp = await client.get(f"/api/pages/{page_id}")+ assert resp.status_code == 200+ data = resp.json()+ assert data["id"] == page_id+ assert data["content"] == "# Main module\n\nEntry point."+++async def test_get_page_by_query(client: AsyncClient, app) -> None:+ repo_id, page_id = await _create_page(client, app.state.session_factory)+ resp = await client.get("/api/pages/lookup", params={"page_id": page_id})+ assert resp.status_code == 200+ assert resp.json()["id"] == page_id+++async def test_get_page_not_found(client: AsyncClient) -> None:+ resp = await client.get("/api/pages/file_page:nonexistent.py")+ assert resp.status_code == 404+++async def test_get_page_versions_empty(client: AsyncClient, app) -> None:+ repo_id, page_id = await _create_page(client, app.state.session_factory)+ resp = await client.get(+ "/api/pages/lookup/versions", params={"page_id": page_id}+ )+ assert resp.status_code == 200+ assert resp.json() == [] # First version has no archived versions+++async def test_regenerate_page_returns_202(client: AsyncClient, app) -> None:+ repo_id, page_id = await _create_page(client, app.state.session_factory)+ resp = await client.post(+ "/api/pages/lookup/regenerate", params={"page_id": page_id}+ )+ assert resp.status_code == 202+ data = resp.json()+ assert "job_id" in data+++async def test_regenerate_page_not_found(client: AsyncClient) -> None:+ resp = await client.post(+ "/api/pages/lookup/regenerate",+ params={"page_id": "file_page:nonexistent.py"},+ )+ assert resp.status_code == 404diff --git a/tests/unit/server/test_repos.py b/tests/unit/server/test_repos.pynew file mode 100644index 000000000..221f2ff94--- /dev/null+++ b/tests/unit/server/test_repos.py@@ -0,0 +1,94 @@+"""Tests for /api/repos endpoints."""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from tests.unit.server.conftest import create_test_repo+++async def test_create_repo(client: AsyncClient) -> None:+ resp = await client.post(+ "/api/repos",+ json={+ "name": "my-repo",+ "local_path": "/tmp/my-repo",+ "url": "https://github.com/example/my-repo",+ },+ )+ assert resp.status_code == 201+ data = resp.json()+ assert data["name"] == "my-repo"+ assert data["local_path"] == "/tmp/my-repo"+ assert data["url"] == "https://github.com/example/my-repo"+ assert data["default_branch"] == "main"+ assert "id" in data+++async def test_list_repos_empty(client: AsyncClient) -> None:+ resp = await client.get("/api/repos")+ assert resp.status_code == 200+ assert resp.json() == []+++async def test_list_repos_with_data(client: AsyncClient) -> None:+ await create_test_repo(client)+ resp = await client.get("/api/repos")+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) == 1+ assert data[0]["name"] == "test-repo"+++async def test_get_repo_by_id(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.get(f"/api/repos/{repo['id']}")+ assert resp.status_code == 200+ assert resp.json()["name"] == "test-repo"+++async def test_get_repo_not_found(client: AsyncClient) -> None:+ resp = await client.get("/api/repos/nonexistent")+ assert resp.status_code == 404+++async def test_update_repo(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.patch(+ f"/api/repos/{repo['id']}",+ json={"name": "updated-name"},+ )+ assert resp.status_code == 200+ assert resp.json()["name"] == "updated-name"+++async def test_sync_repo_returns_202(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.post(f"/api/repos/{repo['id']}/sync")+ assert resp.status_code == 202+ data = resp.json()+ assert "job_id" in data+ assert data["status"] == "accepted"+++async def test_sync_repo_not_found(client: AsyncClient) -> None:+ resp = await client.post("/api/repos/nonexistent/sync")+ assert resp.status_code == 404+++async def test_full_resync_returns_202(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.post(f"/api/repos/{repo['id']}/full-resync")+ assert resp.status_code == 202+ data = resp.json()+ assert "job_id" in datadiff --git a/tests/unit/server/test_search.py b/tests/unit/server/test_search.pynew file mode 100644index 000000000..3827a2d58--- /dev/null+++ b/tests/unit/server/test_search.py@@ -0,0 +1,82 @@+"""Tests for /api/search endpoints."""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from wikicode.core.persistence import crud+from wikicode.core.persistence.database import get_session++from tests.unit.server.conftest import create_test_repo+++async def test_semantic_search_empty(client: AsyncClient) -> None:+ resp = await client.get("/api/search", params={"query": "auth module"})+ assert resp.status_code == 200+ assert resp.json() == []+++async def test_semantic_search_with_data(client: AsyncClient, app) -> None:+ # Insert a page and embed it in the vector store+ repo = await create_test_repo(client)+ repo_id = repo["id"]++ async with get_session(app.state.session_factory) as session:+ await crud.upsert_page(+ session,+ page_id="file_page:src/auth.py",+ repository_id=repo_id,+ page_type="file_page",+ title="auth.py",+ content="# Authentication module\n\nHandles user login and logout.",+ target_path="src/auth.py",+ source_hash="def456",+ model_name="mock",+ provider_name="mock",+ )++ # Embed in vector store+ await app.state.vector_store.embed_and_upsert(+ "file_page:src/auth.py",+ "Authentication module handles user login and logout",+ {+ "title": "auth.py",+ "page_type": "file_page",+ "target_path": "src/auth.py",+ "content": "Authentication module handles user login and logout",+ },+ )++ resp = await client.get("/api/search", params={"query": "authentication"})+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) >= 1+ assert data[0]["page_id"] == "file_page:src/auth.py"+ assert data[0]["search_type"] == "vector"+++async def test_fulltext_search(client: AsyncClient, app) -> None:+ # Index a page in FTS+ await app.state.fts.index(+ "file_page:src/main.py",+ "main.py",+ "Entry point for the application with routing logic",+ )++ resp = await client.get(+ "/api/search",+ params={"query": "routing", "search_type": "fulltext"},+ )+ assert resp.status_code == 200+ # FTS requires exact word match; this may or may not match+ # depending on tokenization, but the endpoint should not error+++async def test_search_requires_query(client: AsyncClient) -> None:+ resp = await client.get("/api/search", params={"query": ""})+ assert resp.status_code == 422 # Validation error: min_length=1diff --git a/tests/unit/server/test_symbols.py b/tests/unit/server/test_symbols.pynew file mode 100644index 000000000..076034627--- /dev/null+++ b/tests/unit/server/test_symbols.py@@ -0,0 +1,128 @@+"""Tests for /api/symbols endpoints."""++from __future__ import annotations++import pytest+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from wikicode.core.persistence.database import get_session+from wikicode.core.persistence.models import WikiSymbol, _new_uuid, _now_utc++from tests.unit.server.conftest import create_test_repo+++async def _insert_symbol(session_factory, repo_id: str, **overrides) -> str:+ """Insert a test symbol and return its DB id."""+ defaults = {+ "id": _new_uuid(),+ "repository_id": repo_id,+ "file_path": "src/main.py",+ "symbol_id": "src/main.py::main",+ "name": "main",+ "qualified_name": "src.main.main",+ "kind": "function",+ "signature": "def main() -> None",+ "start_line": 1,+ "end_line": 10,+ "visibility": "public",+ "language": "python",+ }+ defaults.update(overrides)+ sym_id = defaults["id"]++ async with get_session(session_factory) as session:+ session.add(WikiSymbol(**defaults))++ return sym_id+++async def test_search_symbols_empty(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ resp = await client.get("/api/symbols", params={"repo_id": repo["id"]})+ assert resp.status_code == 200+ assert resp.json() == []+++async def test_search_symbols_by_name(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_symbol(app.state.session_factory, repo["id"])++ resp = await client.get(+ "/api/symbols", params={"repo_id": repo["id"], "q": "main"}+ )+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) == 1+ assert data[0]["name"] == "main"+ assert data[0]["kind"] == "function"+++async def test_search_symbols_by_kind(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_symbol(+ app.state.session_factory,+ repo["id"],+ name="MyClass",+ symbol_id="src/main.py::MyClass",+ kind="class",+ )++ resp = await client.get(+ "/api/symbols", params={"repo_id": repo["id"], "kind": "class"}+ )+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) == 1+ assert data[0]["kind"] == "class"+++async def test_lookup_by_name_exact(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_symbol(app.state.session_factory, repo["id"])++ resp = await client.get(+ "/api/symbols/by-name/main", params={"repo_id": repo["id"]}+ )+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) == 1+ assert data[0]["name"] == "main"+++async def test_lookup_by_name_fuzzy(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_symbol(+ app.state.session_factory,+ repo["id"],+ name="authenticate_user",+ symbol_id="src/auth.py::authenticate_user",+ )++ resp = await client.get(+ "/api/symbols/by-name/auth", params={"repo_id": repo["id"]}+ )+ assert resp.status_code == 200+ data = resp.json()+ assert len(data) >= 1+++async def test_get_symbol_by_db_id(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ sym_id = await _insert_symbol(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/symbols/{sym_id}")+ assert resp.status_code == 200+ assert resp.json()["name"] == "main"+++async def test_get_symbol_not_found(client: AsyncClient) -> None:+ resp = await client.get("/api/symbols/nonexistent")+ assert resp.status_code == 404diff --git a/tests/unit/server/test_webhooks.py b/tests/unit/server/test_webhooks.pynew file mode 100644index 000000000..9ccbd908b--- /dev/null+++ b/tests/unit/server/test_webhooks.py@@ -0,0 +1,130 @@+"""Tests for /api/webhooks endpoints."""++from __future__ import annotations++import hashlib+import hmac+import json+import os+from unittest.mock import patch++import pytest+from httpx import AsyncClient++from tests.unit.server.conftest import create_test_repo+++async def test_github_webhook_no_secret(client: AsyncClient) -> None:+ """Without a secret configured, any payload is accepted."""+ payload = {+ "ref": "refs/heads/main",+ "repository": {"clone_url": "https://github.com/example/test-repo.git"},+ }+ resp = await client.post(+ "/api/webhooks/github",+ content=json.dumps(payload),+ headers={+ "X-GitHub-Event": "push",+ "X-GitHub-Delivery": "test-delivery-1",+ "Content-Type": "application/json",+ },+ )+ assert resp.status_code == 200+ data = resp.json()+ assert "event_id" in data+ assert data["status"] == "accepted"+++async def test_github_webhook_valid_signature(client: AsyncClient) -> None:+ """With a secret configured, a valid signature passes."""+ secret = "test-webhook-secret"+ payload = json.dumps({"ref": "refs/heads/main", "repository": {}})+ sig = "sha256=" + hmac.new(+ secret.encode(), payload.encode(), hashlib.sha256+ ).hexdigest()++ with patch.dict(os.environ, {"WIKICODE_GITHUB_WEBHOOK_SECRET": ""}):+ # Patch the module-level variable+ import wikicode.server.routers.webhooks as wh_mod++ original_secret = wh_mod._GITHUB_SECRET+ wh_mod._GITHUB_SECRET = secret+ try:+ resp = await client.post(+ "/api/webhooks/github",+ content=payload,+ headers={+ "X-GitHub-Event": "push",+ "X-Hub-Signature-256": sig,+ "Content-Type": "application/json",+ },+ )+ assert resp.status_code == 200+ finally:+ wh_mod._GITHUB_SECRET = original_secret+++async def test_github_webhook_invalid_signature(client: AsyncClient) -> None:+ """With a secret configured, an invalid signature is rejected."""+ import wikicode.server.routers.webhooks as wh_mod++ original_secret = wh_mod._GITHUB_SECRET+ wh_mod._GITHUB_SECRET = "real-secret"+ try:+ resp = await client.post(+ "/api/webhooks/github",+ content=json.dumps({"ref": "refs/heads/main"}),+ headers={+ "X-GitHub-Event": "push",+ "X-Hub-Signature-256": "sha256=invalid",+ "Content-Type": "application/json",+ },+ )+ assert resp.status_code == 401+ finally:+ wh_mod._GITHUB_SECRET = original_secret+++async def test_gitlab_webhook_no_token(client: AsyncClient) -> None:+ """Without a token configured, any payload is accepted."""+ payload = {+ "ref": "refs/heads/main",+ "project": {"web_url": "https://gitlab.com/example/test-repo"},+ }+ resp = await client.post(+ "/api/webhooks/gitlab",+ content=json.dumps(payload),+ headers={+ "X-Gitlab-Event": "Push Hook",+ "Content-Type": "application/json",+ },+ )+ assert resp.status_code == 200+ data = resp.json()+ assert "event_id" in data+++async def test_gitlab_webhook_invalid_token(client: AsyncClient) -> None:+ """With a token configured, wrong token is rejected."""+ import wikicode.server.routers.webhooks as wh_mod++ original_token = wh_mod._GITLAB_TOKEN+ wh_mod._GITLAB_TOKEN = "correct-token"+ try:+ resp = await client.post(+ "/api/webhooks/gitlab",+ content=json.dumps({"ref": "refs/heads/main"}),+ headers={+ "X-Gitlab-Event": "Push Hook",+ "X-Gitlab-Token": "wrong-token",+ "Content-Type": "application/json",+ },+ )+ assert resp.status_code == 401+ finally:+ wh_mod._GITLAB_TOKEN = original_tokendiff --git a/tests/unit/test_confidence_with_git.py b/tests/unit/test_confidence_with_git.pynew file mode 100644index 000000000..4aeb6f1df--- /dev/null+++ b/tests/unit/test_confidence_with_git.py@@ -0,0 +1,63 @@+"""Unit tests for compute_confidence_decay_with_git."""++import pytest++from wikicode.core.generation.models import compute_confidence_decay_with_git+++class TestComputeConfidenceDecayWithGit:+ """Tests for git-informed confidence decay modifiers."""++ def test_hotspot_decays_faster(self) -> None:+ """Hotspot file with direct relationship should decay faster (*0.94)."""+ base_decay = 0.85+ git_meta = {"is_hotspot": True, "is_stable": False}++ result = compute_confidence_decay_with_git(+ base_decay=base_decay,+ relationship="direct",+ git_meta=git_meta,+ commit_message=None,+ )++ assert result == pytest.approx(base_decay * 0.94)++ def test_stable_decays_slower(self) -> None:+ """Stable file with direct relationship should decay slower (*1.03)."""+ base_decay = 0.85+ git_meta = {"is_hotspot": False, "is_stable": True}++ result = compute_confidence_decay_with_git(+ base_decay=base_decay,+ relationship="direct",+ git_meta=git_meta,+ commit_message=None,+ )++ assert result == pytest.approx(base_decay * 1.03)++ def test_rewrite_commit_hard_decay(self) -> None:+ """Commit message containing 'refactor' should apply hard decay (*0.71)."""+ base_decay = 0.85++ result = compute_confidence_decay_with_git(+ base_decay=base_decay,+ relationship="direct",+ git_meta=None,+ commit_message="refactor: extract helper module",+ )++ assert result == pytest.approx(base_decay * 0.71)++ def test_typo_commit_soft_decay(self) -> None:+ """Commit message containing 'typo' should apply soft decay (*1.12)."""+ base_decay = 0.85++ result = compute_confidence_decay_with_git(+ base_decay=base_decay,+ relationship="direct",+ git_meta=None,+ commit_message="fix typo in docstring",+ )++ assert result == pytest.approx(base_decay * 1.12)diff --git a/tests/unit/test_dead_code.py b/tests/unit/test_dead_code.pynew file mode 100644index 000000000..bb012b5b4--- /dev/null+++ b/tests/unit/test_dead_code.py@@ -0,0 +1,550 @@+"""Unit tests for DeadCodeAnalyzer."""++from __future__ import annotations++from datetime import datetime, timedelta, timezone++import networkx as nx+import pytest++from wikicode.core.analysis.dead_code import (+ DeadCodeAnalyzer,+ DeadCodeKind,+ DeadCodeReport,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _now() -> datetime:+ return datetime.now(timezone.utc)+++def _old_date(days: int = 365) -> datetime:+ """Return a datetime `days` ago (timezone-aware)."""+ return _now() - timedelta(days=days)+++def _build_graph(+ nodes: dict[str, dict],+ edges: list[tuple[str, str]] | None = None,+) -> nx.DiGraph:+ """Create a DiGraph with the given node attributes and edges.++ ``nodes`` maps node-id to its attribute dict.+ ``edges`` is a list of (src, dst) pairs; edge data can be+ supplied as a 3-tuple (src, dst, data_dict).+ """+ g = nx.DiGraph()+ for name, attrs in nodes.items():+ g.add_node(name, **attrs)+ for edge in edges or []:+ if len(edge) == 3:+ g.add_edge(edge[0], edge[1], **(edge[2]))+ else:+ g.add_edge(edge[0], edge[1])+ return g+++# ---------------------------------------------------------------------------+# 1. test_unreachable_file_detected+# ---------------------------------------------------------------------------++def test_unreachable_file_detected():+ """A file with in_degree=0, not an entry point, should be flagged as unreachable."""+ g = _build_graph(+ nodes={+ "pkg/orphan.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 5,+ "symbols": [],+ },+ "pkg/main.py": {+ "is_entry_point": True,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 10,+ "symbols": [],+ },+ },+ edges=[], # orphan.py has in_degree=0+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})++ unreachable = [f for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE]+ paths = [f.file_path for f in unreachable]+ assert "pkg/orphan.py" in paths+++# ---------------------------------------------------------------------------+# 2. test_entry_point_not_flagged+# ---------------------------------------------------------------------------++def test_entry_point_not_flagged():+ """A file marked as is_entry_point=True should NOT be flagged even with in_degree=0."""+ g = _build_graph(+ nodes={+ "pkg/main.py": {+ "is_entry_point": True,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 10,+ "symbols": [],+ },+ },+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})++ assert all(f.file_path != "pkg/main.py" for f in report.findings)+++# ---------------------------------------------------------------------------+# 3. test_test_files_excluded+# ---------------------------------------------------------------------------++def test_test_files_excluded():+ """A test file (is_test=True) with in_degree=0 should NOT be flagged."""+ g = _build_graph(+ nodes={+ "tests/test_something.py": {+ "is_entry_point": False,+ "is_test": True,+ "is_api_contract": False,+ "symbol_count": 8,+ "symbols": [],+ },+ },+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})++ assert all(f.file_path != "tests/test_something.py" for f in report.findings)+++# ---------------------------------------------------------------------------+# 4. test_unused_export_detected+# ---------------------------------------------------------------------------++def test_unused_export_detected():+ """A public symbol with no importers should be flagged as unused export."""+ g = _build_graph(+ nodes={+ "pkg/utils.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 3,+ "symbols": [+ {+ "name": "helper_func",+ "kind": "function",+ "visibility": "public",+ "decorators": [],+ "start_line": 1,+ "end_line": 10,+ "complexity_estimate": 2,+ },+ ],+ },+ "pkg/main.py": {+ "is_entry_point": True,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 10,+ "symbols": [],+ },+ },+ # main.py imports utils.py but does NOT import helper_func by name+ edges=[("pkg/main.py", "pkg/utils.py", {"imported_names": ["other_func"]})],+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze({+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ })++ unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ sym_names = [f.symbol_name for f in unused]+ assert "helper_func" in sym_names+++# ---------------------------------------------------------------------------+# 5. test_framework_decorator_excluded+# ---------------------------------------------------------------------------++def test_framework_decorator_excluded():+ """A symbol decorated with pytest.fixture should NOT be flagged."""+ g = _build_graph(+ nodes={+ "pkg/conftest.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 2,+ "symbols": [+ {+ "name": "db_session",+ "kind": "function",+ "visibility": "public",+ "decorators": ["pytest.fixture"],+ "start_line": 1,+ "end_line": 15,+ "complexity_estimate": 1,+ },+ ],+ },+ },+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze({+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ })++ sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ assert "db_session" not in sym_names+++# ---------------------------------------------------------------------------+# 6. test_dynamic_pattern_excluded+# ---------------------------------------------------------------------------++def test_dynamic_pattern_excluded():+ """A symbol matching '*Handler' dynamic pattern should NOT be flagged as unused."""+ g = _build_graph(+ nodes={+ "pkg/events.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 2,+ "symbols": [+ {+ "name": "EventHandler",+ "kind": "class",+ "visibility": "public",+ "decorators": [],+ "start_line": 1,+ "end_line": 40,+ "complexity_estimate": 3,+ },+ ],+ },+ },+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze({+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ })++ sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ assert "EventHandler" not in sym_names+++# ---------------------------------------------------------------------------+# 7. test_confidence_low_for_recent_files+# ---------------------------------------------------------------------------++def test_confidence_low_for_recent_files():+ """Unreachable file with commit_count_90d > 0 should have confidence 0.4."""+ g = _build_graph(+ nodes={+ "pkg/recent.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 5,+ "symbols": [],+ },+ },+ )++ git_meta = {+ "pkg/recent.py": {+ "commit_count_90d": 3,+ "last_commit_at": _now() - timedelta(days=10),+ "age_days": 100,+ "primary_owner_name": "[email protected]",+ },+ }++ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)+ report = analyzer.analyze({+ "detect_unused_exports": False,+ "detect_zombie_packages": False,+ "min_confidence": 0.0,+ })++ findings = [f for f in report.findings if f.file_path == "pkg/recent.py"]+ assert len(findings) == 1+ assert findings[0].confidence == pytest.approx(0.4)+++# ---------------------------------------------------------------------------+# 8. test_confidence_high_for_stale_unreachable+# ---------------------------------------------------------------------------++def test_confidence_high_for_stale_unreachable():+ """Unreachable file with no commits in 90d and last commit > 6 months ago -> confidence 1.0."""+ g = _build_graph(+ nodes={+ "pkg/stale.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 5,+ "symbols": [],+ },+ },+ )++ git_meta = {+ "pkg/stale.py": {+ "commit_count_90d": 0,+ "last_commit_at": _old_date(days=365),+ "age_days": 730,+ "primary_owner_name": "[email protected]",+ },+ }++ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)+ report = analyzer.analyze({+ "detect_unused_exports": False,+ "detect_zombie_packages": False,+ })++ findings = [f for f in report.findings if f.file_path == "pkg/stale.py"]+ assert len(findings) == 1+ assert findings[0].confidence == pytest.approx(1.0)+++# ---------------------------------------------------------------------------+# 9. test_zombie_package_detected+# ---------------------------------------------------------------------------++def test_zombie_package_detected():+ """A package with no incoming inter-package imports should be flagged as zombie."""+ g = _build_graph(+ nodes={+ "pkgA/mod1.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 5,+ "symbols": [],+ },+ "pkgA/mod2.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 3,+ "symbols": [],+ },+ "pkgB/mod1.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 7,+ "symbols": [],+ },+ },+ edges=[+ # pkgA/mod1 imports from pkgA/mod2 (intra-package only)+ ("pkgA/mod1.py", "pkgA/mod2.py"),+ # pkgB has no inter-package importers either, but we focus on pkgA+ # having NO imports from pkgB -> pkgA+ ],+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze({+ "detect_unreachable_files": False,+ "detect_unused_exports": False,+ "min_confidence": 0.0,+ })++ zombie = [f for f in report.findings if f.kind == DeadCodeKind.ZOMBIE_PACKAGE]+ pkgs = [f.package for f in zombie]+ # Both pkgA and pkgB are zombie since neither has inter-package importers+ assert "pkgA" in pkgs+ assert "pkgB" in pkgs+++# ---------------------------------------------------------------------------+# 10. test_whitelist_respected+# ---------------------------------------------------------------------------++def test_whitelist_respected():+ """A file in the whitelist should NOT be flagged even if it is unreachable."""+ g = _build_graph(+ nodes={+ "pkg/legacy.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 20,+ "symbols": [],+ },+ },+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze({+ "detect_unused_exports": False,+ "detect_zombie_packages": False,+ "whitelist": ["pkg/legacy.py"],+ })++ assert all(f.file_path != "pkg/legacy.py" for f in report.findings)+++# ---------------------------------------------------------------------------+# 11. test_safe_to_delete_conservative+# ---------------------------------------------------------------------------++def test_safe_to_delete_conservative():+ """safe_to_delete is True only when confidence >= 0.7 AND file does not match dynamic patterns."""+ g = _build_graph(+ nodes={+ # High confidence, no dynamic pattern match -> safe+ "pkg/old_unused.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 5,+ "symbols": [],+ },+ # High confidence, but file stem matches *Handler -> NOT safe+ "pkg/RequestHandler.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 5,+ "symbols": [],+ },+ # Low confidence (recently touched) -> NOT safe+ "pkg/fresh.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 5,+ "symbols": [],+ },+ },+ )++ git_meta = {+ "pkg/old_unused.py": {+ "commit_count_90d": 0,+ "last_commit_at": _old_date(days=365),+ "age_days": 500,+ },+ "pkg/RequestHandler.py": {+ "commit_count_90d": 0,+ "last_commit_at": _old_date(days=365),+ "age_days": 500,+ },+ "pkg/fresh.py": {+ "commit_count_90d": 5,+ "last_commit_at": _now() - timedelta(days=3),+ "age_days": 60,+ },+ }++ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)+ report = analyzer.analyze({+ "detect_unused_exports": False,+ "detect_zombie_packages": False,+ "min_confidence": 0.0,+ })++ by_path = {f.file_path: f for f in report.findings}+ # High confidence + no dynamic pattern -> safe+ assert by_path["pkg/old_unused.py"].safe_to_delete is True+ # High confidence but matches *Handler -> not safe+ assert by_path["pkg/RequestHandler.py"].safe_to_delete is False+ # Low confidence (0.4) -> not safe+ assert by_path["pkg/fresh.py"].safe_to_delete is False+++# ---------------------------------------------------------------------------+# 12. test_report_deletable_lines_sum+# ---------------------------------------------------------------------------++def test_report_deletable_lines_sum():+ """report.deletable_lines should equal the sum of lines for safe_to_delete findings."""+ g = _build_graph(+ nodes={+ "pkg/dead1.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 10, # lines = 10 * 10 = 100+ "symbols": [],+ },+ "pkg/dead2.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 20, # lines = 20 * 10 = 200+ "symbols": [],+ },+ "pkg/alive.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 15, # lines = 15 * 10 = 150, but NOT safe+ "symbols": [],+ },+ },+ )++ git_meta = {+ "pkg/dead1.py": {+ "commit_count_90d": 0,+ "last_commit_at": _old_date(days=365),+ "age_days": 400,+ },+ "pkg/dead2.py": {+ "commit_count_90d": 0,+ "last_commit_at": _old_date(days=365),+ "age_days": 400,+ },+ # Recently touched -> confidence 0.4, safe_to_delete=False+ "pkg/alive.py": {+ "commit_count_90d": 5,+ "last_commit_at": _now() - timedelta(days=2),+ "age_days": 60,+ },+ }++ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)+ report = analyzer.analyze({+ "detect_unused_exports": False,+ "detect_zombie_packages": False,+ "min_confidence": 0.0,+ })++ safe_findings = [f for f in report.findings if f.safe_to_delete]+ expected_lines = sum(f.lines for f in safe_findings)+ assert report.deletable_lines == expected_lines+ # Verify that the safe findings include the two stale files+ safe_paths = {f.file_path for f in safe_findings}+ assert "pkg/dead1.py" in safe_paths+ assert "pkg/dead2.py" in safe_paths+ assert "pkg/alive.py" not in safe_paths+ # Verify the actual sum+ assert report.deletable_lines == 100 + 200diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.pynew file mode 100644index 000000000..2ca905ab2--- /dev/null+++ b/tests/unit/test_git_indexer.py@@ -0,0 +1,317 @@+"""Unit tests for GitIndexer."""++from __future__ import annotations++import asyncio+from collections import Counter+from datetime import datetime, timedelta, timezone+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from wikicode.core.ingestion.git_indexer import GitIndexer+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_commit(+ message: str = "feat: add feature X to the system",+ author_name: str = "Alice",+ author_email: str = "[email protected]",+ hexsha: str = "abcd1234",+ committed_datetime: datetime | None = None,+ parents: list | None = None,+):+ """Return a lightweight mock commit object mimicking gitpython's Commit."""+ c = MagicMock()+ c.message = message+ c.hexsha = hexsha+ c.author.name = author_name+ c.author.email = author_email+ c.committed_datetime = committed_datetime or datetime.now(timezone.utc)+ c.parents = parents if parents is not None else [MagicMock()]+ return c+++def _make_diff(b_path: str, a_path: str | None = None):+ """Return a lightweight mock diff entry."""+ d = MagicMock()+ d.b_path = b_path+ d.a_path = a_path or b_path+ return d+++# ---------------------------------------------------------------------------+# 1. test_significant_commit_filter+# ---------------------------------------------------------------------------+++class TestSignificantCommitFilter:+ """Merges, bumps, chore, and bot commits are filtered out; normal commits pass."""++ def test_significant_commit_filter(self) -> None:+ indexer = GitIndexer("/tmp/repo")++ # --- Should be filtered (return False) ---++ # Prefix-based filtering+ assert indexer._is_significant_commit("Merge branch 'main' into feature", "Alice") is False+ assert indexer._is_significant_commit("Bump lodash from 4.17.15 to 4.17.21", "Alice") is False+ assert indexer._is_significant_commit("chore: update dependencies across the board", "Alice") is False+ assert indexer._is_significant_commit("ci: fix the github actions workflow", "Alice") is False+ assert indexer._is_significant_commit("style: run prettier on the codebase", "Alice") is False+ assert indexer._is_significant_commit("build: update webpack config for prod", "Alice") is False+ assert indexer._is_significant_commit("release: v2.3.0 official release cut", "Alice") is False+ assert indexer._is_significant_commit("revert: undo the last commit change", "Alice") is False++ # Author-based filtering (bot accounts)+ assert indexer._is_significant_commit(+ "chore(deps): bump axios from 0.21.1 to 0.21.2",+ "dependabot[bot]",+ ) is False+ assert indexer._is_significant_commit(+ "fix(deps): update dependency express to v5",+ "renovate[bot]",+ ) is False+ assert indexer._is_significant_commit(+ "chore: automated release pipeline",+ "github-actions[bot]",+ ) is False++ # Too short (< 20 chars)+ assert indexer._is_significant_commit("fix typo", "Alice") is False++ # --- Should pass (return True) ---+ assert indexer._is_significant_commit(+ "feat: add authentication module with OAuth2 support", "Alice"+ ) is True+ assert indexer._is_significant_commit(+ "fix: resolve race condition in worker queue", "Bob"+ ) is True+++# ---------------------------------------------------------------------------+# 2. test_co_change_detection+# ---------------------------------------------------------------------------+++class TestCoChangeDetection:+ """Files changed together >= 3 times are detected as co-change partners."""++ def test_co_change_detection(self) -> None:+ indexer = GitIndexer("/tmp/repo")++ mock_repo = MagicMock()+ all_files = {"a.py", "b.py", "c.py"}++ # Build 4 commits where a.py and b.py always change together.+ # c.py only changes in 1 commit.+ parent = MagicMock()+ commits = []+ for i in range(4):+ c = _make_commit(hexsha=f"sha{i}", parents=[parent])+ diffs = [_make_diff("a.py"), _make_diff("b.py")]+ if i == 0:+ diffs.append(_make_diff("c.py"))+ c.diff.return_value = diffs+ commits.append(c)++ mock_repo.iter_commits.return_value = commits++ result = indexer._compute_co_changes(mock_repo, all_files, commit_limit=500, min_count=3)++ # a.py <-> b.py should appear (co-changed 4 times, >= min_count=3)+ assert "a.py" in result+ partner_paths = [p["file_path"] for p in result["a.py"]]+ assert "b.py" in partner_paths++ assert "b.py" in result+ partner_paths_b = [p["file_path"] for p in result["b.py"]]+ assert "a.py" in partner_paths_b++ # Verify the count is 4+ co_count = next(p["co_change_count"] for p in result["a.py"] if p["file_path"] == "b.py")+ assert co_count == 4+++# ---------------------------------------------------------------------------+# 3. test_hotspot_classification+# ---------------------------------------------------------------------------+++class TestHotspotClassification:+ """Top 25% churn + activity marks a file as is_hotspot."""++ def test_hotspot_classification(self) -> None:+ indexer = GitIndexer("/tmp/repo")++ # Create 8 files: 6 with low churn, 2 with high churn.+ # The top 25% threshold = index 6 in sorted order (0-indexed).+ # Files with commit_count_90d > p75 AND > 0 should be hotspots.+ metadata_list = []+ for i in range(6):+ metadata_list.append({+ "file_path": f"low_{i}.py",+ "commit_count_90d": 1,+ "is_hotspot": False,+ })+ # Two high-churn files+ metadata_list.append({+ "file_path": "hot_a.py",+ "commit_count_90d": 50,+ "is_hotspot": False,+ })+ metadata_list.append({+ "file_path": "hot_b.py",+ "commit_count_90d": 40,+ "is_hotspot": False,+ })++ indexer._compute_percentiles(metadata_list)++ # The two high-churn files should be hotspots+ hot_a = next(m for m in metadata_list if m["file_path"] == "hot_a.py")+ hot_b = next(m for m in metadata_list if m["file_path"] == "hot_b.py")+ assert hot_a["is_hotspot"] is True+ assert hot_b["is_hotspot"] is True++ # Low-churn files should NOT be hotspots+ for m in metadata_list:+ if m["file_path"].startswith("low_"):+ assert m["is_hotspot"] is False++ # All files should have churn_percentile set+ for m in metadata_list:+ assert "churn_percentile" in m+ assert 0.0 <= m["churn_percentile"] <= 1.0+++# ---------------------------------------------------------------------------+# 4. test_stable_classification+# ---------------------------------------------------------------------------+++class TestStableClassification:+ """>10 total commits, 0 in last 90 days = is_stable."""++ def test_stable_classification(self) -> None:+ indexer = GitIndexer("/tmp/repo")++ mock_repo = MagicMock()++ # Build 15 commits all older than 90 days+ old_date = datetime.now(timezone.utc) - timedelta(days=180)+ commits = [+ _make_commit(+ hexsha=f"sha{i:04d}",+ committed_datetime=old_date - timedelta(days=i),+ )+ for i in range(15)+ ]+ mock_repo.iter_commits.return_value = commits++ # Mock blame to return a simple result+ mock_repo.blame.return_value = [+ (_make_commit(author_name="Alice", author_email="[email protected]"), ["line"] * 100),+ ]++ meta = indexer._index_file("stable_file.py", mock_repo)++ assert meta["commit_count_total"] == 15+ assert meta["commit_count_90d"] == 0+ assert meta["is_stable"] is True+++# ---------------------------------------------------------------------------+# 5. test_git_unavailable_graceful+# ---------------------------------------------------------------------------+++class TestGitUnavailableGraceful:+ """When git is unavailable, index_repo returns empty metadata without crashing."""++ @pytest.mark.asyncio+ async def test_git_unavailable_graceful(self) -> None:+ indexer = GitIndexer("/nonexistent/path")++ # Patch _get_repo to return None (simulating git unavailable)+ with patch.object(indexer, "_get_repo", return_value=None):+ summary, metadata = await indexer.index_repo("test-repo-id")++ assert summary.files_indexed == 0+ assert summary.hotspots == 0+ assert summary.stable_files == 0+ assert metadata == []+++# ---------------------------------------------------------------------------+# 6. test_co_change_below_threshold_skipped+# ---------------------------------------------------------------------------+++class TestCoChangeBelowThresholdSkipped:+ """Pairs with co-change count < min_count are not stored."""++ def test_co_change_below_threshold_skipped(self) -> None:+ indexer = GitIndexer("/tmp/repo")++ mock_repo = MagicMock()+ all_files = {"x.py", "y.py", "z.py"}++ # Only 2 commits with x.py + y.py together (below default min_count=3)+ parent = MagicMock()+ commits = []+ for i in range(2):+ c = _make_commit(hexsha=f"sha{i}", parents=[parent])+ c.diff.return_value = [_make_diff("x.py"), _make_diff("y.py")]+ commits.append(c)++ # 1 commit with x.py + z.py (below min_count=3)+ c_single = _make_commit(hexsha="sha_z", parents=[parent])+ c_single.diff.return_value = [_make_diff("x.py"), _make_diff("z.py")]+ commits.append(c_single)++ mock_repo.iter_commits.return_value = commits++ result = indexer._compute_co_changes(mock_repo, all_files, commit_limit=500, min_count=3)++ # No pairs should appear since none reach min_count=3+ assert result == {}+++# ---------------------------------------------------------------------------+# 7. test_blame_ownership_computed+# ---------------------------------------------------------------------------+++class TestBlameOwnershipComputed:+ """Primary owner is set to the dominant author from git blame."""++ def test_blame_ownership_computed(self) -> None:+ indexer = GitIndexer("/tmp/repo")++ mock_repo = MagicMock()++ # Simulate blame output: Alice owns 80 lines, Bob owns 20 lines+ alice_commit = MagicMock()+ alice_commit.author.name = "Alice"+ alice_commit.author.email = "[email protected]"++ bob_commit = MagicMock()+ bob_commit.author.name = "Bob"+ bob_commit.author.email = "[email protected]"++ mock_repo.blame.return_value = [+ (alice_commit, ["line"] * 80),+ (bob_commit, ["line"] * 20),+ ]++ name, email, pct = indexer._get_blame_ownership("src/main.py", mock_repo)++ assert name == "Alice"+ assert email == "[email protected]"+ assert pct == pytest.approx(0.8)diff --git a/tests/unit/test_persistence/__init__.py b/tests/unit/test_persistence/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/unit/test_persistence/test_openai_embedder.py b/tests/unit/test_persistence/test_openai_embedder.pynew file mode 100644index 000000000..b458dfda2--- /dev/null+++ b/tests/unit/test_persistence/test_openai_embedder.py@@ -0,0 +1,109 @@+"""Unit tests for OpenAIEmbedder.++All tests mock openai.OpenAI — no real API calls are made.+"""++from __future__ import annotations++import math+from unittest.mock import MagicMock, patch++import pytest++from wikicode.core.persistence.openai_embedder import OpenAIEmbedder+++# ---------------------------------------------------------------------------+# Construction+# ---------------------------------------------------------------------------+++def test_missing_api_key_raises(monkeypatch):+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ with pytest.raises(ValueError, match="OpenAI API key required"):+ OpenAIEmbedder(api_key=None)+++def test_api_key_from_env(monkeypatch):+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")+ emb = OpenAIEmbedder()+ assert emb._api_key == "sk-test"+++def test_dimensions_small():+ emb = OpenAIEmbedder(api_key="k", model="text-embedding-3-small")+ assert emb.dimensions == 1536+++def test_dimensions_large():+ emb = OpenAIEmbedder(api_key="k", model="text-embedding-3-large")+ assert emb.dimensions == 3072+++def test_dimensions_unknown_model_defaults_to_1536():+ emb = OpenAIEmbedder(api_key="k", model="some-future-model")+ assert emb.dimensions == 1536+++# ---------------------------------------------------------------------------+# Embedding+# ---------------------------------------------------------------------------+++def _make_mock_embedding(values: list[float]) -> MagicMock:+ item = MagicMock()+ item.embedding = values+ return item+++def _make_mock_response(vectors: list[list[float]]) -> MagicMock:+ response = MagicMock()+ response.data = [_make_mock_embedding(v) for v in vectors]+ return response+++async def test_embed_empty_returns_empty():+ emb = OpenAIEmbedder(api_key="k")+ result = await emb.embed([])+ assert result == []+++async def test_embed_returns_normalized_vectors():+ raw = [1.0, 0.0, 0.0]+ emb = OpenAIEmbedder(api_key="k")++ with patch("openai.OpenAI") as MockClient:+ MockClient.return_value.embeddings.create.return_value = _make_mock_response([raw])+ result = await emb.embed(["hello"])++ assert len(result) == 1+ norm = math.sqrt(sum(x * x for x in result[0]))+ assert abs(norm - 1.0) < 1e-6+++async def test_embed_batch_returns_correct_count():+ texts = ["a", "b", "c"]+ raw_vecs = [[1.0, 0.0], [0.0, 1.0], [0.707, 0.707]]+ emb = OpenAIEmbedder(api_key="k")++ with patch("openai.OpenAI") as MockClient:+ MockClient.return_value.embeddings.create.return_value = _make_mock_response(raw_vecs)+ result = await emb.embed(texts)++ assert len(result) == 3+++async def test_embed_passes_model_and_input():+ emb = OpenAIEmbedder(api_key="k", model="text-embedding-3-large")+ captured: list = []++ def fake_create(model, input):+ captured.append({"model": model, "input": input})+ return _make_mock_response([[1.0, 0.0]])++ with patch("openai.OpenAI") as MockClient:+ MockClient.return_value.embeddings.create.side_effect = fake_create+ await emb.embed(["test text"])++ assert captured[0]["model"] == "text-embedding-3-large"+ assert captured[0]["input"] == ["test text"]diff --git a/tests/unit/test_providers/__init__.py b/tests/unit/test_providers/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/unit/test_providers/test_gemini_provider.py b/tests/unit/test_providers/test_gemini_provider.pynew file mode 100644index 000000000..8a6f4a67f--- /dev/null+++ b/tests/unit/test_providers/test_gemini_provider.py@@ -0,0 +1,159 @@+"""Unit tests for GeminiProvider.++All tests mock google.genai.Client — no real API calls are made.+"""++from __future__ import annotations++from unittest.mock import MagicMock, patch++import pytest++from wikicode.core.providers.base import GeneratedResponse, ProviderError, RateLimitError+from wikicode.core.providers.gemini import GeminiProvider+++# ---------------------------------------------------------------------------+# Construction+# ---------------------------------------------------------------------------+++def test_missing_api_key_raises_provider_error(monkeypatch):+ monkeypatch.delenv("GEMINI_API_KEY", raising=False)+ monkeypatch.delenv("GOOGLE_API_KEY", raising=False)+ with pytest.raises(ProviderError, match="No API key found"):+ GeminiProvider(api_key=None)+++def test_api_key_from_env(monkeypatch):+ monkeypatch.setenv("GEMINI_API_KEY", "test-key")+ p = GeminiProvider()+ assert p.provider_name == "gemini"+++def test_google_api_key_fallback(monkeypatch):+ monkeypatch.delenv("GEMINI_API_KEY", raising=False)+ monkeypatch.setenv("GOOGLE_API_KEY", "google-key")+ p = GeminiProvider()+ assert p._api_key == "google-key"+++def test_provider_name():+ p = GeminiProvider(api_key="k")+ assert p.provider_name == "gemini"+++def test_model_name_default():+ p = GeminiProvider(api_key="k")+ assert p.model_name == "gemini-3.1-flash-lite-preview"+++def test_model_name_custom():+ p = GeminiProvider(model="gemini-3-flash-preview", api_key="k")+ assert p.model_name == "gemini-3-flash-preview"+++# ---------------------------------------------------------------------------+# Successful generation+# ---------------------------------------------------------------------------+++def _make_mock_response(text: str = "# Doc\nContent here.") -> MagicMock:+ usage = MagicMock()+ usage.prompt_token_count = 100+ usage.candidates_token_count = 50+ usage.cached_content_token_count = 0+ usage.total_token_count = 150++ response = MagicMock()+ response.text = text+ response.usage_metadata = usage+ return response+++async def test_generate_returns_generated_response():+ provider = GeminiProvider(api_key="fake-key")+ mock_response = _make_mock_response("Hello world")++ with patch("google.genai.Client") as MockClient:+ MockClient.return_value.models.generate_content.return_value = mock_response+ result = await provider.generate("sys", "user")++ assert isinstance(result, GeneratedResponse)+ assert result.content == "Hello world"+++async def test_generate_token_counts():+ provider = GeminiProvider(api_key="fake-key")+ mock_response = _make_mock_response()++ with patch("google.genai.Client") as MockClient:+ MockClient.return_value.models.generate_content.return_value = mock_response+ result = await provider.generate("sys", "user")++ assert result.input_tokens == 100+ assert result.output_tokens == 50+ assert result.cached_tokens == 0+++async def test_generate_passes_max_tokens():+ provider = GeminiProvider(api_key="fake-key")+ mock_response = _make_mock_response()+ captured: list = []++ def fake_generate_content(model, contents, config):+ captured.append(config)+ return mock_response++ with patch("google.genai.Client") as MockClient:+ MockClient.return_value.models.generate_content.side_effect = fake_generate_content+ await provider.generate("sys", "user", max_tokens=1234)++ assert captured[0].max_output_tokens == 1234+++# ---------------------------------------------------------------------------+# Error mapping+# ---------------------------------------------------------------------------+++async def test_rate_limit_error_on_429():+ provider = GeminiProvider(api_key="fake-key")++ class FakeRateLimit(Exception):+ status_code = 429++ with patch("google.genai.Client") as MockClient:+ MockClient.return_value.models.generate_content.side_effect = FakeRateLimit("quota exceeded")+ with pytest.raises(RateLimitError):+ await provider.generate("sys", "user")+++async def test_rate_limit_error_on_quota_message():+ provider = GeminiProvider(api_key="fake-key")++ with patch("google.genai.Client") as MockClient:+ MockClient.return_value.models.generate_content.side_effect = Exception("quota exceeded for project")+ with pytest.raises(RateLimitError):+ await provider.generate("sys", "user")+++async def test_api_error_on_generic_exception():+ provider = GeminiProvider(api_key="fake-key")++ with patch("google.genai.Client") as MockClient:+ MockClient.return_value.models.generate_content.side_effect = Exception("internal server error")+ with pytest.raises(ProviderError):+ await provider.generate("sys", "user")+++async def test_provider_error_message_includes_exception_type():+ provider = GeminiProvider(api_key="fake-key")++ class CustomError(Exception):+ pass++ with patch("google.genai.Client") as MockClient:+ MockClient.return_value.models.generate_content.side_effect = CustomError("bad request")+ with pytest.raises(ProviderError, match="CustomError"):+ await provider.generate("sys", "user")