@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +149 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3633 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +141 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +93 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +379 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +1011 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +288 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +426 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +400 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +716 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +59531 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1923 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,230 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer - standalone compression-event logger.
3
+
4
+ Hot-path compression paths (read_cache first-read, bash unmatched-output,
5
+ structured-data compression) need to record a repriceable compression_events
6
+ row WITHOUT importing measure.py (~135ms import blows the <500ms hook budget).
7
+
8
+ This mirrors the self-contained logging pattern in archive_result.py
9
+ (_log_savings_event): own minimal schema, short DB timeout, fail-open, never
10
+ raises. It writes to the SAME compression_events table measure.py owns; the
11
+ schema here is kept in sync with measure.py's _SCHEMA literal.
12
+
13
+ Three-tier accounting (KTD5): every event written here declares a `tier` from
14
+ {"measured", "estimated", "opportunity"}. Tiers are never summed into one
15
+ headline downstream; this module only records the tag.
16
+
17
+ Phase A discipline (KTD4): every row carries a stable `session_uuid` (the join
18
+ key) and a non-null `model`. When the model cannot be resolved cheaply on the
19
+ hot path it is stored as "unknown" (non-null, backfillable from session_log via
20
+ session_uuid at reprice time) rather than NULL (which reprices inert at 1.0x).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import os
26
+ import re
27
+ import sqlite3
28
+ from datetime import datetime
29
+ from pathlib import Path
30
+
31
+ from plugin_env import resolve_snapshot_dir
32
+
33
+ try:
34
+ from token_estimate import estimate_tokens as _estimate_tokens
35
+ except Exception: # pragma: no cover - fail-open if shared estimator missing
36
+ def _estimate_tokens(text: str) -> int:
37
+ if not text:
38
+ return 0
39
+ return len(text.encode("utf-8", errors="replace")) // 4
40
+
41
+ SNAPSHOT_DIR = resolve_snapshot_dir()
42
+
43
+
44
+ def _run_origin() -> str:
45
+ """runtime_env.run_origin(), or 'local' if it cannot be imported."""
46
+ try:
47
+ from runtime_env import run_origin
48
+ return run_origin()
49
+ except Exception:
50
+ return "local"
51
+
52
+ TRENDS_DB = SNAPSHOT_DIR / "trends.db"
53
+
54
+ _DB_TIMEOUT_SECONDS = 0.05
55
+ _DB_BUSY_TIMEOUT_MS = 50
56
+
57
+ _VALID_TIERS = ("measured", "estimated", "opportunity")
58
+
59
+ # Kept in sync with measure.py's compression_events _SCHEMA literal.
60
+ _COMPRESSION_SCHEMA = """
61
+ CREATE TABLE IF NOT EXISTS compression_events (
62
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
63
+ timestamp TEXT NOT NULL,
64
+ session_id TEXT,
65
+ session_uuid TEXT,
66
+ feature TEXT NOT NULL,
67
+ command_pattern TEXT,
68
+ original_tokens INTEGER DEFAULT 0,
69
+ compressed_tokens INTEGER DEFAULT 0,
70
+ compression_ratio REAL DEFAULT 0.0,
71
+ quality_preserved INTEGER DEFAULT 1,
72
+ verified INTEGER DEFAULT 0,
73
+ detail TEXT,
74
+ model TEXT,
75
+ tier TEXT
76
+ );
77
+ """
78
+
79
+ _UUID_PAT = re.compile(
80
+ r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
81
+ re.IGNORECASE,
82
+ )
83
+ _NON_SESSION_IDS = ("unknown", "test-123", "perf_test", "regtest", "demo")
84
+
85
+
86
+ def _extract_session_uuid(session_id: str | None) -> str | None:
87
+ """Return the stable join UUID for a session_id, or None.
88
+
89
+ Pure-function mirror of measure._extract_session_uuid (no I/O) so the hot
90
+ path stays fast. A valid Claude session UUID (8-4-4-4-12 hex) is the join
91
+ key; anything else (short agent_ids, test ids, empty) yields None.
92
+ """
93
+ if not session_id or session_id in _NON_SESSION_IDS:
94
+ return None
95
+ if _UUID_PAT.match(session_id):
96
+ return session_id
97
+ return None
98
+
99
+
100
+ def _resolve_model(model: str | None) -> str:
101
+ """Resolve the event-time model cheaply (no JSONL scan).
102
+
103
+ Order: explicit arg > env hint > "unknown" sentinel. Never NULL, so the
104
+ repricing path is not forced inert; "unknown" is backfillable via the
105
+ session_uuid join to session_log.
106
+ """
107
+ if model:
108
+ return model
109
+ env_model = os.environ.get("TOKEN_OPTIMIZER_SESSION_MODEL", "").strip()
110
+ if env_model:
111
+ return env_model
112
+ return "unknown"
113
+
114
+
115
+ def _chmod_private(path: Path) -> None:
116
+ try:
117
+ if path.exists():
118
+ os.chmod(str(path), 0o600)
119
+ except Exception:
120
+ pass
121
+
122
+
123
+ def log_compression_event(
124
+ feature: str,
125
+ original_text: str = "",
126
+ compressed_text: str = "",
127
+ session_id: str | None = None,
128
+ command_pattern: str | None = None,
129
+ tier: str | None = None,
130
+ model: str | None = None,
131
+ verified: bool = False,
132
+ quality_preserved: bool = True,
133
+ detail: str | None = None,
134
+ original_tokens: int | None = None,
135
+ compressed_tokens: int | None = None,
136
+ ) -> None:
137
+ """Write one compression_events row. Fail-open: never raises.
138
+
139
+ `tier` must be one of {"measured", "estimated", "opportunity"}; an invalid
140
+ or missing tier is coerced to "estimated" (the conservative middle tier)
141
+ rather than dropped, so a mis-tagged caller still produces a joinable row.
142
+
143
+ `original_tokens`/`compressed_tokens` override the text-derived estimate when
144
+ the caller already has accurate counts (e.g. the first-read shadow path holds
145
+ the file's token estimate and the skeleton's `replacement_tokens_est`). This
146
+ avoids re-encoding multi-megabyte content on the hot PreToolUse path.
147
+ """
148
+ conn: sqlite3.Connection | None = None
149
+ try:
150
+ if original_tokens is None:
151
+ original_tokens = _estimate_tokens(original_text)
152
+ if compressed_tokens is None:
153
+ compressed_tokens = _estimate_tokens(compressed_text)
154
+ ratio = 0.0
155
+ if original_tokens > 0:
156
+ ratio = round(1.0 - compressed_tokens / original_tokens, 4)
157
+
158
+ # DB boundary: command_pattern/detail can embed a file name or label
159
+ # carrying a credential shape. Redact here so no caller can persist
160
+ # them raw; on a redactor refusal the text columns go NULL while the
161
+ # token counts still land. feature/session_id are caller text too —
162
+ # redaction is a no-op on the real inputs (constant feature names,
163
+ # host-generated session ids, so joins still hold) but a tainted value
164
+ # can no longer reach disk verbatim.
165
+ try:
166
+ from credential_patterns import redact_credentials as _ce_redact
167
+ if feature:
168
+ feature = _ce_redact(feature)
169
+ if session_id:
170
+ session_id = _ce_redact(session_id)
171
+ if command_pattern:
172
+ command_pattern = _ce_redact(command_pattern)
173
+ if detail:
174
+ detail = _ce_redact(detail)
175
+ except Exception:
176
+ feature = "unknown"
177
+ session_id = None
178
+ command_pattern = None
179
+ detail = None
180
+
181
+ safe_tier = tier if tier in _VALID_TIERS else "estimated"
182
+ session_uuid = _extract_session_uuid(session_id)
183
+ resolved_model = _resolve_model(model)
184
+
185
+ SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
186
+ conn = sqlite3.connect(str(TRENDS_DB), timeout=_DB_TIMEOUT_SECONDS)
187
+ conn.execute(f"PRAGMA busy_timeout={_DB_BUSY_TIMEOUT_MS}")
188
+ conn.execute("PRAGMA synchronous=NORMAL")
189
+ conn.executescript(_COMPRESSION_SCHEMA)
190
+ # Idempotent tier migration in case the table predates the tier column.
191
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(compression_events)").fetchall()}
192
+ if "tier" not in cols:
193
+ conn.execute("ALTER TABLE compression_events ADD COLUMN tier TEXT")
194
+ # origin: local / cloud / cowork (runtime_env.run_origin). If the column
195
+ # cannot be added right now the event is kept without it.
196
+ has_origin = "origin" in cols
197
+ if not has_origin:
198
+ try:
199
+ conn.execute("ALTER TABLE compression_events ADD COLUMN origin TEXT")
200
+ has_origin = True
201
+ except sqlite3.Error:
202
+ has_origin = False
203
+ origin_cols = ", origin" if has_origin else ""
204
+ origin_mark = ", ?" if has_origin else ""
205
+ values = (datetime.now().isoformat(), session_id, session_uuid, feature, command_pattern,
206
+ original_tokens, compressed_tokens, ratio,
207
+ 1 if quality_preserved else 0,
208
+ 1 if verified else 0,
209
+ detail, resolved_model, safe_tier)
210
+ if has_origin:
211
+ values = values + (_run_origin(),)
212
+ conn.execute(
213
+ "INSERT INTO compression_events "
214
+ "(timestamp, session_id, session_uuid, feature, command_pattern, original_tokens, "
215
+ "compressed_tokens, compression_ratio, quality_preserved, verified, detail, model, tier"
216
+ + origin_cols + ") "
217
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?" + origin_mark + ")",
218
+ values,
219
+ )
220
+ conn.commit()
221
+ for suffix in ("", "-wal", "-shm"):
222
+ _chmod_private(Path(str(TRENDS_DB) + suffix))
223
+ except Exception:
224
+ pass
225
+ finally:
226
+ if conn is not None:
227
+ try:
228
+ conn.close()
229
+ except Exception:
230
+ pass
@@ -0,0 +1,331 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer v5.6 - Context Intelligence + Activity Tracking + Decision Extraction.
3
+
4
+ PostToolUse handler that generates heuristic summaries for large tool outputs
5
+ and logs them to the Session Knowledge Store. Shadow mode only: no
6
+ systemMessage injection, no additionalContext, zero cache impact.
7
+
8
+ The accumulated summaries feed into Dynamic Compact Instructions (measure.py)
9
+ so the model gets session-aware guidance at compaction time.
10
+
11
+ Summary generation is heuristic (<30ms), not LLM-based. Extracts:
12
+ - File paths mentioned in output
13
+ - Error/warning lines
14
+ - Line counts and size
15
+ - First/last N lines for context
16
+
17
+ Cooldown: max 3 summaries per 5 minutes to avoid write contention.
18
+
19
+ Hook registration: PostToolUse on Bash|PowerShell|Read|Grep|Glob|mcp__.*
20
+ (the consolidated runner also fires it on the edit tools).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import re
27
+ import time
28
+
29
+ from hook_io import read_stdin_hook_input
30
+ from session_store import SessionStore
31
+
32
+ _OUTPUT_THRESHOLD = 8192 # Only summarize outputs >= 8K chars
33
+ _SUMMARY_CAP = 600 # Max chars per summary
34
+ _COOLDOWN_WINDOW = 300 # 5 minutes
35
+ _COOLDOWN_MAX = 3 # Max summaries per window
36
+ _STDIN_MAX_BYTES = 524_288 # 512KB: sufficient for 50KB extraction limit
37
+
38
+ _PATH_RE = re.compile(
39
+ r"(?:^|[\s\"':=])(/[\w./-]{3,120}(?:\.\w{1,10})?)",
40
+ re.MULTILINE,
41
+ )
42
+ _ERROR_RE = re.compile(
43
+ r"^.*(?:error|Error|ERROR|FAIL|FAILED|panic|exception|Exception"
44
+ r"|TypeError|ValueError|KeyError|ImportError|ModuleNotFoundError"
45
+ r"|SyntaxError|RuntimeError|AttributeError|NameError|OSError"
46
+ r"|FileNotFoundError|PermissionError|ConnectionError"
47
+ r"|traceback|Traceback).*$",
48
+ re.MULTILINE,
49
+ )
50
+ _WARNING_RE = re.compile(
51
+ r"^.*(?:warning|Warning|WARNING|WARN|deprecated|DEPRECATED).*$",
52
+ re.MULTILINE,
53
+ )
54
+ _ERROR_TYPE_RE = re.compile(
55
+ r"(TypeError|ValueError|KeyError|ImportError|ModuleNotFoundError"
56
+ r"|SyntaxError|RuntimeError|AttributeError|NameError|OSError"
57
+ r"|FileNotFoundError|PermissionError|ConnectionError"
58
+ r"|Error|FAIL|FAILED|panic|exception|Exception"
59
+ r"|warning|Warning|WARNING|WARN|deprecated)",
60
+ )
61
+ _SAFE_TOOL_NAME_RE = re.compile(r"[^A-Za-z0-9._:/-]")
62
+
63
+
64
+
65
+
66
+ def _check_cooldown(store: SessionStore) -> bool:
67
+ """Check cooldown via SQLite (persists across subprocess invocations)."""
68
+ try:
69
+ cutoff = time.time() - _COOLDOWN_WINDOW
70
+ conn = store._connect()
71
+ row = conn.execute(
72
+ "SELECT COUNT(*) FROM context_intel_events WHERE timestamp > ?",
73
+ (cutoff,),
74
+ ).fetchone()
75
+ return (row[0] if row else 0) < _COOLDOWN_MAX
76
+ except Exception:
77
+ return True
78
+
79
+
80
+ # Sensitive path segments — paths containing any of these are excluded from
81
+ # SQLite logging. Mirrors the exclusion set in delta_diff.py for consistency.
82
+ _SENSITIVE_PATH_SEGMENTS = (
83
+ "/.ssh/",
84
+ "/.aws/",
85
+ "/.gnupg/",
86
+ "/etc/",
87
+ "/run/secrets",
88
+ "credentials",
89
+ "secrets",
90
+ ".env",
91
+ "id_rsa",
92
+ "id_ed25519",
93
+ ".pem",
94
+ ".key",
95
+ )
96
+
97
+
98
+ def _is_sensitive_path(path: str) -> bool:
99
+ """Return True if the path references a credential or secret location."""
100
+ lower = path.lower()
101
+ return any(seg in lower for seg in _SENSITIVE_PATH_SEGMENTS)
102
+
103
+
104
+ def _extract_paths(text: str) -> list[str]:
105
+ matches = _PATH_RE.findall(text[:50_000])
106
+ seen: set[str] = set()
107
+ paths: list[str] = []
108
+ for m in matches:
109
+ if m not in seen and not m.startswith("/dev/") and not m.startswith("/proc/"):
110
+ # Skip paths that reference credential stores or secret files.
111
+ if _is_sensitive_path(m):
112
+ continue
113
+ seen.add(m)
114
+ paths.append(m)
115
+ if len(paths) >= 10:
116
+ break
117
+ return paths
118
+
119
+
120
+ def _sanitize_signal(raw_line: str, prefix: str) -> str:
121
+ """Extract structural digest from an error/warning line.
122
+
123
+ Returns e.g. "ERR: TypeError in /src/auth.py" rather than raw text,
124
+ to prevent tool output content from flowing verbatim into compaction
125
+ prompts.
126
+ """
127
+ error_type = _ERROR_TYPE_RE.search(raw_line)
128
+ type_str = error_type.group(0) if error_type else "unknown"
129
+ paths = _PATH_RE.findall(raw_line)
130
+ path_str = f" in {paths[0]}" if paths else ""
131
+ return f"{prefix}: {type_str}{path_str}"
132
+
133
+
134
+ def _extract_signals(text: str) -> list[str]:
135
+ signals: list[str] = []
136
+ seen: set[str] = set()
137
+
138
+ errors = _ERROR_RE.findall(text[:50_000])
139
+ for e in errors:
140
+ sanitized = _sanitize_signal(e, "ERR")
141
+ if sanitized not in seen:
142
+ seen.add(sanitized)
143
+ signals.append(sanitized)
144
+ if len(signals) >= 5:
145
+ break
146
+
147
+ warnings = _WARNING_RE.findall(text[:50_000])
148
+ for w in warnings:
149
+ sanitized = _sanitize_signal(w, "WARN")
150
+ if sanitized not in seen:
151
+ seen.add(sanitized)
152
+ signals.append(sanitized)
153
+ if len(signals) >= 8:
154
+ break
155
+
156
+ return signals
157
+
158
+
159
+ def _sanitize_tool_name(name: str) -> str:
160
+ sanitized = _SAFE_TOOL_NAME_RE.sub("", name)
161
+ return sanitized[:64]
162
+
163
+
164
+ def _summarize_output(tool_name: str, output: str) -> str:
165
+ tool_name = _sanitize_tool_name(tool_name)
166
+ lines = output.splitlines()
167
+ line_count = len(lines)
168
+ char_count = len(output)
169
+
170
+ parts: list[str] = []
171
+ parts.append(f"{tool_name}: {line_count} lines, {char_count} chars")
172
+
173
+ paths = _extract_paths(output)
174
+ if paths:
175
+ parts.append(f"Files: {', '.join(paths[:5])}")
176
+ if len(paths) > 5:
177
+ parts.append(f" +{len(paths) - 5} more paths")
178
+
179
+ signals = _extract_signals(output)
180
+ for s in signals[:4]:
181
+ parts.append(s)
182
+
183
+ if line_count > 20 and not signals:
184
+ parts.append(f"Output: {line_count} lines, no errors detected")
185
+
186
+ summary = "\n".join(parts)
187
+ return summary[:_SUMMARY_CAP]
188
+
189
+
190
+ _DECISION_RE = re.compile(
191
+ r'\b(chose|decided|because|instead of|went with|going with|switched to|'
192
+ r'prefer|better to|should use|will use|picking|opting for|let\'s use|'
193
+ r'using .+ over|settled on|sticking with)\b',
194
+ re.IGNORECASE,
195
+ )
196
+ _MAX_DECISIONS = 10
197
+ _SENTENCE_SPLIT_RE = re.compile(r"[.!?\n]+")
198
+
199
+
200
+ # How far past the 5000-char decision sample the redactor reads (see below).
201
+ _DECISION_REDACT_WINDOW = 6000
202
+
203
+
204
+ def _extract_decisions(text: str, store: SessionStore) -> None:
205
+ """Extract decision statements from tool output and store incrementally.
206
+
207
+ Uses split-then-filter to avoid catastrophic regex backtracking on
208
+ large outputs without sentence-ending punctuation (build logs, JSON).
209
+ Uses SessionStore's auto-commit get_meta/set_meta (no explicit transaction)
210
+ to avoid conflicting with the implicit transaction from log_tool_use on
211
+ the same shared connection.
212
+ """
213
+ if len(text) < 50:
214
+ return
215
+ sample = text[:5000]
216
+ if not _DECISION_RE.search(sample):
217
+ return
218
+
219
+ # No persistence without the shared redactor: these sentences are raw
220
+ # tool output and may carry credentials (a decision quoting a token, a
221
+ # connection string, a PEM line). If the redactor is missing or refuses
222
+ # (broken custom pattern config), store nothing rather than persist text
223
+ # the org rules were meant to cover. Redact BEFORE the width cuts below:
224
+ # a secret straddling a cut is a prefix no pattern recognises. The window
225
+ # is read a little past the 5000-char sample so a secret that straddles
226
+ # the sample edge is whole when the redactor sees it.
227
+ try:
228
+ from credential_patterns import redact_credentials as _redact_decision
229
+ sample = _redact_decision(text[:_DECISION_REDACT_WINDOW])[:5000]
230
+ except Exception:
231
+ return
232
+
233
+ sentences = [
234
+ s.strip() for s in _SENTENCE_SPLIT_RE.split(sample)
235
+ if 20 <= len(s.strip()) <= 200
236
+ ]
237
+ new_decisions = []
238
+ for sentence in sentences:
239
+ if _DECISION_RE.search(sentence):
240
+ new_decisions.append(sentence.strip()[:150])
241
+ if len(new_decisions) >= 3:
242
+ break
243
+
244
+ if not new_decisions:
245
+ return
246
+
247
+ try:
248
+ existing_raw = store.get_meta("session_decisions")
249
+ existing = json.loads(existing_raw) if existing_raw else []
250
+
251
+ if len(existing) >= _MAX_DECISIONS:
252
+ return
253
+
254
+ for d in new_decisions:
255
+ if d not in existing:
256
+ existing.append(d)
257
+ if len(existing) >= _MAX_DECISIONS:
258
+ break
259
+
260
+ store.set_meta("session_decisions", json.dumps(existing, ensure_ascii=False))
261
+ except Exception:
262
+ pass
263
+
264
+
265
+ def _has_error_signals(text: str) -> bool:
266
+ """Quick check for error indicators in tool output."""
267
+ if len(text) < 10:
268
+ return False
269
+ sample = text[:20_000]
270
+ return bool(_ERROR_RE.search(sample))
271
+
272
+
273
+ def handle_post_tool_use() -> None:
274
+ hook_input = read_stdin_hook_input(_STDIN_MAX_BYTES)
275
+ if not hook_input:
276
+ return
277
+
278
+ tool_name = hook_input.get("tool_name", "")
279
+ tool_use_id = hook_input.get("tool_use_id", "")
280
+ tool_response = hook_input.get("tool_response", "")
281
+ session_id = hook_input.get("session_id", "")
282
+ tool_input = hook_input.get("tool_input", {})
283
+
284
+ if not session_id:
285
+ return
286
+
287
+ try:
288
+ store = SessionStore(session_id)
289
+ try:
290
+ # Activity tracking runs on every tool call, regardless of output size
291
+ try:
292
+ from activity_tracker import log_tool_use
293
+ command = ""
294
+ # PowerShell tool input carries the same `command` field as
295
+ # Bash (it is the Windows shell tool); the text is only logged,
296
+ # never interpreted as Bash syntax.
297
+ if tool_name in ("Bash", "PowerShell") and isinstance(tool_input, dict):
298
+ command = tool_input.get("command", "")
299
+ has_error = _has_error_signals(tool_response) if isinstance(tool_response, str) else False
300
+ log_tool_use(store, tool_name, command=command, has_error=has_error)
301
+ except Exception:
302
+ pass
303
+
304
+ # Decision extraction on outputs likely to contain decisions (>500 chars)
305
+ if isinstance(tool_response, str) and len(tool_response) > 500:
306
+ try:
307
+ _extract_decisions(tool_response, store)
308
+ except Exception:
309
+ pass
310
+
311
+ # Context intel summary only for large outputs
312
+ if not tool_use_id or not isinstance(tool_response, str) or len(tool_response) < _OUTPUT_THRESHOLD:
313
+ return
314
+
315
+ if not _check_cooldown(store):
316
+ return
317
+ summary = _summarize_output(tool_name, tool_response)
318
+ store.insert_intel_event(
319
+ tool_name=tool_name,
320
+ tool_use_id=tool_use_id,
321
+ summary=summary,
322
+ output_chars=len(tool_response),
323
+ )
324
+ finally:
325
+ store.close()
326
+ except Exception:
327
+ pass
328
+
329
+
330
+ if __name__ == "__main__":
331
+ handle_post_tool_use()
@@ -0,0 +1,115 @@
1
+ """Context pressure detection for hook injection gating.
2
+
3
+ Hooks that inject content into the conversation check pressure level
4
+ before emitting. At high fill, informational injections are suppressed.
5
+ At critical fill, all non-essential injections are suppressed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ from runtime_env import runtime_home
15
+
16
+ PRESSURE_NORMAL = "normal"
17
+ PRESSURE_HIGH = "high"
18
+ PRESSURE_CRITICAL = "critical"
19
+
20
+ _HIGH_THRESHOLD = 75
21
+ _CRITICAL_THRESHOLD = 90
22
+
23
+ _VALID_PRIORITIES = frozenset({"essential", "token-saving", "informational"})
24
+
25
+ _QUALITY_CACHE_DIR = runtime_home() / "token-optimizer"
26
+
27
+
28
+ def _sanitize_id(raw: str) -> str:
29
+ """Strip unsafe characters and fall back to 'unknown' if empty."""
30
+ safe = "".join(c for c in raw if c.isalnum() or c in "-_")
31
+ return safe or "unknown"
32
+
33
+
34
+ def _resolve_cache_path(
35
+ session_file: str | None = None,
36
+ session_id: str | None = None,
37
+ ) -> Path:
38
+ """Derive quality cache path from session file or session ID."""
39
+ if session_file:
40
+ safe = _sanitize_id(Path(session_file).stem)
41
+ return _QUALITY_CACHE_DIR / f"quality-cache-{safe}.json"
42
+ if session_id:
43
+ safe = _sanitize_id(session_id)
44
+ return _QUALITY_CACHE_DIR / f"quality-cache-{safe}.json"
45
+ return _QUALITY_CACHE_DIR / "quality-cache.json"
46
+
47
+
48
+ def get_pressure_level(
49
+ session_file: str | None = None,
50
+ session_id: str | None = None,
51
+ ) -> str:
52
+ """Return context pressure level based on quality cache fill_pct.
53
+
54
+ Args:
55
+ session_file: Path to the session JSONL file.
56
+ session_id: Session UUID (used when transcript_path unavailable).
57
+ Either parameter derives the per-session cache path.
58
+ Falls back to global cache when neither is provided.
59
+
60
+ Returns:
61
+ "normal" (<75% fill), "high" (75-90%), or "critical" (>=90%).
62
+ Defaults to "normal" on any error (fail-open).
63
+ """
64
+ try:
65
+ cache_path = _resolve_cache_path(session_file, session_id)
66
+ data = json.loads(cache_path.read_text(encoding="utf-8"))
67
+ fill_pct = float(data.get("fill_pct", 0) or 0)
68
+
69
+ if fill_pct >= _CRITICAL_THRESHOLD:
70
+ return PRESSURE_CRITICAL
71
+ if fill_pct >= _HIGH_THRESHOLD:
72
+ return PRESSURE_HIGH
73
+ return PRESSURE_NORMAL
74
+ except Exception:
75
+ return PRESSURE_NORMAL
76
+
77
+
78
+ def should_inject(
79
+ session_file: str | None = None,
80
+ session_id: str | None = None,
81
+ *,
82
+ priority: str = "informational",
83
+ ) -> bool:
84
+ """Check whether an injection should proceed given current pressure.
85
+
86
+ Args:
87
+ session_file: Path to session JSONL for per-session cache lookup.
88
+ session_id: Session UUID (alternative to session_file).
89
+ priority: "essential" (compact guidance, checkpoint body),
90
+ "token-saving" (read cache, bash rewrites),
91
+ or "informational" (quality warnings, archive confirmations).
92
+
93
+ Returns:
94
+ True if the injection should proceed, False if suppressed.
95
+ """
96
+ if priority not in _VALID_PRIORITIES:
97
+ return True
98
+
99
+ pressure = get_pressure_level(session_file, session_id)
100
+
101
+ if pressure == PRESSURE_NORMAL:
102
+ return True
103
+
104
+ if pressure == PRESSURE_HIGH:
105
+ return priority in ("essential", "token-saving")
106
+
107
+ return priority == "essential"
108
+
109
+
110
+ def log_suppression(injection_name: str, pressure: str) -> None:
111
+ """Log to stderr when an injection is suppressed."""
112
+ print(
113
+ f"[Token Optimizer] Suppressed {injection_name} (context pressure: {pressure})",
114
+ file=sys.stderr,
115
+ )