@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,766 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer v5.12: PostToolUse Bash Compression Hook.
3
+
4
+ Compresses Bash tool output AFTER execution via Claude Code's
5
+ ``updatedToolOutput`` mechanism. This is the UNIT B expansion: it handles
6
+ pipeline and metachar-containing commands that PreToolUse bash_hook.py
7
+ categorically rejects.
8
+
9
+ Architecture:
10
+ CC runs Bash tool → PostToolUse fires → this hook receives tool_response
11
+ → pipeline_analyzer checks read-only eligibility → bash_compress.compress()
12
+ compresses stdout → archive raw original → attach archive pointer →
13
+ enforce the baseline-size invariant → updatedToolOutput replaces what
14
+ Claude sees.
15
+
16
+ The existing PreToolUse bash_hook.py continues to handle simple (metachar-free)
17
+ commands. This hook handles everything else — pipes, &&, ||, ;, redirections,
18
+ heredocs, and command substitutions.
19
+
20
+ Safety (same stack as bash_hook.py):
21
+ - Fail-open: any exception → exit 0 with no output → Claude sees raw result
22
+ - Read-only only: pipeline_analyzer rejects any side-effecting stage
23
+ - No double-execution: command already ran; we only compress captured output
24
+ - Token preservation: credential scan runs BEFORE compression
25
+ - Raw output archived: the full stdout is stored with a retrievable key;
26
+ the compressed output carries an expand pointer.
27
+ - Baseline-size invariant: _enforce_baseline_invariant runs so the compressed
28
+ preview never exceeds what Claude Code would show as baseline.
29
+ - Error-on-stdout guard: _ERROR_STDERR_PATTERNS checked against stdout
30
+ when stderr was redirected (2>&1), so compressed output never swallows
31
+ error lines that appear on stdout.
32
+ - Exit behavior: no output = pass through; JSON output = compress
33
+
34
+ Hook config (hooks/hooks.json):
35
+ PostToolUse matcher "Bash" → bash_compress_hook.py --quiet
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import hashlib
41
+ import json
42
+ import os
43
+ import re
44
+ import sys
45
+ import time
46
+ from pathlib import Path
47
+
48
+
49
+ # Prefix Claude Code puts on a Bash tool_response delivered as a string when
50
+ # the command exited non-zero. The remainder of the string is the output.
51
+ _EXIT_CODE_RESPONSE_RE = re.compile(r"^Error: Exit code (\d+)\s*\n?")
52
+
53
+ # Codex/Cowork deliver a failed Bash tool_response as a plain string starting
54
+ # with "Exit code N\n..." (no "Error: " prefix). Anchored at the string START
55
+ # so a successful command whose output merely contains "Exit code 1" on a later
56
+ # line cannot misfire the failure parse.
57
+ _EXIT_CODE_RESPONSE_RE_CODEX = re.compile(r"^Exit code (\d+)\s*\n?")
58
+
59
+ # Claude Code omits agent_id for the main context. Keep that context on the
60
+ # historical session-only store id while giving every explicit agent its own
61
+ # store. This sentinel is process-local plumbing, never persisted as an id.
62
+ _MAIN_AGENT_SENTINEL = "__main_agent__"
63
+ _DEDUP_AGENT_ENV = "TOKEN_OPTIMIZER_DEDUP_AGENT_ID"
64
+ # Window for recognising a twin hook that predates last_tool_use_id (see
65
+ # _crossturn_dedup). Two processes for one call land well inside it.
66
+ _LEGACY_TWIN_SECONDS = 2.0
67
+
68
+
69
+ def _pending_redaction_warning() -> str | None:
70
+ """One-time user-facing warning that custom redaction is inactive.
71
+
72
+ Populated only when a configured pattern file failed to load; folds into
73
+ the hook's own JSON envelope as ``systemMessage`` so the user sees it
74
+ instead of only a stderr line."""
75
+ try:
76
+ from credential_patterns import pop_redaction_warning
77
+ return pop_redaction_warning()
78
+ except Exception:
79
+ return None
80
+
81
+
82
+ def main() -> None:
83
+ """Read PostToolUse hook input, compress Bash stdout if eligible."""
84
+ try:
85
+ from hook_io import read_stdin_hook_input
86
+ payload = read_stdin_hook_input(max_bytes=5_242_880) # 5MB
87
+ if not payload:
88
+ return
89
+ except (json.JSONDecodeError, OSError, ImportError):
90
+ return # Bad input, exit silently
91
+
92
+ # CC delivers the session id in the PostToolUse payload, not the env. Thread
93
+ # it into CLAUDE_SESSION_ID so the archive key, cross-turn dedup, and the
94
+ # savings log (all of which read the env) attribute to the real session
95
+ # instead of "". Empty session_id priced every event oneshot-only, dropping
96
+ # its reread annuity (current-week-undercount). Scoped to this hook run:
97
+ # the finally below removes it again so in-process callers never observe a
98
+ # mutated parent environment.
99
+ _sid = str(payload.get("session_id", "") or "")
100
+ _injected = bool(_sid) and not os.environ.get("CLAUDE_SESSION_ID")
101
+ if _injected:
102
+ os.environ["CLAUDE_SESSION_ID"] = _sid
103
+ # Payload identity is authoritative for this invocation. A hook process may
104
+ # be reused or nested with a stale value in its environment, so always
105
+ # override it for the call, then restore the exact prior state. A supplied
106
+ # agent_id is an OPAQUE identity: strip is consulted ONLY to decide
107
+ # emptiness, never to normalize. A whitespace-only agent_id is not a real
108
+ # identity, so it falls back to the main-agent sentinel and a host that
109
+ # sends " " cannot silently fork the main agent off its own dedup/streak
110
+ # history. A non-empty id is carried through UN-stripped, so " agent-A " and
111
+ # "agent-A" stay distinct stores (no accidental merge of two supplied ids).
112
+ _raw_agent_id = str(payload.get("agent_id", "") or "")
113
+ _agent_context = _raw_agent_id if _raw_agent_id.strip() else _MAIN_AGENT_SENTINEL
114
+ _agent_was_present = _DEDUP_AGENT_ENV in os.environ
115
+ _previous_agent_context = os.environ.get(_DEDUP_AGENT_ENV)
116
+ os.environ[_DEDUP_AGENT_ENV] = _agent_context
117
+ try:
118
+ _run(payload)
119
+ finally:
120
+ if _agent_was_present:
121
+ # os.environ values are always strings when the key is present, so
122
+ # the restore is unconditional (the prior value may be "" but never
123
+ # None here).
124
+ os.environ[_DEDUP_AGENT_ENV] = _previous_agent_context
125
+ else:
126
+ os.environ.pop(_DEDUP_AGENT_ENV, None)
127
+ if _injected:
128
+ del os.environ["CLAUDE_SESSION_ID"]
129
+
130
+
131
+ def _run(payload: dict) -> None:
132
+ tool_name = payload.get("tool_name", "")
133
+ if tool_name != "Bash":
134
+ return
135
+
136
+ from recovery_output import is_recovery_output
137
+ if is_recovery_output(tool_name, payload.get("tool_input", {})):
138
+ return
139
+
140
+ # Extract tool response across ALL host payload shapes so the thrash guard
141
+ # records EVERY Bash run (not just the ones with a shape we recognize):
142
+ # - Claude Code PostToolUse: dict with stdout/stderr/exit_code
143
+ # - Claude Code PostToolUseFailure: ``error`` string "Exit code N\n..."
144
+ # (handled by the separate PostToolUseFailure path, not here)
145
+ # - Codex/Cowork PostToolUse: dict with exit_code, OR a plain string
146
+ # "Exit code N\n..." (no "Error: " prefix)
147
+ # - Any host: a plain string that does not match a failure prefix is a
148
+ # successful command's output (exit_code=0) -- do NOT return early,
149
+ # or the thrash guard never records it.
150
+ tool_response = payload.get("tool_response", {})
151
+ exit_code: int | None = None
152
+ if isinstance(tool_response, str):
153
+ m = _EXIT_CODE_RESPONSE_RE.match(tool_response)
154
+ if m is None:
155
+ m = _EXIT_CODE_RESPONSE_RE_CODEX.match(tool_response)
156
+ if m is not None:
157
+ exit_code = int(m.group(1))
158
+ stdout = tool_response[m.end():]
159
+ stderr = ""
160
+ else:
161
+ # No failure prefix: treat as a successful command's output so the
162
+ # thrash guard still records it. exit_code stays None (success).
163
+ stdout = tool_response
164
+ stderr = ""
165
+ else:
166
+ if not tool_response or not isinstance(tool_response, dict):
167
+ return
168
+
169
+ # Skip interrupted or image output
170
+ if tool_response.get("interrupted", False):
171
+ return
172
+ if tool_response.get("isImage", False):
173
+ return
174
+
175
+ stdout = tool_response.get("stdout", "") or ""
176
+ stderr = tool_response.get("stderr", "") or ""
177
+ structured_exit = tool_response.get("exit_code")
178
+ if isinstance(structured_exit, int):
179
+ exit_code = structured_exit
180
+
181
+ # Get the command that was run
182
+ tool_input = payload.get("tool_input", {})
183
+ command = tool_input.get("command", "")
184
+ if not command:
185
+ return
186
+
187
+ # Runtime thrash guard: record EVERY Bash run and, when the same command
188
+ # has produced byte-identical output >= 3 times in a row, append a one-line
189
+ # nudge. Nudge-only: the command already ran, nothing is denied, and any
190
+ # material output change resets the streak inside thrash_guard.check().
191
+ # Runs BEFORE every eligibility gate below because thrash is exactly the
192
+ # small-output / failing-command case those gates skip, and before the
193
+ # already-compressed marker check so PreToolUse-compressed repeats are
194
+ # counted too. The nudge is saved and appended at whichever exit point
195
+ # the compression pipeline reaches, so compression/dedup still runs on
196
+ # nudge-firing runs (a large thrashing output is deduped, not skipped).
197
+ _nudge = None
198
+ try:
199
+ from thrash_guard import check as _thrash_check
200
+ # Scope the thrash streak store by the SAME agent identity as the
201
+ # cross-turn dedup path (issue #189). Without this, the streak store
202
+ # keys on the bare session id, so a subagent gets a "ran N times this
203
+ # session" nudge for runs the MAIN agent made, and the subagent's runs
204
+ # bump the main agent's streak -- the exact cross-agent contamination
205
+ # the dedup path was scoped to prevent. Pass the already-computed scoped
206
+ # store id (a string, so no circular import back into this module). The
207
+ # main/no-agent case resolves to the bare session id, so behavior there
208
+ # is byte-identical to before.
209
+ _thrash_store_id = _dedup_store_id(
210
+ os.environ.get("CLAUDE_SESSION_ID", ""),
211
+ os.environ.get(_DEDUP_AGENT_ENV, _MAIN_AGENT_SENTINEL),
212
+ )
213
+ _nudge = _thrash_check(command, stdout, stderr=stderr,
214
+ exit_code=exit_code, store_id=_thrash_store_id)
215
+ except Exception:
216
+ pass # Fail open: the raw output stands
217
+
218
+ # Codex-via-install perf optimization: TOKEN_OPTIMIZER_NO_UPDATED_TOOL_OUTPUT
219
+ # skips the compression compute entirely. updatedToolOutput is ignored by
220
+ # Codex anyway (collapse there is via archival), so skipping the compute
221
+ # loses nothing. The nudge still reaches the model via additionalContext,
222
+ # which every host honors (Claude Code, Codex, Cowork). One nudge, once.
223
+ if os.environ.get("TOKEN_OPTIMIZER_NO_UPDATED_TOOL_OUTPUT", "").strip():
224
+ _redact_warn = _pending_redaction_warning()
225
+ if _nudge or _redact_warn:
226
+ _payload = {"hookSpecificOutput": {
227
+ "hookEventName": "PostToolUse",
228
+ "additionalContext": _nudge,
229
+ }}
230
+ if _redact_warn:
231
+ _payload["systemMessage"] = _redact_warn
232
+ print(json.dumps(_payload))
233
+ return
234
+
235
+ # Too small to compress
236
+ if not stdout or len(stdout) < 100:
237
+ if _nudge:
238
+ _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
239
+ return
240
+
241
+ # Detect if the output was ALREADY compressed by PreToolUse bash_hook.
242
+ if "[Full result archived" in stdout or "[bash_compress]" in stdout:
243
+ if _nudge:
244
+ _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
245
+ return
246
+
247
+ # Check pipeline read-only eligibility
248
+ try:
249
+ from pipeline_analyzer import is_read_only_pipeline
250
+ is_ro, reason = is_read_only_pipeline(command)
251
+ if not is_ro:
252
+ # --- K1: build/test/run output compression (PostToolUse) ---
253
+ # The command is not read-only, so the standard compression path
254
+ # skips it. But build/test/run commands (gcc, pytest, cargo, npm,
255
+ # make, ...) produce the bulk of agent tokens and are safe to
256
+ # compress PostToolUse: the command already ran, we only compress
257
+ # the captured stdout. Fail-open at every step.
258
+ #
259
+ # Performance guard: the line-count gate and the
260
+ # command-string classify() must run BEFORE importing
261
+ # build_output_compress, so small non-read-only commands (the
262
+ # common case) pay no import cost. The gate mirrors
263
+ # build_output_compress._MIN_COMPRESS_LINES without the import.
264
+ if stdout and len(stdout.splitlines()) >= 25:
265
+ try:
266
+ # Stage 1: command-string classification (no import needed
267
+ # for the check itself; classify() is a pure function that
268
+ # only uses shlex + a static dict).
269
+ from build_output_compress import classify as _build_classify
270
+ _is_build = _build_classify(command)
271
+ # Stage 2: shape fallback only if command didn't match and
272
+ # the output is large enough to justify the scan.
273
+ if not _is_build:
274
+ from build_output_compress import classify_by_shape as _build_shape
275
+ _is_build = _build_shape(stdout, command)
276
+ if _is_build:
277
+ _compressed_build = _try_build_output_compress(
278
+ command, stdout)
279
+ if _compressed_build is not None:
280
+ _emit_updated_tool_output(
281
+ _compressed_build, stderr, nudge=_nudge)
282
+ return
283
+ except Exception:
284
+ pass # Fail open: raw output stands
285
+ if _nudge:
286
+ _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
287
+ return # Not eligible, pass through raw
288
+ except Exception:
289
+ if _nudge:
290
+ _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
291
+ return # Fail open
292
+
293
+ # Compression
294
+ try:
295
+ script_dir = str(Path(__file__).resolve().parent)
296
+ if script_dir not in sys.path:
297
+ sys.path.insert(0, script_dir)
298
+
299
+ from bash_compress import (
300
+ compress,
301
+ _looks_like_failure,
302
+ _strip_ansi,
303
+ _find_preserved_lines,
304
+ _ERROR_STDERR_PATTERNS,
305
+ _enforce_baseline_invariant,
306
+ )
307
+
308
+ # --- check for failure (exit code or stderr patterns) ---
309
+ if _looks_like_failure(exit_code, stderr):
310
+ if _nudge:
311
+ _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
312
+ return # Don't compress failure output
313
+
314
+ # Clean ANSI escape codes before compression
315
+ cleaned_stdout = _strip_ansi(stdout)
316
+
317
+ # --- also scan stdout for error patterns ---
318
+ # When stderr is redirected to stdout (2>&1), error lines appear
319
+ # on stdout. If the pipeline exits 0 but stdout contains error
320
+ # patterns, pass through raw so the model sees the errors.
321
+ if _stdout_has_error_patterns(cleaned_stdout):
322
+ if _nudge:
323
+ _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
324
+ return # Error on stdout: pass through raw
325
+
326
+ # Run the standard compression pipeline
327
+ compressed = compress(command, cleaned_stdout, returncode=exit_code, stderr=stderr)
328
+
329
+ # Best single-output representation: the compressed preview when it
330
+ # actually shrank the output by >=10%, else the raw output.
331
+ from token_estimate import estimate_tokens as _est
332
+ orig_tokens = _est(cleaned_stdout)
333
+ comp_helped = bool(compressed) and compressed != cleaned_stdout and (
334
+ orig_tokens == 0 or (1.0 - _est(compressed) / orig_tokens) >= 0.10)
335
+ best = compressed if comp_helped else cleaned_stdout
336
+
337
+ # Cross-turn dedup: if this command's output repeats a recent same-session
338
+ # run, emit a compact delta reference instead. Catches repeats even when
339
+ # single-output compression did not help (a small repeated `git status`),
340
+ # which per-command tools cannot do -- they have no session memory.
341
+ deduped = _crossturn_dedup(command, best, str(payload.get("tool_use_id", "") or ""))
342
+ _log_feature = "bash_compress_pipeline"
343
+ if deduped is not None:
344
+ best, comp_helped = deduped, True
345
+ _log_feature = "crossturn_dedup"
346
+
347
+ if not comp_helped:
348
+ if _nudge:
349
+ _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
350
+ return # nothing shrank the output -> pass through raw
351
+ compressed = best
352
+
353
+ # --- archive raw stdout + attach a retrieval pointer ---
354
+ # Progressive disclosure: the full uncompressed original is stored
355
+ # on disk so the model can retrieve it via `expand <key>`. Mirror
356
+ # the exact archiving path from bash_compress.main().
357
+ _archive_key = None
358
+ if len(stdout) > 500:
359
+ try:
360
+ from archive_result import (
361
+ archive_entry_exists,
362
+ archive_original,
363
+ build_archive_pointer,
364
+ )
365
+ _session_id = os.environ.get("CLAUDE_SESSION_ID", "")
366
+ _archive_key = hashlib.sha256(
367
+ f"{_session_id}|{command}|{time.time()}|{os.urandom(4).hex()}".encode("utf-8", errors="replace")
368
+ ).hexdigest()[:16]
369
+ if archive_original(stdout, _session_id, _archive_key, "Bash") is not None:
370
+ if archive_entry_exists(_session_id, _archive_key):
371
+ compressed = build_archive_pointer(compressed, len(stdout), _archive_key)
372
+ else:
373
+ # Entry was pruned after write — serve raw, not lossy preview.
374
+ # This matches the guarantee in bash_compress.main().
375
+ compressed = stdout
376
+ _archive_key = None
377
+ else:
378
+ _archive_key = None
379
+ except Exception:
380
+ _archive_key = None
381
+
382
+ # --- enforce the baseline-size invariant ---
383
+ # If our compressed preview + archive pointer would exceed what
384
+ # Claude Code would show as a baseline stub, shrink to fit.
385
+ try:
386
+ compressed = _enforce_baseline_invariant(compressed, stdout, _archive_key)
387
+ except Exception:
388
+ pass
389
+
390
+ # Log compression event to trends.db
391
+ _log_event(command, cleaned_stdout, compressed, feature=_log_feature)
392
+
393
+ # Emit updatedToolOutput to replace what Claude sees. The thrash nudge,
394
+ # if present, goes out as additionalContext in the same envelope (every
395
+ # host honors it), NOT appended to the compressed stdout, so Claude Code
396
+ # users see the nudge exactly once and Codex/Cowork users see it too.
397
+ _emit_updated_tool_output(compressed, stderr, nudge=_nudge)
398
+
399
+ except Exception:
400
+ if _nudge:
401
+ _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
402
+ return # Fail open: any error → pass through raw
403
+
404
+
405
+ # C-3: pre-compiled combined error pattern regex. The old code iterated
406
+ # every line against all 13 patterns with no early termination: O(lines ×
407
+ # 13). Measured: 2.9s for 10K lines, 9.5s for 50K lines (clean output),
408
+ # exceeding the ~2s PostToolUse hook timeout. A single combined regex
409
+ # does one DFA pass per line instead of 13, and the early-exit below
410
+ # returns as soon as the density threshold is met.
411
+ _COMBINED_ERROR_RE = None
412
+
413
+
414
+ def _get_combined_error_re():
415
+ """Lazily build the combined error pattern regex on first call."""
416
+ global _COMBINED_ERROR_RE
417
+ if _COMBINED_ERROR_RE is not None:
418
+ return _COMBINED_ERROR_RE
419
+ try:
420
+ from bash_compress import _ERROR_STDERR_PATTERNS
421
+ # Join all patterns into a single alternation. N-2: each pattern's
422
+ # case sensitivity is preserved by wrapping only the originally
423
+ # case-insensitive patterns in a scoped inline (?i:...) group. A
424
+ # global re.I would silently upgrade the case-sensitive patterns
425
+ # (\bFAILED\b,
426
+ # \bTraceback\b) and made benign output containing lowercase
427
+ # "failed"/"traceback" trip the error-density gate.
428
+ parts = []
429
+ for pat in _ERROR_STDERR_PATTERNS:
430
+ if pat.flags & re.I:
431
+ parts.append(f"(?i:{pat.pattern})")
432
+ else:
433
+ parts.append(f"(?:{pat.pattern})")
434
+ _COMBINED_ERROR_RE = re.compile("|".join(parts))
435
+ except Exception:
436
+ _COMBINED_ERROR_RE = False # sentinel: build failed
437
+ return _COMBINED_ERROR_RE
438
+
439
+
440
+ def _stdout_has_error_patterns(stdout: str) -> bool:
441
+ """Check stdout for error patterns (covers 2>&1 redirect case).
442
+
443
+ Uses the same _ERROR_STDERR_PATTERNS list as _looks_like_failure.
444
+ Only triggers when stdout is large enough to make compression
445
+ meaningful (>500 chars), so small outputs with coincidental
446
+ error-keyword lines are not blocked.
447
+ """
448
+ if not stdout or len(stdout) < 500:
449
+ return False
450
+ try:
451
+ combined = _get_combined_error_re()
452
+ if not combined:
453
+ # Fallback: fall back to the old per-pattern loop if the
454
+ # combined regex could not be built.
455
+ from bash_compress import _ERROR_STDERR_PATTERNS
456
+ lines = stdout.splitlines()
457
+ match_count = 0
458
+ for line in lines:
459
+ for pat in _ERROR_STDERR_PATTERNS:
460
+ if pat.search(line):
461
+ match_count += 1
462
+ break
463
+ if match_count >= 3 and match_count > len(lines) * 0.10:
464
+ return True
465
+ return False
466
+ # C-3: single combined regex per line + early exit when the
467
+ # density threshold is met. O(lines × 1) instead of O(lines × 13).
468
+ lines = stdout.splitlines()
469
+ total_lines = len(lines)
470
+ threshold = total_lines * 0.10
471
+ match_count = 0
472
+ for line in lines:
473
+ if combined.search(line):
474
+ match_count += 1
475
+ # Early exit: once we have enough matches AND the density
476
+ # threshold is met, no need to scan the rest.
477
+ if match_count >= 3 and match_count > threshold:
478
+ return True
479
+ # Final check in case we never hit the early-exit condition but
480
+ # the full scan meets the threshold.
481
+ if match_count >= 3 and match_count > threshold:
482
+ return True
483
+ except Exception:
484
+ return False
485
+ return False
486
+
487
+
488
+ def _dedup_store_id(session_id: str, agent_id: str) -> str:
489
+ """Return the storage identity for one model-visible conversation context.
490
+
491
+ Main-agent calls retain the historical session id exactly. Explicit agents
492
+ use a short digest so arbitrary host identifiers cannot create invalid or
493
+ excessively long SQLite filenames. A supplied agent_id is an OPAQUE identity:
494
+ strip is consulted ONLY to decide emptiness, never to normalize. A
495
+ whitespace-only agent_id is not a real identity, so it falls back to the
496
+ session-only id and a host that sends " " cannot fork the main agent off its
497
+ own history. A non-empty id is hashed exactly as received (un-stripped), so
498
+ " agent-A ", "agent-A", and "agent-A " are three DISTINCT stores.
499
+ """
500
+ stripped = (agent_id or "").strip()
501
+ if not stripped or agent_id == _MAIN_AGENT_SENTINEL:
502
+ return session_id
503
+ agent_digest = hashlib.sha256(
504
+ agent_id.encode("utf-8", errors="replace")
505
+ ).hexdigest()[:16]
506
+ return f"{session_id}-agent-{agent_digest}"
507
+
508
+
509
+ def _crossturn_dedup(command: str, output: str, tool_use_id: str = ""):
510
+ """Return a compact delta-reference when this command's output repeats a
511
+ recent same-session run, else None.
512
+
513
+ Per-command wrappers (e.g. Boost) compress each invocation in isolation and
514
+ so re-pay for every re-run of `git status`, `ls`, a test suite, etc. Token
515
+ Optimizer is a session-stateful hook, so it can collapse the repeat: the
516
+ identical case becomes a one-line note, a small change becomes just the diff.
517
+ Reuses the (previously dormant) command_outputs store + delta_diff. The
518
+ caller still attaches the progressive-disclosure pointer, so `expand`
519
+ recovers the full (credential-redacted) output even if the referenced run
520
+ has scrolled out of context -- the reference is self-sufficient, never a
521
+ dangling pointer.
522
+ Never raises (fail-open): any trouble returns None and normal output stands.
523
+ """
524
+ try:
525
+ session_id = os.environ.get("CLAUDE_SESSION_ID", "")
526
+ if not session_id or len(output) < 200:
527
+ return None
528
+ from session_store import SessionStore
529
+ from delta_diff import content_hash, compute_delta
530
+ # Canonical source: credential_patterns.redact_credentials. Importing the
531
+ # private archive_result._redact_credentials wrapper coupled this hot path
532
+ # to archive_result's import side effects and its _TOKEN_PATTERNS fallback
533
+ # (which emits generic [REDACTED] labels). The shared module is the single
534
+ # owner of the labeled-placeholder redaction contract (L-1).
535
+ from credential_patterns import redact_credentials as _redact_credentials
536
+
537
+ agent_id = os.environ.get(_DEDUP_AGENT_ENV, _MAIN_AGENT_SENTINEL)
538
+ store = SessionStore(_dedup_store_id(session_id, agent_id))
539
+ try:
540
+ cmd_h = content_hash(command.strip())
541
+ out_h = content_hash(output) # identical-detection stays on raw bytes
542
+ # Redact before anything is persisted or diffed, mirroring the
543
+ # archive path (archive_result._redact_credentials), so a secret in
544
+ # command output never reaches the on-disk dedup store.
545
+ safe_output = _redact_credentials(output)
546
+ # The command itself can carry inline secrets (an auth header, a
547
+ # -pPASSWORD, a connection string). Redact BEFORE truncating so a
548
+ # secret split across the 500-char cutoff can't survive, matching the
549
+ # archive path which redacts the command too. cmd_h stays on the raw
550
+ # command -- the hash is non-reversible, like out_h.
551
+ safe_command = _redact_credentials(command, command=True)[:500]
552
+ prior = store.get_command_output(cmd_h)
553
+ # Record THIS run (redacted output) for the next comparison BEFORE we
554
+ # return a delta, so deltas always chain off full (redacted) outputs,
555
+ # not refs.
556
+ store.insert_command_output(
557
+ cmd_h, safe_command, out_h, len(output), safe_output,
558
+ tool_use_id=tool_use_id,
559
+ )
560
+ if not prior or not prior.get("compressed_output"):
561
+ return None
562
+ # Same tool_use_id = the SAME command seen by a second Token Optimizer
563
+ # install (e.g. a synced Cowork copy that predates the stand-down fix),
564
+ # not a re-run. Referencing it would say "identical to your previous
565
+ # output" about output the model has never seen.
566
+ if tool_use_id and prior.get("last_tool_use_id") == tool_use_id:
567
+ return None
568
+ # A pre-fix install writes no tool_use_id, so its twin row can only be
569
+ # recognised by shape: same bytes, written a moment ago. A genuine
570
+ # re-run this fast is rare, and missing one dedup costs nothing.
571
+ if (tool_use_id and not prior.get("last_tool_use_id")
572
+ and prior.get("output_hash") == out_h
573
+ and time.time() - float(prior.get("timestamp") or 0) < _LEGACY_TWIN_SECONDS):
574
+ return None
575
+ # Recency guard: only reference a run from the last hour, a rough
576
+ # proxy for "probably still in the agent's context".
577
+ if time.time() - float(prior.get("timestamp") or 0) > 3600:
578
+ return None
579
+ # C-1: the label is embedded in the ref string that becomes
580
+ # updatedToolOutput.stdout (the model sees it) AND is logged to
581
+ # trends.db as compressed_text via _log_event. Use the redacted
582
+ # command so an inline secret (Bearer token, -pPASSWORD, connection
583
+ # string) never reaches the model context or disk. safe_command is
584
+ # already computed above and in scope.
585
+ label = safe_command.strip()[:60]
586
+ if prior.get("output_hash") == out_h:
587
+ ref = (f"[Token Optimizer: identical to your previous `{label}` "
588
+ f"output this session; unchanged.]")
589
+ else:
590
+ delta, _stats = compute_delta(
591
+ prior["compressed_output"], safe_output, filename=label)
592
+ if not delta:
593
+ return None
594
+ ref = (f"[Token Optimizer: same as your previous `{label}` output "
595
+ f"this session, except:]\n{delta}")
596
+ return ref if len(ref) < len(output) * 0.85 else None
597
+ finally:
598
+ store.close()
599
+ except Exception as exc:
600
+ # M-15: log the exception type (not the message, which may contain
601
+ # unredacted text) so an admin can distinguish "no prior run" from
602
+ # "redaction failed" from logs. Fail-open: still return None.
603
+ try:
604
+ sys.stderr.write(
605
+ f"[Token Optimizer] crossturn dedup failed: "
606
+ f"{type(exc).__name__}\n"
607
+ )
608
+ sys.stderr.flush()
609
+ except (OSError, ValueError):
610
+ pass
611
+ return None
612
+
613
+
614
+ def _log_event(command: str, original: str, compressed: str,
615
+ feature: str = "bash_compress_pipeline") -> None:
616
+ """Log a compression event to trends.db. Fail-open, never raises.
617
+
618
+ ``feature`` distinguishes the plain pipeline path ("bash_compress_pipeline")
619
+ from the session-stateful cross-turn dedup ("crossturn_dedup") so each shows
620
+ in its own dashboard bucket. Both are headline-eligible categories.
621
+ """
622
+ try:
623
+ from compression_log import log_compression_event
624
+ # C-2: command_pattern is persisted to trends.db's compression_events
625
+ # table. Redact BEFORE truncating so an inline secret (Bearer token,
626
+ # mysql -pPASSWORD, PGPASSWORD=... psql) never reaches disk in
627
+ # cleartext. The dedup store path was redacted by PR #164 but this
628
+ # adjacent path in the same main() flow was missed.
629
+ from credential_patterns import redact_credentials as _redact
630
+ session_id = os.environ.get("CLAUDE_SESSION_ID", "")
631
+ log_compression_event(
632
+ feature=feature,
633
+ original_text=original,
634
+ compressed_text=compressed,
635
+ session_id=session_id,
636
+ command_pattern=_redact(command)[:100],
637
+ quality_preserved=True,
638
+ verified=True,
639
+ tier="measured",
640
+ )
641
+ except Exception:
642
+ pass
643
+
644
+
645
+ def _try_build_output_compress(command: str, stdout: str) -> str | None:
646
+ """Compress build/test/run output and attach the archive pointer.
647
+
648
+ Called from the not-read-only branch when classify() or classify_by_shape()
649
+ says the output is build/test/run. Returns the compressed+archived output,
650
+ or None to signal "pass through raw". Fail-open: any exception -> None.
651
+
652
+ Mirrors the read-only compression path: strip ANSI, compress, archive the
653
+ full original, attach the expand pointer, enforce the baseline invariant,
654
+ log to trends.db with feature=build_output_compress.
655
+ """
656
+ try:
657
+ script_dir = str(Path(__file__).resolve().parent)
658
+ if script_dir not in sys.path:
659
+ sys.path.insert(0, script_dir)
660
+
661
+ from bash_compress import _strip_ansi, _enforce_baseline_invariant
662
+ from build_output_compress import compress as _build_compress
663
+
664
+ cleaned_stdout = _strip_ansi(stdout)
665
+ compressed = _build_compress(command, cleaned_stdout)
666
+ if not compressed or compressed == cleaned_stdout:
667
+ return None
668
+
669
+ # Check that compression actually helped by >= 10%
670
+ from token_estimate import estimate_tokens as _est
671
+ orig_tokens = _est(cleaned_stdout)
672
+ if orig_tokens > 0:
673
+ comp_tokens = _est(compressed)
674
+ if (1.0 - comp_tokens / orig_tokens) < 0.10:
675
+ return None
676
+
677
+ # Archive raw stdout + attach retrieval pointer (same path as read-only)
678
+ # F6: if archiving was attempted but failed (exception, or archive
679
+ # returned None, or the entry was pruned after write), return None so
680
+ # the caller serves raw stdout. Never return a lossy preview with no
681
+ # archive pointer — the model would have no way to retrieve the original.
682
+ _archive_attempted = len(stdout) > 500
683
+ _archive_key = None
684
+ if _archive_attempted:
685
+ try:
686
+ from archive_result import (
687
+ archive_entry_exists,
688
+ archive_original,
689
+ build_archive_pointer,
690
+ )
691
+ _session_id = os.environ.get("CLAUDE_SESSION_ID", "")
692
+ _key = hashlib.sha256(
693
+ f"{_session_id}|{command}|{time.time()}|{os.urandom(4).hex()}".encode("utf-8", errors="replace")
694
+ ).hexdigest()[:16]
695
+ # _archive_key stays None until both archive write and
696
+ # existence check succeed, so any failure path (exception,
697
+ # archive_original returning None, entry pruned) leaves it
698
+ # None and the post-block check returns raw.
699
+ if archive_original(stdout, _session_id, _key, "Bash") is not None:
700
+ if archive_entry_exists(_session_id, _key):
701
+ compressed = build_archive_pointer(compressed, len(stdout), _key)
702
+ _archive_key = _key
703
+ except Exception:
704
+ pass
705
+
706
+ # F6: archive failure -> raw, never lossy preview.
707
+ if _archive_attempted and _archive_key is None:
708
+ return None
709
+
710
+ # Enforce the baseline-size invariant
711
+ try:
712
+ compressed = _enforce_baseline_invariant(compressed, stdout, _archive_key)
713
+ except Exception:
714
+ pass
715
+
716
+ # Log to trends.db with the build_output_compress feature
717
+ _log_event(command, cleaned_stdout, compressed, feature="build_output_compress")
718
+
719
+ return compressed
720
+ except Exception:
721
+ return None
722
+
723
+
724
+ def _emit_updated_tool_output(stdout: str, stderr: str,
725
+ nudge: str | None = None) -> None:
726
+ """Emit the PostToolUse updatedToolOutput envelope, with an optional nudge
727
+ carried as additionalContext.
728
+
729
+ The compression/replacement goes in ``updatedToolOutput`` (honored by Claude
730
+ Code; ignored as an unrecognized field by Codex/Cowork, where long-output
731
+ collapse is via ``archive_result`` archival instead). The nudge goes in
732
+ ``additionalContext``, which every host honors, so burn/inline nudges reach
733
+ the model on Claude Code AND Codex AND Cowork. The nudge is NOT duplicated
734
+ inside ``updatedToolOutput``, so Claude Code users see it exactly once.
735
+
736
+ ``TOKEN_OPTIMIZER_NO_UPDATED_TOOL_OUTPUT`` is checked in ``main()`` before
737
+ any compression compute, so this function is only reached on hosts that
738
+ honor ``updatedToolOutput`` (Claude Code) or on Codex-via-marketplace (which
739
+ shares the byte-identical hooks.json and ignores the field harmlessly). The
740
+ codex-install profile sets the env flag to skip the compression compute as a
741
+ perf optimization; the nudge still goes out via ``additionalContext`` from
742
+ the early-return path in ``main()``.
743
+ """
744
+ envelope: dict = {
745
+ "hookSpecificOutput": {
746
+ "hookEventName": "PostToolUse",
747
+ "updatedToolOutput": {
748
+ "stdout": stdout,
749
+ "stderr": stderr,
750
+ "interrupted": False,
751
+ "isImage": False,
752
+ },
753
+ }
754
+ }
755
+ if nudge:
756
+ envelope["hookSpecificOutput"]["additionalContext"] = nudge
757
+ # A broken custom pattern file keeps redacted writes out of every cache —
758
+ # surface that once per file hash as a user-visible systemMessage.
759
+ _redact_warn = _pending_redaction_warning()
760
+ if _redact_warn:
761
+ envelope["systemMessage"] = _redact_warn
762
+ print(json.dumps(envelope))
763
+
764
+
765
+ if __name__ == "__main__":
766
+ main()