Skip to content

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

chore: remove verified dead code across CLI, core, server, and web (#906)

Raghav Chamadiya5403328d91fa
diff --git a/packages/cli/src/repowise/cli/cost_estimator/calibration.py b/packages/cli/src/repowise/cli/cost_estimator/calibration.py
deleted file mode 100644
index b9818f0b0..000000000
--- a/packages/cli/src/repowise/cli/cost_estimator/calibration.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""Backward-compatible re-export; the module lives in core now."""
-
-from repowise.core.cost_estimator.calibration import load_telemetry_averages
-
-__all__ = ["load_telemetry_averages"]
diff --git a/packages/cli/src/repowise/cli/editor_files.py b/packages/cli/src/repowise/cli/editor_files.py
index 3a8ccd96e..5e4499ca2 100644
--- a/packages/cli/src/repowise/cli/editor_files.py
+++ b/packages/cli/src/repowise/cli/editor_files.py
@@ -7,7 +7,6 @@ from pathlib import Path
from repowise.cli.helpers import get_db_url_for_repo, load_config
from repowise.core.generation.editor_files import (
AgentsMdGenerator,
- ClaudeMdGenerator,
EditorFileData,
EditorFileDataFetcher,
)
@@ -69,14 +68,6 @@ async def fetch_editor_file_data(repo_path: Path) -> EditorFileData | None:
await engine.dispose()
-async def write_claude_md(repo_path: Path) -> Path | None:
- """Fetch editor data and write .claude/CLAUDE.md."""
- data = await fetch_editor_file_data(repo_path)
- if data is None:
- return None
- return ClaudeMdGenerator().write(repo_path, data)
-
-
async def write_agents_md(repo_path: Path) -> Path | None:
"""Fetch editor data and write AGENTS.md."""
data = await fetch_editor_file_data(repo_path)
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 0775b2395..d73653725 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -5,7 +5,6 @@ from __future__ import annotations
import asyncio
import json
import os
-import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal, TypeVar
@@ -182,25 +181,6 @@ def get_db_url_for_repo(repo_path: Path) -> str:
return resolve_db_url(repo_path)
-async def _ensure_db_async(repo_path: Path) -> tuple[Any, Any]:
- from repowise.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
# ---------------------------------------------------------------------------
@@ -1138,15 +1118,3 @@ def resolve_command_target(
reason="no workspace nearby",
auto_detected=False,
)
-
-
-def is_interactive_session() -> bool:
- """Best-effort check for an interactive TTY.
-
- Centralized so commands can share one definition; some test runners
- fake stdin in ways that break ``sys.stdin.isatty()``.
- """
- try:
- return sys.stdin.isatty()
- except (AttributeError, ValueError):
- return False
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
index 802a571cc..06e07805e 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
@@ -77,7 +77,8 @@ class FileContext:
repo_commit_counts: dict[str, int] = field(default_factory=dict)
# Per-line blame index produced by the FULL git tier (see
# ``ingestion.git_indexer.function_blame``). ``None`` on ESSENTIAL
- # tier until ``backfill_blame()`` runs; function-level biomarkers
+ # tier until the FULL-tier backfill (``backfill_full_tier()``) runs;
+ # function-level biomarkers
# must treat ``None`` (and an empty index) as the documented
# "no signal" outcome and emit zero findings.
blame_index: BlameIndex | None = None
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.py b/packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.py
index 87106b475..545a185ef 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.py
@@ -16,7 +16,8 @@ by the FULL git tier:
Tier-aware: when ``ctx.blame_index`` is ``None`` (ESSENTIAL git tier),
or empty, the detector emits zero findings. Function-level no-op is the
-documented "no signal" outcome until ``backfill_blame()`` runs.
+documented "no signal" outcome until the FULL-tier backfill
+(``backfill_full_tier()``) runs.
Severity (calibrated against the 1-year / 2-year age boundaries):
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.py b/packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.py
index 555d8ca11..ffc338a4d 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.py
@@ -7,7 +7,8 @@ project commit shas onto each function's line range and pair churn with
structural complexity.
Tier-aware: ``ctx.blame_index`` is ``None`` on the ESSENTIAL git tier
-(per-line blame is deferred to ``backfill_blame()``); in that case the
+(per-line blame is deferred to the FULL-tier backfill,
+``backfill_full_tier()``); in that case the
detector emits zero findings. The same no-op holds when the engine
could not compute the repo-wide p80 (no functions had a non-zero
mod_count).
diff --git a/packages/core/src/repowise/core/analysis/health/duplication/rabin_karp.py b/packages/core/src/repowise/core/analysis/health/duplication/rabin_karp.py
index 846169f71..7bbd42f0a 100644
--- a/packages/core/src/repowise/core/analysis/health/duplication/rabin_karp.py
+++ b/packages/core/src/repowise/core/analysis/health/duplication/rabin_karp.py
@@ -20,7 +20,7 @@ distributed. Modulus is a large prime under 2**63.
from __future__ import annotations
-from collections.abc import Iterable, Iterator
+from collections.abc import Iterable
from dataclasses import dataclass
from .tokenizer import Token
@@ -107,23 +107,3 @@ def index_by_hash(hashes: Iterable[WindowHash]) -> dict[int, list[WindowHash]]:
for w in hashes:
bucket.setdefault(w.hash_value, []).append(w)
return bucket
-
-
-def iter_collisions(
- bucket: dict[int, list[WindowHash]],
-) -> Iterator[tuple[WindowHash, WindowHash]]:
- """Yield (a, b) pairs of windows that share a hash, a different file
- or non-overlapping windows in the same file. The verifier in
- ``detector.py`` then confirms by token-by-token compare."""
- for windows in bucket.values():
- if len(windows) < 2:
- continue
- for i in range(len(windows)):
- for j in range(i + 1, len(windows)):
- a, b = windows[i], windows[j]
- if a.file_path == b.file_path and abs(a.start_index - b.start_index) < (
- b.end_line - b.start_line + 1
- ):
- # Skip overlapping windows in the same file.
- continue
- yield a, b
diff --git a/packages/core/src/repowise/core/analysis/health/trends.py b/packages/core/src/repowise/core/analysis/health/trends.py
index fd5036b3c..a76ccca07 100644
--- a/packages/core/src/repowise/core/analysis/health/trends.py
+++ b/packages/core/src/repowise/core/analysis/health/trends.py
@@ -27,24 +27,13 @@ from __future__ import annotations
import json
from dataclasses import dataclass, field
from datetime import datetime
-from typing import Any, Protocol
+from typing import Any
DECLINE_THRESHOLD: float = 0.5
DECLINE_LOOKBACK: int = 5 # compare current vs snapshot N positions back
PREDICTED_DECLINE_CONSECUTIVE: int = 3
-class SnapshotLike(Protocol):
- """Minimal shape the trend logic needs from a snapshot row."""
-
- taken_at: datetime
- hotspot_health: float
- average_health: float
- worst_performer_path: str | None
- worst_performer_score: float | None
- per_file_scores_json: str
-
-
@dataclass
class TrendAlert:
"""A single trend signal worth surfacing on the dashboard / CLI."""
diff --git a/packages/core/src/repowise/core/generation/__init__.py b/packages/core/src/repowise/core/generation/__init__.py
index de454b1f9..1cb2d71bc 100644
--- a/packages/core/src/repowise/core/generation/__init__.py
+++ b/packages/core/src/repowise/core/generation/__init__.py
@@ -40,11 +40,9 @@ _EXPORTS = {
"JobSystem": ".job_system",
"GENERATION_LEVELS": ".models",
"ConfidenceDecayResult": ".models",
- "DeadCodeConfig": ".models",
"FreshnessStatus": ".models",
"GeneratedPage": ".models",
"GenerationConfig": ".models",
- "GitConfig": ".models",
"PageType": ".models",
"compute_confidence_decay_with_git": ".models",
"compute_freshness": ".models",
diff --git a/packages/core/src/repowise/core/generation/models.py b/packages/core/src/repowise/core/generation/models.py
index 98144e173..d5bc07c94 100644
--- a/packages/core/src/repowise/core/generation/models.py
+++ b/packages/core/src/repowise/core/generation/models.py
@@ -383,45 +383,6 @@ def compute_source_hash(text: str) -> str:
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
- 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 = True
- 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)
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/generation/selection/selector.py b/packages/core/src/repowise/core/generation/selection/selector.py
index 5fe7118eb..4c3262adc 100644
--- a/packages/core/src/repowise/core/generation/selection/selector.py
+++ b/packages/core/src/repowise/core/generation/selection/selector.py
@@ -8,7 +8,6 @@ emitted.
from __future__ import annotations
-from collections import Counter
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -625,10 +624,3 @@ def summarize_selection(sel: Selection) -> dict[str, int]:
internals.
"""
return sel.counts()
-
-
-def language_summary(parsed_files: list[Any]) -> dict[str, int]:
- """Return ``{language: file_count}`` — used by the init UI to
- describe the repo shape next to the coverage table.
- """
- return dict(Counter(p.file_info.language for p in parsed_files))
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/backfill.py b/packages/core/src/repowise/core/ingestion/git_indexer/backfill.py
index 104da7bdf..3ed784bf8 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/backfill.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/backfill.py
@@ -29,14 +29,10 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
-__all__ = ["BACKFILL_BLAME_PHASE", "BACKFILL_PHASE", "backfill_blame", "backfill_full_tier"]
+__all__ = ["BACKFILL_PHASE", "backfill_full_tier"]
# Phase name used for the JobStore record so resume detection can find it.
BACKFILL_PHASE = "git.backfill"
-# Sub-phase covering per-line blame index population only. Reuses the FULL
-# orchestration; named so callers can distinguish a blame-only backfill from
-# a full tier promotion in logs and job records.
-BACKFILL_BLAME_PHASE = "git.backfill.blame"
async def backfill_full_tier(
@@ -83,51 +79,3 @@ async def backfill_full_tier(
files=summary.files_indexed,
)
return summary, results
-
-
-async def backfill_blame(
- indexer: GitIndexer,
- repo_id: str,
- *,
- job_store: JobStore | None = None, # type: ignore[name-defined]
-) -> tuple[GitIndexSummary, list[dict]]:
- """Promote an ESSENTIAL index to include per-line blame indexes.
-
- Thin wrapper around :func:`backfill_full_tier` — the FULL tier already
- builds the :class:`~.function_blame.BlameIndex` inline alongside
- ownership blame, so the same orchestration covers both. The wrapper
- exists so callers (and tests) can express "I just need blame populated"
- intent independent of the larger FULL promotion.
- """
- from repowise.core.persistence._interfaces.job_store import JobState
-
- job_id: str | None = None
- if job_store is not None:
- job = await job_store.create_job(
- repository_id=repo_id,
- phase=BACKFILL_BLAME_PHASE,
- metadata={"tier": GitIndexTier.FULL.value, "scope": "blame"},
- )
- job_id = job.id
- await job_store.update_state(job_id, JobState.RUNNING)
-
- original_tier = indexer.tier
- indexer.tier = GitIndexTier.FULL
- try:
- summary, results = await indexer.index_repo(repo_id)
- except Exception as exc:
- if job_store is not None and job_id is not None:
- await job_store.update_state(job_id, JobState.FAILED, error=str(exc))
- logger.warning("git_blame_backfill_failed", repo_id=repo_id, error=str(exc))
- raise
- finally:
- indexer.tier = original_tier
-
- if job_store is not None and job_id is not None:
- await job_store.update_state(job_id, JobState.COMPLETED, cursor=str(summary.files_indexed))
- logger.info(
- "git_blame_backfill_complete",
- repo_id=repo_id,
- files=summary.files_indexed,
- )
- return summary, results
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/tiers.py b/packages/core/src/repowise/core/ingestion/git_indexer/tiers.py
index 5aa49cfd7..f62c69854 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/tiers.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/tiers.py
@@ -35,8 +35,8 @@ class GitIndexTier(enum.StrEnum):
"""Whether the per-line :class:`BlameIndex` is built per file.
Built inline alongside ownership blame on FULL; ESSENTIAL defers
- until ``backfill_blame()`` runs. Function-level biomarkers no-op
- cleanly when the index is absent.
+ until the FULL-tier backfill (``backfill_full_tier()``) runs.
+ Function-level biomarkers no-op cleanly when the index is absent.
"""
return self is GitIndexTier.FULL
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
index 6983422a0..58f91bfc2 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py
@@ -130,24 +130,3 @@ def path_has_dotnet_scan_skip_dir(path: Path, repo_root: Path) -> bool:
except ValueError:
parts = path.parts
return any(part.casefold() in _DOTNET_SCAN_SKIP_DIRS_CASEFOLDED for part in parts)
-
-
-def find_directory_build_props(start: Path, repo_root: Path) -> list[Path]:
- """Walk from *start* up to *repo_root* collecting Directory.Build.props.
-
- The first match closer to start "wins" but MSBuild semantics merge them
- bottom-up. Repowise just collects them so the resolver can union the
- implicit-using flags and project usings.
- """
- out: list[Path] = []
- cur = start.resolve()
- repo_root = repo_root.resolve()
- while True:
- for name in ("Directory.Build.props", "Directory.Build.targets", "Directory.Packages.props"):
- cand = cur / name
- if cand.exists():
- out.append(cand)
- if cur == repo_root or cur.parent == cur:
- break
- cur = cur.parent
- return out
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
index 64ca16754..653734789 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
@@ -303,11 +303,6 @@ def get_or_build_workspace_info(ctx: "ResolverContext") -> dict[str, dict[str, A
return info
-def get_or_build_workspace_map(ctx: "ResolverContext") -> dict[str, str]:
- """Backward-compat shim — kept for callers that only need name → dir."""
- return {name: info["dir"] for name, info in get_or_build_workspace_info(ctx).items()}
-
-
_PROBE_EXTENSIONS: tuple[str, ...] = (
".ts",
".tsx",
diff --git a/packages/core/src/repowise/core/platform/telemetry.py b/packages/core/src/repowise/core/platform/telemetry.py
index a242b812b..45934f9cd 100644
--- a/packages/core/src/repowise/core/platform/telemetry.py
+++ b/packages/core/src/repowise/core/platform/telemetry.py
@@ -89,20 +89,6 @@ def _env_truthy(name: str) -> bool:
return os.environ.get(name, "").strip().lower() in _TRUTHY
-def is_enabled() -> bool:
- """Return whether telemetry may currently be sent.
-
- Mirrors the CLI's opt-out precedence: ``DO_NOT_TRACK`` and
- ``REPOWISE_TELEMETRY_DISABLED`` are hard offs; otherwise enabled unless the
- user explicitly stored a disable via ``repowise telemetry disable``.
- """
- if _env_truthy("DO_NOT_TRACK"):
- return False
- if _env_truthy("REPOWISE_TELEMETRY_DISABLED"):
- return False
- return _load_state().get("telemetry_enabled") is not False
-
-
def debug_mode() -> bool:
"""``REPOWISE_TELEMETRY_DEBUG`` prints the payload to stderr instead of sending."""
return _env_truthy("REPOWISE_TELEMETRY_DEBUG")
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index cb8d23daa..be1fbb994 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -284,39 +284,6 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = None
return out
-# Question patterns where narrative wiki context wins over symbol-body slicing.
-# Used to suppress "use get_symbol" hints — those questions need surrounding prose.
-_EXPLAIN_TOKENS = (
- "explain",
- "why ",
- "why is",
- "why does",
- "why was",
- "how does",
- "how do",
- "how is",
- "how are",
- "what is the relationship",
- "describe",
- "walk me through",
- "tell me about",
- "purpose of",
-)
-
-
-def is_explanation_question(question: str | None) -> bool:
- """True if the question reads like 'explain X', not 'find X'.
-
- Used as a guard before any hint that would push the agent toward
- symbol-level (narrower) retrieval. Conservative by design: any explanation
- cue suppresses the hint.
- """
- if not question:
- return False
- q = question.strip().lower()
- return any(tok in q for tok in _EXPLAIN_TOKENS)
-
-
def build_meta(
*,
timing_ms: float | None = None,
diff --git a/packages/server/src/repowise/server/search_helpers.py b/packages/server/src/repowise/server/search_helpers.py
index f6bcb882e..c97137b93 100644
--- a/packages/server/src/repowise/server/search_helpers.py
+++ b/packages/server/src/repowise/server/search_helpers.py
@@ -155,15 +155,6 @@ async def resolve_repo_vector_store(
return store
-async def resolve_workspace_vector_store(app, repo_id: str) -> Any | None:
- """Backward-compatible app wrapper for repo vector-store resolution.
-
- Search callers do not create a new index, so ``None`` is returned when the
- repository has no persisted LanceDB directory yet.
- """
- return await resolve_repo_vector_store(app.state, repo_id)
-
-
def _resolve_embedder_from_state(app_state):
"""Pull the same embedder the primary vector store was built with.
diff --git a/packages/ui/src/c4/theme/theme-variables.ts b/packages/ui/src/c4/theme/theme-variables.ts
index 433a997ea..b8ae041e6 100644
--- a/packages/ui/src/c4/theme/theme-variables.ts
+++ b/packages/ui/src/c4/theme/theme-variables.ts
@@ -87,11 +87,6 @@ export const THEME = {
},
} as const;
-/** Edge color for a relation type, falling back to the muted default. */
-export function edgeColor(edgeType: string): string {
- return THEME.edge[edgeType] ?? "var(--color-text-tertiary)";
-}
-
export const KEYFRAMES = {
accentPulse: `
@keyframes accentPulse {
diff --git a/packages/vscode/src/core/gitApi.ts b/packages/vscode/src/core/gitApi.ts
index b0144a31d..b5eab464b 100644
--- a/packages/vscode/src/core/gitApi.ts
+++ b/packages/vscode/src/core/gitApi.ts
@@ -156,30 +156,6 @@ export function commitsMatch(a: string, b: string): boolean {
return shorter.length > 0 && longer.startsWith(shorter);
}
-/**
- * Invokes `cb` when the repository's HEAD name or commit changes. Returns a
- * disposable, or a no-op disposable when git is unavailable. The underlying
- * `state.onDidChange` fires on any repository change, so we filter to HEAD
- * transitions to avoid waking callers on unrelated working-tree events.
- */
-export async function onDidChangeHead(
- repoRoot: string,
- cb: () => void,
-): Promise<vscode.Disposable> {
- const repo = await getRepository(repoRoot);
- if (!repo) return { dispose: () => {} };
- let lastName = repo.state.HEAD?.name;
- let lastCommit = repo.state.HEAD?.commit;
- return repo.state.onDidChange(() => {
- const name = repo.state.HEAD?.name;
- const commit = repo.state.HEAD?.commit;
- if (name === lastName && commit === lastCommit) return;
- lastName = name;
- lastCommit = commit;
- cb();
- });
-}
-
/** Uncommitted changes split by staging state; paths are repo-relative POSIX. */
export interface ChangedFiles {
/** Staged (index) paths. */
@@ -249,7 +225,7 @@ export async function getBranchChangedFiles(
/**
* Invokes `cb` on any repository state change (staging, working-tree edits, HEAD
- * moves). Unlike {@link onDidChangeHead} this does not filter, so callers must
+ * moves). This does not filter to a specific change kind, so callers must
* debounce. Returns a no-op disposable when git is unavailable.
*/
export async function onDidChangeRepoState(
diff --git a/packages/vscode/src/features/trees/shared.ts b/packages/vscode/src/features/trees/shared.ts
index d70332442..4f506ab9a 100644
--- a/packages/vscode/src/features/trees/shared.ts
+++ b/packages/vscode/src/features/trees/shared.ts
@@ -249,8 +249,3 @@ export function humanizeType(type: string): string {
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join(" ");
}
-
-/** Truncates to `max` characters, appending an ellipsis when cut. */
-export function truncate(text: string, max = 80): string {
- return text.length > max ? `${text.slice(0, max - 1)}…` : text;
-}
diff --git a/packages/web/README.md b/packages/web/README.md
index 2bc8ca6c6..6e4d6d838 100644
--- a/packages/web/README.md
+++ b/packages/web/README.md
@@ -149,7 +149,7 @@ Organized by domain — `repos.ts`, `pages.ts`, `graph.ts`, `search.ts`, `symbol
| Hook | Purpose |
|------|---------|
-| `useRepo`, `useRepos` | SWR wrappers for repository data with 30s refresh |
+| `useRepo` | SWR wrapper for repository data with 30s refresh |
| `usePage`, `usePageVersions` | Page content and version history |
| `useSearch` | Debounced search (300ms, min 2 chars) |
| `useGraph` (+ variants) | Graph data with stable caching (no revalidate on focus) |
diff --git a/packages/web/src/components/c4/c4-detail-panel-host.tsx b/packages/web/src/components/c4/c4-detail-panel-host.tsx
deleted file mode 100644
index f78fb88b1..000000000
--- a/packages/web/src/components/c4/c4-detail-panel-host.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-"use client";
-
-/**
- * Web-side wrapper around <C4DetailPanel> that fetches per-selection
- * docs + module health and feeds them into the shared UI panel.
- *
- * The shared panel lives in @repowise-dev/ui/c4 — no fetch logic. This
- * host knits SWR data into the panel's prop shape.
- */
-
-import { useRouter } from "next/navigation";
-import { C4DetailPanel, type C4NodeData } from "@repowise-dev/ui/c4";
-import { ChatMarkdown } from "@repowise-dev/ui/chat/chat-markdown";
-import {
- useC4SelectionContext,
-} from "@/lib/hooks/use-c4-context";
-
-interface C4DetailPanelHostProps {
- repoId: string;
- data: C4NodeData;
- pageIdByPath: ReadonlyMap<string, string>;
- onClose: () => void;
- onDrillIn?: ((containerId: string) => void) | undefined;
-}
-
-function selectionPath(data: C4NodeData): string | null {
- if (data.kind === "container") return data.container.path;
- if (data.kind === "component") return data.component.path;
- return null;
-}
-
-export function C4DetailPanelHost({
- repoId,
- data,
- pageIdByPath,
- onClose,
- onDrillIn,
-}: C4DetailPanelHostProps) {
- const router = useRouter();
- const path = selectionPath(data);
- const pageId = path ? pageIdByPath.get(path) ?? null : null;
-
- const { health, page, isLoading } = useC4SelectionContext(repoId, path, pageId);
-
- const doc = page
- ? {
- title: page.title,
- excerpt: page.content.split("\n").slice(0, 6).join("\n"),
- href: `/repos/${repoId}/docs?page=${encodeURIComponent(page.id)}`,
- }
- : null;
-
- const contributors =
- health?.owners?.slice(0, 5).map((o) => ({ name: o.name, files: o.file_count, pct: o.pct })) ?? [];
-
- return (
- <C4DetailPanel
- data={data}
- loading={isLoading}
- doc={doc}
- docContent={page ? (page.content.length > 300 ? page.content.slice(0, 300).trimEnd() + "..." : page.content) : null}
- renderDoc={(content) => <ChatMarkdown content={content} />}
- health={
- health
- ? {
- health_score: health.health_score,
- hotspot_count: health.hotspot_count,
- dead_code_count: health.dead_code_count,
- doc_coverage_pct: health.doc_coverage_pct,
- primary_owner: health.primary_owner,
- primary_owner_pct: health.primary_owner_pct,
- contributor_count: health.contributor_count,
- is_silo: health.is_silo,
- }
- : null
- }
- contributors={contributors}
- onClose={onClose}
- onDrillIn={onDrillIn}
- onOpenInGraph={path ? (p) => router.push(`/repos/${repoId}/architecture?view=graph&node=${encodeURIComponent(p)}`) : undefined}
- onOpenDoc={(href) => router.push(href)}
- />
- );
-}
diff --git a/packages/web/src/components/dead-code/finding-row.tsx b/packages/web/src/components/dead-code/finding-row.tsx
deleted file mode 100644
index 4049314a7..000000000
--- a/packages/web/src/components/dead-code/finding-row.tsx
+++ /dev/null
@@ -1,219 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { toast } from "sonner";
-import { GitBranch, Code2 } from "lucide-react";
-import { Button } from "@repowise-dev/ui/ui/button";
-import { Badge } from "@repowise-dev/ui/ui/badge";
-import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";
-import { RowActions } from "@repowise-dev/ui/shared/row-actions";
-import { formatConfidence } from "@repowise-dev/ui/lib/format";
-import { patchDeadCodeFinding } from "@/lib/api/dead-code";
-import { cn } from "@/lib/utils/cn";
-import type { DeadCodeFindingResponse } from "@/lib/api/types";
-import type { DeadCodeStatus } from "@repowise-dev/types/dead-code";
-
-const STATUS_LABELS: Record<string, { title: string; description: string; confirmLabel: string; destructive: boolean }> = {
- resolved: {
- title: "Resolve finding?",
- description: "Mark this finding as resolved. You can undo from the toast.",
- confirmLabel: "Resolve",
- destructive: false,
- },
- acknowledged: {
- title: "Acknowledge finding?",
- description: "Mark this finding as acknowledged.",
- confirmLabel: "Acknowledge",
- destructive: false,
- },
- false_positive: {
- title: "Mark as false positive?",
- description: "This finding will be excluded from future analyses. You can undo from the toast.",
- confirmLabel: "Mark FP",
- destructive: true,
- },
-};
-
-interface FindingRowProps {
- finding: DeadCodeFindingResponse;
- repoId: string;
- 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, repoId, selected, onToggle, onUpdate }: FindingRowProps) {
- const [pending, setPending] = useState(false);
- const [confirmStatus, setConfirmStatus] = useState<DeadCodeStatus | null>(null);
-
- const previousStatus = finding.status;
-
- const applyPatch = async (status: DeadCodeStatus) => {
- setPending(true);
- try {
- const updated = await patchDeadCodeFinding(finding.id, { status });
- onUpdate(updated);
- setConfirmStatus(null);
- toast.success(`Finding ${status.replace(/_/g, " ")}`, {
- action: {
- label: "Undo",
- onClick: async () => {
- try {
- const reverted = await patchDeadCodeFinding(finding.id, { status: previousStatus });
- onUpdate(reverted);
- } catch (err) {
- toast.error(
- err instanceof Error ? `Couldn't undo: ${err.message}` : "Couldn't undo",
- );
- }
- },
- },
- duration: 6000,
- });
- } catch (err) {
- toast.error(
- err instanceof Error ? `Couldn't update finding: ${err.message}` : "Couldn't update finding",
- );
- } finally {
- setPending(false);
- }
- };
-
- const requestPatch = (status: DeadCodeStatus) => setConfirmStatus(status);
-
- const confirmConfig = confirmStatus ? STATUS_LABELS[confirmStatus] : null;
-
- 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)}
- aria-label={`Select finding ${finding.file_path}`}
- className="rounded border-[var(--color-border-default)]"
- />
- </td>
- <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] min-w-[200px] max-w-[480px]">
- <span className="truncate block" title={finding.file_path}>{finding.file_path}</span>
- {finding.symbol_name && (
- <span className="block truncate text-[var(--color-text-tertiary)]" title={finding.symbol_name}>{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)] hidden md:table-cell">
- {finding.primary_owner ?? "—"}
- </td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-tertiary)] tabular-nums hidden md:table-cell">
- {finding.lines}
- </td>
- <td className="px-4 py-2.5 hidden sm:table-cell">
- {finding.safe_to_delete ? (
- <Badge variant="fresh">Candidate</Badge>
- ) : (
- <Badge
- variant="default"
- title={
- finding.risk_factors && finding.risk_factors.length > 0
- ? `Runtime-load risk (${finding.risk_factors.join(", ")}) — verify it isn't loaded outside static imports before deleting`
- : "Lower confidence — verify before deleting"
- }
- >
- Review
- </Badge>
- )}
- </td>
- <td className="px-4 py-2.5 hidden sm:table-cell">
- <span
- className={cn(
- "inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium",
- STATUS_COLORS[finding.status] ?? STATUS_COLORS.open,
- )}
- >
- {finding.status.replace(/_/g, " ")}
- </span>
- </td>
- <td className="px-4 py-2.5">
- <div className="flex items-center gap-1 flex-wrap justify-end">
- <RowActions
- actions={[
- { icon: GitBranch, label: "Graph", href: `/repos/${repoId}/architecture?view=graph&node=${encodeURIComponent(finding.file_path)}` },
- ...(finding.symbol_name ? [{ icon: Code2, label: "Symbol", href: `/repos/${repoId}/architecture?view=symbols` }] : []),
- ]}
- />
- {finding.status === "open" && (
- <div className="flex items-center gap-1 flex-wrap justify-end">
- <Button
- size="sm"
- variant="ghost"
- disabled={pending}
- onClick={() => requestPatch("resolved")}
- className="h-6 px-2 text-xs text-green-500 hover:text-green-400"
- aria-label={`Resolve ${finding.file_path}`}
- >
- Resolve
- </Button>
- <Button
- size="sm"
- variant="ghost"
- disabled={pending}
- onClick={() => requestPatch("acknowledged")}
- className="h-6 px-2 text-xs"
- aria-label={`Acknowledge ${finding.file_path}`}
- >
- Ack
- </Button>
- <Button
- size="sm"
- variant="ghost"
- disabled={pending}
- onClick={() => requestPatch("false_positive")}
- className="h-6 px-2 text-xs text-[var(--color-text-tertiary)]"
- aria-label={`Mark ${finding.file_path} as false positive`}
- >
- FP
- </Button>
- </div>
- )}
- </div>
- </td>
- {confirmConfig && (
- <ConfirmDialog
- open={confirmStatus !== null}
- onOpenChange={(o) => !o && setConfirmStatus(null)}
- title={confirmConfig.title}
- description={confirmConfig.description}
- confirmLabel={confirmConfig.confirmLabel}
- destructive={confirmConfig.destructive}
- loading={pending}
- onConfirm={() => applyPatch(confirmStatus!)}
- />
- )}
- </tr>
- );
-}
diff --git a/packages/web/src/components/health/health-risks-panel.tsx b/packages/web/src/components/health/health-risks-panel.tsx
deleted file mode 100644
index 4ae766484..000000000
--- a/packages/web/src/components/health/health-risks-panel.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-"use client";
-
-import Link from "next/link";
-import useSWR from "swr";
-import { HealthBadge } from "@repowise-dev/ui/health";
-import {
- getHealthOverview,
- type HealthOverviewResponse,
-} from "@/lib/api/code-health";
-
-export interface HealthRisksPanelProps {
- repoId: string;
- title?: string;
- limit?: number;
-}
-
-/** Inline health-risk sidecar: lowest-scoring files with badges.
- * Page-level only — does not modify any shared list/table component. */
-export function HealthRisksPanel({
- repoId,
- title = "Health risks",
- limit = 6,
-}: HealthRisksPanelProps) {
- const { data } = useSWR<HealthOverviewResponse>(
- `health-overview-panel:${repoId}`,
- () => getHealthOverview(repoId, limit),
- { revalidateOnFocus: false },
- );
- if (!data || data.files.length === 0) return null;
- const rows = [...data.files]
- .sort((a, b) => a.score - b.score)
- .slice(0, limit);
- return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 space-y-2">
- <div className="flex items-center justify-between text-xs">
- <span className="font-semibold text-[var(--color-text-primary)]">
- {title}
- </span>
- <Link
- href={`/repos/${repoId}/code-health`}
- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
- >
- See all →
- </Link>
- </div>
- <ul className="space-y-1.5">
- {rows.map((f) => (
- <li
- key={f.file_path}
- className="flex items-center gap-2 text-xs"
- >
- <HealthBadge score={f.score} />
- <span
- className="font-mono truncate text-[var(--color-text-secondary)]"
- title={f.file_path}
- >
- {f.file_path}
- </span>
- </li>
- ))}
- </ul>
- </div>
- );
-}
diff --git a/packages/web/src/components/wiki/human-notes.tsx b/packages/web/src/components/wiki/human-notes.tsx
deleted file mode 100644
index c53d86e96..000000000
--- a/packages/web/src/components/wiki/human-notes.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-"use client";
-
-import { toast } from "sonner";
-import { HumanNotes as HumanNotesShell } from "@repowise-dev/ui/wiki/human-notes";
-import { updatePageNotes } from "@/lib/api/pages";
-import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
-
-/**
- * Web data wrapper around the presentational ``HumanNotes`` ui shell — owns the
- * persistence call and toast feedback. Notes survive regeneration server-side.
- */
-export function HumanNotes({
- pageId,
- initialNotes,
-}: {
- pageId: string;
- initialNotes: string | null;
-}) {
- return (
- <HumanNotesShell
- initialNotes={initialNotes}
- onSave={async (value) => {
- try {
- const updated = await updatePageNotes(pageId, value);
- toast.success(updated.human_notes ? "Note saved" : "Note removed");
- return updated.human_notes;
- } catch (e) {
- toast.error("Couldn't save note", {
- description: toFriendlyMessage(e),
- });
- throw e;
- }
- }}
- />
- );
-}
diff --git a/packages/web/src/components/wiki/regenerate-button.tsx b/packages/web/src/components/wiki/regenerate-button.tsx
deleted file mode 100644
index 0c7b62a75..000000000
--- a/packages/web/src/components/wiki/regenerate-button.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { toast } from "sonner";
-import useSWR, { useSWRConfig } from "swr";
-import { RegenerateButton as RegenerateButtonShell } from "@repowise-dev/ui/wiki/regenerate-button";
-import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";
-import { formatTokens } from "@repowise-dev/ui/lib/format";
-import { getPageById, regeneratePage } from "@/lib/api/pages";
-import { GenerationProgressWrapper as GenerationProgress } from "@/components/jobs/generation-progress-wrapper";
-import { WIKI_STYLES } from "@repowise-dev/types";
-import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
-
-interface Props {
- pageId: string;
- // repoId retained for parent compat; not currently consumed in the wrapper.
- repoId: string;
-}
-
-export function RegenerateButtonWrapper({ pageId }: Props) {
- const { mutate } = useSWRConfig();
- const [loading, setLoading] = useState(false);
- const [jobId, setJobId] = useState<string | null>(null);
- const [confirmOpen, setConfirmOpen] = useState(false);
- // Empty string = use the repo's default style; otherwise a per-page override.
- const [styleOverride, setStyleOverride] = useState("");
-
- // Token history for the cost estimate in the confirm dialog. Same SWR key
- // the wiki page uses, so this is usually already cached.
- const { data: page } = useSWR(
- `/api/pages/lookup?page_id=${pageId}`,
- () => getPageById(pageId),
- { revalidateOnFocus: false },
- );
-
- const estimate =
- page && (page.input_tokens > 0 || page.output_tokens > 0)
- ? `Based on the last generation this will spend roughly ${formatTokens(
- page.input_tokens,
- )} input + ${formatTokens(page.output_tokens)} output tokens` +
- (page.provider_name ? ` on ${page.provider_name}` : "") +
- "."
- : "Token cost depends on the page's sources; no previous generation is recorded to estimate from.";
-
- async function handleRegenerate() {
- setConfirmOpen(false);
- setLoading(true);
- try {
- const result = await regeneratePage(pageId, styleOverride || undefined);
- setJobId(result.job_id);
- toast.info("Regeneration queued");
- } catch (e) {
- toast.error("Failed to queue regeneration", {
- description: toFriendlyMessage(e),
- });
- } finally {
- setLoading(false);
- }
- }
-
- function handleDone() {
- // Revalidate the page data so confidence badge and content refresh
- void mutate(`/api/pages/lookup?page_id=${pageId}`);
- setJobId(null);
- }
-
- const styleNote = styleOverride
- ? ` This page will be regenerated in the "${styleOverride}" style (overriding the repo default).`
- : "";
-
- return (
- <>
- <div className="flex items-center gap-2">
- <select
- aria-label="Regenerate in style"
- value={styleOverride}
- onChange={(e) => setStyleOverride(e.target.value)}
- className="h-8 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-default)] px-2 text-xs text-[var(--color-text-secondary)]"
- >
- <option value="">Repo style</option>
- {WIKI_STYLES.map((s) => (
- <option key={s.id} value={s.id}>
- {s.label}
- </option>
- ))}
- </select>
- <RegenerateButtonShell
- onRegenerate={() => setConfirmOpen(true)}
- isLoading={loading}
- isInProgress={!!jobId}
- onDialogClose={() => setJobId(null)}
- jobSlot={jobId ? <GenerationProgress jobId={jobId} onDone={handleDone} /> : null}
- />
- </div>
- <ConfirmDialog
- open={confirmOpen}
- onOpenChange={setConfirmOpen}
- title="Regenerate this page?"
- description={`The current content is archived as a version and replaced.${styleNote} ${estimate}`}
- confirmLabel="Regenerate"
- destructive={false}
- loading={loading}
- onConfirm={() => void handleRegenerate()}
- />
- </>
- );
-}
diff --git a/packages/web/src/lib/hooks/use-c4.ts b/packages/web/src/lib/hooks/use-c4.ts
deleted file mode 100644
index bd8dfbe3e..000000000
--- a/packages/web/src/lib/hooks/use-c4.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-"use client";
-
-/**
- * SWR-backed hooks for the C4 endpoints. One hook per level so consumers
- * can opt into only what they render — L1 view doesn't need to fetch L3.
- */
-
-import useSWR from "swr";
-import type { C4L1, C4L2, C4L3 } from "@repowise-dev/ui/c4";
-import { getC4L1, getC4L2, getC4L3 } from "@/lib/api/c4";
-
-const SWR_OPTS = { revalidateOnFocus: false, revalidateOnReconnect: false };
-
-export function useC4L1(repoId: string | null) {
- const { data, error, isLoading } = useSWR<C4L1>(
- repoId ? `c4-l1:${repoId}` : null,
- () => getC4L1(repoId!),
- SWR_OPTS,
- );
- return { view: data ?? null, error: (error as Error | undefined) ?? null, isLoading };
-}
-
-export function useC4L2(repoId: string | null) {
- const { data, error, isLoading } = useSWR<C4L2>(
- repoId ? `c4-l2:${repoId}` : null,
- () => getC4L2(repoId!),
- SWR_OPTS,
- );
- return { view: data ?? null, error: (error as Error | undefined) ?? null, isLoading };
-}
-
-export function useC4L3(repoId: string | null, containerId: string | null) {
- const { data, error, isLoading } = useSWR<C4L3>(
- repoId && containerId ? `c4-l3:${repoId}:${containerId}` : null,
- () => getC4L3(repoId!, containerId!),
- SWR_OPTS,
- );
- return { view: data ?? null, error: (error as Error | undefined) ?? null, isLoading };
-}
diff --git a/packages/web/src/lib/hooks/use-graph.ts b/packages/web/src/lib/hooks/use-graph.ts
index e13cea10d..c9f959991 100644
--- a/packages/web/src/lib/hooks/use-graph.ts
+++ b/packages/web/src/lib/hooks/use-graph.ts
@@ -9,7 +9,6 @@ import {
getCommunityDetail,
getCommunitySlice,
getDeadCodeGraph,
- getEgoGraph,
getExecutionFlows,
getGraph,
getGraphMetrics,
@@ -23,7 +22,6 @@ import type {
CommunitySliceResponse,
CommunitySummaryItem,
DeadCodeGraphResponse,
- EgoGraphResponse,
ExecutionFlowsResponse,
GraphExportResponse,
GraphMetricsResponse,
@@ -51,15 +49,6 @@ export function useModuleGraph(repoId: string | null) {
return { graph: data, error, isLoading };
}
-export function useEgoGraph(repoId: string | null, nodeId: string | null, hops = 2) {
- const { data, error, isLoading } = useSWR<EgoGraphResponse>(
- repoId && nodeId ? `ego-graph:${repoId}:${nodeId}:${hops}` : null,
- () => getEgoGraph(repoId!, nodeId!, hops),
- SWR_OPTS,
- );
- return { graph: data, error, isLoading };
-}
-
/**
* Community super-graph for the constellation (radial Knowledge Graph) scope.
* Conditional SWR: only fetched when a repoId is given (the wrapper gates it
diff --git a/packages/web/src/lib/hooks/use-repo.ts b/packages/web/src/lib/hooks/use-repo.ts
index 71c2b9def..27f8b709c 100644
--- a/packages/web/src/lib/hooks/use-repo.ts
+++ b/packages/web/src/lib/hooks/use-repo.ts
@@ -1,7 +1,7 @@
"use client";
import useSWR from "swr";
-import { listRepos, getRepo } from "@/lib/api/repos";
+import { getRepo } from "@/lib/api/repos";
import { ApiClientError } from "@/lib/api/client";
import type { RepoResponse } from "@/lib/api/types";
@@ -21,15 +21,6 @@ function skipRetryOn404(
);
}
-export function useRepos() {
- const { data, error, isLoading, mutate } = useSWR<RepoResponse[]>(
- "repos",
- () => listRepos(),
- { refreshInterval: 30_000, onErrorRetry: skipRetryOn404 },
- );
- return { repos: data ?? [], error, isLoading, mutate };
-}
-
export function useRepo(repoId: string | null) {
const { data, error, isLoading, mutate } = useSWR<RepoResponse>(
repoId ? `repo:${repoId}` : null,
diff --git a/scripts/extract-demo-data.py b/scripts/extract-demo-data.py
deleted file mode 100644
index ab24f0f07..000000000
--- a/scripts/extract-demo-data.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/usr/bin/env python3
-"""Extract data from fastapi/.repowise/wiki.db into static JSON files for the hosted frontend demo."""
-
-import json
-import os
-import sqlite3
-from collections import defaultdict
-from pathlib import Path
-
-DB_PATH = Path(__file__).parent.parent / "fastapi" / ".repowise" / "wiki.db"
-OUT_DIR = Path(__file__).parent.parent / "repowise-hosted-frontend" / "public" / "data" / "fastapi"
-REPO_ID = "4912f43143cb4cb881ee805268de797c"
-
-
-def write_json(filename: str, data):
- path = OUT_DIR / filename
- with open(path, "w") as f:
- json.dump(data, f, separators=(",", ":"), default=str)
- size_kb = path.stat().st_size / 1024
- print(f" {filename}: {size_kb:.1f} KB")
-
-
-def extract_repo(cur):
- row = cur.execute(
- "SELECT id, name, url, local_path, default_branch, head_commit, settings_json, created_at, updated_at FROM repositories WHERE id = ?",
- (REPO_ID,),
- ).fetchone()
- if not row:
- raise RuntimeError(f"Repo {REPO_ID} not found")
- repo = {
- "id": row[0],
- "name": row[1] or "fastapi",
- "url": row[2] or "https://github.com/tiangolo/fastapi",
- "local_path": row[3],
- "default_branch": row[4],
- "head_commit": row[5],
- "settings": json.loads(row[6]) if row[6] else {},
- "created_at": row[7],
- "updated_at": row[8],
- }
- write_json("repo.json", repo)
- return repo
-
-
-def extract_stats(cur):
- file_count = cur.execute(
- "SELECT COUNT(*) FROM graph_nodes WHERE repository_id = ? AND node_type = 'file'", (REPO_ID,)
- ).fetchone()[0]
- symbol_count = cur.execute(
- "SELECT COUNT(*) FROM wiki_symbols WHERE repository_id = ?", (REPO_ID,)
- ).fetchone()[0]
- entry_point_count = cur.execute(
- "SELECT COUNT(*) FROM graph_nodes WHERE repository_id = ? AND is_entry_point = 1", (REPO_ID,)
- ).fetchone()[0]
-
- total_pages = cur.execute(
- "SELECT COUNT(*) FROM wiki_pages WHERE repository_id = ?", (REPO_ID,)
- ).fetchone()[0]
- fresh_pages = cur.execute(
- "SELECT COUNT(*) FROM wiki_pages WHERE repository_id = ? AND freshness_status = 'fresh'", (REPO_ID,)
- ).fetchone()[0]
- doc_coverage = round((fresh_pages / total_pages * 100) if total_pages else 0, 1)
- freshness_score = round(
- cur.execute(
- "SELECT AVG(confidence) FROM wiki_pages WHERE repository_id = ?", (REPO_ID,)
- ).fetchone()[0]
- or 0,
- 2,
- )
- dead_export_count = cur.execute(
- "SELECT COUNT(*) FROM dead_code_findings WHERE repository_id = ? AND kind = 'unused_export'", (REPO_ID,)
- ).fetchone()[0]
-
- stats = {
- "file_count": file_count,
- "symbol_count": symbol_count,
- "entry_point_count": entry_point_count,
- "doc_coverage_pct": doc_coverage,
- "freshness_score": freshness_score,
- "dead_export_count": dead_export_count,
- }
- write_json("stats.json", stats)
-
-
-def extract_pages(cur):
- rows = cur.execute(
- """SELECT id, repository_id, page_type, title, content, target_path, source_hash,
- model_name, provider_name, input_tokens, output_tokens, cached_tokens,
- generation_level, version, confidence, freshness_status, metadata_json,
- created_at, updated_at
- FROM wiki_pages WHERE repository_id = ?
- ORDER BY target_path""",
- (REPO_ID,),
- ).fetchall()
-
- pages_index = []
- pages_content = []
- for r in rows:
- meta = json.loads(r[16]) if r[16] else {}
- page = {
- "id": r[0],
- "repository_id": r[1],
- "page_type": r[2],
- "title": r[3],
- "content": r[4],
- "target_path": r[5],
- "source_hash": r[6],
- "model_name": r[7],
- "provider_name": r[8],
- "input_tokens": r[9],
- "output_tokens": r[10],
- "cached_tokens": r[11],
- "generation_level": r[12],
- "version": r[13],
- "confidence": r[14],
- "freshness_status": r[15],
- "metadata": meta,
- "created_at": r[17],
- "updated_at": r[18],
- }
- pages_content.append(page)
- # Index entry: same but without content
- idx = {k: v for k, v in page.items() if k != "content"}
- pages_index.append(idx)
-
- write_json("pages-index.json", pages_index)
- write_json("pages-content.json", pages_content)
- print(f" -> {len(pages_content)} pages extracted")
-
-
-def extract_graph(cur):
- # Get set of documented paths
- doc_paths = set()
- for (tp,) in cur.execute(
- "SELECT target_path FROM wiki_pages WHERE repository_id = ?", (REPO_ID,)
- ):
- doc_paths.add(tp)
-
- nodes = []
- for r in cur.execute(
- """SELECT node_id, node_type, language, symbol_count, pagerank, betweenness,
- community_id, is_test, is_entry_point
- FROM graph_nodes WHERE repository_id = ?""",
- (REPO_ID,),
- ):
- nodes.append({
- "node_id": r[0],
- "node_type": r[1],
- "language": r[2],
- "symbol_count": r[3],
- "pagerank": round(r[4], 6),
- "betweenness": round(r[5], 6),
- "community_id": r[6],
- "is_test": bool(r[7]),
- "is_entry_point": bool(r[8]),
- "has_doc": r[0] in doc_paths,
- })
-
- links = []
- for r in cur.execute(
- """SELECT source_node_id, target_node_id, imported_names_json
- FROM graph_edges WHERE repository_id = ?""",
- (REPO_ID,),
- ):
- names = json.loads(r[2]) if r[2] else []
- links.append({
- "source": r[0],
- "target": r[1],
- "imported_names": names,
- })
-
- graph = {"nodes": nodes, "links": links}
- write_json("graph.json", graph)
- print(f" -> {len(nodes)} nodes, {len(links)} edges")
-
-
-def extract_symbols(cur):
- rows = cur.execute(
- """SELECT id, repository_id, file_path, symbol_id, name, qualified_name, kind,
- signature, start_line, end_line, docstring, visibility, is_async,
- complexity_estimate, language, parent_name
- FROM wiki_symbols WHERE repository_id = ?
- ORDER BY file_path, start_line""",
- (REPO_ID,),
- ).fetchall()
-
- symbols = []
- for r in rows:
- symbols.append({
- "id": r[0],
- "repository_id": r[1],
- "file_path": r[2],
- "symbol_id": r[3],
- "name": r[4],
- "qualified_name": r[5],
- "kind": r[6],
- "signature": r[7],
- "start_line": r[8],
- "end_line": r[9],
- "docstring": r[10],
- "visibility": r[11],
- "is_async": bool(r[12]),
- "complexity_estimate": r[13],
- "language": r[14],
- "parent_name": r[15],
- })
-
- write_json("symbols.json", symbols)
- print(f" -> {len(symbols)} symbols")
-
-
-def extract_hotspots(cur):
- rows = cur.execute(
- """SELECT file_path, commit_count_90d, commit_count_30d, churn_percentile,
- primary_owner_name, is_hotspot, is_stable, bus_factor, contributor_count,
- lines_added_90d, lines_deleted_90d, avg_commit_size, commit_categories_json
- FROM git_metadata WHERE repository_id = ?
- ORDER BY churn_percentile DESC
- LIMIT 100""",
- (REPO_ID,),
- ).fetchall()
-
- hotspots = []
- for r in rows:
- cats = json.loads(r[12]) if r[12] else {}
- hotspots.append({
- "file_path": r[0],
- "commit_count_90d": r[1],
- "commit_count_30d": r[2],
- "churn_percentile": round(r[3], 4),
- "primary_owner": r[4],
- "is_hotspot": bool(r[5]),
- "is_stable": bool(r[6]),
- "bus_factor": r[7],
- "contributor_count": r[8],
- "lines_added_90d": r[9],
- "lines_deleted_90d": r[10],
- "avg_commit_size": round(r[11], 1),
- "commit_categories": cats,
- })
-
- write_json("hotspots.json", hotspots)
- print(f" -> {len(hotspots)} hotspots")
-
-
-def extract_git_summary(cur):
- total_files = cur.execute(
- "SELECT COUNT(*) FROM git_metadata WHERE repository_id = ?", (REPO_ID,)
- ).fetchone()[0]
- hotspot_count = cur.execute(
- "SELECT COUNT(*) FROM git_metadata WHERE repository_id = ? AND is_hotspot = 1", (REPO_ID,)
- ).fetchone()[0]
- stable_count = cur.execute(
- "SELECT COUNT(*) FROM git_metadata WHERE repository_id = ? AND is_stable = 1", (REPO_ID,)
- ).fetchone()[0]
- avg_churn = cur.execute(
- "SELECT AVG(churn_percentile) FROM git_metadata WHERE repository_id = ?", (REPO_ID,)
- ).fetchone()[0] or 0
-
- # Top owners
- owner_counts = defaultdict(int)
- for (owner,) in cur.execute(
- "SELECT primary_owner_name FROM git_metadata WHERE repository_id = ? AND primary_owner_name IS NOT NULL",
- (REPO_ID,),
- ):
- owner_counts[owner] += 1
-
- top_owners = sorted(owner_counts.items(), key=lambda x: x[1], reverse=True)[:10]
- top_owners_list = [
- {"name": name, "file_count": count, "pct": round(count / total_files * 100, 1)}
- for name, count in top_owners
- ]
-
- summary = {
- "total_files": total_files,
- "hotspot_count": hotspot_count,
- "stable_count": stable_count,
- "average_churn_percentile": round(avg_churn, 2),
- "top_owners": top_owners_list,
- }
- write_json("git-summary.json", summary)
-
-
-def extract_ownership(cur):
- # Module-level ownership: group by top-level directory
- rows = cur.execute(
- """SELECT file_path, primary_owner_name, primary_owner_commit_pct, bus_factor
- FROM git_metadata WHERE repository_id = ?""",
- (REPO_ID,),
- ).fetchall()
-
- module_map = defaultdict(lambda: {"files": [], "owners": defaultdict(int)})
- file_ownership = []
-
- for fp, owner, pct, bf in rows:
- parts = fp.split("/")
- module = parts[0] if len(parts) > 1 else "."
-
- module_map[module]["files"].append(fp)
- if owner:
- module_map[module]["owners"][owner] += 1
-
- file_ownership.append({
- "module_path": fp,
- "primary_owner": owner,
- "owner_pct": round(pct, 1) if pct else None,
- "file_count": 1,
- "is_silo": bf <= 1 if bf else False,
- })
-
- module_ownership = []
- for mod, data in sorted(module_map.items()):
- file_count = len(data["files"])
- owners = data["owners"]
- if owners:
- top_owner = max(owners, key=owners.get)
- top_pct = round(owners[top_owner] / file_count * 100, 1)
- else:
- top_owner = None
- top_pct = None
- is_silo = len(owners) <= 1
- module_ownership.append({
- "module_path": mod,
- "primary_owner": top_owner,
- "owner_pct": top_pct,
- "file_count": file_count,
- "is_silo": is_silo,
- })
-
- write_json("ownership-module.json", module_ownership)
- write_json("ownership-file.json", file_ownership)
- print(f" -> {len(module_ownership)} modules, {len(file_ownership)} files")
-
-
-def extract_dead_code(cur):
- rows = cur.execute(
- """SELECT id, kind, file_path, symbol_name, symbol_kind, confidence, reason,
- lines, safe_to_delete, primary_owner, status, note
- FROM dead_code_findings WHERE repository_id = ?
- ORDER BY confidence DESC""",
- (REPO_ID,),
- ).fetchall()
-
- findings = []
- by_kind = defaultdict(int)
- conf_summary = {"high": 0, "medium": 0, "low": 0}
- deletable_lines = 0
- total_lines = 0
-
- for r in rows:
- conf = r[5]
- finding = {
- "id": r[0],
- "kind": r[1],
- "file_path": r[2],
- "symbol_name": r[3],
- "symbol_kind": r[4],
- "confidence": round(conf, 2),
- "reason": r[6],
- "lines": r[7],
- "safe_to_delete": bool(r[8]),
- "primary_owner": r[9],
- "status": r[10],
- "note": r[11],
- }
- findings.append(finding)
- by_kind[r[1]] += 1
- total_lines += r[7]
- if bool(r[8]):
- deletable_lines += r[7]
- if conf >= 0.8:
- conf_summary["high"] += 1
- elif conf >= 0.5:
- conf_summary["medium"] += 1
- else:
- conf_summary["low"] += 1
-
- write_json("dead-code.json", findings)
- write_json("dead-code-summary.json", {
- "total_findings": len(findings),
- "confidence_summary": conf_summary,
- "deletable_lines": deletable_lines,
- "total_lines": total_lines,
- "by_kind": dict(by_kind),
- })
- print(f" -> {len(findings)} findings")
-
-
-def extract_decisions(cur):
- rows = cur.execute(
- """SELECT id, repository_id, title, status, context, decision, rationale,
- alternatives_json, consequences_json, affected_files_json,
- affected_modules_json, tags_json, evidence_commits_json, source,
- evidence_file, evidence_line, confidence, staleness_score,
- superseded_by, last_code_change, created_at, updated_at
- FROM decision_records WHERE repository_id = ?
- ORDER BY confidence DESC""",
- (REPO_ID,),
- ).fetchall()
-
- decisions = []
- for r in rows:
- decisions.append({
- "id": r[0],
- "repository_id": r[1],
- "title": r[2],
- "status": r[3],
- "context": r[4],
- "decision": r[5],
- "rationale": r[6],
- "alternatives": json.loads(r[7]) if r[7] else [],
- "consequences": json.loads(r[8]) if r[8] else [],
- "affected_files": json.loads(r[9]) if r[9] else [],
- "affected_modules": json.loads(r[10]) if r[10] else [],
- "tags": json.loads(r[11]) if r[11] else [],
- "evidence_commits": json.loads(r[12]) if r[12] else [],
- "source": r[13],
- "evidence_file": r[14],
- "evidence_line": r[15],
- "confidence": round(r[16], 2),
- "staleness_score": round(r[17], 2),
- "superseded_by": r[18],
- "last_code_change": r[19],
- "created_at": r[20],
- "updated_at": r[21],
- })
-
- write_json("decisions.json", decisions)
- print(f" -> {len(decisions)} decisions")
-
-
-def main():
- print(f"Reading: {DB_PATH}")
- print(f"Output: {OUT_DIR}")
- OUT_DIR.mkdir(parents=True, exist_ok=True)
-
- conn = sqlite3.connect(str(DB_PATH))
- cur = conn.cursor()
-
- print("\nExtracting...")
- extract_repo(cur)
- extract_stats(cur)
- extract_pages(cur)
- extract_graph(cur)
- extract_symbols(cur)
- extract_hotspots(cur)
- extract_git_summary(cur)
- extract_ownership(cur)
- extract_dead_code(cur)
- extract_decisions(cur)
-
- conn.close()
- print("\nDone!")
-
-
-if __name__ == "__main__":
- main()
diff --git a/tests/unit/test_platform_telemetry.py b/tests/unit/test_platform_telemetry.py
index 7c767dabc..ca3ea75fa 100644
--- a/tests/unit/test_platform_telemetry.py
+++ b/tests/unit/test_platform_telemetry.py
@@ -48,11 +48,6 @@ def _capture(monkeypatch: pytest.MonkeyPatch) -> list[dict]:
class TestConsent:
- def test_enabled_by_default(self, isolated):
- _, path = isolated
- _write_state(path, anon_id="abc")
- assert telemetry.is_enabled() is True
-
def test_do_not_track_blocks_send(self, isolated, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("DO_NOT_TRACK", "1")
sent = _capture(monkeypatch)