Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(decisions): ground each marker decision in its own span, and stop scoring untouched files as stale (#1315)

Raghav Chamadiyaa2006cffc64d
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.py
index 96b47bff9..95964bdf9 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
@@ -693,6 +693,7 @@ _INJECTIONS_TABLE_SQL = (
"chars INTEGER NOT NULL DEFAULT 0, "
"duration_ms INTEGER NOT NULL DEFAULT 0, "
"acted INTEGER NOT NULL DEFAULT 0, "
+ "verdict TEXT NOT NULL DEFAULT '', "
"PRIMARY KEY (session_id, decision_id))"
)
@@ -704,6 +705,7 @@ _LEDGER_COLUMNS = (
("chars", "INTEGER NOT NULL DEFAULT 0"),
("duration_ms", "INTEGER NOT NULL DEFAULT 0"),
("acted", "INTEGER NOT NULL DEFAULT 0"),
+ ("verdict", "TEXT NOT NULL DEFAULT ''"),
)
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index bfcf57b33..2cac00921 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -562,6 +562,7 @@ def hook_stats(path: str | None, as_json: bool) -> None:
session_totals = store.session_duration_totals()
runs = store.hook_run_totals()
by_tool = store.hook_run_by_tool()
+ feedback = store.decision_feedback_totals()
finally:
store.close()
if not rows:
@@ -569,7 +570,9 @@ def hook_stats(path: str | None, as_json: bool) -> None:
return
if as_json:
- console.print_json(json_mod.dumps({"surfaces": rows, "runs": by_tool}))
+ console.print_json(
+ json_mod.dumps({"surfaces": rows, "runs": by_tool, "decision_feedback": feedback})
+ )
return
from rich.table import Table
@@ -615,6 +618,27 @@ def hook_stats(path: str | None, as_json: bool) -> None:
"action to take, and read/reread counts as respected-not-re-offended.[/dim]"
)
+ # The decision surface's own verdict, which the acted-on rate above cannot
+ # carry: an injected decision is judged by whether the session went on to
+ # contradict it, not by whether a tool call followed it.
+ if any(feedback.values()):
+ judged = feedback["followed"] + feedback["contradicted"]
+ parts = [
+ f"[green]{feedback['followed']} followed[/green]",
+ f"[yellow]{feedback['contradicted']} contradicted[/yellow]",
+ ]
+ if feedback["pending"]:
+ parts.append(f"[dim]{feedback['pending']} awaiting the next update[/dim]")
+ if feedback["no_verdict"]:
+ parts.append(f"[dim]{feedback['no_verdict']} settled without a verdict[/dim]")
+ console.print(f" injected decisions: {', '.join(parts)}")
+ if judged:
+ pct = 100.0 * feedback["followed"] / judged
+ console.print(
+ f" [dim]{pct:.0f}% of judged injections were followed; "
+ "contradicted ones bump the record's staleness.[/dim]"
+ )
+
if session_totals:
session_totals.sort()
median = session_totals[len(session_totals) // 2]
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.py
index af13ada80..5eea8beff 100644
--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py
+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py
@@ -78,6 +78,25 @@ def _truncate_title(text: str, limit: int) -> str:
return window[:cut].rstrip() + "…"
+def _coerce_line(value: object) -> int | None:
+ """Read an LLM-reported line number, or ``None`` if it isn't one.
+
+ Models answer ``12``, ``"12"`` and ``"line 12"`` interchangeably; anything
+ that isn't a positive integer is no attribution at all and must not be
+ guessed at.
+ """
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value if value > 0 else None
+ if isinstance(value, str):
+ digits = re.search(r"\d+", value)
+ if digits:
+ line = int(digits.group())
+ return line if line > 0 else None
+ return None
+
+
def _as_aware_utc(value: datetime) -> datetime:
"""Return ``value`` as a timezone-aware UTC datetime.
@@ -427,23 +446,35 @@ class DecisionExtractor:
# 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)
+ markers_by_line = {m["line"]: m 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:
+ # Attribute the decision to the one marker it was drawn
+ # from (the prompt asks for `marker_line`, which the
+ # parser lands in `evidence_line`). Joining every
+ # marker's context into one span and handing it to all
+ # of them let the substring gate stamp a decision
+ # `exact` against a *different* marker's text, and put
+ # marker 1's line number on marker 3's decision. A
+ # decision we cannot attribute gets no source span at
+ # all: the gate then leaves it `unverified`, which is
+ # the honest verdict, rather than verifying it against
+ # a neighbour.
+ marker = markers_by_line.get(d.evidence_line)
+ if marker is None and len(markers) == 1:
+ marker = markers[0] # unambiguous without the hint
d.evidence_file = file_path
- d.evidence_line = markers[0]["line"] if markers else None
+ d.evidence_line = marker["line"] if marker else None
d.affected_files = list({file_path} | set(affected))
d.affected_modules = self._infer_modules(d.affected_files)
d.source = "inline_marker"
d.status = "active"
d.confidence = 0.95
- d.source_text = marker_source_text
+ d.source_text = marker.get("context", "") if marker else ""
decisions.extend(llm_decisions)
except Exception:
logger.warning(
@@ -1535,6 +1566,10 @@ class DecisionExtractor:
consequences=item.get("consequences", []),
tags=item.get("tags", []),
evidence_commits=[item["commit_sha"]] if "commit_sha" in item else [],
+ # Which marker this came from, for the inline-marker miner's
+ # per-marker attribution. Absent (and left None) for every
+ # other prompt — they scope by sha or by file instead.
+ evidence_line=_coerce_line(item.get("marker_line")),
source_quote=item.get("source_quote", ""),
)
)
diff --git a/packages/core/src/repowise/core/analysis/decisions/prompts.py b/packages/core/src/repowise/core/analysis/decisions/prompts.py
index 1a9a47ae9..ee954a7cd 100644
--- a/packages/core/src/repowise/core/analysis/decisions/prompts.py
+++ b/packages/core/src/repowise/core/analysis/decisions/prompts.py
@@ -22,6 +22,7 @@ Markers found in file: {file_path}
For each marker, return a JSON object:
{{
+ "marker_line": the line number of the marker this decision came from,
"title": "short title of the decision",
"context": "what situation forced this",
"decision": "what was chosen",
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index 1208cbc2a..866d6be38 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -1013,6 +1013,47 @@ async def purge_proposed_decisions_by_source(
return len(ids)
+async def _fill_git_meta_gaps(
+ session: AsyncSession,
+ repository_id: str,
+ git_meta_map: dict[str, dict],
+ wanted: set[str],
+) -> dict[str, dict]:
+ """``git_meta_map`` widened with persisted rows for the *wanted* paths.
+
+ The caller's map is one run's git metadata, and on an incremental update
+ that is only the files that changed in it. Staleness scoring reads a path
+ with no entry as a file that is gone and scores it 1.00, so every decision
+ over an untouched file went maximally stale for not having been touched.
+ The persisted rows cover every file the index has seen, which is the set
+ that answers "is this file still here"; a path missing from those too is
+ genuinely untracked and still scores 1.00. The run's own entries win —
+ they are this run's fresher numbers for the files it re-read.
+ """
+ missing = wanted - git_meta_map.keys()
+ if not missing:
+ return git_meta_map
+
+ filled: dict[str, dict] = {}
+ # Chunked so the IN clause stays under SQLite's bind-parameter ceiling.
+ batch = sorted(missing)
+ for start in range(0, len(batch), 500):
+ rows = await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repository_id,
+ GitMetadata.file_path.in_(batch[start : start + 500]),
+ )
+ )
+ for row in rows.scalars().all():
+ filled[row.file_path] = {
+ col.name: getattr(row, col.name)
+ for col in row.__table__.columns
+ if col.name not in ("id", "repository_id")
+ }
+ filled.update(git_meta_map)
+ return filled
+
+
async def recompute_decision_staleness(
session: AsyncSession,
repository_id: str,
@@ -1027,10 +1068,25 @@ async def recompute_decision_staleness(
)
decisions = list(result.scalars().all())
+ affected_by_id: dict[str, list[str]] = {}
+ for dec in decisions:
+ affected = json.loads(dec.affected_files_json)
+ if affected:
+ affected_by_id[dec.id] = affected
+ if not affected_by_id:
+ return 0
+
+ git_meta_map = await _fill_git_meta_gaps(
+ session,
+ repository_id,
+ git_meta_map,
+ {fp for paths in affected_by_id.values() for fp in paths},
+ )
+
now = _now_utc()
updated = 0
for dec in decisions:
- affected = json.loads(dec.affected_files_json)
+ affected = affected_by_id.get(dec.id)
if not affected:
continue
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index 82bc59c99..54fca31b6 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -651,6 +651,7 @@ async def apply_injection_feedback(
quotes_by_session: dict[str, list[str]] = {}
verdicts: dict[str, bool] = {} # decision_id -> contradicted anywhere
+ judged: list[tuple[str, str]] = [] # (session_id, decision_id) settled here
for inj in injections:
rec = records.get(inj["decision_id"])
if rec is None:
@@ -666,7 +667,19 @@ async def apply_injection_feedback(
contradicts(decision_text, quote)[0] for quote in quotes_by_session[session_id]
)
verdicts[rec.id] = verdicts.get(rec.id, False) or contradicted
- store.mark_injection_evaluated(session_id, inj["decision_id"])
+ judged.append((session_id, inj["decision_id"]))
+
+ # Settle the ledger after the aggregation, not during it: the verdict
+ # 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. 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 in judged:
+ store.mark_injection_evaluated(
+ session_id,
+ decision_id,
+ verdict="contradicted" if verdicts.get(decision_id) else "followed",
+ )
from datetime import UTC, datetime
diff --git a/packages/core/src/repowise/core/sessions/staging.py b/packages/core/src/repowise/core/sessions/staging.py
index 237a43d24..fa954ffbc 100644
--- a/packages/core/src/repowise/core/sessions/staging.py
+++ b/packages/core/src/repowise/core/sessions/staging.py
@@ -93,6 +93,7 @@ CREATE TABLE IF NOT EXISTS injections (
chars INTEGER NOT NULL DEFAULT 0,
duration_ms INTEGER NOT NULL DEFAULT 0,
acted INTEGER NOT NULL DEFAULT 0,
+ verdict TEXT NOT NULL DEFAULT '',
PRIMARY KEY (session_id, decision_id)
);
CREATE INDEX IF NOT EXISTS idx_raw_pending ON raw_candidates(structured_key)
@@ -111,6 +112,10 @@ INJECTIONS_LEDGER_COLUMNS = (
# :mod:`repowise.core.sessions.efficacy` for how both are filled in.
("duration_ms", "INTEGER NOT NULL DEFAULT 0"),
("acted", "INTEGER NOT NULL DEFAULT 0"),
+ # How a decision injection was judged: 'followed' | 'contradicted', or ''
+ # for a row judged on some other surface, not yet judged, or evaluated
+ # before this column existed. See :meth:`decision_feedback_totals`.
+ ("verdict", "TEXT NOT NULL DEFAULT ''"),
)
@@ -545,12 +550,48 @@ class SessionStagingStore:
for r in rows
]
- def mark_injection_evaluated(self, session_id: str, decision_id: str) -> None:
+ def mark_injection_evaluated(
+ self, session_id: str, decision_id: str, *, verdict: str = ""
+ ) -> None:
+ """Settle one injection row, recording *verdict* when there is one.
+
+ A row judged with no verdict (the decision record is gone, so there is
+ nothing to judge against) is still marked evaluated so it is not
+ re-examined forever — it just doesn't count towards either side.
+ """
self._conn.execute(
- "UPDATE injections SET evaluated = 1 WHERE session_id = ? AND decision_id = ?",
- (session_id, decision_id),
+ "UPDATE injections SET evaluated = 1, verdict = ? "
+ "WHERE session_id = ? AND decision_id = ?",
+ (verdict, session_id, decision_id),
)
+ def decision_feedback_totals(self) -> dict[str, int]:
+ """Counts of decision injections by followed-vs-contradicted verdict.
+
+ Covers :data:`DECISION_SURFACES` only — the surfaces whose rows are
+ judged against the decision records rather than by the transcript
+ classifier. ``pending`` is rows awaiting the next update's judgement;
+ ``no_verdict`` is rows already settled without one — a drained orphan
+ (the decision record was gone), or a row judged before this column
+ existed. Neither is recoverable, so both are reported rather than
+ quietly folded into one of the two real verdicts.
+ """
+ placeholders = ",".join("?" * len(self.DECISION_SURFACES))
+ rows = self._conn.execute(
+ "SELECT verdict, evaluated, COUNT(*) FROM injections "
+ f"WHERE surface IN ({placeholders}) GROUP BY verdict, evaluated",
+ self.DECISION_SURFACES,
+ ).fetchall()
+ totals = {"followed": 0, "contradicted": 0, "pending": 0, "no_verdict": 0}
+ for verdict, evaluated, count in rows:
+ if verdict in ("followed", "contradicted"):
+ totals[verdict] += count
+ elif evaluated:
+ totals["no_verdict"] += count
+ else:
+ totals["pending"] += count
+ return totals
+
def correction_quotes(self, session_id: str) -> list[str]:
"""Verbatim user-correction quotes mined from one session's transcript."""
rows = self._conn.execute(
diff --git a/tests/unit/analysis/test_decision_inline_markers.py b/tests/unit/analysis/test_decision_inline_markers.py
new file mode 100644
index 000000000..fb521e91f
--- /dev/null
+++ b/tests/unit/analysis/test_decision_inline_markers.py
@@ -0,0 +1,127 @@
+"""Inline-marker decisions are attributed to the marker they came from.
+
+The scan groups every marker in a file together and hands the group to one LLM
+call. Before this, the whole group's context was joined into a single span and
+given to every decision the call returned, so the substring gate could verify a
+decision against a *different* marker's text and stamp it ``exact`` — and every
+decision inherited the first marker's line number.
+"""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+from repowise.core.analysis.decision_extractor import DecisionExtractor
+
+# The two markers sit far enough apart that their ±20-line context windows do
+# not overlap, so a span carrying the other marker's words can only have come
+# from the join this test exists to rule out.
+_FILLER = "\n".join(f" x{i} = {i}" for i in range(60))
+_SOURCE = (
+ "def connect():\n"
+ " # DECISION: pin the driver to 2.x because 3.x drops the sync API\n"
+ " return driver.connect()\n"
+ f"{_FILLER}\n"
+ "def render():\n"
+ " # DECISION: render server-side so the crawler sees the markup\n"
+ " return html\n"
+)
+_SECOND_MARKER_LINE = 65
+
+
+class _StubProvider:
+ """Returns one canned JSON payload and remembers the prompt it was given."""
+
+ def __init__(self, payload: list[dict]) -> None:
+ self._payload = payload
+ self.prompt = ""
+
+ async def generate(self, system: str, prompt: str, **kwargs: object) -> SimpleNamespace:
+ self.prompt = prompt
+ return SimpleNamespace(content=json.dumps(self._payload))
+
+
+def _write_source(tmp_path):
+ (tmp_path / "app.py").write_text(_SOURCE, encoding="utf-8")
+
+
+async def test_each_decision_is_scoped_to_its_own_marker(tmp_path):
+ _write_source(tmp_path)
+ provider = _StubProvider(
+ [
+ {
+ "marker_line": 2,
+ "title": "Pin the driver to 2.x",
+ "decision": "pin the driver to 2.x",
+ "rationale": "3.x drops the sync API",
+ },
+ {
+ "marker_line": _SECOND_MARKER_LINE,
+ "title": "Render server-side",
+ "decision": "render server-side",
+ "rationale": "so the crawler sees the markup",
+ },
+ ]
+ )
+
+ decisions = await DecisionExtractor(
+ repo_path=tmp_path, provider=provider
+ ).scan_inline_markers()
+
+ by_title = {d.title: d for d in decisions}
+ assert len(by_title) == 2
+ assert by_title["Pin the driver to 2.x"].evidence_line == 2
+ assert by_title["Render server-side"].evidence_line == _SECOND_MARKER_LINE
+ # Each span is its own marker's context, not the file's markers joined.
+ assert "crawler" not in by_title["Pin the driver to 2.x"].source_text
+ assert "sync API" not in by_title["Render server-side"].source_text
+ # The prompt has to carry the line numbers for any of this to be answerable.
+ assert "line 2" in provider.prompt
+ assert f"line {_SECOND_MARKER_LINE}" in provider.prompt
+
+
+async def test_unattributable_decision_gets_no_span_rather_than_a_neighbours(tmp_path):
+ """No usable ``marker_line`` and more than one marker: attribute nothing.
+
+ The gate then leaves the record ``unverified``, which is the honest
+ verdict. Verifying it against whichever marker happened to be first is
+ what produced rationales belonging to a different decision.
+ """
+ _write_source(tmp_path)
+ provider = _StubProvider(
+ [
+ {
+ "title": "Something the model did not locate",
+ "decision": "render server-side",
+ "rationale": "so the crawler sees the markup",
+ }
+ ]
+ )
+
+ decisions = await DecisionExtractor(
+ repo_path=tmp_path, provider=provider
+ ).scan_inline_markers()
+
+ assert len(decisions) == 1
+ assert decisions[0].evidence_line is None
+ assert decisions[0].source_text == ""
+
+
+async def test_single_marker_file_needs_no_hint(tmp_path):
+ """One marker in the file is unambiguous, hint or not."""
+ (tmp_path / "app.py").write_text(
+ "# DECISION: pin the driver to 2.x because 3.x drops the sync API\n",
+ encoding="utf-8",
+ )
+ provider = _StubProvider(
+ [{"title": "Pin the driver", "decision": "pin the driver to 2.x"}]
+ )
+
+ decisions = await DecisionExtractor(
+ repo_path=tmp_path, provider=provider
+ ).scan_inline_markers()
+
+ assert len(decisions) == 1
+ assert decisions[0].evidence_line == 1
+ assert "pin the driver" in decisions[0].source_text
diff --git a/tests/unit/persistence/test_decision_staleness_recompute.py b/tests/unit/persistence/test_decision_staleness_recompute.py
new file mode 100644
index 000000000..7c002ff31
--- /dev/null
+++ b/tests/unit/persistence/test_decision_staleness_recompute.py
@@ -0,0 +1,121 @@
+"""Staleness is scored against the repo, not against one run's change set.
+
+``recompute_decision_staleness`` is handed the git metadata the *current* run
+produced. On an incremental update that is only the files that changed in it,
+and the scorer reads a file with no entry as a file that is gone (1.00). So
+every decision over a file that simply wasn't touched went maximally stale for
+not having been touched.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.persistence.crud import recompute_decision_staleness
+from repowise.core.persistence.database import init_db
+from repowise.core.persistence.models import (
+ DecisionRecord,
+ GitMetadata,
+ Repository,
+)
+
+_REPO_ID = "repo1"
+
+
+async def session():
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with factory() as s:
+ s.add(Repository(id=_REPO_ID, name="r", local_path="/tmp/r"))
+ await s.flush()
+ yield s
+ await engine.dispose()
+
+
+async def _add_decision(session, *, files: list[str], staleness: float) -> DecisionRecord:
+ import json
+
+ rec = DecisionRecord(
+ id="d1",
+ repository_id=_REPO_ID,
+ title="Use JWT tokens",
+ decision="all service auth uses JWT tokens",
+ status="active",
+ staleness_score=staleness,
+ affected_files_json=json.dumps(files),
+ created_at=datetime.now(UTC) - timedelta(days=30),
+ )
+ session.add(rec)
+ await session.flush()
+ return rec
+
+
+async def _add_git_metadata(session, path: str, *, days_ago: int, commits: int) -> None:
+ session.add(
+ GitMetadata(
+ repository_id=_REPO_ID,
+ file_path=path,
+ commit_count_90d=commits,
+ last_commit_at=datetime.now(UTC) - timedelta(days=days_ago),
+ )
+ )
+ await session.flush()
+
+
+async def test_untouched_file_is_scored_from_persisted_metadata(session):
+ """The file is absent from this run's map but present in the index."""
+ await _add_decision(session, files=["src/untouched.py"], staleness=0.0)
+ # Last committed *before* the decision was created, so nothing has moved
+ # under it: the honest score is 0.0, not 1.00.
+ await _add_git_metadata(session, "src/untouched.py", days_ago=60, commits=1)
+
+ updated = await recompute_decision_staleness(
+ session, _REPO_ID, {"src/changed.py": {"last_commit_at": None}}
+ )
+
+ rec = await session.get(DecisionRecord, "d1")
+ assert updated == 0
+ assert rec.staleness_score == pytest.approx(0.0)
+
+
+async def test_this_runs_numbers_win_over_the_persisted_ones(session):
+ """A file in both maps is scored from the run's fresher entry."""
+ await _add_decision(session, files=["src/hot.py"], staleness=0.0)
+ await _add_git_metadata(session, "src/hot.py", days_ago=60, commits=0)
+
+ await recompute_decision_staleness(
+ session,
+ _REPO_ID,
+ {
+ "src/hot.py": {
+ "last_commit_at": datetime.now(UTC), # committed just now
+ "commit_count_90d": 30,
+ }
+ },
+ )
+
+ rec = await session.get(DecisionRecord, "d1")
+ assert rec.staleness_score > 0.5
+
+
+async def test_file_the_index_has_never_seen_still_scores_stale(session):
+ """Absent from both maps is the case the 1.00 was written for."""
+ await _add_decision(session, files=["src/deleted.py"], staleness=0.0)
+
+ updated = await recompute_decision_staleness(
+ session, _REPO_ID, {"src/changed.py": {"last_commit_at": None}}
+ )
+
+ rec = await session.get(DecisionRecord, "d1")
+ assert updated == 1
+ assert rec.staleness_score == pytest.approx(1.0)
diff --git a/tests/unit/sessions/test_injection_feedback.py b/tests/unit/sessions/test_injection_feedback.py
index 27232032d..d23327410 100644
--- a/tests/unit/sessions/test_injection_feedback.py
+++ b/tests/unit/sessions/test_injection_feedback.py
@@ -153,6 +153,47 @@ async def test_vanished_decision_row_is_drained_not_retried(session, tmp_path):
assert store.unevaluated_injections(before=_NOW) == []
+async def test_verdicts_are_kept_on_the_ledger_for_hook_stats(session, tmp_path):
+ """The followed/contradicted split survives the run that computed it.
+
+ Without a stored verdict the numbers existed only in one `update
+ --verbose` line, so `repowise hook stats` — where someone goes to ask
+ whether the layer works — had nothing to report.
+ """
+ session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))
+ await _add_decision(session, "d1", staleness=0.5)
+ await _add_decision(session, "d2", staleness=0.5)
+ _record_injection(tmp_path, "sess-1", "d1", _OLD_ENOUGH)
+ _record_injection(tmp_path, "sess-2", "d2", _OLD_ENOUGH)
+ _record_injection(tmp_path, "sess-3", "d1", _NOW - 60) # too recent to judge
+ _stage_correction(
+ tmp_path, "sess-1", "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() == {
+ "followed": 1,
+ "contradicted": 1,
+ "pending": 1,
+ "no_verdict": 0,
+ }
+
+
+async def test_drained_orphan_is_counted_as_neither_side(session, tmp_path):
+ session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))
+ await session.flush()
+ _record_injection(tmp_path, "sess-1", "gone", _OLD_ENOUGH)
+
+ 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["no_verdict"] == 1
+ assert totals["followed"] == totals["contradicted"] == 0
+
+
def test_hook_written_injections_table_is_schema_compatible(tmp_path):
"""The hook's raw CREATE TABLE and the staging schema must agree."""
from repowise.cli.commands.augment_cmd.decision_inject import _record_injections