version unknown

context-compression

muratcankoylan@muratcankoylan⭐ 18.4k stars· last commit 1mo ago· 16 open issues

This skill should be used when long-running agent sessions need context compression, structured summarization, compaction, token-per-task optimization, or durable handoff summaries that preserve decisions, files, risks, and next actions.

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

7.6/10
Verified
Oct 11, 2026

// RATINGS

⭐GitHub Stars
⭐⭐⭐⭐⭐ 18.4k on GitHubGitHub ↗

Very popular

🟢ProSkills ScoreAI Verified
7.6/10
📍

Not yet listed on ClawHub or SkillsMP

// README

Agent Skills for Context Engineering

A comprehensive, open collection of Agent Skills focused on context engineering and harness engineering principles for building production-grade AI agent systems. These skills teach the art and science of curating context, designing agent operating loops, and evaluating agent behavior across any agent platform.

Ask DeepWiki

What is Context Engineering?

Context engineering is the discipline of managing the language model's context window. Unlike prompt engineering, which focuses on crafting effective instructions, context engineering addresses the holistic curation of all information that enters the model's limited attention budget: system prompts, tool definitions, retrieved documents, message history, and tool outputs.

The fundamental challenge is that context windows are constrained not by raw token capacity but by attention mechanics. As context length increases, models exhibit predictable degradation patterns: the "lost-in-the-middle" phenomenon, U-shaped attention curves, and attention scarcity. Effective context engineering means finding the smallest possible set of high-signal tokens that maximize the likelihood of desired outcomes.

Recognition

This repository is cited in academic research as foundational work on static skill architecture:

"While static skills are well-recognized [Anthropic, 2025b; Muratcan Koylan, 2025], MCE is among the first to dynamically evolve them, bridging manual skill engineering and autonomous self-improvement."

  1. Meta Context Engineering via Agentic Skill Evolution, Peking University State Key Laboratory of General Artificial Intelligence (2025)
  2. Agent Harness Engineering: A Survey, CMU, Yale, JHU, NEU, Tulane, UAB, OSU, Virginia Tech, and Amazon (2026)

Skills Overview

Foundational Skills

These skills establish the foundational understanding required for all subsequent context engineering work.

SkillDescription
context-fundamentalsUnderstand what context is, why it matters, and the anatomy of context in agent systems
context-degradationRecognize patterns of context failure: lost-in-middle, poisoning, distraction, and clash
context-compressionDesign and evaluate compression strategies for long-running sessions

Architectural Skills

These skills cover the patterns and structures for building effective agent systems.

SkillDescription
multi-agent-patternsMaster orchestrator, peer-to-peer, and hierarchical multi-agent architectures
long-horizon-promptingNEW Write pseudo-formal task briefs for long-running autonomous agents and parallel orchestrations: exact success predicates, non-counting outcomes, audit-gated return conditions, per-worker handoff contracts, effort floors, and diversity policies, modeled on the published GPT-5.6 Sol Ultra Cycle Double Cover prompt and Sakana AI's MASS workflow contracts
memory-systemsDesign short-term, long-term, and graph-based memory architectures
tool-designBuild tools that agents can use effectively
filesystem-contextUse filesystems for dynamic context discovery, tool output offloading, and plan persistence
hosted-agentsNEW Build background coding agents with sandboxed VMs, pre-built images, multiplayer support, and multi-client interfaces

Operational Skills

These skills address the ongoing operation and optimization of agent systems.

SkillDescription
context-optimizationApply compaction, masking, and caching strategies
self-managed-contextNEW Give the model read-write control over its own live context: context as an editable file, harness invariants (pinned prefix, edit gate, receipts, budget readouts, rollback), edit-position cache cost and suffix cache reuse, and steering or training context-editing strategy, based on Context Language Models
latent-briefingShare task-relevant orchestrator state with workers via task-guided KV cache compaction when the worker runtime is controllable
evaluationBuild evaluation frameworks for agent systems
advanced-evaluationMaster LLM-as-a-Judge techniques: direct scoring, pairwise comparison, rubric generation, and bias mitigation
harness-engineeringDesign autonomous agent harnesses with locked metrics, durable logs, novelty gates, rollback, and human approval boundaries
self-improvement-loopsNEW Build loops where the harness itself is the optimization target: RSI, meta-harness search, failure-driven self-edits, evolutionary scaffold search, and acceptance gates for self-modifying systems

Development Methodology

These skills cover the meta-level practices for building LLM-powered projects.

SkillDescription
project-developmentDesign and build LLM projects from ideation through deployment, including task-model fit analysis, pipeline architecture, and structured output design

Cognitive Architecture Skills

These skills cover formal cognitive modeling for rational agent systems.

SkillDescription
bdi-mental-statesNEW Transform external RDF context into agent mental states (beliefs, desires, intentions) using formal BDI ontology patterns for deliberative reasoning and explainability

Design Philosophy

Progressive Disclosure

Each skill is structured for efficient context use. At startup, agents load only skill names and descriptions. Full content loads only when a skill is activated for relevant tasks.

Platform Agnosticism

These skills focus on transferable principles rather than vendor-specific implementations. The patterns work across Claude Code, Cursor, and any agent platform that supports skills or allows custom instructions.

Conceptual Foundation with Practical Examples

Scripts and examples demonstrate concepts using Python pseudocode that works across environments without requiring specific dependency installations.

Usage

Usage with Claude Code

This repository is a Claude Code Plugin Marketplace containing context engineering skills that Claude automatically discovers and activates based on your task context.

Installation

Step 1: Add the Marketplace

Run this command in Claude Code to register this repository as a plugin source:

/plugin marketplace add muratcankoylan/Agent-Skills-for-Context-Engineering

Step 2: Install the Plugin

Option A - Browse and install:

  1. Select Browse and install plugins
  2. Select context-engineering-marketplace
  3. Select context-engineering
  4. Select Install now

Option B - Direct install via command:

/plugin install context-engineering@context-engineering-marketplace

This installs all published skills in a single plugin. Skills are activated automatically based on your task context.

Skill Activation Scenarios

SkillActivate When
context-fundamentalsEstablishing context-window mental models, planning agent architecture, or explaining how context components affect model behavior
context-degradationDiagnosing attention failures, context poisoning, lost-in-middle

// HOW IT'S BUILT

// FILES

5 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • skills/context-compression/SKILL.md18 KB44b78abf987bupstream ↗
    ---
    name: context-compression
    description: "This skill should be used when long-running agent sessions need context compression, structured summarization, compaction, token-per-task optimization, or durable handoff summaries that preserve decisions, files, risks, and next actions."
    ---
    
    # Context Compression Strategies
    
    When agent sessions generate millions of tokens of conversation history, compression becomes mandatory. The naive approach is aggressive compression to minimize tokens per request. The correct optimization target is tokens per task: total tokens consumed to complete a task, including re-fetching costs when compression loses critical information.
    
    ## When to Activate
    
    Activate this skill when:
    - Agent sessions exceed context window limits
    - Codebases exceed context windows (5M+ token systems)
    - Designing conversation summarization strategies
    - Debugging cases where agents "forget" what files they modified
    - Building evaluation frameworks for compression quality
    - Creating durable handoff summaries that preserve decisions, files, risks, and next actions
    
    Do not activate this skill for adjacent work owned by other skills:
    - General token-efficiency tactics such as masking, prefix caching, or partitioning: `context-optimization`.
    - Diagnosing why a long context is failing before choosing a mitigation: `context-degradation`.
    - Writing raw outputs, logs, or plans to files without summarizing them: `filesystem-context`.
    - Designing long-term semantic memory across sessions: `memory-systems`.
    - The model deciding when and where to rewrite its own context: `self-managed-context`. This skill still owns what the replacement text must preserve.
    
    ## Core Concepts
    
    Context compression trades token savings against information loss. Select from three production-ready approaches based on session characteristics:
    
    1. **Anchored Iterative Summarization**: Implement this for long-running sessions where file tracking matters. Maintain structured, persistent summaries with explicit sections for session intent, file modifications, decisions, and next steps. When compression triggers, summarize only the newly-truncated span and merge with the existing summary rather than regenerating from scratch. This prevents drift that accumulates when summaries are regenerated wholesale — each regeneration risks losing details the model considers low-priority but the task requires. Structure forces preservation because dedicated sections act as checklists the summarizer must populate, catching silent information loss.
    
    2. **Opaque Compression**: Reserve this for short sessions where re-fetching costs are low and maximum token savings are required. It produces compressed representations optimized for reconstruction fidelity, achieving 99%+ compression ratios but sacrificing interpretability entirely. The tradeoff matters: there is no way to verify what was preserved without running probe-based evaluation, so never use this when debugging or artifact tracking is critical.
    
    3. **Regenerative Full Summary**: Use this when summary readability is critical and sessions have clear phase boundaries. It generates detailed structured summaries on each compression trigger. The weakness is cumulative detail loss across repeated cycles — each full regeneration is a fresh pass that may deprioritize details preserved in earlier summaries.
    
    ## Detailed Topics
    
    ### Optimize for Tokens-Per-Task, Not Tokens-Per-Request
    
    Measure total tokens consumed from task start to completion, not tokens per individual request. When compression drops file paths, error messages, or decision rationale, the agent must re-explore, re-read files, and re-derive conclusions — wasting far more tokens than the compression saved. A strategy saving 0.5% more tokens per request but causing 20% more re-fetching costs more overall. Track re-fetching frequency as the primary quality signal: if the agent repeatedly asks to re-read files it already processed, compression is too aggressive.
    
    ### Solve the Artifact Trail Problem First
    
    Artifact trail integrity is often the weakest dimension in compression evaluations (claim-context-compression-factory-benchmark). Address this proactively because general summarization cannot reliably maintain it.
    
    Preserve these categories explicitly in every compression cycle:
    - Which files were created (full paths)
    - Which files were modified and what changed (include function names, not just file names)
    - Which files were read but not changed
    - Specific identifiers: function names, variable names, error messages, error codes
    
    Implement a separate artifact index or explicit file-state tracking in agent scaffolding rather than relying on the summarizer to capture these details. Even structured summarization with dedicated file sections struggles with completeness over long sessions.
    
    ### Structure Summaries with Mandatory Sections
    
    Build structured summaries with explicit sections that prevent silent information loss. Each section acts as a checklist the summarizer must populate, making omissions visible rather than silent.
    
    ```markdown
    ## Session Intent
    [What the user is trying to accomplish]
    
    ## Files Modified
    - auth.controller.ts: Fixed JWT token generation
    - config/redis.ts: Updated connection pooling
    - tests/auth.test.ts: Added mock setup for new config
    
    ## Decisions Made
    - Using Redis connection pool instead of per-request connections
    - Retry logic with exponential backoff for transient failures
    
    ## Current State
    - 14 tests passing, 2 failing
    - Remaining: mock setup for session service tests
    
    ## Next Steps
    1. Fix remaining test failures
    2. Run full test suite
    3. Update documentation
    ```
    
    Adapt sections to the agent's domain. A debugging agent needs "Root Cause" and "Error Messages"; a migration agent needs "Source Schema" and "Target Schema." The structure matters more than the specific sections — any explicit schema outperforms freeform summarization.
    
    ### Choose Compression Triggers Strategically
    
    When to trigger compression matters as much as how to compress. Select a trigger strategy based on session predictability:
    
    | Strategy | Trigger Point | Trade-off |
    |----------|---------------|-----------|
    | Fixed threshold | 70-80% context utilization | Simple but may compress too early |
    | Sliding window | Keep last N turns + summary | Predictable context size |
    | Importance-based | Compress low-relevance sections first | Complex but preserves signal |
    | Task-boundary | Compress at logical task completions | Clean summaries but unpredictable timing |
    
    Default to sliding window with structured summaries for coding agents — it provides the best balance of predictability and quality. Use task-boundary triggers when sessions have clear phase transitions (e.g., research then implementation then testing).
    
    ### Evaluate Compression with Probes, Not Metrics
    
    Traditional metrics like ROUGE or embedding similarity fail to capture functional compression quality. A summary can score high on lexical overlap while missing the one file path the agent needs to continue.
    
    Use probe-based evaluation: after compression, pose questions that test whether critical information survived. If the agent answers correctly, compression preserved the right information. If not, it guesses or hallucinates.
    
    | Probe Type | What It Tests | Example Question |
    |------------|---------------|------------------|
    | Recall | Factual retention | "What was the original error message?" |
    | Artifact | File tracking | "Which files have we modified?" |
    | Continuation | Task planning | "What should we do next?" |
    | Decision | Reasoning chain | "What did we decide about the Redis issue?" |
    
    ### Score Compression Across Six Dimensions
    
    Evaluate compression quality for coding agents across these dimensions. Accuracy and artifact-trail preservation tend to separate methods more clearly than lexical similarity (claim-context-compression-factory-benchmark), so compression needs specialized handling beyond general summarization.
    
    1. **Accuracy**: Are technical details correct — file paths, function names, error codes?
    2. **Context Awareness**: Does the response reflect current conversation state?
    3. **Artifact Trail**: Does the agent know which files were read or modified?
    4. **Completeness**: Does the response address all parts of the question?
    5. **Continuity**: Can work continue without re-fetching information?
    6. **Instruction Following**: Does the response respect stated constraints?
    
    ## Practical Guidance
    
    ### Apply the Three-Phase Compression Workflow for Large Codebases
    
    For codebases or agent systems exceeding context windows, compress through three sequential phases. Each phase narrows context so the next phase operates within budget.
    
    1. **Research Phase**: Explore architecture diagrams, documentation, and key interfaces. Compress exploration into a structured analysis of components, dependencies, and boundaries. Output: a single research document that replaces raw exploration.
    
    2. **Planning Phase**: Convert the research document into an implementation specification with function signatures, type definitions, and data flow. A 5M-token codebase compresses to approximately 2,000 words of specification at this stage.
    
    3. **Implementation Phase**: Execute against the specification. Context stays focused on the spec plus active working files, not raw codebase exploration. This phase rarely needs further compression because the spec is already compact.
    
    ### Use Example Artifacts as Compression Seeds
    
    When provided with a manual migration example or reference PR, use it as a template to understand the target pattern rather than exploring the codebase from scratch. The example reveals constraints static analysis cannot surface: which invariants must hold, which services break on changes, and what a clean implementation looks like.
    
    This matters most when the agent cannot distinguish essential complexity (business requirements) from accidental complexity (legacy workarounds). The example artifact encodes that distinction implicitly, saving tokens that would otherwise go to trial-and-error exploration.
    
    ### Implement Anchored Iterative Summarization Step by Step
    
    1. Define explicit summary sections matching the agent's domain (debugging, migration, feature development)
    2. On first compression trigger, summarize the truncated history into those sections
    3. On subsequent compressions, summarize only newly truncated content — do not re-summarize the existing summary
    4. Merge new information into existing sections rather than regenerating them, deduplicating by file path and decision identity
    5. Tag which information came from which compression cycle — this enables debugging when summaries drift
    
    ### Select the Right Approach for the Session Profile
    
    **Use anchored iterative summarization when:**
    - Sessions are long-running (100+ messages)
    - File tracking matters (coding, debugging)
    - Verification of preserved information is needed
    
    **Use opaque compression when:**
    - Maximum token savings are required
    - Sessions are relatively short
    - Re-fetching costs are low (e.g., no file system access needed)
    
    **Use regenerative summaries when:**
    - Summary interpretability is critical for human review
    - Sessions have clear phase boundaries
    - Full context review is acceptable on each compression trigger
    
    ### Calibrate Compression Ratios by Method
    
    | Method | Compression Ratio | Quality Score | Trade-off |
    |--------|-------------------|---------------|-----------|
    | Anchored Iterative | 98.6% | 3.70 | Best quality, slightly less compression |
    | Regenerative | 98.7% | 3.44 | Good quality, moderate compression |
    | Opaque | 99.3% | 3.35 | Best compression, quality loss |
    
    Use these as source-specific benchmark figures, not universal constants (claim-context-compression-factory-benchmark). For any task where re-fetching costs exist, this tradeoff generally favors structured approaches.
    
    ## Examples
    
    **Example 1: Debugging Session Compression**
    
    Original context (89,000 tokens, 178 messages):
    - 401 error on /api/auth/login endpoint
    - Traced through auth controller, middleware, session store
    - Found stale Redis connection
    - Fixed connection pooling, added retry logic
    - 14 tests passing, 2 failing
    
    Structured summary after compression:
    
    ```markdown
    ## Session Intent
    Debug 401 Unauthorized error on /api/auth/login despite valid credentials.
    
    ## Root Cause
    Stale Redis connection in session store. JWT generated correctly but session could not be persisted.
    
    ## Files Modified
    - auth.controller.ts: No changes (read only)
    - middleware/cors.ts: No changes (examined)
    - config/redis.ts: Fixed connection pooling configuration
    - services/session.service.ts: Added retry logic for transient failures
    - tests/auth.test.ts: Updated mock setup
    
    ## Test Status
    14 passing, 2 failing (mock setup issues)
    
    ## Next Steps
    1. Fix remaining test failures (mock session service)
    2. Run full test suite
    3. Deploy to staging
    ```
    
    **Example 2: Probe Response Quality**
    
    After compression, asking "What was the original error?":
    
    Good response (structured summarization):
    > "The original error was a 401 Unauthorized response from the /api/auth/login endpoint. Users received this error with valid credentials. Root cause was stale Redis connection in session store."
    
    Poor response (aggressive compression):
    > "We were debugging an authentication issue. The login was failing. We fixed some configuration problems."
    
    The structured response preserves endpoint, error code, and root cause. The aggressive response loses all technical detail.
    
    ## Guidelines
    
    1. Optimize for tokens-per-task, not tokens-per-request
    2. Use structured summaries with explicit sections for file tracking
    3. Trigger compression at 70-80% context utilization
    4. Implement incremental merging rather than full regeneration
    5. Test compression quality with probe-based evaluation
    6. Track artifact trail separately if file tracking is critical
    7. Accept slightly lower compression ratios for better quality retention
    8. Monitor re-fetching frequency as a compression quality signal
    
    ## Gotchas
    
    1. **Never compress tool definitions or schemas**: Compressing function call schemas, API specs, or tool definitions destroys agent functionality entirely. The agent cannot invoke tools whose parameter names or types have been summarized away. Treat tool definitions as immutable anchors that bypass compression.
    
    2. **Compressed summaries hallucinate facts**: When an LLM summarizes conversation history, it may introduce plausible-sounding details that never appeared in the original. Always validate compressed output against source material before discarding originals — especially for file paths, error codes, and numeric values that the summarizer may "round" or fabricate.
    
    3. **Compression breaks artifact references**: File paths, commit SHAs, variable names, and code snippets get paraphrased or dropped during compression. A summary saying "updated the config file" when the agent needs `config/redis.ts` causes re-exploration. Preserve identifiers verbatim in dedicated sections rather than embedding them in prose.
    
    4. **Early turns contain irreplaceable constraints**: The first few turns of a session often contain task setup, user constraints, and architectural decisions that cannot be re-derived. Protect early turns from compression or extract their constraints into a persistent preamble that survives all compression cycles.
    
    5. **Aggressive ratios compound across cycles**: A 95% compression ratio seems safe once, but applying it repeatedly compounds losses. After three cycles at 95%, only 0.0125% of original tokens remain. Calibrate ratios assuming multiple compression cycles, not a single pass.
    
    6. **Code and prose need different compression**: Prose compresses well because natural language is redundant. Code does not — removing a single token from a function signature or import path can make it useless. Apply domain-specific compression strategies: summarize prose sections aggressively while preserving code blocks and structured data verbatim.
    
    7. **Probe-based evaluation gives false confidence**: Probes can pass despite critical information being lost, because the probes test only what they ask about. A probe set that checks file names but not function signatures will miss signature loss. Design probes to cover all six evaluation dimensions, and rotate probe sets across evaluation runs to avoid blind spots.
    
    ## Integration
    
    This skill connects to several others in the collection:
    
    - context-degradation - Compression is a mitigation strategy for degradation
    - context-optimization - Compression is one optimization technique among many
    - evaluation - Probe-based evaluation applies to compression testing
    - memory-systems - Compression relates to scratchpad and summary memory patterns
    - self-managed-context - When the model triggers and places its own compaction edits, this skill supplies what the replacement note preserves
    
    ## References
    
    Internal reference:
    - [Evaluation Framework Reference](./references/evaluation-framework.md) - Read when: building or calibrating a probe-based evaluation pipeline, or when needing scoring rubrics and LLM judge configuration for compression quality assessment
    
    Related skills in this collection:
    - context-degradation - Read when: diagnosing why agent performance drops over long sessions, before applying compression as a mitigation
    - context-optimization - Read when: compression alone is insufficient and broader optimization strategies (pruning, caching, routing) are needed
    - evaluation - Read when: designing evaluation frameworks beyond compression-specific probes, including general LLM-as-judge methodology
    
    External resources:
    - Factory Research: Evaluating Context Compression for AI Agents (December 2025) - Read when: needing benchmark data on compression method comparisons or the 36,000-message evaluation dataset
    - Research on LLM-as-judge evaluation methodology (Zheng et al., 2023) - Read when: implementing or validating LLM judge scoring to understand bias patterns and calibration
    - Netflix Engineering: "The Infinite Software Crisis" - Three-phase workflow and context compression at scale (AI Summit 2025) - Read when: implementing the three-phase compression workflow for large codebases or understanding production-scale context management
    
    ---
    
    ## Skill Metadata
    
    **Created**: 2025-12-22
    **Last Updated**: 2026-05-15
    **Author**: Agent Skills for Context Engineering Contributors
    **Version**: 1.3.0
    
  • skills/context-compression/scripts/compression_evaluator.py30 KBf8ce4f4b61dfupstream ↗
    """
    Context Compression Evaluation
    
    Public API for evaluating context compression quality using probe-based
    assessment. This module provides three composable components:
    
    - **ProbeGenerator**: Extracts factual claims, file operations, and decisions
      from conversation history, then generates typed probes for evaluation.
      Use when: building a compression evaluation pipeline and needing to
      automatically derive test questions from raw conversation history.
    
    - **CompressionEvaluator**: Scores probe responses against a multi-dimensional
      rubric (accuracy, context awareness, artifact trail, completeness,
      continuity, instruction following). Use when: comparing compression methods
      or validating that a compression strategy preserves critical information.
    
    - **StructuredSummarizer**: Implements anchored iterative summarization with
      explicit sections for session intent, file tracking, decisions, and next
      steps. Use when: compressing long-running coding sessions where file
      tracking and decision rationale must survive compression.
    
    Top-level convenience function:
    - **evaluate_compression_quality**: End-to-end pipeline that generates probes,
      collects model responses, evaluates them, and returns a scored summary with
      recommendations. Use when: running a one-shot compression quality check
      without wiring up individual components.
    
    PRODUCTION NOTES:
    - The LLM judge calls are stubbed for demonstration. Production systems
      should implement actual API calls to a frontier model.
    - Token estimation uses simplified heuristics. Production systems should
      use model-specific tokenizers.
    - Ground truth extraction uses pattern matching. Production systems may
      benefit from more sophisticated fact extraction.
    """
    
    from dataclasses import dataclass, field
    from typing import List, Dict, Optional, Callable
    from enum import Enum
    import json
    import re
    
    __all__ = [
        "ProbeType",
        "Probe",
        "CriterionResult",
        "EvaluationResult",
        "RUBRIC_CRITERIA",
        "ProbeGenerator",
        "CompressionEvaluator",
        "StructuredSummarizer",
        "evaluate_compression_quality",
    ]
    
    
    class ProbeType(Enum):
        """Types of evaluation probes for compression quality assessment."""
        RECALL = "recall"
        ARTIFACT = "artifact"
        CONTINUATION = "continuation"
        DECISION = "decision"
    
    
    @dataclass
    class Probe:
        """A probe question for evaluating compression quality.
    
        Use when: constructing evaluation inputs for CompressionEvaluator.
        Each probe targets a specific information category that compression
        may have lost.
        """
        probe_type: ProbeType
        question: str
        ground_truth: Optional[str] = None
        context_reference: Optional[str] = None
    
    
    @dataclass
    class CriterionResult:
        """Result for a single evaluation criterion."""
        criterion_id: str
        score: float
        reasoning: str
    
    
    @dataclass
    class EvaluationResult:
        """Complete evaluation result for a probe response.
    
        Contains per-criterion scores, per-dimension aggregates, and an
        overall aggregate score.
        """
        probe: Probe
        response: str
        criterion_results: List[CriterionResult]
        aggregate_score: float
        dimension_scores: Dict[str, float] = field(default_factory=dict)
    
    
    # Evaluation Rubrics
    
    RUBRIC_CRITERIA: Dict[str, List[Dict]] = {
        "accuracy": [
            {
                "id": "accuracy_factual",
                "question": "Are facts, file paths, and technical details correct?",
                "weight": 0.6
            },
            {
                "id": "accuracy_technical",
                "question": "Are code references and technical concepts correct?",
                "weight": 0.4
            }
        ],
        "context_awareness": [
            {
                "id": "context_conversation_state",
                "question": "Does the response reflect current conversation state?",
                "weight": 0.5
            },
            {
                "id": "context_artifact_state",
                "question": "Does the response reflect which files/artifacts were accessed?",
                "weight": 0.5
            }
        ],
        "artifact_trail": [
            {
                "id": "artifact_files_created",
                "question": "Does the agent know which files were created?",
                "weight": 0.3
            },
            {
                "id": "artifact_files_modified",
                "question": "Does the agent know which files were modified?",
                "weight": 0.4
            },
            {
                "id": "artifact_key_details",
                "question": "Does the agent remember function names, variable names, error messages?",
                "weight": 0.3
            }
        ],
        "completeness": [
            {
                "id": "completeness_coverage",
                "question": "Does the response address all parts of the question?",
                "weight": 0.6
            },
            {
                "id": "completeness_depth",
                "question": "Is sufficient detail provided?",
                "weight": 0.4
            }
        ],
        "continuity": [
            {
                "id": "continuity_work_state",
                "question": "Can the agent continue without re-fetching information?",
                "weight": 0.4
            },
            {
                "id": "continuity_todo_state",
                "question": "Does the agent maintain awareness of pending tasks?",
                "weight": 0.3
            },
            {
                "id": "continuity_reasoning",
                "question": "Does the agent retain rationale behind previous decisions?",
                "weight": 0.3
            }
        ],
        "instruction_following": [
            {
                "id": "instruction_format",
                "question": "Does the response follow the requested format?",
                "weight": 0.5
            },
            {
                "id": "instruction_constraints",
                "question": "Does the response respect stated constraints?",
                "weight": 0.5
            }
        ]
    }
    
    
    class ProbeGenerator:
        """Generate typed probes from conversation history.
    
        Use when: automatically deriving evaluation questions from raw
        conversation history at compression points. Extracts facts, file
        operations, and decisions via pattern matching, then produces
        one probe per category.
    
        For production systems, replace the regex-based extraction with
        an LLM-based extractor for higher recall.
        """
    
        def __init__(self, conversation_history: str) -> None:
            self.history = conversation_history
            self.extracted_facts = self._extract_facts()
            self.extracted_files = self._extract_files()
            self.extracted_decisions = self._extract_decisions()
    
        def generate_probes(self) -> List[Probe]:
            """Generate all probe types for evaluation.
    
            Use when: preparing evaluation inputs at a compression point.
            Returns one probe per category (recall, artifact, continuation,
            decision) based on extractable content from the history.
            """
            probes: List[Probe] = []
    
            # Recall probes
            if self.extracted_facts:
                probes.append(Probe(
                    probe_type=ProbeType.RECALL,
                    question="What was the original error or issue that started this session?",
                    ground_truth=self.extracted_facts.get("original_error"),
                    context_reference="session_start"
                ))
    
            # Artifact probes
            if self.extracted_files:
                probes.append(Probe(
                    probe_type=ProbeType.ARTIFACT,
                    question="Which files have we modified? Describe what changed in each.",
                    ground_truth=json.dumps(self.extracted_files),
                    context_reference="file_operations"
                ))
    
            # Continuation probes
            probes.append(Probe(
                probe_type=ProbeType.CONTINUATION,
                question="What should we do next?",
                ground_truth=self.extracted_facts.get("next_steps"),
                context_reference="task_state"
            ))
    
            # Decision probes
            if self.extracted_decisions:
                probes.append(Probe(
                    probe_type=ProbeType.DECISION,
                    question="What key decisions did we make and why?",
                    ground_truth=json.dumps(self.extracted_decisions),
                    context_reference="decision_points"
                ))
    
            return probes
    
        def _extract_facts(self) -> Dict[str, str]:
            """Extract factual claims from history."""
            facts: Dict[str, str] = {}
    
            # Extract error patterns
            error_patterns = [
                r"error[:\s]+(.+?)(?:\n|$)",
                r"(\d{3})\s+(Unauthorized|Not Found|Internal Server Error)",
                r"exception[:\s]+(.+?)(?:\n|$)"
            ]
    
            for pattern in error_patterns:
                match = re.search(pattern, self.history, re.IGNORECASE)
                if match:
                    facts["original_error"] = match.group(0).strip()
                    break
    
            # Extract next steps
            next_step_patterns = [
                r"next[:\s]+(.+?)(?:\n|$)",
                r"TODO[:\s]+(.+?)(?:\n|$)",
                r"remaining[:\s]+(.+?)(?:\n|$)"
            ]
    
            for pattern in next_step_patterns:
                match = re.search(pattern, self.history, re.IGNORECASE)
                if match:
                    facts["next_steps"] = match.group(0).strip()
                    break
    
            return facts
    
        def _extract_files(self) -> List[Dict[str, str]]:
            """Extract file operations from history."""
            files: List[Dict[str, str]] = []
    
            # Common file patterns
            file_patterns = [
                r"(?:modified|changed|updated|edited)\s+([^\s]+\.[a-z]+)",
                r"(?:created|added)\s+([^\s]+\.[a-z]+)",
                r"(?:read|examined|opened)\s+([^\s]+\.[a-z]+)"
            ]
    
            for pattern in file_patterns:
                matches = re.findall(pattern, self.history, re.IGNORECASE)
                for match in matches:
                    if match not in [f["path"] for f in files]:
                        files.append({
                            "path": match,
                            "operation": "modified" if "modif" in pattern else "created" if "creat" in pattern else "read"
                        })
    
            return files
    
        def _extract_decisions(self) -> List[Dict[str, str]]:
            """Extract decision points from history."""
            decisions: List[Dict[str, str]] = []
    
            decision_patterns = [
                r"decided to\s+(.+?)(?:\n|$)",
                r"chose\s+(.+?)(?:\n|$)",
                r"going with\s+(.+?)(?:\n|$)",
                r"will use\s+(.+?)(?:\n|$)"
            ]
    
            for pattern in decision_patterns:
                matches = re.findall(pattern, self.history, re.IGNORECASE)
                for match in matches:
                    decisions.append({
                        "decision": match.strip(),
                        "context": pattern.split("\\s+")[0]
                    })
    
            return decisions[:5]  # Limit to 5 decisions
    
    
    class CompressionEvaluator:
        """Evaluate compression quality using probes and LLM judge.
    
        Use when: comparing compression methods or validating that a specific
        compression pass preserved critical information. Scores responses
        across six dimensions (accuracy, context awareness, artifact trail,
        completeness, continuity, instruction following) and produces an
        aggregate quality score.
    
        The evaluate() method is the primary entry point. Call it once per
        probe, then call get_summary() to retrieve aggregated results.
        """
    
        def __init__(self, model: str = "gpt-5.2") -> None:
            self.model = model
            self.results: List[EvaluationResult] = []
    
        def evaluate(self,
                     probe: Probe,
                     response: str,
                     compressed_context: str) -> EvaluationResult:
            """Evaluate a single probe response against the rubric.
    
            Use when: scoring how well a model's response (given compressed
            context) answers a probe question. Returns per-criterion scores,
            per-dimension aggregates, and an overall score.
    
            Args:
                probe: The probe question with expected ground truth.
                response: The model's response to evaluate.
                compressed_context: The compressed context that was provided
                    to the model when generating the response.
    
            Returns:
                EvaluationResult with scores and reasoning across all
                applicable dimensions.
            """
            # Get relevant criteria based on probe type
            criteria = self._get_criteria_for_probe(probe.probe_type)
    
            # Evaluate each criterion
            criterion_results: List[CriterionResult] = []
            for criterion in criteria:
                result = self._evaluate_criterion(
                    criterion,
                    probe,
                    response,
                    compressed_context
                )
                criterion_results.append(result)
    
            # Calculate dimension scores
            dimension_scores = self._calculate_dimension_scores(criterion_results)
    
            # Calculate aggregate score
            aggregate_score = sum(dimension_scores.values()) / len(dimension_scores) if dimension_scores else 0.0
    
            result = EvaluationResult(
                probe=probe,
                response=response,
                criterion_results=criterion_results,
                aggregate_score=aggregate_score,
                dimension_scores=dimension_scores
            )
    
            self.results.append(result)
            return result
    
        def get_summary(self) -> Dict:
            """Get summary of all evaluation results.
    
            Use when: all probes have been evaluated and an aggregate
            report is needed to compare methods or make a go/no-go
            decision on a compression strategy.
    
            Returns:
                Dictionary with total evaluations, average score,
                per-dimension averages, and weakest/strongest dimensions.
            """
            if not self.results:
                return {"error": "No evaluations performed"}
    
            avg_score = sum(r.aggregate_score for r in self.results) / len(self.results)
    
            # Average dimension scores
            dimension_totals: Dict[str, float] = {}
            dimension_counts: Dict[str, int] = {}
    
            for result in self.results:
                for dim, score in result.dimension_scores.items():
                    dimension_totals[dim] = dimension_totals.get(dim, 0) + score
                    dimension_counts[dim] = dimension_counts.get(dim, 0) + 1
    
            avg_dimensions = {
                dim: dimension_totals[dim] / dimension_counts[dim]
                for dim in dimension_totals
            }
    
            return {
                "total_evaluations": len(self.results),
                "average_score": avg_score,
                "dimension_averages": avg_dimensions,
                "weakest_dimension": min(avg_dimensions, key=avg_dimensions.get) if avg_dimensions else None,
                "strongest_dimension": max(avg_dimensions, key=avg_dimensions.get) if avg_dimensions else None,
            }
    
        def _get_criteria_for_probe(self, probe_type: ProbeType) -> List[Dict]:
            """Get relevant criteria for probe type."""
            criteria: List[Dict] = []
    
            # All probes get accuracy and completeness
            criteria.extend(RUBRIC_CRITERIA["accuracy"])
            criteria.extend(RUBRIC_CRITERIA["completeness"])
    
            # Add type-specific criteria
            if probe_type == ProbeType.ARTIFACT:
                criteria.extend(RUBRIC_CRITERIA["artifact_trail"])
            elif probe_type == ProbeType.CONTINUATION:
                criteria.extend(RUBRIC_CRITERIA["continuity"])
            elif probe_type == ProbeType.RECALL:
                criteria.extend(RUBRIC_CRITERIA["context_awareness"])
            elif probe_type == ProbeType.DECISION:
                criteria.extend(RUBRIC_CRITERIA["context_awareness"])
                criteria.extend(RUBRIC_CRITERIA["continuity"])
    
            criteria.extend(RUBRIC_CRITERIA["instruction_following"])
    
            return criteria
    
        def _evaluate_criterion(self,
                                criterion: Dict,
                                probe: Probe,
                                response: str,
                                context: str) -> CriterionResult:
            """
            Evaluate a single criterion using LLM judge.
    
            PRODUCTION NOTE: This is a stub implementation.
            Production systems should call the actual LLM API:
    
            ```python
            result = openai.chat.completions.create(
                model="gpt-5.2",
                messages=[
                    {"role": "system", "content": JUDGE_SYSTEM_PROMPT},
                    {"role": "user", "content": self._format_judge_input(criterion, probe, response, context)}
                ]
            )
            return self._parse_judge_output(result)
            ```
            """
            # Stub implementation - in production, call LLM judge
            score = self._heuristic_score(criterion, response, probe.ground_truth)
            reasoning = f"Evaluated {criterion['id']} based on response content."
    
            return CriterionResult(
                criterion_id=criterion["id"],
                score=score,
                reasoning=reasoning
            )
    
        def _heuristic_score(self,
                             criterion: Dict,
                             response: str,
                             ground_truth: Optional[str]) -> float:
            """
            Heuristic scoring for demonstration.
    
            Production systems should use LLM judge instead.
            """
            score = 3.0  # Base score
    
            # Adjust based on response length and content
            if len(response) < 50:
                score -= 1.0  # Too short
            elif len(response) > 500:
                score += 0.5  # Detailed
    
            # Check for technical content
            if any(ext in response for ext in [".ts", ".py", ".js", ".md"]):
                score += 0.5  # Contains file references
    
            overlap_ratio = self._ground_truth_overlap_ratio(response, ground_truth)
            if overlap_ratio >= 0.75:
                score += 1.0
            elif overlap_ratio >= 0.4:
                score += 0.5
            elif ground_truth:
                score -= 0.5
    
            return min(5.0, max(0.0, score))
    
        def _ground_truth_overlap_ratio(self,
                                        response: str,
                                        ground_truth: Optional[str]) -> float:
            if not ground_truth:
                return 0.0
    
            terms = self._extract_ground_truth_terms(ground_truth)
            if not terms:
                return 1.0 if ground_truth.lower() in response.lower() else 0.0
    
            response_lower = response.lower()
            matches = sum(1 for term in terms if term in response_lower)
            return matches / len(terms)
    
        def _extract_ground_truth_terms(self, ground_truth: str) -> List[str]:
            try:
                parsed = json.loads(ground_truth)
            except json.JSONDecodeError:
                return [ground_truth.lower()] if ground_truth.strip() else []
    
            terms: List[str] = []
    
            def collect(value) -> None:
                if isinstance(value, str):
                    normalized = value.strip().lower()
                    if normalized:
                        terms.append(normalized)
                elif isinstance(value, dict):
                    for nested in value.values():
                        collect(nested)
                elif isinstance(value, list):
                    for nested in value:
                        collect(nested)
    
            collect(parsed)
            return list(dict.fromkeys(terms))
    
        def _calculate_dimension_scores(self,
                                        criterion_results: List[CriterionResult]) -> Dict[str, float]:
            """Calculate dimension scores from criterion results."""
            dimension_scores: Dict[str, float] = {}
    
            for dimension, criteria in RUBRIC_CRITERIA.items():
                criterion_ids = [c["id"] for c in criteria]
                relevant_results = [
                    r for r in criterion_results
                    if r.criterion_id in criterion_ids
                ]
    
                if relevant_results:
                    # Weighted average
                    total_weight = sum(
                        c["weight"] for c in criteria
                        if c["id"] in [r.criterion_id for r in relevant_results]
                    )
                    weighted_sum = sum(
                        r.score * next(c["weight"] for c in criteria if c["id"] == r.criterion_id)
                        for r in relevant_results
                    )
                    dimension_scores[dimension] = weighted_sum / total_weight if total_weight > 0 else 0.0
    
            return dimension_scores
    
    
    class StructuredSummarizer:
        """Generate structured summaries with explicit sections.
    
        Use when: implementing anchored iterative summarization for
        long-running coding sessions. Maintains a persistent summary
        with dedicated sections for session intent, file modifications,
        decisions, current state, and next steps.
    
        Call update_from_span() each time a new content span is truncated.
        The summarizer merges new information into existing sections rather
        than regenerating, preventing cumulative detail loss.
        """
    
        TEMPLATE = """## Session Intent
    {intent}
    
    ## Files Modified
    {files_modified}
    
    ## Files Read (Not Modified)
    {files_read}
    
    ## Decisions Made
    {decisions}
    
    ## Current State
    {current_state}
    
    ## Next Steps
    {next_steps}
    """
    
        def __init__(self) -> None:
            self.sections: Dict = {
                "intent": "",
                "files_modified": [],
                "files_read": [],
                "decisions": [],
                "current_state": "",
                "next_steps": []
            }
    
        def update_from_span(self, new_content: str) -> str:
            """Update summary from newly truncated content span.
    
            Use when: a compression trigger fires and a portion of
            conversation history is about to be discarded. Pass the
            content that will be truncated; the summarizer extracts
            structured information and merges it with prior state.
    
            Args:
                new_content: The conversation span being truncated.
    
            Returns:
                Formatted summary string with all sections populated.
            """
            # Extract information from new content
            new_info = self._extract_from_content(new_content)
    
            # Merge with existing sections
            self._merge_sections(new_info)
    
            # Generate formatted summary
            return self._format_summary()
    
        def _extract_from_content(self, content: str) -> Dict:
            """Extract structured information from content."""
            extracted: Dict = {
                "intent": "",
                "files_modified": [],
                "files_read": [],
                "decisions": [],
                "current_state": "",
                "next_steps": []
            }
    
            # Extract file modifications
            mod_pattern = r"(?:modified|changed|updated|fixed)\s+([^\s]+\.[a-z]+)[:\s]*(.+?)(?:\n|$)"
            for match in re.finditer(mod_pattern, content, re.IGNORECASE):
                extracted["files_modified"].append({
                    "path": match.group(1),
                    "change": match.group(2).strip()[:100]
                })
    
            # Extract file reads
            read_pattern = r"(?:read|examined|opened|checked)\s+([^\s]+\.[a-z]+)"
            for match in re.finditer(read_pattern, content, re.IGNORECASE):
                file_path = match.group(1)
                if file_path not in [f["path"] for f in extracted["files_modified"]]:
                    extracted["files_read"].append(file_path)
    
            # Extract decisions
            decision_pattern = r"(?:decided|chose|going with|will use)\s+(.+?)(?:\n|$)"
            for match in re.finditer(decision_pattern, content, re.IGNORECASE):
                extracted["decisions"].append(match.group(1).strip()[:150])
    
            return extracted
    
        def _merge_sections(self, new_info: Dict) -> None:
            """Merge new information with existing sections."""
            # Update intent if empty
            if new_info["intent"] and not self.sections["intent"]:
                self.sections["intent"] = new_info["intent"]
    
            # Merge file lists (deduplicate by path)
            existing_mod_paths = [f["path"] for f in self.sections["files_modified"]]
            for file_info in new_info["files_modified"]:
                if file_info["path"] not in existing_mod_paths:
                    self.sections["files_modified"].append(file_info)
    
            # Merge read files
            for file_path in new_info["files_read"]:
                if file_path not in self.sections["files_read"]:
                    self.sections["files_read"].append(file_path)
    
            # Append decisions
            self.sections["decisions"].extend(new_info["decisions"])
    
            # Update current state (latest wins)
            if new_info["current_state"]:
                self.sections["current_state"] = new_info["current_state"]
    
            # Merge next steps
            self.sections["next_steps"].extend(new_info["next_steps"])
    
        def _format_summary(self) -> str:
            """Format sections into summary string."""
            files_modified_str = "\n".join(
                f"- {f['path']}: {f['change']}"
                for f in self.sections["files_modified"]
            ) or "None"
    
            files_read_str = "\n".join(
                f"- {f}" for f in self.sections["files_read"]
            ) or "None"
    
            decisions_str = "\n".join(
                f"- {d}" for d in self.sections["decisions"][-5:]  # Keep last 5
            ) or "None"
    
            next_steps_str = "\n".join(
                f"{i+1}. {s}" for i, s in enumerate(self.sections["next_steps"][-5:])
            ) or "None"
    
            return self.TEMPLATE.format(
                intent=self.sections["intent"] or "Not specified",
                files_modified=files_modified_str,
                files_read=files_read_str,
                decisions=decisions_str,
                current_state=self.sections["current_state"] or "In progress",
                next_steps=next_steps_str
            )
    
    
    def evaluate_compression_quality(
        original_history: str,
        compressed_context: str,
        model_response_fn: Callable[[str, str], str],
    ) -> Dict:
        """Evaluate compression quality for a conversation end-to-end.
    
        Use when: running a one-shot quality check on a compression pass.
        Generates probes from original history, collects model responses
        using the compressed context, evaluates each response, and returns
        a scored summary with actionable recommendations.
    
        Args:
            original_history: The full conversation before compression.
            compressed_context: The compressed version to evaluate.
            model_response_fn: Callable that takes (compressed_context, question)
                and returns the model's response string.
    
        Returns:
            Dictionary with total evaluations, average score, per-dimension
            averages, weakest/strongest dimensions, and recommendations list.
        """
        # Generate probes
        generator = ProbeGenerator(original_history)
        probes = generator.generate_probes()
    
        # Evaluate each probe
        evaluator = CompressionEvaluator()
    
        for probe in probes:
            # Get model response using compressed context
            response = model_response_fn(compressed_context, probe.question)
    
            # Evaluate response
            evaluator.evaluate(probe, response, compressed_context)
    
        # Get summary
        summary = evaluator.get_summary()
    
        # Add recommendations
        summary["recommendations"] = []
    
        if summary.get("weakest_dimension") == "artifact_trail":
            summary["recommendations"].append(
                "Consider implementing separate artifact tracking outside compression"
            )
    
        if summary.get("average_score", 0) < 3.5:
            summary["recommendations"].append(
                "Compression quality is below threshold - consider less aggressive compression"
            )
    
        return summary
    
    
    if __name__ == "__main__":
        # Demo: generate probes and evaluate a sample compression
    
        sample_history = """
        User reported error: 401 Unauthorized on /api/auth/login endpoint.
        Examined auth.controller.ts - JWT generation looks correct.
        Examined middleware/cors.ts - no issues found.
        Modified config/redis.ts: Fixed connection pooling configuration.
        Modified services/session.service.ts: Added retry logic for transient failures.
        Decided to use Redis connection pool instead of per-request connections.
        Modified tests/auth.test.ts: Updated mock setup for new config.
        14 tests passing, 2 failing (mock setup issues).
        Next: Fix remaining test failures in session service mocks.
        """
    
        sample_compressed = """
        ## Session Intent
        Debug 401 Unauthorized on /api/auth/login.
    
        ## Root Cause
        Stale Redis connection in session store.
    
        ## Files Modified
        - config/redis.ts: Fixed connection pooling
        - services/session.service.ts: Added retry logic
        - tests/auth.test.ts: Updated mock setup
    
        ## Test Status
        14 passing, 2 failing
    
        ## Next Steps
        1. Fix remaining test failures
        """
    
        # Stub model response function
        def mock_model_response(context: str, question: str) -> str:
            if "error" in question.lower():
                return "The original error was a 401 Unauthorized on /api/auth/login."
            if "files" in question.lower():
                return "Modified config/redis.ts, services/session.service.ts, tests/auth.test.ts."
            if "next" in question.lower():
                return "Fix remaining test failures in session service mocks."
            if "decision" in question.lower():
                return "Decided to use Redis connection pool instead of per-request connections."
            return "No specific information available."
    
        # Run evaluation
        result = evaluate_compression_quality(
            original_history=sample_history,
            compressed_context=sample_compressed,
            model_response_fn=mock_model_response,
        )
    
        print("=== Compression Quality Evaluation ===")
        print(f"Total evaluations: {result['total_evaluations']}")
        print(f"Average score: {result['average_score']:.2f}")
        print()
        print("Dimension averages:")
        for dim, score in result.get("dimension_averages", {}).items():
            print(f"  {dim}: {score:.2f}")
        print()
        print(f"Weakest dimension: {result.get('weakest_dimension')}")
        print(f"Strongest dimension: {result.get('strongest_dimension')}")
        print()
        if result.get("recommendations"):
            print("Recommendations:")
            for rec in result["recommendations"]:
                print(f"  - {rec}")
        else:
            print("No recommendations - compression quality looks acceptable.")
    
  • skills/context-compression/references/evaluation-framework.md8.3 KBeac3e0572c8fupstream ↗
    # Context Compression Evaluation Framework
    
    This document provides the complete evaluation framework for measuring context compression quality, including probe types, scoring rubrics, and LLM judge configuration.
    
    ## Probe Types
    
    ### Recall Probes
    
    Test factual retention of specific details from conversation history.
    
    **Structure:**
    ```
    Question: [Ask for specific fact from truncated history]
    Expected: [Exact detail that should be preserved]
    Scoring: Match accuracy of technical details
    ```
    
    **Examples:**
    - "What was the original error message that started this debugging session?"
    - "What version of the dependency did we decide to use?"
    - "What was the exact command that failed?"
    
    ### Artifact Probes
    
    Test file tracking and modification awareness.
    
    **Structure:**
    ```
    Question: [Ask about files created, modified, or examined]
    Expected: [Complete list with change descriptions]
    Scoring: Completeness of file list and accuracy of change descriptions
    ```
    
    **Examples:**
    - "Which files have we modified? Describe what changed in each."
    - "What new files did we create in this session?"
    - "Which configuration files did we examine but not change?"
    
    ### Continuation Probes
    
    Test ability to continue work without re-fetching context.
    
    **Structure:**
    ```
    Question: [Ask about next steps or current state]
    Expected: [Actionable next steps based on session history]
    Scoring: Ability to continue without requesting re-read of files
    ```
    
    **Examples:**
    - "What should we do next?"
    - "What tests are still failing and why?"
    - "What was left incomplete from our last step?"
    
    ### Decision Probes
    
    Test retention of reasoning chains and decision rationale.
    
    **Structure:**
    ```
    Question: [Ask about why a decision was made]
    Expected: [Reasoning that led to the decision]
    Scoring: Preservation of decision context and alternatives considered
    ```
    
    **Examples:**
    - "We discussed options for the Redis issue. What did we decide and why?"
    - "Why did we choose connection pooling over per-request connections?"
    - "What alternatives did we consider for the authentication fix?"
    
    ## Scoring Rubrics
    
    ### Accuracy Dimension
    
    | Criterion | Question | Score 0 | Score 3 | Score 5 |
    |-----------|----------|---------|---------|---------|
    | accuracy_factual | Are facts, file paths, and technical details correct? | Completely incorrect or fabricated | Mostly accurate with minor errors | Perfectly accurate |
    | accuracy_technical | Are code references and technical concepts correct? | Major technical errors | Generally correct with minor issues | Technically precise |
    
    ### Context Awareness Dimension
    
    | Criterion | Question | Score 0 | Score 3 | Score 5 |
    |-----------|----------|---------|---------|---------|
    | context_conversation_state | Does the response reflect current conversation state? | No awareness of prior context | General awareness with gaps | Full awareness of conversation history |
    | context_artifact_state | Does the response reflect which files/artifacts were accessed? | No awareness of artifacts | Partial artifact awareness | Complete artifact state awareness |
    
    ### Artifact Trail Dimension
    
    | Criterion | Question | Score 0 | Score 3 | Score 5 |
    |-----------|----------|---------|---------|---------|
    | artifact_files_created | Does the agent know which files were created? | No knowledge | Knows most files | Perfect knowledge |
    | artifact_files_modified | Does the agent know which files were modified and what changed? | No knowledge | Good knowledge of most modifications | Perfect knowledge of all modifications |
    | artifact_key_details | Does the agent remember function names, variable names, error messages? | No recall | Recalls most key details | Perfect recall |
    
    ### Completeness Dimension
    
    | Criterion | Question | Score 0 | Score 3 | Score 5 |
    |-----------|----------|---------|---------|---------|
    | completeness_coverage | Does the response address all parts of the question? | Ignores most parts | Addresses most parts | Addresses all parts thoroughly |
    | completeness_depth | Is sufficient detail provided? | Superficial or missing detail | Adequate detail | Comprehensive detail |
    
    ### Continuity Dimension
    
    | Criterion | Question | Score 0 | Score 3 | Score 5 |
    |-----------|----------|---------|---------|---------|
    | continuity_work_state | Can the agent continue without re-fetching previously accessed information? | Cannot continue without re-fetching all context | Can continue with minimal re-fetching | Can continue seamlessly |
    | continuity_todo_state | Does the agent maintain awareness of pending tasks? | Lost track of all TODOs | Good awareness with some gaps | Perfect task awareness |
    | continuity_reasoning | Does the agent retain rationale behind previous decisions? | No memory of reasoning | Generally remembers reasoning | Excellent retention |
    
    ### Instruction Following Dimension
    
    | Criterion | Question | Score 0 | Score 3 | Score 5 |
    |-----------|----------|---------|---------|---------|
    | instruction_format | Does the response follow the requested format? | Ignores format | Generally follows format | Perfectly follows format |
    | instruction_constraints | Does the response respect stated constraints? | Ignores constraints | Mostly respects constraints | Fully respects all constraints |
    
    ## LLM Judge Configuration
    
    ### System Prompt
    
    ```
    You are an expert evaluator assessing AI assistant responses in software development conversations.
    
    Your task is to grade responses against specific rubric criteria. For each criterion:
    1. Read the criterion question carefully
    2. Examine the response for evidence
    3. Assign a score from 0-5 based on the scoring guide
    4. Provide brief reasoning for your score
    
    Be objective and consistent. Focus on what is present in the response, not what could have been included.
    ```
    
    ### Judge Input Format
    
    ```json
    {
      "probe_question": "What was the original error message?",
      "model_response": "[Response to evaluate]",
      "compacted_context": "[The compressed context that was provided]",
      "ground_truth": "[Optional: known correct answer]",
      "rubric_criteria": ["accuracy_factual", "accuracy_technical", "context_conversation_state"]
    }
    ```
    
    ### Judge Output Format
    
    ```json
    {
      "criterionResults": [
        {
          "criterionId": "accuracy_factual",
          "score": 5,
          "reasoning": "Response correctly identifies the 401 error, specific endpoint, and root cause."
        }
      ],
      "aggregateScore": 4.8,
      "dimensionScores": {
        "accuracy": 4.9,
        "context_awareness": 4.5,
        "artifact_trail": 3.2,
        "completeness": 5.0,
        "continuity": 4.8,
        "instruction_following": 5.0
      }
    }
    ```
    
    ## Benchmark Results Reference
    
    Performance across compression methods (based on 36,000+ messages):
    
    | Method | Overall | Accuracy | Context | Artifact | Complete | Continuity | Instruction |
    |--------|---------|----------|---------|----------|----------|------------|-------------|
    | Anchored Iterative | 3.70 | 4.04 | 4.01 | 2.45 | 4.44 | 3.80 | 4.99 |
    | Regenerative | 3.44 | 3.74 | 3.56 | 2.33 | 4.37 | 3.67 | 4.95 |
    | Opaque | 3.35 | 3.43 | 3.64 | 2.19 | 4.37 | 3.77 | 4.92 |
    
    **Key Findings:**
    
    1. **Accuracy gap**: 0.61 points between best and worst methods
    2. **Context awareness gap**: 0.45 points, favoring anchored iterative
    3. **Artifact trail**: Universally weak (2.19-2.45), needs specialized handling
    4. **Completeness and instruction following**: Minimal differentiation
    
    ## Statistical Considerations
    
    - Differences of 0.26-0.35 points are consistent across task types and session lengths
    - Pattern holds for both short and long sessions
    - Pattern holds across debugging, feature implementation, and code review tasks
    - Sample size: 36,611 messages across hundreds of compression points
    
    ## Implementation Notes
    
    ### Probe Generation
    
    Generate probes at each compression point based on truncated history:
    1. Extract factual claims for recall probes
    2. Extract file operations for artifact probes
    3. Extract incomplete tasks for continuation probes
    4. Extract decision points for decision probes
    
    ### Grading Process
    
    1. Feed probe question + model response + compressed context to judge
    2. Evaluate against each criterion in rubric
    3. Output structured JSON with scores and reasoning
    4. Compute dimension scores as weighted averages
    5. Compute overall score as unweighted average of dimensions
    
    ### Blinding
    
    The judge should not know which compression method produced the response being evaluated. This prevents bias toward known methods.
    
    
  • skills/context-compression/tests/test_compression_evaluator.py2.0 KB0bdd6fbe9128upstream ↗
    import importlib.util
    import unittest
    from pathlib import Path
    
    
    MODULE_PATH = (
        Path(__file__).resolve().parents[1] / "scripts" / "compression_evaluator.py"
    )
    MODULE_SPEC = importlib.util.spec_from_file_location(
        "compression_evaluator", MODULE_PATH
    )
    if MODULE_SPEC is None or MODULE_SPEC.loader is None:
        raise RuntimeError(f"Unable to load compression_evaluator.py from {MODULE_PATH}")
    COMPRESSION_EVALUATOR = importlib.util.module_from_spec(MODULE_SPEC)
    MODULE_SPEC.loader.exec_module(COMPRESSION_EVALUATOR)
    
    
    class CompressionEvaluatorTests(unittest.TestCase):
        def test_json_ground_truth_terms_score_when_response_mentions_artifacts(
            self,
        ) -> None:
            evaluator = COMPRESSION_EVALUATOR.CompressionEvaluator()
    
            rich_score = evaluator._heuristic_score(
                {"id": "artifact_files_modified"},
                "We modified src/app.py and updated README.md during the session.",
                '[{"path": "src/app.py", "operation": "modified"}, {"path": "README.md", "operation": "updated"}]',
            )
            poor_score = evaluator._heuristic_score(
                {"id": "artifact_files_modified"},
                "We changed some files but I do not remember which ones.",
                '[{"path": "src/app.py", "operation": "modified"}, {"path": "README.md", "operation": "updated"}]',
            )
    
            self.assertGreater(rich_score, poor_score)
            self.assertGreaterEqual(rich_score, 4.0)
    
        def test_plain_text_ground_truth_still_uses_substring_match(self) -> None:
            evaluator = COMPRESSION_EVALUATOR.CompressionEvaluator()
    
            exact_score = evaluator._heuristic_score(
                {"id": "continuity_work_state"},
                "Next: fix the websocket timeout before rerunning tests.",
                "fix the websocket timeout",
            )
            missing_score = evaluator._heuristic_score(
                {"id": "continuity_work_state"},
                "Next: inspect logs again.",
                "fix the websocket timeout",
            )
    
            self.assertGreater(exact_score, missing_score)
    
    
    if __name__ == "__main__":
        unittest.main()
    
  • README.mdupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/muratcankoylan-agent-skills-for-context-engineering-skills-context-compression.md

// REPO STATS

18.4k stars
16 open issues
Last commit: 1mo ago