---
name: ao-optimize-instructions
description: "Optimize agent instruction files by extracting project-specific sections to .agent/ops/references/ and reducing context size. Works across all editors (Copilot, Claude Code, Cursor, Windsurf, OpenCode)."
category: extended
invokes: [ao-project-sections, ao-interview]
invoked_by: [ao-init, User request]
state_files:
  read: [focus.json, constitution.md]
  write: [focus.json]
---

# Instruction File Optimization Workflow

## Purpose

Optimize agent instruction files by:

1. Scanning all instruction files in the target project
2. Extracting project-specific content to `.agent/ops/references/`
3. Replacing verbose sections with concise summaries and links
4. Generating editor-specific path-scoped files where supported
5. Reducing total context size while preserving information

## Golden Rule: Content Placement

| Location | Contains | Examples |
|----------|----------|----------|
| `.ao/references/` | AO **framework** docs — methodology, generic patterns | `confidence.md`, `lang-python.md`, `issue-handling.md` |
| `.agent/ops/references/` | **Project-specific** content — code standards, architecture, testing | `code-standards.md`, `architecture.md`, `testing-conventions.md` |

**Never** put project-specific content in `.ao/`. The `.ao/` directory is framework-agnostic and shared across all projects.

## Editor Loading Behavior

| Editor | Always-loaded file | Path-scoped mechanism | Import/reference syntax | Progressive disclosure |
|--------|-------------------|----------------------|------------------------|----------------------|
| **VS Code Copilot** | `copilot-instructions.md`, `AGENTS.md` | `.github/instructions/*.instructions.md` with `applyTo:` frontmatter | None (inline only) | Skills (name+desc loaded, body on-demand) |
| **Claude Code** | `CLAUDE.md` (root + ancestors) | `.claude/rules/*.md` with `paths:` frontmatter | `@path/to/file` (5-hop recursive) | Automatic via @-imports |
| **Cursor** | `.cursorrules` | None | None | None |
| **Windsurf** | `.windsurfrules` | None | None | None |
| **OpenCode** | `AGENTS.md` | None | None | None |

## Token Budget Guidelines

| File | Recommended max | Approx tokens | Action if exceeded |
|------|----------------|---------------|-------------------|
| `copilot-instructions.md` | 500 lines (~2 pages) | ~8k | Extract to `.agent/ops/references/` |
| `AGENTS.md` | 200 lines | ~4k | Extract to `.agent/ops/references/` |
| `CLAUDE.md` | 100 lines (use @-imports) | ~2k inline | @-import from `.agent/ops/references/` |
| `.cursorrules` / `.windsurfrules` | 500 lines | ~8k | Consolidate; no import mechanism |
| `.github/instructions/*.md` | 50 lines each | ~1k each | Keep focused; one concern per file |
| `.claude/rules/*.md` | 50 lines each | ~1k each | Keep focused; one concern per file |
| Skill `SKILL.md` | 500 lines | ~8k | Extract examples to REFERENCE.md |
| Skill description (frontmatter) | 1024 chars | ~200 | Must fit; agents see this always |

## Decision Tree: Where Does Content Go?

```
Is this content about AO methodology/framework?
├── YES → .ao/references/ (e.g., confidence.md, issue-handling.md)
└── NO → Is it project-specific?
    ├── YES → .agent/ops/references/ (e.g., code-standards.md, architecture.md)
    └── NO → Is it a generic language/pattern guide?
        ├── YES → .ao/references/lang-{language}.md (shared across projects)
        └── NO → Keep inline in the instruction file
```

## When to Use

- Instruction file exceeds token budget (see table above)
- File contains large code examples or project-specific procedures
- Multiple instruction files duplicate the same content
- Agent consistently runs out of context
- Running `ao init` on a new project with existing instruction files

## Optimization Strategies

### Strategy 1: Section Extraction (to .agent/ops/references/)

Extract large project-specific sections into reference files.

**Before:**
```markdown
# copilot-instructions.md (1200 lines)

## Code Standards
{400 lines of project-specific coding conventions}

## Architecture
{300 lines of project directory tree and module descriptions}
```

**After:**
```markdown
# copilot-instructions.md (200 lines)

## Code Standards
See: [code-standards.md](.agent/ops/references/code-standards.md)
Key points: Type annotations required, max 15 lines per function, pathlib only.

## Architecture
See: [architecture.md](.agent/ops/references/architecture.md)
Key points: src/ layout, internal modules, web/ for API.
```

### Strategy 2: Editor-Specific Path-Scoped Files

Generate path-scoped instruction files for editors that support them.

**For Copilot** — `.github/instructions/{concern}.instructions.md`:
```yaml
---
applyTo: "**/*.py"
---
# Python conventions for this project
Type annotations on all functions. Use pathlib.Path for file ops.
```

**For Claude Code** — `.claude/rules/{concern}.md`:
```yaml
---
paths:
  - "tests/**"
---
# Testing conventions for this project
Use pytest with tmp_path. Never touch the project directory.
```

### Strategy 3: @-Import Chains (Claude Code)

Use @-imports to keep CLAUDE.md minimal:
```markdown
# CLAUDE.md
@.ao/references/ao-workflow.md
@.ao/skill-index.md
@.agent/ops/references/code-standards.md
@.agent/ops/references/architecture.md
@.agent/ops/references/testing-conventions.md
```

**Note:** Always include `.ao/references/ao-workflow.md` and `.ao/skill-index.md` in every
generated instruction file. These are the AO framework entry points that agents
need to discover skills and understand the workflow protocol.

### Strategy 4: Tiered Detail

Keep high-level summary inline, link to detailed version:
```markdown
## Error Handling
**Quick reference:** Try/except with specific types, log via structured logger.
**Full guide:** [error-handling.md](.agent/ops/references/error-handling.md)
```

## Procedure

### Phase 1: Discovery

1. **Scan for instruction files** in the target project:
   - `copilot-instructions.md`, `AGENTS.md`, `CLAUDE.md`
   - `.cursorrules`, `.windsurfrules`
   - `.github/instructions/*.instructions.md`
   - `.claude/rules/*.md`
   - Skill files (`SKILL.md`, `REFERENCE.md`)
2. **Measure sizes**: Count lines, estimate tokens per file
3. **Detect editors in use**: Which instruction files exist?

### Phase 2: Analysis

1. **Identify section boundaries**: Headers, code blocks, tables
2. **Classify each section**:
   - ✅ **Extract**: Large (>50 lines), project-specific, reference-style → `.agent/ops/references/`
   - ⚠️ **Consider**: Medium (20-50 lines), may lose context if extracted
   - ❌ **Keep inline**: Small (<20 lines), critical workflow, frequently referenced
3. **Check for duplication**: Same content across multiple instruction files?
4. **Apply decision tree**: Route each section to correct location

### Phase 3: User Confirmation

Present optimization plan:
```
## Instruction Optimization Plan

### Files Scanned
| File | Current lines | Over budget? |
|------|--------------|-------------|
| copilot-instructions.md | 1,200 | ✅ Yes (500 max) |
| AGENTS.md | 150 | No |
| CLAUDE.md | (not present) | — |

### Proposed Extractions → .agent/ops/references/

| Section | Source file | Lines | Target |
|---------|-----------|-------|--------|
| Code Standards | copilot-instructions.md | 400 | references/code-standards.md |
| Architecture | copilot-instructions.md | 300 | references/architecture.md |
| Testing | copilot-instructions.md | 250 | references/testing-conventions.md |

### Editor-Specific Files to Generate
| File | applyTo / paths | Content source |
|------|----------------|---------------|
| .github/instructions/python.instructions.md | **/*.py | Code Standards (summary) |
| .claude/rules/testing.md | tests/** | Testing (summary) |

### Projected Result
Before: 1,200 lines (~48k tokens)
After: ~350 lines (~14k tokens) + 3 reference files

Proceed? [Y]es / [E]dit plan / [C]ancel
```

### Phase 4: Execution

1. **Create `.agent/ops/references/`** if needed
2. **Extract sections** to reference files:
   - Copy full content to `.agent/ops/references/{name}.md`
   - Add frontmatter with source reference
3. **Update source files**:
   - Replace extracted sections with summary + link
   - Preserve header structure
4. **Generate editor-specific files** where supported:
   - Copilot: `.github/instructions/` with `applyTo:` frontmatter
   - Claude Code: `.claude/rules/` with `paths:` frontmatter
   - Claude Code: Create/update `CLAUDE.md` with @-imports
5. **Validate links**: Ensure all references resolve

### Phase 5: Verification

1. **Check file sizes**: All under budget?
2. **Validate markdown**: No broken links, proper formatting
3. **Report results**

## Reference File Template

```markdown
---
title: {Section Title}
extracted_from: {source file path}
extracted_date: {YYYY-MM-DD}
---

# {Section Title}

{Full content from original section}
```

## Completion Criteria

- [ ] Source file sizes reduced to within budget
- [ ] All extracted content preserved in `.agent/ops/references/`
- [ ] No project-specific content in `.ao/references/`
- [ ] Editor-specific path-scoped files generated where applicable
- [ ] Links validate (no broken references)
- [ ] Summaries capture key points inline
- [ ] Size reduction reported

## Anti-patterns (avoid)

- ❌ Putting project content in `.ao/references/` (use `.agent/ops/references/`)
- ❌ Extracting critical workflow steps (keep inline)
- ❌ Creating too many tiny files (consolidate related content)
- ❌ Losing context between extracted sections
- ❌ Removing all examples (keep 1-2 inline for quick reference)
- ❌ Generating editor files for editors not in use by the project
