optimize-agent-docs
Build a retrieval-optimized knowledge layer over agent documentation in dotfiles (.claude, .codex, .cursor, .aider). Use when asked to "optimize docs", "improve agent knowledge", "make docs more efficient", or when documentation has accumulated and retrieval feels inefficient. Generates a manifest mapping task-contexts to knowledge chunks, optimizes information density, and creates compiled artifacts for efficient agent consumption.
What this skill does
# Agent Knowledge Optimizer
Transform accumulated documentation into a retrieval-optimized knowledge system.
## Core Principle
File organization is a human concern. Agents don't browse—they search and load. Optimize for:
- **Discovery**: What knowledge exists?
- **Relevance**: Is it needed for this task?
- **Efficiency**: What's the minimum to load?
## Workflow
### Phase 1: Knowledge Extraction
Inventory all agent documentation:
```bash
# Find all agent doc sources
find . -maxdepth 2 -name "*.md" -path "*/.claude/*" -o \
-name "*.md" -path "*/.codex/*" -o \
-name "*.md" -path "*/.cursor/*" -o \
-name "CLAUDE.md" -o -name "AGENTS.md" -o -name "INSTRUCTIONS.md"
```
For each file, extract:
- Discrete facts (single pieces of actionable information)
- Instructions (procedures, rules, constraints)
- Context triggers (when is this knowledge needed?)
### Phase 2: Chunk Analysis
Break content into **retrieval units**—the smallest self-contained piece of information that makes sense alone.
Good chunk:
```
## Adding API Endpoints
1. Create handler in src/handlers/
2. Register route in src/routes.rs
3. Add OpenAPI spec to docs/api.yaml
```
Bad chunk (too coupled):
```
See the API section for endpoint patterns, but first read the auth docs,
which reference the middleware guide...
```
Score each chunk:
- **Self-contained?** Can agent act on this without loading more?
- **Task-specific?** Clear when this is needed?
- **Information-dense?** High signal per token?
### Phase 3: Build Knowledge Manifest
Generate `.claude/KNOWLEDGE.md`—a lightweight index the agent reads first:
```markdown
# Knowledge Manifest
## Task → Knowledge Map
| When working on... | Load | Key terms |
|-------------------|------|-----------|
| API endpoints | references/api.md | route, handler, endpoint |
| Authentication | references/auth.md | token, session, login |
| Database changes | references/schema.md | migration, model, query |
| Testing | references/testing.md | spec, fixture, mock |
| Deployment | references/deploy.md | release, staging, prod |
## Quick Reference
### Build Commands
- `npm run dev` — Start dev server (port 3000)
- `npm test` — Run test suite
- `npm run build` — Production build
### Key Paths
- Handlers: `src/handlers/`
- Routes: `src/routes.ts`
- Tests: `tests/`
### Critical Rules
- Never commit .env files
- All PRs require tests
- Use conventional commits
```
The manifest contains:
1. **Task→Knowledge map**: What to load for what context
2. **Quick reference**: High-frequency facts (no file loading needed)
3. **Critical rules**: Must-know constraints (always relevant)
### Phase 4: Compile Optimized Artifacts
Transform verbose source docs into dense, agent-optimized versions.
**Compression techniques:**
| Source (verbose) | Compiled (dense) |
|-----------------|------------------|
| "When you want to add a new endpoint, you should first create a handler function..." | `New endpoint: handler → route → spec` |
| Long prose paragraphs | Structured tables |
| Repeated information | Single source of truth |
| Examples with explanation | Just the pattern |
**Output structure:**
```
.claude/
├── CLAUDE.md # Human-readable, can stay verbose
├── KNOWLEDGE.md # Agent manifest (generated)
└── compiled/ # Agent-optimized versions (generated)
├── api.md # Dense API reference
├── patterns.md # Code patterns as templates
└── rules.md # All constraints in one place
```
### Phase 5: Generate Retrieval Hints
Add grep-friendly markers throughout compiled docs:
```markdown
<!-- @task:new-endpoint @load:api,routes -->
## Adding Endpoints
<!-- @task:fix-auth @load:auth,middleware -->
## Authentication Flow
<!-- @task:write-test @load:testing -->
## Test Patterns
```
These markers enable:
```bash
# Find relevant sections for a task
grep -l "@task:new-endpoint" .claude/compiled/*.md
```
### Phase 6: Validation
Test the optimized system:
1. **Coverage check**: Every fact from source exists in compiled output
2. **Retrieval test**: Can common tasks be served with minimal loading?
3. **Density check**: Compiled versions smaller than sources?
```bash
# Compare sizes
wc -l .claude/references/*.md # Source
wc -l .claude/compiled/*.md # Compiled (should be smaller)
```
## Manifest Format
The `KNOWLEDGE.md` manifest follows this structure:
```markdown
# Knowledge Manifest
<!-- Auto-generated. Source: .claude/references/, CLAUDE.md -->
## Task Context Map
<!-- What to load based on current work -->
| Context | Load | Search |
|---------|------|--------|
| [task description] | [file path] | [grep terms] |
## Always-Loaded Facts
<!-- High-frequency, never needs file lookup -->
### Commands
[Most-used commands as a table]
### Paths
[Key directories and their purposes]
### Rules
[Critical constraints that always apply]
## Chunk Index
<!-- What exists and where -->
| Topic | Location | Lines | Summary |
|-------|----------|-------|---------|
| [topic] | [file:line-range] | [count] | [one-line summary] |
```
## Information Density Principles
### Convert Prose to Structure
Before:
> "The authentication system uses JWT tokens stored in httpOnly cookies.
> When a user logs in, the server validates credentials against the database,
> generates a token with a 24-hour expiry, and sets it as a cookie..."
After:
```
## Auth Flow
- Method: JWT in httpOnly cookie
- Expiry: 24h
- Flow: credentials → DB validate → token → cookie
```
### Eliminate Redundancy
If the same information appears in multiple places, create one canonical source and reference it:
```markdown
## Token Handling
See: [Auth Flow](#auth-flow) — tokens section
```
### Prefer Tables Over Lists
Before:
```markdown
- The API endpoint for users is /api/users
- The API endpoint for posts is /api/posts
- The API endpoint for comments is /api/comments
```
After:
```markdown
| Resource | Endpoint |
|----------|----------|
| Users | /api/users |
| Posts | /api/posts |
| Comments | /api/comments |
```
### Use Patterns Over Examples
Before:
```markdown
To create a user handler:
```javascript
export async function createUser(req, res) {
const { name, email } = req.body;
const user = await db.users.create({ name, email });
res.json(user);
}
```
After:
```markdown
Handler pattern: `export async function {action}{Resource}(req, res)`
Body: Extract params → DB operation → Return result
```
## Output Checklist
After optimization, verify:
- [ ] `KNOWLEDGE.md` exists and is under 100 lines
- [ ] Task→knowledge mappings cover common workflows
- [ ] Quick reference has most-used facts
- [ ] Compiled docs are denser than sources
- [ ] No orphaned knowledge (everything indexed)
- [ ] Retrieval hints enable grep-based discovery
- [ ] Original source docs untouched (human reference)
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.