Context optimizer

From rjmurillo/ai-agents · View interactive version

Context optimizer is an AI agent skill from the GitHub repository rjmurillo/ai-agents. Analyze skill content for optimal placement (Skill vs Passive Context vs Hybrid), compress markdown to pipe-delimited format, and validate compliance against the decision framework. Passive context wins for what the model cannot know (post-cutoff APIs, repo gotchas); pre-trained knowledge belongs in

How to use this skill

Skill file

Context Optimizer

Tooling suite for optimizing Claude Code context placement. Passive context

performed better than skills in the Vercel knowledge-injection eval by

eliminating retrieval decisions.

Triggers

Process

  1. Analyze: Run analyze_skill_placement.py to classify content
  2. Compress: Run compress_markdown_content.py to reduce context overhead
  3. Validate: Run test_skill_passive_compliance.py to check compliance
  4. Verify: Confirm output JSON contains expected classification and details

Verification

Scripts

| Script | Purpose | Exit Codes |

|--------|---------|------------|

| analyze_skill_placement.py | Classify content as Skill/PassiveContext/Hybrid | 0=success, 1=error |

| compress_markdown_content.py | Compress markdown and report the result | 0=success, 1=error, 2=config, 3=external |

| test_skill_passive_compliance.py | Validate compliance with decision framework | 0=pass, 1=violations |

| extract_and_index.py | Extract sections into detail files with pipe-delimited index | 0=success, 1=error, 2=config, 3=external |

| distill_artifact.py | Distill a log, diff, or long text once into a cached digest with line citations; no model call | 0=success, 2=config, 3=external |

| path_validation.py | Shared CWE-22 repo-root-anchored path validation | N/A (library module) |

Run a command you expect to print thousands of lines (full test run, build, log dump) through the repository's run_with_receipt wrapper when the checkout ships it. Never trade a gate, a test, or evidence in a report for tokens. The full redacted output lands in a file and you read a bounded receipt.

Prerequisites

Python 3.12+ with tiktoken for local token counting:

uv pip install -e ".[dev]"   # includes tiktoken
pip install tiktoken           # or install directly

tiktoken is an offline tokenizer (cl100k_base encoding) that approximates Claude tokenization. No API key is required for these scripts.

Decision Framework

The first question is not "skill or passive context." It is: does the model already know this?

Passive Context Earns Its Slot Only For What The Model Cannot Know

Keep Out Of Passive Context

Use Skills For

Hybrid Pattern

Why This Matters

| Configuration | Outcome |

|---------------|---------|

| Baseline (no docs) | Weaker than passive context |

| Skill (default) | Weaker than passive context |

| Skill + explicit instructions | Better than the default skill |

| AGENTS.md passive context | Strongest result in the eval |

Skills create decision points where agents must choose whether to retrieve documentation. These introduce 4 failure modes: late retrieval, partial retrieval, integration failure, and instruction fragility. Passive context eliminates all four by being always-available.

Read That Table Honestly

The Vercel result is real and narrow. Its suite targeted Next.js 16 APIs chosen

because they were absent from model training data. That is a

knowledge-injection problem: an agent cannot retrieve what it does not know it

is missing, so putting the docs in front of it wins.

It is not evidence that pre-trained knowledge belongs in passive context. Anthropic's Claude 5 context-engineering guidance points the other way for behavioral instruction, naming overconstraint as the failure mode after reducing a system prompt without measurable coding-eval loss. Both results hold, because they answer different questions:

| Content | Model already knows it | Where it goes |

|---------|------------------------|---------------|

| A post-cutoff framework API | No | Passive context |

| This repo's dash ban, its gates | No | Passive context |

| SOLID, Clean Code, refactoring | Yes | Progressive disclosure, or nowhere |

| Deep book material | Partly | Progressive disclosure |

Passive context is paid on every request, whether or not the task needs it.

Use progressive disclosure for guidance that does not apply to every file.

Read the doctrine and the audit procedure before adding always-on text.

Prefer deleting a duplicate over compressing one.

References

<details>

<summary><strong>Tool Details: Skill/Passive Content Analyzer</strong></summary>

Script: scripts/analyze_skill_placement.py

Analyzes skill content and recommends Skill, Passive Context, or Hybrid placement.

The script reports shape, not admission. It cannot tell whether the model

already knows the content, and that is the question the Decision Framework

above turns on. Use it for placement and duplication; the Decision Framework

decides what earns an always-on slot.

Classification Logic:

Usage:

# Analyze a skill directory (from repo root)
( for d in "${CLAUDE_PLUGIN_ROOT}" "${COPILOT_PLUGIN_ROOT}" .claude; do if [ -n "$d" ] && [ -f "$d/lib/ptk_run.py" ]; then exec python3 "$d/lib/ptk_run.py" skills/context-optimizer/scripts/analyze_skill_placement.py -p .claude/skills/github; fi; done; echo "ptk_run: no plugin root holds lib/ptk_run.py" >&2; exit 2 )

# Analyze a specific SKILL.md
( for d in "${CLAUDE_PLUGIN_ROOT}" "${COPILOT_PLUGIN_ROOT}" .claude; do if [ -n "$d" ] && [ -f "$d/lib/ptk_run.py" ]; then exec python3 "$d/lib/ptk_run.py" skills/context-optimizer/scripts/analyze_skill_placement.py -p .claude/skills/github/SKILL.md; fi; done; echo "ptk_run: no plugin root holds lib/ptk_run.py" >&2; exit 2 )

# Get detailed metrics
( for d in "${CLAUDE_PLUGIN_ROOT}" "${COPILOT_PLUGIN_ROOT}" .claude; do if [ -n "$d" ] && [ -f "$d/lib/ptk_run.py" ]; then exec python3 "$d/lib/ptk_run.py" skills/context-optimizer/scripts/analyze_skill_placement.py -p .claude/skills/github -d; fi; done; echo "ptk_run: no plugin root holds lib/ptk_run.py" >&2; exit 2 )

Output:

{
  "classification": "Hybrid",
  "confidence": 85,
  "reasoning": "High tool execution (12 calls); High reference content ratio (0.75)",
  "recommendations": {
    "Passive": ["Routing Rules", "Classification Framework"],
    "Skill": ["Get-UnaddressedComments.ps1", "Post-PRCommentReply.ps1"]
  }
}

Classification Thresholds:

| Classification | Criteria | Confidence |

|----------------|----------|------------|

| Skill | skillScore > passiveScore + 3 | 70-90% |

| PassiveContext | passiveScore > skillScore + 3 | 70-90% |

| Hybrid | abs(skillScore - passiveScore) <= 3 | 50-70% |

</details>

<details>

<summary><strong>Tool Details: Content Compression Utility</strong></summary>

Script: scripts/compress_markdown_content.py

Compress markdown to pipe-delimited format while preserving the information

needed for retrieval.

Compression Techniques:

Usage:

# Basic compression (JSON output to stdout)
python3 scripts/compress_markdown_content.py -i README.md -l medium

# Save to file with aggressive compression
python3 scripts/compress_markdown_content.py -i CRITICAL-CONTEXT.md -l aggressive -o compressed.txt

# With verbose metrics
python3 scripts/compress_markdown_content.py -i input.md -l medium -v

Compression Levels:

| Level | Techniques |

|-------|-----------|

| Light | Headers, tables, whitespace |

| Medium | Redundant words, tighter whitespace |

| Aggressive | H3 compression, lists, abbreviations |

Example:

Before:

## Session Protocol

The session protocol has multiple phases:

1. Serena Activation - You must activate Serena

After:

[Session Protocol]
session protocol has multiple phases:
1. Serena Activation - activate Serena

</details>

<details>

<summary><strong>Tool Details: Extract-and-Index Utility</strong></summary>

Script: scripts/extract_and_index.py

Implements the Vercel extract-and-index pattern. Splits markdown by headings

into detail files and generates a compact pipe-delimited index.

Usage:

# Extract sections and output JSON to stdout
python3 scripts/extract_and_index.py -i AGENTS.md -d .agents-details

# Write index to a file
python3 scripts/extract_and_index.py -i AGENTS.md -d .agents-details -o AGENTS-INDEX.md

# Custom reference path in index
python3 scripts/extract_and_index.py -i AGENTS.md -d .agents-details -r .agents-docs -o AGENTS-INDEX.md

Output Index Format (Vercel pattern):

[Architecture]
|Layered design with separation of concerns (see: .agents-details/architecture.md)
[Testing]
|Coverage required for business logic (see: .agents-details/testing.md)

Works with CLAUDE.md @import mechanism. Reference via @AGENTS-INDEX.md.

</details>

<details>

<summary><strong>Tool Details: Distill Artifact</strong></summary>

Script: distill_artifact.py

Boils one log, diff, or long text down to a markdown digest with line

citations. No model call. The digest is cached by content and source, so a

repeat call reuses it.

Use it for an artifact you will read on more than one turn, or one too large

to read whole. The digest keeps signal lines (error, fail, warning, and

similar), the first and last 15 lines, and per-file counts for a diff. Middle

lines without a signal are omitted, so a clean git log digests thin: use

git log --oneline for chronology instead.

Usage:

# Save the output and its exit code first, so the raw stays searchable
some_command > build.log 2>&1; echo "exit=$?"

# Distill the saved file; prints the digest path
( for d in "${CLAUDE_PLUGIN_ROOT}" "${COPILOT_PLUGIN_ROOT}" .claude; do if [ -n "$d" ] && [ -f "$d/lib/ptk_run.py" ]; then exec python3 "$d/lib/ptk_run.py" skills/context-optimizer/scripts/distill_artifact.py build.log; fi; done; echo "ptk_run: no plugin root holds lib/ptk_run.py" >&2; exit 2 )

# JSON adds cached, kind, raw and digest bytes, ratio
( for d in "${CLAUDE_PLUGIN_ROOT}" "${COPILOT_PLUGIN_ROOT}" .claude; do if [ -n "$d" ] && [ -f "$d/lib/ptk_run.py" ]; then exec python3 "$d/lib/ptk_run.py" skills/context-optimizer/scripts/distill_artifact.py build.log --format json; fi; done; echo "ptk_run: no plugin root holds lib/ptk_run.py" >&2; exit 2 )

- reads stdin, but then no raw copy remains to search, and a pipe reports

the distiller's exit code, not the command's. Save to a file first.

Use the digest to locate evidence (L{n} cites the raw line). It omits middle

lines without a signal, so search the raw source for any detail it lacks and

read the matching lines with their context.

</details>

<details>

<summary><strong>Tool Details: Compliance Validator</strong></summary>

Script: scripts/test_skill_passive_compliance.py

Validates content placement against the skill vs passive context decision framework.

Evaluated Checks:

  1. Skills contain actions (verbs, tool execution, scripts)
  2. Passive context is knowledge-only (no action patterns)
  3. @imported files exist and are readable
  4. Skills have frontmatter (name and description)
  5. No duplicate content between skills and passive context
  6. Declared size exceptions include rationale and safeguard evidence

The report examines the selected CLAUDE.md file separately from imported

content, hierarchical CLAUDE.md and AGENTS.md files, generated instruction

layers, and plugin context. That result is diagnostic, not a compliance

verdict.

Claude Code loads CLAUDE.md files in full. Auto-memory uses MEMORY.md and

follows separate vendor behavior. This repository applies its own skill

validation policy in skill_size.py.

Source:

<https://docs.anthropic.com/en/docs/claude-code/memory>

Skill size is also separate. In a full rjmurillo/ai-agents checkout, run the

repository's skill_size.py validator against both the canonical and generated

skill trees.

The report states what it does not evaluate. Content value still needs

evidence-based review. Classify each passive rule as one of:

  1. Non-inferable gotcha with cited evidence
  2. Local arbitration between otherwise reasonable rules
  3. Costly-failure safeguard
  4. Task procedure that belongs in a skill
  5. Inferable restatement that should be removed

Lexical matches do not prove those categories. Cite the incident, source, or

test that supports each keep or remove decision.

Usage:

# Scan .claude directory (JSON output)
python3 scripts/test_skill_passive_compliance.py

# Scan specific directory with table output
python3 scripts/test_skill_passive_compliance.py --path .claude/skills/github --format table

Exit Codes: 0 = all passed, 1 = violations detected

Common Violations:

| Violation | Fix |

|-----------|-----|

| Missing @import file | Create file or remove @import directive |

| Skill missing frontmatter | Add --- block with name: and description: |

| Skill has no actions | Add scripts or move to passive context |

| Passive has actions | Extract executable content to a skill |

| Duplicate content | Remove redundant content from skill or passive |

| Unaudited size exception | Add invariant, behavior tests, and review trigger |

</details>

<details>

<summary><strong>Classification Examples</strong></summary>

Clear Skill Classification

Input: GitHub skill with gh pr create, gh issue close commands

{"classification": "Skill", "confidence": 85, "reasoning": "High tool execution (8 calls); Many action verbs (12)"}

Clear Passive Classification

Input: Memory hierarchy reference, tables and lists, no commands

{"classification": "PassiveContext", "confidence": 80, "reasoning": "High reference content ratio (0.85)"}

Hybrid Classification

Input: PR comment responder with routing rules + script execution

{
  "classification": "Hybrid",
  "confidence": 65,
  "reasoning": "High reference content ratio (0.72); Some tool execution (4 calls)",
  "recommendations": {
    "Passive": ["Routing Rules", "Classification Framework"],
    "Skill": ["Get-UnaddressedComments.ps1", "Post-PRCommentReply.ps1"]
  }
}

</details>

<details>

<summary><strong>Testing</strong></summary>

python3 -m pytest tests/                                          # all tests
python3 -m pytest tests/test_skill_passive_compliance_test.py -v  # specific
python3 -m pytest tests/ --cov=scripts --cov-report=term-missing  # coverage

Coverage Summary:

| Component | Key Areas |

|-----------|-----------|

| Compliance Validator | Placement, @imports, frontmatter, duplicates, exit codes |

| Analyzer | Tool calls, action verbs, classification logic, confidence scoring |

| Extract-and-Index | Slug generation, parsing, index format |

| Compressor | Compression levels, code block preservation |

</details>

<details>

<summary><strong>Implementation Notes</strong></summary>

Marketplace Value

</details>

<!-- vendor-portability: declared. This skill cites .project-toolkit/analysis/vercel-passive-context-vs-skills-research.md as background reading. It is a documentation citation; the optimizer runs without reading the file, and a vendored install loses only the link target. -->

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.