Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(decisions): let a measured capture tier deliver without an acceptance (#2451)
Raghav Chamadiyae0e8c2062144
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.pyindex 2fa4476af..a0019ee05 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py@@ -326,6 +326,22 @@ _UNMIGRATED = "1 = 1"#: ``lifecycle.AGREEMENT_KIND``, spelled out for the same reason as _ACCEPTED._AGREEMENT_KIND = "agreement"+#: Capture tiers a record may be delivered on with no acceptance row. A+#: ``(source, scope_basis)`` pair belongs here only once a census of its+#: (record, file) pairs has measured at least 90% governs with a 95% lower+#: bound of at least 80%; today only ``comment`` has. That is a result about+#: this corpus and not a property of the miner, so re-measure before adding a+#: pair, and re-measure if comment attribution changes.+_EVIDENCE_TIERS: frozenset[tuple[str, str]] = frozenset({("comment", "")})++#: Measured trust per tier, for ordering the candidate lane only. It orders,+#: it does not admit: the relevance floor still decides what enters the lane.+_TIER_TRUST: dict[tuple[str, str], int] = {+ ("comment", ""): 2,+ ("pr", "commit_selected"): 1,+ ("git_archaeology", "commit_selected"): 1,+}+def _accepted_clause(conn: sqlite3.Connection, ref: str) -> str:"""The acceptance filter for *ref*, or a no-op on a pre-split store."""@@ -355,6 +371,64 @@ def _kind_column(conn: sqlite3.Connection) -> str:return "kind" if any(c[1] == "kind" for c in cols) else "NULL"+def _has_column(conn: sqlite3.Connection, column: str) -> bool:+ """Whether ``decision_records`` has *column* on this store.++ Probed for the reason :func:`_kind_column` gives. A store without+ ``scope_basis`` cannot say how a record was scoped, so it delivers nothing+ on evidence and keeps the acceptance path it has.+ """+ try:+ return any(c[1] == column for c in conn.execute("PRAGMA table_info(decision_records)"))+ except sqlite3.Error:+ return False+++def _untouched_clause(conn: sqlite3.Connection, ref: str) -> str:+ """SQL matching records no reviewer has acted on.++ ``review_state`` is the column that knows, not ``status``: of the four+ review actions only ``dismiss_candidate`` writes ``status``, so a merged or+ split-flagged candidate still reads as ``proposed`` with no acceptance row.+ ``1 = 0`` where the store has no such table -- unreadable is not untouched.+ """+ try:+ found = conn.execute(+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",+ ("decision_candidate_meta",),+ ).fetchone()+ except sqlite3.Error:+ return "1 = 0"+ if not found:+ return "1 = 0"+ return (+ f"NOT EXISTS (SELECT 1 FROM decision_candidate_meta m "+ f"WHERE m.decision_id = {ref}.id AND m.review_state <> 'open')"+ )+++def _evidence_tier_clause(conn: sqlite3.Connection, ref: str) -> str:+ """SQL matching records whose capture tier delivers on its own evidence.++ ``1 = 0`` where the store cannot answer, which is the safe direction: a+ tier that cannot be read is not a tier that has been earned.+ """+ if not _EVIDENCE_TIERS or not _has_column(conn, "scope_basis"):+ return "1 = 0"+ # Interpolated, so anything but a bare identifier must not reach the SQL.+ if any(+ not isinstance(v, str) or not re.fullmatch(r"[a-z_]*", v)+ for pair in _EVIDENCE_TIERS+ for v in pair+ ):+ return "1 = 0"+ terms = [+ f"({ref}.source = '{src}' AND COALESCE({ref}.scope_basis, '') = '{basis}')"+ for src, basis in sorted(_EVIDENCE_TIERS)+ ]+ return "(" + " OR ".join(terms) + ")"++def _load_active_decisions(conn: sqlite3.Connection) -> list[dict]:"""Accepted, current decisions with their node links, as plain dicts."""return _load_decisions(@@ -394,6 +468,8 @@ def _load_decisions(conn: sqlite3.Connection, where: str) -> list[dict]:rows = conn.execute("SELECT id, title, decision, rationale, confidence, staleness_score, source, "+ _kind_column(conn)+ + ", "+ + ("COALESCE(scope_basis, '')" if _has_column(conn, "scope_basis") else "''")+ " FROM decision_records WHERE "+ where).fetchall()@@ -409,6 +485,7 @@ def _load_decisions(conn: sqlite3.Connection, where: str) -> list[dict]:"staleness": r[5] if isinstance(r[5], (int, float)) else 0.0,"source": r[6] or "","kind": r[7],+ "basis": r[8] or "","links": [],}for r in rows@@ -517,13 +594,32 @@ _CANDIDATE_HEADER = ()+def _tier_trust(decision: dict) -> int:+ """How far the capture tier of *decision* was measured to be trusted."""+ return _TIER_TRUST.get((decision.get("source") or "", decision.get("basis") or ""), 0)++def _rank(- decisions: list[dict], seeds: set[str], hop: set[str], tokens: list[str]+ decisions: list[dict],+ seeds: set[str],+ hop: set[str],+ tokens: list[str],+ *,+ by_tier: bool = False,) -> list[dict]:- """Decisions above the relevance floor, most relevant first."""+ """Decisions above the relevance floor, most relevant first.++ *by_tier* orders by measured capture tier before relevance, for the+ candidate lane only: nobody has agreed to anything there, so how a record+ was scoped is all that separates two of them. The accepted lane does not+ use it, because a signature outranks a capture tier.+ """scored = [(d, _score_decision(d, seeds, hop, tokens)) for d in decisions]scored = [(d, score) for d, score in scored if score >= _RELEVANCE_FLOOR]- scored.sort(key=lambda pair: pair[1], reverse=True)+ if by_tier:+ scored.sort(key=lambda pair: (_tier_trust(pair[0]), pair[1]), reverse=True)+ else:+ scored.sort(key=lambda pair: pair[1], reverse=True)return [d for d, _ in scored]@@ -586,7 +682,7 @@ def _session_decision_block(repo_path: Path, session_id: str) -> str | None:hop = _expand_one_hop(conn, seeds)tokens = _branch_tokens(branch)ranked = _rank(decisions, seed_set, hop, tokens)- ranked_candidates = _rank(candidates, seed_set, hop, tokens)+ ranked_candidates = _rank(candidates, seed_set, hop, tokens, by_tier=True)finally:conn.close()@@ -626,7 +722,16 @@ def _session_decision_block(repo_path: Path, session_id: str) -> str | None:def _governing_decisions(conn: sqlite3.Connection, rel: str) -> list[dict]:- """Active decisions governing *rel* via file links or module-prefix links.+ """Decisions governing *rel* via file links or module-prefix links.++ Two disjoint ways in: a record someone accepted, or one nobody has+ reviewed whose capture tier was measured to hold (:data:`_EVIDENCE_TIERS`).+ Review wins either way -- accepting delivers whatever the tier, and any+ other review action removes the record from the tier branch.++ **File links only.** What was measured is whether a record governs a file+ it names; a module link claims a whole subtree, so those stay+ acceptance-only.Link node ids are matched in POSIX regardless of how they were stored(Windows extraction persists backslashes). Top-level module links are@@ -635,34 +740,55 @@ def _governing_decisions(conn: sqlite3.Connection, rel: str) -> list[dict]:out: list[dict] = []seen: set[str] = set()native = rel.replace("/", "\\")+ accepted = _accepted_clause(conn, "d")+ on_evidence = (+ f"(d.status IN ('active', 'proposed') AND NOT ({accepted}) "+ f"AND {_untouched_clause(conn, 'd')} "+ f"AND {_evidence_tier_clause(conn, 'd')})"+ )+ governs_file = f"(d.status = 'active' AND {accepted}) OR {on_evidence}"+ # A tier delivers on the surface it was measured on: file pairs, not+ # subtrees.+ governs_module = f"d.status = 'active' AND {accepted}"with contextlib.suppress(sqlite3.Error):for row in conn.execute(- "SELECT d.id, d.title, d.decision, d.rationale "+ "SELECT d.id, d.title, d.decision, d.rationale, " + accepted + " ""FROM decision_node_links l JOIN decision_records d ON d.id = l.decision_id "- "WHERE l.node_id IN (?, ?) AND l.link_type = 'file' AND d.status = 'active' "- "AND " + _accepted_clause(conn, "d"),+ "WHERE l.node_id IN (?, ?) AND l.link_type = 'file' AND (" + governs_file + ")",(rel, native),):if row[0] not in seen:seen.add(row[0])- out.append({"id": row[0], "title": row[1], "decision": row[2], "rationale": row[3]})+ out.append(_governing_row(row))# Module links are few; prefix-match them in Python.for row in conn.execute(- "SELECT d.id, d.title, d.decision, d.rationale, l.node_id "+ "SELECT d.id, d.title, d.decision, d.rationale, " + accepted + ", l.node_id ""FROM decision_node_links l JOIN decision_records d ON d.id = l.decision_id "- "WHERE l.link_type = 'module' AND d.status = 'active' "- "AND " + _accepted_clause(conn, "d")+ "WHERE l.link_type = 'module' AND (" + governs_module + ")"):if (row[0] not in seen- and _module_deep_enough(row[4])- and rel.startswith(_norm_path(row[4]).rstrip("/") + "/")+ and _module_deep_enough(row[5])+ and rel.startswith(_norm_path(row[5]).rstrip("/") + "/")):seen.add(row[0])- out.append({"id": row[0], "title": row[1], "decision": row[2], "rationale": row[3]})+ out.append(_governing_row(row))+ # A reviewed decision outranks a mined one whatever the link order said.+ out.sort(key=lambda d: not d["accepted"])return out+def _governing_row(row: tuple) -> dict:+ """One ``_governing_decisions`` row, with how it earned its place."""+ return {+ "id": row[0],+ "title": row[1],+ "decision": row[2],+ "rationale": row[3],+ "accepted": bool(row[4]),+ }++def _session_evidence_count(conn: sqlite3.Connection, decision_id: str) -> int:"""Distinct sessions that attested to this decision (evidence rows)."""try:@@ -711,7 +837,15 @@ def _edit_decision_notice(repo_path: Path, rel: str, session_id: str, state: dicwhy = _clip(decision["rationale"] or decision["decision"], _CLIP_RATIONALE)if _echoes_title(decision["title"], why):why = "" # legacy rows echo the title into decision/rationale- line = f"[repowise] {rel} is governed by a standing decision: {_clip(decision['title'], 100)}"+ # "Standing" means a person stood behind it, so a record delivered on its+ # tier alone must not borrow the word.+ if decision["accepted"]:+ line = f"[repowise] {rel} is governed by a standing decision: {_clip(decision['title'], 100)}"+ else:+ line = (+ f"[repowise] {rel} has a decision recorded in it, mined but not reviewed: "+ f"{_clip(decision['title'], 100)}"+ )if why:line += f" because {why}"if sessions_n >= 2:diff --git a/packages/core/src/repowise/core/analysis/decisions/scope.py b/packages/core/src/repowise/core/analysis/decisions/scope.pyindex c41e5323f..62dcaa96e 100644--- a/packages/core/src/repowise/core/analysis/decisions/scope.py+++ b/packages/core/src/repowise/core/analysis/decisions/scope.py@@ -76,12 +76,18 @@ SCOPE_BASIS_REPOSITORY = "repository"#: legacy backfill never touches it, so a selected scope survives the repair#: that stamps every pre-selector commit record as a footprint.#:-#: Measured out of sample, on 43 selections over 29 records drawn from the dev-#: store: 93% of selected files govern the file they are shown on and none are-#: noise, against 27% governs and 18% noise for the same records' whole commit-#: lists. Every one of the 20 records that had a genuinely governing file kept-#: one; the 5 the model emptied had none to keep. Evidence in-#: ``local-stash/decision-layer-research/capture-2026-09-19/RESULTS.md``.+#: **Measured twice, and the second number is the one to quote.** Offline, on+#: 43 selections over 29 records, it scored 93% governs and 0% noise against+#: 27%/18% for the same records' whole commit lists+#: (``capture-2026-09-19/RESULTS.md``). On the first real index after the+#: miners' token budget was fixed it scores **71% governs and 3% noise** over a+#: census of 208 pairs (``tier-2026-09-20/RESULTS.md``).+#:+#: So the basis fixed noise and not relevance: what survives is a wide+#: ``related`` band, files genuinely touched by the change a record describes+#: where the record is still not a rule about them. It is good enough to offer+#: an agent as a candidate and not good enough to answer "what governs this+#: file", which is why ``decision_inject._EVIDENCE_TIERS`` excludes it.SCOPE_BASIS_SELECTED = "commit_selected"#: The basis value marking a scope a person stated: typed at the CLI, writtendiff --git a/tests/unit/cli/test_augment_decision_inject.py b/tests/unit/cli/test_augment_decision_inject.pyindex 990389f42..d27a045ef 100644--- a/tests/unit/cli/test_augment_decision_inject.py+++ b/tests/unit/cli/test_augment_decision_inject.py@@ -23,6 +23,7 @@ from repowise.core.analysis.decisions.lifecycle import (from repowise.core.persistence.database import init_dbfrom repowise.core.persistence.models import (DecisionAcceptance,+ DecisionCandidateMeta,DecisionEvidence,DecisionNodeLink,DecisionRecord,@@ -54,6 +55,7 @@ async def _build_wiki_db(repo_root: Path, decisions: list[dict], extras=None) ->status=spec.get("status", "active"),kind=spec.get("kind", ARCHITECTURAL_KIND),source=spec.get("source", "cli"),+ scope_basis=spec.get("scope_basis", ""),confidence=spec.get("confidence", 0.9),staleness_score=spec.get("staleness", 0.0),evidence_file=spec["id"], # keeps the unique constraint happy@@ -76,6 +78,16 @@ async def _build_wiki_db(repo_root: Path, decisions: list[dict], extras=None) ->accepter="tester",))+ # Review state lives here, not on the record: three of the four+ # review actions leave ``status`` alone (see _untouched_clause).+ if spec.get("review_state"):+ session.add(+ DecisionCandidateMeta(+ decision_id=spec["id"],+ repository_id=_REPO_ID,+ review_state=spec["review_state"],+ )+ )for node_id, link_type in spec.get("links", []):session.add(DecisionNodeLink(@@ -922,3 +934,284 @@ async def test_a_candidate_is_never_injected(tmp_path):],)assert decision_inject._edit_decision_notice(tmp_path, "src/app.py", "s1", {}) is None+++# ---------------------------------------------------------------------------+# Delivery on capture tier (see tier-2026-09-20/RESULTS.md)+# ---------------------------------------------------------------------------+++async def test_a_measured_tier_reaches_edit_time_without_an_acceptance(tmp_path, monkeypatch):+ """A `comment` record governs the file it was extracted from, unreviewed.++ That tier is in `_EVIDENCE_TIERS` because a census of its 27 pairs put it+ at 100% governs with a Wilson lower bound of 88%, over the pre-registered+ 90/80 bar. Before this, an unaccepted record could not reach this surface+ at all, and the store has held zero acceptance rows since 2026-09-12.+ """+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-comment",+ "title": "Keep the parser allocation-free",+ "decision": "reuse the buffer",+ "source": "comment",+ "scope_basis": "",+ "accepted": False,+ "status": "proposed",+ "links": [("src/core/auth.py", "file")],+ }+ ],+ )+ notice = decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", {})+ assert notice is not None+ # It must not borrow the reviewed lane's word for itself.+ assert "mined but not reviewed" in notice+ assert "standing decision" not in notice+++async def test_an_unmeasured_tier_stays_out_of_edit_time(tmp_path, monkeypatch):+ """`commit_selected` measured 71% on 191 pairs, under the bar, so it does+ not get to say a file is governed. It remains a SessionStart candidate."""+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-selected",+ "title": "Bind the selected files",+ "decision": "whatever the selector chose",+ "source": "pr",+ "scope_basis": "commit_selected",+ "accepted": False,+ "status": "proposed",+ "links": [("src/core/auth.py", "file")],+ }+ ],+ )+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", {}) is None+++async def test_a_dismissed_record_is_not_rescued_by_its_tier(tmp_path, monkeypatch):+ """Acceptance overrides downward. A candidate someone tombstoned leaves+ ``active``/``proposed``, and no capture tier may bring it back."""+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-dismissed",+ "title": "Keep the parser allocation-free",+ "decision": "reuse the buffer",+ "source": "comment",+ "scope_basis": "",+ "accepted": False,+ "status": "dismissed",+ "links": [("src/core/auth.py", "file")],+ }+ ],+ )+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", {}) is None+++async def test_an_accepted_record_still_speaks_as_a_standing_decision(tmp_path, monkeypatch):+ """Acceptance overrides upward, and keeps its wording. A source outside+ every measured tier still governs once a person has stood behind it."""+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-accepted",+ "title": "Never fan out parse subprocesses",+ "decision": "keep it in-process",+ "source": "session",+ "accepted": True,+ "links": [("src/core/auth.py", "file")],+ }+ ],+ )+ notice = decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", {})+ assert notice is not None+ assert "governed by a standing decision" in notice+++async def test_the_candidate_lane_prefers_the_better_measured_tier(tmp_path, monkeypatch):+ """The lane holds two slots and was blind to capture, so a `session`+ record at 29% governs / 29% noise competed evenly with a `commit_selected`+ one at 71% / 3%. Relevance alone would rank the session record first."""+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-weak",+ "title": "Weak tier candidate",+ "decision": "mined from a transcript",+ "source": "session",+ "scope_basis": "",+ "confidence": 0.95,+ "accepted": False,+ "status": "proposed",+ "links": [("src/core/auth.py", "file")],+ },+ {+ "id": "d-strong",+ "title": "Better tier candidate",+ "decision": "mined from a commit the model read",+ "source": "pr",+ "scope_basis": "commit_selected",+ "confidence": 0.5,+ "accepted": False,+ "status": "proposed",+ "links": [("src/core/auth.py", "file")],+ },+ ],+ )+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])+ block = decision_inject._session_decision_block(tmp_path, "sess-1")+ assert block is not None+ lines = [ln for ln in block.splitlines() if "candidate" in ln.lower()]+ assert lines and "Better tier candidate" in lines[0]+++async def test_a_store_without_scope_basis_delivers_nothing_on_evidence(tmp_path, monkeypatch):+ """A tier is a claim about how a record was scoped. A store that cannot+ answer that question keeps the acceptance path it already had, rather than+ guessing its way into delivering a whole review queue."""+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-comment",+ "title": "Keep the parser allocation-free",+ "decision": "reuse the buffer",+ "source": "comment",+ "accepted": False,+ "status": "proposed",+ "links": [("src/core/auth.py", "file")],+ },+ {+ "id": "d-accepted-control",+ "title": "A reviewed decision",+ "decision": "someone stood behind this",+ "source": "session",+ "accepted": True,+ "links": [("src/other.py", "file")],+ },+ ],+ )+ conn = sqlite3.connect(tmp_path / ".repowise" / "wiki.db")+ conn.execute("ALTER TABLE decision_records DROP COLUMN scope_basis")+ conn.commit()+ conn.close()++ # Asserting only that the candidate is refused would pass for the wrong+ # reason: a query that referenced the missing column would raise, the+ # caller suppresses sqlite3.Error, and silence would look like refusal.+ # The accepted record is the control — it proves the statement still ran.+ assert decision_inject._edit_decision_notice(tmp_path, "src/other.py", "s1", {}) is not None+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", {}) is None+++async def test_a_tier_does_not_reach_through_a_module_link(tmp_path, monkeypatch):+ """The census measured (record, file) pairs, so the tier delivers on file+ links and not on module ones. On the live store the difference is 12+ measured file matches against 78 files a module prefix would have served.+ """+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-module",+ "title": "Centralize package attribution",+ "decision": "one helper decides what a package is",+ "source": "comment",+ "scope_basis": "",+ "accepted": False,+ "status": "proposed",+ "links": [("src/core/health", "module")],+ }+ ],+ )+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/health/engine.py", "s1", {}) is None+++async def test_an_accepted_module_link_still_governs_its_subtree(tmp_path, monkeypatch):+ """The control for the test above: restricting the tier to file links must+ not disturb the module path a reviewed decision already had."""+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-module-accepted",+ "title": "Centralize package attribution",+ "decision": "one helper decides what a package is",+ "source": "comment",+ "accepted": True,+ "links": [("src/core/health", "module")],+ }+ ],+ )+ notice = decision_inject._edit_decision_notice(tmp_path, "src/core/health/engine.py", "s1", {})+ assert notice is not None+ assert "governed by a standing decision" in notice+++async def test_a_merged_candidate_is_not_delivered_on_its_tier(tmp_path, monkeypatch):+ """Review overrides downward even where it leaves ``status`` alone.++ ``merge_candidate`` records the acceptance on the *target* and leaves the+ folded-away candidate at ``proposed`` with no acceptance row of its own, so+ an acceptance test alone reads it as untouched. Only ``review_state`` knows.+ """+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-open",+ "title": "Keep the parser allocation-free",+ "decision": "reuse the buffer",+ "source": "comment",+ "scope_basis": "",+ "accepted": False,+ "status": "proposed",+ "links": [("src/core/open.py", "file")],+ },+ {+ "id": "d-merged",+ "title": "Keep the parser allocation-free",+ "decision": "reuse the buffer",+ "source": "comment",+ "scope_basis": "",+ "accepted": False,+ "status": "proposed",+ "review_state": "merged",+ "links": [("src/core/auth.py", "file")],+ },+ ],+ )+ # The control: an untouched record on the same tier is delivered, so the+ # silence below is a refusal and not a query that failed.+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/open.py", "s1", {}) is not None+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s2", {}) is None+++async def test_a_candidate_flagged_for_a_split_is_not_delivered_on_its_tier(tmp_path, monkeypatch):+ """``request_split`` touches neither ``status`` nor the acceptance log+ either. A record a person flagged as bundling two choices is not one to+ hand an agent as a single rule about a file."""+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-split",+ "title": "Keep the parser allocation-free",+ "decision": "reuse the buffer",+ "source": "comment",+ "scope_basis": "",+ "accepted": False,+ "status": "proposed",+ "review_state": "needs_split",+ "links": [("src/core/auth.py", "file")],+ }+ ],+ )+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", {}) is None