kneepad 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kneepad/hook.py ADDED
@@ -0,0 +1,160 @@
1
+ """Claude Code PreToolUse hook.
2
+
3
+ Contract (verified against the Claude Code hooks documentation):
4
+ * stdin: a JSON object with ``tool_name``, ``tool_input``, ``cwd``, ``hook_event_name``...
5
+ * to block: print {"hookSpecificOutput": {"hookEventName": "PreToolUse",
6
+ "permissionDecision": "deny", "permissionDecisionReason": "..."}} and exit 0.
7
+ * to ask the user: same shape with "ask".
8
+ * to stay out of the way: print NOTHING and exit 0.
9
+
10
+ Kneepad never prints "allow". An "allow" from a hook skips Claude Code's own
11
+ permission prompts, which would silently approve commands the user would
12
+ otherwise have been asked about. Silence means "no opinion", and the normal
13
+ permission flow continues.
14
+
15
+ Failure mode: if anything inside Kneepad breaks, it answers "ask" rather than
16
+ staying silent, so a bug can never quietly turn into an allow.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ from typing import Dict, List, Optional, Tuple
24
+
25
+ from .adapters import Adapter, get_adapter
26
+ from .audit import AuditLog
27
+ from .config import load_config
28
+ from .engine import Analyzer, Decision, Finding
29
+ from .snapshots import SnapshotError, SnapshotStore
30
+ from .util import redact, kneepad_home
31
+
32
+ MAX_STDIN = 8_000_000
33
+
34
+
35
+ def _out(action: str, reason: str) -> str:
36
+ return json.dumps({
37
+ "hookSpecificOutput": {
38
+ "hookEventName": "PreToolUse",
39
+ "permissionDecision": action,
40
+ "permissionDecisionReason": reason,
41
+ }
42
+ })
43
+
44
+
45
+ def _log(audit: AuditLog, payload: dict, tool: str, decision: Decision, snaps: List[str], extra: Optional[dict] = None) -> None:
46
+ data = {
47
+ "tool": tool,
48
+ "action": decision.action,
49
+ "mode": decision.mode,
50
+ "cwd": str(payload.get("cwd", "")),
51
+ "session": str(payload.get("session_id", ""))[:64],
52
+ "tool_use_id": str(payload.get("tool_use_id", ""))[:64],
53
+ "findings": [
54
+ {"rule": f.rule_id, "severity": f.severity, "action": f.action, "detail": redact(f.detail, 300)}
55
+ for f in decision.findings
56
+ ],
57
+ "snapshots": snaps,
58
+ }
59
+ if tool == "Bash":
60
+ data["command"] = redact(str((payload.get("tool_input") or {}).get("command", "")))
61
+ elif "file_path" in (payload.get("tool_input") or {}):
62
+ data["path"] = redact(str(payload["tool_input"]["file_path"]), 500)
63
+ if extra:
64
+ data.update(extra)
65
+ try:
66
+ audit.append("decision", data)
67
+ except Exception:
68
+ pass # logging must never change the decision
69
+
70
+
71
+ def _normalised(parsed) -> dict:
72
+ tin = dict(parsed.tin) if isinstance(parsed.tin, dict) else {}
73
+ if parsed.kind == "write" and "file_path" not in tin:
74
+ for k in ("path", "filePath", "notebook_path", "target_file", "filename"):
75
+ if isinstance(tin.get(k), str):
76
+ tin["file_path"] = tin[k]
77
+ break
78
+ return {"cwd": parsed.cwd, "session_id": parsed.session, "tool_use_id": parsed.use_id, "tool_input": tin}
79
+
80
+
81
+ def handle(stdin_text: str, home: Optional[str] = None, integration: str = "claude") -> Tuple[int, str]:
82
+ """Process one hook invocation. Returns (exit_code, stdout_text)."""
83
+ home = home or kneepad_home()
84
+ ad: Adapter = get_adapter(integration)
85
+ audit = AuditLog(home)
86
+
87
+ def out(action: str, reason: str) -> Tuple[int, str]:
88
+ return ad.render(action, reason)
89
+
90
+ try:
91
+ if len(stdin_text) > MAX_STDIN:
92
+ return out("ask", "Kneepad: the tool input is too large to analyse. Confirm manually.")
93
+ try:
94
+ payload = json.loads(stdin_text.lstrip("\ufeff"))
95
+ except ValueError:
96
+ return out("ask", "Kneepad could not parse the hook input, so it could not check this action. Confirm manually.")
97
+ if not isinstance(payload, dict):
98
+ return out("ask", "Kneepad received unexpected hook input. Confirm manually.")
99
+ if not ad.event_ok(payload):
100
+ return 0, ""
101
+ parsed = ad.parse(payload)
102
+ if parsed.kind is None:
103
+ return ad.render("allow", "") if ad.requires_explicit_allow else (0, "")
104
+ tin = parsed.tin if isinstance(parsed.tin, dict) else {}
105
+ cwd = parsed.cwd
106
+ if not cwd or not os.path.isdir(cwd):
107
+ cwd = os.getcwd()
108
+ cfg = load_config(cwd, home)
109
+ az = Analyzer(config=cfg, cwd=cwd)
110
+ if parsed.kind == "bash":
111
+ cmd = tin.get("command", "")
112
+ decision = az.analyze_shell(cmd if isinstance(cmd, str) else json.dumps(cmd))
113
+ tool = "Bash"
114
+ elif parsed.kind == "write":
115
+ path = tin.get("file_path") or tin.get("path") or tin.get("filePath") or tin.get("notebook_path") or tin.get("target_file")
116
+ if not isinstance(path, str) or not path:
117
+ return ad.render("allow", "") if ad.requires_explicit_allow else (0, "")
118
+ decision = az.analyze_write_path(path)
119
+ tool = parsed.tool or "Write"
120
+ else:
121
+ decision = az.analyze_mcp(parsed.tool, tin)
122
+ tool = parsed.tool
123
+ if not decision.findings:
124
+ return ad.render("allow", "") if ad.requires_explicit_allow else (0, "")
125
+
126
+ snap_ids: List[str] = []
127
+ if decision.plans:
128
+ store = SnapshotStore(home)
129
+ try:
130
+ for plan in decision.plans:
131
+ snap_ids.append(store.create(plan)["id"])
132
+ store.prune(max_total_mb=cfg.snapshot_total_mb)
133
+ except SnapshotError as exc:
134
+ rule = az.by_id["snapshot-unavailable"]
135
+ decision.findings.append(Finding(
136
+ rule_id=rule.id, title="safety snapshot could not be taken", severity="medium", action="ask",
137
+ why=f"Kneepad tried to copy what this command would delete, and failed: {exc}",
138
+ safer="Back up what you need manually, then confirm.", detail=str(exc)[:160],
139
+ ))
140
+ decision.action = "ask"
141
+
142
+ norm = _normalised(parsed)
143
+ _log(audit, norm, "Bash" if parsed.kind == "bash" else tool, decision, snap_ids, {"integration": integration})
144
+ if cfg.mode == "monitor":
145
+ return ad.render("allow", "") if ad.requires_explicit_allow else (0, "")
146
+ if decision.action == "allow":
147
+ # Snapshot (if any) is already taken; the command proceeds through the agent's normal flow.
148
+ return ad.render("allow", "") if ad.requires_explicit_allow else (0, "")
149
+ reason = decision.reason()
150
+ if snap_ids and decision.action == "ask":
151
+ reason += f"\nA safety snapshot was taken first: kneepad snapshots show {snap_ids[0]}"
152
+ for w in cfg.warnings[:2]:
153
+ reason += f"\nConfig warning: {w}"
154
+ return out(decision.action, reason)
155
+ except Exception as exc: # fail to "ask" (or deny where there is no ask), never to silent allow
156
+ try:
157
+ audit.append("error", {"error": type(exc).__name__, "message": redact(str(exc), 300)})
158
+ except Exception:
159
+ pass
160
+ return out("ask", f"Kneepad hit an internal error ({type(exc).__name__}) and could not check this action. Confirm manually.")
kneepad/installer.py ADDED
@@ -0,0 +1,139 @@
1
+ """Register or remove the Kneepad hook in Claude Code settings, safely."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import sys
9
+ import tempfile
10
+ from typing import List
11
+
12
+ from .util import quote_exe
13
+
14
+ MATCHER = "Bash|Write|Edit|MultiEdit|NotebookEdit|mcp__.*"
15
+
16
+
17
+ class InstallError(Exception):
18
+ pass
19
+
20
+
21
+ def hook_command() -> str:
22
+ exe = shutil.which("kneepad")
23
+ if exe:
24
+ return f"{quote_exe(exe)} hook claude"
25
+ return f"{quote_exe(sys.executable)} -m kneepad hook claude"
26
+
27
+
28
+ def settings_path(scope: str, cwd: str) -> str:
29
+ if scope == "user":
30
+ return os.path.join(os.path.expanduser("~"), ".claude", "settings.json")
31
+ if scope == "project":
32
+ return os.path.join(os.path.abspath(cwd), ".claude", "settings.json")
33
+ raise InstallError(f"unknown scope {scope!r}")
34
+
35
+
36
+ def _is_ours(handler: object) -> bool:
37
+ if not isinstance(handler, dict):
38
+ return False
39
+ cmd = str(handler.get("command", ""))
40
+ return "kneepad" in cmd and " hook " in f" {cmd} "
41
+
42
+
43
+ def _load(path: str) -> dict:
44
+ try:
45
+ with open(path, "r", encoding="utf-8") as fh:
46
+ text = fh.read()
47
+ except FileNotFoundError:
48
+ return {}
49
+ if not text.strip():
50
+ return {}
51
+ try:
52
+ data = json.loads(text)
53
+ except ValueError as exc:
54
+ raise InstallError(f"{path} is not valid JSON ({exc}); refusing to modify it") from exc
55
+ if not isinstance(data, dict):
56
+ raise InstallError(f"{path} is not a JSON object; refusing to modify it")
57
+ return data
58
+
59
+
60
+ def _write_atomic(path: str, data: dict) -> None:
61
+ d = os.path.dirname(path) or "."
62
+ os.makedirs(d, exist_ok=True)
63
+ fd, tmp = tempfile.mkstemp(prefix=".kneepad-", suffix=".tmp", dir=d)
64
+ try:
65
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
66
+ json.dump(data, fh, indent=2)
67
+ fh.write("\n")
68
+ os.replace(tmp, path)
69
+ except Exception:
70
+ try:
71
+ os.unlink(tmp)
72
+ except OSError:
73
+ pass
74
+ raise
75
+
76
+
77
+ def _groups(data: dict) -> List[dict]:
78
+ hooks = data.get("hooks")
79
+ if not isinstance(hooks, dict):
80
+ return []
81
+ pre = hooks.get("PreToolUse")
82
+ return [g for g in pre if isinstance(g, dict)] if isinstance(pre, list) else []
83
+
84
+
85
+ def is_installed(path: str) -> bool:
86
+ try:
87
+ data = _load(path)
88
+ except InstallError:
89
+ return False
90
+ return any(_is_ours(h) for g in _groups(data) for h in (g.get("hooks") or []) if isinstance(g.get("hooks"), list))
91
+
92
+
93
+ def install(path: str, command: str) -> str:
94
+ data = _load(path)
95
+ if is_installed(path):
96
+ return "already-installed"
97
+ hooks = data.setdefault("hooks", {})
98
+ if not isinstance(hooks, dict):
99
+ raise InstallError(f"'hooks' in {path} is not an object; refusing to modify it")
100
+ pre = hooks.setdefault("PreToolUse", [])
101
+ if not isinstance(pre, list):
102
+ raise InstallError(f"'hooks.PreToolUse' in {path} is not a list; refusing to modify it")
103
+ pre.append({"matcher": MATCHER, "hooks": [{"type": "command", "command": command}]})
104
+ if os.path.exists(path):
105
+ shutil.copy2(path, path + ".kneepad-bak")
106
+ _write_atomic(path, data)
107
+ return "installed"
108
+
109
+
110
+ def uninstall(path: str) -> str:
111
+ if not os.path.exists(path):
112
+ return "not-installed"
113
+ data = _load(path)
114
+ pre = (data.get("hooks") or {}).get("PreToolUse") if isinstance(data.get("hooks"), dict) else None
115
+ if not isinstance(pre, list):
116
+ return "not-installed"
117
+ changed = False
118
+ new_pre = []
119
+ for g in pre:
120
+ if isinstance(g, dict) and isinstance(g.get("hooks"), list):
121
+ kept = [h for h in g["hooks"] if not _is_ours(h)]
122
+ if len(kept) != len(g["hooks"]):
123
+ changed = True
124
+ if kept:
125
+ g = dict(g)
126
+ g["hooks"] = kept
127
+ new_pre.append(g)
128
+ else:
129
+ new_pre.append(g)
130
+ if not changed:
131
+ return "not-installed"
132
+ shutil.copy2(path, path + ".kneepad-bak")
133
+ data["hooks"]["PreToolUse"] = new_pre
134
+ if not new_pre:
135
+ del data["hooks"]["PreToolUse"]
136
+ if not data["hooks"]:
137
+ del data["hooks"]
138
+ _write_atomic(path, data)
139
+ return "removed"
@@ -0,0 +1,254 @@
1
+ """Install and remove Kneepad in each supported agent's own configuration, safely.
2
+
3
+ All edits are additive and reversible: other settings are preserved, invalid files are refused,
4
+ writes are atomic, and a backup is kept. Only entries whose command contains "kneepad hook" are
5
+ ever touched on uninstall.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import shutil
12
+ import stat
13
+ import sys
14
+ from typing import Callable, Dict, List, Optional, Tuple
15
+
16
+ from .installer import InstallError, _load, _write_atomic
17
+ from .util import is_windows, quote_exe
18
+
19
+
20
+ def _exe() -> str:
21
+ exe = shutil.which("kneepad")
22
+ return quote_exe(exe) if exe else f"{quote_exe(sys.executable)} -m kneepad"
23
+
24
+
25
+ def cmd_for(target: str) -> str:
26
+ return f"{_exe()} hook {target}"
27
+
28
+
29
+ def _ours(entry: object) -> bool:
30
+ if not isinstance(entry, dict):
31
+ return False
32
+ c = str(entry.get("command", "")) + str(entry.get("bash", "")) + str(entry.get("powershell", ""))
33
+ return "kneepad" in c and " hook " in f" {c} "
34
+
35
+
36
+ def _backup(path: str) -> None:
37
+ if os.path.exists(path):
38
+ shutil.copy2(path, path + ".kneepad-bak")
39
+
40
+
41
+ # ---------------------------------------------------------------- flat lists: Cursor, Copilot
42
+ def _flat_install(path: str, events: Dict[str, dict], top: Dict[str, object]) -> str:
43
+ data = _load(path)
44
+ for k, v in top.items():
45
+ data.setdefault(k, v)
46
+ hooks = data.setdefault("hooks", {})
47
+ if not isinstance(hooks, dict):
48
+ raise InstallError(f"'hooks' in {path} is not an object; refusing to modify it")
49
+ changed = False
50
+ for ev, entry in events.items():
51
+ lst = hooks.setdefault(ev, [])
52
+ if not isinstance(lst, list):
53
+ raise InstallError(f"'hooks.{ev}' in {path} is not a list; refusing to modify it")
54
+ if not any(_ours(e) for e in lst):
55
+ lst.append(entry)
56
+ changed = True
57
+ if not changed:
58
+ return "already-installed"
59
+ _backup(path)
60
+ _write_atomic(path, data)
61
+ return "installed"
62
+
63
+
64
+ def _flat_uninstall(path: str) -> str:
65
+ if not os.path.exists(path):
66
+ return "not-installed"
67
+ data = _load(path)
68
+ hooks = data.get("hooks")
69
+ if not isinstance(hooks, dict):
70
+ return "not-installed"
71
+ changed = False
72
+ for ev in list(hooks):
73
+ lst = hooks[ev]
74
+ if isinstance(lst, list):
75
+ kept = [e for e in lst if not _ours(e)]
76
+ if len(kept) != len(lst):
77
+ changed = True
78
+ if kept:
79
+ hooks[ev] = kept
80
+ else:
81
+ del hooks[ev]
82
+ if not changed:
83
+ return "not-installed"
84
+ _backup(path)
85
+ _write_atomic(path, data)
86
+ return "removed"
87
+
88
+
89
+ def _flat_is_installed(path: str) -> bool:
90
+ try:
91
+ data = _load(path)
92
+ except InstallError:
93
+ return False
94
+ hooks = data.get("hooks")
95
+ return isinstance(hooks, dict) and any(isinstance(v, list) and any(_ours(e) for e in v) for v in hooks.values())
96
+
97
+
98
+ # ---------------------------------------------------------------- nested: Gemini, Codex
99
+ def _nested_install(path: str, event: str, matcher: str, hook: dict) -> str:
100
+ data = _load(path)
101
+ hooks = data.setdefault("hooks", {})
102
+ if not isinstance(hooks, dict):
103
+ raise InstallError(f"'hooks' in {path} is not an object; refusing to modify it")
104
+ lst = hooks.setdefault(event, [])
105
+ if not isinstance(lst, list):
106
+ raise InstallError(f"'hooks.{event}' in {path} is not a list; refusing to modify it")
107
+ for g in lst:
108
+ if isinstance(g, dict) and isinstance(g.get("hooks"), list) and any(_ours(h) for h in g["hooks"]):
109
+ return "already-installed"
110
+ lst.append({"matcher": matcher, "hooks": [hook]})
111
+ _backup(path)
112
+ _write_atomic(path, data)
113
+ return "installed"
114
+
115
+
116
+ def _nested_uninstall(path: str, event: str) -> str:
117
+ if not os.path.exists(path):
118
+ return "not-installed"
119
+ data = _load(path)
120
+ hooks = data.get("hooks")
121
+ lst = hooks.get(event) if isinstance(hooks, dict) else None
122
+ if not isinstance(lst, list):
123
+ return "not-installed"
124
+ changed = False
125
+ new = []
126
+ for g in lst:
127
+ if isinstance(g, dict) and isinstance(g.get("hooks"), list):
128
+ kept = [h for h in g["hooks"] if not _ours(h)]
129
+ if len(kept) != len(g["hooks"]):
130
+ changed = True
131
+ if kept:
132
+ g = dict(g)
133
+ g["hooks"] = kept
134
+ new.append(g)
135
+ else:
136
+ new.append(g)
137
+ if not changed:
138
+ return "not-installed"
139
+ if new:
140
+ hooks[event] = new
141
+ else:
142
+ del hooks[event]
143
+ _backup(path)
144
+ _write_atomic(path, data)
145
+ return "removed"
146
+
147
+
148
+ def _nested_is_installed(path: str, event: str) -> bool:
149
+ try:
150
+ data = _load(path)
151
+ except InstallError:
152
+ return False
153
+ hooks = data.get("hooks")
154
+ lst = hooks.get(event) if isinstance(hooks, dict) else None
155
+ return isinstance(lst, list) and any(
156
+ isinstance(g, dict) and isinstance(g.get("hooks"), list) and any(_ours(h) for h in g["hooks"]) for g in lst)
157
+
158
+
159
+ # ---------------------------------------------------------------- Cline: script file
160
+ CLINE_MARK = "# kneepad-managed hook"
161
+
162
+
163
+ def _cline_script() -> str:
164
+ return f"#!/usr/bin/env bash\n{CLINE_MARK}\nexec {cmd_for('cline')}\n"
165
+
166
+
167
+ # ---------------------------------------------------------------- targets
168
+ def path_for(target: str, scope: str, cwd: str) -> str:
169
+ home = os.path.expanduser("~")
170
+ proj = os.path.abspath(cwd)
171
+ if target == "cursor":
172
+ return os.path.join(home if scope == "user" else proj, ".cursor", "hooks.json")
173
+ if target == "gemini":
174
+ return os.path.join(home if scope == "user" else proj, ".gemini", "settings.json")
175
+ if target == "codex":
176
+ return os.path.join(home if scope == "user" else proj, ".codex", "hooks.json")
177
+ if target == "copilot":
178
+ return os.path.join(home, ".copilot", "hooks", "kneepad.json") if scope == "user" else os.path.join(proj, ".github", "hooks", "kneepad.json")
179
+ if target == "cline":
180
+ base = os.path.join(home, "Documents", "Cline", "Hooks") if scope == "user" else os.path.join(proj, ".clinerules", "hooks")
181
+ return os.path.join(base, "PreToolUse")
182
+ raise InstallError(f"no installer for {target!r}")
183
+
184
+
185
+ def install_target(target: str, scope: str, cwd: str) -> Tuple[str, str]:
186
+ path = path_for(target, scope, cwd)
187
+ c = cmd_for(target)
188
+ if target == "cursor":
189
+ entry = {"command": c, "failClosed": True}
190
+ r = _flat_install(path, {"beforeShellExecution": entry, "beforeMCPExecution": entry}, {"version": 1})
191
+ elif target == "copilot":
192
+ entry = {"type": "command", "bash": c, "timeoutSec": 30}
193
+ if is_windows():
194
+ entry["powershell"] = c
195
+ r = _flat_install(path, {"preToolUse": entry}, {"version": 1})
196
+ elif target == "gemini":
197
+ r = _nested_install(path, "BeforeTool", ".*", {"name": "kneepad", "type": "command", "command": c, "timeout": 30000})
198
+ elif target == "codex":
199
+ r = _nested_install(path, "PreToolUse", ".*", {"type": "command", "command": c, "timeout": 30})
200
+ elif target == "cline":
201
+ if is_windows():
202
+ raise InstallError("Cline's hooks are documented for macOS and Linux only; Kneepad does not install them on Windows")
203
+ if os.path.exists(path):
204
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
205
+ if CLINE_MARK in fh.read():
206
+ return "already-installed", path
207
+ raise InstallError(f"{path} already exists and is not managed by Kneepad; refusing to overwrite it")
208
+ os.makedirs(os.path.dirname(path), exist_ok=True)
209
+ with open(path, "w", encoding="utf-8") as fh:
210
+ fh.write(_cline_script())
211
+ os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
212
+ r = "installed"
213
+ else:
214
+ raise InstallError(f"no installer for {target!r}")
215
+ return r, path
216
+
217
+
218
+ def uninstall_target(target: str, scope: str, cwd: str) -> Tuple[str, str]:
219
+ path = path_for(target, scope, cwd)
220
+ if target in ("cursor", "copilot"):
221
+ return _flat_uninstall(path), path
222
+ if target == "gemini":
223
+ return _nested_uninstall(path, "BeforeTool"), path
224
+ if target == "codex":
225
+ return _nested_uninstall(path, "PreToolUse"), path
226
+ if target == "cline":
227
+ if not os.path.exists(path):
228
+ return "not-installed", path
229
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
230
+ if CLINE_MARK not in fh.read():
231
+ return "not-installed", path
232
+ os.unlink(path)
233
+ return "removed", path
234
+ raise InstallError(f"no installer for {target!r}")
235
+
236
+
237
+ def is_target_installed(target: str, scope: str, cwd: str) -> bool:
238
+ path = path_for(target, scope, cwd)
239
+ if target in ("cursor", "copilot"):
240
+ return _flat_is_installed(path)
241
+ if target == "gemini":
242
+ return _nested_is_installed(path, "BeforeTool")
243
+ if target == "codex":
244
+ return _nested_is_installed(path, "PreToolUse")
245
+ if target == "cline":
246
+ try:
247
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
248
+ return CLINE_MARK in fh.read()
249
+ except OSError:
250
+ return False
251
+ return False
252
+
253
+
254
+ TARGETS = ("cursor", "gemini", "codex", "copilot", "cline")