agentleFS
Bruno-Cunha-SouzaBruno-Cunha-Souza/ValarMindSkills/skills/context-optimization/SKILL.md

context-optimization

Skill5 starsChanged 6 months agoMITView on GitHub

Lifecycle context audit/optimize/plan. Audit mode (Phase 0..6) + Guide mode (catalog lookup). Targets long-conv agents, RAG pipelines, sub-agents, large-doc workflows. Detects bloat/dedup/cache/masking/partition opportunities. Emits findings (SAFE/REVIEW/BREAKING) + optimization plan + token delta. Read-only — LGTM if sound. Triggers: 'optimize context', 'compact context', 'auditar contexto', 'otimizar contexto', '/context-optimization'.

24 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use bdi-mental-states, long-horizon-prompting and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • Downey6689Skill

    bdi-mental-states

    Transforms external RDF context into BDI mental states. Invoke when modeling beliefs, desires, and intentions.

    Also in 7 projects that use this

  • DVwebBiz11Skill

    long-horizon-prompting

    This skill should be used when writing, enhancing, or evaluating the launch prompt for a long-running autonomous agent or a parallel multi-agent orchestration attacking a hard problem: pseudo-formal task briefs that define terms and an exact success predicate linguistically, enumerate non-counting outcomes, set persistence rules with explicit stop and return conditions and effort floors, manage a diverse portfolio of parallel approaches with an approach registry and blocked-route bookkeeping, and gate the return on adversarial audit. Route agent topology and coordination protocols to multi-agent-patterns, runtime control surfaces and loop governance to harness-engineering, evaluator and quality-gate construction to evaluation, judge design to advanced-evaluation, and compaction or memory mechanics to context-compression and memory-systems.

    Also in 5 projects that use this

  • Downey6689Skill

    hosted-agents

    Guidance for hosted/sandboxed agents. Invoke when running background agents in isolated VMs or multi-client setups.

    Also in 6 projects that use this

  • DVwebBiz11Skill

    self-improvement-loops

    This skill should be used when the harness, scaffold, workflow, or optimizer itself is the optimization target: recursive self-improvement (RSI) loops, meta-harnesses, self-improving harnesses that mine their own failures and propose bounded edits, evolutionary or population-based search over agent scaffolds, acceptance gates for self-modifying systems, and agentic context evolution where the mechanism that produces context is versioned and evolved. Route governance of a single autonomous loop (locked surfaces, durable logs, rollback, novelty gates, approval boundaries) to harness-engineering, measurement and quality-gate design to evaluation, judge design to advanced-evaluation, and remote sandbox infrastructure to hosted-agents.

    Also in 4 projects that use this

  • AbdelrhmanAlquranSkill

    latent-briefing

    This skill should be used when the user asks to "share memory between agents", "KV cache compaction for multi-agent", "orchestrator worker context", "latent briefing", "reduce worker tokens", "cross-agent memory without summarization", or discusses Attention Matching compaction, recursive language models with workers, or token explosion in hierarchical agents.

    Also in 4 projects that use this

  • rohunvoraSkill

    advanced-evaluation

    Master LLM-as-a-Judge evaluation techniques including direct scoring, pairwise comparison, rubric generation, and bias mitigation. Use when building evaluation systems, comparing model outputs, or establishing quality standards for AI-generated content.

    Also in 6 projects that use this

  • +1 more from Downey6689

The file

We split this skill into the rules it gives an agent

4 rules. 0 are common, 1 is distinctive, and 3 are very specific to this project.

  • 0

    Common

    Most of the 22 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    No degradation signal reported

    line 51
  2. Very specific:

    When harness ≠ agnostic, Block 3 emits concrete commands per HARNESS_NOTES.md: Claude Code /compact, Codex session.compaction, Antigravity …

    line 93
  3. Very specific:

    If the audited configuration has a version field, Block 3 emits a SemVer hint: PATCH (only SAFE), MINOR (≥ 1 REVIEW), MAJOR (≥ 1 BREAKING).

    line 97
  4. Very specific:

    Never compact a never/must not/do not rule.

    line 103

“Common” is measured: kept by at least 6 in 10 of the 22 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Context Optimization Lifecycle

Audits and plans optimization for an LLM context (system prompt, tool defs, message history, retrieved chunks, tool outputs). Two modes, classified at Phase 0.2: Audit (Phase 0..6 lifecycle → 5-block report) when a session/context is pasted; Guide (catalog lookup §1..§13) when invoked as a knowledge source. Read-only — never auto-applies. Evidence-first: every finding cites a measurable category in the inventory or a configuration line. Zero-findings is a valid LGTM.

When to Use

  • Long-conversation agents (50+ turn sessions; cache miss + tool-output bloat + late compaction).
  • RAG pipelines (top-K stuffing without re-rank, duplicate chunks, prompt-injection via chunk content).
  • Sub-agent orchestrators (parent window blowup, per-child unbounded budgets, cost-tier mis-routing).
  • Large-doc workflows (single-shot > 100k, no caching across runs, output-token cap clipping synthesis).
  • Skill-prompt context (whole-skill payload eats budget on every load).

Trigger: user pastes session/RAG template, statusline shows ≥ 80% utilization, or another skill cross-links @context-optimization.

Do not use when

  • Audit target is a single prompt (clarity, refusal hooks, schema) — use @prompt-engineering.
  • User wants response brevity — out of scope; this skill compresses input (context), not output.
  • User wants project-specific skills or agents generated — use @celebrimbor.
  • Phase 0.5 triage gate fires (trivial context).
  • Domain has stricter compliance than the skill can verify (legal hold, audit trail).

Prerequisites

InputRequiredHow to obtain
Context inventory (categories + sizes)YesUser pastes, or bash scripts/run-all.sh <project> (invokes ctxopt Rust binary)
Use caseYeslong-conv-agent / rag-pipeline / sub-agent-orchestrator / large-doc / skill-prompt
Target harnessNoclaude-code / codex / opencode / antigravity / agnostic — drives §13 plan output
Current utilization (%)NoEstimate via ctxopt count <project> or harness statusline
Known degradation signalNoQuality drop, cost spike, latency — focuses the audit

Skill never sends context to another model. Findings derived from inventory against TECHNIQUES.md catalog.

Phase 0 — Capture & Classify

Capture inventory verbatim (Phase 0.1). Classify mode + use case + harness on three axes (Phase 0.2). Bound against use-case ceiling (Phase 0.3). Honest audit pledge — see CHECKLIST §Skill self-audit (Phase 0.4). Then triage gate:

0.5 Triage gate

Drop the audit when all three hold:

  • Estimated context < 8000 tokens
  • Window utilization < 50%
  • No degradation signal reported

→ emit Block 1 (inventory) + Block 2 row (out of scope: trivial context — audit overhead exceeds value) + stop.

Otherwise, proceed to Phase 1.

Phase 1 — Inventory

Break inventory into five categories (system prompt · tool defs · message history · retrieved chunks · tool outputs) with token estimate per category. Top category > 50% = top-of-mind finding. Evidence-based audit invokes the ctxopt Rust binary (built at install time):

bash scripts/run-all.sh <project_root>
# or directly:
scripts/bin/ctxopt run-all <project_root> --format toon

Outputs out/findings.toon, out/summary.{toon,json}, out/report.md. Detailed checklist: CHECKLIST Phase 1.

Phase 2 — Cost & Quality Audit

Walk cost levers (cache hit rate · dedup ratio · masking opportunity · partition candidates · harness primitive coverage) against the inventory. Each lever absent or weakly applied is a finding with category-cite. Severity per SEVERITY_RUBRIC.md. Heuristic findings start Medium; promotion requires manual confirmation.

Phase 3 — Technique Selection

Walk TECHNIQUES.md §1..§13. Use case dispatches the subset (see TECHNIQUES §How the skill uses):

Use caseRequired techniques
long-conv-agent§1, §2, §3, §4, §6, §9, §13
rag-pipeline§1, §3, §6, §8, §9, §10, §11
sub-agent-orchestrator§1, §7, §9, §11
large-doc§1, §5, §7, §9, §11, §12
skill-promptcross-link @prompt-engineering for single-prompt audit

Common context-bloat smells (quick-detection): see TECHNIQUES §Common context-bloat smells.

Phase 4 — Plan Recommendations

Plan ordered by ROI (highest token-cost or quality-impact first). Canonical skeleton per use case in USE_CASES.md §1–§4. Generic order: cache layer (§1+§9) → compression (§2/§3/§4/§5/§6) → architecture (§7) → RAG-specific (§8/§10) → cost (§11/§12) → harness (§13).

4.1 Harness-specific plan output

When harness ≠ agnostic, Block 3 emits concrete commands per HARNESS_NOTES.md: Claude Code /compact, Codex session.compaction, Antigravity manual UI re-prompt. A plan that says "use compaction" without naming the harness primitive is itself a finding.

4.2 Living-context versioning

If the audited configuration has a version field, Block 3 emits a SemVer hint: PATCH (only SAFE), MINOR (≥ 1 REVIEW), MAJOR (≥ 1 BREAKING). Soft-spec; skips when no version.

Phase 5 — Token Economy

5.1 Compression rules

Never compact a never/must not/do not rule. Never drop a refusal hook during compaction. Never paraphrase citation-bound text (use §6 verbatim deletion). Always dedupe (§10) before compacting (§2). Always preserve verbatim when surviving content is citation-bound. Detailed checklist: CHECKLIST Phase 5.

5.2 Reporting the delta

Estimate before/after token count. Report signed delta + cache hit projection + invariants preserved (safety rules, refusal hooks, citation chunk_ids).

5.3 Token budget per use case

The plan respects a per-use-case ceiling. Excess → finding T-001 Token budget exceeded (REVIEW).

Use caseCeiling (after plan applied)
long-conv-agent≤ 100k tokens (50% Sonnet/Opus 200k window)
rag-pipelinestable prefix ≤ 8k + dynamic ≤ 32k
sub-agent-orchestratorparent ≤ 30k; each child ≤ 30k
large-doc≤ 200k (single-shot, no growth)
skill-prompt≤ 800 tokens (aligns with prompt-engineering 5.3)
Other≤ 50% of model window

User can override with explicit rationale; without override, T-001 fires.

5.4 Cache-friendly ordering

Position stable (system prompt, tool defs, schema, refusal hooks, few-shot) before dynamic (user input, retrieved chunks, conversation history). Anthropic prompt caching reuses prefix tokens with 5min/1h TTL; OpenAI auto-caches prefixes ≥ 1024 tokens. Reordering converts repeated tokens into cache hits — without §9, §1 caches only the leading stable prefix until the first dynamic byte.

Phase 6 — Output

Five-block report. Block 5 conditional (REQUIRED if overall risk = REVIEW or BREAKING; OPTIONAL if SAFE).

BlockContent
1Original context inventory (verbatim, fenced)
2Findings table + per-finding detail (id, severity, confidence, risk, category-cite, fix, technique §N)
3Optimization plan (ordered by ROI; harness-specific commands per HARNESS_NOTES.md when harness ≠ agnostic)
4Summary table (cost lever coverage / token delta / cache-hit projection / risk tag / confidence)
5Verification suggestions

Worked example + verbatim output template: EXAMPLE.md. Zero-findings contract + LGTM rules: CHECKLIST §Skill self-audit.

Constraints

Three load-bearing rules (full 15-rule list in CHECKLIST §Skill self-audit):

RuleWhy
Never apply the plan automaticallyReviewer not optimizer — Block 3 = proposal
Never strip a safety rule from system prompt during compactionnever/must not/do not/refuse if survive every compaction
Always emit Block 1 verbatimInventory contract; second auditor must reach same verdict

Related Skills

  • @prompt-engineering — primary sibling. Audits single prompts; this skill audits whole context. Run @prompt-engineering first to fix the prompt; then /valarmindskills:context-optimization to optimize the surrounding context.
  • @celebrimbor — forges project-specific skills, agents, and tool scripts.
  • @code-security-review — pattern source for scripts/ architecture.

References

  • TECHNIQUES — §1..§13 catalog (cache, compression, architecture, RAG, cost, tool-specific)
  • USE_CASES — canonical skeletons + findings catalogs for the four primary classes
  • CHECKLIST — copy-paste cheat sheet by phase + skill self-audit
  • SEVERITY_RUBRIC — Severity × Category matrix and risk-tag rubric
  • HARNESS_NOTES — Claude Code / Codex / OpenCode / Antigravity primitives
  • EXAMPLE — long-conv-agent worked example with verbatim output template
  • scripts/ — evidence-based audit tools (scripts/README.md)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.