Magic Context Documentation

repository·master·Indexed 23 days ago

https://github.com/cortexkit/magic-context

A long-term memory and context management system for coding agents designed to prevent 'anterograde amnesia' and context compaction pauses. It includes the mc-core cache-stability core, a Tauri-based dashboard for inspecting internal state and diagnostics, and plugins for OpenCode and Pi. The system allows agents to maintain unbounded sessions by capturing, consolidating, and recalling project knowledge in the background via a shared SQLite database.

Tokens
137.8K
Snippets
194
Records
717
Agent score
77%

What's inside Magic Context

  1. What is Magic Context?

    master

    Magic Context is a plugin for OpenCode and Pi (>= 0.74.0) designed to provide coding agents with persistent memory and automated context management. It solves the problem of 'starting from zero' in new sessions by capturing decisions, constraints, and conventions into project memory.

    Core Capabilities

    • Persistent Memory: Project memories persist across different sessions and across both OpenCode and Pi harnesses.
    • Automated Context Management: A background 'historian agent' compresses older conversation parts into tiered compartments without interrupting the user's flow or requiring manual compaction pauses.
    • Full Recall: Instead of discarding old data, Magic Context compresses and indexes it. The agent can expand compressed compartments back to the original transcript or search across memories and git commits.

    Key Agent Tools

    • ctx_expand: Used to expand a compressed compartment back to its original transcript on demand.
    • ctx_search: Allows the agent to search across memories, compressed session history, and indexed git commits in a single call.
  2. Overview of the CortexKit plugin ecosystem

    master

    Magic Context is one of three core plugins in the CortexKit family. These plugins work together using a single shared CortexKit store, allowing memory to be unified across different harnesses and tools.

    PluginRoleFunctionality
    Magic ContextHippocampus & Inner Temporal LobeMan Manages self-contained context and long-term memory; allows sessions to continue without compaction interruptions; captures and recalls project knowledge across sessions.
    AFTSensory & Motor CortexPerceives and interacts with code structures accurately within IDEs and OS environments.
    AlfonsoPrefrontal CortexExecutive control: planning, task decomposition, agent/model selection, and decision-making (when to ask, verify, or commit).
  3. Overview of Magic Context Architecture

    master

    Magic Context is an @opencode-ai/plugin designed to manage long LLM sessions by rewriting message arrays and system prompts. It ensures session history stays within context windows without losing critical information.

    Key architectural features include:

    • Durable SQLite State: Uses a persistent database at ~/.local/share/cortexkit/magic-context/context.db to store session and project-scoped data. It fails closed if storage is unavailable to prevent context overflow.
    • Cache Stability (Replay-everything): To maintain Anthropic prompt cache stability, every message mutation (such as reasoning clearing, structural noise stripping, or compression) is applied deterministically on every transform pass. This ensures wire bytes remain identical across requests.
    • Out-of-band Processing: Heavy LLM work is performed by hidden subagents (historian, historian-editor, dreamer, sidekick) so the main transform pipeline remains lightweight and does not perform LLM calls itself.
    • Multi-Runtime Support: Supports Bun (bun:sqlite), Node (node:sqlite), and Electron. It also features an experimental Rust runtime mode (transform_mode: "rust") for high-performance processing via a subconscious daemon (subc).
  4. The CortexKit Plugin Ecosystem

    master

    CortexKit is a family of plugins designed to function like different regions of a brain. While Magic Context manages memory, other plugins provide different capabilities. All plugins share a common CortexKit store, allowing memories to persist across different harnesses and tools.

    PluginBrain RegionFunction
    Magic ContextHippocampus & Medial Temporal LobeSelf-managed context and long-term memory. Forms and recalls project knowledge.
    AFTSensorimotor CortexUnderstands and operates on code structure; acts as the IDE/OS interface.
    Alfonso (Coming Soon)Prefrontal CortexExecutive control: planning, task decomposition, and decision making.
  5. Understand the Magic Context monorepo structure

    master

    Magic Context is organized as a monorepo containing both TypeScript packages and Rust crates:

    TypeScript Packages (packages/)

    • @cortexkit/opencode-magic-context (packages/plugin/): The core OpenCode plugin.
    • @cortexkit/pi-magic-context (packages/pi-plugin/): The Pi plugin implementation.
    • @cortexkit/magic-context (packages/cli/): The unified CLI for setup, doctor, and migration tasks.
    • @cortexkit/magic-context-dashboard: The Tauri-based dashboard.

    Rust Crates (crates/)

    These provide harness-agnostic core logic that runs under the subc daemon:

    • mc-core: Cache-stability transform and classifier.
    • mc-store: SQLite-backed durable cache-state store.
    • mc-tokenizer: Claude BPE token estimator.
    • mc-module: The subc module (CK-in/CK-out protocol handler).
  6. Understand Magic Context Dashboard features

    master

    The dashboard provides several tools for managing and inspecting Magic Context:

    • Memory Browser: Browse, search, edit, and manage cross-session memories.
    • Session History Viewer: Inspect compartments, facts, notes, and session metadata.
    • Cache Diagnostics: View a real-time cache hit timeline and analyze the causes of cache busts.
    • Dreamer Management: Monitor and trigger dream tasks.
    • Configuration Editor: A visual editor for the magic-context.jsonc configuration file.
    • Log Viewer: A real-time log tail with filtering capabilities and cache hit indicators.
  7. What Magic Context does

    master

    Magic Context provides persistent memory and self-managing context for coding agents. Its core capabilities include:

    • Unbounded sessions: A background 'Historian' condenses old conversations into a compact, tiered history to prevent context walls or lossy compaction pauses.
    • Project memory: Durable facts, rules, and constraints persist across sessions, ensuring new sessions are pre-loaded with project knowledge.
    • Full recall: Agents can search and re-expand original conversations, project memories, and indexed git history.
    • Prompt-cache aware: Context management is engineered around provider prompt caching to optimize costs by minimizing prefix re-billing.
  8. What is the Dreamer agent and how does it run?

    master

    The Dreamer is an optional background agent that performs off-hours maintenance to ensure memory quality and keep project documentation current. It operates by spinning up ephemeral child sessions, each dedicated to a specific maintenance task.

    Execution Model

    • Scheduled Runs: Each task runs on its own independent cron schedule. A process-wide timer checks these schedules and executes due tasks.
    • Manual Triggers: You can trigger tasks manually using CLI commands:
      • /ctx-dream: Runs all enabled tasks immediately.
      • /ctx-dream <task>: Runs one specific task immediately.
    • Concurrency & Safety: Tasks like map-memories, verify, curate, and the primer tasks share a per-project memory lease to prevent collisions. Other tasks run independently. If a task times out, it banks its progress so the next run can continue where it left off.
    • Circuit Breaker: To prevent excessive costs or errors, the Dreamer aborts remaining tasks after three consecutive identical-error failures, marking a circuit-breaker entry in the run history.
  9. Pi-only mechanism: Transform-decision attribution delay

    master

    In Pi, the attribution of a transform decision to a specific message is delayed by one prompt compared to OpenCode.

    Reasoning: Because the AgentMessage has no stable ID and the assistant SessionEntry wrapper hasn't been appended at message_end, Pi records the decision in memory using a snapshot of the newest assistant entry ID seen at the start of the pass. The decision is then resolved at the start of the next context pass by finding the newest SessionEntry.id. This means the final turn's decision is written during the subsequent prompt.

  10. Maintain memory with the Dreamer agent

    master

    The dreamer is an optional agent that runs during inactivity (e.g., overnight) to maintain high-quality memory. It performs several tasks:

    • Verify: Checks memories against current code to correct or remove obsolete facts.
    • Curate: Merges duplicates and archives low-value entries.
    • Classify: Scores importance and scope of memories.
    • Maintain Documents: Updates ARCHITECTURE.md and STRUCTURE.md based on code changes.
    • User Memories: Promotes observations about your work style to a <user-profile>.
    • Smart Notes: Evaluates deferred notes based on surface_condition.

    You can trigger a manual maintenance run using the /ctx-dream command.

  11. Understand Transform Pass mechanics and lifecycle

    master

    The core of the system is the transform pass, which is an invocation of experimental.chat.messages.transform. This process is executed once per LLM round-trip (per step within a turn) and is wrapped defensively to ensure that if a transient SQLITE_BUSY error occurs, the messages are returned unmodified so the prompt loop can proceed.

    Pass Lifecycle Order

    1. Resolve usage + scheduler decision: Determine if the pass should execute or defer.
    2. Emergency overflow recovery: Triggered if usage is $\ge 95%$.
    3. Compartment trigger check: Checks the in-memory args.messages tail. If eligible, the historian is fired asynchronously.
    4. Prepare compartment injection: Decides on m[0]/m[1] materialization.
    5. Tag messages: Replays dropped-status, caveman, reasoning, placeholder, and image strips.
    6. Compartment phase: Injects the <session-history> (m[0]/m[1]) into message[0].
    7. Postprocess: Executes mutation gates (pending-op drain, heuristic cleanup, nudges, synthetic-todowrite, auto-search) via transform-postprocess-phase.ts.
    experimental.chat.messages.transform
  12. How Magic Context manages context and history

    master

    Magic Context provides an 'infinite session' experience by managing the context window in the background, preventing the need for manual compaction pauses. Key mechanisms include:

    • Historian Compartmentalization: A background process that compresses raw history into layered compartments (chronological summaries). Each compartment has an importance score to keep the active window small without losing context. This can run on cheaper or local models.
    • Decay Rendering: Uses deterministic rules (no LLM required) to show compartments with the necessary precision based on the model's context window. Old history fades smoothly rather than being abruptly dropped.
    • Agent-driven Reduction: When enabled, the agent can call ctx_reduce to mark old tool outputs or long messages for deletion. These are queued and applied in cache-safe moments to avoid invalidating the prefix prompt cache.
    • Cache-stable Compaction: Designed so that background work never invalidates the cached prefix prompt, preserving cache efficiency throughout the session.
    • Caveman Text Compression (Optional/Disabled by default): A deterministic age-based rule that progressively compresses the oldest user and assistant text when agent-driven reduction is disabled.