tokensafe 2.7.0 → 2.7.2
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/bin/tokensafe +1 -1
- package/extensions/cursor-tokensafe/extension.js +21 -8
- package/hooks/claude_code_hook.py +13 -5
- package/hooks/cursor_hook.py +7 -4
- package/hooks/post_tool_use.py +24 -6
- package/hooks/pre_invocation.py +40 -27
- package/hooks/pre_tool_use.py +85 -83
- package/hooks/session_start.py +8 -4
- package/hooks/stop_hook.py +7 -4
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/agent_firewall.py +38 -21
- package/src/cache_normalizer.py +39 -10
- package/src/cli.py +139 -83
- package/src/command_sanitizer.py +248 -136
- package/src/compactor.py +55 -25
- package/src/dashboard.py +17 -10
- package/src/deepseek_distiller.py +26 -17
- package/src/dependency_prefetcher.py +65 -40
- package/src/diff_slicer.py +23 -17
- package/src/distiller.py +45 -17
- package/src/distiller_cache.py +80 -48
- package/src/environment_auditor.py +34 -12
- package/src/governor.py +83 -26
- package/src/graph_engine.py +1 -1
- package/src/guard.py +316 -132
- package/src/history_compactor.py +57 -26
- package/src/installer.py +174 -131
- package/src/license_manager.py +12 -9
- package/src/loop_detector.py +68 -29
- package/src/mcp_server.py +206 -65
- package/src/metrics.py +141 -54
- package/src/paths.py +32 -6
- package/src/proxy.py +121 -52
- package/src/scoped_search.py +18 -6
- package/src/secret_redactor.py +78 -59
- package/src/slicer.py +15 -3
- package/src/team_cache.py +89 -16
- package/src/telemetry_sync.py +110 -39
- package/src/tokenizer.py +24 -13
- package/src/treesitter_backend.py +1 -0
- package/src/version_checker.py +67 -32
- package/src/weekly_digest.py +6 -3
package/src/command_sanitizer.py
CHANGED
|
@@ -12,6 +12,7 @@ excludes landing on `npm test` after `git diff && npm test`).
|
|
|
12
12
|
import json
|
|
13
13
|
import os
|
|
14
14
|
import re
|
|
15
|
+
import shlex
|
|
15
16
|
from typing import Tuple, Dict, Any, List, Optional
|
|
16
17
|
|
|
17
18
|
class CommandSanitizer:
|
|
@@ -24,12 +25,9 @@ class CommandSanitizer:
|
|
|
24
25
|
_VITEST_RE = re.compile(r"^\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+)?(?:npx\s+|yarn\s+|pnpm\s+|bunx\s+)?vitest(?:\s|$)")
|
|
25
26
|
_JEST_RE = re.compile(r"^\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+)?(?:npx\s+|yarn\s+|pnpm\s+|bunx\s+)?jest(?:\s|$)")
|
|
26
27
|
_JEST_SCRIPT_RE = re.compile(r"\b(?:react-scripts|craco)\s+test\b")
|
|
27
|
-
_PKG_MANAGER_TEST_RE = re.compile(r"\b(?:yarn|npm|pnpm|bun)\s+(?:run\s+)?test\b")
|
|
28
28
|
# Jest-only flags positively fingerprint jest behind an opaque test script
|
|
29
29
|
_JEST_FINGERPRINT_RE = re.compile(r"--watchAll|--detectOpenHandles|--testPathPattern|--testMatch|--runInBand")
|
|
30
30
|
_BARE_WATCH_RE = re.compile(r"\s--watch(?=[\s]|$)")
|
|
31
|
-
_NPM_TEST_RE = re.compile(r"\bnpm\s+(?:run\s+)?test[\w:./-]*")
|
|
32
|
-
_CD_RE = re.compile(r'^\s*cd\s+(["\']?)(.+?)\1\s*$')
|
|
33
31
|
|
|
34
32
|
# Lockfiles and binary patterns that should never be dumped in git diffs or searches
|
|
35
33
|
LOCKFILE_EXCLUDES = [
|
|
@@ -55,8 +53,25 @@ class CommandSanitizer:
|
|
|
55
53
|
r"|.*\.min\.js|.*\.min\.css|.*\.bundle\.js|.*\.map)$"
|
|
56
54
|
)
|
|
57
55
|
|
|
58
|
-
# Output limiters that make an extra `| head`
|
|
59
|
-
_LIMITER_RE = re.compile(
|
|
56
|
+
# Output limiters at command position that make an extra `| head` redundant
|
|
57
|
+
_LIMITER_RE = re.compile(
|
|
58
|
+
r"^(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+|env\s+)?(?:head|tail|less|wc|jq)\b"
|
|
59
|
+
)
|
|
60
|
+
_GIT_REF_RE = re.compile(
|
|
61
|
+
r"^(?:HEAD(?:[~^]\d*)*|main|master|origin/[\w./-]+|[0-9a-f]{7,40}|[\w./-]+(?:\.\.\.?|@\{)[\w./@-]*|v?\d+\.\d+(?:\.\d+)*)$"
|
|
62
|
+
)
|
|
63
|
+
_FD_DUP_RE = re.compile(r"(?:^|\s)[0-9]*>&[0-9-]+(?=\s|$)")
|
|
64
|
+
_FILE_REDIRECT_RE = re.compile(r"(?:^|\s)(?:[0-9]*>{1,2}|&>{1,2})")
|
|
65
|
+
_PRECOMPILED_QUOTED_RE = re.compile(r"""'(?:[^']*)'|"(?:\\.|[^"\\])*"|`(?:[^`]*)`""")
|
|
66
|
+
_ENV_PREFIX_RE = re.compile(r"""^\s*(?:[A-Za-z_]\w*=(?:"(?:\\.|[^"\\])*"|'[^']*'|\S*)\s+|sudo\s+|env\s+)*""")
|
|
67
|
+
_SUBSHELL_WRAP_RE = re.compile(r"^\s*[\(\{].*[\)\}]\s*$")
|
|
68
|
+
_GIT_DIFF_LIMIT_RE = re.compile(r"(?:\s-[0-9]+|\s-n\s*\d+|\s--max-count[=\s]\d+)")
|
|
69
|
+
_GIT_SHOW_SHORT_RE = re.compile(r"--stat|--name-only|--name-status|\s-s\b|--oneline")
|
|
70
|
+
_CURL_FILE_RE = re.compile(r"-o\s|-O\b|--output|-F\b|--form|-T\b|--upload-file|-I\b|--head")
|
|
71
|
+
_LS_VERBOSE_RE = re.compile(r"\bls\s+-[lah1pF]*(?:l|a)[lah1pF]*(?=\s|$)")
|
|
72
|
+
_PKG_MANAGER_TEST_RE = re.compile(r"\b(?:yarn|npm|pnpm|bun)\s+(?:run\s+)?test(?:[:_-][\w.-]+)?\b")
|
|
73
|
+
_NPM_TEST_RE = re.compile(r"\bnpm\s+(?:run\s+)?test[\w:./-]*")
|
|
74
|
+
_CD_RE = re.compile(r'^\s*(?:cd|pushd)\s+(?:--\s+)?(["\']?)(.+?)\1\s*$')
|
|
60
75
|
|
|
61
76
|
# (unit, limit) specs for end-of-command output caps
|
|
62
77
|
_CAP_LINES_30 = ("n", 30)
|
|
@@ -66,14 +81,15 @@ class CommandSanitizer:
|
|
|
66
81
|
@staticmethod
|
|
67
82
|
def split_stages(cmd: str) -> List[Tuple[str, str]]:
|
|
68
83
|
"""
|
|
69
|
-
Quote-aware split of a shell command into
|
|
70
|
-
Operators: ''
|
|
71
|
-
rejoining with join_stages() yields an equivalent command line.
|
|
84
|
+
Quote-, escape-, and subshell-aware split of a shell command into
|
|
85
|
+
(operator, stage) pairs. Operators: '', '|', '||', '&&', ';', '\\n'.
|
|
72
86
|
"""
|
|
73
87
|
pairs: List[Tuple[str, str]] = []
|
|
74
88
|
buf: List[str] = []
|
|
75
89
|
quote = ""
|
|
76
|
-
|
|
90
|
+
paren_depth = 0
|
|
91
|
+
brace_depth = 0
|
|
92
|
+
pending_op = ""
|
|
77
93
|
i = 0
|
|
78
94
|
n = len(cmd)
|
|
79
95
|
|
|
@@ -85,7 +101,8 @@ class CommandSanitizer:
|
|
|
85
101
|
while i < n:
|
|
86
102
|
ch = cmd[i]
|
|
87
103
|
if quote:
|
|
88
|
-
|
|
104
|
+
# In POSIX shells, backslash only escapes inside "..." (not inside '...')
|
|
105
|
+
if ch == "\\" and quote == '"' and i + 1 < n:
|
|
89
106
|
buf.append(ch)
|
|
90
107
|
buf.append(cmd[i + 1])
|
|
91
108
|
i += 2
|
|
@@ -93,30 +110,66 @@ class CommandSanitizer:
|
|
|
93
110
|
if ch == quote:
|
|
94
111
|
quote = ""
|
|
95
112
|
buf.append(ch)
|
|
96
|
-
|
|
97
|
-
|
|
113
|
+
i += 1
|
|
114
|
+
continue
|
|
115
|
+
|
|
116
|
+
if ch == "\\" and i + 1 < n:
|
|
98
117
|
buf.append(ch)
|
|
99
|
-
|
|
100
|
-
flush()
|
|
101
|
-
pending_op = "&&"
|
|
118
|
+
buf.append(cmd[i + 1])
|
|
102
119
|
i += 2
|
|
103
120
|
continue
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
i +=
|
|
121
|
+
if ch in ("'", '"', "`"):
|
|
122
|
+
quote = ch
|
|
123
|
+
buf.append(ch)
|
|
124
|
+
i += 1
|
|
108
125
|
continue
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
126
|
+
if ch == "(":
|
|
127
|
+
paren_depth += 1
|
|
128
|
+
buf.append(ch)
|
|
129
|
+
i += 1
|
|
130
|
+
continue
|
|
131
|
+
if ch == ")" and paren_depth > 0:
|
|
132
|
+
paren_depth -= 1
|
|
116
133
|
buf.append(ch)
|
|
134
|
+
i += 1
|
|
135
|
+
continue
|
|
136
|
+
if ch == "{" and (i == 0 or cmd[i - 1].isspace()):
|
|
137
|
+
brace_depth += 1
|
|
138
|
+
buf.append(ch)
|
|
139
|
+
i += 1
|
|
140
|
+
continue
|
|
141
|
+
if ch == "}" and brace_depth > 0:
|
|
142
|
+
brace_depth -= 1
|
|
143
|
+
buf.append(ch)
|
|
144
|
+
i += 1
|
|
145
|
+
continue
|
|
146
|
+
|
|
147
|
+
if paren_depth == 0 and brace_depth == 0:
|
|
148
|
+
if ch == "&" and i + 1 < n and cmd[i + 1] == "&":
|
|
149
|
+
flush()
|
|
150
|
+
pending_op = "&&"
|
|
151
|
+
i += 2
|
|
152
|
+
continue
|
|
153
|
+
if ch == "|" and i + 1 < n and cmd[i + 1] == "|":
|
|
154
|
+
flush()
|
|
155
|
+
pending_op = "||"
|
|
156
|
+
i += 2
|
|
157
|
+
continue
|
|
158
|
+
if ch == "|":
|
|
159
|
+
flush()
|
|
160
|
+
pending_op = "|"
|
|
161
|
+
i += 1
|
|
162
|
+
continue
|
|
163
|
+
if ch in (";", "\n"):
|
|
164
|
+
flush()
|
|
165
|
+
pending_op = ch
|
|
166
|
+
i += 1
|
|
167
|
+
continue
|
|
168
|
+
|
|
169
|
+
buf.append(ch)
|
|
117
170
|
i += 1
|
|
171
|
+
|
|
118
172
|
flush()
|
|
119
|
-
# Drop empty stages but keep at least one slot so rejoin stays valid
|
|
120
173
|
cleaned = [(op, s) for op, s in pairs if s]
|
|
121
174
|
if not cleaned:
|
|
122
175
|
cleaned = [("", "")]
|
|
@@ -129,6 +182,8 @@ class CommandSanitizer:
|
|
|
129
182
|
for op, stage in pairs:
|
|
130
183
|
if not out:
|
|
131
184
|
out = stage
|
|
185
|
+
elif op == "\n":
|
|
186
|
+
out += f"\n{stage}"
|
|
132
187
|
elif op == "|":
|
|
133
188
|
out += f" | {stage}"
|
|
134
189
|
else:
|
|
@@ -161,137 +216,184 @@ class CommandSanitizer:
|
|
|
161
216
|
stages.append(stage)
|
|
162
217
|
return [s for s in (st.strip() for st in stages) if s]
|
|
163
218
|
|
|
164
|
-
@
|
|
165
|
-
def _has_redirect(stage: str) -> bool:
|
|
166
|
-
"""True if the stage redirects stdout
|
|
167
|
-
|
|
219
|
+
@classmethod
|
|
220
|
+
def _has_redirect(cls, stage: str) -> bool:
|
|
221
|
+
"""True if the stage redirects stdout to a file/stream (ignoring 2>&1 merges and quoted '>')."""
|
|
222
|
+
unquoted = cls._PRECOMPILED_QUOTED_RE.sub(" ", stage)
|
|
223
|
+
without_fd_dups = cls._FD_DUP_RE.sub(" ", unquoted)
|
|
224
|
+
return bool(cls._FILE_REDIRECT_RE.search(without_fd_dups))
|
|
225
|
+
|
|
226
|
+
@classmethod
|
|
227
|
+
def _strip_cmd_prefix(cls, stage: str) -> str:
|
|
228
|
+
return cls._ENV_PREFIX_RE.sub("", stage.lstrip())
|
|
229
|
+
|
|
230
|
+
@classmethod
|
|
231
|
+
def _split_tokens_safe(cls, stage: str) -> List[str]:
|
|
232
|
+
try:
|
|
233
|
+
return shlex.split(stage)
|
|
234
|
+
except ValueError:
|
|
235
|
+
return stage.split()
|
|
236
|
+
|
|
237
|
+
@classmethod
|
|
238
|
+
def _primary_cmd_and_args(cls, stage: str) -> Tuple[str, List[str]]:
|
|
239
|
+
tokens = cls._split_tokens_safe(stage)
|
|
240
|
+
idx = 0
|
|
241
|
+
while idx < len(tokens):
|
|
242
|
+
tok = tokens[idx]
|
|
243
|
+
if tok in ("sudo", "env", "command", "time", "nohup"):
|
|
244
|
+
idx += 1
|
|
245
|
+
continue
|
|
246
|
+
if "=" in tok and not tok.startswith("-") and tok.split("=", 1)[0].replace("_", "").isalnum():
|
|
247
|
+
idx += 1
|
|
248
|
+
continue
|
|
249
|
+
break
|
|
250
|
+
if idx >= len(tokens):
|
|
251
|
+
return "", []
|
|
252
|
+
cmd_tok = os.path.basename(tokens[idx])
|
|
253
|
+
return cmd_tok, tokens[idx + 1 :]
|
|
168
254
|
|
|
169
255
|
@classmethod
|
|
170
256
|
def _optimize_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, Optional[Tuple[str, int]]]]:
|
|
171
257
|
"""
|
|
172
|
-
Applies one rewrite rule to a single stage.
|
|
258
|
+
Applies one rewrite rule to a single stage (command-position aware).
|
|
173
259
|
Returns (new_stage, est_saved, reason, cap_spec) or None.
|
|
174
|
-
cap_spec = (unit, limit) marks rules whose unbounded output must be
|
|
175
|
-
capped; the cap is appended to the END of the whole command (never
|
|
176
|
-
mid-compound), so `||` / `&&` exit-status semantics are untouched.
|
|
177
|
-
new_stage may equal stage for cap-only rules (git show, blame, curl).
|
|
178
260
|
"""
|
|
261
|
+
if cls._SUBSHELL_WRAP_RE.match(stage):
|
|
262
|
+
return None
|
|
179
263
|
|
|
180
|
-
|
|
181
|
-
if
|
|
182
|
-
|
|
183
|
-
tokens = stage.split()[2:] # args after git diff
|
|
184
|
-
has_path = any(not t.startswith('-') and not re.match(r'^(HEAD(~[0-9]+)?|main|master|[0-9a-f]{7,40})$', t) for t in tokens)
|
|
185
|
-
if not has_path:
|
|
186
|
-
excludes_str = " ".join(cls.LOCKFILE_EXCLUDES)
|
|
187
|
-
if " -- " in stage:
|
|
188
|
-
new_stage = f"{stage} {excludes_str}"
|
|
189
|
-
else:
|
|
190
|
-
new_stage = f"{stage} -- {excludes_str}"
|
|
191
|
-
return new_stage, 3500, "Excluded lockfiles/bundles from git diff", None
|
|
192
|
-
|
|
193
|
-
# git log: cap unbounded commit history
|
|
194
|
-
if re.search(r"\bgit\s+log\b", stage):
|
|
195
|
-
has_limit = re.search(r"(\s-[0-9]+|\s-n\s*\d+|\s--max-count[=\s]\d+)", stage)
|
|
196
|
-
if not has_limit:
|
|
197
|
-
if "--oneline" not in stage:
|
|
198
|
-
new_stage = re.sub(r"\bgit\s+log\b", "git log -n 10 --oneline", stage, count=1)
|
|
199
|
-
else:
|
|
200
|
-
new_stage = re.sub(r"\bgit\s+log\b", "git log -n 10", stage, count=1)
|
|
201
|
-
return new_stage, 1200, "Capped unbounded git log to 10 entries", None
|
|
264
|
+
cmd_tok, cmd_args = cls._primary_cmd_and_args(stage)
|
|
265
|
+
if not cmd_tok:
|
|
266
|
+
return None
|
|
202
267
|
|
|
203
|
-
#
|
|
204
|
-
if
|
|
205
|
-
|
|
206
|
-
|
|
268
|
+
# git subcommands (skip optional flags like -C <dir>, -c k=v, --git-dir=...)
|
|
269
|
+
if cmd_tok == "git":
|
|
270
|
+
sub_idx = 0
|
|
271
|
+
while sub_idx < len(cmd_args):
|
|
272
|
+
a = cmd_args[sub_idx]
|
|
273
|
+
if a in ("-C", "-c", "--git-dir", "--work-tree"):
|
|
274
|
+
sub_idx += 2
|
|
275
|
+
elif a.startswith("-"):
|
|
276
|
+
sub_idx += 1
|
|
277
|
+
else:
|
|
278
|
+
break
|
|
279
|
+
subcmd = cmd_args[sub_idx] if sub_idx < len(cmd_args) else ""
|
|
280
|
+
sub_args = cmd_args[sub_idx + 1 :]
|
|
281
|
+
|
|
282
|
+
# git diff: exclude lockfiles/bundles when diffing unscoped repository
|
|
283
|
+
if subcmd == "diff":
|
|
284
|
+
if not any(a.startswith(":!") for a in sub_args) and ":!" not in stage:
|
|
285
|
+
has_path = any(not a.startswith("-") and not cls._GIT_REF_RE.match(a) for a in sub_args)
|
|
286
|
+
if not has_path:
|
|
287
|
+
excludes_str = " ".join(cls.LOCKFILE_EXCLUDES)
|
|
288
|
+
if " -- " in stage or stage.rstrip().endswith(" --"):
|
|
289
|
+
new_stage = f"{stage.rstrip()} {excludes_str}"
|
|
290
|
+
else:
|
|
291
|
+
new_stage = f"{stage.rstrip()} -- {excludes_str}"
|
|
292
|
+
return new_stage, 3500, "Excluded lockfiles/bundles from git diff", None
|
|
293
|
+
|
|
294
|
+
# git log: cap unbounded commit history
|
|
295
|
+
elif subcmd == "log":
|
|
296
|
+
has_limit = bool(cls._GIT_DIFF_LIMIT_RE.search(stage))
|
|
297
|
+
if not has_limit:
|
|
298
|
+
if "--oneline" not in sub_args:
|
|
299
|
+
new_stage = re.sub(r"\b(git(?:\s+-C\s+\S+)?\s+log)\b", r"\1 -n 10 --oneline", stage, count=1)
|
|
300
|
+
else:
|
|
301
|
+
new_stage = re.sub(r"\b(git(?:\s+-C\s+\S+)?\s+log)\b", r"\1 -n 10", stage, count=1)
|
|
302
|
+
return new_stage, 1200, "Capped unbounded git log to 10 entries", None
|
|
303
|
+
|
|
304
|
+
# git grep: exclude lockfiles & generated dirs via pathspecs
|
|
305
|
+
elif subcmd == "grep":
|
|
306
|
+
if ":!*.lock" not in stage and ":!bun.lock" not in stage:
|
|
307
|
+
git_excludes = "':!*.lock' ':!bun.lock' ':!bun.lockb' ':!package-lock.json' ':!dist' ':!build' ':!node_modules'"
|
|
308
|
+
if " -- " in stage or stage.rstrip().endswith(" --"):
|
|
309
|
+
new_stage = f"{stage.rstrip()} {git_excludes}"
|
|
310
|
+
else:
|
|
311
|
+
new_stage = f"{stage.rstrip()} -- . {git_excludes}"
|
|
312
|
+
return new_stage, 3500, "Excluded lockfiles from git grep and capped output", cls._CAP_LINES_30
|
|
313
|
+
|
|
314
|
+
# git show: full patch dumps are capped
|
|
315
|
+
elif subcmd == "show":
|
|
316
|
+
if not cls._GIT_SHOW_SHORT_RE.search(stage):
|
|
317
|
+
return stage, 1500, "Capped git show patch output", cls._CAP_LINES_200
|
|
318
|
+
|
|
319
|
+
# git blame: one output line per file line
|
|
320
|
+
elif subcmd == "blame":
|
|
321
|
+
if "-L" not in sub_args and not any(a.startswith("-L") for a in sub_args):
|
|
322
|
+
return stage, 1500, "Capped git blame output", cls._CAP_LINES_200
|
|
323
|
+
|
|
324
|
+
# pytest (or python -m pytest): compact quiet traceback
|
|
325
|
+
if cmd_tok == "pytest" or (cmd_tok.startswith("python") and "-m" in cmd_args and "pytest" in cmd_args):
|
|
326
|
+
if "--tb=" not in stage and "-q" not in cmd_args and "--quiet" not in cmd_args:
|
|
207
327
|
return f"{stage} -q --tb=short", 800, "Applied short traceback to pytest", None
|
|
208
328
|
|
|
209
|
-
# test runners: agents block on
|
|
210
|
-
# an unclosed jest handle means the process never exits (infinite wait)
|
|
329
|
+
# test runners: agents block on watch mode
|
|
211
330
|
guard = cls._optimize_test_stage(stage, cwd)
|
|
212
331
|
if guard:
|
|
213
332
|
return guard
|
|
214
333
|
|
|
215
|
-
# find: prune unbounded recursion
|
|
216
|
-
if
|
|
217
|
-
|
|
334
|
+
# find: prune unbounded recursion on simple directory crawls (avoid breaking -o / -exec / -delete expressions)
|
|
335
|
+
if cmd_tok == "find" and "node_modules" not in stage and ".git" not in stage:
|
|
336
|
+
has_complex = any(a in ("-o", "-or", "-exec", "-execdir", "-delete", "(") for a in cmd_args)
|
|
337
|
+
if not has_complex and (
|
|
338
|
+
re.search(r"\bfind\s+(\.|\/|[\w./-]+)\s*$", stage)
|
|
339
|
+
or re.search(r"\bfind\s+\.\s+-name\b", stage)
|
|
340
|
+
):
|
|
218
341
|
new_stage = f"{stage} -not -path '*/.*' -not -path '*/node_modules/*' -not -path '*/venv/*'"
|
|
219
342
|
return new_stage, 1500, "Pruned .git, node_modules, and venv from find", None
|
|
220
343
|
|
|
221
|
-
# git grep: exclude lockfiles & generated dirs via pathspecs
|
|
222
|
-
if re.search(r"\bgit\b.*?\bgrep\b", stage):
|
|
223
|
-
if ":!*.lock" not in stage and ":!bun.lock" not in stage:
|
|
224
|
-
git_excludes = "':!*.lock' ':!bun.lock' ':!bun.lockb' ':!package-lock.json' ':!dist' ':!build' ':!node_modules'"
|
|
225
|
-
if " -- " in stage:
|
|
226
|
-
new_stage = f"{stage} {git_excludes}"
|
|
227
|
-
else:
|
|
228
|
-
new_stage = f"{stage} -- . {git_excludes}"
|
|
229
|
-
return new_stage, 3500, "Excluded lockfiles from git grep and capped output", cls._CAP_LINES_30
|
|
230
|
-
|
|
231
344
|
# grep / egrep recursive search: exclude junk dirs and cap output
|
|
232
|
-
if
|
|
233
|
-
is_recursive =
|
|
345
|
+
if cmd_tok in ("grep", "egrep"):
|
|
346
|
+
is_recursive = any(
|
|
347
|
+
(a.startswith("-") and not a.startswith("--") and ("r" in a or "R" in a)) or a == "--recursive"
|
|
348
|
+
for a in cmd_args
|
|
349
|
+
)
|
|
234
350
|
if is_recursive and "--exclude-dir" not in stage and "node_modules" not in stage:
|
|
235
351
|
excludes = "--exclude='*.lock' --exclude='*.lockb' --exclude-dir={dist,build,node_modules,.git,coverage,__pycache__,.next,data}"
|
|
236
352
|
return f"{stage} {excludes}", 2500, "Sanitized grep directories and capped output to 30 matches", cls._CAP_LINES_30
|
|
237
353
|
|
|
238
|
-
# ripgrep: cap
|
|
239
|
-
if
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
if not re.search(r"--stat|--name-only|--name-status|\s-s\b|--oneline", stage):
|
|
249
|
-
return stage, 1500, "Capped git show patch output", cls._CAP_LINES_200
|
|
250
|
-
|
|
251
|
-
# git blame: one output line per file line — huge on big files unless -L limited
|
|
252
|
-
if re.search(r"\bgit\s+blame\b", stage):
|
|
253
|
-
if "-L" not in stage:
|
|
254
|
-
return stage, 1500, "Capped git blame output", cls._CAP_LINES_200
|
|
255
|
-
|
|
256
|
-
# docker logs: bound container log dumps
|
|
257
|
-
if re.search(r"\bdocker\s+(container\s+)?logs\b", stage):
|
|
258
|
-
if "--tail" not in stage and not re.search(r"\s-n\s*\d+", stage):
|
|
354
|
+
# ripgrep: cap output
|
|
355
|
+
if cmd_tok == "rg" and "-- " not in cmd_args and not any(a in ("-m", "--max-count", "-g", "--glob") or a.startswith(("-m", "--max-count=", "-g", "--glob=")) for a in cmd_args):
|
|
356
|
+
new_stage = stage
|
|
357
|
+
if "--no-ignore" in cmd_args:
|
|
358
|
+
new_stage += " -g '!node_modules' -g '!.git' -g '!dist' -g '!build'"
|
|
359
|
+
return new_stage, 2500, "Capped rg output to 30 matches and excluded junk dirs", cls._CAP_LINES_30
|
|
360
|
+
|
|
361
|
+
# docker logs / docker container logs
|
|
362
|
+
if cmd_tok == "docker" and (cmd_args[:1] == ["logs"] or cmd_args[:2] == ["container", "logs"]):
|
|
363
|
+
if "--tail" not in stage and not any(a == "-n" or a.startswith(("-n", "--tail=")) for a in cmd_args):
|
|
259
364
|
return f"{stage} --tail 100", 2000, "Capped docker logs to last 100 lines", None
|
|
260
365
|
|
|
261
|
-
# kubectl logs
|
|
262
|
-
if
|
|
366
|
+
# kubectl logs
|
|
367
|
+
if cmd_tok == "kubectl" and cmd_args[:1] == ["logs"]:
|
|
263
368
|
if "--tail" not in stage:
|
|
264
369
|
return f"{stage} --tail=100", 2000, "Capped kubectl logs to last 100 lines", None
|
|
265
370
|
|
|
266
|
-
# npm
|
|
267
|
-
if
|
|
268
|
-
if "--no-audit" not in
|
|
371
|
+
# npm install/i/ci/add
|
|
372
|
+
if cmd_tok == "npm" and cmd_args and cmd_args[0] in ("install", "i", "ci", "add"):
|
|
373
|
+
if "--no-audit" not in cmd_args:
|
|
269
374
|
return f"{stage} --no-progress --no-fund --no-audit", 600, "Silenced npm install progress/audit output", None
|
|
270
375
|
|
|
271
|
-
# pip
|
|
272
|
-
if
|
|
273
|
-
if not
|
|
376
|
+
# pip / pip3 install
|
|
377
|
+
if cmd_tok in ("pip", "pip3") and cmd_args[:1] == ["install"]:
|
|
378
|
+
if "-q" not in cmd_args and "--quiet" not in cmd_args:
|
|
274
379
|
return f"{stage} -q", 400, "Applied quiet mode to pip install", None
|
|
275
380
|
|
|
276
|
-
# cat on lockfiles/minified bundles:
|
|
277
|
-
if
|
|
278
|
-
if not
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
if re.search(r"\bcurl\b", stage):
|
|
287
|
-
if not re.search(r"-o\s|-O\b|--output|-F\b|--form|-T\b|--upload-file|-I\b|--head", stage):
|
|
381
|
+
# cat on lockfiles/minified bundles: only rewrite when all paths are junk so normal files are never truncated
|
|
382
|
+
if cmd_tok == "cat" and not cls._has_redirect(stage):
|
|
383
|
+
if cmd_args and all(not p.startswith("-") for p in cmd_args):
|
|
384
|
+
if all(cls._CAT_JUNK_RE.search(p) for p in cmd_args):
|
|
385
|
+
quoted_paths = " ".join(shlex.quote(p) for p in cmd_args)
|
|
386
|
+
return f"head -n 120 {quoted_paths}", 3000, "Replaced cat of lockfile/bundle with bounded head", None
|
|
387
|
+
|
|
388
|
+
# curl printing to stdout
|
|
389
|
+
if cmd_tok == "curl":
|
|
390
|
+
if not cls._CURL_FILE_RE.search(stage):
|
|
288
391
|
return stage, 3000, "Capped curl stdout to 4096 bytes", cls._CAP_BYTES_4K
|
|
289
392
|
|
|
290
|
-
# ls: replace verbose
|
|
291
|
-
if
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
return new_stage, 380, "Replaced verbose ls flags with compact, secret-safe format (-1 -p)", None
|
|
393
|
+
# ls: replace verbose flags (-l, -a, -la, -lah) while preserving functional flags like -R, -t, -S
|
|
394
|
+
if cmd_tok == "ls" and cls._LS_VERBOSE_RE.search(stage):
|
|
395
|
+
new_stage = cls._LS_VERBOSE_RE.sub("ls -1 -p", stage, count=1)
|
|
396
|
+
return new_stage, 380, "Replaced verbose ls flags with compact, secret-safe format (-1 -p)", None
|
|
295
397
|
|
|
296
398
|
return None
|
|
297
399
|
|
|
@@ -318,11 +420,14 @@ class CommandSanitizer:
|
|
|
318
420
|
"""
|
|
319
421
|
if cls._TOKENSAFE_TESTS_RE.search(stage):
|
|
320
422
|
return None
|
|
321
|
-
|
|
423
|
+
cmd_tok, cmd_args = cls._primary_cmd_and_args(stage)
|
|
424
|
+
# Do not rewrite `vitest bench` or `vitest typecheck`
|
|
425
|
+
vitest_sub = cmd_args[1:2] if cmd_tok in ("npx", "yarn", "pnpm", "bunx") and cmd_args[:1] == ["vitest"] else cmd_args[:1]
|
|
426
|
+
if (cmd_tok == "vitest" or cls._VITEST_RE.match(stage)) and not any(a in ("bench", "typecheck") for a in vitest_sub):
|
|
322
427
|
runner = "vitest"
|
|
323
428
|
elif cls._JEST_RE.match(stage) or cls._JEST_SCRIPT_RE.search(stage):
|
|
324
429
|
runner = "jest"
|
|
325
|
-
elif cls._PKG_MANAGER_TEST_RE.
|
|
430
|
+
elif cls._PKG_MANAGER_TEST_RE.match(cls._strip_cmd_prefix(stage)):
|
|
326
431
|
if cls._JEST_FINGERPRINT_RE.search(stage):
|
|
327
432
|
runner = "jest"
|
|
328
433
|
else:
|
|
@@ -340,8 +445,13 @@ class CommandSanitizer:
|
|
|
340
445
|
new_stage = cls._BARE_WATCH_RE.sub("", new_stage)
|
|
341
446
|
reasons.append("Dropped bare --watch from vitest command")
|
|
342
447
|
saved += 300
|
|
343
|
-
if
|
|
344
|
-
|
|
448
|
+
if (
|
|
449
|
+
runner == "vitest"
|
|
450
|
+
and not re.search(r"\bvitest\s+(?:run|bench|typecheck)\b", new_stage)
|
|
451
|
+
and "--run" not in cmd_args
|
|
452
|
+
):
|
|
453
|
+
# Replace vitest at command position, never inside an env-var value
|
|
454
|
+
new_stage = re.sub(r"^(\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+)?(?:npx\s+|yarn\s+|pnpm\s+|bunx\s+)?)vitest\b", r"\1vitest run", new_stage, count=1)
|
|
345
455
|
reasons.append("Rewrote vitest to one-shot `vitest run`")
|
|
346
456
|
saved += 400
|
|
347
457
|
elif runner in ("jest", "script-jest"):
|
|
@@ -364,13 +474,15 @@ class CommandSanitizer:
|
|
|
364
474
|
reasons.append("Appended --forceExit so jest exits despite open handles")
|
|
365
475
|
saved += 800
|
|
366
476
|
|
|
367
|
-
# npm silently swallows args without ` -- `:
|
|
368
|
-
#
|
|
477
|
+
# npm silently swallows args without ` -- `: insert ` -- ` unless caller is
|
|
478
|
+
# passing npm's own flags (--workspace, --prefix, --silent, -w, --if-present).
|
|
369
479
|
npm_match = cls._NPM_TEST_RE.search(new_stage)
|
|
370
|
-
if npm_match and " -- " not in new_stage
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
480
|
+
if npm_match and " -- " not in new_stage:
|
|
481
|
+
tail = new_stage[npm_match.end():].lstrip()
|
|
482
|
+
if tail and not tail.startswith(("--workspace", "-w ", "-w=", "--prefix", "--silent", "--if-present")):
|
|
483
|
+
new_stage = new_stage[:npm_match.end()] + " -- " + tail
|
|
484
|
+
reasons.append("Inserted ` -- ` so npm forwards args to the test runner")
|
|
485
|
+
saved += 600
|
|
374
486
|
|
|
375
487
|
if not re.search(r"\bCI=", new_stage):
|
|
376
488
|
new_stage = f"CI=true {new_stage}"
|
|
@@ -460,7 +572,7 @@ class CommandSanitizer:
|
|
|
460
572
|
cap_applied = False
|
|
461
573
|
if cap_spec:
|
|
462
574
|
last_stage = pairs[-1][1]
|
|
463
|
-
if not cls._LIMITER_RE.
|
|
575
|
+
if not cls._LIMITER_RE.match(last_stage) and not cls._has_redirect(last_stage):
|
|
464
576
|
unit, limit = cap_spec
|
|
465
577
|
pairs[-1] = (pairs[-1][0], f"{last_stage} | head -{unit} {limit}")
|
|
466
578
|
cap_applied = True
|
package/src/compactor.py
CHANGED
|
@@ -13,6 +13,7 @@ from src.tokenizer import count_tokens
|
|
|
13
13
|
from src.distiller import UniversalDistiller
|
|
14
14
|
from src.secret_redactor import SecretRedactor
|
|
15
15
|
from src.license_manager import LicenseManager
|
|
16
|
+
from src.paths import resolve_data_dir
|
|
16
17
|
|
|
17
18
|
class PromptCompactor:
|
|
18
19
|
"""Transforms verbose natural language requests into compact Intent IR across major world languages."""
|
|
@@ -324,8 +325,7 @@ class PromptCompactor:
|
|
|
324
325
|
@classmethod
|
|
325
326
|
def _get_min_distill_tokens(cls) -> int:
|
|
326
327
|
"""Loads minimum token threshold for LLM distillation from config or returns 100."""
|
|
327
|
-
|
|
328
|
-
config_path = os.path.join(base_dir, "data", "config.json")
|
|
328
|
+
config_path = os.path.join(resolve_data_dir(), "config.json")
|
|
329
329
|
if os.path.exists(config_path):
|
|
330
330
|
try:
|
|
331
331
|
with open(config_path, "r", encoding="utf-8") as f:
|
|
@@ -431,8 +431,8 @@ class PromptCompactor:
|
|
|
431
431
|
# Extract symbol
|
|
432
432
|
symbol = cls.extract_symbol(raw_text, target_file)
|
|
433
433
|
|
|
434
|
-
# Extract traits
|
|
435
|
-
trait_match = re.search(r"
|
|
434
|
+
# Extract traits from S-Expression header (before quoted minimal_intent)
|
|
435
|
+
trait_match = re.search(r'^\([A-Z]+(?:\s+[^\[\]"]+)?\s+\[(.*?)\]', distilled)
|
|
436
436
|
traits = trait_match.group(1).split() if trait_match else []
|
|
437
437
|
|
|
438
438
|
return {
|
|
@@ -450,13 +450,28 @@ class PromptCompactor:
|
|
|
450
450
|
}
|
|
451
451
|
|
|
452
452
|
# Tier 1: Multilingual Local Regex Compactor
|
|
453
|
-
|
|
453
|
+
# Skip destructive regex rewriting when fenced code blocks dominate, and mask URLs /
|
|
454
|
+
# inline code spans before matching FILE_REGEX or punctuation stripping.
|
|
455
|
+
has_fenced_code = "```" in raw_text
|
|
456
|
+
protected_spans: Dict[str, str] = {}
|
|
457
|
+
|
|
458
|
+
def _mask_span(m: re.Match) -> str:
|
|
459
|
+
tok = f"__TSPH_{len(protected_spans)}__"
|
|
460
|
+
protected_spans[tok] = m.group(0)
|
|
461
|
+
return tok
|
|
462
|
+
|
|
463
|
+
url_free = re.sub(r"https?://[^\s<>'\"`]+", _mask_span, raw_text)
|
|
464
|
+
code_free = re.sub(r"```[\s\S]*?```|`[^`\n]+`", _mask_span, url_free)
|
|
465
|
+
|
|
466
|
+
files = cls.FILE_REGEX.findall(url_free)
|
|
454
467
|
target_file = files[0] if files else ""
|
|
455
468
|
|
|
456
469
|
action = "TASK"
|
|
470
|
+
matched_action_regex = None
|
|
457
471
|
for act_name, regex in cls.ACTION_PATTERNS:
|
|
458
472
|
if regex.search(raw_text):
|
|
459
473
|
action = act_name
|
|
474
|
+
matched_action_regex = regex
|
|
460
475
|
break
|
|
461
476
|
|
|
462
477
|
traits = []
|
|
@@ -467,24 +482,39 @@ class PromptCompactor:
|
|
|
467
482
|
|
|
468
483
|
symbol = cls.extract_symbol(raw_text, target_file)
|
|
469
484
|
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
delta =
|
|
473
|
-
|
|
474
|
-
delta =
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
485
|
+
if has_fenced_code:
|
|
486
|
+
# Keep fenced code verbatim by skipping Tier 1 word/punctuation mangling
|
|
487
|
+
delta = raw_text.strip()
|
|
488
|
+
else:
|
|
489
|
+
delta = url_free
|
|
490
|
+
if target_file:
|
|
491
|
+
delta = delta.replace(target_file, " ")
|
|
492
|
+
if symbol:
|
|
493
|
+
delta = re.sub(r"\b" + re.escape(symbol) + r"\b", " ", delta)
|
|
494
|
+
delta = delta.replace(f"`{symbol}`", " ")
|
|
495
|
+
|
|
496
|
+
# Protect remaining secondary filenames and inline backtick code spans
|
|
497
|
+
delta = re.sub(r"`[^`\n]+`", _mask_span, delta)
|
|
498
|
+
for extra_f in files[1:]:
|
|
499
|
+
if extra_f and extra_f in delta:
|
|
500
|
+
tok = f"__TSPH_{len(protected_spans)}__"
|
|
501
|
+
protected_spans[tok] = extra_f
|
|
502
|
+
delta = delta.replace(extra_f, tok)
|
|
503
|
+
|
|
504
|
+
for pattern in cls.STOP_PHRASES:
|
|
505
|
+
delta = re.sub(pattern, " ", delta, flags=re.I)
|
|
506
|
+
|
|
507
|
+
# Strip only the matched primary action word so secondary intents ("Fix error") survive
|
|
508
|
+
if matched_action_regex is not None:
|
|
509
|
+
delta = matched_action_regex.sub(" ", delta)
|
|
510
|
+
|
|
511
|
+
for regex, _ in cls.TRAIT_MAPPINGS:
|
|
512
|
+
delta = regex.sub(" ", delta)
|
|
513
|
+
|
|
514
|
+
delta = re.sub(r"[\.,:;\"'\(\)\[\]\{\}`\?¿¡!。,:;“”‘’「」『』、]", " ", delta)
|
|
515
|
+
for tok, orig_val in protected_spans.items():
|
|
516
|
+
delta = delta.replace(tok, orig_val)
|
|
517
|
+
delta = re.sub(r"\s+", " ", delta).strip()
|
|
488
518
|
|
|
489
519
|
parts = [action]
|
|
490
520
|
if target_file:
|
|
@@ -493,10 +523,10 @@ class PromptCompactor:
|
|
|
493
523
|
parts.append(symbol)
|
|
494
524
|
if traits:
|
|
495
525
|
parts.append(f"[{' '.join(traits)}]")
|
|
496
|
-
if delta and len(delta) > 2:
|
|
526
|
+
if delta and len(delta) > 2 and not has_fenced_code:
|
|
497
527
|
parts.append(f'"{delta}"')
|
|
498
528
|
|
|
499
|
-
compact_expr = f"({' '.join(parts)})"
|
|
529
|
+
compact_expr = raw_text.strip() if has_fenced_code else f"({' '.join(parts)})"
|
|
500
530
|
compact_tokens = count_tokens(compact_expr)
|
|
501
531
|
|
|
502
532
|
if compact_tokens > original_tokens:
|