@alexgreensh/token-optimizer 5.13.62 → 5.13.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/sessionstart_runner.py +25 -4
- package/package.json +1 -1
- package/skills/fleet-auditor/SKILL.md +1 -1
- package/skills/fleet-auditor/scripts/fleet.py +4 -1
- package/skills/fleet-auditor/scripts/shared.py +31 -14
- package/skills/token-coach/SKILL.md +49 -40
- package/skills/token-coach/references/deterministic-stages.md +1 -1
- package/skills/token-coach/references/keepwarm-consent.md +7 -7
- package/skills/token-dashboard/SKILL.md +30 -6
- package/skills/token-optimizer/SKILL.md +42 -44
- package/skills/token-optimizer/assets/dashboard.html +571 -106
- package/skills/token-optimizer/references/agent-prompts.md +4 -1
- package/skills/token-optimizer/references/codex-workflow.md +30 -12
- package/skills/token-optimizer/references/cursor-workflow.md +9 -7
- package/skills/token-optimizer/references/implementation-playbook.md +4 -4
- package/skills/token-optimizer/references/keepwarm-consent.md +7 -7
- package/skills/token-optimizer/references/opencode-workflow.md +4 -2
- package/skills/token-optimizer/references/optimization-checklist.md +9 -9
- package/skills/token-optimizer/references/phase0-setup.md +9 -9
- package/skills/token-optimizer/references/presentation-workflow.md +3 -3
- package/skills/token-optimizer/references/session-continuity.md +1 -1
- package/skills/token-optimizer/references/token-flow-architecture.md +2 -1
- package/skills/token-optimizer/scripts/adapter_hook_command.py +94 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +12 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +4 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +9 -18
- package/skills/token-optimizer/scripts/antigravity_session.py +31 -6
- package/skills/token-optimizer/scripts/archive_result.py +6 -1
- package/skills/token-optimizer/scripts/archive_window.py +274 -0
- package/skills/token-optimizer/scripts/checkpoint_state.py +385 -0
- package/skills/token-optimizer/scripts/codex_install.py +5 -3
- package/skills/token-optimizer/scripts/codex_session.py +149 -1
- package/skills/token-optimizer/scripts/cursor_doctor.py +12 -27
- package/skills/token-optimizer/scripts/cursor_install.py +11 -19
- package/skills/token-optimizer/scripts/devin_source.py +3 -3
- package/skills/token-optimizer/scripts/grok_doctor.py +12 -24
- package/skills/token-optimizer/scripts/grok_install.py +9 -16
- package/skills/token-optimizer/scripts/measure.py +7300 -1642
- package/skills/token-optimizer/scripts/read_cache.py +52 -27
- package/skills/token-optimizer/scripts/recovery_output.py +67 -18
- package/skills/token-optimizer/scripts/refetch_guard.py +9 -3
- package/skills/token-optimizer/scripts/session_activity.py +169 -0
- package/skills/token-optimizer/scripts/session_store.py +127 -9
- package/skills/token-optimizer/scripts/statusline.js +4 -6
|
@@ -446,7 +446,10 @@ Output file: {COORD_PATH}/audit/advanced.md
|
|
|
446
446
|
- Does the user have ANY model routing guidance? (Yes/No)
|
|
447
447
|
- If yes, is it specific (task-to-model table) or vague ("use appropriate models")?
|
|
448
448
|
b. If measure.py trends DB exists (~/.claude/_backups/token-optimizer/trends.db):
|
|
449
|
-
- Run:
|
|
449
|
+
- Run: "$PY" "$MEASURE_PY" trends --json --days 30
|
|
450
|
+
(if either variable is unset in your shell, re-resolve them with the
|
|
451
|
+
SKILL.md Step 0b snippet first; `$PY` is the verified interpreter, never
|
|
452
|
+
the bare `python3` name)
|
|
450
453
|
- If the command fails (non-zero exit) or output is not valid JSON (e.g., prints
|
|
451
454
|
"No session logs found"), treat as "no trends data" and skip to step (d)
|
|
452
455
|
- The JSON output has raw token counts per full model ID (a full id such as a dated Haiku id mapped to a count, e.g. 50000).
|
|
@@ -41,21 +41,39 @@ done <<EOF
|
|
|
41
41
|
$(find -L "$HOME/.claude/skills" "$HOME/.claude/plugins/cache" "$HOME/.claude/token-optimizer" "$HOME/.codex/skills" "$HOME/.codex/plugins/cache" "$HOME/.config/opencode/plugins" -type f -name measure.py -path '*token-optimizer*/scripts/measure.py' 2>/dev/null)
|
|
42
42
|
EOF
|
|
43
43
|
if [ -z "$MEASURE_PY" ]; then echo "[Error] measure.py not found. Is Token Optimizer installed?"; exit 1; fi
|
|
44
|
-
|
|
44
|
+
|
|
45
|
+
# Resolve an interpreter that really runs Python. On native-Windows Git Bash
|
|
46
|
+
# `python3` is often the Microsoft Store alias stub, which prints "Python was
|
|
47
|
+
# not found" instead of running -- and a gate piped to `head` then looks like
|
|
48
|
+
# a pass (#301). Probe `python` first there, `python3` first elsewhere, and
|
|
49
|
+
# accept only a clean >=3.9 version reply (same ladder install.sh uses).
|
|
50
|
+
PY=""; _py_candidates="python3 python"
|
|
51
|
+
case "$(uname -s 2>/dev/null)" in MINGW*|MSYS*|CYGWIN*) _py_candidates="python python3" ;; esac
|
|
52
|
+
for _py in $_py_candidates; do
|
|
53
|
+
command -v "$_py" >/dev/null 2>&1 || continue
|
|
54
|
+
_py_ver="$("$_py" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null)" || _py_ver=""
|
|
55
|
+
_py_major="$(echo "$_py_ver" | cut -d. -f1)"; _py_minor="$(echo "$_py_ver" | cut -d. -f2)"
|
|
56
|
+
[ -n "$_py_major" ] && [ -n "$_py_minor" ] || continue
|
|
57
|
+
case "$_py_major$_py_minor" in *[!0-9]*) continue ;; esac
|
|
58
|
+
if [ "$_py_major" -lt 3 ] 2>/dev/null || { [ "$_py_major" -eq 3 ] && [ "$_py_minor" -lt 9 ]; } 2>/dev/null; then continue; fi
|
|
59
|
+
PY="$_py"; break
|
|
60
|
+
done
|
|
61
|
+
if [ -z "$PY" ]; then echo "[Error] Python 3.9+ not found (the Windows Store python3 stub does not count). Install Python, then retry."; exit 1; fi
|
|
62
|
+
echo "Using: $MEASURE_PY" >&2
|
|
45
63
|
```
|
|
46
64
|
|
|
47
|
-
Use `TOKEN_OPTIMIZER_RUNTIME=codex
|
|
65
|
+
Use `TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" ...` for Codex commands.
|
|
48
66
|
|
|
49
67
|
## 1. Start With Chat Status
|
|
50
68
|
|
|
51
69
|
Run these before giving advice:
|
|
52
70
|
|
|
53
71
|
```bash
|
|
54
|
-
TOKEN_OPTIMIZER_RUNTIME=codex
|
|
55
|
-
TOKEN_OPTIMIZER_RUNTIME=codex
|
|
56
|
-
TOKEN_OPTIMIZER_RUNTIME=codex
|
|
57
|
-
TOKEN_OPTIMIZER_RUNTIME=codex
|
|
58
|
-
TOKEN_OPTIMIZER_RUNTIME=codex
|
|
72
|
+
TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" report
|
|
73
|
+
TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" coach --json
|
|
74
|
+
TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" quality current --json
|
|
75
|
+
TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" codex-state --json
|
|
76
|
+
TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" codex-doctor --project "$PWD" --json
|
|
59
77
|
```
|
|
60
78
|
|
|
61
79
|
`codex-state` reads Codex's versioned SQLite state read-only (`state_*.sqlite`, `goals_*.sqlite`): subagent count and token cost (with leaked/never-closed subagents), memory overhead from `stage1_outputs`, and goal budget utilization. It is empty-safe when those tables have no rows yet.
|
|
@@ -105,8 +123,8 @@ Use `codex-doctor` as the setup truth source.
|
|
|
105
123
|
If hooks are missing or stale:
|
|
106
124
|
|
|
107
125
|
```bash
|
|
108
|
-
TOKEN_OPTIMIZER_RUNTIME=codex
|
|
109
|
-
TOKEN_OPTIMIZER_RUNTIME=codex
|
|
126
|
+
TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" codex-install --project "$PWD" --dry-run
|
|
127
|
+
TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" codex-install --project "$PWD"
|
|
110
128
|
```
|
|
111
129
|
|
|
112
130
|
Default to the balanced profile. Balanced means:
|
|
@@ -120,9 +138,9 @@ Default to the balanced profile. Balanced means:
|
|
|
120
138
|
Only suggest these when the user accepts the tradeoff:
|
|
121
139
|
|
|
122
140
|
```bash
|
|
123
|
-
TOKEN_OPTIMIZER_RUNTIME=codex
|
|
124
|
-
TOKEN_OPTIMIZER_RUNTIME=codex
|
|
125
|
-
TOKEN_OPTIMIZER_RUNTIME=codex
|
|
141
|
+
TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" codex-install --project "$PWD" --profile quiet
|
|
142
|
+
TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" codex-install --project "$PWD" --profile telemetry
|
|
143
|
+
TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" codex-install --project "$PWD" --profile aggressive
|
|
126
144
|
```
|
|
127
145
|
|
|
128
146
|
Quiet is Stop-only. Telemetry adds visible PostToolUse rows. Aggressive enables all current hooks, including experimental Bash PreToolUse. Do not make aggressive the default.
|
|
@@ -34,13 +34,15 @@ The audit phases do not run under Cursor. Use the Cursor-native commands
|
|
|
34
34
|
instead. Manual `cursor-summary` / `cursor-rollup` require the runtime prefix
|
|
35
35
|
(the bridge sets it automatically):
|
|
36
36
|
|
|
37
|
+
Resolve `$MEASURE_PY` and `$PY` first with the SKILL.md Step 0b snippet (this file is followed instead of the audit phases, so they are not set yet).
|
|
38
|
+
|
|
37
39
|
```bash
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
TOKEN_OPTIMIZER_RUNTIME=cursor
|
|
42
|
-
TOKEN_OPTIMIZER_RUNTIME=cursor
|
|
43
|
-
|
|
40
|
+
"$PY" "$MEASURE_PY" cursor-install # wire Token Optimizer into ~/.cursor/hooks.json
|
|
41
|
+
"$PY" "$MEASURE_PY" cursor-doctor # readiness report (checks + fix hints)
|
|
42
|
+
"$PY" "$MEASURE_PY" cursor-doctor --probe # replay each wired event through the installed command
|
|
43
|
+
TOKEN_OPTIMIZER_RUNTIME=cursor "$PY" "$MEASURE_PY" cursor-summary
|
|
44
|
+
TOKEN_OPTIMIZER_RUNTIME=cursor "$PY" "$MEASURE_PY" cursor-rollup
|
|
45
|
+
"$PY" "$MEASURE_PY" cursor-uninstall # remove only Token Optimizer's entries + payload
|
|
44
46
|
```
|
|
45
47
|
|
|
46
48
|
Install from a checkout with `bash install.sh --cursor` (merges into Cursor's
|
|
@@ -67,7 +69,7 @@ If the user genuinely wants to audit a Claude Code setup *from* Cursor (rare),
|
|
|
67
69
|
they can force the runtime:
|
|
68
70
|
|
|
69
71
|
```bash
|
|
70
|
-
TOKEN_OPTIMIZER_RUNTIME=claude
|
|
72
|
+
TOKEN_OPTIMIZER_RUNTIME=claude "$PY" "$MEASURE_PY" report
|
|
71
73
|
```
|
|
72
74
|
|
|
73
75
|
This is opt-in and explicit. The default under Cursor is to never touch
|
|
@@ -180,7 +180,7 @@ Estimated savings: ~X tokens
|
|
|
180
180
|
Handled in Phase 0 setup. If the user skipped it there, offer again here:
|
|
181
181
|
|
|
182
182
|
```bash
|
|
183
|
-
|
|
183
|
+
"$PY" "$MEASURE_PY" check-hook
|
|
184
184
|
```
|
|
185
185
|
|
|
186
186
|
If not installed, run `setup-hook --dry-run` to show the proposed change, then `setup-hook` after confirmation. The hook runs `measure.py collect --quiet` once per session close (~1 second, zero background processes).
|
|
@@ -324,7 +324,7 @@ Add or improve model routing instructions in CLAUDE.md.
|
|
|
324
324
|
- opus: architecture decisions, novel debugging, cross-cutting synthesis
|
|
325
325
|
```
|
|
326
326
|
3. If routing instructions exist, compare against actual model_mix usage:
|
|
327
|
-
- Run `
|
|
327
|
+
- Run `"$PY" "$MEASURE_PY" trends --json --days 30` if trends DB exists
|
|
328
328
|
- Are subagents actually following the routing? (check model_mix percentages)
|
|
329
329
|
- Is the instruction specific enough? ("default to haiku" vs detailed task-to-model table)
|
|
330
330
|
- If >70% of tokens go to Opus despite routing instructions, the instructions may be too vague
|
|
@@ -348,7 +348,7 @@ Check the user's Claude Code version (`claude --version`) and apply version-spec
|
|
|
348
348
|
**v2.1.86+: Read tool native deduplication**
|
|
349
349
|
- Claude Code deduplicates unchanged re-reads natively (compact line-number format)
|
|
350
350
|
- If Token Optimizer's `read_cache.py` PreToolUse hook is installed, it is redundant on v2.1.86+
|
|
351
|
-
- Check: run `
|
|
351
|
+
- Check: run `"$PY" "$MEASURE_PY" read-cache-stats --session current`. If "blocks: 0" for recent sessions, native dedup is handling it.
|
|
352
352
|
- Action: Disable the read-cache hook (`TOKEN_OPTIMIZER_READ_CACHE=0` in settings.json env block) to eliminate hook process overhead
|
|
353
353
|
|
|
354
354
|
**v2.1.86+: @ file mentions no longer JSON-escaped**
|
|
@@ -413,4 +413,4 @@ Check the user's Claude Code version (`claude --version`) and apply version-spec
|
|
|
413
413
|
| User says 'skip verification' | "Noted. Skipping verification. Recommend running /cost before and after to measure actual savings." |
|
|
414
414
|
| Backup is empty/missing | "Backup directory appears empty. This could mean a fresh setup or a write failure. Proceeding without backup, but will not modify any files without explicit user confirmation for each change." |
|
|
415
415
|
| File write fails mid-implementation | "Write failed for [file]. Restoring from backup. Check disk space and permissions." Present the restore command from the Restoring Backups section. |
|
|
416
|
-
| Synthesis output missing | "Synthesis agent did not produce output. Showing raw audit findings instead." Present the individual audit files from
|
|
416
|
+
| Synthesis output missing | "Synthesis agent did not produce output. Showing raw audit findings instead." Present the individual audit files from {COORD_PATH}/audit/ for user review. |
|
|
@@ -5,7 +5,7 @@ Keep-Warm pings the prompt cache before it expires so a paused session resumes w
|
|
|
5
5
|
## 1. Check whether to ask
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
|
-
|
|
8
|
+
"$PY" "$MEASURE_PY" keepwarm-consent-status # JSON: {billing_mode, consent, should_ask}
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
`should_ask` false: say nothing. True (API-billed, not yet asked): continue.
|
|
@@ -13,7 +13,7 @@ python3 "$MEASURE_PY" keepwarm-consent-status # JSON: {billing_mode, consent,
|
|
|
13
13
|
## 2. Compute the user's own projection
|
|
14
14
|
|
|
15
15
|
```bash
|
|
16
|
-
|
|
16
|
+
"$PY" "$MEASURE_PY" keepwarm-backfill --json --no-fence # read modes."probe-only".net_usd
|
|
17
17
|
```
|
|
18
18
|
|
|
19
19
|
## 3. Pitch
|
|
@@ -28,21 +28,21 @@ When a session pauses past its cache window and resumes, the whole prefix is wri
|
|
|
28
28
|
Recording the answer before anything else means an interrupted run never leaves an "asked" marker with no answer.
|
|
29
29
|
|
|
30
30
|
```bash
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
"$PY" "$MEASURE_PY" keepwarm-enable # yes: records consent and installs the scheduler (macOS)
|
|
32
|
+
"$PY" "$MEASURE_PY" keepwarm-disable # no
|
|
33
33
|
```
|
|
34
34
|
|
|
35
35
|
Both are final, so the user is not asked again. Only when the user neither accepts nor declines:
|
|
36
36
|
|
|
37
37
|
```bash
|
|
38
|
-
|
|
38
|
+
"$PY" "$MEASURE_PY" keepwarm-consent-asked # marks the question as shown
|
|
39
39
|
```
|
|
40
40
|
|
|
41
41
|
## 5. Confirm it is armed (after a yes)
|
|
42
42
|
|
|
43
43
|
```bash
|
|
44
|
-
|
|
45
|
-
|
|
44
|
+
"$PY" "$MEASURE_PY" keepwarm-scheduler status # installed and loaded state (macOS)
|
|
45
|
+
"$PY" "$MEASURE_PY" keepwarm-tick --dry-run # what the next tick would decide
|
|
46
46
|
```
|
|
47
47
|
|
|
48
48
|
On Linux and Windows the scheduler is not shipped yet: Keep-Warm runs watchdog-only until the user wires `keepwarm-tick` to their own cron or timer. Tell them that plainly.
|
|
@@ -45,8 +45,10 @@ Or drop a local build into `~/.config/opencode/plugins/` (OpenCode auto-loads it
|
|
|
45
45
|
If the user genuinely wants to audit a Claude Code setup *from* OpenCode (rare),
|
|
46
46
|
they can force the runtime:
|
|
47
47
|
|
|
48
|
+
Resolve `$MEASURE_PY` and `$PY` first with the SKILL.md Step 0b snippet (this file is followed instead of the audit phases, so they are not set yet).
|
|
49
|
+
|
|
48
50
|
```bash
|
|
49
|
-
TOKEN_OPTIMIZER_RUNTIME=claude
|
|
51
|
+
TOKEN_OPTIMIZER_RUNTIME=claude "$PY" "$MEASURE_PY" report
|
|
50
52
|
```
|
|
51
53
|
|
|
52
54
|
This is opt-in and explicit. The default under OpenCode is to never touch
|
|
@@ -64,7 +66,7 @@ hooks into `~/.claude/settings.json` (via `measure.py setup-all-hooks`).
|
|
|
64
66
|
- If you use **OpenCode only**: the Claude hooks are unnecessary. After
|
|
65
67
|
running `install.sh`, remove them with:
|
|
66
68
|
```bash
|
|
67
|
-
|
|
69
|
+
"$PY" ~/.claude/token-optimizer/skills/token-optimizer/scripts/measure.py cleanup-duplicate-hooks
|
|
68
70
|
```
|
|
69
71
|
Or simply re-create the symlink manually:
|
|
70
72
|
```bash
|
|
@@ -468,9 +468,9 @@ See `examples/hooks-starter.json` for a ready-to-use template.
|
|
|
468
468
|
**What it does**: Captures structured session state before compaction fires, then restores the critical pieces after compaction completes. Decisions, error-fix sequences, agent state, and modified files survive the lossy compaction process.
|
|
469
469
|
|
|
470
470
|
**Actions**:
|
|
471
|
-
- [ ] Install Smart Compaction hooks: `
|
|
472
|
-
- [ ] Run `
|
|
473
|
-
- [ ] Generate project-specific Compact Instructions: `
|
|
471
|
+
- [ ] Install Smart Compaction hooks: `"$PY" "$MEASURE_PY" setup-smart-compact --dry-run` (preview first)
|
|
472
|
+
- [ ] Run `"$PY" "$MEASURE_PY" setup-smart-compact` to install
|
|
473
|
+
- [ ] Generate project-specific Compact Instructions: `"$PY" "$MEASURE_PY" compact-instructions`
|
|
474
474
|
- [ ] Add the generated instructions to `.claude/settings.json` under `compactInstructions`
|
|
475
475
|
|
|
476
476
|
**What the hooks do**:
|
|
@@ -490,7 +490,7 @@ See `examples/hooks-starter.json` for a ready-to-use template.
|
|
|
490
490
|
**What it does**: Analyzes your session JSONL and scores how useful your context content is. A session at 60% with clean, relevant content performs differently from 60% stuffed with stale reads and duplicate injections.
|
|
491
491
|
|
|
492
492
|
**Actions**:
|
|
493
|
-
- [ ] Run `
|
|
493
|
+
- [ ] Run `"$PY" "$MEASURE_PY" quality` on your current or recent session
|
|
494
494
|
- [ ] Check your score: 85+ is excellent, 70-84 good, 50-69 degraded, <50 critical
|
|
495
495
|
- [ ] Act on specific issues: stale reads, bloated results, duplicate reminders
|
|
496
496
|
|
|
@@ -498,7 +498,7 @@ See `examples/hooks-starter.json` for a ready-to-use template.
|
|
|
498
498
|
- Stale read ratio (files read then later edited, making the read content outdated)
|
|
499
499
|
- Tool result bloat (large results never referenced again)
|
|
500
500
|
- Duplicate content (repeated system reminders)
|
|
501
|
-
- Compaction
|
|
501
|
+
- Compaction count (descriptive only; measured post-boundary recovery signals are reported separately)
|
|
502
502
|
- Decision density (ratio of substantive to overhead exchanges)
|
|
503
503
|
- Agent efficiency (dispatch cost vs useful result size)
|
|
504
504
|
|
|
@@ -512,16 +512,16 @@ See `examples/hooks-starter.json` for a ready-to-use template.
|
|
|
512
512
|
|
|
513
513
|
```bash
|
|
514
514
|
# Measure current state
|
|
515
|
-
|
|
515
|
+
"$PY" "$MEASURE_PY" report
|
|
516
516
|
|
|
517
517
|
# Save snapshot before optimizing
|
|
518
|
-
|
|
518
|
+
"$PY" "$MEASURE_PY" snapshot before
|
|
519
519
|
|
|
520
520
|
# After optimization
|
|
521
|
-
|
|
521
|
+
"$PY" "$MEASURE_PY" snapshot after
|
|
522
522
|
|
|
523
523
|
# Compare
|
|
524
|
-
|
|
524
|
+
"$PY" "$MEASURE_PY" compare
|
|
525
525
|
```
|
|
526
526
|
|
|
527
527
|
Also track with `/cost` at end of each session and `measure.py trends` for historical data. The SessionEnd hook auto-collects usage into a local SQLite database.
|
|
@@ -21,7 +21,7 @@ Keep this quick, one question max.
|
|
|
21
21
|
|
|
22
22
|
## Quick Pre-Check
|
|
23
23
|
|
|
24
|
-
Run `
|
|
24
|
+
Run `"$PY" "$MEASURE_PY" report`.
|
|
25
25
|
If estimated controllable tokens < 1,000 and no CLAUDE.md exists, short-circuit:
|
|
26
26
|
```
|
|
27
27
|
[Token Optimizer] Your setup is already minimal (~X tokens overhead).
|
|
@@ -63,7 +63,7 @@ mkdir -p "$COORD_PATH"/{audit,analysis,plan,verification}
|
|
|
63
63
|
## SessionEnd Hook Check
|
|
64
64
|
|
|
65
65
|
```bash
|
|
66
|
-
|
|
66
|
+
"$PY" "$MEASURE_PY" check-hook
|
|
67
67
|
```
|
|
68
68
|
- Exit 0: already installed, skip to Phase 1.
|
|
69
69
|
- Exit 1 (manual/script install users only): explain and offer to install:
|
|
@@ -81,7 +81,7 @@ What this does:
|
|
|
81
81
|
- All data stays on your machine (stored in ~/.claude/_backups/token-optimizer/)
|
|
82
82
|
- Powers the Trends and Health tabs in your dashboard
|
|
83
83
|
|
|
84
|
-
Remove anytime:
|
|
84
|
+
Remove anytime: "$PY" "$MEASURE_PY" setup-hook --uninstall
|
|
85
85
|
```
|
|
86
86
|
|
|
87
87
|
Ask user: 1) Install (dry-run first), 2) Show JSON first, 3) Skip
|
|
@@ -90,8 +90,8 @@ Ask user: 1) Install (dry-run first), 2) Show JSON first, 3) Skip
|
|
|
90
90
|
|
|
91
91
|
Run BOTH probes in one pass:
|
|
92
92
|
```bash
|
|
93
|
-
|
|
94
|
-
|
|
93
|
+
"$PY" "$MEASURE_PY" daemon-status
|
|
94
|
+
"$PY" "$MEASURE_PY" daemon-consent --get
|
|
95
95
|
```
|
|
96
96
|
|
|
97
97
|
`daemon-status` prints `DAEMON_RUNNING`, `DAEMON_FOREIGN`, or `DAEMON_NOT_RUNNING`.
|
|
@@ -116,7 +116,7 @@ What installing the URL does:
|
|
|
116
116
|
- Starts automatically at login, restarts if it ever stops
|
|
117
117
|
- Only reachable from this machine (localhost)
|
|
118
118
|
|
|
119
|
-
Remove anytime:
|
|
119
|
+
Remove anytime: "$PY" "$MEASURE_PY" setup-daemon --uninstall
|
|
120
120
|
```
|
|
121
121
|
|
|
122
122
|
Ask user: 1) Install (write consent first, then install), 2) Skip (set consent no)
|
|
@@ -125,7 +125,7 @@ On Linux/BSD: skip silently, mention `file://` URL works.
|
|
|
125
125
|
## Smart Compaction Check
|
|
126
126
|
|
|
127
127
|
```bash
|
|
128
|
-
|
|
128
|
+
"$PY" "$MEASURE_PY" setup-smart-compact --status
|
|
129
129
|
```
|
|
130
130
|
- All 4 hooks installed: skip entirely.
|
|
131
131
|
- Partially or not installed: explain and offer:
|
|
@@ -134,9 +134,9 @@ python3 $MEASURE_PY setup-smart-compact --status
|
|
|
134
134
|
[Token Optimizer] Smart Compaction captures session state BEFORE compaction fires,
|
|
135
135
|
then restores it afterward. Decisions, modified files, errors, agent state.
|
|
136
136
|
|
|
137
|
-
Remove anytime:
|
|
137
|
+
Remove anytime: "$PY" "$MEASURE_PY" setup-smart-compact --uninstall
|
|
138
138
|
```
|
|
139
139
|
|
|
140
140
|
Ask user: 1) Install (dry-run first), 2) Show JSON first, 3) Skip
|
|
141
141
|
|
|
142
|
-
Output: `[Token Optimizer Initialized] Backup:
|
|
142
|
+
Output: `[Token Optimizer Initialized] Backup: {BACKUP_DIR} | Coordination: {COORD_PATH}`
|
|
@@ -39,7 +39,7 @@ What should we tackle first?
|
|
|
39
39
|
## Dashboard Generation
|
|
40
40
|
|
|
41
41
|
```bash
|
|
42
|
-
|
|
42
|
+
"$PY" "$MEASURE_PY" dashboard --coord-path "$COORD_PATH"
|
|
43
43
|
```
|
|
44
44
|
|
|
45
45
|
Tell the user: "Dashboard opened in your browser. Browse findings by category, check the optimizations you want, click Copy Prompt and paste back here. Or just tell me directly what to tackle."
|
|
@@ -48,7 +48,7 @@ Tell the user: "Dashboard opened in your browser. Browse findings by category, c
|
|
|
48
48
|
|
|
49
49
|
Check daemon status first:
|
|
50
50
|
```bash
|
|
51
|
-
|
|
51
|
+
"$PY" "$MEASURE_PY" daemon-status 2>/dev/null || echo "DAEMON_NOT_RUNNING"
|
|
52
52
|
```
|
|
53
53
|
|
|
54
54
|
If DAEMON_RUNNING:
|
|
@@ -64,7 +64,7 @@ Your persistent dashboard (auto-updated every session):
|
|
|
64
64
|
File: <read from `measure.py dashboard` output, line beginning ` Dashboard: `>
|
|
65
65
|
```
|
|
66
66
|
Never hardcode the file path. It is install-dependent, so cite the path the command actually printed.
|
|
67
|
-
On macOS only, suggest: "Want a bookmarkable URL? Run: `
|
|
67
|
+
On macOS only, suggest: "Want a bookmarkable URL? Run: `"$PY" "$MEASURE_PY" setup-daemon`"
|
|
68
68
|
Do NOT mention `localhost:24842` if daemon is not running.
|
|
69
69
|
|
|
70
70
|
For headless/remote: user can run `dashboard --serve` separately. Never use `--serve` from within the orchestrator (it blocks with `serve_forever`).
|
|
@@ -13,7 +13,7 @@ work, check what we discussed last session"), the continuity hook reconstructs a
|
|
|
13
13
|
- **Savings** are credited as a realized `resume_lean` event (avoided cold-resume
|
|
14
14
|
cache-rewrite minus the lean block), idempotent per target session, shown in the
|
|
15
15
|
Savings view. Realized tier, same as `checkpoint_restore`.
|
|
16
|
-
- **Manual fallback**: `
|
|
16
|
+
- **Manual fallback**: `"$PY" "$MEASURE_PY" resume-lean` lists cold sessions;
|
|
17
17
|
`resume-lean <#|session_id> --print` emits the block for `claude "$(...)"`.
|
|
18
18
|
- Ported across Claude Code, Codex, OpenClaw, opencode (checkpoint richness varies
|
|
19
19
|
by platform; the lean block adapts to available fields).
|
|
@@ -367,7 +367,8 @@ Most Claude Code users are on Max subscriptions ($100-200/month), not per-token
|
|
|
367
367
|
35K overhead = 18% of 200K (3.5% of 1M). Compaction arrives that much sooner.
|
|
368
368
|
|
|
369
369
|
2. MORE COMPACTION CYCLES
|
|
370
|
-
Each compaction
|
|
370
|
+
Each compaction rewrites context to a summary; recovery quality is measured
|
|
371
|
+
per boundary, not assumed. More compactions still means more summary passes.
|
|
371
372
|
A session with 35K overhead compacts ~2x more often than 20K.
|
|
372
373
|
|
|
373
374
|
3. QUALITY DEGRADATION
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Hook command text for adapters whose host runs the command through a shell
|
|
2
|
+
(Antigravity, Cursor, Grok).
|
|
3
|
+
|
|
4
|
+
macOS / Linux: ``TOKEN_OPTIMIZER_RUNTIME=<rt> '<python>' [flags] '<bridge>' <event>``,
|
|
5
|
+
POSIX-quoted.
|
|
6
|
+
|
|
7
|
+
Native Windows: the host may run the command through PowerShell or cmd.exe, so
|
|
8
|
+
the text must parse the same in both. That means a bare first token, double-
|
|
9
|
+
quoted arguments and no ``VAR=value`` prefix (cmd.exe and PowerShell both reject
|
|
10
|
+
it). The bridges set TOKEN_OPTIMIZER_RUNTIME themselves, so the prefix is not
|
|
11
|
+
needed. Paths holding a character either shell expands go through their 8.3
|
|
12
|
+
short names, using the same rules as the Codex hooks.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import ntpath
|
|
17
|
+
import os
|
|
18
|
+
import posixpath
|
|
19
|
+
import shlex
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _is_windows(windows: bool | None) -> bool:
|
|
23
|
+
return (os.name == "nt") if windows is None else windows
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build(python: str, bridge: str, event: str, *, runtime: str,
|
|
27
|
+
python_flags: tuple[str, ...] = (), windows: bool | None = None) -> str:
|
|
28
|
+
"""The persisted hook command. Raises RuntimeError on Windows when no
|
|
29
|
+
spelling runs the same under PowerShell and cmd.exe."""
|
|
30
|
+
if not _is_windows(windows):
|
|
31
|
+
parts = [f"TOKEN_OPTIMIZER_RUNTIME={runtime}", shlex.quote(python), *python_flags,
|
|
32
|
+
shlex.quote(bridge), event]
|
|
33
|
+
return " ".join(parts)
|
|
34
|
+
from codex_install import _neutral_child_arg, _shell_neutral_exe # noqa: PLC0415
|
|
35
|
+
|
|
36
|
+
exe = _shell_neutral_exe(python)
|
|
37
|
+
parent, leaf = ntpath.split(bridge)
|
|
38
|
+
bridge_arg = _neutral_child_arg(parent, leaf) if parent and leaf else None
|
|
39
|
+
if exe is None or bridge_arg is None:
|
|
40
|
+
bad = python if exe is None else bridge
|
|
41
|
+
raise RuntimeError(
|
|
42
|
+
f"cannot write a Windows hook command for {bad}: the path holds a character "
|
|
43
|
+
"PowerShell or cmd.exe would expand ($, backtick, %, !) and has no 8.3 short "
|
|
44
|
+
"name. Move it to a plain folder, or set TOKEN_OPTIMIZER_PYTHON to a python "
|
|
45
|
+
"in a plain folder, and re-run the install."
|
|
46
|
+
)
|
|
47
|
+
return " ".join([exe, *python_flags, bridge_arg, event])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def parse(command: str, *, runtime: str, events, python_flags: tuple[str, ...] = (),
|
|
51
|
+
windows: bool | None = None) -> list | None:
|
|
52
|
+
"""Parse a command written by build() into ``[python, bridge, event]``, or
|
|
53
|
+
None when it is not exactly that shape. Strict on purpose: doctors replay
|
|
54
|
+
these commands, so a corrupted or foreign entry must never be accepted."""
|
|
55
|
+
win = _is_windows(windows)
|
|
56
|
+
try:
|
|
57
|
+
# posix=False keeps Windows backslashes; the double quotes stay on the
|
|
58
|
+
# token and are stripped below.
|
|
59
|
+
tokens = shlex.split(command, posix=not win)
|
|
60
|
+
except ValueError:
|
|
61
|
+
return None
|
|
62
|
+
pin = f"TOKEN_OPTIMIZER_RUNTIME={runtime}"
|
|
63
|
+
if win:
|
|
64
|
+
tokens = [t[1:-1] if len(t) >= 2 and t[0] == t[-1] == '"' else t for t in tokens]
|
|
65
|
+
# Older installs wrote the POSIX shape with Windows paths; still ours.
|
|
66
|
+
if tokens and tokens[0] == pin:
|
|
67
|
+
tokens = tokens[1:]
|
|
68
|
+
else:
|
|
69
|
+
if not tokens or tokens[0] != pin:
|
|
70
|
+
return None
|
|
71
|
+
tokens = tokens[1:]
|
|
72
|
+
n = len(python_flags)
|
|
73
|
+
if len(tokens) != 3 + n or tuple(tokens[1:1 + n]) != tuple(python_flags):
|
|
74
|
+
return None
|
|
75
|
+
py, bridge, event = tokens[0], tokens[1 + n], tokens[2 + n]
|
|
76
|
+
isabs = ntpath.isabs if win else posixpath.isabs
|
|
77
|
+
if not isabs(py) or not isabs(bridge) or event not in events:
|
|
78
|
+
return None
|
|
79
|
+
return [py, bridge, event]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def path_spellings(path: str, *, windows: bool | None = None) -> set[str]:
|
|
83
|
+
"""Every spelling build() may have written for ``path``: the path itself
|
|
84
|
+
and, on Windows, the form through its folder's 8.3 short name. Use this
|
|
85
|
+
to recognise our own entries in a shared hooks file."""
|
|
86
|
+
out = {path}
|
|
87
|
+
if _is_windows(windows):
|
|
88
|
+
from codex_install import _short_path # noqa: PLC0415
|
|
89
|
+
|
|
90
|
+
parent, leaf = ntpath.split(path)
|
|
91
|
+
short = _short_path(parent) if parent else None
|
|
92
|
+
if short:
|
|
93
|
+
out.add(short.rstrip("\\/") + "\\" + leaf)
|
|
94
|
+
return out
|
|
@@ -33,6 +33,7 @@ from pathlib import Path
|
|
|
33
33
|
_SCRIPT_DIR = Path(__file__).resolve().parent
|
|
34
34
|
sys.path.insert(0, str(_SCRIPT_DIR))
|
|
35
35
|
|
|
36
|
+
import adapter_hook_command # noqa: E402
|
|
36
37
|
from runtime_env import antigravity_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
|
|
37
38
|
|
|
38
39
|
DAEMON_PORT = 24847
|
|
@@ -196,6 +197,17 @@ def _plugin_checks() -> list:
|
|
|
196
197
|
expected = {"PreInvocation", "PreToolUse", "Stop"}
|
|
197
198
|
if not expected <= set(events):
|
|
198
199
|
raise ValueError(f"missing events: {sorted(expected - set(events))}")
|
|
200
|
+
# Every hook must call the bridge inside this plugin dir. Installs
|
|
201
|
+
# before 5.13.63 named a temporary staging dir that no longer exists.
|
|
202
|
+
bridge = str(pdir / "antigravity_hook_bridge.py")
|
|
203
|
+
spellings = adapter_hook_command.path_spellings(bridge)
|
|
204
|
+
for name in sorted(expected):
|
|
205
|
+
entries = group.get(name) or []
|
|
206
|
+
handlers = [h for e in entries if isinstance(e, dict)
|
|
207
|
+
for h in (e.get("hooks") if isinstance(e.get("hooks"), list) else [e])]
|
|
208
|
+
cmds = [h.get("command", "") for h in handlers if isinstance(h, dict)]
|
|
209
|
+
if not any(isinstance(c, str) and any(s in c for s in spellings) for c in cmds):
|
|
210
|
+
raise ValueError(f"{name} hook does not call {bridge}")
|
|
199
211
|
checks.append(
|
|
200
212
|
_check(
|
|
201
213
|
"ok", "plugin hooks", f"{hooks_path} (events: {', '.join(events)})"
|
|
@@ -466,6 +466,10 @@ def main(argv=None) -> int:
|
|
|
466
466
|
except Exception:
|
|
467
467
|
pass
|
|
468
468
|
|
|
469
|
+
# Pinned here as well as in the hook command: the Windows command cannot
|
|
470
|
+
# carry an env prefix, and the bridge must never process-scan to guess.
|
|
471
|
+
os.environ.setdefault("TOKEN_OPTIMIZER_RUNTIME", "antigravity")
|
|
472
|
+
|
|
469
473
|
event = ""
|
|
470
474
|
if argv:
|
|
471
475
|
event = argv[0]
|
|
@@ -26,7 +26,6 @@ import argparse
|
|
|
26
26
|
import json
|
|
27
27
|
import os
|
|
28
28
|
import stat as _stat
|
|
29
|
-
import shlex
|
|
30
29
|
import shutil
|
|
31
30
|
import sys
|
|
32
31
|
from pathlib import Path
|
|
@@ -34,6 +33,7 @@ from pathlib import Path
|
|
|
34
33
|
_SCRIPT_DIR = Path(__file__).resolve().parent
|
|
35
34
|
sys.path.insert(0, str(_SCRIPT_DIR))
|
|
36
35
|
|
|
36
|
+
import adapter_hook_command # noqa: E402
|
|
37
37
|
from py_trust import py_path_is_trusted, py_trust_reason # noqa: E402
|
|
38
38
|
from runtime_env import antigravity_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
|
|
39
39
|
|
|
@@ -132,16 +132,16 @@ def _hooks_config(bridge_path: Path) -> dict:
|
|
|
132
132
|
docs): a JSON object keyed by hook NAME; PreToolUse uses a matcher group,
|
|
133
133
|
PreInvocation/Stop are flat handler lists."""
|
|
134
134
|
py = _resolve_safe_python()
|
|
135
|
-
py_q = shlex.quote(py)
|
|
136
|
-
bridge_q = shlex.quote(str(bridge_path))
|
|
137
135
|
|
|
138
136
|
def cmd(event: str, timeout: int) -> dict:
|
|
139
137
|
return {
|
|
140
138
|
"type": "command",
|
|
141
139
|
# -E -s: ignore PYTHONPATH + user site so an inherited env cannot
|
|
142
|
-
# hijack payload imports (R16).
|
|
143
|
-
# the bridge
|
|
144
|
-
|
|
140
|
+
# hijack payload imports (R16). The runtime is pinned (env prefix on
|
|
141
|
+
# POSIX, set by the bridge itself on Windows) so the bridge never
|
|
142
|
+
# process-scans on the hot path.
|
|
143
|
+
"command": adapter_hook_command.build(
|
|
144
|
+
py, str(bridge_path), event, runtime="antigravity", python_flags=("-E", "-s")),
|
|
145
145
|
"timeout": timeout,
|
|
146
146
|
}
|
|
147
147
|
|
|
@@ -192,16 +192,6 @@ def _write_consent(home: Path) -> None:
|
|
|
192
192
|
|
|
193
193
|
def install(*, dry_run: bool = False, home: Path | None = None) -> dict:
|
|
194
194
|
"""Install the adapter. Returns a summary dict of actions taken."""
|
|
195
|
-
# Windows refusal (deferred quoting: cmd.exe would not parse shlex.quote,
|
|
196
|
-
# and the env-prefix form of the persisted hook command is POSIX-only).
|
|
197
|
-
# Refuse loudly rather than register hooks that can never fire.
|
|
198
|
-
if os.name == "nt":
|
|
199
|
-
raise RuntimeError(
|
|
200
|
-
"Antigravity install on native Windows is not supported yet: the "
|
|
201
|
-
"persisted hook command is POSIX-shell quoted and cmd.exe would "
|
|
202
|
-
"not parse it. Install from a POSIX shell or WSL."
|
|
203
|
-
)
|
|
204
|
-
|
|
205
195
|
root = home if home is not None else antigravity_home()
|
|
206
196
|
actions = {
|
|
207
197
|
"copied": [],
|
|
@@ -270,9 +260,10 @@ def install(*, dry_run: bool = False, home: Path | None = None) -> dict:
|
|
|
270
260
|
)
|
|
271
261
|
|
|
272
262
|
# Write hooks.json, then plugin.json LAST so a partial payload
|
|
273
|
-
# never registers hooks (R1/U5).
|
|
263
|
+
# never registers hooks (R1/U5). The commands name the FINAL
|
|
264
|
+
# plugin dir: the staging dir is renamed away below.
|
|
274
265
|
(staging / "hooks.json").write_text(
|
|
275
|
-
json.dumps(_hooks_config(
|
|
266
|
+
json.dumps(_hooks_config(pdir / "antigravity_hook_bridge.py"), indent=2)
|
|
276
267
|
+ "\n",
|
|
277
268
|
encoding="utf-8",
|
|
278
269
|
)
|