@alexgreensh/token-optimizer 5.13.66 → 5.13.68

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 (43) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/hooks.json +0 -10
  4. package/package.json +1 -1
  5. package/skills/token-optimizer/examples/hooks-starter.json +0 -10
  6. package/skills/token-optimizer/scripts/_measure/_compat.py +2 -2
  7. package/skills/token-optimizer/scripts/_measure/_vendor/README.md +15 -0
  8. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +63 -0
  9. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/LICENSE +21 -0
  10. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +39 -0
  11. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/py.typed +1 -0
  12. package/skills/token-optimizer/scripts/_measure/audit.py +5 -21
  13. package/skills/token-optimizer/scripts/_measure/cache_policy.py +54 -1
  14. package/skills/token-optimizer/scripts/_measure/daemon.py +21 -51
  15. package/skills/token-optimizer/scripts/_measure/lifecycle.py +81 -327
  16. package/skills/token-optimizer/scripts/_tomli.py +916 -0
  17. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +11 -3
  18. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  19. package/skills/token-optimizer/scripts/bash_compress.py +3 -3
  20. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -7
  21. package/skills/token-optimizer/scripts/cloud_kit.py +21 -21
  22. package/skills/token-optimizer/scripts/codex_compact_prompt.py +2 -2
  23. package/skills/token-optimizer/scripts/codex_doctor.py +33 -7
  24. package/skills/token-optimizer/scripts/codex_hook_provenance.py +268 -0
  25. package/skills/token-optimizer/scripts/codex_install.py +33 -69
  26. package/skills/token-optimizer/scripts/command_filters.py +359 -18
  27. package/skills/token-optimizer/scripts/copilot_install.py +5 -0
  28. package/skills/token-optimizer/scripts/cursor_install.py +5 -0
  29. package/skills/token-optimizer/scripts/devin_install.py +6 -12
  30. package/skills/token-optimizer/scripts/devin_source.py +6 -5
  31. package/skills/token-optimizer/scripts/devin_verify.py +16 -0
  32. package/skills/token-optimizer/scripts/grok_install.py +5 -0
  33. package/skills/token-optimizer/scripts/heal_report.py +92 -0
  34. package/skills/token-optimizer/scripts/hook_heal.py +138 -0
  35. package/skills/token-optimizer/scripts/hook_provenance.py +878 -0
  36. package/skills/token-optimizer/scripts/measure.py +2 -2
  37. package/skills/token-optimizer/scripts/owned_hooks.py +420 -0
  38. package/skills/token-optimizer/scripts/read_cache.py +20 -21
  39. package/skills/token-optimizer/scripts/reset_epoch.py +177 -0
  40. package/skills/token-optimizer/scripts/session_store.py +11 -48
  41. package/skills/token-optimizer/scripts/shipped_codex_hook_templates.json +5815 -0
  42. package/skills/token-optimizer/scripts/shipped_hook_templates.py +252 -0
  43. package/skills/token-optimizer/scripts/shipped_starter_hooks.py +55 -0
@@ -3,7 +3,7 @@
3
3
 
4
4
  Lets a user opt NEW read-only commands into existing compression handlers
5
5
  and exclude commands from compression, without weakening safety. The loader
6
- is pure stdlib (tomllib with a no-tomllib fallback), performs no file writes,
6
+ is pure stdlib (tomllib, or the vendored _tomli parser on Python 3.9/3.10), performs no file writes,
7
7
  and gates every ``add`` entry through ``_is_safe_add`` before it reaches the
8
8
  effective allowlist.
9
9
 
@@ -37,7 +37,10 @@ Rules:
37
37
  from __future__ import annotations
38
38
 
39
39
  import fnmatch
40
+ import functools
40
41
  import os
42
+ import stat
43
+ import re
41
44
  import sys
42
45
  from dataclasses import dataclass, field
43
46
  from pathlib import Path
@@ -48,6 +51,29 @@ try:
48
51
  except ImportError:
49
52
  tomllib = None # type: ignore[assignment]
50
53
 
54
+ # ---------------------------------------------------------------------------
55
+ # TOML parser fallback (Python 3.9 and 3.10 have no tomllib)
56
+ # ---------------------------------------------------------------------------
57
+ # The vendored flat Tomli parser ships as the _tomli payload module so the
58
+ # Devin closed set can serve it without importing _measure. It is imported
59
+ # lazily on first use so hooks that never read a filters file pay nothing.
60
+
61
+ _MISSING = object()
62
+ _tomli_module = _MISSING
63
+
64
+
65
+ def _load_tomli_fallback():
66
+ """Return the vendored Tomli module, importing it once. None if absent."""
67
+ global _tomli_module
68
+ if _tomli_module is _MISSING:
69
+ try:
70
+ import _tomli as module
71
+ except ImportError:
72
+ module = None
73
+ _tomli_module = module
74
+ return _tomli_module
75
+
76
+
51
77
  # ---------------------------------------------------------------------------
52
78
  # Constants
53
79
  # ---------------------------------------------------------------------------
@@ -71,6 +97,7 @@ _UNSAFE_INTERPRETERS = frozenset({
71
97
  "bash", "sh", "zsh", "dash", "ksh", "fish", "csh", "tcsh",
72
98
  "python", "python3", "python2", "ruby", "perl", "node", "deno", "bun",
73
99
  "lua", "tcl", "awk", "sed", "eval", "exec", "source", ".",
100
+ "osascript", "php", "gawk", "mawk", "nawk", "rscript",
74
101
  })
75
102
  _UNSAFE_PREFIXES = frozenset({"sudo", "su", "doas", "pkexec", "gksudo"})
76
103
  _UNSAFE_WRITE_SUBCMDS = frozenset({
@@ -80,6 +107,75 @@ _UNSAFE_WRITE_SUBCMDS = frozenset({
80
107
  })
81
108
  _DANGEROUS_CHARS = frozenset(";|&`$(){}><\n\r\x00")
82
109
 
110
+ # git subcommands that write. Superset of bash_whitelist._GIT_WRITE_SUBCMDS
111
+ # (a test pins the superset relation; importing it here would create a
112
+ # circular dependency on the hot path). Bounded, not a full git grammar:
113
+ # ambiguous subcommands that can write with the right flag (``branch -D``,
114
+ # ``config``, ``reflog delete``) are treated as writes outright.
115
+ _GIT_WRITE_SUBCMDS = frozenset({
116
+ "commit", "push", "pull", "merge", "rebase", "reset", "checkout",
117
+ "switch", "stash", "tag", "cherry-pick", "revert", "am", "apply",
118
+ "add", "rm", "mv", "restore", "bisect", "clean", "fetch", "clone",
119
+ "init", "remote", "submodule", "worktree",
120
+ "branch", "config", "gc", "prune", "reflog", "notes", "replace",
121
+ "filter-branch", "update-ref", "symbolic-ref", "repack", "write-tree",
122
+ "commit-tree", "update-index", "read-tree", "hash-object",
123
+ })
124
+ # git subcommands treated as read-only. Anything outside
125
+ # _GIT_WRITE_SUBCMDS | _GIT_READONLY_SUBCMDS (aliases, plumbing, new
126
+ # subcommands) is refused, matching the compress hook's own stance that an
127
+ # unknown git invocation is not provably read-only.
128
+ _GIT_READONLY_SUBCMDS = frozenset({
129
+ "status", "log", "diff", "show", "ls-files", "ls-tree", "blame",
130
+ "annotate", "grep", "rev-parse", "rev-list", "describe", "shortlog",
131
+ "show-ref", "cat-file", "count-objects", "var", "version", "whatchanged",
132
+ })
133
+ # find flags that delete, write or run another program.
134
+ _FIND_DESTRUCTIVE_FLAGS = frozenset({
135
+ "-delete", "-exec", "-execdir", "-ok", "-okdir",
136
+ "-fprint", "-fprint0", "-fls", "-fprintf",
137
+ })
138
+ _GLOB_CHARS = frozenset("*?[")
139
+ # Runner / wrapper commands: they exec another command (``timeout 5 rm -rf x``,
140
+ # ``nice rm x``, ``xargs rm``), so the real command is not argv[0]. Refused
141
+ # outright (fail closed) rather than unwrapped, since each has its own option
142
+ # grammar. Windows shells are interpreters too.
143
+ _LAUNCHERS = frozenset({
144
+ "timeout", "nice", "ionice", "nohup", "stdbuf", "time", "chrt", "taskset",
145
+ "watch", "xargs", "parallel", "command", "exec", "builtin", "setsid",
146
+ "unbuffer", "strace", "ltrace", "nsenter", "chroot", "flock", "busybox",
147
+ "script", "runuser", "systemd-run", "at", "batch", "ssh", "wsl", "cmd",
148
+ "powershell", "pwsh", "start", "sh.exe",
149
+ })
150
+ # Minimum set of known writers that are not in _UNSAFE_WRITE_SUBCMDS. This is
151
+ # a bounded denylist, not a claim that every other command is read-only.
152
+ _KNOWN_WRITERS = frozenset({
153
+ "tee", "truncate", "shred", "touch", "unlink", "install", "rsync", "patch",
154
+ "sponge", "scp", "rename", "del", "erase", "rd", "move", "copy", "ren",
155
+ })
156
+ _NEVER_COMPRESS_CMD0 = (
157
+ _UNSAFE_INTERPRETERS | _UNSAFE_PREFIXES | _UNSAFE_WRITE_SUBCMDS
158
+ | _LAUNCHERS | _KNOWN_WRITERS
159
+ )
160
+ # Interpreters named by version (python3.12.1, python3.13t, python3.12m,
161
+ # pypy3.10-v7.3) and the Windows ``py`` launcher; fullmatch on the normalized
162
+ # word, so python3-config, pyright, pytest and pyenv do not match.
163
+ _VERSIONED_INTERPRETER_RE = re.compile(
164
+ r"python\d+(?:\.\d+)*[a-z]*|pypy\d*(?:\.\d+)*(?:[-.][a-z0-9.]+)?|py")
165
+ _EXE_SUFFIXES = (".exe", ".com", ".bat", ".cmd")
166
+ # fnmatch candidates: bare names plus their Windows executable spellings, so
167
+ # ``rm.*`` / ``r*.exe`` are caught as well as ``r*``. Versioned interpreter
168
+ # spellings carry ABI suffixes (t, m, d) so ``python3.13?`` is caught too.
169
+ # Built on first use: only the add-entry gate needs it, not per-command matching.
170
+ @functools.lru_cache(maxsize=1)
171
+ def _glob_names() -> frozenset:
172
+ return frozenset(
173
+ n + ext for n in _NEVER_COMPRESS_CMD0 | {"py", "pypy", "pypy2", "pypy3"}
174
+ | {f"{p}{m}.{n}{abi}" for p in ("python", "pypy") for m in (2, 3)
175
+ for n in range(20) for abi in ("", "t", "m", "d", "td")}
176
+ for ext in ("",) + _EXE_SUFFIXES
177
+ )
178
+
83
179
  _warned_paths: set = set()
84
180
 
85
181
 
@@ -110,7 +206,10 @@ class CommandFilterConfig:
110
206
 
111
207
  def find_add(self, command_str: str) -> Optional[AddEntry]:
112
208
  """Return the first add entry whose command matches ``command_str``,
113
- or None."""
209
+ or None. Never matches a destructive command."""
210
+ # No entries means no match; skip the tokenizing check on the hot path.
211
+ if not self.adds or is_destructive_command(command_str):
212
+ return None
114
213
  for entry in self.adds:
115
214
  if entry.command == command_str:
116
215
  return entry
@@ -134,6 +233,11 @@ class EffectiveFilters:
134
233
  return False
135
234
 
136
235
  def find_user_add(self, command_str: str) -> Optional[AddEntry]:
236
+ # A glob in an add entry must never make a destructive command
237
+ # eligible for compression (the wrapper would run it). No entries means
238
+ # no match, so the tokenizing check is skipped on the hot path.
239
+ if not self.user_adds or is_destructive_command(command_str):
240
+ return None
137
241
  for entry in self.user_adds:
138
242
  if entry.command == command_str:
139
243
  return entry
@@ -153,20 +257,28 @@ def _is_all_wildcard(token: str) -> bool:
153
257
  return bool(token) and set(token) <= {"*"}
154
258
 
155
259
 
156
- def _effective_cmd0(tokens: List[str]) -> Optional[str]:
157
- """Return the basename of the REAL command being run.
260
+ def _effective_cmd_token(tokens: List[str]) -> Optional[str]:
261
+ """Return the token of the REAL command being run.
158
262
 
159
263
  Normalizes away the path (so ``/bin/bash``, ``./python``, ``/usr/bin/sudo``
160
264
  are recognized as ``bash``/``python``/``sudo``) and resolves a leading
161
265
  ``env`` invocation by skipping ``VAR=val`` assignments and env's own options
162
- (``-i``, and the operand-taking ``-u``/``-C``/``-S``) to reach the command
163
- env would exec. Returns None when no command token remains.
266
+ (``-i``, and the operand-taking ``-u``/``-C``/``--chdir``) to reach the
267
+ command env would exec, looping through nested ``env``. ``-S`` /
268
+ ``--split-string`` and any unrecognized ``-`` option fail closed (None).
269
+ Returns None when no command token remains.
164
270
  """
165
271
  if not tokens:
166
272
  return None
167
273
  i = 0
168
- if os.path.basename(tokens[0]) == "env":
169
- i = 1
274
+ # ``env`` may be nested (``env env rm x``) and may carry assignments and
275
+ # options before the real command, so unwrap repeatedly. Any option token
276
+ # this parser does not model exactly -- ``--opt=val``, joined
277
+ # ``-uVAL``/``-CVAL``/``-SVAL``, or ``-S``/``--split-string`` whose operand
278
+ # is itself a command string -- fails closed by returning None rather
279
+ # than guessing which later token is the command.
280
+ while i < len(tokens) and _norm_cmd(tokens[i]) == "env":
281
+ i += 1
170
282
  while i < len(tokens):
171
283
  tok = tokens[i]
172
284
  if "=" in tok and not tok.startswith("-"):
@@ -175,13 +287,203 @@ def _effective_cmd0(tokens: List[str]) -> Optional[str]:
175
287
  if tok in ("-i", "--ignore-environment", "-", "-v", "--debug"):
176
288
  i += 1
177
289
  continue
178
- if tok in ("-u", "--unset", "-C", "--chdir", "-S", "--split-string"):
179
- i += 2 # option consumes its operand
290
+ if tok in ("-u", "--unset", "-C", "--chdir"):
291
+ i += 2 # option consumes its operand (``--`` included: it is
292
+ # a legal operand, e.g. ``env -u -- rm`` unsets ``--``)
180
293
  continue
294
+ if tok == "--":
295
+ i += 1
296
+ break # env end-of-options: the next token is the command
297
+ if tok.startswith("-"):
298
+ return None
181
299
  break # first non-option, non-assignment token = the command
182
300
  if i >= len(tokens):
183
301
  return None
184
- return os.path.basename(tokens[i])
302
+ return tokens[i]
303
+
304
+
305
+ def _effective_cmd0(tokens: List[str]) -> Optional[str]:
306
+ tok = _effective_cmd_token(tokens)
307
+ return None if tok is None else _norm_cmd(tok)
308
+
309
+
310
+ def _raw_cmd_word(tokens: List[str]) -> str:
311
+ """Lower-cased basename of the command word, backslash paths included,
312
+ WITHOUT stripping an executable suffix (so ``rm.*`` stays a glob)."""
313
+ cmd = _effective_cmd_token(tokens)
314
+ return os.path.basename(cmd.replace("\\", "/")).lower() if cmd else ""
315
+
316
+
317
+ def _norm_cmd(token: str) -> str:
318
+ """Basename, lower-cased, without a Windows executable suffix, so
319
+ ``RM``, ``/bin/rm`` and ``rm.exe`` all compare as ``rm``."""
320
+ name = os.path.basename(token.replace("\\", "/")).lower()
321
+ for ext in (".exe", ".com", ".bat", ".cmd"):
322
+ if name.endswith(ext):
323
+ return name[: -len(ext)]
324
+ return name
325
+
326
+
327
+ def _git_subcommand_tokens(tokens: List[str]) -> List[str]:
328
+ """Return the tokens after ``git``'s global options, starting at the
329
+ subcommand word (skips ``-C <dir>``, ``-c k=v``, ``--git-dir <d>``...)."""
330
+ idx = next((i for i, t in enumerate(tokens) if _norm_cmd(t) == "git"), None)
331
+ if idx is None:
332
+ return []
333
+ rest = tokens[idx + 1:]
334
+ j = 0
335
+ while j < len(rest) and rest[j].startswith("-"):
336
+ j += 2 if rest[j] in ("-C", "-c", "--git-dir", "--work-tree", "--namespace") else 1
337
+ return rest[j:]
338
+
339
+
340
+ def _git_writes_output(sub: List[str]) -> bool:
341
+ """``git diff/log/show --output[=]FILE`` writes FILE: treat it as a write."""
342
+ return any(t == "--output" or t.startswith("--output=") for t in sub[1:])
343
+
344
+
345
+ def _git_has_config_options(tokens: List[str]) -> bool:
346
+ """True when git global options other than ``-C <dir>`` / ``--no-pager``
347
+ / ``--no-optional-locks`` precede the subcommand. ``-c alias.x=!cmd``,
348
+ ``--config-env``, ``--exec-path`` and friends can run arbitrary programs."""
349
+ idx = next((i for i, t in enumerate(tokens) if _norm_cmd(t) == "git"), None)
350
+ if idx is None:
351
+ return False
352
+ rest = tokens[idx + 1:]
353
+ j = 0
354
+ while j < len(rest) and rest[j].startswith("-"):
355
+ if rest[j] == "-C":
356
+ j += 2
357
+ elif rest[j] in ("--no-pager", "--no-optional-locks"):
358
+ j += 1
359
+ else:
360
+ return True
361
+ return False
362
+
363
+
364
+ def is_destructive_command(command_str: str) -> bool:
365
+ """True when ``command_str`` runs something that writes, deletes or
366
+ launches another program (rm, mv, sudo, an interpreter, a git write
367
+ subcommand, find -delete/-exec, ...).
368
+
369
+ Used at match time so a glob in a user ``add`` entry can never make such
370
+ a command eligible for compression, whatever the glob expands to.
371
+ Fails closed: an unparseable command counts as destructive, and unknown
372
+ git subcommands (possible aliases) count as writes.
373
+
374
+ Bounded by design: this module ships inside the Devin payload closed
375
+ set, so it cannot depend on the hook's read-only classifier
376
+ (pipeline_analyzer); the closed-set policy test forbids that import.
377
+ The checks are self-contained denylists, not a full shell parser;
378
+ commands they do not recognize stay eligible for user ``add`` entries,
379
+ as before.
380
+ """
381
+ # Multi-line input hides extra commands (``mytool --flag\nrm -rf x``)
382
+ # and command/process substitution executes whatever it nests
383
+ # (``echo $(rm -rf x)``, ``cat <(rm -rf x)``): refuse on the raw string.
384
+ if any(c in command_str for c in ("\n", "\r")):
385
+ return True
386
+ if "$(" in command_str or "`" in command_str or "<(" in command_str:
387
+ return True
388
+ import shlex
389
+ try:
390
+ # punctuation_chars splits glued shell operators (``cat;rm -rf x``)
391
+ # into real separator tokens so the per-stage checks below see them.
392
+ tokens = list(shlex.shlex(command_str, posix=True,
393
+ punctuation_chars="|&;<>(){}"))
394
+ except ValueError:
395
+ return True
396
+ # POSIX shlex eats backslashes (``C:\\bin\\rm.exe`` -> ``C:binrm.exe``), so
397
+ # also judge the raw whitespace split; destructive if either view is.
398
+ raw = command_str.split()
399
+ if raw != tokens and _tokens_destructive(raw):
400
+ return True
401
+ return _tokens_destructive(tokens)
402
+
403
+
404
+ def _segment_destructive(tokens: List[str]) -> bool:
405
+ # Skip leading VAR=val assignments; _effective_cmd0 then resolves env.
406
+ start = 0
407
+ while start < len(tokens) and "=" in tokens[start] and not tokens[start].startswith("-"):
408
+ start += 1
409
+ tokens = tokens[start:]
410
+ # A bare ``--`` ends option parsing, but inside ``env`` it is also a
411
+ # legal option operand (``env -u -- rm`` unsets a var named ``--`` and
412
+ # runs ``rm``) or env's own end-of-options marker, so only non-env
413
+ # segments get the blanket strip; the env unwrapper models ``--``.
414
+ if not tokens or _norm_cmd(tokens[0]) != "env":
415
+ tokens = [t for t in tokens if t != "--"]
416
+ if not tokens:
417
+ return False
418
+ cmd0 = _effective_cmd0(tokens)
419
+ if (cmd0 is None or cmd0 in _NEVER_COMPRESS_CMD0
420
+ or _VERSIONED_INTERPRETER_RE.fullmatch(cmd0)):
421
+ return True
422
+ if tokens and tokens[0] in _SHELL_STRUCT_TOKENS:
423
+ return True
424
+ if cmd0 == "git":
425
+ if _git_has_config_options(tokens):
426
+ return True
427
+ sub = _git_subcommand_tokens(tokens)
428
+ if not sub:
429
+ return True
430
+ name = sub[0].lower()
431
+ if name in _GIT_WRITE_SUBCMDS or _git_writes_output(sub):
432
+ return True
433
+ if name not in _GIT_READONLY_SUBCMDS:
434
+ # Unknown subcommand: could be an alias defined in repo config.
435
+ return True
436
+ if cmd0 == "find" and any(t in _FIND_DESTRUCTIVE_FLAGS for t in tokens):
437
+ return True
438
+ if cmd0 == "sed" and any(t == "-i" or t.startswith("-i")
439
+ or t.startswith("--in-place") for t in tokens):
440
+ return True
441
+ return False
442
+
443
+
444
+ _PIPELINE_SEPARATORS = frozenset({
445
+ "|", "||", "&", "&&", ";", ";;", ";&", ";;&", "|&", "(", ")", "{", "}",
446
+ })
447
+ _PUNCT_CHARS = frozenset("|&;<>(){}")
448
+ # Shell grammar keywords and groupers: a segment LED by one of these hides
449
+ # the real command behind it (``if true; then rm x; fi``, ``{ rm x; }``).
450
+ # Refused outright (fail closed on recognized grammar) rather than
451
+ # mini-interpreting the shell.
452
+ _SHELL_STRUCT_TOKENS = frozenset({
453
+ "if", "then", "else", "elif", "fi", "for", "while", "until", "do",
454
+ "done", "case", "esac", "select", "coproc", "!", "{", "}", "(", ")",
455
+ })
456
+
457
+
458
+ def _tokens_destructive(tokens: List[str]) -> bool:
459
+ # shlex splits runs of punctuation into single tokens (``|&``, ``;;``).
460
+ # Only the exact recognized separators split a stage; ANY other
461
+ # all-punctuation run (every redirect, fd dup, glued or invalid grammar)
462
+ # fails closed rather than risking an exception that hides a writer.
463
+ segments = [[]]
464
+ i = 0
465
+ while i < len(tokens):
466
+ t = tokens[i]
467
+ if t and all(c in _PUNCT_CHARS for c in t):
468
+ if t in _PIPELINE_SEPARATORS:
469
+ segments.append([])
470
+ i += 1
471
+ continue
472
+ # Unrecognized punctuation run (incl. all redirects): fail closed.
473
+ return True
474
+ segments[-1].append(t)
475
+ i += 1
476
+ # Check every pipeline stage, not just argv[0]: ``ls | tee out`` writes
477
+ # through the second stage.
478
+ return any(_segment_destructive(seg) for seg in segments if seg)
479
+
480
+
481
+ def _glob_can_match_unsafe(token: str, names) -> bool:
482
+ """True when ``token`` contains a glob and fnmatch could expand it to one
483
+ of ``names`` (e.g. ``r*``, ``?m``, ``[r]m`` all match ``rm``)."""
484
+ if not any(ch in _GLOB_CHARS for ch in token):
485
+ return False
486
+ return any(fnmatch.fnmatchcase(name, token) for name in names)
185
487
 
186
488
 
187
489
  def _is_safe_add(command: str, handler: str) -> bool:
@@ -221,12 +523,35 @@ def _is_safe_add(command: str, handler: str) -> bool:
221
523
  return False
222
524
  if _is_all_wildcard(cmd0):
223
525
  return False
224
- if cmd0 in _UNSAFE_INTERPRETERS:
526
+ cmd0 = cmd0.lower()
527
+ # _raw_cmd_word already lower-cases and takes the basename of any
528
+ # backslash path, so one glob check against the dangerous names suffices.
529
+ raw0 = _raw_cmd_word(tokens)
530
+ if raw0 and _glob_can_match_unsafe(raw0, _glob_names()):
531
+ return False
532
+ if cmd0 in _SHELL_STRUCT_TOKENS or _glob_can_match_unsafe(cmd0, _SHELL_STRUCT_TOKENS):
533
+ return False
534
+ if raw0 and _glob_can_match_unsafe(raw0, _SHELL_STRUCT_TOKENS):
535
+ return False
536
+ if cmd0 in _UNSAFE_INTERPRETERS or _VERSIONED_INTERPRETER_RE.fullmatch(cmd0):
225
537
  return False
226
538
  if cmd0 in _UNSAFE_PREFIXES:
227
539
  return False
228
540
  if cmd0 in _UNSAFE_WRITE_SUBCMDS:
229
541
  return False
542
+ # Globs: the command string is later matched with fnmatch, so ``r*`` also
543
+ # matches ``rm -rf target``. Reject a glob command word that could match
544
+ # any destructive / interpreter / privilege command name.
545
+ if cmd0 in _NEVER_COMPRESS_CMD0 or _glob_can_match_unsafe(cmd0, _glob_names()):
546
+ return False
547
+ # ``git <glob>``: the subcommand word must not be able to match a write.
548
+ if cmd0 == "git":
549
+ if _git_has_config_options(tokens):
550
+ return False
551
+ sub = _git_subcommand_tokens(tokens)
552
+ if sub and (sub[0].lower() in _GIT_WRITE_SUBCMDS or _git_writes_output(sub)
553
+ or _glob_can_match_unsafe(sub[0].lower(), _GIT_WRITE_SUBCMDS)):
554
+ return False
230
555
  return True
231
556
 
232
557
 
@@ -278,13 +603,28 @@ def load_filters() -> CommandFilterConfig:
278
603
  path = _filters_path()
279
604
  if path is None or not path.exists():
280
605
  return CommandFilterConfig()
281
- if tomllib is None:
282
- _warn_once(path, "tomllib not available; ignoring")
283
- return CommandFilterConfig()
284
606
  try:
285
- with open(path, "rb") as handle:
286
- data = tomllib.load(handle)
287
- except (OSError, tomllib.TOMLDecodeError) as exc:
607
+ parser = tomllib if tomllib is not None else _load_tomli_fallback()
608
+ if parser is None:
609
+ _warn_once(path, "no TOML parser available; ignoring")
610
+ return CommandFilterConfig()
611
+ # Open without blocking and require a regular file, so a FIFO or
612
+ # device at the filters path can never hang the hook.
613
+ fd = os.open(str(path), os.O_RDONLY | getattr(os, "O_NONBLOCK", 0))
614
+ try:
615
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
616
+ os.close(fd)
617
+ _warn_once(path, "not a regular file; ignoring")
618
+ return CommandFilterConfig()
619
+ handle = os.fdopen(fd, "rb")
620
+ except BaseException:
621
+ os.close(fd)
622
+ raise
623
+ with handle:
624
+ data = parser.load(handle)
625
+ except (OSError, UnicodeDecodeError, ValueError, RecursionError) as exc:
626
+ # tomllib.TOMLDecodeError and tomli.TOMLDecodeError are both ValueError;
627
+ # a deeply nested file can also exhaust the parser's recursion.
288
628
  _warn_once(path, f"malformed TOML ({exc}); ignoring")
289
629
  return CommandFilterConfig()
290
630
  return _parse_filters(data, path)
@@ -380,6 +720,7 @@ __all__ = [
380
720
  "EffectiveFilters",
381
721
  "VALID_HANDLERS",
382
722
  "get_effective_filters",
723
+ "is_destructive_command",
383
724
  "load_filters",
384
725
  "merge_filters",
385
726
  "reset_cache",
@@ -50,6 +50,11 @@ _PAYLOAD_MODULES = (
50
50
  "bash_compress.py",
51
51
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
52
52
  "bash_whitelist.py",
53
+ # command_filters + _tomli: user [filters.*] TOML config consulted by
54
+ # bash_compress/bash_whitelist; _tomli is the 3.9/3.10 parser it
55
+ # lazy-imports when tomllib is absent.
56
+ "command_filters.py",
57
+ "_tomli.py",
53
58
  "hook_io.py",
54
59
  "plugin_env.py",
55
60
  "runtime_env.py",
@@ -51,6 +51,11 @@ _PAYLOAD_MODULES = (
51
51
  "bash_compress.py",
52
52
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
53
53
  "bash_whitelist.py",
54
+ # command_filters + _tomli: user [filters.*] TOML config consulted by
55
+ # bash_compress/bash_whitelist; _tomli is the 3.9/3.10 parser it
56
+ # lazy-imports when tomllib is absent.
57
+ "command_filters.py",
58
+ "_tomli.py",
54
59
  "hook_io.py",
55
60
  "plugin_env.py",
56
61
  "runtime_env.py",
@@ -23,7 +23,7 @@ if str(SCRIPTS) not in sys.path:
23
23
  sys.path.insert(0, str(SCRIPTS))
24
24
 
25
25
  import devin_state as state
26
- from devin_verify import PAYLOAD
26
+ from devin_verify import PAYLOAD, payload_key_shapes
27
27
  from py_trust import py_path_is_trusted
28
28
  import devin_hooks as hooks
29
29
  SKILL_NAME = 'token-optimizer-output'
@@ -132,16 +132,12 @@ def _ownership(*, allow_missing=False) -> dict | None:
132
132
  raise OSError('invalid ownership record; run uninstall --purge (which also removes stored captures) to discard adapter state')
133
133
  if not isinstance(record, dict) or record.get('owner') != MARKER or not isinstance(record.get('files'), dict):
134
134
  raise OSError('invalid ownership record; run uninstall --purge (which also removes stored captures) to discard adapter state')
135
- expected = {str(state.data_dir() / 'plugin' / name) for name in PAYLOAD} | {str(skill_dir() / 'SKILL.md')}
136
- # Earlier releases shipped fewer payload files: 5.13.43 had no hook module,
137
- # and releases before it also lacked the two plugin-env modules.
138
- previous = expected - {str(state.data_dir() / 'plugin' / 'devin_hooks.py')}
139
- legacy = previous - {str(state.data_dir() / 'plugin' / name) for name in ('plugin_env.py', 'refetch_fingerprint.py')}
135
+ _, shapes = payload_key_shapes(state.data_dir() / 'plugin', PAYLOAD, skill_dir() / 'SKILL.md')
140
136
  try:
141
137
  record_keys = _resolved_keys(record['files'])
142
138
  except (OSError, ValueError, TypeError, RuntimeError):
143
139
  raise OSError('recorded paths cannot be resolved; run uninstall --purge (which also removes stored captures) to discard adapter state')
144
- if record_keys not in (sorted(expected), sorted(previous), sorted(legacy)):
140
+ if record_keys not in shapes:
145
141
  # A recorded path routed through a symlink resolves elsewhere; name the
146
142
  # real cause before falling through to the version/spelling advice.
147
143
  for name in record['files']:
@@ -533,16 +529,14 @@ def _recover_pending() -> None:
533
529
  value=json.loads(_private_bytes(pending))
534
530
  except (ValueError,RecursionError):
535
531
  value=None
536
- expected={str(state.data_dir()/'plugin'/name) for name in PAYLOAD}|{str(skill_dir()/'SKILL.md')}
537
- previous=expected - {str(state.data_dir()/'plugin'/'devin_hooks.py')}
538
- legacy=previous - {str(state.data_dir()/'plugin'/name) for name in ('plugin_env.py','refetch_fingerprint.py')}
532
+ expected,shapes=payload_key_shapes(state.data_dir()/'plugin',PAYLOAD,skill_dir()/'SKILL.md')
539
533
  files=value.get('files') if isinstance(value,dict) else None
540
534
  try:
541
535
  keys=_resolved_keys(files) if isinstance(files,dict) else None
542
536
  except (OSError,ValueError,TypeError,RuntimeError):
543
537
  keys=None
544
538
  if (not isinstance(value,dict) or value.get('owner')!=MARKER
545
- or keys not in (sorted(expected),sorted(previous),sorted(legacy))):
539
+ or keys not in shapes):
546
540
  raise OSError('invalid pending install record: ' + str(pending) + '; preserved; run uninstall --purge (which also removes stored captures) to discard adapter state')
547
541
  # Reconcile published new bytes first: stale pending must not undo a completed update.
548
542
  if manifest_path().exists():
@@ -563,7 +557,7 @@ def _recover_pending() -> None:
563
557
  raise OSError('pending version/content ambiguous: ' + str(pending) + '; preserved; run uninstall --purge (which also removes stored captures) to discard adapter state, or follow the documented manual repair')
564
558
  old=value.get('previous')
565
559
  if old is not None:
566
- if not isinstance(old,dict) or _resolved_keys(old) not in (sorted(expected),sorted(legacy)):raise OSError('invalid refresh recovery record')
560
+ if not isinstance(old,dict) or _resolved_keys(old) not in shapes:raise OSError('invalid refresh recovery record')
567
561
  if any(not isinstance(content,str) for content in old.values()) or not isinstance(value.get('previous_manifest'),str):
568
562
  raise OSError('invalid refresh recovery encoding')
569
563
  previous={name:base64.b64decode(content,validate=True) for name,content in old.items()}
@@ -11,22 +11,23 @@ import sys
11
11
  PAYLOAD = ('devin_compress.py', 'devin_state.py', 'devin_doctor.py', 'devin_verify.py', 'devin_source.py',
12
12
  'bash_compress.py', 'bash_whitelist.py', 'credential_patterns.py',
13
13
  'token_estimate.py', 'command_filters.py', 'runtime_env.py', 'py_trust.py', 'plugin_env.py', 'refetch_fingerprint.py',
14
- 'devin_hooks.py')
14
+ '_tomli.py', 'devin_hooks.py')
15
15
  ALLOWED_MODULES = frozenset(Path(name).stem for name in PAYLOAD)
16
16
 
17
17
  # Repo names outside the installed closure must never fall back to sys.path.
18
18
  REPO_MODULES = frozenset((
19
- '_measure',
19
+ '_measure', '_tomli',
20
20
  'activity_tracker', 'adapter_hook_command', 'antigravity_doctor', 'antigravity_hook_bridge', 'antigravity_install',
21
21
  'antigravity_proto', 'antigravity_session', 'antigravity_state', 'archive_result',
22
22
  'bash_compress', 'bash_compress_hook', 'bash_hook', 'bash_whitelist', 'benchmark', 'cloud_kit',
23
23
  'build_output_compress', 'codex_command_compress', 'codex_compact_prompt', 'codex_doctor',
24
- 'codex_hook_bridge', 'codex_install', 'codex_io', 'codex_log_index', 'codex_models',
24
+ 'codex_hook_bridge', 'codex_hook_provenance', 'codex_install', 'codex_io', 'codex_log_index', 'codex_models',
25
25
  'codex_session', 'codex_state', 'codex_statusline', 'command_filters',
26
26
  'compression_backfill', 'compression_log', 'context_intel', 'context_pressure',
27
27
  'copilot_doctor', 'copilot_hook_bridge', 'copilot_install', 'copilot_session',
28
28
  'copilot_state', 'copilot_vscode', 'cowork_doctor', 'cowork_install',
29
- 'credential_patterns', 'cursor_doctor', 'cursor_hook_bridge', 'cursor_install',
29
+ 'credential_patterns', 'heal_report', 'hook_heal', 'hook_provenance', 'owned_hooks',
30
+ 'shipped_hook_templates', 'shipped_starter_hooks', 'cursor_doctor', 'cursor_hook_bridge', 'cursor_install',
30
31
  'cursor_session', 'cursor_state', 'delta_diff', 'detectors', 'deterministic_candidates',
31
32
  'devin_compress', 'devin_doctor', 'devin_hooks', 'devin_install', 'devin_source', 'devin_state',
32
33
  'devin_verify', 'grok_doctor', 'grok_hook_bridge', 'grok_install', 'grok_session',
@@ -34,7 +35,7 @@ REPO_MODULES = frozenset((
34
35
  'hermes_state', 'hermes_tool_hooks', 'hook_io', 'hook_runtime', 'injection', 'install_reconcile', 'measure',
35
36
  'outline', 'pipeline_analyzer', 'plugin_env', 'py_trust', 'quality_cache_gate',
36
37
  'read_cache', 'recovery_output', 'refetch_fingerprint', 'refetch_guard', 'routing_advisor',
37
- 'runtime_env', 'session_activity', 'session_store', 'spawn_utils', 'structure_map', 'structure_map_ts',
38
+ 'reset_epoch', 'runtime_env', 'session_activity', 'session_store', 'spawn_utils', 'structure_map', 'structure_map_ts',
38
39
  'structure_replay', 'thrash_guard', 'token_estimate', 'tool_search_diagnostic', 'utf8_io', 'archive_window', 'checkpoint_state',
39
40
  ))
40
41
 
@@ -65,3 +65,19 @@ def verify_install():
65
65
  state.private_path(state.data_dir()/'consent.json')
66
66
  if not state.consent_ok():raise OSError('missing local data consent')
67
67
  return True
68
+
69
+
70
+ def payload_key_shapes(plugin, names, skill_md):
71
+ """Recorded-key sets for every payload shape an install record may carry.
72
+
73
+ Returns ``(expected, shapes)``: the current payload's path set plus the
74
+ sorted key lists of the current, pre-Tomli, previous and legacy shapes.
75
+ Earlier releases shipped fewer payload files: 5.13.43 had no hook module,
76
+ releases before it also lacked the two plugin-env modules, and every
77
+ existing record predates the _tomli.py payload module shipped now.
78
+ """
79
+ expected={str(plugin/name) for name in names}|{str(skill_md)}
80
+ tomli=str(plugin/'_tomli.py')
81
+ previous=expected-{str(plugin/'devin_hooks.py'),tomli}
82
+ legacy=previous-{str(plugin/name) for name in ('plugin_env.py','refetch_fingerprint.py')}
83
+ return expected,tuple(sorted(keys) for keys in (expected,expected-{tomli},previous,legacy))
@@ -61,6 +61,11 @@ _PAYLOAD_MODULES = (
61
61
  # sets _bash_hook = None, and the entire PreToolUse bash compression
62
62
  # feature silently no-ops.
63
63
  "bash_whitelist.py",
64
+ # command_filters + _tomli: user [filters.*] TOML config consulted by
65
+ # bash_compress/bash_whitelist; _tomli is the 3.9/3.10 parser it
66
+ # lazy-imports when tomllib is absent.
67
+ "command_filters.py",
68
+ "_tomli.py",
64
69
  "hook_io.py",
65
70
  "plugin_env.py",
66
71
  "runtime_env.py",