kneepad 0.3.0__tar.gz → 0.3.1__tar.gz

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.
Files changed (51) hide show
  1. {kneepad-0.3.0/src/kneepad.egg-info → kneepad-0.3.1}/PKG-INFO +5 -5
  2. {kneepad-0.3.0 → kneepad-0.3.1}/README.md +4 -4
  3. {kneepad-0.3.0 → kneepad-0.3.1}/pyproject.toml +1 -1
  4. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/__init__.py +1 -1
  5. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/api.py +3 -0
  6. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/argvtools.py +2 -0
  7. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/audit.py +76 -8
  8. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/cli.py +134 -46
  9. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/engine.py +61 -12
  10. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/installer.py +27 -6
  11. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/integrations.py +2 -2
  12. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/util.py +12 -0
  13. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/winshell.py +44 -4
  14. {kneepad-0.3.0 → kneepad-0.3.1/src/kneepad.egg-info}/PKG-INFO +5 -5
  15. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad.egg-info/SOURCES.txt +9 -1
  16. kneepad-0.3.1/tests/test_allow_deny_matrix.py +284 -0
  17. {kneepad-0.3.0 → kneepad-0.3.1}/tests/test_audit_snapshots_hook.py +2 -0
  18. kneepad-0.3.1/tests/test_branches.py +698 -0
  19. {kneepad-0.3.0 → kneepad-0.3.1}/tests/test_engine.py +5 -3
  20. {kneepad-0.3.0 → kneepad-0.3.1}/tests/test_integrations.py +15 -7
  21. kneepad-0.3.1/tests/test_qa_corpus.py +64 -0
  22. kneepad-0.3.1/tests/test_qa_regressions.py +210 -0
  23. kneepad-0.3.1/tests/test_races.py +210 -0
  24. kneepad-0.3.1/tests/test_symlink_alias.py +49 -0
  25. kneepad-0.3.1/tests/test_verify_rules_fuzz.py +282 -0
  26. kneepad-0.3.1/tests/test_windows_parity.py +207 -0
  27. {kneepad-0.3.0 → kneepad-0.3.1}/LICENSE +0 -0
  28. {kneepad-0.3.0 → kneepad-0.3.1}/setup.cfg +0 -0
  29. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/__main__.py +0 -0
  30. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/adapters.py +0 -0
  31. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/badge.py +0 -0
  32. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/config.py +0 -0
  33. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/data/footguns.toml +0 -0
  34. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/data/footguns_ext.toml +0 -0
  35. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/data/footguns_macos.toml +0 -0
  36. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/data/footguns_windows.toml +0 -0
  37. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/hook.py +0 -0
  38. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/rules.py +0 -0
  39. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/shellparse.py +0 -0
  40. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/snapshots.py +0 -0
  41. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad/sqlscan.py +0 -0
  42. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad.egg-info/dependency_links.txt +0 -0
  43. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad.egg-info/entry_points.txt +0 -0
  44. {kneepad-0.3.0 → kneepad-0.3.1}/src/kneepad.egg-info/top_level.txt +0 -0
  45. {kneepad-0.3.0 → kneepad-0.3.1}/tests/test_corpus.py +0 -0
  46. {kneepad-0.3.0 → kneepad-0.3.1}/tests/test_hardening.py +0 -0
  47. {kneepad-0.3.0 → kneepad-0.3.1}/tests/test_platforms.py +0 -0
  48. {kneepad-0.3.0 → kneepad-0.3.1}/tests/test_robustness.py +0 -0
  49. {kneepad-0.3.0 → kneepad-0.3.1}/tests/test_rules_db.py +0 -0
  50. {kneepad-0.3.0 → kneepad-0.3.1}/tests/test_shellparse.py +0 -0
  51. {kneepad-0.3.0 → kneepad-0.3.1}/tests/test_sqlscan.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: kneepad
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: Local safety layer for AI coding agents on Linux, macOS and Windows: blocks or snapshots destructive commands, with a footgun database and a tamper-evident audit log.
5
5
  License: MIT
6
6
  Classifier: Programming Language :: Python :: 3
@@ -26,7 +26,7 @@ Zero dependencies. Python 3.11+. Linux, macOS and Windows. Runs entirely on your
26
26
  - **Footgun database.** 249 rules (216 pattern rules plus 33 emitted by engine code) for the commands that ruin days: `rm -rf` on the wrong path, `git push --force` to main, `terraform destroy`, `DROP TABLE`, `kubectl delete ns`, `aws s3 rb --force`, `prisma migrate reset`, `curl | sh`, writes to `~/.ssh` and `.bashrc`, and more. Rules are pattern families (one rule covers every `delete`/`destroy`/`terminate` subcommand of a cloud CLI, for example), across about 560 named tools, including Windows and macOS tools. Count of rules is not coverage: more rules also means more false positives, so every rule must pass the benign corpus. Every rule ships with examples that the test suite executes.
27
27
  - **Understands shell, not just text.** Quotes, `$(...)`, backticks, heredocs, pipes, `bash -c`, `eval`, `ssh host '...'`, `docker exec`, `kubectl exec --`, `sudo`/`env`/`nice` wrappers, `npx`/`poetry run`/`bundle exec`, and shell scripts the agent is about to run. `echo "rm -rf /"` is not flagged. `DIR=; rm -rf $DIR/` is.
28
28
  - **Snapshots before risky-but-allowed actions.** Deleting untracked files, `git reset --hard`, `git clean`, `git branch -D` each take a copy first. Restore with `kneepad snapshots restore <id>`.
29
- - **Hash-chained audit log.** Every decision is appended to a JSONL log where each entry commits to the previous one and is signed with a local key. Editing, deleting, reordering or inserting entries is detected by `kneepad verify`.
29
+ - **Hash-chained audit log.** Every decision that has a finding (anything other than a plain allow), and every `kneepad run` decision, is appended to a JSONL log where each entry commits to the previous one and is signed with a local key. Editing, deleting, reordering or inserting entries is detected by `kneepad verify`.
30
30
  - **"Protected by Kneepad" badge.** `kneepad badge` writes an SVG, and refuses to if the hook is not installed or the log does not verify.
31
31
 
32
32
  Decision model: Kneepad never says "allow". Safe commands pass through silently and keep your normal permission flow. Risky ones get `ask`. Catastrophic ones get `deny`. If Kneepad itself errors, it answers `ask`.
@@ -41,9 +41,9 @@ Claude Code, OpenAI Codex CLI, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, an
41
41
  |---|---|---|---|
42
42
  | Command analysis | yes | yes: `diskutil`, `tmutil`, `csrutil`, `launchctl`, `security`, `dscl`, `osascript do shell script`, `/private` paths, case-insensitive volumes | yes: cmd.exe and PowerShell syntax, drive and UNC paths, `Remove-Item`/`del`/`rd`, registry, `-EncodedCommand` is decoded, `wsl`/`cmd /c`/`powershell -c` are unwrapped |
43
43
  | Agent hook installers | all | all | all except Cline (its docs say macOS and Linux only) |
44
- | Continuous integration | full suite | full suite | rule examples and platform tests (experimental, not yet seen green) |
44
+ | Continuous integration | full suite | full suite | rule examples and platform tests (the suites that run there passed on real Windows runners for 0.3.0) |
45
45
 
46
- Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The CI workflow runs on macOS and Windows runners, but until you have seen it pass there, treat both as unproven on real machines. No agent integration has been run inside its real vendor app on any operating system. Known gaps are listed in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
46
+ Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The full suite passes on real macOS runners, and the Windows-specific tests pass on real Windows runners (Windows does not run the whole suite). Neither has been used by a person on a real machine with a real agent, so treat both as lightly proven. No agent integration has been run inside its real vendor app on any operating system. Known gaps are listed in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
47
47
 
48
48
  ## Install
49
49
 
@@ -99,6 +99,6 @@ Read [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) before relying on it. In short
99
99
  python3 -m unittest discover -s tests
100
100
  ```
101
101
 
102
- 258 tests: parser, SQL scanner, every rule example, about 280 everyday commands that must pass silently, about 120 destructive commands that must be stopped, audit tamper fuzzing (every single byte flip is detected), concurrent writers, hostile-repo handling, random-input robustness, and Windows and macOS path and syntax simulation. `python tools/smoke_hook.py` installs the hooks into a throwaway home and runs the written hook command through your real OS shell.
102
+ 408 tests: parser, SQL scanner, every rule example, about 280 everyday commands that must pass silently, about 120 destructive commands that must be stopped, audit tamper fuzzing (every single byte flip is detected), concurrent writers, hostile-repo handling, random-input robustness, and Windows and macOS path and syntax simulation. `python tools/smoke_hook.py` installs the hooks into a throwaway home and runs the written hook command through your real OS shell.
103
103
 
104
104
  Adding a rule: see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md). The rule list is in [docs/FOOTGUNS.md](docs/FOOTGUNS.md).
@@ -9,7 +9,7 @@ Zero dependencies. Python 3.11+. Linux, macOS and Windows. Runs entirely on your
9
9
  - **Footgun database.** 249 rules (216 pattern rules plus 33 emitted by engine code) for the commands that ruin days: `rm -rf` on the wrong path, `git push --force` to main, `terraform destroy`, `DROP TABLE`, `kubectl delete ns`, `aws s3 rb --force`, `prisma migrate reset`, `curl | sh`, writes to `~/.ssh` and `.bashrc`, and more. Rules are pattern families (one rule covers every `delete`/`destroy`/`terminate` subcommand of a cloud CLI, for example), across about 560 named tools, including Windows and macOS tools. Count of rules is not coverage: more rules also means more false positives, so every rule must pass the benign corpus. Every rule ships with examples that the test suite executes.
10
10
  - **Understands shell, not just text.** Quotes, `$(...)`, backticks, heredocs, pipes, `bash -c`, `eval`, `ssh host '...'`, `docker exec`, `kubectl exec --`, `sudo`/`env`/`nice` wrappers, `npx`/`poetry run`/`bundle exec`, and shell scripts the agent is about to run. `echo "rm -rf /"` is not flagged. `DIR=; rm -rf $DIR/` is.
11
11
  - **Snapshots before risky-but-allowed actions.** Deleting untracked files, `git reset --hard`, `git clean`, `git branch -D` each take a copy first. Restore with `kneepad snapshots restore <id>`.
12
- - **Hash-chained audit log.** Every decision is appended to a JSONL log where each entry commits to the previous one and is signed with a local key. Editing, deleting, reordering or inserting entries is detected by `kneepad verify`.
12
+ - **Hash-chained audit log.** Every decision that has a finding (anything other than a plain allow), and every `kneepad run` decision, is appended to a JSONL log where each entry commits to the previous one and is signed with a local key. Editing, deleting, reordering or inserting entries is detected by `kneepad verify`.
13
13
  - **"Protected by Kneepad" badge.** `kneepad badge` writes an SVG, and refuses to if the hook is not installed or the log does not verify.
14
14
 
15
15
  Decision model: Kneepad never says "allow". Safe commands pass through silently and keep your normal permission flow. Risky ones get `ask`. Catastrophic ones get `deny`. If Kneepad itself errors, it answers `ask`.
@@ -24,9 +24,9 @@ Claude Code, OpenAI Codex CLI, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, an
24
24
  |---|---|---|---|
25
25
  | Command analysis | yes | yes: `diskutil`, `tmutil`, `csrutil`, `launchctl`, `security`, `dscl`, `osascript do shell script`, `/private` paths, case-insensitive volumes | yes: cmd.exe and PowerShell syntax, drive and UNC paths, `Remove-Item`/`del`/`rd`, registry, `-EncodedCommand` is decoded, `wsl`/`cmd /c`/`powershell -c` are unwrapped |
26
26
  | Agent hook installers | all | all | all except Cline (its docs say macOS and Linux only) |
27
- | Continuous integration | full suite | full suite | rule examples and platform tests (experimental, not yet seen green) |
27
+ | Continuous integration | full suite | full suite | rule examples and platform tests (the suites that run there passed on real Windows runners for 0.3.0) |
28
28
 
29
- Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The CI workflow runs on macOS and Windows runners, but until you have seen it pass there, treat both as unproven on real machines. No agent integration has been run inside its real vendor app on any operating system. Known gaps are listed in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
29
+ Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The full suite passes on real macOS runners, and the Windows-specific tests pass on real Windows runners (Windows does not run the whole suite). Neither has been used by a person on a real machine with a real agent, so treat both as lightly proven. No agent integration has been run inside its real vendor app on any operating system. Known gaps are listed in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
30
30
 
31
31
  ## Install
32
32
 
@@ -82,6 +82,6 @@ Read [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) before relying on it. In short
82
82
  python3 -m unittest discover -s tests
83
83
  ```
84
84
 
85
- 258 tests: parser, SQL scanner, every rule example, about 280 everyday commands that must pass silently, about 120 destructive commands that must be stopped, audit tamper fuzzing (every single byte flip is detected), concurrent writers, hostile-repo handling, random-input robustness, and Windows and macOS path and syntax simulation. `python tools/smoke_hook.py` installs the hooks into a throwaway home and runs the written hook command through your real OS shell.
85
+ 408 tests: parser, SQL scanner, every rule example, about 280 everyday commands that must pass silently, about 120 destructive commands that must be stopped, audit tamper fuzzing (every single byte flip is detected), concurrent writers, hostile-repo handling, random-input robustness, and Windows and macOS path and syntax simulation. `python tools/smoke_hook.py` installs the hooks into a throwaway home and runs the written hook command through your real OS shell.
86
86
 
87
87
  Adding a rule: see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md). The rule list is in [docs/FOOTGUNS.md](docs/FOOTGUNS.md).
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "kneepad"
7
- version = "0.3.0"
7
+ version = "0.3.1"
8
8
  description = "Local safety layer for AI coding agents on Linux, macOS and Windows: blocks or snapshots destructive commands, with a footgun database and a tamper-evident audit log."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -1,3 +1,3 @@
1
1
  """Kneepad: a kneepad for AI coding agents."""
2
2
 
3
- __version__ = "0.3.0"
3
+ __version__ = "0.3.1"
@@ -59,4 +59,7 @@ def guard(func: Optional[Callable] = None, *, arg: str = "command", allow_ask: b
59
59
 
60
60
  return inner
61
61
 
62
+ if func is not None and not callable(func):
63
+ raise TypeError("guard decorates a function: use @guard or @guard(allow_ask=True), not guard('command'). "
64
+ "To check a command string use check_command().")
62
65
  return wrap(func) if func is not None else wrap
@@ -40,6 +40,8 @@ _WRAPPERS: Dict[str, Tuple[Set[str], int]] = {
40
40
  "npx": ({"-p", "--package", "-c", "--call"}, 0),
41
41
  "pnpx": (set(), 0),
42
42
  "bunx": (set(), 0),
43
+ "busybox": (set(), 0),
44
+ "toybox": (set(), 0),
43
45
  }
44
46
 
45
47
  # Options that consume the next token, per command. Keeps values out of positionals.
@@ -32,6 +32,7 @@ from .util import ensure_private_dir, now_iso, kneepad_home
32
32
  GENESIS = "0" * 64
33
33
  _BIN = getattr(os, "O_BINARY", 0) # Windows translates newlines unless the descriptor is binary
34
34
  VERSION = 1
35
+ _COPY_ROTATION = os.name == "nt" # Windows cannot rename a file that is open; see AuditLog._set_aside
35
36
 
36
37
  try: # POSIX
37
38
  import fcntl
@@ -41,6 +42,9 @@ try: # POSIX
41
42
 
42
43
  def _unlock(fd: int) -> None:
43
44
  fcntl.flock(fd, fcntl.LOCK_UN)
45
+
46
+ def _lock_shared(fd: int) -> None:
47
+ fcntl.flock(fd, fcntl.LOCK_SH)
44
48
  except ImportError: # Windows
45
49
  import msvcrt
46
50
 
@@ -60,6 +64,8 @@ except ImportError: # Windows
60
64
  os.lseek(fd, 0, os.SEEK_SET)
61
65
  msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
62
66
 
67
+ _lock_shared = _lock # Windows has no shared byte-range lock here; an exclusive one is brief
68
+
63
69
 
64
70
  def canonical(obj: Dict[str, Any]) -> str:
65
71
  return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
@@ -84,6 +90,10 @@ class _Rotated(Exception):
84
90
  pass
85
91
 
86
92
 
93
+ class _Stale(Exception):
94
+ """The file we locked is no longer the live log (another writer rotated it while we waited)."""
95
+
96
+
87
97
  class AuditLog:
88
98
  def __init__(self, home: Optional[str] = None) -> None:
89
99
  self.home = home or kneepad_home()
@@ -138,26 +148,78 @@ class AuditLog:
138
148
  while pos > 0:
139
149
  read = min(chunk, pos)
140
150
  pos -= read
141
- data = os.pread(fd, read, pos) + data
151
+ os.lseek(fd, pos, os.SEEK_SET) # portable: os.pread does not exist on Windows
152
+ data = os.read(fd, read) + data
142
153
  body = data.rstrip(b"\n")
143
154
  if b"\n" in body or pos == 0:
144
155
  break
145
156
  body = data.rstrip(b"\n")
146
157
  return body.rsplit(b"\n", 1)[-1] if body else None
147
158
 
148
- def append(self, event: str, data: Dict[str, Any]) -> Dict[str, Any]:
159
+ def append_if_empty(self, event: str, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
160
+ """Append only when the log has no entries yet, atomically (parallel `init` calls write one init event)."""
161
+ return self.append(event, data, only_if_empty=True)
162
+
163
+ def append(self, event: str, data: Dict[str, Any], only_if_empty: bool = False) -> Optional[Dict[str, Any]]:
164
+ note = False
165
+ for _attempt in range(50):
166
+ try:
167
+ return self._append(event, {**data, "note": "previous log was corrupt and was set aside"} if note else data,
168
+ only_if_empty)
169
+ except _Rotated:
170
+ note = True
171
+ except _Stale:
172
+ continue
173
+ raise OSError("audit log kept changing underneath this writer; giving up")
174
+
175
+ def _is_live(self, fd: int) -> bool:
176
+ """True when ``fd`` still refers to the file currently at self.path (not one a peer rotated away)."""
149
177
  try:
150
- return self._append(event, data)
151
- except _Rotated:
152
- return self._append(event, {**data, "note": "previous log was corrupt and was set aside"})
178
+ a, b = os.stat(self.path), os.fstat(fd)
179
+ except OSError:
180
+ return False
181
+ if not a.st_ino or not b.st_ino: # some Windows filesystems report no inode: assume live
182
+ return True
183
+ return (a.st_ino, a.st_dev) == (b.st_ino, b.st_dev)
184
+
185
+ def _set_aside(self, fd: int, dest: str) -> None:
186
+ """Move the corrupt log out of the way while this writer still holds it open and locked.
187
+
188
+ POSIX renames the file. Windows refuses to rename a file that any handle has open (WinError 32), including ours, so
189
+ there the evidence is copied to ``dest`` and the live file is emptied in place; peers waiting on the lock then see
190
+ an empty log and start a fresh chain, exactly as they do after a rename."""
191
+ if not _COPY_ROTATION:
192
+ os.replace(self.path, dest)
193
+ return
194
+ size = os.fstat(fd).st_size
195
+ out = os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _BIN, 0o600)
196
+ try:
197
+ os.lseek(fd, 0, os.SEEK_SET)
198
+ left = size
199
+ while left > 0:
200
+ chunk = os.read(fd, min(left, 1 << 20))
201
+ if not chunk:
202
+ break
203
+ view = memoryview(chunk)
204
+ while view:
205
+ view = view[os.write(out, view):]
206
+ left -= len(chunk)
207
+ os.fsync(out)
208
+ finally:
209
+ os.close(out)
210
+ os.ftruncate(fd, 0)
153
211
 
154
- def _append(self, event: str, data: Dict[str, Any]) -> Dict[str, Any]:
212
+ def _append(self, event: str, data: Dict[str, Any], only_if_empty: bool = False) -> Optional[Dict[str, Any]]:
155
213
  key = self.ensure_key()
156
214
  fd = os.open(self.path, os.O_RDWR | os.O_CREAT | os.O_APPEND | _BIN, 0o600)
157
215
  try:
158
216
  _lock(fd)
159
217
  try:
218
+ if not self._is_live(fd):
219
+ raise _Stale()
160
220
  last_raw = self._last_line(fd)
221
+ if only_if_empty and last_raw is not None:
222
+ return None
161
223
  last: Optional[Dict[str, Any]] = None
162
224
  if last_raw is not None:
163
225
  try:
@@ -173,7 +235,7 @@ class AuditLog:
173
235
  while os.path.exists(dest):
174
236
  n += 1
175
237
  dest = f"{self.path}.corrupt-{int(time.time())}-{n}"
176
- os.replace(self.path, dest)
238
+ self._set_aside(fd, dest)
177
239
  raise _Rotated()
178
240
  seq = (last["seq"] + 1) if last else 1
179
241
  prev = last["hash"] if last else GENESIS
@@ -210,7 +272,7 @@ class AuditLog:
210
272
  return out
211
273
 
212
274
  def tail(self, n: int = 20) -> List[Dict[str, Any]]:
213
- return self.read_all()[-n:]
275
+ return self.read_all()[-n:] if n > 0 else []
214
276
 
215
277
  def verify(self, anchor: Optional[str] = None) -> VerifyResult:
216
278
  res = VerifyResult(ok=True)
@@ -234,6 +296,12 @@ class AuditLog:
234
296
  return VerifyResult(ok=False, error="no audit log exists but an anchor was supplied")
235
297
  return res
236
298
  with fh:
299
+ try:
300
+ # Wait for any append in progress, so a half-written last line is never mistaken for tampering.
301
+ # Closing the file at the end of this block releases the lock.
302
+ _lock_shared(fh.fileno())
303
+ except (OSError, ValueError):
304
+ pass
237
305
  for lineno, raw in enumerate(fh, 1):
238
306
  raw = raw.rstrip(b"\n")
239
307
  if not raw:
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import argparse
6
6
  import json
7
7
  import os
8
+ import re
8
9
  import shlex
9
10
  import shutil
10
11
  import stat
@@ -24,7 +25,7 @@ from .integrations import TARGETS, install_target, uninstall_target
24
25
  from .installer import InstallError, hook_command, install, is_installed, settings_path, uninstall
25
26
  from .rules import load_default_rules, load_rules_text
26
27
  from .snapshots import SnapshotError, SnapshotStore
27
- from .util import kneepad_home
28
+ from .util import kneepad_home, redact
28
29
 
29
30
  EXIT_ALLOW, EXIT_ASK, EXIT_DENY = 0, 10, 20
30
31
 
@@ -86,8 +87,7 @@ def cmd_init(args) -> int:
86
87
  home = kneepad_home()
87
88
  log = AuditLog(home)
88
89
  log.ensure_key()
89
- if not log.read_all():
90
- log.append("init", {"version": __version__})
90
+ log.append_if_empty("init", {"version": __version__})
91
91
  print(f"Kneepad state directory: {home}")
92
92
  targets = list(getattr(args, "target", None) or [])
93
93
  if "all" in targets:
@@ -139,6 +139,9 @@ def cmd_uninstall(args) -> int:
139
139
 
140
140
 
141
141
  def cmd_log(args) -> int:
142
+ if args.n < 0:
143
+ print("kneepad log: -n must be 0 or greater", file=sys.stderr)
144
+ return 2
142
145
  entries = AuditLog().tail(args.n)
143
146
  if args.json:
144
147
  print(json.dumps(entries, indent=2))
@@ -184,7 +187,7 @@ def cmd_rules(args) -> int:
184
187
  except (OSError, ValueError) as exc:
185
188
  print(f"INVALID: {exc}")
186
189
  return 1
187
- print(f"OK: {len(rules)} rules")
190
+ print(f"OK: {len(rules)} rules (structure and regexes only; the test suite runs each rule's examples)")
188
191
  return 0
189
192
  rules = load_default_rules()
190
193
  if args.rules_cmd == "list":
@@ -312,8 +315,12 @@ def cmd_badge(args) -> int:
312
315
  "does not verify. Run `kneepad doctor`. (Use --force to override.)", file=sys.stderr)
313
316
  return 1
314
317
  out = args.out
315
- with open(out, "w", encoding="utf-8") as fh:
316
- fh.write(make_badge())
318
+ try:
319
+ with open(out, "w", encoding="utf-8") as fh:
320
+ fh.write(make_badge())
321
+ except OSError as exc:
322
+ print(f"kneepad badge: cannot write {out}: {exc}", file=sys.stderr)
323
+ return 1
317
324
  print(f"wrote {out}")
318
325
  print(f"Markdown: ![Protected by Kneepad](./{os.path.basename(out)})")
319
326
  return 0
@@ -328,6 +335,74 @@ def _default_real_shell() -> str:
328
335
  return "/bin/sh"
329
336
 
330
337
 
338
+ def _shell_command_arg(argv: List[str]) -> Optional[str]:
339
+ """Return the command string of a `sh -c STRING` style invocation, or None when there is none.
340
+
341
+ Handles clustered short options (-ec, -xc, -lc, -euc), separate options before -c (-l -c, -o pipefail -c),
342
+ and long options (--norc). Stops at the first non-option word, which a shell treats as a script path.
343
+ """
344
+ i = 0
345
+ while i < len(argv):
346
+ a = argv[i]
347
+ if a == "--":
348
+ return None
349
+ if a in ("-o", "+o", "-O", "+O", "--rcfile", "--init-file"):
350
+ i += 2
351
+ continue
352
+ if a.startswith("--"):
353
+ i += 1
354
+ continue
355
+ if re.fullmatch(r"[-+][A-Za-z]+", a):
356
+ if a[0] == "-" and "c" in a:
357
+ return argv[i + 1] if i + 1 < len(argv) else None
358
+ i += 1
359
+ continue
360
+ return None
361
+ return None
362
+
363
+
364
+ def _vet_command(text: str, tool: str, interactive_ask: bool) -> int:
365
+ """Shared by `run` and `shell`: analyse, snapshot, log, and return 0 to proceed or 126 to refuse.
366
+
367
+ Every outcome is written to the audit log, including refusals. A failure to write the log is reported on
368
+ stderr instead of being swallowed.
369
+ """
370
+ cfg = load_config(os.getcwd())
371
+ d = Analyzer(config=cfg, cwd=os.getcwd()).analyze_shell(text)
372
+ refused = False
373
+ if d.action in ("deny", "ask") and cfg.mode != "monitor":
374
+ print(d.reason(), file=sys.stderr)
375
+ if d.action == "deny":
376
+ refused = True
377
+ elif interactive_ask and sys.stdin.isatty():
378
+ refused = input("Run it anyway? [y/N] ").strip().lower() != "y"
379
+ else:
380
+ print("Not a terminal, so Kneepad cannot ask. Refusing." if interactive_ask else "Kneepad blocked this command.",
381
+ file=sys.stderr)
382
+ refused = True
383
+ snaps: List[str] = []
384
+ if not refused and d.plans:
385
+ try:
386
+ store = SnapshotStore()
387
+ for p in d.plans:
388
+ sid = store.create(p)["id"]
389
+ snaps.append(sid)
390
+ print(f"kneepad: snapshot {sid}", file=sys.stderr)
391
+ except SnapshotError as exc:
392
+ print(f"kneepad: snapshot failed ({exc}); refusing to run.", file=sys.stderr)
393
+ refused = True
394
+ try:
395
+ AuditLog().append("decision", {
396
+ "tool": tool, "action": d.action, "mode": cfg.mode, "refused": refused, "cwd": os.getcwd(),
397
+ "command": redact(text, 2000), "snapshots": snaps,
398
+ "findings": [{"rule": f.rule_id, "severity": f.severity, "action": f.action, "detail": redact(f.detail, 300)}
399
+ for f in d.findings]})
400
+ except Exception as exc:
401
+ print(f"kneepad: warning: could not write the audit log ({type(exc).__name__}: {exc}). "
402
+ "Continuing, but this decision is not recorded.", file=sys.stderr)
403
+ return 126 if refused else 0
404
+
405
+
331
406
  def cmd_shell(args) -> int:
332
407
  """Drop-in for $SHELL: `kneepad shell -c "cmd"` checks the command, then runs it with the real shell.
333
408
 
@@ -337,13 +412,9 @@ def cmd_shell(args) -> int:
337
412
  argv = list(args.argv)
338
413
  if argv and argv[0] == "--":
339
414
  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
415
+ cmd_text = _shell_command_arg(argv)
416
+ if cmd_text is not None and _vet_command(cmd_text, "shell", interactive_ask=False) != 0:
417
+ return 126
347
418
  if sys.platform == "win32": # os.execv on Windows detaches and loses the exit code
348
419
  try:
349
420
  return subprocess.call([real] + argv)
@@ -356,39 +427,28 @@ def cmd_shell(args) -> int:
356
427
 
357
428
  def cmd_run(args) -> int:
358
429
  argv = args.argv
430
+ if argv and argv[0] in ("-h", "--help"):
431
+ print("usage: kneepad run [--] COMMAND [ARGS...]\n\nAnalyse COMMAND with Kneepad and run it only if it is allowed.\n"
432
+ "Exit codes: the command's own exit code; 126 when Kneepad refuses; 127 when the program is not found.")
433
+ return 0
359
434
  if argv and argv[0] == "--":
360
435
  argv = argv[1:]
361
436
  if not argv:
362
- print("usage: kneepad run -- COMMAND [ARGS...]", file=sys.stderr)
437
+ print("usage: kneepad run [--] COMMAND [ARGS...]", file=sys.stderr)
363
438
  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
439
+ # POSIX quoting on every platform: the analyser parses shell syntax, and list2cmdline leaves backslash paths unquoted, which
440
+ # the parser reads as escapes (C:\Users\me\proj became a harmless-looking relative name and `rm -rf` of it was allowed).
441
+ text = shlex.join(argv)
442
+ if _vet_command(text, "run", interactive_ask=True) != 0:
443
+ return 126
386
444
  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)
445
+ return subprocess.call(argv)
446
+ except FileNotFoundError:
447
+ print(f"kneepad run: command not found: {argv[0]}", file=sys.stderr)
448
+ return 127
449
+ except OSError as exc:
450
+ print(f"kneepad run: cannot execute {argv[0]}: {exc}", file=sys.stderr)
451
+ return 126
392
452
 
393
453
 
394
454
  def build_parser() -> argparse.ArgumentParser:
@@ -397,15 +457,15 @@ def build_parser() -> argparse.ArgumentParser:
397
457
  sub = p.add_subparsers(dest="cmd", required=True)
398
458
 
399
459
  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")
460
+ s.add_argument("--claude-code", action="store_true", help="install the Claude Code PreToolUse hook")
401
461
  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")
462
+ s.add_argument("--scope", choices=["user", "project"], default="user", help="user: your home directory (default); project: this repository only")
403
463
  s.set_defaults(func=cmd_init)
404
464
 
405
465
  s = sub.add_parser("uninstall", help="remove the Claude Code hook (or --target another agent)")
406
466
  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")
467
+ s.add_argument("--target", action="append", choices=list(TARGETS) + ["all"], help="agent to remove the hook from (repeatable)")
468
+ s.add_argument("--scope", choices=["user", "project"], default="user", help="user: your home directory (default); project: this repository only")
409
469
  s.set_defaults(func=cmd_uninstall)
410
470
 
411
471
  s = sub.add_parser("hook", help="run as a hook (reads JSON on stdin)")
@@ -419,7 +479,7 @@ def build_parser() -> argparse.ArgumentParser:
419
479
  s.add_argument("--json", action="store_true")
420
480
  s.set_defaults(func=cmd_check)
421
481
 
422
- s = sub.add_parser("shell", help="shell wrapper for agents that run commands through $SHELL -c")
482
+ s = sub.add_parser("shell", help="shell wrapper for agents that run commands through $SHELL -c (all arguments go to the real shell, so --help shows the shell's help)")
423
483
  s.add_argument("argv", nargs=argparse.REMAINDER)
424
484
  s.set_defaults(func=cmd_shell)
425
485
 
@@ -479,7 +539,32 @@ def shell_main() -> int:
479
539
  return main(["shell"] + sys.argv[1:])
480
540
 
481
541
 
542
+ def _flush_std(rc: int) -> int:
543
+ """Flush stdout and stderr inside main() so a reader that went away (`kneepad rules list | head -1`) is handled here.
544
+
545
+ A broken pipe caught earlier still leaves the final partial buffer pending; the interpreter would then fail to flush it
546
+ at exit and print "Exception ignored ... BrokenPipeError" with exit status 120. Pointing the descriptor at /dev/null
547
+ (the recipe from the Python documentation) makes that exit-time flush harmless."""
548
+ for stream in (sys.stdout, sys.stderr):
549
+ if stream is None:
550
+ continue
551
+ try:
552
+ stream.flush()
553
+ except BrokenPipeError:
554
+ try:
555
+ os.dup2(os.open(os.devnull, os.O_WRONLY), stream.fileno())
556
+ except (OSError, ValueError, AttributeError):
557
+ pass
558
+ except (OSError, ValueError):
559
+ pass
560
+ return rc
561
+
562
+
482
563
  def main(argv: Optional[List[str]] = None) -> int:
564
+ return _flush_std(_main(argv))
565
+
566
+
567
+ def _main(argv: Optional[List[str]] = None) -> int:
483
568
  raw = list(sys.argv[1:] if argv is None else argv)
484
569
  # `shell` and `run` forward arbitrary arguments (including -c and other dash options) to another
485
570
  # program, which argparse cannot express with REMAINDER when the first token starts with a dash.
@@ -496,3 +581,6 @@ def main(argv: Optional[List[str]] = None) -> int:
496
581
  return 130
497
582
  except BrokenPipeError:
498
583
  return 0
584
+ except OSError as exc:
585
+ print(f"kneepad: error: {exc}", file=sys.stderr)
586
+ return 1