|
| 1 | +"""Hook command — Claude Code hook integrations. |
| 2 | +
|
| 3 | +Entry-point functions (_guard_credentials, _memory_bridge, _precompact_memory_bridge) |
| 4 | +are defined here so that ``patch("agent_notes.commands.hook.<name>", ...)`` targets |
| 5 | +in tests resolve to this module's namespace and intercept calls correctly. |
| 6 | +
|
| 7 | +Implementation logic is split across focused submodules: |
| 8 | + _guard.py — credential detection helpers + evaluate_credential_access |
| 9 | + _session.py — _session_discover |
| 10 | + _memory.py — _load_memory_index (shared renderer) |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import json |
| 16 | +import sys |
| 17 | + |
| 18 | +# Re-export everything tests import from this package |
| 19 | +from ._guard import ( |
| 20 | + evaluate_credential_access, |
| 21 | + _is_credential_path, |
| 22 | + _bash_reads_credential, |
| 23 | + _keyword_in_segment, |
| 24 | + _deny_payload, |
| 25 | + _is_template_file, |
| 26 | + _is_path_shaped, |
| 27 | + _first_effective_command, |
| 28 | + _strip_token_punctuation, |
| 29 | + _command_contains_credential_path, |
| 30 | + _TEMPLATE_MARKERS, |
| 31 | + _HARD_SECRET_EXTS, |
| 32 | + _SOURCE_EXTS, |
| 33 | + _CREDENTIAL_BASENAME_PATTERNS, |
| 34 | + _SEG_SEPS, |
| 35 | + _TOKEN_SPLIT, |
| 36 | + _CREDENTIAL_SEGMENT_KEYWORDS, |
| 37 | + _SAFE_EXISTENCE_COMMANDS, |
| 38 | + _COMMAND_PREFIXES, |
| 39 | +) |
| 40 | +from ._session import _session_discover |
| 41 | +from ._memory import _load_memory_index |
| 42 | + |
| 43 | + |
| 44 | +# --------------------------------------------------------------------------- |
| 45 | +# Dispatch |
| 46 | +# --------------------------------------------------------------------------- |
| 47 | + |
| 48 | +def hook(subaction: str) -> None: |
| 49 | + """Handle hook subactions.""" |
| 50 | + if subaction == "memory-bridge": |
| 51 | + _memory_bridge() |
| 52 | + elif subaction == "precompact-memory-bridge": |
| 53 | + _precompact_memory_bridge() |
| 54 | + elif subaction == "session-discover": |
| 55 | + _session_discover() |
| 56 | + elif subaction == "guard-credentials": |
| 57 | + _guard_credentials() |
| 58 | + |
| 59 | + |
| 60 | +# --------------------------------------------------------------------------- |
| 61 | +# Entry-point functions that call module-level names (kept here so that |
| 62 | +# patch("agent_notes.commands.hook.<dep>", ...) intercepts their calls). |
| 63 | +# --------------------------------------------------------------------------- |
| 64 | + |
| 65 | +def _guard_credentials() -> None: |
| 66 | + """PreToolUse hook that denies attempts to read credential files. |
| 67 | +
|
| 68 | + Reads the PreToolUse JSON payload from stdin, calls evaluate_credential_access, |
| 69 | + and prints a deny or allow response. Always exits 0 so Claude Code parses stdout. |
| 70 | +
|
| 71 | + Fail-closed for recognized tool types: if stdin parsed and tool_name is a |
| 72 | + guarded tool (Read/Bash/Grep), any downstream error emits a static deny. |
| 73 | + Only a total stdin/JSON parse failure fails open (writes to stderr). |
| 74 | + """ |
| 75 | + raw = "" |
| 76 | + try: |
| 77 | + raw = sys.stdin.read() |
| 78 | + payload = json.loads(raw) |
| 79 | + except Exception as exc: |
| 80 | + # Total infrastructure failure — cannot parse stdin at all; fail open |
| 81 | + # with a stderr note so operators can diagnose. |
| 82 | + print(f"credential-guard: stdin parse error ({exc})", file=sys.stderr) |
| 83 | + return |
| 84 | + |
| 85 | + tool_name = payload.get("tool_name", "") |
| 86 | + tool_input = payload.get("tool_input", {}) |
| 87 | + |
| 88 | + _GUARDED_TOOLS = {"Read", "Bash", "Grep"} |
| 89 | + |
| 90 | + if tool_name in _GUARDED_TOOLS: |
| 91 | + try: |
| 92 | + decision = evaluate_credential_access(tool_name, tool_input) |
| 93 | + if decision is not None: |
| 94 | + print(json.dumps(decision)) |
| 95 | + except Exception: |
| 96 | + # Evaluation error on a guarded tool — fail closed |
| 97 | + print(json.dumps(_deny_payload( |
| 98 | + "Credential guard: evaluation error — denying as a precaution; " |
| 99 | + "remove the guard hook from settings.json to override." |
| 100 | + ))) |
| 101 | + else: |
| 102 | + # Non-guarded tool: pass through (hook matcher already scopes to Read|Bash|Grep, |
| 103 | + # but defensive check here in case Claude Code invokes us for other tools) |
| 104 | + try: |
| 105 | + decision = evaluate_credential_access(tool_name, tool_input) |
| 106 | + if decision is not None: |
| 107 | + print(json.dumps(decision)) |
| 108 | + except Exception: |
| 109 | + pass # Non-guarded tool errors fail open |
| 110 | + |
| 111 | + |
| 112 | +def _memory_bridge() -> None: |
| 113 | + """SessionStart hook that prints the agent-notes memory index. |
| 114 | +
|
| 115 | + Unconditionally loads and prints the memory index so it is visible in |
| 116 | + context at the start of every Claude Code session. |
| 117 | + """ |
| 118 | + content = _load_memory_index() |
| 119 | + if content is None: |
| 120 | + return |
| 121 | + print("<!-- agent-notes memory index (auto-loaded) -->") |
| 122 | + print(content) |
| 123 | + |
| 124 | + |
| 125 | +def _precompact_memory_bridge() -> None: |
| 126 | + """PreCompact hook that re-emits the memory index before context compaction. |
| 127 | +
|
| 128 | + When Claude Code compacts a long conversation the SessionStart context |
| 129 | + injected by memory-bridge can be summarised away, losing the pointer to |
| 130 | + durable memory. This hook fires immediately before compaction and returns |
| 131 | + the index via the `additionalContext` field in the hook JSON output schema |
| 132 | + (see docs/CLI_CAPABILITIES.md §Hooks → "JSON output schema"). Claude Code |
| 133 | + merges `additionalContext` into the compacted context, keeping the memory |
| 134 | + pointer alive. |
| 135 | +
|
| 136 | + Contract: exit 0, emit a single JSON object to stdout: |
| 137 | + {"additionalContext": "<header>\\n<index content>"} |
| 138 | + If the memory index is unavailable (no backend configured, no index file) |
| 139 | + the hook exits silently with no output so compaction proceeds normally. |
| 140 | + """ |
| 141 | + content = _load_memory_index() |
| 142 | + if content is None: |
| 143 | + return |
| 144 | + payload = { |
| 145 | + "additionalContext": "<!-- agent-notes memory index (auto-loaded) -->\n" + content, |
| 146 | + } |
| 147 | + print(json.dumps(payload)) |
0 commit comments