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(hooks): stop counting an injection nothing could disagree with as followed (#1335)

Raghav Chamadiya9b8fca93428d
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/__init__.py b/packages/cli/src/repowise/cli/commands/augment_cmd/__init__.py
index fba8876a7..a2c33f686 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/__init__.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/__init__.py
@@ -8,6 +8,8 @@ Split out of a single ~1300-line module into cohesive submodules:
* :mod:`.read_state` — per-session Read/Edit read-intelligence state machine.
* :mod:`.decision_inject` — relevance-ranked standing-decision injection
(SessionStart block + edit-time governing-decision notice).
+* :mod:`.ledger` — the sessions.db efficacy ledger every surface writes to.
+* :mod:`.served_reads` — read-after-served bookkeeping (measurement only).
* :mod:`.bash_staleness` — post-git-commit stale-wiki detection.
* :mod:`.codex` — Codex lifecycle hooks.
* :mod:`.command` — the Click command, stdin dispatch, and emission dedup.
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
index af480ec81..cbe3bfbf5 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
@@ -187,7 +187,7 @@ def _count_run(cwd: str, session_id: str, event: str, tool: str, *, emitted: boo
return
try:
from ._shared import _find_repo_root
- from .decision_inject import _record_hook_run
+ from .ledger import _record_hook_run
repo_path = _find_repo_root(Path(cwd))
if repo_path is not None:
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 95964bdf9..fdb073f16 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
@@ -30,7 +30,6 @@ import contextlib
import json
import re
import sqlite3
-import time
from pathlib import Path
# --- SessionStart tunables -------------------------------------------------
@@ -437,6 +436,8 @@ def _session_decision_block(repo_path: Path, session_id: str) -> str | None:
globals_shown += 1
if not shown:
return None
+ from .ledger import _record_injections
+
_record_injections(repo_path, session_id, [d["id"] for d in shown], node_id="")
return "\n".join(lines)
@@ -523,7 +524,11 @@ def _edit_decision_notice(repo_path: Path, rel: str, session_id: str, state: dic
shown.append(decision["id"])
if session_id:
- claimed, session_total = _claim_injection(repo_path, session_id, decision["id"], rel)
+ from .ledger import _claim_injection
+
+ claimed, session_total = _claim_injection(
+ repo_path, session_id, decision["id"], rel
+ )
if not claimed or session_total > _MAX_EDIT_NOTICES:
return None
@@ -624,6 +629,7 @@ def _edit_fix_history_notice(repo_path: Path, rel: str, session_id: str) -> str
if session_id:
from ._shared import _ledger_key
+ from .ledger import _claim_ledger
claimed, shown = _claim_ledger(
repo_path,
@@ -677,234 +683,3 @@ def _top_fix_symbol(raw: object) -> str | None:
if not isinstance(counts, dict) or not counts:
return None
return str(next(iter(counts))).rsplit("::", 1)[-1] or None
-
-
-# ---------------------------------------------------------------------------
-# Injection recording (usage feedback v1)
-# ---------------------------------------------------------------------------
-
-_INJECTIONS_TABLE_SQL = (
- "CREATE TABLE IF NOT EXISTS injections ("
- "session_id TEXT NOT NULL, decision_id TEXT NOT NULL, "
- "node_id TEXT NOT NULL DEFAULT '', shown_at REAL NOT NULL, "
- "evaluated INTEGER NOT NULL DEFAULT 0, "
- "surface TEXT NOT NULL DEFAULT '', "
- "category TEXT NOT NULL DEFAULT '', "
- "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))"
-)
-
-#: Mirror of core.sessions.staging.INJECTIONS_LEDGER_COLUMNS — the hook path
-#: must not import repowise.core, so the migration is duplicated verbatim.
-_LEDGER_COLUMNS = (
- ("surface", "TEXT NOT NULL DEFAULT ''"),
- ("category", "TEXT NOT NULL DEFAULT ''"),
- ("chars", "INTEGER NOT NULL DEFAULT 0"),
- ("duration_ms", "INTEGER NOT NULL DEFAULT 0"),
- ("acted", "INTEGER NOT NULL DEFAULT 0"),
- ("verdict", "TEXT NOT NULL DEFAULT ''"),
-)
-
-
-#: One ledger connection per hook process, opened lazily. A single invocation
-#: can write several rows (two notices plus the run counter), and connect +
-#: WAL pragma + the CREATE/PRAGMA/ALTER migration is the expensive part, not
-#: the INSERT. The process is short-lived and single-threaded, so caching is
-#: safe; every writer commits, and process exit closes the handle.
-#: Keyed by repo path, not global: a hook process only ever sees one repo, but
-#: the test suite drives many through one interpreter, and a cache that
-#: ignored the path would hand the second repo the first one's database.
-_CONN: dict[Path, sqlite3.Connection | None] = {}
-
-
-def _open_injections(repo_path: Path) -> sqlite3.Connection | None:
- """The shared ledger connection, migrated and ready. None if unusable.
-
- Callers must NOT close the returned connection — see :data:`_CONN`.
- """
- if repo_path in _CONN:
- return _CONN[repo_path]
- db_path = repo_path / ".repowise" / "sessions" / "sessions.db"
- try:
- db_path.parent.mkdir(parents=True, exist_ok=True)
- conn = sqlite3.connect(db_path, timeout=1)
- conn.execute("PRAGMA journal_mode=WAL")
- conn.execute("PRAGMA busy_timeout=1000")
- conn.execute(_INJECTIONS_TABLE_SQL)
- conn.execute(_HOOK_RUNS_TABLE_SQL)
- existing = {row[1] for row in conn.execute("PRAGMA table_info(injections)")}
- for name, decl in _LEDGER_COLUMNS:
- if name not in existing:
- conn.execute(f"ALTER TABLE injections ADD COLUMN {name} {decl}")
- _CONN[repo_path] = conn
- return conn
- except (sqlite3.Error, OSError):
- _CONN[repo_path] = None
- return None
-
-
-_HOOK_RUNS_TABLE_SQL = (
- "CREATE TABLE IF NOT EXISTS hook_runs ("
- "session_id TEXT NOT NULL, event TEXT NOT NULL, tool TEXT NOT NULL, "
- "calls INTEGER NOT NULL DEFAULT 0, emitted INTEGER NOT NULL DEFAULT 0, "
- "total_ms INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (session_id, event, tool))"
-)
-
-
-def _record_hook_run(
- repo_path: Path, session_id: str, event: str, tool: str, *, emitted: bool
-) -> None:
- """Count one hook invocation and what it cost. Best-effort, never raises.
-
- Every invocation lands here, including the large majority that return
- nothing: the matcher covers Read/Edit/Write/Grep/Glob/Bash/PowerShell and
- the repowise MCP tools, and a silent run still pays the import cost. The
- harness only writes a transcript record for hooks that *emitted*, so
- without this counter the silent invocations — the bulk of the bill — are
- invisible. Aggregated per (session, event, tool) rather than one row per
- call, so the table stays small and the write stays a single upsert.
- """
- if not session_id:
- return
- from ._shared import _elapsed_ms
-
- conn = _open_injections(repo_path)
- if conn is None:
- return
- try:
- conn.execute(
- "INSERT INTO hook_runs (session_id, event, tool, calls, emitted, total_ms) "
- "VALUES (?, ?, ?, 1, ?, ?) "
- "ON CONFLICT(session_id, event, tool) DO UPDATE SET "
- "calls = calls + 1, emitted = emitted + excluded.emitted, "
- "total_ms = total_ms + excluded.total_ms",
- (session_id, event, tool, 1 if emitted else 0, _elapsed_ms()),
- )
- conn.commit()
- except sqlite3.Error:
- pass
-
-
-def _record_injections(
- repo_path: Path, session_id: str, decision_ids: list[str], *, node_id: str
-) -> None:
- """Log shown decisions in the sessions.db sidecar; best-effort, never raises.
-
- The update-time miner reads these rows to judge whether injected guidance
- was followed or contradicted (usage feedback v1). Written with raw stdlib
- sqlite3 so the hook path never imports repowise.core.
- """
- if not session_id or not decision_ids:
- return
- conn = _open_injections(repo_path)
- if conn is None:
- return
- try:
- from ._shared import _elapsed_ms
-
- now = time.time()
- elapsed = _elapsed_ms()
- conn.executemany(
- "INSERT OR IGNORE INTO injections "
- "(session_id, decision_id, node_id, shown_at, surface, category, duration_ms) "
- "VALUES (?, ?, ?, ?, 'decision', 'session_start', ?)",
- [(session_id, did, node_id, now, elapsed) for did in decision_ids],
- )
- conn.commit()
- except sqlite3.Error:
- pass
-
-
-def _claim_ledger(
- repo_path: Path,
- session_id: str,
- key: str,
- *,
- node_id: str,
- surface: str,
- category: str,
- chars: int,
-) -> tuple[bool, int]:
- """Atomically claim one non-decision ledger emission.
-
- Generic twin of :func:`_claim_injection` for the read/search enrichment
- surfaces: *key* replaces the decision id in the primary key, so INSERT OR
- IGNORE is the once-per-session-per-key gate. Returns ``(claimed,
- surface_injection_count)`` where the count covers only rows that actually
- carried text (``chars > 0``) on *surface* — pure measurement rows must not
- eat into an injection cap. Fail-closed: any error reports unclaimed.
-
- ``duration_ms`` records what this firing has cost so far (see
- :func:`_shared._elapsed_ms`); it is what ``repowise hook stats`` reports
- until a transcript pass replaces it with the harness-measured total.
- """
- from ._shared import _elapsed_ms
-
- conn = _open_injections(repo_path)
- if conn is None:
- return False, 0
- try:
- cur = conn.execute(
- "INSERT OR IGNORE INTO injections "
- "(session_id, decision_id, node_id, shown_at, surface, category, chars, "
- "duration_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
- (
- session_id,
- key,
- node_id,
- time.time(),
- surface,
- category,
- chars,
- _elapsed_ms(),
- ),
- )
- claimed = cur.rowcount > 0
- count = conn.execute(
- "SELECT COUNT(*) FROM injections WHERE session_id = ? AND surface = ? AND chars > 0",
- (session_id, surface),
- ).fetchone()[0]
- conn.commit()
- return claimed, int(count)
- except sqlite3.Error:
- return False, 0
-
-
-def _claim_injection(
- repo_path: Path, session_id: str, decision_id: str, node_id: str
-) -> tuple[bool, int]:
- """Atomically claim the right to show one decision this session.
-
- Returns ``(claimed, edit_notice_count)``. The primary key makes the
- INSERT OR IGNORE the once-per-session-per-decision gate, immune to the
- state-file races two concurrent hook processes produce; the count backs
- the strict per-session notice cap. Fail-closed: any error reports
- unclaimed, so a sidecar glitch degrades to silence, never to spam.
- """
- from ._shared import _elapsed_ms
-
- conn = _open_injections(repo_path)
- if conn is None:
- return False, 0
- try:
- cur = conn.execute(
- "INSERT OR IGNORE INTO injections "
- "(session_id, decision_id, node_id, shown_at, surface, category, duration_ms) "
- "VALUES (?, ?, ?, ?, 'decision', 'edit_notice', ?)",
- (session_id, decision_id, node_id, time.time(), _elapsed_ms()),
- )
- claimed = cur.rowcount > 0
- # Surface-scoped: read/search enrichment rows also carry a node_id and
- # must not eat into the edit-notice cap.
- count = conn.execute(
- "SELECT COUNT(*) FROM injections WHERE session_id = ? AND node_id != '' "
- "AND surface IN ('', 'decision')",
- (session_id,),
- ).fetchone()[0]
- conn.commit()
- return claimed, int(count)
- except sqlite3.Error:
- return False, 0
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/ledger.py b/packages/cli/src/repowise/cli/commands/augment_cmd/ledger.py
new file mode 100644
index 000000000..52167896c
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/ledger.py
@@ -0,0 +1,257 @@
+"""The hook path's write side of the ``sessions.db`` efficacy ledger.
+
+Every augment surface records what it showed and what it cost here, so the
+update-time miner and ``repowise hook stats`` can judge one corpus rather than
+one per surface. These helpers grew inside :mod:`decision_inject`, which owns
+only the *decision* surface, so the read, search and served-read surfaces were
+importing the shared ledger from a peer that has nothing to do with them. This
+module is that shared thing, named.
+
+Import it lazily, inside the function that writes, the way every caller here
+does. Two reasons and both are load-bearing: a hook invocation that says
+nothing must not pay for a database module it never opens, and a module-scope
+``from .ledger import x`` binds a copy that a test patching ``ledger.x`` will
+not reach — so a spy would silently miss whichever surfaces bound early.
+
+Two constraints shape everything here, and neither is negotiable:
+
+* **No ``repowise.core``.** The hook budget is 155 ms and importing the ORM
+ costs more than that on its own, so this is raw stdlib :mod:`sqlite3` and the
+ ``injections`` migration is duplicated verbatim from
+ ``core.sessions.staging`` rather than imported.
+ ``tests/unit/cli/test_augment_hook_perf.py`` asserts on the import graph.
+* **Silence over failure.** A hook must never surface an error into the agent's
+ transcript, so every function here swallows :class:`sqlite3.Error` and the
+ claim helpers fail *closed* — an unusable sidecar degrades to saying nothing,
+ never to saying it twice.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+import time
+from pathlib import Path
+
+_INJECTIONS_TABLE_SQL = (
+ "CREATE TABLE IF NOT EXISTS injections ("
+ "session_id TEXT NOT NULL, decision_id TEXT NOT NULL, "
+ "node_id TEXT NOT NULL DEFAULT '', shown_at REAL NOT NULL, "
+ "evaluated INTEGER NOT NULL DEFAULT 0, "
+ "surface TEXT NOT NULL DEFAULT '', "
+ "category TEXT NOT NULL DEFAULT '', "
+ "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))"
+)
+
+_HOOK_RUNS_TABLE_SQL = (
+ "CREATE TABLE IF NOT EXISTS hook_runs ("
+ "session_id TEXT NOT NULL, event TEXT NOT NULL, tool TEXT NOT NULL, "
+ "calls INTEGER NOT NULL DEFAULT 0, emitted INTEGER NOT NULL DEFAULT 0, "
+ "total_ms INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (session_id, event, tool))"
+)
+
+#: Mirror of core.sessions.staging.INJECTIONS_LEDGER_COLUMNS — the hook path
+#: must not import repowise.core, so the migration is duplicated verbatim.
+_LEDGER_COLUMNS = (
+ ("surface", "TEXT NOT NULL DEFAULT ''"),
+ ("category", "TEXT NOT NULL DEFAULT ''"),
+ ("chars", "INTEGER NOT NULL DEFAULT 0"),
+ ("duration_ms", "INTEGER NOT NULL DEFAULT 0"),
+ ("acted", "INTEGER NOT NULL DEFAULT 0"),
+ ("verdict", "TEXT NOT NULL DEFAULT ''"),
+)
+
+#: One ledger connection per hook process, opened lazily. A single invocation
+#: can write several rows (two notices plus the run counter), and connect +
+#: WAL pragma + the CREATE/PRAGMA/ALTER migration is the expensive part, not
+#: the INSERT. The process is short-lived and single-threaded, so caching is
+#: safe; every writer commits, and process exit closes the handle.
+#: Keyed by repo path, not global: a hook process only ever sees one repo, but
+#: the test suite drives many through one interpreter, and a cache that
+#: ignored the path would hand the second repo the first one's database.
+_CONN: dict[Path, sqlite3.Connection | None] = {}
+
+
+def _open_injections(repo_path: Path) -> sqlite3.Connection | None:
+ """The shared ledger connection, migrated and ready. None if unusable.
+
+ Callers must NOT close the returned connection — see :data:`_CONN`.
+ """
+ if repo_path in _CONN:
+ return _CONN[repo_path]
+ db_path = repo_path / ".repowise" / "sessions" / "sessions.db"
+ try:
+ db_path.parent.mkdir(parents=True, exist_ok=True)
+ conn = sqlite3.connect(db_path, timeout=1)
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("PRAGMA busy_timeout=1000")
+ conn.execute(_INJECTIONS_TABLE_SQL)
+ conn.execute(_HOOK_RUNS_TABLE_SQL)
+ existing = {row[1] for row in conn.execute("PRAGMA table_info(injections)")}
+ for name, decl in _LEDGER_COLUMNS:
+ if name not in existing:
+ conn.execute(f"ALTER TABLE injections ADD COLUMN {name} {decl}")
+ _CONN[repo_path] = conn
+ return conn
+ except (sqlite3.Error, OSError):
+ _CONN[repo_path] = None
+ return None
+
+
+def _record_hook_run(
+ repo_path: Path, session_id: str, event: str, tool: str, *, emitted: bool
+) -> None:
+ """Count one hook invocation and what it cost. Best-effort, never raises.
+
+ Every invocation lands here, including the large majority that return
+ nothing: the matcher covers Read/Edit/Write/Grep/Glob/Bash/PowerShell and
+ the repowise MCP tools, and a silent run still pays the import cost. The
+ harness only writes a transcript record for hooks that *emitted*, so
+ without this counter the silent invocations — the bulk of the bill — are
+ invisible. Aggregated per (session, event, tool) rather than one row per
+ call, so the table stays small and the write stays a single upsert.
+ """
+ if not session_id:
+ return
+ from ._shared import _elapsed_ms
+
+ conn = _open_injections(repo_path)
+ if conn is None:
+ return
+ try:
+ conn.execute(
+ "INSERT INTO hook_runs (session_id, event, tool, calls, emitted, total_ms) "
+ "VALUES (?, ?, ?, 1, ?, ?) "
+ "ON CONFLICT(session_id, event, tool) DO UPDATE SET "
+ "calls = calls + 1, emitted = emitted + excluded.emitted, "
+ "total_ms = total_ms + excluded.total_ms",
+ (session_id, event, tool, 1 if emitted else 0, _elapsed_ms()),
+ )
+ conn.commit()
+ except sqlite3.Error:
+ pass
+
+
+def _record_injections(
+ repo_path: Path, session_id: str, decision_ids: list[str], *, node_id: str
+) -> None:
+ """Log shown decisions in the sessions.db sidecar; best-effort, never raises.
+
+ The update-time miner reads these rows to judge whether injected guidance
+ was followed or contradicted (usage feedback v1). Written with raw stdlib
+ sqlite3 so the hook path never imports repowise.core.
+ """
+ if not session_id or not decision_ids:
+ return
+ conn = _open_injections(repo_path)
+ if conn is None:
+ return
+ try:
+ from ._shared import _elapsed_ms
+
+ now = time.time()
+ elapsed = _elapsed_ms()
+ conn.executemany(
+ "INSERT OR IGNORE INTO injections "
+ "(session_id, decision_id, node_id, shown_at, surface, category, duration_ms) "
+ "VALUES (?, ?, ?, ?, 'decision', 'session_start', ?)",
+ [(session_id, did, node_id, now, elapsed) for did in decision_ids],
+ )
+ conn.commit()
+ except sqlite3.Error:
+ pass
+
+
+def _claim_ledger(
+ repo_path: Path,
+ session_id: str,
+ key: str,
+ *,
+ node_id: str,
+ surface: str,
+ category: str,
+ chars: int,
+) -> tuple[bool, int]:
+ """Atomically claim one non-decision ledger emission.
+
+ Generic twin of :func:`_claim_injection` for the read/search enrichment
+ surfaces: *key* replaces the decision id in the primary key, so INSERT OR
+ IGNORE is the once-per-session-per-key gate. Returns ``(claimed,
+ surface_injection_count)`` where the count covers only rows that actually
+ carried text (``chars > 0``) on *surface* — pure measurement rows must not
+ eat into an injection cap. Fail-closed: any error reports unclaimed.
+
+ ``duration_ms`` records what this firing has cost so far (see
+ :func:`_shared._elapsed_ms`); it is what ``repowise hook stats`` reports
+ until a transcript pass replaces it with the harness-measured total.
+ """
+ from ._shared import _elapsed_ms
+
+ conn = _open_injections(repo_path)
+ if conn is None:
+ return False, 0
+ try:
+ cur = conn.execute(
+ "INSERT OR IGNORE INTO injections "
+ "(session_id, decision_id, node_id, shown_at, surface, category, chars, "
+ "duration_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ session_id,
+ key,
+ node_id,
+ time.time(),
+ surface,
+ category,
+ chars,
+ _elapsed_ms(),
+ ),
+ )
+ claimed = cur.rowcount > 0
+ count = conn.execute(
+ "SELECT COUNT(*) FROM injections WHERE session_id = ? AND surface = ? AND chars > 0",
+ (session_id, surface),
+ ).fetchone()[0]
+ conn.commit()
+ return claimed, int(count)
+ except sqlite3.Error:
+ return False, 0
+
+
+def _claim_injection(
+ repo_path: Path, session_id: str, decision_id: str, node_id: str
+) -> tuple[bool, int]:
+ """Atomically claim the right to show one decision this session.
+
+ Returns ``(claimed, edit_notice_count)``. The primary key makes the
+ INSERT OR IGNORE the once-per-session-per-decision gate, immune to the
+ state-file races two concurrent hook processes produce; the count backs
+ the strict per-session notice cap. Fail-closed: any error reports
+ unclaimed, so a sidecar glitch degrades to silence, never to spam.
+ """
+ from ._shared import _elapsed_ms
+
+ conn = _open_injections(repo_path)
+ if conn is None:
+ return False, 0
+ try:
+ cur = conn.execute(
+ "INSERT OR IGNORE INTO injections "
+ "(session_id, decision_id, node_id, shown_at, surface, category, duration_ms) "
+ "VALUES (?, ?, ?, ?, 'decision', 'edit_notice', ?)",
+ (session_id, decision_id, node_id, time.time(), _elapsed_ms()),
+ )
+ claimed = cur.rowcount > 0
+ # Surface-scoped: read/search enrichment rows also carry a node_id and
+ # must not eat into the edit-notice cap.
+ count = conn.execute(
+ "SELECT COUNT(*) FROM injections WHERE session_id = ? AND node_id != '' "
+ "AND surface IN ('', 'decision')",
+ (session_id,),
+ ).fetchone()[0]
+ conn.commit()
+ return claimed, int(count)
+ except sqlite3.Error:
+ return False, 0
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py b/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py
index d996a2748..7be9d4b20 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py
@@ -466,7 +466,7 @@ def _log_read_firing(
if not session_id:
return
from ._shared import _ledger_key
- from .decision_inject import _claim_ledger
+ from .ledger import _claim_ledger
_claim_ledger(
repo_path,
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/search.py b/packages/cli/src/repowise/cli/commands/augment_cmd/search.py
index 0fa36ac10..635484cc8 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/search.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/search.py
@@ -263,7 +263,7 @@ def _log_search_firing(
if not session_id:
return
from ._shared import _ledger_key
- from .decision_inject import _claim_ledger
+ from .ledger import _claim_ledger
_claim_ledger(
repo_path,
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py b/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py
index 8981169fd..703f33201 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py
@@ -27,7 +27,6 @@ import json
from pathlib import Path
from ._shared import _find_repo_root, _relativize
-from .decision_inject import _claim_ledger
_SERVED_COVERAGE = 0.8 # served share of a Read window that counts as covered
_MAX_SERVED_FILES = 50 # served-range bookkeeping caps (state-file hygiene)
@@ -65,6 +64,8 @@ def _log_read_after_served(
return
start, end = window
if _served_covers(repo_path, session_id, rel, start, end):
+ from .ledger import _claim_ledger
+
_claim_ledger(
repo_path,
session_id,
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index 2cac00921..73524135c 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -630,13 +630,17 @@ def hook_stats(path: str | None, as_json: bool) -> None:
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]")
+ parts.append(
+ f"[dim]{feedback['no_verdict']} unjudged, mostly for want of "
+ "anything to judge them against[/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]"
+ f" [dim]{pct:.0f}% of judged injections were followed. Judged means the "
+ "session mined a correction that could have disagreed; the rest are "
+ "counted nowhere.[/dim]"
)
if session_totals:
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index f217dec05..1e7c959b4 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -93,8 +93,24 @@ __all__ = [
# session of memory; a false one pollutes the record for every future session.
# ---------------------------------------------------------------------------
-#: A user message opening with one of these reads as pushback on what the
-#: agent just did or proposed. Matched at the start of the message only.
+#: A sentence opening with one of these reads as pushback on what the agent
+#: just did or proposed. Matched at the start of any *sentence*, not only at
+#: the start of the message: measured over this machine's 436 transcripts,
+#: requiring the whole message to open with a lead finds 62 corrections while
+#: the same list at sentence start finds 249, and the gap is not noise. Over
+#: the two days before this was written the message-start form found **zero**
+#: while pushback language stayed at its long-run density (19.3% of messages
+#: contain a lead somewhere, against 20.1% before), because a correction
+#: increasingly arrives as one sentence inside a longer brief rather than as
+#: a short reply that opens with it. A gate that only sees the short reply
+#: reports "no corrections" for a corpus full of them, which is worse than
+#: reporting none: :func:`apply_injection_feedback` reads silence here as
+#: "followed".
+#:
+#: ``actually`` is deliberately absent. It is the one lead that does not
+#: survive the move — at message start it read as a reversal, but mid-message
+#: half its hits are narrative ("actually produces.", "actually does now.")
+#: rather than pushback, and 11 corpus hits do not pay for that.
PUSHBACK_LEADS: tuple[str, ...] = (
"no,",
"no.",
@@ -114,8 +130,6 @@ PUSHBACK_LEADS: tuple[str, ...] = (
"revert",
"instead",
"never ",
- "actually,",
- "actually ",
)
#: A sentence needs one of these to read as a choice being made (paired with
@@ -175,7 +189,31 @@ class SessionCandidate:
@property
def hash(self) -> str:
- """Content identity for staging dedup (kind + normalized quotes)."""
+ """Content identity for staging dedup (kind + normalized quotes).
+
+ Deliberately session-independent: ``add_raw`` is INSERT OR IGNORE on
+ this, so one quote is structured by the LLM once however many sessions
+ produced it.
+
+ **Known ceiling, and it arrived with sentence-level corrections.**
+ ``raw_candidates`` keeps one ``session_id`` per hash — the first — so a
+ repeated correction is bound to the session that said it first and
+ :meth:`~SessionStagingStore.correction_quotes` returns nothing for the
+ rest. Whole-message quotes almost never repeated, so this cost nothing
+ before; sentence quotes do repeat, and they repeat precisely on the
+ standing rules ("No em dashes.", "Do NOT branch off stale local main.")
+ that are the most likely to contradict an injected decision. Measured
+ over 436 transcripts: 14 of 249 corrections dropped, 5 of 185 sessions
+ losing their only one, and it is a **ratchet** — :meth:`prune` only
+ drops rows that were never structured, so one structured correction
+ blocks that sentence for every future session. It fails safe rather
+ than wrong — those sessions become unjudgeable rather than falsely
+ "followed" — which is why this is a note and not a fix, and why
+ :meth:`~SessionStagingStore.retire_unjudgeable_verdicts` runs once
+ rather than perpetually. The upgrade is a raw-to-session association rather
+ than a session-scoped hash: the ``decisions`` table already carries a
+ ``sessions`` list for the promoted row, and the raw row wants the same.
+ """
norm = " ".join(" ".join(q.lower().split()) for q in self.quotes)
return hashlib.sha256(f"{self.kind}|{norm}".encode()).hexdigest()[:16]
@@ -198,15 +236,46 @@ def _interrupt_guidance(text: str) -> str:
return "\n".join(lines).strip()
-def _correction_quote(event: Event) -> str | None:
- """The verbatim correction text, or None when the gate does not fire."""
+def _pushback_sentences(text: str) -> list[str]:
+ """Sentences that open with a pushback lead, verbatim, capped at two.
+
+ Scans sentences rather than the message so a correction buried in a longer
+ brief still counts — see :data:`PUSHBACK_LEADS` for the measurement that
+ forced this. Returns the sentences alone, not the message around them,
+ which is also what the one consumer wants: :func:`apply_injection_feedback`
+ feeds these to ``contradicts()`` against a single decision statement, and a
+ 600-character brief with one contradicting clause in it is a worse input
+ to that comparison than the clause.
+
+ **Two rather than one, and the second is not a bonus.** Of the messages
+ this gate newly catches, 89 of 221 carry more than one lead sentence, and
+ the gate's precision is roughly 75% — the residue is declarative rather
+ than directive ("No releases yet.", "No prose job has ever run in
+ production."), which no cheap rule separates from the directive form it is
+ identical to ("No Claude attribution in commits.", "No em dashes."). A
+ lead-list narrow enough to exclude the first excludes the second: dropping
+ bare "no" mid-message costs 119 of 398 sentences and takes the standing
+ rules with it. So the residue is accepted and the *first-match* rule is
+ what gets fixed — taking one sentence would let a declarative opener
+ discard the real correction behind it, which the whole-message quote never
+ did.
+ """
+ out: list[str] = []
+ for sentence in _SENTENCE_SPLIT_RE.split(text):
+ sentence = sentence.strip()
+ if len(sentence) >= 12 and sentence.lower().startswith(PUSHBACK_LEADS):
+ out.append(_clip(sentence))
+ if len(out) == _MAX_QUOTES_PER_EVENT:
+ break
+ return out
+
+
+def _correction_quotes(event: Event) -> list[str]:
+ """The verbatim correction text, or empty when the gate does not fire."""
if event.interrupted:
guidance = _interrupt_guidance(event.text)
- return _clip(guidance) if len(guidance) >= 8 else None
- low = event.text.strip().lower()
- if len(low) >= 12 and low.startswith(PUSHBACK_LEADS):
- return _clip(event.text)
- return None
+ return [_clip(guidance)] if len(guidance) >= 8 else []
+ return _pushback_sentences(event.text)
def _choice_sentences(text: str) -> list[str]:
@@ -346,18 +415,23 @@ def mine_events(events: Iterable[Event], repo_prefix: str) -> list[SessionCandid
continue
if is_prose_user_text(event):
- quote = _correction_quote(event)
- if quote is not None:
+ quotes = _correction_quotes(event)
+ if quotes:
_add(
SessionCandidate(
kind="user_correction",
- quotes=[quote],
+ quotes=quotes,
files=list(dict.fromkeys(trailing_files)),
session_id=event.session_id,
ts=event.ts,
)
)
- continue
+ # Deliberately falls through to the choice gate rather than
+ # skipping it. Skipping was harmless while a correction was a
+ # short reply that was *only* a correction; now that one lead
+ # sentence inside a long brief fires this gate, a `continue`
+ # silently costs the brief its explicit choices — measured at
+ # 22 candidates over this corpus.
# Explicit choices: user prose or main-thread assistant prose.
if event.text and not event.is_meta and not event.is_compact_summary:
@@ -589,10 +663,24 @@ async def apply_injection_feedback(
about whether the governed files moved, and a per-machine session verdict
may not overwrite a value the dashboard and hosted both read.
+ **A decision no session could have contradicted is not "followed".**
+ "Followed" was the else branch of the contradiction test, so a corpus in
+ which the two halves never meet reported a perfect score from an
+ instrument that had no opportunity to fire. Measured on this machine
+ before the change: 100 followed, 0 contradicted, and *zero* of those 100
+ rows came from a session holding any mined correction at all. Those rows
+ are now settled with no verdict — the ``no_verdict`` bucket
+ :meth:`~SessionStagingStore.decision_feedback_totals` already reports —
+ so the followed rate is computed over injections that were genuinely
+ judgeable. It reads as a much smaller number, and that is the point.
+
Deliberately binary for v1 (followed / contradicted); the
followed-vs-ignored split and relevance decay are the validation-gated
backlog item that rides on this data. Returns
- ``{"followed": n, "contradicted": n}``.
+ ``{"followed": n, "contradicted": n, "unjudgeable": n}``, counted over
+ **ledger rows** so it reconciles with
+ :meth:`~SessionStagingStore.decision_feedback_totals` rather than
+ disagreeing with it by a factor of however many sessions saw a decision.
"""
import time
@@ -602,10 +690,25 @@ async def apply_injection_feedback(
from repowise.core.persistence.models import DecisionRecord
ts = now if now is not None else time.time()
- summary = {"followed": 0, "contradicted": 0}
+ summary = {"followed": 0, "contradicted": 0, "unjudgeable": 0}
store = SessionStagingStore.open_default(Path(repo_path).resolve())
try:
+ # Before judging anything new, retire the verdicts an older version
+ # awarded for free. Those rows are already evaluated, so this pass
+ # would never reach them otherwise and the reported rate would stay
+ # pinned at whatever the else branch produced.
+ retired = store.retire_unjudgeable_verdicts()
+ # 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
+ # judge, and the repair re-arms itself — so 90 days later, once
+ # 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)
+
injections = store.unevaluated_injections(before=ts - INJECTION_EVAL_MIN_AGE_SECONDS)
if not injections:
return summary
@@ -621,7 +724,13 @@ 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
+ #: (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]] = []
for inj in injections:
rec = records.get(inj["decision_id"])
if rec is None:
@@ -632,33 +741,41 @@ async def apply_injection_feedback(
session_id = inj["session_id"]
if session_id not in quotes_by_session:
quotes_by_session[session_id] = store.correction_quotes(session_id)
+ quotes = quotes_by_session[session_id]
decision_text = f"{rec.title}. {rec.decision}"
- contradicted = any(
- contradicts(decision_text, quote)[0] for quote in quotes_by_session[session_id]
- )
+ 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"]))
+ judged.append((session_id, inj["decision_id"], bool(quotes)))
# 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:
+ # *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:
+ if not judgeable:
+ # Settled, so it is not re-read every update, but with no
+ # verdict: this session mined nothing that could have
+ # disagreed, so neither verdict is a claim the data supports.
+ store.mark_injection_evaluated(session_id, decision_id)
+ summary["unjudgeable"] += 1
+ continue
+ contradicted = bool(verdicts.get(decision_id))
store.mark_injection_evaluated(
session_id,
decision_id,
- verdict="contradicted" if verdicts.get(decision_id) else "followed",
+ verdict="contradicted" if contradicted else "followed",
)
-
- for contradicted in verdicts.values():
summary["contradicted" if contradicted else "followed"] += 1
store.commit()
finally:
store.close()
- if summary["followed"] or summary["contradicted"]:
+ if any(summary.values()):
logger.info("session_mining.injection_feedback", **summary)
return summary
diff --git a/packages/core/src/repowise/core/sessions/staging.py b/packages/core/src/repowise/core/sessions/staging.py
index fa954ffbc..f0139fb46 100644
--- a/packages/core/src/repowise/core/sessions/staging.py
+++ b/packages/core/src/repowise/core/sessions/staging.py
@@ -41,6 +41,12 @@ SESSIONS_DB_FILENAME = "sessions.db"
#: backlog would grow the batched LLM pass forever.
RAW_TTL_DAYS = 90.0
+#: ``PRAGMA user_version`` marking that :meth:`retire_unjudgeable_verdicts`
+#: has run on this store. A one-shot data repair, not a schema migration, so
+#: it rides the pragma rather than a table: the hook path opens this same
+#: database with raw sqlite3 and must not learn about a new one.
+_VERDICT_REPAIR_VERSION = 1
+
#: Cap on the distinct session ids tracked per structured decision. Two is
#: enough to promote; beyond a handful the extra ids only pad evidence.
_MAX_SESSIONS_TRACKED = 20
@@ -565,16 +571,56 @@ class SessionStagingStore:
(verdict, session_id, decision_id),
)
+ def retire_unjudgeable_verdicts(self) -> int:
+ """Drop ``followed`` from rows nothing could have contradicted.
+
+ ``followed`` used to be the else branch of the contradiction test, so
+ every injection into a session with no mined correction earned one for
+ free, and those rows are already ``evaluated`` — the live judgement
+ never reads them again. Without this the reported rate stays pinned at
+ whatever the else branch produced, which on this machine was all 106
+ of them at 100%.
+
+ **Runs exactly once per store**, gated on ``PRAGMA user_version``
+ rather than repeated every pass, and that is not a cost decision. The
+ test it applies — the showing session mined no ``user_correction`` —
+ is only true-forever for rows written under the old rule. Run
+ perpetually it would also retire *earned* verdicts, on two paths: as
+ :data:`RAW_TTL_DAYS` prunes the corrections that justified them, and
+ as a session's only correction turns out to be a repeat of one already
+ staged under another session (see ``SessionCandidate.hash``). Either
+ way a real "followed" would decay to no-verdict and the rate would
+ understate itself a little more each quarter. Returns the number of
+ rows retired, and 0 on a store that has already had it.
+ """
+ if self._conn.execute("PRAGMA user_version").fetchone()[0] >= _VERDICT_REPAIR_VERSION:
+ return 0
+ placeholders = ",".join("?" * len(self.DECISION_SURFACES))
+ cur = self._conn.execute(
+ f"UPDATE injections SET verdict = '' WHERE surface IN ({placeholders}) "
+ "AND verdict = 'followed' AND NOT EXISTS ("
+ "SELECT 1 FROM raw_candidates rc WHERE rc.session_id = injections.session_id "
+ "AND rc.kind = 'user_correction')",
+ self.DECISION_SURFACES,
+ )
+ # PRAGMA takes no parameters, hence the interpolation of an int constant.
+ self._conn.execute(f"PRAGMA user_version = {_VERDICT_REPAIR_VERSION}")
+ return cur.rowcount or 0
+
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.
+ ``no_verdict`` is rows already settled without one — most of them
+ injections no session could have disagreed with, because no correction
+ was mined from any session that saw them (see
+ :func:`~repowise.core.sessions.miners.decisions.apply_injection_feedback`),
+ plus a drained orphan (the decision record was gone) or a row judged
+ before this column existed. None of it is recoverable, so all of it is
+ reported rather than quietly folded into one of the two real verdicts,
+ which is exactly how the followed rate came to read 100%.
"""
placeholders = ",".join("?" * len(self.DECISION_SURFACES))
rows = self._conn.execute(
diff --git a/tests/unit/cli/test_augment_served_reads.py b/tests/unit/cli/test_augment_served_reads.py
index e09a1bc26..fd4699fc9 100644
--- a/tests/unit/cli/test_augment_served_reads.py
+++ b/tests/unit/cli/test_augment_served_reads.py
@@ -14,7 +14,7 @@ import sqlite3
from pathlib import Path
from repowise.cli.commands.augment_cmd import served_reads
-from repowise.cli.commands.augment_cmd.decision_inject import _claim_ledger
+from repowise.cli.commands.augment_cmd.ledger import _claim_ledger
from repowise.cli.commands.augment_cmd.search import _log_search_firing
_TARGET = "src/core/models.py"
diff --git a/tests/unit/sessions/test_decision_miner.py b/tests/unit/sessions/test_decision_miner.py
index 08161b04a..77a2eed49 100644
--- a/tests/unit/sessions/test_decision_miner.py
+++ b/tests/unit/sessions/test_decision_miner.py
@@ -71,6 +71,76 @@ def test_short_pushback_is_skipped():
assert mine_events([_user("no")], REPO_PREFIX) == []
+def test_pushback_inside_a_longer_brief_is_a_correction():
+ """The gate scans sentences, not just the opening of the message.
+
+ Measured over 436 transcripts: requiring the whole message to open with a
+ lead found 62 corrections and, over the two most recent days, zero — while
+ pushback language held its long-run density. A correction now usually
+ arrives as one sentence inside a longer brief.
+ """
+ events = [
+ _user(
+ "Work on the hook track next session. Do not run uv sync in the "
+ "worktree, it triggers a numpy source build. Then open the PR."
+ )
+ ]
+ (candidate,) = mine_events(events, REPO_PREFIX)
+ assert candidate.kind == "user_correction"
+ assert candidate.quotes == [
+ "Do not run uv sync in the worktree, it triggers a numpy source build."
+ ]
+
+
+def test_correction_quote_is_the_sentence_not_the_message():
+ """``contradicts()`` compares one statement; give it one statement."""
+ events = [_user("Some preamble that sets up the task. Never run ruff format here.")]
+ (candidate,) = mine_events(events, REPO_PREFIX)
+ assert candidate.quotes == ["Never run ruff format here."]
+
+
+def test_actually_is_not_a_pushback_lead():
+ """Mid-message it is narrative as often as reversal; see PUSHBACK_LEADS.
+
+ Opens with the lead, so it fails the moment "actually" goes back on the
+ list — which the weaker phrasing of this test did not.
+ """
+ events = [_user("Actually, that produces the right total after all.")]
+ assert [c for c in mine_events(events, REPO_PREFIX) if c.kind == "user_correction"] == []
+
+
+def test_a_brief_that_corrects_still_yields_its_explicit_choices():
+ """The correction gate must not swallow the rest of a long message.
+
+ Skipping the choice gate was harmless while a correction was a short reply
+ that was only a correction; one lead sentence inside a brief is not.
+ """
+ events = [
+ _tool_call("Edit", {"file_path": f"{CWD}\\svc.py"}),
+ _user(
+ "Do not use the shared pool here. We went with per-request sessions "
+ "because the pool leaks under the test runner."
+ ),
+ ]
+ kinds = _kinds(mine_events(events, REPO_PREFIX))
+ assert "user_correction" in kinds
+ assert "explicit_choice" in kinds
+
+
+def test_two_corrections_in_one_message_are_both_quoted():
+ """One declarative opener must not discard the real correction behind it."""
+ events = [
+ _user(
+ "No releases yet. Never run the formatter here, CI only checks lint."
+ )
+ ]
+ (candidate,) = mine_events(events, REPO_PREFIX)
+ assert candidate.quotes == [
+ "No releases yet.",
+ "Never run the formatter here, CI only checks lint.",
+ ]
+
+
def test_meta_compact_sidechain_and_tag_text_skipped():
events = [
_user("Don't ever do that again, use the helper because it exists", is_meta=True),
diff --git a/tests/unit/sessions/test_injection_feedback.py b/tests/unit/sessions/test_injection_feedback.py
index 7fd7d2751..efab61e77 100644
--- a/tests/unit/sessions/test_injection_feedback.py
+++ b/tests/unit/sessions/test_injection_feedback.py
@@ -2,8 +2,10 @@
The augment hooks record shown-decision ids in the staging sidecar; at update
time the miner replays each showing session's mined user corrections against
-the decision text. Contradiction bumps staleness (the evolution 'amended'
-move), silence relaxes it (the 'reaffirmed' move), and every row is judged at
+the decision text. Contradiction is a verdict, and so is silence — but only
+where a correction existed to be silent about. An injection no session could
+have disagreed with is settled with no verdict, because counting it as
+followed is what made the followed rate read 100%. Every row is judged at
most once.
"""
@@ -86,14 +88,21 @@ def _stage_correction(repo_root, session_id: str, quote: str) -> None:
store.commit()
-async def test_uncontradicted_injection_counts_as_followed(session, tmp_path):
+async def test_injection_no_session_could_disagree_with_is_not_followed(session, tmp_path):
+ """Silence is not agreement when nothing was ever mined to disagree with.
+
+ "Followed" is the else branch of the contradiction test, so a session with
+ no mined correction used to produce one for free. On this machine that
+ read as 100 followed / 0 contradicted, with zero of the 100 coming from a
+ session that held any correction at all.
+ """
session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))
await _add_decision(session, "d1", staleness=0.5)
_record_injection(tmp_path, "sess-1", "d1", _OLD_ENOUGH)
summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)
- assert summary == {"followed": 1, "contradicted": 0}
+ assert summary == {"followed": 0, "contradicted": 0, "unjudgeable": 1}
# The verdict lands on the injection ledger and nowhere else. It used to
# also relax the record's staleness, which is now a measured fact about
# whether the governed files moved — a per-machine session verdict may not
@@ -101,9 +110,11 @@ async def test_uncontradicted_injection_counts_as_followed(session, tmp_path):
rec = await session.get(DecisionRecord, "d1")
assert rec.staleness_score == pytest.approx(0.5)
- # Judged once: a second pass finds nothing unevaluated.
+ # Settled all the same, so it is not re-read on every future update.
again = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)
- assert again == {"followed": 0, "contradicted": 0}
+ assert again == {"followed": 0, "contradicted": 0, "unjudgeable": 0}
+ with SessionStagingStore(default_store_path(tmp_path)) as store:
+ assert store.decision_feedback_totals()["no_verdict"] == 1
async def test_contradicting_correction_is_recorded_without_touching_staleness(
@@ -118,7 +129,7 @@ async def test_contradicting_correction_is_recorded_without_touching_staleness(
summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)
- assert summary == {"followed": 0, "contradicted": 1}
+ assert summary == {"followed": 0, "contradicted": 1, "unjudgeable": 0}
# Contradiction is a judgement about the record; staleness is a fact about
# the code. The first no longer writes the second.
rec = await session.get(DecisionRecord, "d1")
@@ -132,7 +143,7 @@ async def test_unrelated_correction_still_counts_as_followed(session, tmp_path):
_stage_correction(tmp_path, "sess-1", "no, format the changelog with bullet points please")
summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)
- assert summary == {"followed": 1, "contradicted": 0}
+ assert summary == {"followed": 1, "contradicted": 0, "unjudgeable": 0}
async def test_recent_injection_is_not_judged_yet(session, tmp_path):
@@ -142,7 +153,7 @@ async def test_recent_injection_is_not_judged_yet(session, tmp_path):
summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)
- assert summary == {"followed": 0, "contradicted": 0}
+ assert summary == {"followed": 0, "contradicted": 0, "unjudgeable": 0}
rec = await session.get(DecisionRecord, "d1")
assert rec.staleness_score == pytest.approx(0.5) # untouched
with SessionStagingStore(default_store_path(tmp_path)) as store:
@@ -156,11 +167,91 @@ async def test_vanished_decision_row_is_drained_not_retried(session, tmp_path):
summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)
- assert summary == {"followed": 0, "contradicted": 0}
+ assert summary == {"followed": 0, "contradicted": 0, "unjudgeable": 0}
with SessionStagingStore(default_store_path(tmp_path)) as store:
assert store.unevaluated_injections(before=_NOW) == []
+async def test_a_free_followed_verdict_from_an_older_ledger_is_retired(session, tmp_path):
+ """Rows an older version judged are already evaluated; nothing re-reads them.
+
+ So the repair has to reach backwards, or `hook stats` keeps reporting the
+ rate the else branch produced — 100% here — forever.
+ """
+ session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))
+ await _add_decision(session, "d1")
+ await _add_decision(session, "d2")
+ _record_injection(tmp_path, "sess-1", "d1", _OLD_ENOUGH)
+ _record_injection(tmp_path, "sess-2", "d2", _OLD_ENOUGH)
+ _stage_correction(tmp_path, "sess-2", "no, put the changelog in reverse order")
+ with SessionStagingStore(default_store_path(tmp_path)) as store:
+ for sid, did in (("sess-1", "d1"), ("sess-2", "d2")):
+ store.mark_injection_evaluated(sid, did, verdict="followed")
+ store.commit()
+
+ 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()
+ # sess-2's verdict stands: a correction existed and did not disagree.
+ assert totals == {"followed": 1, "contradicted": 0, "pending": 0, "no_verdict": 1}
+
+
+async def test_one_judgeable_session_does_not_vouch_for_the_others(session, tmp_path):
+ """Judgeability is per row; the totals count rows, so this is the whole point.
+
+ A decision shown to twenty sessions, one of which happened to hold a
+ correction, would otherwise book twenty followed verdicts off one session's
+ evidence — the same free-verdict bug one level up.
+ """
+ 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, put the changelog in reverse order")
+
+ summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)
+
+ assert summary == {"followed": 1, "contradicted": 0, "unjudgeable": 1}
+ with SessionStagingStore(default_store_path(tmp_path)) as store:
+ assert store.decision_feedback_totals() == {
+ "followed": 1,
+ "contradicted": 0,
+ "pending": 0,
+ "no_verdict": 1,
+ }
+
+
+async def test_the_verdict_repair_does_not_run_twice(session, tmp_path):
+ """Once is a repair; every pass would eat earned verdicts as raws expire.
+
+ The test it applies is only true-forever for rows written under the old
+ rule. Left running, `RAW_TTL_DAYS` pruning a correction would retire the
+ verdict it had justified, so every real "followed" decays at 90 days.
+ """
+ session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))
+ await _add_decision(session, "d1")
+ _record_injection(tmp_path, "sess-1", "d1", _OLD_ENOUGH)
+ _stage_correction(tmp_path, "sess-1", "no, put the changelog in reverse order")
+
+ 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
+ # The correction ages out; the verdict it earned must survive it.
+ store._conn.execute("DELETE FROM raw_candidates")
+ store.commit()
+ assert store.retire_unjudgeable_verdicts() == 0
+ assert store.decision_feedback_totals()["followed"] == 1
+
+ # And the mark is durable across processes, not just within this one.
+ # It is written on the pass that retires nothing too, or the repair
+ # re-arms and fires once RAW_TTL_DAYS prunes what justified a verdict.
+ 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
+
+
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.
@@ -174,18 +265,21 @@ async def test_verdicts_are_kept_on_the_ledger_for_hook_stats(session, tmp_path)
_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
+ _record_injection(tmp_path, "sess-4", "d3", _OLD_ENOUGH) # nothing to judge it against
+ await _add_decision(session, "d3", staleness=0.5)
_stage_correction(
tmp_path, "sess-1", "no, stop using JWT tokens for service auth, revert to sessions"
)
+ _stage_correction(tmp_path, "sess-2", "no, put the changelog in reverse order")
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,
+ "followed": 1, # d2: a correction existed and did not disagree
+ "contradicted": 1, # d1
+ "pending": 1, # d1 again, shown too recently in sess-3
+ "no_verdict": 1, # d3: sess-4 mined no correction at all
}
@@ -204,7 +298,7 @@ async def test_drained_orphan_is_counted_as_neither_side(session, tmp_path):
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
+ from repowise.cli.commands.augment_cmd.ledger import _record_injections
# Hook writes first (cold sidecar), store opens the same DB afterwards.
_record_injections(tmp_path, "sess-1", ["d1"], node_id="src/a.py")