spend-guard
/spend-guard
Obniża koszty AI w projekcie, kierując rutynowe zadania do tańszego modelu, a krytyczne do silniejszych.
- Autor
- PrashantAHD ↗
- Repozytorium
- spend-guard ↗
- Licencja
- MIT
- Ostatnia zmiana repozytorium
- 13.11.2026
Ocena i bezpieczeństwo
- Pliki w paczce
- 2
- Skrypty
- 1
- Komentarze HTML
- 0
- Adresy URL w SKILL.md
- 0
Brak sygnałów. Repozytorium zmienione 13.11.2026, bez odwołań do wycofanych modeli i API.
MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.
- 1 skrypt w paczce. Przejrzyj je przed instalacją, bo Claude może je uruchomić.
Skrypty: spendguard.py
Co robi i kiedy
Obniża koszty AI w projekcie, kierując rutynowe zadania do tańszego modelu, a krytyczne do silniejszych.
Argumenty
/spend-guard setup | update | remove | report | stale
Oryginalny opis (EN)
Cut AI (Copilot/agent) spend in a project: a cheap default model for routine work, automatic hand-off of coding, security reviews and accuracy-critical work to stronger models, an optional independent second pass, and a guard that moves new tasks out of long chats. Use when asked to reduce AI costs, set up model routing, add Spend-Guard to a project, update or remove it, or report AI spend.
Jak działa
- Setup in a project (/spend-guard or "set up spend-guard")
- Other commands
- Plan schema
Podgląd SKILL.md
---
name: spend-guard
description: 'Cut AI (Copilot/agent) spend in a project: a cheap default model for routine work, automatic hand-off of coding, security reviews and accuracy-critical work to stronger models, an optional independent second pass, and a guard that moves new tasks out of long chats. Use when asked to reduce AI costs, set up model routing, add Spend-Guard to a project, update or remove it, or report AI spend.'
argument-hint: 'setup | update | remove | report | stale'
---
# Spend-Guard
Sets a project up so every task gets the model it actually needs:
| Tier | Used for |
|---|---|
| cheap (default) | routine work: running tools and tests, small edits, docs, git |
| standard | writing and fixing code |
| accurate | security reviews and accuracy-critical work |
| checker | an independent second pass from a different model family |
Spend-Guard can generate the same routing policy for Copilot and Claude Code. Copilot remains the
default provider for backwards compatibility; add `"providers": ["copilot", "claude"]` to a plan
to generate `.claude/skills/` and a marked `CLAUDE.md` section as well. Existing Claude files are
never overwritten.
The mechanical part is [spendguard.py](./spendguard.py) (standard library only); your job is the judgement:
understanding the project and proposing the right specialists. Never overwrite files Spend-Guard didn't
create; the script already refuses to.
Each applied project also gets `.github/notes.md` when that file is missing. It is a short, user-maintained
handoff: append 1-3 lines at task completion with a decision, current state, half-done work or a gotcha.
Condense older entries around 60 lines. Never put secrets or client data there. Update and remove leave it
untouched.
The generated `sessionStart` hook automatically adds the capped notes and a deterministic digest of the
most recently modified previous chat in the same workspace to startup context. It reads local session logs
only, makes no model call, and fails open if the input or logs are unavailable. It also runs the same
local instruction-health check as `validate` and, if anything is wrong, appends a single
"Spend-Guard instruction health warning" line (warn-only; it never blocks the chat).
The generated `userPromptTransformed` hook, on the first prompt of each local day in an applied
tool, checks whether a newer Spend-Guard version exists. If it does, it asks the user to upgrade
and still continues the user's request. Later prompts that day stay quiet. The check fails open.
The same hook also checks speed. When a prompt arrives it classifies the task with the same classifier as
`dispatch` (routine, code, accuracy, sensitive) and works out how long it should take: the median
cheap-model seconds of the last 30 completed tasks of that kind on this machine (60s for routine, 240s
otherwise until 5 tasks exist). The budget is twice that. A `postToolUse` hook checks the budget after each
tool call. If the cheap model is still running the task and has used more model time than the budget, it
tells the agent once to step up one tier and hand the rest of the task to a standard-tier subagent. An
`agentStop` hook adds tasks that stayed within budget to the history, so expectations follow real
speed. Separately, if the cheap model's last 5 calls in a chat already have a median of 45s or more, the
step-up is suggested before the task starts. It never moves to the accurate tier just for speed.
`SPEND_GUARD_BUDGET_FACTOR` (default 2, `0` disables) and `SPEND_GUARD_SLOW_SECONDS` (default 45, `0`
disables) tune it. State lives in `~/.copilot/spend-guard/`; it makes no model or network call.
An optional `spendguard.py graph <folder>` command builds a local deterministic code graph from supported
source files using the Python standard library. It records only relative paths, symbol names, imports and
SHA-256 fingerprints; it excludes secret-looking files, symlinks, dependency/build directories and files
over 200 KB. It makes no network or model calls and writes `GRAPH_REPORT.md` under
`.github/spend-guard-graph/`. The startup hook includes only the bounded report, never the graph or source
contents.
Applied projects also receive `.github/spend-guard-providers.json`, an opt-in policy for compatible
external API tools. Its default allowlist is limited to Claude/Anthropic, GPT/OpenAI, Grok/xAI,
NVIDIA and Gemini/Google. Use one primary provider and fall back only on an unavailable provider,
timeout or failed validation. External routing is `free_only` and requires explicit free-quota
confirmation; paid external fallback is blocked. Copilot models, including Copilot catalog Grok,
remain the default route. This policy does not reroute GitHub Copilot's endpoint, stores no credentials,
and does not add provider SDK dependencies.
The route-only dispatcher (`spendguard.py dispatch <folder> <task> [--free-quota-confirmed]`) classifies
work locally and returns JSON selecting Copilot or an approved external provider. Copilot is the default.
An external route requires explicit confirmation that the provider's quota is free; sensitive tasks are
limited to Anthropic/OpenAI and always retain a Copilot fallback. It makes no model or network calls and
never reads credentials. The calling client must confirm quota and execute the route.
Keywords match whole words with simple inflections (so `latest`, `prefix` or `scanner` do not upgrade a
task), and questions, status checks or re-runs that do not ask for a change or a review stay on the cheap
tier. `tests/test_spendguard.py` keeps a routing case set that checks both directions.
Run the script as `python "<this skill folder>/spendguard.py" <command>` (on macOS/Linux `python3`).
**On every Spend-Guard request:** run `spendguard.py stale <workspace folder>` first. That checks
the current tool plus any previously applied tools. If `outdated` is not empty, tell the user
which ones are behind this version and ask whether to `update` them now. Do not update without
confirmation.
## Setup in a project (`/spend-guard` or "set up spend-guard")
1. **Check it's allowed.** If the repository looks like company or client work, ask the user to confirm
their employer allows changing how AI tools are used there. Never send code anywhere new.
2. **Scan the tool:** `spendguard.py analyze <workspace folder>` then
`spendguard.py propose <workspace folder>`. Propose reads that project's skills, instructions,
languages, tests, secrets and sensitive paths and drafts a routing plan for *this* tool — cheap
default, specialists, `cheap_overrides` from workflows it found, review cap, and the 100k-token
new-chat guard. It does not hardcode another product's task names. Skim the README (first ~60
lines) and any existing `AGENTS.md`/`.github/copilot-instructions.md` only to tighten the
one-line summary. Don't read big files.
3. **Adjust the drafted plan** (JSON, schema below) rather than writing one from scratch:
- `project`, `main_name` (short, e.g. the project name), one-line `summary`.
- `routine`: what the cheap main agent does itself (run tests, regenerate outputs, docs, git, ...).
- `test_command` from the analysis.
- `avoid_files`: the analysis `big_files` (and any large reference data). Agents will search them, never open them whole.
- `rules`: safety rules every agent follows, e.g. "Never read or print `config.json`" for each
`secret_files` entry; "Search `<file>` and read only the ranges you need" for each `big_code_files`
entry; and any project rule from existing docs that must not be broken (keep them short).
- If `always_loaded_instructions` lists files with `applyTo: '**'`, mention to the user that they load on
every request and cost tokens each time; trimming them or narrowing `applyTo` saves more. Don't edit them yourself.
- `specialists`:
- a **developer** (`role: developer`, tier standard) for any project with code;
- a **reviewer** (`role: reviewer`, tier accurate, read-only) only if there is security-sensitive code
(`sensitive_code` in the analysis, or auth, payments, signing, infra, permissions). Make `when`
name the exact areas;
- an **extractor** (`role: extractor`, tier accurate) when the project reads documents, images,
handwriting, scans or data where a misread is costly. Set `double_check: true` to add an
independent checker on a different model family;
- `custom` specialists only for a clearly separate expensive task type.
Keep it minimal: every specialist adds a hand-off cost. Most projects need just the developer.
4. **Confirm with the user** in one question form: the specialists (name, what they handle, tier), whether
anything needs the accuracy double-check, and the files to avoid. Adjust the plan to their answers.
5. **Apply:** write the plan to a temporary file, run `spendguard.py apply <folder> --plan <file> --dry-run`,
check the output, then run it without `--dry-run`. If it skipped a file that already exists (not created by
Spend-Guard), tell the user; don't work around it.
6. **Report back** in a few lines: what each agent does and which model, what was skipped, and that new chats
in this project start on the cheap model. Suggest committing `.github/agents/`, `.github/hooks/`,
`.github/spend-guard.json`, `.github/notes.md`, `AGENTS.md` and `.vscode/settings.json`.
## Other commands
- **propose** (`spendguard.py propose <folder>`): scan the project and print a draft plan. First-time
setup should start here so routing matches that tool's workflows, not a built-in list.
- **update** (`spendguard.py update <folder>`): re-render everything from the saved plan, e.g. after
editing `.github/spend-guard.json` or the model tiers.
- **remove** (`spendguard.py remove <folder>`): removes only what Spend-Guard created.
- **report** (`spendguard.py report --days 7`): AI cost per project and model from the local Copilot logs,
compared with the previous period, plus chats that grew past 100k tokens. Summarise it in a few lines with
one or two concrete suggestions.
- **tiers** (`spendguard.py tiers [--init]`): show the model tiers; `--init` writes an editable copy to
`~/.copilot/spend-guard/tiers.json`. After editing, run `update` in each project.
- **graph** (`spendguard.py graph <folder>`): build or incrementally update the local code graph and report.
- **memory search** (`spendguard.py memory search <folder> <query> [--all-workspaces]`): search approved
user and assistant messages from existing Copilot sessions. It is local-only, searches the current
workspace by default, and supports intentional cross-workspace lookup with `--all-workspaces`. It
excludes subagent/automation sessions, redacts credential-like values, ignores `config.json`/`.env`
references, includes source workspace paths, caps output at about 6,000 characters, and makes no model
calls. It is on-demand rather than automatically injected, so it does not add tokens to ordinary requests.
- **dispatch** (`spendguard.py dispatch <folder> <task>`): return a deterministic, route-only decision
between Copilot and an approved provider based on task kind. It never invokes a provider.
- **validate** (`spendguard.py validate <folder> [--strict]`): audit the generated setup, hooks, notes,
provider policy, syntax and reviewer coverage without running project code or making model/network
calls. Strict mode turns warnings into failures.
- **stale** (`spendguard.py stale [folder ...]`): list applied tools whose saved
`spend_guard_version` is behind this skill. Pass the current workspace so unregistered tools
are still checked. Prompt the user to `update` each outdated one.
## Plan schema
```json
{
"project": "Billing API",
"main_name": "Billing",
"summary": "REST API that issues invoices",
"routine": ["running tests", "small edits", "docs", "git"],
"test_command": "python -m pytest",
"providers": ["copilot", "claude"],
"provider_policy": {
"allowed": ["anthropic", "openai", "xai", "nvidia", "google"],
"routing": {
"cheap": ["google", "openai", "nvidia"],
"standard": ["anthropic", "openai", "google"],
"accurate": ["anthropic", "openai"],
"checker": ["google", "xai"]
},
"dispatcher": {
"external_mode": "compatible_tasks",
"sensitive_external": "trusted_external",
"external_cost_mode": "free_only",
"require_free_quota_confirmation": true
}
},
"avoid_files": ["data/rates.csv"],
"rules": ["Never read or print `.env`."],
"guard_tokens": 100000,
"cheap_overrides": ["nightly report refresh", "regenerating reports from saved evidence"],
"review_policy": {
"max_rounds": 2,
"blocking_severities": ["critical", "high"],
"when": "before_push"
},
"specialists": [
{"name": "Billing Developer", "role": "developer", "when": "Code changes beyond a one-line fix"},
{"name": "Billing Security Reviewer", "role": "reviewer",
"when": "After a change to auth/, payments/ or webhook signing"},
{"name": "Invoice Reader", "role": "extractor", "double_check": true,
"when": "Reading scanned invoices or PDFs",
"instructions": "Amounts use a comma as the decimal separator."}
]
}
```
`role`: developer | reviewer | extractor | custom. `tier` defaults by role (developer: standard,
reviewer and extractor: accurate, custom: standard). `read_only` defaults to true for reviewers.
`instructions` adds project-specific guidance to that agent.
`cheap_overrides` are project-specific phrases (not hardcoded tool names). They are matched before
specialists and stay on the cheap model. Escalate those to the extractor/checker only when counts
or IDs do not reconcile. Each consuming project lists its own overrides in its plan.
Every generated agent (Copilot and Claude) and the always-loaded routing section include a built-in
cheap-first rule: always prefer the cheapest capable model for simple tasks, and use lightweight
subagents for simple delegated work. It needs no plan entry; `validate` warns if the main agent lacks it.
`review_policy` defaults to at most 2 rounds, only Critical/High findings block, and review only
immediately before a push. The 100k-token hook tells the agent to stop and start a fresh cheap chat
instead of continuing past the cap. `validate` runs warn-only instruction-health checks on `AGENTS.md`,
`CLAUDE.md`, `.github/copilot-instructions.md` and `.github/instructions/*.instructions.md`: always-loaded
files (`applyTo: '**'` or `.github/copilot-instructions.md`) longer than 40 lines, backticked or linked
relative paths that no longer exist (URLs, globs and placeholders are ignored), and duplicate, unbalanced,
or misplaced Spend-Guard sections that could give conflicting routing rules. These are warnings only;
they fail `validate` only with `--strict`.
Pliki w paczce (2)
- SKILL.md 15 KB
- spendguard.py 105 KB
Wersje
W bazie nie ma innych skilli o nazwie spend-guard.
Migawka bazy z 13.11.2026 · wersja paczki 4157d3024aee (skrót SHA-256 całej paczki)
Pobrania w ostatnich 30 dniach: 0 · ranking
Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.
Podobne skille
- 100code-team-init
Ustawia, który model AI obsługuje każdy rodzaj pracy kodowej, aby ograniczyć koszty tokenów w różnych narzędziach. - 100route-cheap-escalate-hard
Obniża koszt LLM przez kierowanie masowej pracy do taniego modelu i eskalowanie do droższego tylko trudnych tur, bez utraty jakości w zadaniach wymagających. - 100cost-aware-llm-pipeline
Obniża koszty wywołań LLM przez routing modeli według złożoności zadania, śledzenie budżetu, ponawianie prób i buforowanie promptów. - 100lindy-cost-tuning
Obniża koszty Lindy AI przez zarządzanie kredytami, dobór modeli i konsolidację agentów oraz analizę zużycia kredytów. - 100cheap-swap-guard
Wymusza przed przejściem na tańszy model zadeklarowanie przypadków, w których model premium nadal wygrywa, i sprawdza, że nadal trafiają do premium. - 100llm-router
Dobiera model i dostawcę LLM do każdego zadania według złożoności, budżetu i wymagań, kierując proste zadania do tanich modeli, a złożone do mocniejszych.