/context-preserve

Documentation MANDATORY Production high usage

/context-preserve

Overview

The /context-preserve command implements real-time session context preservation with forensic-grade integrity for the Prismatic Platform. Every development session generates critical knowledge -- decisions made, files modified, problems solved, patterns discovered -- and without systematic preservation, this knowledge evaporates between sessions. Context preservation transforms ephemeral session state into persistent, queryable, and restorable institutional memory.

This command evolved from the Wave 3 documentation excellence initiative, which produced 60KB of forensic-grade session documentation across four specialized squads. That experience demonstrated that comprehensive context preservation achieves 100% session restoration capability, enabling any future session to resume exactly where a previous session ended. The pattern has since been elevated to MANDATORY authority level, making context preservation non-optional for all platform operations.

The command operates under MANDATORY authority and is executed by the context-preservation-specialist agent. It is part of the platform's 216-command slash command registry, built on the AIAD (Autonomous Intelligence Agent Design) standard. Unlike most commands that operate on request, context preservation runs continuously through automatic triggers -- session start, periodic auto-save, phase completion, agent handoff, and session end.

The forensic integrity model ensures that every preserved context is cryptographically sealed, timestamped, and cross-referenced. This creates an immutable audit trail that satisfies both operational continuity requirements and the platform's NO MERCY, NO DOUBTS doctrine, which demands evidence-based decision-making with full provenance tracking.

Architecture

Context Preservation Pipeline

Session Start
    |
    v
LOAD LATEST CONTEXT
    +-- Scan .claude/session-context/
    +-- Identify most recent session file
    +-- Parse restoration instructions
    +-- Validate context integrity
    |
    v
ACTIVE SESSION MONITORING
    +-- Track file modifications
    +-- Record decisions and rationale
    +-- Capture agent handoffs
    +-- Monitor quality gate results
    |
    v
TRIGGER-BASED PRESERVATION
    +-- Auto-save (configurable interval)
    +-- Phase completion snapshots
    +-- Agent handoff transfers
    +-- Error/termination emergency saves
    |
    v
FORENSIC SEALING
    +-- Content hash generation
    +-- Timestamp embedding
    +-- Cross-reference validation
    +-- Integrity verification
    |
    v
PERSISTENT STORAGE
    +-- .claude/session-context/{dated-file}.md
    +-- LATEST_SESSION.md symlink update

Documentation Quality Levels

FormatSizeUse CaseDetail Level
Minimal~1KBEmergency saves, quick checkpointsEssential mission state only
Standard~5KBRegular auto-savesActions, files, decisions
Comprehensive~15KBPhase completions, session endsFull context with rationale
Forensic~30KB+Critical sessions, agent handoffsComplete audit trail with evidence

Usage

Automatic Preservation (Default)

# Auto-save with default settings (30-minute interval, comprehensive format)
/context-preserve

# Configure auto-save interval to 15 minutes
/context-preserve auto --interval 15

# Set minimal format for high-frequency saves
/context-preserve auto --interval 5 --format minimal

Manual Preservation

# Manual comprehensive save at current point
/context-preserve manual --format comprehensive

# Forensic-grade save with full audit trail
/context-preserve manual --format forensic

# Quick checkpoint save with label
/context-preserve manual --format standard --label "pre-refactoring"

Phase and Handoff Preservation

# Save at phase completion
/context-preserve phase-complete --audit-trail true

# Agent handoff with full context transfer
/context-preserve agent-handoff --coordination true

# Emergency save on error detection
/context-preserve error --format comprehensive

Options & Parameters

ParameterTypeRequiredDefaultDescription
triggerstringNoautoTrigger type: auto, manual, phase-complete, agent-handoff, error
--formatenumNocomprehensiveDetail level: minimal, standard, comprehensive, forensic
--intervalintegerNo30Auto-save interval in minutes (5-60)
--coordinationbooleanNotrueEnable cross-agent context coordination
--audit-trailbooleanNotrueInclude forensic audit trail
--labelstringNo--Optional label for checkpoint identification

Execution Flow

/context-preserve [trigger] [options]
    |
    v
PHASE 1: TRIGGER DETECTION (< 50ms)
    +-- Identify preservation trigger type
    +-- Validate authority (MANDATORY level)
    +-- Load current session metadata
    +-- Determine format requirements
    |
    v
PHASE 2: STATE CAPTURE (< 500ms)
    +-- Snapshot current session state
    +-- Collect file modification log
    +-- Record pending decisions and actions
    +-- Gather quality gate results
    +-- Capture agent coordination state
    |
    v
PHASE 3: CONTEXT ASSEMBLY (< 1s)
    +-- Structure content per format template
    +-- Generate restoration instructions
    +-- Build cross-reference links
    +-- Compile deliverables inventory
    +-- Produce next-steps guidance
    |
    v
PHASE 4: FORENSIC SEALING (< 200ms)
    +-- Compute content hash (SHA-256)
    +-- Embed creation timestamp
    +-- Validate cross-references
    +-- Verify content integrity
    |
    v
PHASE 5: PERSISTENCE (< 300ms)
    +-- Write to .claude/session-context/
    +-- Update LATEST_SESSION.md symlink
    +-- Log telemetry event
    +-- Confirm preservation success

Context Content Structure

mandatory_content:
  mission_description: "Complete objectives and scope"
  actions_timeline: "All actions with timestamps"
  files_modified: "Every file changed with purpose"
  deliverables: "All outputs created"
  decisions_made: "Key decisions with rationale"
  verification_results: "All validation outcomes"
  next_steps: "Clear continuation instructions"
  restoration_guide: "Step-by-step restoration"

optional_content:
  quality_metrics: "Quality gate results and scores"
  agent_coordination: "Multi-agent handoff state"
  error_log: "Errors encountered and resolutions"
  performance_data: "Timing and resource usage"

Integration Points

ComponentRelationshipDetails
Prismatic AgentsExecuted by context-preservation-specialistAgent manages all preservation triggers and formatting
AIAD RegistryCommand specification and discoveryMANDATORY authority ensures universal execution
Session LifecycleAutomatic trigger integrationHooks into SessionLifecycle GenServer events
Quality GatesPre/post execution quality validationQuality results captured in every context save
TelemetryEvent tracking[:prismatic_claude, :context_preserve, *] events
Stack ConversationFrame state coordinationPreserves stack frame state for session continuity
Multi-Agent OrchestrationCross-agent context sharingHandoff protocol for seamless agent transitions

Cross-Agent Context Coordination

context_coordination = %{
  shared_state: %{
    mission_objectives: :shared,
    platform_state: :shared,
    quality_metrics: :shared,
    deliverables: :coordinated
  },
  handoff_protocol: %{
    current_agent: "source-agent-id",
    next_agent: "target-agent-id",
    context_transfer: "seamless",
    state_validation: "verified"
  },
  coordination_topics: [
    "mcp:context",
    "mcp:session-state",
    "mcp:agent-handoff"
  ]
}

File System Integration

.claude/session-context/
+-- 2026-01-31-perimeter-mvp-completion-session.md
+-- 2026-01-28-archer-supreme-strategic-analysis-session.md
+-- 2026-01-25-quality-floor-guardian-session.md
+-- LATEST_SESSION.md -> (symlink to most recent)

Naming Convention: YYYY-MM-DD-{agent-or-mission-name}-{unique-identifier}-session.md

Best Practices

  1. Never skip session-end saves -- The MANDATORY authority level exists because lost session context directly impacts platform productivity. Every session must produce a final comprehensive context file.

  2. Use forensic format for critical sessions -- Any session involving production deployments, security operations, or architectural decisions warrants forensic-grade documentation.

  3. Keep auto-save interval proportional to risk -- High-risk operations (data migrations, security fixes) warrant 5-minute intervals. Standard development work is well-served by 30-minute intervals.

  4. Label checkpoints meaningfully -- When using manual checkpoints, include descriptive labels like "pre-database-migration" or "post-security-audit" for rapid identification during restoration.

  5. Validate restoration instructions -- Before ending a session, mentally walk through the restoration guide to ensure a future session can resume without ambiguity.

  6. Coordinate handoffs explicitly -- When transferring work between agents, always trigger an agent-handoff preservation to capture both the outgoing context and the incoming agent's requirements.

Error Handling

ErrorCauseResolution
WRITE_PERMISSION_DENIEDCannot write to session-context directoryCheck filesystem permissions on .claude/session-context/
CONTEXT_CORRUPTIONHash verification failed on loadFall back to previous context file, report corruption
SYMLINK_FAILURECannot update LATEST_SESSION.mdManually update symlink, check filesystem state
INTERVAL_TOO_SHORTAuto-save interval below minimum (5 min)Set interval to at least 5 minutes
COLLISION_DETECTEDParallel sessions writing simultaneouslySession collision detection triggers unique naming
FORMAT_INVALIDUnknown format specifiedUse one of: minimal, standard, comprehensive, forensic

Emergency Preservation

When errors or unexpected termination occur, the system automatically triggers an emergency save:

# Emergency save is automatic, but can be triggered manually
/context-preserve error --format comprehensive

# Recovery from corrupted context
/context-preserve manual --format forensic --label "recovery-after-corruption"

Advanced Usage

Programmatic Context Access

# Access context preservation via GenServer
{:ok, context} = PrismaticClaude.ContextPreservation.save(%{
  trigger: :manual,
  format: :comprehensive,
  label: "api-integration-complete"
})

# Load most recent context
{:ok, latest} = PrismaticClaude.ContextPreservation.load_latest()

# Query context history
{:ok, history} = PrismaticClaude.ContextPreservation.list_contexts(
  since: ~D[2026-01-01],
  format: :forensic
)

Custom Trigger Registration

# Register custom preservation trigger
PrismaticClaude.SessionLifecycle.register_hook(%{
  phase: :post_command,
  priority: 50,
  handler: fn event ->
    if event.command in [:deploy, :migrate] do
      PrismaticClaude.ContextPreservation.save(%{
        trigger: :phase_complete,
        format: :forensic
      })
    end
  end
})

Context Quality Metrics

The Wave 3 documentation excellence established measurable quality benchmarks:

MetricTargetWave 3 Actual
Session restoration capability100%100%
Documentation volume15KB+ per session15KB average
Forensic audit trail coverageCompleteComplete
Startup time acceleration20%+ faster20-30% faster
Cross-reference accuracy100%100%

Doctrine Compliance

All commands operate under the NO MERCY, NO DOUBTS doctrine:

  • NO MERCY: Zero tolerance for incomplete context preservation. Every session must produce restorable context. No session ends without a final save. No agent handoff occurs without context transfer. MANDATORY authority means no exceptions.
  • NO DOUBTS: Full session state investigation before preservation. Context integrity is cryptographically verified. Restoration instructions are validated for completeness. Evidence-based provenance tracking for every decision recorded.

Context preservation directly implements the NABLA axiom of Provenance Mandatory -- all beliefs, decisions, and actions must be traceable to their origin through preserved session context.

  • /chronic - Chronic documentation scan and technical hygiene maintenance
  • /find-lowfruit - Identify low-hanging fruit improvements across codebase
  • /scan-mycelium - Mycelial pattern scanning across documentation and code
  • /doc - Technical documentation and API reference generation
  • /fix - Bug fix implementation with mandatory regression tests
  • /refactor - Safe refactoring with zero-regression guarantee
  • /optimize - Performance optimization with measurement validation

Connect & Contribute

Created by Tomáš Korcak (korczis) | Open Source under GHL