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
fix(decisions): make the contradiction rate mean what it says (#2479)
Raghav Chamadiya5c8739fd3317
diff --git a/packages/core/src/repowise/core/analysis/decisions/evolution.py b/packages/core/src/repowise/core/analysis/decisions/evolution.pyindex 053140853..8919d9237 100644--- a/packages/core/src/repowise/core/analysis/decisions/evolution.py+++ b/packages/core/src/repowise/core/analysis/decisions/evolution.py@@ -33,6 +33,7 @@ from __future__ import annotationsimport jsonimport re+from functools import lru_cachefrom typing import Anyimport structlog@@ -185,18 +186,35 @@ _REVERSAL_SIGNALS: tuple[str, ...] = (_OPPOSING_VERB_PAIRS: tuple[tuple[frozenset[str], frozenset[str]], ...] = ((frozenset(- {"adopt", "adopted", "use", "using", "add", "added", "introduce", "enable", "enabled"}+ {+ "adopt",+ "adopted",+ "adopting",+ "use",+ "using",+ "add",+ "added",+ "introduce",+ "introducing",+ "enable",+ "enabled",+ "enabling",+ }),frozenset({"drop","dropped",+ "dropping","remove","removed",+ "removing","deprecate","deprecated",+ "deprecating","disable","disabled",+ "disabling","revert","reverted","abandon",@@ -280,13 +298,58 @@ def is_reversal(text: str) -> tuple[bool, str]:return False, ""-def contradicts(text_a: str, text_b: str) -> tuple[bool, str]:+#: A verb as a word, plus the ``-s``/``-ed`` inflections corrections are+#: written in -- :data:`_OPPOSING_VERB_PAIRS` lists ``removed`` but not+#: *removes*. It cannot build a silent-e or doubled ``-ing`` (*removing*,+#: *dropping*), so those are listed there instead. The left edge excludes+#: ``-`` too, so ``blocking`` does not match inside *non-blocking*, which sits+#: on the other side of its own pair.+_VERB_RE = r"(?<![\w-]){verb}(?:s|es|d|ed|ing)?\b"+++@lru_cache(maxsize=512)+def _verb_pattern(verb: str) -> re.Pattern[str]:+ return re.compile(_VERB_RE.format(verb=re.escape(verb)))+++def _mentions(low: str, verbs: frozenset[str]) -> bool:+ """Does *low* use any of *verbs* as a word, rather than inside one?++ Substring matching put ``use`` inside *user*, ``add`` inside *address* and+ ``sync`` inside *asynchronous*, each scoring an agreeing correction as a+ contradiction. The straddle is the only test the default path has left.+ """+ return any(_verb_pattern(v).search(low) for v in verbs)+++def contradicts(+ text_a: str, text_b: str, *, lone_reversal_counts: bool = False+) -> 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)``.+ True when an opposing verb pair straddles the two texts *and* they share+ enough content tokens to be about the same topic (so "deprecate X" and+ "adopt Y" for unrelated X/Y don't false-positive) — or, for a caller that+ passes ``lone_reversal_counts``, when one text carries a directional+ reversal signal. Returns ``(bool, signal)``.++ A directional reversal signal in **one** text is not, on its own, evidence+ that the two contradict: it says that text changes something, never that+ it changes *this*. Token overlap is far too weak to supply the missing+ half. Measured over this repository's whole injection corpus — 426+ (decision, quote) pairs behind 201 judged rows — 96% of pairs share zero or+ one token, the opposing-verb straddle fires on none of them, and the lone+ reversal branch fires exactly once: the word *migration*, in a quote about+ not mutating production, against a record reading "Never run Ruff format",+ on the two tokens *run* and *not*. That single firing is the whole of the+ 10.0% contradiction rate this layer has published.++ ``lone_reversal_counts`` restores the old branch for a caller that has+ already established the two texts are about the same thing by a stronger+ test than token overlap. Supersession detection is that caller: it only+ reaches here for pairs a vector store scored between ``RELATED_TAU`` and+ ``DEFAULT_DEDUP_TAU``, where "the newer one says it replaces something" is+ genuine evidence. Injection feedback has no such gate and must not pass it."""if not _shared_topic(text_a, text_b):return False, ""@@ -294,13 +357,15 @@ def contradicts(text_a: str, text_b: str) -> tuple[bool, str]: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)+ a_left = _mentions(low_a, left)+ b_right = _mentions(low_b, right)+ a_right = _mentions(low_a, right)+ b_left = _mentions(low_b, left)if (a_left and b_right) or (a_right and b_left):return True, "opposing-verbs"+ if not lone_reversal_counts:+ return False, ""rev_a, sig_a = is_reversal(text_a)if rev_a:return True, sig_a@@ -409,7 +474,9 @@ async def detect_supersessions_and_conflicts(text_new = f"{rec.title}. {rec.decision}"text_old = f"{other.title}. {other.decision}"- contra, signal = contradicts(text_new, text_old)+ # Vector similarity already put these two on the same topic, which+ # is the gate a lone reversal signal needs to mean anything.+ contra, signal = contradicts(text_new, text_old, lone_reversal_counts=True)if not contra and provider is not None:contra, signal = await _llm_contradiction_judge(provider, text_a=text_new, text_b=text_olddiff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.pyindex 0aa0b2e9c..f9c1029e7 100644--- a/packages/core/src/repowise/core/sessions/miners/decisions.py+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py@@ -877,6 +877,41 @@ def promotion_decisions(INJECTION_EVAL_MIN_AGE_SECONDS = 3600.0+async def _records_by_alias(+ db_session: Any, repository_id: str, alias_ids: list[str]+) -> dict[str, Any]:+ """Live records for retired ids, keyed by the **retired** id.++ Keyed by the alias so the caller can look a sidecar row up under the id it+ stored.++ One hop, because re-keying does not chain: ``decision_aliases.decision_id``+ is in ``_DEPENDENT_COLUMNS``, so re-keying a record that is already some+ id's target repoints the existing alias rather than writing a hop beside+ it. A merge *can* chain, since a merged candidate keeps its record, so+ ``A -> B -> C`` is reachable with ``B`` live. One hop is still the right+ answer there: ``A`` has no record, ``B`` has a real one, and ``B``'s text+ is what was shown.+ """+ if not alias_ids:+ return {}++ from sqlalchemy import select++ from repowise.core.persistence.models import DecisionAlias, DecisionRecord++ rows = await db_session.execute(+ select(DecisionAlias.alias_id, DecisionRecord)+ .join(DecisionRecord, DecisionRecord.id == DecisionAlias.decision_id)+ .where(+ DecisionAlias.alias_id.in_(alias_ids),+ DecisionAlias.repository_id == repository_id,+ DecisionRecord.repository_id == repository_id,+ )+ )+ return {alias_id: rec for alias_id, rec in rows.all()}++async def apply_injection_feedback(db_session: Any,repository_id: str,@@ -932,6 +967,11 @@ async def apply_injection_feedback(# would never reach them otherwise and the reported rate would stay# pinned at whatever the else branch produced.retired = store.retire_unjudgeable_verdicts()+ # Beside it: rows another session's match settled, handed back to the+ # judge below. **This order is load-bearing** -- both repairs ride one+ # `PRAGMA user_version` and this one writes the higher number, so+ # reversing them skips the retirement for good.+ reopened = store.reopen_smeared_contradictions()# Commit even when nothing matched, because what is being persisted is# the "already repaired" mark, not the rows. Without this the mark is# rolled back by the early return below on any store with nothing to@@ -939,8 +979,12 @@ async def apply_injection_feedback(# RAW_TTL_DAYS has pruned the corrections, it would fire on verdicts# that were earned. That is the exact decay the one-shot prevents.store.commit()- if retired:- logger.info("session_mining.injection_verdicts_retired", rows=retired)+ if retired or reopened:+ logger.info(+ "session_mining.injection_verdicts_repaired",+ retired=retired,+ reopened=reopened,+ )injections = store.unevaluated_injections(before=ts - INJECTION_EVAL_MIN_AGE_SECONDS)if not injections:@@ -954,16 +998,20 @@ async def apply_injection_feedback())records = {rec.id: rec for rec in rows.scalars().all()}+ # A record's id moves when its scope does and nothing rewrites the+ # sidecar, so without the aliases those rows read as "the decision is+ # gone" and are drained, discarding feedback already earned -- 372 of+ # 421 settled rows on this store.+ records |= await _records_by_alias(+ db_session, repository_id, [d for d in decision_ids if d not in records]+ )quotes_by_session: dict[str, list[str]] = {}- verdicts: dict[str, bool] = {} # decision_id -> contradicted anywhere- #: (session_id, decision_id, this session had a correction to test it- #: against) for every row settled here. Judgeability is per *row*, not- #: per decision, because the totals count rows: one session that- #: happened to hold a correction would otherwise hand a free verdict- #: to every other session the same decision was shown to, which is the- #: bug this whole change is about, one level up.- judged: list[tuple[str, str, bool]] = []+ #: (session_id, decision_id, judgeable, this session's own verdict).+ #: **Both flags are per row**, because the totals count rows: a verdict+ #: shared across every session a decision was shown to is multiplied by+ #: however many that was.+ judged: list[tuple[str, str, bool, bool]] = []for inj in injections:rec = records.get(inj["decision_id"])if rec is None:@@ -977,18 +1025,12 @@ async def apply_injection_feedback(quotes = quotes_by_session[session_id]decision_text = f"{rec.title}. {rec.decision}"contradicted = any(contradicts(decision_text, quote)[0] for quote in quotes)- verdicts[rec.id] = verdicts.get(rec.id, False) or contradicted- judged.append((session_id, inj["decision_id"], bool(quotes)))-- # Settle the ledger after the aggregation, not during it: the verdict- # *value* is per decision across every session that saw it, so a row's- # own judgement is not final until the last of them has been read.- # Whether a row gets that value at all is per row, and the two are- # different questions — a decision contradicted in one session says- # nothing about a session that mined no correction at all. Storing it- # is what lets `repowise hook stats` report the split — until now the- # numbers existed only in one update run's console output.- for session_id, decision_id, judgeable in judged:+ judged.append((session_id, inj["decision_id"], bool(quotes), contradicted))++ # Each row settles on its own session's corrections: a decision+ # contradicted in one session says nothing about a session that mined+ # different corrections, or none. Stored so `hook stats` can report it.+ for session_id, decision_id, judgeable, contradicted in judged:if not judgeable:# Settled, so it is not re-read every update, but with no# verdict: this session mined nothing that could have@@ -996,7 +1038,6 @@ async def apply_injection_feedback(store.mark_injection_evaluated(session_id, decision_id)summary["unjudgeable"] += 1continue- contradicted = bool(verdicts.get(decision_id))store.mark_injection_evaluated(session_id,decision_id,diff --git a/packages/core/src/repowise/core/sessions/staging.py b/packages/core/src/repowise/core/sessions/staging.pyindex 80921dee7..d3cb434f8 100644--- a/packages/core/src/repowise/core/sessions/staging.py+++ b/packages/core/src/repowise/core/sessions/staging.py@@ -49,6 +49,11 @@ RAW_TTL_DAYS = 90.0#: database with raw sqlite3 and must not learn about a new one._VERDICT_REPAIR_VERSION = 1+#: As above, for :meth:`reopen_smeared_contradictions`. The pragma is a single+#: integer, so the repairs are ordered and a store carrying version 1 gets+#: this one on its next update.+_SMEAR_REPAIR_VERSION = 2+#: ``raw_candidates.kind`` for a broad-discovery candidate. Discovery writes#: its raw row only as the anchor ``upsert_structured`` needs, never as work#: for the deterministic structuring pass.@@ -844,6 +849,55 @@ class SessionStagingStore:self._conn.execute(f"PRAGMA user_version = {_VERDICT_REPAIR_VERSION}")return cur.rowcount or 0+ def reopen_smeared_contradictions(self) -> int:+ """Re-open contradicted rows so each is re-judged on its own session.++ The verdict used to be computed per decision and stored per row, so one+ session's match settled every row for that decision. On this+ repository's store that turned a single match into 20 contradicted rows+ and produced the layer's only published outcome number, 10.0%.++ Re-opening rather than clearing, so a row that earned its verdict is+ given the chance to earn it again. ``contradicted`` is the only value+ the smear could invent — it was an ``or`` across sessions, so it could+ add a contradiction but never remove one — which is why ``followed``+ rows are left alone.++ **Only rows whose session still holds a correction.** Re-opening a row+ whose evidence has gone is a deletion, not a re-judgement: the judge+ finds no quote and settles it with no verdict, which+ :meth:`decision_feedback_totals` calls unrecoverable. And it does go --+ :meth:`prune` drops an unstructured ``raw_candidates`` row at+ :data:`RAW_TTL_DAYS` while :meth:`correction_quotes` ignores+ ``structured_key``, and ``prune`` runs earlier in the same update. The+ same clause as :meth:`retire_unjudgeable_verdicts`, inverted.++ **Partial in both directions, and not repairable from here.** A session+ that kept some corrections but lost the one that fired re-judges to+ ``followed``, a positive claim rather than a gap; a genuinely smeared+ row whose corrections have gone fails this guard and keeps+ ``contradicted`` for good. The guard sees whether a session has+ corrections, never which one produced a verdict, and cannot see+ ``decision_records`` at all -- so a row whose decision was purged is+ re-opened here and drained by the judge.++ **Runs exactly once per store**, like the repair above: "written under+ the old rule" is only true-forever for rows already here.+ """+ if self._conn.execute("PRAGMA user_version").fetchone()[0] >= _SMEAR_REPAIR_VERSION:+ return 0+ placeholders = ",".join("?" * len(self.DECISION_SURFACES))+ cur = self._conn.execute(+ f"UPDATE injections SET evaluated = 0, verdict = '' "+ f"WHERE surface IN ({placeholders}) AND verdict = 'contradicted' "+ "AND EXISTS ("+ "SELECT 1 FROM raw_candidates rc WHERE rc.session_id = injections.session_id "+ "AND rc.kind = 'user_correction')",+ self.DECISION_SURFACES,+ )+ self._conn.execute(f"PRAGMA user_version = {_SMEAR_REPAIR_VERSION}")+ return cur.rowcount or 0+def decision_feedback_totals(self) -> dict[str, int]:"""Counts of decision injections by followed-vs-contradicted verdict.diff --git a/tests/unit/persistence/test_decision_evolution_update.py b/tests/unit/persistence/test_decision_evolution_update.pyindex 459c6f1b4..44d76b1ce 100644--- a/tests/unit/persistence/test_decision_evolution_update.py+++ b/tests/unit/persistence/test_decision_evolution_update.py@@ -41,10 +41,26 @@ def test_is_reversal():def test_contradicts_requires_shared_topic():- # Reversal + shared topic → contradiction.- assert contradicts("Replace sessions with JWT for auth", "Use sessions for auth")[0] is True# Opposing verbs but unrelated topics → not a contradiction.assert contradicts("Drop the Redis cache", "Adopt gRPC transport")[0] is False+ # Opposing verbs on a shared topic → contradiction, on the default path.+ assert contradicts("Drop the Redis cache layer", "Adopt the Redis cache layer")[0] is True+++def test_a_lone_reversal_signal_needs_a_caller_that_vouches_for_the_topic():+ """A real reversal the default declines, and the reason it declines it.++ "Replace sessions" against "Use sessions" is a true contradiction that no+ opposing verb pair straddles, so requiring two-sided evidence gives it up.+ That is a deliberate loss, taken because the one-sided branch is not+ selective enough to keep: over this repository's whole injection corpus it+ fired once, wrongly, and that firing is the layer's only published outcome+ number. Supersession keeps the branch by opting in, having already+ established the shared topic with a vector score.+ """+ pair = ("Replace sessions with JWT for auth", "Use sessions for auth")+ assert contradicts(*pair)[0] is False+ assert contradicts(*pair, lone_reversal_counts=True)[0] is Truedef test_supersession_confidence_bounds_and_bumps():diff --git a/tests/unit/sessions/test_contradiction_heuristic.py b/tests/unit/sessions/test_contradiction_heuristic.pynew file mode 100644index 000000000..4ca9cd0bc--- /dev/null+++ b/tests/unit/sessions/test_contradiction_heuristic.py@@ -0,0 +1,159 @@+"""`contradicts()` needs two-sided evidence, not one text's mood.++The heuristic gates on shared content tokens and then asks whether the two+texts push in opposite directions. It used to accept a directional reversal+signal found in *either* text on its own, which says that text changes+something and never that it changes *this*. Token overlap cannot supply the+missing half: measured over this repository's whole injection corpus, 426+(decision, quote) pairs behind 201 judged rows, 96% of pairs share zero or one+token and the two-sided test fires on none of them, while the lone-reversal+branch fires exactly once — and wrongly. That single firing is the whole of+the 10.0% contradiction rate the layer has published.++That measurement was taken against the straddle as it matched then, by+unanchored substring. The tests below also pin the anchoring that followed, in+both directions: the false positives it removes, the inflections it must not+cost, and one false positive it cannot reach. The straddle has its own+false-positive rate and this corpus has not measured it.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.decisions.evolution import contradicts++#: The exact pair behind all 20 contradicted rows on this repository's store.+#: They share precisely two content tokens, *run* and *not*, which clears the+#: shared-topic gate, and the quote contains the reversal signal *migration*.+_RUFF_RECORD = "Never run Ruff format. Do not run `ruff format` on the codebase."+_PRODUCTION_QUOTE = (+ "Do not run migration 141, backfill, update rows, deploy, alter Dodo, "+ "or otherwise mutate production."+)+++def test_a_lone_reversal_word_is_not_a_contradiction():+ """The false positive that produced this layer's only outcome number."""+ assert contradicts(_RUFF_RECORD, _PRODUCTION_QUOTE) == (False, "")+++def test_a_caller_with_its_own_topic_gate_can_opt_the_branch_back_in():+ """Supersession reaches the heuristic only for vector-similar pairs.++ There "the newer one says it replaces something" is genuine evidence,+ because something stronger than token overlap already established the two+ are about the same thing.+ """+ assert contradicts(_RUFF_RECORD, _PRODUCTION_QUOTE, lone_reversal_counts=True) == (+ True,+ "migration",+ )+++def test_an_opposing_verb_pair_straddling_the_texts_still_fires():+ """The two-sided test is the default's whole content."""+ fired, signal = contradicts(+ "Use JWT tokens for service auth. all service auth uses JWT tokens",+ "no, stop using JWT tokens for service auth, revert to sessions",+ )+ assert (fired, signal) == (True, "opposing-verbs")+++def test_opposing_verbs_still_need_a_shared_topic():+ """Otherwise "adopt X" contradicts "drop Y" for unrelated X and Y."""+ assert contradicts(+ "Adopt Postgres for the primary store.",+ "we removed the legacy avatar cropper",+ ) == (False, "")+++def test_an_unrelated_correction_does_not_contradict():+ assert contradicts(+ "Use JWT tokens for service auth. all service auth uses JWT tokens",+ "no, format the changelog with bullet points please",+ ) == (False, "")+++def test_an_opposing_verb_must_be_a_word_and_not_a_substring():+ """`use` lives inside *user*, *because* and *reuse*; `add` inside *address*.++ Unanchored membership made the straddle fire on a correction that agrees+ with its record: `use` matched inside *user*, against `remove` in the+ quote. It matters more now than it did, because with the lone-reversal+ branch gone the straddle is the only firing path the default has.+ """+ assert contradicts(+ "Never log user email addresses. Do not put a user email in any log line.",+ "no, do not remove the user email validation from the signup form",+ ) == (False, "")+++def test_opposing_verbs_about_different_objects_still_fire():+ """A known limit of the straddle, recorded rather than claimed fixed.++ Here `use` and `dropped` are both whole words and both really present, so+ word-boundary matching does not and cannot help: the two verbs are about+ different objects, and nothing short of knowing what each verb governs+ separates this from a real reversal. The pair is only reached at all+ because `mcp` and `context` are shared, and it is why the default path+ remains a cheap pre-filter rather than a judgement.+ """+ assert contradicts(+ "Use the repowise MCP for context. Always use the repowise mcp tools.",+ "no, we dropped the legacy mcp context shim because it was unused",+ ) == (True, "opposing-verbs")+++ ("record", "quote"),+ [+ ("Uses Postgres for the primary store",+ "no, we removed Postgres from the primary store"),+ ("Used Postgres for the primary store",+ "no, we removed Postgres from the primary store"),+ ("Adopted Postgres for the primary store",+ "no, that removes Postgres from the primary store"),+ ("Adds Postgres to the primary store",+ "no, we dropped Postgres from the primary store"),+ ("Use Postgres for the primary store",+ "no, we abandoned Postgres for the primary store"),+ ("Enable the Postgres pool", "no, that disables the Postgres pool"),+ ("Adopt the Postgres pool", "no, it reverts the Postgres pool"),+ ("Introduced the Postgres pool", "no, we removed the Postgres pool"),+ # `-ing` the suffix group cannot build: silent-e and doubled consonant.+ ("Adopt the Postgres pool", "no, we are removing the Postgres pool"),+ ("Adopt the Postgres pool", "no, we are dropping the Postgres pool"),+ ("Adopt the Postgres pool", "no, we are disabling the Postgres pool"),+ ("Enabling the Postgres pool", "no, that disables the Postgres pool"),+ ],+)+def test_the_straddle_survives_the_inflections_corrections_are_written_in(record, quote):+ """Anchoring the verbs must not cost the forms people actually write.++ `_OPPOSING_VERB_PAIRS` lists `removed` but not *removes*, `use` but not+ *uses*. Plain whole-word matching dropped every one of these, which on the+ injection side is the only firing path there is, so anchoring alone would+ have cost more recall than the false-positive class it removes. The `-ing`+ forms the suffix group cannot build are listed in the pairs instead.+ """+ assert contradicts(record, quote) == (True, "opposing-verbs")+++def test_one_hyphenated_word_cannot_satisfy_both_sides_of_a_pair():+ """`blocking` sits inside *non-blocking*, and a hyphen is a word boundary.++ So whole-word matching alone does not separate them: a text containing+ only *non-blocking* matched the sync side and the async side at once, and+ two texts that agree scored as a contradiction. The left edge excludes the+ hyphen for this. Same class, reached by substring rather than by boundary:+ `sync` inside *asynchronous*.+ """+ assert contradicts(+ "Use non-blocking IO in the request handler",+ "no, keep the non-blocking IO request handler",+ ) == (False, "")+ assert contradicts(+ "The IO layer is asynchronous everywhere",+ "no, keep the IO layer asynchronous everywhere",+ ) == (False, "")diff --git a/tests/unit/sessions/test_injection_feedback.py b/tests/unit/sessions/test_injection_feedback.pyindex b9c05b781..8064d5f3b 100644--- a/tests/unit/sessions/test_injection_feedback.py+++ b/tests/unit/sessions/test_injection_feedback.py@@ -322,3 +322,167 @@ def test_hook_written_injections_table_is_schema_compatible(tmp_path):conn = sqlite3.connect(default_store_path(repo2))assert conn.execute("SELECT COUNT(*) FROM injections").fetchone()[0] == 1conn.close()+++async def test_a_contradiction_in_one_session_does_not_settle_another(session, tmp_path):+ """The verdict is per row, like judgeability already was.++ It used to be computed per decision and stored per row, so one session's+ match settled every row for that decision. The totals count rows, so the+ reported rate was that one match multiplied by however many sessions had+ been shown the decision. On this repository's store that was 20 rows from+ a single match, and it is the whole of the published 10.0%.+ """+ session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))+ await _add_decision(session, "d1")+ _record_injection(tmp_path, "sess-a", "d1", _OLD_ENOUGH)+ _record_injection(tmp_path, "sess-b", "d1", _OLD_ENOUGH)+ _stage_correction(+ tmp_path, "sess-a", "no, stop using JWT tokens for service auth, revert to sessions"+ )+ # sess-b mined a correction too, so it is judgeable — and it said nothing+ # about JWT. Its row must read followed, not sess-a's contradiction.+ _stage_correction(tmp_path, "sess-b", "no, put the changelog in reverse order")++ summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)++ assert summary == {"followed": 1, "contradicted": 1, "unjudgeable": 0}+ with SessionStagingStore(default_store_path(tmp_path)) as store:+ verdicts = dict(+ store._conn.execute(+ "SELECT session_id, verdict FROM injections WHERE decision_id = 'd1'"+ ).fetchall()+ )+ assert verdicts == {"sess-a": "contradicted", "sess-b": "followed"}+++async def test_smeared_contradictions_from_an_older_ledger_are_reopened(session, tmp_path):+ """Rows the old rule marked contradicted are already evaluated.++ Nothing re-reads them, so without a repair reaching backwards the rate+ stays at whatever the smear produced. Re-opened rather than cleared, so a+ row is given the chance to earn its verdict again — which it keeps only+ while the correction that earned it is still there.+ """+ session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))+ await _add_decision(session, "d1")+ _record_injection(tmp_path, "sess-a", "d1", _OLD_ENOUGH)+ _record_injection(tmp_path, "sess-b", "d1", _OLD_ENOUGH)+ _stage_correction(+ tmp_path, "sess-a", "no, stop using JWT tokens for service auth, revert to sessions"+ )+ _stage_correction(tmp_path, "sess-b", "no, put the changelog in reverse order")+ # The smear, as the old version left it: both rows contradicted.+ with SessionStagingStore(default_store_path(tmp_path)) as store:+ for sid in ("sess-a", "sess-b"):+ store.mark_injection_evaluated(sid, "d1", verdict="contradicted")+ store.commit()+ assert store.decision_feedback_totals()["contradicted"] == 2++ await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)++ with SessionStagingStore(default_store_path(tmp_path)) as store:+ assert store.decision_feedback_totals() == {+ "followed": 1, # sess-b, re-judged on its own correction+ "contradicted": 1, # sess-a keeps the verdict it earned+ "pending": 0,+ "no_verdict": 0,+ }+++async def test_the_smear_repair_does_not_run_twice(session, tmp_path):+ """Once is a repair; every pass would churn verdicts and lose some.++ The correction is left in place here on purpose. Deleting it first would+ make the pass return 0 through the evidence guard instead of the one-shot+ gate, and the test would pass whether or not the gate existed.++ The loss the gate prevents once the guard is in: a contradicted row whose+ session still holds its correction, but whose decision record has since+ been deleted with no alias. Re-opening that row re-judges it against a+ record that is not there, and it is drained with no verdict.+ """+ from repowise.core.persistence.models import DecisionRecord as _Rec++ session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))+ await _add_decision(session, "d1")+ _record_injection(tmp_path, "sess-a", "d1", _OLD_ENOUGH)+ _stage_correction(+ tmp_path, "sess-a", "no, stop using JWT tokens for service auth, revert to sessions"+ )++ await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)++ with SessionStagingStore(default_store_path(tmp_path)) as store:+ assert store.decision_feedback_totals()["contradicted"] == 1+ # Eligible on every count except the gate: the row is contradicted and+ # its correction is still there.+ assert store.reopen_smeared_contradictions() == 0++ # The record goes away, as a purge or an unaliased re-key would take it.+ await session.delete(await session.get(_Rec, "d1"))+ await session.flush()++ await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)+ with SessionStagingStore(default_store_path(tmp_path)) as store:+ assert store.decision_feedback_totals()["contradicted"] == 1+++async def test_a_rekeyed_decision_id_still_resolves_through_its_alias(session, tmp_path):+ """A record's id moves when its scope does, and nothing rewrites the sidecar.++ Without the aliases the row reads as "the decision is gone" and is drained+ with no verdict, so an ordinary scope edit discards feedback already+ earned. Measured on this repository's store: 372 of 421 settled rows+ resolve only this way.+ """+ from repowise.core.persistence.models import DecisionAlias++ session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))+ await _add_decision(session, "new-id")+ session.add(+ DecisionAlias(+ alias_id="old-id",+ repository_id=_REPO_ID,+ decision_id="new-id",+ reason="rekeyed",+ )+ )+ await session.flush()+ # The sidecar still holds the id that was live when the hook wrote it.+ _record_injection(tmp_path, "sess-1", "old-id", _OLD_ENOUGH)+ _stage_correction(+ tmp_path, "sess-1", "no, stop using JWT tokens for service auth, revert to sessions"+ )++ summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)++ assert summary == {"followed": 0, "contradicted": 1, "unjudgeable": 0}+++async def test_a_contradiction_whose_evidence_has_aged_out_is_not_reopened(+ session, tmp_path+):+ """Re-opening a row nothing can re-judge is a deletion, not a re-judgement.++ `prune` drops an unstructured `raw_candidates` row at RAW_TTL_DAYS while+ `correction_quotes` reads those rows regardless of `structured_key`, and+ `prune` runs earlier in the same update. So a genuinely earned+ contradiction can reach the repair with its evidence already gone, and+ re-opening it would settle it as no-verdict, which is unrecoverable.+ """+ session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))+ await _add_decision(session, "d1")+ _record_injection(tmp_path, "sess-a", "d1", _OLD_ENOUGH)+ # Earned under the old rule, and its correction has since been pruned.+ with SessionStagingStore(default_store_path(tmp_path)) as store:+ store.mark_injection_evaluated("sess-a", "d1", verdict="contradicted")+ store.commit()+ assert store.reopen_smeared_contradictions() == 0++ await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)++ with SessionStagingStore(default_store_path(tmp_path)) as store:+ totals = store.decision_feedback_totals()+ assert totals["contradicted"] == 1+ assert totals["no_verdict"] == 0