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(ingestion): load grammars per language and warn when COBOL indexes without symbols (#4433)

Raghav Chamadiyae2a1fc7dd375
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index be2ef5225..7da9c340b 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -74,6 +74,9 @@ Scala, Elixir and F# have dedicated import resolvers with known gaps; see
\* COBOL is excluded from dead-code claims: JCL, schedulers and dynamic program
calls are entry paths the repository graph cannot observe.
+The COBOL and Apex grammars download on first use; offline, set
+`REPOWISE_GRAMMAR_DIR` to a pre-staged grammar cache. `repowise doctor` reports
+whether it is cached.
Apex (`.cls`, `.trigger`, `.apex`) is parsed for symbols, heritage and calls,
resolved case-insensitively within each sfdx project's namespace; its dead-code
findings are review-only. Apex test coverage from the Salesforce CLI is read as a
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/core.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/core.py
index 1ce7ad80f..388c1d581 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/core.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/core.py
@@ -222,6 +222,60 @@ def _store_format_row(repo_path: _DoctorPath) -> DoctorCheck:
return _check("Store format", True, f"Could not check: {e}")
+def _runtime_grammar_rows(repo_path: _DoctorPath) -> list[DoctorCheck]:
+ """One row per runtime-downloaded grammar the repo needs, read from the cache only."""
+ import subprocess
+
+ from repowise.core.ingestion.languages.registry import REGISTRY
+ from repowise.core.ingestion.parser.grammars import (
+ downloads_grammar_at_runtime,
+ runtime_grammar_cache,
+ )
+
+ by_ext = {
+ ext: tag
+ for ext, tag in REGISTRY.all_extensions().items()
+ if downloads_grammar_at_runtime(tag)
+ }
+ try:
+ listed = subprocess.run(
+ ["git", "ls-files", "-z"],
+ cwd=repo_path,
+ capture_output=True,
+ check=True,
+ ).stdout.decode("utf-8", errors="replace")
+ except (OSError, subprocess.CalledProcessError):
+ return []
+ counts: dict[str, int] = {}
+ for path in filter(None, listed.split("\0")):
+ tag = by_ext.get(os.path.splitext(path)[1].lower())
+ if tag:
+ counts[tag] = counts.get(tag, 0) + 1
+
+ rows = []
+ for tag, count in sorted(counts.items()):
+ spec = REGISTRY.get(tag)
+ name = f"{spec.display_name if spec else tag} grammar"
+ try:
+ cached, cache_dir = runtime_grammar_cache(tag)
+ except Exception as exc:
+ rows.append(_check(name, False, f"could not read the grammar cache ({exc})"))
+ continue
+ if cached:
+ rows.append(_check(name, True, f"cached in {cache_dir}"))
+ else:
+ rows.append(
+ _check(
+ name,
+ False,
+ f"not downloaded; {count:,} files would index without symbols. "
+ "Re-run 'repowise init' with network access, or set "
+ "REPOWISE_GRAMMAR_DIR to a pre-staged grammar cache first",
+ )
+ )
+ return rows
+
+
def core_checks(ctx: CheckContext) -> list[DoctorCheck]:
"""Checks 1-4b, in order. Fills the database and state fields of *ctx*."""
checks = [_git_check(ctx.repo_path)]
@@ -233,4 +287,5 @@ def core_checks(ctx: CheckContext) -> list[DoctorCheck]:
checks.append(_state_row(ctx))
if ctx.state_ok:
checks.append(_store_format_row(ctx.repo_path))
+ checks.extend(_runtime_grammar_rows(ctx.repo_path))
return checks
diff --git a/packages/core/src/repowise/core/ingestion/parser/__init__.py b/packages/core/src/repowise/core/ingestion/parser/__init__.py
index 78bfc009b..e6a8a611e 100644
--- a/packages/core/src/repowise/core/ingestion/parser/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/parser/__init__.py
@@ -74,7 +74,6 @@ from .grammars import (
_MISSING_GRAMMAR_REPORTED,
_PASSTHROUGH_LANGUAGES,
QUERIES_DIR,
- _build_language_registry,
_compile_query,
_get_language,
_load_compiled_query,
@@ -84,6 +83,7 @@ from .grammars import (
grammar_tag_for,
log,
missing_grammar_languages,
+ unavailable_runtime_grammars,
)
from .imports import _extract_imports
from .references import (
diff --git a/packages/core/src/repowise/core/ingestion/parser/grammars.py b/packages/core/src/repowise/core/ingestion/parser/grammars.py
index c9091abd3..c217f55b4 100644
--- a/packages/core/src/repowise/core/ingestion/parser/grammars.py
+++ b/packages/core/src/repowise/core/ingestion/parser/grammars.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import os
import re
from collections.abc import Iterable
from functools import cache
@@ -87,53 +88,75 @@ _PASSTHROUGH_LANGUAGES: frozenset[str] = _LANG_REGISTRY.unparseable_data_languag
# ---------------------------------------------------------------------------
-def _build_language_registry() -> dict[str, Language]:
- """Lazily load installed tree-sitter language packages.
+# Downloads its grammars on first use rather than shipping them in a wheel.
+_RUNTIME_DOWNLOAD_PACKAGE = "tree_sitter_language_pack"
+# A pre-staged language-pack cache, for machines with no network.
+GRAMMAR_DIR_ENV = "REPOWISE_GRAMMAR_DIR"
- Driven by ``LanguageSpec.grammar_package`` / ``grammar_loader`` /
- ``shares_grammar_with`` from the centralised registry.
- """
- registry: dict[str, Language] = {}
-
- for spec in _LANG_REGISTRY.all_specs():
- # Languages that share another's grammar (e.g. C → cpp)
- if spec.shares_grammar_with:
- shared = registry.get(spec.shares_grammar_with)
- if shared:
- registry[spec.tag] = shared
- continue
-
- if not spec.grammar_package:
- continue
- try:
- mod = __import__(spec.grammar_package)
- loader_fn = getattr(mod, spec.grammar_loader)
- loaded = loader_fn(*spec.grammar_loader_args)
- # Standalone grammar wheels return a PyCapsule; shared grammar
- # packs may return the fully constructed Language directly.
- lang_obj = loaded if isinstance(loaded, Language) else Language(loaded)
- registry[spec.tag] = lang_obj
- except Exception as exc:
- log.debug(
- "tree-sitter language unavailable",
- language=spec.tag,
- reason=str(exc),
- )
-
- # TypeScript's tsx variant — special case: same package, different loader
- if "typescript" in registry and "tsx" not in registry:
+def _load_language(tag: str) -> Language | None:
+ """Load *tag*'s grammar alone, so a repo never loads one it has no files for."""
+ if tag == "tsx":
+ # TypeScript's tsx variant: same package, different loader.
try:
import tree_sitter_typescript as _ts_mod
- registry["tsx"] = Language(_ts_mod.language_tsx())
+ return Language(_ts_mod.language_tsx())
except Exception as exc:
- log.debug("tree-sitter language unavailable", language="tsx", reason=str(exc))
+ _GRAMMAR_FAILURES[tag] = str(exc)
+ log.debug("tree-sitter language unavailable", language=tag, reason=str(exc))
+ return None
+
+ spec = _LANG_REGISTRY.get(tag)
+ if spec is None:
+ return None
+ # Languages that share another's grammar (e.g. C -> cpp).
+ if spec.shares_grammar_with:
+ return _get_language(spec.shares_grammar_with)
+ if not spec.grammar_package:
+ return None
+
+ try:
+ mod = __import__(spec.grammar_package)
+ if spec.grammar_package == _RUNTIME_DOWNLOAD_PACKAGE:
+ _configure_grammar_dir(mod)
+ loaded = getattr(mod, spec.grammar_loader)(*spec.grammar_loader_args)
+ # Standalone grammar wheels return a PyCapsule; shared grammar
+ # packs may return the fully constructed Language directly.
+ return loaded if isinstance(loaded, Language) else Language(loaded)
+ except Exception as exc:
+ _GRAMMAR_FAILURES[tag] = str(exc)
+ log.debug("tree-sitter language unavailable", language=tag, reason=str(exc))
+ return None
+
+
+def _configure_grammar_dir(pack: object) -> None:
+ """Point the language pack at ``$REPOWISE_GRAMMAR_DIR`` when it is set."""
+ grammar_dir = os.environ.get(GRAMMAR_DIR_ENV, "").strip()
+ if grammar_dir:
+ pack.configure(pack.PackConfig(cache_dir=grammar_dir)) # type: ignore[attr-defined]
- return registry
+def downloads_grammar_at_runtime(tag: str) -> bool:
+ """Whether *tag*'s grammar comes from the language pack's runtime download."""
+ spec = _LANG_REGISTRY.get(tag)
+ return spec is not None and spec.grammar_package == _RUNTIME_DOWNLOAD_PACKAGE
+
+def runtime_grammar_cache(tag: str) -> tuple[bool, str]:
+ """``(cached, cache_dir)`` for a runtime-downloaded grammar, with no network call."""
+ import tree_sitter_language_pack as pack
+
+ _configure_grammar_dir(pack)
+ spec = _LANG_REGISTRY.get(tag)
+ name = spec.grammar_loader_args[0] if spec and spec.grammar_loader_args else tag
+ return name in pack.downloaded_languages(), str(pack.cache_dir())
+
+
+# Loaded grammars, filled one language at a time by ``_get_language``.
_LANGUAGE_REGISTRY: dict[str, Language] = {}
+# Failed tags and why; a failure is not retried per file.
+_GRAMMAR_FAILURES: dict[str, str] = {}
# Languages already reported as having a config but no installed grammar:
# one line per language per process, not one per file.
@@ -213,11 +236,32 @@ def failed_query_languages(language_tags: Iterable[str]) -> list[tuple[str, str]
return sorted(failed, key=lambda x: x[0])
+def unavailable_runtime_grammars(language_tags: Iterable[str]) -> list[tuple[str, str]]:
+ """``(tag, reason)`` for each runtime-downloaded grammar in *language_tags* that fails to load.
+
+ Loaded in the parent, which also fills the cache before the parse workers start.
+ """
+ failed: list[tuple[str, str]] = []
+ for tag in sorted(set(language_tags)):
+ if (
+ tag in LANGUAGE_CONFIGS
+ and downloads_grammar_at_runtime(tag)
+ and _get_language(tag) is None
+ ):
+ failed.append((tag, _GRAMMAR_FAILURES.get(tag, "not loadable")))
+ return failed
+
+
def _get_language(tag: str) -> Language | None:
# Filled in place, never rebound: the package re-exports this dict.
- if not _LANGUAGE_REGISTRY:
- _LANGUAGE_REGISTRY.update(_build_language_registry())
- return _LANGUAGE_REGISTRY.get(tag)
+ if tag in _LANGUAGE_REGISTRY:
+ return _LANGUAGE_REGISTRY[tag]
+ if tag in _GRAMMAR_FAILURES:
+ return None
+ language = _load_language(tag)
+ if language is not None:
+ _LANGUAGE_REGISTRY[tag] = language
+ return language
def grammar_tag_for(language: str, path: str) -> str:
diff --git a/packages/core/src/repowise/core/pipeline/phases/ingestion.py b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
index a6d84d9f2..1d61db884 100644
--- a/packages/core/src/repowise/core/pipeline/phases/ingestion.py
+++ b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
@@ -11,6 +11,7 @@ import contextlib
import multiprocessing
import os
import time
+from collections import Counter
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
@@ -38,21 +39,34 @@ def _report_missing_grammars(stats: Any, progress: ProgressCallback | None) -> N
if not lang_counts:
return
try:
- from repowise.core.ingestion.parser import missing_grammar_languages
+ from repowise.core.ingestion.languages.registry import REGISTRY
+ from repowise.core.ingestion.parser import (
+ missing_grammar_languages,
+ unavailable_runtime_grammars,
+ )
missing = missing_grammar_languages(lang_counts)
+ unavailable = unavailable_runtime_grammars(lang_counts)
except Exception:
logger.debug("grammar_preflight_failed", exc_info=True)
return
- if not missing:
- return
- detail = ", ".join(f"{lang} ({lang_counts[lang]:,} files)" for lang in missing)
- emit_warning(
- progress,
- f"No parser installed for: {detail}. "
- "These files are indexed but contribute no symbols; "
- "reinstall repowise to pick up the missing grammars.",
- )
+ if missing:
+ detail = ", ".join(f"{lang} ({lang_counts[lang]:,} files)" for lang in missing)
+ emit_warning(
+ progress,
+ f"No parser installed for: {detail}. "
+ "These files are indexed but contribute no symbols; "
+ "reinstall repowise to pick up the missing grammars.",
+ )
+ for lang, reason in unavailable:
+ spec = REGISTRY.get(lang)
+ emit_warning(
+ progress,
+ f"{spec.display_name if spec else lang} grammar unavailable: "
+ f"{lang_counts[lang]:,} files indexed without symbols ({reason}). "
+ "It downloads on first use; on a machine with no network, set "
+ "REPOWISE_GRAMMAR_DIR to a pre-staged grammar cache.",
+ )
def _report_query_compilation_failures(stats: Any, progress: ProgressCallback | None) -> None:
@@ -502,7 +516,10 @@ async def _traverse_stage(
repo_path, traverser, allow_formatter_check=walk.derive_environment_facts
)
_phase_done(progress, "traverse")
- return traverser, _filter_file_infos(file_infos, walk), repo_structure
+ file_infos = _filter_file_infos(file_infos, walk)
+ # The threaded walk skips ``traverse()``, which is what counts languages.
+ traverser.stats.lang_counts = dict(Counter(f.language for f in file_infos))
+ return traverser, file_infos, repo_structure
async def _parse_in_pool(
diff --git a/scripts/cobol_acceptance.py b/scripts/cobol_acceptance.py
new file mode 100644
index 000000000..6ef28d3eb
--- /dev/null
+++ b/scripts/cobol_acceptance.py
@@ -0,0 +1,242 @@
+"""COBOL acceptance metrics: ground truth from source text vs a built index.
+
+Usage::
+
+ python scripts/cobol_acceptance.py <repo> [--json out.json]
+
+``<repo>`` must hold ``.repowise/wiki.db`` from ``repowise init --no-prose``.
+Truth is read with regexes that know nothing about the parser, so the two are
+independent. Built for AWS CardDemo (``59cc6c2``); every count is generic.
+"""
+
+from __future__ import annotations
+
+import argparse
+import collections
+import json
+import os
+import re
+import sqlite3
+import sys
+
+_PROGRAM_EXTS = {".cbl", ".cob", ".cobol"}
+_COPYBOOK_EXTS = {".cpy"}
+_JCL_EXTS = {".jcl", ".prc", ".proc"}
+_BMS_EXTS = {".bms"}
+_NOT_A_PARAGRAPH = {"UNTIL", "VARYING", "WITH", "TEST", "FOREVER", "THRU", "THROUGH"}
+_STRUCTURAL = ("calls", "imports")
+
+
+def _walk(root: str) -> dict[str, dict[str, list[str]]]:
+ """``{kind: {STEM: [relpath, ...]}}`` for programs, copybooks, JCL and BMS."""
+ found: dict[str, dict[str, list[str]]] = {
+ k: collections.defaultdict(list) for k in ("program", "copybook", "jcl", "bms")
+ }
+ for dirpath, dirnames, filenames in os.walk(root):
+ dirnames[:] = [d for d in dirnames if d not in (".git", ".repowise")]
+ for name in filenames:
+ stem, ext = os.path.splitext(name)
+ ext = ext.lower()
+ rel = os.path.relpath(os.path.join(dirpath, name), root).replace("\\", "/")
+ kind = (
+ "program"
+ if ext in _PROGRAM_EXTS
+ else "copybook"
+ if ext in _COPYBOOK_EXTS
+ else "jcl"
+ if ext in _JCL_EXTS
+ else "bms"
+ if ext in _BMS_EXTS
+ else None
+ )
+ if kind:
+ found[kind][stem.upper()].append(rel)
+ return found
+
+
+def _code_lines(path: str) -> list[tuple[int, str, str]]:
+ """``(line, area_a_char, text)`` for fixed-format code lines (cols 8-72)."""
+ out = []
+ with open(path, encoding="latin-1") as fh:
+ for number, raw in enumerate(fh, 1):
+ raw = raw.rstrip("\r\n")
+ if len(raw) > 6 and raw[6] in "*/":
+ continue
+ out.append((number, raw[7:8], raw[7:72]))
+ return out
+
+
+def truth(root: str) -> dict:
+ files = _walk(root)
+ progs, cpys, jcls, bms = (files[k] for k in ("program", "copybook", "jcl", "bms"))
+ paragraphs: set[tuple[str, str]] = set()
+ performs: set[tuple[str, str]] = set()
+ pairs: dict[str, set[tuple[str, str]]] = collections.defaultdict(set)
+
+ for rels in progs.values():
+ for rel in rels:
+ lines = _code_lines(os.path.join(root, rel))
+ text = "\n".join(t for _, _, t in lines)
+ own: set[str] = set()
+ in_proc = False
+ for _, area_a, body in lines:
+ if re.search(r"PROCEDURE\s+DIVISION", body, re.I):
+ in_proc = True
+ continue
+ if not in_proc:
+ continue
+ m = re.match(r"([A-Z0-9][A-Z0-9-]*)(\s+SECTION)?\s*\.\s*$", body.rstrip(), re.I)
+ if m and area_a != " ":
+ own.add(m.group(1).upper())
+ paragraphs |= {(rel, p) for p in own}
+ for m in re.finditer(r"\bPERFORM\s+([A-Z0-9][A-Z0-9-]*)", text, re.I):
+ target = m.group(1).upper()
+ if target in own and target not in _NOT_A_PARAGRAPH:
+ performs.add((rel, target))
+ for m in re.finditer(r"^\s*COPY\s+'?([A-Z0-9#@$-]+)'?", text, re.I | re.M):
+ for cpy in cpys.get(m.group(1).upper(), []):
+ pairs["copy"].add((rel, cpy))
+ for m in re.finditer(r"\bCALL\s+'([A-Z0-9#@$-]+)'", text, re.I):
+ for dst in progs.get(m.group(1).upper(), []):
+ pairs["call"].add((rel, dst))
+ literals = _literal_assignments(text)
+ for m in re.finditer(r"EXEC\s+CICS\s+(?:LINK|XCTL)\b(.*?)END-EXEC", text, re.I | re.S):
+ pm = re.search(r"PROGRAM\s*\(\s*('?)([A-Z0-9#@$-]+)'?\s*\)", m.group(1), re.I)
+ if not pm:
+ continue
+ name = pm.group(2).upper()
+ targets = {name} if pm.group(1) else literals.get(name, set())
+ for target in targets:
+ for dst in progs.get(target, []):
+ if dst != rel:
+ pairs["cics"].add((rel, dst))
+ for m in re.finditer(
+ r"EXEC\s+CICS\s+(?:SEND|RECEIVE)\s+MAP\s*\(.*?END-EXEC", text, re.I | re.S
+ ):
+ ms = re.search(r"MAPSET\s*\(\s*'?([A-Z0-9#@$-]+)'?\s*\)", m.group(0), re.I)
+ for dst in bms.get(ms.group(1).upper() if ms else "", []):
+ pairs["bms"].add((rel, dst))
+
+ for rels in jcls.values():
+ for rel in rels:
+ with open(os.path.join(root, rel), encoding="latin-1") as fh:
+ for raw in fh:
+ if raw.startswith("//*"):
+ continue
+ m = re.search(r"\bEXEC\s+PGM=([A-Z0-9#@$]+)", raw, re.I)
+ if m:
+ for dst in progs.get(m.group(1).upper(), []):
+ pairs["jcl"].add((rel, dst))
+
+ return {
+ "files": {k: sorted(r for v in d.values() for r in v) for k, d in files.items()},
+ "paragraphs": paragraphs,
+ "performs": performs,
+ "pairs": pairs,
+ }
+
+
+def _literal_assignments(text: str) -> dict[str, set[str]]:
+ """``{VAR: {'LIT', ...}}`` from ``MOVE 'LIT' TO VAR`` and ``VAR ... VALUE 'LIT'``."""
+ out: dict[str, set[str]] = collections.defaultdict(set)
+ for m in re.finditer(r"\bMOVE\s+'([A-Z0-9#@$-]+)'\s+TO\s+([A-Z0-9-]+)", text, re.I):
+ out[m.group(2).upper()].add(m.group(1).upper())
+ for m in re.finditer(
+ r"^\s*\d\d\s+([A-Z0-9-]+)\s+PIC[^.]*?VALUE\s+'([A-Z0-9#@$-]+)'", text, re.I | re.M
+ ):
+ out[m.group(1).upper()].add(m.group(2).upper())
+ return out
+
+
+def index_view(db: str) -> dict:
+ con = sqlite3.connect(db)
+ nodes = {
+ r[0]: r
+ for r in con.execute(
+ "select node_id, node_type, language, file_path, name, kind from graph_nodes"
+ )
+ }
+
+ def file_of(node_id: str) -> str:
+ row = nodes.get(node_id)
+ if row is None:
+ return node_id
+ return row[0] if row[1] == "file" else (row[3] or node_id)
+
+ edges = con.execute(
+ "select source_node_id, target_node_id, edge_type from graph_edges"
+ ).fetchall()
+ symbols = [r for r in nodes.values() if r[1] == "symbol" and r[2] == "cobol"]
+ procs = {(r[3], r[4].upper()) for r in symbols if r[5] == "function"}
+ same_file_calls, cross_perform = set(), 0
+ file_pairs: dict[str, set[tuple[str, str]]] = collections.defaultdict(set)
+ for src, dst, etype in edges:
+ fs, ft = file_of(src), file_of(dst)
+ if etype == "calls":
+ target = nodes.get(dst)
+ if fs == ft and target is not None:
+ same_file_calls.add((fs, (target[4] or "").upper()))
+ elif target is not None and target[5] == "function" and target[2] == "cobol":
+ cross_perform += 1
+ if etype in _STRUCTURAL and fs != ft and dst in nodes:
+ file_pairs[etype].add((fs, ft))
+ return {
+ "nodes": nodes,
+ "cobol_symbols": len(symbols),
+ "procs": procs,
+ "same_file_calls": same_file_calls,
+ "cross_perform": cross_perform,
+ "file_pairs": file_pairs,
+ }
+
+
+def metrics(root: str, db: str) -> dict:
+ t, ix = truth(root), index_view(db)
+ any_pairs = set().union(*ix["file_pairs"].values()) if ix["file_pairs"] else set()
+ imports = ix["file_pairs"].get("imports", set())
+
+ def ratio(found: int, total: int) -> str:
+ return f"{found}/{total} ({found / total:.0%})" if total else "0/0"
+
+ per_prog = collections.defaultdict(set)
+ for rel, name in t["paragraphs"]:
+ per_prog[rel].add(name)
+ whole = sum(1 for rel, names in per_prog.items() if all((rel, n) in ix["procs"] for n in names))
+ cobol_files = t["files"]["program"] + t["files"]["copybook"]
+ touched = {f for pair in any_pairs for f in pair}
+ pair_hits = {
+ kind: ratio(
+ len(t["pairs"][kind] & (imports if kind == "copy" else any_pairs)),
+ len(t["pairs"][kind]),
+ )
+ for kind in ("copy", "call", "cics", "jcl", "bms")
+ }
+ return {
+ "cobol_symbols": ix["cobol_symbols"],
+ "programs_whole": ratio(whole, len(t["files"]["program"])),
+ "paragraph_recall": ratio(len(t["paragraphs"] & ix["procs"]), len(t["paragraphs"])),
+ "perform_recall": ratio(len(t["performs"] & ix["same_file_calls"]), len(t["performs"])),
+ **{f"{k}_pairs": v for k, v in pair_hits.items()},
+ "cross_program_perform_edges": ix["cross_perform"],
+ "cobol_files_isolated": ratio(
+ sum(1 for f in cobol_files if f not in touched), len(cobol_files)
+ ),
+ }
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ ap.add_argument("repo")
+ ap.add_argument("--json", help="write the metrics here as JSON")
+ args = ap.parse_args()
+ result = metrics(args.repo, os.path.join(args.repo, ".repowise", "wiki.db"))
+ for key, value in result.items():
+ print(f"{key:30s} {value}")
+ if args.json:
+ with open(args.json, "w", encoding="utf-8") as fh:
+ json.dump(result, fh, indent=1)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/unit/ingestion/test_runtime_grammars.py b/tests/unit/ingestion/test_runtime_grammars.py
new file mode 100644
index 000000000..c3e5d2e46
--- /dev/null
+++ b/tests/unit/ingestion/test_runtime_grammars.py
@@ -0,0 +1,117 @@
+"""Runtime-downloaded grammars (COBOL, Apex) load lazily and fail loudly."""
+
+from __future__ import annotations
+
+import subprocess
+from typing import ClassVar
+
+import pytest
+
+from repowise.core.ingestion.parser import grammars
+
+
+def fresh_registry(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(grammars, "_LANGUAGE_REGISTRY", {})
+ monkeypatch.setattr(grammars, "_GRAMMAR_FAILURES", {})
+
+
+def offline_pack(monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ """The language pack as an offline machine sees it: every load raises."""
+ import tree_sitter_language_pack as pack
+
+ calls: list[str] = []
+
+ def _offline(name: str) -> object:
+ calls.append(name)
+ raise RuntimeError("Download error: Failed to fetch manifest")
+
+ monkeypatch.setattr(pack, "get_language", _offline)
+ return calls
+
+
+def test_loading_one_grammar_does_not_load_the_language_pack(
+ fresh_registry: None, offline_pack: list[str]
+) -> None:
+ """A Python-only index must never reach the runtime download."""
+ assert grammars._get_language("python") is not None
+ assert offline_pack == []
+ assert "cobol" not in grammars._GRAMMAR_FAILURES
+
+
+def test_an_unloadable_runtime_grammar_is_reported_with_its_reason(
+ fresh_registry: None, offline_pack: list[str]
+) -> None:
+ result = grammars.unavailable_runtime_grammars(["python", "cobol", "cobol"])
+
+ assert result == [("cobol", "Download error: Failed to fetch manifest")]
+
+
+def test_a_failed_grammar_is_not_retried_per_file(
+ fresh_registry: None, offline_pack: list[str]
+) -> None:
+ """One attempt per process, not one network timeout per COBOL file."""
+ for _ in range(5):
+ assert grammars._get_language("cobol") is None
+
+ assert offline_pack == ["cobol"]
+
+
+def test_the_grammar_dir_setting_points_the_pack_at_a_staged_cache(
+ fresh_registry: None, monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ import tree_sitter_language_pack as pack
+
+ configured: list[object] = []
+ monkeypatch.setattr(pack, "configure", configured.append)
+ monkeypatch.setattr(pack, "get_language", lambda name: (_ for _ in ()).throw(OSError()))
+ monkeypatch.setenv(grammars.GRAMMAR_DIR_ENV, str(tmp_path))
+
+ grammars._get_language("cobol")
+
+ assert len(configured) == 1
+ assert configured[0].cache_dir == str(tmp_path)
+
+
+def test_the_ingestion_preflight_names_the_language_and_file_count(
+ fresh_registry: None, offline_pack: list[str]
+) -> None:
+ from repowise.core.pipeline.phases.ingestion import _report_missing_grammars
+
+ class _Stats:
+ lang_counts: ClassVar[dict] = {"cobol": 106, "python": 3}
+
+ class _Progress:
+ def __init__(self) -> None:
+ self.messages: list[tuple[str, str]] = []
+
+ def on_message(self, level: str, text: str) -> None:
+ self.messages.append((level, text))
+
+ progress = _Progress()
+ _report_missing_grammars(_Stats(), progress)
+
+ assert len(progress.messages) == 1
+ level, text = progress.messages[0]
+ assert level == "warning"
+ assert "COBOL grammar unavailable: 106 files indexed without symbols" in text
+ assert grammars.GRAMMAR_DIR_ENV in text
+
+
+def test_doctor_reports_an_uncached_grammar_without_downloading_it(
+ tmp_path, monkeypatch: pytest.MonkeyPatch, offline_pack: list[str]
+) -> None:
+ from repowise.cli.commands.doctor_cmd._checks import core
+
+ subprocess.run(["git", "init", "-q", str(tmp_path)], check=True)
+ (tmp_path / "PAYROLL.cbl").write_text(" IDENTIFICATION DIVISION.\n")
+ (tmp_path / "app.py").write_text("")
+ subprocess.run(["git", "-C", str(tmp_path), "add", "."], check=True)
+ monkeypatch.setattr(grammars, "runtime_grammar_cache", lambda tag: (False, "/cache"))
+
+ rows = core._runtime_grammar_rows(tmp_path)
+
+ assert [(r.name, r.ok) for r in rows] == [("COBOL grammar", False)]
+ assert "1 files would index without symbols" in rows[0].detail
+ assert offline_pack == []