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.

feat(decisions): ask the agent to record the choice it just committed (#2465)

Raghav Chamadiya5ca69552553d
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.md
index 6bf22bbca..ed47a079d 100644
--- a/docs/layers/DECISIONS.md
+++ b/docs/layers/DECISIONS.md
@@ -678,6 +678,7 @@ the scope that decision governs.
| `repowise decision add` | Guided interactive capture: kind, title, context, decision, rationale, rejected alternatives, tradeoffs, affected files, tags. Answering the prompts is an acceptance, recorded as one. An architectural record that names no files is kept as a candidate instead, because a decision that names nothing cannot be checked against the code. `--kind agreement` records the other noun — a rule about how the work is conducted — which is accepted without naming files, because it governs the repository rather than part of it, and reaches an agent at session start rather than when a file is edited. |
| `repowise decision list` | Table of id, title, status, source, confidence, staleness, created date. |
| `repowise decision show ID` | Full record including alternatives, consequences, affected files, and the evidence file and line. |
+| `repowise decision add --evidence-commit SHA` | Record which commit a decision was made in. Repeatable. The capture prompt passes it, and it is what stops the prompt asking again for a commit already recorded. |
| `repowise decision confirm ID...` | Accept candidates. Refuses, naming the gap, when one has no reason, scope or evidence; `--reason`, `--scope` and `--evidence` supply them. A refused id does not stop the others. `--preview` writes nothing. `--agent SLUG` signs as an agent rather than as you, and needs `decision config agent-acceptance --on`. |
| `repowise decision dismiss ID...` | Tombstone them. Never re-proposed on reindex. `--preview` writes nothing. |
| `repowise decision deprecate ID` | Retire it, optionally `--superseded-by <ID>`, which writes the lineage edge. |
@@ -691,6 +692,7 @@ the scope that decision governs.
| `repowise decision config show` | The resolved capture policy: every source, its status, and why. |
| `repowise decision config preset NAME` | Apply `off`, `local_only`, `balanced`, or `full`. |
| `repowise decision config agent-acceptance --on/--off` | Whether an agent may grant a decision authority. Off by default; no preset changes it. |
+| `repowise decision config capture-prompt --on/--off` | After a commit whose message states a choice, ask the agent once a session to record it. Off by default; no preset turns it on. `--on` also installs the `Bash\|PowerShell` PostToolUse entry it fires from, because the shared matcher deliberately excludes the shell tools; `--off` removes it, for every repository on the machine. Silent while `decisions.enabled` is off. |
| `repowise decision source list` | The source registry with capabilities and current state. |
| `repowise decision source set SRC --on/--off` | Switch one source. `--llm/--no-llm` switches only its model stage. |
| `repowise decision llm --on/--off` | Master switch for decision-extraction model calls. |
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 07516d642..c2af3a033 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1029,6 +1029,8 @@ repowise decision config show [PATH] # the resolved capture policy
repowise decision config preset NAME [PATH] # default | off | local_only | balanced | full
repowise decision config discovery [PATH] # budget for the one broad discovery call
repowise decision config agent-acceptance --on|--off # may an agent grant authority? off by default
+repowise decision config capture-prompt --on|--off # ask the agent to record what it just committed;
+ # off by default, and --on installs the shell hook it needs
repowise decision source list [PATH] # the source registry and its state
repowise decision source set SRC --on|--off # switch one source
repowise decision source set SRC --llm|--no-llm # switch only its model stage
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 5dbd98fb2..970272845 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -412,6 +412,7 @@ decisions:
harnesses: # whose transcripts the session lane reads
- claude_code # the default; add codex to read that store too
agent_acceptance: false # may an agent grant a decision authority?
+ capture_prompt: false # ask the agent to record what it just committed
```
`agent_acceptance` is the one key here that is not about capture. Off, an agent
@@ -420,6 +421,21 @@ accept, and the acceptance is recorded as an agent's — with the session that
signed it — on every surface, never as yours. It ships off and no preset turns
it on.
+`capture_prompt` is the other. On, a successful `git commit` whose message
+carries two or more decision signals prompts the agent, once per session, to
+run `repowise decision add` — never for a commit a record already cites, and
+never as anything but a proposal. An agent cannot decline a hook, so this also
+ships off and no preset turns it on:
+`repowise decision config capture-prompt --on`.
+
+That command also installs what it needs. The shared PostToolUse matcher
+deliberately excludes the shell tools — measured at 51% of hook invocations
+for 0.7% of emissions — so switching the prompt on adds a separate
+`Bash|PowerShell` PostToolUse entry, and switching it off removes it. The
+entry is per install rather than per repository: other repositories on the
+machine pay a process start on shell calls and emit nothing unless they
+switch it on too, and switching it off here turns it off for all of them.
+
Every key is optional. **A config with no `decisions:` block behaves exactly as
it did before these switches existed**: every source that shipped on is on,
model stages on. That resolved policy is named `default`. A source added after
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py
index 143e5c9b8..4567960cf 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py
@@ -53,6 +53,13 @@ def as_result(value: HookResult | str | None) -> HookResult:
return value
return HookResult(context=value or None)
+
+def join_notices(*notices: str | None) -> str | None:
+ """One context block from several handlers, or ``None`` when all are quiet."""
+ spoken = [n for n in notices if n]
+ return "\n".join(spoken) if spoken else None
+
+
#: Wall clock at the first moment repowise code runs in this hook process.
#: Every ledger row carries the elapsed time to its own write, which is the
#: part of hook latency repowise controls. It is a *lower bound* on what the
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/bash_staleness.py b/packages/cli/src/repowise/cli/commands/augment_cmd/bash_staleness.py
index b4716d27f..78c8944b9 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/bash_staleness.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/bash_staleness.py
@@ -39,7 +39,7 @@ def _handle_bash_post(tool_input: dict, tool_output: object, cwd: str) -> str |
out of sync.
"""
output = tool_output if isinstance(tool_output, dict) else {"stdout": str(tool_output)}
- exit_code = _extract_exit_code(output)
+ exit_code = extract_exit_code(output)
if exit_code is None:
stdout = output.get("stdout", "")
stderr = output.get("stderr", "")
@@ -191,7 +191,7 @@ def _record_warning(repo_path: object, head: str) -> None:
marker.write_text(head, encoding="utf-8")
-def _extract_exit_code(tool_output: dict) -> int | None:
+def extract_exit_code(tool_output: dict) -> int | None:
"""Extract a process exit code from known hook output shapes."""
for key in ("exit_code", "exitCode", "status"):
value = tool_output.get(key)
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 30f034769..b05463471 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
@@ -96,9 +96,10 @@ import click
from repowise.cli._setup import configure_cli_logging
from repowise.cli.agent_adapters import adapter_for
-from ._shared import HookResult, as_result
+from ._shared import HookResult, as_result, join_notices
from .bash_staleness import _handle_bash_post
from .codex import _handle_codex_context_event, _handle_post_edit_use
+from .decision_capture import commit_capture_notice
from .read_state import _handle_edit_post, _handle_read_post, _record_edit
from .search import _handle_search_post
from .served_reads import _handle_mcp_read_post, _log_read_after_served
@@ -389,7 +390,12 @@ def _handle_post_tool_use(
# The PowerShell tool (Windows Claude Code) and Codex's several names
# for its shell all surface the same stdout/stderr response shape as
# Bash — one handler covers them.
- return as_result(_handle_bash_post(tool_input, tool_output, cwd))
+ return as_result(
+ join_notices(
+ _handle_bash_post(tool_input, tool_output, cwd),
+ commit_capture_notice(tool_input, tool_output, cwd, session_id),
+ )
+ )
if tool_name in adapter.search_tool_names:
# The adapter reaches this one because the flood digest can *replace*
# the tool output, and not every harness's protocol can honour that.
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_capture.py b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_capture.py
new file mode 100644
index 000000000..15672ecd2
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_capture.py
@@ -0,0 +1,225 @@
+"""PostToolUse Bash: ask the agent to record the choice it just committed.
+
+The only write-side hook this layer has. Every other surface delivers what was
+already recorded; nothing asked for a record, and of the records this
+repository holds from ``decision add`` a person wrote all of them.
+
+**An agent cannot decline a hook**, so the gates matter more than the wording.
+This fires at most once per session, only after a fresh commit in *this*
+repository, only when the message carries two or more decision signals, and
+never for a commit a record already cites. It proposes; the agent decides and
+writes the record itself, which is what makes the record worth having — the
+agent knows what it chose and why, and a miner reading the message afterwards
+can only infer.
+
+Budget: no ``repowise.core`` import at module scope, raw :mod:`sqlite3`, and
+silence on every failure.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+import subprocess
+import time
+from pathlib import Path
+
+from ._shared import _find_repo_root
+
+#: How many distinct signal keywords the message must carry. One admits 58% of
+#: this repository's commits and two admits 25%; the once-per-session gate is
+#: what bounds the cost, and this keeps the session's one ask for a commit that
+#: reads like a choice.
+_MIN_SIGNALS = 2
+
+#: How recently HEAD must have been committed for this to be *that* commit.
+#: The success of the shell call cannot be trusted on its own — the PowerShell
+#: tool result carries no exit code, so a string scan is all that is left, and
+#: a commit subject saying "remove the old fatal handler" reads as a failure
+#: while `nothing to commit` reads as a success. Freshness answers the question
+#: the exit code was standing in for: did this call produce a new commit.
+#:
+#: Generous, because the hook fires when the whole shell call returns and not
+#: when ``git commit`` does — ``git commit && npm test`` is one call. It only
+#: has to separate this call's commit from yesterday's.
+_MAX_COMMIT_AGE_SECONDS = 900.0
+
+#: Only a commit. A merge or a rebase replays choices somebody already had the
+#: chance to record. ``--dry-run`` writes nothing, so it must not consume the
+#: session's one ask on whatever HEAD happens to be.
+_COMMIT_PATTERNS = ("git commit",)
+_NOT_A_COMMIT = ("--dry-run", "--no-verify --dry-run")
+
+_PROMPT = (
+ "[repowise] Commit {sha} states a choice and nothing records it. If it is a "
+ "decision a future edit should follow, record it while you still have the "
+ "reasoning:\n"
+ " repowise decision add --title '<short>' --decision '<what you chose>' "
+ "--rationale '<why, and what you rejected>' --affects <path> "
+ "--evidence-commit {sha} --format json\n"
+ " Lands as a candidate for review, never as a rule. Once a session. "
+ "Off: repowise decision config capture-prompt --off"
+)
+
+
+def commit_capture_notice(
+ tool_input: dict, tool_output: object, cwd: str, session_id: str
+) -> str | None:
+ """The capture prompt for a just-made commit, or ``None`` to stay quiet."""
+ try:
+ return _notice(tool_input, tool_output, cwd, session_id)
+ except Exception:
+ return None
+
+
+def _notice(tool_input: dict, tool_output: object, cwd: str, session_id: str) -> str | None:
+ command = tool_input.get("command", "")
+ if not isinstance(command, str):
+ return None
+ if not any(p in command for p in _COMMIT_PATTERNS) or any(
+ p in command for p in _NOT_A_COMMIT
+ ):
+ return None
+ if _failed(tool_output):
+ return None
+ # An unidentified session would share one state file with every other, and
+ # the flag below is claimed and never cleared, so one such call would
+ # silence the repository for good.
+ if not session_id:
+ return None
+
+ repo_path = _find_repo_root(Path(cwd))
+ if repo_path is None or not (repo_path / ".repowise").exists():
+ return None
+ # Checked before the session state is read: the switch ships off, so the
+ # opted-out repository should pay one config read and nothing else.
+ if not _capture_enabled(repo_path):
+ return None
+ # ``.repowise`` marks the indexed repository, not the git one. This tree
+ # nests other repositories inside it, and a commit made in one of those
+ # must not be read as a commit here.
+ here = _git_root(cwd)
+ if here is None or here != _git_root(str(repo_path)):
+ return None
+
+ sha, committed_at, message = _head_commit(repo_path)
+ # Both sides: a committer date ahead of this clock — a pulled commit, a
+ # machine whose clock jumped — otherwise passes an age test for free, and
+ # the age test is the only thing standing in for "did this call commit".
+ if not sha or abs(time.time() - committed_at) > _MAX_COMMIT_AGE_SECONDS:
+ return None
+
+ from repowise.core.analysis.decisions.commit_signals import count_decision_signals
+
+ if count_decision_signals(message) < _MIN_SIGNALS:
+ return None
+ if _already_recorded(repo_path, sha):
+ return None
+
+ from .read_state import _load_session_state, _save_session_state
+
+ state = _load_session_state(repo_path, session_id)
+ if state.get("capture_prompted"):
+ return None
+
+ from .command import _claim_emission
+
+ # Both hooks fire on one tool event, and the session state is a
+ # read-modify-write of a file the Read surfaces also own. Claiming first
+ # means the loser writes nothing: it neither clobbers that file nor spends
+ # the session's one ask on a prompt it will not return.
+ if not _claim_emission("decision-capture", f"{session_id}{chr(0)}{sha}"):
+ return None
+ # Claimed rather than confirmed: a session that saw the prompt and ignored
+ # it has still had its ask, and re-asking is the tax.
+ state["capture_prompted"] = True
+ if not _save_session_state(repo_path, state):
+ return None
+ return _PROMPT.format(sha=sha[:8])
+
+
+def _failed(tool_output: object) -> bool:
+ """Whether the shell call reported a non-zero exit.
+
+ Only the exit code, and only when the harness sent one. The string scan
+ that used to stand in for it is wrong in both directions, and freshness
+ covers the case where no code arrives at all.
+ """
+ from .bash_staleness import extract_exit_code
+
+ output = tool_output if isinstance(tool_output, dict) else {}
+ code = extract_exit_code(output)
+ return code is not None and code != 0
+
+
+def _capture_enabled(repo_path: Path) -> bool:
+ """Whether this repository switched the prompt on. Off is the default.
+
+ ``decisions.enabled`` gates it too. That flag is the master switch for
+ capture and ``preset off`` is how a repository says it wants none, so a
+ prompt that survived it would be the one part of the layer nobody could
+ turn off without knowing this switch by name.
+ """
+ from repowise.core.analysis.decisions.policy_store import load_policy
+
+ policy = load_policy(repo_path).policy
+ return bool(policy.enabled and policy.capture_prompt)
+
+
+def _git_root(path: str) -> str | None:
+ """The git work tree *path* sits in, as a resolved posix string."""
+ result = subprocess.run(
+ ["git", "rev-parse", "--show-toplevel"],
+ cwd=path,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ if result.returncode != 0 or not result.stdout.strip():
+ return None
+ return Path(result.stdout.strip()).resolve().as_posix()
+
+
+def _head_commit(repo_path: Path) -> tuple[str, float, str]:
+ """``(sha, committed_at, subject + body)`` for HEAD, or ``("", 0.0, "")``.
+
+ Read from git rather than parsed out of the command: a commit made with
+ ``-F``, a heredoc or an editor carries its message nowhere the hook can
+ see it. No ``--no-merges`` — that filters merges out of the walk and
+ returns an older ancestor, so finishing a conflicted merge with
+ ``git commit`` would gate on an unrelated commit.
+ """
+ result = subprocess.run(
+ ["git", "log", "-1", "--pretty=%H%n%ct%n%s%n%b"],
+ cwd=str(repo_path),
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ if result.returncode != 0:
+ return "", 0.0, ""
+ head, _, rest = result.stdout.partition("\n")
+ stamp, _, message = rest.partition("\n")
+ try:
+ committed_at = float(stamp.strip())
+ except ValueError:
+ return "", 0.0, ""
+ return head.strip(), committed_at, message.strip()
+
+
+def _already_recorded(repo_path: Path, sha: str) -> bool:
+ """Whether a record already cites this commit. Fails closed, into silence."""
+ from .decision_inject import _open_wiki_ro
+
+ conn = _open_wiki_ro(repo_path)
+ if conn is None:
+ return True
+ try:
+ row = conn.execute(
+ "SELECT 1 FROM decision_records WHERE evidence_commits_json LIKE ? LIMIT 1",
+ (f"%{sha[:8]}%",),
+ ).fetchone()
+ except sqlite3.Error:
+ return True
+ finally:
+ conn.close()
+ return row is not None
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 552c7f356..5daabf7ef 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
@@ -143,6 +143,10 @@ def _load_session_state(repo_path: Path, session_id: str) -> dict:
"read_whole": [],
"skeleton_edit_warned": [],
"decisions_shown": [],
+ # Whether this session has already been asked to record a decision.
+ # One ask per session is the whole cost control on a hook nobody can
+ # decline, so it is claimed on the ask and never cleared.
+ "capture_prompted": False,
# File ranges served by repowise MCP responses this session, kept for
# the read-after-served KPI (see read_enrich; rel -> [[start, end]]).
"served": {},
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index cb784c94b..3e71b6ca2 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -230,6 +230,12 @@ async def _resolve_decision_id(session, decision_id: str) -> str | None:
"--affects", "affected", multiple=True, help="A file or module this governs. Repeatable."
)
@click.option("--tag", "tags", multiple=True, help="A tag. Repeatable.")
+ "--evidence-commit",
+ "evidence_commits",
+ multiple=True,
+ help="A commit this decision was made in. Repeatable.",
+)
@click.option(
"--kind",
type=click.Choice(DECISION_KINDS),
@@ -248,6 +254,7 @@ def decision_add(
consequences: tuple[str, ...],
affected: tuple[str, ...],
tags: tuple[str, ...],
+ evidence_commits: tuple[str, ...],
kind: str,
fmt: str,
) -> None:
@@ -270,7 +277,7 @@ def decision_add(
non_interactive = bool(title and decision_text)
if not non_interactive:
flagged = any((title, context, decision_text, rationale)) or any(
- (alternatives, consequences, affected, tags)
+ (alternatives, consequences, affected, tags, evidence_commits)
)
if flagged or fmt == "json":
_ta.emit_error(
@@ -363,6 +370,9 @@ def decision_add(
# None derives them from the files; [] would clear them.
affected_modules=None,
tags=tags_list,
+ # What the capture hook suppresses on: without it, the hook
+ # asks again next session for a commit already recorded.
+ evidence_commits=list(evidence_commits),
kind=kind,
source="cli",
# No confidence: upsert_decision scores a manual entry.
diff --git a/packages/cli/src/repowise/cli/commands/decision_config_cmd.py b/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
index fb4bdbc17..8fe177868 100644
--- a/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
@@ -117,6 +117,29 @@ def _emit(repo_path: Path, resolution, fmt: str) -> None:
)
else:
console.print(" [dim]Agent acceptance: off. Agents withdraw authority, never grant it.[/dim]")
+ if policy.capture_prompt:
+ from repowise.cli.editor_integrations.claude_config import (
+ claude_code_capture_hook_installed,
+ )
+
+ console.print(
+ " [dim]Capture prompt: on. After a commit that states a choice, the "
+ "agent is asked once a session to record it.[/dim]"
+ )
+ if not policy.enabled:
+ console.print(
+ " [yellow] ...but decision capture is off for this repository, "
+ "so it stays silent. `decision config enable` to use it.[/yellow]"
+ )
+ elif not claude_code_capture_hook_installed():
+ # The flag is per repository and the hook is per install, so the
+ # two drift: another repository's --off removes the shared entry.
+ console.print(
+ " [yellow] ...but no shell hook is installed to fire it. "
+ "Re-run `decision config capture-prompt --on`.[/yellow]"
+ )
+ else:
+ console.print(" [dim]Capture prompt: off. Nothing asks an agent to record a decision.[/dim]")
console.print("")
for warning in resolution.warnings:
@@ -193,6 +216,14 @@ def _diff(before: DecisionPolicy, after: DecisionPolicy) -> list[dict[str, str]]
"to": str(after.agent_acceptance),
}
)
+ if before.capture_prompt != after.capture_prompt:
+ changes.append(
+ {
+ "key": "capture_prompt",
+ "from": str(before.capture_prompt),
+ "to": str(after.capture_prompt),
+ }
+ )
if before.harnesses != after.harnesses:
changes.append(
{
@@ -238,8 +269,9 @@ def config_preset(name: str, path: str | None, dry_run: bool, fmt: str) -> None:
from repowise.core.analysis.decisions.policy import preset_policy
repo_path = _resolve_decision_repo(path, fmt)
- # A preset names source membership; the harness list and the agent-grant
- # switch are not, so applying one leaves both as the caller set them.
+ # A preset names source membership. The harness list and the two agent
+ # switches are not membership, so applying one leaves them as the caller
+ # set them.
current = _load(repo_path).policy
_apply(
repo_path,
@@ -247,6 +279,7 @@ def config_preset(name: str, path: str | None, dry_run: bool, fmt: str) -> None:
preset_policy(name),
harnesses=current.harnesses,
agent_acceptance=current.agent_acceptance,
+ capture_prompt=current.capture_prompt,
),
fmt,
dry_run,
@@ -324,6 +357,74 @@ def config_agent_acceptance(
_apply(repo_path, current.with_agent_acceptance(bool(enabled)), fmt, dry_run)
+@config_group.command("capture-prompt")
[email protected]("path", required=False, default=None)
+ "--on/--off", "enabled", default=None, required=True, help="Ask the agent to record."
+)
[email protected]("--dry-run", is_flag=True, default=False, help="Show the change; write nothing.")
+@format_option()
+def config_capture_prompt(
+ path: str | None, enabled: bool | None, dry_run: bool, fmt: str
+) -> None:
+ """Ask the agent to record a decision after a commit that states one.
+
+ Off by default. An agent cannot decline a hook, so this fires at most once
+ a session, only on a commit whose message carries two or more decision
+ signals, and never on one a record already cites. It proposes; nothing is
+ recorded without the agent running `repowise decision add`.
+ """
+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo
+
+ repo_path = _resolve_decision_repo(path, fmt)
+ current = _load(repo_path).policy
+ _apply(repo_path, current.with_capture_prompt(bool(enabled)), fmt, dry_run)
+ if dry_run:
+ return
+ # The flag is per repository; the hook it fires from is a per-install
+ # matcher, and the shared one deliberately excludes the shell tools.
+ # Writing the flag without this would store a switch nothing reads.
+ from repowise.cli.editor_integrations.claude_config import (
+ claude_code_capture_hook_installed,
+ set_claude_code_capture_hook,
+ )
+
+ settings = set_claude_code_capture_hook(bool(enabled))
+ if fmt == "json":
+ emit_json(
+ {
+ "repo": str(repo_path),
+ "capture_prompt": bool(enabled),
+ "hook_settings_file": str(settings) if settings else None,
+ "hook_installed": claude_code_capture_hook_installed(),
+ }
+ )
+ return
+ if enabled and not claude_code_capture_hook_installed():
+ # The flag alone is a switch nothing reads. Silence here is the defect
+ # this command was changed to fix, one level down.
+ console.print(
+ "[yellow]Flag written, but no Claude Code settings file was found to "
+ "install the shell hook into, so nothing will fire it. Run "
+ "`repowise init` or install the editor integration first.[/yellow]"
+ )
+ return
+ if settings is None:
+ return
+ if enabled:
+ console.print(
+ f"[dim]Added a shell PostToolUse hook to {settings}. Other "
+ "repositories on this machine pay a process start on shell calls "
+ "and emit nothing unless they switch this on too.[/dim]"
+ )
+ else:
+ console.print(
+ f"[dim]Removed the shell PostToolUse hook from {settings}. Any "
+ "other repository using the capture prompt needs "
+ "`capture-prompt --on` again.[/dim]"
+ )
+
+
@click.group("source")
def source_group() -> None:
"""List and switch individual capture sources."""
diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
index a3842b5a7..c6dbc6ed8 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
@@ -260,6 +260,102 @@ _AUGMENT_HOOK_COMMAND = (
_FAILURE_MATCHER = "Read|Edit|Write|Grep|Glob|NotebookEdit"
+#: The shell tools, as their own PostToolUse entry rather than widened into
+#: :data:`_AUGMENT_MATCHER`. The capture prompt is the only thing that needs
+#: them, it is off by default, and the narrowing of the shared matcher is a
+#: measured decision this must not quietly reverse: 51% of hook invocations
+#: for 0.7% of emissions. A separate entry means the cost is paid only where
+#: the prompt is switched on, and removing it is removing one entry.
+#:
+#: **Never add this to :data:`_LEGACY_AUGMENT_MATCHERS`.** That list is what
+#: the self-heal rewrites to the narrow matcher, and this entry exists
+#: precisely to survive it.
+_CAPTURE_MATCHER = "Bash|PowerShell"
+
+
+def _capture_entry() -> dict:
+ return {
+ "matcher": _CAPTURE_MATCHER,
+ "hooks": [
+ {
+ "type": "command",
+ "command": _AUGMENT_HOOK_COMMAND,
+ "timeout": 10,
+ "statusMessage": "Checking for a decision to record...",
+ }
+ ],
+ }
+
+
+def _is_capture_entry(entry: object) -> bool:
+ if not isinstance(entry, dict) or entry.get("matcher") != _CAPTURE_MATCHER:
+ return False
+ entry_hooks = _hooks_of(entry)
+ return bool(entry_hooks) and all(_is_repowise_hook(h) for h in entry_hooks)
+
+
+def set_claude_code_capture_hook(enabled: bool) -> Path | None:
+ """Add or remove the shell PostToolUse entry the capture prompt needs.
+
+ The switch owns its own prerequisite: `decisions.capture_prompt` is a
+ per-repository policy, but the hook it fires from is a per-install
+ matcher, so turning the policy on without this writes a flag nothing
+ reads. Returns the settings file when it changed, else ``None``.
+
+ The entry is per *install*, so one repository opting in widens the surface
+ for every repository on this machine. They pay a process start on shell
+ calls and nothing else — the handler returns before any work when their
+ own policy is off — and turning it off here narrows it back for all of
+ them, which is why the caller says so.
+ """
+ settings_path = _claude_code_settings_path()
+ if not settings_path.exists():
+ return None
+ try:
+ existing = load_existing_config(settings_path)
+ except Exception:
+ return None
+
+ hooks = existing.setdefault("hooks", {}) if enabled else existing.get("hooks")
+ if not isinstance(hooks, dict):
+ return None
+ entries = hooks.get("PostToolUse")
+ if not isinstance(entries, list):
+ if not enabled:
+ return None
+ entries = []
+ hooks["PostToolUse"] = entries
+
+ present = any(_is_capture_entry(e) for e in entries)
+ if enabled == present:
+ return None
+ if enabled:
+ entries.append(_capture_entry())
+ else:
+ entries[:] = [e for e in entries if not _is_capture_entry(e)]
+ if not entries:
+ hooks.pop("PostToolUse", None)
+ if not hooks:
+ existing.pop("hooks", None)
+ return settings_path if _write_settings(settings_path, existing) else None
+
+
+def claude_code_capture_hook_installed() -> bool:
+ """Whether the shell PostToolUse entry is present."""
+ settings_path = _claude_code_settings_path()
+ if not settings_path.exists():
+ return False
+ try:
+ existing = load_existing_config(settings_path)
+ except Exception:
+ return False
+ hooks = existing.get("hooks")
+ if not isinstance(hooks, dict):
+ return False
+ entries = hooks.get("PostToolUse")
+ return isinstance(entries, list) and any(_is_capture_entry(e) for e in entries)
+
+
def _session_start_entry() -> dict:
return {
"matcher": _SESSION_START_MATCHER,
@@ -308,7 +404,7 @@ def _failure_entry() -> dict:
def install_claude_code_hooks() -> Path | None:
"""Register the augment hooks in ~/.claude/settings.json.
- PostToolUse detects git staleness, enriches Grep/Glob results, and emits
+ PostToolUse enriches Grep/Glob results and emits
Read-intelligence notices; SessionStart injects the live index-freshness
context block; PostToolUseFailure carries the wrong-path rescue. Existing
user hooks are preserved.
diff --git a/packages/core/src/repowise/core/analysis/decisions/commit_signals.py b/packages/core/src/repowise/core/analysis/decisions/commit_signals.py
new file mode 100644
index 000000000..02249bb9a
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/commit_signals.py
@@ -0,0 +1,45 @@
+"""Whether a commit message sounds like it states a choice.
+
+Deliberately stdlib-only and import-free: the capture hook runs inside the
+PostToolUse budget and cannot reach :mod:`extractor`, which is where these
+keywords used to live and which pulls the whole extraction stack. The miner
+and the hook must agree on what a signal is, so they share this module rather
+than a copy.
+
+The list is a cheap pre-filter, not a classifier. Measured over 137 commits on
+this repository, one keyword admits 58% of them — ``remove``, ``drop``,
+``split`` and ``extract`` are ordinary words in a commit subject. Two or more
+admits 25%. Callers choose their own threshold.
+"""
+
+from __future__ import annotations
+
+__all__ = ["DECISION_SIGNAL_KEYWORDS", "count_decision_signals"]
+
+DECISION_SIGNAL_KEYWORDS = [
+ "migrate",
+ "migration",
+ "switch to",
+ "replace",
+ "replaced",
+ "refactor to",
+ "move from",
+ "adopt",
+ "introduce",
+ "deprecate",
+ "remove",
+ "drop",
+ "upgrade",
+ "rewrite",
+ "extract",
+ "split",
+ "convert",
+ "transition",
+ "revert",
+]
+
+
+def count_decision_signals(text: str) -> int:
+ """How many distinct signal keywords *text* contains, case-insensitively."""
+ low = text.lower()
+ return sum(1 for keyword in DECISION_SIGNAL_KEYWORDS if keyword in low)
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.py
index 0173e279b..03a15cafa 100644
--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py
+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py
@@ -63,6 +63,7 @@ from repowise.core.analysis.decisions.scope import (
from repowise.core.fs_walk import PRUNED_DIRS, walk_repo
from repowise.core.ingestion.traverser import load_gitignore_spec
+from .commit_signals import count_decision_signals
from .prompts import (
_SYSTEM_PROMPT,
COMMENT_ARCHAEOLOGY_PROMPT,
@@ -375,31 +376,6 @@ _BINARY_EXTENSIONS = frozenset(
}
)
-# ---------------------------------------------------------------------------
-# Decision signal keywords for git archaeology
-# ---------------------------------------------------------------------------
-
-DECISION_SIGNAL_KEYWORDS = [
- "migrate",
- "migration",
- "switch to",
- "replace",
- "replaced",
- "refactor to",
- "move from",
- "adopt",
- "introduce",
- "deprecate",
- "remove",
- "drop",
- "upgrade",
- "rewrite",
- "extract",
- "split",
- "convert",
- "transition",
- "revert",
-]
# ---------------------------------------------------------------------------
# ADR / PR / comment source configuration
@@ -767,7 +743,7 @@ class DecisionExtractor:
# Scan subject + body for signals — squash-merge repos carry the
# decision rationale in the body, not the one-line subject.
signal_text = f"{msg}\n{body}".lower()
- signal_count = sum(1 for kw in DECISION_SIGNAL_KEYWORDS if kw in signal_text)
+ signal_count = count_decision_signals(signal_text)
if signal_count > 0:
commit_map[sha] = {
"sha": sha,
@@ -1051,7 +1027,7 @@ class DecisionExtractor:
continue
low = body.lower()
is_prish = c.get("pr_number") is not None or any(m in low for m in _PR_BODY_MARKERS)
- has_signal = any(k in low for k in DECISION_SIGNAL_KEYWORDS)
+ has_signal = count_decision_signals(low) > 0
if is_prish and has_signal:
candidates[sha] = {
"sha": sha,
diff --git a/packages/core/src/repowise/core/analysis/decisions/policy.py b/packages/core/src/repowise/core/analysis/decisions/policy.py
index 57875cfe1..58d5bc3eb 100644
--- a/packages/core/src/repowise/core/analysis/decisions/policy.py
+++ b/packages/core/src/repowise/core/analysis/decisions/policy.py
@@ -348,6 +348,9 @@ class DecisionPolicy:
#: setting here that lets something other than a person create a
#: constraint, so it ships off and no preset turns it on.
agent_acceptance: bool = False
+ #: Whether the commit hook asks the agent to record a decision. An agent
+ #: cannot decline a hook, so this ships off and no preset turns it on.
+ capture_prompt: bool = False
# -- queries ---------------------------------------------------------
@@ -496,6 +499,8 @@ class DecisionPolicy:
block["harnesses"] = list(self.harnesses)
if self.agent_acceptance:
block["agent_acceptance"] = True
+ if self.capture_prompt:
+ block["capture_prompt"] = True
return block
def to_dict(self, *, provider_available: bool = True) -> dict[str, Any]:
@@ -507,6 +512,7 @@ class DecisionPolicy:
"discovery": self.discovery.to_dict(),
"harnesses": list(self.harnesses),
"agent_acceptance": self.agent_acceptance,
+ "capture_prompt": self.capture_prompt,
"sources": [rt.to_dict() for rt in self.runtime(provider_available=provider_available)],
}
@@ -544,6 +550,9 @@ class DecisionPolicy:
def with_agent_acceptance(self, value: bool) -> DecisionPolicy:
return replace(self, agent_acceptance=value)
+ def with_capture_prompt(self, value: bool) -> DecisionPolicy:
+ return replace(self, capture_prompt=value)
+
@dataclass(frozen=True, slots=True)
class PolicyResolution:
@@ -623,6 +632,7 @@ POLICY_CONFIG_KEYS: frozenset[str] = frozenset(
"discovery",
"harnesses",
"agent_acceptance",
+ "capture_prompt",
}
)
@@ -780,6 +790,12 @@ def resolve_policy(repo_config: dict[str, Any] | None) -> PolicyResolution:
warnings.append("`decisions.agent_acceptance` is not a boolean; ignoring it.")
agent_acceptance = False
+ capture_prompt = _as_bool(raw.get("capture_prompt"))
+ if capture_prompt is None:
+ if "capture_prompt" in raw:
+ warnings.append("`decisions.capture_prompt` is not a boolean; ignoring it.")
+ capture_prompt = False
+
for field in set(raw) - POLICY_CONFIG_KEYS:
warnings.append(f"Unknown key `decisions.{field}`; ignoring it.")
@@ -791,6 +807,7 @@ def resolve_policy(repo_config: dict[str, Any] | None) -> PolicyResolution:
discovery=discovery,
harnesses=harnesses,
agent_acceptance=agent_acceptance,
+ capture_prompt=capture_prompt,
),
warnings=tuple(warnings),
legacy_keys=tuple(legacy),
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index 988f231cf..d08fffb44 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -334,7 +334,12 @@ async def upsert_decision(
scope_modules(affected_files or [], affected_modules)
)
rec.tags_json = json.dumps(tags or [])
- rec.evidence_commits_json = json.dumps(evidence_commits or [])
+ # ``None`` leaves the commits alone, like ``kind`` above: a caller
+ # restating a record without naming them has not disowned them, and
+ # the capture hook's suppression reads this column — wiping it asks
+ # the agent again for a decision it has already recorded.
+ if evidence_commits is not None:
+ rec.evidence_commits_json = json.dumps(evidence_commits)
rec.evidence_line = evidence_line
rec.confidence = confidence
rec.verification = verification
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index 40a491710..e4dcbf90b 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -444,6 +444,7 @@ async def update_decision_settings(
discovery=policy.discovery,
harnesses=policy.harnesses,
agent_acceptance=policy.agent_acceptance,
+ capture_prompt=policy.capture_prompt,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
diff --git a/tests/unit/cli/test_augment_decision_capture.py b/tests/unit/cli/test_augment_decision_capture.py
new file mode 100644
index 000000000..b337e60b7
--- /dev/null
+++ b/tests/unit/cli/test_augment_decision_capture.py
@@ -0,0 +1,471 @@
+"""The capture prompt: the gates, not the wording.
+
+An agent cannot decline a hook, so every gate is a cost control and each one
+is tested on its own. The contract: off unless the repository switched it on,
+at most once per session, only after a *fresh* commit in *this* repository,
+only on a message carrying two or more decision signals, and never for a
+commit a record already cites.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+import subprocess
+import time
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands.augment_cmd import decision_capture
+from repowise.cli.commands.augment_cmd.decision_capture import commit_capture_notice
+
+_MESSAGE = "refactor to one queue\n\nReplace the three ad-hoc queues; migrate callers."
+_SHA = "abc12345deadbeefcafe0000111122223333aaaa"
+_COMMIT = {"command": "git commit -m 'refactor to one queue'"}
+_OK = {"exit_code": 0, "stdout": "", "stderr": ""}
+
+
[email protected](autouse=True)
+def _no_cross_test_claim(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The emission claim is a temp-dir marker; keep tests independent of it."""
+ from repowise.cli.commands.augment_cmd import command
+
+ monkeypatch.setattr(command, "_claim_emission", lambda event, context: True)
+
+
+def repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ root = tmp_path / "repo"
+ (root / ".repowise").mkdir(parents=True)
+ _write_policy(root, capture_prompt=True)
+ _write_wiki(root, evidence=[])
+ _fake_git(monkeypatch, root, _SHA, _MESSAGE)
+ return root
+
+
+def _write_policy(root: Path, *, capture_prompt: bool) -> None:
+ (root / ".repowise" / "config.yaml").write_text(
+ "decisions:\n capture_prompt: " + ("true" if capture_prompt else "false") + "\n",
+ encoding="utf-8",
+ )
+
+
+def _write_wiki(root: Path, *, evidence: list[str]) -> None:
+ conn = sqlite3.connect(root / ".repowise" / "wiki.db")
+ conn.execute(
+ "CREATE TABLE decision_records (id TEXT PRIMARY KEY, evidence_commits_json TEXT)"
+ )
+ for i, sha in enumerate(evidence):
+ conn.execute("INSERT INTO decision_records VALUES (?, ?)", (str(i), json.dumps([sha])))
+ conn.commit()
+ conn.close()
+
+
+def _fake_git(
+ monkeypatch: pytest.MonkeyPatch,
+ root: Path,
+ sha: str,
+ message: str,
+ *,
+ age: float = 1.0,
+ nested_root: Path | None = None,
+ log_returncode: int = 0,
+) -> None:
+ """Stand in for both git calls: the work-tree root and HEAD.
+
+ *nested_root* is what ``rev-parse`` answers for a cwd that is not the
+ repowise root — the sibling-repo layout this tree actually has.
+ """
+ stamp = int(time.time() - age)
+
+ def _run(args, **kwargs):
+ if "rev-parse" in args:
+ here = kwargs.get("cwd")
+ where = nested_root if (nested_root and here != str(root)) else root
+ return subprocess.CompletedProcess(args, 0, stdout=f"{where}\n", stderr="")
+ return subprocess.CompletedProcess(
+ args, log_returncode, stdout=f"{sha}\n{stamp}\n{message}", stderr=""
+ )
+
+ monkeypatch.setattr(decision_capture.subprocess, "run", _run)
+
+
+def _fire(root: Path, session: str = "s1", **over) -> str | None:
+ payload = {"tool_input": _COMMIT, "tool_output": _OK, "cwd": str(root), "session_id": session}
+ payload.update(over)
+ return commit_capture_notice(
+ payload["tool_input"], payload["tool_output"], payload["cwd"], payload["session_id"]
+ )
+
+
+# --- it fires ---------------------------------------------------------------
+
+
+def test_it_fires_on_a_commit_that_states_a_choice(repo: Path) -> None:
+ notice = _fire(repo)
+ assert notice is not None
+ assert "repowise decision add" in notice
+ # The sha is in the prompt so the record can cite it and suppress the ask.
+ assert _SHA[:8] in notice
+ assert "--evidence-commit" in notice
+
+
+def test_it_fires_at_most_once_a_session(repo: Path) -> None:
+ assert _fire(repo) is not None
+ assert _fire(repo) is None
+
+
+def test_a_second_session_gets_its_own_ask(repo: Path) -> None:
+ assert _fire(repo, session="s1") is not None
+ assert _fire(repo, session="s2") is not None
+
+
+# --- the switch -------------------------------------------------------------
+
+
+def test_off_by_default(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ root = tmp_path / "repo"
+ (root / ".repowise").mkdir(parents=True)
+ _write_wiki(root, evidence=[])
+ _fake_git(monkeypatch, root, _SHA, _MESSAGE)
+
+ assert _fire(root) is None
+
+
+def test_the_off_switch_turns_it_off(repo: Path) -> None:
+ _write_policy(repo, capture_prompt=False)
+
+ assert _fire(repo) is None
+
+
+def test_an_absent_key_resolves_to_off(tmp_path: Path) -> None:
+ """The parser's own default, not the dataclass field the parser overrides."""
+ from repowise.core.analysis.decisions.policy_store import load_policy
+
+ root = tmp_path / "unconfigured"
+ (root / ".repowise").mkdir(parents=True)
+
+ assert load_policy(root).policy.capture_prompt is False
+
+
+def test_a_non_boolean_switch_warns_and_stays_off(tmp_path: Path) -> None:
+ from repowise.core.analysis.decisions.policy_store import load_policy
+
+ root = tmp_path / "typo"
+ (root / ".repowise").mkdir(parents=True)
+ (root / ".repowise" / "config.yaml").write_text(
+ "decisions:\n capture_prompt: yesplease\n", encoding="utf-8"
+ )
+
+ resolved = load_policy(root)
+ assert resolved.policy.capture_prompt is False
+ assert any("capture_prompt" in w for w in resolved.warnings)
+
+
+def test_a_preset_does_not_switch_it_off(tmp_path: Path) -> None:
+ """A preset names source membership; it must not reset an agent switch."""
+ from dataclasses import replace
+
+ from repowise.core.analysis.decisions.policy import preset_policy
+ from repowise.core.analysis.decisions.policy_store import load_policy, write_policy
+
+ root = tmp_path / "preset"
+ (root / ".repowise").mkdir(parents=True)
+ _write_policy(root, capture_prompt=True)
+ current = load_policy(root).policy
+
+ write_policy(
+ root,
+ replace(
+ preset_policy("balanced"),
+ harnesses=current.harnesses,
+ agent_acceptance=current.agent_acceptance,
+ capture_prompt=current.capture_prompt,
+ ),
+ )
+
+ assert load_policy(root).policy.capture_prompt is True
+
+
+# --- what counts as the commit ---------------------------------------------
+
+
+def test_a_failed_commit_says_nothing(repo: Path) -> None:
+ assert _fire(repo, tool_output={"exit_code": 1, "stdout": "", "stderr": ""}) is None
+
+
+def test_a_status_key_is_read_as_an_exit_code(repo: Path) -> None:
+ """One answer to "did that shell call succeed", shared with the staleness hook."""
+ assert _fire(repo, tool_output={"status": 1, "stdout": "", "stderr": ""}) is None
+
+
+def test_a_subject_that_says_error_still_fires(repo: Path, monkeypatch) -> None:
+ """The old string scan read this as a failed commit. It is the target case."""
+ _fake_git(
+ monkeypatch, repo, _SHA, "refactor to one error path; remove the old fatal handler"
+ )
+
+ notice = _fire(repo, tool_output={"stdout": "[main abc1234] refactor to one error path"})
+
+ assert notice is not None
+
+
+def test_a_stale_head_is_not_this_commit(repo: Path, monkeypatch) -> None:
+ """`git commit` with nothing staged prints no "error" and leaves HEAD alone."""
+ _fake_git(monkeypatch, repo, _SHA, _MESSAGE, age=86_400)
+
+ assert _fire(repo, tool_output={"stdout": "nothing to commit, working tree clean"}) is None
+
+
+def test_a_dry_run_does_not_consume_the_ask(repo: Path) -> None:
+ assert _fire(repo, tool_input={"command": "git commit --dry-run"}) is None
+ assert _fire(repo) is not None
+
+
+def test_a_non_commit_shell_call_says_nothing(repo: Path) -> None:
+ assert _fire(repo, tool_input={"command": "git status"}) is None
+
+
+def test_a_merge_is_not_a_commit_worth_asking_about(repo: Path) -> None:
+ assert _fire(repo, tool_input={"command": "git merge --no-ff feature"}) is None
+
+
+def test_a_commit_in_a_nested_repository_is_not_this_one(
+ repo: Path, monkeypatch, tmp_path: Path
+) -> None:
+ """`backend/` and `frontend/` are separate git repos inside this tree."""
+ nested = repo / "backend"
+ nested.mkdir(parents=True, exist_ok=True)
+ _fake_git(monkeypatch, repo, _SHA, _MESSAGE, nested_root=nested)
+
+ assert _fire(repo, cwd=str(nested)) is None
+
+
+def test_an_unidentified_session_says_nothing(repo: Path) -> None:
+ """One shared state file, and the flag is never cleared: it would be permanent."""
+ assert _fire(repo, session="") is None
+ assert _fire(repo, session="s1") is not None
+
+
+# --- what counts as a choice ------------------------------------------------
+
+
+def test_one_signal_is_not_enough(repo: Path, monkeypatch) -> None:
+ _fake_git(monkeypatch, repo, _SHA, "remove a stray newline")
+
+ assert _fire(repo) is None
+
+
+def test_a_commit_a_record_already_cites_says_nothing(repo: Path) -> None:
+ (repo / ".repowise" / "wiki.db").unlink()
+ _write_wiki(repo, evidence=[_SHA[:8]])
+
+ assert _fire(repo) is None
+
+
+def test_an_unreadable_store_stays_quiet_rather_than_guessing(repo: Path) -> None:
+ (repo / ".repowise" / "wiki.db").write_text("not a database", encoding="utf-8")
+
+ assert _fire(repo) is None
+
+
+def test_a_missing_store_stays_quiet_rather_than_guessing(repo: Path) -> None:
+ (repo / ".repowise" / "wiki.db").unlink()
+
+ assert _fire(repo) is None
+
+
+def test_a_git_failure_stays_quiet(repo: Path, monkeypatch) -> None:
+ _fake_git(monkeypatch, repo, _SHA, _MESSAGE, log_returncode=128)
+
+ assert _fire(repo) is None
+
+
+def test_the_session_is_claimed_even_though_the_agent_may_ignore_it(repo: Path) -> None:
+ _fire(repo)
+ state = json.loads(
+ next((repo / ".repowise" / "hook-sessions").glob("*.json")).read_text(encoding="utf-8")
+ )
+ assert state["capture_prompted"] is True
+
+
+def test_the_prompt_carries_no_console_markup(repo: Path) -> None:
+ """`additionalContext` reaches the agent as text; rich markup would be literal."""
+ notice = _fire(repo)
+
+ assert "[dim]" not in notice and "[/dim]" not in notice
+
+
+def test_a_commit_dated_ahead_of_this_clock_is_not_fresh(repo: Path, monkeypatch) -> None:
+ """A one-sided age test passes a future stamp for free."""
+ _fake_git(monkeypatch, repo, _SHA, _MESSAGE, age=-3600)
+
+ assert _fire(repo) is None
+
+
+def test_a_commit_and_a_slow_follow_up_still_fires(repo: Path, monkeypatch) -> None:
+ """The hook fires when the whole shell call returns, not when git does."""
+ _fake_git(monkeypatch, repo, _SHA, _MESSAGE, age=300)
+
+ assert _fire(repo, tool_input={"command": "git commit -am wip && npm test"}) is not None
+
+
+def test_two_unknown_git_roots_are_not_a_match(repo: Path, monkeypatch) -> None:
+ """`None == None` read as "the roots match"."""
+
+ def _run(args, **kwargs):
+ if "rev-parse" in args:
+ return subprocess.CompletedProcess(args, 128, stdout="", stderr="not a git repo")
+ return subprocess.CompletedProcess(args, 0, stdout=f"{_SHA}\n{int(time.time())}\n{_MESSAGE}")
+
+ monkeypatch.setattr(decision_capture.subprocess, "run", _run)
+
+ assert _fire(repo) is None
+
+
+def test_the_loser_of_the_claim_keeps_its_ask(repo: Path, monkeypatch) -> None:
+ """Claiming after the state write burns the session on a prompt never shown."""
+ from repowise.cli.commands.augment_cmd import command
+
+ monkeypatch.setattr(command, "_claim_emission", lambda event, context: False)
+ assert _fire(repo) is None
+
+ monkeypatch.setattr(command, "_claim_emission", lambda event, context: True)
+ assert _fire(repo) is not None
+
+
+# --- the switch installs its own prerequisite --------------------------------
+
+
+def settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """A Claude Code settings.json carrying the narrowed augment entry."""
+ from repowise.cli.editor_integrations import claude_config
+
+ path = tmp_path / "settings.json"
+ path.write_text(
+ json.dumps(
+ {
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": claude_config._AUGMENT_MATCHER,
+ "hooks": [
+ {
+ "type": "command",
+ "command": claude_config._AUGMENT_HOOK_COMMAND,
+ }
+ ],
+ }
+ ]
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: path)
+ return path
+
+
+def _post_matchers(path: Path) -> list[str]:
+ hooks = json.loads(path.read_text(encoding="utf-8")).get("hooks", {})
+ return [e.get("matcher") for e in hooks.get("PostToolUse", [])]
+
+
+def test_switching_on_adds_the_shell_entry(settings: Path) -> None:
+ """Without it the policy is a flag no hook ever reads."""
+ from repowise.cli.editor_integrations.claude_config import set_claude_code_capture_hook
+
+ assert set_claude_code_capture_hook(True) == settings
+
+ assert "Bash|PowerShell" in _post_matchers(settings)
+
+
+def test_switching_off_removes_it(settings: Path) -> None:
+ from repowise.cli.editor_integrations.claude_config import set_claude_code_capture_hook
+
+ set_claude_code_capture_hook(True)
+ assert set_claude_code_capture_hook(False) == settings
+
+ assert "Bash|PowerShell" not in _post_matchers(settings)
+
+
+def test_both_directions_are_idempotent(settings: Path) -> None:
+ from repowise.cli.editor_integrations.claude_config import set_claude_code_capture_hook
+
+ set_claude_code_capture_hook(True)
+ assert set_claude_code_capture_hook(True) is None
+ set_claude_code_capture_hook(False)
+ assert set_claude_code_capture_hook(False) is None
+
+
+def test_it_leaves_the_narrowed_augment_entry_alone(settings: Path) -> None:
+ """The shared matcher's narrowing is a measured decision, not ours to undo."""
+ from repowise.cli.editor_integrations import claude_config
+
+ claude_config.set_claude_code_capture_hook(True)
+
+ assert claude_config._AUGMENT_MATCHER in _post_matchers(settings)
+
+
+def test_the_self_heal_does_not_strip_it(settings: Path) -> None:
+ """It survives the migration that rewrites every legacy wide matcher."""
+ from repowise.cli.editor_integrations import claude_config
+
+ assert "Bash|PowerShell" not in claude_config._LEGACY_AUGMENT_MATCHERS
+ claude_config.set_claude_code_capture_hook(True)
+
+ claude_config.migrate_claude_code_hooks()
+
+ assert "Bash|PowerShell" in _post_matchers(settings)
+
+
+def test_the_augment_uninstall_takes_it_too(settings: Path) -> None:
+ from repowise.cli.editor_integrations import claude_config
+
+ claude_config.set_claude_code_capture_hook(True)
+
+ claude_config.uninstall_claude_code_augment_hooks()
+
+ assert "Bash|PowerShell" not in _post_matchers(settings)
+
+
+def test_a_users_own_shell_hook_survives_the_removal(settings: Path) -> None:
+ from repowise.cli.editor_integrations import claude_config
+
+ payload = json.loads(settings.read_text(encoding="utf-8"))
+ payload["hooks"]["PostToolUse"].append(
+ {"matcher": "Bash|PowerShell", "hooks": [{"type": "command", "command": "mytool"}]}
+ )
+ settings.write_text(json.dumps(payload), encoding="utf-8")
+ claude_config.set_claude_code_capture_hook(True)
+
+ claude_config.set_claude_code_capture_hook(False)
+
+ remaining = json.loads(settings.read_text(encoding="utf-8"))["hooks"]["PostToolUse"]
+ assert any(
+ h.get("command") == "mytool" for e in remaining for h in e.get("hooks", [])
+ )
+
+
+def test_the_master_capture_switch_silences_it(repo: Path) -> None:
+ """`preset off` must not leave one part of the layer nobody can turn off."""
+ (repo / ".repowise" / "config.yaml").write_text(
+ "decisions:\n enabled: false\n capture_prompt: true\n", encoding="utf-8"
+ )
+
+ assert _fire(repo) is None
+
+
+def test_the_hook_entry_is_not_installed_without_a_settings_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A flag nothing reads is the defect the switch was changed to fix."""
+ from repowise.cli.editor_integrations import claude_config
+
+ missing = tmp_path / "nope" / "settings.json"
+ monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: missing)
+
+ assert claude_config.set_claude_code_capture_hook(True) is None
+ assert claude_config.claude_code_capture_hook_installed() is False
diff --git a/tests/unit/persistence/test_decision_scope_links.py b/tests/unit/persistence/test_decision_scope_links.py
index 098c4faaf..defbf0e41 100644
--- a/tests/unit/persistence/test_decision_scope_links.py
+++ b/tests/unit/persistence/test_decision_scope_links.py
@@ -345,3 +345,51 @@ async def test_upsert_derives_modules_when_none_are_given(async_session):
rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
assert await _links(async_session, rec.id) == {("a/one.py", "file"), ("a", "module")}
+
+
+async def test_restating_a_record_keeps_the_commit_it_cites(async_session):
+ """Otherwise the capture prompt re-arms for a decision already recorded."""
+ repo = await insert_repo(async_session)
+ first = await upsert_decision(
+ async_session,
+ repository_id=repo.id,
+ title="Use one queue",
+ decision="One queue.",
+ source="cli",
+ evidence_commits=["abc12345"],
+ )
+ assert json.loads(first.evidence_commits_json) == ["abc12345"]
+
+ again = await upsert_decision(
+ async_session,
+ repository_id=repo.id,
+ title="Use one queue",
+ decision="One queue, refined.",
+ source="cli",
+ )
+
+ assert again.id == first.id
+ assert json.loads(again.evidence_commits_json) == ["abc12345"]
+
+
+async def test_an_explicit_empty_list_still_disowns_them(async_session):
+ repo = await insert_repo(async_session)
+ await upsert_decision(
+ async_session,
+ repository_id=repo.id,
+ title="Use one queue",
+ decision="One queue.",
+ source="cli",
+ evidence_commits=["abc12345"],
+ )
+
+ again = await upsert_decision(
+ async_session,
+ repository_id=repo.id,
+ title="Use one queue",
+ decision="One queue.",
+ source="cli",
+ evidence_commits=[],
+ )
+
+ assert json.loads(again.evidence_commits_json) == []