Delega Efficiente
ASecurityUse when the user asks how to organize, split or delegate work - a batch of similar items, several files, subagents, workflows, a cheaper model, a quota to protect - and before launching any Agent/Task/Workflow call, when the pre-delegation gate denied one, when large tool outputs or a filling context window are the problem, or when closing a task that blew past its expected cost or escalated through repeated failures. The kernel carries the six routing axes; this body has the delegation cont...
- 4 stars
- 0 votes
- 0 copies
- 2 views
- Added September 2, 2026
Works with
Security analysis
100/100Pro scans all 3 files and shows the line behind each finding
npx -y skills add frsorrentino/fable-director --skill delega-efficiente --agent claude-codeAre you the author of Delega Efficiente?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/frsorrentino-delega-efficiente)---
name: delega-efficiente
description: Use when the user asks how to organize, split or delegate work - a batch of similar items, several files, subagents, workflows, a cheaper model, a quota to protect - and before launching any Agent/Task/Workflow call, when the pre-delegation gate denied one, when large tool outputs or a filling context window are the problem, or when closing a task that blew past its expected cost or escalated through repeated failures. The kernel carries the six routing axes; this body has the delegation contract, the pre-budget flags, the verification ladder and the playbook the plan needs.
---
# Delega efficiente
Operating policy (user directive): the top model plans, judges and verifies; execution goes to the cheapest adequate means. Scripts cost zero — prefer them over any model call for deterministic work. Quality-sensitive code always goes to the top model, accepting extra tokens.
Policy complexity budget (meta-rule): every addition to this skill must delete an existing policy or replace two exceptions — the skill never grows net. Same principle as the playbook's 30-line cap: each rule is a permanent cognitive cost paid at every invocation.
## Route by task properties
Any route involving delegation/orchestration declares a one-line pre-budget (see "Falsifiable pre-budget"). Before planning batch/workflow/multi-agent work, consult the playbook at `~/.claude/delega-playbook.md` (init from the plugin's `playbook-template.md` if missing; a team may point it to a shared repo file via symlink).
Route the REMAINDER, not the task: sunk tokens never justify staying on the current route — compare the cost of the NEXT step only. A mid-task route change is a `reversal` (log it — see Telemetry): not an error, a falsified initial decision.
Score the task on six axes, top to bottom; earlier axes override later ones:
1. **Interactivity** — needs live iteration (visual, browser, user feedback)? → top model inline, never delegate.
2. **Error cost** — production code, client-facing numbers/wording, irreversible or externally visible writes? → top model, accepting extra tokens. Reclassifying a task as low-error-cost to save tokens is the canonical Goodhart failure: when in doubt, it IS quality-sensitive. Risk class only ratchets UP mid-task, never down.
3. **Determinism** — is the core doable by code? → script, zero model tokens (see Script promotion).
4. **Cardinality** — N similar items? → workflow, mid-model agents grouped ~10-15 by affinity (brand/domain/file), forced JSON schema. Default executor: agent `fd-executor` (shipped with the plugin, effort pinned `low` in frontmatter — the Agent tool has no per-call effort parameter, so pinned agents are the only real effort lever; declare the tier with `budget-open --effort`). Single item, 1-2 files → inline, zero orchestration. Fan-out is 1+(N-1): ONE canary verified rung-1 before the rest — a systemic failure (hallucinated schema, changed DOM) costs 1× not N×. Canary guards systemic failures only; skip for playbook-confirmed recurring pipelines.
5. **Verifiability** — objective test exists? → deterministic assertions (ladder rung 1). None → contract-first checklist + adversarial verifier per finding on top model (rung 3).
6. **Cache locality** — every subagent pays a COLD START: own uncached prefix, re-fed context (it does NOT break the main thread's cache); switching model or editing plugins/skills mid-session invalidates the prompt cache. Before spawning: does the cold start cost more than the delegation saves? Topology follows: one workflow with grouped items ≫ N single-item subagents (one warm prefix vs N cold starts; siblings launched in the same message share the system prefix and pay about half the cold start — measured 2026-09-01: 29k create for the first, 13k create + 16k read for the next). FORK ≠ fresh subagent: the fork inherits conversation + prompt cache (measured n=3, 2026-09-01, CC 2.1.257: per-turn cache_create 200-2.000 tok, cache_read = the whole ~150k parent context, model override ignored) but re-pays the whole parent context every turn at cache_read rates, always on the parent's model, and its spend is nearly invisible to the 2×/3× gate (fresh-token accounting excludes cache_read; eq accounting captures it ex post, per model). The parity point is MODEL-CONDITIONAL (`model-economics.json`): on Claude Fable 5.1 (cache reads 0.025×) a fork turn at 150k CTX costs ~4-5k eq against a 17-37k eq cold start → fork pays off up to ~7-12 turns; on 0.1×-cache models the same turn costs ~15k eq → ~2 turns. The parity scales inversely with the parent model's `cache_read` in `model-economics.json`; rates between these two anchors (e.g. 0.05× on Claude Opus 5.5) are an extrapolation until measured. Fork for short, context-heavy tasks no spec can bundle; batch/spec-able work stays on fresh pinned executors (measured n=3 real items: `fd-executor` at low effort on sonnet vs on Fable 5.1 — same eq, same correctness, 5.5× the USD on Fable; the executor stays on sonnet). Cost VETO on borderline axis-4/5 routes — never forces delegation, never overrides axes 1-2.
Axes compose rather than exclude: a batch (4) of quality-sensitive items (2) → mid-model executes, top model reviews every diff before delivery.
Route verdict: on every non-trivial task, one line — cheaper/external route yes/no and why, citing both the allowing and the forbidding axis. `[fd-route-hint]` lines (UserPromptSubmit hook, keyword match on `hint_keywords` in soft-deps.json + cardinality signals) are deterministic CANDIDATES to evaluate, never directives; `quality_guard`/`data_class` of the matched entry stay sovereign. Hint events land in telemetry (`route_hint`) so `/review` can compare hinted vs taken routes.
**Binding precedents** — anchor the axes, not exhaustive:
- Production code (any stack) → axis 2: top model inline; mid-model ONLY for verbatim transcription from a complete spec; new features via brainstorm→spec→plan. Verify: tests/lint/dry-run + top-model diff review.
- Bug fixing → axes 1+2: top model inline (systematic debugging); delegate only broad code search (a read-only search agent — PIN a cheap model on it: the built-in Explore agent runs on the session model (`model: inherit`, verified in Claude Code 2.1.282), so on a top-model session an unpinned broad search bills at top rates; compressed investigators or an explicit low-tier `model:` override cost a fraction for the same file:line map). Verify: reproduce → fix → re-test.
- Web design / UI → axis 1: never delegate aesthetics. Verify: screenshot + user.
- SEO / migrations / imports → axis 4. Verify: assertion ladder. Low-risk work — classification, text transformations, first drafts, second opinions, batches of similar non-code items — goes BY DEFAULT to a free external executor, without asking (`scripts/external-exec.py` — Gemini/Codex via cross-family config, setup check `--doctor`, logs `external_exec`, built-in JSON rung-1; `--schema-file` enforces a JSON Schema provider-side (Codex `--output-schema`) plus a local required-keys re-check; `--resume-last` continues the last Codex thread of this cwd for a sequential delta-retry after `needs_context`/`json-invalid` — never in parallel batches; `--effort low` for massive batches vs the config's `high` verify default, one placeholder-driven provider entry): the top model re-checks the output where it matters (rung-1 JSON always, rung 2-3 per the ladder); `report` tracks the ok-rate per type (the gate nudges once/day on idle daily free credits: unused free quota is lost every day). Never on this route: axis 2 items (client-facing final text without top-model review), `--data-class restricted` inputs. Providers with `billing:"paid"` are consent-gated: never proposed by default, `--paid-ok` only after an explicit user yes with the cost cited (fail-closed — a provider without `billing` counts as paid). When a free provider is configured and `--doctor` is OK, use it directly for eligible work and say so in the route verdict line; the user is not asked. Accounting is a SEPARATE LEDGER: declare `--route external`; the 2×/3× budget counts Claude transcript tokens only, external volume lives in `external_exec` events (`report`, `[XF]`, `/status`) and is never mixed with the Claude budget.
- Family prefixes (no budget, no config beyond `cross-family.json`; UserPromptSubmit hook): a prompt starting with `gemini:` / `codex:` / `gemini-stable:` gets an external DRAFT injected before the turn — correct it and deliver it as your own answer, never quote it as-is; `gemini?` / `codex?` brings back a second OPINION to report to the user AS IS, attributed and delimited, plus at most one line of yours if you disagree. `xfamily?` asks BOTH gemini and codex in parallel and reports both, always gemini first then codex, one line of yours only if they diverge; `xfamily:` yields two drafts — pick ONE as base (say which and why in one line), correct it, never merge. The prefix never overrides `data_class` (restricted budget → normal turn, said aloud) nor the quality guard (code fences, code paths with implementation verbs → normal turn); billed providers are never included without explicit consent; a provider down leaves the other, both down = normal turn with the line. Only the prompt text leaves the machine. Every call is one `external_exec` event per provider (`mode: draft|opinion`, `pair` links the xfamily couple) in the separate ledger.
- Text/content editing → mid-model with primary source; client-facing tone and numbers hit axis 2. Verify: spot-check. Axis-2-borderline content: draft-and-patch — mid drafts the complete deliverable, top model EDITS the draft instead of re-authoring. NEVER draft-and-patch for production code (Goodhart reentry).
- Consulting / web research → fan-out on mid-model, synthesis and judgment on top model; adversarial verify risky claims only.
- Video / audio / voice-over timing → skill `analisi-video` (media: ffprobe facts and contact sheets first, top model reads; `media-analyze.py` external route only for long footage, budget open).
- Session model → `/advisor fable` with Claude Opus 5.5 as the main model: Opus executes, Fable advises — the "top model judges, cheaper means executes" policy inside one session, at Opus prices for the turns and Fable prices only for the advice (server-side advisor tool; the advisor must be at least as capable as the main model; it stays on until `/clear` or `/compact`). Pinned agents keep their own model. `/advisor fable` never replaces the verifier: advice is the maker's context, rung 3 needs the fresh one. `opusplan` (Claude Code's native alias, `/model opusplan`: `opus` in plan mode, `sonnet` once execution starts) is the same split by MODE instead of by task — it sees neither error cost nor cardinality, so it is an alternative to MEASURE against the pinned routing, not a default: open the budgets of a few `opusplan` sessions under their own type (`budget-open --type <type>-opusplan`) and compare them with the same work routed by the axes — the similar-tasks line `budget-open` prints for each type (cost against the estimate, outcomes) and the verification hit-rate in `fd-telemetry.py report`; no figure stands until measured. `inherit` takes the model the session is using when the subagent starts, so under `opusplan` the verifier `fd-verifier` (`model: inherit`) runs on `sonnet` outside plan mode: part of what the measurement weighs.
- Five-hour window at the wall → `/low-priority` (continue now at lower priority on the weekly limit: slower, not stopped), the route the `[fd-route-hint]` line names at that point. Never another account (the session's context would move to another organization); with the weekly limit gone too, inline work until the reset.
## Delegation contract
- Before decomposing, pin the TASK's verifiable **done** — a command that passes, an observable behavior, or an enumerable checklist — plus the **stop condition** (include a failure cap, e.g. "stop after 3 attempts, emit a blocker report"). If done isn't verifiable, interview until it is BEFORE delegating: the top model owns "done", executors never self-assess it. Unverifiable done means the delegation isn't ready — not a licence to wing it. (This is the up-front twin of the Verification ladder, which is HOW you check; this is WHAT counts as finished.)
- Every delegation prompt is a 5-part spec contract — Objective / Files (exact paths in scope) / Interfaces (output format + status token) / Constraints (tools, sources, boundaries, hard caps) / Verification (the command or check the subagent must run and report actual output of). Vague delegation ("occupati di X") duplicates work — forbidden; a spec the subagent can execute without shared context is the test that the route is delegable at all. For GPT/Codex-family executors (external route) wrap the 5 parts in XML blocks with stable tag names (`<task>`, `<output_contract>`, `<default_follow_through_policy>`, `<grounding_rules>`): block contracts hold better than prose on that family (distilled from openai/codex-plugin-cc); tighten the contract before raising effort. The contract's measured falsifier is **rework**: files reopened after their first write (auto-counted by the Stop hook and `report`) mean information landed AFTER the code was written — the context bundle was incomplete, not the executor weak. A task type with recurring reopens is a **context-pack candidate**: a deterministic script that gathers files/state/schemas BEFORE delegation, so the spec ships the whole picture instead of letting anyone discover it piecemeal.
- Code-writing contracts carry a standard Constraints line: *write only what's needed — less redundancy, more quality, never brevity for its own sake; reuse > stdlib > native platform feature > installed dependency > new code; no unrequested abstractions; ties go to the option more correct on edge cases and more efficient, never merely shorter*. Known edge cases (inflections, boundaries, empty inputs) belong in the contract explicitly — what Verification doesn't test doesn't exist, and unrequested care is variance, not a guarantee (measured in an A/B, 2026-08). The executor's escape valve for out-of-contract value is a `PROPOSAL:` line in its report, never silent code — the director decides.
- The subagent ends with a status token: `DONE / DONE_WITH_CONCERNS / NEEDS_CONTEXT / BLOCKED / ABSTAIN`. Grant explicit permission to ABSTAIN when unsure — an honest abstention triggers immediate escalation and skips a whole verify-fail-diagnose cycle; plausible-but-wrong is the worst outcome. Status feeds the rule-of-3 diagnosis.
- Interfaces in practice: hard cap (default ~1-2k tokens), forced schema (strict JSON or grep-able `path:line — finding` lines), full-content dumps forbidden — paths, counts, anomalies only. The subagent's output is the next turn's input: a token the orchestrator won't consume is waste. The INPUT side has the same discipline: when the executor only CONSUMES an API (calls it, never edits it), Files ships its surface — `tools/skeleton.py FILE` prints signatures with file:line at ~5% of the file's tokens — not the full file; fresh input per agent is the dominant delegation cost.
- Fan-out size comes from the five-hour window, or the weekly pace where the account has no such window, and the per-agent anchors (Harness mechanics below), never from a fixed band. Multi-agent costs an order of magnitude more than a single chat (measure YOUR ratio: `report` delegation_overhead): if task value doesn't justify that multiple, don't orchestrate.
## Harness mechanics (learned from real waste)
- NEVER read a workflow's full output/TaskOutput dump. Extract via script from `<transcriptDir>/journal.jsonl` (raw result per agent; map agentId→item by grepping each `agent-*.jsonl` prompt).
- Run failed partway (session limit, hang): relaunch with `resumeFromRunId` — completed agents replay from cache, only failures re-run. Hung run: `TaskStop` first. Never restart from zero.
- Claude Code 2.1.285-2.1.287, what changed for delegation:
- A fork runs under its parent's permission mode: from plan mode it stays in plan mode and cannot exit it, from `dontAsk` it cannot ask. A fork is not a way to write from a read-only session.
- In auto mode a subagent ends as soon as it hands its report back: no extra turns after the report. Per-agent anchors measured before 2.1.285 can be slightly high.
- A Workflow subagent whose connection stalls no longer restarts from its original prompt, so a stall no longer pays the agent twice. A real hang still takes `TaskStop` and a resume.
- A folder's CLAUDE.md is no longer attached twice after a resume or a compaction. Post-resume context measured before 2.1.287 includes that duplicate.
- Since 2.1.288 a plugin agent spawned by name (agent teams, `name:` on the Agent call) keeps its own prompt, tools and effort; before, that path ran with the defaults. Checked on 2.1.288: `fd-executor` by name ran on sonnet at `low`, `fd-verifier` as a teammate on its model at `high`. Plain Agent calls kept the pins on earlier versions too.
- The fallback notice says when the fallback dropped the window from 1M to 200K. A long session past 200K on that fallback compacts at once: hand off (`/fable-director:handoff`) instead of going on.
- Claude Code 2.1.302-2.1.305, what changed for delegation:
- Forks (`subagent_type: "fork"`) are on by default in `claude -p`, the Agent SDK, the desktop app and VS Code. A fork is an Agent call like any other: the gate denies it without an open budget and counts it, in `-p` too (`tests/fork-headless-verify.py`). A fork the user starts with `/subtask` raises no PreToolUse: SubagentStart counts it, nothing can refuse it. Resuming a finished subagent with `SendMessage` is not an Agent call: the gate neither refuses nor counts it, though it can cost as much as a new one.
- After a compaction the skill list comes back (2.1.304): a fixed cost for each compaction. Measured 20/10/2026 on the personal account: 175 skills, about 30k characters. A fresh session after `/clear` pays the same list, so it does not change the handoff verdict; it makes frequent compactions dearer. `report` counts the lists sent after a compaction.
- A PreToolUse deny reason is no longer replaced by the timeout of an Agent SDK callback hook on the same call (2.1.304).
- Claude Code 2.1.307, what changed for delegation:
- Before 2.1.307 a subagent's transcript recorded every streamed response with the usage of `message_start`: input, cache_read and cache_creation true, `output_tokens` 1, `stop_reason` empty. Every figure read from `agent-*.jsonl` on those versions understates subagent output, the 5× component of eq: `delegation_outcome.eq`, the window calibration, `subagent_output`, `delegation_overhead`, `coordination_cost`, the main-vs-subagent turn ratio and the per-agent anchors above. The meter now writes `cc_version` on every outcome and summary, `placeholder_turns` and `usage_placeholder` where it sees the pattern; the calibration skips flagged agents and `report` warns. `scripts/usage-placeholder-audit.py` counts the damage per version (one `--root` per account). Re-measure the subagent-side anchors on 2.1.307 or later only.
- Forks launched together in one message now each know which Agent call is theirs; before, a fan-out of forks could take a sibling's task. Parallel forks are usable; their economics do not change: each fork re-pays the whole parent context every turn, so N forks cost N× one fork per turn and the axis-6 parity point holds per fork.
- OpenTelemetry event `claude_code.safety_event`: every call stopped, paused or rejected by a permission rule, auto mode, a hook or the sandbox. With telemetry on it is the only counter that also sees the fail-closed blocks (`onFailure: "block"` when a gate cannot run), which `gate_deny` and `perimeter_deny` never log. Off by default; not wired yet.
- Workflow economics (measured 2026-09-03 on a 16-agent legal panel: 4 waves, 49 agent transcripts, 10.4M eq of agents + 8.4M eq of launcher thread, ~70% waste):
- A five-hour window at Fable 5.1 rates absorbed 2.3M / 3.7M / 4.9M eq before the wall; a judge-type agent costs 350-580k eq, a reader 130-260k, a verifier 110-200k. Size the fan-out to the window BEFORE launching — the gate does the arithmetic from `--agents N` (warning above the remaining window, deny above 2×, options listed). Chunk wide stages so that what is in flight at the wall stays small: the loss at the wall = in-flight width × per-agent cost, paid again after the reset.
- An account whose quota data has no live five-hour figure (absent, null or past its reset; read from the data, never from the plan name) runs on the weekly pace: weekly quota left ÷ days to the reset (at least 1) = today's share. The gate denies a new fan-out above that share, 1× and not 2×, because no shorter wall stops a runaway run any more; resume always passes. It warns above 5%/h of weekly quota in the last hour (`weekly_burn_pct_h_ceiling`). Weekly capacity in eq is estimated from the five-hour figures until 5 measured pairs replace it (`weekly_eq` overrides).
- Resume replays only the longest UNCHANGED PREFIX of agent() calls (prompt + opts). Pass `args` as an object (never a JSON string), keep volatile parameters (dates) out of the early stages, edit the script only after the last cached call. The gate compares every resume with the launch record and says which agents will re-run. Before Claude Code 2.1.305 a resume also re-ran agents of `pipeline()` and `parallel()` that had already completed (a bug, fixed): resume costs measured on older versions are high.
- `model:` and `effort:` per agent() call: readers, fetchers, extractors and citation checkers are axis 3-5 work → `model: 'sonnet'`, effort low/medium; the top model and `effort: 'max'` only for the judgment/synthesis stages (measured: judges at max = 33-68k output tokens each, 40-60% of their cost); a stage's `model:` also holds when the session sits on a model fallback — Claude Code ≥ 2.1.283 retries the configured model per agent, no relaunch.
- Scanned PDFs read by agents cost ~1.5k tokens per page as images, PER agent: convert once (`ocrmypdf --sidecar`, `pdftotext`, zero model tokens) and point the prompts at the .txt.
- Launch and resume long workflows from a LEAN session: a 600k launcher re-caches ~1.2M eq at every resume after the wall (main-thread cache writes last one hour: 2× input; 3 resumes = a wave of judges). From Claude Code 2.1.299 a launcher over 200k left idle ~54 min is compacted instead: cheaper to resume, but the summary drops the detail the judgment needs (`"idleCompaction": false` in settings.json, or from 2.1.302 the "Idle compaction" row in /config, keeps it whole, `CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS` moves the threshold). Distillate on disk + fresh session (`budget-open --route bg-session`), or at least close the heavy one before the reset.
- `CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL=sonnet` (Claude Code 2.1.296) runs every workflow agent on one model and makes Claude Code ignore `model:` in `agent()` — the judgment stages too: a lever for long fan-outs whose stages all fit the cheap model.
- `+Nk` in the launch prompt sets a HARD output-token ceiling shared by main loop and workflows (`budget.remaining()` inside the script): a native fuse that stops NEW agent() calls before the wall — in-flight agents finish and get cached.
- Subagents return path + counts + anomalies, never full content.
- Tool output is next turn's input — the same discipline applies to YOUR tool calls: never pull a whole file into context when a slice will do: grep → head → partial read (`sed -n`, offset/limit) → summary script. Same for `git diff` (`--stat`, `--name-only` first) and logs (`tail`, pattern filter). The harness truncates >25k, but the 2-20k band passes whole and silently bloats context.
## Verification ladder
1. Deterministic assertions covering ~100% (counts, grep, length/schema checks, tests).
2. Top-model spot-check on 2-3 samples.
3. LLM verifiers only for individually risky claims — use agent `fd-verifier` (shipped with the plugin: read-only, effort pinned `high`, one verdict per rubric finding), always in a fresh-context subagent that receives ONLY artifact + rubric, never the maker's reasoning trail (inline self-critique is structurally self-preferential: the maker prefers conclusions consistent with what it already wrote); per-item across a batch only when no objective test exists.
4. (optional, rare, highest stakes) Cross-family verifier: `scripts/cross-verify.py --claim ... --rubric ... [--type SLUG]` — a different model family has uncorrelated blind spots, and it's out of Claude quota. Soft-dep: on `STATUS: unavailable` fall back to rung 3 EXPLICITLY — unavailable is never "verified".
- WHEN it's worth the rung (decorrelation on an OBJECTIVE claim rungs 1-3 don't settle — NOT "the other model is better", an unverified capability claim that decays): seed candidates `cross-lingua` (IT↔EN client deliverables — Gemini's different multilingual training is genuinely uncorrelated), `security-review` (shared "looks-safe" blind spots break across families), `spec-compliance` / numeric-algorithmic (the other family derives it independently). NOT for subjective/aesthetic (no ground truth → decorrelation is noise) nor anything a rung-1 assertion already covers.
- These 3 are a SEED, not doctrine: always pass `--type <slug>` so telemetry logs which types cross-family actually REFUTES. `fd-telemetry.py report` breaks hit-rate down per type — the list is confirmed or killed by data (same discipline as the per-type density table), never by asserted model rankings.
Gate depth on OBSERVED risk too, not only predicted: huge diff, many files touched, flaky tests escalate the rung even when the task was classified low-risk — never de-escalate below the axis-2 floor. A clean verification is paid insurance, not waste: the logged hit-rate (see Telemetry) calibrates depth per task type, it is NEVER a reason to skip verification where error cost is high.
## Escalation on repeated failure (rule of 3)
Diagnose the failure TYPE before retrying — blind model escalation is itself waste:
- infra (timeout, 403, rate/session limit) → retry/resume, same executor; escalation doesn't help
- capability (wrong/incomplete output again) → if output is objectively verifiable, first try best-of-3: three independent generations on the SAME executor, pick the best (pays when top costs ≫ 3× mid). Still failing → escalate model
- approach (same error, same strategy) → change strategy/diagnosis, not just the model
- tool/target (web nav misses element, form won't submit) → change tool or technique (e.g. static fetch → real browser, blind selector → wait-for-element → screenshot), not the model
Ladder: 1st failure → targeted fix, retry same executor. 2nd → change something STRUCTURAL (model ↑ or tool or approach, per type above). 3rd → stop the loop: top model takes it inline, or ask the user. Never an identical 4th automatic attempt.
No-progress termination (independent of retries and budget): if the last ~5 turns produced no new artifact, test result, or verifiable fact, stop and ask the user. Does not apply to user-requested analysis, where prose IS the artifact.
## Falsifiable pre-budget
Before executing any task that involves delegation or orchestration, the plan states one line: `approach / fallback / expected input tokens / expected output tokens`. Estimation anchors (don't guess from feel): expected input ≈ bytes of files/outputs to be read ÷ 4, times the number of passes — a FRESH-token budget: cache reads are excluded from enforcement accounting by design; expected output ≈ size of the DELIVERABLE only (schema × N items), reasoning excluded. Cache is never budgeted ex ante (noise that improves no decision) — analyzed ex post only.
Then IMMEDIATELY mirror the estimate machine-readably — a PreToolUse gate denies any Agent/Task/Workflow call with no open budget, so opening it is not optional (the same gate also denies NEW Workflow calls when the five-hour quota window is above ~90% — a fan-out that dies mid-flight at the session limit burns tokens with zero deliverable; resume via `resumeFromRunId` always passes):
`<plugin>/scripts/fd-telemetry.py budget-open --task "..." --expected-output N [--expected-input N] [--agents N] [--type slug] [--route inline|workflow|script|agent|external] [--reason "axis2>axis4"] [--alternative "..."] [--effort low|medium|high|xhigh|max] [--verify "cmd/checklist"] [--data-class public|internal|restricted] [--paths "glob,glob"]`
(`--agents` = declared fan-out: the CLI warns (never denies) when the estimate sits below the empirical per-agent anchor — ~20k output and ~17k cold-start input PER AGENT before any file is read (confirmed playbook rule: per-agent overhead dominates the deliverable ~25×). `--type` = task category slug — reuse existing ones, feeds the density table. `--route/--reason/--alternative` = decision record: which route, why, what was discarded — it feeds reversal analysis, costs one line. `--effort` = declared reasoning tier: real lever only through pinned agents `fd-executor`/`fd-verifier`; on mismatch the gate warns and logs `effort_mismatch`, never denies. A session-wide ceiling — `maxEffortLevel` in settings.json, Claude Code ≥ 2.1.267, top-level or per model under `modelSettings` — caps EVERY request, pinned agents included (measured 2026-09-09: cap `medium`, `fd-verifier` pinned `high` ran at `medium`, the meter logged `effort_ignored`): keep the cap at or above the verifier's tier, or rung 3 runs shallower than declared. `--verify` = the delegation contract's verifiable done as a command that can fail (`scripts/verify-lint.py` judges it): the gate denies a delegation whose budget has none, or only prose; a fake one — `true`, `echo`, `exit 0`, `… || true`, `…; exit 0`, a pipe ending in `tail`/`head`/`wc`, `grep -c` without a comparison, `git status`/`git diff` without `--quiet`, `--exit-zero` — is refused at budget-open. Fix it in place with `budget-amend --verify "cmd"`. `--type` also sets the type's reliability, measured on its last 20 closes (failed = flagged/abandoned/red verify; hard path = fail_streak or escalation in its session window, output >2× the estimate, ≥3 reopens): `fragile` → `budget-close --outcome ok` needs an `fd-verifier` run in the session (or `--no-verifier "reason"`, kept in the receipt) and the verify re-runs after every write; `reliable` → the verify re-runs at most every 15 min and the contract lint stays quiet. `--data-class restricted` = inputs must not leave the machine: external-exec/cross-verify refuse deterministically. `--paths` = the task's write perimeter, REQUIRED on the delegating routes (`agent`, `workflow`, `bg-session`; `--paths none` = explicit waiver), enforced on Write/Edit inside the project by a dedicated hook, which also denies on Bash the git subcommands listed in `deny_git` — out-of-perimeter writes are denied until `budget-amend --add-paths "..." --reason "..."` (explicit, logged; files outside the project — scratchpad, /tmp — are never constrained); user `never_write` patterns in `.fd-perimeter.json` are denied unconditionally.)
`budget-close` captures the actual in/out consumption from the Stop hook's state file and prints the path of a readable `.md` receipt (estimate, actual, verification result, duration) to hand on as it is: `report` then shows estimate calibration per type/route (median actual/expected) and the script-promotion queue (types recurring ≥2 on model routes) — read both before re-estimating similar tasks.
Calibrated estimates (measured, never automatic): with 5 or more closed tasks of the same `--type` in the last 90 days, `budget-open` prints `FD ✎ <type>: on N closed tasks the output ran F× the estimate — suggested --expected-output X instead of Y, not applied`, and keeps the suggestion in the budget and the receipt (`calibration`). The declared figure stays the one the 2×/3× check uses; adopt the factor by declaring the corrected figure next time, and say that you did. Within 0.9-1.1× the line says the estimates hold. Abandoned closes and closes with no measured consumption are excluded. The table per type: `fd-telemetry.py calibration [--days N] [--min-n N] [--type slug]` (also `/fable-director:calibration`).
This writes `~/.claude/fable-director/budgets/<cwd-slug>.json`. The plugin's Stop hook compares actual tokens (since declaration, from the main transcript PLUS the Workflow tool's agent files, which never surface in the main transcript) at every turn end: at ≥2× it warns ONCE (checkpoint: reassess the route now — a reversal at 2× is cheaper than a post-mortem at 3×); at ≥3× it BLOCKS closure and demands the post-mortem. Thresholds on consumed tokens only, never on self-estimated progress.
**Reservation (1.60):** the Stop hook only counts at turn end, so N agents launched in ONE message would all spend before any check fired. The gate therefore commits each delegation's share of the estimate the moment it is allowed — estimate ÷ `--agents` per agent (a Workflow commits its whole declared fan-out at launch, minus the agents already in its journal on a resume); without `--agents`, the empirical anchor (~20k out, ~17k in) per call, never above the estimate. Committed = settled actual + max(new actual, open reservations) + this call: at ≥2× one warning per round (`FD ⚠ reservation`), at ≥3× the call is DENIED (rule `reservation`) until the in-flight delegations settle — the Stop hook settles them against real usage at every turn end (event `reservation_settle`: reserved vs measured, a calibration figure), keeping only the entries of agents still in flight per the delegation meter. Declare the real fan-out with `--agents`: the reservation is exact then, a guess otherwise. **Reminder inside long turns:** every `FD_REMIND_GAP_S` seconds (default 600; `remind_gap_s` in cost-checkpoint.json; 0 disables) a PostToolUse hook on Bash/Write/Edit injects ONE line — `[fable-director] budget '<task>' open N min: output X of Y (r×), fresh input …; K delegations in flight reserving …; room before the 2× checkpoint …` — so the remaining budget is known mid-turn, not only at the 2× warning and the 3× block.
The estimate is a FALSIFICATION SIGNAL, never a selection constraint — the quality routes above take lexical priority (production code stays on the top model even if it busts the estimate; switching executor to honor a declared budget is Goodhart failure, forbidden).
At task end run `tools/session-cost-report.py` (this skill's dir; reads the budget file automatically, prints cache/delegation metrics and the 3× flags) or `budget.spent()` inside workflows, then close: `fd-telemetry.py budget-close --outcome ok|flagged|abandoned`.
- actual ≥ 3× estimate (either dimension) → the Stop hook already blocked closure and auto-logged the `budget_flag` event; you owe only the mini post-mortem (which assumption broke?) → playbook entry, then `budget-close --outcome flagged`.
- under 3× → no action. LLM estimates are noisy; don't post-mortem noise.
## Orchestration playbook (learning loop)
`~/.claude/delega-playbook.md` (external to the plugin so updates never overwrite it): capped registry of delegation heuristics, one line each, HARD CAP 30.
- Consult before planning batch/workflow/multi-agent orchestration. Not loaded for small inline tasks.
- Write an entry when: rule-of-3 ends at level 3 for approach/tool failure, or pre-budget busts ≥3×. Entry = root cause → heuristic, tagged `[candidata]`.
- `[candidata]` becomes a confirmed rule only on its 2nd independent occurrence — n=1 is overfitting, never generalize a single incident into a ban.
- `[seed]` entries are allowed: proven patterns imported deliberately (not incident-born), exempt from the double-confirmation rule but counted in the cap.
- Each entry carries counters `(uses:N ok:N ko:N)`: increment `uses` when you apply the heuristic, `ok`/`ko` by objective outcome. With small N the counters inform consolidation at cap time (drop the never-used, keep the proven); automatic ranking only when N justifies it — ordering by counters at N≤5 is noise.
- At cap: consolidate/merge/delete before appending (counters decide what dies first). Append-only growth forbidden.
## Script promotion
When model tokens were spent on deterministic work (parsing, extraction, transformation, reporting) and the task has recurred ≥2 times or recurrence is certain: the final step of the task is not closure — it is crystallizing the operation into a script in the target repo's `tools/` (in client repos propose the commit, don't auto-commit) plus one index line in the playbook. That task routes as "Script (zero cost)" from then on. Do NOT promote one-offs or unstable interfaces: script rot is real cost.
Prompt promotion — same logic, for instructions instead of operations: a delegation prompt repeated ≥3 times near-identically becomes a skill or a CLAUDE.md entry. Propose it; the user confirms.
## Telemetry (objective events only)
SQLite DB `~/.claude/fable-director/telemetry.db`; CLI `<plugin>/scripts/fd-telemetry.py`. The SessionEnd hook auto-logs a `session_summary` per session (zero model tokens: token totals, cache/delegation/coordination metrics, cache_resets, first-write turn, tool counts). This auto-path is the reliable data; the model-logged events below are opt-in and only worth the keystroke when you'll actually read the `report` later.
- `budget_flag` (the 3× bust) is logged AUTOMATICALLY by the Stop hook — deterministic, no model action. At the post-mortem you only diagnose the broken assumption + write the playbook entry + `budget-close`; you do NOT log the flag. Those flags come back at you: the SessionStart **hindsight** hook replays this cwd's past busts (task, ratio, real consumption; max 5 lines, silent where there's no history). When today's task resembles one of them, the past ACTUAL beats today's estimate — it is measured, not intuited.
- What a hook writes is recorded; what the model promises to write is not (measured over 161 sessions, 2026-09-14: hook-written events fired every time, model-logged ones between 0% and 9% of the occasions). If a signal matters, a hook writes it.
- Hook-written, no model action: `verification` `{found,kind:"rung1-command",rc}` by the Stop hook whenever it runs the `--verify` command · `escalation` `{class:"unclassified",binary,streak}` by the fail-streak hook the first time a streak reaches 3 (the rule-of-3 stop level); the CLASS is yours — re-log it once you have diagnosed the failure type · `script_promotion` is a question `budget-close` asks when the closed type recurs for the second time on a model route: answer it, and log the event only if you actually promote.
- Log AT EVENT TIME (never reconstructed), `fd-telemetry.py log <kind> --json '{...}'`, one line each, for what a hook cannot see: `retry` `{class,tokens_est}` at the retry · `reversal` `{from,to}` at any route change.
- NEVER log self-assessed quality scores — quality is derived only from objective indicators (tests, rollback, later fix). Visual work has no objective proxy: stays heuristic-routed forever.
- Every derived metric is an ALARM with a threshold, not a target — gaming coordination_cost or verification volume down is Goodhart reentry; cache-thrash is diagnostic, never blocking.
- `fd-telemetry.py report [--days N]` aggregates all of the above. Density is CODIFIED: data may override a routing rule only for task types marked DENSE (N≥10 closed tasks); elsewhere rules stay priors.
## Idempotency cache (opt-in)
Recurring deterministic transform → promote to a script instead (zero cost, first choice). Only when that's impossible (semi-deterministic transform on unchanged input — periodic import, SEO re-run): `cache-get KEY [--model M]` before delegating, on miss run + verify rung-1 + `cache-put KEY --file F --verified [--model M]` (unverified writes refused). `KEY = sha256(schema_version + prompt_template + input)`; the CLI then mixes plugin version and `--model` into the effective key — a plugin upgrade or executor change invalidates stale hits by construction. TTL 90d, cap 500.
## Session boundaries
At a verified boundary in a long session: `/fable-director:handoff` writes the resume note (decisions, verified facts, open items, run ids and paths, what to invoke next) to `~/.claude/fable-director/handoffs/<cwd>/<date>.md` (`--here` for the repo's `docs/`); the next session in that cwd is pointed at it at startup. Refused with an open budget. Persist reusable scripts to the repo, not /tmp.
## Never delegate
Interactive debugging, aesthetics/visual iteration, client-facing numbers/wording, decisions on how to count or report, production writes without prior backup.
Files in this skill
- SKILL.md
- tools/session-cost-report.py
- tools/skeleton.py
Attribution
Related skills
View all in ai-agents →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.