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/cli.py ADDED
@@ -0,0 +1,498 @@
1
+ """Command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import shlex
9
+ import shutil
10
+ import stat
11
+ import subprocess
12
+ import sys
13
+ from typing import List, Optional
14
+
15
+ from . import integrations
16
+ from . import __version__
17
+ from .adapters import ADAPTERS
18
+ from .audit import AuditLog
19
+ from .badge import make_badge
20
+ from .config import load_config
21
+ from .engine import Analyzer
22
+ from .hook import handle
23
+ from .integrations import TARGETS, install_target, uninstall_target
24
+ from .installer import InstallError, hook_command, install, is_installed, settings_path, uninstall
25
+ from .rules import load_default_rules, load_rules_text
26
+ from .snapshots import SnapshotError, SnapshotStore
27
+ from .util import kneepad_home
28
+
29
+ EXIT_ALLOW, EXIT_ASK, EXIT_DENY = 0, 10, 20
30
+
31
+
32
+ def _print_decision(d, as_json: bool) -> None:
33
+ if as_json:
34
+ print(json.dumps(d.to_dict(), indent=2))
35
+ return
36
+ print(f"decision: {d.action.upper()}" + (" (monitor mode: not enforced)" if d.mode == "monitor" else ""))
37
+ if not d.findings:
38
+ print("no findings")
39
+ for f in d.findings:
40
+ print(f"- [{f.severity}] {f.rule_id}: {f.title} -> {f.action}")
41
+ if f.detail:
42
+ print(f" matched: {f.detail}")
43
+ if f.note:
44
+ print(f" note: {f.note}")
45
+ if d.plans:
46
+ print("snapshots that would be taken first: " + ", ".join(sorted({p.kind for p in d.plans})))
47
+ for n in d.notes:
48
+ print(f"note: {n}")
49
+
50
+
51
+ def cmd_check(args) -> int:
52
+ cwd = args.cwd or os.getcwd()
53
+ cfg = load_config(cwd)
54
+ az = Analyzer(config=cfg, cwd=cwd)
55
+ if args.tool == "Bash":
56
+ d = az.analyze_shell(args.command)
57
+ elif args.tool == "Write":
58
+ d = az.analyze_write_path(args.command)
59
+ else:
60
+ d = az.analyze_mcp(args.tool, {"query": args.command, "command": args.command})
61
+ _print_decision(d, args.json)
62
+ for w in cfg.warnings:
63
+ print(f"config warning: {w}", file=sys.stderr)
64
+ return {"allow": EXIT_ALLOW, "ask": EXIT_ASK, "deny": EXIT_DENY}[d.action]
65
+
66
+
67
+ def _utf8_streams() -> None:
68
+ """Agents send and expect UTF-8 JSON. Windows consoles default to a legacy code page."""
69
+ for stream in (sys.stdin, sys.stdout, sys.stderr):
70
+ try:
71
+ stream.reconfigure(encoding="utf-8", errors="replace")
72
+ except (AttributeError, ValueError, OSError):
73
+ pass
74
+
75
+
76
+ def cmd_hook(args) -> int:
77
+ _utf8_streams()
78
+ raw = sys.stdin.read()
79
+ code, out = handle(raw, integration=args.target)
80
+ if out:
81
+ (sys.stderr if args.target == "generic" else sys.stdout).write(out + "\n")
82
+ return code
83
+
84
+
85
+ def cmd_init(args) -> int:
86
+ home = kneepad_home()
87
+ log = AuditLog(home)
88
+ log.ensure_key()
89
+ if not log.read_all():
90
+ log.append("init", {"version": __version__})
91
+ print(f"Kneepad state directory: {home}")
92
+ targets = list(getattr(args, "target", None) or [])
93
+ if "all" in targets:
94
+ targets = list(TARGETS)
95
+ for t in targets:
96
+ try:
97
+ res, tpath = install_target(t, args.scope, os.getcwd())
98
+ except InstallError as exc:
99
+ print(f"error ({t}): {exc}", file=sys.stderr)
100
+ return 1
101
+ print(f"{t} hook {res} in {tpath}")
102
+ if args.claude_code:
103
+ path = settings_path(args.scope, os.getcwd())
104
+ try:
105
+ result = install(path, hook_command())
106
+ except InstallError as exc:
107
+ print(f"error: {exc}", file=sys.stderr)
108
+ return 1
109
+ print(f"Claude Code hook {result} in {path}")
110
+ if result == "installed":
111
+ print("Restart Claude Code (or open /hooks) for the change to take effect.")
112
+ elif not targets:
113
+ print("Next: kneepad init --claude-code (add --scope project to install for this repository only)")
114
+ print("Other agents: kneepad init --target cursor|gemini|codex|copilot|cline|all")
115
+ print("Try it: kneepad check 'rm -rf /'")
116
+ return 0
117
+
118
+
119
+ def cmd_uninstall(args) -> int:
120
+ targets = list(getattr(args, "target", None) or [])
121
+ if "all" in targets:
122
+ targets = list(TARGETS)
123
+ for t in targets:
124
+ try:
125
+ res, tpath = uninstall_target(t, args.scope, os.getcwd())
126
+ except InstallError as exc:
127
+ print(f"error ({t}): {exc}", file=sys.stderr)
128
+ return 1
129
+ print(f"{t}: {res}: {tpath}")
130
+ if targets and not getattr(args, "claude_code", False):
131
+ return 0
132
+ path = settings_path(args.scope, os.getcwd())
133
+ try:
134
+ print(f"{uninstall(path)}: {path}")
135
+ except InstallError as exc:
136
+ print(f"error: {exc}", file=sys.stderr)
137
+ return 1
138
+ return 0
139
+
140
+
141
+ def cmd_log(args) -> int:
142
+ entries = AuditLog().tail(args.n)
143
+ if args.json:
144
+ print(json.dumps(entries, indent=2))
145
+ return 0
146
+ for e in entries:
147
+ d = e.get("data", {})
148
+ extra = d.get("command") or d.get("path") or ""
149
+ rules = ",".join(f["rule"] for f in d.get("findings", []))
150
+ print(f"{e['seq']:>5} {e['ts']} {e['event']:<9} {d.get('action', ''):<6} {rules} {extra}"[:200])
151
+ return 0
152
+
153
+
154
+ def cmd_verify(args) -> int:
155
+ log = AuditLog()
156
+ r = log.verify(anchor=args.anchor)
157
+ if r.ok:
158
+ print(f"OK: {r.count} entries, head seq {r.head_seq}, hash {r.head_hash}")
159
+ print("signatures verified" if r.hmac_verified else "signatures NOT verified")
160
+ for w in r.warnings:
161
+ print(f"warning: {w}")
162
+ if not args.anchor:
163
+ print("note: this cannot detect deleted entries at the end of the log. Use `kneepad anchor` and `--anchor`.")
164
+ return 0
165
+ print(f"FAILED: {r.error}")
166
+ return 1
167
+
168
+
169
+ def cmd_anchor(args) -> int:
170
+ a = AuditLog().anchor()
171
+ if not a:
172
+ print("no verifiable log to anchor", file=sys.stderr)
173
+ return 1
174
+ print(a)
175
+ print("Store this value somewhere the agent cannot write, then check with: kneepad verify --anchor " + a)
176
+ return 0
177
+
178
+
179
+ def cmd_rules(args) -> int:
180
+ if args.rules_cmd == "validate":
181
+ try:
182
+ with open(args.file, encoding="utf-8") as fh:
183
+ rules = load_rules_text(fh.read())
184
+ except (OSError, ValueError) as exc:
185
+ print(f"INVALID: {exc}")
186
+ return 1
187
+ print(f"OK: {len(rules)} rules")
188
+ return 0
189
+ rules = load_default_rules()
190
+ if args.rules_cmd == "list":
191
+ for r in rules:
192
+ if args.family and r.family != args.family:
193
+ continue
194
+ print(f"{r.id:<42} {r.severity:<8} {r.action:<5} {r.title}")
195
+ return 0
196
+ if args.rules_cmd == "show":
197
+ for r in rules:
198
+ if r.id == args.id:
199
+ print(f"{r.id}: {r.title}\nfamily: {r.family} severity: {r.severity} action: {r.action} reversible: {r.reversible}")
200
+ print(f"\nWhy: {r.why}\n\nSafer: {r.safer}")
201
+ if r.recipe:
202
+ print(f"\nBack up first: {r.recipe}")
203
+ for u in r.refs:
204
+ print(f"ref: {u}")
205
+ return 0
206
+ print(f"no such rule: {args.id}", file=sys.stderr)
207
+ return 1
208
+ return 2
209
+
210
+
211
+ def cmd_snapshots(args) -> int:
212
+ store = SnapshotStore()
213
+ if args.snap_cmd == "list":
214
+ for m in store.list():
215
+ print(f"{m['id']} {m['kind']:<10} {m.get('rule', ''):<28} {m['cwd']}")
216
+ return 0
217
+ if args.snap_cmd == "show":
218
+ m = store.get(args.id)
219
+ if not m:
220
+ print("no such snapshot", file=sys.stderr)
221
+ return 1
222
+ print(json.dumps(m, indent=2))
223
+ return 0
224
+ if args.snap_cmd == "restore":
225
+ try:
226
+ for line in store.restore(args.id, force=args.force, to=args.to, apply=args.apply):
227
+ print(line)
228
+ except SnapshotError as exc:
229
+ print(f"error: {exc}", file=sys.stderr)
230
+ return 1
231
+ return 0
232
+ if args.snap_cmd == "prune":
233
+ removed = store.prune(older_than_days=args.older_than_days, max_total_mb=args.max_total_mb)
234
+ print(f"removed {len(removed)} snapshots")
235
+ return 0
236
+ return 2
237
+
238
+
239
+ def _check_item(ok: Optional[bool], label: str, detail: str = "") -> str:
240
+ tag = {True: "OK ", False: "FAIL", None: "WARN"}[ok]
241
+ return f"[{tag}] {label}" + (f": {detail}" if detail else "")
242
+
243
+
244
+ def run_doctor(cwd: str) -> List[tuple]:
245
+ """Return a list of (status, label, detail). status is True, False or None (warning)."""
246
+ items: List[tuple] = []
247
+ home = kneepad_home()
248
+ items.append((sys.version_info >= (3, 11), "Python >= 3.11", sys.version.split()[0]))
249
+ try:
250
+ rules = load_default_rules()
251
+ items.append((True, "footgun database loads and validates", f"{len(rules)} rules"))
252
+ except Exception as exc:
253
+ items.append((False, "footgun database", str(exc)[:200]))
254
+ win = sys.platform == "win32"
255
+ if os.path.isdir(home) and win:
256
+ items.append((None, "state directory is private", f"{home} (NTFS: protected by your user profile ACL, not checked)"))
257
+ elif os.path.isdir(home):
258
+ mode = stat.S_IMODE(os.stat(home).st_mode)
259
+ items.append((mode & 0o077 == 0 or None, "state directory is private", f"{home} mode {oct(mode)}"))
260
+ else:
261
+ items.append((None, "state directory exists", f"{home} not created yet; run kneepad init"))
262
+ log = AuditLog(home)
263
+ if os.path.exists(log.key_path) and win:
264
+ items.append((None, "audit key is private", "NTFS: protected by your user profile ACL, not checked"))
265
+ elif os.path.exists(log.key_path):
266
+ mode = stat.S_IMODE(os.stat(log.key_path).st_mode)
267
+ items.append((mode & 0o077 == 0, "audit key is private", oct(mode)))
268
+ else:
269
+ items.append((None, "audit key", "missing; run kneepad init"))
270
+ r = log.verify()
271
+ items.append((r.ok, "audit log verifies", f"{r.count} entries" if r.ok else r.error))
272
+ user_ok = is_installed(settings_path("user", cwd))
273
+ proj_ok = is_installed(settings_path("project", cwd))
274
+ others = []
275
+ for t in integrations.TARGETS:
276
+ for scope in ("user", "project"):
277
+ try:
278
+ if integrations.is_target_installed(t, scope, cwd):
279
+ others.append((t, scope))
280
+ break
281
+ except Exception:
282
+ continue
283
+ claude_ok = user_ok or proj_ok
284
+ any_ok = claude_ok or bool(others)
285
+ items.append((True if claude_ok else (None if any_ok else False), "Claude Code hook installed",
286
+ "user" if user_ok else ("project" if proj_ok else "not installed" if any_ok else "not found; run kneepad init --claude-code")))
287
+ for t, scope in others:
288
+ items.append((True, f"{t} hook installed", scope))
289
+ items.append((True if subprocess.run(["git", "--version"], capture_output=True).returncode == 0 else None,
290
+ "git available (needed for git snapshots)", ""))
291
+ cfg = load_config(cwd)
292
+ for w in cfg.warnings:
293
+ items.append((None, "config warning", w))
294
+ items.append((True if cfg.mode == "enforce" else None, "mode", cfg.mode))
295
+ return items
296
+
297
+
298
+ def cmd_doctor(args) -> int:
299
+ items = run_doctor(os.getcwd())
300
+ for status, label, detail in items:
301
+ print(_check_item(status, label, detail))
302
+ return 1 if any(s is False for s, _l, _d in items) else 0
303
+
304
+
305
+ def cmd_badge(args) -> int:
306
+ if not args.force:
307
+ items = run_doctor(os.getcwd())
308
+ hook = any(s is True for s, l, _d in items if l.endswith("hook installed"))
309
+ log_ok = next(s for s, l, _d in items if l == "audit log verifies")
310
+ if not (hook and log_ok):
311
+ print("Refusing to create a 'protected by kneepad' badge: the hook is not installed or the audit log "
312
+ "does not verify. Run `kneepad doctor`. (Use --force to override.)", file=sys.stderr)
313
+ return 1
314
+ out = args.out
315
+ with open(out, "w", encoding="utf-8") as fh:
316
+ fh.write(make_badge())
317
+ print(f"wrote {out}")
318
+ print(f"Markdown: ![Protected by Kneepad](./{os.path.basename(out)})")
319
+ return 0
320
+
321
+
322
+ def _default_real_shell() -> str:
323
+ if sys.platform == "win32":
324
+ return shutil.which("bash") or shutil.which("sh") or "bash"
325
+ for cand in ("/bin/bash", "/usr/bin/bash", "/bin/sh"):
326
+ if os.path.exists(cand):
327
+ return cand
328
+ return "/bin/sh"
329
+
330
+
331
+ def cmd_shell(args) -> int:
332
+ """Drop-in for $SHELL: `kneepad shell -c "cmd"` checks the command, then runs it with the real shell.
333
+
334
+ Works with any agent that executes commands through $SHELL -c (set SHELL to the wrapper path).
335
+ """
336
+ real = os.environ.get("KNEEPAD_REAL_SHELL") or _default_real_shell()
337
+ argv = list(args.argv)
338
+ if argv and argv[0] == "--":
339
+ argv = argv[1:]
340
+ if len(argv) >= 2 and argv[0] in ("-c", "-lc", "-ic", "-cl", "-l", "-i") and argv[0].endswith("c"):
341
+ cfg = load_config(os.getcwd())
342
+ d = Analyzer(config=cfg, cwd=os.getcwd()).analyze_shell(argv[1])
343
+ if d.action in ("deny", "ask") and cfg.mode != "monitor":
344
+ print(d.reason(), file=sys.stderr)
345
+ print("Kneepad blocked this command.", file=sys.stderr)
346
+ return 126
347
+ if sys.platform == "win32": # os.execv on Windows detaches and loses the exit code
348
+ try:
349
+ return subprocess.call([real] + argv)
350
+ except OSError as exc:
351
+ print(f"kneepad shell: cannot run {real}: {exc}", file=sys.stderr)
352
+ return 127
353
+ os.execv(real, [real] + argv)
354
+ return 127 # pragma: no cover
355
+
356
+
357
+ def cmd_run(args) -> int:
358
+ argv = args.argv
359
+ if argv and argv[0] == "--":
360
+ argv = argv[1:]
361
+ if not argv:
362
+ print("usage: kneepad run -- COMMAND [ARGS...]", file=sys.stderr)
363
+ return 2
364
+ text = subprocess.list2cmdline(argv) if sys.platform == "win32" else shlex.join(argv)
365
+ cfg = load_config(os.getcwd())
366
+ az = Analyzer(config=cfg, cwd=os.getcwd())
367
+ d = az.analyze_shell(text)
368
+ if d.action in ("deny", "ask") and cfg.mode != "monitor":
369
+ print(d.reason(), file=sys.stderr)
370
+ if d.action == "deny":
371
+ return 126
372
+ if not sys.stdin.isatty():
373
+ print("Not a terminal, so Kneepad cannot ask. Refusing.", file=sys.stderr)
374
+ return 126
375
+ if input("Run it anyway? [y/N] ").strip().lower() != "y":
376
+ return 126
377
+ if d.plans:
378
+ store = SnapshotStore()
379
+ try:
380
+ for p in d.plans:
381
+ sid = store.create(p)["id"]
382
+ print(f"kneepad: snapshot {sid}", file=sys.stderr)
383
+ except SnapshotError as exc:
384
+ print(f"kneepad: snapshot failed ({exc}); refusing to run.", file=sys.stderr)
385
+ return 126
386
+ try:
387
+ AuditLog().append("decision", {"tool": "run", "action": d.action, "command": text[:2000],
388
+ "findings": [{"rule": f.rule_id, "action": f.action} for f in d.findings]})
389
+ except Exception:
390
+ pass
391
+ return subprocess.call(argv)
392
+
393
+
394
+ def build_parser() -> argparse.ArgumentParser:
395
+ p = argparse.ArgumentParser(prog="kneepad", description="A kneepad for AI coding agents.")
396
+ p.add_argument("--version", action="version", version=f"kneepad {__version__}")
397
+ sub = p.add_subparsers(dest="cmd", required=True)
398
+
399
+ s = sub.add_parser("init", help="create state, key and optionally install the Claude Code hook")
400
+ s.add_argument("--claude-code", action="store_true")
401
+ s.add_argument("--target", action="append", choices=list(TARGETS) + ["all"], help="also install for another agent (repeatable)")
402
+ s.add_argument("--scope", choices=["user", "project"], default="user")
403
+ s.set_defaults(func=cmd_init)
404
+
405
+ s = sub.add_parser("uninstall", help="remove the Claude Code hook (or --target another agent)")
406
+ s.add_argument("--claude-code", action="store_true", help="also remove the Claude Code hook when --target is given")
407
+ s.add_argument("--target", action="append", choices=list(TARGETS) + ["all"])
408
+ s.add_argument("--scope", choices=["user", "project"], default="user")
409
+ s.set_defaults(func=cmd_uninstall)
410
+
411
+ s = sub.add_parser("hook", help="run as a hook (reads JSON on stdin)")
412
+ s.add_argument("target", choices=sorted(ADAPTERS))
413
+ s.set_defaults(func=cmd_hook)
414
+
415
+ s = sub.add_parser("check", help="dry-run a command and show the decision")
416
+ s.add_argument("command")
417
+ s.add_argument("--cwd")
418
+ s.add_argument("--tool", default="Bash", help="Bash (default), Write, or an mcp__ tool name")
419
+ s.add_argument("--json", action="store_true")
420
+ s.set_defaults(func=cmd_check)
421
+
422
+ s = sub.add_parser("shell", help="shell wrapper for agents that run commands through $SHELL -c")
423
+ s.add_argument("argv", nargs=argparse.REMAINDER)
424
+ s.set_defaults(func=cmd_shell)
425
+
426
+ s = sub.add_parser("run", help="analyse a command and, if allowed, run it")
427
+ s.add_argument("argv", nargs=argparse.REMAINDER)
428
+ s.set_defaults(func=cmd_run)
429
+
430
+ s = sub.add_parser("log", help="show recent audit log entries")
431
+ s.add_argument("-n", type=int, default=20)
432
+ s.add_argument("--json", action="store_true")
433
+ s.set_defaults(func=cmd_log)
434
+
435
+ s = sub.add_parser("verify", help="verify the audit log hash chain and signatures")
436
+ s.add_argument("--anchor", help="SEQ:HASH recorded earlier with `kneepad anchor`")
437
+ s.set_defaults(func=cmd_verify)
438
+
439
+ s = sub.add_parser("anchor", help="print the current head of the log to store externally")
440
+ s.set_defaults(func=cmd_anchor)
441
+
442
+ s = sub.add_parser("rules", help="browse and validate the footgun database")
443
+ rs = s.add_subparsers(dest="rules_cmd", required=True)
444
+ r = rs.add_parser("list")
445
+ r.add_argument("--family")
446
+ r = rs.add_parser("show")
447
+ r.add_argument("id")
448
+ r = rs.add_parser("validate")
449
+ r.add_argument("file")
450
+ s.set_defaults(func=cmd_rules)
451
+
452
+ s = sub.add_parser("snapshots", help="list, show, restore or prune safety snapshots")
453
+ ss = s.add_subparsers(dest="snap_cmd", required=True)
454
+ ss.add_parser("list")
455
+ x = ss.add_parser("show")
456
+ x.add_argument("id")
457
+ x = ss.add_parser("restore")
458
+ x.add_argument("id")
459
+ x.add_argument("--force", action="store_true")
460
+ x.add_argument("--to")
461
+ x.add_argument("--apply", action="store_true", help="for git snapshots: apply saved changes")
462
+ x = ss.add_parser("prune")
463
+ x.add_argument("--older-than-days", type=float)
464
+ x.add_argument("--max-total-mb", type=int)
465
+ s.set_defaults(func=cmd_snapshots)
466
+
467
+ s = sub.add_parser("doctor", help="check the installation")
468
+ s.set_defaults(func=cmd_doctor)
469
+
470
+ s = sub.add_parser("badge", help="write the 'protected by kneepad' badge (only if actually protected)")
471
+ s.add_argument("--out", default="kneepad-badge.svg")
472
+ s.add_argument("--force", action="store_true")
473
+ s.set_defaults(func=cmd_badge)
474
+ return p
475
+
476
+
477
+ def shell_main() -> int:
478
+ """Entry point for `kneepad-shell`: a drop-in value for $SHELL."""
479
+ return main(["shell"] + sys.argv[1:])
480
+
481
+
482
+ def main(argv: Optional[List[str]] = None) -> int:
483
+ raw = list(sys.argv[1:] if argv is None else argv)
484
+ # `shell` and `run` forward arbitrary arguments (including -c and other dash options) to another
485
+ # program, which argparse cannot express with REMAINDER when the first token starts with a dash.
486
+ if raw and raw[0] in ("shell", "run"):
487
+ ns = argparse.Namespace(argv=raw[1:])
488
+ try:
489
+ return int((cmd_shell if raw[0] == "shell" else cmd_run)(ns))
490
+ except KeyboardInterrupt:
491
+ return 130
492
+ args = build_parser().parse_args(raw)
493
+ try:
494
+ return int(args.func(args))
495
+ except KeyboardInterrupt:
496
+ return 130
497
+ except BrokenPipeError:
498
+ return 0
kneepad/config.py ADDED
@@ -0,0 +1,185 @@
1
+ """Configuration loading.
2
+
3
+ Two layers:
4
+
5
+ * User config at ``$KNEEPAD_HOME/config.toml`` (default ``~/.kneepad/config.toml``).
6
+ This is trusted. It may relax or disable rules.
7
+ * Project config at ``.kneepad.toml`` found by walking up from the working
8
+ directory. A repository is untrusted input, because an agent works inside
9
+ repositories it did not write. Project config can therefore only make Kneepad
10
+ *stricter*. Any attempt to relax it is ignored and reported as a warning.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import tomllib
17
+ from dataclasses import dataclass, field
18
+ from typing import Dict, List, Optional, Set
19
+
20
+ from .rules import ACTION_RANK, ACTIONS
21
+ from .util import kneepad_home
22
+
23
+ DEFAULT_IGNORE_DIRS = frozenset(
24
+ {
25
+ "node_modules", "__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".tox",
26
+ ".venv", "venv", "dist", "build", ".next", ".nuxt", ".cache", ".gradle", ".parcel-cache",
27
+ ".turbo", ".terraform", "coverage", ".eggs", ".sass-cache", ".angular",
28
+ }
29
+ )
30
+
31
+ DEFAULT_PROD_MARKERS = [r"(?i)(?<![a-z0-9])(?:prod|production|prd)(?![a-z0-9])"]
32
+
33
+ USER_KEYS = {
34
+ "mode", "disable_rules", "action_overrides", "allow_patterns", "protected_paths",
35
+ "allow_write_paths", "prod_markers", "snapshot_max_mb", "snapshot_max_files",
36
+ "snapshot_total_mb", "ignore_dirs", "protected_branches",
37
+ }
38
+ PROJECT_KEYS = {"protected_paths", "prod_markers", "escalate", "snapshot_max_mb", "protected_branches"}
39
+
40
+
41
+ @dataclass
42
+ class Config:
43
+ mode: str = "enforce"
44
+ disable_rules: Set[str] = field(default_factory=set)
45
+ action_overrides: Dict[str, str] = field(default_factory=dict)
46
+ escalations: Dict[str, str] = field(default_factory=dict)
47
+ allow_patterns: List[str] = field(default_factory=list)
48
+ protected_paths: List[str] = field(default_factory=list)
49
+ allow_write_paths: List[str] = field(default_factory=list)
50
+ prod_markers: List[str] = field(default_factory=lambda: list(DEFAULT_PROD_MARKERS))
51
+ snapshot_max_mb: int = 200
52
+ snapshot_max_files: int = 50000
53
+ snapshot_total_mb: int = 2048
54
+ ignore_dirs: Set[str] = field(default_factory=lambda: set(DEFAULT_IGNORE_DIRS))
55
+ protected_branches: List[str] = field(default_factory=list)
56
+ warnings: List[str] = field(default_factory=list)
57
+ sources: List[str] = field(default_factory=list)
58
+
59
+
60
+ def _read_toml(path: str, warnings: List[str]) -> Optional[dict]:
61
+ try:
62
+ with open(path, "rb") as fh:
63
+ return tomllib.load(fh)
64
+ except FileNotFoundError:
65
+ return None
66
+ except (tomllib.TOMLDecodeError, OSError, UnicodeDecodeError) as exc:
67
+ warnings.append(f"{path}: could not be read ({exc}); ignored")
68
+ return None
69
+
70
+
71
+ def _str_list(val, key: str, warnings: List[str], src: str) -> List[str]:
72
+ if isinstance(val, list) and all(isinstance(x, str) for x in val):
73
+ return list(val)
74
+ warnings.append(f"{src}: {key} must be a list of strings; ignored")
75
+ return []
76
+
77
+
78
+ def _apply_user(cfg: Config, data: dict, src: str) -> None:
79
+ for key in data:
80
+ if key not in USER_KEYS:
81
+ cfg.warnings.append(f"{src}: unknown key {key!r} ignored")
82
+ mode = data.get("mode")
83
+ if mode is not None:
84
+ if mode in ("enforce", "monitor"):
85
+ cfg.mode = mode
86
+ else:
87
+ cfg.warnings.append(f"{src}: mode must be 'enforce' or 'monitor'; ignored")
88
+ if "disable_rules" in data:
89
+ cfg.disable_rules |= set(_str_list(data["disable_rules"], "disable_rules", cfg.warnings, src))
90
+ if "action_overrides" in data:
91
+ ov = data["action_overrides"]
92
+ if isinstance(ov, dict):
93
+ for rid, act in ov.items():
94
+ if act in ACTIONS:
95
+ cfg.action_overrides[rid] = act
96
+ else:
97
+ cfg.warnings.append(f"{src}: action_overrides[{rid}] must be one of {ACTIONS}; ignored")
98
+ else:
99
+ cfg.warnings.append(f"{src}: action_overrides must be a table; ignored")
100
+ for key in ("allow_patterns", "protected_paths", "allow_write_paths", "prod_markers", "protected_branches"):
101
+ if key in data:
102
+ vals = _str_list(data[key], key, cfg.warnings, src)
103
+ if key == "prod_markers":
104
+ cfg.prod_markers.extend(vals)
105
+ else:
106
+ getattr(cfg, key).extend(vals)
107
+ for key in ("snapshot_max_mb", "snapshot_max_files", "snapshot_total_mb"):
108
+ if key in data:
109
+ v = data[key]
110
+ if isinstance(v, int) and not isinstance(v, bool) and v >= 0:
111
+ setattr(cfg, key, v)
112
+ else:
113
+ cfg.warnings.append(f"{src}: {key} must be a non-negative integer; ignored")
114
+ if "ignore_dirs" in data:
115
+ cfg.ignore_dirs |= set(_str_list(data["ignore_dirs"], "ignore_dirs", cfg.warnings, src))
116
+
117
+
118
+ def _apply_project(cfg: Config, data: dict, src: str) -> None:
119
+ for key in data:
120
+ if key not in PROJECT_KEYS:
121
+ if key in USER_KEYS:
122
+ cfg.warnings.append(
123
+ f"{src}: {key!r} would relax protection and is ignored. "
124
+ "Project config can only make Kneepad stricter; put relaxations in your user config."
125
+ )
126
+ else:
127
+ cfg.warnings.append(f"{src}: unknown key {key!r} ignored")
128
+ if "protected_paths" in data:
129
+ cfg.protected_paths.extend(_str_list(data["protected_paths"], "protected_paths", cfg.warnings, src))
130
+ if "prod_markers" in data:
131
+ cfg.prod_markers.extend(_str_list(data["prod_markers"], "prod_markers", cfg.warnings, src))
132
+ if "protected_branches" in data:
133
+ cfg.protected_branches.extend(_str_list(data["protected_branches"], "protected_branches", cfg.warnings, src))
134
+ if "escalate" in data:
135
+ esc = data["escalate"]
136
+ if isinstance(esc, dict):
137
+ for rid, act in esc.items():
138
+ if act in ("ask", "deny"):
139
+ cfg.escalations[rid] = act
140
+ else:
141
+ cfg.warnings.append(f"{src}: escalate[{rid}] must be 'ask' or 'deny'; ignored")
142
+ else:
143
+ cfg.warnings.append(f"{src}: escalate must be a table; ignored")
144
+ if "snapshot_max_mb" in data:
145
+ v = data["snapshot_max_mb"]
146
+ if isinstance(v, int) and not isinstance(v, bool) and 0 <= v <= cfg.snapshot_max_mb:
147
+ cfg.snapshot_max_mb = v
148
+ else:
149
+ cfg.warnings.append(f"{src}: snapshot_max_mb may only be lowered; ignored")
150
+
151
+
152
+ def find_project_config(cwd: str) -> Optional[str]:
153
+ d = os.path.abspath(cwd)
154
+ while True:
155
+ cand = os.path.join(d, ".kneepad.toml")
156
+ if os.path.isfile(cand):
157
+ return cand
158
+ parent = os.path.dirname(d)
159
+ if parent == d:
160
+ return None
161
+ d = parent
162
+
163
+
164
+ def load_config(cwd: Optional[str] = None, home: Optional[str] = None) -> Config:
165
+ cfg = Config()
166
+ base = home or kneepad_home()
167
+ user_path = os.path.join(base, "config.toml")
168
+ data = _read_toml(user_path, cfg.warnings)
169
+ if data is not None:
170
+ _apply_user(cfg, data, user_path)
171
+ cfg.sources.append(user_path)
172
+ env_mode = os.environ.get("KNEEPAD_MODE")
173
+ if env_mode in ("enforce", "monitor"):
174
+ cfg.mode = env_mode
175
+ proj = find_project_config(cwd or os.getcwd())
176
+ if proj:
177
+ pdata = _read_toml(proj, cfg.warnings)
178
+ if pdata is not None:
179
+ _apply_project(cfg, pdata, proj)
180
+ cfg.sources.append(proj)
181
+ return cfg
182
+
183
+
184
+ def stronger(a: str, b: str) -> str:
185
+ return a if ACTION_RANK[a] >= ACTION_RANK[b] else b