@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer v5: PreToolUse Bash Hook.
3
+
4
+ On Claude Code this hook is always silent. It used to rewrite whitelisted
5
+ commands through bash_compress.py and return permissionDecision "allow" so the
6
+ rewrite ran without a prompt. A hook "allow" approves the call outright: it
7
+ skips the user's permission prompt and the auto mode classifier, and the
8
+ whitelist includes commands that can delete (`find -delete`, cloud CLIs,
9
+ `git branch -D`). Bash output is compressed after the command has run, by the
10
+ PostToolUse bash_compress_hook.py, which takes no part in permissions.
11
+
12
+ This module still holds the shared gates the other host bridges import.
13
+
14
+ Exit behavior:
15
+ - No output, always = no decision, the normal permission flow applies
16
+ """
17
+
18
+ from plugin_env import is_v5_flag_enabled
19
+
20
+ # The whitelist gate lives in a dependency-free module so the compression
21
+ # wrapper's startup self-check can import it without this module's
22
+ # environment-resolution import chain.
23
+ from bash_whitelist import (
24
+ _DANGEROUS_CHARS,
25
+ _GIT_WRITE_SUBCMDS,
26
+ _SAFE_ENV_VARS,
27
+ _WHITELIST_COMPOUND,
28
+ _WHITELIST_SINGLE,
29
+ has_dangerous_chars as _has_dangerous_chars_impl,
30
+ is_auto_approvable as _is_auto_approvable_impl,
31
+ is_whitelisted as _is_whitelisted_impl,
32
+ )
33
+
34
+
35
+ def _has_dangerous_chars(command_str):
36
+ """Check if command contains shell metacharacters."""
37
+ return _has_dangerous_chars_impl(command_str)
38
+
39
+
40
+ def _is_whitelisted(command_str):
41
+ """Check if command matches the compression whitelist."""
42
+ return _is_whitelisted_impl(command_str)
43
+
44
+
45
+ def _is_auto_approvable(command_str):
46
+ """Check if a command is safe for a rewrite that also approves the call."""
47
+ return _is_auto_approvable_impl(command_str)
48
+
49
+
50
+ def _is_bash_compress_enabled():
51
+ """Check if bash compression is enabled. Default ON since v5.5."""
52
+ return is_v5_flag_enabled("v5_bash_compress", "TOKEN_OPTIMIZER_BASH_COMPRESS", default=True)
53
+
54
+
55
+ def main():
56
+ # Never print: any PreToolUse output here would be a permission decision.
57
+ return
58
+
59
+
60
+ if __name__ == "__main__":
61
+ main()
@@ -0,0 +1,243 @@
1
+ #!/usr/bin/env python3
2
+ """Shared command whitelist gate for the Bash compression path.
3
+
4
+ Dependency-free by design: this module is imported by bash_compress.py's
5
+ startup self-check, which runs on every whitelisted Bash command, so it must
6
+ not pull in any module that does filesystem or environment resolution at
7
+ import time. Heavier concerns (plugin data dirs, runtimes) stay in their own
8
+ modules and are consulted by callers, not here.
9
+ """
10
+
11
+ import shlex
12
+
13
+ # Categorical exclusion: if ANY of these appear in the raw command string,
14
+ # never rewrite. Checked BEFORE shlex tokenization to catch all forms.
15
+ # Includes newlines/nulls to prevent multi-line command injection.
16
+ _DANGEROUS_CHARS = frozenset(";|&`$(){}><\n\r\x00")
17
+
18
+ # Only these env var names are safe to pass through when stripping prefixes.
19
+ # LD_PRELOAD, DYLD_*, PATH etc. can be used for library injection.
20
+ _SAFE_ENV_VARS = frozenset({
21
+ "TERM", "LANG", "LC_ALL", "LC_CTYPE", "COLOR", "NO_COLOR", "FORCE_COLOR",
22
+ "GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL",
23
+ "GIT_DIR", "GIT_WORK_TREE", "HOME", "USER", "LOGNAME",
24
+ })
25
+
26
+ # Commands eligible for compression (argv[0] or argv[0:2])
27
+ _WHITELIST_SINGLE = frozenset({
28
+ "git", "pytest", "py.test", "jest", "vitest", "rspec", "ls", "find",
29
+ # v5.1 lint handlers (read-only static analysis)
30
+ "eslint", "flake8", "pylint", "shellcheck", "rubocop",
31
+ # v5.1 logs handler (read-only log inspection)
32
+ "tail", "journalctl",
33
+ # v5.1 tree handler (read-only directory tree)
34
+ "tree",
35
+ # v5.1 build handler (type-check / bundler builds — read-only compile)
36
+ "tsc", "webpack", "esbuild",
37
+ # v5.1 extended test runners (read-only test execution)
38
+ "mocha", "karma",
39
+ # v5.8 additional test runners (read-only test execution)
40
+ "tox", "nox", "ava", "gradle", "gradlew", "mvn", "deno", "bun",
41
+ # v5.5 read-only utilities
42
+ "sqlite3", "wc", "du", "df",
43
+ # v5.8 JSON/CSV handlers (read-only data inspection)
44
+ "jq", "yq", "csvtool", "mlr", "csvcut",
45
+ # v5.8 cloud CLI handlers (read-only inventory queries)
46
+ "gcloud", "aws", "az",
47
+ # v5.9 search results handler (read-only code search)
48
+ "grep", "rg", "ag", "ack",
49
+ })
50
+ _WHITELIST_COMPOUND = {
51
+ ("git", "status"), ("git", "log"), ("git", "diff"), ("git", "show"), ("git", "branch"),
52
+ ("python", "-m"), ("python3", "-m"), # python -m pytest
53
+ ("npx", "jest"), ("npx", "vitest"),
54
+ # NOTE: npm install, npm ci, pip install, pip3 install, cargo build, docker build
55
+ # are intentionally excluded. They execute postinstall/build scripts, produce
56
+ # security-relevant output (vulnerability warnings, deprecation notices), and
57
+ # are NOT read-only. Silent compression could hide important errors.
58
+ ("npm", "test"),
59
+ ("cargo", "test"),
60
+ ("go", "test"),
61
+ # v5.1 lint handlers (multi-word lint invocations)
62
+ ("ruff", "check"),
63
+ ("biome", "lint"),
64
+ ("golangci-lint", "run"),
65
+ # v5.1 progress handler (docker pull — read-only layer fetch)
66
+ # docker build excluded: executes Dockerfile RUN instructions (write side-effects)
67
+ ("docker", "pull"),
68
+ # v5.1 list handlers (read-only inventory queries)
69
+ ("pip", "list"), ("pip3", "list"),
70
+ ("npm", "ls"),
71
+ ("pnpm", "list"),
72
+ ("docker", "ps"),
73
+ ("brew", "list"),
74
+ # v5.1 build handlers (multi-word build commands)
75
+ ("vite", "build"),
76
+ ("next", "build"),
77
+ ("go", "build"),
78
+ # v5.1 extended test runners (multi-word invocations)
79
+ ("cypress", "run"),
80
+ ("playwright", "test"),
81
+ ("npx", "cypress"),
82
+ ("npx", "playwright"),
83
+ ("npx", "mocha"),
84
+ ("npx", "karma"),
85
+ # v5.8 additional test runners (multi-word invocations)
86
+ ("npx", "ava"),
87
+ ("gradle", "test"),
88
+ ("gradlew", "test"),
89
+ ("mvn", "test"),
90
+ ("deno", "test"),
91
+ ("bun", "test"),
92
+ # v5.5 docker/kubectl read-only inspection
93
+ ("docker", "logs"),
94
+ ("docker", "inspect"),
95
+ ("kubectl", "get"),
96
+ ("kubectl", "describe"),
97
+ ("kubectl", "logs"),
98
+ # v5.8 kubectl extended read-only queries
99
+ ("kubectl", "top"),
100
+ ("kubectl", "events"),
101
+ # v5.8 JSON inspection via node/deno/bun (read-only)
102
+ # ("node", "-e") — intentionally excluded: arbitrary code execution
103
+ }
104
+
105
+ # Git write commands that should NOT be compressed
106
+ _GIT_WRITE_SUBCMDS = frozenset({
107
+ "commit", "push", "pull", "merge", "rebase", "reset", "checkout",
108
+ "switch", "stash", "tag", "cherry-pick", "revert", "am", "apply",
109
+ "add", "rm", "mv", "restore", "bisect", "clean", "fetch", "clone",
110
+ "init", "remote", "submodule", "worktree",
111
+ })
112
+
113
+
114
+ # Inspection-only commands a hook may rewrite when the rewrite ALSO approves
115
+ # the call (a host where the hook's answer skips the user's approval step).
116
+ # Deliberately tiny: the compression whitelist above includes builds, tests,
117
+ # cloud CLIs and `find`, all of which can delete or write.
118
+ _AUTO_APPROVE_COMMANDS = frozenset({"ls", "wc", "du", "df", "tail", "tree", "rg", "grep"})
119
+ _AUTO_APPROVE_GIT_SUBCMDS = frozenset({"status", "log"})
120
+ # Flags that write a file or run another program from an otherwise read-only command.
121
+ _AUTO_APPROVE_BLOCKED_FLAG_PREFIXES = (
122
+ "--output", "--ext-diff", "--textconv", "--pre", "--hostname-bin",
123
+ )
124
+
125
+
126
+ def is_auto_approvable(command_str):
127
+ """True only for commands that cannot write, delete or run other programs.
128
+
129
+ The compression whitelist decides what is worth compressing. This decides
130
+ what a hook may wave through without the user's approval, which is a much
131
+ higher bar. Every caller that emits an approval must pass this gate.
132
+ """
133
+ if has_dangerous_chars(command_str) or not is_whitelisted(command_str):
134
+ return False
135
+ try:
136
+ tokens = shlex.split(command_str)
137
+ except ValueError:
138
+ return False
139
+ # No env prefixes: GIT_DIR / HOME and friends retarget an approved command.
140
+ if not tokens or "=" in tokens[0]:
141
+ return False
142
+ cmd, args = tokens[0], tokens[1:]
143
+ if any(a.startswith(_AUTO_APPROVE_BLOCKED_FLAG_PREFIXES) for a in args):
144
+ return False
145
+ if cmd == "git":
146
+ return bool(args) and args[0] in _AUTO_APPROVE_GIT_SUBCMDS
147
+ if cmd == "tree":
148
+ # `tree -o FILE` writes the listing to FILE.
149
+ return not any(a == "-o" or (a.startswith("-") and not a.startswith("--") and "o" in a[1:]) for a in args)
150
+ return cmd in _AUTO_APPROVE_COMMANDS
151
+
152
+
153
+ def has_dangerous_chars(command_str):
154
+ """Check if command contains shell metacharacters."""
155
+ for ch in command_str:
156
+ if ch in _DANGEROUS_CHARS:
157
+ return True
158
+ return False
159
+
160
+
161
+ def is_whitelisted(command_str):
162
+ """Check if command matches the compression whitelist."""
163
+ # U9: consult user TOML command filters. User exclude overrides the
164
+ # built-in whitelist (a user can remove "git status" from compression);
165
+ # user add extends it (a user can add "cargo test" with a handler). The
166
+ # _is_safe_add gate already ran in the loader, so add entries are
167
+ # read-only and handler-validated. Categorical exclusions (dangerous
168
+ # chars, git write subcmds, interpreters) are enforced by the caller
169
+ # BEFORE this function and are not affected by user config.
170
+ eff = None
171
+ try:
172
+ from command_filters import get_effective_filters
173
+ eff = get_effective_filters()
174
+ if eff.is_user_excluded(command_str):
175
+ return False
176
+ except Exception:
177
+ pass
178
+
179
+ try:
180
+ tokens = shlex.split(command_str)
181
+ except ValueError:
182
+ return False # malformed quoting
183
+
184
+ if not tokens:
185
+ return False
186
+
187
+ # Strip leading env var assignments (VAR=val), only safe var names
188
+ cmd_start = 0
189
+ while cmd_start < len(tokens) and "=" in tokens[cmd_start] and not tokens[cmd_start].startswith("-"):
190
+ var_name = tokens[cmd_start].split("=", 1)[0]
191
+ if var_name not in _SAFE_ENV_VARS:
192
+ return False # Unsafe env var (e.g., LD_PRELOAD), reject entirely
193
+ cmd_start += 1
194
+
195
+ if cmd_start >= len(tokens):
196
+ return False
197
+
198
+ cmd = tokens[cmd_start]
199
+ subcmd = tokens[cmd_start + 1] if cmd_start + 1 < len(tokens) else ""
200
+
201
+ # Check compound whitelist first (more specific)
202
+ if (cmd, subcmd) in _WHITELIST_COMPOUND:
203
+ if cmd == "git" and subcmd in _GIT_WRITE_SUBCMDS:
204
+ return False
205
+ if cmd == "kubectl":
206
+ remaining = tokens[cmd_start + 2:]
207
+ if any(arg == "secret" or arg == "secrets" or arg.startswith("secret/") or arg.startswith("secrets/") for arg in remaining):
208
+ return False
209
+ return True
210
+
211
+ # Check single command whitelist
212
+ if cmd in _WHITELIST_SINGLE:
213
+ if cmd == "git":
214
+ if subcmd in _GIT_WRITE_SUBCMDS or not subcmd:
215
+ return False
216
+ if subcmd not in ("status", "log", "diff", "show", "branch"):
217
+ return False
218
+ if cmd == "sqlite3":
219
+ cmd_lower = command_str.lower()
220
+ if any(w in cmd_lower for w in ("insert", "update", "delete", "drop", "alter", "create")):
221
+ return False
222
+ remaining = tokens[cmd_start + 1:]
223
+ if any(t.startswith(".") for t in remaining):
224
+ return False
225
+ return True
226
+
227
+ # Never rewrite shell interpreters or privilege-escalation wrappers (also prevents recursion on rewritten commands).
228
+ if cmd in ("bash", "sh", "zsh", "dash", "fish", "sudo", "su"):
229
+ return False
230
+
231
+ # U9: user add entries extend the whitelist. The _is_safe_add gate already
232
+ # ran in the loader (command_filters.load_filters), so the entry is
233
+ # read-only and mapped to a known handler. Built-in detection ran first,
234
+ # so user rules only extend, never replace a built-in handler.
235
+ try:
236
+ if eff is not None:
237
+ add_entry = eff.find_user_add(command_str)
238
+ if add_entry is not None:
239
+ return True
240
+ except Exception:
241
+ pass
242
+
243
+ return False