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.

refactor(core): decompose the decision miners and share their batching (#2559)

Raghav Chamadiya90a273c62993
diff --git a/packages/core/src/repowise/core/analysis/decisions/adr.py b/packages/core/src/repowise/core/analysis/decisions/adr.py
new file mode 100644
index 000000000..b7d782fea
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/adr.py
@@ -0,0 +1,158 @@
+"""Architecture Decision Record discovery and Nygard/MADR section parsing."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from repowise.core.fs_walk import walk_repo
+from repowise.core.ingestion.traverser import load_gitignore_spec
+
+from .source_files import _SKIP_DIRS
+
+# Conventional ADR homes, as repo-root-relative posix directories. Every ``.md``
+# directly inside one is a candidate regardless of filename; matching is on the
+# whole relative dir, so a stray ``vendor/x/adr/`` does not qualify.
+_ADR_DIRS = frozenset(
+ {
+ "adr",
+ "adrs",
+ "docs/adr",
+ "docs/adrs",
+ "docs/decisions",
+ "decisions",
+ "architecture",
+ "doc/adr",
+ }
+)
+_MAX_ADR_FILES = 60
+
+# Nygard/MADR section headings. Mapped to the ExtractedDecision fields they
+# populate during the deterministic (LLM-free) parse.
+_ADR_HEADING_RE = re.compile(r"^#{1,6}\s+(.+?)\s*$")
+_ADR_FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
+_ADR_STATUS_MAP = {
+ "accepted": "active",
+ "approved": "active",
+ "active": "active",
+ "proposed": "proposed",
+ "draft": "proposed",
+ "rejected": "deprecated",
+ "deprecated": "deprecated",
+ "superseded": "superseded",
+}
+
+
+def find_adr_files(repo_path: Path) -> list[Path]:
+ """Collect candidate ADR files from the conventional dirs + name match.
+
+ One :func:`walk_repo` pass answers both halves: files directly under a
+ conventional ADR directory (root-anchored, as the old shallow globs
+ were) rank ahead of loose ``*adr*.md`` name matches, and the cap is
+ applied to the two buckets in that order.
+
+ Ignored paths are excluded. :mod:`repowise.core.fs_walk` prunes junk
+ dirs and nested repos but deliberately reads no ignore files, so
+ gitignore/``info/exclude`` handling is this function's job: without it
+ a scratch dir that ``git status`` cannot see contributes ``active``
+ decision records citing files no clone of the repo contains.
+ """
+ ignore = load_gitignore_spec(repo_path)
+ conventional: list[Path] = []
+ loose: list[Path] = []
+ for dirpath, dirnames, filenames in walk_repo(repo_path, prune_dirs=_SKIP_DIRS):
+ rel_dir = dirpath.relative_to(repo_path).as_posix()
+ rel_dir = "" if rel_dir == "." else rel_dir
+ # Prune ignored and packaging-metadata subtrees in place. Ignored
+ # DIRECTORIES match with a trailing slash, as git matches them.
+ dirnames[:] = [
+ d
+ for d in dirnames
+ if not d.endswith((".egg-info", ".dist-info"))
+ and not ignore.match_file(f"{rel_dir}/{d}/" if rel_dir else f"{d}/")
+ ]
+
+ in_adr_dir = rel_dir in _ADR_DIRS
+ for fname in filenames:
+ bucket = _adr_bucket(fname, in_adr_dir, conventional, loose)
+ if bucket is None:
+ continue
+ if ignore.match_file(f"{rel_dir}/{fname}" if rel_dir else fname):
+ continue
+ bucket.append(dirpath / fname)
+
+ if len(conventional) + len(loose) >= _MAX_ADR_FILES:
+ break
+
+ # No dedup pass: walk_repo yields each directory once, and each file
+ # lands in exactly one bucket.
+ return [*conventional, *loose][:_MAX_ADR_FILES]
+
+
+def _adr_bucket(
+ fname: str, in_adr_dir: bool, conventional: list[Path], loose: list[Path]
+) -> list[Path] | None:
+ """Which candidate list *fname* belongs in, or None if it is no ADR."""
+ low = fname.lower()
+ if not low.endswith(".md"):
+ return None
+ if in_adr_dir:
+ return conventional
+ if "adr" in low and low != "readme.md" and "template" not in low:
+ return loose
+ return None
+
+
+def read_front_matter(content: str) -> tuple[str, str, str]:
+ """``(status, title, body)`` from an ADR's optional YAML front matter.
+
+ Status and title are empty when the front matter does not set them, and
+ the body is the document after the front matter (all of it when absent).
+ """
+ status = ""
+ title = ""
+ fm = _ADR_FRONTMATTER_RE.match(content)
+ if not fm:
+ return status, title, content
+ for line in fm.group(1).splitlines():
+ if ":" not in line:
+ continue
+ k, _, v = line.partition(":")
+ key = k.strip().lower()
+ val = v.strip().strip("\"'")
+ if key == "status":
+ status = val
+ elif key == "title":
+ title = val
+ return status, title, content[fm.end() :]
+
+
+def split_headings(text: str) -> dict[str, str]:
+ """Map lowercased markdown headings to their section bodies."""
+ sections: dict[str, str] = {}
+ current: str | None = None
+ buf: list[str] = []
+ for line in text.splitlines():
+ m = _ADR_HEADING_RE.match(line)
+ if m:
+ if current is not None:
+ sections[current] = "\n".join(buf).strip()
+ current = m.group(1).strip().lower()
+ buf = []
+ elif current is not None:
+ buf.append(line)
+ if current is not None:
+ sections[current] = "\n".join(buf).strip()
+ return sections
+
+
+def bullets(text: str) -> list[str]:
+ """Extract markdown bullet items from a section body."""
+ out: list[str] = []
+ for line in text.splitlines():
+ s = line.strip()
+ if s.startswith(("-", "*", "+")):
+ item = s[1:].strip()
+ if item:
+ out.append(item)
+ return out
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.py
index 03a15cafa..caf1ebc59 100644
--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py
+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py
@@ -60,10 +60,14 @@ from repowise.core.analysis.decisions.scope import (
resolve_module_nodes,
selected_scope_files,
)
-from repowise.core.fs_walk import PRUNED_DIRS, walk_repo
-from repowise.core.ingestion.traverser import load_gitignore_spec
+from .adr import _ADR_STATUS_MAP, bullets, find_adr_files, read_front_matter, split_headings
from .commit_signals import count_decision_signals
+from .markers import ( # noqa: F401 (MARKER_RE re-exported)
+ MARKER_RE,
+ find_markers,
+ strip_code_blocks,
+)
from .prompts import (
_SYSTEM_PROMPT,
COMMENT_ARCHAEOLOGY_PROMPT,
@@ -72,6 +76,11 @@ from .prompts import (
PR_BODY_MINING_PROMPT,
README_MINING_PROMPT,
)
+from .source_files import (
+ _BINARY_EXTENSIONS,
+ extract_leading_prose,
+ iter_source_files,
+)
logger = structlog.get_logger(__name__)
@@ -312,108 +321,10 @@ def enabled_source_names(repo_config: dict[str, Any] | None) -> tuple[str, ...]:
# Comment marker detection
# ---------------------------------------------------------------------------
-# The keyword is deliberately case-SENSITIVE. These are annotation
-# conventions, written in caps like TODO:/FIXME:/HACK:, and matching them
-# case-insensitively turns ordinary prose into architectural decisions. Two
-# real examples from this repo, both of which reached the store as `active`
-# records: a wrapped sentence whose continuation line began "# decision:
-# namespace, batched like the pages", and a test's "# Rejected: nothing to
-# extract." Across 3,860 tracked files those were the ONLY two matches — a
-# 100% false-positive rate — because no genuine marker was written in lower
-# case. A missed marker costs one record; a false positive publishes a
-# sentence fragment as a decision governing every file it touches.
-MARKER_RE = re.compile(
- r"^\s*(?:#|//|--|/\*|\*)\s*"
- r"(?P<keyword>WHY|DECISION|TRADEOFF|ADR|RATIONALE|REJECTED)"
- r"\s*:\s*(?P<text>.+)",
-)
-
-# fs_walk's never-source set plus the two derived-output names the decision
-# walks have always skipped: a bundled ``dist``/``build`` copy of a source file
-# would double every marker it contains.
-_SKIP_DIRS = PRUNED_DIRS | {"dist", "build"}
-
-# Regex to detect fenced code blocks in markdown files (``` or ~~~).
-_CODE_FENCE_RE = re.compile(r"^\s*(`{3,}|~{3,})")
-
-_BINARY_EXTENSIONS = frozenset(
- {
- ".png",
- ".jpg",
- ".jpeg",
- ".gif",
- ".ico",
- ".svg",
- ".bmp",
- ".webp",
- ".woff",
- ".woff2",
- ".ttf",
- ".eot",
- ".otf",
- ".zip",
- ".tar",
- ".gz",
- ".bz2",
- ".rar",
- ".7z",
- ".pdf",
- ".doc",
- ".docx",
- ".xls",
- ".xlsx",
- ".pyc",
- ".pyo",
- ".so",
- ".dll",
- ".dylib",
- ".exe",
- ".db",
- ".sqlite",
- ".sqlite3",
- ".lance",
- ".lock",
- }
-)
-
-
# ---------------------------------------------------------------------------
# ADR / PR / comment source configuration
# ---------------------------------------------------------------------------
-# Conventional ADR homes, as repo-root-relative posix directories. Every ``.md``
-# directly inside one is a candidate regardless of filename; matching is on the
-# whole relative dir, so a stray ``vendor/x/adr/`` does not qualify.
-_ADR_DIRS = frozenset(
- {
- "adr",
- "adrs",
- "docs/adr",
- "docs/adrs",
- "docs/decisions",
- "decisions",
- "architecture",
- "doc/adr",
- }
-)
-_MAX_ADR_FILES = 60
-
-# Nygard/MADR section headings. Mapped to the ExtractedDecision fields they
-# populate during the deterministic (LLM-free) parse.
-_ADR_HEADING_RE = re.compile(r"^#{1,6}\s+(.+?)\s*$")
-_ADR_FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
-_ADR_STATUS_MAP = {
- "accepted": "active",
- "approved": "active",
- "active": "active",
- "proposed": "proposed",
- "draft": "proposed",
- "rejected": "deprecated",
- "deprecated": "deprecated",
- "superseded": "superseded",
-}
-
-
# PR/squash body markers — a body containing any of these reads like a PR
# description worth mining (vs an incidental multi-line commit message).
_PR_BODY_MARKERS = (
@@ -488,6 +399,117 @@ def _scope_from_selection(
+def _signal_commit_info(commit: dict) -> dict | None:
+ """The prompt-ready record of a commit with decision signals, else None."""
+ msg = commit.get("message", "")
+ body = commit.get("body", "")
+ # Scan subject + body for signals — squash-merge repos carry the
+ # decision rationale in the body, not the one-line subject.
+ signal_count = count_decision_signals(f"{msg}\n{body}".lower())
+ if signal_count <= 0:
+ return None
+ return {
+ "sha": commit.get("sha", ""),
+ "message": msg,
+ "body": body,
+ "author": commit.get("author", ""),
+ "date": commit.get("date", ""),
+ "signal_count": signal_count,
+ }
+
+async def _run_batches(
+ source: str,
+ items: Sequence[Any],
+ size: int,
+ process: Any,
+) -> list[ExtractedDecision]:
+ """Run *process* over *items* in batches of *size*, concurrently.
+
+ Each batch's failure is contained and counted by :func:`_collect_batches`,
+ which raises only when every batch failed.
+ """
+ batches = [items[i : i + size] for i in range(0, len(items), size)]
+ results = await asyncio.gather(*[process(b) for b in batches], return_exceptions=True)
+ return _collect_batches(source, list(results))
+
+
+def _attribute_to_commit(
+ decision: ExtractedDecision,
+ batch: list[dict],
+ subject_key: str,
+ files_by_sha: dict[str, list[str]],
+ source_by_sha: dict[str, str],
+) -> str:
+ """Bind a decision mined from a batch of commits to the commit it came from.
+
+ Prefers the sha the model reported, else the first commit whose subject
+ (``batch[i][subject_key]``, first 40 chars) appears in the title. Scopes
+ the decision to that commit's files and returns the sha, or ``""`` when
+ nothing matched.
+ """
+ sha = decision.evidence_commits[0] if decision.evidence_commits else ""
+ if not sha:
+ # Try to match back to a commit
+ for c in batch:
+ if c[subject_key][:40].lower() in decision.title.lower():
+ sha = c["sha"]
+ break
+ if sha:
+ decision.evidence_commits = [sha]
+ decision.affected_files, decision.scope_basis = _scope_from_selection(
+ decision, files_by_sha.get(sha)
+ )
+ decision.source_text = source_by_sha.get(sha, "")
+ # Cleared whether or not the sha resolved: an unattributed decision has no
+ # commit to validate paths against, so the model's list is unusable rather
+ # than merely unused.
+ decision.proposed_files = None
+ return sha
+
+
+def _load_json_payload(content: str) -> Any | None:
+ """Decode a model's JSON answer, tolerating code fences and surrounding prose."""
+ if content.startswith("```"):
+ # Remove markdown code fences
+ lines = content.split("\n")
+ content = "\n".join(line for line in lines if not line.strip().startswith("```"))
+ try:
+ return json.loads(content)
+ except json.JSONDecodeError:
+ pass
+ # Try to find JSON array in the response
+ match = re.search(r"\[.*\]", content, re.DOTALL)
+ if not match:
+ return None
+ try:
+ return json.loads(match.group())
+ except json.JSONDecodeError:
+ return None
+
+
+def _decision_from_item(item: dict) -> ExtractedDecision:
+ """One decision from one object of a model's JSON answer."""
+ return ExtractedDecision(
+ title=item.get("title", ""),
+ context=item.get("context", ""),
+ decision=item.get("decision", ""),
+ rationale=item.get("rationale", ""),
+ alternatives=item.get("alternatives", []),
+ consequences=item.get("consequences", []),
+ tags=item.get("tags", []),
+ # Only the two commit prompts ask for this. Every other prompt omits
+ # the key, so this stays None and the miner that owns those decisions
+ # keeps scoping them its own way.
+ proposed_files=_coerce_paths(item.get("affected_files")),
+ evidence_commits=[item["commit_sha"]] if "commit_sha" in item else [],
+ # Which marker this came from, for the inline-marker miner's per-marker
+ # attribution. Absent (and left None) for every other prompt; they
+ # scope by sha or by file instead.
+ evidence_line=_coerce_line(item.get("marker_line")),
+ source_quote=item.get("source_quote", ""),
+ )
+
+
class DecisionExtractor:
"""Extracts architectural decisions from multiple sources."""
@@ -550,103 +572,70 @@ class DecisionExtractor:
markers_found=sum(len(v) for v in markers_by_file.values()),
)
- lines = text.splitlines()
- # Track whether we're inside a fenced code block in markdown
- # files so we don't treat example markers as real decisions.
- is_markdown = Path(rel_path).suffix.lower() in (".md", ".mdx", ".rst")
- in_code_fence = False
- for line_num, line in enumerate(lines, start=1):
- if is_markdown:
- fence_match = _CODE_FENCE_RE.match(line)
- if fence_match:
- in_code_fence = not in_code_fence
- continue
- if in_code_fence:
- continue
- m = MARKER_RE.match(line)
- if m:
- # Collect continuation lines (same comment prefix, no keyword)
- marker_text = m.group("text").strip()
- for cont_line in lines[line_num : line_num + 5]:
- cont = cont_line.strip()
- if cont.startswith(("#", "//", "--", "*")) and ":" not in cont[:20]:
- # Strip comment prefix
- cleaned = re.sub(r"^\s*(?:#|//|--|/\*|\*)\s*", "", cont)
- if cleaned:
- marker_text += " " + cleaned
- else:
- break
-
- # Context window: ±20 lines
- ctx_start = max(0, line_num - 21)
- ctx_end = min(len(lines), line_num + 20)
- context = "\n".join(lines[ctx_start:ctx_end])
-
- markers_by_file.setdefault(rel_path, []).append(
- {
- "keyword": m.group("keyword"),
- "text": marker_text,
- "line": line_num,
- "context": context,
- }
- )
+ found = find_markers(rel_path, text)
+ if found:
+ markers_by_file.setdefault(rel_path, []).extend(found)
if not markers_by_file:
return []
marker_llm = self._llm("inline_marker")
decisions: list[ExtractedDecision] = []
-
for file_path, markers in markers_by_file.items():
- # Get 1-hop graph neighbors for affected_files
- affected = self._get_neighbors(file_path)
-
- markers_by_line = {m["line"]: m for m in markers}
+ decisions.extend(await self._decisions_from_markers(file_path, markers, marker_llm))
+ return decisions
- if marker_llm:
- # Use LLM to structure markers
- try:
- llm_decisions = await self._structure_markers_via_llm(file_path, markers)
- for d in llm_decisions:
- # Attribute the decision to the one marker it was drawn
- # from (the prompt asks for `marker_line`, which the
- # parser lands in `evidence_line`). Joining every
- # marker's context into one span and handing it to all
- # of them let the substring gate stamp a decision
- # `exact` against a *different* marker's text, and put
- # marker 1's line number on marker 3's decision. A
- # decision we cannot attribute gets no source span at
- # all: the gate then leaves it `unverified`, which is
- # the honest verdict, rather than verifying it against
- # a neighbour.
- marker = markers_by_line.get(d.evidence_line)
- if marker is None and len(markers) == 1:
- marker = markers[0] # unambiguous without the hint
- d.evidence_file = file_path
- d.evidence_line = marker["line"] if marker else None
- d.affected_files = list({file_path} | set(affected))
- d.affected_modules = self._infer_modules(d.affected_files)
- d.source = "inline_marker"
- d.status = "active"
- d.confidence = 0.95
- d.source_text = marker.get("context", "") if marker else ""
- decisions.extend(llm_decisions)
- except Exception:
- logger.warning(
- "decision_extractor.llm_structuring_failed",
- file=file_path,
- )
- # Fall through to raw extraction below
- for marker in markers:
- decisions.append(
- self._raw_decision_from_marker(file_path, marker, affected)
- )
- else:
- # No LLM — create minimal decisions from raw marker text
- for marker in markers:
- decisions.append(self._raw_decision_from_marker(file_path, marker, affected))
+ async def _decisions_from_markers(
+ self, file_path: str, markers: list[dict], marker_llm: Any | None
+ ) -> list[ExtractedDecision]:
+ """One file's markers as decisions: model-structured when possible, else raw."""
+ # Get 1-hop graph neighbors for affected_files
+ affected = self._get_neighbors(file_path)
+ if not marker_llm:
+ # No LLM — create minimal decisions from raw marker text
+ return [self._raw_decision_from_marker(file_path, m, affected) for m in markers]
+ try:
+ llm_decisions = await self._structure_markers_via_llm(file_path, markers)
+ self._attribute_to_markers(llm_decisions, file_path, markers, affected)
+ except Exception:
+ logger.warning(
+ "decision_extractor.llm_structuring_failed",
+ file=file_path,
+ )
+ # Fall through to raw extraction
+ return [self._raw_decision_from_marker(file_path, m, affected) for m in markers]
+ return llm_decisions
- return decisions
+ def _attribute_to_markers(
+ self,
+ decisions: list[ExtractedDecision],
+ file_path: str,
+ markers: list[dict],
+ affected: list[str],
+ ) -> None:
+ """Bind each model-structured decision to the marker it was drawn from."""
+ markers_by_line = {m["line"]: m for m in markers}
+ for d in decisions:
+ # Attribute the decision to the one marker it was drawn from (the
+ # prompt asks for `marker_line`, which the parser lands in
+ # `evidence_line`). Joining every marker's context into one span
+ # and handing it to all of them let the substring gate stamp a
+ # decision `exact` against a *different* marker's text, and put
+ # marker 1's line number on marker 3's decision. A decision we
+ # cannot attribute gets no source span at all: the gate then leaves
+ # it `unverified`, which is the honest verdict, rather than
+ # verifying it against a neighbour.
+ marker = markers_by_line.get(d.evidence_line)
+ if marker is None and len(markers) == 1:
+ marker = markers[0] # unambiguous without the hint
+ d.evidence_file = file_path
+ d.evidence_line = marker["line"] if marker else None
+ d.affected_files = list({file_path} | set(affected))
+ d.affected_modules = self._infer_modules(d.affected_files)
+ d.source = "inline_marker"
+ d.status = "active"
+ d.confidence = 0.95
+ d.source_text = marker.get("context", "") if marker else ""
def _raw_decision_from_marker(
self,
@@ -719,42 +708,7 @@ class DecisionExtractor:
if not provider or not self._git_meta_map:
return []
- # Collect unique significant commits with decision signals
- commit_map: dict[str, dict] = {} # sha → commit info
- commit_files: dict[str, list[str]] = {} # sha → files
-
- for file_path, meta in self._git_meta_map.items():
- commits_json = meta.get("significant_commits_json", "[]")
- if isinstance(commits_json, str):
- try:
- commits = json.loads(commits_json)
- except (json.JSONDecodeError, TypeError):
- continue
- else:
- commits = commits_json
-
- for commit in commits:
- sha = commit.get("sha", "")
- if not sha or sha in commit_map:
- commit_files.setdefault(sha, []).append(file_path)
- continue
- msg = commit.get("message", "")
- body = commit.get("body", "")
- # Scan subject + body for signals — squash-merge repos carry the
- # decision rationale in the body, not the one-line subject.
- signal_text = f"{msg}\n{body}".lower()
- signal_count = count_decision_signals(signal_text)
- if signal_count > 0:
- commit_map[sha] = {
- "sha": sha,
- "message": msg,
- "body": body,
- "author": commit.get("author", ""),
- "date": commit.get("date", ""),
- "signal_count": signal_count,
- }
- commit_files.setdefault(sha, []).append(file_path)
-
+ commit_map, commit_files = self._signal_commits()
if not commit_map:
return []
@@ -766,9 +720,6 @@ class DecisionExtractor:
)[:20]
# Batch LLM calls (5 commits per batch)
- decisions: list[ExtractedDecision] = []
- batches = [ranked[i : i + 5] for i in range(0, len(ranked), 5)]
-
async def _process_batch(batch: list[dict]) -> list[ExtractedDecision]:
commits_block = ""
source_by_sha: dict[str, str] = {}
@@ -795,23 +746,7 @@ class DecisionExtractor:
# Enrich with commit metadata
for d in extracted:
- sha = d.evidence_commits[0] if d.evidence_commits else ""
- if not sha:
- # Try to match back to a commit
- for c in batch:
- if c["message"][:40].lower() in d.title.lower():
- sha = c["sha"]
- break
- if sha:
- d.evidence_commits = [sha]
- d.affected_files, d.scope_basis = _scope_from_selection(
- d, commit_files.get(sha)
- )
- d.source_text = source_by_sha.get(sha, "")
- # Cleared whether or not the sha resolved: an unattributed
- # decision has no commit to validate paths against, so the
- # model's list is unusable rather than merely unused.
- d.proposed_files = None
+ sha = _attribute_to_commit(d, batch, "message", commit_files, source_by_sha)
d.source = "git_archaeology"
d.status = "proposed"
signal = max(
@@ -823,13 +758,35 @@ class DecisionExtractor:
return extracted
- results = await asyncio.gather(
- *[_process_batch(b) for b in batches],
- return_exceptions=True,
- )
- decisions.extend(_collect_batches("git_archaeology", list(results)))
+ return await _run_batches("git_archaeology", ranked, 5, _process_batch)
- return decisions
+ def _signal_commits(self) -> tuple[dict[str, dict], dict[str, list[str]]]:
+ """Unique significant commits carrying decision signals, and each one's files.
+
+ Returns ``(sha -> commit info, sha -> files it touched)``.
+ """
+ commit_map: dict[str, dict] = {} # sha → commit info
+ commit_files: dict[str, list[str]] = {} # sha → files
+
+ for file_path, meta in self._git_meta_map.items():
+ commits_json = meta.get("significant_commits_json", "[]")
+ if isinstance(commits_json, str):
+ try:
+ commits = json.loads(commits_json)
+ except (json.JSONDecodeError, TypeError):
+ continue
+ else:
+ commits = commits_json
+
+ for commit in commits:
+ sha = commit.get("sha", "")
+ if sha and sha not in commit_map:
+ info = _signal_commit_info(commit)
+ if info is None:
+ continue
+ commit_map[sha] = info
+ commit_files.setdefault(sha, []).append(file_path)
+ return commit_map, commit_files
# ------------------------------------------------------------------
# Source 3: ADR auto-discovery (deterministic-first)
@@ -844,7 +801,7 @@ class DecisionExtractor:
carry an ADR name but no recognizable structure fall back to the LLM
prose miner when a provider is available. Highest source rank.
"""
- adr_paths = self._find_adr_files()
+ adr_paths = find_adr_files(self._repo_path)
if not adr_paths:
return []
provider = self._llm("adr")
@@ -867,7 +824,7 @@ class DecisionExtractor:
decisions.append(parsed)
elif provider:
try:
- stripped = self._strip_code_blocks(content)
+ stripped = strip_code_blocks(content)
prompt = README_MINING_PROMPT.format(file_path=rel, content=stripped[:15_000])
response = await provider.generate(
_SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
@@ -887,57 +844,6 @@ class DecisionExtractor:
return decisions
- def _find_adr_files(self) -> list[Path]:
- """Collect candidate ADR files from the conventional dirs + name match.
-
- One :func:`walk_repo` pass answers both halves: files directly under a
- conventional ADR directory (root-anchored, as the old shallow globs
- were) rank ahead of loose ``*adr*.md`` name matches, and the cap is
- applied to the two buckets in that order.
-
- Ignored paths are excluded. :mod:`repowise.core.fs_walk` prunes junk
- dirs and nested repos but deliberately reads no ignore files, so
- gitignore/``info/exclude`` handling is this function's job: without it
- a scratch dir that ``git status`` cannot see contributes ``active``
- decision records citing files no clone of the repo contains.
- """
- ignore = load_gitignore_spec(self._repo_path)
- conventional: list[Path] = []
- loose: list[Path] = []
- for dirpath, dirnames, filenames in walk_repo(self._repo_path, prune_dirs=_SKIP_DIRS):
- rel_dir = dirpath.relative_to(self._repo_path).as_posix()
- rel_dir = "" if rel_dir == "." else rel_dir
- # Prune ignored and packaging-metadata subtrees in place. Ignored
- # DIRECTORIES match with a trailing slash, as git matches them.
- dirnames[:] = [
- d
- for d in dirnames
- if not d.endswith((".egg-info", ".dist-info"))
- and not ignore.match_file(f"{rel_dir}/{d}/" if rel_dir else f"{d}/")
- ]
-
- in_adr_dir = rel_dir in _ADR_DIRS
- for fname in filenames:
- low = fname.lower()
- if not low.endswith(".md"):
- continue
- if in_adr_dir:
- bucket = conventional
- elif "adr" in low and low != "readme.md" and "template" not in low:
- bucket = loose
- else:
- continue
- if ignore.match_file(f"{rel_dir}/{fname}" if rel_dir else fname):
- continue
- bucket.append(dirpath / fname)
-
- if len(conventional) + len(loose) >= _MAX_ADR_FILES:
- break
-
- # No dedup pass: walk_repo yields each directory once, and each file
- # lands in exactly one bucket.
- return [*conventional, *loose][:_MAX_ADR_FILES]
-
def _parse_adr(self, content: str, rel_path: str) -> ExtractedDecision | None:
"""Deterministically parse a structured ADR. Returns None if unstructured.
@@ -945,23 +851,8 @@ class DecisionExtractor:
decision is grounded by construction and passes the substring gate as
``exact``.
"""
- status = ""
- title = ""
- body = content
- fm = _ADR_FRONTMATTER_RE.match(content)
- if fm:
- for line in fm.group(1).splitlines():
- if ":" in line:
- k, _, v = line.partition(":")
- key = k.strip().lower()
- val = v.strip().strip("\"'")
- if key == "status":
- status = val
- elif key == "title":
- title = val
- body = content[fm.end() :]
-
- sections = self._split_headings(body)
+ status, title, body = read_front_matter(content)
+ sections = split_headings(body)
if not title:
m = re.search(r"^#\s+(.+)$", body, re.MULTILINE)
if m:
@@ -993,7 +884,7 @@ class DecisionExtractor:
context=context.strip(),
decision=decision_txt.strip(),
rationale=rationale.strip(),
- consequences=self._bullets(consequences),
+ consequences=bullets(consequences),
source="adr",
status=mapped_status,
confidence=0.90,
@@ -1040,7 +931,6 @@ class DecisionExtractor:
return []
ranked = list(candidates.values())[:_MAX_PR_BODIES]
- batches = [ranked[i : i + 5] for i in range(0, len(ranked), 5)]
async def _process_batch(batch: list[dict]) -> list[ExtractedDecision]:
bodies_block = ""
@@ -1070,29 +960,14 @@ class DecisionExtractor:
)
extracted = self._parse_decisions_json(response.content)
for d in extracted:
- sha = d.evidence_commits[0] if d.evidence_commits else ""
- if not sha:
- for c in batch:
- if c["subject"][:40].lower() in d.title.lower():
- sha = c["sha"]
- break
- if sha:
- d.evidence_commits = [sha]
- d.affected_files, d.scope_basis = _scope_from_selection(
- d, files_by_sha.get(sha)
- )
- d.source_text = source_by_sha.get(sha, "")
- d.proposed_files = None
+ _attribute_to_commit(d, batch, "subject", files_by_sha, source_by_sha)
d.source = "pr"
d.status = "proposed"
d.confidence = 0.80
d.affected_modules = self._infer_modules(d.affected_files)
return extracted
- results = await asyncio.gather(
- *[_process_batch(b) for b in batches], return_exceptions=True
- )
- return _collect_batches("pr", list(results))
+ return await _run_batches("pr", ranked, 5, _process_batch)
# ------------------------------------------------------------------
# Source 5: Comment archaeology (centrality-bounded)
@@ -1116,15 +991,12 @@ class DecisionExtractor:
snippets: list[tuple[str, str]] = []
for fp in top_files:
- prose = self._extract_leading_prose(fp)
+ prose = extract_leading_prose(self._repo_path, fp)
if prose and any(cue in prose.lower() for cue in _COMMENT_RATIONALE_CUES):
snippets.append((fp, prose))
if not snippets:
return []
- decisions: list[ExtractedDecision] = []
- batches = [snippets[i : i + 4] for i in range(0, len(snippets), 4)]
-
async def _process_batch(batch: list[tuple[str, str]]) -> list[ExtractedDecision]:
comments_block = ""
for fp, prose in batch:
@@ -1156,11 +1028,7 @@ class DecisionExtractor:
d.affected_modules = self._infer_modules([best_fp])
return extracted
- results = await asyncio.gather(
- *[_process_batch(b) for b in batches], return_exceptions=True
- )
- decisions.extend(_collect_batches("comment", list(results)))
- return decisions
+ return await _run_batches("comment", snippets, 4, _process_batch)
# ------------------------------------------------------------------
# Source 6: Conventions (deterministic, graph-counted)
@@ -1219,41 +1087,6 @@ class DecisionExtractor:
out.append(node)
return out
- def _extract_leading_prose(self, file_path: str) -> str:
- """Return the leading module docstring / header comment block of a file."""
- p = self._repo_path / file_path
- try:
- text = p.read_text(encoding="utf-8", errors="replace")
- except (OSError, UnicodeDecodeError):
- return ""
- prose: list[str] = []
- in_doc = False
- for line in text.splitlines()[:120]:
- s = line.strip()
- if not in_doc and (s.startswith('"""') or s.startswith("'''")):
- quote = s[:3]
- inner = s.strip("\"' ")
- if inner:
- prose.append(inner)
- # Single-line docstring closes on the same line.
- if s.count(quote) < 2:
- in_doc = True
- continue
- if in_doc:
- if s.endswith('"""') or s.endswith("'''"):
- in_doc = False
- inner = s.strip("\"' ")
- if inner:
- prose.append(inner)
- else:
- prose.append(s)
- continue
- if s.startswith(("#", "//", "*", "/*", "--")):
- cleaned = re.sub(r"^\s*(?:#|//|--|/\*|\*/|\*)\s?", "", s)
- if cleaned:
- prose.append(cleaned)
- return "\n".join(prose).strip()[:2000]
-
@staticmethod
def _loads_commits(value: Any) -> list[dict]:
"""Parse a ``significant_commits_json`` blob into a list of dicts."""
@@ -1267,37 +1100,6 @@ class DecisionExtractor:
return data if isinstance(data, list) else []
return []
- @staticmethod
- def _split_headings(text: str) -> dict[str, str]:
- """Map lowercased markdown headings to their section bodies."""
- sections: dict[str, str] = {}
- current: str | None = None
- buf: list[str] = []
- for line in text.splitlines():
- m = _ADR_HEADING_RE.match(line)
- if m:
- if current is not None:
- sections[current] = "\n".join(buf).strip()
- current = m.group(1).strip().lower()
- buf = []
- elif current is not None:
- buf.append(line)
- if current is not None:
- sections[current] = "\n".join(buf).strip()
- return sections
-
- @staticmethod
- def _bullets(text: str) -> list[str]:
- """Extract markdown bullet items from a section body."""
- out: list[str] = []
- for line in text.splitlines():
- s = line.strip()
- if s.startswith(("-", "*", "+")):
- item = s[1:].strip()
- if item:
- out.append(item)
- return out
-
# ------------------------------------------------------------------
# Anti-hallucination substring gate (Phase 1D)
# ------------------------------------------------------------------
@@ -1522,7 +1324,7 @@ class DecisionExtractor:
yield rel_path, source.decode("utf-8", errors="replace")
return
- for file_path in self._iter_source_files():
+ for file_path in iter_source_files(self._repo_path):
if not file_path.is_file():
continue
try:
@@ -1553,70 +1355,6 @@ class DecisionExtractor:
except (OSError, UnicodeDecodeError):
return None
- def _tracked_files(self) -> set[Path] | None:
- """Resolved paths git tracks under ``repo_path``, or ``None``.
-
- ``None`` means "no git scoping available" (not a git repo, git missing,
- or the command failed) — callers then fall back to walking the tree.
- Restricting to tracked files keeps untracked / gitignored / git-excluded
- working directories (``local-stash/``, vendored dumps, scratch folders)
- out of the harvest: their comments are not part of the indexed codebase
- and must not become decision records.
- """
- import subprocess
-
- try:
- proc = subprocess.run(
- ["git", "-C", str(self._repo_path), "ls-files", "-z"],
- capture_output=True,
- timeout=30,
- check=False,
- )
- except (OSError, subprocess.SubprocessError):
- return None
- if proc.returncode != 0 or not proc.stdout:
- return None
- out = proc.stdout.decode("utf-8", errors="replace")
- tracked: set[Path] = set()
- for rel in out.split("\0"):
- if not rel:
- continue
- try:
- tracked.add((self._repo_path / rel).resolve())
- except OSError:
- continue
- return tracked or None
-
- def _iter_source_files(self):
- """Yield source files under repo_path, skipping irrelevant dirs.
-
- Walks via :func:`walk_repo`, which prunes junk subtrees and nested git
- repos (separate codebases that must not contribute decisions to the
- parent) without descending into them. When the repo is a git checkout,
- the walk is further restricted to git-tracked files so untracked /
- excluded working directories never contribute decisions; gitless
- indexes fall back to the full walk.
- """
- tracked = self._tracked_files()
-
- for dirpath, dirnames, filenames in walk_repo(self._repo_path, prune_dirs=_SKIP_DIRS):
- # Skip setuptools build metadata: PKG-INFO embeds the README
- # verbatim, so example marker lines in docs become spurious
- # decisions. Same risk for *.dist-info from wheels.
- dirnames[:] = [d for d in dirnames if not d.endswith((".egg-info", ".dist-info"))]
-
- for fname in filenames:
- fpath = Path(dirpath) / fname
- if fpath.suffix.lower() in _BINARY_EXTENSIONS:
- continue
- if tracked is not None:
- try:
- if fpath.resolve() not in tracked:
- continue
- except OSError:
- continue
- yield fpath
-
def _get_neighbors(self, file_path: str) -> list[str]:
"""Get 1-hop graph neighbors for a file."""
if self._graph is None:
@@ -1628,20 +1366,6 @@ class DecisionExtractor:
neighbors.discard(file_path)
return list(neighbors)[:20] # Cap at 20
- @staticmethod
- def _strip_code_blocks(text: str) -> str:
- """Remove fenced code blocks from markdown to avoid parsing examples."""
- lines = text.splitlines()
- out: list[str] = []
- in_fence = False
- for line in lines:
- if _CODE_FENCE_RE.match(line):
- in_fence = not in_fence
- continue
- if not in_fence:
- out.append(line)
- return "\n".join(out)
-
def _infer_modules(self, file_paths: list[str]) -> list[str]:
"""Infer the module paths a record governs from the files it names."""
return resolve_module_nodes(file_paths)
@@ -1700,55 +1424,13 @@ class DecisionExtractor:
raise EmptyModelResponseError(
"the model returned no content for this batch"
)
- if content.startswith("```"):
- # Remove markdown code fences
- lines = content.split("\n")
- content = "\n".join(line for line in lines if not line.strip().startswith("```"))
-
- try:
- data = json.loads(content)
- except json.JSONDecodeError:
- # Try to find JSON array in the response
- match = re.search(r"\[.*\]", content, re.DOTALL)
- if match:
- try:
- data = json.loads(match.group())
- except json.JSONDecodeError:
- return []
- else:
- return []
-
+ data = _load_json_payload(content)
if isinstance(data, dict):
data = [data]
if not isinstance(data, list):
return []
-
- decisions = []
- for item in data:
- if not isinstance(item, dict):
- continue
- title = item.get("title", "")
- if not title:
- continue
- decisions.append(
- ExtractedDecision(
- title=title,
- context=item.get("context", ""),
- decision=item.get("decision", ""),
- rationale=item.get("rationale", ""),
- alternatives=item.get("alternatives", []),
- consequences=item.get("consequences", []),
- tags=item.get("tags", []),
- # Only the two commit prompts ask for this. Every other
- # prompt omits the key, so this stays None and the miner
- # that owns those decisions keeps scoping them its own way.
- proposed_files=_coerce_paths(item.get("affected_files")),
- evidence_commits=[item["commit_sha"]] if "commit_sha" in item else [],
- # Which marker this came from, for the inline-marker miner's
- # per-marker attribution. Absent (and left None) for every
- # other prompt — they scope by sha or by file instead.
- evidence_line=_coerce_line(item.get("marker_line")),
- source_quote=item.get("source_quote", ""),
- )
- )
- return decisions
+ return [
+ _decision_from_item(item)
+ for item in data
+ if isinstance(item, dict) and item.get("title", "")
+ ]
diff --git a/packages/core/src/repowise/core/analysis/decisions/markers.py b/packages/core/src/repowise/core/analysis/decisions/markers.py
new file mode 100644
index 000000000..269646369
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/markers.py
@@ -0,0 +1,80 @@
+"""Inline decision markers (``# WHY:``, ``# DECISION:`` ...) in source text."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+# Case-sensitive on purpose: markers are caps conventions like TODO:, and a
+# lowercase match turns ordinary prose ("# decision: ...") into a decision.
+MARKER_RE = re.compile(
+ r"^\s*(?:#|//|--|/\*|\*)\s*"
+ r"(?P<keyword>WHY|DECISION|TRADEOFF|ADR|RATIONALE|REJECTED)"
+ r"\s*:\s*(?P<text>.+)",
+)
+
+# Regex to detect fenced code blocks in markdown files (``` or ~~~).
+_CODE_FENCE_RE = re.compile(r"^\s*(`{3,}|~{3,})")
+
+
+def strip_code_blocks(text: str) -> str:
+ """Remove fenced code blocks from markdown to avoid parsing examples."""
+ lines = text.splitlines()
+ out: list[str] = []
+ in_fence = False
+ for line in lines:
+ if _CODE_FENCE_RE.match(line):
+ in_fence = not in_fence
+ continue
+ if not in_fence:
+ out.append(line)
+ return "\n".join(out)
+
+
+def find_markers(rel_path: str, text: str) -> list[dict]:
+ """Every decision marker in one file, with its continuation and context.
+
+ Markers inside fenced code blocks of a markdown file are examples, not
+ decisions, and are skipped.
+ """
+ lines = text.splitlines()
+ # Track whether we're inside a fenced code block in markdown
+ # files so we don't treat example markers as real decisions.
+ is_markdown = Path(rel_path).suffix.lower() in (".md", ".mdx", ".rst")
+ in_code_fence = False
+ found: list[dict] = []
+ for line_num, line in enumerate(lines, start=1):
+ if is_markdown:
+ if _CODE_FENCE_RE.match(line):
+ in_code_fence = not in_code_fence
+ continue
+ if in_code_fence:
+ continue
+ m = MARKER_RE.match(line)
+ if not m:
+ continue
+ # Context window: ±20 lines
+ ctx_start = max(0, line_num - 21)
+ ctx_end = min(len(lines), line_num + 20)
+ found.append(
+ {
+ "keyword": m.group("keyword"),
+ "text": _with_continuation(m.group("text").strip(), lines[line_num : line_num + 5]),
+ "line": line_num,
+ "context": "\n".join(lines[ctx_start:ctx_end]),
+ }
+ )
+ return found
+
+
+def _with_continuation(marker_text: str, following: list[str]) -> str:
+ """Append continuation lines (same comment prefix, no keyword) to a marker."""
+ for cont_line in following:
+ cont = cont_line.strip()
+ if not (cont.startswith(("#", "//", "--", "*")) and ":" not in cont[:20]):
+ break
+ # Strip comment prefix
+ cleaned = re.sub(r"^\s*(?:#|//|--|/\*|\*)\s*", "", cont)
+ if cleaned:
+ marker_text += " " + cleaned
+ return marker_text
diff --git a/packages/core/src/repowise/core/analysis/decisions/source_files.py b/packages/core/src/repowise/core/analysis/decisions/source_files.py
new file mode 100644
index 000000000..a9973d843
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/source_files.py
@@ -0,0 +1,159 @@
+"""Which repository files decision mining reads, and how it reads them."""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterator
+from pathlib import Path
+
+from repowise.core.fs_walk import PRUNED_DIRS, walk_repo
+
+# fs_walk's never-source set plus the two derived-output names the decision
+# walks have always skipped: a bundled ``dist``/``build`` copy of a source file
+# would double every marker it contains.
+_SKIP_DIRS = PRUNED_DIRS | {"dist", "build"}
+
+_BINARY_EXTENSIONS = frozenset(
+ {
+ ".png",
+ ".jpg",
+ ".jpeg",
+ ".gif",
+ ".ico",
+ ".svg",
+ ".bmp",
+ ".webp",
+ ".woff",
+ ".woff2",
+ ".ttf",
+ ".eot",
+ ".otf",
+ ".zip",
+ ".tar",
+ ".gz",
+ ".bz2",
+ ".rar",
+ ".7z",
+ ".pdf",
+ ".doc",
+ ".docx",
+ ".xls",
+ ".xlsx",
+ ".pyc",
+ ".pyo",
+ ".so",
+ ".dll",
+ ".dylib",
+ ".exe",
+ ".db",
+ ".sqlite",
+ ".sqlite3",
+ ".lance",
+ ".lock",
+ }
+)
+
+
+def tracked_files(repo_path: Path) -> set[Path] | None:
+ """Resolved paths git tracks under ``repo_path``, or ``None``.
+
+ ``None`` means "no git scoping available" (not a git repo, git missing,
+ or the command failed) — callers then fall back to walking the tree.
+ Restricting to tracked files keeps untracked / gitignored / git-excluded
+ working directories (``local-stash/``, vendored dumps, scratch folders)
+ out of the harvest: their comments are not part of the indexed codebase
+ and must not become decision records.
+ """
+ import subprocess
+
+ try:
+ proc = subprocess.run(
+ ["git", "-C", str(repo_path), "ls-files", "-z"],
+ capture_output=True,
+ timeout=30,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if proc.returncode != 0 or not proc.stdout:
+ return None
+ out = proc.stdout.decode("utf-8", errors="replace")
+ tracked: set[Path] = set()
+ for rel in out.split("\0"):
+ if not rel:
+ continue
+ try:
+ tracked.add((repo_path / rel).resolve())
+ except OSError:
+ continue
+ return tracked or None
+
+
+def iter_source_files(repo_path: Path) -> Iterator[Path]:
+ """Yield source files under repo_path, skipping irrelevant dirs.
+
+ Walks via :func:`walk_repo`, which prunes junk subtrees and nested git
+ repos (separate codebases that must not contribute decisions to the
+ parent) without descending into them. When the repo is a git checkout,
+ the walk is further restricted to git-tracked files so untracked /
+ excluded working directories never contribute decisions; gitless
+ indexes fall back to the full walk.
+ """
+ tracked = tracked_files(repo_path)
+
+ for dirpath, dirnames, filenames in walk_repo(repo_path, prune_dirs=_SKIP_DIRS):
+ # Skip setuptools build metadata: PKG-INFO embeds the README
+ # verbatim, so example marker lines in docs become spurious
+ # decisions. Same risk for *.dist-info from wheels.
+ dirnames[:] = [d for d in dirnames if not d.endswith((".egg-info", ".dist-info"))]
+
+ for fname in filenames:
+ fpath = Path(dirpath) / fname
+ if fpath.suffix.lower() in _BINARY_EXTENSIONS:
+ continue
+ if tracked is not None and not _is_tracked(fpath, tracked):
+ continue
+ yield fpath
+
+
+def _is_tracked(fpath: Path, tracked: set[Path]) -> bool:
+ try:
+ return fpath.resolve() in tracked
+ except OSError:
+ return False
+
+
+def extract_leading_prose(repo_path: Path, file_path: str) -> str:
+ """Return the leading module docstring / header comment block of a file."""
+ p = repo_path / file_path
+ try:
+ text = p.read_text(encoding="utf-8", errors="replace")
+ except (OSError, UnicodeDecodeError):
+ return ""
+ prose: list[str] = []
+ in_doc = False
+ for line in text.splitlines()[:120]:
+ s = line.strip()
+ if not in_doc and (s.startswith('"""') or s.startswith("'''")):
+ quote = s[:3]
+ inner = s.strip("\"' ")
+ if inner:
+ prose.append(inner)
+ # Single-line docstring closes on the same line.
+ if s.count(quote) < 2:
+ in_doc = True
+ continue
+ if in_doc:
+ if s.endswith('"""') or s.endswith("'''"):
+ in_doc = False
+ inner = s.strip("\"' ")
+ if inner:
+ prose.append(inner)
+ else:
+ prose.append(s)
+ continue
+ if s.startswith(("#", "//", "*", "/*", "--")):
+ cleaned = re.sub(r"^\s*(?:#|//|--|/\*|\*/|\*)\s?", "", s)
+ if cleaned:
+ prose.append(cleaned)
+ return "\n".join(prose).strip()[:2000]