Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat: relevance-ranked decision delivery, SessionStart + edit-time injection with usage feedback (#776)
Raghav Chamadiyae3fd88badfa3
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.mdindex faac80593..f0e9f307b 100644--- a/docs/CLI_REFERENCE.md+++ b/docs/CLI_REFERENCE.md@@ -987,7 +987,7 @@ repowise delete <repo-id> --force # delete a specific repo's index, no pr### `repowise augment`-Hook-driven context enrichment engine. Not meant to be called manually, invoked by Claude Code and Codex hooks installed during `repowise init`. Claude Code uses it for search-result enrichment and stale-wiki checks; Codex uses it for `SessionStart`, `UserPromptSubmit`, and `PostToolUse` lifecycle guidance.+Hook-driven context enrichment engine. Not meant to be called manually, invoked by Claude Code and Codex hooks installed during `repowise init`. Claude Code uses it for search-result enrichment, stale-wiki checks, and decision injection: session start gets the standing decisions relevant to the session's working set (relevance-ranked, hard token cap, silent when nothing clears the floor), and editing a governed file gets a one-line "governed by" notice once per session per decision. Codex uses it for `SessionStart`, `UserPromptSubmit`, and `PostToolUse` lifecycle guidance. Shown decisions are recorded in `.repowise/sessions/sessions.db` so the next `repowise update` can judge whether the guidance was followed or contradicted and adjust decision staleness.### `repowise-augment` / `repowise-rewrite`diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex e1eb5fd2e..b0a759e33 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -863,14 +863,23 @@ Wiki is stale, run `repowise update` to refreshThis ensures agents are never silently working from outdated documentation.+#### Decision injection, relevance-ranked++The decision layer reaches the agent at the two moments it matters, with no LLM calls and indexed SQLite lookups only:++- **Session start.** Repowise scores the repo's active decisions against the session's likely working set: dirty and staged files, files changed on the branch vs main, the previous session's edited files, and branch-name tokens, expanded one hop through import edges and co-change partners. The top few land in a compact block under a hard ~400-token cap. Nothing clears the relevance floor, nothing is injected; decisions are never injected just for being high-confidence. Repo-wide rules mined from your own corrections (see session decision mining in the CLI reference) are the exception: they apply everywhere, so they compete at a flat base relevance.+- **Edit time.** When the agent edits a file governed by a decision (via `decision_node_links`), it gets a one-line "governed by" notice with the rationale, once per session per decision and at most a few times per session.++Injected decision ids are recorded locally in `.repowise/sessions/sessions.db`. On the next `repowise update`, the session miner checks whether the guidance was followed or contradicted by your corrections in that session, relaxing or bumping the decision's staleness accordingly, so guidance that stops being true stops being injected.+### ConfigurationClaude Code hooks are written to `~/.claude/settings.json` automatically during `repowise init`. Codex hooks are written to `.codex/hooks.json` by `repowise init --codex`.| Hook type | Matcher | Action ||-----------|---------|--------|-| Claude `SessionStart` | `startup\|resume\|clear` | Inject live index freshness (current / behind with a changed-file count / update in progress) and the core-tool trust rule |-| Claude `PostToolUse` | `Bash\|PowerShell\|Grep\|Glob\|Read\|Edit\|Write` | Check git freshness, add search rescue/triage context, and emit Read-intelligence notices |+| Claude `SessionStart` | `startup\|resume\|clear` | Inject live index freshness (current / behind with a changed-file count / update in progress), the core-tool trust rule, and the standing decisions relevant to the session's working set |+| Claude `PostToolUse` | `Bash\|PowerShell\|Grep\|Glob\|Read\|Edit\|Write` | Check git freshness, add search rescue/triage context, emit Read-intelligence notices, and surface the governing decision when a governed file is edited || Codex `SessionStart` / `UserPromptSubmit` | lifecycle | Remind Codex to use Repowise MCP tools || Codex `PostToolUse` | `Bash`, `apply_patch\|Edit\|Write` | Check git/edit freshness |diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/__init__.py b/packages/cli/src/repowise/cli/commands/augment_cmd/__init__.pyindex a9bb79a02..fba8876a7 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/__init__.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/__init__.py@@ -6,6 +6,8 @@ Split out of a single ~1300-line module into cohesive submodules:path relativisation) that every other submodule builds on.* :mod:`.search` — PostToolUse Grep/Glob rescue / triage / flood digest.* :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:`.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.pyindex 2bac2af29..97193ebde 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py@@ -27,7 +27,8 @@ Codex SessionStart/UserPromptSubmit: adds short repowise MCP usage guidance.* Emits a one-paragraph context block: whether the index is current,behind (with a changed-file count), or mid-update, plus the core-tooltrust rule. CLAUDE.md stays static and cache-friendly; live freshness- arrives here instead.+ arrives here instead. When active decisions are relevant to the+ session's working set, a capped standing-decisions block rides along.PostToolUse → Bash* After a successful git commit/merge/rebase/cherry-pick/pull, if@@ -46,8 +47,10 @@ Codex SessionStart/UserPromptSubmit: adds short repowise MCP usage guidance.PostToolUse → Edit / Write* Record the edit in the per-session state file so a later Read can- detect staleness. Emits nothing itself (Claude clients); Codex- lifecycle hooks additionally get the index-staleness reminder below.+ detect staleness. Claude clients additionally get a one-line notice+ when the edited file has a governing decision (once per session per+ decision, strictly capped); Codex lifecycle hooks instead get the+ index-staleness reminder below.PostToolUse → edit tools (Codex)* After file edits, emit a short reminder that the indexed context may@@ -78,7 +81,7 @@ import clickfrom .bash_staleness import _handle_bash_postfrom .codex import _handle_codex_context_event, _handle_post_edit_use-from .read_state import _handle_read_post, _record_edit+from .read_state import _handle_edit_post, _handle_read_post, _record_editfrom .search import _handle_search_postfrom .session_start import _handle_claude_session_start@@ -126,8 +129,12 @@ def _run_augment(*, client: str | None = None) -> None:returnif event == "SessionStart":- # Claude Code lifecycle hook: live index-freshness + trust context.- result = _handle_claude_session_start(cwd)+ # Claude Code lifecycle hook: live index-freshness + trust context,+ # plus the relevance-ranked standing-decisions block.+ session_id = payload.get("session_id", "")+ result = _handle_claude_session_start(+ cwd, session_id if isinstance(session_id, str) else ""+ )if result:_emit_response(event, result)return@@ -231,12 +238,13 @@ def _handle_post_tool_use(# The edit-tool freshness notice is a Codex-only lifecycle hook, gated on# the Codex client so the widened Claude matcher (Read|Edit|Write) can't# emit Codex-flavored banners to Claude Code users. Both clients record- # the edit for the per-session stale-read state machine first.+ # the edit for the per-session stale-read state machine; Claude clients+ # additionally get the once-per-decision governing-decision notice.if tool_name in _EDIT_TOOL_NAMES:- _record_edit(tool_input, cwd, session_id)if client == "codex":+ _record_edit(tool_input, cwd, session_id)return _handle_post_edit_use(cwd)- return None+ return _handle_edit_post(tool_input, cwd, session_id)if tool_name == "Read":return _handle_read_post(tool_input, tool_output, cwd, session_id)if tool_name in ("Bash", "PowerShell"):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.pynew file mode 100644index 000000000..97f51fa52--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py@@ -0,0 +1,625 @@+"""Relevance-ranked decision injection for the agent hooks.++Two delivery moments, both pure indexed-SQLite lookups (no LLM, no network,+target well under 100ms):++ * SessionStart — score the repo's active decisions against the session's+ likely working set (dirty/staged files, branch-vs-main changed files, the+ previous session's edited files, branch-name tokens) expanded one hop via+ import edges and co-change partners, and inject the top few under a hard+ token cap. Relevance or silence: nothing clears the floor, nothing is+ injected. Never top-confidence-globally.+ * Edit-time (PostToolUse Edit/Write) — when the edited file has a governing+ decision (via decision_node_links), say so once per session per decision,+ under a strict per-session cap.++Repo-wide session rules (user corrections with no named files, so no node+links) can only reach the agent here: they carry a flat base relevance at+SessionStart so a rule like "never use em dashes" is deliverable at all, but+they still compete under the same floor and cap as everything else.++Every injected decision id is recorded in the sessions.db sidecar so the+update-time miner can check whether the guidance was followed or contradicted+(usage feedback v1). Same operational rules as the rest of augment: any+failure degrades to silence, never an error in the agent transcript.+"""++from __future__ import annotations++import contextlib+import json+import re+import sqlite3+import time+from pathlib import Path++# --- SessionStart tunables -------------------------------------------------++#: Hard budget for the whole injected block, in estimated tokens (chars/4).+_TOKEN_CAP = 400+#: Minimum final score a decision needs to be injected at all.+_RELEVANCE_FLOOR = 0.25+#: Never inject more than this many decisions regardless of the token cap.+_MAX_ITEMS = 6+#: Working-set caps keep the SQL IN-lists and the hop expansion bounded.+_MAX_SEEDS = 30+_MAX_HOP = 100++#: Hop weights: a decision governing a file the session is actually touching+#: outranks one governing a neighbor of that file.+_W_SEED_FILE = 0.6+_W_HOP_FILE = 0.3+#: Module links are broader claims than file links, so they count for half.+_MODULE_FACTOR = 0.5+#: Score contribution when a branch-name token appears in the decision text.+_W_BRANCH_TOKEN = 0.4+#: Base relevance for repo-wide session rules (active, session-sourced, no+#: node links). They apply everywhere, so SessionStart is their only path.+_W_GLOBAL_RULE = 0.5+#: At most this many unlinked global rules per block. Working-set-relevant+#: decisions must never be crowded out by always-eligible rules, and a+#: mis-promoted one-off (dogfood: "merge the backend PRs" made it to active)+#: costs at most one slot until it is dismissed.+_MAX_GLOBAL_RULES = 2++#: Branch-name tokens that identify workflow, not topic.+_GENERIC_BRANCH_TOKENS = frozenset(+ {+ "feat",+ "feature",+ "fix",+ "bugfix",+ "hotfix",+ "chore",+ "refactor",+ "docs",+ "test",+ "tests",+ "wip",+ "dev",+ "main",+ "master",+ "head",+ "release",+ "branch",+ }+)++# --- Edit-time tunables ------------------------------------------------------++#: Strict per-session cap on edit-time decision notices.+_MAX_EDIT_NOTICES = 3++_CLIP_DECISION = 220+_CLIP_RATIONALE = 160+++# ---------------------------------------------------------------------------+# Shared SQLite plumbing (read-only wiki.db, stdlib sqlite3 — the hook path+# must not pay the sqlalchemy import; same pattern as the skeleton nudge)+# ---------------------------------------------------------------------------+++def _open_wiki_ro(repo_path: Path) -> sqlite3.Connection | None:+ db_path = repo_path / ".repowise" / "wiki.db"+ if not db_path.exists():+ return None+ try:+ return sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=1)+ except sqlite3.Error:+ return None+++def _clip(text: str, cap: int) -> str:+ text = " ".join((text or "").split())+ return text if len(text) <= cap else text[: cap - 1] + "…"+++def _norm_path(node_id: str) -> str:+ """Link node ids are stored OS-native (backslashes on Windows); the seed+ set is POSIX. Compare everything in POSIX."""+ return (node_id or "").replace("\\", "/")+++def _module_deep_enough(node_id: str) -> bool:+ """A top-level module link ("packages") governs the whole tree — that is+ an extraction artifact, not governance, and injecting it on every edit is+ pure noise (dogfood: a truncated legacy record linked to `packages` fired+ on unrelated files). Require at least two path segments."""+ return "/" in _norm_path(node_id).strip("/")+++def _echoes_title(title: str, text: str) -> bool:+ """True when *text* is just the title again (legacy records often store+ the same truncated string in title, decision, and rationale)."""+ a = " ".join((title or "").lower().split())+ b = " ".join((text or "").lower().split())+ if not a or not b:+ return False+ probe = min(len(a), len(b), 60)+ return a[:probe] == b[:probe]+++def _estimate_tokens(text: str) -> int:+ return len(text) // 4+++# ---------------------------------------------------------------------------+# SessionStart: seed collection+# ---------------------------------------------------------------------------+++def _git_lines(repo_path: Path, *args: str) -> list[str] | None:+ import subprocess++ try:+ out = subprocess.run(+ ["git", *args],+ cwd=str(repo_path),+ capture_output=True,+ text=True,+ timeout=5,+ stdin=subprocess.DEVNULL,+ )+ except Exception:+ return None+ if out.returncode != 0:+ return None+ return [ln for ln in out.stdout.splitlines() if ln.strip()]+++def _dirty_files_and_branch(repo_path: Path) -> tuple[list[str], str]:+ """Dirty + staged paths and the branch name, from one git call.++ ``git status --porcelain --branch`` carries both (the ``## branch...``+ header line), halving the subprocess cost of seed collection — git+ startup dominates this hook's latency on Windows. Renames yield the new+ path; untracked directories are skipped.+ """+ lines = _git_lines(repo_path, "status", "--porcelain", "--branch") or []+ files: list[str] = []+ branch = ""+ for ln in lines:+ if ln.startswith("## "):+ head = ln[3:].split("...", 1)[0].strip()+ branch = "" if "(" in head else head # "## HEAD (no branch)" etc.+ continue+ path = ln[3:].strip()+ if " -> " in path:+ path = path.split(" -> ", 1)[1]+ path = path.strip().strip('"')+ if path and not path.endswith("/"):+ files.append(path)+ return files, branch+++def _branch_changed_files(repo_path: Path, branch: str) -> list[str]:+ """Files changed on this branch vs the default branch (merge-base diff)."""+ if branch in ("", "HEAD", "main", "master"):+ return []+ for base in ("main", "master"):+ lines = _git_lines(repo_path, "diff", "--name-only", f"{base}...HEAD")+ if lines is not None:+ return [ln.strip() for ln in lines if ln.strip()]+ return []+++def _previous_session_edits(repo_path: Path) -> list[str]:+ """Edited files recorded by the previous session's read/edit state.++ At SessionStart the state file still holds the last session's entries+ (the new session_id resets it only on the first PostToolUse event).+ """+ state_path = repo_path / ".repowise" / ".augment-session.json"+ try:+ state = json.loads(state_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return []+ edits = state.get("edits") if isinstance(state, dict) else None+ return [f for f in edits if isinstance(f, str)] if isinstance(edits, dict) else []+++_BRANCH_SPLIT_RE = re.compile(r"[^a-z0-9]+")+++def _branch_tokens(branch: str) -> list[str]:+ """Topic-bearing tokens from a branch name (workflow prefixes dropped)."""+ return [+ t+ for t in _BRANCH_SPLIT_RE.split(branch.lower())+ if len(t) >= 3 and t not in _GENERIC_BRANCH_TOKENS+ ]+++def _collect_seeds(repo_path: Path) -> tuple[list[str], str]:+ """The session's likely working set (repo-relative POSIX) + branch name."""+ dirty, branch = _dirty_files_and_branch(repo_path)+ seen: dict[str, None] = {}+ for f in dirty + _branch_changed_files(repo_path, branch) + _previous_session_edits(repo_path):+ norm = f.replace("\\", "/").lstrip("./")+ if norm:+ seen.setdefault(norm, None)+ return list(seen)[:_MAX_SEEDS], branch+++# ---------------------------------------------------------------------------+# SessionStart: one-hop expansion (import edges + co-change partners)+# ---------------------------------------------------------------------------+++def _looks_like_file_node(node_id: str) -> bool:+ return "::" not in node_id and not node_id.startswith("external:")+++def _expand_one_hop(conn: sqlite3.Connection, seeds: list[str]) -> set[str]:+ """Files one graph/co-change hop away from the seed set."""+ if not seeds:+ return set()+ hop: set[str] = set()+ marks = ",".join("?" * len(seeds))+ with contextlib.suppress(sqlite3.Error):+ rows = conn.execute(+ f"SELECT source_node_id, target_node_id FROM graph_edges "+ f"WHERE source_node_id IN ({marks}) OR target_node_id IN ({marks})",+ (*seeds, *seeds),+ ).fetchall()+ seed_set = set(seeds)+ for src, dst in rows:+ for node in (src, dst):+ if isinstance(node, str) and node not in seed_set and _looks_like_file_node(node):+ hop.add(node)+ if len(hop) >= _MAX_HOP:+ return hop+ with contextlib.suppress(sqlite3.Error):+ rows = conn.execute(+ f"SELECT co_change_partners_json FROM git_metadata WHERE file_path IN ({marks})",+ tuple(seeds),+ ).fetchall()+ for (raw,) in rows:+ try:+ partners = json.loads(raw or "[]")+ except (TypeError, ValueError):+ continue+ if not isinstance(partners, list):+ continue+ for p in partners:+ path = p.get("file_path") if isinstance(p, dict) else None+ if isinstance(path, str) and path and path not in seeds:+ hop.add(path)+ if len(hop) >= _MAX_HOP:+ return hop+ return hop+++# ---------------------------------------------------------------------------+# Decision loading + scoring+# ---------------------------------------------------------------------------+++def _load_active_decisions(conn: sqlite3.Connection) -> list[dict]:+ """Active decisions with their node links, as plain dicts."""+ try:+ rows = conn.execute(+ "SELECT id, title, decision, rationale, confidence, staleness_score, source "+ "FROM decision_records WHERE status = 'active'"+ ).fetchall()+ except sqlite3.Error:+ return []+ decisions = [+ {+ "id": r[0],+ "title": r[1] or "",+ "decision": r[2] or "",+ "rationale": r[3] or "",+ "confidence": r[4] if isinstance(r[4], (int, float)) else 0.5,+ "staleness": r[5] if isinstance(r[5], (int, float)) else 0.0,+ "source": r[6] or "",+ "links": [],+ }+ for r in rows+ ]+ if not decisions:+ return []+ by_id = {d["id"]: d for d in decisions}+ marks = ",".join("?" * len(by_id))+ with contextlib.suppress(sqlite3.Error):+ for decision_id, node_id, link_type in conn.execute(+ f"SELECT decision_id, node_id, link_type FROM decision_node_links "+ f"WHERE decision_id IN ({marks})",+ tuple(by_id),+ ):+ by_id[decision_id]["links"].append((_norm_path(node_id), link_type))+ return decisions+++def _freshness(staleness: float) -> float:+ """Staleness discounts relevance but never zeroes an otherwise-relevant hit."""+ return 1.0 - 0.6 * max(0.0, min(1.0, staleness))+++def _overlap_score(links: list[tuple[str, str]], seeds: set[str], hop: set[str]) -> float:+ score = 0.0+ for node_id, link_type in links:+ if link_type == "module":+ if not _module_deep_enough(node_id):+ continue # a top-level module link "governs" everything: noise+ prefix = node_id.rstrip("/") + "/"+ if any(f.startswith(prefix) for f in seeds):+ score += _W_SEED_FILE * _MODULE_FACTOR+ elif any(f.startswith(prefix) for f in hop):+ score += _W_HOP_FILE * _MODULE_FACTOR+ elif node_id in seeds:+ score += _W_SEED_FILE+ elif node_id in hop:+ score += _W_HOP_FILE+ return min(1.0, score)+++def _score_decision(+ decision: dict, seeds: set[str], hop: set[str], branch_tokens: list[str]+) -> float:+ relevance = _overlap_score(decision["links"], seeds, hop)+ if branch_tokens:+ text = f"{decision['title']} {decision['decision']}".lower()+ if any(t in text for t in branch_tokens):+ relevance = min(1.0, relevance + _W_BRANCH_TOKEN)+ if not decision["links"] and decision["source"] == "session":+ # A repo-wide rule mined from user corrections: applies everywhere,+ # so it gets a base relevance instead of file overlap.+ relevance = max(relevance, _W_GLOBAL_RULE)+ return relevance * decision["confidence"] * _freshness(decision["staleness"])+++# ---------------------------------------------------------------------------+# SessionStart entry point+# ---------------------------------------------------------------------------+++def _format_decision_line(decision: dict) -> str:+ title = _clip(decision["title"], 100)+ body = _clip(decision["decision"], _CLIP_DECISION)+ rationale = _clip(decision["rationale"], _CLIP_RATIONALE)+ # Legacy records echo the title into decision/rationale; saying a thing+ # once is guidance, saying it three times is noise.+ if _echoes_title(decision["title"], body):+ body = ""+ if _echoes_title(decision["title"], rationale) or _echoes_title(body, rationale):+ rationale = ""+ line = f"- {title}: {body}" if body else f"- {title}"+ if rationale:+ line += f" (because {rationale})"+ return line+++def _session_decision_block(repo_path: Path, session_id: str) -> str | None:+ """The relevance-ranked SessionStart decision block, or None (silence)."""+ conn = _open_wiki_ro(repo_path)+ if conn is None:+ return None+ try:+ decisions = _load_active_decisions(conn)+ if not decisions:+ return None+ seeds, branch = _collect_seeds(repo_path)+ hop = _expand_one_hop(conn, seeds)+ tokens = _branch_tokens(branch)++ scored = [(d, _score_decision(d, set(seeds), hop, tokens)) for d in decisions]+ scored = [(d, s) for d, s in scored if s >= _RELEVANCE_FLOOR]+ if not scored:+ return None+ scored.sort(key=lambda pair: pair[1], reverse=True)+ finally:+ conn.close()++ header = (+ "[repowise] Standing decisions relevant to this session's working set "+ "(accumulated from prior sessions; follow them unless the user says otherwise):"+ )+ lines = [header]+ budget = _TOKEN_CAP - _estimate_tokens(header)+ shown: list[dict] = []+ globals_shown = 0+ for decision, _score in scored:+ if len(shown) >= _MAX_ITEMS:+ break+ is_global = not decision["links"] and decision["source"] == "session"+ if is_global and globals_shown >= _MAX_GLOBAL_RULES:+ continue+ line = _format_decision_line(decision)+ cost = _estimate_tokens(line)+ if cost > budget:+ break+ lines.append(line)+ budget -= cost+ shown.append(decision)+ if is_global:+ globals_shown += 1+ if not shown:+ return None+ _record_injections(repo_path, session_id, [d["id"] for d in shown], node_id="")+ return "\n".join(lines)+++# ---------------------------------------------------------------------------+# Edit-time governing-decision notice+# ---------------------------------------------------------------------------+++def _governing_decisions(conn: sqlite3.Connection, rel: str) -> list[dict]:+ """Active decisions governing *rel* via file links or module-prefix links.++ Link node ids are matched in POSIX regardless of how they were stored+ (Windows extraction persists backslashes). Top-level module links are+ ignored (see :func:`_module_deep_enough`).+ """+ out: list[dict] = []+ seen: set[str] = set()+ native = rel.replace("/", "\\")+ with contextlib.suppress(sqlite3.Error):+ for row in conn.execute(+ "SELECT d.id, d.title, d.decision, d.rationale "+ "FROM decision_node_links l JOIN decision_records d ON d.id = l.decision_id "+ "WHERE l.node_id IN (?, ?) AND l.link_type = 'file' AND d.status = 'active'",+ (rel, native),+ ):+ if row[0] not in seen:+ seen.add(row[0])+ out.append({"id": row[0], "title": row[1], "decision": row[2], "rationale": row[3]})+ # Module links are few; prefix-match them in Python.+ for row in conn.execute(+ "SELECT d.id, d.title, d.decision, d.rationale, l.node_id "+ "FROM decision_node_links l JOIN decision_records d ON d.id = l.decision_id "+ "WHERE l.link_type = 'module' AND d.status = 'active'"+ ):+ if (+ row[0] not in seen+ and _module_deep_enough(row[4])+ and rel.startswith(_norm_path(row[4]).rstrip("/") + "/")+ ):+ seen.add(row[0])+ out.append({"id": row[0], "title": row[1], "decision": row[2], "rationale": row[3]})+ return out+++def _session_evidence_count(conn: sqlite3.Connection, decision_id: str) -> int:+ """Distinct sessions that attested to this decision (evidence rows)."""+ try:+ row = conn.execute(+ "SELECT COUNT(DISTINCT evidence_commit) FROM decision_evidence "+ "WHERE decision_id = ? AND source = 'session' AND evidence_commit IS NOT NULL",+ (decision_id,),+ ).fetchone()+ except sqlite3.Error:+ return 0+ return row[0] if row and isinstance(row[0], int) else 0+++def _edit_decision_notice(repo_path: Path, rel: str, session_id: str, state: dict) -> str | None:+ """One-line governing-decision notice for an edited file, deduplicated.++ Once per session per decision, and at most :data:`_MAX_EDIT_NOTICES`+ notices per session total — an agent editing many governed files gets the+ first few, not a drumbeat. The authoritative dedup is the atomic+ ``INSERT OR IGNORE`` into the injections sidecar: the JSON session state+ is written read-modify-write by concurrently racing hook processes and+ loses updates (dogfood: the same decision re-fired minutes apart), so it+ is kept only as a cheap fast-path. The caller owns loading/saving *state*.+ """+ shown: list = state.setdefault("decisions_shown", [])+ if len(shown) >= _MAX_EDIT_NOTICES:+ return None+ conn = _open_wiki_ro(repo_path)+ if conn is None:+ return None+ try:+ governing = [d for d in _governing_decisions(conn, rel) if d["id"] not in shown]+ if not governing:+ return None+ decision = governing[0]+ sessions_n = _session_evidence_count(conn, decision["id"])+ finally:+ conn.close()++ shown.append(decision["id"])+ if session_id:+ claimed, session_total = _claim_injection(repo_path, session_id, decision["id"], rel)+ if not claimed or session_total > _MAX_EDIT_NOTICES:+ return None++ why = _clip(decision["rationale"] or decision["decision"], _CLIP_RATIONALE)+ if _echoes_title(decision["title"], why):+ why = "" # legacy rows echo the title into decision/rationale+ line = f"[repowise] {rel} is governed by a standing decision: {_clip(decision['title'], 100)}"+ if why:+ line += f" because {why}"+ if sessions_n >= 2:+ line += f" (confirmed across {sessions_n} sessions)"+ return line + "."+++# ---------------------------------------------------------------------------+# 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, "+ "PRIMARY KEY (session_id, decision_id))"+)+++def _open_injections(repo_path: Path) -> sqlite3.Connection | None:+ 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)+ return conn+ except (sqlite3.Error, OSError):+ return None+++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:+ now = time.time()+ conn.executemany(+ "INSERT OR IGNORE INTO injections (session_id, decision_id, node_id, shown_at) "+ "VALUES (?, ?, ?, ?)",+ [(session_id, did, node_id, now) for did in decision_ids],+ )+ conn.commit()+ except sqlite3.Error:+ pass+ finally:+ conn.close()+++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.+ """+ 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) "+ "VALUES (?, ?, ?, ?)",+ (session_id, decision_id, node_id, time.time()),+ )+ claimed = cur.rowcount > 0+ count = conn.execute(+ "SELECT COUNT(*) FROM injections WHERE session_id = ? AND node_id != ''",+ (session_id,),+ ).fetchone()[0]+ conn.commit()+ return claimed, int(count)+ except sqlite3.Error:+ return False, 0+ finally:+ conn.close()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.pyindex 7e0ab17bb..f1ddb5019 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@@ -49,6 +49,7 @@ def _load_session_state(repo_path: Path, session_id: str) -> dict:"nudged": [],"stale_notified": [],"reread_notified": [],+ "decisions_shown": [],}try:state = json.loads(_session_state_path(repo_path).read_text(encoding="utf-8"))@@ -75,19 +76,47 @@ def _save_session_state(repo_path: Path, state: dict) -> None:def _record_edit(tool_input: dict, cwd: str, session_id: str) -> None:"""Note an Edit/Write so a later Read of the file can flag staleness."""+ _handle_edit_post(tool_input, cwd, session_id, with_decisions=False)+++def _handle_edit_post(+ tool_input: dict,+ cwd: str,+ session_id: str,+ *,+ with_decisions: bool = True,+) -> str | None:+ """Record an Edit/Write; surface the file's governing decision, if any.++ The decision notice fires once per session per decision under a strict+ per-session cap (see :func:`decision_inject._edit_decision_notice`) so a+ governed file gets one heads-up, not a drumbeat. Codex lifecycle hooks+ call this with ``with_decisions=False``: they get their own edit banner.+ """file_path = tool_input.get("file_path") if isinstance(tool_input, dict) else Noneif not isinstance(file_path, str) or not file_path.strip():- return+ return Nonerepo_path = _find_repo_root(Path(cwd))if repo_path is None:- return+ return Nonerel = _relativize(file_path, repo_path)if rel is None:- return+ return Nonestate = _load_session_state(repo_path, session_id)state["seq"] += 1state["edits"][rel] = state["seq"]++ notice: str | None = None+ if with_decisions:+ from .decision_inject import _edit_decision_notice++ try:+ notice = _edit_decision_notice(repo_path, rel, session_id, state)+ except Exception:+ notice = None+_save_session_state(repo_path, state)+ return noticedef _handle_read_post(diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/session_start.py b/packages/cli/src/repowise/cli/commands/augment_cmd/session_start.pyindex 2aa80be86..e4f5c0987 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/session_start.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/session_start.py@@ -12,7 +12,9 @@ discovering staleness mid-task:Deliberately no hotspot/health lines here: CLAUDE.md already carries thosestatically, and this block is re-billed every session; freshness is the only-signal that must be live.+signal that must be live. The one addition is the relevance-ranked standing+decisions block (see :mod:`.decision_inject`), which is also live by nature:+it is scored against what this session is about to touch.Same operational rules as the rest of augment: stdlib + git subprocess only,any failure returns None, and a git failure never produces a false "current"@@ -26,11 +28,12 @@ from pathlib import Pathfrom ._shared import _find_repo_rootfrom .bash_staleness import _read_in_flight_marker+from .decision_inject import _session_decision_block_CORE_TOOLS = "get_answer, get_context, get_symbol, search_codebase, get_risk"-def _handle_claude_session_start(cwd: str) -> str | None:+def _handle_claude_session_start(cwd: str, session_id: str = "") -> str | None:"""Return the session context block, or None outside indexed repos."""repo_path = _find_repo_root(Path(cwd))if repo_path is None:@@ -43,6 +46,21 @@ def _handle_claude_session_start(cwd: str) -> str | None:if not isinstance(last_sync, str) or not last_sync:return None+ freshness = _freshness_block(repo_path, last_sync)+ if freshness is None:+ return None++ # Relevance-ranked standing decisions for this session's working set;+ # silent whenever nothing clears the floor (see decision_inject).+ try:+ decisions = _session_decision_block(repo_path, session_id)+ except Exception:+ decisions = None+ return f"{freshness}\n{decisions}" if decisions else freshness+++def _freshness_block(repo_path: Path, last_sync: str) -> str | None:+ """The live index-freshness paragraph (the original SessionStart block)."""head = _git_head(repo_path)if head is None:return (diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 2854df3da..13d6bd200 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -814,6 +814,49 @@ def run_update(if verbose:console.print(f"[yellow]Session decision mining skipped: {exc}[/yellow]")+ # Usage feedback v1: decisions the augment hooks injected into agent+ # sessions are judged against those sessions' mined corrections (followed+ # -> staleness relaxes, contradicted -> staleness bumps). Pure SQLite over+ # the staging sidecar + decision_records; no LLM.+ try:+ from repowise.core.sessions.miners.decisions import apply_injection_feedback++ if session_mining_enabled(cfg):++ async def _run_injection_feedback() -> dict:+ from repowise.cli.helpers import get_db_url_for_repo+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await upsert_repository(+ session, name=repo_path.name, local_path=str(repo_path)+ )+ res = await apply_injection_feedback(session, repo.id, repo_path)+ await engine.dispose()+ return res++ feedback = run_async(_run_injection_feedback())+ if verbose and (feedback.get("followed") or feedback.get("contradicted")):+ console.print(+ f"Injected-decision feedback: [green]{feedback.get('followed', 0)} "+ f"followed[/green], [yellow]{feedback.get('contradicted', 0)} "+ "contradicted[/yellow]"+ )+ except Exception as exc:+ degraded.append(f"Injection feedback: {exc}")+ if verbose:+ console.print(f"[yellow]Injection feedback skipped: {exc}[/yellow]")+# Count of decision records touched by evolution, surfaced in the panel.decisions_evolved = 0diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.pyindex 12d24b791..82bc59c99 100644--- a/packages/core/src/repowise/core/sessions/miners/decisions.py+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py@@ -70,6 +70,7 @@ logger = structlog.get_logger(__name__)__all__ = ["SessionCandidate",+ "apply_injection_feedback","mine_events","mine_session_decisions","session_mining_enabled",@@ -589,9 +590,105 @@ def _promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[Extracted# ----------------------------------------------------------------------------# Orchestration: one call per `repowise update`+# Usage feedback v1: were injected decisions followed or contradicted?# ---------------------------------------------------------------------------+#: An injection is judged only after this long: the showing session must have+#: had time to react (or end) before "no contradiction" reads as "followed".+INJECTION_EVAL_MIN_AGE_SECONDS = 3600.0++#: Staleness levels mirroring run_update_evolution's amended/reaffirmed moves.+_CONTRADICTED_STALENESS = 0.6+_FOLLOWED_STALENESS = 0.2+++async def apply_injection_feedback(+ db_session: Any,+ repository_id: str,+ repo_path: Path,+ *,+ now: float | None = None,+) -> dict[str, int]:+ """Judge shown-decision injections against what the session actually did.++ For every injection row the augment hooks recorded (see the staging+ sidecar's ``injections`` table), check the same session's mined user+ corrections: a correction that contradicts the shown decision (the+ :func:`~repowise.core.analysis.decisions.evolution.contradicts` heuristic)+ marks it contradicted and bumps staleness so the evolution machinery+ surfaces the drift; otherwise the guidance counts as followed and+ staleness relaxes, the same reaffirm move ``run_update_evolution`` makes.++ 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}``.+ """+ import time++ from sqlalchemy import select++ from repowise.core.analysis.decisions.evolution import contradicts+ from repowise.core.persistence.models import DecisionRecord++ ts = now if now is not None else time.time()+ summary = {"followed": 0, "contradicted": 0}++ store = SessionStagingStore.open_default(Path(repo_path).resolve())+ try:+ injections = store.unevaluated_injections(before=ts - INJECTION_EVAL_MIN_AGE_SECONDS)+ if not injections:+ return summary++ decision_ids = list({inj["decision_id"] for inj in injections})+ rows = await db_session.execute(+ select(DecisionRecord).where(+ DecisionRecord.id.in_(decision_ids),+ DecisionRecord.repository_id == repository_id,+ )+ )+ records = {rec.id: rec for rec in rows.scalars().all()}++ quotes_by_session: dict[str, list[str]] = {}+ verdicts: dict[str, bool] = {} # decision_id -> contradicted anywhere+ for inj in injections:+ rec = records.get(inj["decision_id"])+ if rec is None:+ # The decision no longer exists in this repo's records; drop+ # the row so it is not re-examined forever.+ store.mark_injection_evaluated(inj["session_id"], inj["decision_id"])+ continue+ session_id = inj["session_id"]+ if session_id not in quotes_by_session:+ quotes_by_session[session_id] = store.correction_quotes(session_id)+ decision_text = f"{rec.title}. {rec.decision}"+ contradicted = any(+ 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"])++ from datetime import UTC, datetime++ for decision_id, contradicted in verdicts.items():+ rec = records[decision_id]+ if contradicted:+ rec.staleness_score = max(rec.staleness_score, _CONTRADICTED_STALENESS)+ summary["contradicted"] += 1+ else:+ rec.staleness_score = min(rec.staleness_score, _FOLLOWED_STALENESS)+ summary["followed"] += 1+ rec.updated_at = datetime.now(UTC)++ store.commit()+ await db_session.flush()+ finally:+ store.close()++ if summary["followed"] or summary["contradicted"]:+ logger.info("session_mining.injection_feedback", **summary)+ return summary+async def mine_session_decisions(repo_path: Path,diff --git a/packages/core/src/repowise/core/sessions/staging.py b/packages/core/src/repowise/core/sessions/staging.pyindex 48de53621..6ea2cd935 100644--- a/packages/core/src/repowise/core/sessions/staging.py+++ b/packages/core/src/repowise/core/sessions/staging.py@@ -16,6 +16,9 @@ never contend with indexing. The sidecar holds three things:``advance`` / ``save`` surface, so :func:`iter_new_events` consumes itunchanged). Living in the same database means a cursor only advances inthe same commit that stages what was read under it.+- ``injections``: decision ids the augment hooks showed to an agent session+ (written hook-side with raw stdlib sqlite3), read back at update time to+ judge whether the guidance was followed or contradicted (usage feedback).Everything is local; transcripts and candidates never leave the machine."""@@ -70,6 +73,14 @@ CREATE TABLE IF NOT EXISTS cursors (offset INTEGER NOT NULL,mtime REAL NOT NULL);+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,+ PRIMARY KEY (session_id, decision_id)+);CREATE INDEX IF NOT EXISTS idx_raw_pending ON raw_candidates(structured_key)WHERE structured_key IS NULL;"""@@ -320,6 +331,45 @@ class SessionStagingStore:(now if now is not None else time.time(), observations, key),)+ # -- injections (usage feedback v1) --------------------------------------+ # The rows themselves are written by the augment hooks with raw stdlib+ # sqlite3 (the hook path never imports repowise.core); these methods are+ # the update-time reader side.++ def unevaluated_injections(self, *, before: float) -> list[dict[str, Any]]:+ """Shown-decision rows not yet judged, old enough that the showing+ session has plausibly moved past the guidance (see *before*)."""+ rows = self._conn.execute(+ "SELECT session_id, decision_id, node_id, shown_at FROM injections "+ "WHERE evaluated = 0 AND shown_at < ? ORDER BY shown_at ASC",+ (before,),+ ).fetchall()+ return [+ {"session_id": r[0], "decision_id": r[1], "node_id": r[2], "shown_at": r[3]}+ for r in rows+ ]++ def mark_injection_evaluated(self, session_id: str, decision_id: str) -> None:+ self._conn.execute(+ "UPDATE injections SET evaluated = 1 WHERE session_id = ? AND decision_id = ?",+ (session_id, decision_id),+ )++ def correction_quotes(self, session_id: str) -> list[str]:+ """Verbatim user-correction quotes mined from one session's transcript."""+ rows = self._conn.execute(+ "SELECT quotes FROM raw_candidates WHERE session_id = ? AND kind = 'user_correction'",+ (session_id,),+ ).fetchall()+ out: list[str] = []+ for (raw,) in rows:+ try:+ quotes = json.loads(raw)+ except (TypeError, ValueError):+ continue+ out.extend(q for q in quotes if isinstance(q, str))+ return out+# -- lifecycle -----------------------------------------------------------def prune(self, *, now: float | None = None) -> None:diff --git a/tests/unit/cli/test_augment_decision_inject.py b/tests/unit/cli/test_augment_decision_inject.pynew file mode 100644index 000000000..d4214d030--- /dev/null+++ b/tests/unit/cli/test_augment_decision_inject.py@@ -0,0 +1,484 @@+"""Relevance-ranked decision injection: SessionStart block + edit-time notice.++The contract under test is "relevance or silence": a decision reaches the+agent only when the working set (or a repo-wide session rule) justifies it,+under a hard token cap, and the edit-time notice fires once per session per+decision under a strict cap. The wiki.db is built through the real ORM schema+so the hook's raw SQL is exercised against the true column names.+"""++from __future__ import annotations++import json+import sqlite3+from pathlib import Path++from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from repowise.cli.commands.augment_cmd import decision_inject+from repowise.core.persistence.database import init_db+from repowise.core.persistence.models import (+ DecisionEvidence,+ DecisionNodeLink,+ DecisionRecord,+ GitMetadata,+ GraphEdge,+ Repository,+)++_REPO_ID = "repo1"+++async def _build_wiki_db(repo_root: Path, decisions: list[dict], extras=None) -> None:+ """Create .repowise/wiki.db via the real schema and insert test rows."""+ db_path = repo_root / ".repowise" / "wiki.db"+ db_path.parent.mkdir(parents=True, exist_ok=True)+ engine = create_async_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")+ await init_db(engine)+ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as session:+ session.add(Repository(id=_REPO_ID, name="repo", local_path=str(repo_root)))+ for spec in decisions:+ session.add(+ DecisionRecord(+ id=spec["id"],+ repository_id=_REPO_ID,+ title=spec["title"],+ decision=spec.get("decision", ""),+ rationale=spec.get("rationale", ""),+ status=spec.get("status", "active"),+ source=spec.get("source", "cli"),+ confidence=spec.get("confidence", 0.9),+ staleness_score=spec.get("staleness", 0.0),+ evidence_file=spec["id"], # keeps the unique constraint happy+ )+ )+ for node_id, link_type in spec.get("links", []):+ session.add(+ DecisionNodeLink(+ repository_id=_REPO_ID,+ decision_id=spec["id"],+ node_id=node_id,+ link_type=link_type,+ )+ )+ for sess in spec.get("evidence_sessions", []):+ session.add(+ DecisionEvidence(+ decision_id=spec["id"],+ source="session",+ evidence_commit=sess,+ source_quote="q",+ )+ )+ for extra in extras or []:+ session.add(extra)+ await session.commit()+ await engine.dispose()+++def _quiet_git(monkeypatch, *, dirty=None, branch="main", branch_files=None) -> None:+ monkeypatch.setattr(+ decision_inject, "_dirty_files_and_branch", lambda p: (list(dirty or []), branch)+ )+ monkeypatch.setattr(+ decision_inject, "_branch_changed_files", lambda p, b: list(branch_files or [])+ )+++_AUTH_DECISION = {+ "id": "d-auth",+ "title": "Use JWT auth",+ "decision": "All service auth uses short-lived JWT tokens",+ "rationale": "session cookies broke the mobile clients",+ "links": [("src/core/auth.py", "file")],+ "evidence_sessions": ["sess-a", "sess-b"],+}+_UNRELATED_DECISION = {+ "id": "d-unrelated",+ "title": "Batch the embed calls",+ "decision": "Embeddings are sent in batches of 64",+ "links": [("src/other/embed.py", "file")],+}+++async def test_seed_linked_decision_injected(tmp_path, monkeypatch):+ await _build_wiki_db(tmp_path, [_AUTH_DECISION, _UNRELATED_DECISION])+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])++ block = decision_inject._session_decision_block(tmp_path, "sess-1")++ assert block is not None+ assert "Standing decisions" in block+ assert "Use JWT auth" in block+ assert "because session cookies broke the mobile clients" in block+ assert "Batch the embed calls" not in block+++async def test_silence_when_nothing_relevant(tmp_path, monkeypatch):+ await _build_wiki_db(tmp_path, [_UNRELATED_DECISION])+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])+ assert decision_inject._session_decision_block(tmp_path, "sess-1") is None+++async def test_silence_without_wiki_db(tmp_path):+ assert decision_inject._session_decision_block(tmp_path, "sess-1") is None+++async def test_proposed_and_dismissed_never_injected(tmp_path, monkeypatch):+ await _build_wiki_db(+ tmp_path,+ [+ {**_AUTH_DECISION, "id": "d-prop", "status": "proposed"},+ {**_AUTH_DECISION, "id": "d-dis", "title": "Dismissed rule", "status": "dismissed"},+ ],+ )+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])+ assert decision_inject._session_decision_block(tmp_path, "sess-1") is None+++async def test_global_session_rule_injected_without_file_overlap(tmp_path, monkeypatch):+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-global",+ "title": "Never use em dashes",+ "decision": "never use em dashes in any output",+ "source": "session",+ "confidence": 0.8,+ "links": [],+ },+ _UNRELATED_DECISION,+ ],+ )+ _quiet_git(monkeypatch) # no seeds at all++ block = decision_inject._session_decision_block(tmp_path, "sess-1")+ assert block is not None+ assert "Never use em dashes" in block+ assert "Batch the embed calls" not in block+++async def test_global_rules_are_capped_and_never_crowd_out_linked(tmp_path, monkeypatch):+ """Unlinked rules are always eligible, so a cap keeps them from flooding+ the block; a working-set-linked decision must still get through."""+ rules = [+ {+ "id": f"d-g{i}",+ "title": f"Global rule {i}",+ "decision": f"always follow global rule number {i}",+ "source": "session",+ "confidence": 0.8,+ "links": [],+ }+ for i in range(5)+ ]+ await _build_wiki_db(tmp_path, [*rules, _AUTH_DECISION])+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])++ block = decision_inject._session_decision_block(tmp_path, "sess-1")+ assert block is not None+ assert "Use JWT auth" in block+ assert sum("Global rule" in ln for ln in block.splitlines()) == 2+++async def test_unlinked_non_session_decision_is_not_global(tmp_path, monkeypatch):+ """Only session-mined rules get the repo-wide base relevance."""+ await _build_wiki_db(+ tmp_path,+ [{"id": "d-cli", "title": "A CLI note", "decision": "some note", "links": []}],+ )+ _quiet_git(monkeypatch)+ assert decision_inject._session_decision_block(tmp_path, "sess-1") is None+++async def test_one_hop_expansion_via_graph_edge(tmp_path, monkeypatch):+ hop_decision = {+ "id": "d-hop",+ "title": "Tokens rotate hourly",+ "decision": "token refresh happens on an hourly schedule",+ "confidence": 0.95,+ "links": [("src/core/token.py", "file")],+ }+ edge = GraphEdge(+ repository_id=_REPO_ID,+ source_node_id="src/core/auth.py",+ target_node_id="src/core/token.py",+ )+ await _build_wiki_db(tmp_path, [hop_decision], extras=[edge])+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])++ block = decision_inject._session_decision_block(tmp_path, "sess-1")+ assert block is not None+ assert "Tokens rotate hourly" in block+++async def test_one_hop_expansion_via_cochange_partner(tmp_path, monkeypatch):+ partner_decision = {+ "id": "d-co",+ "title": "Schema and parser move together",+ "decision": "schema changes always update the parser in the same PR",+ "confidence": 0.95,+ "links": [("src/core/parser.py", "file")],+ }+ meta = GitMetadata(+ repository_id=_REPO_ID,+ file_path="src/core/auth.py",+ co_change_partners_json=json.dumps(+ [{"file_path": "src/core/parser.py", "co_change_count": 7}]+ ),+ )+ await _build_wiki_db(tmp_path, [partner_decision], extras=[meta])+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])++ block = decision_inject._session_decision_block(tmp_path, "sess-1")+ assert block is not None+ assert "Schema and parser move together" in block+++async def test_branch_tokens_match_decision_text(tmp_path, monkeypatch):+ await _build_wiki_db(tmp_path, [_AUTH_DECISION])+ _quiet_git(monkeypatch, branch="feat/jwt-rotation") # no file seeds++ block = decision_inject._session_decision_block(tmp_path, "sess-1")+ assert block is not None+ assert "Use JWT auth" in block+++async def test_previous_session_edits_seed_the_set(tmp_path, monkeypatch):+ await _build_wiki_db(tmp_path, [_AUTH_DECISION])+ (tmp_path / ".repowise" / ".augment-session.json").write_text(+ json.dumps({"session_id": "old", "edits": {"src/core/auth.py": 3}}),+ encoding="utf-8",+ )+ _quiet_git(monkeypatch)++ block = decision_inject._session_decision_block(tmp_path, "sess-2")+ assert block is not None+ assert "Use JWT auth" in block+++async def test_token_cap_and_item_cap(tmp_path, monkeypatch):+ long_text = "this decision line pads the token budget " * 8+ decisions = [+ {+ "id": f"d-{i}",+ "title": f"Decision number {i}",+ "decision": long_text,+ "links": [("src/core/auth.py", "file")],+ }+ for i in range(10)+ ]+ await _build_wiki_db(tmp_path, decisions)+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])++ block = decision_inject._session_decision_block(tmp_path, "sess-1")+ assert block is not None+ lines = block.splitlines()+ assert len(lines) - 1 <= decision_inject._MAX_ITEMS+ assert decision_inject._estimate_tokens(block) <= decision_inject._TOKEN_CAP+++async def test_sessionstart_injections_recorded(tmp_path, monkeypatch):+ await _build_wiki_db(tmp_path, [_AUTH_DECISION])+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])++ assert decision_inject._session_decision_block(tmp_path, "sess-9") is not None++ conn = sqlite3.connect(tmp_path / ".repowise" / "sessions" / "sessions.db")+ rows = conn.execute(+ "SELECT session_id, decision_id, node_id, evaluated FROM injections"+ ).fetchall()+ conn.close()+ assert rows == [("sess-9", "d-auth", "", 0)]+++async def test_no_recording_without_session_id(tmp_path, monkeypatch):+ await _build_wiki_db(tmp_path, [_AUTH_DECISION])+ _quiet_git(monkeypatch, dirty=["src/core/auth.py"])++ assert decision_inject._session_decision_block(tmp_path, "") is not None+ assert not (tmp_path / ".repowise" / "sessions" / "sessions.db").exists()+++# ---------------------------------------------------------------------------+# Edit-time notice+# ---------------------------------------------------------------------------+++async def test_edit_notice_fires_once_per_decision(tmp_path):+ await _build_wiki_db(tmp_path, [_AUTH_DECISION])+ state: dict = {}++ notice = decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", state)+ assert notice is not None+ assert "governed by a standing decision" in notice+ assert "Use JWT auth" in notice+ assert "because session cookies broke the mobile clients" in notice+ assert "confirmed across 2 sessions" in notice++ # Same decision again this session: silence.+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", state) is None+++async def test_edit_notice_module_link_prefix_match(tmp_path):+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-mod",+ "title": "Core stays sync",+ "decision": "no asyncio inside src/core",+ "links": [("src/core", "module")],+ }+ ],+ )+ state: dict = {}+ notice = decision_inject._edit_decision_notice(tmp_path, "src/core/deep/file.py", "s1", state)+ assert notice is not None+ assert "Core stays sync" in notice+ # Not a prefix match: src/core_extra must not count as src/core.+ assert decision_inject._edit_decision_notice(tmp_path, "src/core_extra/f.py", "s1", {}) is None+++async def test_edit_notice_dedup_survives_state_loss(tmp_path):+ """The sidecar claim, not the racy JSON state, is the real dedup.++ Two concurrent hook processes race read-modify-write on the state file+ and can lose the decisions_shown entry; a fresh state dict simulates+ that. The atomic INSERT OR IGNORE must still keep the notice single.+ """+ await _build_wiki_db(tmp_path, [_AUTH_DECISION])+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", {}) is not None+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", {}) is None+++async def test_edit_notice_matches_backslash_stored_links(tmp_path):+ """Windows extraction stores link node ids with backslashes."""+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-win",+ "title": "Keep the CLI stdlib only",+ "decision": "hook-path modules import only the stdlib",+ "links": [("src\\cli\\hook.py", "file")],+ }+ ],+ )+ notice = decision_inject._edit_decision_notice(tmp_path, "src/cli/hook.py", "s1", {})+ assert notice is not None+ assert "Keep the CLI stdlib only" in notice+++async def test_top_level_module_link_never_fires(tmp_path):+ """A link to a root module like `packages` is an extraction artifact."""+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-root",+ "title": "namespace, batched like the pages",+ "decision": "namespace, batched like the pages",+ "links": [("packages", "module")],+ }+ ],+ )+ assert (+ decision_inject._edit_decision_notice(tmp_path, "packages/cli/src/x.py", "s1", {}) is None+ )+ _quiet = decision_inject._session_decision_block # scoring path, same guard+ # Seed inside the "governed" tree must still not surface it.+ import unittest.mock as mock++ with (+ mock.patch.object(+ decision_inject,+ "_dirty_files_and_branch",+ lambda p: (["packages/cli/src/x.py"], "main"),+ ),+ mock.patch.object(decision_inject, "_branch_changed_files", lambda p, b: []),+ ):+ assert _quiet(tmp_path, "s1") is None+++async def test_echoed_title_is_not_repeated(tmp_path):+ """Legacy rows carry the same text in title/decision/rationale."""+ text = "namespace, batched like the pages. Uses embed_batch directly"+ await _build_wiki_db(+ tmp_path,+ [+ {+ "id": "d-echo",+ "title": text,+ "decision": text + " (which raises on failure)",+ "rationale": text,+ "links": [("src/core/embed.py", "file")],+ }+ ],+ )+ notice = decision_inject._edit_decision_notice(tmp_path, "src/core/embed.py", "s1", {})+ assert notice is not None+ assert notice.count("namespace, batched") == 1+ assert "because" not in notice+++async def test_edit_notice_respects_session_cap(tmp_path):+ await _build_wiki_db(tmp_path, [_AUTH_DECISION])+ state = {"decisions_shown": ["x", "y", "z"]}+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "s1", state) is None+++async def test_edit_notice_silent_for_ungoverned_file(tmp_path):+ await _build_wiki_db(tmp_path, [_AUTH_DECISION])+ assert decision_inject._edit_decision_notice(tmp_path, "README.md", "s1", {}) is None+++async def test_edit_notice_records_injection(tmp_path):+ await _build_wiki_db(tmp_path, [_AUTH_DECISION])+ decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "sess-7", {})+ conn = sqlite3.connect(tmp_path / ".repowise" / "sessions" / "sessions.db")+ rows = conn.execute("SELECT session_id, decision_id, node_id FROM injections").fetchall()+ conn.close()+ assert rows == [("sess-7", "d-auth", "src/core/auth.py")]+++# ---------------------------------------------------------------------------+# Seed plumbing details (pure helpers)+# ---------------------------------------------------------------------------+++def test_branch_tokens_drop_workflow_words():+ assert decision_inject._branch_tokens("feat/decision-injection") == [+ "decision",+ "injection",+ ]+ assert decision_inject._branch_tokens("main") == []+ assert decision_inject._branch_tokens("fix/wip") == []+++def test_dirty_files_parses_porcelain_branch_and_renames(tmp_path, monkeypatch):+ monkeypatch.setattr(+ decision_inject,+ "_git_lines",+ lambda p, *a: [+ "## feat/x...origin/main [ahead 2]",+ " M src/a.py",+ "?? new dir/",+ "R old.py -> new.py",+ 'A "sp ace.py"',+ ],+ )+ files, branch = decision_inject._dirty_files_and_branch(tmp_path)+ assert files == ["src/a.py", "new.py", "sp ace.py"]+ assert branch == "feat/x"+++def test_detached_head_yields_no_branch(tmp_path, monkeypatch):+ monkeypatch.setattr(+ decision_inject, "_git_lines", lambda p, *a: ["## HEAD (no branch)", " M a.py"]+ )+ files, branch = decision_inject._dirty_files_and_branch(tmp_path)+ assert files == ["a.py"]+ assert branch == ""diff --git a/tests/unit/sessions/test_injection_feedback.py b/tests/unit/sessions/test_injection_feedback.pynew file mode 100644index 000000000..27232032d--- /dev/null+++ b/tests/unit/sessions/test_injection_feedback.py@@ -0,0 +1,181 @@+"""Usage feedback v1: injected decisions judged followed or contradicted.++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+most once.+"""++from __future__ import annotations++import sqlite3++import pytest+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine+from sqlalchemy.pool import StaticPool++from repowise.core.persistence.database import init_db+from repowise.core.persistence.models import DecisionRecord, Repository+from repowise.core.sessions.miners.decisions import (+ INJECTION_EVAL_MIN_AGE_SECONDS,+ apply_injection_feedback,+)+from repowise.core.sessions.staging import SessionStagingStore, default_store_path++_REPO_ID = "repo1"+_NOW = 1_000_000.0+_OLD_ENOUGH = _NOW - INJECTION_EVAL_MIN_AGE_SECONDS - 10+++async def engine():+ eng = create_async_engine(+ "sqlite+aiosqlite:///:memory:",+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+ )+ await init_db(eng)+ yield eng+ await eng.dispose()+++async def session(engine):+ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as s:+ yield s+ await s.commit()+++async def _add_decision(session, decision_id: str, *, staleness: float = 0.5) -> None:+ session.add(+ DecisionRecord(+ id=decision_id,+ repository_id=_REPO_ID,+ title="Use JWT tokens for service auth",+ decision="all service auth uses JWT tokens",+ status="active",+ staleness_score=staleness,+ evidence_file=decision_id,+ )+ )+ await session.flush()+++def _record_injection(repo_root, session_id: str, decision_id: str, shown_at: float) -> None:+ """Insert an injection row the way the hook does (raw sqlite)."""+ with SessionStagingStore(default_store_path(repo_root)) as store:+ store._conn.execute(+ "INSERT OR IGNORE INTO injections (session_id, decision_id, shown_at) VALUES (?, ?, ?)",+ (session_id, decision_id, shown_at),+ )+ store.commit()+++def _stage_correction(repo_root, session_id: str, quote: str) -> None:+ with SessionStagingStore(default_store_path(repo_root)) as store:+ store.add_raw(+ hash_=f"h-{session_id}-{abs(hash(quote)) % 10**8}",+ kind="user_correction",+ quotes=[quote],+ files=[],+ session_id=session_id,+ now=_OLD_ENOUGH,+ )+ store.commit()+++async def test_uncontradicted_injection_counts_as_followed(session, tmp_path):+ 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}+ rec = await session.get(DecisionRecord, "d1")+ assert rec.staleness_score == pytest.approx(0.2)++ # Judged once: a second pass finds nothing unevaluated.+ again = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)+ assert again == {"followed": 0, "contradicted": 0}+++async def test_contradicting_correction_bumps_staleness(session, tmp_path):+ session.add(Repository(id=_REPO_ID, name="r", local_path=str(tmp_path)))+ await _add_decision(session, "d1", staleness=0.1)+ _record_injection(tmp_path, "sess-1", "d1", _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}+ rec = await session.get(DecisionRecord, "d1")+ assert rec.staleness_score == pytest.approx(0.6)+++async def test_unrelated_correction_still_counts_as_followed(session, tmp_path):+ 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)+ _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}+++async def test_recent_injection_is_not_judged_yet(session, tmp_path):+ 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", _NOW - 60) # a minute ago++ summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)++ assert summary == {"followed": 0, "contradicted": 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:+ assert len(store.unevaluated_injections(before=_NOW)) == 1 # still pending+++async def test_vanished_decision_row_is_drained_not_retried(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)++ summary = await apply_injection_feedback(session, _REPO_ID, tmp_path, now=_NOW)++ assert summary == {"followed": 0, "contradicted": 0}+ with SessionStagingStore(default_store_path(tmp_path)) as store:+ assert store.unevaluated_injections(before=_NOW) == []+++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++ # Hook writes first (cold sidecar), store opens the same DB afterwards.+ _record_injections(tmp_path, "sess-1", ["d1"], node_id="src/a.py")+ db = tmp_path / ".repowise" / "sessions" / "sessions.db"+ assert db.exists()+ with SessionStagingStore(db) as store:+ rows = store.unevaluated_injections(before=9e12)+ assert [(r["session_id"], r["decision_id"], r["node_id"]) for r in rows] == [+ ("sess-1", "d1", "src/a.py")+ ]+ store.mark_injection_evaluated("sess-1", "d1")+ store.commit()+ assert store.unevaluated_injections(before=9e12) == []++ # And the reverse order: store-created schema accepts hook writes.+ repo2 = tmp_path / "second"+ (repo2 / ".repowise").mkdir(parents=True)+ with SessionStagingStore(default_store_path(repo2)):+ pass+ _record_injections(repo2, "sess-2", ["d2"], node_id="")+ conn = sqlite3.connect(default_store_path(repo2))+ assert conn.execute("SELECT COUNT(*) FROM injections").fetchone()[0] == 1+ conn.close()