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.

fix: C++ dependency resolution, decision extraction timeout, oversized file visibility, resume, and progress bar

FellowTravelerb6c919c88353
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.py
index 10312ea9c..ba706e8c7 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py
@@ -537,6 +537,7 @@ def init_command(
vector_store=vector_store,
concurrency=concurrency,
progress=gen_callback,
+ resume=resume,
)
)
diff --git a/packages/core/src/repowise/core/analysis/decision_extractor.py b/packages/core/src/repowise/core/analysis/decision_extractor.py
index 60a233a3b..0a2c281a5 100644
--- a/packages/core/src/repowise/core/analysis/decision_extractor.py
+++ b/packages/core/src/repowise/core/analysis/decision_extractor.py
@@ -271,7 +271,16 @@ class DecisionExtractor:
else:
files_to_scan = list(self._iter_source_files())
- for file_path in files_to_scan:
+ total_files = len(files_to_scan)
+ logger.info("decision_extractor.scanning_inline_markers", total_files=total_files)
+ for idx, file_path in enumerate(files_to_scan):
+ if idx > 0 and idx % 1000 == 0:
+ logger.info(
+ "decision_extractor.scan_progress",
+ scanned=idx,
+ total=total_files,
+ markers_found=sum(len(v) for v in markers_by_file.values()),
+ )
if not file_path.is_file():
continue
try:
@@ -700,28 +709,39 @@ class DecisionExtractor:
async def _safe_inline() -> list[ExtractedDecision]:
try:
- return await self.scan_inline_markers()
- except Exception:
- logger.warning("decision_extractor.inline_markers_failed")
+ logger.info("decision_extractor.starting_inline_markers")
+ result = await self.scan_inline_markers()
+ logger.info("decision_extractor.finished_inline_markers", count=len(result))
+ return result
+ except Exception as exc:
+ logger.warning("decision_extractor.inline_markers_failed", error=str(exc))
return []
async def _safe_git() -> list[ExtractedDecision]:
try:
- return await self.mine_git_archaeology()
- except Exception:
- logger.warning("decision_extractor.git_archaeology_failed")
+ logger.info("decision_extractor.starting_git_archaeology")
+ result = await self.mine_git_archaeology()
+ logger.info("decision_extractor.finished_git_archaeology", count=len(result))
+ return result
+ except Exception as exc:
+ logger.warning("decision_extractor.git_archaeology_failed", error=str(exc))
return []
async def _safe_readme() -> list[ExtractedDecision]:
try:
- return await self.mine_readme_docs()
- except Exception:
- logger.warning("decision_extractor.readme_mining_failed")
+ logger.info("decision_extractor.starting_readme_mining")
+ result = await self.mine_readme_docs()
+ logger.info("decision_extractor.finished_readme_mining", count=len(result))
+ return result
+ except Exception as exc:
+ logger.warning("decision_extractor.readme_mining_failed", error=str(exc))
return []
+ logger.info("decision_extractor.extract_all_start")
inline, git_decisions, readme_decisions = await asyncio.gather(
_safe_inline(), _safe_git(), _safe_readme()
)
+ logger.info("decision_extractor.extract_all_done")
decisions = inline + git_decisions + readme_decisions
by_source = {
diff --git a/packages/core/src/repowise/core/generation/page_generator.py b/packages/core/src/repowise/core/generation/page_generator.py
index 5438b46fb..84843cb2b 100644
--- a/packages/core/src/repowise/core/generation/page_generator.py
+++ b/packages/core/src/repowise/core/generation/page_generator.py
@@ -409,7 +409,10 @@ class PageGenerator:
repo_name: str,
job_system: Any | None = None, # JobSystem | None
on_page_done: Callable[[str], None] | None = None,
+ on_total_known: Callable[[int], None] | None = None,
git_meta_map: dict[str, dict] | None = None,
+ resume: bool = False,
+ repo_path: Path | str | None = None,
) -> list[GeneratedPage]:
"""Generate all wiki pages for a repository.
@@ -452,8 +455,17 @@ class PageGenerator:
completed_ids: set[str] = set()
job_id: str | None = None
if job_system is not None:
+ repo_path_str = str(Path(repo_path).resolve()) if repo_path else str(getattr(repo_structure, "root_path", "."))
+ # On resume, query the vector store directly — it is the ground truth
+ if resume and self._vector_store is not None:
+ completed_ids = await self._vector_store.list_page_ids()
+ if completed_ids:
+ log.info(
+ "Resuming generation from vector store",
+ already_completed=len(completed_ids),
+ )
job_id = job_system.create_job(
- str(getattr(repo_structure, "root_path", ".")),
+ repo_path_str,
self._config,
self._provider.provider_name,
self._provider.model_name,
@@ -486,6 +498,9 @@ class PageGenerator:
completed_page_summaries[result.target_path] = _extract_summary(
result.content
)
+ # Report progress immediately (not batched after gather)
+ if on_page_done is not None:
+ on_page_done(result.page_type)
return result
except Exception as exc:
if job_system is not None and job_id is not None:
@@ -501,9 +516,6 @@ class PageGenerator:
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)
@@ -583,26 +595,37 @@ class PageGenerator:
)
_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))
+ # Compute estimated total and notify progress (A7)
+ # Use the actual file_page count (files passing _is_significant_file), not
+ # _n_file_cap. The cap sets pr_threshold, but files with high betweenness or
+ # entry_point status bypass that threshold, so actual count > _n_file_cap.
+ _actual_file_page_count = sum(
+ 1
+ for p in code_files
+ if _is_significant_file(p, pagerank, betweenness, self._config, pr_threshold)
+ )
+ estimated_total = (
+ sum(1 for p in parsed_files if p.file_info.is_api_contract)
+ + _n_sym_cap
+ + _actual_file_page_count
+ + 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))
+ )
+ remaining_total = max(0, estimated_total - len(completed_ids))
+ if on_total_known is not None:
+ on_total_known(remaining_total)
+ if job_system is not None and job_id is not None:
job_system.start_job(job_id, estimated_total)
# ---- Level 0: api_contract ----
diff --git a/packages/core/src/repowise/core/ingestion/graph.py b/packages/core/src/repowise/core/ingestion/graph.py
index c6c8b4bc6..a003d6451 100644
--- a/packages/core/src/repowise/core/ingestion/graph.py
+++ b/packages/core/src/repowise/core/ingestion/graph.py
@@ -21,6 +21,7 @@ graph_edges). Phase 4 will replace this with the full SQLAlchemy schema.
from __future__ import annotations
import json
+import shlex
from pathlib import Path
from typing import Any
@@ -46,10 +47,12 @@ class GraphBuilder:
pr = builder.pagerank()
"""
- def __init__(self) -> None:
+ def __init__(self, repo_path: Path | str | None = None) -> None:
self._graph: nx.DiGraph = nx.DiGraph()
self._parsed_files: dict[str, ParsedFile] = {} # path → ParsedFile
self._built = False
+ self._repo_path: Path | None = Path(repo_path) if repo_path else None
+ self._compile_commands_cache: dict[str, dict] | None = None
# ------------------------------------------------------------------
# Building
@@ -247,6 +250,91 @@ class GraphBuilder:
# Internal helpers
# ------------------------------------------------------------------
+ def _load_compile_commands(self) -> dict[str, dict] | None:
+ """Load and cache compile_commands.json if present in the repo.
+
+ Returns dict[source_file_relpath] → command entry, or None if not found.
+ """
+ if self._compile_commands_cache is not None:
+ return self._compile_commands_cache
+ if not self._repo_path:
+ return None
+ for candidate in [
+ self._repo_path / "compile_commands.json",
+ self._repo_path / "build" / "compile_commands.json",
+ ]:
+ if candidate.exists():
+ try:
+ with open(candidate) as f:
+ commands = json.load(f)
+ result: dict[str, dict] = {}
+ for entry in commands:
+ file_path = Path(entry.get("file", ""))
+ if file_path.is_absolute():
+ try:
+ file_rel = file_path.relative_to(self._repo_path)
+ except ValueError:
+ continue
+ else:
+ file_rel = file_path
+ result[file_rel.as_posix()] = entry
+ if result:
+ self._compile_commands_cache = result
+ log.info(
+ "Loaded compile_commands.json",
+ path=str(candidate),
+ entries=len(self._compile_commands_cache),
+ )
+ return self._compile_commands_cache
+ # No valid entries — try next candidate
+ log.debug("compile_commands.json had no resolvable entries", path=str(candidate))
+ except Exception as exc:
+ log.debug("Failed to load compile_commands.json", error=str(exc))
+ return None
+
+ def _extract_include_dirs(self, source_file: str) -> list[str]:
+ """Return absolute include directories for source_file from compile_commands.json."""
+ commands = self._load_compile_commands()
+ if not commands or source_file not in commands:
+ return []
+ entry = commands[source_file]
+ cmd_dir = Path(entry.get("directory", str(self._repo_path or "")))
+ # compile_commands.json entries use either "arguments" (pre-split array)
+ # or "command" (shell-quoted string) — check arguments first
+ if "arguments" in entry:
+ tokens = list(entry["arguments"])
+ else:
+ command = entry.get("command", "")
+ try:
+ tokens = shlex.split(command)
+ except ValueError:
+ return []
+ include_dirs: list[str] = []
+ i = 0
+ while i < len(tokens):
+ tok = tokens[i]
+ if tok in ("-I", "-isystem", "-iquote"):
+ if i + 1 < len(tokens):
+ include_dirs.append(tokens[i + 1])
+ i += 2
+ else:
+ i += 1
+ elif tok.startswith("-I") and len(tok) > 2:
+ include_dirs.append(tok[2:])
+ i += 1
+ elif tok.startswith("-isystem") and len(tok) > 8:
+ include_dirs.append(tok[8:])
+ i += 1
+ else:
+ i += 1
+ result: list[str] = []
+ for d in include_dirs:
+ p = Path(d)
+ if not p.is_absolute():
+ p = cmd_dir / p
+ result.append(str(p.resolve()))
+ return result
+
def _resolve_import(
self,
module_path: str,
@@ -320,6 +408,31 @@ class GraphBuilder:
stem = module_path.rsplit("/", 1)[-1].lower()
return stem_map.get(stem)
+ # --- C / C++ ---
+ if language in ("cpp", "c"):
+ repo_root = self._repo_path.resolve() if self._repo_path else None
+ # 1. Try compile_commands.json include paths
+ for inc_dir in self._extract_include_dirs(importer_path):
+ candidate = (Path(inc_dir) / module_path).resolve()
+ if repo_root:
+ try:
+ rel = candidate.relative_to(repo_root).as_posix()
+ if rel in path_set:
+ return rel
+ except ValueError:
+ pass
+ # 2. Try relative to the importer's directory
+ if repo_root:
+ try:
+ rel = (importer_dir / module_path).resolve().relative_to(repo_root).as_posix()
+ if rel in path_set:
+ return rel
+ except ValueError:
+ pass
+ # 3. Stem-matching fallback
+ stem = Path(module_path).stem.lower()
+ return stem_map.get(stem)
+
# --- Generic fallback: stem matching ---
stem = Path(module_path).stem.lower()
return stem_map.get(stem)
diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.py
index 61c9ec730..25894a745 100644
--- a/packages/core/src/repowise/core/ingestion/traverser.py
+++ b/packages/core/src/repowise/core/ingestion/traverser.py
@@ -192,6 +192,7 @@ class FileTraverser:
str(self.repo_root): self._extra_ignore,
}
self._oversized_skip_count: int = 0
+ self._oversized_files: list[tuple[str, int]] = [] # (path, size_bytes)
self._count_lock = threading.Lock()
log.info(
"FileTraverser initialised",
@@ -316,6 +317,8 @@ class FileTraverser:
if size_bytes > self.max_file_size_bytes:
with self._count_lock:
self._oversized_skip_count += 1
+ self._oversized_files.append((rel_str, size_bytes))
+ log.debug("Skipping oversized file", path=rel_str, size_kb=size_bytes // 1024)
return None
# Blocked extension
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index 472582bee..dfae3d193 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -27,6 +27,10 @@ from repowise.core.pipeline.progress import ProgressCallback
logger = structlog.get_logger(__name__)
+# Maximum seconds to spend on decision extraction before giving up.
+# Large repos with tens of thousands of files can take arbitrarily long.
+DECISION_EXTRACTION_TIMEOUT_SECS = 300
+
# ---------------------------------------------------------------------------
# Result dataclass
@@ -105,6 +109,7 @@ async def run_pipeline(
vector_store: Any | None = None,
concurrency: int = 5,
test_run: bool = False,
+ resume: bool = False,
progress: ProgressCallback | None = None,
) -> PipelineResult:
"""Run the repowise indexing/analysis/generation pipeline.
@@ -240,6 +245,7 @@ async def run_pipeline(
vector_store=vector_store,
concurrency=concurrency,
progress=progress,
+ resume=resume,
)
# ---- Build result -------------------------------------------------------
@@ -336,7 +342,7 @@ async def _run_ingestion(
parser = ASTParser()
parsed_files: list[Any] = []
source_map: dict[str, bytes] = {}
- graph_builder = GraphBuilder()
+ graph_builder = GraphBuilder(repo_path=repo_path)
for i, fi in enumerate(file_infos):
try:
@@ -377,6 +383,14 @@ async def _run_ingestion(
f"Skipped {traverser._oversized_skip_count} oversized files "
f"(>{traverser.max_file_size_bytes // 1024} KB)",
)
+ for path, size_bytes in sorted(
+ traverser._oversized_files, key=lambda x: x[1], reverse=True
+ ):
+ logger.info(
+ "oversized_file_skipped",
+ path=path,
+ size_kb=size_bytes // 1024,
+ )
return parsed_files, file_infos, repo_structure, source_map, graph_builder
@@ -487,7 +501,7 @@ async def _run_decision_extraction(
git_meta_map=git_meta_map,
parsed_files=parsed_files,
)
- report = await extractor.extract_all()
+ report = await asyncio.wait_for(extractor.extract_all(), timeout=DECISION_EXTRACTION_TIMEOUT_SECS)
if progress:
inline = report.by_source.get("inline_marker", 0)
@@ -518,6 +532,7 @@ async def run_generation(
vector_store: Any | None,
concurrency: int,
progress: ProgressCallback | None,
+ resume: bool = False,
) -> list[Any]:
"""Run LLM-powered page generation.
@@ -562,6 +577,10 @@ async def run_generation(
if progress:
progress.on_phase_start("generation", None)
+ def on_total_known(total: int) -> None:
+ if progress:
+ progress.on_phase_start("generation", total)
+
generated_pages = await generator.generate_all(
parsed_files,
source_map,
@@ -570,7 +589,10 @@ async def run_generation(
repo_name,
job_system=job_system,
on_page_done=on_page_done,
+ on_total_known=on_total_known,
git_meta_map=git_meta_map if git_meta_map else None,
+ resume=resume,
+ repo_path=repo_path,
)
if progress:
diff --git a/tests/unit/ingestion/test_graph.py b/tests/unit/ingestion/test_graph.py
index f0d949267..f9069a1ba 100644
--- a/tests/unit/ingestion/test_graph.py
+++ b/tests/unit/ingestion/test_graph.py
@@ -409,4 +409,118 @@ class TestPersist:
assert row is not None
assert row[0] == "my-project"
- asyncio.run(run())
+
+# ---------------------------------------------------------------------------
+# C++ compile_commands.json dependency resolution
+# ---------------------------------------------------------------------------
+
+
+def _cpp(path: str, imports: list[Import] | None = None) -> ParsedFile:
+ return _parsed(path, language="cpp", imports=imports or [])
+
+
+def _cinclude(header: str) -> Import:
+ return Import(
+ raw_statement=f'#include "{header}"',
+ module_path=header,
+ imported_names=[],
+ is_relative=False,
+ resolved_file=None,
+ )
+
+
+class TestCppCompileCommandsResolution:
+ def test_include_via_arguments_array(self, tmp_path: Path) -> None:
+ """compile_commands 'arguments' array format resolves #include via -I flag."""
+ inc_dir = tmp_path / "include"
+ inc_dir.mkdir()
+ (inc_dir / "foo.hpp").write_text("") # header exists on disk
+
+ compile_commands = [
+ {
+ "file": "src/main.cpp",
+ "directory": str(tmp_path),
+ "arguments": ["g++", "-I", str(inc_dir), "-c", "src/main.cpp"],
+ }
+ ]
+ import json
+ (tmp_path / "compile_commands.json").write_text(json.dumps(compile_commands))
+ (tmp_path / "src").mkdir()
+
+ b = GraphBuilder(repo_path=tmp_path)
+ b.add_file(_cpp("include/foo.hpp"))
+ b.add_file(_cpp("src/main.cpp", imports=[_cinclude("foo.hpp")]))
+ b.build()
+ assert b.graph().has_edge("src/main.cpp", "include/foo.hpp")
+
+ def test_include_via_command_string(self, tmp_path: Path) -> None:
+ """compile_commands 'command' shell-string format resolves #include via -I flag."""
+ inc_dir = tmp_path / "include"
+ inc_dir.mkdir()
+
+ compile_commands = [
+ {
+ "file": "src/main.cpp",
+ "directory": str(tmp_path),
+ "command": f"g++ -I{inc_dir} -c src/main.cpp",
+ }
+ ]
+ import json
+ (tmp_path / "compile_commands.json").write_text(json.dumps(compile_commands))
+ (tmp_path / "src").mkdir()
+
+ b = GraphBuilder(repo_path=tmp_path)
+ b.add_file(_cpp("include/foo.hpp"))
+ b.add_file(_cpp("src/main.cpp", imports=[_cinclude("foo.hpp")]))
+ b.build()
+ assert b.graph().has_edge("src/main.cpp", "include/foo.hpp")
+
+ def test_relative_include_fallback(self, tmp_path: Path) -> None:
+ """Without compile_commands.json, #include resolves relative to importer dir."""
+ (tmp_path / "src").mkdir()
+
+ b = GraphBuilder(repo_path=tmp_path)
+ b.add_file(_cpp("src/utils.hpp"))
+ b.add_file(_cpp("src/main.cpp", imports=[_cinclude("utils.hpp")]))
+ b.build()
+ assert b.graph().has_edge("src/main.cpp", "src/utils.hpp")
+
+ def test_stem_fallback_when_no_compile_commands(self, tmp_path: Path) -> None:
+ """When compile_commands.json is absent, stem-matching still works for C++."""
+ b = GraphBuilder(repo_path=tmp_path)
+ b.add_file(_cpp("lib/crypto.hpp"))
+ b.add_file(_cpp("src/main.cpp", imports=[_cinclude("crypto.hpp")]))
+ b.build()
+ assert b.graph().has_edge("src/main.cpp", "lib/crypto.hpp")
+
+ def test_no_compile_commands_no_crash(self, tmp_path: Path) -> None:
+ """Missing compile_commands.json does not crash — falls through to stem matching."""
+ b = GraphBuilder(repo_path=tmp_path)
+ b.add_file(_cpp("src/main.cpp", imports=[_cinclude("nonexistent.hpp")]))
+ b.build()
+ # No edge, no exception
+ assert b.graph().number_of_edges() == 0
+
+ def test_compile_commands_in_build_subdir(self, tmp_path: Path) -> None:
+ """compile_commands.json under build/ subdirectory is also found."""
+ build_dir = tmp_path / "build"
+ build_dir.mkdir()
+ inc_dir = tmp_path / "include"
+ inc_dir.mkdir()
+
+ compile_commands = [
+ {
+ "file": str(tmp_path / "src" / "main.cpp"),
+ "directory": str(tmp_path),
+ "arguments": ["g++", "-I", str(inc_dir), "-c", "src/main.cpp"],
+ }
+ ]
+ import json
+ (build_dir / "compile_commands.json").write_text(json.dumps(compile_commands))
+ (tmp_path / "src").mkdir()
+
+ b = GraphBuilder(repo_path=tmp_path)
+ b.add_file(_cpp("include/bar.hpp"))
+ b.add_file(_cpp("src/main.cpp", imports=[_cinclude("bar.hpp")]))
+ b.build()
+ assert b.graph().has_edge("src/main.cpp", "include/bar.hpp")