GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(compaction): Hybrid compaction pipeline with deterministic extraction + LLM by thijs-hakkenberg · Pull Request #7104 · anomalyco/opencode

Conversation

@thijs-hakkenberg

@thijs-hakkenberg thijs-hakkenberg commented Jan 6, 2026

Copy link
Copy Markdown

Description

This PR introduces a novel hybrid compaction approach that significantly improves session continuation quality by combining deterministic extraction with targeted LLM semantic analysis.

Problem

The current compaction implementation uses a generic freeform LLM prompt that often loses critical details:

  • File paths and modifications get omitted or summarized incorrectly
  • Error resolution status is lost
  • Agent context and constraints disappear after compaction
  • No quality validation of compaction output

Solution

A hybrid pipeline that runs sequentially for optimal token efficiency:

┌─────────────────────────────────────────────────────────────┐
│ HYBRID PIPELINE │
├─────────────────────────────────────────────────────────────┤
│ Phase 1: Deterministic Extraction │
│ ├── Files read/modified/created (from tool calls) │
│ ├── Errors detected + resolution status │
│ └── Tool usage summary │
├─────────────────────────────────────────────────────────────┤
│ Phase 2: Context Condensation │
│ └── Build compact representation (~90% token reduction) │
├─────────────────────────────────────────────────────────────┤
│ Phase 3: LLM Extraction (with condensed context) │
│ ├── Session intent │
│ ├── Current state │
│ ├── Key decisions + rationale │
│ ├── Pending tasks │
│ └── Critical context │
├─────────────────────────────────────────────────────────────┤
│ Phase 4: Quality Validation (optional) │
│ └── Score completeness + information retention │
└─────────────────────────────────────────────────────────────┘

Key Features

  • Enabled by default - Works out of the box, no configuration needed
  • Token efficient - Deterministic extraction runs first, LLM receives condensed context instead of full message history
  • Structured output - JSON schema ensures consistent, parseable compaction results
  • Quality validation - Optional threshold-based quality gate with detailed scoring
  • Agent context preservation - Extracts constraints from system prompts to maintain agent personality
  • Backward compatible - Falls back to legacy compaction via config flag

New Files

packages/opencode/src/session/compaction/
├── schema.ts # Zod schemas for structured template
├── extractors.ts # Deterministic file/error/tool extraction
├── llm-extractor.ts # Prompt builder + response parser
├── quality.ts # Completeness & retention scoring
├── pipeline.ts # Pipeline orchestrator
└── index.ts # Module exports

packages/opencode/test/session/
└── compaction-hybrid.test.ts # Comprehensive test suite

Configuration

{
"compaction": {
"hybrid": {
"enabled": true, // default: true
"preserve_agent_context": true, // default: true
"quality_threshold": 0.7 // optional (0-1)
}
}
}

Example Output

Session Compaction

Generated: 2025-01-06T12:00:00.000Z

Session Intent

Implement user authentication with JWT tokens

Artifacts

Files Read

  • /src/auth/middleware.ts
  • /src/config/jwt.ts

Files Modified

  • /src/routes/auth.ts: Added login and logout endpoints

Files Created

  • /src/auth/jwt-service.ts

Tool Usage Summary

  • Read: 5x (5/5 successful)
  • Edit: 3x (3/3 successful)
  • Bash: 2x (2/2 successful)

Decisions Made

  • Use JWT tokens: Stateless authentication, better for horizontal scaling

Current State

Login endpoint complete, working on refresh token implementation

Pending Tasks

  • Add refresh token endpoint
  • Write integration tests

Key Context

Express.js backend with PostgreSQL. User requested no external auth providers.


Compression: 94.2% (50000 → 2900 tokens)

Testing

  • Comprehensive test suite with 50+ test cases
  • Tests for schema validation, extractors, LLM parsing, quality scoring, and full pipeline
  • Developed using TDD (test-driven development)

Breaking Changes

None. Hybrid compaction is additive and enabled by default. Can be disabled via compaction.hybrid.enabled: false.


To run tests locally:
bun test packages/opencode/test/session/compaction-hybrid.test.ts

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
thijshakkenbergecolab and others added 9 commits January 6, 2026 18:38
@thijshakkenbergecolab @claude
feat(compaction): add schema for hybrid compaction template
b656871
- Add CompactionTemplate schema with Zod validation
- Define deterministic sections: artifacts, tool_calls, errors
- Define LLM sections: session_intent, current_state, decisions, pending_tasks, key_context
- Add optional agent_context for preserving agent personality
- Add compression metrics tracking
- Include comprehensive test suite for schema validation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@thijshakkenbergecolab @claude
feat(compaction): add deterministic extractors for files, errors, and…
73f4ef8
… tools

- Add extractFiles() to extract file operations from Read/Edit/Write tools
- Add extractErrors() with pattern matching for common error types
- Add extractToolCalls() to consolidate tool usage statistics
- Add condenseContext() to create LLM-friendly summary
- Track error resolution status based on success indicators
- Comprehensive test coverage for all extractors

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@thijshakkenbergecolab @claude
feat(compaction): add LLM extractor for semantic section extraction
93e7252
- Add buildPrompt() to create efficient extraction prompt
- Add messagesToRecentContext() to convert messages to text with limits
- Add parseResponse() to handle JSON extraction with fallbacks
- Add extractAgentContext() to preserve agent personality/constraints
- Define structured output schema for generateObject integration
- Comprehensive test coverage including edge cases

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@thijshakkenbergecolab @claude
feat(compaction): add quality scorer for compaction validation
8162f98
- Add scoreCompleteness() to validate critical sections are filled
- Add scoreInformationRetention() to check file path preservation
- Add getIssues() to identify specific quality problems
- Add scoreCompaction() combining all quality checks with threshold
- Weighted scoring: 60% completeness, 40% retention
- Comprehensive test coverage for scoring edge cases

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@thijshakkenbergecolab @claude
feat(compaction): add hybrid pipeline orchestrator (TDD)
fd543e8
Implements HybridCompactionPipeline namespace with:
- runDeterministicPhase(): orchestrates extractors, creates condensed context
- estimateTokens(): estimates token count from messages
- assembleTemplate(): combines deterministic + LLM results
- templateToText(): converts template to human-readable format
- buildLLMPrompt(): constructs prompt for LLM extraction
- validateQuality(): runs quality validation with threshold

Key design: Sequential execution where deterministic phase runs FIRST,
creating condensed context that reduces token usage for LLM phase.

Tests added for all pipeline functions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@thijshakkenbergecolab @claude
feat(compaction): integrate hybrid pipeline into main compaction module
b7fa473
Integration changes:
- compaction.ts: Use HybridCompactionPipeline when enabled (default: true)
  - Phase 1: Deterministic extraction (files, errors, tool calls)
  - Phase 2: Build condensed LLM prompt (reduces token usage)
  - Phase 3: Run LLM extraction via processor
  - Phase 4: Optional quality validation with threshold
  - Falls back to legacy compaction if hybrid disabled
- config.ts: Add hybrid compaction config options:
  - enabled: Enable/disable hybrid pipeline (default: true)
  - preserve_agent_context: Preserve agent context (default: true)
  - quality_threshold: Optional quality gate (0-1)
- compaction.txt: Update prompt for structured JSON extraction
- index.ts: Re-export all compaction modules

Key design: Sequential execution - deterministic extraction runs FIRST,
creating condensed context that significantly reduces LLM token usage.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@thijshakkenbergecolab @claude
fix(compaction): improve error pattern matching for specific error types
dc9a429
Fix TypeError detection by:
- Reordering patterns: specific error types (TypeError, ReferenceError, etc.) first
- Capturing the full error including the type name in the message
- Using negative lookbehind to prevent general Error pattern from matching specific types

All 61 tests now pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@thijshakkenbergecolab @claude
feat(benchmark): add compaction benchmark evaluation framework
b420995
Add a new CLI command `opencode benchmark` to compare hybrid vs legacy
compaction methods. Features include:

- BenchmarkMetrics: Type definitions for metrics collection
- BenchmarkRunner: Orchestrates benchmark runs with both methods
- RefactorTask: Complex multi-file refactoring task for testing
- CompactionJudge: LLM-based evaluation of compaction quality
- CLI command with options for task selection, model, and judge

Metrics captured per compaction:
- Input/output tokens and total
- Timing (duration_ms)
- Compression ratio
- Compaction output text (for LLM judgment)

Results are saved to JSON files for analysis.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@thijshakkenbergecolab @claude
feat(benchmark): add standalone runner and real benchmark results
f3379d5
Add run-benchmark.ts for running benchmarks without full CLI dependencies.
Include real benchmark results comparing hybrid vs legacy compaction:

Results with xiaomi/mimo-v2-flash:free:
- Hybrid: 3,327ms, 979 tokens, 55.1% compression
- Legacy: 5,978ms, 1,389 tokens, -2.6% compression
- Token savings: 29.5%
- Time savings: 44.4%
- Winner: HYBRID

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
This was referenced Jan 22, 2026
fix(tui): preserve agent state after compaction #10101
Closed
fix(opencode): accumulate step tokens for compaction #10215
Closed
fix: add prompt caching to session compaction - Issue #10342 #10380
Closed
@thdxr
thdxr force-pushed the dev branch from cbab81f to 2d3c7a0 Compare January 30, 2026 04:50
@opencode-agent
opencode-agent Bot force-pushed the dev branch from 00637c0 to 71e0ba2 Compare January 30, 2026 14:32
@thdxr
thdxr force-pushed the dev branch 3 times, most recently from f1ae801 to 08fa7f7 Compare January 30, 2026 14:37
@github-actions github-actions Bot mentioned this pull request Jan 31, 2026
feat: add experimental compaction prompt and preserve prefix support #11492
Closed
@github-actions github-actions Bot mentioned this pull request Feb 24, 2026
feat(compaction): preserve original user prompt across compaction #14846
Closed
3 tasks done
@github-actions

github-actions Bot commented Mar 8, 2026

Copy link
Copy Markdown
Contributor

Closing this pull request because it has had no updates for more than 60 days. If you plan to continue working on it, feel free to reopen or open a new PR.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions github-actions Bot closed this Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@thijs-hakkenberg @thijshakkenbergecolab
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.