optimize-agents-md

Original🇨🇳 Chinese
Translated

Guide for Writing and Optimizing AGENTS.md, following the principle of progressive disclosure. This skill must be loaded when users create, modify, or refactor AGENTS.md, discuss AI agent instruction structures, rule placement, or mention terms like "progressive disclosure", "modularity", "AGENTS.md best practices". Even if users simply say "help me write an AGENTS.md", "optimize this configuration file", or "split the rules", this skill should be used.

2installs
Added on

NPX Install

npx skill4agent add cnife/skills optimize-agents-md

SKILL.md Content (Chinese)

View Translation Comparison →

Guide for Writing and Optimizing AGENTS.md

Problem Diagnosis

Split AGENTS.md when it exhibits the following symptoms:
  • The file exceeds 100 lines and contains rules for multiple unrelated modules
  • Rules for different tech stacks are mixed (Python + Frontend + Database)
  • The Agent loads a large amount of irrelevant content in each session
  • High coupling between rules, making independent maintenance difficult

Principles for Creating AGENTS.md

1. Start with Simplicity

The root AGENTS.md should only contain rules that are "required in every session":
  • Language preferences
  • Core working principles
  • Global Git specifications
  • Project entry instructions
Goal: Keep the root AGENTS.md under 50 lines.

2. Plan by Scope

Before adding a rule, first determine its scope:
This rule → Global effect? → Yes → Root AGENTS.md
         → Specific module? → Yes → Subdirectory AGENTS.md or Skill
         → Complex workflow? → Yes → Skill
         → Uncertain? → Consider if it's really necessary

3. Avoid Common Pitfalls

PitfallProblemCorrect Approach
Stuffing all rules into one fileContext waste, Agent confusionSplit by scope
Tutorial-style content (how to use X)Irrelevant content loaded in every sessionPlace in Skill or documentation
Overly specific command examplesRule bloat, difficult to maintainOnly write core principles
Conflicts with other rulesInconsistent Agent behaviorMerge or delete conflicting rules

4. Writing Style

  • Concise: Use phrases instead of paragraphs
  • Clear: Avoid words like "maybe" or "perhaps"; use "should" or "prohibit"
  • Structured: Use lists and tables for quick scanning
  • Explain why: Briefly state the importance of each rule

Progressive Disclosure Principle

Core idea: Start simple, add complexity on demand.
LevelContentLoading Timing
1. Metadataname + descriptionAlways visible
2. SKILL.md bodyCore instructionsLoaded when the Agent judges it relevant
3. ReferencesDetailed documentationLoaded only when needed
Benefits:
  • Saves context window space
  • The Agent only sees relevant rules
  • Rules are easier to maintain

File Placement Rules (Important)

Core Principles

  • AGENTS.md related to a specific folder/module → Place in that folder
  • Project-wide document-type AGENTS.md → Place in the
    docs/
    directory
  • User global rules → Place in
    ~/.config/opencode/AGENTS.md
    (applies to all projects)

Hierarchical Structure

~/.config/opencode/AGENTS.md   # User global (shared by all projects)
    ↓ Inherit/Override
project/AGENTS.md              # Project root (project-level rules)
    ↓ Inherit/Override
project/src/python/AGENTS.md   # Module-level (specific module rules)
Rule Priority: Module-level > Project-level > User global-level (more specific rules override more general ones)

No Duplication Principle

AGENTS.md files at different levels must not contain duplicate content for the following reasons:
  • Wastes context window space
  • May cause rule conflicts
  • Increases maintenance burden
Correct Approach:
LevelShould ContainShould Not Contain
User globalCross-project general rules (language preferences, Git specifications)Project-specific rules, module rules
Project rootProject-specific rules (project architecture, team agreements)Rules already defined in user global, module rules
Module directoryModule-specific rules (tech stack specifications, file naming)Rules already defined in upper levels
Example:
markdown
# ❌ Wrong: Project AGENTS.md duplicates user global rules
# Language
Always respond in Chinese.          # Already defined in ~/.config/opencode/AGENTS.md, duplicate!

# Git
Short commit messages, no prefix    # Already defined in ~/.config/opencode/AGENTS.md, duplicate!

# ✅ Correct: Project AGENTS.md only contains project-specific rules
# Project Structure
src/ is the source code directory, tests/ is the test directory.

# Team Agreement
PRs must be reviewed by at least one person.

File Placement Example

~/.config/opencode/
└── AGENTS.md                # User global rules (shared by all projects)

project/
├── AGENTS.md                # Project global rules (< 50 lines)
├── docs/
│   ├── AGENTS.md            # Project-level documentation rules, architecture descriptions
│   ├── architecture.md      # Architecture documentation
│   └── api-guide.md         # API usage guide
├── src/
│   ├── python/
│   │   └── AGENTS.md        # Python module-specific rules
│   └── frontend/
│       └── AGENTS.md        # Frontend module-specific rules
└── .opencode/
    └── skills/
        └── deploy/SKILL.md  # Deployment workflow (complex task)

Judgment Criteria

Content TypePlacementExample
User global constraints
~/.config/opencode/AGENTS.md
Language preferences, Git specifications, core principles
Project global constraintsProject root AGENTS.mdProject architecture, team agreements, entry instructions
Module/folder rulesAGENTS.md in that folderPython specifications, frontend specifications, API module rules
Project-level documentation instructions
docs/AGENTS.md
Architecture descriptions, documentation writing specifications, project guides
Complex workflowsSkillDeployment processes, PR creation processes

Why Distinguish Between docs/ and Subdirectory AGENTS.md?

  • Subdirectory AGENTS.md: Automatically loaded when the Agent works in that directory, providing immediate context
  • docs/AGENTS.md: Project-level instructions, loaded only when explicitly referenced or searched, avoiding loading large amounts of documentation content in every session

Why Distinguish Between User Global and Project AGENTS.md?

  • User global AGENTS.md: Define once, shared by all projects, avoiding repeating the same personal preferences in each project
  • Project AGENTS.md: Project-specific rules, only effective in this project, without affecting other projects

Split Strategy

1. Categorize Rules

Rule TypePlacementExample
User global rules
~/.config/opencode/AGENTS.md
Language preferences, Git specifications, core principles
Project global rulesProject root AGENTS.mdProject architecture, team agreements, entry instructions
Module rulesSubdirectory AGENTS.mdPython specifications →
python/AGENTS.md
Project documentation rules
docs/AGENTS.md
Documentation writing specifications, architecture descriptions
Task rulesSkillComplex workflows, specific task guides

2. Decision Tree

Is this rule needed in every session?
├── Yes → Is it needed for all projects?
│   ├── Yes → Place in ~/.config/opencode/AGENTS.md (user global)
│   └── No → Place in project root AGENTS.md
└── No → Is it for a specific module/folder?
    ├── Yes → Place in AGENTS.md under that folder
    └── No → Is it project-level documentation/architecture description?
        ├── Yes → Place in docs/AGENTS.md
        └── No → Is it a complex workflow?
            ├── Yes → Create a Skill
            └── No → Consider if this rule is really necessary

Execution Steps

1. Create a New AGENTS.md

1. Confirm which global rules are needed (language, principles, Git)
2. Determine if module-level rules need to be placed separately
3. Write a concise root AGENTS.md
4. If needed, create subdirectory AGENTS.md, docs/AGENTS.md or Skill

2. Analyze Existing Content

1. Read the existing AGENTS.md
2. List all rule modules
3. Mark the scope of each module (global/module/project documentation/task)

3. Develop a Split Plan

Show users:
  • Which content remains in the root directory
  • Which content is split into subdirectory AGENTS.md
  • Which content should be placed in docs/AGENTS.md
  • A content summary for each new file

4. Execute the Split

1. Create subdirectory AGENTS.md, docs/AGENTS.md or Skill files
2. Migrate relevant rules (maintain format and hierarchy)
3. Update the root AGENTS.md, removing split content
4. Add necessary reference notes (optional)

5. Verification

1. Check if the root AGENTS.md is concise
2. Confirm that subdirectory files have complete content
3. Verify no rules are lost or duplicated
4. Confirm docs/AGENTS.md contains project-level documentation rules (if applicable)

Skill vs AGENTS.md Selection

ScenarioRecommendationReason
Cross-project personal preferences (language, Git)
~/.config/opencode/AGENTS.md
Shared by all projects
Project constraints (architecture, team agreements)Project AGENTS.mdEffective at project level
Tech stack specifications (Python, frontend)Subdirectory AGENTS.md or SkillLoaded on demand
Project documentation/architecture descriptions
docs/AGENTS.md
Loaded when needed
Complex workflows (deployment, PR)SkillProgressive disclosure + reusable
Team agreements (naming, formatting)Project AGENTS.mdGlobal constraints

Best Practices

Keep Root AGENTS.md Concise

markdown
# Language
Always respond in Chinese.

# Core Principles
- Prioritize simple, maintainable solutions
- Avoid over-engineering

# Git
- Short commit messages, no prefix

# Module Rules
Python projects → Refer to src/python/AGENTS.md
Frontend projects → Refer to src/frontend/AGENTS.md

# Documentation
Project architecture → Refer to docs/AGENTS.md

Subdirectory AGENTS.md Focuses on a Single Module

markdown
# Python Project Specifications

## Tools
Use uv for dependency management, ruff for formatting.

## Principles
- Fast-fail: Only use try-except at the outer layer
- Prohibit hard-coded credentials

docs/AGENTS.md for Project-level Documentation

markdown
# Project Documentation Specifications

## Architecture Description
This project uses a three-tier architecture, see architecture.md for details.

## API Documentation
- REST API specifications → api-guide.md
- GraphQL Schema → schema.graphql

Skill for Complex Tasks

When rules involve multi-step workflows or require progressive disclosure of large amounts of content, create a Skill instead of AGENTS.md.

Common Mistakes

MistakeConsequenceCorrection
Overly long root AGENTS.mdContext wasteSplit into subdirectories, docs/ or Skill
Duplicate rule definitionsAgent confusionEach rule appears only once
Duplicate content across levelsContext waste, rule conflictsDefine each rule only at the most appropriate level
Overly fine-grained splittingMaintenance burdenMerge related rules
Forgetting to delete original contentRule conflictsMust delete original content after splitting
Module rules placed in root directoryIrrelevant rules loadedMove to corresponding subdirectory
Project documentation rules placed in root directoryContext bloatMove to docs/AGENTS.md
Project rules placed in user globalAffects other projectsMove to project AGENTS.md