Instructions¶
Patterns for writing, structuring, and governing the instruction files and system prompts that shape agent behavior.
Instruction Files¶
Every major AI coding tool ships a project-level instruction file. These pages cover the conventions, ecosystems, and design patterns for authoring them.
- CLAUDE.md Convention — CLAUDE.md is Claude Code's project-level instruction file, read at session start to understand project conventions, tooling, and behavioral rules
- Project Instruction File Ecosystem — Every major AI coding tool invented a project-level instruction file independently; understanding how they relate helps teams avoid content drift and duplication
- Divergent Rules Across Coexisting Agent Instruction Files — In 386 sampled same-topic section pairs, 16.1% gave divergent guidance; consolidate first, then compare same-scope sections by topic, not heading
- AGENTS.md Design Patterns: Commands, Boundaries, and Personas — Four concrete patterns drawn from analysis of 2,500+ real repositories for writing effective AGENTS.md files
- AGENTS.md as Table of Contents, Not Encyclopedia — Keep AGENTS.md to ~100 lines as a pointer map; put structured knowledge in a versioned docs/ directory
- Encode Project Conventions in Distributed AGENTS.md Files — Capture team-specific patterns, style rules, and tooling requirements in AGENTS.md files throughout the codebase
- Evaluating AGENTS.md: When Context Files Hurt More Than Help — Auto-generated context files reduce task success rates; human-written files improve success only when they contain minimal, specific instructions
- Agent-File Instruction Coverage Does Not Determine Cost or Necessarily Improve Correctness — Across 310 generated variants, category count did not determine generation cost and did not necessarily improve correctness; cut what the agent can discover, keep what it cannot infer
- Probe-and-Refine Tuning of Repository Guidance for Coding Agents — Tune a repo-guidance file by probing the agent with synthetic bug-fix tasks and refining on the diagnosed failures; the artifact is model-specific, not transferable
- Verified Norm Packages for Repository Contribution Rules — Extract repository contribution rules once, verify each against repository evidence, and index them at the paths they govern; grade them on compliance
- Knowledge Gap or Skill Gap: Triage Before Writing Context — Classify agent near-misses before enlarging a context file; a two-agent ablation found near-misses trace to implementation skill, which context cannot supply
- Encoding Values in AGENTS.md: Why Prose Without Verification Fails — Corpus studies show ethics, fairness, and accessibility are largely absent from AGENTS.md; pair every value with a verification command or move it to a lower layer
- Public Rules-File Corpora as Evidence — Corpus studies of
.cursorrulesfiles measure who wrote them and when, so read the 4.2% security share as an authorship artifact rather than as advice - Audit Your Agent File Against Counted Census Figures, Not Coded Ones — A census of 22,854 repositories counted adoption and file history from the API but assigned its content shares with a model, so only the first kind of figure makes a target
- RAMP: Committed AI Configuration and the Quality Cost — A four-level maturity scale across 441 commercial repositories, where agent-first repos with no committed configuration take twice the cognitive-complexity hit
- Documentation Read Counts Measure Retrievability, Not Value — Behavioral traces put instruction files and agent working notes at 60.5% of documentation interactions, but the same corpus leaves the consult-to-edit link at 0.002
- Natural-Language Customization Bootstrap — Describe the customization in plain language; the agent drafts the instruction file, skill, subagent, or hook for you to review and commit
Instruction Design¶
How you phrase, frame, and structure individual rules determines whether agents follow them or quietly ignore them.
- Written Priority Rules for Coding-Agent Migrations — state when the target convention overrides existing handlers
- Instruction Polarity: Positive Rules Over Negative — Positive directives outperform negative instructions in agent compliance, especially as instruction count grows
- Guardrails Beat Guidance: Rule Design for Coding Agents — On SWE-bench, negative constraints are the only individually beneficial rule type; positive directives actively hurt — and rules work through context priming, not instruction specificity
- Code Precedence Over Stale Instruction Files — One sentence in the user-level instruction file, giving existing code precedence over documentation, moved convention choices from 4.2% code-matching to 91.4% across 320 runs
- Restraint Rules Need External Enforcement — Agents comply with rules that add work and never with rules that stop it; additive rules belong in the auto-loaded instruction file, restraint rules in CI or required review
- Name What an Agent May Edit Before It Starts Editing — Four per-task file lists (editable, inspect-only, required, protected) given before the first edit; strictly acceptable patches rose from 9 to 18 of 40 in a pilot, and a wrong list steers the agent wrong
- Enforce the Rules Your Code Cannot Show — In one evaluation, anchoring plus demanded proof lifted process-rule following from 0.35 to 0.87 and code-visible rules only from 0.59 to 0.75, so budget enforcement per rule
- Stop-and-Report Instructions Need a Resuming Loop — One prompt line telling a Codex-based agent to stop when unsure raised mean scores on two game benchmarks at 2-52% more token cost, and left a terminal-coding benchmark mixed
- Ordering Is the Weakest Process Constraint You Write — Agents satisfy the steps of a workflow and drop their required order; ordering held 46.7% on ANCHOR, the weakest of three relation types
- Do Not Price the Rules in Your Agent Instruction File — Naming a penalty beside a rule can lower compliance with it, because a stated price turns a prohibition into an affordable option
- Write Agent Rules You Can Grade From the Transcript — A deployed agent followed every prompt rule that could be scored from its output and none of the rules about manner; countability buys an observable failure, not compliance
- Security Knowledge Priming for Code Generation (SPARK) — A brief task-relevant CWE cue in the prompt activates the model's latent security knowledge — supplementary to mechanical scanners, not a replacement
- Negative Space Instructions: What NOT to Do — Exclusions and constraints eliminate entire classes of mistakes more efficiently than equivalent positive guidance
- Example-Driven vs Rule-Driven Instructions — Rules generalize; examples anchor — knowing when to use each determines whether agents interpret your intent or invent their own
- Personalized vs Generic Agent Skills: Where Effort Pays — Per-developer skill files distilled from interaction history matched a random colleague's file; the gain arrives only above roughly six task-relevant prior sessions
- Encoding Product-Design Taste into Agent Context — Encode product-design decisions as observable rules and mode-routed skill files; pair with design tokens and lint, never instead of them
- Publishing Agent Instructions Outside the Repo (design.md) — A file read beside the code it governs leans on that code for meaning; published at a URL it needs named primitives and observable decisions in place of the missing examples
- Iterative Binary Feedback for Pattern Adherence — Looping yes/no pattern judgments through capable models beats verbose critique for design-pattern adherence when the predicate space is small and the judge is deterministic
- Hints Over Code Samples in Agent Prompts — Reference existing code by path instead of embedding samples in prompts — hints stay current, cost fewer tokens, and eliminate maintenance drift
- Critical Instruction Repetition: Exploiting Primacy and Recency Bias — Repeating a critical instruction at both the start and end of a prompt exploits primacy and recency bias for higher compliance
- The Instruction Compliance Ceiling — Instruction compliance degrades as rule count grows; adding more rules past a threshold produces omission errors, not better behavior
- Constraint Degradation in AI Code Generation — LLM code generation accuracy drops sharply as simultaneous constraint count increases; reduce constraint load through decomposition, schemas, and mechanical enforcement
- Constraint Encoding Does Not Fix Constraint Compliance — Restructuring how constraints are formatted in prompts does not improve model compliance; the compliance lever is constraint design, not encoding form
- Policy Wording Tests for Coding-Agent Instruction Files
- Configuration File Structure Does Not Drive Compliance — A factorial study of file size, instruction position, file architecture, and contradictions found none of the four variables produced detectable compliance contrasts within realistic file sizes
- System Prompt Altitude: Specific Without Being Brittle — Effective prompts sit at the altitude that produces consistent behavior across variation, neither too brittle nor too vague
- Match Tool Instructions to the Agent Workflow — Better tools do not improve an agent unless the prompt encodes how the task's workflow gathers information; GitHub's Copilot code review regressed on a tool upgrade until the instructions were rewritten to match the review workflow
- Three Knowledge Tiers: Sourced, Unverified, Hallucinated — Classify agent knowledge into three tiers to preserve useful training knowledge while maintaining accuracy standards
- Cost-Aware Skill Rewriting: Preserve Operational Anchors, Not Skill Tokens — Rewriting a skill is an economic trade-off, not pure compression — stripping sparse operational anchors makes the agent explore and retry, raising total cost despite a shorter document
- Typed Pseudocode for Skill Libraries (Skill-as-Pseudocode) — Converting prose skill files to typed pseudocode pays only when the invocation template ships with the contract; the schema alone tested below the prose it replaced
- Codified Effort and Escalation Policy in the Instruction File — Write the default-cheap, escalate-on-evidence effort and model-routing rule into the instruction file so the cheap path is the default and survives context switches
- Advisory Prompts Distilled from Reasoning Traces — Distill the cases where thinking mode fixed an answer into standing procedural advice and run with reasoning off; the technique buys output tokens at a per-model accuracy price, not reasoning parity
Architecture & Composition¶
Structuring instructions across scopes, layers, and files so the right context reaches the right agent at the right time.
- OpenAI Model Spec Boundaries and Overridable Defaults — distinguish vendor policy boundaries from defaults your instructions can change
- Layered Instruction Scopes — Structure agent instructions in concentric layers — global defaults, project-level files, and directory overrides — so the most specific rule always wins
- Hierarchical CLAUDE.md — Layer CLAUDE.md files at multiple scopes so each agent session receives only the context relevant to its working location
- Size Limits on Instruction Files That Load on Demand — Claude Code injects only the start of a subdirectory CLAUDE.md or rules file that is over its per-file character limit, so the rest waits on a Read
- claudeMdExcludes: Selective Ancestor Instruction-File Exclusion — Skip irrelevant ancestor CLAUDE.md files in a monorepo with a glob list, so the agent's context is not burned on conventions for packages you never touch
- Per-Subagent Instruction Inheritance (omitClaudeMd) — Drop the user, project, and local CLAUDE.md layer for one subagent; managed policy files still load, unless the subagent itself is deployed through managed settings
- @import Composition Pattern for Instruction Files — Claude Code supports
@path/to/fileimports in CLAUDE.md, enabling modular instruction authoring; other tools rely on hierarchical discovery instead - Prompt File Libraries — Store reusable, parameterized prompt templates as version-controlled files that team members invoke on demand
- Production System Prompt Architecture — Structural patterns from a 102K-char production system prompt: XML-sectioned concern isolation, skills registries, and deferred tool loading
- Prompt Transpilation: Instructions as Build Artifacts — Compile modular skill files into one validated prompt at build time, with static dependency checks and a golden-file CI gate, so a broken instruction set fails the build not a run
- Capture the Assembled Request, Not the System Prompt — In the study's latest captured Claude Code request, tool definitions were 77.4% and the system prompt 13%, so record what the agent sent rather than inferring it
System Prompts¶
Designing, replacing, and dynamically augmenting the system-level instructions that define an agent's identity and capabilities.
- Domain-Specific System Prompts with Concrete Examples — Domain-specific system prompts with worked examples produce consistent, high-quality agent behavior in your specific context
- System Prompt Replacement for Domain-Specific Agent Personas — Replace the default coding-focused system prompt entirely to transform an agent into a domain specialist while preserving its tool ecosystem
- Event-Driven System Reminders — Inject targeted guidance at specific points during agent execution to combat instruction fade-out without bloating the static system prompt
- Repairing Agent Prompts from Trace Contrast, Not Search — Mine divergent runs of the same task for the semantic features that separate pass from fail, then inject those as prompt rules with no candidate ranking
Specifications & Standards¶
Leveraging existing artifacts — specs, schemas, standards files — as agent instructions rather than writing natural-language duplicates.
- The Specification as Prompt — Use types, schemas, tests, and API definitions as agent instructions instead of natural language descriptions
- Frozen Spec File — Write goals, non-goals, constraints, and completion criteria into an immutable file the agent reads but cannot modify, preventing drift across context compaction
- Feature List Files — Maintain a structured JSON file defining every feature with status and acceptance criteria; agents work through it sequentially
- Standards as Agent Instructions — A standards file actionable for humans is, verbatim, an instruction file for agents — the same document does both jobs when written precisely
- Encoding AI Writing Tells as a Prose Style Contract — Adopt a catalog of AI writing tells as a revision standard for all prose, enforce only the entries with a narrow false-positive surface, and write the carve-outs first
- Convention Over Configuration for Agent Workflows — Reduce agent errors by encoding decisions into naming conventions, directory structure, and label schemes so agents follow patterns rather than invent them
- WRAP Framework for Agent Instructions — A four-step checklist for writing agent-ready task descriptions that maximize autonomous execution quality
- Agent-Ready Bug Reports for Software Repair Agents — Rank bug report fields by measured effect on an AI repair agent's correct-fix rate; localization and suggested fixes beat human-style reproduction steps
- Multi-Layer Specification Redundancy as a Robustness Budget — Independent specification layers absorb prompt noise that would otherwise degrade code-generation correctness; prose repetition and brittle terminology do not
- Stage-Targeted Prompt Structure for Pull Request Outcomes — Specificity, Context, and Verification each move a different stage of the LLM-assisted PR pipeline — diagnose which stage is failing, then raise that dimension
- Ubiquitous Language for AI Plans — A maintained domain glossary plus ADRs anchors agent plans in existing code so plans, source, and prompt share one vocabulary
- Standard-Grounded NFR Specs: Quality Up, Correctness Flat — Grounding a non-functional requirement in a published quality model cuts static defect density and wording variance, but leaves correctness flat and hurts error handling
- Requirement Smells: No Category Signal, Density Unconfirmed — Pass rates fell in some model and application pairings as defective requirements accumulated, but no defect category did consistently more damage and no density correlation survived multiple-comparison correction
- Match Architecture Spec Format to Model Capability — Spec format barely moves a frontier model and decides what a weak one ships; pick the format from the tier you drive
- Constraint Preambles and the Gain Your Scanner Misses — A fixed block of output constraints cut named defect classes in all five models tested, and the two classes that moved most sit outside every scanner's rule set
- Specification Portability Across Coding Agents — Handing one agent's specification to another moves the generated code in both directions; measure the swap against a baseline instead of assuming the artifact is agent-neutral
- Diagram as the Shared Spec: One Artifact for the Picture and the Prompt — One diagram source serves the human's picture and the agent's spec, which removes the sync step; it does not raise output quality, and the rules still belong somewhere a checker can read
- Zero-Decision Plans and Rejected Alternatives in Agent-Readable Specs — A plan fails if its implementer must make any design choice; a feature spec fails if it shows one path with no rejected alternatives
- Stage Plans and Artifact Handoffs for Multi-Skill Tasks — Give an agent holding three or more skills stage objectives, and add named artifact handoffs at five or more; a bare use order helped one of three configurations
- Per-Step Preconditions and Postconditions in Skill Files — Give each skill step a precondition and a postcondition so a reviewer can compare declared intent against implementation; it finds silent mismatches and enforces nothing
Governance & Maintenance¶
Reviewing, versioning, and repairing instruction files over time so they remain effective as projects evolve.
- Enforcing Agent Behavior with Hooks — Move critical behavioral rules out of prompts and into deterministic shell hooks that the model cannot override
- Rule Lifecycle Metadata for Prunable Instruction Surfaces — Tagging each rule with source, applies_to, and retire_when converts the rule-budget audit from a counting exercise into a pruning exercise so the instruction surface can actually shrink
- The No-Op Test: Prune Agent Docs by Behavior, Not Length — Delete a line, rerun the task, and keep it only if behavior moved; the two loads say where deleted material goes
- Writing Retained Instructions for Later Tasks — Across seven informative transfer events in one study, the two adaptations covering what later sessions hit removed the targeted action; a list carrying a closed-world default drew the verification it was written to prevent
- Skill Rule Novelty: Add What the Skill Does Not Name — An added skill rule moves the agent when it names a command or path the file lacked; discount the gain for on-demand loading and for how rarely a request needs it
- Irreducibility Triage: What to Write Down for Agents — Rank agent artifacts by whether a better model could ever supply their content; adequacy judgment, renegotiated domain knowledge, and a system's intended trajectory are the three kinds no corpus holds
- Why an Encoded Rule Still Fails After a Passing Eval — A rule that passes the eval and keeps failing in production is unclear, not loading, inexpressible in the available primitives, or in the wrong medium; only the first is wording
- Agent Context File Evolution: Treating ACFs as Configuration Code — ACFs are actively-maintained artifacts that drift with code and grow monotonically; the maintenance discipline is two loops — add-on-drift and compact-on-add — that keep the file under the compliance ceiling
- Prompt Governance via PR — Store agent instructions as plain markdown files in git and use pull requests to propose, review, and merge behavior changes
- Agent Config as a Managed Supply Chain — Treat CLAUDE.md and AGENTS.md as a content-addressed, version-pinned, permission-declaring artifact; the benefit is provenance and rollback at multi-repo scale, not model compliance
- Frontmatter and Body Rule Drift in Agentic Workflows — A workflow file's configuration region is enforced and its prose region is not, and most maintenance edits touch only one of the two
- Policy File Validation: Catching Silent Non-Enforcement — A defect in a governance config file stops the rule applying instead of erroring; a commit-time check that names the file and the path inside it turns that silence into a fixable error, and never reaches the well-formed typo
- Pre-Execution Skill Selection: Layers Over Install Counts — Among candidate skills that are all already popular, community popularity signals tracked measured task performance at between -0.1557 and 0.0679, none significant; score the metadata, constraints, resources, and instructions layers instead
- Skill Packs: Registry Distribution Needs Pinning Discipline — A registry pack gives a team one addressable, updatable skill bundle; the version pin, the review gate, and the size limit stay the team's job
- Shipping a Shared Agent Toolkit as a Versioned Plugin — Shared constraints, instructions, and tool connections belong in the package while application evidence and decisions stay in the repo; in Copilot CLI a packaged agent or skill loses to a local definition of the same identifier, and a packaged MCP server overrides the consumer's
- Workspace-Hosted Skills: Authorship Outside the Repo — A skill whose source of truth is a document workspace makes page edit permission the mutation gate and page view permission the install gate; mirror the workspace into git to keep a revision you can roll back to
- Dependabot Version Updates for Agent Package Dependencies
- Skill File Linting: Which Three Checks to Run First — Description shape, no name-as-H1, and externalized code cover most SKILL.md defects; the gate buys routing and review hygiene, never a safety verdict
- Plugin Component Co-Change: Scripts and Their Instructions Move Together — Inside one plugin a bundled script and the markdown describing it are one interface; pair the edits where the prose carries operational detail, and
claude plugin validatewill not catch the gap - Post-Compaction Re-read Protocol — Restore behavioral contracts after context compaction by triggering a targeted re-read of CLAUDE.md or AGENTS.md
- Content Exclusion Gap in Agent Systems — Security boundaries defined for one AI interaction mode may not apply across all modes; content exclusion rules for completions and chat can be silently ignored in agent mode
- Prompt-Rewrite Discipline on Cross-Generation Model Migration — Discard the inherited prompt stack on cross-generation hops, start from the smallest prompt that preserves the product contract, and re-tune reasoning effort, verbosity, tool descriptions, and output format against representative examples
- HTML as Agent Output Format: When to Ask for HTML Instead of Markdown — Markdown won by token efficiency on small context windows; on frontier models, asking for HTML unlocks interactive review artifacts and explainers — but only when the output will be opened in a browser, not piped into a Markdown-rendering surface
- Mermaid as Agent Output Format: When to Ask for a Diagram Instead of Prose — Asking the agent for a Mermaid block instead of a prose list scans faster for graph-shaped information — but only on surfaces that render Mermaid inline; the decision is a property of the consumer surface, not the model