Claude Skill

opus-tuner

Token-budget discipline for long sessions - context size, session limits, compaction, handoff, tier and gear routing.

LLM Mart · 0 points · 1 views 0 listing impressions 0 install-command copies
Download yahyalendani-opus-tuner-claude-skill-skills_opus-tuner-803d7ee.zip · 75 KB

Install

skills CLI npx skills add https://github.com/YahyaLendani/opus-tuner-claude-skill/tree/main/skills/opus-tuner
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install yahyalendani-opus-tuner-claude-skill@llmmart
Git git clone https://github.com/YahyaLendani/opus-tuner-claude-skill.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole yahyalendani/opus-tuner-claude-skill collection as a plugin from our marketplace. Git is the plain clone.

README

opus-tuner — technical reference

Token-budget control for long Claude Code sessions on a fixed model (Opus, high).

Nothing here calls a third-party endpoint, needs an API key, or runs /clear for you. The repo-level README covers installation; this file is the reference for what is wired where and why. The scripts run on Windows PowerShell 5.1 and on pwsh 7 (macOS, Linux, and Windows); see docs/platforms.md for the platform layer.

What is wired where

Piece Location Cost
Rules the model always sees ~/.claude/CLAUDE.md (token discipline block) ~130 tok/turn (block is 473 chars)
Decision playbook skills/opus-tuner/SKILL.md 0 until invoked
Deep tactics skills/opus-tuner/references/playbook.md 0 until read
Effort gears skills/gear-{low,medium,xhigh,max} ~100 tok/turn total (descriptions stay visible so a gear can be picked when the router is silent)
Handoff writer skills/wrap + scripts/brief.ps1 0 until invoked
Profile switch skills/profile + scripts/profile.ps1 installed only with hooks; 0 (user-only skill); creative adds ~100 tok once per session
Portable rules skills/claude-skill installed only with -NoHooks; for clients without hooks
Hooks ~/.claude/settings.json 0 tokens
Status line settings.json → statusline.ps1 0 tokens

The knobs

~/.claude/tuner.config.json. Every key is optional; missing keys fall back to the defaults below.

Key Default Meaning
mode assist off silences everything; monitor shows numbers only; assist also routes, advises and loads handoffs; guard also fires the interruptions below that you turn on. The old names advise and enforce still work
routineTokens 150000 routine ceiling
deepTokens 250000 deep ceiling; autoCompactWindow sits above it at 300000
graceTokens 25000 band above the routine ceiling where the tier steps up instead of wrapping
nudgeAt 0.7 fraction of the ceiling for the first warning
maxTurnsPerSession 2 hard cap on gear-max turns
minCtxForDownshift 100000 below this the router does not ask for a gear-down
downshiftRequiresBulk true below 200k, bulk wording must justify the extra request
hardWrap false guard mode: Stop hook asks once at the ceiling for a handoff if work remains
blockManualCompact false guard mode: PreCompact refuses the first manual /compact per session; auto is never blocked
logDecisions true one row per decision in state/tuner/decisions.csv
deepPatterns / mechanicalPatterns / bulkPatterns regex editable classification vocabulary
weakDeepPatterns regex deep only with a second signal (failure, 3+ files, plan mode, 400+ char prompt)
bigOutputTokens / bigOutputWarnings 6000 / 3 note on one oversized tool result; cap per session
weeklyDigest true one zero-token summary line per week at session start
autoTune true switch the low gear off for 14 days when 40%+ of 5+ recent low-gear turns hit a failure
pricingFile (bundled) another pricing table for audit.ps1, in the format of references/pricing.json
downshift true false never picks gear-low
profile dev dev or creative; applied after the keys above. See configuration
profiles — per-profile overrides

Two environment variables exist for tests and experiments: OPUS_TUNER_CONFIG and OPUS_TUNER_STATE override the config file and state directory. CLAUDE_CONFIG_DIR relocates the whole ~/.claude tree, which is how the test suites stay away from a live install.

Scripts

Script Runs on Notes
route.ps1 UserPromptSubmit classify, escalate tier, pick gear. Escalate-only.
post-tool.ps1 PostToolUse / PostToolUseFailure counts failures, tracks edited files, writes state only when a signal changed (it runs on every tool call); notes one oversized result, at most bigOutputWarnings per session. Matcher covers Read, Grep, Glob, WebFetch, MCP tools, the edit tools, and Bash and PowerShell — on Windows the shell tool is PowerShell, and missing it latches the repair-loop signal.
pre-tool.ps1 PreToolUse (Read) guard mode only, and registered only with -Enforce; refuses unbounded reads at the ceiling
stop.ps1 Stop two-stage banner; in guard mode with hardWrap, one handoff prompt at the ceiling
session-start.ps1 SessionStart resets tier; on clear, loads the handoff the session claimed unless another /clear in this project is pending; on startup, loads the only waiting handoff in this project if the session that wrote it has ended and it is under 24 h old; otherwise only announces it; reports (via systemMessage, 0 model tokens) a malformed config and the size of a large resumed session; weekly digest on startup
session-end.ps1 SessionEnd marks this session's verified handoff as ended, and on clear as claimed; a clear with no verified handoff leaves a .cleared marker that the next start uses up
pre-compact.ps1 PreCompact logs every compaction; in guard mode with blockManualCompact, blocks the first manual /compact per session. Auto is never blocked
brief.ps1 manual (/wrap) drafts state/tuner/handoffs/<session>.md from this session's transcript; -Verify checks the sections and masks credentials
ctx.ps1 manual current context vs ceiling
profile.ps1 manual (/profile) swap or set the dev / creative profile; show prints it and the note it adds
audit.ps1 manual per-session cache read/write, output, peak context, API-equivalent estimate; -Baseline x.csv prints deltas
stats.ps1 manual what the tuner decided: actions, context at each, per day
weekly.ps1 manual audit + stats against the newest baseline, written to state/tuner/weekly-<date>.txt
doctor.ps1 manual install health check: hook wiring, config validity, skills, script parse, state writable. -Replay executes the registered commands too; -SkillsOnly (implied when no hooks are registered) reports an advisory install and exits 0
statusline.ps1 status line live ctx/ceiling, tier, effort, 5h and 7d windows
selftest.ps1 manual / CI assertions against a synthetic transcript

VERSION sits beside this README and is installed with it. doctor.ps1 prints that number above its sections and reports it as version in -Json; the installer and uninstaller print it in their banner. It is the string to include in a bug report.

One-time Stop prompt

Only in guard mode with "hardWrap": true. At the ceiling, stop.ps1 returns decision: "block" with a reason that asks for a handoff if work remains. It is a prompt, not a limit: the next stop is allowed and nothing limits the context between stops.

  • it fires once per crossing (nudged.hardWrap), and never when stop_hook_active is set, so a model that ignores the reason can still finish the turn;
  • "hardWrap": false keeps the banner without the prompt.

The block never runs /clear for you. It cannot — hooks cannot invoke slash commands — and clearing a session unattended would throw away work you may still be reading.

Compaction

pre-compact.ps1 receives trigger: manual|auto and does two things:

  • logs the event (compact-manual, compact-auto, or compact-blocked) with the context size, so stats.ps1 can count how often it happens;
  • only in guard mode with "blockManualCompact": true, refuses the first manual /compact per session (nudged.compact), offering a handoff instead. A second /compact proceeds.

Automatic compaction is never blocked. If it fires to recover from a context-limit error the API already returned, blocking it surfaces that error and fails the request — worse than the compaction. PreCompact also discards systemMessage, which is why the log is the only reporting channel.

Decision log

route.ps1 and stop.ps1 append one row per decision — not per prompt — to state/tuner/decisions.csv: time, session, context, tier, gear, action. Rotates at 1 MB, keeps one previous file. stats.ps1 answers "what did it actually do":

# Windows
powershell -NoProfile -File "$env:USERPROFILE\.claude\skills\opus-tuner\scripts\stats.ps1" -Days 7
# macOS / Linux
pwsh -NoProfile -File "$HOME/.claude/skills/opus-tuner/scripts/stats.ps1" -Days 7

Rows at small context mean a threshold is too low. hard-wrap rows count the Stop prompts that fired in guard mode.

Model and effort (verified against the 2.1.312 settings schema)

The session model is "model": "opus", which resolves to Opus 5.5 on the Anthropic API. Its effort level is set per model, because that is the only form Opus 5.5 reads:

"modelSettings": { "claude-opus-5-5": { "effortLevel": "high" } }

The top-level "effortLevel" is deliberately not the mechanism for Opus 5.5: the docs state that a top-level effortLevel "doesn't count for Opus 5.5", which starts at medium unless a per-model level is saved. Within one settings file the per-model level wins, so Opus runs at high and the top-level value only applies to older models and to subagent models that have no saved level of their own. claude-opus-5-5 is the canonical name Claude Code sends, confirmed from transcripts.

A gear's effort: frontmatter applies to that turn only; later turns fall back to the resolved session level. gear-max uses effort: max, which Opus 5.5 supports even though max is not a valid persisted effortLevel value.

When a new model ships

The model name is data, not code: doctor.ps1 validates the effortLevel of every entry under modelSettings, whatever the model is called, so a new model does not silently turn the check off. Retarget the key when you switch:

"modelSettings": { "claude-opus-6": { "effortLevel": "high" } }

Persisted values are low, medium, high and xhigh. max is a routing choice for one turn, not something to write into settings; the doctor fails on it by name rather than ignoring it.

In VS Code, the terminal, and Desktop

All three run the same Claude Code binary and read the same ~/.claude/settings.json, so the hook set is identical. The VS Code extension ships its own CLI binary (resources/native-binary/claude.exe in %USERPROFILE%\.vscode\extensions\anthropic.claude-code-*), so the panel does not use whatever claude is on PATH — the two can be different versions. ~/.claude/settings.json is shared by both, so hooks, skillOverrides and autoCompactWindow apply either way.

Two differences that matter:

  • Reload after editing hooks. Each client reads settings at session start. The terminal needs a restart, the panel needs Developer: Reload Window (or a restart of the extension host), and the Desktop app needs a restart. Then check /hooks shows UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SessionStart, SessionEnd, PreCompact and /skills lists the seven skills for that mode.
  • New conversations usually start as startup, not clear. The panel's new-chat button does not always emit the /clear source, so session-start.ps1 also loads a handoff on startup when it is the only one waiting in this project, under 24 hours old, and the session that wrote it has ended. Anything less certain is announced, not loaded, since it may belong to another session.

A fresh conversation with no brief is the safest moment to change model or effort; that is what SessionStart does, and it is why nothing in this bundle switches mid-session.

In the panel, /clear is also available as /reset and /new. The custom statusLine is a terminal-UI feature and is not drawn by the graphical panel or the Desktop app, which have their own built-in context indicator; enable claudeCode.useTerminal if you want the custom bar.

Latency

Measured on one Windows 11 machine (Windows PowerShell 5.1, no pwsh). A blocking hook is ~440–490 ms end to end. Almost none of that is the tuner's own work:

Cost Time
powershell.exe -NoProfile start (measured with a no-op script) ~150 ms
parse _common.ps1 + the hook ~50 ms
first ConvertFrom-Json in the process (the config read) ~90 ms
first file read and regex use (the transcript tail) ~100 ms
state read/write, classification, decision append ~30 ms

Once those engines are warm, the tuner's own work is ~20 ms: Get-ContextInfo took 3–14 ms a call on a 12 MB transcript, tail read and parsed record included, and ~120 ms on the first call in a process, which is the warm-up in the table above. The rest is one-time warm-up that every PowerShell hook pays, and it cannot be avoided without a long-lived hook process, which Claude Code does not offer. This is also why the two JSON parses are not worth merging: parsing the config first moves the ~90 ms assembly load onto the hook input, not away from it.

Where it lands:

Hook Blocking? Measured Frequency
route.ps1 yes ~450–560 ms once per prompt
stop.ps1 yes ~440–460 ms once per response
statusline.ps1 UI only ~330–360 ms per message
post-tool.ps1 no (async: true) ~310–360 ms per tool call

Three optimisations were measured and rejected because they did not move the number: a hand-rolled flat-JSON config reader (the assembly load just moves to the input parser), a 512 KB → 128 KB first read window (the tail decode is not the bottleneck; the first read costs 45 ms at 128 KB and 9 ms at 512 KB once warm), and a backwards LastIndexOf scan instead of collecting every "usage" match (2.1 ms vs 6.5 ms on a 137 MB transcript, ~1% of hook time).

Why not PowerShell 7 on Windows

PowerShell 7 was installed, measured, and removed on the development machine. It was slower there, and leaving it installed is actively harmful because Claude Code auto-detects pwsh.exe on PATH for every shell: "powershell" hook:

Windows PowerShell 5.1 PowerShell 7.6.9 (MSI) PowerShell 7.6.9 (MSIX)
bare start 132 ms 235 ms 271 ms
route.ps1 ~450 ms 550–620 ms ~590 ms
post-tool.ps1 ~310 ms ~470 ms —

Process creation is already slow on that box (5.1 at 132 ms against a typical 80), so pwsh's larger .NET runtime costs ~100 ms that its faster JSON parsing never wins back. The MSIX/Store build is slower still. Re-measure before reinstalling on different hardware; do not assume the usual "pwsh is faster" advice applies.

This is a Windows measurement and says nothing about macOS or Linux, where pwsh is the only option and the same ~150 ms startup floor applies. See docs/platforms.md.

Read guard

The guard only takes effect in guard mode, once the PreToolUse hook is registered, which it is not by default because it costs another blocking invocation on every Read. Register it with:

# Windows
powershell -NoProfile -ExecutionPolicy Bypass -File install.ps1 -Force -Enforce
# macOS / Linux
./install.sh -Force -Enforce

Then set "mode": "guard" in tuner.config.json.

Removing it

# Windows
powershell -NoProfile -ExecutionPolicy Bypass -File uninstall.ps1
# macOS / Linux
pwsh -NoProfile -File uninstall.ps1

That removes only this bundle's hooks, status line, CLAUDE.md block, and skill folders. -KeepSkills keeps the folders; -Purge also removes tuner.config.json and state/tuner.

Skill manifest

opus-tuner

Every request re-reads the whole context, so these rules are about how much gets re-read and how many requests read it.

The five rules

  1. Batch independent tool calls. Four greps in one message read the context once; four separate messages read it four times.
  2. Grep before read, and bound every read. Read with no limit, or above 400 lines, only when you are certain. Otherwise offset/limit, or search first. Never recursive-scan a repo to find one symbol.
  3. Never trade verification for tokens. A "saving" that causes rework is a loss.
  4. Delegate breadth, not judgement. Exploration, mechanical multi-file edits and test runs go to a subagent: the built-in Explore agent for finding code, a general-purpose one (Sonnet is enough) for mechanical edits and test runs. Its context is discarded when it returns; yours is re-read every turn.
  5. Hand off when the user asks. Do it at a boundary, not mid-task, with /wrap. When the user wants to continue in a fresh session, prepare and verify a handoff. Ask them to run /clear afterward. Runtime hooks separately control any configured compaction interruption.

Tiers

Tier Ceiling Use
routine 150k default
deep 250k refactors, hard debugging, architecture

The tier escalates automatically on prompt vocabulary, a repair loop (2+ consecutive failures), breadth (6+ files edited), plan mode, or crossing the routine ceiling while still inside the 25k grace band. It never auto-downgrades mid-session; a reset happens only at session start.

A ceiling is a reference point, not a limit. If a hook message asks for a handoff and work remains, follow it once with /wrap. If the work is done, say so.

Ask with ctx.ps1:

# Windows
powershell -NoProfile -File "$env:USERPROFILE\.claude\skills\opus-tuner\scripts\ctx.ps1"

# macOS / Linux
pwsh -NoProfile -File "$HOME/.claude/skills/opus-tuner/scripts/ctx.ps1"

If CLAUDE_CONFIG_DIR is set, substitute it for ~/.claude in that path.

Gears

Session default is high and needs no skill. A gear costs one extra request, so the router only asks for one on a clear signal.

Gear When
gear-low mechanical, bulk, and context already large
gear-medium light edits, docs
(high) default
gear-xhigh hard reasoning, or a failed attempt
gear-max a wrong answer would cost a full turn; capped per session

If the router injects [tuner] gear=X, invoke /gear-X as your first action.

What not to do

  • Do not suggest switching the main-thread model mid-session. The new model starts without the prompt cache.
  • Do not read a large file "to get context". Grep for the symbol.
  • Do not restate the plan back to the user before acting on a mechanical turn.

Full tactics: references/playbook.md.

Files (opus-tuner-claude-skill)
  • references
    • playbook.md 3.1 KB
      Loading…
    • pricing.json 3.3 KB
      Loading…
  • scripts
    • audit.ps1 16.9 KB · in bundle
    • brief.ps1 12.5 KB · in bundle
    • ctx.ps1 2.5 KB · in bundle
    • doctor.ps1 21 KB · in bundle
    • post-tool.ps1 5.1 KB · in bundle
    • pre-compact.ps1 2.9 KB · in bundle
    • pre-tool.ps1 1.5 KB · in bundle
    • profile.ps1 4.3 KB · in bundle
    • route.ps1 7.7 KB · in bundle
    • selftest.ps1 42.2 KB · in bundle
    • session-end.ps1 1.3 KB · in bundle
    • session-start.ps1 7.1 KB · in bundle
    • stats.ps1 2.7 KB · in bundle
    • statusline.ps1 3.2 KB · in bundle
    • stop.ps1 4.8 KB · in bundle
    • weekly.ps1 2.7 KB · in bundle
    • _common.ps1 50.4 KB · in bundle
    • _pricing.ps1 5.3 KB · in bundle
  • README.md 15.6 KB
    # opus-tuner — technical reference
    
    Token-budget control for long Claude Code sessions on a fixed model (Opus, high).
    
    Nothing here calls a third-party endpoint, needs an API key, or runs `/clear` for
    you. The repo-level [README](../../README.md) covers installation; this file is the
    reference for what is wired where and why. The scripts run on Windows PowerShell
    5.1 and on `pwsh` 7 (macOS, Linux, and Windows); see
    [docs/platforms.md](../../docs/platforms.md) for the platform layer.
    
    ## What is wired where
    
    | Piece | Location | Cost |
    |---|---|---|
    | Rules the model always sees | `~/.claude/CLAUDE.md` (token discipline block) | ~130 tok/turn (block is 473 chars) |
    | Decision playbook | `skills/opus-tuner/SKILL.md` | 0 until invoked |
    | Deep tactics | `skills/opus-tuner/references/playbook.md` | 0 until read |
    | Effort gears | `skills/gear-{low,medium,xhigh,max}` | ~100 tok/turn total (descriptions stay visible so a gear can be picked when the router is silent) |
    | Handoff writer | `skills/wrap` + `scripts/brief.ps1` | 0 until invoked |
    | Profile switch | `skills/profile` + `scripts/profile.ps1` | installed only with hooks; 0 (user-only skill); creative adds ~100 tok once per session |
    | Portable rules | `skills/claude-skill` | installed only with `-NoHooks`; for clients without hooks |
    | Hooks | `~/.claude/settings.json` | 0 tokens |
    | Status line | `settings.json` → `statusline.ps1` | 0 tokens |
    
    ## The knobs
    
    `~/.claude/tuner.config.json`. Every key is optional; missing keys fall back to
    the defaults below.
    
    | Key | Default | Meaning |
    |---|---|---|
    | `mode` | `assist` | `off` silences everything; `monitor` shows numbers only; `assist` also routes, advises and loads handoffs; `guard` also fires the interruptions below that you turn on. The old names `advise` and `enforce` still work |
    | `routineTokens` | 150000 | routine ceiling |
    | `deepTokens` | 250000 | deep ceiling; `autoCompactWindow` sits above it at 300000 |
    | `graceTokens` | 25000 | band above the routine ceiling where the tier steps up instead of wrapping |
    | `nudgeAt` | 0.7 | fraction of the ceiling for the first warning |
    | `maxTurnsPerSession` | 2 | hard cap on `gear-max` turns |
    | `minCtxForDownshift` | 100000 | below this the router does not ask for a gear-down |
    | `downshiftRequiresBulk` | true | below 200k, bulk wording must justify the extra request |
    | `hardWrap` | false | guard mode: Stop hook asks once at the ceiling for a handoff if work remains |
    | `blockManualCompact` | false | guard mode: PreCompact refuses the first manual `/compact` per session; auto is never blocked |
    | `logDecisions` | true | one row per decision in `state/tuner/decisions.csv` |
    | `deepPatterns` / `mechanicalPatterns` / `bulkPatterns` | regex | editable classification vocabulary |
    | `weakDeepPatterns` | regex | deep only with a second signal (failure, 3+ files, plan mode, 400+ char prompt) |
    | `bigOutputTokens` / `bigOutputWarnings` | 6000 / 3 | note on one oversized tool result; cap per session |
    | `weeklyDigest` | true | one zero-token summary line per week at session start |
    | `autoTune` | true | switch the low gear off for 14 days when 40%+ of 5+ recent low-gear turns hit a failure |
    | `pricingFile` | (bundled) | another pricing table for `audit.ps1`, in the format of `references/pricing.json` |
    | `downshift` | true | `false` never picks `gear-low` |
    | `profile` | `dev` | `dev` or `creative`; applied after the keys above. See [configuration](../../docs/configuration.md#profiles) |
    | `profiles` | — | per-profile overrides |
    
    Two environment variables exist for tests and experiments:
    `OPUS_TUNER_CONFIG` and `OPUS_TUNER_STATE` override the config file and state
    directory. `CLAUDE_CONFIG_DIR` relocates the whole `~/.claude` tree, which is how
    the test suites stay away from a live install.
    
    ## Scripts
    
    | Script | Runs on | Notes |
    |---|---|---|
    | `route.ps1` | UserPromptSubmit | classify, escalate tier, pick gear. Escalate-only. |
    | `post-tool.ps1` | PostToolUse / PostToolUseFailure | counts failures, tracks edited files, writes state only when a signal changed (it runs on every tool call); notes one oversized result, at most `bigOutputWarnings` per session. Matcher covers `Read`, `Grep`, `Glob`, `WebFetch`, MCP tools, the edit tools, and `Bash` **and** `PowerShell` — on Windows the shell tool is `PowerShell`, and missing it latches the repair-loop signal. |
    | `pre-tool.ps1` | PreToolUse (Read) | guard mode only, and registered only with `-Enforce`; refuses unbounded reads at the ceiling |
    | `stop.ps1` | Stop | two-stage banner; in guard mode with `hardWrap`, one handoff prompt at the ceiling |
    | `session-start.ps1` | SessionStart | resets tier; on `clear`, loads the handoff the session claimed unless another `/clear` in this project is pending; on `startup`, loads the only waiting handoff in this project if the session that wrote it has ended and it is under 24 h old; otherwise only announces it; reports (via `systemMessage`, 0 model tokens) a malformed config and the size of a large resumed session; weekly digest on `startup` |
    | `session-end.ps1` | SessionEnd | marks this session's verified handoff as ended, and on `clear` as claimed; a `clear` with no verified handoff leaves a `.cleared` marker that the next start uses up |
    | `pre-compact.ps1` | PreCompact | logs every compaction; in guard mode with `blockManualCompact`, blocks the first manual `/compact` per session. Auto is never blocked |
    | `brief.ps1` | manual (`/wrap`) | drafts `state/tuner/handoffs/<session>.md` from this session's transcript; `-Verify` checks the sections and masks credentials |
    | `ctx.ps1` | manual | current context vs ceiling |
    | `profile.ps1` | manual (`/profile`) | swap or set the dev / creative profile; `show` prints it and the note it adds |
    | `audit.ps1` | manual | per-session cache read/write, output, peak context, API-equivalent estimate; `-Baseline x.csv` prints deltas |
    | `stats.ps1` | manual | what the tuner decided: actions, context at each, per day |
    | `weekly.ps1` | manual | audit + stats against the newest baseline, written to `state/tuner/weekly-<date>.txt` |
    | `doctor.ps1` | manual | install health check: hook wiring, config validity, skills, script parse, state writable. `-Replay` executes the registered commands too; `-SkillsOnly` (implied when no hooks are registered) reports an advisory install and exits 0 |
    | `statusline.ps1` | status line | live `ctx/ceiling`, tier, effort, 5h and 7d windows |
    | `selftest.ps1` | manual / CI | assertions against a synthetic transcript |
    
    `VERSION` sits beside this README and is installed with it. `doctor.ps1` prints
    that number above its sections and reports it as `version` in `-Json`; the
    installer and uninstaller print it in their banner. It is the string to include in
    a bug report.
    
    ## One-time Stop prompt
    
    Only in guard mode with `"hardWrap": true`. At the ceiling, `stop.ps1` returns
    `decision: "block"` with a reason that asks for a handoff if work remains. It is a
    prompt, not a limit: the next stop is allowed and nothing limits the context between
    stops.
    
    - it fires **once per crossing** (`nudged.hardWrap`), and never when
      `stop_hook_active` is set, so a model that ignores the reason can still finish
      the turn;
    - `"hardWrap": false` keeps the banner without the prompt.
    
    The block never runs `/clear` for you. It cannot — hooks cannot invoke slash
    commands — and clearing a session unattended would throw away work you may still
    be reading.
    
    ## Compaction
    
    `pre-compact.ps1` receives `trigger: manual|auto` and does two things:
    
    - logs the event (`compact-manual`, `compact-auto`, or `compact-blocked`) with the
      context size, so `stats.ps1` can count how often it happens;
    - only in guard mode with `"blockManualCompact": true`, refuses the **first** manual
      `/compact` per session (`nudged.compact`), offering a handoff instead. A second
      `/compact` proceeds.
    
    Automatic compaction is never blocked. If it fires to recover from a
    context-limit error the API already returned, blocking it surfaces that error and
    fails the request — worse than the compaction. `PreCompact` also discards
    `systemMessage`, which is why the log is the only reporting channel.
    
    ## Decision log
    
    `route.ps1` and `stop.ps1` append one row per *decision* — not per prompt — to
    `state/tuner/decisions.csv`: time, session, context, tier, gear, action. Rotates
    at 1 MB, keeps one previous file. `stats.ps1` answers "what did it actually do":
    
    ```powershell
    # Windows
    powershell -NoProfile -File "$env:USERPROFILE\.claude\skills\opus-tuner\scripts\stats.ps1" -Days 7
    ```
    
    ```sh
    # macOS / Linux
    pwsh -NoProfile -File "$HOME/.claude/skills/opus-tuner/scripts/stats.ps1" -Days 7
    ```
    
    Rows at small context mean a threshold is too low. `hard-wrap` rows count the Stop
    prompts that fired in guard mode.
    
    ## Model and effort (verified against the 2.1.312 settings schema)
    
    The session model is `"model": "opus"`, which resolves to **Opus 5.5** on the
    Anthropic API. Its effort level is set per model, because that is the only form
    Opus 5.5 reads:
    
    ```json
    "modelSettings": { "claude-opus-5-5": { "effortLevel": "high" } }
    ```
    
    The top-level `"effortLevel"` is deliberately *not* the mechanism for Opus 5.5:
    the docs state that a top-level `effortLevel` "doesn't count for Opus 5.5", which
    starts at `medium` unless a per-model level is saved. Within one settings file the
    per-model level wins, so Opus runs at `high` and the top-level value only applies
    to older models and to subagent models that have no saved level of their own.
    `claude-opus-5-5` is the canonical name Claude Code sends, confirmed from
    transcripts.
    
    A gear's `effort:` frontmatter applies to **that turn only**; later turns fall
    back to the resolved session level. `gear-max` uses `effort: max`, which Opus 5.5
    supports even though `max` is not a valid *persisted* `effortLevel` value.
    
    ### When a new model ships
    
    The model name is data, not code: `doctor.ps1` validates the `effortLevel` of
    **every** entry under `modelSettings`, whatever the model is called, so a new
    model does not silently turn the check off. Retarget the key when you switch:
    
    ```json
    "modelSettings": { "claude-opus-6": { "effortLevel": "high" } }
    ```
    
    Persisted values are `low`, `medium`, `high` and `xhigh`. `max` is a routing
    choice for one turn, not something to write into settings; the doctor fails on it
    by name rather than ignoring it.
    
    ## In VS Code, the terminal, and Desktop
    
    All three run the same Claude Code binary and read the same
    `~/.claude/settings.json`, so the hook set is identical. The VS Code extension
    ships its own CLI binary (`resources/native-binary/claude.exe` in
    `%USERPROFILE%\.vscode\extensions\anthropic.claude-code-*`), so the panel does
    **not** use whatever `claude` is on PATH — the two can be different versions.
    `~/.claude/settings.json` is shared by both, so hooks, `skillOverrides` and
    `autoCompactWindow` apply either way.
    
    Two differences that matter:
    
    - **Reload after editing hooks.** Each client reads settings at session start. The
      terminal needs a restart, the panel needs *Developer: Reload Window* (or a
      restart of the extension host), and the Desktop app needs a restart. Then check
      `/hooks` shows `UserPromptSubmit`, `PostToolUse`, `PostToolUseFailure`, `Stop`,
      `SessionStart`, `SessionEnd`, `PreCompact` and `/skills` lists the seven skills for
      that mode.
    - **New conversations usually start as `startup`, not `clear`.** The panel's
      new-chat button does not always emit the `/clear` source, so `session-start.ps1`
      also loads a handoff on `startup` when it is the only one waiting in this project,
      under 24 hours old, and the session that wrote it has ended. Anything less certain
      is announced, not loaded, since it may belong to another session.
    
    A fresh conversation with no brief is the safest moment to change model or
    effort; that is what `SessionStart` does, and it is why nothing in this bundle
    switches mid-session.
    
    In the panel, `/clear` is also available as `/reset` and `/new`. The custom
    `statusLine` is a terminal-UI feature and is not drawn by the graphical panel or
    the Desktop app, which have their own built-in context indicator; enable
    `claudeCode.useTerminal` if you want the custom bar.
    
    ## Latency
    
    Measured on one Windows 11 machine (Windows PowerShell 5.1, no `pwsh`). A blocking
    hook is **~440–490 ms** end to end. Almost none of that is the tuner's own work:
    
    | Cost | Time |
    |---|---|
    | `powershell.exe -NoProfile` start (measured with a no-op script) | ~150 ms |
    | parse `_common.ps1` + the hook | ~50 ms |
    | first `ConvertFrom-Json` in the process (the config read) | ~90 ms |
    | first file read and regex use (the transcript tail) | ~100 ms |
    | state read/write, classification, decision append | ~30 ms |
    
    Once those engines are warm, the tuner's own work is ~20 ms: `Get-ContextInfo` took
    3–14 ms a call on a 12 MB transcript, tail read and parsed record included, and
    ~120 ms on the first call in a process, which is the warm-up in the table above.
    The rest is one-time warm-up that every PowerShell hook pays, and it cannot be
    avoided without a long-lived hook process, which Claude Code does not offer. This
    is also why the two JSON parses are not worth merging: parsing the config first
    moves the ~90 ms assembly load onto the hook input, not away from it.
    
    Where it lands:
    
    | Hook | Blocking? | Measured | Frequency |
    |---|---|---|---|
    | `route.ps1` | yes | ~450–560 ms | once per prompt |
    | `stop.ps1` | yes | ~440–460 ms | once per response |
    | `statusline.ps1` | UI only | ~330–360 ms | per message |
    | `post-tool.ps1` | **no** (`async: true`) | ~310–360 ms | per tool call |
    
    Three optimisations were measured and rejected because they did not move the
    number: a hand-rolled flat-JSON config reader (the assembly load just moves to the
    input parser), a 512 KB → 128 KB first read window (the tail decode is not the
    bottleneck; the first read costs 45 ms at 128 KB and 9 ms at 512 KB once warm),
    and a backwards `LastIndexOf` scan instead of collecting every `"usage"` match
    (2.1 ms vs 6.5 ms on a 137 MB transcript, ~1% of hook time).
    
    ### Why not PowerShell 7 on Windows
    
    PowerShell 7 was installed, measured, and removed on the development machine. It
    was **slower** there, and leaving it installed is actively harmful because Claude
    Code auto-detects `pwsh.exe` on PATH for every `shell: "powershell"` hook:
    
    | | Windows PowerShell 5.1 | PowerShell 7.6.9 (MSI) | PowerShell 7.6.9 (MSIX) |
    |---|---|---|---|
    | bare start | **132 ms** | 235 ms | 271 ms |
    | `route.ps1` | **~450 ms** | 550–620 ms | ~590 ms |
    | `post-tool.ps1` | **~310 ms** | ~470 ms | — |
    
    Process creation is already slow on that box (5.1 at 132 ms against a typical 80),
    so pwsh's larger .NET runtime costs ~100 ms that its faster JSON parsing never
    wins back. The MSIX/Store build is slower still. Re-measure before reinstalling
    on different hardware; do not assume the usual "pwsh is faster" advice applies.
    
    This is a Windows measurement and says nothing about macOS or Linux, where `pwsh`
    is the only option and the same ~150 ms startup floor applies. See
    [docs/platforms.md](../../docs/platforms.md).
    
    ## Read guard
    
    The guard only takes effect in guard mode, once the `PreToolUse` hook is registered,
    which it is not by default because it costs another blocking invocation on every
    `Read`. Register it with:
    
    ```powershell
    # Windows
    powershell -NoProfile -ExecutionPolicy Bypass -File install.ps1 -Force -Enforce
    ```
    
    ```sh
    # macOS / Linux
    ./install.sh -Force -Enforce
    ```
    
    Then set `"mode": "guard"` in `tuner.config.json`.
    
    ## Removing it
    
    ```powershell
    # Windows
    powershell -NoProfile -ExecutionPolicy Bypass -File uninstall.ps1
    ```
    
    ```sh
    # macOS / Linux
    pwsh -NoProfile -File uninstall.ps1
    ```
    
    That removes only this bundle's hooks, status line, `CLAUDE.md` block, and skill
    folders. `-KeepSkills` keeps the folders; `-Purge` also removes
    `tuner.config.json` and `state/tuner`.
    
  • SKILL.md 3 KB
    ---
    name: opus-tuner
    description: Token-budget discipline for long sessions - context size, session limits, compaction, handoff, tier and gear routing.
    ---
    
    # opus-tuner
    
    Every request re-reads the whole context, so these rules are about how much gets
    re-read and how many requests read it.
    
    ## The five rules
    
    1. **Batch independent tool calls.** Four greps in one message read the context
       once; four separate messages read it four times.
    2. **Grep before read, and bound every read.** `Read` with no `limit`, or above 400
       lines, only when you are certain. Otherwise `offset`/`limit`, or search first.
       Never recursive-scan a repo to find one symbol.
    3. **Never trade verification for tokens.** A "saving" that causes rework is a loss.
    4. **Delegate breadth, not judgement.** Exploration, mechanical multi-file edits and
       test runs go to a subagent: the built-in `Explore` agent for finding code, a
       general-purpose one (Sonnet is enough) for mechanical edits and test runs. Its
       context is discarded when it returns; yours is re-read every turn.
    5. **Hand off when the user asks.** Do it at a boundary, not mid-task, with `/wrap`.
       When the user wants to continue in a fresh session, prepare and verify a handoff. Ask them to run `/clear` afterward.
       Runtime hooks separately control any configured compaction interruption.
    
    ## Tiers
    
    | Tier | Ceiling | Use |
    |---|---|---|
    | routine | 150k | default |
    | deep | 250k | refactors, hard debugging, architecture |
    
    The tier escalates automatically on prompt vocabulary, a repair loop (2+ consecutive
    failures), breadth (6+ files edited), plan mode, or crossing the routine ceiling while
    still inside the 25k grace band. It never auto-downgrades mid-session; a reset happens
    only at session start.
    
    A ceiling is a reference point, not a limit. If a hook message asks for a handoff and
    work remains, follow it once with `/wrap`. If the work is done, say so.
    
    Ask with `ctx.ps1`:
    
    ```
    # Windows
    powershell -NoProfile -File "$env:USERPROFILE\.claude\skills\opus-tuner\scripts\ctx.ps1"
    
    # macOS / Linux
    pwsh -NoProfile -File "$HOME/.claude/skills/opus-tuner/scripts/ctx.ps1"
    ```
    
    If `CLAUDE_CONFIG_DIR` is set, substitute it for `~/.claude` in that path.
    
    ## Gears
    
    Session default is **high** and needs no skill. A gear costs one extra request, so
    the router only asks for one on a clear signal.
    
    | Gear | When |
    |---|---|
    | `gear-low` | mechanical, bulk, and context already large |
    | `gear-medium` | light edits, docs |
    | *(high)* | default |
    | `gear-xhigh` | hard reasoning, or a failed attempt |
    | `gear-max` | a wrong answer would cost a full turn; capped per session |
    
    If the router injects `[tuner] gear=X`, invoke `/gear-X` as your first action.
    
    ## What not to do
    
    - Do not suggest switching the main-thread model mid-session. The new model starts
      without the prompt cache.
    - Do not read a large file "to get context". Grep for the symbol.
    - Do not restate the plan back to the user before acting on a mechanical turn.
    
    Full tactics: `references/playbook.md`.
    
  • VERSION 6 B · in bundle

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.