diff --git a/corpus/CLAUDE.learned.md b/corpus/CLAUDE.learned.md
index a0915658..3ba236dd 100644
--- a/corpus/CLAUDE.learned.md
+++ b/corpus/CLAUDE.learned.md
@@ -45,3 +45,4 @@ Engine-only install drops this file; reflect Accepted global rules land here.
- Before asking me whether to run a script, read its whole body, not its header comment, usage text, or `--dry-run` output, and name in the question every process it kills, file it deletes, and service it restarts. A header states what the author meant; the body is what runs, so a consent question built from the header asks me to approve something other than what will happen. No known prior art.
- When finishing a merge or rebase, reconcile three things before calling it resolved: what each side declared (its commit messages and PR description: the intent, and the tests it names), what each side's code actually does, and what the resolved result does. All three must agree: every declared intent is still visible in `git diff -- `, and every test either side named still passes on the result. A merge with no textual conflict can still break one side's declared behavior, so a clean merge is checked the same way. Never take one side's whole file (`git checkout --theirs` / `--ours `, or copying the file from one branch) unless the other side's changes to that file are provably empty; taking a whole side silently reverts what the other branch added, including hunks that never conflicted (git-checkout(1), `--ours`/`--theirs`: https://git-scm.com/docs/git-checkout#Documentation/git-checkout.txt---ours). When a declaration and its code disagree, or the two sides' intents contradict, stop and flag it to me instead of choosing: run `why` on the conflicting lines (`git log -L` or `git log -S` plus each commit's PR body) and apply `principle-prove-it`, so the flag names the two commits or PRs, quotes the declared intent next to the code, and pastes the failing test output. Brun, Holmes, Ernst and Notkin, "Proactive Detection of Collaboration Conflicts" (ESEC/FSE 2011, https://doi.org/10.1145/2025113.2025139), across Git, Perl5 and Voldemort, found "that 33% of merges that were reported to contain no textual conflicts by the VCS in fact contained higher-order conflicts" (build or test failures), so a clean textual merge is not evidence the two intentions still hold.
- An item I approved as "fix it properly later" stays in every status update and every final summary, marked open, until it is done or I drop it. A recap that lists only what finished makes the deferred half disappear, and the next session never learns it was owed. No known prior art.
+- Before spending more than a couple of tool calls on an infrastructure, security, or "does X exist" question, search saved memory for the topic and for its reverse framing: the fix as well as the symptom, "X is off" as well as "X is missing". An answer already written down costs one read; rediscovering it costs the whole investigation. No known prior art.
diff --git a/engine/hooks/_sdk/runtime.py b/engine/hooks/_sdk/runtime.py
index d1ea4351..d4db3c5c 100644
--- a/engine/hooks/_sdk/runtime.py
+++ b/engine/hooks/_sdk/runtime.py
@@ -25,7 +25,7 @@ def run_hook(
event = json.load(sys.stdin)
except json.JSONDecodeError as exc:
_write_findings_file([])
- print(f"catstack-hook-error {hook}: JSONDecodeError: {exc}", file=sys.stderr)
+ print(f"catstack-hook-error {hook}: JSONDecodeError: hook payload is not JSON: {exc}", file=sys.stderr)
stdout_text, _stderr_text, _exit_code = render(
harness,
hook_event_name or "",
diff --git a/engine/hooks/cat-mode-default/README.md b/engine/hooks/cat-mode-default/README.md
index dc571635..d293dfc9 100644
--- a/engine/hooks/cat-mode-default/README.md
+++ b/engine/hooks/cat-mode-default/README.md
@@ -60,13 +60,22 @@ It stays silent when the flag is off or when the prompt already mentions
cat-mode anywhere (a parent that told the subagent to read it gets no
second copy). Same flag resolution as the prompt hook.
+The shared registry keeps this hook in `warn` mode. Set
+`CATSTACK_HOOK_MODE_CAT_MODE_DEFAULT=off|warn|stop` for a machine-local
+override; `stop` turns the `PreToolUse` (Agent) companion into a real block
+(exit 2) instead of rewriting the subagent's prompt. Detection or metrics
+failures allow the harness action.
+
## Files
-- `detect.py`: flag resolution, typed `/cat-mode` detection, context text.
-- `claude_prompt_submit.py`: the Claude entrypoint; fail-open, never denies.
-- `claude.prompt.hook.json`: settings fragment `install_claude_hook.py` merges.
-- `claude_pretooluse_agent.py` + `claude.agent.hook.json`: the `PreToolUse`
- (`Agent`) companion that carries the default into subagent prompts.
+- `detect.py`: flag resolution, typed `/cat-mode` detection, context text,
+ and `detect(event)`, the SDK entrypoint returning `Finding` objects.
+- `claude_prompt_submit.py` / `claude_pretooluse_agent.py`: thin calls into
+ `engine/hooks/_sdk/runtime.py`. The agent finding carries
+ `output={"updatedInput": ...}`, which the shared renderer emits as
+ `updatedInput` rather than its generic `additionalContext`.
+- `claude.prompt.hook.json` / `claude.agent.hook.json`: settings fragments
+ `install_claude_hook.py` merges.
- `tests/fixtures/*.json`: one scenario each (fires / silent) with the
environment, optional `.env` content, and payload.
- `tests/fixtures/agent_*.json`: the same for the Agent-tool companion.
diff --git a/engine/hooks/cat-mode-default/tests/test_agent_hook.py b/engine/hooks/cat-mode-default/tests/test_agent_hook.py
index c87cfafd..c4427043 100644
--- a/engine/hooks/cat-mode-default/tests/test_agent_hook.py
+++ b/engine/hooks/cat-mode-default/tests/test_agent_hook.py
@@ -13,6 +13,7 @@
import json
import os
import sys
+import tempfile
import unittest
from contextlib import redirect_stderr, redirect_stdout
from unittest.mock import patch
@@ -150,6 +151,19 @@ def test_unrelated_prompt_does_not_count(self) -> None:
class FailOpenCase(unittest.TestCase):
+ def setUp(self) -> None:
+ self.tmp = tempfile.TemporaryDirectory()
+ self.metrics_env = patch.dict(
+ os.environ,
+ {"CATSTACK_HOOK_METRICS_DIR": self.tmp.name},
+ clear=False,
+ )
+ self.metrics_env.start()
+
+ def tearDown(self) -> None:
+ self.metrics_env.stop()
+ self.tmp.cleanup()
+
def test_malformed_stdin_prints_nothing(self) -> None:
out = io.StringIO()
with patch.object(sys, "stdin", io.StringIO("not json")):
diff --git a/engine/hooks/cat-mode-default/tests/test_hooks.py b/engine/hooks/cat-mode-default/tests/test_hooks.py
index 9a080562..61b0a782 100644
--- a/engine/hooks/cat-mode-default/tests/test_hooks.py
+++ b/engine/hooks/cat-mode-default/tests/test_hooks.py
@@ -260,6 +260,19 @@ def test_flags_missing_install_instead_of_dead_path(self) -> None:
class FailOpenCase(unittest.TestCase):
+ def setUp(self) -> None:
+ self.tmp = tempfile.TemporaryDirectory()
+ self.metrics_env = patch.dict(
+ os.environ,
+ {"CATSTACK_HOOK_METRICS_DIR": self.tmp.name},
+ clear=False,
+ )
+ self.metrics_env.start()
+
+ def tearDown(self) -> None:
+ self.metrics_env.stop()
+ self.tmp.cleanup()
+
def test_malformed_stdin_prints_nothing(self) -> None:
out = io.StringIO()
with patch.object(sys, "stdin", io.StringIO("not json")):
diff --git a/engine/hooks/categorical-scope-guard/README.md b/engine/hooks/categorical-scope-guard/README.md
index 3eb5b2dc..2aabdff3 100644
--- a/engine/hooks/categorical-scope-guard/README.md
+++ b/engine/hooks/categorical-scope-guard/README.md
@@ -91,9 +91,12 @@ Do one of two things:
## Three outcomes, and the fail direction
-- **HIT** — exit 2 with the message above.
+- **HIT** — finding `categorical-scope-guard.partial-status-filter`. The
+ registry default is `stop`, so the shared runtime exits 2 with the
+ message above unless a local mode override lowers it to a warning.
- **CLEAN** — exit 0.
-- **UNCHECKED** — exit 2. **This hook fails closed.** It blocks, and says
+- **UNCHECKED** — finding `categorical-scope-guard.unchecked`. **This hook
+ fails closed.** With the default `stop` mode it blocks, and says
`UNCHECKED`, when:
- the transcript path is absent, the file is missing, a line is malformed
JSON (a torn final line is tolerated), the window runs past the 64 MB
@@ -132,8 +135,10 @@ reason and let the user answer.
## Files
-- `detect.py` — command parser, human-turn reader, `decide()`.
-- `claude_pretooluse.py` — the entrypoint.
+- `detect.py` — command parser, human-turn reader, `decide()`, and
+ `detect(event)`.
+- `claude_pretooluse.py`, `cursor_pretooluse.py`, `codex_pretooluse.py` —
+ thin runtime entrypoints.
- `claude.hook.json`, `install_claude_hook.py` — the settings merge that
`install.sh` runs.
- `tests/test_hooks.py`, `tests/fixtures/` — the fixtures are real commands
diff --git a/engine/hooks/categorical-scope-guard/claude_pretooluse.py b/engine/hooks/categorical-scope-guard/claude_pretooluse.py
index 673c734c..a3724044 100644
--- a/engine/hooks/categorical-scope-guard/claude_pretooluse.py
+++ b/engine/hooks/categorical-scope-guard/claude_pretooluse.py
@@ -1,55 +1,19 @@
#!/usr/bin/env python3
-"""Claude PreToolUse on Bash: block a status-narrowed mutation of a target the
-live human turn quantified with all / every / each. Exits 2 with the reason on
-stderr for HIT and for UNCHECKED; exits 0 for CLEAN.
-"""
+"""Claude Code PreToolUse entrypoint for categorical-scope-guard."""
from __future__ import annotations
-import json
import os
import sys
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "_sdk"))
-from detect import CLEAN, decide_payload
-
-SHELL_LIKE_TOOL_NAMES = (
- "Bash", "bash", "shell", "Shell", "exec", "exec_command",
- "run_terminal_cmd", "local_shell", "run_command", "shell_call",
-)
-
-
-def _tool_name(payload: dict) -> str:
- return str(
- payload.get("tool_name")
- or payload.get("toolName")
- or payload.get("tool")
- or payload.get("name")
- or ""
- )
+from detect import detect # noqa: E402
+from runtime import run_hook # noqa: E402
def main() -> None:
- raw = sys.stdin.read()
- try:
- payload = json.loads(raw)
- except (json.JSONDecodeError, OSError) as exc:
- sys.stderr.write(f"categorical-scope-guard: hook payload is not JSON, nothing to classify: {exc}\n")
- return
- if not isinstance(payload, dict) or _tool_name(payload) not in SHELL_LIKE_TOOL_NAMES:
- return
- try:
- verdict = decide_payload(payload)
- except Exception as exc:
- sys.stderr.write(
- f"categorical-scope-guard: UNCHECKED -- the detector failed ({exc!r}) while classifying a "
- "status-filtered mutation. Blocked rather than passed; drop the status filter or rephrase the command.\n"
- )
- sys.exit(2)
- if verdict.outcome == CLEAN:
- return
- sys.stderr.write(verdict.message + "\n")
- sys.exit(2)
+ run_hook("categorical-scope-guard", "claude", detect, "PreToolUse")
if __name__ == "__main__":
diff --git a/engine/hooks/categorical-scope-guard/codex_pretooluse.py b/engine/hooks/categorical-scope-guard/codex_pretooluse.py
new file mode 100644
index 00000000..e2f2a14d
--- /dev/null
+++ b/engine/hooks/categorical-scope-guard/codex_pretooluse.py
@@ -0,0 +1,20 @@
+#!/usr/bin/env python3
+"""Codex PreToolUse entrypoint for categorical-scope-guard."""
+from __future__ import annotations
+
+import os
+import sys
+
+sys.path.insert(0, os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "_sdk"))
+
+from detect import detect # noqa: E402
+from runtime import run_hook # noqa: E402
+
+
+def main() -> None:
+ run_hook("categorical-scope-guard", "codex", detect, "PreToolUse")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/engine/hooks/categorical-scope-guard/cursor_pretooluse.py b/engine/hooks/categorical-scope-guard/cursor_pretooluse.py
new file mode 100644
index 00000000..bf6714e8
--- /dev/null
+++ b/engine/hooks/categorical-scope-guard/cursor_pretooluse.py
@@ -0,0 +1,20 @@
+#!/usr/bin/env python3
+"""Cursor PreToolUse entrypoint for categorical-scope-guard."""
+from __future__ import annotations
+
+import os
+import sys
+
+sys.path.insert(0, os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "_sdk"))
+
+from detect import detect # noqa: E402
+from runtime import run_hook # noqa: E402
+
+
+def main() -> None:
+ run_hook("categorical-scope-guard", "cursor", detect, "PreToolUse")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/engine/hooks/categorical-scope-guard/detect.py b/engine/hooks/categorical-scope-guard/detect.py
index bc0f1912..b37566b4 100644
--- a/engine/hooks/categorical-scope-guard/detect.py
+++ b/engine/hooks/categorical-scope-guard/detect.py
@@ -14,14 +14,24 @@
from __future__ import annotations
import sys
+import hashlib
import json
import os
import re
from dataclasses import dataclass, field
+from pathlib import Path
+
+SDK_DIR = Path(__file__).resolve().parents[1] / "_sdk"
+if str(SDK_DIR) not in sys.path:
+ sys.path.insert(0, str(SDK_DIR))
+
+from finding import Finding # noqa: E402
HIT = "hit"
CLEAN = "clean"
UNCHECKED = "unchecked"
+RULE_PARTIAL_STATUS_FILTER = "categorical-scope-guard.partial-status-filter"
+RULE_UNCHECKED = "categorical-scope-guard.unchecked"
LIVE_TURNS = 4
MAX_SCAN_BYTES = 64 * 1024 * 1024
@@ -872,3 +882,54 @@ def decide_payload(payload: dict) -> Verdict:
return Verdict(CLEAN)
path = payload.get("transcript_path") or payload.get("transcriptPath") or ""
return decide(command, lambda: read_live_window(path if isinstance(path, str) else ""))
+
+
+SHELL_LIKE_TOOL_NAMES = (
+ "Bash", "bash", "shell", "Shell", "exec", "exec_command",
+ "run_terminal_cmd", "local_shell", "run_command", "shell_call",
+)
+
+
+def _tool_name(payload: dict) -> str:
+ return str(
+ payload.get("tool_name")
+ or payload.get("toolName")
+ or payload.get("tool")
+ or payload.get("name")
+ or ""
+ )
+
+
+def _command_subject(payload: dict) -> str:
+ tool_input = payload.get("tool_input") or payload.get("toolInput") or {}
+ command = tool_input.get("command") if isinstance(tool_input, dict) else ""
+ if not isinstance(command, str):
+ command = ""
+ return "command:" + hashlib.sha256(command.encode("utf-8")).hexdigest()[:16]
+
+
+def _finding(rule_id: str, payload: dict, message: str) -> Finding:
+ return Finding(
+ rule_id=rule_id,
+ subject=_command_subject(payload),
+ message=message,
+ evidence=message,
+ )
+
+
+def detect(event: dict) -> list[Finding]:
+ if _tool_name(event) not in SHELL_LIKE_TOOL_NAMES:
+ return []
+ try:
+ verdict = decide_payload(event)
+ except Exception as exc:
+ print(f"catstack-hook-error categorical-scope-guard: {type(exc).__name__}: {exc}", file=sys.stderr)
+ message = (
+ f"categorical-scope-guard: UNCHECKED -- the detector failed ({exc!r}) while classifying a "
+ "status-filtered mutation. Blocked rather than passed; drop the status filter or rephrase the command."
+ )
+ return [_finding(RULE_UNCHECKED, event, message)]
+ if verdict.outcome == CLEAN:
+ return []
+ rule_id = RULE_PARTIAL_STATUS_FILTER if verdict.outcome == HIT else RULE_UNCHECKED
+ return [_finding(rule_id, event, verdict.message)]
diff --git a/engine/hooks/categorical-scope-guard/tests/test_hooks_sdk_mode.py b/engine/hooks/categorical-scope-guard/tests/test_hooks_sdk_mode.py
new file mode 100644
index 00000000..b61c0c3b
--- /dev/null
+++ b/engine/hooks/categorical-scope-guard/tests/test_hooks_sdk_mode.py
@@ -0,0 +1,105 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+HOOK_DIR = os.path.dirname(HERE)
+FIXTURES = os.path.join(HERE, "fixtures")
+ENTRYPOINT = os.path.join(HOOK_DIR, "claude_pretooluse.py")
+
+
+def fixture(name: str) -> str:
+ with open(os.path.join(FIXTURES, name), encoding="utf-8") as handle:
+ return handle.read()
+
+
+def human(text: str) -> dict[str, object]:
+ return {"type": "user", "message": {"role": "user", "content": text}}
+
+
+def write_transcript(entries: list[dict[str, object]]) -> str:
+ handle = tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False, encoding="utf-8")
+ with handle:
+ for entry in entries:
+ handle.write(json.dumps(entry) + "\n")
+ return handle.name
+
+
+def run_entrypoint(payload: dict[str, object], env: dict[str, str]) -> subprocess.CompletedProcess[str]:
+ merged_env = os.environ.copy()
+ merged_env.update(env)
+ return subprocess.run(
+ [sys.executable, ENTRYPOINT],
+ input=json.dumps(payload),
+ capture_output=True,
+ text=True,
+ env=merged_env,
+ )
+
+
+class SdkModeTest(unittest.TestCase):
+ def test_mode_override_warn_changes_block_to_warning(self) -> None:
+ path = write_transcript([human("can you make all tasks use claude and local executor")])
+ try:
+ result = run_entrypoint(
+ {
+ "tool_name": "Bash",
+ "hook_event_name": "PreToolUse",
+ "transcript_path": path,
+ "tool_input": {"command": fixture("update_tasks_status_in_pending_queued.txt")},
+ },
+ {"CATSTACK_HOOK_MODE_CATEGORICAL_SCOPE_GUARD": "warn"},
+ )
+ finally:
+ os.unlink(path)
+
+ self.assertEqual(0, result.returncode, result.stderr)
+ self.assertEqual("", result.stderr)
+ rendered = json.loads(result.stdout)
+ self.assertIn(
+ "categorical-scope-guard",
+ rendered["hookSpecificOutput"]["additionalContext"],
+ )
+
+ def test_each_finding_writes_one_event_row_with_rule_id(self) -> None:
+ path = write_transcript([human("can you make all tasks use claude and local executor")])
+ try:
+ with tempfile.TemporaryDirectory() as tmp:
+ result = run_entrypoint(
+ {
+ "tool_name": "Bash",
+ "hook_event_name": "PreToolUse",
+ "session_id": "categorical-scope-guard-sdk-mode",
+ "transcript_path": path,
+ "tool_input": {"command": fixture("update_tasks_status_in_pending_queued.txt")},
+ },
+ {
+ "CATSTACK_HOOK_METRICS_DIR": tmp,
+ "CATSTACK_HOOK_MODE_CATEGORICAL_SCOPE_GUARD": "warn",
+ },
+ )
+ rows = [
+ json.loads(line)
+ for file in Path(tmp).glob("events-*.jsonl")
+ for line in file.read_text(encoding="utf-8").splitlines()
+ ]
+ finally:
+ os.unlink(path)
+
+ self.assertEqual(0, result.returncode, result.stderr)
+ self.assertEqual(1, len(rows))
+ self.assertEqual("categorical-scope-guard", rows[0]["hook"])
+ self.assertEqual("categorical-scope-guard.partial-status-filter", rows[0]["rule_id"])
+ self.assertEqual("warn", rows[0]["mode"])
+ self.assertEqual("override", rows[0]["mode_source"])
+ self.assertEqual("warned", rows[0]["action"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/engine/hooks/demo-freeze/claude_pretooluse_check.py b/engine/hooks/demo-freeze/claude_pretooluse_check.py
index 3ccc1f1d..4d94563d 100755
--- a/engine/hooks/demo-freeze/claude_pretooluse_check.py
+++ b/engine/hooks/demo-freeze/claude_pretooluse_check.py
@@ -16,13 +16,19 @@
not haunt tomorrow's session), and any parse/read error fails open.
"""
import fnmatch
-import json
import os
import sys
import time
+sys.path.insert(0, os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "_sdk"))
+
+from finding import Finding # noqa: E402
+from runtime import run_hook # noqa: E402
+
MARKER = os.environ.get("DEMO_FREEZE_FILE", "/tmp/.demo-freeze")
MAX_AGE_SECS = 2 * 3600
+RULE_FROZEN_PATH = "demo-freeze.frozen-path"
def frozen_patterns():
@@ -48,28 +54,35 @@ def matches(target, pattern):
return target_abs == os.path.abspath(pattern)
-def main():
- try:
- data = json.load(sys.stdin)
- except json.JSONDecodeError:
- return
- tool_input = data.get("tool_input") or {}
- target = (
+def _tool_target(event):
+ tool_input = event.get("tool_input") or event.get("toolInput") or {}
+ if not isinstance(tool_input, dict):
+ return None
+ return (
tool_input.get("file_path")
or tool_input.get("path")
or tool_input.get("notebook_path")
)
+
+
+def detect(event):
+ target = _tool_target(event)
if not target:
- return
+ return []
for pattern in frozen_patterns():
if matches(target, pattern):
- sys.stderr.write(
+ message = (
f"Demo surface frozen: {target} matches {pattern!r} in {MARKER}. "
"The user is mid-test — don't change what they're looking at unless "
"they asked or the test is failing. Remove the marker file to "
- "unfreeze once the live window ends.\n"
+ "unfreeze once the live window ends."
)
- sys.exit(2)
+ return [Finding(rule_id=RULE_FROZEN_PATH, subject=target, message=message, evidence=message)]
+ return []
+
+
+def main():
+ run_hook("demo-freeze", "claude", detect, "PreToolUse")
if __name__ == "__main__":
diff --git a/engine/hooks/demo-freeze/tests/test_hooks.py b/engine/hooks/demo-freeze/tests/test_hooks.py
index ded538ab..56b60110 100755
--- a/engine/hooks/demo-freeze/tests/test_hooks.py
+++ b/engine/hooks/demo-freeze/tests/test_hooks.py
@@ -74,7 +74,10 @@ def test_no_marker_fails_open(self):
with patch.object(claude_pretooluse_check, "MARKER", "/nonexistent/.demo-freeze"):
with patch.object(sys, "stdin", io.StringIO(json.dumps(payload))):
with redirect_stderr(err):
- claude_pretooluse_check.main()
+ try:
+ claude_pretooluse_check.main()
+ except SystemExit:
+ pass
self.assertEqual(err.getvalue(), "")
def test_non_file_tool_input_passes(self):
diff --git a/engine/hooks/demo-freeze/tests/test_hooks_sdk_mode.py b/engine/hooks/demo-freeze/tests/test_hooks_sdk_mode.py
new file mode 100644
index 00000000..11eabc11
--- /dev/null
+++ b/engine/hooks/demo-freeze/tests/test_hooks_sdk_mode.py
@@ -0,0 +1,104 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+HOOK_DIR = os.path.dirname(HERE)
+ENTRYPOINT = os.path.join(HOOK_DIR, "claude_pretooluse_check.py")
+
+
+def write_marker(lines: list[str]) -> str:
+ handle = tempfile.NamedTemporaryFile("w", suffix=".demo-freeze", delete=False, encoding="utf-8")
+ with handle:
+ handle.write("\n".join(lines) + "\n")
+ return handle.name
+
+
+def run_entrypoint(payload: dict[str, object], env: dict[str, str]) -> subprocess.CompletedProcess[str]:
+ merged_env = os.environ.copy()
+ merged_env.update(env)
+ return subprocess.run(
+ [sys.executable, ENTRYPOINT],
+ input=json.dumps(payload),
+ capture_output=True,
+ text=True,
+ env=merged_env,
+ )
+
+
+class SdkModeTest(unittest.TestCase):
+ def test_mode_override_warn_changes_block_to_warning(self) -> None:
+ marker = write_marker(["/tmp/demo/call.html"])
+ try:
+ result = run_entrypoint(
+ {"tool_name": "Edit", "tool_input": {"file_path": "/tmp/demo/call.html"}},
+ {
+ "DEMO_FREEZE_FILE": marker,
+ "CATSTACK_HOOK_MODE_DEMO_FREEZE": "warn",
+ },
+ )
+ finally:
+ os.unlink(marker)
+
+ self.assertEqual(0, result.returncode, result.stderr)
+ self.assertEqual("", result.stderr)
+ rendered = json.loads(result.stdout)
+ self.assertIn(
+ "Demo surface frozen",
+ rendered["hookSpecificOutput"]["additionalContext"],
+ )
+
+ def test_mode_stop_still_blocks_by_default(self) -> None:
+ marker = write_marker(["/tmp/demo/call.html"])
+ try:
+ result = run_entrypoint(
+ {"tool_name": "Edit", "tool_input": {"file_path": "/tmp/demo/call.html"}},
+ {"DEMO_FREEZE_FILE": marker},
+ )
+ finally:
+ os.unlink(marker)
+
+ self.assertEqual(2, result.returncode)
+ self.assertIn("Demo surface frozen", result.stderr)
+
+ def test_each_finding_writes_one_event_row_with_rule_id(self) -> None:
+ marker = write_marker(["/tmp/demo/call.html"])
+ try:
+ with tempfile.TemporaryDirectory() as tmp:
+ result = run_entrypoint(
+ {
+ "tool_name": "Edit",
+ "session_id": "demo-freeze-sdk-mode",
+ "tool_input": {"file_path": "/tmp/demo/call.html"},
+ },
+ {
+ "DEMO_FREEZE_FILE": marker,
+ "CATSTACK_HOOK_METRICS_DIR": tmp,
+ "CATSTACK_HOOK_MODE_DEMO_FREEZE": "warn",
+ },
+ )
+ rows = [
+ json.loads(line)
+ for file in Path(tmp).glob("events-*.jsonl")
+ for line in file.read_text(encoding="utf-8").splitlines()
+ ]
+ finally:
+ os.unlink(marker)
+
+ self.assertEqual(0, result.returncode, result.stderr)
+ self.assertEqual(1, len(rows))
+ self.assertEqual("demo-freeze", rows[0]["hook"])
+ self.assertEqual("demo-freeze.frozen-path", rows[0]["rule_id"])
+ self.assertEqual("warn", rows[0]["mode"])
+ self.assertEqual("override", rows[0]["mode_source"])
+ self.assertEqual("warned", rows[0]["action"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/engine/hooks/diu-stop/claude_prompt_reminder.py b/engine/hooks/diu-stop/claude_prompt_reminder.py
index 68bd3079..e0c07a10 100644
--- a/engine/hooks/diu-stop/claude_prompt_reminder.py
+++ b/engine/hooks/diu-stop/claude_prompt_reminder.py
@@ -16,11 +16,19 @@
reminder repeated every turn is exactly the kind of thing this skill tells
the model to cut.
"""
-import json
+import os
import sys
from diu_limit import rule_text
+sys.path.insert(0, os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "_sdk"))
+
+from finding import Finding # noqa: E402
+from runtime import run_hook # noqa: E402
+
+RULE_REMINDER = "diu-stop.prompt-reminder"
+
REMINDER = (
"diu reminder: lead with the outcome, no preamble or closing "
f"pleasantries, ELI5 {rule_text()}, unless this turn needs technical "
@@ -29,17 +37,13 @@
)
+def detect(event):
+ subject = event.get("session_id") or ""
+ return [Finding(rule_id=RULE_REMINDER, subject=subject, message=REMINDER, evidence=REMINDER)]
+
+
def main():
- try:
- json.load(sys.stdin)
- except json.JSONDecodeError:
- return
- print(json.dumps({
- "hookSpecificOutput": {
- "hookEventName": "UserPromptSubmit",
- "additionalContext": REMINDER,
- }
- }))
+ run_hook("diu-stop", "claude", detect, "UserPromptSubmit")
if __name__ == "__main__":
diff --git a/engine/hooks/diu-stop/claude_stop_check.py b/engine/hooks/diu-stop/claude_stop_check.py
index 4eeff269..125ec520 100755
--- a/engine/hooks/diu-stop/claude_stop_check.py
+++ b/engine/hooks/diu-stop/claude_stop_check.py
@@ -45,7 +45,6 @@
Every block names every flagged sentence, so one rewrite that fixes them
all gets through.
"""
-import json
import os
import re
import sys
@@ -55,8 +54,18 @@
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "_markers"))
+sys.path.insert(0, os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "_sdk"))
import markers # noqa: E402
+from finding import Finding # noqa: E402
+from runtime import run_hook # noqa: E402
+
+RULE_WORD_LIMIT = "diu-stop.word-limit"
+RULE_UNVERIFIED_CLAIM = "diu-stop.unverified-claim"
+RULE_MALFORMED_MARKER_TAG = "diu-stop.malformed-marker-tag"
+RULE_LEGACY_MARKER = "diu-stop.legacy-marker"
+RULE_PLAIN_WORDS = "diu-stop.plain-words"
# Phrases banned outright (from this user's global CLAUDE.md evidence
# rules) -- rarely legitimate even mid-sentence, so no opener restriction.
@@ -219,31 +228,28 @@ def find_unverified_claim(message):
return claims[0][0] if claims else None
-def main():
- try:
- data = json.load(sys.stdin)
- except json.JSONDecodeError:
- return
-
- if data.get("agent_id"):
- return
- retry = bool(data.get("stop_hook_active"))
+def detect(event):
+ if event.get("agent_id"):
+ return []
+ retry = bool(event.get("stop_hook_active"))
- message = data.get("last_assistant_message") or ""
+ message = event.get("last_assistant_message") or ""
- plain_words_note = try_check_reply(data)
+ plain_words_note = try_check_reply(event)
word_count = counted_words(message)
over_limit = word_count > WORD_LIMIT and not retry
claims = find_unverified_claims(message)
marker_problems = find_marker_problems(message)
- if not over_limit and not claims and not marker_problems and not plain_words_note:
- return
-
- parts = []
+ findings = []
if plain_words_note:
- parts.append(plain_words_note)
+ findings.append(Finding(
+ rule_id=RULE_PLAIN_WORDS,
+ subject=message,
+ message=plain_words_note,
+ evidence=plain_words_note,
+ ))
if claims:
lines = [
"This message makes an unverified-shaped claim with no adjacent "
@@ -259,18 +265,30 @@ def main():
"of what was actually run/checked in its paragraph, or -- only if "
"the check cannot run -- tag the claim there and say why."
)
- parts.append("\n".join(lines))
- parts.extend(marker_problems)
+ claim_message = "\n".join(lines)
+ findings.append(Finding(
+ rule_id=RULE_UNVERIFIED_CLAIM,
+ subject=claim_message,
+ message=claim_message,
+ evidence=claim_message,
+ ))
+ for problem in marker_problems:
+ rule_id = RULE_MALFORMED_MARKER_TAG if problem == markers.MALFORMED_TAG_MESSAGE else RULE_LEGACY_MARKER
+ findings.append(Finding(rule_id=rule_id, subject=message, message=problem, evidence=problem))
if over_limit:
- parts.append(
+ over_message = (
f"Apply diu: {word_count} words, over the {WORD_LIMIT}-word "
f"guideline. Cut at least {word_count - WORD_LIMIT} words by "
"dropping a whole section or list, not by trimming words. "
"Unless this turn genuinely asked for full technical detail "
"or a specific long format."
)
- sys.stderr.write("\n".join(parts) + "\n")
- sys.exit(2)
+ findings.append(Finding(rule_id=RULE_WORD_LIMIT, subject=message, message=over_message, evidence=over_message))
+ return findings
+
+
+def main():
+ run_hook("diu-stop", "claude", detect, "Stop")
if __name__ == "__main__":
diff --git a/engine/hooks/diu-stop/codex_notify.py b/engine/hooks/diu-stop/codex_notify.py
index fd88a3d6..c763cb23 100755
--- a/engine/hooks/diu-stop/codex_notify.py
+++ b/engine/hooks/diu-stop/codex_notify.py
@@ -17,10 +17,34 @@
becomes `old-notify-binary some-arg ` when this fires.
"""
import json
+import os
import subprocess
import sys
+sys.path.insert(0, os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "_sdk"))
+
+from events import write_events # noqa: E402
+from finding import Finding # noqa: E402
+from modes import effective_mode # noqa: E402
+
WORD_LIMIT = 150
+RULE_WORD_LIMIT = "diu-stop.word-limit"
+
+
+def detect(payload):
+ if payload.get("type") != "agent-turn-complete":
+ return []
+ message = payload.get("last-assistant-message") or ""
+ word_count = len(message.split())
+ if word_count <= WORD_LIMIT:
+ return []
+ message_text = (
+ f"diu-stop: last response was {word_count} words (over the "
+ f"{WORD_LIMIT}-word diu guideline). Codex can't be forced to redo "
+ "it -- check by hand whether it should have been ELI5."
+ )
+ return [Finding(rule_id=RULE_WORD_LIMIT, subject=message, message=message_text, evidence=message_text)]
def main():
@@ -40,18 +64,18 @@ def main():
except json.JSONDecodeError:
return
- if payload.get("type") != "agent-turn-complete":
+ findings = detect(payload)
+ if not findings:
return
- message = payload.get("last-assistant-message") or ""
- word_count = len(message.split())
- if word_count > WORD_LIMIT:
- print(
- f"diu-stop: last response was {word_count} words (over the "
- f"{WORD_LIMIT}-word diu guideline). Codex can't be forced to redo "
- "it -- check by hand whether it should have been ELI5.",
- file=sys.stderr,
- )
+ mode, mode_source = effective_mode("diu-stop", payload)
+ if mode == "off":
+ return
+
+ for finding in findings:
+ print(finding.message, file=sys.stderr)
+
+ write_events("diu-stop", "codex", payload, findings, mode, mode_source, 0)
if __name__ == "__main__":
diff --git a/engine/hooks/diu-stop/tests/test_hooks.py b/engine/hooks/diu-stop/tests/test_hooks.py
index 69570da5..0e6dd831 100644
--- a/engine/hooks/diu-stop/tests/test_hooks.py
+++ b/engine/hooks/diu-stop/tests/test_hooks.py
@@ -56,7 +56,10 @@ def run_prompt_reminder(stdin_obj):
buf = io.StringIO()
with patch.object(sys, "stdin", io.StringIO(json.dumps(stdin_obj))):
with redirect_stdout(buf):
- claude_prompt_reminder.main()
+ try:
+ claude_prompt_reminder.main()
+ except SystemExit:
+ pass
return buf.getvalue()
@@ -140,7 +143,10 @@ def test_malformed_stdin_json_does_not_crash(self):
buf = io.StringIO()
with patch.object(sys, "stdin", io.StringIO("not json")):
with redirect_stdout(buf):
- claude_stop_check.main() # must not raise
+ try:
+ claude_stop_check.main()
+ except SystemExit:
+ pass
self.assertEqual(buf.getvalue(), "")
@@ -176,7 +182,10 @@ def test_malformed_stdin_json_does_not_crash(self):
buf = io.StringIO()
with patch.object(sys, "stdin", io.StringIO("not json")):
with redirect_stdout(buf):
- claude_prompt_reminder.main() # must not raise
+ try:
+ claude_prompt_reminder.main()
+ except SystemExit:
+ pass
self.assertEqual(buf.getvalue(), "")
diff --git a/engine/hooks/diu-stop/tests/test_hooks_sdk_mode.py b/engine/hooks/diu-stop/tests/test_hooks_sdk_mode.py
new file mode 100644
index 00000000..51c808ea
--- /dev/null
+++ b/engine/hooks/diu-stop/tests/test_hooks_sdk_mode.py
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+HOOK_DIR = os.path.dirname(HERE)
+ENTRYPOINT = os.path.join(HOOK_DIR, "claude_stop_check.py")
+
+LONG_MESSAGE = " ".join(["word"] * 200)
+
+
+def run_entrypoint(payload: dict[str, object], env: dict[str, str]) -> subprocess.CompletedProcess[str]:
+ merged_env = os.environ.copy()
+ merged_env.update(env)
+ return subprocess.run(
+ [sys.executable, ENTRYPOINT],
+ input=json.dumps(payload),
+ capture_output=True,
+ text=True,
+ env=merged_env,
+ )
+
+
+class SdkModeTest(unittest.TestCase):
+ def test_mode_override_warn_changes_block_to_warning(self) -> None:
+ result = run_entrypoint(
+ {"last_assistant_message": LONG_MESSAGE},
+ {"CATSTACK_HOOK_MODE_DIU_STOP": "warn"},
+ )
+
+ self.assertEqual(0, result.returncode, result.stderr)
+ self.assertEqual("", result.stderr)
+ rendered = json.loads(result.stdout)
+ self.assertIn(
+ "Apply diu",
+ rendered["hookSpecificOutput"]["additionalContext"],
+ )
+
+ def test_mode_stop_still_blocks_by_default(self) -> None:
+ result = run_entrypoint({"last_assistant_message": LONG_MESSAGE}, {})
+
+ self.assertEqual(2, result.returncode)
+ self.assertIn("Apply diu", result.stderr)
+
+ def test_each_finding_writes_one_event_row_with_rule_id(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ result = run_entrypoint(
+ {
+ "session_id": "diu-stop-sdk-mode",
+ "last_assistant_message": LONG_MESSAGE,
+ },
+ {
+ "CATSTACK_HOOK_METRICS_DIR": tmp,
+ "CATSTACK_HOOK_MODE_DIU_STOP": "warn",
+ },
+ )
+ rows = [
+ json.loads(line)
+ for file in Path(tmp).glob("events-*.jsonl")
+ for line in file.read_text(encoding="utf-8").splitlines()
+ ]
+
+ self.assertEqual(0, result.returncode, result.stderr)
+ self.assertEqual(1, len(rows))
+ self.assertEqual("diu-stop", rows[0]["hook"])
+ self.assertEqual("diu-stop.word-limit", rows[0]["rule_id"])
+ self.assertEqual("warn", rows[0]["mode"])
+ self.assertEqual("override", rows[0]["mode_source"])
+ self.assertEqual("warned", rows[0]["action"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_check_memory_first_rule.py b/tests/test_check_memory_first_rule.py
new file mode 100644
index 00000000..15712b92
--- /dev/null
+++ b/tests/test_check_memory_first_rule.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+"""Pin the learned rule: search saved memory, both ways, before a deep dive.
+
+A detector cannot judge this reliably, so the test proves the rule is present
+with its trigger, required action, and reason; deleting or hollowing it fails here.
+"""
+import os
+import unittest
+
+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+LEARNED = os.path.join(REPO_ROOT, "corpus", "CLAUDE.learned.md")
+
+
+def working_style_section():
+ with open(LEARNED, encoding="utf-8") as handle:
+ text = handle.read()
+ start = text.index("# Working style")
+ end = text.find("\n# ", start + 1)
+ return text[start:] if end == -1 else text[start:end]
+
+
+def bullet_starting(prefix):
+ for line in working_style_section().splitlines():
+ if line.startswith(prefix):
+ return line
+ raise AssertionError(f"no working-style rule starts with {prefix!r}")
+
+
+class TestCheckMemoryFirst(unittest.TestCase):
+ PREFIX = "- Before spending more than a couple of tool calls"
+
+ def test_rule_searches_memory_both_ways(self):
+ rule = bullet_starting(self.PREFIX)
+ self.assertIn("search saved memory", rule)
+ self.assertIn("reverse framing", rule)
+
+
+if __name__ == "__main__":
+ unittest.main()