git:20260801.840fcb8 to git:20260828.bfc4c3c

279 added, 427 removed. Audit A to A.

---
name: prompt-engineering
- description: "Prompt design techniques for LLMs: structure, examples, reasoning patterns, and optimization. Invoke whenever task involves any interaction with AI instructions — crafting, debugging, improving, or evaluating prompts for skills, agents, output styles, or system configurations."
+ description: >-
+ Writing instruction text that models read: one-shot requests, persistent context such as system prompts and CLAUDE.md
+ and skills, tool and schema descriptions, and prompts written for other model instances. Invoke whenever task involves
+ any interaction with AI instructions — writing, debugging, auditing, or improving prompts, skills, agent definitions,
+ output styles, or system configurations.
---
# Prompt Engineering
- **Every prompt is an interface contract — clarity of intent determines quality of output.** Apply when crafting skills,
- agents, output styles, system prompts, or any AI instructions.
-
- ## Read first when
-
- - **You are writing a prompt for another model** (skill, subagent, system prompt, agent instruction, output style) →
- load [`${CLAUDE_SKILL_DIR}/references/agent-authored-prompts.md`] **BEFORE drafting**. Agent-authored prompts have
- distinct failure modes (over-specification, context leakage, ambiguous output contracts, silent degradation across
- pipeline stages) that the diagnostic table below does NOT cover. The summary in
- [Writing Prompts as an Agent](#writing-prompts-as-an-agent) is incomplete — the reference holds the workflow.
-
- ## What's Wrong With Your Prompt?
-
- - **Wrong format** — add explicit format + example. See [Output Format](#output-format)
- - **Missing information** — be more specific about what to include. See [Be Specific](#be-specific)
- - **Hallucination** — add context, request citations. See [Provide Context](#provide-context)
- - **Ignores instructions** — place critical rules at top and end, use XML tags. See
- [Persistent Context](#prompting-in-persistent-context)
- - **Complex reasoning fails** — use extended thinking or CoT. See [Reasoning](#reasoning)
- - **Inconsistent results** — add 3-5 examples. See [Examples](#use-examples-few-shot)
- - **Too verbose** — specify word/sentence limits. See [Be Specific](#be-specific)
- - **Security concerns** — validate input, filter output. See [`${CLAUDE_SKILL_DIR}/references/security.md`]
-
- ## References
-
- - **Reasoning techniques** — [`${CLAUDE_SKILL_DIR}/references/reasoning-techniques.md`] CoT variants (zero-shot,
- few-shot, auto), Tree-of-Thoughts, Self-Consistency, adaptive thinking, reasoning models (GPT-5.x), CRANE constrained
- reasoning, academic citations
- - **Learning paradigms** — [`${CLAUDE_SKILL_DIR}/references/learning-paradigms.md`] ICL theory, zero/few-shot
- techniques, example selection research, generated knowledge prompting, active prompting
- - **Workflow patterns** — [`${CLAUDE_SKILL_DIR}/references/workflow-patterns.md`] Prompt chaining topologies, iterative
- refinement, meta prompting, APE, automated optimization survey
- - **Prompt security** — [`${CLAUDE_SKILL_DIR}/references/security.md`] OWASP Top 10 for LLM 2025, injection defense,
- agentic pipeline security, threat modeling, defense patterns
- - **Optimization strategies** — [`${CLAUDE_SKILL_DIR}/references/optimization-strategies.md`] Promptware engineering
- lifecycle, DSPy declarative optimization, RAG integration, manual iteration discipline
- - **Claude-specific** — [`${CLAUDE_SKILL_DIR}/references/claude-specific.md`] Adaptive thinking, effort parameter,
- prefill migration, mid-conversation system messages, prompt caching (automatic + explicit, 1-hour TTL), structured
- outputs, context windows, technique combinations
- - **Model behavior** — [`${CLAUDE_SKILL_DIR}/references/model-behavior.md`] Per-model behavioral prompting: the
- migration trap (over-prescriptive prompts overtrigger on newer models), cross-model shifts (literal instruction
- following, effort as primary lever, tool triggering), Claude Fable 5 / Opus 4.8 / Sonnet 5 steering patterns, GPT-5.x
- profile
- - **Long context** — [`${CLAUDE_SKILL_DIR}/references/long-context.md`] Document organization patterns, XML structuring
- for multi-doc, chunking strategies, context rot mitigation
- - **Agent & tool patterns** — [`${CLAUDE_SKILL_DIR}/references/agent-patterns.md`] ReAct, PAL, Reflexion, ART, ACE
- implementation patterns, failure modes, pattern selection
- - **Agent-authored prompts** — [`${CLAUDE_SKILL_DIR}/references/agent-authored-prompts.md`] Agents writing prompts:
- decomposition workflow, quality dimensions, failure modes, SPL pattern, pipeline rules
- - **Persistent context** — [`${CLAUDE_SKILL_DIR}/references/persistent-context.md`] Technique transfer to skills/system
- prompts, instruction degradation research, format sensitivity, declarative vs procedural, U-shaped attention,
- minimalism principle
- - **Structured data formats** — [`${CLAUDE_SKILL_DIR}/references/structured-data-formats.md`] Format benchmarks (KV vs
- table vs YAML vs JSON), TOON verdict, output format restrictions, CFPO, format selection rules
- - **Context engineering** — [`${CLAUDE_SKILL_DIR}/references/context-engineering.md`] The discipline beyond prompts:
- context types, quality principles, retrieval strategies, management patterns, layered architecture
-
- Read the relevant reference before proceeding.
-
- ---
-
- ## Core Techniques
-
- Start with the simplest technique that fits the problem. Most issues are solved by the first three.
-
- ### Be Clear and Direct
-
- **The golden rule:** show your prompt to a colleague with minimal context. If they're confused, Claude will be too.
-
- #### Provide Context
-
- Tell Claude:
-
- - What the task results will be used for
- - Who the audience is
- - What success looks like
-
- #### Be Specific
-
- - "Summarize this" → "Summarize in 3 bullets, each under 20 words"
- - "Make it better" → "Fix grammar errors, reduce word count by 30%"
- - "Analyze the data" → "Calculate YoY growth, identify top 3 trends"
-
- #### Output Format
-
- Always specify format explicitly. Show an example if structure matters:
-
- ```
- Extract the following as JSON:
- - Product name
- - Price (number only)
- - In stock (boolean)
-
- Example output:
- {"name": "Widget Pro", "price": 29.99, "in_stock": true}
- ```
-
- ### Use Examples (Few-Shot)
-
- 3-5 examples typically sufficient. Cover edge cases. Format consistency and input distribution matter more than perfect
- label accuracy. Performance plateaus after 8-16 examples.
-
- **On current frontier models, examples constrain as much as they teach.** Worked examples anchor the model to the
- demonstrated paths and narrow its exploration space — use them to pin format and style, not to demonstrate behavior the
- model already handles. For tool and agentic behavior, prefer interface design over usage examples: expressive parameter
- names, enums, and constraints in the tool definition (a `status` enum of `pending | in_progress | completed` plus "keep
- exactly one item in_progress") define the behavior without spending example tokens.
-
- **Example selection rules:**
-
- - Cover diversity — represent different categories, edge cases, styles
- - Order simple to complex — build understanding progressively
- - Balance output classes — equal representation across categories
- - Put representative examples last — recency bias makes later examples more influential
- - Prioritize format consistency over perfect labeling
- - Wrap in `<examples>` tags for clear separation
- - In system context, examples at the start outperform those placed later (primacy bias)
-
- **Choosing the right paradigm:**
-
- - Simple, well-known task → zero-shot (just ask)
- - Need specific output format → one-shot (1 example)
- - Complex classification / nuanced judgment → few-shot (3-5 examples)
- - Domain-specific task → few-shot with domain examples
- - Highly nuanced + complex reasoning → few-shot + CoT
-
- Extended paradigm details and ICL theory: see [`${CLAUDE_SKILL_DIR}/references/learning-paradigms.md`].
-
- ### Use XML Tags
-
- Separate components for clarity and parseability:
-
- ```xml
- <instructions>
- Analyze the contract for risks.
- </instructions>
-
- <contract>
- {{CONTRACT_TEXT}}
- </contract>
-
- <output_format>
- List risks in <risks> tags, recommendations in <recommendations>.
- </output_format>
- ```
-
- - Use consistent tag names throughout the prompt
- - Reference tags in instructions: "Using the contract in `<contract>`..."
- - Nest for hierarchy: `<outer><inner>...</inner></outer>`
- - Critical for multi-component prompts — significantly improves instruction following
-
- ### Reasoning
-
- For complex reasoning, ask Claude to show its work:
-
- ```
- Think through this in <thinking> tags.
- Then provide your answer in <answer> tags.
- ```
-
- **Critical:** Claude must output its thinking. Without outputting the thought process, no thinking actually occurs.
-
- **Reasoning models (Claude adaptive thinking, OpenAI GPT-5.x):**
-
- - These models reason internally — do NOT add "think step by step" (it's redundant and may degrade quality)
- - Prefer general instructions ("think thoroughly") over prescriptive step-by-step plans
- - Use `<thinking>` tags in few-shot examples to demonstrate desired reasoning style
- - Ask for self-verification: "Before finishing, verify your answer against [criteria]"
- - Use the `effort` parameter to control reasoning depth, not prompt-level CoT
-
- **Standard models (no native reasoning):**
-
- - Use explicit CoT when the problem requires multi-step reasoning
- - Use extended thinking when the problem requires exploring multiple approaches
- - Use neither for simple factual tasks
-
- **CoT trade-off:** helpful for structural formatting and complex logic; harmful for tasks with many mechanical
- constraints (word limits, format rules).
-
- Detailed techniques, ToT, self-consistency: see [`${CLAUDE_SKILL_DIR}/references/reasoning-techniques.md`].
-
- ### Use Sequential Steps
-
- For multi-step tasks, number the steps:
-
- ```
- 1. Replace customer names with "CUSTOMER_[ID]"
- 2. Replace emails with "EMAIL_[ID]@example.com"
- 3. Redact phone numbers as "PHONE_[ID]"
- 4. Leave product names intact
- 5. Output only processed messages, separated by "---"
- ```
-
- Cap at ~10-15 steps per sequence; beyond that, decompose into sub-procedures (Hierarchical Task Networks).
-
- ---
-
- ## Structured Data in Prompts
-
- Format choice measurably affects LLM accuracy — up to 16pp between best and worst formats on identical content.
-
- - **Key-value lists** for lookup/routing data where entries are independent — +8.8pp accuracy over tables
- - **Markdown tables** only for genuinely 2D comparisons where cross-criteria scanning IS the point
- - **YAML** for deeply nested data (configs, hierarchies) — best accuracy for nested structures
- - **Avoid CSV, JSONL, XML for input data** — consistently underperform alternatives
-
- **Test:** if removing a column would lose comparative meaning → table. Otherwise → KV list.
-
- **Output format restrictions degrade reasoning.** Use structured output only when downstream consumers require it;
- prefer post-processing free-form output for reasoning-heavy tasks.
-
- Full benchmarks and selection rules: see [`${CLAUDE_SKILL_DIR}/references/structured-data-formats.md`].
-
- ---
-
- ## Choosing a Technique
-
- - Simple task, clear format → zero-shot with clear instructions
- - Consistent output format → few-shot (3-5 examples)
- - Complex reasoning → CoT (standard models) or extended thinking (reasoning models)
- - Very complex / exploratory → extended thinking with high effort
- - Multi-step workflow → prompt chaining. See [`${CLAUDE_SKILL_DIR}/references/workflow-patterns.md`]
- - External information needed → ReAct. See [`${CLAUDE_SKILL_DIR}/references/agent-patterns.md`]
- - Precise calculation → PAL (generate code). See [`${CLAUDE_SKILL_DIR}/references/agent-patterns.md`]
- - Multi-attempt allowed → Reflexion. See [`${CLAUDE_SKILL_DIR}/references/agent-patterns.md`]
-
- ---
-
- ## Worked Example: Diagnosing and Fixing a Prompt
-
- <example>
- **Original prompt:**
- ```
- You are a helpful assistant. Analyze this code and give me feedback.
- Make sure to be thorough. Also format it nicely.
- ```
-
- **Diagnosis:**
-
- - Wrong format → no explicit format specified
- - Missing information → "feedback" and "thorough" are vague
- - Ignores instructions → "format it nicely" is ambiguous
-
- **Fixed prompt:**
-
- ```xml
- <instructions>
- Review the provided code for three categories of issues:
- 1. Bugs — logic errors, off-by-one, null handling
- 2. Security — injection, auth bypass, data exposure
- 3. Performance — unnecessary allocations, O(n^2) loops
- </instructions>
-
- <output_format>
- For each issue found, return:
- - **Location:** file:line
- - **Category:** Bug | Security | Performance
- - **Severity:** Critical | Major | Minor
- - **Fix:** concrete code change (not just description)
-
- If no issues found in a category, state "None found."
- </output_format>
-
- <code>
- {{CODE}}
- </code>
- ```
-
- **What changed:** vague task → specific categories. No format → explicit structure. Persona removed (adds no value).
- Single paragraph → XML-separated components.
-
- </example>
-
- ---
-
- ## Prompting in Persistent Context
-
- Techniques behave differently in persistent context (skills, system prompts, CLAUDE.md) vs. one-shot user messages.
-
- - **Place critical rules at top and end of context.** The U-shaped attention curve makes the middle the worst location.
- - **Prefer declarative bullets over numbered procedures** — except when ordering matters; cap sequences at ~10-15 steps.
- - **Prime the domain, don't assign a persona.** "This is a security review task" beats "You are an expert auditor."
- - **Format swings compliance up to 40%.** XML tags and Markdown headers beat prose; JSON/YAML are for data, not
- instructions.
- - **Every instruction must earn its place.** Apply the deletion test: if removing it doesn't change output, remove it.
-
- Full research synthesis: see [`${CLAUDE_SKILL_DIR}/references/persistent-context.md`].
+ **A model that reasons natively does not need to be taught how to think. It needs to be told what done looks like, and
+ left alone.** Instruction text that explains, encourages, or supervises costs more than it buys — the model already does
+ those things, and your text competes with its own judgment.
- ---
+ Prompt text lives on four surfaces, and the same words behave differently on each. A rule that helps in a request can
+ tax every turn for months as persistent context. Identify the surface before writing.
- ## Claude-Specific Rules
+ ## On encountering a defective prompt
- ### Adaptive Thinking and Effort
+ Do not read past it. Prompt text that violates these rules is found far more often than it is written — in a skill, a
+ tool description, a standing instruction file, a subagent brief.
- Current Claude models (Opus 4.7+, Sonnet 5, Fable 5) use **adaptive thinking** — the only thinking mode; Claude
- dynamically determines when and how deeply to reason:
+ - **Already editing that file** — fix it, in the same change.
+ - **Not editing that file** — name the defect and the fix, once, in a sentence. Then continue the task you were asked to
+ do.
+ - **Flag what changes behavior**, not what offends taste. A stale fact, a contradiction between two rules, a filter that
+ suppresses recall, a rule the model already follows — these cost output. Wording preferences do not.
+ - **One flag, then proceed.** A task does not become a prompt audit because a prompt was involved. Raising the same
+ class of defect repeatedly in one session costs more attention than the defect does.
- ```json
- { "thinking": { "type": "adaptive" }, "output_config": { "effort": "high" } }
- ```
+ ## Not a prompt problem
- - **effort levels:** `low`, `medium`, `high` (default), `xhigh` (best for hard coding/agentic work), `max`
- - Effort affects all tokens: text, tool calls, and thinking; raise effort rather than prompting around shallow reasoning
- - Defaults when `thinking` is omitted: Fable 5 always thinks (omit the param; `disabled` returns 400); Sonnet 5 runs
- adaptive; Opus 4.7/4.8 run without thinking
- - `budget_tokens` returns 400 on current models — use effort + adaptive thinking
- - Thinking display defaults to `omitted` — set `display: "summarized"` if reasoning is surfaced to users
+ Write nothing for these. Each has a fix that prompt text cannot reach, and reaching for words instead is the most common
+ wasted motion in this skill's domain.
- ### Prefilling (removed)
+ - **Reasoning is too shallow or too deep** → the effort setting, not the wording
+ - **Context degrades across a multi-turn run** → compaction and reasoning persistence. This is not the same as a single
+ prompt carrying large documents, which is prompt text — see [Long context](#long-context)
+ - **A prohibition must actually hold** → permissions, schemas, sandboxes. Prose steers; it does not enforce
+ - **The rule is deterministic and machine-checkable** → compile it into code and have the model call it
+ - **Deterministic filtering or aggregation over tool output** → run it as code outside the context window
- Prefilling a partial `assistant` message returns a 400 on Claude 4.6+ and Fable 5 (legacy models only). Migrate:
+ The scale matters. A wrong setting can cost more than every prompt decision on the page combined, and no amount of craft
+ in the wording recovers it. Check the setting first; it is faster to rule out than to write around.
- - Forcing JSON/schema → structured outputs (`output_config.format`)
- - Skipping preamble → system instruction: "Respond directly without preamble"
- - Continuing an interrupted response → quote the last text in the user turn and ask to continue
+ ## Routing by symptom
- ### Prompt Caching
+ - **Output shape, tone, or format is wrong** → [request](#1-the-request)
+ - **A standing rule is ignored despite being stated** → [persistent context](#2-persistent-context). The file is too
+ long and the rule is lost. Delete others rather than restating this one louder
+ - **A tool is used wrongly, or not at all** → [tool and schema text](#3-tool-and-schema-text)
+ - **A subagent returns work that misses context you never gave it** → [delegated prompts](#4-delegated-prompts)
+ - **The model obeyed exactly and the result got worse** → [literalism](#instructions-are-followed-exactly)
+ - **Output is consistently the wrong shape and the prompt has examples** → the examples are specifying it. See
+ [Examples are read literally too](#examples-are-read-literally-too)
+ - **Answers degrade as the prompt grows, or cite the wrong part of a document** → [long context](#long-context)
+ - **The instruction was true when written and is false now** → [timelessness](#timelessness)
- Cache stable context to cut latency and cost. Two modes: automatic (top-level `cache_control`) and explicit (block-level
- breakpoints). Key rules:
+ ## The four surfaces
- - Up to 4 breakpoints per request; 5-minute TTL (default) or 1-hour TTL
- - Cache read: 0.1x input price. Cache write: 1.25x (5-min) or 2x (1-hour)
- - Place breakpoint on the last block that stays identical across requests
- - Cache invalidation hierarchy: tools → system → messages
+ ### 1. The request
- ### Structured Outputs
+ The one-shot ask. Read once, acted on once. This is the surface where explicit structure pays: clear sectioning,
+ examples, tags when a prompt mixes instructions with data, and a stated output contract.
- Constrained decoding guaranteeing schema-compliant JSON. Use `output_config.format` for response format or
- `strict: true` on tool definitions. Incompatible with citations and prefilling. Grammar applies only to final text
- output — thinking is unconstrained.
+ - **Specify the output contract.** Format, length, constraints, and what "done" means. This is the one thing the model
+ cannot infer, and the one thing worth spending words on.
+ - **Give the reason, not only the rule.** "Never use ellipses" underperforms "this is read aloud by a speech engine,
+ which cannot pronounce them." Stated motivation generalizes to cases you did not enumerate; a bare rule does not.
+ - **Examples pin shape, never reasoning path.** Three to five, wrapped in tags, when the target is a format, a tone, or
+ a genuinely ambiguous label the model cannot infer from a description. An example demonstrating _how to approach_ a
+ problem is read as the approach to take — see [Examples are read literally too](#examples-are-read-literally-too),
+ which is the mechanism behind every rule in this bullet.
+ - **The cost of an example scales with how often it is read.** In a one-shot request an unhelpful example wastes tokens
+ once. In persistent context it constrains every future run, silently, in a direction nobody re-examines. This skill
+ therefore carries no worked prompt: a "here is a bad prompt, here is the fix" walkthrough would teach the shape of
+ that one fix to every prompt written afterward.
+ - **Ask for uncertainty explicitly.** Permission to say "I don't know" has to be granted or the model fills the gap.
+ - **Say what you want, not what you fear.** Positive examples of the target style outperform prohibitions against the
+ wrong one.
- ### Model-Specific Behavior
+ ### 2. Persistent context
- Behavioral defaults (verbosity, tool eagerness, subagent use, design taste) shift per model release — techniques
- transfer, defaults don't. When tuning for a specific model, first remove prior-model scaffolding (it overtriggers on
- newer models), then check the model's own prompting guide. Per-model profiles and steering patterns: see
- [`${CLAUDE_SKILL_DIR}/references/model-behavior.md`].
+ System prompts, CLAUDE.md, skills, memory files. Read on every request, forever.
- Full API details and technique combinations: see [`${CLAUDE_SKILL_DIR}/references/claude-specific.md`].
+ **A request that is slightly wrong costs one bad response. A standing rule that is slightly wrong costs a small tax on
+ every request for months — and because it is always present, you stop seeing it.**
- ---
+ - **Admit a rule only if changing it would change intended behavior.** Everything else belongs in runtime injection or
+ retrieval.
+ - **Never restate what the agent can discover.** Repository overviews measurably fail: context files did not improve
+ task success while adding over 20% inference cost. The mechanism is not that agents ignore them — it is that agents
+ follow them _too_ diligently, treating the extra content as additional constraints to satisfy.
+ - **Prefer prohibitions with real thresholds over style prescriptions.** Prohibitions with a stated boundary hold;
+ prescriptions about how to do the work compete with the judgment the model applies to the case in front of it.
+ - **Four categories earn their place** — operator opinions the model cannot infer, project facts that surprise, routing
+ rules with stated thresholds, named integrations. Persona framing, restated general knowledge, emphasis scaffolding
+ (`CRITICAL`, all-caps, emoji markers), and redundant verification demands do not.
+ - **Prime the domain instead of assigning a persona.** Audience, register, length, and structure give the model a
+ target. A persona gives it a vibe, and vibes drift.
+ - **Add back one rule at a time, only after repeated failure on the same specific issue.** Never speculatively — the
+ model reads every line on every turn.
+ - **Deleting is not automatically safe.** Cutting a standing rule is the default move, but confirm the behavior it
+ prevented does not return. A rule that earns its place survives this check; most do not.
- ## Context Engineering
+ Why standing rules behave this way — U-shaped attention, instruction drift, constraint overload, and the
+ declarative-over-procedural split: [`${CLAUDE_SKILL_DIR}/references/persistent-context.md`].
- Context engineering is the 2026 evolution beyond prompt engineering — designing dynamic systems that provide the right
- information and tools, in the right format, at the right time.
+ ### 3. Tool and schema text
- **Key distinction:** prompt engineering crafts a single text string; context engineering manages all inputs to the model
- — system prompts, conversation history, retrieved documents, tool results, memory.
+ Parameter names, enums, constraints, and tool descriptions. This is prompt text: the model reads it to decide what a
+ tool is for and how to call it.
- **Core principles:**
+ - **Encode behavior in the interface rather than in usage examples.** A `status` enum of
+ `pending | in_progress | completed` plus one constraint sentence in the description teaches more reliably than worked
+ examples — and does not narrow the model's exploration space the way examples do.
+ - **Put tool instructions in the tool description, not the system prompt.** Duplicating them across both is where
+ conflicting guidance comes from, and a model burns reasoning deciding which instruction wins before doing the work.
+ - **Name parameters so the name carries the constraint.** Expressive names and enums do work that prose cannot, because
+ they are present at the moment of the call.
+ - **State the trigger in the description.** "Call this when the user asks about current prices" belongs on the tool, not
+ in a system-prompt paragraph the model reads a thousand tokens earlier.
- - Most agent failures are context failures, not model failures
- - Find the smallest set of high-signal tokens that maximizes the desired outcome
- - Treat context as a finite resource with diminishing marginal returns
- - Organize context into explicit labeled sections for model parseability
+ ### 4. Delegated prompts
- **Management patterns:**
+ Text you write for another model instance — a subagent, a pipeline stage, a generated skill.
- - **Compaction** — summarize nearing-limit context; preserve decisions and open questions, discard raw tool outputs
- - **Structured note-taking** — agent writes selective notes to persistent storage for state continuity
- - **Multi-agent isolation** — sub-agents handle deep dives in clean contexts; return condensed summaries
- - **Just-in-time retrieval** — load identifiers upfront, fetch full content on demand via tools
+ - **The receiving agent has none of your context.** Every delegated prompt must be self-contained; orchestrator state
+ that leaks in as an unexplained reference is the dominant failure mode.
+ - **Define the contract before the prose** — inputs, outputs, and how the receiver knows it succeeded.
+ - **Include a concrete output example**, not a description of one.
+ - **Sanitize anything user-supplied** before it enters a generated prompt.
- Full depth: see [`${CLAUDE_SKILL_DIR}/references/context-engineering.md`].
+ Contract-first workflow, failure modes, trust boundaries for untrusted content, verifier delegation, and the
+ self-containment check: [`${CLAUDE_SKILL_DIR}/references/delegated-prompts.md`]. This covers the text; whether to
+ delegate at all, and how to scope the isolation, is a separate decision.
- ---
+ ## The instruction budget
- ## Long Context Rules
+ A context holds roughly 100 to 150 instructions before adherence degrades measurably. Past that, the model does not
+ report strain — it drops or partially applies clauses, and which ones it drops is not predictable. The number is
+ calibrated against one model generation and moves with capability; the shape of the curve does not.
- When working with 20K+ token documents:
+ - **The budget is shared, not per-file.** System prompt, every active skill, every instruction file, and every tool
+ description draw on the same allowance. A 30-line addition to a context already holding 120 instructions is not a
+ 30-line decision.
+ - **The ceiling is not a target.** Fewer is strictly better at every point below it. There is no threshold under which
+ additional instructions become free.
+ - **Count before adding, not after.** The cost of an instruction is paid on every turn; the benefit only on turns where
+ it applies. A rule that matters one time in twenty is a bad trade at any length.
+ - **Over budget: delete, do not compress.** A rule shortened from three lines to one still occupies a slot. Compression
+ saves tokens and saves no attention. Only removal returns budget.
+ - **Load conditionally what applies conditionally.** Rules needed in one phase belong in a file read at that phase. A
+ rule present on every turn should be one that matters on most of them.
- - **Documents at the top, query at the bottom** — exploits the U-shaped attention curve
- - **Wrap each document in XML tags** with identifying metadata (source, type, date)
- - **Ground responses in quotes** — ask Claude to quote relevant passages before answering
- - **Remove noise** before including documents — strip boilerplate, headers, navigation
- - **Place instructions at the end** after all documents
+ ## Long context
- Document organization, chunking strategies: see [`${CLAUDE_SKILL_DIR}/references/long-context.md`].
+ Arranging large inputs inside a prompt is prompt text, not configuration. The rules below apply to a single request
+ carrying documents and to an agent whose standing context has grown — both are the same problem.
- ---
+ **Volume itself carries a cost that relevance does not offset.** One controlled run put the passing rate at 8/10 with
+ ~11k characters of context and 3/10 with ~299k, and the drop was the same whether the added material was relevant or
+ irrelevant. One run is a direction, not a constant — and the direction is that selection beats relevance, so adding
+ context to fix a wrong answer is the wrong reflex.
- ## Prompt Chaining Rules
+ - **Documents at the top, the question at the bottom.** Attention is U-shaped: the middle is where content goes to be
+ forgotten. Put the instruction after the material it operates on, not before.
+ - **Label every document with identifying metadata** — source, type, date, id — in a wrapper tag. Unlabeled documents
+ cannot be cited, and a model that cannot cite will paraphrase from the wrong one without signalling.
+ - **Ask for quotes before answers.** Requiring the model to quote the passages it relies on, before it reasons over
+ them, grounds the answer and makes a wrong retrieval visible in the output instead of invisible inside it.
+ - **Strip noise before including.** Boilerplate, navigation, headers, and changelog cruft consume the same budget as
+ signal and degrade the same way.
+ - **Do not rebuild state from raw history every turn.** Maintain the authoritative state as its own object and pass
+ that. Re-deriving it from an accumulating transcript is how a long-running agent drifts.
+ - **Cut before you add.** When an answer is wrong at high volume, the reflex to add clarifying context is backwards; the
+ first move is removing material that is present but not load-bearing.
- When a single prompt produces error propagation, decompose into a chain of simpler prompts:
+ Document templates, chunking strategies, quote-grounding patterns, and the point where this stops being a prompt
+ problem: [`${CLAUDE_SKILL_DIR}/references/long-context.md`].
- - **Single responsibility** — each prompt does one thing well
- - **Clear interfaces** — define what each step receives and produces
- - **Validation points** — check output before passing to next step
- - **Chain when there's a natural validation boundary** — avoid over-chaining
+ ## Wording
- Chain topologies, meta prompting, APE: see [`${CLAUDE_SKILL_DIR}/references/workflow-patterns.md`].
+ A rule is read by a system that resolves ambiguity silently — and read again months later, when what it describes has
+ moved. A sentence fails in two directions: misread now, or read exactly right and no longer true. Neither failure
+ reports itself, and both are decided at the level of the sentence.
- ---
+ - **One term per concept, every time.** Synonyms read as distinctions. A "rule" that becomes a "directive" three lines
+ later may be treated as a second thing with separate scope.
+ - **Imperative for instructions.** "Return the parsed result." Not "you should return" or "the result should be
+ returned."
+ - **One instruction per sentence.** A sentence carrying two requirements reliably gets one of them applied.
+ - **Active voice with a named actor.** "The verifier reports findings" leaves no question about who acts. "Findings are
+ reported" leaves it open, and the model will pick.
+ - **Short sentences.** A long sentence buries its operative clause in the middle, where attention is weakest — the same
+ curve that governs a whole file governs a sentence.
+ - **No noun stacks.** Three nouns in a row is the ceiling. "Prompt quality review process checklist" parses as many
+ things and specifies none.
+ - **Every pronoun resolves to exactly one antecedent.** "It", "this", and "that" are where silent misreadings enter. If
+ two candidates exist, name the thing.
- ## When Prompting Isn't Enough
+ ### Rules about rules
- Start with prompt engineering. If quality plateaus, consider:
+ - **A rule must be checkable.** If you cannot tell from the output whether it was followed, it is a sentiment. "Write
+ clearly" cannot be checked. "One instruction per sentence" can.
+ - **State the boundary, not the sentiment.** Bounded beats unbounded regardless of polarity: "do not refactor unrelated
+ code" and "keep responses under 200 words" both work. "Follow good style" and "avoid verbosity" do not.
+ - **Delete hedges.** "Generally", "typically", "where possible", "as appropriate", and "try to" convert a rule into a
+ preference the model may weigh away against something else. If the rule has real exceptions, name them. If it does
+ not, state it flat.
+ - **The reason earns its place only when it generalizes.** In a one-shot request, motivation extends the rule to cases
+ you did not enumerate. In persistent context, a reason that explains only the stated case is read on every turn and
+ changes nothing.
+ - **Terse is not compressed.** Cut words that do not change meaning. A rule shortened past the point where its scope is
+ clear costs more than the tokens it saved.
- - **RAG** — need current/accurate external data the model doesn't have
- - **DSPy** — metric-driven automatic prompt optimization for complex pipelines with labeled eval data
- - **Fine-tuning** — need deep domain expertise prompting can't achieve
+ ### Timelessness
- These compose — combine as needed. Treat prompts as software: version them, test them, monitor them in production.
+ Persistent instructions are read later by a reader that cannot discount them. A human meeting "not currently supported"
+ in an old document notices its age and downgrades the claim; a model reads a present-tense assertion from a
+ system-authority source and complies. **A stale instruction is not ignored — it is obeyed**, and nothing errors.
- Strategy comparison, DSPy details, production quality gates: see
- [`${CLAUDE_SKILL_DIR}/references/optimization-strategies.md`].
+ - **The runtime owns `now`; the text owns invariants.** Never assert a date, a live version, or a model roster in
+ persistent context. The harness already injects the real current date, and your text competes with a channel that is
+ always more current than it is.
+ - **Rolling referents are banned** — `currently`, `now`, `latest`, `newer`, `no longer`, `soon`, `still`,
+ `does not yet`, `as of this writing`. Each names a moving target.
+ - **A rolling word is admissible only with a fixed anchor beside it** — a version range or a date. "Removed in current
+ versions" rots; "removed in 3.0 and later" does not.
+ - **Domain time is preserved verbatim.** Durations, expiry, retry backoff, ordering, and migrations are part of what the
+ subject does. The naive reading of this rule — delete temporal words — destroys meaning. The test is whether the
+ referent moves with the reader, not whether the word looks temporal.
+ - **A plan is never written as a fact.** "Planned for Q4" stays modal. Canonicalizing it into "the product supports X"
+ makes the prose cleaner and the claim false.
+ - **Time-stamped genres are exempt** — changelogs, release notes, migration guides, decision records, and evidence logs
+ are dated by design. Keep them out of persistent context rather than de-tensing them.
+ - **Timeless is not immutable.** Hard invariants outlive model generations; soft defaults are calibrated against one and
+ need re-examining when it moves. A file nobody revisits is not timeless, it is abandoned.
- ---
+ **This buys durability, not compliance.** Tense has no measured effect on instruction-following. Write timeless to keep
+ the artifact true, not to make the model obey harder.
- ## Security Rules
+ Deictic-vs-domain table, both-direction failure modes, and the evidence:
+ [`${CLAUDE_SKILL_DIR}/references/timelessness.md`].
- When a prompt handles **untrusted input** (user-provided content, web scraping, external documents):
+ ## Formatting
- - **Mark trust boundaries** — separate trusted instructions from untrusted data with delimiters
- - **Harden the system prompt** — explicit boundaries, sandwich defense (repeat critical instructions after user content)
- - **Validate input** — flag instruction-override patterns, unusual length, encoding attempts
- - **Filter output** — block responses containing sensitive data patterns
- - **Apply least privilege** — give the LLM access only to data and tools it needs
- - **Require human approval** for sensitive or destructive actions
+ Sentence-level precision is not enough alone — the shape of the surrounding text decides whether the model reads a rule
+ as one thing or several.
- **Prompt injection cannot be fully prevented** — defense is about reducing attack surface, limiting blast radius, and
- detecting incidents.
+ ### Choosing a data shape
- OWASP Top 10, attack taxonomy, defense patterns: see [`${CLAUDE_SKILL_DIR}/references/security.md`].
+ - **Independent entries → key-value list.** Route tables, tool inventories, configuration mappings, permission modes.
+ Each entry stands alone and nothing is gained by scanning across.
+ - **Genuine comparison → table.** Only where cross-criteria scanning is the point. **The test**: remove a column. If
+ comparative meaning is lost it is a table; if the rows still stand alone it was a list wearing table formatting.
+ - **Nested structure → YAML.** Configurations and hierarchies beyond two levels. More accurate than JSON or XML at
+ depth, and cheaper.
+ - **Ordered procedure → numbered list.** Only where sequence changes the outcome.
+ - **Everything else → bullets.** If items reorder without changing meaning, they are bullets.
- ---
+ Misusing a table for independent entries is the most common formatting defect and the cheapest to fix. Selection depth,
+ and why a rigid output schema costs reasoning quality: [`${CLAUDE_SKILL_DIR}/references/structured-data-formats.md`].
- ## Writing Prompts as an Agent
+ ### Marking regions with tags
- **STOP — load [`${CLAUDE_SKILL_DIR}/references/agent-authored-prompts.md`] before drafting.** The summary below is
- orientation only; the reference holds the decomposition workflow, failure-mode taxonomy, and pipeline rules required to
- write a non-broken agent prompt.
+ Tags separate parts of a prompt a reader could otherwise run together — instructions, supplied data, examples, and the
+ output specification.
- When you (the AI) are authoring a prompt for another model to execute — skills, system prompts, subagent instructions:
+ - **Tag where the prompt has parts that could be confused.** A single-purpose prompt gains nothing from tags and pays
+ for them in noise.
+ - **One tag name per concept, reused exactly.** The same discipline as terminology: a region called `<context>` in one
+ place and `<background>` in another reads as two regions.
+ - **Reference the tag from the instruction.** "Using the constraints in `<constraints>`" creates a link the model can
+ follow. An unreferenced tag is decoration.
+ - **Nest for real hierarchy only.** Documents inside `<documents>`, each in its own `<document>`. Nesting that mirrors
+ no actual structure adds depth without meaning.
+ - **Tags mark, they do not enforce.** A region labelled as data is still read, and labelling it does not stop
+ instructions inside it from being followed. Where that matters, the boundary belongs in permissions or schema.
- - Treat prompts as programs — define signature (inputs, outputs, success criteria) before writing text
- - Decompose into components, scaffold with XML, then draft
- - Every generated prompt must be self-contained — the receiving agent has zero knowledge of your context
- - Include explicit output format with a concrete example, not just a description
- - Embed validation criteria the receiving agent can self-check against
- - Sanitize all user-supplied content before incorporating into generated prompts
+ ## Instructions compound with defaults
- **Key failure modes:** blob-prompts (unstructured paragraphs), context leakage (embedding orchestrator state), ambiguous
- output contracts, instruction drift across iterative rewrites.
+ An instruction does not replace the model's default behavior. It adds to it. Where the two push the same direction, the
+ result overshoots — and the overshoot is invisible, because the output looks like compliance.
- ---
+ - **Delete verification instructions.** "Include a final verification step", "double-check your answer", "use a subagent
+ to verify" stack on top of checking the model already does. Removing them costs nothing in quality.
+ - **Delete thoroughness nudges, forced progress scaffolding, and `if in doubt, use X`.** A model that reaches for a tool
+ appropriately does not need telling; the nudge makes it reach when it should not.
+ - **The same trap runs the other way.** "Be concise" added to a model that is already terse produces answers too short
+ to be useful. Whichever direction the default already points, a redundant instruction pushes past the useful amount.
+ - **Check the target model before generalizing.** Guidance for one model can say strip self-verification while guidance
+ for another recommends explicit interval checks with fresh-context verifier subagents on long-horizon runs. Both hold;
+ the split is by task horizon.
- ## Quality Checklist
+ Whether a named technique is worth reaching for at all — CoT, few-shot, self-consistency, Tree-of-Thoughts, ReAct, PAL,
+ Reflexion, personas, chaining, meta-prompting, APE, DSPy, XML tags, prefilling:
+ [`${CLAUDE_SKILL_DIR}/references/superseded-techniques.md`].
- Before finalizing a prompt:
+ ## Instructions are followed exactly
- - [ ] Task is clear (single action verb + objective)
- - [ ] Output format is explicit (with example if structure matters)
- - [ ] Constraints are specific (not "appropriately" or "as needed")
- - [ ] Examples cover normal and edge cases (if using few-shot)
- - [ ] Golden rule passed (colleague wouldn't be confused)
- - [ ] Long documents placed at top, query at bottom
- - [ ] XML tags separate distinct components
- - [ ] Critical rules in top 20% and/or bottom 20% (not buried in middle)
- - [ ] Security considered (if handling untrusted input)
- - [ ] Right technique chosen (zero-shot → few-shot → CoT → extended thinking)
+ An instruction is applied as written, to exactly the scope named, without the charitable interpretation a person would
+ supply. Reasonable-sounding instructions therefore produce unreasonable outcomes.
- **For persistent context (skills, system prompts, CLAUDE.md):**
+ - **Separate finding from filtering.** "Only report high-severity issues" is obeyed literally — the model finds the bugs
+ and then declines to report them. Ask for everything; filter downstream.
+ - **Every caution instruction is a threshold decision with a recall cost.** Stronger evidence-gating cut false answers
+ by 30.6pp on one model while raising unnecessary abstention by 9.7pp on the same benchmark.
+ - **State scope explicitly.** The model will not infer that a rule extends past the item you named.
- - [ ] Every instruction earns its place (deletion test: removing it changes output)
- - [ ] Declarative style for constraints; procedural only for ordered workflows
- - [ ] Domain priming over persona assignment
- - [ ] No blanket CoT — let reasoning models decide depth per request
- - [ ] KV lists for lookups; tables only for genuinely 2D comparisons
- - [ ] Few-shot examples calibrate format/style, not teach known patterns; tool behavior encoded in interface design
- (parameters, enums, tool descriptions), not usage examples
- - [ ] Prior-model scaffolding removed when targeting a newer model (old triggers overtrigger)
+ ### Examples are read literally too
- **When you authored the prompt as an agent (skill, subagent, system prompt, output style):**
+ An example is not an illustration of what you want. It is a specification, and the model complies with **every**
+ property of it — including the ones you never decided.
- - [ ] Loaded [`agent-authored-prompts.md`] BEFORE drafting — not after
- - [ ] Generated prompt is self-contained — no orchestrator context leakage
- - [ ] Output format example included (concrete, not just a description)
- - [ ] Validation criteria embedded for the receiving agent to self-check
- - [ ] User-supplied content sanitized before incorporation
- - [ ] Output contract (signature: inputs, outputs, success criteria) defined before text was written
+ - **Incidental properties become requirements.** If all your examples happen to have three bullets, you have specified
+ three bullets. Length, ordering, field presence, register, punctuation, and depth all transfer whether or not you
+ intended them. Nothing marks which parts were the point.
+ - **Vary what you do not want copied.** One example is a template; several that differ only in content are the same
+ template stated three times. If the acceptable output spans a range, the examples must span it — otherwise you have
+ demonstrated a point and asked for a space.
+ - **The last example weighs most.** Recency applies inside the example block. Put the most representative case last, not
+ the most interesting one.
+ - **This is why examples narrow exploration.** The model reads a demonstrated approach as the approach to take and stops
+ looking for a better one it would otherwise have found. Demonstrating _how to solve_ is the costly case; demonstrating
+ _what the answer looks like_ is the safe one.
+ - **When output is consistently the wrong shape and examples are present, the examples are the cause.** Adding an
+ instruction to correct it puts prose in conflict with a specification, and the specification wins.
- ## Related Skills
+ ## Quality checklist
- - `skill-engineering` — applies prompt techniques to SKILL.md design, description formulas, and content architecture
- - `subagent-engineering` — applies prompt techniques to subagent system prompts, tool scoping, and delegation triggers
- - `output-style-engineering` — applies prompt techniques to persona definition, tone examples, and behavioral rules
- - `claude-code-sdk` — reference for Claude Code extensibility APIs when building any AI artifact
+ - [ ] Confirmed this is a prompt problem — not effort, compaction, permissions, or code
+ - [ ] Surface identified before drafting; the rule is written for the surface it lands on
+ - [ ] Output contract explicit — format, length, and what "done" means
+ - [ ] Reasons given alongside rules, so they generalize
+ - [ ] No instruction pushing the same direction as a default the model already has
+ - [ ] Tool behavior in parameters, enums, and descriptions — not in prompt prose or usage examples
+ - [ ] Nothing restates what the agent can discover for itself
+ - [ ] Filtering separated from finding; no severity filter suppressing recall
+ - [ ] Delegated prompts self-contained, with a concrete output example
+ - [ ] Instruction count checked against what the context already holds, not against this file alone
+ - [ ] Key-value lists for independent entries; tables only where removing a column loses meaning
+ - [ ] Tags used only where parts could be confused, named consistently, referenced from the instruction
+ - [ ] Rules are imperative, one instruction per sentence, one term per concept
+ - [ ] No hedges — every rule states a boundary that can be checked from the output
+ - [ ] Defective prompt text encountered during the task was fixed or flagged once
+ - [ ] Every standing rule survives the deletion test and stays true over time
+ - [ ] No rolling referents; version-gated facts carry a fixed anchor