@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.
- package/.claude-plugin/marketplace.json +76 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +130 -0
- package/LICENSE-SMALL-BUSINESS.md +62 -0
- package/PRIVACY.md +200 -0
- package/README.md +13 -2
- package/hooks/codex-hooks.json +4 -0
- package/hooks/hooks.json +182 -0
- package/hooks/module_runner.py +149 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +776 -0
- package/hooks/sessionstart_runner.py +629 -0
- package/hooks/stop_runner.py +408 -0
- package/hooks/userpromptsubmit_runner.py +722 -0
- package/hooks/windows-launcher.py +163 -0
- package/install-cloud.sh +23 -0
- package/package.json +29 -4
- package/skills/fleet-auditor/SKILL.md +150 -0
- package/skills/fleet-auditor/references/fleet-systems.md +167 -0
- package/skills/fleet-auditor/references/report-template.md +50 -0
- package/skills/fleet-auditor/references/waste-patterns.md +126 -0
- package/skills/fleet-auditor/scripts/fleet.py +3612 -0
- package/skills/fleet-auditor/scripts/shared.py +277 -0
- package/skills/resume-checkpoint/SKILL.md +52 -0
- package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
- package/skills/token-coach/SKILL.md +129 -0
- package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
- package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
- package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
- package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
- package/skills/token-coach/references/agentic-systems.md +147 -0
- package/skills/token-coach/references/coach-patterns.md +120 -0
- package/skills/token-coach/references/coaching-scripts.md +146 -0
- package/skills/token-coach/references/deterministic-stages.md +102 -0
- package/skills/token-coach/references/keepwarm-consent.md +48 -0
- package/skills/token-coach/references/quick-reference.md +155 -0
- package/skills/token-dashboard/SKILL.md +72 -0
- package/skills/token-optimizer/SKILL.md +150 -0
- package/skills/token-optimizer/assets/dashboard.html +7251 -0
- package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
- package/skills/token-optimizer/examples/hooks-starter.json +179 -0
- package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
- package/skills/token-optimizer/pricing/prices.json +695 -0
- package/skills/token-optimizer/references/agent-prompts.md +687 -0
- package/skills/token-optimizer/references/cli-reference.md +92 -0
- package/skills/token-optimizer/references/codex-workflow.md +188 -0
- package/skills/token-optimizer/references/cursor-workflow.md +74 -0
- package/skills/token-optimizer/references/error-recovery.md +37 -0
- package/skills/token-optimizer/references/implementation-playbook.md +416 -0
- package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
- package/skills/token-optimizer/references/opencode-workflow.md +72 -0
- package/skills/token-optimizer/references/optimization-checklist.md +714 -0
- package/skills/token-optimizer/references/phase0-setup.md +142 -0
- package/skills/token-optimizer/references/presentation-workflow.md +72 -0
- package/skills/token-optimizer/references/session-continuity.md +19 -0
- package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
- package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
- package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
- package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
- package/skills/token-optimizer/scripts/archive_result.py +1725 -0
- package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
- package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
- package/skills/token-optimizer/scripts/bash_hook.py +61 -0
- package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
- package/skills/token-optimizer/scripts/benchmark.py +1765 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
- package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
- package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
- package/skills/token-optimizer/scripts/codex_install.py +810 -0
- package/skills/token-optimizer/scripts/codex_io.py +119 -0
- package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
- package/skills/token-optimizer/scripts/codex_models.py +34 -0
- package/skills/token-optimizer/scripts/codex_session.py +1186 -0
- package/skills/token-optimizer/scripts/codex_state.py +707 -0
- package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
- package/skills/token-optimizer/scripts/command_filters.py +386 -0
- package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
- package/skills/token-optimizer/scripts/compression_log.py +230 -0
- package/skills/token-optimizer/scripts/context_intel.py +331 -0
- package/skills/token-optimizer/scripts/context_pressure.py +115 -0
- package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
- package/skills/token-optimizer/scripts/copilot_install.py +277 -0
- package/skills/token-optimizer/scripts/copilot_session.py +496 -0
- package/skills/token-optimizer/scripts/copilot_state.py +569 -0
- package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
- package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
- package/skills/token-optimizer/scripts/cowork_install.py +380 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
- package/skills/token-optimizer/scripts/cursor_install.py +423 -0
- package/skills/token-optimizer/scripts/cursor_session.py +303 -0
- package/skills/token-optimizer/scripts/cursor_state.py +348 -0
- package/skills/token-optimizer/scripts/delta_diff.py +110 -0
- package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
- package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
- package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
- package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
- package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
- package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
- package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
- package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
- package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
- package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
- package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
- package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
- package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
- package/skills/token-optimizer/scripts/devin_compress.py +790 -0
- package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
- package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
- package/skills/token-optimizer/scripts/devin_install.py +1086 -0
- package/skills/token-optimizer/scripts/devin_source.py +119 -0
- package/skills/token-optimizer/scripts/devin_state.py +330 -0
- package/skills/token-optimizer/scripts/devin_verify.py +67 -0
- package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
- package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
- package/skills/token-optimizer/scripts/grok_install.py +397 -0
- package/skills/token-optimizer/scripts/grok_session.py +317 -0
- package/skills/token-optimizer/scripts/grok_state.py +299 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
- package/skills/token-optimizer/scripts/hermes_install.py +668 -0
- package/skills/token-optimizer/scripts/hermes_session.py +691 -0
- package/skills/token-optimizer/scripts/hermes_state.py +448 -0
- package/skills/token-optimizer/scripts/hook_io.py +120 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
- package/skills/token-optimizer/scripts/injection.py +156 -0
- package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
- package/skills/token-optimizer/scripts/measure.py +58739 -0
- package/skills/token-optimizer/scripts/outline.py +53 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
- package/skills/token-optimizer/scripts/plugin_env.py +562 -0
- package/skills/token-optimizer/scripts/py_trust.py +80 -0
- package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
- package/skills/token-optimizer/scripts/read_cache.py +2489 -0
- package/skills/token-optimizer/scripts/recovery_output.py +110 -0
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
- package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
- package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
- package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
- package/skills/token-optimizer/scripts/session_store.py +979 -0
- package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
- package/skills/token-optimizer/scripts/statusline.js +660 -0
- package/skills/token-optimizer/scripts/structure_map.py +2880 -0
- package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
- package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
- package/skills/token-optimizer/scripts/token_estimate.py +80 -0
- package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
- package/skills/token-optimizer/scripts/utf8_io.py +219 -0
|
@@ -0,0 +1,723 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Token Optimizer v5.12: Pipeline-aware read-only safety classifier.
|
|
3
|
+
|
|
4
|
+
Used by the PostToolUse bash_compress_hook.py to decide whether a pipeline
|
|
5
|
+
or metachar-containing command is safe to compress. Unlike the PreToolUse
|
|
6
|
+
bash_hook.py (which categorically rejects metachar commands), this module
|
|
7
|
+
SPLITS the command into pipeline stages and checks EACH stage individually
|
|
8
|
+
against a consolidated read-only whitelist.
|
|
9
|
+
|
|
10
|
+
A pipeline is eligible for compression ONLY when EVERY stage is a known
|
|
11
|
+
read-only command. Any unrecognized, side-effecting, or unparseable stage
|
|
12
|
+
causes the whole pipeline to be rejected (fail-closed: pass through raw).
|
|
13
|
+
|
|
14
|
+
SECURITY hardening:
|
|
15
|
+
- Raw command string is screened for injection constructs BEFORE tokenization:
|
|
16
|
+
newlines, $(), backticks, <(), >(), and bare & (async/background).
|
|
17
|
+
- Every token is checked for glued operators (a|rm passes shlex but
|
|
18
|
+
contains | as a substring). Any token containing | ; && inside it is
|
|
19
|
+
rejected unless it IS exactly that separator.
|
|
20
|
+
- The read-only whitelist is narrowed to genuinely read-only commands.
|
|
21
|
+
env, command, xargs, tee, awk, aws, gcloud, az removed.
|
|
22
|
+
- Cloud CLIs require explicit read-only subcommand allow-list.
|
|
23
|
+
- git uses an explicit ALLOW-list (not deny-list).
|
|
24
|
+
- git branch rejects delete (-d/-D/--delete), rename (-m/-M/--move),
|
|
25
|
+
copy (-c/-C/--copy) and --force/-f flags.
|
|
26
|
+
- find rejects -delete/-exec/-ok/-fprint/-fls.
|
|
27
|
+
- sqlite3 rejects replace, vacuum, .import, .restore, pragma.
|
|
28
|
+
- npm run / terraform state / git config / kubectl config / docker pull
|
|
29
|
+
removed from compound whitelist.
|
|
30
|
+
- python -m only allowed for known read-only modules (pytest, unittest,
|
|
31
|
+
json.tool — NOT pip).
|
|
32
|
+
|
|
33
|
+
The consolidated whitelist merges bash_hook._WHITELIST_SINGLE,
|
|
34
|
+
bash_hook._WHITELIST_COMPOUND, and additional pipeline-consumer commands.
|
|
35
|
+
|
|
36
|
+
Security invariants:
|
|
37
|
+
- Read-only only: no write, no side-effect, no interpreter
|
|
38
|
+
- Fail-closed default: unknown command → not read-only → pass through raw
|
|
39
|
+
- No shell=True, no command reconstruction, no re-execution
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import re
|
|
45
|
+
import shlex
|
|
46
|
+
|
|
47
|
+
# ---------------------------------------------------------------------------
|
|
48
|
+
# Pre-tokenization injection screen: reject raw command strings containing
|
|
49
|
+
# constructs that shlex.split() is blind to.
|
|
50
|
+
# ---------------------------------------------------------------------------
|
|
51
|
+
|
|
52
|
+
# Newlines in commands indicate injection (ls -la\nrm -rf build).
|
|
53
|
+
_DANGEROUS_RAW_CHARS = re.compile(r"[\n\r]")
|
|
54
|
+
|
|
55
|
+
# Command substitution: $(...) and backticks.
|
|
56
|
+
_DANGEROUS_SUBSTITUTION = re.compile(r"\$\(|`")
|
|
57
|
+
|
|
58
|
+
# Process substitution: <(...) and >(...).
|
|
59
|
+
_DANGEROUS_PROCESS_SUBST = re.compile(r"[<>]\(")
|
|
60
|
+
|
|
61
|
+
# ---------------------------------------------------------------------------
|
|
62
|
+
# Pipeline separators (tokens that split one command into multiple stages).
|
|
63
|
+
# ---------------------------------------------------------------------------
|
|
64
|
+
_PIPELINE_SEPARATORS = frozenset({"|", "|&", "&&", "||", ";"})
|
|
65
|
+
|
|
66
|
+
# Glued-operator check: any token containing these as substrings (but is not
|
|
67
|
+
# exactly one of them) indicates a glued operator like a|b or cat;rm.
|
|
68
|
+
_GLUED_OPERATOR_CHARS = frozenset({"|", ";"})
|
|
69
|
+
|
|
70
|
+
# ---------------------------------------------------------------------------
|
|
71
|
+
# Redirection tokens and handlers.
|
|
72
|
+
# ---------------------------------------------------------------------------
|
|
73
|
+
_REDIRECT_TOKENS = frozenset({">", ">>", "<", "<<", "<>", ">&", "&>"})
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _is_redirect_token(tok: str) -> bool:
|
|
77
|
+
"""True if token is a shell redirection operator."""
|
|
78
|
+
if tok in _REDIRECT_TOKENS:
|
|
79
|
+
return True
|
|
80
|
+
if any(c.isdigit() for c in tok[:1]) and any(c in tok for c in (">", "<")):
|
|
81
|
+
i = 0
|
|
82
|
+
while i < len(tok) and tok[i].isdigit():
|
|
83
|
+
i += 1
|
|
84
|
+
rest = tok[i:]
|
|
85
|
+
if rest and rest[0] in (">", "<", "&"):
|
|
86
|
+
return True
|
|
87
|
+
if rest.startswith(">") or rest.startswith("<"):
|
|
88
|
+
return True
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# Redirect targets that are safe to strip (not real file writes).
|
|
93
|
+
# /dev/null, /dev/stderr, /dev/stdout — these are sinks, not file writes.
|
|
94
|
+
# Bare file descriptors (2>&1, 1>&2) are self-contained.
|
|
95
|
+
_SAFE_REDIRECT_TARGETS = frozenset({"/dev/null", "/dev/stderr", "/dev/stdout", "/dev/fd/1", "/dev/fd/2"})
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _redirect_has_file_target(tok: str) -> bool:
|
|
99
|
+
"""True if this redirect token expects a filename target."""
|
|
100
|
+
if tok in (">", ">>", "<", "<<", "<>"):
|
|
101
|
+
return True
|
|
102
|
+
if any(c.isdigit() for c in tok[:1]):
|
|
103
|
+
i = 0
|
|
104
|
+
while i < len(tok) and tok[i].isdigit():
|
|
105
|
+
i += 1
|
|
106
|
+
rest = tok[i:]
|
|
107
|
+
if rest.startswith(">&"):
|
|
108
|
+
return False
|
|
109
|
+
if rest == ">&":
|
|
110
|
+
return False
|
|
111
|
+
if rest.startswith(">") or rest.startswith("<"):
|
|
112
|
+
return True
|
|
113
|
+
if tok in ("&>", "&>>"):
|
|
114
|
+
return True
|
|
115
|
+
return False
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _redirect_target_is_safe(target: str) -> bool:
|
|
119
|
+
"""True if the redirect target is safe (/dev/null, /dev/stderr) not a real file.
|
|
120
|
+
|
|
121
|
+
A redirect like ``>/dev/null`` or ``2>&1`` is harmless (sink or fd-duplication).
|
|
122
|
+
A redirect like ``>/etc/hosts`` or ``>>file.log`` is a file WRITE and makes
|
|
123
|
+
the command NOT read-only."""
|
|
124
|
+
if not target:
|
|
125
|
+
return True # self-contained redirect like 2>&1 has no target
|
|
126
|
+
if target in _SAFE_REDIRECT_TARGETS:
|
|
127
|
+
return True
|
|
128
|
+
return False
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _strip_redirections(tokens: list[str]) -> tuple[list[str], bool]:
|
|
132
|
+
"""Remove safe redirection tokens from a stage.
|
|
133
|
+
|
|
134
|
+
Returns (cleaned_tokens, has_file_redirect) where has_file_redirect is
|
|
135
|
+
True when ANY redirect in the stage targets a real file path (a write).
|
|
136
|
+
Callers must reject the stage when has_file_redirect is True.
|
|
137
|
+
"""
|
|
138
|
+
clean: list[str] = []
|
|
139
|
+
has_file_redirect = False
|
|
140
|
+
i = 0
|
|
141
|
+
while i < len(tokens):
|
|
142
|
+
tok = tokens[i]
|
|
143
|
+
if _is_redirect_token(tok):
|
|
144
|
+
i += 1
|
|
145
|
+
if _redirect_has_file_target(tok):
|
|
146
|
+
if i < len(tokens) and not _is_redirect_token(tokens[i]):
|
|
147
|
+
target = tokens[i]
|
|
148
|
+
if _redirect_target_is_safe(target):
|
|
149
|
+
i += 1 # skip safe target
|
|
150
|
+
else:
|
|
151
|
+
# Redirect to a real file = WRITE → reject
|
|
152
|
+
has_file_redirect = True
|
|
153
|
+
i += 1 # still skip (avoids treating /etc/hosts as an arg)
|
|
154
|
+
# else: no target token (redirect at end of command) — reject
|
|
155
|
+
else:
|
|
156
|
+
has_file_redirect = True
|
|
157
|
+
continue
|
|
158
|
+
clean.append(tok)
|
|
159
|
+
i += 1
|
|
160
|
+
return clean, has_file_redirect
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# ---------------------------------------------------------------------------
|
|
164
|
+
# Glued-operator detection: any token that contains | or ; as a substring
|
|
165
|
+
# but is NOT exactly that separator indicates a glued operator attack.
|
|
166
|
+
# "a|rm" passes shlex.split() as a single token and would otherwise be
|
|
167
|
+
# treated as a command name.
|
|
168
|
+
# ---------------------------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
def _token_has_glued_operator(tok: str) -> bool:
|
|
171
|
+
"""True if token contains | or ; as a glued-operator attack.
|
|
172
|
+
|
|
173
|
+
A glued operator is | or ; appearing INSIDE a longer token that is
|
|
174
|
+
NOT the standalone separator. Examples: a|rm, cat;evil.
|
|
175
|
+
|
|
176
|
+
Excludes:
|
|
177
|
+
- Tokens that ARE the separator (|, ;, |&, &&, ||).
|
|
178
|
+
- Tokens where | is inside [... or (... (character classes,
|
|
179
|
+
tr patterns, grep regex alternations) — these are not pipes.
|
|
180
|
+
"""
|
|
181
|
+
# The token IS the separator — not a glued attack.
|
|
182
|
+
if tok in _PIPELINE_SEPARATORS or tok == ";":
|
|
183
|
+
return False
|
|
184
|
+
for ch in _GLUED_OPERATOR_CHARS:
|
|
185
|
+
if ch in tok:
|
|
186
|
+
# | inside [...] (character class) or (... ) (regex alternation
|
|
187
|
+
# like grep -E '(passing|failing)') is not a pipe operator.
|
|
188
|
+
if ch == "|":
|
|
189
|
+
paren_open = None
|
|
190
|
+
paren_close = None
|
|
191
|
+
# Try brackets first.
|
|
192
|
+
if "[" in tok and "]" in tok:
|
|
193
|
+
paren_open = tok.index("[")
|
|
194
|
+
paren_close = tok.rindex("]")
|
|
195
|
+
# Then parentheses (but NOT $( — command sub screened earlier).
|
|
196
|
+
elif "(" in tok and ")" in tok:
|
|
197
|
+
paren_open = tok.index("(")
|
|
198
|
+
paren_close = tok.rindex(")")
|
|
199
|
+
if paren_open is not None and paren_close is not None:
|
|
200
|
+
pipe_pos = tok.index(ch)
|
|
201
|
+
if paren_open < pipe_pos < paren_close:
|
|
202
|
+
continue # | is inside grouping, not a pipe
|
|
203
|
+
return True
|
|
204
|
+
return False
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _split_stages(tokens: list[str]) -> list[list[str]]:
|
|
208
|
+
"""Split tokens into pipeline stages on separators (|, &&, ||, ;)."""
|
|
209
|
+
stages: list[list[str]] = []
|
|
210
|
+
current: list[str] = []
|
|
211
|
+
for tok in tokens:
|
|
212
|
+
if tok in _PIPELINE_SEPARATORS:
|
|
213
|
+
if current:
|
|
214
|
+
stages.append(current)
|
|
215
|
+
current = []
|
|
216
|
+
else:
|
|
217
|
+
current.append(tok)
|
|
218
|
+
if current:
|
|
219
|
+
stages.append(current)
|
|
220
|
+
return stages
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# ============================================================================
|
|
224
|
+
# Consolidated read-only command whitelist.
|
|
225
|
+
#
|
|
226
|
+
# SOURCE OF TRUTH for the base list: bash_hook._WHITELIST_SINGLE and
|
|
227
|
+
# bash_hook._WHITELIST_COMPOUND. When those lists are updated, this list
|
|
228
|
+
# should be updated too. Pipeline-consumer additions are marked with [P].
|
|
229
|
+
#
|
|
230
|
+
# POST-AUDIT HARDENING:
|
|
231
|
+
# REMOVED from _READ_ONLY_SINGLE: env, command, xargs, tee, awk,
|
|
232
|
+
# aws, gcloud, az (too broad / bypassable).
|
|
233
|
+
# REMOVED from _READ_ONLY_COMPOUND: npm run, terraform state, git config,
|
|
234
|
+
# kubectl config, docker pull, python -m (only known modules allowed).
|
|
235
|
+
# git: explicit ALLOW-list of read-only subcommands.
|
|
236
|
+
# find: rejected with -delete/-exec/-ok/-fprint/-fls.
|
|
237
|
+
# sqlite3: mutating keywords extended to include replace, vacuum, etc.
|
|
238
|
+
# git branch: -d/-D/--delete/-m/-M guarded.
|
|
239
|
+
# ============================================================================
|
|
240
|
+
|
|
241
|
+
# Commands eligible by name alone (any subcommand, as long as not excluded).
|
|
242
|
+
# Cloud CLIs (aws, gcloud, az) REMOVED — require explicit subcommand allow-list.
|
|
243
|
+
# env, command, xargs, tee, awk REMOVED — too broad, bypassable.
|
|
244
|
+
_READ_ONLY_SINGLE = frozenset({
|
|
245
|
+
# === From bash_hook._WHITELIST_SINGLE ===
|
|
246
|
+
"git", "pytest", "py.test", "jest", "vitest", "rspec", "ls", "find",
|
|
247
|
+
"eslint", "flake8", "pylint", "shellcheck", "rubocop",
|
|
248
|
+
"tail", "journalctl", "tree",
|
|
249
|
+
"tsc", "webpack", "esbuild",
|
|
250
|
+
"mocha", "karma", "tox", "nox", "ava", "gradle", "gradlew", "mvn",
|
|
251
|
+
"deno", "bun",
|
|
252
|
+
"sqlite3", "wc", "du", "df",
|
|
253
|
+
"jq", "yq", "csvtool", "mlr", "csvcut",
|
|
254
|
+
"grep", "rg", "ag", "ack",
|
|
255
|
+
# === [P] Pipeline consumers (read-only text filters) ===
|
|
256
|
+
"head", "sort", "uniq", "cut", "tr", "column",
|
|
257
|
+
"nl", "fmt", "fold", "paste", "join", "comm",
|
|
258
|
+
"sed",
|
|
259
|
+
# === [P] Additional read-only utilities safe in pipelines ===
|
|
260
|
+
"cat", "echo", "printf", "printenv",
|
|
261
|
+
"which", "type", "file", "stat",
|
|
262
|
+
"dirname", "basename", "realpath", "readlink",
|
|
263
|
+
"date", "id", "whoami", "hostname",
|
|
264
|
+
"pwd", "ps", "uptime", "uname",
|
|
265
|
+
"true", "false", "test", "[",
|
|
266
|
+
# === [P] Compression/decompression (read-only stdout) ===
|
|
267
|
+
"gzip", "gunzip", "bzip2", "bunzip2", "xz", "unxz",
|
|
268
|
+
"zcat", "bzcat", "xzcat",
|
|
269
|
+
# === [P] Network diagnostic tools (read-only output) ===
|
|
270
|
+
"ping", "traceroute", "nslookup", "dig", "host",
|
|
271
|
+
})
|
|
272
|
+
|
|
273
|
+
# Compound whitelist: (command, subcommand) pairs.
|
|
274
|
+
# POST-AUDIT REMOVED: ("npm","run"), ("pnpm","run"), ("yarn","run"),
|
|
275
|
+
# ("terraform","state"), ("git","config"), ("kubectl","config"),
|
|
276
|
+
# ("docker","pull"), ("python","-m"), ("python3","-m").
|
|
277
|
+
_READ_ONLY_COMPOUND = frozenset({
|
|
278
|
+
# === From bash_hook._WHITELIST_COMPOUND ===
|
|
279
|
+
("git", "status"), ("git", "log"), ("git", "diff"), ("git", "show"),
|
|
280
|
+
("git", "branch"), ("git", "blame"), ("git", "grep"),
|
|
281
|
+
("git", "ls-files"), ("git", "ls-tree"),
|
|
282
|
+
("git", "rev-parse"), ("git", "rev-list"),
|
|
283
|
+
("git", "describe"), ("git", "shortlog"),
|
|
284
|
+
("git", "stash"), ("git", "remote"),
|
|
285
|
+
("npx", "jest"), ("npx", "vitest"),
|
|
286
|
+
("npm", "test"),
|
|
287
|
+
("cargo", "test"),
|
|
288
|
+
("go", "test"),
|
|
289
|
+
("ruff", "check"),
|
|
290
|
+
("biome", "lint"),
|
|
291
|
+
("golangci-lint", "run"),
|
|
292
|
+
("pip", "list"), ("pip3", "list"),
|
|
293
|
+
("npm", "ls"),
|
|
294
|
+
("pnpm", "list"),
|
|
295
|
+
("docker", "ps"),
|
|
296
|
+
("brew", "list"),
|
|
297
|
+
("vite", "build"),
|
|
298
|
+
("next", "build"),
|
|
299
|
+
("go", "build"),
|
|
300
|
+
("cypress", "run"),
|
|
301
|
+
("playwright", "test"),
|
|
302
|
+
("npx", "cypress"),
|
|
303
|
+
("npx", "playwright"),
|
|
304
|
+
("npx", "mocha"),
|
|
305
|
+
("npx", "karma"),
|
|
306
|
+
("npx", "ava"),
|
|
307
|
+
("gradle", "test"),
|
|
308
|
+
("gradlew", "test"),
|
|
309
|
+
("mvn", "test"),
|
|
310
|
+
("deno", "test"),
|
|
311
|
+
("bun", "test"),
|
|
312
|
+
("docker", "logs"),
|
|
313
|
+
("docker", "inspect"),
|
|
314
|
+
("docker", "images"),
|
|
315
|
+
("docker", "info"),
|
|
316
|
+
("docker", "version"),
|
|
317
|
+
("docker", "compose"),
|
|
318
|
+
("kubectl", "get"),
|
|
319
|
+
("kubectl", "describe"),
|
|
320
|
+
("kubectl", "logs"),
|
|
321
|
+
("kubectl", "top"),
|
|
322
|
+
("kubectl", "events"),
|
|
323
|
+
("kubectl", "explain"),
|
|
324
|
+
("kubectl", "api-resources"),
|
|
325
|
+
("kubectl", "api-versions"),
|
|
326
|
+
("helm", "list"),
|
|
327
|
+
("helm", "status"),
|
|
328
|
+
("helm", "history"),
|
|
329
|
+
("helm", "get"),
|
|
330
|
+
("terraform", "plan"),
|
|
331
|
+
("terraform", "show"),
|
|
332
|
+
("terraform", "output"),
|
|
333
|
+
("yarn", "test"),
|
|
334
|
+
("make", "-n"),
|
|
335
|
+
("cargo", "check"),
|
|
336
|
+
})
|
|
337
|
+
|
|
338
|
+
# ============================================================================
|
|
339
|
+
# git: explicit ALLOW-list of read-only subcommands.
|
|
340
|
+
# Everything else (not in this list) is rejected as potentially side-effecting.
|
|
341
|
+
# ============================================================================
|
|
342
|
+
_GIT_READ_ONLY_SUBCMDS = frozenset({
|
|
343
|
+
"status", "log", "diff", "show", "branch",
|
|
344
|
+
"blame", "grep", "ls-files", "ls-tree",
|
|
345
|
+
"rev-parse", "rev-list", "describe", "shortlog",
|
|
346
|
+
"stash", "remote",
|
|
347
|
+
})
|
|
348
|
+
|
|
349
|
+
# git branch destructive flags. Covers delete (-d/-D/--delete), rename
|
|
350
|
+
# (-m/-M/--move) and copy (-c/-C/--copy, which are copy/force-copy, not
|
|
351
|
+
# "create"). All are state-changing and must not pass the read-only gate.
|
|
352
|
+
#
|
|
353
|
+
# M-14: -f/--force is NOT in this set. `git branch -f <branchname>
|
|
354
|
+
# <startpoint>` is a legitimate non-destructive operation (force-create/
|
|
355
|
+
# reset a branch pointer). -f only forces a destructive operation when
|
|
356
|
+
# combined with -d/-D/-m/-M/-c/-C (e.g. `git branch -Df`), and those
|
|
357
|
+
# combined forms are caught by the short-flag expansion check below.
|
|
358
|
+
_GIT_BRANCH_DESTRUCTIVE_FLAGS = frozenset({
|
|
359
|
+
"-d", "-D", "--delete",
|
|
360
|
+
"-m", "-M", "--move",
|
|
361
|
+
"-c", "-C", "--copy",
|
|
362
|
+
})
|
|
363
|
+
|
|
364
|
+
# H-3: destructive short-flag characters for combined-flag expansion. Git
|
|
365
|
+
# allows bundling short flags: `git branch -Df` = -D + -f. The token "-Df"
|
|
366
|
+
# is NOT in the frozenset above, so the exact-match check bypasses it. For
|
|
367
|
+
# any token starting with a single dash (not --) with len > 2, check if
|
|
368
|
+
# any character after the dash is in this set. -f is deliberately excluded
|
|
369
|
+
# (M-14): -f alone is non-destructive, and -f combined with a destructive
|
|
370
|
+
# flag is caught by the destructive character in the same token.
|
|
371
|
+
_GIT_BRANCH_DESTRUCTIVE_SHORT_CHARS = frozenset({"d", "D", "m", "M", "c", "C"})
|
|
372
|
+
|
|
373
|
+
# find destructive flags.
|
|
374
|
+
_FIND_DESTRUCTIVE_FLAGS = frozenset({"-delete", "-exec", "-execdir", "-ok", "-okdir",
|
|
375
|
+
"-fprint", "-fprint0", "-fls"})
|
|
376
|
+
|
|
377
|
+
# ============================================================================
|
|
378
|
+
# Never-read-only: shell interpreters, privilege escalation, arbitrary code.
|
|
379
|
+
# ============================================================================
|
|
380
|
+
_NEVER_READ_ONLY = frozenset({
|
|
381
|
+
"bash", "sh", "zsh", "dash", "fish", "ksh",
|
|
382
|
+
"sudo", "su", "doas", "pkexec",
|
|
383
|
+
"python", "python3", "python2",
|
|
384
|
+
"node",
|
|
385
|
+
"ruby", "perl", "php", "lua",
|
|
386
|
+
"eval", "exec", "source",
|
|
387
|
+
"env", # env can launch arbitrary commands
|
|
388
|
+
"command", # command can launch arbitrary commands
|
|
389
|
+
"xargs", # xargs can launch arbitrary commands
|
|
390
|
+
})
|
|
391
|
+
|
|
392
|
+
# python -m modules that are known read-only.
|
|
393
|
+
_PYTHON_M_SAFE_MODULES = frozenset({"pytest", "unittest", "json.tool"})
|
|
394
|
+
|
|
395
|
+
# sqlite3 mutation keywords (case-insensitive check).
|
|
396
|
+
_SQLITE3_MUTATION_KEYWORDS = frozenset({
|
|
397
|
+
"insert", "update", "delete", "drop", "alter", "create",
|
|
398
|
+
"replace", "vacuum", "pragma",
|
|
399
|
+
})
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _is_stage_read_only(tokens: list[str]) -> tuple[bool, str]:
|
|
403
|
+
"""Check if a single pipeline stage is read-only.
|
|
404
|
+
|
|
405
|
+
Args:
|
|
406
|
+
tokens: The shlex-split tokens for this stage, with redirections
|
|
407
|
+
already stripped.
|
|
408
|
+
|
|
409
|
+
Returns:
|
|
410
|
+
(is_read_only, reason) — reason is a short string for diagnostics.
|
|
411
|
+
"""
|
|
412
|
+
if not tokens:
|
|
413
|
+
return False, "empty-stage"
|
|
414
|
+
|
|
415
|
+
# Strip leading env var assignments (FOO=bar)
|
|
416
|
+
cmd_start = 0
|
|
417
|
+
while cmd_start < len(tokens) and "=" in tokens[cmd_start] and not tokens[cmd_start].startswith("-"):
|
|
418
|
+
cmd_start += 1
|
|
419
|
+
|
|
420
|
+
if cmd_start >= len(tokens):
|
|
421
|
+
return False, "env-only-stage"
|
|
422
|
+
|
|
423
|
+
cmd = tokens[cmd_start]
|
|
424
|
+
subcmd = tokens[cmd_start + 1] if cmd_start + 1 < len(tokens) else ""
|
|
425
|
+
remaining = tokens[cmd_start + 2:]
|
|
426
|
+
|
|
427
|
+
# Hard block: interpreters, privilege escalation, and broad launchers.
|
|
428
|
+
if cmd in _NEVER_READ_ONLY:
|
|
429
|
+
if cmd in ("python", "python3", "python2"):
|
|
430
|
+
if subcmd == "-m" and cmd_start + 2 < len(tokens):
|
|
431
|
+
module = tokens[cmd_start + 2]
|
|
432
|
+
if module in _PYTHON_M_SAFE_MODULES:
|
|
433
|
+
return True, "python-m-whitelisted-module"
|
|
434
|
+
return False, "python-not-whitelisted"
|
|
435
|
+
if cmd == "node":
|
|
436
|
+
if subcmd == "-e":
|
|
437
|
+
return False, "node-e-arbitrary-code"
|
|
438
|
+
remaining_for_node = tokens[cmd_start + 1:]
|
|
439
|
+
if any(arg.endswith(".json") or ".json" in arg for arg in remaining_for_node):
|
|
440
|
+
return True, "node-json-inspection"
|
|
441
|
+
return False, "node-not-whitelisted"
|
|
442
|
+
return False, f"never-read-only:{cmd}"
|
|
443
|
+
|
|
444
|
+
# -------------------------------------------------------------------
|
|
445
|
+
# git: explicit ALLOW-list (not deny-list).
|
|
446
|
+
# -------------------------------------------------------------------
|
|
447
|
+
if cmd == "git":
|
|
448
|
+
if not subcmd:
|
|
449
|
+
return False, "git-no-subcmd"
|
|
450
|
+
if subcmd not in _GIT_READ_ONLY_SUBCMDS:
|
|
451
|
+
return False, f"git-forbidden-subcmd:{subcmd}"
|
|
452
|
+
# Special guard: git branch with destructive flags.
|
|
453
|
+
if subcmd == "branch":
|
|
454
|
+
for tok in remaining:
|
|
455
|
+
# Exact match against long flags and single short flags.
|
|
456
|
+
if tok in _GIT_BRANCH_DESTRUCTIVE_FLAGS:
|
|
457
|
+
return False, f"git-branch-destructive-flag:{tok}"
|
|
458
|
+
# H-3: expand combined short flags. Git allows bundling:
|
|
459
|
+
# `git branch -Df` = -D + -f. The token "-Df" is not in
|
|
460
|
+
# the frozenset, so the exact-match check above bypasses
|
|
461
|
+
# it. For any single-dash token with len > 2, check if any
|
|
462
|
+
# character after the dash is a destructive short flag.
|
|
463
|
+
if (len(tok) > 2 and tok.startswith("-")
|
|
464
|
+
and not tok.startswith("--")):
|
|
465
|
+
for ch in tok[1:]:
|
|
466
|
+
if ch in _GIT_BRANCH_DESTRUCTIVE_SHORT_CHARS:
|
|
467
|
+
return False, f"git-branch-destructive-flag:{tok}"
|
|
468
|
+
return True, "git-read-only"
|
|
469
|
+
|
|
470
|
+
# -------------------------------------------------------------------
|
|
471
|
+
# find: reject if destructive flags present.
|
|
472
|
+
# -------------------------------------------------------------------
|
|
473
|
+
if cmd == "find":
|
|
474
|
+
all_tokens = tokens[cmd_start:]
|
|
475
|
+
for tok in all_tokens:
|
|
476
|
+
if tok in _FIND_DESTRUCTIVE_FLAGS:
|
|
477
|
+
return False, f"find-destructive-flag:{tok}"
|
|
478
|
+
return True, "find-read-only"
|
|
479
|
+
|
|
480
|
+
# -------------------------------------------------------------------
|
|
481
|
+
# sqlite3: extended mutation keyword blocklist.
|
|
482
|
+
# -------------------------------------------------------------------
|
|
483
|
+
if cmd == "sqlite3":
|
|
484
|
+
all_tokens = tokens[cmd_start:]
|
|
485
|
+
tokens_lower = [t.lower() for t in all_tokens]
|
|
486
|
+
# Check each token for mutation keywords (substring match).
|
|
487
|
+
for t in tokens_lower:
|
|
488
|
+
for kw in _SQLITE3_MUTATION_KEYWORDS:
|
|
489
|
+
if kw in t:
|
|
490
|
+
return False, f"sqlite3-mutation:{kw}"
|
|
491
|
+
# Dot-commands: .import, .restore are writes.
|
|
492
|
+
if t in (".import", ".restore"):
|
|
493
|
+
return False, f"sqlite3-dotcmd-write:{t}"
|
|
494
|
+
return True, "sqlite3-read-only"
|
|
495
|
+
|
|
496
|
+
# -------------------------------------------------------------------
|
|
497
|
+
# sed: -i is in-place edit.
|
|
498
|
+
# -------------------------------------------------------------------
|
|
499
|
+
if cmd == "sed":
|
|
500
|
+
# Scan all arguments after the command (including subcmd/index-1).
|
|
501
|
+
sed_args = tokens[cmd_start + 1:]
|
|
502
|
+
for arg in sed_args:
|
|
503
|
+
if arg == "-i" or (arg.startswith("-") and "i" in arg.replace("-", "")):
|
|
504
|
+
return False, "sed-in-place"
|
|
505
|
+
return True, "sed-read-only"
|
|
506
|
+
|
|
507
|
+
# -------------------------------------------------------------------
|
|
508
|
+
# deno / bun: only allow known safe subcommands.
|
|
509
|
+
# "deno test" and "bun test" are in compound. Anything else: reject.
|
|
510
|
+
# "deno run -A evil.ts" would not match compound → falls through to
|
|
511
|
+
# single check → only "test" subcmd allowed.
|
|
512
|
+
# -------------------------------------------------------------------
|
|
513
|
+
if cmd in ("deno", "bun"):
|
|
514
|
+
if subcmd != "test":
|
|
515
|
+
return False, f"{cmd}-forbidden-subcmd:{subcmd}"
|
|
516
|
+
return True, f"{cmd}-test-only"
|
|
517
|
+
|
|
518
|
+
# -------------------------------------------------------------------
|
|
519
|
+
# mvn: only "test" subcmd. "mvn deploy" rejected.
|
|
520
|
+
# -------------------------------------------------------------------
|
|
521
|
+
if cmd == "mvn":
|
|
522
|
+
if subcmd != "test":
|
|
523
|
+
return False, f"mvn-forbidden-subcmd:{subcmd}"
|
|
524
|
+
return True, "mvn-test-only"
|
|
525
|
+
|
|
526
|
+
# -------------------------------------------------------------------
|
|
527
|
+
# sqlite3 already handled above. Return here only for compound match
|
|
528
|
+
# before single-whitelist fallthrough.
|
|
529
|
+
# -------------------------------------------------------------------
|
|
530
|
+
|
|
531
|
+
# -------------------------------------------------------------------
|
|
532
|
+
# Compound whitelist check.
|
|
533
|
+
# -------------------------------------------------------------------
|
|
534
|
+
if (cmd, subcmd) in _READ_ONLY_COMPOUND:
|
|
535
|
+
# kubectl: secrets exclusion.
|
|
536
|
+
if cmd == "kubectl":
|
|
537
|
+
if any(arg in ("secret", "secrets") or arg.startswith(("secret/", "secrets/")) for arg in remaining):
|
|
538
|
+
return False, "kubectl-secrets"
|
|
539
|
+
# docker compose: sub-subcommand check.
|
|
540
|
+
if cmd == "docker" and subcmd == "compose":
|
|
541
|
+
subsub = tokens[cmd_start + 2] if cmd_start + 2 < len(tokens) else ""
|
|
542
|
+
if subsub in ("ps", "logs", "config", "images", "version", "top", "events"):
|
|
543
|
+
return True, "docker-compose-read-only"
|
|
544
|
+
if subsub in ("up", "down", "build", "run", "exec", "pull", "push", "restart", "start", "stop", "rm"):
|
|
545
|
+
return False, "docker-compose-side-effect"
|
|
546
|
+
return False, "docker-compose-unknown"
|
|
547
|
+
return True, "compound-whitelist"
|
|
548
|
+
|
|
549
|
+
# -------------------------------------------------------------------
|
|
550
|
+
# Single command whitelist.
|
|
551
|
+
# -------------------------------------------------------------------
|
|
552
|
+
if cmd in _READ_ONLY_SINGLE:
|
|
553
|
+
return True, "single-whitelist"
|
|
554
|
+
|
|
555
|
+
# Not in any whitelist.
|
|
556
|
+
return False, f"not-whitelisted:{cmd}"
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
# ============================================================================
|
|
560
|
+
# Main entry points
|
|
561
|
+
# ============================================================================
|
|
562
|
+
|
|
563
|
+
def _raw_command_has_dangerous_constructs(command_str: str) -> tuple[bool, str]:
|
|
564
|
+
"""Check the raw command string for constructs shlex is blind to.
|
|
565
|
+
|
|
566
|
+
Must run BEFORE shlex.split() to catch injection payloads embedded in
|
|
567
|
+
whitespace, command substitution, process substitution, and background/async.
|
|
568
|
+
|
|
569
|
+
Returns (has_dangerous, reason).
|
|
570
|
+
"""
|
|
571
|
+
# Newlines indicate injection payloads split across lines.
|
|
572
|
+
if _DANGEROUS_RAW_CHARS.search(command_str):
|
|
573
|
+
return True, "contains-newline-injection"
|
|
574
|
+
|
|
575
|
+
# Command substitution: $() and backticks.
|
|
576
|
+
if _DANGEROUS_SUBSTITUTION.search(command_str):
|
|
577
|
+
return True, "contains-command-substitution"
|
|
578
|
+
|
|
579
|
+
# Process substitution: <() and >().
|
|
580
|
+
if _DANGEROUS_PROCESS_SUBST.search(command_str):
|
|
581
|
+
return True, "contains-process-substitution"
|
|
582
|
+
|
|
583
|
+
return False, "clean"
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def is_read_only_pipeline(command_str: str) -> tuple[bool, str]:
|
|
587
|
+
"""Check if a shell command is read-only in all pipeline stages.
|
|
588
|
+
|
|
589
|
+
Args:
|
|
590
|
+
command_str: The raw shell command string from tool_input.command.
|
|
591
|
+
|
|
592
|
+
Returns:
|
|
593
|
+
(is_read_only, reason) tuple. When is_read_only is True, the
|
|
594
|
+
command is safe for output compression. When False, `reason`
|
|
595
|
+
provides a short diagnostic.
|
|
596
|
+
"""
|
|
597
|
+
if not command_str or not isinstance(command_str, str):
|
|
598
|
+
return False, "empty-or-non-string"
|
|
599
|
+
|
|
600
|
+
if command_str.strip() == "":
|
|
601
|
+
return False, "whitespace-only"
|
|
602
|
+
|
|
603
|
+
# --- PRE-TOKENIZATION SCREEN ---
|
|
604
|
+
# Reject raw strings with injection constructs shlex is blind to.
|
|
605
|
+
has_danger, reason = _raw_command_has_dangerous_constructs(command_str)
|
|
606
|
+
if has_danger:
|
|
607
|
+
return False, reason
|
|
608
|
+
|
|
609
|
+
# Parse the command into tokens.
|
|
610
|
+
try:
|
|
611
|
+
tokens = shlex.split(command_str, comments=True)
|
|
612
|
+
except ValueError:
|
|
613
|
+
return False, "unparseable-quoting"
|
|
614
|
+
|
|
615
|
+
if not tokens:
|
|
616
|
+
return False, "empty-after-split"
|
|
617
|
+
|
|
618
|
+
# --- TOKEN-LEVEL SCREEN ---
|
|
619
|
+
# Reject glued operators (a|b, cat;rm) where | or ; appears inside a token
|
|
620
|
+
# but is not the standalone separator token.
|
|
621
|
+
for tok in tokens:
|
|
622
|
+
if _token_has_glued_operator(tok):
|
|
623
|
+
return False, f"glued-operator-in-token:{tok}"
|
|
624
|
+
# Also reject bare & (async/background) — not part of &&, >&, &>.
|
|
625
|
+
if tok == "&":
|
|
626
|
+
return False, "bare-ampersand-async"
|
|
627
|
+
|
|
628
|
+
# Split into stages.
|
|
629
|
+
stages = _split_stages(tokens)
|
|
630
|
+
if not stages:
|
|
631
|
+
return False, "no-stages"
|
|
632
|
+
|
|
633
|
+
# Check each stage.
|
|
634
|
+
for i, stage_tokens in enumerate(stages):
|
|
635
|
+
clean, has_file_redirect = _strip_redirections(stage_tokens)
|
|
636
|
+
if has_file_redirect:
|
|
637
|
+
return False, f"stage-{i + 1}:file-redirect-write"
|
|
638
|
+
if not clean:
|
|
639
|
+
continue # empty after redirection stripping (all redirections)
|
|
640
|
+
ok, reason = _is_stage_read_only(clean)
|
|
641
|
+
if not ok:
|
|
642
|
+
return False, f"stage-{i + 1}:{reason}"
|
|
643
|
+
|
|
644
|
+
return True, "all-stages-read-only"
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def get_pipeline_eligibility(command_str: str) -> dict:
|
|
648
|
+
"""Diagnostic function: return detailed eligibility information."""
|
|
649
|
+
result: dict = {
|
|
650
|
+
"is_eligible": False,
|
|
651
|
+
"reason": "",
|
|
652
|
+
"stage_count": 0,
|
|
653
|
+
"stages": [],
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
if not command_str or command_str.strip() == "":
|
|
657
|
+
result["reason"] = "empty"
|
|
658
|
+
return result
|
|
659
|
+
|
|
660
|
+
# Pre-tokenization screen.
|
|
661
|
+
has_danger, danger_reason = _raw_command_has_dangerous_constructs(command_str)
|
|
662
|
+
if has_danger:
|
|
663
|
+
result["reason"] = danger_reason
|
|
664
|
+
return result
|
|
665
|
+
|
|
666
|
+
try:
|
|
667
|
+
tokens = shlex.split(command_str, comments=True)
|
|
668
|
+
except ValueError:
|
|
669
|
+
result["reason"] = "unparseable"
|
|
670
|
+
return result
|
|
671
|
+
|
|
672
|
+
if not tokens:
|
|
673
|
+
result["reason"] = "empty-after-split"
|
|
674
|
+
return result
|
|
675
|
+
|
|
676
|
+
# Token-level screen.
|
|
677
|
+
for tok in tokens:
|
|
678
|
+
if _token_has_glued_operator(tok):
|
|
679
|
+
result["reason"] = f"glued-operator-in-token:{tok}"
|
|
680
|
+
return result
|
|
681
|
+
if tok == "&":
|
|
682
|
+
result["reason"] = "bare-ampersand-async"
|
|
683
|
+
return result
|
|
684
|
+
|
|
685
|
+
stages = _split_stages(tokens)
|
|
686
|
+
result["stage_count"] = len(stages)
|
|
687
|
+
|
|
688
|
+
all_read_only = True
|
|
689
|
+
for i, stage_tokens in enumerate(stages):
|
|
690
|
+
clean, has_file_redirect = _strip_redirections(stage_tokens)
|
|
691
|
+
stage_info = {
|
|
692
|
+
"index": i,
|
|
693
|
+
"raw_tokens": stage_tokens,
|
|
694
|
+
"cleaned_tokens": clean,
|
|
695
|
+
"is_read_only": True,
|
|
696
|
+
"reason": "",
|
|
697
|
+
}
|
|
698
|
+
if has_file_redirect:
|
|
699
|
+
stage_info["is_read_only"] = False
|
|
700
|
+
stage_info["reason"] = "file-redirect-write"
|
|
701
|
+
all_read_only = False
|
|
702
|
+
elif not clean:
|
|
703
|
+
stage_info["is_read_only"] = True
|
|
704
|
+
stage_info["reason"] = "empty-after-redirect-strip"
|
|
705
|
+
else:
|
|
706
|
+
ok, reason = _is_stage_read_only(clean)
|
|
707
|
+
stage_info["is_read_only"] = ok
|
|
708
|
+
stage_info["reason"] = reason
|
|
709
|
+
if not ok:
|
|
710
|
+
all_read_only = False
|
|
711
|
+
|
|
712
|
+
result["stages"].append(stage_info)
|
|
713
|
+
|
|
714
|
+
if all_read_only:
|
|
715
|
+
result["is_eligible"] = True
|
|
716
|
+
result["reason"] = "all-stages-read-only"
|
|
717
|
+
else:
|
|
718
|
+
for s in result["stages"]:
|
|
719
|
+
if not s["is_read_only"]:
|
|
720
|
+
result["reason"] = f"stage-{s['index'] + 1}:{s['reason']}"
|
|
721
|
+
break
|
|
722
|
+
|
|
723
|
+
return result
|