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(analysis): group decision_*.py into an analysis/decisions/ package (#259)

Swati Ahuja1e22903cb675
diff --git a/packages/core/src/repowise/core/analysis/decision_evolution.py b/packages/core/src/repowise/core/analysis/decision_evolution.py
index 18ca0777c..e360989c8 100644
--- a/packages/core/src/repowise/core/analysis/decision_evolution.py
+++ b/packages/core/src/repowise/core/analysis/decision_evolution.py
@@ -1,688 +1,8 @@
-"""Decision evolution — supersession/conflict detection + two-pass update scan.
+"""Back-compat façade — moved to ``repowise.core.analysis.decisions.evolution``.
-Phase 3B + 3C of the decision-layer overhaul. Two complementary mechanisms,
-both small and gated, both leaning on the Phase-2 primitives
-(:data:`decision_semantic_match.DEFAULT_DEDUP_TAU` for similarity and
-:func:`decision_gate.apply_substring_gate` for anti-hallucination):
-
-**3B — semantic supersession & conflict** (:func:`detect_supersessions_and_conflicts`).
- When a freshly upserted decision is semantically *about the same topic* as
- an existing one (cosine in the band ``[RELATED_TAU, DEDUP_TAU)`` — related
- but not a duplicate) **and** contradicts it (opposing verbs / a reversal
- signal, optionally confirmed by a gated LLM judge), record a typed edge:
- ``supersedes`` when one clearly reverses the other (auto-flip the older to
- ``superseded`` only above :data:`SUPERSEDE_AUTOFLIP_CONFIDENCE`, otherwise a
- reviewable proposal), or ``conflicts_with`` when two *active* decisions
- contradict with no clear winner.
-
-**3C — two-pass evolution on ``repowise update``** (:func:`run_update_evolution`).
- Pass 1 (cheap, no LLM): scan changed files' diffs + new commit bodies for
- evolution signals (``migrate``/``replace``/``deprecate``/…) and cross-ref
- existing decisions touching those files. Pass 2 (LLM, survivors only,
- gated): ask whether each surviving decision is *amended* / *superseded* /
- *reaffirmed* by the change. The caller runs this **before** page
- regeneration so the governed pages of an amended decision re-render in the
- same run.
-
-Cheap-before-expensive: Pass 1 gates Pass 2 (LLM only on survivors); semantic
-comparisons reuse the shared store; edge writes are O(candidates); the lineage
-walk that consumes these edges is bounded elsewhere.
+Import from the new path; this re-export keeps existing imports working.
"""
from __future__ import annotations
-import json
-import re
-from typing import Any
-
-import structlog
-
-from repowise.core.analysis.decision_gate import apply_substring_gate
-from repowise.core.analysis.decision_provenance import normalize_text
-from repowise.core.analysis.decision_semantic_match import (
- DEFAULT_DEDUP_TAU,
- find_related_decisions,
-)
-
-logger = structlog.get_logger(__name__)
-
-__all__ = [
- "EVOLUTION_SIGNALS",
- "RELATED_TAU",
- "SUPERSEDE_AUTOFLIP_CONFIDENCE",
- "contradicts",
- "detect_supersessions_and_conflicts",
- "is_reversal",
- "pass1_evolution_candidates",
- "run_update_evolution",
- "scan_evolution_signals",
- "supersession_confidence",
-]
-
-# ---------------------------------------------------------------------------
-# Tunable knobs (live next to DEFAULT_DEDUP_TAU; pick empirically on real repos)
-# ---------------------------------------------------------------------------
-
-# Lower bound of the "same topic" similarity band. The upper bound is the dedup
-# threshold: above it the two would have merged into one record (not a
-# supersession); below RELATED_TAU they are unrelated. So a supersession
-# candidate sits in ``[RELATED_TAU, DEFAULT_DEDUP_TAU)``.
-RELATED_TAU = 0.6
-
-# A detected supersession always records the edge; the *older* decision is only
-# auto-flipped to ``superseded`` when confidence clears this bar. Conservative
-# by design — everything below stays a reviewable proposal.
-SUPERSEDE_AUTOFLIP_CONFIDENCE = 0.85
-
-# ---------------------------------------------------------------------------
-# Evolution signals (Pass-1 pattern scan) + contradiction heuristics
-# ---------------------------------------------------------------------------
-
-# Substrings that, in a diff or commit body, hint the change *evolves* a prior
-# decision rather than just touching code. Kept lowercase; matched as substrings.
-EVOLUTION_SIGNALS: frozenset[str] = frozenset(
- {
- "migrate",
- "migrated",
- "migration",
- "replace",
- "replaced",
- "switch to",
- "switched to",
- "move to",
- "moved to",
- "move away",
- "moved away",
- "chose",
- "choose",
- "because",
- "instead of",
- "rather than",
- "deprecate",
- "deprecated",
- "revert",
- "reverted",
- "no longer",
- "stop using",
- "drop ",
- "dropped ",
- "in favor of",
- "in favour of",
- }
-)
-
-# Directional reversal phrases: their presence in the *newer* decision means it
-# reverses/replaces a predecessor (→ supersedes, not merely conflicts).
-_REVERSAL_SIGNALS: tuple[str, ...] = (
- "replace",
- "replaced",
- "migrate",
- "migrated",
- "migration",
- "switch to",
- "switched to",
- "move away",
- "moved away",
- "move to",
- "moved to",
- "revert",
- "reverted",
- "deprecate",
- "deprecated",
- "no longer",
- "stop using",
- "instead of",
- "in favor of",
- "in favour of",
-)
-
-# Opposing verb/intent pairs. A pair where one side appears in text A and the
-# other in text B signals the two decisions push in opposite directions.
-_OPPOSING_VERB_PAIRS: tuple[tuple[frozenset[str], frozenset[str]], ...] = (
- (
- frozenset(
- {"adopt", "adopted", "use", "using", "add", "added", "introduce", "enable", "enabled"}
- ),
- frozenset(
- {
- "drop",
- "dropped",
- "remove",
- "removed",
- "deprecate",
- "deprecated",
- "disable",
- "disabled",
- "revert",
- "reverted",
- "abandon",
- }
- ),
- ),
- (
- frozenset({"switch to", "migrate to", "move to"}),
- frozenset({"revert", "roll back", "rollback", "move back"}),
- ),
- (
- frozenset({"sync", "synchronous", "blocking"}),
- frozenset({"async", "asynchronous", "non-blocking"}),
- ),
- (frozenset({"monolith", "monolithic"}), frozenset({"microservice", "microservices"})),
-)
-
-_STOPWORDS = frozenset(
- {
- "the",
- "a",
- "an",
- "to",
- "of",
- "for",
- "and",
- "or",
- "in",
- "on",
- "with",
- "we",
- "our",
- "use",
- "using",
- "should",
- "this",
- "that",
- "is",
- "are",
- "be",
- "by",
- "as",
- "it",
- "its",
- "from",
- "at",
- "via",
- "into",
- }
-)
-
-_TOKEN_RE = re.compile(r"[a-z0-9]+")
-
-
-def _content_tokens(text: str) -> set[str]:
- """Lowercased content tokens (stopwords + short tokens dropped)."""
- return {
- t for t in _TOKEN_RE.findall((text or "").lower()) if len(t) > 2 and t not in _STOPWORDS
- }
-
-
-def _shared_topic(text_a: str, text_b: str, *, min_shared: int = 2) -> bool:
- """Do two texts share enough content tokens to be 'about the same thing'?"""
- return len(_content_tokens(text_a) & _content_tokens(text_b)) >= min_shared
-
-
-def scan_evolution_signals(text: str) -> list[str]:
- """Return the evolution signals present in *text* (Pass-1 cheap filter)."""
- low = normalize_text(text)
- if not low:
- return []
- return sorted(s for s in EVOLUTION_SIGNALS if s.strip() in low)
-
-
-def is_reversal(text: str) -> tuple[bool, str]:
- """Does *text* read like it reverses/replaces a prior choice? → (bool, signal)."""
- low = normalize_text(text)
- for sig in _REVERSAL_SIGNALS:
- if sig in low:
- return True, sig
- return False, ""
-
-
-def contradicts(text_a: str, text_b: str) -> tuple[bool, str]:
- """Heuristic: do two decision texts push in opposite directions?
-
- True when (a) an opposing verb pair straddles the two texts, or (b) either
- text carries a directional reversal signal — *and* the two share enough
- content tokens to be about the same topic (so "deprecate X" and "adopt Y"
- for unrelated X/Y don't false-positive). Returns ``(bool, signal)``.
- """
- if not _shared_topic(text_a, text_b):
- return False, ""
- low_a = normalize_text(text_a)
- low_b = normalize_text(text_b)
-
- for left, right in _OPPOSING_VERB_PAIRS:
- a_left = any(v in low_a for v in left)
- b_right = any(v in low_b for v in right)
- a_right = any(v in low_a for v in right)
- b_left = any(v in low_b for v in left)
- if (a_left and b_right) or (a_right and b_left):
- return True, "opposing-verbs"
-
- rev_a, sig_a = is_reversal(text_a)
- if rev_a:
- return True, sig_a
- rev_b, sig_b = is_reversal(text_b)
- if rev_b:
- return True, sig_b
- return False, ""
-
-
-def supersession_confidence(
- similarity: float,
- *,
- verified: bool = False,
- has_reversal_signal: bool = False,
-) -> float:
- """Confidence that one decision supersedes another. Bounded ``[0, 0.99]``.
-
- Rises with semantic similarity, bumped when the newer decision carries an
- explicit reversal signal and when its headline is a verified quote. Kept
- deliberately conservative around :data:`SUPERSEDE_AUTOFLIP_CONFIDENCE` so a
- borderline match stays a proposal rather than auto-flipping the older one.
- """
- conf = 0.45 + 0.4 * max(0.0, min(1.0, similarity))
- if has_reversal_signal:
- conf += 0.1
- if verified:
- conf += 0.05
- return round(max(0.0, min(0.99, conf)), 3)
-
-
-# ---------------------------------------------------------------------------
-# 3B — semantic supersession & conflict detection
-# ---------------------------------------------------------------------------
-
-
-def _created_at(rec: Any) -> Any:
- return getattr(rec, "created_at", None)
-
-
-async def detect_supersessions_and_conflicts(
- session: Any,
- repository_id: str,
- *,
- touched_ids: list[str],
- vector_store: Any | None = None,
- provider: Any | None = None,
- autoflip_confidence: float = SUPERSEDE_AUTOFLIP_CONFIDENCE,
-) -> dict[str, int]:
- """Record supersedes/conflicts edges for the just-upserted decisions.
-
- For each touched decision, find existing decisions in the "same topic" band
- and, where they contradict, write a typed :class:`DecisionEdge`. ``supersedes``
- edges auto-flip the older decision to ``superseded`` only above
- *autoflip_confidence*. Best-effort: requires *vector_store* (the semantic
- signal); returns zero-counts and does nothing without it. *provider*, when
- supplied, is a gated tiebreaker for pairs the heuristic misses.
-
- Returns ``{"supersedes": n, "conflicts": n, "flipped": n}``.
- """
- summary = {"supersedes": 0, "conflicts": 0, "flipped": 0}
- if not touched_ids or vector_store is None:
- return summary
-
- from datetime import UTC, datetime
-
- from repowise.core.persistence.decision_graph import upsert_decision_edge
- from repowise.core.persistence.models import DecisionRecord
-
- # Avoid recording both (A supersedes B) and (B supersedes A) within one run.
- handled_pairs: set[frozenset[str]] = set()
-
- for tid in touched_ids:
- rec = await session.get(DecisionRecord, tid)
- if rec is None or rec.repository_id != repository_id:
- continue
- related = await find_related_decisions(
- vector_store,
- title=rec.title,
- decision=rec.decision or "",
- lo=RELATED_TAU,
- hi=DEFAULT_DEDUP_TAU,
- exclude_ids={rec.id},
- )
- for other_id, sim in related:
- pair = frozenset({rec.id, other_id})
- if pair in handled_pairs:
- continue
- other = await session.get(DecisionRecord, other_id)
- if other is None or other.repository_id != repository_id:
- continue
-
- text_new = f"{rec.title}. {rec.decision}"
- text_old = f"{other.title}. {other.decision}"
- contra, signal = contradicts(text_new, text_old)
- if not contra and provider is not None:
- contra, signal = await _llm_contradiction_judge(
- provider, text_a=text_new, text_b=text_old
- )
- if not contra:
- continue
- handled_pairs.add(pair)
-
- # Temporal order decides direction: the newer decision supersedes.
- ca_rec, ca_other = _created_at(rec), _created_at(other)
- if ca_rec is not None and ca_other is not None and ca_other > ca_rec:
- newer, older = other, rec
- else:
- newer, older = rec, other
-
- rev, rev_sig = is_reversal(f"{newer.title}. {newer.decision}")
- conf = supersession_confidence(
- sim,
- verified=(newer.verification == "exact"),
- has_reversal_signal=rev,
- )
-
- if rev or older.status not in ("active",) or newer.status not in ("active",):
- # A clear reversal, or at least one side not co-active → model
- # it as supersession (newer over older).
- edge = await upsert_decision_edge(
- session,
- repository_id=repository_id,
- src_decision_id=newer.id,
- dst_decision_id=older.id,
- kind="supersedes",
- confidence=conf,
- evidence=f"auto-detected: {signal or rev_sig or 'semantic'} (sim={sim:.2f})",
- )
- if edge is not None:
- summary["supersedes"] += 1
- if conf >= autoflip_confidence and older.status in ("active", "proposed"):
- older.status = "superseded"
- older.superseded_by = newer.id
- older.updated_at = datetime.now(UTC)
- summary["flipped"] += 1
- else:
- # Two active decisions contradict, neither clearly reverses the
- # other → a governance smell, surfaced in health.
- edge = await upsert_decision_edge(
- session,
- repository_id=repository_id,
- src_decision_id=newer.id,
- dst_decision_id=older.id,
- kind="conflicts_with",
- confidence=conf,
- evidence=f"auto-detected: {signal or 'semantic'} (sim={sim:.2f})",
- )
- if edge is not None:
- summary["conflicts"] += 1
-
- await session.flush()
- return summary
-
-
-_CONTRADICTION_SYSTEM = (
- "You judge whether two architectural decisions contradict each other. "
- "Answer with a single word: CONTRADICT or COMPATIBLE."
-)
-
-
-async def _llm_contradiction_judge(provider: Any, *, text_a: str, text_b: str) -> tuple[bool, str]:
- """Gated LLM tiebreaker: do two decisions contradict? Best-effort → (bool, signal)."""
- prompt = (
- "Decision A:\n"
- f"{text_a}\n\n"
- "Decision B:\n"
- f"{text_b}\n\n"
- "Do these two decisions contradict each other (one reverses, replaces, "
- "or is incompatible with the other)? Answer CONTRADICT or COMPATIBLE."
- )
- try:
- response = await provider.generate(
- _CONTRADICTION_SYSTEM, prompt, max_tokens=8, temperature=0.0
- )
- except Exception:
- return False, ""
- verdict = (response.content or "").strip().upper()
- if verdict.startswith("CONTRADICT"):
- return True, "llm-judge"
- return False, ""
-
-
-# ---------------------------------------------------------------------------
-# 3C — two-pass evolution on update
-# ---------------------------------------------------------------------------
-
-
-def pass1_evolution_candidates(
- changed_files: set[str],
- evidence_by_file: dict[str, str],
- existing_decisions: list[Any],
-) -> list[tuple[Any, str, list[str]]]:
- """Pass 1 (no LLM): existing decisions whose governed files changed *with*
- an evolution signal in the change evidence.
-
- *evidence_by_file* maps a changed file path to the text to scan (its diff +
- triggering commit subject/body — NOT the whole file, to keep ``because`` /
- ``instead of`` from firing on every source file). Returns
- ``[(decision, evidence_text, signals)]`` — the survivors handed to Pass 2.
- """
- out: list[tuple[Any, str, list[str]]] = []
- for dec in existing_decisions:
- try:
- affected = set(json.loads(dec.affected_files_json or "[]"))
- except (TypeError, ValueError):
- affected = set()
- touched = affected & changed_files
- if not touched:
- continue
- signals: set[str] = set()
- parts: list[str] = []
- for f in sorted(touched):
- evidence = evidence_by_file.get(f, "")
- sigs = scan_evolution_signals(evidence)
- if sigs:
- signals.update(sigs)
- parts.append(evidence[:2000])
- if signals:
- out.append((dec, "\n\n".join(parts), sorted(signals)))
- return out
-
-
-_EVOLUTION_JUDGE_SYSTEM = (
- "You assess whether a code change evolves a previously recorded "
- "architectural decision. Return only valid JSON. "
- "Never invent rationale not present in the change evidence."
-)
-
-_EVOLUTION_JUDGE_PROMPT = """\
-An existing architectural decision and a recent code change are given below. \
-Decide how the change affects the decision.
-
-EXISTING DECISION
-Title: {title}
-Decision: {decision}
-Rationale: {rationale}
-
-CHANGE EVIDENCE (diff + commit messages)
-{evidence}
-
-Respond with a JSON object:
-{{"verdict": "superseded" | "amended" | "reaffirmed" | "none",
- "rationale": "<one sentence quoting the change evidence>",
- "source_quote": "<verbatim span from the change evidence supporting the verdict>"}}
-
-- "superseded": the change reverses/replaces the decision.
-- "amended": the change modifies the decision without fully reversing it.
-- "reaffirmed": the change is consistent with and strengthens the decision.
-- "none": the change does not affect the decision.
-Quote only text that appears verbatim in the change evidence."""
-
-
-class _JudgeCandidate:
- """Minimal duck-typed shape for :func:`apply_substring_gate`."""
-
- def __init__(self, *, rationale: str, source_quote: str, source_text: str) -> None:
- self.decision = ""
- self.rationale = rationale
- self.source_quote = source_quote
- self.source_text = source_text
- self.verification = "unverified"
-
-
-async def _judge_evolution(
- provider: Any,
- *,
- title: str,
- decision: str,
- rationale: str,
- evidence_text: str,
-) -> dict | None:
- """Pass 2: ask the LLM how the change affects one decision (gated).
-
- Any rationale/quote the LLM produces must substring/token-match the change
- evidence (the same anti-hallucination gate the extractor + harvest use) —
- an ungrounded verdict is discarded. Returns the parsed, gated verdict dict
- or ``None``.
- """
- prompt = _EVOLUTION_JUDGE_PROMPT.format(
- title=title,
- decision=decision,
- rationale=rationale,
- evidence=evidence_text[:6000],
- )
- try:
- response = await provider.generate(
- _EVOLUTION_JUDGE_SYSTEM, prompt, max_tokens=400, temperature=0.1
- )
- except Exception:
- return None
-
- parsed = _parse_judge_json(response.content)
- if not parsed:
- return None
- verdict = (parsed.get("verdict") or "none").strip().lower()
- if verdict not in ("superseded", "amended", "reaffirmed"):
- return None
-
- # Gate the produced rationale/quote against the change evidence.
- cand = _JudgeCandidate(
- rationale=parsed.get("rationale") or "",
- source_quote=parsed.get("source_quote") or "",
- source_text=evidence_text,
- )
- kept, _ = apply_substring_gate([cand])
- if not kept:
- # Reaffirmed verdicts need no grounded quote (they assert "nothing
- # changed"); supersede/amend must be evidence-backed.
- if verdict == "reaffirmed":
- return {
- "verdict": verdict,
- "rationale": "",
- "source_quote": "",
- "verification": "unverified",
- }
- return None
- survivor = kept[0]
- return {
- "verdict": verdict,
- "rationale": survivor.rationale,
- "source_quote": survivor.source_quote,
- "verification": survivor.verification,
- }
-
-
-_JSON_BLOCK_RE = re.compile(r"\{.*\}", re.DOTALL)
-
-
-def _parse_judge_json(content: str | None) -> dict | None:
- if not content:
- return None
- try:
- return json.loads(content)
- except (TypeError, ValueError):
- pass
- match = _JSON_BLOCK_RE.search(content)
- if not match:
- return None
- try:
- parsed = json.loads(match.group(0))
- return parsed if isinstance(parsed, dict) else None
- except (TypeError, ValueError):
- return None
-
-
-async def run_update_evolution(
- session: Any,
- repository_id: str,
- *,
- changed_files: set[str],
- evidence_by_file: dict[str, str],
- provider: Any | None = None,
-) -> dict[str, Any]:
- """Two-pass evolution for ``repowise update``, run *before* page regen.
-
- Returns ``{"regen_files": set[str], "superseded": n, "amended": n,
- "reaffirmed": n}``. ``regen_files`` are the governed files of every decision
- the change superseded or amended — the caller folds them into the
- regeneration set so they re-render in the same run.
-
- Pass 1 always runs (cheap). Pass 2 needs a *provider*; without one the
- survivors' governed pages are still scheduled for regen (the signal alone is
- enough to warrant a refresh) but no status change is made.
- """
- from datetime import UTC, datetime
-
- from repowise.core.persistence.crud import list_decisions
-
- result: dict[str, Any] = {
- "regen_files": set(),
- "superseded": 0,
- "amended": 0,
- "reaffirmed": 0,
- }
- if not changed_files:
- return result
-
- existing = await list_decisions(session, repository_id, include_proposed=True, limit=500)
- candidates = pass1_evolution_candidates(changed_files, evidence_by_file, existing)
- if not candidates:
- return result
-
- regen: set[str] = result["regen_files"]
- now = datetime.now(UTC)
-
- for dec, evidence_text, _signals in candidates:
- try:
- governed = list(json.loads(dec.affected_files_json or "[]"))
- except (TypeError, ValueError):
- governed = []
-
- if provider is None:
- # No LLM available: a signal touched a governed file — re-render the
- # governed pages so docs stay fresh, but don't change status.
- regen.update(governed)
- continue
-
- verdict = await _judge_evolution(
- provider,
- title=dec.title,
- decision=dec.decision,
- rationale=dec.rationale,
- evidence_text=evidence_text,
- )
- if verdict is None:
- continue
-
- kind = verdict["verdict"]
- if kind == "superseded":
- if dec.status in ("active", "proposed"):
- dec.status = "superseded"
- dec.updated_at = now
- regen.update(governed)
- result["superseded"] += 1
- elif kind == "amended":
- # Keep it active but mark it stale so its drift is visible, and
- # re-render its governed pages to reflect the amendment.
- dec.staleness_score = max(dec.staleness_score, 0.6)
- dec.updated_at = now
- regen.update(governed)
- result["amended"] += 1
- elif kind == "reaffirmed":
- # Still holds — relax staleness; no regen needed.
- dec.staleness_score = min(dec.staleness_score, 0.2)
- dec.updated_at = now
- result["reaffirmed"] += 1
-
- await session.flush()
- return result
+from repowise.core.analysis.decisions.evolution import * # noqa: F403
diff --git a/packages/core/src/repowise/core/analysis/decision_extractor.py b/packages/core/src/repowise/core/analysis/decision_extractor.py
index 4e0326a91..3ad001d08 100644
--- a/packages/core/src/repowise/core/analysis/decision_extractor.py
+++ b/packages/core/src/repowise/core/analysis/decision_extractor.py
@@ -1,1700 +1,8 @@
-"""Architectural Decision Intelligence - extraction from multiple sources.
+"""Back-compat façade — moved to ``repowise.core.analysis.decisions.extractor``.
-Capture sources (see ``decision_provenance.SOURCE_RANK`` for the trust ladder):
- 1. Inline markers (# WHY:, # DECISION:, etc.)
- 2. Git archaeology (significant commit messages)
- 3. README / docs mining (implicit decisions in prose)
- 4. ADR auto-discovery (Nygard/MADR records — deterministic parse first)
- 5. CHANGELOG mining (keep-a-changelog Changed/Removed/Deprecated)
- 6. PR / squash-body mining (commit bodies captured in git indexing)
- 7. Comment archaeology (rationale prose on high-centrality code)
- + CLI capture (manual entry)
-
-Determinism-first: ADR/CHANGELOG are parsed structurally before any LLM call.
-Every extracted decision passes an anti-hallucination substring gate
-(:meth:`DecisionExtractor._apply_substring_gate`) — fields not grounded in the
-verbatim source span are dropped, and evidence-less decisions are rejected.
-
-All LLM calls are wrapped in try/except - failures never propagate.
+Import from the new path; this re-export keeps existing imports working.
"""
from __future__ import annotations
-import asyncio
-import json
-import re
-from dataclasses import dataclass, field
-from datetime import UTC, datetime
-from pathlib import Path
-from typing import Any
-
-import structlog
-
-from repowise.core.analysis.decision_gate import apply_substring_gate
-
-logger = structlog.get_logger(__name__)
-
-# ---------------------------------------------------------------------------
-# Data models
-# ---------------------------------------------------------------------------
-
-
-@dataclass
-class ExtractedDecision:
- title: str
- context: str = ""
- decision: str = ""
- rationale: str = ""
- alternatives: list[str] = field(default_factory=list)
- consequences: list[str] = field(default_factory=list)
- affected_files: list[str] = field(default_factory=list)
- affected_modules: list[str] = field(default_factory=list)
- tags: list[str] = field(default_factory=list)
- source: str = "inline_marker"
- evidence_commits: list[str] = field(default_factory=list)
- evidence_file: str | None = None
- evidence_line: int | None = None
- confidence: float = 0.5
- status: str = "proposed"
- # The verbatim claimed quote (LLM/parser output) and the verdict from the
- # anti-hallucination substring gate (Phase 1D).
- source_quote: str = ""
- verification: str = "unverified" # exact | fuzzy | unverified
- # Transient: the verbatim source span this decision was drawn from. Set by
- # each extractor, consumed by the substring gate, then cleared before
- # persistence (the persistence layer ignores unknown dict keys anyway).
- source_text: str = ""
-
-
-@dataclass
-class DecisionExtractionReport:
- total_found: int
- decisions: list[ExtractedDecision]
- by_source: dict[str, int]
-
-
-# ---------------------------------------------------------------------------
-# Comment marker detection
-# ---------------------------------------------------------------------------
-
-MARKER_RE = re.compile(
- r"^\s*(?:#|//|--|/\*|\*)\s*"
- r"(?P<keyword>WHY|DECISION|TRADEOFF|ADR|RATIONALE|REJECTED)"
- r"\s*:\s*(?P<text>.+)",
- re.IGNORECASE,
-)
-
-_SKIP_DIRS = frozenset(
- {
- ".git",
- "node_modules",
- "__pycache__",
- ".repowise",
- ".venv",
- "venv",
- ".tox",
- ".mypy_cache",
- ".pytest_cache",
- "dist",
- "build",
- ".next",
- ".nuxt",
- }
-)
-
-# 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",
- }
-)
-
-# ---------------------------------------------------------------------------
-# Decision signal keywords for git archaeology
-# ---------------------------------------------------------------------------
-
-DECISION_SIGNAL_KEYWORDS = [
- "migrate",
- "migration",
- "switch to",
- "replace",
- "replaced",
- "refactor to",
- "move from",
- "adopt",
- "introduce",
- "deprecate",
- "remove",
- "drop",
- "upgrade",
- "rewrite",
- "extract",
- "split",
- "convert",
- "transition",
- "revert",
-]
-
-# ---------------------------------------------------------------------------
-# ADR / CHANGELOG / PR / comment source configuration (Phase 1B)
-# ---------------------------------------------------------------------------
-
-# Directories conventionally holding Architecture Decision Records, plus a
-# filename glob for ADRs that live loose. Globbed relative to the repo root.
-_ADR_DIR_GLOBS = (
- "adr/*.md",
- "adrs/*.md",
- "docs/adr/*.md",
- "docs/adrs/*.md",
- "docs/decisions/*.md",
- "decisions/*.md",
- "architecture/*.md",
- "doc/adr/*.md",
-)
-_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",
-}
-
-# CHANGELOG / HISTORY / NEWS filenames (case-insensitive match on the stem).
-_CHANGELOG_NAMES = frozenset(
- {"changelog", "history", "news", "changes", "releasenotes", "release-notes"}
-)
-# keep-a-changelog section headers that carry decision signal. "Added" is
-# excluded — additions are rarely *decisions* about structure, just features.
-_CHANGELOG_DECISION_SECTIONS = frozenset({"changed", "removed", "deprecated", "security"})
-_MAX_CHANGELOG_VERSIONS = 15
-
-# 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 = (
- "## why",
- "## motivation",
- "## what",
- "## changes",
- "## context",
- "## summary",
- "closes #",
- "fixes #",
- "resolves #",
- "before:",
- "after:",
-)
-_MAX_PR_BODIES = 25
-
-# Prose that signals rationale in a block comment / docstring (beyond the
-# explicit WHY:/DECISION: markers already covered by inline_marker).
-_COMMENT_RATIONALE_CUES = (
- "because",
- "instead of",
- "rather than",
- "trade-off",
- "tradeoff",
- "we chose",
- "we decided",
- "the reason",
- "in order to",
- "this avoids",
- "to avoid",
- "deliberately",
- "intentionally",
-)
-_MAX_COMMENT_NODES = 30
-
-# ---------------------------------------------------------------------------
-# LLM Prompts
-# ---------------------------------------------------------------------------
-
-_SYSTEM_PROMPT = (
- "You are an architectural decision extractor. "
- "You extract structured decision records from code context. "
- "Return only valid JSON. Never invent rationale not present in the source."
-)
-
-INLINE_MARKER_PROMPT = """\
-A developer left architectural decision markers in their code. \
-Extract each one as a structured decision record.
-
-Markers found in file: {file_path}
-
-{markers_block}
-
-For each marker, return a JSON object:
-{{
- "title": "short title of the decision",
- "context": "what situation forced this",
- "decision": "what was chosen",
- "rationale": "why",
- "alternatives": ["rejected alternatives if mentioned"],
- "consequences": ["tradeoffs if mentioned"],
- "tags": ["relevant tags from: auth, database, api, performance, security, infra, testing"]
-}}
-
-Return a JSON array of decision objects. If a marker is not an architectural \
-decision, skip it. Return [] if none qualify.
-"""
-
-GIT_ARCHAEOLOGY_PROMPT = """\
-Analyze these git commits to determine if they represent architectural decisions.
-
-{commits_block}
-
-For each commit that IS an architectural decision (a deliberate choice about \
-system structure, patterns, migrations, or technology), return a JSON object:
-{{
- "commit_sha": "the sha",
- "title": "short title",
- "context": "what situation forced this",
- "decision": "what was chosen or changed",
- "rationale": "why this approach (infer from message and files only)",
- "alternatives": [],
- "consequences": [],
- "tags": ["relevant tags"]
-}}
-
-Return a JSON array. Skip commits that are just bug fixes or minor changes. \
-Return [] if none qualify. Do not hallucinate rationale.
-"""
-
-README_MINING_PROMPT = """\
-Analyze this documentation file and extract any architectural decisions.
-
-File: {file_path}
-Content:
-{content}
-
-Look for:
-- Technology choices and why ("We use X because Y")
-- Things replaced or migrated away from
-- Explicit architectural constraints
-- Design patterns chosen and why
-
-Return a JSON array of decisions:
-{{
- "title": "short title",
- "context": "situation that forced it",
- "decision": "what was chosen",
- "rationale": "why",
- "alternatives": [],
- "consequences": [],
- "tags": [],
- "source_quote": "exact quote from the document"
-}}
-
-Only extract explicit decisions. Return [] if none found.
-"""
-
-CHANGELOG_MINING_PROMPT = """\
-These are CHANGELOG entries from sections that usually record deliberate \
-changes (Changed / Removed / Deprecated). Extract any that represent an \
-architectural decision (a technology/pattern change, a removal, a deprecation \
-with a reason).
-
-{entries_block}
-
-Return a JSON array of decisions:
-{{
- "title": "short title",
- "context": "what prompted it (only if stated)",
- "decision": "what was changed/removed/deprecated",
- "rationale": "why (only if stated — do not invent)",
- "alternatives": [],
- "consequences": [],
- "tags": [],
- "source_quote": "the exact changelog line this came from"
-}}
-
-Skip pure feature additions and trivial fixes. Return [] if none qualify.
-"""
-
-PR_BODY_MINING_PROMPT = """\
-These are squash-merge / PR commit bodies. Extract any architectural decision \
-described in them (technology choices, migrations, structural changes, things \
-deliberately rejected).
-
-{bodies_block}
-
-For each decision return a JSON object:
-{{
- "commit_sha": "the sha shown",
- "title": "short title",
- "context": "what situation forced this (only if stated)",
- "decision": "what was chosen or changed",
- "rationale": "why (quote/paraphrase the body — never invent)",
- "alternatives": ["rejected alternatives if mentioned"],
- "consequences": [],
- "tags": [],
- "source_quote": "the exact sentence from the body this came from"
-}}
-
-Return a JSON array. Skip bodies that are just checklists or release noise. \
-Return [] if none qualify.
-"""
-
-COMMENT_ARCHAEOLOGY_PROMPT = """\
-These are block comments / docstrings from high-centrality code (the files \
-most other code depends on). Extract any architectural decision whose \
-rationale is explained in the prose.
-
-{comments_block}
-
-For each decision return a JSON object:
-{{
- "title": "short title",
- "context": "what situation forced this (only if stated)",
- "decision": "what was chosen",
- "rationale": "why (quote/paraphrase the comment — never invent)",
- "alternatives": [],
- "consequences": [],
- "tags": [],
- "source_quote": "the exact sentence from the comment this came from"
-}}
-
-Only extract decisions whose reasoning is actually written in the prose. \
-Return [] if none qualify.
-"""
-
-
-# ---------------------------------------------------------------------------
-# Main extractor
-# ---------------------------------------------------------------------------
-
-
-class DecisionExtractor:
- """Extracts architectural decisions from multiple sources."""
-
- def __init__(
- self,
- repo_path: Path,
- provider: Any | None = None,
- graph: Any | None = None,
- git_meta_map: dict[str, dict] | None = None,
- parsed_files: list[Any] | None = None,
- ) -> None:
- self._repo_path = Path(repo_path)
- self._provider = provider
- self._graph = graph
- self._git_meta_map = git_meta_map or {}
- self._parsed_files = parsed_files or []
-
- # ------------------------------------------------------------------
- # Source 1: Inline markers
- # ------------------------------------------------------------------
-
- async def scan_inline_markers(
- self,
- restrict_to_files: list[str] | None = None,
- ) -> list[ExtractedDecision]:
- """Scan source files for decision markers (WHY:, DECISION:, etc.)."""
- markers_by_file: dict[str, list[dict]] = {}
-
- if restrict_to_files:
- files_to_scan = [self._repo_path / fp for fp in restrict_to_files]
- else:
- files_to_scan = list(self._iter_source_files())
-
- 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:
- text = file_path.read_text(encoding="utf-8", errors="replace")
- except (OSError, UnicodeDecodeError):
- continue
-
- 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 = file_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])
-
- try:
- rel_path = str(file_path.relative_to(self._repo_path))
- except ValueError:
- rel_path = str(file_path)
-
- markers_by_file.setdefault(rel_path, []).append(
- {
- "keyword": m.group("keyword"),
- "text": marker_text,
- "line": line_num,
- "context": context,
- }
- )
-
- if not markers_by_file:
- return []
-
- decisions: list[ExtractedDecision] = []
-
- for file_path, markers in markers_by_file.items():
- # Get 1-hop graph neighbors for affected_files
- affected = self._get_neighbors(file_path)
-
- # The concatenated marker contexts are the verbatim source span the
- # substring gate verifies the structured decision against.
- marker_source_text = "\n".join(m.get("context", "") for m in markers)
-
- if self._provider:
- # Use LLM to structure markers
- try:
- llm_decisions = await self._structure_markers_via_llm(file_path, markers)
- for d in llm_decisions:
- d.evidence_file = file_path
- d.evidence_line = markers[0]["line"] if markers else None
- d.affected_files = list({file_path} | set(affected))
- d.affected_modules = self._infer_modules(d.affected_files)
- d.source = "inline_marker"
- d.status = "active"
- d.confidence = 0.95
- d.source_text = marker_source_text
- decisions.extend(llm_decisions)
- except Exception:
- logger.warning(
- "decision_extractor.llm_structuring_failed",
- file=file_path,
- )
- # Fall through to raw extraction below
- for marker in markers:
- decisions.append(
- self._raw_decision_from_marker(file_path, marker, affected)
- )
- else:
- # No LLM — create minimal decisions from raw marker text
- for marker in markers:
- decisions.append(self._raw_decision_from_marker(file_path, marker, affected))
-
- return decisions
-
- def _raw_decision_from_marker(
- self,
- file_path: str,
- marker: dict,
- affected: list[str],
- ) -> ExtractedDecision:
- """Create a minimal decision from a raw marker without LLM."""
- return ExtractedDecision(
- title=marker["text"][:100],
- decision=marker["text"],
- context=f"Found in {file_path}:{marker['line']}",
- source="inline_marker",
- status="active",
- confidence=0.7,
- evidence_file=file_path,
- evidence_line=marker["line"],
- affected_files=list({file_path} | set(affected)),
- affected_modules=self._infer_modules([file_path, *affected]),
- tags=self._infer_tags(marker["text"]),
- source_quote=marker["text"],
- source_text=marker.get("context", marker["text"]),
- )
-
- async def _structure_markers_via_llm(
- self, file_path: str, markers: list[dict]
- ) -> list[ExtractedDecision]:
- """Use LLM to structure inline markers into decision records."""
- markers_block = ""
- for m in markers[:5]: # Batch up to 5 per call
- markers_block += (
- f"\n--- Marker ({m['keyword']}) at line {m['line']} ---\n"
- f"Text: {m['text']}\n"
- f"Surrounding code:\n{m['context'][:1500]}\n"
- )
-
- prompt = INLINE_MARKER_PROMPT.format(
- file_path=file_path,
- markers_block=markers_block,
- )
-
- response = await self._provider.generate(
- _SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
- )
- return self._parse_decisions_json(response.content)
-
- # ------------------------------------------------------------------
- # Source 2: Git archaeology
- # ------------------------------------------------------------------
-
- async def mine_git_archaeology(self) -> list[ExtractedDecision]:
- """Extract decisions from significant git commits."""
- if not self._provider or not self._git_meta_map:
- return []
-
- # Collect unique significant commits with decision signals
- commit_map: dict[str, dict] = {} # sha → commit info
- commit_files: dict[str, list[str]] = {} # sha → files
-
- for file_path, meta in self._git_meta_map.items():
- commits_json = meta.get("significant_commits_json", "[]")
- if isinstance(commits_json, str):
- try:
- commits = json.loads(commits_json)
- except (json.JSONDecodeError, TypeError):
- continue
- else:
- commits = commits_json
-
- for commit in commits:
- sha = commit.get("sha", "")
- if not sha or sha in commit_map:
- commit_files.setdefault(sha, []).append(file_path)
- continue
- msg = commit.get("message", "")
- 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 = sum(1 for kw in DECISION_SIGNAL_KEYWORDS if kw in 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)
-
- if not commit_map:
- return []
-
- # Rank by signal count, take top 20
- ranked = sorted(
- commit_map.values(),
- key=lambda c: c["signal_count"],
- reverse=True,
- )[:20]
-
- # Batch LLM calls (5 commits per batch)
- decisions: list[ExtractedDecision] = []
- batches = [ranked[i : i + 5] for i in range(0, len(ranked), 5)]
-
- async def _process_batch(batch: list[dict]) -> list[ExtractedDecision]:
- commits_block = ""
- source_by_sha: dict[str, str] = {}
- for c in batch:
- files = commit_files.get(c["sha"], [])
- body = (c.get("body") or "").strip()
- body_block = f"Body: {body[:1500]}\n" if body else ""
- commits_block += (
- f"\n--- Commit {c['sha'][:8]} ---\n"
- f"Message: {c['message']}\n"
- f"{body_block}"
- f"Author: {c['author']}\n"
- f"Date: {c['date']}\n"
- f"Files changed: {', '.join(files[:20])}\n"
- )
- source_by_sha[c["sha"]] = f"{c['message']}\n{body}".strip()
-
- prompt = GIT_ARCHAEOLOGY_PROMPT.format(commits_block=commits_block)
- response = await self._provider.generate(
- _SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
- )
- extracted = self._parse_decisions_json(response.content)
-
- # Enrich with commit metadata
- for d in extracted:
- sha = d.evidence_commits[0] if d.evidence_commits else ""
- if not sha:
- # Try to match back to a commit
- for c in batch:
- if c["message"][:40].lower() in d.title.lower():
- sha = c["sha"]
- break
- if sha:
- d.evidence_commits = [sha]
- d.affected_files = commit_files.get(sha, [])
- d.source_text = source_by_sha.get(sha, "")
- d.source = "git_archaeology"
- d.status = "proposed"
- signal = max(
- (c["signal_count"] for c in batch if c["sha"] == sha),
- default=1,
- )
- d.confidence = 0.85 if signal >= 2 else 0.70
- d.affected_modules = self._infer_modules(d.affected_files)
-
- return extracted
-
- results = await asyncio.gather(
- *[_process_batch(b) for b in batches],
- return_exceptions=True,
- )
- for result in results:
- if isinstance(result, list):
- decisions.extend(result)
- else:
- logger.warning(
- "decision_extractor.git_batch_failed",
- error=str(result),
- )
-
- return decisions
-
- # ------------------------------------------------------------------
- # Source 3: README / docs mining
- # ------------------------------------------------------------------
-
- async def mine_readme_docs(self) -> list[ExtractedDecision]:
- """Extract decisions from documentation files."""
- if not self._provider:
- return []
-
- doc_patterns = [
- "README.md",
- "CLAUDE.md",
- "ARCHITECTURE.md",
- "CONTRIBUTING.md",
- "DESIGN.md",
- "DECISIONS.md",
- ]
- doc_files: list[Path] = []
-
- for pattern in doc_patterns:
- p = self._repo_path / pattern
- if p.is_file():
- doc_files.append(p)
-
- # Also check docs/ directory
- docs_dir = self._repo_path / "docs"
- if docs_dir.is_dir():
- for md_file in docs_dir.rglob("*.md"):
- if len(doc_files) >= 10:
- break
- doc_files.append(md_file)
-
- decisions: list[ExtractedDecision] = []
-
- for doc_path in doc_files[:10]:
- try:
- content = doc_path.read_text(encoding="utf-8", errors="replace")
- except (OSError, UnicodeDecodeError):
- continue
-
- # Skip very large files
- if len(content) > 50_000:
- continue
-
- # Strip fenced code blocks to avoid treating example markers
- # (e.g. `# WHY: ...` in code examples) as real decisions.
- content = self._strip_code_blocks(content)
-
- try:
- rel_path = str(doc_path.relative_to(self._repo_path))
- except ValueError:
- rel_path = str(doc_path)
-
- try:
- prompt = README_MINING_PROMPT.format(
- file_path=rel_path,
- content=content[:15_000], # Limit token usage
- )
- response = await self._provider.generate(
- _SYSTEM_PROMPT, prompt, max_tokens=3000, temperature=0.2
- )
- extracted = self._parse_decisions_json(response.content)
- for d in extracted:
- d.source = "readme_mining"
- d.status = "proposed"
- d.confidence = 0.60
- d.evidence_file = rel_path
- d.affected_modules = self._infer_modules_from_text(d.title + " " + d.decision)
- d.source_text = content
- decisions.extend(extracted)
- except Exception:
- logger.warning(
- "decision_extractor.readme_mining_failed",
- file=rel_path,
- )
-
- return decisions
-
- # ------------------------------------------------------------------
- # Source 4: ADR auto-discovery (deterministic-first)
- # ------------------------------------------------------------------
-
- async def discover_adrs(self) -> list[ExtractedDecision]:
- """Discover and parse Architecture Decision Records.
-
- Deterministic-first: ADRs follow the Nygard/MADR templates (optional
- YAML front-matter + Status / Context / Decision / Consequences
- headings), so structured files are parsed without the LLM. Files that
- 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()
- if not adr_paths:
- return []
-
- decisions: list[ExtractedDecision] = []
- for path in adr_paths:
- try:
- content = path.read_text(encoding="utf-8", errors="replace")
- except (OSError, UnicodeDecodeError):
- continue
- if len(content) > 50_000:
- content = content[:50_000]
- try:
- rel = str(path.relative_to(self._repo_path))
- except ValueError:
- rel = str(path)
-
- parsed = self._parse_adr(content, rel)
- if parsed is not None:
- decisions.append(parsed)
- elif self._provider:
- try:
- stripped = self._strip_code_blocks(content)
- prompt = README_MINING_PROMPT.format(file_path=rel, content=stripped[:15_000])
- response = await self._provider.generate(
- _SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
- )
- for d in self._parse_decisions_json(response.content):
- d.source = "adr"
- d.status = "proposed"
- d.confidence = 0.80
- d.evidence_file = rel
- d.source_text = stripped
- d.affected_modules = self._infer_modules_from_text(
- d.title + " " + d.decision
- )
- decisions.append(d)
- except Exception:
- logger.warning("decision_extractor.adr_llm_failed", file=rel)
-
- return decisions
-
- def _find_adr_files(self) -> list[Path]:
- """Collect candidate ADR files from the conventional dirs + name match.
-
- Performance: the conventional-dir globs are shallow (one directory
- each). The loose ``*adr*.md`` scan uses a pruned ``os.walk`` rather than
- a recursive ``**`` glob so it never descends into ``node_modules`` /
- ``.git`` / ``.venv`` on a large repo, and bails as soon as the cap is
- hit.
- """
- import os
-
- seen: set[Path] = set()
- files: list[Path] = []
- for pattern in _ADR_DIR_GLOBS:
- for p in self._repo_path.glob(pattern):
- if p.is_file() and p not in seen:
- seen.add(p)
- files.append(p)
-
- if len(files) < _MAX_ADR_FILES:
- for dirpath, dirnames, filenames in os.walk(self._repo_path):
- # Prune skip-listed + nested-git subtrees in place.
- dirnames[:] = [
- d
- for d in dirnames
- if d not in _SKIP_DIRS
- and not d.endswith((".egg-info", ".dist-info"))
- and not (Path(dirpath) / d / ".git").exists()
- ]
- for fname in filenames:
- low = fname.lower()
- if not low.endswith(".md") or "adr" not in low:
- continue
- if low == "readme.md" or "template" in low:
- continue
- p = Path(dirpath) / fname
- if p in seen:
- continue
- seen.add(p)
- files.append(p)
- if len(files) >= _MAX_ADR_FILES:
- break
- if len(files) >= _MAX_ADR_FILES:
- break
-
- return files[:_MAX_ADR_FILES]
-
- def _parse_adr(self, content: str, rel_path: str) -> ExtractedDecision | None:
- """Deterministically parse a structured ADR. Returns None if unstructured.
-
- Because every field is lifted verbatim from the document, the resulting
- 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)
- if not title:
- m = re.search(r"^#\s+(.+)$", body, re.MULTILINE)
- if m:
- title = m.group(1).strip()
- # Strip an "ADR-0007:" style prefix from the title.
- title = re.sub(r"^ADR[-\s]*\d+[:\s-]*", "", title, flags=re.IGNORECASE).strip() or title
-
- context = sections.get("context") or sections.get("context and problem statement", "")
- decision_txt = sections.get("decision") or sections.get("decision outcome", "")
- rationale = sections.get("rationale") or sections.get("decision drivers", "")
- consequences = sections.get("consequences", "")
- if not status:
- status = sections.get("status", "")
-
- # Require recognizable ADR structure — at minimum a Decision or Context
- # section — otherwise let the LLM fallback handle it.
- if not (decision_txt or context):
- return None
-
- status_key = status.strip().lower().split()[0] if status.strip() else ""
- mapped_status = _ADR_STATUS_MAP.get(status_key, "active")
-
- return ExtractedDecision(
- title=(title or rel_path)[:200],
- context=context.strip(),
- decision=decision_txt.strip(),
- rationale=rationale.strip(),
- consequences=self._bullets(consequences),
- source="adr",
- status=mapped_status,
- confidence=0.90,
- evidence_file=rel_path,
- source_quote=(decision_txt or context).strip()[:500],
- source_text=content,
- tags=self._infer_tags(f"{title} {decision_txt}"),
- affected_modules=self._infer_modules_from_text(f"{title} {decision_txt}"),
- )
-
- # ------------------------------------------------------------------
- # Source 5: CHANGELOG mining
- # ------------------------------------------------------------------
-
- async def mine_changelog(self) -> list[ExtractedDecision]:
- """Mine keep-a-changelog Changed/Removed/Deprecated sections."""
- path = self._find_changelog()
- if path is None:
- return []
- try:
- content = path.read_text(encoding="utf-8", errors="replace")
- except (OSError, UnicodeDecodeError):
- return []
- try:
- rel = str(path.relative_to(self._repo_path))
- except ValueError:
- rel = str(path)
-
- entries = self._parse_changelog(content)
- if not entries:
- return []
-
- if self._provider:
- return await self._structure_changelog_entries(entries, rel, content)
-
- # No LLM — emit raw decisions straight from the decision-y bullets.
- decisions: list[ExtractedDecision] = []
- for section, bullet in entries[:50]:
- decisions.append(
- ExtractedDecision(
- title=bullet[:100],
- decision=bullet,
- context=f"CHANGELOG · {section.title()}",
- source="changelog",
- status="proposed",
- confidence=0.50,
- evidence_file=rel,
- source_quote=bullet,
- source_text=content,
- tags=self._infer_tags(bullet),
- )
- )
- return decisions
-
- def _find_changelog(self) -> Path | None:
- """Locate a CHANGELOG/HISTORY/NEWS file (any extension).
-
- Checks the repo root first, then the conventional documentation
- subdirectories (``docs/``, ``doc/``, ``.github/``). Many projects keep
- their changelog under ``docs/`` rather than at the root, so a root-only
- scan silently skips this source.
- """
- search_dirs = [
- self._repo_path,
- self._repo_path / "docs",
- self._repo_path / "doc",
- self._repo_path / ".github",
- ]
- for directory in search_dirs:
- if not directory.is_dir():
- continue
- for p in sorted(directory.glob("*")):
- if not p.is_file():
- continue
- stem = re.sub(r"[^a-z]", "", p.stem.lower())
- if stem in _CHANGELOG_NAMES:
- return p
- return None
-
- def _parse_changelog(self, content: str) -> list[tuple[str, str]]:
- """Return ``(section, bullet)`` pairs from decision-relevant sections."""
- entries: list[tuple[str, str]] = []
- version_count = 0
- current_section: str | None = None
- in_version = True
- for line in content.splitlines():
- h2 = re.match(r"^##\s+(.+)$", line)
- if h2:
- name = h2.group(1).strip().lower().strip("[]")
- base = name.split()[0] if name else ""
- if base in _CHANGELOG_DECISION_SECTIONS:
- # Some changelogs use H2 section headers directly.
- current_section = base
- else:
- version_count += 1
- in_version = version_count <= _MAX_CHANGELOG_VERSIONS
- current_section = None
- continue
- h3 = re.match(r"^###\s+(.+)$", line)
- if h3:
- current_section = h3.group(1).strip().lower()
- continue
- if not in_version or current_section not in _CHANGELOG_DECISION_SECTIONS:
- continue
- s = line.strip()
- if s.startswith(("-", "*", "+")):
- bullet = s[1:].strip()
- if bullet:
- entries.append((current_section, bullet))
- return entries
-
- async def _structure_changelog_entries(
- self, entries: list[tuple[str, str]], rel: str, content: str
- ) -> list[ExtractedDecision]:
- """LLM-structure the highest-signal changelog bullets into decisions."""
- signal = [
- (s, b)
- for (s, b) in entries
- if s in ("removed", "deprecated")
- or any(k in b.lower() for k in DECISION_SIGNAL_KEYWORDS)
- ]
- chosen = (signal or entries)[:40]
- block = "\n".join(f"- [{s.title()}] {b}" for s, b in chosen)
- prompt = CHANGELOG_MINING_PROMPT.format(entries_block=block)
- try:
- response = await self._provider.generate(
- _SYSTEM_PROMPT, prompt, max_tokens=2500, temperature=0.2
- )
- except Exception:
- logger.warning("decision_extractor.changelog_mining_failed", file=rel)
- return []
- extracted = self._parse_decisions_json(response.content)
- for d in extracted:
- d.source = "changelog"
- d.status = "proposed"
- d.confidence = 0.60
- d.evidence_file = rel
- d.source_text = content
- d.affected_modules = self._infer_modules_from_text(d.title + " " + d.decision)
- return extracted
-
- # ------------------------------------------------------------------
- # Source 6: PR / squash-body mining (consumes commit bodies from 1A)
- # ------------------------------------------------------------------
-
- async def mine_pr_bodies(self) -> list[ExtractedDecision]:
- """Extract decisions from PR / squash-merge commit bodies."""
- if not self._provider or not self._git_meta_map:
- return []
-
- candidates: dict[str, dict] = {}
- files_by_sha: dict[str, list[str]] = {}
- for fp, meta in self._git_meta_map.items():
- for c in self._loads_commits(meta.get("significant_commits_json")):
- sha = c.get("sha", "")
- if not sha:
- continue
- files_by_sha.setdefault(sha, []).append(fp)
- body = (c.get("body") or "").strip()
- if sha in candidates or not body:
- continue
- low = body.lower()
- is_prish = c.get("pr_number") is not None or any(m in low for m in _PR_BODY_MARKERS)
- has_signal = any(k in low for k in DECISION_SIGNAL_KEYWORDS)
- if is_prish and has_signal:
- candidates[sha] = {
- "sha": sha,
- "subject": c.get("message", ""),
- "body": body,
- "pr": c.get("pr_number"),
- }
-
- if not candidates:
- 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 = ""
- source_by_sha: dict[str, str] = {}
- for c in batch:
- pr_label = f" (PR #{c['pr']})" if c.get("pr") else ""
- bodies_block += (
- f"\n--- Commit {c['sha'][:8]}{pr_label} ---\n"
- f"Subject: {c['subject']}\n"
- f"Body:\n{c['body'][:2000]}\n"
- )
- source_by_sha[c["sha"]] = f"{c['subject']}\n{c['body']}"
- prompt = PR_BODY_MINING_PROMPT.format(bodies_block=bodies_block)
- try:
- response = await self._provider.generate(
- _SYSTEM_PROMPT, prompt, max_tokens=2500, temperature=0.2
- )
- except Exception:
- return []
- 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 = files_by_sha.get(sha, [])
- d.source_text = source_by_sha.get(sha, "")
- d.source = "pr"
- d.status = "proposed"
- d.confidence = 0.80
- d.affected_modules = self._infer_modules(d.affected_files)
- return extracted
-
- decisions: list[ExtractedDecision] = []
- results = await asyncio.gather(
- *[_process_batch(b) for b in batches], return_exceptions=True
- )
- for result in results:
- if isinstance(result, list):
- decisions.extend(result)
- else:
- logger.warning("decision_extractor.pr_batch_failed", error=str(result))
- return decisions
-
- # ------------------------------------------------------------------
- # Source 7: Comment archaeology (centrality-bounded)
- # ------------------------------------------------------------------
-
- async def mine_comment_archaeology(self) -> list[ExtractedDecision]:
- """Mine rationale prose from comments on the most central code.
-
- Bounded to the top-N nodes by PageRank (degree fallback) so it never
- scans the whole tree, and looks for *reasoning* prose (``because``,
- ``instead of`` …) rather than the explicit markers already covered by
- ``scan_inline_markers``.
- """
- if not self._provider or self._graph is None:
- return []
-
- top_files = self._top_central_files(_MAX_COMMENT_NODES)
- if not top_files:
- return []
-
- snippets: list[tuple[str, str]] = []
- for fp in top_files:
- prose = self._extract_leading_prose(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:
- comments_block += f"\n--- {fp} ---\n{prose[:1500]}\n"
- prompt = COMMENT_ARCHAEOLOGY_PROMPT.format(comments_block=comments_block)
- try:
- response = await self._provider.generate(
- _SYSTEM_PROMPT, prompt, max_tokens=2500, temperature=0.2
- )
- except Exception:
- return []
- extracted = self._parse_decisions_json(response.content)
- # Best-effort attribution to the originating file by token overlap.
- for d in extracted:
- best_fp, best_prose = batch[0]
- hay = (d.title + " " + d.decision).lower()
- for fp, prose in batch:
- stem = Path(fp).stem.lower()
- if stem and stem in hay:
- best_fp, best_prose = fp, prose
- break
- d.source = "comment"
- d.status = "proposed"
- d.confidence = 0.55
- d.evidence_file = best_fp
- d.source_text = best_prose
- d.affected_files = [best_fp]
- d.affected_modules = self._infer_modules([best_fp])
- return extracted
-
- results = await asyncio.gather(
- *[_process_batch(b) for b in batches], return_exceptions=True
- )
- for result in results:
- if isinstance(result, list):
- decisions.extend(result)
- return decisions
-
- # Above this node count, skip the iterative PageRank solve and use degree
- # centrality (O(nodes)) instead — comment archaeology only needs a rough
- # "most depended-on files" ranking, not exact PageRank, and the iterative
- # solve would otherwise add seconds on very large graphs.
- _PAGERANK_NODE_CEILING = 20_000
-
- def _top_central_files(self, n: int) -> list[str]:
- """Top-*n* file nodes by centrality (existing on disk).
-
- Uses PageRank on modest graphs and falls back to cheap degree
- centrality on very large graphs (or if networkx is unavailable) so this
- never becomes an ingestion bottleneck.
- """
- g = self._graph
- if g is None:
- return []
- scores: dict[str, float] = {}
- try:
- node_count = g.number_of_nodes()
- except Exception:
- node_count = 0
- if 0 < node_count <= self._PAGERANK_NODE_CEILING:
- try:
- import networkx as nx
-
- scores = nx.pagerank(g, max_iter=50, tol=1e-4)
- except Exception:
- scores = {}
- if not scores:
- try:
- scores = {node: float(g.degree(node)) for node in g.nodes}
- except Exception:
- return []
- ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
- out: list[str] = []
- for node, _score in ranked:
- if len(out) >= n:
- break
- p = self._repo_path / node
- if p.is_file() and p.suffix.lower() not in _BINARY_EXTENSIONS:
- 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."""
- if isinstance(value, list):
- return value
- if isinstance(value, str):
- try:
- data = json.loads(value)
- except (json.JSONDecodeError, TypeError):
- return []
- 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)
- # ------------------------------------------------------------------
-
- def _apply_substring_gate(
- self, decisions: list[ExtractedDecision]
- ) -> tuple[list[ExtractedDecision], int]:
- """Run the shared anti-hallucination gate over extracted decisions.
-
- Thin wrapper around :func:`decision_gate.apply_substring_gate` — the
- gate orchestration is factored out so the Phase-2 LLM-docs harvest path
- enforces the *same* grounding rules. See that module for the contract.
- """
- return apply_substring_gate(decisions)
-
- # ------------------------------------------------------------------
- # Staleness computation (static method)
- # ------------------------------------------------------------------
-
- # Keywords that signal a decision may have been contradicted or superseded.
- _CONFLICT_SIGNALS = frozenset(
- {
- "replace",
- "remove",
- "deprecate",
- "switch from",
- "migrate away",
- "drop",
- "revert",
- "undo",
- "disable",
- "eliminate",
- }
- )
-
- @staticmethod
- def compute_staleness(
- decision_created_at: datetime,
- affected_files: list[str],
- git_meta_map: dict[str, dict],
- decision_text: str = "",
- ) -> float:
- """Compute staleness score for a decision. Returns 0.0-1.0.
-
- In addition to commit volume and age, checks whether recent commit
- messages contain keywords that conflict with the decision text
- (e.g. decision says "use Redis" but a recent commit says "migrate
- away from Redis"). This boosts staleness when the underlying code
- may have diverged from the decision's intent.
- """
- if not affected_files:
- return 0.0
-
- now = datetime.now(UTC)
- scores: list[float] = []
- decision_lower = decision_text.lower()
-
- for fp in affected_files:
- meta = git_meta_map.get(fp)
- if meta is None:
- scores.append(1.0) # File missing / not tracked
- continue
-
- last_commit = meta.get("last_commit_at")
- if last_commit and decision_created_at:
- if isinstance(last_commit, str):
- last_commit = datetime.fromisoformat(last_commit.replace("Z", "+00:00"))
- _created = decision_created_at
- if isinstance(_created, str):
- _created = datetime.fromisoformat(_created.replace("Z", "+00:00"))
- if last_commit > _created:
- age_days = (now - _created).days
- commit_count = meta.get("commit_count_90d", 0)
- base_score = min(
- 1.0,
- commit_count / 15 * 0.7 + age_days / 365 * 0.3,
- )
-
- # Keyword conflict boost: check if recent commits
- # contradict the decision's content.
- conflict_boost = 0.0
- if decision_lower:
- sig_json = meta.get("significant_commits_json", "[]")
- try:
- sig_commits = (
- json.loads(sig_json) if isinstance(sig_json, str) else sig_json
- )
- except (json.JSONDecodeError, TypeError):
- sig_commits = []
- for sc in sig_commits:
- sc_date = sc.get("date", "")
- # Only consider commits after the decision was created
- if sc_date and sc_date > _created.isoformat():
- msg_lower = sc.get("message", "").lower()
- for signal in DecisionExtractor._CONFLICT_SIGNALS:
- if signal in msg_lower:
- # Check if the commit message shares meaningful
- # words with the decision text (context overlap)
- msg_words = set(msg_lower.split())
- dec_words = set(decision_lower.split())
- overlap = msg_words & dec_words - {
- "the",
- "a",
- "an",
- "to",
- "in",
- "for",
- "and",
- "or",
- "of",
- "is",
- "was",
- "with",
- }
- if len(overlap) >= 2:
- conflict_boost = max(conflict_boost, 0.3)
- break
-
- score = min(1.0, base_score + conflict_boost)
- scores.append(score)
- else:
- scores.append(0.0)
- else:
- scores.append(0.0)
-
- return round(sum(scores) / len(scores), 3) if scores else 0.0
-
- # ------------------------------------------------------------------
- # Main entry point
- # ------------------------------------------------------------------
-
- async def extract_all(self, *, on_step: Any | None = None) -> DecisionExtractionReport:
- """Run all capture sources in parallel. LLM failures are caught per-source.
-
- *on_step* is an optional callable invoked with the source name as each
- sub-extractor finishes (``inline_marker``, ``git_archaeology``,
- ``readme_mining``, ``adr``, ``changelog``, ``pr``, ``comment``). Used by
- the CLI to surface per-source progress.
-
- Every extracted decision is then put through the anti-hallucination
- substring gate (:meth:`_apply_substring_gate`) before being returned —
- ungrounded LLM fields are dropped and evidence-less decisions rejected.
- """
-
- async def _safe_source(name: str, coro_fn: Any) -> list[ExtractedDecision]:
- try:
- logger.info("decision_extractor.starting", source=name)
- result = await coro_fn()
- logger.info("decision_extractor.finished", source=name, count=len(result))
- return result
- except Exception as exc:
- logger.warning("decision_extractor.source_failed", source=name, error=str(exc))
- return []
- finally:
- if on_step:
- on_step(name)
-
- # (source name, bound coroutine factory) — order is the progress order.
- sources: list[tuple[str, Any]] = [
- ("inline_marker", self.scan_inline_markers),
- ("git_archaeology", self.mine_git_archaeology),
- ("readme_mining", self.mine_readme_docs),
- ("adr", self.discover_adrs),
- ("changelog", self.mine_changelog),
- ("pr", self.mine_pr_bodies),
- ("comment", self.mine_comment_archaeology),
- ]
-
- logger.info("decision_extractor.extract_all_start")
- results = await asyncio.gather(*[_safe_source(name, fn) for name, fn in sources])
- logger.info("decision_extractor.extract_all_done")
-
- # Raw per-source pool, then the anti-hallucination gate.
- raw: list[ExtractedDecision] = []
- by_source: dict[str, int] = {}
- for (name, _fn), source_decisions in zip(sources, results, strict=True):
- by_source[name] = len(source_decisions)
- raw.extend(source_decisions)
-
- decisions, rejected = self._apply_substring_gate(raw)
- logger.info(
- "decision_extractor.substring_gate",
- kept=len(decisions),
- rejected=rejected,
- )
-
- return DecisionExtractionReport(
- total_found=len(decisions),
- decisions=decisions,
- by_source=by_source,
- )
-
- # ------------------------------------------------------------------
- # Helpers
- # ------------------------------------------------------------------
-
- def _iter_source_files(self):
- """Yield source files under repo_path, skipping irrelevant dirs.
-
- Uses os.walk so we can prune entire subtrees (nested git repos,
- node_modules, etc.) without descending into them.
- """
- import os
-
- for dirpath, dirnames, filenames in os.walk(self._repo_path):
- # Prune skip-listed directories in-place so os.walk won't descend
- dirnames[:] = [
- d
- for d in dirnames
- if d not in _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.
- and not d.endswith(".egg-info")
- and not d.endswith(".dist-info")
- # Skip nested git repositories — they are separate codebases
- # and should not contribute decisions to the parent repo.
- and not (Path(dirpath) / d / ".git").exists()
- ]
-
- for fname in filenames:
- fpath = Path(dirpath) / fname
- if fpath.suffix.lower() not in _BINARY_EXTENSIONS:
- yield fpath
-
- def _get_neighbors(self, file_path: str) -> list[str]:
- """Get 1-hop graph neighbors for a file."""
- if self._graph is None:
- return []
- neighbors: set[str] = set()
- if file_path in self._graph:
- neighbors.update(self._graph.successors(file_path))
- neighbors.update(self._graph.predecessors(file_path))
- neighbors.discard(file_path)
- return list(neighbors)[:20] # Cap at 20
-
- @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 top-level module paths from file paths."""
- modules: set[str] = set()
- for fp in file_paths:
- parts = fp.replace("\\", "/").split("/")
- if len(parts) > 1:
- modules.add(parts[0])
- return sorted(modules)
-
- def _infer_modules_from_text(self, text: str) -> list[str]:
- """Infer module names by matching text against graph nodes."""
- if not self._graph:
- return []
- modules: set[str] = set()
- text_lower = text.lower()
- for node in self._graph.nodes:
- parts = node.replace("\\", "/").split("/")
- if len(parts) > 1 and parts[0].lower() in text_lower:
- modules.add(parts[0])
- return sorted(modules)[:5]
-
- def _infer_tags(self, text: str) -> list[str]:
- """Infer tags from decision text."""
- tag_keywords = {
- "auth": ["auth", "jwt", "oauth", "token", "session", "login"],
- "database": ["database", "sql", "postgres", "sqlite", "redis", "mongo", "db"],
- "api": ["api", "rest", "graphql", "endpoint", "route"],
- "performance": ["performance", "cache", "speed", "latency", "optimize"],
- "security": ["security", "encrypt", "hash", "cors", "csrf", "xss"],
- "infra": ["docker", "kubernetes", "deploy", "ci", "cd", "terraform"],
- "testing": ["test", "mock", "fixture", "assert"],
- }
- text_lower = text.lower()
- tags = []
- for tag, keywords in tag_keywords.items():
- if any(kw in text_lower for kw in keywords):
- tags.append(tag)
- return tags
-
- def _parse_decisions_json(self, content: str) -> list[ExtractedDecision]:
- """Parse LLM response as JSON array of decisions."""
- # Extract JSON from response (may be wrapped in markdown code blocks)
- content = content.strip()
- if content.startswith("```"):
- # Remove markdown code fences
- lines = content.split("\n")
- content = "\n".join(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 []
-
- if isinstance(data, dict):
- data = [data]
- if not isinstance(data, list):
- return []
-
- decisions = []
- for item in data:
- if not isinstance(item, dict):
- continue
- title = item.get("title", "")
- if not title:
- continue
- decisions.append(
- ExtractedDecision(
- title=title,
- context=item.get("context", ""),
- decision=item.get("decision", ""),
- rationale=item.get("rationale", ""),
- alternatives=item.get("alternatives", []),
- consequences=item.get("consequences", []),
- tags=item.get("tags", []),
- evidence_commits=[item["commit_sha"]] if "commit_sha" in item else [],
- source_quote=item.get("source_quote", ""),
- )
- )
- return decisions
+from repowise.core.analysis.decisions.extractor import * # noqa: F403
diff --git a/packages/core/src/repowise/core/analysis/decision_gate.py b/packages/core/src/repowise/core/analysis/decision_gate.py
index 3788addfe..e99f3d984 100644
--- a/packages/core/src/repowise/core/analysis/decision_gate.py
+++ b/packages/core/src/repowise/core/analysis/decision_gate.py
@@ -1,105 +1,8 @@
-"""Anti-hallucination substring gate — orchestration shared by every path
-that produces decision candidates (the multi-source extractor *and* the
-Phase-2 LLM-docs harvest).
+"""Back-compat façade — moved to ``repowise.core.analysis.decisions.gate``.
-The gate is the product guarantee: a ``decision`` / ``rationale`` /
-``source_quote`` field that does not substring- or token-match the verbatim
-source span it claims to come from is **dropped**, and a candidate whose every
-produced field is ungrounded is **rejected**. It became critical in Phase 2
-because the page generator now *generates* decision candidates rather than only
-reading them — the gate is what stops a fluent-but-invented rationale from being
-stored as institutional memory.
-
-This module operates on duck-typed candidates (anything exposing the
-``decision`` / ``rationale`` / ``source_quote`` / ``source_text`` /
-``verification`` attributes — :class:`~repowise.core.analysis.decision_extractor.ExtractedDecision`
-is the in-tree shape) so it depends on neither the extractor nor the generator,
-and both can call it without a cycle.
+Import from the new path; this re-export keeps existing imports working.
"""
from __future__ import annotations
-from typing import Protocol, TypeVar
-
-from repowise.core.analysis.decision_provenance import normalize_text, verify_quote
-
-__all__ = ["GateCandidate", "apply_substring_gate"]
-
-# Fields whose verbatim grounding the gate enforces, in priority order. The
-# strongest surviving verdict across them is stamped onto ``verification``.
-_GATED_FIELDS = ("decision", "rationale", "source_quote")
-
-
-class GateCandidate(Protocol):
- """Structural shape the gate reads and mutates."""
-
- decision: str
- rationale: str
- source_quote: str
- source_text: str
- verification: str
-
-
-_C = TypeVar("_C", bound=GateCandidate)
-
-
-def apply_substring_gate(decisions: list[_C]) -> tuple[list[_C], int]:
- """Drop ungrounded fields, reject candidates with no surviving evidence.
-
- Every produced ``decision`` / ``rationale`` / ``source_quote`` must
- substring- or token-match the verbatim ``source_text`` the producer
- recorded (see :func:`decision_provenance.verify_quote`). Unverifiable
- fields are cleared; a candidate whose every produced field is unverifiable
- is rejected. ``verification`` is stamped with the strongest surviving
- verdict. A candidate with no ``source_text`` (nothing to check against) is
- kept but left ``unverified`` — we never fabricate a rejection we cannot
- justify. ``source_text`` is cleared on every survivor since it is a
- transient and must never reach persistence.
-
- Returns ``(kept, rejected_count)``.
- """
- kept: list[_C] = []
- rejected = 0
- for d in decisions:
- src = getattr(d, "source_text", "") or ""
- if not src:
- d.verification = "unverified"
- d.source_text = ""
- kept.append(d)
- continue
-
- # Normalize the (possibly large) source span once per candidate and
- # reuse it across the field checks — verify_quote re-normalizes its
- # second arg, but normalizing an already-collapsed string is a cheap
- # no-op, so the gate stays O(source span) per candidate.
- norm_src = normalize_text(src)
-
- verdicts: list[str] = []
- produced_any = False
- grounded_any = False
- for fname in _GATED_FIELDS:
- val = (getattr(d, fname, "") or "").strip()
- if not val:
- continue
- produced_any = True
- verdict = verify_quote(val, norm_src)
- if verdict == "unverified":
- setattr(d, fname, "") # drop the hallucinated field
- else:
- grounded_any = True
- verdicts.append(verdict)
-
- if produced_any and not grounded_any:
- rejected += 1
- continue
-
- if "exact" in verdicts:
- d.verification = "exact"
- elif "fuzzy" in verdicts:
- d.verification = "fuzzy"
- else:
- d.verification = "unverified"
- d.source_text = "" # transient — don't carry into persistence
- kept.append(d)
-
- return kept, rejected
+from repowise.core.analysis.decisions.gate import * # noqa: F403
diff --git a/packages/core/src/repowise/core/analysis/decision_provenance.py b/packages/core/src/repowise/core/analysis/decision_provenance.py
index 43abbfe60..eaae4779c 100644
--- a/packages/core/src/repowise/core/analysis/decision_provenance.py
+++ b/packages/core/src/repowise/core/analysis/decision_provenance.py
@@ -1,127 +1,8 @@
-"""Provenance primitives shared by the decision extractor and the persistence
-layer: the source-ranking ladder, the corroboration-aware confidence formula,
-and the anti-hallucination substring gate helpers.
+"""Back-compat façade — moved to ``repowise.core.analysis.decisions.provenance``.
-This module deliberately depends on nothing from ``decision_extractor`` or the
-persistence layer so both can import it without a cycle (``crud.py`` consumes
-the ranking ladder + confidence formula; ``decision_extractor`` consumes the
-verification helpers).
-
-Note: this is the *decision* provenance subsystem and is unrelated to the
-page-level provenance in ``generation.page_generator`` (``_attach_file_provenance``),
-which records a page's source files / KG layer. They share a word, not a concern.
+Import from the new path; this re-export keeps existing imports working.
"""
from __future__ import annotations
-import re
-
-__all__ = [
- "MAX_SOURCE_RANK",
- "SOURCE_RANK",
- "compute_confidence",
- "normalize_text",
- "rank_for_source",
- "verify_quote",
-]
-
-# ---------------------------------------------------------------------------
-# Source ranking ladder
-# ---------------------------------------------------------------------------
-#
-# Higher rank = more authoritative provenance. When two sources describe the
-# same decision, the headline fields come from the highest-rank evidence and
-# the lower-rank source is retained as a corroborating evidence row (never
-# discarded). ``test_name`` and ``inferred`` are placeholders for later phases
-# (LLM-docs harvest lands ``llm_inferred`` in Phase 2) but the full ladder is
-# defined now so ranks are stable across phases.
-SOURCE_RANK: dict[str, int] = {
- "cli": 9, # human-authored manual entry — most authoritative
- "adr": 8, # architecture decision records (structured, intentional)
- "pr": 7, # PR / squash-merge body
- "commit": 6, # individual commit message
- "git_archaeology": 6, # alias for commit-mined decisions
- "changelog": 5, # keep-a-changelog Changed/Removed/Deprecated
- "inline_marker": 4, # # WHY: / # DECISION: code markers
- "comment": 3, # rationale prose in block comments / docstrings
- "readme_mining": 3, # implicit decisions in README/docs prose
- "test_name": 2, # placeholder — behaviour asserted by a test name
- "inferred": 1, # placeholder — purely inferred, no verbatim source
- "llm_inferred": 1, # Phase 2 LLM-docs harvest
-}
-
-MAX_SOURCE_RANK: int = max(SOURCE_RANK.values())
-
-
-def rank_for_source(source: str | None) -> int:
- """Return the ranking ladder value for *source* (unknown → lowest rank)."""
- return SOURCE_RANK.get((source or "").lower(), 1)
-
-
-# ---------------------------------------------------------------------------
-# Confidence: a function of best source rank + corroboration + verification
-# ---------------------------------------------------------------------------
-
-
-def compute_confidence(
- top_rank: int,
- corroboration_count: int = 1,
- verification: str = "exact",
-) -> float:
- """Confidence for a decision backed by ``corroboration_count`` evidence rows.
-
- Rises with the best source rank and with the number of *independent*
- corroborating sources; multiplicatively decayed when the strongest
- surviving evidence is only fuzzy- or un-verified. Bounded to ``[0, 0.99]``
- (we never claim certainty). Recency decay is deferred — staleness scoring
- already models age separately.
- """
- base = 0.4 + 0.5 * (top_rank / MAX_SOURCE_RANK)
- corroboration_bonus = min(0.12, 0.04 * max(0, corroboration_count - 1))
- conf = base + corroboration_bonus
- if verification == "fuzzy":
- conf *= 0.85
- elif verification == "unverified":
- conf *= 0.6
- return round(max(0.0, min(0.99, conf)), 3)
-
-
-# ---------------------------------------------------------------------------
-# Anti-hallucination substring gate
-# ---------------------------------------------------------------------------
-
-_WS_RE = re.compile(r"\s+")
-
-
-def normalize_text(text: str | None) -> str:
- """Collapse whitespace + lowercase for substring/token comparison."""
- if not text:
- return ""
- return _WS_RE.sub(" ", text).strip().lower()
-
-
-def verify_quote(
- quote: str | None,
- source_text: str | None,
- *,
- fuzzy_threshold: float = 0.6,
-) -> str:
- """Classify how well *quote* is grounded in *source_text*.
-
- Returns:
- ``"exact"`` — *quote* is a normalized substring of the source span.
- ``"fuzzy"`` — token overlap ≥ *fuzzy_threshold* (paraphrase / reflow).
- ``"unverified"`` — neither (likely hallucinated, or no source to check).
- """
- q = normalize_text(quote)
- src = normalize_text(source_text)
- if not q or not src:
- return "unverified"
- if q in src:
- return "exact"
- q_tokens = set(q.split())
- if not q_tokens:
- return "unverified"
- src_tokens = set(src.split())
- overlap = len(q_tokens & src_tokens) / len(q_tokens)
- return "fuzzy" if overlap >= fuzzy_threshold else "unverified"
+from repowise.core.analysis.decisions.provenance import * # noqa: F403
diff --git a/packages/core/src/repowise/core/analysis/decision_semantic_match.py b/packages/core/src/repowise/core/analysis/decision_semantic_match.py
index 0ba3b3340..e18c16cdd 100644
--- a/packages/core/src/repowise/core/analysis/decision_semantic_match.py
+++ b/packages/core/src/repowise/core/analysis/decision_semantic_match.py
@@ -1,188 +1,8 @@
-"""Embedding-based semantic matching for decision dedup (Phase 2C).
+"""Back-compat façade — moved to ``repowise.core.analysis.decisions.semantic_match``.
-Title-string dedup (the cheap first pass in ``crud.bulk_upsert_decisions``)
-collapses decisions whose normalized titles are identical, but it misses
-paraphrases: *"Use Redis"* and *"Adopt Redis cache"* describe one decision yet
-share no normalized title. This module adds the second pass on top of the
-**page-generator vector store** — the same store wiki pages live in.
-
-Decisions are embedded into that shared store under a ``decision:`` page-id
-namespace with ``page_type="decision_record"``. Two consequences, both wanted:
-
-- **Dedup reuses the store.** A residual (title-unmatched) candidate is matched
- by querying the store and keeping the nearest ``decision:`` neighbour whose
- cosine similarity clears a threshold — no separate decision index, no
- in-process re-embedding of the whole decision set.
-- **Decisions become searchable.** Because they live in the same store as
- pages, ``search_codebase`` surfaces them alongside docs — a feature, not a
- leak: a query like "why Redis?" can return the decision record directly.
-
-All backends return cosine similarity from ``search`` (InMemory/pgvector
-natively; LanceDB normalised in ``lancedb_store``), so a single similarity
-threshold applies uniformly.
+Import from the new path; this re-export keeps existing imports working.
"""
from __future__ import annotations
-import contextlib
-from typing import Any
-
-__all__ = [
- "DECISION_PAGE_TYPE",
- "DECISION_VECTOR_PREFIX",
- "DEFAULT_DEDUP_TAU",
- "decision_match_text",
- "find_duplicate_decision",
- "find_related_decisions",
- "upsert_decision_vector",
-]
-
-# Cosine threshold above which two decision texts are treated as the same
-# decision. Tuned conservatively: high enough that unrelated decisions don't
-# collapse, low enough that genuine paraphrases ("use Redis" / "adopt Redis
-# cache") merge. Revisit empirically alongside the Phase-3 conflict detector,
-# which reuses this similarity signal.
-DEFAULT_DEDUP_TAU = 0.83
-
-# Page-id namespace + page_type for decision vectors co-located in the page
-# store. The prefix lets dedup filter store hits down to decisions; the
-# page_type lets search surfaces label them.
-DECISION_VECTOR_PREFIX = "decision:"
-DECISION_PAGE_TYPE = "decision_record"
-
-# How many nearest neighbours to pull before filtering to the decision
-# namespace. Decisions are a small slice of a store dominated by page vectors,
-# so we over-fetch to make sure a genuine paraphrase (which sits at very high
-# similarity) isn't crowded out of the window by unrelated-but-near pages.
-_SEARCH_FETCH = 50
-
-
-def decision_match_text(title: str, decision: str = "") -> str:
- """The text used to embed a decision for semantic matching.
-
- Title carries the most signal; the decision statement disambiguates
- same-titled-but-different records. Kept in one place so the stored vector
- and the query side always embed the same shape.
- """
- title = (title or "").strip()
- decision = (decision or "").strip()
- return f"{title}\n{decision}".strip() if decision else title
-
-
-def _decision_page_id(decision_id: str) -> str:
- return f"{DECISION_VECTOR_PREFIX}{decision_id}"
-
-
-async def upsert_decision_vector(
- store: Any,
- decision_id: str,
- *,
- title: str,
- decision: str = "",
- evidence_file: str | None = None,
-) -> None:
- """Embed a decision into the shared page store (idempotent on its id).
-
- Makes the decision both matchable for dedup and discoverable via
- ``search_codebase``. Failures are swallowed: a vector-store hiccup must
- never abort the SQL upsert that already happened.
- """
- text = decision_match_text(title, decision)
- if not text:
- return
- # Best-effort: search visibility / dedup is an enhancement, not a
- # correctness requirement for the SQL record, so a store hiccup is swallowed.
- with contextlib.suppress(Exception):
- await store.embed_and_upsert(
- _decision_page_id(decision_id),
- text,
- {
- "title": title or "",
- "page_type": DECISION_PAGE_TYPE,
- "target_path": evidence_file or "",
- "content": text,
- },
- )
-
-
-async def find_duplicate_decision(
- store: Any,
- *,
- title: str,
- decision: str = "",
- tau: float = DEFAULT_DEDUP_TAU,
- exclude_ids: set[str] | None = None,
-) -> str | None:
- """Return the id of an existing decision that is a semantic duplicate.
-
- Queries the shared store, filters hits to the ``decision:`` namespace
- (dropping any in *exclude_ids*), and returns the nearest one whose cosine
- similarity is ≥ *tau* — or None when nothing clears the bar. Store errors
- degrade to None (title dedup still applied upstream).
- """
- query = decision_match_text(title, decision)
- if not query:
- return None
- exclude = exclude_ids or set()
- try:
- results = await store.search(query, limit=_SEARCH_FETCH)
- except Exception:
- return None
-
- for r in results: # results are ordered best-first
- page_id = getattr(r, "page_id", "")
- if not page_id.startswith(DECISION_VECTOR_PREFIX):
- continue
- decision_id = page_id[len(DECISION_VECTOR_PREFIX) :]
- if decision_id in exclude:
- continue
- # First (nearest) decision hit decides: if it clears the bar it's the
- # match; if not, nothing closer exists, so there is no duplicate.
- return decision_id if getattr(r, "score", 0.0) >= tau else None
- return None
-
-
-async def find_related_decisions(
- store: Any,
- *,
- title: str,
- decision: str = "",
- lo: float,
- hi: float = 1.01,
- exclude_ids: set[str] | None = None,
- limit: int = 25,
-) -> list[tuple[str, float]]:
- """Return ``(decision_id, similarity)`` for decisions *about the same topic*.
-
- Powers Phase-3 supersession/conflict detection. Where
- :func:`find_duplicate_decision` returns the single nearest neighbour above
- the dedup threshold (a *merge*), this returns every ``decision:`` neighbour
- whose cosine similarity sits in the band ``[lo, hi)`` — high enough to be
- the same topic, but (by default) *below* the dedup threshold so they were
- not collapsed into one record. Those are exactly the candidates that might
- contradict / supersede each other. Ordered best-first; store errors degrade
- to an empty list.
- """
- query = decision_match_text(title, decision)
- if not query:
- return []
- exclude = exclude_ids or set()
- try:
- results = await store.search(query, limit=_SEARCH_FETCH)
- except Exception:
- return []
-
- out: list[tuple[str, float]] = []
- for r in results:
- page_id = getattr(r, "page_id", "")
- if not page_id.startswith(DECISION_VECTOR_PREFIX):
- continue
- decision_id = page_id[len(DECISION_VECTOR_PREFIX) :]
- if decision_id in exclude:
- continue
- score = getattr(r, "score", 0.0)
- if lo <= score < hi:
- out.append((decision_id, score))
- if len(out) >= limit:
- break
- return out
+from repowise.core.analysis.decisions.semantic_match import * # noqa: F403
diff --git a/packages/core/src/repowise/core/analysis/decisions/__init__.py b/packages/core/src/repowise/core/analysis/decisions/__init__.py
new file mode 100644
index 000000000..ef3b4fc59
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/__init__.py
@@ -0,0 +1,4 @@
+"""Architectural decision intelligence — extraction, provenance, gating,
+semantic dedup, and evolution. Grouped from the former analysis/decision_*.py
+modules.
+"""
diff --git a/packages/core/src/repowise/core/analysis/decisions/evolution.py b/packages/core/src/repowise/core/analysis/decisions/evolution.py
new file mode 100644
index 000000000..25b6d3867
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/evolution.py
@@ -0,0 +1,688 @@
+"""Decision evolution — supersession/conflict detection + two-pass update scan.
+
+Phase 3B + 3C of the decision-layer overhaul. Two complementary mechanisms,
+both small and gated, both leaning on the Phase-2 primitives
+(:data:`decision_semantic_match.DEFAULT_DEDUP_TAU` for similarity and
+:func:`decision_gate.apply_substring_gate` for anti-hallucination):
+
+**3B — semantic supersession & conflict** (:func:`detect_supersessions_and_conflicts`).
+ When a freshly upserted decision is semantically *about the same topic* as
+ an existing one (cosine in the band ``[RELATED_TAU, DEDUP_TAU)`` — related
+ but not a duplicate) **and** contradicts it (opposing verbs / a reversal
+ signal, optionally confirmed by a gated LLM judge), record a typed edge:
+ ``supersedes`` when one clearly reverses the other (auto-flip the older to
+ ``superseded`` only above :data:`SUPERSEDE_AUTOFLIP_CONFIDENCE`, otherwise a
+ reviewable proposal), or ``conflicts_with`` when two *active* decisions
+ contradict with no clear winner.
+
+**3C — two-pass evolution on ``repowise update``** (:func:`run_update_evolution`).
+ Pass 1 (cheap, no LLM): scan changed files' diffs + new commit bodies for
+ evolution signals (``migrate``/``replace``/``deprecate``/…) and cross-ref
+ existing decisions touching those files. Pass 2 (LLM, survivors only,
+ gated): ask whether each surviving decision is *amended* / *superseded* /
+ *reaffirmed* by the change. The caller runs this **before** page
+ regeneration so the governed pages of an amended decision re-render in the
+ same run.
+
+Cheap-before-expensive: Pass 1 gates Pass 2 (LLM only on survivors); semantic
+comparisons reuse the shared store; edge writes are O(candidates); the lineage
+walk that consumes these edges is bounded elsewhere.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any
+
+import structlog
+
+from repowise.core.analysis.decisions.gate import apply_substring_gate
+from repowise.core.analysis.decisions.provenance import normalize_text
+from repowise.core.analysis.decisions.semantic_match import (
+ DEFAULT_DEDUP_TAU,
+ find_related_decisions,
+)
+
+logger = structlog.get_logger(__name__)
+
+__all__ = [
+ "EVOLUTION_SIGNALS",
+ "RELATED_TAU",
+ "SUPERSEDE_AUTOFLIP_CONFIDENCE",
+ "contradicts",
+ "detect_supersessions_and_conflicts",
+ "is_reversal",
+ "pass1_evolution_candidates",
+ "run_update_evolution",
+ "scan_evolution_signals",
+ "supersession_confidence",
+]
+
+# ---------------------------------------------------------------------------
+# Tunable knobs (live next to DEFAULT_DEDUP_TAU; pick empirically on real repos)
+# ---------------------------------------------------------------------------
+
+# Lower bound of the "same topic" similarity band. The upper bound is the dedup
+# threshold: above it the two would have merged into one record (not a
+# supersession); below RELATED_TAU they are unrelated. So a supersession
+# candidate sits in ``[RELATED_TAU, DEFAULT_DEDUP_TAU)``.
+RELATED_TAU = 0.6
+
+# A detected supersession always records the edge; the *older* decision is only
+# auto-flipped to ``superseded`` when confidence clears this bar. Conservative
+# by design — everything below stays a reviewable proposal.
+SUPERSEDE_AUTOFLIP_CONFIDENCE = 0.85
+
+# ---------------------------------------------------------------------------
+# Evolution signals (Pass-1 pattern scan) + contradiction heuristics
+# ---------------------------------------------------------------------------
+
+# Substrings that, in a diff or commit body, hint the change *evolves* a prior
+# decision rather than just touching code. Kept lowercase; matched as substrings.
+EVOLUTION_SIGNALS: frozenset[str] = frozenset(
+ {
+ "migrate",
+ "migrated",
+ "migration",
+ "replace",
+ "replaced",
+ "switch to",
+ "switched to",
+ "move to",
+ "moved to",
+ "move away",
+ "moved away",
+ "chose",
+ "choose",
+ "because",
+ "instead of",
+ "rather than",
+ "deprecate",
+ "deprecated",
+ "revert",
+ "reverted",
+ "no longer",
+ "stop using",
+ "drop ",
+ "dropped ",
+ "in favor of",
+ "in favour of",
+ }
+)
+
+# Directional reversal phrases: their presence in the *newer* decision means it
+# reverses/replaces a predecessor (→ supersedes, not merely conflicts).
+_REVERSAL_SIGNALS: tuple[str, ...] = (
+ "replace",
+ "replaced",
+ "migrate",
+ "migrated",
+ "migration",
+ "switch to",
+ "switched to",
+ "move away",
+ "moved away",
+ "move to",
+ "moved to",
+ "revert",
+ "reverted",
+ "deprecate",
+ "deprecated",
+ "no longer",
+ "stop using",
+ "instead of",
+ "in favor of",
+ "in favour of",
+)
+
+# Opposing verb/intent pairs. A pair where one side appears in text A and the
+# other in text B signals the two decisions push in opposite directions.
+_OPPOSING_VERB_PAIRS: tuple[tuple[frozenset[str], frozenset[str]], ...] = (
+ (
+ frozenset(
+ {"adopt", "adopted", "use", "using", "add", "added", "introduce", "enable", "enabled"}
+ ),
+ frozenset(
+ {
+ "drop",
+ "dropped",
+ "remove",
+ "removed",
+ "deprecate",
+ "deprecated",
+ "disable",
+ "disabled",
+ "revert",
+ "reverted",
+ "abandon",
+ }
+ ),
+ ),
+ (
+ frozenset({"switch to", "migrate to", "move to"}),
+ frozenset({"revert", "roll back", "rollback", "move back"}),
+ ),
+ (
+ frozenset({"sync", "synchronous", "blocking"}),
+ frozenset({"async", "asynchronous", "non-blocking"}),
+ ),
+ (frozenset({"monolith", "monolithic"}), frozenset({"microservice", "microservices"})),
+)
+
+_STOPWORDS = frozenset(
+ {
+ "the",
+ "a",
+ "an",
+ "to",
+ "of",
+ "for",
+ "and",
+ "or",
+ "in",
+ "on",
+ "with",
+ "we",
+ "our",
+ "use",
+ "using",
+ "should",
+ "this",
+ "that",
+ "is",
+ "are",
+ "be",
+ "by",
+ "as",
+ "it",
+ "its",
+ "from",
+ "at",
+ "via",
+ "into",
+ }
+)
+
+_TOKEN_RE = re.compile(r"[a-z0-9]+")
+
+
+def _content_tokens(text: str) -> set[str]:
+ """Lowercased content tokens (stopwords + short tokens dropped)."""
+ return {
+ t for t in _TOKEN_RE.findall((text or "").lower()) if len(t) > 2 and t not in _STOPWORDS
+ }
+
+
+def _shared_topic(text_a: str, text_b: str, *, min_shared: int = 2) -> bool:
+ """Do two texts share enough content tokens to be 'about the same thing'?"""
+ return len(_content_tokens(text_a) & _content_tokens(text_b)) >= min_shared
+
+
+def scan_evolution_signals(text: str) -> list[str]:
+ """Return the evolution signals present in *text* (Pass-1 cheap filter)."""
+ low = normalize_text(text)
+ if not low:
+ return []
+ return sorted(s for s in EVOLUTION_SIGNALS if s.strip() in low)
+
+
+def is_reversal(text: str) -> tuple[bool, str]:
+ """Does *text* read like it reverses/replaces a prior choice? → (bool, signal)."""
+ low = normalize_text(text)
+ for sig in _REVERSAL_SIGNALS:
+ if sig in low:
+ return True, sig
+ return False, ""
+
+
+def contradicts(text_a: str, text_b: str) -> tuple[bool, str]:
+ """Heuristic: do two decision texts push in opposite directions?
+
+ True when (a) an opposing verb pair straddles the two texts, or (b) either
+ text carries a directional reversal signal — *and* the two share enough
+ content tokens to be about the same topic (so "deprecate X" and "adopt Y"
+ for unrelated X/Y don't false-positive). Returns ``(bool, signal)``.
+ """
+ if not _shared_topic(text_a, text_b):
+ return False, ""
+ low_a = normalize_text(text_a)
+ low_b = normalize_text(text_b)
+
+ for left, right in _OPPOSING_VERB_PAIRS:
+ a_left = any(v in low_a for v in left)
+ b_right = any(v in low_b for v in right)
+ a_right = any(v in low_a for v in right)
+ b_left = any(v in low_b for v in left)
+ if (a_left and b_right) or (a_right and b_left):
+ return True, "opposing-verbs"
+
+ rev_a, sig_a = is_reversal(text_a)
+ if rev_a:
+ return True, sig_a
+ rev_b, sig_b = is_reversal(text_b)
+ if rev_b:
+ return True, sig_b
+ return False, ""
+
+
+def supersession_confidence(
+ similarity: float,
+ *,
+ verified: bool = False,
+ has_reversal_signal: bool = False,
+) -> float:
+ """Confidence that one decision supersedes another. Bounded ``[0, 0.99]``.
+
+ Rises with semantic similarity, bumped when the newer decision carries an
+ explicit reversal signal and when its headline is a verified quote. Kept
+ deliberately conservative around :data:`SUPERSEDE_AUTOFLIP_CONFIDENCE` so a
+ borderline match stays a proposal rather than auto-flipping the older one.
+ """
+ conf = 0.45 + 0.4 * max(0.0, min(1.0, similarity))
+ if has_reversal_signal:
+ conf += 0.1
+ if verified:
+ conf += 0.05
+ return round(max(0.0, min(0.99, conf)), 3)
+
+
+# ---------------------------------------------------------------------------
+# 3B — semantic supersession & conflict detection
+# ---------------------------------------------------------------------------
+
+
+def _created_at(rec: Any) -> Any:
+ return getattr(rec, "created_at", None)
+
+
+async def detect_supersessions_and_conflicts(
+ session: Any,
+ repository_id: str,
+ *,
+ touched_ids: list[str],
+ vector_store: Any | None = None,
+ provider: Any | None = None,
+ autoflip_confidence: float = SUPERSEDE_AUTOFLIP_CONFIDENCE,
+) -> dict[str, int]:
+ """Record supersedes/conflicts edges for the just-upserted decisions.
+
+ For each touched decision, find existing decisions in the "same topic" band
+ and, where they contradict, write a typed :class:`DecisionEdge`. ``supersedes``
+ edges auto-flip the older decision to ``superseded`` only above
+ *autoflip_confidence*. Best-effort: requires *vector_store* (the semantic
+ signal); returns zero-counts and does nothing without it. *provider*, when
+ supplied, is a gated tiebreaker for pairs the heuristic misses.
+
+ Returns ``{"supersedes": n, "conflicts": n, "flipped": n}``.
+ """
+ summary = {"supersedes": 0, "conflicts": 0, "flipped": 0}
+ if not touched_ids or vector_store is None:
+ return summary
+
+ from datetime import UTC, datetime
+
+ from repowise.core.persistence.decision_graph import upsert_decision_edge
+ from repowise.core.persistence.models import DecisionRecord
+
+ # Avoid recording both (A supersedes B) and (B supersedes A) within one run.
+ handled_pairs: set[frozenset[str]] = set()
+
+ for tid in touched_ids:
+ rec = await session.get(DecisionRecord, tid)
+ if rec is None or rec.repository_id != repository_id:
+ continue
+ related = await find_related_decisions(
+ vector_store,
+ title=rec.title,
+ decision=rec.decision or "",
+ lo=RELATED_TAU,
+ hi=DEFAULT_DEDUP_TAU,
+ exclude_ids={rec.id},
+ )
+ for other_id, sim in related:
+ pair = frozenset({rec.id, other_id})
+ if pair in handled_pairs:
+ continue
+ other = await session.get(DecisionRecord, other_id)
+ if other is None or other.repository_id != repository_id:
+ continue
+
+ text_new = f"{rec.title}. {rec.decision}"
+ text_old = f"{other.title}. {other.decision}"
+ contra, signal = contradicts(text_new, text_old)
+ if not contra and provider is not None:
+ contra, signal = await _llm_contradiction_judge(
+ provider, text_a=text_new, text_b=text_old
+ )
+ if not contra:
+ continue
+ handled_pairs.add(pair)
+
+ # Temporal order decides direction: the newer decision supersedes.
+ ca_rec, ca_other = _created_at(rec), _created_at(other)
+ if ca_rec is not None and ca_other is not None and ca_other > ca_rec:
+ newer, older = other, rec
+ else:
+ newer, older = rec, other
+
+ rev, rev_sig = is_reversal(f"{newer.title}. {newer.decision}")
+ conf = supersession_confidence(
+ sim,
+ verified=(newer.verification == "exact"),
+ has_reversal_signal=rev,
+ )
+
+ if rev or older.status not in ("active",) or newer.status not in ("active",):
+ # A clear reversal, or at least one side not co-active → model
+ # it as supersession (newer over older).
+ edge = await upsert_decision_edge(
+ session,
+ repository_id=repository_id,
+ src_decision_id=newer.id,
+ dst_decision_id=older.id,
+ kind="supersedes",
+ confidence=conf,
+ evidence=f"auto-detected: {signal or rev_sig or 'semantic'} (sim={sim:.2f})",
+ )
+ if edge is not None:
+ summary["supersedes"] += 1
+ if conf >= autoflip_confidence and older.status in ("active", "proposed"):
+ older.status = "superseded"
+ older.superseded_by = newer.id
+ older.updated_at = datetime.now(UTC)
+ summary["flipped"] += 1
+ else:
+ # Two active decisions contradict, neither clearly reverses the
+ # other → a governance smell, surfaced in health.
+ edge = await upsert_decision_edge(
+ session,
+ repository_id=repository_id,
+ src_decision_id=newer.id,
+ dst_decision_id=older.id,
+ kind="conflicts_with",
+ confidence=conf,
+ evidence=f"auto-detected: {signal or 'semantic'} (sim={sim:.2f})",
+ )
+ if edge is not None:
+ summary["conflicts"] += 1
+
+ await session.flush()
+ return summary
+
+
+_CONTRADICTION_SYSTEM = (
+ "You judge whether two architectural decisions contradict each other. "
+ "Answer with a single word: CONTRADICT or COMPATIBLE."
+)
+
+
+async def _llm_contradiction_judge(provider: Any, *, text_a: str, text_b: str) -> tuple[bool, str]:
+ """Gated LLM tiebreaker: do two decisions contradict? Best-effort → (bool, signal)."""
+ prompt = (
+ "Decision A:\n"
+ f"{text_a}\n\n"
+ "Decision B:\n"
+ f"{text_b}\n\n"
+ "Do these two decisions contradict each other (one reverses, replaces, "
+ "or is incompatible with the other)? Answer CONTRADICT or COMPATIBLE."
+ )
+ try:
+ response = await provider.generate(
+ _CONTRADICTION_SYSTEM, prompt, max_tokens=8, temperature=0.0
+ )
+ except Exception:
+ return False, ""
+ verdict = (response.content or "").strip().upper()
+ if verdict.startswith("CONTRADICT"):
+ return True, "llm-judge"
+ return False, ""
+
+
+# ---------------------------------------------------------------------------
+# 3C — two-pass evolution on update
+# ---------------------------------------------------------------------------
+
+
+def pass1_evolution_candidates(
+ changed_files: set[str],
+ evidence_by_file: dict[str, str],
+ existing_decisions: list[Any],
+) -> list[tuple[Any, str, list[str]]]:
+ """Pass 1 (no LLM): existing decisions whose governed files changed *with*
+ an evolution signal in the change evidence.
+
+ *evidence_by_file* maps a changed file path to the text to scan (its diff +
+ triggering commit subject/body — NOT the whole file, to keep ``because`` /
+ ``instead of`` from firing on every source file). Returns
+ ``[(decision, evidence_text, signals)]`` — the survivors handed to Pass 2.
+ """
+ out: list[tuple[Any, str, list[str]]] = []
+ for dec in existing_decisions:
+ try:
+ affected = set(json.loads(dec.affected_files_json or "[]"))
+ except (TypeError, ValueError):
+ affected = set()
+ touched = affected & changed_files
+ if not touched:
+ continue
+ signals: set[str] = set()
+ parts: list[str] = []
+ for f in sorted(touched):
+ evidence = evidence_by_file.get(f, "")
+ sigs = scan_evolution_signals(evidence)
+ if sigs:
+ signals.update(sigs)
+ parts.append(evidence[:2000])
+ if signals:
+ out.append((dec, "\n\n".join(parts), sorted(signals)))
+ return out
+
+
+_EVOLUTION_JUDGE_SYSTEM = (
+ "You assess whether a code change evolves a previously recorded "
+ "architectural decision. Return only valid JSON. "
+ "Never invent rationale not present in the change evidence."
+)
+
+_EVOLUTION_JUDGE_PROMPT = """\
+An existing architectural decision and a recent code change are given below. \
+Decide how the change affects the decision.
+
+EXISTING DECISION
+Title: {title}
+Decision: {decision}
+Rationale: {rationale}
+
+CHANGE EVIDENCE (diff + commit messages)
+{evidence}
+
+Respond with a JSON object:
+{{"verdict": "superseded" | "amended" | "reaffirmed" | "none",
+ "rationale": "<one sentence quoting the change evidence>",
+ "source_quote": "<verbatim span from the change evidence supporting the verdict>"}}
+
+- "superseded": the change reverses/replaces the decision.
+- "amended": the change modifies the decision without fully reversing it.
+- "reaffirmed": the change is consistent with and strengthens the decision.
+- "none": the change does not affect the decision.
+Quote only text that appears verbatim in the change evidence."""
+
+
+class _JudgeCandidate:
+ """Minimal duck-typed shape for :func:`apply_substring_gate`."""
+
+ def __init__(self, *, rationale: str, source_quote: str, source_text: str) -> None:
+ self.decision = ""
+ self.rationale = rationale
+ self.source_quote = source_quote
+ self.source_text = source_text
+ self.verification = "unverified"
+
+
+async def _judge_evolution(
+ provider: Any,
+ *,
+ title: str,
+ decision: str,
+ rationale: str,
+ evidence_text: str,
+) -> dict | None:
+ """Pass 2: ask the LLM how the change affects one decision (gated).
+
+ Any rationale/quote the LLM produces must substring/token-match the change
+ evidence (the same anti-hallucination gate the extractor + harvest use) —
+ an ungrounded verdict is discarded. Returns the parsed, gated verdict dict
+ or ``None``.
+ """
+ prompt = _EVOLUTION_JUDGE_PROMPT.format(
+ title=title,
+ decision=decision,
+ rationale=rationale,
+ evidence=evidence_text[:6000],
+ )
+ try:
+ response = await provider.generate(
+ _EVOLUTION_JUDGE_SYSTEM, prompt, max_tokens=400, temperature=0.1
+ )
+ except Exception:
+ return None
+
+ parsed = _parse_judge_json(response.content)
+ if not parsed:
+ return None
+ verdict = (parsed.get("verdict") or "none").strip().lower()
+ if verdict not in ("superseded", "amended", "reaffirmed"):
+ return None
+
+ # Gate the produced rationale/quote against the change evidence.
+ cand = _JudgeCandidate(
+ rationale=parsed.get("rationale") or "",
+ source_quote=parsed.get("source_quote") or "",
+ source_text=evidence_text,
+ )
+ kept, _ = apply_substring_gate([cand])
+ if not kept:
+ # Reaffirmed verdicts need no grounded quote (they assert "nothing
+ # changed"); supersede/amend must be evidence-backed.
+ if verdict == "reaffirmed":
+ return {
+ "verdict": verdict,
+ "rationale": "",
+ "source_quote": "",
+ "verification": "unverified",
+ }
+ return None
+ survivor = kept[0]
+ return {
+ "verdict": verdict,
+ "rationale": survivor.rationale,
+ "source_quote": survivor.source_quote,
+ "verification": survivor.verification,
+ }
+
+
+_JSON_BLOCK_RE = re.compile(r"\{.*\}", re.DOTALL)
+
+
+def _parse_judge_json(content: str | None) -> dict | None:
+ if not content:
+ return None
+ try:
+ return json.loads(content)
+ except (TypeError, ValueError):
+ pass
+ match = _JSON_BLOCK_RE.search(content)
+ if not match:
+ return None
+ try:
+ parsed = json.loads(match.group(0))
+ return parsed if isinstance(parsed, dict) else None
+ except (TypeError, ValueError):
+ return None
+
+
+async def run_update_evolution(
+ session: Any,
+ repository_id: str,
+ *,
+ changed_files: set[str],
+ evidence_by_file: dict[str, str],
+ provider: Any | None = None,
+) -> dict[str, Any]:
+ """Two-pass evolution for ``repowise update``, run *before* page regen.
+
+ Returns ``{"regen_files": set[str], "superseded": n, "amended": n,
+ "reaffirmed": n}``. ``regen_files`` are the governed files of every decision
+ the change superseded or amended — the caller folds them into the
+ regeneration set so they re-render in the same run.
+
+ Pass 1 always runs (cheap). Pass 2 needs a *provider*; without one the
+ survivors' governed pages are still scheduled for regen (the signal alone is
+ enough to warrant a refresh) but no status change is made.
+ """
+ from datetime import UTC, datetime
+
+ from repowise.core.persistence.crud import list_decisions
+
+ result: dict[str, Any] = {
+ "regen_files": set(),
+ "superseded": 0,
+ "amended": 0,
+ "reaffirmed": 0,
+ }
+ if not changed_files:
+ return result
+
+ existing = await list_decisions(session, repository_id, include_proposed=True, limit=500)
+ candidates = pass1_evolution_candidates(changed_files, evidence_by_file, existing)
+ if not candidates:
+ return result
+
+ regen: set[str] = result["regen_files"]
+ now = datetime.now(UTC)
+
+ for dec, evidence_text, _signals in candidates:
+ try:
+ governed = list(json.loads(dec.affected_files_json or "[]"))
+ except (TypeError, ValueError):
+ governed = []
+
+ if provider is None:
+ # No LLM available: a signal touched a governed file — re-render the
+ # governed pages so docs stay fresh, but don't change status.
+ regen.update(governed)
+ continue
+
+ verdict = await _judge_evolution(
+ provider,
+ title=dec.title,
+ decision=dec.decision,
+ rationale=dec.rationale,
+ evidence_text=evidence_text,
+ )
+ if verdict is None:
+ continue
+
+ kind = verdict["verdict"]
+ if kind == "superseded":
+ if dec.status in ("active", "proposed"):
+ dec.status = "superseded"
+ dec.updated_at = now
+ regen.update(governed)
+ result["superseded"] += 1
+ elif kind == "amended":
+ # Keep it active but mark it stale so its drift is visible, and
+ # re-render its governed pages to reflect the amendment.
+ dec.staleness_score = max(dec.staleness_score, 0.6)
+ dec.updated_at = now
+ regen.update(governed)
+ result["amended"] += 1
+ elif kind == "reaffirmed":
+ # Still holds — relax staleness; no regen needed.
+ dec.staleness_score = min(dec.staleness_score, 0.2)
+ dec.updated_at = now
+ result["reaffirmed"] += 1
+
+ await session.flush()
+ return result
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.py
new file mode 100644
index 000000000..9278f2f70
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py
@@ -0,0 +1,1557 @@
+"""Architectural Decision Intelligence - extraction from multiple sources.
+
+Capture sources (see ``decision_provenance.SOURCE_RANK`` for the trust ladder):
+ 1. Inline markers (# WHY:, # DECISION:, etc.)
+ 2. Git archaeology (significant commit messages)
+ 3. README / docs mining (implicit decisions in prose)
+ 4. ADR auto-discovery (Nygard/MADR records — deterministic parse first)
+ 5. CHANGELOG mining (keep-a-changelog Changed/Removed/Deprecated)
+ 6. PR / squash-body mining (commit bodies captured in git indexing)
+ 7. Comment archaeology (rationale prose on high-centrality code)
+ + CLI capture (manual entry)
+
+Determinism-first: ADR/CHANGELOG are parsed structurally before any LLM call.
+Every extracted decision passes an anti-hallucination substring gate
+(:meth:`DecisionExtractor._apply_substring_gate`) — fields not grounded in the
+verbatim source span are dropped, and evidence-less decisions are rejected.
+
+All LLM calls are wrapped in try/except - failures never propagate.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+from repowise.core.analysis.decisions.gate import apply_substring_gate
+
+from .prompts import (
+ _SYSTEM_PROMPT,
+ CHANGELOG_MINING_PROMPT,
+ COMMENT_ARCHAEOLOGY_PROMPT,
+ GIT_ARCHAEOLOGY_PROMPT,
+ INLINE_MARKER_PROMPT,
+ PR_BODY_MINING_PROMPT,
+ README_MINING_PROMPT,
+)
+
+logger = structlog.get_logger(__name__)
+
+# ---------------------------------------------------------------------------
+# Data models
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class ExtractedDecision:
+ title: str
+ context: str = ""
+ decision: str = ""
+ rationale: str = ""
+ alternatives: list[str] = field(default_factory=list)
+ consequences: list[str] = field(default_factory=list)
+ affected_files: list[str] = field(default_factory=list)
+ affected_modules: list[str] = field(default_factory=list)
+ tags: list[str] = field(default_factory=list)
+ source: str = "inline_marker"
+ evidence_commits: list[str] = field(default_factory=list)
+ evidence_file: str | None = None
+ evidence_line: int | None = None
+ confidence: float = 0.5
+ status: str = "proposed"
+ # The verbatim claimed quote (LLM/parser output) and the verdict from the
+ # anti-hallucination substring gate (Phase 1D).
+ source_quote: str = ""
+ verification: str = "unverified" # exact | fuzzy | unverified
+ # Transient: the verbatim source span this decision was drawn from. Set by
+ # each extractor, consumed by the substring gate, then cleared before
+ # persistence (the persistence layer ignores unknown dict keys anyway).
+ source_text: str = ""
+
+
+@dataclass
+class DecisionExtractionReport:
+ total_found: int
+ decisions: list[ExtractedDecision]
+ by_source: dict[str, int]
+
+
+# ---------------------------------------------------------------------------
+# Comment marker detection
+# ---------------------------------------------------------------------------
+
+MARKER_RE = re.compile(
+ r"^\s*(?:#|//|--|/\*|\*)\s*"
+ r"(?P<keyword>WHY|DECISION|TRADEOFF|ADR|RATIONALE|REJECTED)"
+ r"\s*:\s*(?P<text>.+)",
+ re.IGNORECASE,
+)
+
+_SKIP_DIRS = frozenset(
+ {
+ ".git",
+ "node_modules",
+ "__pycache__",
+ ".repowise",
+ ".venv",
+ "venv",
+ ".tox",
+ ".mypy_cache",
+ ".pytest_cache",
+ "dist",
+ "build",
+ ".next",
+ ".nuxt",
+ }
+)
+
+# 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",
+ }
+)
+
+# ---------------------------------------------------------------------------
+# Decision signal keywords for git archaeology
+# ---------------------------------------------------------------------------
+
+DECISION_SIGNAL_KEYWORDS = [
+ "migrate",
+ "migration",
+ "switch to",
+ "replace",
+ "replaced",
+ "refactor to",
+ "move from",
+ "adopt",
+ "introduce",
+ "deprecate",
+ "remove",
+ "drop",
+ "upgrade",
+ "rewrite",
+ "extract",
+ "split",
+ "convert",
+ "transition",
+ "revert",
+]
+
+# ---------------------------------------------------------------------------
+# ADR / CHANGELOG / PR / comment source configuration (Phase 1B)
+# ---------------------------------------------------------------------------
+
+# Directories conventionally holding Architecture Decision Records, plus a
+# filename glob for ADRs that live loose. Globbed relative to the repo root.
+_ADR_DIR_GLOBS = (
+ "adr/*.md",
+ "adrs/*.md",
+ "docs/adr/*.md",
+ "docs/adrs/*.md",
+ "docs/decisions/*.md",
+ "decisions/*.md",
+ "architecture/*.md",
+ "doc/adr/*.md",
+)
+_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",
+}
+
+# CHANGELOG / HISTORY / NEWS filenames (case-insensitive match on the stem).
+_CHANGELOG_NAMES = frozenset(
+ {"changelog", "history", "news", "changes", "releasenotes", "release-notes"}
+)
+# keep-a-changelog section headers that carry decision signal. "Added" is
+# excluded — additions are rarely *decisions* about structure, just features.
+_CHANGELOG_DECISION_SECTIONS = frozenset({"changed", "removed", "deprecated", "security"})
+_MAX_CHANGELOG_VERSIONS = 15
+
+# 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 = (
+ "## why",
+ "## motivation",
+ "## what",
+ "## changes",
+ "## context",
+ "## summary",
+ "closes #",
+ "fixes #",
+ "resolves #",
+ "before:",
+ "after:",
+)
+_MAX_PR_BODIES = 25
+
+# Prose that signals rationale in a block comment / docstring (beyond the
+# explicit WHY:/DECISION: markers already covered by inline_marker).
+_COMMENT_RATIONALE_CUES = (
+ "because",
+ "instead of",
+ "rather than",
+ "trade-off",
+ "tradeoff",
+ "we chose",
+ "we decided",
+ "the reason",
+ "in order to",
+ "this avoids",
+ "to avoid",
+ "deliberately",
+ "intentionally",
+)
+_MAX_COMMENT_NODES = 30
+
+# ---------------------------------------------------------------------------
+# ---------------------------------------------------------------------------
+# Main extractor
+# ---------------------------------------------------------------------------
+
+
+class DecisionExtractor:
+ """Extracts architectural decisions from multiple sources."""
+
+ def __init__(
+ self,
+ repo_path: Path,
+ provider: Any | None = None,
+ graph: Any | None = None,
+ git_meta_map: dict[str, dict] | None = None,
+ parsed_files: list[Any] | None = None,
+ ) -> None:
+ self._repo_path = Path(repo_path)
+ self._provider = provider
+ self._graph = graph
+ self._git_meta_map = git_meta_map or {}
+ self._parsed_files = parsed_files or []
+
+ # ------------------------------------------------------------------
+ # Source 1: Inline markers
+ # ------------------------------------------------------------------
+
+ async def scan_inline_markers(
+ self,
+ restrict_to_files: list[str] | None = None,
+ ) -> list[ExtractedDecision]:
+ """Scan source files for decision markers (WHY:, DECISION:, etc.)."""
+ markers_by_file: dict[str, list[dict]] = {}
+
+ if restrict_to_files:
+ files_to_scan = [self._repo_path / fp for fp in restrict_to_files]
+ else:
+ files_to_scan = list(self._iter_source_files())
+
+ 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:
+ text = file_path.read_text(encoding="utf-8", errors="replace")
+ except (OSError, UnicodeDecodeError):
+ continue
+
+ 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 = file_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])
+
+ try:
+ rel_path = str(file_path.relative_to(self._repo_path))
+ except ValueError:
+ rel_path = str(file_path)
+
+ markers_by_file.setdefault(rel_path, []).append(
+ {
+ "keyword": m.group("keyword"),
+ "text": marker_text,
+ "line": line_num,
+ "context": context,
+ }
+ )
+
+ if not markers_by_file:
+ return []
+
+ decisions: list[ExtractedDecision] = []
+
+ for file_path, markers in markers_by_file.items():
+ # Get 1-hop graph neighbors for affected_files
+ affected = self._get_neighbors(file_path)
+
+ # The concatenated marker contexts are the verbatim source span the
+ # substring gate verifies the structured decision against.
+ marker_source_text = "\n".join(m.get("context", "") for m in markers)
+
+ if self._provider:
+ # Use LLM to structure markers
+ try:
+ llm_decisions = await self._structure_markers_via_llm(file_path, markers)
+ for d in llm_decisions:
+ d.evidence_file = file_path
+ d.evidence_line = markers[0]["line"] if markers else None
+ d.affected_files = list({file_path} | set(affected))
+ d.affected_modules = self._infer_modules(d.affected_files)
+ d.source = "inline_marker"
+ d.status = "active"
+ d.confidence = 0.95
+ d.source_text = marker_source_text
+ decisions.extend(llm_decisions)
+ except Exception:
+ logger.warning(
+ "decision_extractor.llm_structuring_failed",
+ file=file_path,
+ )
+ # Fall through to raw extraction below
+ for marker in markers:
+ decisions.append(
+ self._raw_decision_from_marker(file_path, marker, affected)
+ )
+ else:
+ # No LLM — create minimal decisions from raw marker text
+ for marker in markers:
+ decisions.append(self._raw_decision_from_marker(file_path, marker, affected))
+
+ return decisions
+
+ def _raw_decision_from_marker(
+ self,
+ file_path: str,
+ marker: dict,
+ affected: list[str],
+ ) -> ExtractedDecision:
+ """Create a minimal decision from a raw marker without LLM."""
+ return ExtractedDecision(
+ title=marker["text"][:100],
+ decision=marker["text"],
+ context=f"Found in {file_path}:{marker['line']}",
+ source="inline_marker",
+ status="active",
+ confidence=0.7,
+ evidence_file=file_path,
+ evidence_line=marker["line"],
+ affected_files=list({file_path} | set(affected)),
+ affected_modules=self._infer_modules([file_path, *affected]),
+ tags=self._infer_tags(marker["text"]),
+ source_quote=marker["text"],
+ source_text=marker.get("context", marker["text"]),
+ )
+
+ async def _structure_markers_via_llm(
+ self, file_path: str, markers: list[dict]
+ ) -> list[ExtractedDecision]:
+ """Use LLM to structure inline markers into decision records."""
+ markers_block = ""
+ for m in markers[:5]: # Batch up to 5 per call
+ markers_block += (
+ f"\n--- Marker ({m['keyword']}) at line {m['line']} ---\n"
+ f"Text: {m['text']}\n"
+ f"Surrounding code:\n{m['context'][:1500]}\n"
+ )
+
+ prompt = INLINE_MARKER_PROMPT.format(
+ file_path=file_path,
+ markers_block=markers_block,
+ )
+
+ response = await self._provider.generate(
+ _SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
+ )
+ return self._parse_decisions_json(response.content)
+
+ # ------------------------------------------------------------------
+ # Source 2: Git archaeology
+ # ------------------------------------------------------------------
+
+ async def mine_git_archaeology(self) -> list[ExtractedDecision]:
+ """Extract decisions from significant git commits."""
+ if not self._provider or not self._git_meta_map:
+ return []
+
+ # Collect unique significant commits with decision signals
+ commit_map: dict[str, dict] = {} # sha → commit info
+ commit_files: dict[str, list[str]] = {} # sha → files
+
+ for file_path, meta in self._git_meta_map.items():
+ commits_json = meta.get("significant_commits_json", "[]")
+ if isinstance(commits_json, str):
+ try:
+ commits = json.loads(commits_json)
+ except (json.JSONDecodeError, TypeError):
+ continue
+ else:
+ commits = commits_json
+
+ for commit in commits:
+ sha = commit.get("sha", "")
+ if not sha or sha in commit_map:
+ commit_files.setdefault(sha, []).append(file_path)
+ continue
+ msg = commit.get("message", "")
+ 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 = sum(1 for kw in DECISION_SIGNAL_KEYWORDS if kw in 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)
+
+ if not commit_map:
+ return []
+
+ # Rank by signal count, take top 20
+ ranked = sorted(
+ commit_map.values(),
+ key=lambda c: c["signal_count"],
+ reverse=True,
+ )[:20]
+
+ # Batch LLM calls (5 commits per batch)
+ decisions: list[ExtractedDecision] = []
+ batches = [ranked[i : i + 5] for i in range(0, len(ranked), 5)]
+
+ async def _process_batch(batch: list[dict]) -> list[ExtractedDecision]:
+ commits_block = ""
+ source_by_sha: dict[str, str] = {}
+ for c in batch:
+ files = commit_files.get(c["sha"], [])
+ body = (c.get("body") or "").strip()
+ body_block = f"Body: {body[:1500]}\n" if body else ""
+ commits_block += (
+ f"\n--- Commit {c['sha'][:8]} ---\n"
+ f"Message: {c['message']}\n"
+ f"{body_block}"
+ f"Author: {c['author']}\n"
+ f"Date: {c['date']}\n"
+ f"Files changed: {', '.join(files[:20])}\n"
+ )
+ source_by_sha[c["sha"]] = f"{c['message']}\n{body}".strip()
+
+ prompt = GIT_ARCHAEOLOGY_PROMPT.format(commits_block=commits_block)
+ response = await self._provider.generate(
+ _SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
+ )
+ extracted = self._parse_decisions_json(response.content)
+
+ # Enrich with commit metadata
+ for d in extracted:
+ sha = d.evidence_commits[0] if d.evidence_commits else ""
+ if not sha:
+ # Try to match back to a commit
+ for c in batch:
+ if c["message"][:40].lower() in d.title.lower():
+ sha = c["sha"]
+ break
+ if sha:
+ d.evidence_commits = [sha]
+ d.affected_files = commit_files.get(sha, [])
+ d.source_text = source_by_sha.get(sha, "")
+ d.source = "git_archaeology"
+ d.status = "proposed"
+ signal = max(
+ (c["signal_count"] for c in batch if c["sha"] == sha),
+ default=1,
+ )
+ d.confidence = 0.85 if signal >= 2 else 0.70
+ d.affected_modules = self._infer_modules(d.affected_files)
+
+ return extracted
+
+ results = await asyncio.gather(
+ *[_process_batch(b) for b in batches],
+ return_exceptions=True,
+ )
+ for result in results:
+ if isinstance(result, list):
+ decisions.extend(result)
+ else:
+ logger.warning(
+ "decision_extractor.git_batch_failed",
+ error=str(result),
+ )
+
+ return decisions
+
+ # ------------------------------------------------------------------
+ # Source 3: README / docs mining
+ # ------------------------------------------------------------------
+
+ async def mine_readme_docs(self) -> list[ExtractedDecision]:
+ """Extract decisions from documentation files."""
+ if not self._provider:
+ return []
+
+ doc_patterns = [
+ "README.md",
+ "CLAUDE.md",
+ "ARCHITECTURE.md",
+ "CONTRIBUTING.md",
+ "DESIGN.md",
+ "DECISIONS.md",
+ ]
+ doc_files: list[Path] = []
+
+ for pattern in doc_patterns:
+ p = self._repo_path / pattern
+ if p.is_file():
+ doc_files.append(p)
+
+ # Also check docs/ directory
+ docs_dir = self._repo_path / "docs"
+ if docs_dir.is_dir():
+ for md_file in docs_dir.rglob("*.md"):
+ if len(doc_files) >= 10:
+ break
+ doc_files.append(md_file)
+
+ decisions: list[ExtractedDecision] = []
+
+ for doc_path in doc_files[:10]:
+ try:
+ content = doc_path.read_text(encoding="utf-8", errors="replace")
+ except (OSError, UnicodeDecodeError):
+ continue
+
+ # Skip very large files
+ if len(content) > 50_000:
+ continue
+
+ # Strip fenced code blocks to avoid treating example markers
+ # (e.g. `# WHY: ...` in code examples) as real decisions.
+ content = self._strip_code_blocks(content)
+
+ try:
+ rel_path = str(doc_path.relative_to(self._repo_path))
+ except ValueError:
+ rel_path = str(doc_path)
+
+ try:
+ prompt = README_MINING_PROMPT.format(
+ file_path=rel_path,
+ content=content[:15_000], # Limit token usage
+ )
+ response = await self._provider.generate(
+ _SYSTEM_PROMPT, prompt, max_tokens=3000, temperature=0.2
+ )
+ extracted = self._parse_decisions_json(response.content)
+ for d in extracted:
+ d.source = "readme_mining"
+ d.status = "proposed"
+ d.confidence = 0.60
+ d.evidence_file = rel_path
+ d.affected_modules = self._infer_modules_from_text(d.title + " " + d.decision)
+ d.source_text = content
+ decisions.extend(extracted)
+ except Exception:
+ logger.warning(
+ "decision_extractor.readme_mining_failed",
+ file=rel_path,
+ )
+
+ return decisions
+
+ # ------------------------------------------------------------------
+ # Source 4: ADR auto-discovery (deterministic-first)
+ # ------------------------------------------------------------------
+
+ async def discover_adrs(self) -> list[ExtractedDecision]:
+ """Discover and parse Architecture Decision Records.
+
+ Deterministic-first: ADRs follow the Nygard/MADR templates (optional
+ YAML front-matter + Status / Context / Decision / Consequences
+ headings), so structured files are parsed without the LLM. Files that
+ 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()
+ if not adr_paths:
+ return []
+
+ decisions: list[ExtractedDecision] = []
+ for path in adr_paths:
+ try:
+ content = path.read_text(encoding="utf-8", errors="replace")
+ except (OSError, UnicodeDecodeError):
+ continue
+ if len(content) > 50_000:
+ content = content[:50_000]
+ try:
+ rel = str(path.relative_to(self._repo_path))
+ except ValueError:
+ rel = str(path)
+
+ parsed = self._parse_adr(content, rel)
+ if parsed is not None:
+ decisions.append(parsed)
+ elif self._provider:
+ try:
+ stripped = self._strip_code_blocks(content)
+ prompt = README_MINING_PROMPT.format(file_path=rel, content=stripped[:15_000])
+ response = await self._provider.generate(
+ _SYSTEM_PROMPT, prompt, max_tokens=2000, temperature=0.2
+ )
+ for d in self._parse_decisions_json(response.content):
+ d.source = "adr"
+ d.status = "proposed"
+ d.confidence = 0.80
+ d.evidence_file = rel
+ d.source_text = stripped
+ d.affected_modules = self._infer_modules_from_text(
+ d.title + " " + d.decision
+ )
+ decisions.append(d)
+ except Exception:
+ logger.warning("decision_extractor.adr_llm_failed", file=rel)
+
+ return decisions
+
+ def _find_adr_files(self) -> list[Path]:
+ """Collect candidate ADR files from the conventional dirs + name match.
+
+ Performance: the conventional-dir globs are shallow (one directory
+ each). The loose ``*adr*.md`` scan uses a pruned ``os.walk`` rather than
+ a recursive ``**`` glob so it never descends into ``node_modules`` /
+ ``.git`` / ``.venv`` on a large repo, and bails as soon as the cap is
+ hit.
+ """
+ import os
+
+ seen: set[Path] = set()
+ files: list[Path] = []
+ for pattern in _ADR_DIR_GLOBS:
+ for p in self._repo_path.glob(pattern):
+ if p.is_file() and p not in seen:
+ seen.add(p)
+ files.append(p)
+
+ if len(files) < _MAX_ADR_FILES:
+ for dirpath, dirnames, filenames in os.walk(self._repo_path):
+ # Prune skip-listed + nested-git subtrees in place.
+ dirnames[:] = [
+ d
+ for d in dirnames
+ if d not in _SKIP_DIRS
+ and not d.endswith((".egg-info", ".dist-info"))
+ and not (Path(dirpath) / d / ".git").exists()
+ ]
+ for fname in filenames:
+ low = fname.lower()
+ if not low.endswith(".md") or "adr" not in low:
+ continue
+ if low == "readme.md" or "template" in low:
+ continue
+ p = Path(dirpath) / fname
+ if p in seen:
+ continue
+ seen.add(p)
+ files.append(p)
+ if len(files) >= _MAX_ADR_FILES:
+ break
+ if len(files) >= _MAX_ADR_FILES:
+ break
+
+ return files[:_MAX_ADR_FILES]
+
+ def _parse_adr(self, content: str, rel_path: str) -> ExtractedDecision | None:
+ """Deterministically parse a structured ADR. Returns None if unstructured.
+
+ Because every field is lifted verbatim from the document, the resulting
+ 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)
+ if not title:
+ m = re.search(r"^#\s+(.+)$", body, re.MULTILINE)
+ if m:
+ title = m.group(1).strip()
+ # Strip an "ADR-0007:" style prefix from the title.
+ title = re.sub(r"^ADR[-\s]*\d+[:\s-]*", "", title, flags=re.IGNORECASE).strip() or title
+
+ context = sections.get("context") or sections.get("context and problem statement", "")
+ decision_txt = sections.get("decision") or sections.get("decision outcome", "")
+ rationale = sections.get("rationale") or sections.get("decision drivers", "")
+ consequences = sections.get("consequences", "")
+ if not status:
+ status = sections.get("status", "")
+
+ # Require recognizable ADR structure — at minimum a Decision or Context
+ # section — otherwise let the LLM fallback handle it.
+ if not (decision_txt or context):
+ return None
+
+ status_key = status.strip().lower().split()[0] if status.strip() else ""
+ mapped_status = _ADR_STATUS_MAP.get(status_key, "active")
+
+ return ExtractedDecision(
+ title=(title or rel_path)[:200],
+ context=context.strip(),
+ decision=decision_txt.strip(),
+ rationale=rationale.strip(),
+ consequences=self._bullets(consequences),
+ source="adr",
+ status=mapped_status,
+ confidence=0.90,
+ evidence_file=rel_path,
+ source_quote=(decision_txt or context).strip()[:500],
+ source_text=content,
+ tags=self._infer_tags(f"{title} {decision_txt}"),
+ affected_modules=self._infer_modules_from_text(f"{title} {decision_txt}"),
+ )
+
+ # ------------------------------------------------------------------
+ # Source 5: CHANGELOG mining
+ # ------------------------------------------------------------------
+
+ async def mine_changelog(self) -> list[ExtractedDecision]:
+ """Mine keep-a-changelog Changed/Removed/Deprecated sections."""
+ path = self._find_changelog()
+ if path is None:
+ return []
+ try:
+ content = path.read_text(encoding="utf-8", errors="replace")
+ except (OSError, UnicodeDecodeError):
+ return []
+ try:
+ rel = str(path.relative_to(self._repo_path))
+ except ValueError:
+ rel = str(path)
+
+ entries = self._parse_changelog(content)
+ if not entries:
+ return []
+
+ if self._provider:
+ return await self._structure_changelog_entries(entries, rel, content)
+
+ # No LLM — emit raw decisions straight from the decision-y bullets.
+ decisions: list[ExtractedDecision] = []
+ for section, bullet in entries[:50]:
+ decisions.append(
+ ExtractedDecision(
+ title=bullet[:100],
+ decision=bullet,
+ context=f"CHANGELOG · {section.title()}",
+ source="changelog",
+ status="proposed",
+ confidence=0.50,
+ evidence_file=rel,
+ source_quote=bullet,
+ source_text=content,
+ tags=self._infer_tags(bullet),
+ )
+ )
+ return decisions
+
+ def _find_changelog(self) -> Path | None:
+ """Locate a CHANGELOG/HISTORY/NEWS file (any extension).
+
+ Checks the repo root first, then the conventional documentation
+ subdirectories (``docs/``, ``doc/``, ``.github/``). Many projects keep
+ their changelog under ``docs/`` rather than at the root, so a root-only
+ scan silently skips this source.
+ """
+ search_dirs = [
+ self._repo_path,
+ self._repo_path / "docs",
+ self._repo_path / "doc",
+ self._repo_path / ".github",
+ ]
+ for directory in search_dirs:
+ if not directory.is_dir():
+ continue
+ for p in sorted(directory.glob("*")):
+ if not p.is_file():
+ continue
+ stem = re.sub(r"[^a-z]", "", p.stem.lower())
+ if stem in _CHANGELOG_NAMES:
+ return p
+ return None
+
+ def _parse_changelog(self, content: str) -> list[tuple[str, str]]:
+ """Return ``(section, bullet)`` pairs from decision-relevant sections."""
+ entries: list[tuple[str, str]] = []
+ version_count = 0
+ current_section: str | None = None
+ in_version = True
+ for line in content.splitlines():
+ h2 = re.match(r"^##\s+(.+)$", line)
+ if h2:
+ name = h2.group(1).strip().lower().strip("[]")
+ base = name.split()[0] if name else ""
+ if base in _CHANGELOG_DECISION_SECTIONS:
+ # Some changelogs use H2 section headers directly.
+ current_section = base
+ else:
+ version_count += 1
+ in_version = version_count <= _MAX_CHANGELOG_VERSIONS
+ current_section = None
+ continue
+ h3 = re.match(r"^###\s+(.+)$", line)
+ if h3:
+ current_section = h3.group(1).strip().lower()
+ continue
+ if not in_version or current_section not in _CHANGELOG_DECISION_SECTIONS:
+ continue
+ s = line.strip()
+ if s.startswith(("-", "*", "+")):
+ bullet = s[1:].strip()
+ if bullet:
+ entries.append((current_section, bullet))
+ return entries
+
+ async def _structure_changelog_entries(
+ self, entries: list[tuple[str, str]], rel: str, content: str
+ ) -> list[ExtractedDecision]:
+ """LLM-structure the highest-signal changelog bullets into decisions."""
+ signal = [
+ (s, b)
+ for (s, b) in entries
+ if s in ("removed", "deprecated")
+ or any(k in b.lower() for k in DECISION_SIGNAL_KEYWORDS)
+ ]
+ chosen = (signal or entries)[:40]
+ block = "\n".join(f"- [{s.title()}] {b}" for s, b in chosen)
+ prompt = CHANGELOG_MINING_PROMPT.format(entries_block=block)
+ try:
+ response = await self._provider.generate(
+ _SYSTEM_PROMPT, prompt, max_tokens=2500, temperature=0.2
+ )
+ except Exception:
+ logger.warning("decision_extractor.changelog_mining_failed", file=rel)
+ return []
+ extracted = self._parse_decisions_json(response.content)
+ for d in extracted:
+ d.source = "changelog"
+ d.status = "proposed"
+ d.confidence = 0.60
+ d.evidence_file = rel
+ d.source_text = content
+ d.affected_modules = self._infer_modules_from_text(d.title + " " + d.decision)
+ return extracted
+
+ # ------------------------------------------------------------------
+ # Source 6: PR / squash-body mining (consumes commit bodies from 1A)
+ # ------------------------------------------------------------------
+
+ async def mine_pr_bodies(self) -> list[ExtractedDecision]:
+ """Extract decisions from PR / squash-merge commit bodies."""
+ if not self._provider or not self._git_meta_map:
+ return []
+
+ candidates: dict[str, dict] = {}
+ files_by_sha: dict[str, list[str]] = {}
+ for fp, meta in self._git_meta_map.items():
+ for c in self._loads_commits(meta.get("significant_commits_json")):
+ sha = c.get("sha", "")
+ if not sha:
+ continue
+ files_by_sha.setdefault(sha, []).append(fp)
+ body = (c.get("body") or "").strip()
+ if sha in candidates or not body:
+ continue
+ low = body.lower()
+ is_prish = c.get("pr_number") is not None or any(m in low for m in _PR_BODY_MARKERS)
+ has_signal = any(k in low for k in DECISION_SIGNAL_KEYWORDS)
+ if is_prish and has_signal:
+ candidates[sha] = {
+ "sha": sha,
+ "subject": c.get("message", ""),
+ "body": body,
+ "pr": c.get("pr_number"),
+ }
+
+ if not candidates:
+ 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 = ""
+ source_by_sha: dict[str, str] = {}
+ for c in batch:
+ pr_label = f" (PR #{c['pr']})" if c.get("pr") else ""
+ bodies_block += (
+ f"\n--- Commit {c['sha'][:8]}{pr_label} ---\n"
+ f"Subject: {c['subject']}\n"
+ f"Body:\n{c['body'][:2000]}\n"
+ )
+ source_by_sha[c["sha"]] = f"{c['subject']}\n{c['body']}"
+ prompt = PR_BODY_MINING_PROMPT.format(bodies_block=bodies_block)
+ try:
+ response = await self._provider.generate(
+ _SYSTEM_PROMPT, prompt, max_tokens=2500, temperature=0.2
+ )
+ except Exception:
+ return []
+ 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 = files_by_sha.get(sha, [])
+ d.source_text = source_by_sha.get(sha, "")
+ d.source = "pr"
+ d.status = "proposed"
+ d.confidence = 0.80
+ d.affected_modules = self._infer_modules(d.affected_files)
+ return extracted
+
+ decisions: list[ExtractedDecision] = []
+ results = await asyncio.gather(
+ *[_process_batch(b) for b in batches], return_exceptions=True
+ )
+ for result in results:
+ if isinstance(result, list):
+ decisions.extend(result)
+ else:
+ logger.warning("decision_extractor.pr_batch_failed", error=str(result))
+ return decisions
+
+ # ------------------------------------------------------------------
+ # Source 7: Comment archaeology (centrality-bounded)
+ # ------------------------------------------------------------------
+
+ async def mine_comment_archaeology(self) -> list[ExtractedDecision]:
+ """Mine rationale prose from comments on the most central code.
+
+ Bounded to the top-N nodes by PageRank (degree fallback) so it never
+ scans the whole tree, and looks for *reasoning* prose (``because``,
+ ``instead of`` …) rather than the explicit markers already covered by
+ ``scan_inline_markers``.
+ """
+ if not self._provider or self._graph is None:
+ return []
+
+ top_files = self._top_central_files(_MAX_COMMENT_NODES)
+ if not top_files:
+ return []
+
+ snippets: list[tuple[str, str]] = []
+ for fp in top_files:
+ prose = self._extract_leading_prose(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:
+ comments_block += f"\n--- {fp} ---\n{prose[:1500]}\n"
+ prompt = COMMENT_ARCHAEOLOGY_PROMPT.format(comments_block=comments_block)
+ try:
+ response = await self._provider.generate(
+ _SYSTEM_PROMPT, prompt, max_tokens=2500, temperature=0.2
+ )
+ except Exception:
+ return []
+ extracted = self._parse_decisions_json(response.content)
+ # Best-effort attribution to the originating file by token overlap.
+ for d in extracted:
+ best_fp, best_prose = batch[0]
+ hay = (d.title + " " + d.decision).lower()
+ for fp, prose in batch:
+ stem = Path(fp).stem.lower()
+ if stem and stem in hay:
+ best_fp, best_prose = fp, prose
+ break
+ d.source = "comment"
+ d.status = "proposed"
+ d.confidence = 0.55
+ d.evidence_file = best_fp
+ d.source_text = best_prose
+ d.affected_files = [best_fp]
+ d.affected_modules = self._infer_modules([best_fp])
+ return extracted
+
+ results = await asyncio.gather(
+ *[_process_batch(b) for b in batches], return_exceptions=True
+ )
+ for result in results:
+ if isinstance(result, list):
+ decisions.extend(result)
+ return decisions
+
+ # Above this node count, skip the iterative PageRank solve and use degree
+ # centrality (O(nodes)) instead — comment archaeology only needs a rough
+ # "most depended-on files" ranking, not exact PageRank, and the iterative
+ # solve would otherwise add seconds on very large graphs.
+ _PAGERANK_NODE_CEILING = 20_000
+
+ def _top_central_files(self, n: int) -> list[str]:
+ """Top-*n* file nodes by centrality (existing on disk).
+
+ Uses PageRank on modest graphs and falls back to cheap degree
+ centrality on very large graphs (or if networkx is unavailable) so this
+ never becomes an ingestion bottleneck.
+ """
+ g = self._graph
+ if g is None:
+ return []
+ scores: dict[str, float] = {}
+ try:
+ node_count = g.number_of_nodes()
+ except Exception:
+ node_count = 0
+ if 0 < node_count <= self._PAGERANK_NODE_CEILING:
+ try:
+ import networkx as nx
+
+ scores = nx.pagerank(g, max_iter=50, tol=1e-4)
+ except Exception:
+ scores = {}
+ if not scores:
+ try:
+ scores = {node: float(g.degree(node)) for node in g.nodes}
+ except Exception:
+ return []
+ ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
+ out: list[str] = []
+ for node, _score in ranked:
+ if len(out) >= n:
+ break
+ p = self._repo_path / node
+ if p.is_file() and p.suffix.lower() not in _BINARY_EXTENSIONS:
+ 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."""
+ if isinstance(value, list):
+ return value
+ if isinstance(value, str):
+ try:
+ data = json.loads(value)
+ except (json.JSONDecodeError, TypeError):
+ return []
+ 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)
+ # ------------------------------------------------------------------
+
+ def _apply_substring_gate(
+ self, decisions: list[ExtractedDecision]
+ ) -> tuple[list[ExtractedDecision], int]:
+ """Run the shared anti-hallucination gate over extracted decisions.
+
+ Thin wrapper around :func:`decision_gate.apply_substring_gate` — the
+ gate orchestration is factored out so the Phase-2 LLM-docs harvest path
+ enforces the *same* grounding rules. See that module for the contract.
+ """
+ return apply_substring_gate(decisions)
+
+ # ------------------------------------------------------------------
+ # Staleness computation (static method)
+ # ------------------------------------------------------------------
+
+ # Keywords that signal a decision may have been contradicted or superseded.
+ _CONFLICT_SIGNALS = frozenset(
+ {
+ "replace",
+ "remove",
+ "deprecate",
+ "switch from",
+ "migrate away",
+ "drop",
+ "revert",
+ "undo",
+ "disable",
+ "eliminate",
+ }
+ )
+
+ @staticmethod
+ def compute_staleness(
+ decision_created_at: datetime,
+ affected_files: list[str],
+ git_meta_map: dict[str, dict],
+ decision_text: str = "",
+ ) -> float:
+ """Compute staleness score for a decision. Returns 0.0-1.0.
+
+ In addition to commit volume and age, checks whether recent commit
+ messages contain keywords that conflict with the decision text
+ (e.g. decision says "use Redis" but a recent commit says "migrate
+ away from Redis"). This boosts staleness when the underlying code
+ may have diverged from the decision's intent.
+ """
+ if not affected_files:
+ return 0.0
+
+ now = datetime.now(UTC)
+ scores: list[float] = []
+ decision_lower = decision_text.lower()
+
+ for fp in affected_files:
+ meta = git_meta_map.get(fp)
+ if meta is None:
+ scores.append(1.0) # File missing / not tracked
+ continue
+
+ last_commit = meta.get("last_commit_at")
+ if last_commit and decision_created_at:
+ if isinstance(last_commit, str):
+ last_commit = datetime.fromisoformat(last_commit.replace("Z", "+00:00"))
+ _created = decision_created_at
+ if isinstance(_created, str):
+ _created = datetime.fromisoformat(_created.replace("Z", "+00:00"))
+ if last_commit > _created:
+ age_days = (now - _created).days
+ commit_count = meta.get("commit_count_90d", 0)
+ base_score = min(
+ 1.0,
+ commit_count / 15 * 0.7 + age_days / 365 * 0.3,
+ )
+
+ # Keyword conflict boost: check if recent commits
+ # contradict the decision's content.
+ conflict_boost = 0.0
+ if decision_lower:
+ sig_json = meta.get("significant_commits_json", "[]")
+ try:
+ sig_commits = (
+ json.loads(sig_json) if isinstance(sig_json, str) else sig_json
+ )
+ except (json.JSONDecodeError, TypeError):
+ sig_commits = []
+ for sc in sig_commits:
+ sc_date = sc.get("date", "")
+ # Only consider commits after the decision was created
+ if sc_date and sc_date > _created.isoformat():
+ msg_lower = sc.get("message", "").lower()
+ for signal in DecisionExtractor._CONFLICT_SIGNALS:
+ if signal in msg_lower:
+ # Check if the commit message shares meaningful
+ # words with the decision text (context overlap)
+ msg_words = set(msg_lower.split())
+ dec_words = set(decision_lower.split())
+ overlap = msg_words & dec_words - {
+ "the",
+ "a",
+ "an",
+ "to",
+ "in",
+ "for",
+ "and",
+ "or",
+ "of",
+ "is",
+ "was",
+ "with",
+ }
+ if len(overlap) >= 2:
+ conflict_boost = max(conflict_boost, 0.3)
+ break
+
+ score = min(1.0, base_score + conflict_boost)
+ scores.append(score)
+ else:
+ scores.append(0.0)
+ else:
+ scores.append(0.0)
+
+ return round(sum(scores) / len(scores), 3) if scores else 0.0
+
+ # ------------------------------------------------------------------
+ # Main entry point
+ # ------------------------------------------------------------------
+
+ async def extract_all(self, *, on_step: Any | None = None) -> DecisionExtractionReport:
+ """Run all capture sources in parallel. LLM failures are caught per-source.
+
+ *on_step* is an optional callable invoked with the source name as each
+ sub-extractor finishes (``inline_marker``, ``git_archaeology``,
+ ``readme_mining``, ``adr``, ``changelog``, ``pr``, ``comment``). Used by
+ the CLI to surface per-source progress.
+
+ Every extracted decision is then put through the anti-hallucination
+ substring gate (:meth:`_apply_substring_gate`) before being returned —
+ ungrounded LLM fields are dropped and evidence-less decisions rejected.
+ """
+
+ async def _safe_source(name: str, coro_fn: Any) -> list[ExtractedDecision]:
+ try:
+ logger.info("decision_extractor.starting", source=name)
+ result = await coro_fn()
+ logger.info("decision_extractor.finished", source=name, count=len(result))
+ return result
+ except Exception as exc:
+ logger.warning("decision_extractor.source_failed", source=name, error=str(exc))
+ return []
+ finally:
+ if on_step:
+ on_step(name)
+
+ # (source name, bound coroutine factory) — order is the progress order.
+ sources: list[tuple[str, Any]] = [
+ ("inline_marker", self.scan_inline_markers),
+ ("git_archaeology", self.mine_git_archaeology),
+ ("readme_mining", self.mine_readme_docs),
+ ("adr", self.discover_adrs),
+ ("changelog", self.mine_changelog),
+ ("pr", self.mine_pr_bodies),
+ ("comment", self.mine_comment_archaeology),
+ ]
+
+ logger.info("decision_extractor.extract_all_start")
+ results = await asyncio.gather(*[_safe_source(name, fn) for name, fn in sources])
+ logger.info("decision_extractor.extract_all_done")
+
+ # Raw per-source pool, then the anti-hallucination gate.
+ raw: list[ExtractedDecision] = []
+ by_source: dict[str, int] = {}
+ for (name, _fn), source_decisions in zip(sources, results, strict=True):
+ by_source[name] = len(source_decisions)
+ raw.extend(source_decisions)
+
+ decisions, rejected = self._apply_substring_gate(raw)
+ logger.info(
+ "decision_extractor.substring_gate",
+ kept=len(decisions),
+ rejected=rejected,
+ )
+
+ return DecisionExtractionReport(
+ total_found=len(decisions),
+ decisions=decisions,
+ by_source=by_source,
+ )
+
+ # ------------------------------------------------------------------
+ # Helpers
+ # ------------------------------------------------------------------
+
+ def _iter_source_files(self):
+ """Yield source files under repo_path, skipping irrelevant dirs.
+
+ Uses os.walk so we can prune entire subtrees (nested git repos,
+ node_modules, etc.) without descending into them.
+ """
+ import os
+
+ for dirpath, dirnames, filenames in os.walk(self._repo_path):
+ # Prune skip-listed directories in-place so os.walk won't descend
+ dirnames[:] = [
+ d
+ for d in dirnames
+ if d not in _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.
+ and not d.endswith(".egg-info")
+ and not d.endswith(".dist-info")
+ # Skip nested git repositories — they are separate codebases
+ # and should not contribute decisions to the parent repo.
+ and not (Path(dirpath) / d / ".git").exists()
+ ]
+
+ for fname in filenames:
+ fpath = Path(dirpath) / fname
+ if fpath.suffix.lower() not in _BINARY_EXTENSIONS:
+ yield fpath
+
+ def _get_neighbors(self, file_path: str) -> list[str]:
+ """Get 1-hop graph neighbors for a file."""
+ if self._graph is None:
+ return []
+ neighbors: set[str] = set()
+ if file_path in self._graph:
+ neighbors.update(self._graph.successors(file_path))
+ neighbors.update(self._graph.predecessors(file_path))
+ neighbors.discard(file_path)
+ return list(neighbors)[:20] # Cap at 20
+
+ @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 top-level module paths from file paths."""
+ modules: set[str] = set()
+ for fp in file_paths:
+ parts = fp.replace("\\", "/").split("/")
+ if len(parts) > 1:
+ modules.add(parts[0])
+ return sorted(modules)
+
+ def _infer_modules_from_text(self, text: str) -> list[str]:
+ """Infer module names by matching text against graph nodes."""
+ if not self._graph:
+ return []
+ modules: set[str] = set()
+ text_lower = text.lower()
+ for node in self._graph.nodes:
+ parts = node.replace("\\", "/").split("/")
+ if len(parts) > 1 and parts[0].lower() in text_lower:
+ modules.add(parts[0])
+ return sorted(modules)[:5]
+
+ def _infer_tags(self, text: str) -> list[str]:
+ """Infer tags from decision text."""
+ tag_keywords = {
+ "auth": ["auth", "jwt", "oauth", "token", "session", "login"],
+ "database": ["database", "sql", "postgres", "sqlite", "redis", "mongo", "db"],
+ "api": ["api", "rest", "graphql", "endpoint", "route"],
+ "performance": ["performance", "cache", "speed", "latency", "optimize"],
+ "security": ["security", "encrypt", "hash", "cors", "csrf", "xss"],
+ "infra": ["docker", "kubernetes", "deploy", "ci", "cd", "terraform"],
+ "testing": ["test", "mock", "fixture", "assert"],
+ }
+ text_lower = text.lower()
+ tags = []
+ for tag, keywords in tag_keywords.items():
+ if any(kw in text_lower for kw in keywords):
+ tags.append(tag)
+ return tags
+
+ def _parse_decisions_json(self, content: str) -> list[ExtractedDecision]:
+ """Parse LLM response as JSON array of decisions."""
+ # Extract JSON from response (may be wrapped in markdown code blocks)
+ content = content.strip()
+ if content.startswith("```"):
+ # Remove markdown code fences
+ lines = content.split("\n")
+ content = "\n".join(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 []
+
+ if isinstance(data, dict):
+ data = [data]
+ if not isinstance(data, list):
+ return []
+
+ decisions = []
+ for item in data:
+ if not isinstance(item, dict):
+ continue
+ title = item.get("title", "")
+ if not title:
+ continue
+ decisions.append(
+ ExtractedDecision(
+ title=title,
+ context=item.get("context", ""),
+ decision=item.get("decision", ""),
+ rationale=item.get("rationale", ""),
+ alternatives=item.get("alternatives", []),
+ consequences=item.get("consequences", []),
+ tags=item.get("tags", []),
+ evidence_commits=[item["commit_sha"]] if "commit_sha" in item else [],
+ source_quote=item.get("source_quote", ""),
+ )
+ )
+ return decisions
diff --git a/packages/core/src/repowise/core/analysis/decisions/gate.py b/packages/core/src/repowise/core/analysis/decisions/gate.py
new file mode 100644
index 000000000..4bc5d9c1b
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/gate.py
@@ -0,0 +1,105 @@
+"""Anti-hallucination substring gate — orchestration shared by every path
+that produces decision candidates (the multi-source extractor *and* the
+Phase-2 LLM-docs harvest).
+
+The gate is the product guarantee: a ``decision`` / ``rationale`` /
+``source_quote`` field that does not substring- or token-match the verbatim
+source span it claims to come from is **dropped**, and a candidate whose every
+produced field is ungrounded is **rejected**. It became critical in Phase 2
+because the page generator now *generates* decision candidates rather than only
+reading them — the gate is what stops a fluent-but-invented rationale from being
+stored as institutional memory.
+
+This module operates on duck-typed candidates (anything exposing the
+``decision`` / ``rationale`` / ``source_quote`` / ``source_text`` /
+``verification`` attributes — :class:`~repowise.core.analysis.decision_extractor.ExtractedDecision`
+is the in-tree shape) so it depends on neither the extractor nor the generator,
+and both can call it without a cycle.
+"""
+
+from __future__ import annotations
+
+from typing import Protocol, TypeVar
+
+from repowise.core.analysis.decisions.provenance import normalize_text, verify_quote
+
+__all__ = ["GateCandidate", "apply_substring_gate"]
+
+# Fields whose verbatim grounding the gate enforces, in priority order. The
+# strongest surviving verdict across them is stamped onto ``verification``.
+_GATED_FIELDS = ("decision", "rationale", "source_quote")
+
+
+class GateCandidate(Protocol):
+ """Structural shape the gate reads and mutates."""
+
+ decision: str
+ rationale: str
+ source_quote: str
+ source_text: str
+ verification: str
+
+
+_C = TypeVar("_C", bound=GateCandidate)
+
+
+def apply_substring_gate(decisions: list[_C]) -> tuple[list[_C], int]:
+ """Drop ungrounded fields, reject candidates with no surviving evidence.
+
+ Every produced ``decision`` / ``rationale`` / ``source_quote`` must
+ substring- or token-match the verbatim ``source_text`` the producer
+ recorded (see :func:`decision_provenance.verify_quote`). Unverifiable
+ fields are cleared; a candidate whose every produced field is unverifiable
+ is rejected. ``verification`` is stamped with the strongest surviving
+ verdict. A candidate with no ``source_text`` (nothing to check against) is
+ kept but left ``unverified`` — we never fabricate a rejection we cannot
+ justify. ``source_text`` is cleared on every survivor since it is a
+ transient and must never reach persistence.
+
+ Returns ``(kept, rejected_count)``.
+ """
+ kept: list[_C] = []
+ rejected = 0
+ for d in decisions:
+ src = getattr(d, "source_text", "") or ""
+ if not src:
+ d.verification = "unverified"
+ d.source_text = ""
+ kept.append(d)
+ continue
+
+ # Normalize the (possibly large) source span once per candidate and
+ # reuse it across the field checks — verify_quote re-normalizes its
+ # second arg, but normalizing an already-collapsed string is a cheap
+ # no-op, so the gate stays O(source span) per candidate.
+ norm_src = normalize_text(src)
+
+ verdicts: list[str] = []
+ produced_any = False
+ grounded_any = False
+ for fname in _GATED_FIELDS:
+ val = (getattr(d, fname, "") or "").strip()
+ if not val:
+ continue
+ produced_any = True
+ verdict = verify_quote(val, norm_src)
+ if verdict == "unverified":
+ setattr(d, fname, "") # drop the hallucinated field
+ else:
+ grounded_any = True
+ verdicts.append(verdict)
+
+ if produced_any and not grounded_any:
+ rejected += 1
+ continue
+
+ if "exact" in verdicts:
+ d.verification = "exact"
+ elif "fuzzy" in verdicts:
+ d.verification = "fuzzy"
+ else:
+ d.verification = "unverified"
+ d.source_text = "" # transient — don't carry into persistence
+ kept.append(d)
+
+ return kept, rejected
diff --git a/packages/core/src/repowise/core/analysis/decisions/prompts.py b/packages/core/src/repowise/core/analysis/decisions/prompts.py
new file mode 100644
index 000000000..8d5c44ccf
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/prompts.py
@@ -0,0 +1,156 @@
+"""LLM prompt templates for the decision extractor.
+
+Extracted from the former decision_extractor.py; imported back into
+``extractor.py``. Internal to the decisions package.
+"""
+
+from __future__ import annotations
+
+_SYSTEM_PROMPT = (
+ "You are an architectural decision extractor. "
+ "You extract structured decision records from code context. "
+ "Return only valid JSON. Never invent rationale not present in the source."
+)
+
+INLINE_MARKER_PROMPT = """\
+A developer left architectural decision markers in their code. \
+Extract each one as a structured decision record.
+
+Markers found in file: {file_path}
+
+{markers_block}
+
+For each marker, return a JSON object:
+{{
+ "title": "short title of the decision",
+ "context": "what situation forced this",
+ "decision": "what was chosen",
+ "rationale": "why",
+ "alternatives": ["rejected alternatives if mentioned"],
+ "consequences": ["tradeoffs if mentioned"],
+ "tags": ["relevant tags from: auth, database, api, performance, security, infra, testing"]
+}}
+
+Return a JSON array of decision objects. If a marker is not an architectural \
+decision, skip it. Return [] if none qualify.
+"""
+
+GIT_ARCHAEOLOGY_PROMPT = """\
+Analyze these git commits to determine if they represent architectural decisions.
+
+{commits_block}
+
+For each commit that IS an architectural decision (a deliberate choice about \
+system structure, patterns, migrations, or technology), return a JSON object:
+{{
+ "commit_sha": "the sha",
+ "title": "short title",
+ "context": "what situation forced this",
+ "decision": "what was chosen or changed",
+ "rationale": "why this approach (infer from message and files only)",
+ "alternatives": [],
+ "consequences": [],
+ "tags": ["relevant tags"]
+}}
+
+Return a JSON array. Skip commits that are just bug fixes or minor changes. \
+Return [] if none qualify. Do not hallucinate rationale.
+"""
+
+README_MINING_PROMPT = """\
+Analyze this documentation file and extract any architectural decisions.
+
+File: {file_path}
+Content:
+{content}
+
+Look for:
+- Technology choices and why ("We use X because Y")
+- Things replaced or migrated away from
+- Explicit architectural constraints
+- Design patterns chosen and why
+
+Return a JSON array of decisions:
+{{
+ "title": "short title",
+ "context": "situation that forced it",
+ "decision": "what was chosen",
+ "rationale": "why",
+ "alternatives": [],
+ "consequences": [],
+ "tags": [],
+ "source_quote": "exact quote from the document"
+}}
+
+Only extract explicit decisions. Return [] if none found.
+"""
+
+CHANGELOG_MINING_PROMPT = """\
+These are CHANGELOG entries from sections that usually record deliberate \
+changes (Changed / Removed / Deprecated). Extract any that represent an \
+architectural decision (a technology/pattern change, a removal, a deprecation \
+with a reason).
+
+{entries_block}
+
+Return a JSON array of decisions:
+{{
+ "title": "short title",
+ "context": "what prompted it (only if stated)",
+ "decision": "what was changed/removed/deprecated",
+ "rationale": "why (only if stated — do not invent)",
+ "alternatives": [],
+ "consequences": [],
+ "tags": [],
+ "source_quote": "the exact changelog line this came from"
+}}
+
+Skip pure feature additions and trivial fixes. Return [] if none qualify.
+"""
+
+PR_BODY_MINING_PROMPT = """\
+These are squash-merge / PR commit bodies. Extract any architectural decision \
+described in them (technology choices, migrations, structural changes, things \
+deliberately rejected).
+
+{bodies_block}
+
+For each decision return a JSON object:
+{{
+ "commit_sha": "the sha shown",
+ "title": "short title",
+ "context": "what situation forced this (only if stated)",
+ "decision": "what was chosen or changed",
+ "rationale": "why (quote/paraphrase the body — never invent)",
+ "alternatives": ["rejected alternatives if mentioned"],
+ "consequences": [],
+ "tags": [],
+ "source_quote": "the exact sentence from the body this came from"
+}}
+
+Return a JSON array. Skip bodies that are just checklists or release noise. \
+Return [] if none qualify.
+"""
+
+COMMENT_ARCHAEOLOGY_PROMPT = """\
+These are block comments / docstrings from high-centrality code (the files \
+most other code depends on). Extract any architectural decision whose \
+rationale is explained in the prose.
+
+{comments_block}
+
+For each decision return a JSON object:
+{{
+ "title": "short title",
+ "context": "what situation forced this (only if stated)",
+ "decision": "what was chosen",
+ "rationale": "why (quote/paraphrase the comment — never invent)",
+ "alternatives": [],
+ "consequences": [],
+ "tags": [],
+ "source_quote": "the exact sentence from the comment this came from"
+}}
+
+Only extract decisions whose reasoning is actually written in the prose. \
+Return [] if none qualify.
+"""
diff --git a/packages/core/src/repowise/core/analysis/decisions/provenance.py b/packages/core/src/repowise/core/analysis/decisions/provenance.py
new file mode 100644
index 000000000..43abbfe60
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/provenance.py
@@ -0,0 +1,127 @@
+"""Provenance primitives shared by the decision extractor and the persistence
+layer: the source-ranking ladder, the corroboration-aware confidence formula,
+and the anti-hallucination substring gate helpers.
+
+This module deliberately depends on nothing from ``decision_extractor`` or the
+persistence layer so both can import it without a cycle (``crud.py`` consumes
+the ranking ladder + confidence formula; ``decision_extractor`` consumes the
+verification helpers).
+
+Note: this is the *decision* provenance subsystem and is unrelated to the
+page-level provenance in ``generation.page_generator`` (``_attach_file_provenance``),
+which records a page's source files / KG layer. They share a word, not a concern.
+"""
+
+from __future__ import annotations
+
+import re
+
+__all__ = [
+ "MAX_SOURCE_RANK",
+ "SOURCE_RANK",
+ "compute_confidence",
+ "normalize_text",
+ "rank_for_source",
+ "verify_quote",
+]
+
+# ---------------------------------------------------------------------------
+# Source ranking ladder
+# ---------------------------------------------------------------------------
+#
+# Higher rank = more authoritative provenance. When two sources describe the
+# same decision, the headline fields come from the highest-rank evidence and
+# the lower-rank source is retained as a corroborating evidence row (never
+# discarded). ``test_name`` and ``inferred`` are placeholders for later phases
+# (LLM-docs harvest lands ``llm_inferred`` in Phase 2) but the full ladder is
+# defined now so ranks are stable across phases.
+SOURCE_RANK: dict[str, int] = {
+ "cli": 9, # human-authored manual entry — most authoritative
+ "adr": 8, # architecture decision records (structured, intentional)
+ "pr": 7, # PR / squash-merge body
+ "commit": 6, # individual commit message
+ "git_archaeology": 6, # alias for commit-mined decisions
+ "changelog": 5, # keep-a-changelog Changed/Removed/Deprecated
+ "inline_marker": 4, # # WHY: / # DECISION: code markers
+ "comment": 3, # rationale prose in block comments / docstrings
+ "readme_mining": 3, # implicit decisions in README/docs prose
+ "test_name": 2, # placeholder — behaviour asserted by a test name
+ "inferred": 1, # placeholder — purely inferred, no verbatim source
+ "llm_inferred": 1, # Phase 2 LLM-docs harvest
+}
+
+MAX_SOURCE_RANK: int = max(SOURCE_RANK.values())
+
+
+def rank_for_source(source: str | None) -> int:
+ """Return the ranking ladder value for *source* (unknown → lowest rank)."""
+ return SOURCE_RANK.get((source or "").lower(), 1)
+
+
+# ---------------------------------------------------------------------------
+# Confidence: a function of best source rank + corroboration + verification
+# ---------------------------------------------------------------------------
+
+
+def compute_confidence(
+ top_rank: int,
+ corroboration_count: int = 1,
+ verification: str = "exact",
+) -> float:
+ """Confidence for a decision backed by ``corroboration_count`` evidence rows.
+
+ Rises with the best source rank and with the number of *independent*
+ corroborating sources; multiplicatively decayed when the strongest
+ surviving evidence is only fuzzy- or un-verified. Bounded to ``[0, 0.99]``
+ (we never claim certainty). Recency decay is deferred — staleness scoring
+ already models age separately.
+ """
+ base = 0.4 + 0.5 * (top_rank / MAX_SOURCE_RANK)
+ corroboration_bonus = min(0.12, 0.04 * max(0, corroboration_count - 1))
+ conf = base + corroboration_bonus
+ if verification == "fuzzy":
+ conf *= 0.85
+ elif verification == "unverified":
+ conf *= 0.6
+ return round(max(0.0, min(0.99, conf)), 3)
+
+
+# ---------------------------------------------------------------------------
+# Anti-hallucination substring gate
+# ---------------------------------------------------------------------------
+
+_WS_RE = re.compile(r"\s+")
+
+
+def normalize_text(text: str | None) -> str:
+ """Collapse whitespace + lowercase for substring/token comparison."""
+ if not text:
+ return ""
+ return _WS_RE.sub(" ", text).strip().lower()
+
+
+def verify_quote(
+ quote: str | None,
+ source_text: str | None,
+ *,
+ fuzzy_threshold: float = 0.6,
+) -> str:
+ """Classify how well *quote* is grounded in *source_text*.
+
+ Returns:
+ ``"exact"`` — *quote* is a normalized substring of the source span.
+ ``"fuzzy"`` — token overlap ≥ *fuzzy_threshold* (paraphrase / reflow).
+ ``"unverified"`` — neither (likely hallucinated, or no source to check).
+ """
+ q = normalize_text(quote)
+ src = normalize_text(source_text)
+ if not q or not src:
+ return "unverified"
+ if q in src:
+ return "exact"
+ q_tokens = set(q.split())
+ if not q_tokens:
+ return "unverified"
+ src_tokens = set(src.split())
+ overlap = len(q_tokens & src_tokens) / len(q_tokens)
+ return "fuzzy" if overlap >= fuzzy_threshold else "unverified"
diff --git a/packages/core/src/repowise/core/analysis/decisions/semantic_match.py b/packages/core/src/repowise/core/analysis/decisions/semantic_match.py
new file mode 100644
index 000000000..0ba3b3340
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/semantic_match.py
@@ -0,0 +1,188 @@
+"""Embedding-based semantic matching for decision dedup (Phase 2C).
+
+Title-string dedup (the cheap first pass in ``crud.bulk_upsert_decisions``)
+collapses decisions whose normalized titles are identical, but it misses
+paraphrases: *"Use Redis"* and *"Adopt Redis cache"* describe one decision yet
+share no normalized title. This module adds the second pass on top of the
+**page-generator vector store** — the same store wiki pages live in.
+
+Decisions are embedded into that shared store under a ``decision:`` page-id
+namespace with ``page_type="decision_record"``. Two consequences, both wanted:
+
+- **Dedup reuses the store.** A residual (title-unmatched) candidate is matched
+ by querying the store and keeping the nearest ``decision:`` neighbour whose
+ cosine similarity clears a threshold — no separate decision index, no
+ in-process re-embedding of the whole decision set.
+- **Decisions become searchable.** Because they live in the same store as
+ pages, ``search_codebase`` surfaces them alongside docs — a feature, not a
+ leak: a query like "why Redis?" can return the decision record directly.
+
+All backends return cosine similarity from ``search`` (InMemory/pgvector
+natively; LanceDB normalised in ``lancedb_store``), so a single similarity
+threshold applies uniformly.
+"""
+
+from __future__ import annotations
+
+import contextlib
+from typing import Any
+
+__all__ = [
+ "DECISION_PAGE_TYPE",
+ "DECISION_VECTOR_PREFIX",
+ "DEFAULT_DEDUP_TAU",
+ "decision_match_text",
+ "find_duplicate_decision",
+ "find_related_decisions",
+ "upsert_decision_vector",
+]
+
+# Cosine threshold above which two decision texts are treated as the same
+# decision. Tuned conservatively: high enough that unrelated decisions don't
+# collapse, low enough that genuine paraphrases ("use Redis" / "adopt Redis
+# cache") merge. Revisit empirically alongside the Phase-3 conflict detector,
+# which reuses this similarity signal.
+DEFAULT_DEDUP_TAU = 0.83
+
+# Page-id namespace + page_type for decision vectors co-located in the page
+# store. The prefix lets dedup filter store hits down to decisions; the
+# page_type lets search surfaces label them.
+DECISION_VECTOR_PREFIX = "decision:"
+DECISION_PAGE_TYPE = "decision_record"
+
+# How many nearest neighbours to pull before filtering to the decision
+# namespace. Decisions are a small slice of a store dominated by page vectors,
+# so we over-fetch to make sure a genuine paraphrase (which sits at very high
+# similarity) isn't crowded out of the window by unrelated-but-near pages.
+_SEARCH_FETCH = 50
+
+
+def decision_match_text(title: str, decision: str = "") -> str:
+ """The text used to embed a decision for semantic matching.
+
+ Title carries the most signal; the decision statement disambiguates
+ same-titled-but-different records. Kept in one place so the stored vector
+ and the query side always embed the same shape.
+ """
+ title = (title or "").strip()
+ decision = (decision or "").strip()
+ return f"{title}\n{decision}".strip() if decision else title
+
+
+def _decision_page_id(decision_id: str) -> str:
+ return f"{DECISION_VECTOR_PREFIX}{decision_id}"
+
+
+async def upsert_decision_vector(
+ store: Any,
+ decision_id: str,
+ *,
+ title: str,
+ decision: str = "",
+ evidence_file: str | None = None,
+) -> None:
+ """Embed a decision into the shared page store (idempotent on its id).
+
+ Makes the decision both matchable for dedup and discoverable via
+ ``search_codebase``. Failures are swallowed: a vector-store hiccup must
+ never abort the SQL upsert that already happened.
+ """
+ text = decision_match_text(title, decision)
+ if not text:
+ return
+ # Best-effort: search visibility / dedup is an enhancement, not a
+ # correctness requirement for the SQL record, so a store hiccup is swallowed.
+ with contextlib.suppress(Exception):
+ await store.embed_and_upsert(
+ _decision_page_id(decision_id),
+ text,
+ {
+ "title": title or "",
+ "page_type": DECISION_PAGE_TYPE,
+ "target_path": evidence_file or "",
+ "content": text,
+ },
+ )
+
+
+async def find_duplicate_decision(
+ store: Any,
+ *,
+ title: str,
+ decision: str = "",
+ tau: float = DEFAULT_DEDUP_TAU,
+ exclude_ids: set[str] | None = None,
+) -> str | None:
+ """Return the id of an existing decision that is a semantic duplicate.
+
+ Queries the shared store, filters hits to the ``decision:`` namespace
+ (dropping any in *exclude_ids*), and returns the nearest one whose cosine
+ similarity is ≥ *tau* — or None when nothing clears the bar. Store errors
+ degrade to None (title dedup still applied upstream).
+ """
+ query = decision_match_text(title, decision)
+ if not query:
+ return None
+ exclude = exclude_ids or set()
+ try:
+ results = await store.search(query, limit=_SEARCH_FETCH)
+ except Exception:
+ return None
+
+ for r in results: # results are ordered best-first
+ page_id = getattr(r, "page_id", "")
+ if not page_id.startswith(DECISION_VECTOR_PREFIX):
+ continue
+ decision_id = page_id[len(DECISION_VECTOR_PREFIX) :]
+ if decision_id in exclude:
+ continue
+ # First (nearest) decision hit decides: if it clears the bar it's the
+ # match; if not, nothing closer exists, so there is no duplicate.
+ return decision_id if getattr(r, "score", 0.0) >= tau else None
+ return None
+
+
+async def find_related_decisions(
+ store: Any,
+ *,
+ title: str,
+ decision: str = "",
+ lo: float,
+ hi: float = 1.01,
+ exclude_ids: set[str] | None = None,
+ limit: int = 25,
+) -> list[tuple[str, float]]:
+ """Return ``(decision_id, similarity)`` for decisions *about the same topic*.
+
+ Powers Phase-3 supersession/conflict detection. Where
+ :func:`find_duplicate_decision` returns the single nearest neighbour above
+ the dedup threshold (a *merge*), this returns every ``decision:`` neighbour
+ whose cosine similarity sits in the band ``[lo, hi)`` — high enough to be
+ the same topic, but (by default) *below* the dedup threshold so they were
+ not collapsed into one record. Those are exactly the candidates that might
+ contradict / supersede each other. Ordered best-first; store errors degrade
+ to an empty list.
+ """
+ query = decision_match_text(title, decision)
+ if not query:
+ return []
+ exclude = exclude_ids or set()
+ try:
+ results = await store.search(query, limit=_SEARCH_FETCH)
+ except Exception:
+ return []
+
+ out: list[tuple[str, float]] = []
+ for r in results:
+ page_id = getattr(r, "page_id", "")
+ if not page_id.startswith(DECISION_VECTOR_PREFIX):
+ continue
+ decision_id = page_id[len(DECISION_VECTOR_PREFIX) :]
+ if decision_id in exclude:
+ continue
+ score = getattr(r, "score", 0.0)
+ if lo <= score < hi:
+ out.append((decision_id, score))
+ if len(out) >= limit:
+ break
+ return out