@alexgreensh/token-optimizer 5.13.74 → 5.13.76

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 (84) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/hooks/posttooluse_runner.py +7 -9
  5. package/hooks/run.py +5 -1
  6. package/hooks/stop_runner.py +15 -56
  7. package/hooks/userpromptsubmit_runner.py +29 -4
  8. package/package.json +1 -1
  9. package/skills/token-optimizer/assets/dashboard.html +30 -14
  10. package/skills/token-optimizer/assets/savings_story.js +103 -27
  11. package/skills/token-optimizer/references/agent-prompts.md +2 -0
  12. package/skills/token-optimizer/references/implementation-playbook.md +1 -0
  13. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  14. package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
  15. package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
  16. package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
  17. package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
  18. package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
  19. package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
  20. package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
  21. package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
  22. package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
  24. package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
  28. package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
  29. package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
  30. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
  31. package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
  32. package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
  33. package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
  34. package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
  35. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
  36. package/skills/token-optimizer/scripts/_measure/savings.py +80 -82
  37. package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
  38. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  39. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
  40. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
  41. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
  42. package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
  43. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
  44. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
  45. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  46. package/skills/token-optimizer/scripts/archive_result.py +16 -28
  47. package/skills/token-optimizer/scripts/archive_verify.py +1 -1
  48. package/skills/token-optimizer/scripts/bash_compress.py +156 -176
  49. package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
  50. package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
  51. package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
  52. package/skills/token-optimizer/scripts/benchmark.py +11 -13
  53. package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
  54. package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
  55. package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
  56. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  57. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  58. package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
  59. package/skills/token-optimizer/scripts/compact_markers.py +129 -0
  60. package/skills/token-optimizer/scripts/copilot_install.py +3 -0
  61. package/skills/token-optimizer/scripts/cursor_install.py +7 -0
  62. package/skills/token-optimizer/scripts/devin_source.py +5 -5
  63. package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
  64. package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
  65. package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
  66. package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
  67. package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
  68. package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
  69. package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
  70. package/skills/token-optimizer/scripts/grok_install.py +3 -0
  71. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  72. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  73. package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
  74. package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
  75. package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
  76. package/skills/token-optimizer/scripts/measure.py +10 -12
  77. package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
  78. package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
  79. package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
  80. package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
  81. package/skills/token-optimizer/scripts/process_identity.py +66 -0
  82. package/skills/token-optimizer/scripts/read_cache.py +51 -60
  83. package/skills/token-optimizer/scripts/statusline.js +21 -3
  84. package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
@@ -0,0 +1,900 @@
1
+ #!/usr/bin/env python3
2
+ """Safe read-only pipeline compression (pipe_compress) and unchanged Bash file
3
+ re-read detection (bash_reread_unchanged).
4
+
5
+ Design invariants:
6
+ - Fail-open: any parse ambiguity, unexpected shape, or exception returns None
7
+ so the caller serves the original output verbatim.
8
+ - Deterministic: identical inputs always produce byte-identical outputs so the
9
+ prompt cache stays stable.
10
+ - Explicit model intent is respected: commands with explicit output limits
11
+ (`head -n`, `tail -n`, `sed -n <range>`) are never shortened.
12
+ - Never compresses mixed output from multiple producers, loops, conditionals
13
+ (`||`, `if`, `for`, `while`, `case`), command substitution (`$(...)`, `` ` ``),
14
+ process substitution (`<()`, `>()`), subshells/braces, heredocs, file
15
+ redirects, or any non-read-only stage.
16
+ - Unchanged Bash `cat` re-read detection never skeletonizes source code and
17
+ only fires when `SessionStore.file_reads` + `compact_markers.py` prove the
18
+ exact unchanged file was already fully shown in this session and is still in
19
+ context.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import os
26
+ import posixpath
27
+ import re
28
+ import shlex
29
+ import stat as stat_module
30
+ import time
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ FEATURE_PIPE_COMPRESS = "pipe_compress"
35
+ FEATURE_BASH_REREAD = "bash_reread_unchanged"
36
+
37
+ # Minimum output thresholds: short outputs pass through untouched.
38
+ MIN_LINES = 15
39
+ MIN_CHARS = 100
40
+ MIN_CAT_BYTES = 500
41
+ MIN_REDUCTION_RATIO = 0.10
42
+ MAX_REREAD_AGE_SECONDS = 3600
43
+
44
+ # Shell control-flow keywords that mean "not a simple read-only command".
45
+ _COMPOUND_KEYWORDS = frozenset({
46
+ "for", "while", "until", "if", "then", "else", "elif", "fi",
47
+ "do", "done", "case", "esac", "function", "select", "{", "}", "[[", "]]",
48
+ })
49
+
50
+ _ASSIGN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
51
+ _SET_FLAGS_RE = re.compile(r"^[-+][euxo]+$")
52
+ _SET_OPTIONS = frozenset({"pipefail", "errexit", "nounset", "xtrace"})
53
+ _SED_RANGE_RE = re.compile(r"(?:^|;)\s*\d+\s*(?:,\s*(?:\d+|\$))?\s*[pq]\b")
54
+ _HEAD_TAIL_NUM_FLAG_RE = re.compile(r"^-[0-9]+$")
55
+
56
+ # Safe sink redirect targets (never file writes).
57
+ _SAFE_REDIRECT_TARGETS = frozenset({
58
+ "/dev/null", "/dev/stderr", "/dev/stdout", "/dev/fd/1", "/dev/fd/2",
59
+ })
60
+
61
+ # Patterns whose output shape is preserved by line-reordering filters (sort/uniq).
62
+ _LINE_ORIENTED_PATTERNS = frozenset({
63
+ "search_results", "find", "ls", "list", "disk_stats", "lint", "logs",
64
+ })
65
+
66
+ # Patterns whose output shape is preserved by bare (unflagged) head/tail.
67
+ _ALL_KNOWN_PIPE_PATTERNS = _LINE_ORIENTED_PATTERNS | frozenset({
68
+ "git_diff", "git_log", "git_status", "tree", "k8s", "pytest", "jest",
69
+ "build", "sqlite3", "csv",
70
+ })
71
+
72
+ # Trailing filters that do not destroy the producer's output shape.
73
+ _ORDER_FILTERS = frozenset({"sort", "uniq"})
74
+ _TRIM_FILTERS = frozenset({"head", "tail"})
75
+
76
+ # Glob / special path characters that disqualify single-file cat matching.
77
+ _GLOB_CHARS = frozenset({"*", "?", "["})
78
+
79
+
80
+ def _tokenize_shell(command_str: str) -> list[tuple[str, bool]] | None:
81
+ """Quote-aware shell tokenizer.
82
+
83
+ Returns a list of ``(token, was_quoted)`` tuples where unquoted shell
84
+ operators (``|``, ``|&``, ``&&``, ``||``, ``;``, redirects) are split into
85
+ standalone unquoted tokens, while quoted characters (e.g. ``'foo|bar'``,
86
+ ``"a;b"``) remain inside their argument token with ``was_quoted=True``.
87
+
88
+ Returns ``None`` on any dangerous or unparseable construct: newlines,
89
+ command/process substitution, heredocs, subshells/braces, bare ``&``,
90
+ unclosed quotes, or ``||``.
91
+ """
92
+ if not command_str or not isinstance(command_str, str):
93
+ return None
94
+ if "\n" in command_str or "\r" in command_str:
95
+ return None
96
+
97
+ tokens: list[tuple[str, bool]] = []
98
+ cur: list[str] = []
99
+ cur_quoted = False
100
+ i, n = 0, len(command_str)
101
+ quote = ""
102
+
103
+ def flush() -> None:
104
+ nonlocal cur, cur_quoted
105
+ if cur or cur_quoted:
106
+ tokens.append(("".join(cur), cur_quoted))
107
+ cur = []
108
+ cur_quoted = False
109
+
110
+ while i < n:
111
+ ch = command_str[i]
112
+ if quote:
113
+ if quote == '"':
114
+ if ch == "\\" and i + 1 < n:
115
+ nxt = command_str[i + 1]
116
+ if nxt in ('"', "\\", "$", "`"):
117
+ cur.append(nxt)
118
+ else:
119
+ cur.append("\\" + nxt)
120
+ i += 2
121
+ continue
122
+ if ch == "`" or command_str.startswith("$(", i):
123
+ return None
124
+ if ch == '"':
125
+ quote = ""
126
+ i += 1
127
+ continue
128
+ cur.append(ch)
129
+ i += 1
130
+ continue
131
+ else:
132
+ if ch == "'":
133
+ quote = ""
134
+ i += 1
135
+ continue
136
+ cur.append(ch)
137
+ i += 1
138
+ continue
139
+
140
+ # Outside quotes
141
+ if ch in (" ", "\t"):
142
+ flush()
143
+ i += 1
144
+ continue
145
+ if ch == "#" and not cur and not cur_quoted:
146
+ # Comment to end of single line
147
+ break
148
+ if ch == "\\":
149
+ if i + 1 >= n:
150
+ return None
151
+ cur.append(command_str[i + 1])
152
+ cur_quoted = True
153
+ i += 2
154
+ continue
155
+ if ch in ("'", '"'):
156
+ quote = ch
157
+ cur_quoted = True
158
+ i += 1
159
+ continue
160
+ if ch == "`" or command_str.startswith("$(", i):
161
+ return None
162
+ if command_str.startswith("<(", i) or command_str.startswith(">(", i):
163
+ return None
164
+ if command_str.startswith("<<", i):
165
+ return None
166
+ if ch in "(){}":
167
+ return None
168
+ if command_str.startswith("||", i):
169
+ return None
170
+ if command_str.startswith("&&", i):
171
+ flush()
172
+ tokens.append(("&&", False))
173
+ i += 2
174
+ continue
175
+ if command_str.startswith("|&", i):
176
+ flush()
177
+ tokens.append(("|&", False))
178
+ i += 2
179
+ continue
180
+ if ch in ("|", ";"):
181
+ flush()
182
+ tokens.append((ch, False))
183
+ i += 1
184
+ continue
185
+ # Fd-prefixed redirections like 2>&1, 2>/dev/null, 1>&2
186
+ if ch.isdigit() and not cur and not cur_quoted:
187
+ j = i
188
+ while j < n and command_str[j].isdigit():
189
+ j += 1
190
+ if j < n and command_str[j] in (">", "<"):
191
+ op_end = j + 1
192
+ if op_end < n and command_str[op_end] in (">", "&"):
193
+ op_end += 1
194
+ if command_str[op_end - 1] == "&":
195
+ while op_end < n and command_str[op_end].isdigit():
196
+ op_end += 1
197
+ tokens.append((command_str[i:op_end], False))
198
+ i = op_end
199
+ continue
200
+ if command_str.startswith("&>>", i):
201
+ flush()
202
+ tokens.append(("&>>", False))
203
+ i += 3
204
+ continue
205
+ if command_str.startswith("&>", i) or command_str.startswith(">&", i):
206
+ flush()
207
+ op_end = i + 2
208
+ while op_end < n and command_str[op_end].isdigit():
209
+ op_end += 1
210
+ tokens.append((command_str[i:op_end], False))
211
+ i = op_end
212
+ continue
213
+ if command_str.startswith(">>", i) or command_str.startswith("<>", i):
214
+ flush()
215
+ tokens.append((command_str[i:i + 2], False))
216
+ i += 2
217
+ continue
218
+ if ch in (">", "<"):
219
+ flush()
220
+ tokens.append((ch, False))
221
+ i += 1
222
+ continue
223
+ if ch == "&":
224
+ # Bare & (backgrounding) is rejected.
225
+ return None
226
+ cur.append(ch)
227
+ i += 1
228
+
229
+ if quote:
230
+ return None
231
+ flush()
232
+ return tokens
233
+
234
+
235
+ def _is_redirect_op(tok: str, quoted: bool) -> bool:
236
+ if quoted or not tok:
237
+ return False
238
+ if tok in (">", ">>", "<", "<>", "&>", "&>>", ">&"):
239
+ return True
240
+ i = 0
241
+ while i < len(tok) and tok[i].isdigit():
242
+ i += 1
243
+ rest = tok[i:]
244
+ if not rest:
245
+ return False
246
+ return rest.startswith((">", "<", "&>"))
247
+
248
+
249
+ def _redirect_needs_target(tok: str) -> bool:
250
+ if tok in (">", ">>", "<", "<>", "&>", "&>>"):
251
+ return True
252
+ i = 0
253
+ while i < len(tok) and tok[i].isdigit():
254
+ i += 1
255
+ rest = tok[i:]
256
+ if rest.startswith(">&"):
257
+ return False
258
+ return rest.startswith((">", "<"))
259
+
260
+
261
+ def _strip_safe_redirects(stage: list[tuple[str, bool]]) -> list[str] | None:
262
+ """Strip safe sink redirects (2>&1, >/dev/null). Reject any real file redirect."""
263
+ out: list[str] = []
264
+ i = 0
265
+ while i < len(stage):
266
+ tok, quoted = stage[i]
267
+ if _is_redirect_op(tok, quoted):
268
+ if _redirect_needs_target(tok):
269
+ if i + 1 >= len(stage):
270
+ return None
271
+ target, _tq = stage[i + 1]
272
+ if target not in _SAFE_REDIRECT_TARGETS:
273
+ return None
274
+ i += 2
275
+ continue
276
+ i += 1
277
+ continue
278
+ out.append(tok)
279
+ i += 1
280
+ return out
281
+
282
+
283
+ def _is_harmless_prefix(tokens: list[str]) -> bool:
284
+ if not tokens:
285
+ return True
286
+ head = tokens[0]
287
+ if head == "cd":
288
+ return len(tokens) <= 2 and (len(tokens) == 1 or tokens[1] != "-")
289
+ if head == "export":
290
+ return len(tokens) >= 2 and all(_ASSIGN_RE.match(t) for t in tokens[1:])
291
+ if head == "set":
292
+ rest = tokens[1:]
293
+ if not rest:
294
+ return False
295
+ for j, t in enumerate(rest):
296
+ if _SET_FLAGS_RE.match(t):
297
+ continue
298
+ if t in _SET_OPTIONS and j > 0 and rest[j - 1].endswith("o"):
299
+ continue
300
+ return False
301
+ return True
302
+ return all(_ASSIGN_RE.match(t) for t in tokens)
303
+
304
+
305
+ def _strip_stage_env_and_git_c(tokens: list[str]) -> list[str]:
306
+ """Drop leading K=V assignments and normalize `git -C <dir> <sub>` -> `git <sub>`."""
307
+ idx = 0
308
+ while idx < len(tokens) and _ASSIGN_RE.match(tokens[idx]):
309
+ idx += 1
310
+ rest = tokens[idx:]
311
+ if len(rest) >= 4 and rest[0] == "git" and rest[1] == "-C":
312
+ j = 1
313
+ while j + 1 < len(rest) and rest[j] == "-C":
314
+ j += 2
315
+ rest = ["git"] + rest[j:]
316
+ return rest
317
+
318
+
319
+ def _stage_has_explicit_limit(tokens: list[str], *, strict_legacy_num: bool = False) -> bool:
320
+ """True when a stage expresses explicit output-limiting intent.
321
+
322
+ - `head -n ...`, `head --lines ...`, `head -c ...`, `head --bytes ...`
323
+ - `tail -n ...`, `tail --lines ...`, `tail -c ...`, `tail --bytes ...`
324
+ - `sed -n ...` (or bundled short flag with `n`, or range script like `10,40p`)
325
+ When ``strict_legacy_num`` is True, also treats legacy ``head -50`` /
326
+ ``tail -50`` as explicit limits.
327
+ """
328
+ clean = _strip_stage_env_and_git_c(tokens)
329
+ if not clean:
330
+ return False
331
+ cmd = clean[0]
332
+ args = clean[1:]
333
+ if cmd in ("head", "tail"):
334
+ for a in args:
335
+ if a in ("-n", "-c") or a.startswith(("-n", "-c", "--lines", "--bytes")):
336
+ return True
337
+ if strict_legacy_num and _HEAD_TAIL_NUM_FLAG_RE.match(a):
338
+ return True
339
+ return False
340
+ if cmd == "sed":
341
+ for a in args:
342
+ if a == "-n" or (a.startswith("-") and not a.startswith("--") and "n" in a[1:]):
343
+ return True
344
+ if _SED_RANGE_RE.search(a):
345
+ return True
346
+ return False
347
+ return False
348
+
349
+
350
+ def has_explicit_output_limit(command: str, *, strict_legacy_num: bool = False) -> bool:
351
+ """True if any stage in ``command`` explicitly limits output via head -n,
352
+ tail -n, or sed -n / line-range."""
353
+ if not command or not isinstance(command, str):
354
+ return False
355
+ toks = _tokenize_shell(command)
356
+ if toks is None:
357
+ # Fallback regex check on raw string when tokenization rejects (e.g.
358
+ # multiline or complex command) so explicit limits still pass through.
359
+ if re.search(r"\bsed\b[^\n|;&]*\s-[a-zA-Z]*n\b", command):
360
+ return True
361
+ if re.search(r"\b(?:head|tail)\b[^\n|;&]*\s(?:-[nc]\s*\d|--lines|--bytes)", command):
362
+ return True
363
+ return False
364
+ stage: list[tuple[str, bool]] = []
365
+ for tok, quoted in toks:
366
+ if not quoted and tok in ("|", "|&", "&&", ";"):
367
+ clean = _strip_safe_redirects(stage)
368
+ if clean and _stage_has_explicit_limit(clean, strict_legacy_num=strict_legacy_num):
369
+ return True
370
+ stage = []
371
+ else:
372
+ stage.append((tok, quoted))
373
+ if stage:
374
+ clean = _strip_safe_redirects(stage)
375
+ if clean and _stage_has_explicit_limit(clean, strict_legacy_num=strict_legacy_num):
376
+ return True
377
+ return False
378
+
379
+
380
+ def _is_git_show_file_content(tokens: list[str]) -> bool:
381
+ if len(tokens) >= 2 and tokens[0] == "git" and tokens[1] == "show":
382
+ return any(":" in t and not t.startswith("-") for t in tokens[2:])
383
+ return False
384
+
385
+
386
+ def _detect_stage_pattern(tokens: list[str]) -> str | None:
387
+ """Detect the known bash_compress pattern for a single cleaned stage."""
388
+ if not tokens:
389
+ return None
390
+ if _is_git_show_file_content(tokens):
391
+ return None
392
+ if tokens[0] == "git" and len(tokens) >= 2 and tokens[1] == "grep":
393
+ return "search_results"
394
+ try:
395
+ from bash_compress import _detect_pattern
396
+ cmd_str = " ".join(shlex.quote(t) for t in tokens)
397
+ return _detect_pattern(cmd_str)
398
+ except Exception:
399
+ return None
400
+
401
+
402
+ def classify_safe_pipeline(command: str) -> tuple[str, str] | None:
403
+ """Return ``(producer_command, pattern_name)`` if ``command`` is a safe
404
+ read-only pipeline or harmless-prefix chain whose last producer has a
405
+ known compressible output shape. Otherwise return ``None``.
406
+ """
407
+ try:
408
+ toks = _tokenize_shell(command)
409
+ if not toks:
410
+ return None
411
+
412
+ # Reject compound shell keywords outside quotes.
413
+ for tok, quoted in toks:
414
+ if not quoted and tok in _COMPOUND_KEYWORDS:
415
+ return None
416
+
417
+ # Split into statements on unquoted `&&` and `;`.
418
+ statements: list[list[tuple[str, bool]]] = []
419
+ cur_stmt: list[tuple[str, bool]] = []
420
+ for tok, quoted in toks:
421
+ if not quoted and tok in ("&&", ";"):
422
+ if cur_stmt:
423
+ statements.append(cur_stmt)
424
+ cur_stmt = []
425
+ else:
426
+ cur_stmt.append((tok, quoted))
427
+ if cur_stmt:
428
+ statements.append(cur_stmt)
429
+ if not statements:
430
+ return None
431
+
432
+ # Strip harmless leading statements (cd, export, set, K=V).
433
+ remaining_stmts: list[list[tuple[str, bool]]] = []
434
+ for stmt in statements:
435
+ # A harmless prefix never contains a pipe.
436
+ has_pipe = any(not q and t in ("|", "|&") for t, q in stmt)
437
+ if not has_pipe and not remaining_stmts:
438
+ clean = _strip_safe_redirects(stmt)
439
+ if clean is None:
440
+ return None
441
+ if _is_harmless_prefix(clean):
442
+ continue
443
+ remaining_stmts.append(stmt)
444
+
445
+ # Must have exactly ONE producer statement (never mixed output).
446
+ if len(remaining_stmts) != 1:
447
+ return None
448
+
449
+ # Split that statement on unquoted `|` / `|&`.
450
+ raw_stages: list[list[tuple[str, bool]]] = []
451
+ cur_stage: list[tuple[str, bool]] = []
452
+ for tok, quoted in remaining_stmts[0]:
453
+ if not quoted and tok in ("|", "|&"):
454
+ if not cur_stage:
455
+ return None # empty stage (e.g. leading/double pipe)
456
+ raw_stages.append(cur_stage)
457
+ cur_stage = []
458
+ else:
459
+ cur_stage.append((tok, quoted))
460
+ if not cur_stage:
461
+ return None
462
+ raw_stages.append(cur_stage)
463
+
464
+ # Validate every stage: no file redirects, no explicit output limits,
465
+ # and every stage must be strictly read-only.
466
+ from pipeline_analyzer import _is_stage_read_only
467
+
468
+ clean_stages: list[list[str]] = []
469
+ for st in raw_stages:
470
+ clean = _strip_safe_redirects(st)
471
+ if not clean:
472
+ return None
473
+ if _stage_has_explicit_limit(clean, strict_legacy_num=True):
474
+ return None
475
+ norm = _strip_stage_env_and_git_c(clean)
476
+ if not norm:
477
+ return None
478
+ ok, _reason = _is_stage_read_only(norm)
479
+ if not ok:
480
+ return None
481
+ clean_stages.append(norm)
482
+
483
+ # Walk from the right across shape-preserving trailing filters to find
484
+ # the last producer whose output shape is known.
485
+ trailing_filters: list[str] = []
486
+ producer_idx = len(clean_stages) - 1
487
+ while producer_idx >= 0:
488
+ head = clean_stages[producer_idx][0]
489
+ if producer_idx > 0 and head in (_ORDER_FILTERS | _TRIM_FILTERS):
490
+ trailing_filters.append(head)
491
+ producer_idx -= 1
492
+ continue
493
+ break
494
+
495
+ producer = clean_stages[producer_idx]
496
+ pattern = _detect_stage_pattern(producer)
497
+ if not pattern or pattern not in _ALL_KNOWN_PIPE_PATTERNS:
498
+ return None
499
+
500
+ # Verify every trailing filter preserves this producer's output shape.
501
+ for filt in trailing_filters:
502
+ if filt in _ORDER_FILTERS and pattern not in _LINE_ORIENTED_PATTERNS:
503
+ return None
504
+
505
+ producer_cmd = " ".join(shlex.quote(t) for t in producer)
506
+ return producer_cmd, pattern
507
+ except Exception:
508
+ return None
509
+
510
+
511
+ def compress_pipe(
512
+ command: str,
513
+ stdout: str,
514
+ returncode: int | None = 0,
515
+ stderr: str = "",
516
+ ) -> str | None:
517
+ """Compress stdout of a safe read-only pipeline deterministically.
518
+
519
+ Returns the compressed text if safe and >=10% smaller, else ``None``.
520
+ Never raises (fail-open).
521
+ """
522
+ try:
523
+ if not stdout or len(stdout) < MIN_CHARS:
524
+ return None
525
+ if len(stdout.splitlines()) < MIN_LINES:
526
+ return None
527
+
528
+ classified = classify_safe_pipeline(command)
529
+ if classified is None:
530
+ return None
531
+ producer_cmd, _pattern = classified
532
+
533
+ from bash_compress import compress as _bc_compress, _looks_like_failure, _strip_ansi
534
+ if _looks_like_failure(returncode, stderr) or (stderr and stderr.strip()):
535
+ return None
536
+
537
+ cleaned = _strip_ansi(stdout)
538
+ if len(cleaned) < MIN_CHARS or len(cleaned.splitlines()) < MIN_LINES:
539
+ return None
540
+
541
+ compressed = _bc_compress(producer_cmd, cleaned, returncode=returncode or 0, stderr=stderr)
542
+ if not compressed or compressed == cleaned:
543
+ return None
544
+
545
+ from token_estimate import estimate_tokens as _est
546
+ orig_tok = _est(cleaned)
547
+ comp_tok = _est(compressed)
548
+ if orig_tok <= 0 or (1.0 - comp_tok / orig_tok) < MIN_REDUCTION_RATIO:
549
+ return None
550
+
551
+ from emit_safety_gate import gate_or_none as _emit_gate_none
552
+ return _emit_gate_none(
553
+ cleaned, compressed, feature=FEATURE_PIPE_COMPRESS,
554
+ tool_name="Bash", command=command, exit_code=returncode,
555
+ require_expand=False,
556
+ )
557
+ except Exception:
558
+ return None
559
+
560
+
561
+ # ---------------------------------------------------------------------------
562
+ # Step 3: Unchanged Bash `cat` file re-read detection (bash_reread_unchanged)
563
+ # ---------------------------------------------------------------------------
564
+
565
+ def _resolve_bash_path(target: str, cwd: str) -> str | None:
566
+ target = os.path.expanduser(target)
567
+ if os.name == "nt":
568
+ # Git Bash uses /c/... for Windows drive paths. Keep shell-root
569
+ # paths such as /tmp distinct from native Windows paths.
570
+ drive = re.match(r"^/([A-Za-z])(?=/|$)", target)
571
+ if drive:
572
+ target = f"{drive[1]}:/{target[3:]}"
573
+ elif target.startswith("/") and not target.startswith("//"):
574
+ return posixpath.normpath(target)
575
+ elif cwd.startswith("/") and not cwd.startswith("//") and not os.path.splitdrive(target)[0]:
576
+ return posixpath.normpath(posixpath.join(cwd, target))
577
+ if os.path.isabs(target):
578
+ return os.path.normpath(target)
579
+ return os.path.normpath(os.path.join(cwd, target)) if cwd else None
580
+
581
+
582
+ def parse_unranged_cat(command: str, cwd: str = "") -> str | None:
583
+ """Return the resolved absolute file path for a bare unranged single-file
584
+ ``cat <file>`` (or ``cd <dir> && cat <file>``), else ``None``.
585
+
586
+ Rejects any flags (except ``--``), multiple files, globs, pipes, redirects,
587
+ or compound constructs.
588
+ """
589
+ try:
590
+ toks = _tokenize_shell(command)
591
+ if not toks:
592
+ return None
593
+ for tok, quoted in toks:
594
+ if not quoted and (tok in _COMPOUND_KEYWORDS or tok in ("|", "|&")):
595
+ return None
596
+
597
+ # Split on unquoted `&&` / `;`
598
+ stmts: list[list[tuple[str, bool]]] = []
599
+ cur: list[tuple[str, bool]] = []
600
+ for tok, quoted in toks:
601
+ if not quoted and tok in ("&&", ";"):
602
+ if cur:
603
+ stmts.append(cur)
604
+ cur = []
605
+ else:
606
+ cur.append((tok, quoted))
607
+ if cur:
608
+ stmts.append(cur)
609
+ if not stmts:
610
+ return None
611
+
612
+ base_dir = (_resolve_bash_path(cwd, "") or cwd) if os.name == "nt" and cwd else cwd
613
+ remaining: list[list[str]] = []
614
+ for stmt in stmts:
615
+ clean = _strip_safe_redirects(stmt)
616
+ if clean is None:
617
+ return None
618
+ if not remaining and _is_harmless_prefix(clean):
619
+ if clean and clean[0] == "cd" and len(clean) == 2:
620
+ base_dir = _resolve_bash_path(clean[1], base_dir or "")
621
+ if base_dir is None:
622
+ return None
623
+ continue
624
+ remaining.append(clean)
625
+
626
+ if len(remaining) != 1:
627
+ return None
628
+
629
+ cat_toks = _strip_stage_env_and_git_c(remaining[0])
630
+ if len(cat_toks) < 2 or cat_toks[0] != "cat":
631
+ return None
632
+
633
+ args = cat_toks[1:]
634
+ if args[0] == "--":
635
+ args = args[1:]
636
+ if len(args) != 1:
637
+ return None
638
+
639
+ target = args[0]
640
+ if not target or target == "-" or target.startswith("-"):
641
+ return None
642
+ if any(ch in target for ch in _GLOB_CHARS):
643
+ return None
644
+ if target.startswith("/dev/"):
645
+ return None
646
+
647
+ return _resolve_bash_path(target, base_dir or "")
648
+ except Exception:
649
+ return None
650
+
651
+
652
+ def _entry_proves_full_unchanged_in_context(
653
+ entry: dict[str, Any] | None,
654
+ st: os.stat_result,
655
+ *,
656
+ tool_use_id: str,
657
+ now: float,
658
+ ) -> bool:
659
+ """Strict proof that ``entry`` represents a full, unchanged, un-edited read
660
+ that is still in context."""
661
+ if not entry or not isinstance(entry, dict):
662
+ return False
663
+ # Exact file identity check (mtime_ns + size_bytes).
664
+ if int(entry.get("mtime_ns", 0) or 0) != st.st_mtime_ns:
665
+ return False
666
+ if int(entry.get("size_bytes", 0) or 0) != st.st_size:
667
+ return False
668
+ # Duplicate hook fire for the same tool_use_id is NOT a second read.
669
+ if tool_use_id and entry.get("last_tool_use_id") == tool_use_id:
670
+ return False
671
+ # Must have a recorded full-file read `[0, 0]`. An Edit/Write clears
672
+ # `ranges_seen` to `[]`, and a ranged Read records `[offset, limit]`.
673
+ ranges_seen = entry.get("ranges_seen") or []
674
+ has_full_read = any(
675
+ isinstance(r, (list, tuple)) and len(r) == 2 and r[0] == 0 and r[1] == 0
676
+ for r in ranges_seen
677
+ )
678
+ if not has_full_read:
679
+ return False
680
+ # If the prior Read was replaced by a skeleton/structure map rather than
681
+ # showing the full file, do not claim the full file is in context.
682
+ if entry.get("last_replacement_type"):
683
+ return False
684
+ # Recency check: only reference a read within the last hour.
685
+ last_access = float(entry.get("last_access") or 0.0)
686
+ if last_access <= 0 or (now - last_access) > MAX_REREAD_AGE_SECONDS:
687
+ return False
688
+ return True
689
+
690
+
691
+ def try_bash_reread_unchanged(
692
+ command: str,
693
+ stdout: str,
694
+ *,
695
+ session_id: str,
696
+ store_id: str,
697
+ transcript_path: str = "",
698
+ cwd: str = "",
699
+ tool_use_id: str = "",
700
+ agent_id: str = "",
701
+ exit_code: int | None = 0,
702
+ stderr: str = "",
703
+ ) -> str | None:
704
+ """If ``command`` is an unranged ``cat <file>`` of an unchanged file proven
705
+ to be fully shown in this session and still in context, return a short
706
+ deterministic note. Otherwise return ``None`` (caller serves full output).
707
+
708
+ Never skeletonizes source code. Fail-open on any doubt or error.
709
+ """
710
+ try:
711
+ if not session_id or not store_id:
712
+ return None
713
+ if exit_code not in (None, 0) or (stderr and stderr.strip()):
714
+ return None
715
+ if not stdout or "\x00" in stdout:
716
+ return None
717
+ if len(stdout) < MIN_CAT_BYTES or len(stdout.splitlines()) < MIN_LINES:
718
+ return None
719
+
720
+ file_path = parse_unranged_cat(command, cwd=cwd)
721
+ if not file_path or (os.name == "nt" and file_path.startswith("/")):
722
+ return None
723
+
724
+ # Must have a real transcript path so compaction/microcompact
725
+ # invalidation can be verified via compact_markers.py. Any doubt -> raw.
726
+ if not transcript_path:
727
+ return None
728
+ try:
729
+ t_st = os.stat(transcript_path)
730
+ if not stat_module.S_ISREG(t_st.st_mode):
731
+ return None
732
+ except OSError:
733
+ return None
734
+
735
+ # Stat target file on disk (must be a regular file).
736
+ try:
737
+ st = os.stat(file_path)
738
+ if not stat_module.S_ISREG(st.st_mode) or st.st_size < MIN_CAT_BYTES:
739
+ return None
740
+ except OSError:
741
+ return None
742
+
743
+ from session_store import SessionStore, mark_context_reset
744
+ from read_cache import _scan_for_compaction
745
+
746
+ store = SessionStore(store_id)
747
+ try:
748
+ # Respect compaction / microcompact / context_management invalidation.
749
+ if _scan_for_compaction(store, transcript_path):
750
+ if agent_id:
751
+ store.clear_file_entries()
752
+ else:
753
+ store.reset_context_state()
754
+ mark_context_reset(session_id)
755
+ return None
756
+
757
+ # Look up by normalized path (and realpath if symlinked).
758
+ real_path = os.path.realpath(file_path)
759
+ entry = store.get_file_entry(file_path)
760
+ if entry is None and real_path != file_path:
761
+ entry = store.get_file_entry(real_path)
762
+
763
+ now = time.time()
764
+ if _entry_proves_full_unchanged_in_context(
765
+ entry, st, tool_use_id=tool_use_id, now=now
766
+ ):
767
+ basename = Path(file_path).name
768
+ line_count = len(stdout.splitlines())
769
+ note = (
770
+ f"[Token Optimizer: {basename} ({line_count} lines, lines 1-{line_count}, "
771
+ f"{st.st_size} bytes) is unchanged since your earlier "
772
+ f"full read in this session.]"
773
+ )
774
+ return note
775
+
776
+ # Record this unranged full `cat` in file_reads so a subsequent
777
+ # unchanged `cat` in the same session (with no edits or compaction)
778
+ # can be proven in context.
779
+ from token_estimate import estimate_tokens_from_bytes
780
+ new_entry = {
781
+ "mtime_ns": st.st_mtime_ns,
782
+ "size_bytes": st.st_size,
783
+ "ranges_seen": [[0, 0]],
784
+ "tokens_est": estimate_tokens_from_bytes(st.st_size),
785
+ "read_count": int((entry or {}).get("read_count", 0) or 0) + 1,
786
+ "last_access": now,
787
+ "last_replacement_fingerprint": "",
788
+ "last_replacement_type": "",
789
+ "repeat_replacement_count": 0,
790
+ "last_structure_reason": "",
791
+ "last_structure_confidence": 0.0,
792
+ "last_tool_use_id": tool_use_id or "",
793
+ }
794
+ store.upsert_file_entry(file_path, new_entry)
795
+ return None
796
+ finally:
797
+ store.close()
798
+ except Exception:
799
+ return None
800
+
801
+
802
+ def archive_and_wrap(command: str, raw_stdout: str, compressed: str, session_id: str = "") -> str | None:
803
+ """Archive raw stdout and attach an expand pointer (fail-closed to None if
804
+ archiving fails for outputs > 500 bytes). Uses a deterministic archive key
805
+ derived from session_id, command, and raw_stdout so identical inputs yield
806
+ identical outputs (prompt-cache stability)."""
807
+ try:
808
+ from bash_compress import _enforce_baseline_invariant
809
+ from archive_result import (
810
+ archive_entry_exists,
811
+ archive_original,
812
+ build_archive_pointer,
813
+ )
814
+ sid = session_id or os.environ.get("CLAUDE_SESSION_ID", "")
815
+ key = hashlib.sha256(
816
+ f"{sid}|{command}|{raw_stdout}".encode("utf-8", errors="replace")
817
+ ).hexdigest()[:16]
818
+ if archive_original(raw_stdout, sid, key, "Bash") is None:
819
+ return None
820
+ if not archive_entry_exists(sid, key):
821
+ return None
822
+ compressed = build_archive_pointer(compressed, len(raw_stdout), key)
823
+ archive_key = key
824
+ try:
825
+ compressed = _enforce_baseline_invariant(compressed, raw_stdout, archive_key)
826
+ except Exception:
827
+ pass
828
+ return compressed
829
+ except Exception:
830
+ return None
831
+
832
+
833
+ def hook_try_cat_reread(
834
+ command: str,
835
+ stdout: str,
836
+ payload: dict[str, Any],
837
+ store_id: str,
838
+ exit_code: int | None,
839
+ stderr: str,
840
+ ) -> tuple[bool, str | None]:
841
+ """Hook adapter for Step 3 (bash_reread_unchanged).
842
+
843
+ Returns ``(is_bare_cat, replacement_stdout)``. When ``is_bare_cat`` is True
844
+ and ``replacement_stdout`` is None, the caller must return raw stdout
845
+ verbatim (never let generic fallback skeletonize or chop a file read).
846
+ """
847
+ cwd = str(payload.get("cwd", "") or "")
848
+ if parse_unranged_cat(command, cwd=cwd) is None:
849
+ return False, None
850
+ sid = os.environ.get("CLAUDE_SESSION_ID", "")
851
+ note = try_bash_reread_unchanged(
852
+ command, stdout,
853
+ session_id=sid,
854
+ store_id=store_id,
855
+ transcript_path=str(payload.get("transcript_path", "") or ""),
856
+ cwd=cwd,
857
+ tool_use_id=str(payload.get("tool_use_id", "") or ""),
858
+ agent_id=str(payload.get("agent_id", "") or ""),
859
+ exit_code=exit_code,
860
+ stderr=stderr,
861
+ )
862
+ if note is None:
863
+ return True, None
864
+ wrapped = archive_and_wrap(command, stdout, note, session_id=sid)
865
+ return True, wrapped
866
+
867
+
868
+ def hook_try_pipe_compress(
869
+ command: str,
870
+ stdout: str,
871
+ exit_code: int | None,
872
+ stderr: str,
873
+ ) -> tuple[str, str, str] | None:
874
+ """Hook adapter for Step 2 (pipe_compress).
875
+
876
+ Returns ``(wrapped_output, cleaned_original, pattern)`` on success, else None.
877
+ """
878
+ cls = classify_safe_pipeline(command)
879
+ if cls is None:
880
+ return None
881
+ comp = compress_pipe(command, stdout, returncode=exit_code, stderr=stderr)
882
+ if comp is None:
883
+ return None
884
+ wrapped = archive_and_wrap(command, stdout, comp)
885
+ if wrapped is None:
886
+ return None
887
+ try:
888
+ from emit_safety_gate import gate_or_none as _emit_gate_none
889
+ wrapped = _emit_gate_none(
890
+ stdout, wrapped, feature=FEATURE_PIPE_COMPRESS,
891
+ tool_name="Bash", command=command, exit_code=exit_code,
892
+ require_expand=True,
893
+ )
894
+ except Exception:
895
+ wrapped = None
896
+ if wrapped is None:
897
+ return None
898
+ from bash_compress import _strip_ansi
899
+ return wrapped, _strip_ansi(stdout), cls[1]
900
+