5.4 KiB
5.4 KiB
Implementation Plan: Enhanced Session Compaction System (9 High-Priority Fixes)
Phase 1: Core Foundation (Types & Configuration)
NEW: packages/ui/src/stores/session-compaction.ts
-
Compaction Types & Interfaces
CompactionMessageFlags: summary, mode, provenance flagsStructuredSummary: Tier A/B schema with what_was_done, files, current_state, key_decisions, next_steps, blockers, artifacts, tags, provenanceCompactionEvent: Audit trail with event_id, timestamp, actor, trigger_reason, token_before/after, model_used, cost_estimateCompactionConfig: autoCompactEnabled, autoCompactThreshold, compactPreserveWindow, pruneReclaimThreshold, userPreference, undoRetentionWindowSessionCompactingHook: Plugin contract for domain-specific rules
-
Configuration Store
- Default config: auto=80%, preserve=40k tokens, prune_threshold=20k, preference="ask"
- Export functions:
getCompactionConfig(),updateCompactionConfig()
Phase 2: Overflow Detection Engine
MODIFY: packages/ui/src/stores/session-compaction.ts
-
Token Monitoring Functions
isOverflowDetected(usage, modelLimit): Check if usage >= threshold%shouldPruneToolOutputs(usage): Check if tool outputs > reclaim thresholdestimateTokenReduction(before, after): Calculate % reduction
-
Audit Trail System
recordCompactionEvent(sessionId, event): Append-only to audit loggetCompactionHistory(sessionId): Retrieve audit trailexportAuditLog(): For compliance/debugging
Phase 3: Secrets Detection & Sanitization
NEW: packages/ui/src/lib/secrets-detector.ts
- Secrets Detector
- Pattern matching for: api keys, passwords, tokens, secrets, credentials
redactSecrets(content): Returns { clean: string, redactions: { path, reason }[] }- Placeholder format:
[REDACTED: {reason}]
Phase 4: AI-Powered Compaction Agent
MODIFY: packages/ui/src/stores/session-compaction.ts
-
Compaction Agent Integration
COMPACTION_AGENT_PROMPT: Structured prompt with instructionsgenerateCompactionSummary(instanceId, sessionId, window): Call sendMessage() to get AI summary- Parse response into Tier A (human) and Tier B (structured JSON)
-
Execute Compaction
executeCompaction(instanceId, sessionId, mode): Main compaction orchestration- Steps: enumerate → plugin hooks → AI summary → sanitize → store → prune → audit
- Returns: preview, token estimate, compaction event
Phase 5: Pruning Engine
MODIFY: packages/ui/src/stores/session-compaction.ts
- Sliding Window Pruning
pruneToolOutputs(instanceId, sessionId): Maintain queue, prune oldest > thresholdisToolOutput(part): Classify build logs, test logs, large JSON
Phase 6: Undo & Rehydration
MODIFY: packages/ui/src/stores/session-compaction.ts
- Undo System
undoCompaction(sessionId, compactionEventId): Rehydrate within retention windowgetCompactedSessionSummary(sessionId): Retrieve stored summaryexpandCompactedView(sessionId): Return archived messages
Phase 7: Integration
MODIFY: packages/ui/src/stores/session-events.ts
- Auto-Compact Trigger
- Monitor
EventSessionUpdatedfor token usage - Trigger based on user preference (auto/ask/never)
- Call existing
showConfirmDialog()with compaction preview
MODIFY: packages/ui/src/stores/session-actions.ts
- Replace compactSession
- Use new
executeCompaction()function - Support both "prune" and "compact" modes
Phase 8: Schema Validation
NEW: packages/ui/src/lib/compaction-validation.ts
- Schema Validation
validateStructuredSummary(summary): Zod schema for Tier BvalidateCompactionEvent(event): Zod schema for audit trailValidationErrorstype with path, message, code
Phase 9: CI Tests
NEW: packages/ui/src/stores/session-compaction.test.ts
- Test Coverage
test_overflow_detection: Verify threshold calculationtest_secrets_redaction: Verify patterns are caughttest_compaction_execution: Full compaction flowtest_undo_rehydration: Verify restore workstest_plugin_hooks: Verify custom rules apply
Phase 10: Canary Rollout
MODIFY: packages/ui/src/stores/session-compaction.ts
- Feature Flag
ENABLE_SMART_COMPACTION: Environment variable or config flag- Default:
falsefor canary, set totruefor full rollout - Graceful degradation: fall back to simple compaction if disabled
Implementation Order (Priority)
- P0 - Foundation: Types, config, schema validation (1-2, 12)
- P0 - Core Engine: Overflow detection, secrets detector (3-5)
- P0 - AI Integration: Compaction agent, execute function (6-7)
- P1 - Pruning: Tool output classification, sliding window (8)
- P1 - Undo: Rehydration system (9)
- P1 - Integration: Session events, actions integration (10-11)
- P2 - Tests: CI test coverage (13)
- P2 - Rollout: Feature flag, canary enablement (14)
Success Criteria
- ✅ AI generates meaningful summaries (not just "0 AI responses")
- ✅ Overflow detected before context limit exceeded
- ✅ Secrets are redacted before storage
- ✅ Audit trail tracks every compaction
- ✅ Undo works within retention window
- ✅ Schema validation prevents corrupt data
- ✅ CI tests ensure reliability
- ✅ Canary flag allows safe rollout