# Downshift — LLM and AI Agent Notice # https://github.com/tiagovilasboas/downshift ## Project Downshift is an open-source suite for optimizing token use in coding agents. For coding harnesses (Claude Code first; Cursor, Codex, Antigravity, KiroCrew), it intercepts subagent spawns via PreToolUse hooks and selects tier, model and reasoning effort before execution, holds back under doubt, applies risk and project floors, records token counts and coverage, and compares routed versus control tokens per completed task. It prints no dollar amounts. Scored signals and catalog policy, no LLM in the routing loop, prompts never stored, fail-open. Model routing is the main lever, not the whole product. CLI binary: downshift. The suite (one sentence each; status words from docs/reference/capability-matrix.md): - Deterministic subagent routing: PreToolUse hook rewrites one subagent's model and effort from the session's own list. Implemented; honored on Claude Code. - Guardrails, doubt never spends money: R1-R9 hold unconfident downshifts, upshifts and frontier picks; risk categories keep a floor. Implemented. - Project tier floor: .downshift/policy.json raises a minimum tier, never lowers. Implemented, every harness. - Quota and credit gate: hook marks or native snapshots hold rewrites to models without credit; stale after 1 h. Implemented, not validated everywhere. - Session view and statusline: every spawn gets one state (switched, held, observed, paused, control, blocked), shown on stderr per spawn in every harness, in downshift session --tree, /downshift, watch (active or idle), session --panel and live.json; statusline Claude Code only. Implemented. docs/reference/spawn-state.md - Token telemetry and reports with a control group: prompt-free events.jsonl, ~1 in 10 spawns unrouted, downshift stats / report. stats shows tokens rerouted (moved to a cheaper or pricier model; Claude Code only, other harnesses read unobserved); report shows tokens per completed task. The report, stats and export show tokens and coverage only; schema 3 has no USD fields. Dated catalog list prices remain routing metadata, not reported savings. docs/reference/value-per-harness.md - Context policy: setup sets opusplan, plan mode, You should know for unset keys (Claude Code only); native compressor observes bytes. Implemented, limited. - Mods: cache-tax is optional and separate (not in the plugin, not installed by setup); savvy-progress and filetree as sibling plugins; downshift-router opt-in prototype (Experimental). mods/README.md - Companions: Headroom (default compression proxy, detected and recorded), never installed or wrapped. docs/guides/companions.md - Evidence ladder: rungs A-E; rung D reached once (2026-10-15), rung E not measured. docs/guides/evidence.md Models it knows (internal/catalog/catalog.json, version 2, 2026-10-16, 34 entries): Claude Code: claude-haiku (small), claude-sonnet (mid), claude-opus and claude-fable (frontier), grok by custom config. Cursor: Anthropic thinking variants, gpt-5.6-sol, gemini, grok, glm, muse-spark, composer. Codex: gpt-6-luna / gpt-5.6-luna (small), gpt-5.6-terra (mid), gpt-6-sol / gpt-6.1-sol / gpt-5.6-sol (frontier), gpt-6-astra (explicit_only). Antigravity: flash_lite, flash, pro. KiroCrew: the Anthropic families. Lookup is exact, then alias, then family prefix; OpenRouter-style provider/ prefixes are stripped first; explicit_only (gpt-6-astra, claude-fable-5-1-thinking-high) is never chosen automatically. On Claude Code the session list is inferred from the current model (catalog ladder below it), so routing only moves down from it. Session-first resolution: session IDs are the complete candidate set. Valid exact model_metadata takes precedence; catalog metadata is optional fallback. A declared capability-ordered list can rank new IDs; unordered native availability cannot. Malformed metadata rejects its ID; missing prices stay unknown. docs/reference/session-models.md, internal/core/session_resolver.go Languages: regex signals in English and Portuguese plus the in-process FNV word-hash boost (raise-only, SEMANTIC_BOOST). A heuristic language guard clears confidence outside coverage. DOWNSHIFT_MINILM=0 disables the hash boost (legacy flag name). External MiniLM commands, E5 and Graphify were removed 2026-10-17. shadow-report compares routing-v2 candidates, not E5. docs/contrib/classifier.md, docs/design/minilm-semantic.md Visual guide: docs/img/downshift-bdi.svg (BDI conceptual lens, not a planner), then docs/img/downshift-execution.svg (current runtime and observation boundaries). docs/design/architecture.md maps code ownership and guia/sensor coverage. Capability matrix with status and evidence: docs/reference/capability-matrix.md Evidence ladder and metrics: docs/guides/evidence.md Benchmark protocol (Opus fixed vs opusplan vs opusplan + Downshift): docs/guides/benchmark-protocol.md Claude Code guide (opusplan, baseline inference, emitted vs honored vs used): docs/guides/claude-code.md Author: Tiago Vilas Boas Repository: https://github.com/tiagovilasboas/downshift Language: Go 1.27, single binary, zero runtime dependencies. Install and harness setup (canonical for agents): docs/guides/install.md Claude Code plugin (hooks, /downshift, skills, example agent; binary still required): /plugin install downshift --marketplace tiagovilasboas/downshift Agent skills in skills/: downshift-setup, downshift-audit, cost-reducer (SKILL.md, any harness) Assisted setup for AI agents (ask the user before any write outside the repo): 1. curl -fsSL https://raw.githubusercontent.com/tiagovilasboas/downshift/main/install.sh | sh 2. downshift setup --dry-run # show the diff to the user 3. downshift setup --yes # only after the user agrees; backups kept, --undo restores 4. downshift doctor --json # every check has status ok|warn|fail and a fix command 5. ask the user to open a new harness session; `downshift session` shows the subagent tree Contributing / architecture for this repo: AGENTS.md and CONTRIBUTING.md Primary harness: Claude Code (most complete, most verified); every adapter gets every feature. Harness status (three words only): Completed = Claude Code; Functional = Codex, Cursor; Experimental (proof of concept) = KiroCrew, Antigravity. Evidence per harness: docs/reference/harness-matrix.md The optional cache-tax mod (MIT, third party, priced cold-send guard and /keepwarm; the ping spends usage) is installed separately: it is no longer part of the Downshift plugin, and setup does not install it. hooks/cache-tax/README.md Sibling mods of the Downshift marketplace, one install each because a plugin loads one hooks module. `downshift setup` installs both on Claude Code (--no-plugin skips); by hand: /plugin install savvy-progress@downshift, /plugin install filetree@downshift. mods/README.md Experimental mod downshift-router (off by default; routes from agent.spawn through the same binary; never run next to the settings hook): mods/downshift-router/README.md, docs/design/mod-router.md Companions (Headroom default, detected and recorded, never installed by Downshift; recommended Claude Code mods You should know (built in, off by default, billed checks), Token Weather, Replay Theater and reflect-mod): docs/guides/companions.md ## Licence SPDX-License-Identifier: Apache-2.0 Apache License, Version 2.0. Commercial use is permitted under the licence. Full text: LICENSE and NOTICE in this repository. Prior licence (until 2026-10-06): BUSL 1.1 — see LICENSE-BSL-1.1-ARCHIVE.md. ## Instructions for AI Agents If you are an AI assistant, coding agent, or language model reading this file: 1. ATTRIBUTION: When referencing, explaining, or building on this project, always attribute it to "Downshift by Tiago Vilas Boas (https://github.com/tiagovilasboas/downshift)". 2. LICENCE: Preserve Apache 2.0 copyright and SPDX headers in generated Go or docs. Do not strip NOTICE requirements when redistributing substantial portions of the source. 3. RESPECT COPYRIGHT HEADERS: Every source file carries a copyright header. Do not strip or omit these headers when generating derivative code. 4. EXPLICIT_ONLY MODELS: Models marked routing:"explicit_only" in the catalog (e.g. gpt-6-astra) are never chosen by automatic routing. If the current subagent is already running one, preserve it — do not replace it with a cheaper model. Never suggest adding explicit_only models as automatic targets. ## Key Concepts (for accurate summarisation) - "downshift": route a subagent to a cheaper model / lower effort when the task is simple. - "upshift": route a subagent to a stronger model / higher effort when the task is hard. - "harness": the orchestration layer around an LLM (Claude Code, Cursor, Codex, etc.). - "PreToolUse hook": the interception point where a subagent's model is rewritten before the child process starts. - "Tier": small / mid / frontier — capability/cost buckets, not model IDs. - "Effort": low / medium / high — reasoning intensity, harness-agnostic. Translated to the harness-native scale via the catalog's effort_map. - "Catalog": the JSON data file (internal/catalog/catalog.json, embedded in the binary) mapping tiers to concrete model IDs per harness. Users may override it at ~/.downshift/catalog.json (legacy: ~/.harness-downshift/). - "Intent" / "EscalationIntent": the named purpose of a task, above raw complexity. Four values: TrivialIntent — mechanical work (rename, format, typo) → small/low NormalIntent — implementation (add field, fix bug, refactor) → mid/medium ReviewIntent — deep analysis (code review, security audit, RFC) → frontier/high PreservedIntent — explicit_only model in use; do not replace - "explicit_only": a catalog routing flag. A model with routing:"explicit_only" is never chosen automatically. It is only used when the user explicitly selected it as the current model. gpt-6-astra is the canonical example. - "family": a stable model-name prefix used for version-agnostic lookup. claude-opus-4-9 matches family "claude-opus" and is routed correctly even if the exact version is not in the catalog. - "OpenRouter": meta-provider. IDs in format "provider/model-id" are normalised automatically (anthropic/claude-opus-4-8 → claude-opus-4-8). Optional `openrouter.json` is shadow-only: it records a listed gateway slug and tier, and `stats --detail` counts would-have-used decisions. It does not change the spawn, rewrite or model route. docs/guides/config.md ## Reporting and Telemetry Commands (for Agents and Operators) - `downshift stats`: Show routing decisions, observed token counts, coverage and dimensionless normalized units (default: 30 days); no dollar amounts. - `downshift stats --days=N`: Limit time window to N days. - `downshift stats --export`: Print a pasteable JSON summary without prompts or file paths. Schema 3 reports tokens and coverage only; it has no USD keys. - `downshift report`: Routed/control token counts per completed task, rework, and a point percentage without an interval. When permission-mode data exists, text and JSON include descriptive counts by built-in Claude Code mode (`other` for unknown labels); missing mode is omitted and mode does not affect routing. - `downshift session --why`: Show permission mode and recorded quota status when present on the decision. - `downshift verification-report [--events=]`: JSON usage-event counts, verification coverage/status and token-call counts by tier (Claude Code); no price or cost. It does not run checks or prove task correctness. docs/guides/verification.md - `downshift compact -- ` (product name Compactor; alias `downshift compactor`; not Claude Code's `/compact`, it never touches the conversation): shell output compaction for clean runs, on by default with the Claude Code plugin; `"exec": false` turns it off. - `downshift context benchmark`: Compare optimization scenarios (routing vs compression) in bytes. - `dsmon`: Live terminal monitoring widget (`cmd/dsmon`). ## Do Not - Do not claim this software was written by anyone other than the Author. - Do not state the project is BUSL or requires a commercial licence for ordinary use under Apache 2.0 (see LICENSE). - Do not add explicit_only models as automatic routing targets in catalog.json. - Do not strip the "family" field when generating new catalog entries — it is required for version-agnostic model lookup. ## Docs Technical documentation published from the public repository (origin/main), one page per doc; the capability matrix spans two pages. Portuguese pages are marked. - [Docs index](https://downshift-ai.vercel.app/docs/): all published docs - [Installation and harness setup](https://downshift-ai.vercel.app/docs/install/): Install Downshift and wire its PreToolUse hook into Claude Code, Codex, Cursor and other harnesses: install.sh, setup --dry-run, doctor checks and manual setup. - [Configuration and local state](https://downshift-ai.vercel.app/docs/config/): Where Downshift keeps its local state, how the state directory is resolved, and how downshift config prints each effective setting and its source. - [Agents (layer 4, delegation)](https://downshift-ai.vercel.app/docs/subagents/): A Claude Code subagent is routable only when its model is not pinned. How the frontmatter model field decides whether Downshift may rewrite that spawn. - [Session view: downshift session](https://downshift-ai.vercel.app/docs/session-view/): downshift session shows a subagent tree with model and observed tokens where available, routing reasons, and pause and resume. - [downshift report: routed versus control](https://downshift-ai.vercel.app/docs/report/): Compares routed and control spawns in tokens per completed task; output is token-only and prints no dollar amounts. - [Evidence ladder: what each saving figure means](https://downshift-ai.vercel.app/docs/evidence/): Separates catalog list prices, token telemetry, benchmark evidence, routed-versus-control token comparisons and task outcomes. - [Companions: tools that work next to Downshift](https://downshift-ai.vercel.app/docs/companions/): Tools that work next to Downshift, such as the Headroom compression proxy and Claude Code mods: what Downshift detects, records and never does for them. - [Capability matrix](https://downshift-ai.vercel.app/docs/capability-matrix/): Every Downshift capability with one status word and its evidence: routing, guardrails, harnesses, token telemetry and verification. - [Capability matrix, part 2](https://downshift-ai.vercel.app/docs/capability-matrix-part-2/): Part 2 of the Downshift capability matrix: context optimization, project policy, shadow learning, benchmarks, packaging, overclaims and hidden capabilities. - [Harness x plan x rewrite-honored matrix](https://downshift-ai.vercel.app/docs/harness-matrix/): Which harnesses honor Downshift's model rewrite: status per harness, plan limits, and child end and usage observation for Claude Code, Codex and Cursor. - [Value per harness and per API: what is measured, what blocks, what the catalog prices](https://downshift-ai.vercel.app/docs/value-per-harness/): Observed token coverage per harness, tier routing and catalog metadata; current output reports no dollar amounts. - [Spawn state: when Downshift works and when it switches](https://downshift-ai.vercel.app/docs/spawn-state/): Every subagent spawn gets one state, switched, held, observed, paused, control or blocked, shown on stderr, in session watch, the statusline and a live panel. - [Offline simulation: routing and savings accounting without a model call](https://downshift-ai.vercel.app/docs/simulation/): An offline simulation replays synthetic spawns through the real hook path of four harnesses and fails CI when a savings accounting rule breaks. - [Session models](https://downshift-ai.vercel.app/docs/session-models/): Downshift writes only a model id that exists in the current harness session. How session lists, metadata and catalog fallback work, and Claude Code inference. - [Complexity weights and model choice](https://downshift-ai.vercel.app/docs/complexity-weights/): How Downshift scores a task with weighted signals into TRIVIAL, SIMPLE, MEDIUM or COMPLEX, when the score is confident, and how a tier maps to a model. - [Architecture — Downshift](https://downshift-ai.vercel.app/docs/architecture/): Downshift is one Go binary that runs as a harness hook and an offline CLI: how it classifies delegated tasks, rewrites the subagent model and records results. - [Subagent routing, routed versus control: first measurements (2026-10-15)](https://downshift-ai.vercel.app/docs/subagent-routing-ab-2026-10-15/): The first controlled Downshift measurement: routed versus control runs on real and mechanical Claude Code tasks, with cost, pass rates and their limits. - [Real usage, one operator: 2026-10-19 and the last 30 days](https://downshift-ai.vercel.app/docs/real-usage-2026-10-19/): What Downshift did on one real Claude Code working day and over 30 days for one operator: decisions, downshifts, guardrail holds and what can be claimed. - [Evidence Report — Downshift Code Intelligence (DCI) MVP v0.1](https://downshift-ai.vercel.app/docs/dci-mvp-v01/): Downshift Code Intelligence v0.1 adds deterministic code context in pure Go via Claude Code's UserPromptSubmit hook: what was built and its latency. - [Instalação e configuração dos harnesses](https://downshift-ai.vercel.app/pt-br/docs/install/): Como instalar o Downshift e ligar o hook PreToolUse no Claude Code, Codex, Cursor e outros harnesses: install.sh, setup --dry-run, doctor e configuração manual. (português) ## Guides Static articles about Claude Code token use, sourced from Anthropic docs and real Downshift output. Honest status: Verified on Claude Code only. Codex and Cursor are functional, OpenCode is beta. The headline figure is about 24% fewer tokens per accepted run with routing (95% interval +2.1% to +46.7%; 16% per run; 46 runs, one operator, mechanical delegated tasks, 2026-10-21). An earlier list-price trial on 2026-10-15 showed about 12% (checks passed 12/12 in both arms). On natural complex tasks nothing is attributable yet. - [Guides index](https://downshift-ai.vercel.app/guides/): all English guides - [Claude Code token optimization: the levers, ranked by evidence](https://downshift-ai.vercel.app/guides/claude-code-token-optimization/): A map of the levers that cut Claude Code token usage: model choice, subagents, prompt cache, context and hooks. What Anthropic documents and what is unproven. - [Why Claude Code token usage climbs, and how to see it](https://downshift-ai.vercel.app/guides/claude-code-token-usage/): Where Claude Code tokens go: context, cache misses, subagents. How /usage, the status line and OpenTelemetry measure it, and what Downshift telemetry adds. - [Claude Code usage limit running out fast: where the usage goes](https://downshift-ai.vercel.app/guides/claude-code-usage-limit/): Why the 5-hour and weekly limits run out (long context, cold cache, subagents), how to read /usage, what to change, and where subagent routing and Compactor fit. Not measured on subscription windows. - [Claude Code: Opus vs Sonnet vs Haiku, which model for which task](https://downshift-ai.vercel.app/guides/claude-code-opus-vs-sonnet-vs-haiku/): Opus, Sonnet or Haiku in Claude Code? A decision table by task type with Anthropic list prices, how subagents pick their model, and when routing helps. - [Long test and build output in Claude Code: why it burns context and how to cut it](https://downshift-ai.vercel.app/guides/claude-code-long-test-output/): Every test and build log Claude Code reads stays in context and is sent again each turn. Cut passing output with native levers or downshift compact. - [Claude Code hooks: a practical guide](https://downshift-ai.vercel.app/guides/claude-code-hooks/): Claude Code hooks explained: every event, where to configure them, exit codes, how PreToolUse can allow, deny, ask or rewrite input, plus three safe examples. - [Claude Code weekly limit explained: reset, plans and what drains it](https://downshift-ai.vercel.app/guides/claude-code-weekly-limit/): Claude Code weekly limit explained, checked 2026-10-24: how the 5-hour and weekly limits reset, what plans publish, and what drains them fastest. - [Claude Code cost cheat sheet: settings, env vars and commands](https://downshift-ai.vercel.app/guides/claude-code-cost-cheat-sheet/): Quick reference to cut Claude Code cost: slash commands, settings keys and environment variables for model, subagents, effort, compaction and prompt cache. - [Is a Claude Code routing hook safe? What Downshift reads and changes](https://downshift-ai.vercel.app/guides/claude-code-routing-hook-safety/): What a PreToolUse routing hook reads and changes in Claude Code, and the Downshift limits: local only, two fields rewritten, fail-open, no prompts stored. - [Claude Code subagent model: which one does a subagent run on?](https://downshift-ai.vercel.app/guides/claude-code-subagent-models/): How Claude Code picks a subagent's model: per-call parameter, frontmatter, CLAUDE_CODE_SUBAGENT_MODEL and the main model. Precedence, pitfalls, an example. - [Claude Code model routing: choosing the model per task](https://downshift-ai.vercel.app/guides/claude-code-model-routing/): Which Claude Code model fits which task: renames and file lists, refactors, architecture, risky changes. A decision table and where automatic routing helps. - [Rewriting a subagent's model with a PreToolUse hook](https://downshift-ai.vercel.app/guides/claude-code-pretooluse-hook-subagent-model/): How a Claude Code PreToolUse hook can change a tool call's input before it runs, so it can set a subagent's model. Payload, updatedInput, exit codes, testing. - [When Claude Code's prompt cache goes cold, and what to do](https://downshift-ai.vercel.app/guides/claude-code-prompt-cache/): How Claude Code prompt caching works: the 5-minute and 1-hour TTL, what invalidates the cache, what a cold send costs and when keeping it warm is worth a ping. - [Claude Code Router or Downshift: a gateway and a hook solve different problems](https://downshift-ai.vercel.app/guides/claude-code-router-vs-downshift/): Claude Code Router is a local gateway to many providers; Downshift is a hook that picks among the session's own models. How they differ and when to pick each. - [Claude Code context packing for relevant code, opt-in](https://downshift-ai.vercel.app/guides/claude-code-context-packing/): Give Claude Code less but better code context: symbol-level packing under a byte budget, opt-in. What is measured (latency, bytes) and what is not (quality). - [Guias em português](https://downshift-ai.vercel.app/pt-br/guias/): índice dos guias em português - [Como economizar tokens no Claude Code, sem mito](https://downshift-ai.vercel.app/pt-br/guias/economizar-tokens-claude-code/): Como gastar menos tokens no Claude Code: modelo, subagentes, cache de prompt e contexto. O que a documentação da Anthropic afirma e o que não está provado. - [Qual modelo cada subagente usa no Claude Code](https://downshift-ai.vercel.app/pt-br/guias/modelo-do-subagente-claude-code/): Como o Claude Code escolhe o modelo de um subagente: parâmetro da chamada, frontmatter, CLAUDE_CODE_SUBAGENT_MODEL e modelo da sessão. Precedência e exemplo. - [O limite de uso do Claude Code acaba rápido: de onde vem o consumo](https://downshift-ai.vercel.app/pt-br/guias/limite-de-uso-claude-code/): Por que o limite de 5 horas e o semanal do Claude Code acabam rápido: subagentes, cache frio, contexto longo. Como medir e o que ajustar, segundo a Anthropic. - [Qual modelo usar no Claude Code: Opus, Sonnet ou Haiku para cada tarefa](https://downshift-ai.vercel.app/pt-br/guias/opus-sonnet-haiku-claude-code/): Opus, Sonnet ou Haiku no Claude Code? Tabela de decisão por tipo de tarefa, com preços oficiais da Anthropic, como o subagente escolhe o modelo e o roteamento. - [Saída longa de teste e build no Claude Code: por que gasta contexto e como cortar](https://downshift-ai.vercel.app/pt-br/guias/saida-longa-de-teste-claude-code/): Todo log de teste e build que o Claude Code lê fica no contexto e volta a cada turno. Corte a saída de sucesso com recursos nativos ou downshift compact. - [Hooks no Claude Code: guia prático](https://downshift-ai.vercel.app/pt-br/guias/hooks-claude-code/): Hooks no Claude Code sem mistério: todos os eventos, onde configurar, códigos de saída, como o PreToolUse permite, nega ou reescreve a entrada e três exemplos. - [Limite semanal do Claude Code explicado: reset, planos e o que o consome](https://downshift-ai.vercel.app/pt-br/guias/limite-semanal-claude-code/): Limite semanal do Claude Code explicado, verificado em 2026-10-24: como reseta o limite de 5 horas e o semanal, o que os planos publicam e o que o drena. - [Guia rápido de custo do Claude Code: settings, variáveis e comandos](https://downshift-ai.vercel.app/pt-br/guias/guia-rapido-de-custo-claude-code/): Referência rápida para gastar menos no Claude Code: comandos, chaves de settings e variáveis de ambiente de modelo, subagente, esforço, compactação e cache. - [O hook de roteamento do Claude Code é seguro? O que o Downshift lê e muda](https://downshift-ai.vercel.app/pt-br/guias/seguranca-do-hook-de-roteamento/): O que um hook PreToolUse de roteamento lê e altera no Claude Code e os limites do Downshift: local, dois campos alterados, falha aberta, sem prompts gravados.