Releases: cortexkit/opencode-magic-context
v0.7.3
v0.7.1
Bug Fixes
- Dreamer re-enqueue loop — Dreamer's own memory mutations (consolidate, verify, improve, archive) set
updated_aton modified memories, which made the next scheduler check think there was new user activity and re-enqueue the project. This caused 4+ dream runs per night instead of 1. Fixed with a 12-hour cooldown:findProjectsNeedingDreamnow skips projects whoselast_dream_atis less than 12 hours old.
v0.7.0
What's New
Experimental: Key File Pinning
Dreamer analyzes which files each session's agent reads most frequently (full reads only, not partial ranges) and pins core orientation files into the system prompt as a <key-files> block. Files are read fresh from disk on each cache-busting pass so edits are always reflected.
Enable with:
"experimental": {
"pin_key_files": {
"enabled": true,
"token_budget": 10000,
"min_reads": 4
}
}Requires dreamer to be enabled. The dreamer uses LLM evaluation to distinguish true orientation files from task-specific reads, with a heuristic fallback when the LLM is unavailable.
Security
- Path traversal guard with
realpathSync()symlink resolution on key-file injection - XML content and attribute escaping using shared utilities
- LLM output filtered against candidate allow-set to prevent hallucinated file pinning
PRAGMA busy_timeout=5000on OpenCode DB readonly connections
Improvements
ctx_notedismiss hint: single footer line instead of per-note boilerplate- Token estimation standardized to
÷3.5ratio across all plugin and TUI estimation sites setKeyFilesensuressession_metarow exists before UPDATE- Compressor same-turn injection refresh after compression
clearInjectionCacheadded at all data-change pointsknapsackFitFilesrenamed togreedyFitFiles(accurate naming)ctx_note updateaction for editing smart note content and conditions
v0.6.2
v0.6.2
Fixes
- FTS full reindex on message removal —
deleteIndexedMessagenow clears all FTS rows and the tracker to avoid ordinal skipping when messages are added after a removal - Memory cache invalidation on all mutation paths —
invalidateAllMemoryBlockCachesnow runs afterupdate,merge, andarchiveactions (was onlywrite/delete) - Stale anchor clearing — sticky turn reminders and note nudges with missing anchors are now cleared on cache-busting passes instead of re-anchored to unrelated messages
- Dashboard tray includes permanent memories — "Run Dreamer" tray action now queries both
activeandpermanentmemories for project identity - Dashboard notes tab count — includes both session notes and smart notes in the tab count
- NaN guard on context percentage — division by zero protection when context limit is 0
- Compaction marker state preserved on removal failure — partial failures no longer orphan OpenCode DB rows
- Migration v1 row count verification — INSERT count checked before DROP TABLE
v0.6.1
Bug Fixes
- Heuristic tool dedup restored —
extractToolInfowas reading tool names fromstate.toolinstead ofpart.tool, so the DEDUP_SAFE_TOOLS deduplication path (mcp_grep, mcp_read, etc.) never fired in production. Fixed to match real OpenCode tool part shape. - Dashboard config path —
resolve_project_config_pathnow checks both<project>/magic-context.jsoncand<project>/.opencode/magic-context.jsonc, so dashboard edits target the correct active config. - Message bus atomicity —
consumeMessagesSELECT+UPDATE now wrapped in a SQLite transaction, preventing duplicate message consumption when TUI and server poll concurrently. "action"message type — added to theMessageTypeunion with proper typing, removing theas nevertype bypass in the TUI action consumer.- Dashboard foreign keys — added
PRAGMA foreign_keys=ONto the dashboard's writable DB connection soON DELETE CASCADEworks correctly (fixes orphanedmemory_embeddingson memory delete). - Dashboard toggle defaults — dreamer, sidekick, and inject_docs toggles now default to
falsematching the schema, instead of showing enabled when the config is unset. - Session cleanup —
clearSessionnow deletesuser_memory_candidatesfor the session, preventing orphaned candidate data from accumulating after session deletion. - Memory count accuracy —
getMemoryCountsByStatusno longer double-counts merged memories as bothmergedandarchived.
443 tests passing.
v0.6.0
What's New
🧪 New Experimental Features
Compaction Markers — after historian compresses older messages, Magic Context injects a boundary into OpenCode's message table. OpenCode's filterCompacted stops at the boundary, so the transform processes only the live tail instead of the full session history. Dramatically reduces per-turn overhead on long sessions. Enable with experimental.compaction_markers: true.
User Memories — historian extracts behavioral observations about the user alongside its normal compartment output (communication style, expertise level, review focus, working patterns). Recurring observations are promoted by the dreamer to stable user memories that appear in all sessions via <user-profile> in the system prompt. Enable with experimental.user_memories.enabled: true (requires dreamer).
Features
- Unified notes —
session_notesandsmart_notesmerged into a singlenotestable with unified ID space.ctx_notegainsupdateaction for editing existing notes.ctx_note readsupportsfilterparam (all, pending, ready, dismissed). - Plugin message bus — SQLite-backed
plugin_messagestable for TUI ↔ server communication. TUI toasts, confirmation dialogs, and action triggers now flow through the bus instead of brittle ignored-message hacks. - Doctor CLI —
bunx @cortexkit/opencode-magic-context doctorauto-fixes plugin registration, TUI config, compaction/DCP/OMO conflicts, and reports missing config. /ctx-recompconfirmation — TUI shows a native confirmation dialog; Desktop uses a double-tap safety gate. Both show compartment count and cost warning before proceeding.- TUI action consumer — server polls for TUI-initiated actions so TUI dialogs can trigger server-side operations without slash command round-trips.
- Version display —
/ctx-statusdialog and TUI sidebar now show the installed version. - Comment-preserving config edits — all JSONC config writes (setup, doctor, conflict fixer) now use
comment-jsonto preserve user comments. - Nested experimental config —
experimental_compaction_markers→experimental.compaction_markersand newexperimental.user_memoriesunder a clean namespace. - JSON Schema —
assets/magic-context.schema.jsonfor editor autocomplete and validation, auto-regenerated on release. - Auto tui.json setup — server plugin auto-adds TUI entry on startup with a one-time notification.
- Startup conflict detection — warns about compaction/DCP/OMO conflicts via toast (TUI) or notification (Desktop).
ctx_searchboundary filter — message history results now exclude ordinals still in the live unsummarized tail.ctx_note update— edit content and/or surface_condition of existing notes.message.removedcleanup — tags, FTS index, note/nudge anchors, stripped-placeholder state all cleaned when messages are reverted.- Historian TC summaries — tool-only assistant turns now emit compact
TC:lines so historian sees what happened during tool-heavy work. - Session token breakdown — dashboard shows proportional bar for System/Compartments/Facts/Memories/Conversation tokens.
Bug Fixes
- Cache-bust fix — decoupled injection cache from scheduler
executedecision.<session-history>is no longer re-rendered from scratch on every turn above the execute threshold; the injection cache is only invalidated when compartments/facts/memories actually change. - Memory sort tiebreaker —
trimMemoriesToBudgetnow usesidas tiebreaker for deterministic cache-stable ordering. - Anchor re-anchoring — sticky turn reminders, assistant nudges, and note nudges now re-anchor to the latest visible message on cache-busting passes when the original anchor falls behind the compaction boundary.
- Migration safety — migration v1 (unified notes) verifies row counts before dropping source tables.
- Compaction marker state — preserved on removal failure so the next update can retry instead of orphaning DB rows.
- Projected reasoning bytes — historian trigger projection now counts
reasoningByteSizeon tool tags for accurate reclaim estimates. - History-budget math —
execute_threshold_percentageresolution now uses live model key in all code paths. - Heuristic cleanup on execute — no longer gated on
hasPendingUserOpswhenctx_reduce_enabled: false. - New session scheduler — sessions with
lastResponseTime=0andcontext=0%return "defer" instead of running pointless execute passes. - Dashboard first-message labeling — correctly identifies the true first message of a session, not the oldest in the display window.
- TUI
src/sharedpackaging —src/sharednow included in npmfilesso TUI imports resolve from published packages.
Internal
- Versioned migration framework (
schema_migrationstable) for safe multi-version schema upgrades plugin_messagestable for cross-process communicationuser_memory_candidatesanduser_memoriestables- 443 tests passing
v0.5.2
v0.5.2
New Features
- TUI Sidebar — Live context breakdown bar in OpenCode's terminal UI showing token usage split across System Prompt, Compartments, Facts, Memories, and Conversation. Includes historian status, memory counts, dreamer last run, and pending queue count. Updates after every message.
- TUI Commands —
/ctx-status,/ctx-flush, and/ctx-augwork directly in TUI mode via dialogs and toasts. - Doctor CLI —
bunx @cortexkit/opencode-magic-context doctorauto-detects and fixes configuration issues: verifies plugin registration, checks for conflicts (compaction, DCP, OMO hooks), ensures TUI sidebar is configured, and adds the plugin entry toopencode.jsonif missing. - Startup Conflict Detection — On startup, the plugin checks for compaction/DCP/OMO conflicts and warns the active session with a fix suggestion.
- Auto tui.json Setup — Server plugin automatically adds the TUI plugin entry to
tui.jsonon startup and notifies the user to restart. - JSON Schema — Published
magic-context.schema.jsonfor editor autocomplete and validation. Setup wizard adds$schemaautomatically.
Improvements
- ctx_search message filter — Message history results now exclude messages still in the live context (not yet compartmentalized), reducing noise from content the agent can already see.
- Comment-preserving config edits — CLI config writes (setup, doctor) now use
comment-jsonto preserve user comments through read-modify-write cycles. - Nudge anchor reset — Rolling nudge positions properly reset after queue execution so they don't drift to unreachable token counts.
- Status dialog —
/ctx-statusin TUI shows full categorized progress bar with per-model config resolution for thresholds and TTL.
Bug Fixes
- Fixed
enabledschema default fromfalsetotrue(zero-config installs no longer silently disabled the plugin). - Fixed
protected_tagsconfig range from 1-20 to 1-100. - Fixed TUI crash when installed from npm —
conflict-fixer.tsno longer importscomment-json(npm dep unavailable in TUI's raw-source runtime). - Fixed doctor issue counting and config filename display.
Documentation
- README: Added TUI Sidebar section, Startup Conflict Detection section, JSON Schema tip,
dream_runsandcompression_depthstorage tables. - CONFIGURATION.md: Added JSON Schema and Doctor sections, fixed
enableddefault andprotected_tagsrange.
| Sidebar | New Status Dialog |
|---|---|
![]() |
![]() |
v0.4.2
Bug Fixes
enablednow defaults totrue— installing the plugin activates it without requiring"enabled": trueinmagic-context.jsonc. Previously defaulted tofalse, which meant users who installed the plugin without a config file got no functionality. The config-parse failure fallback correctly staysenabled: false.
SORRY!
v0.4.1
What's New
Proactive Memory Embedding
Memories are now embedded immediately after ctx_memory write (fire-and-forget) and swept periodically on the dream timer. The first ctx_search after dreamer runs no longer pays bulk embedding latency. The lazy search-time fallback remains as a safety net.
Smarter Compressor Selection
The compressor no longer always picks the oldest compartments for compression. A new weighted scoring system (0.7 × age + 0.3 × inverse compression depth) prevents the earliest compartments from being re-compressed indefinitely while untouched middle history exists. Per-message compression depth is tracked in a new compression_depth table and incremented after each successful pass.
Depth-Aware U: Line Handling
The compressor prompt now adapts based on how many times the selected compartments have been compressed:
- Avg depth < 2: Preserve all
U:lines exactly as-is — compression targets prose only - Avg depth 2–3: Condense each
U:line to its core intent in one sentence - Avg depth 3+: Fold
U:intent into narrative prose — no separateU:lines
This preserves user voice in recent history while allowing graceful degradation in ultra-long sessions.
Bug Fixes
- History budget formula: Was
contextLimit × historyBudgetPercentage, now correctlycontextLimit × executeThreshold × historyBudgetPercentageas originally designed. Withexecute_threshold=40%andhistory_budget=15%, the budget was 150k (wrong) instead of the correct 60k.
v0.4.0
What's New
Configurable Commit Cluster Trigger
Historian can now fire based on commit clusters — distinct work phases where the agent made git commits, separated by meaningful user turns. This captures natural work-unit boundaries even when context pressure is low.
{
"commit_cluster_trigger": {
"enabled": true,
"min_clusters": 3
}
}Default changed from 2 to 3 minimum clusters. Can be disabled entirely to rely only on pressure-based triggers.
Dream Run History
Dreamer now persists structured run history. The dashboard Dreamer page shows per-project run cards with:
- Task breakdown (name, duration, output size, success/failure)
- Smart note evaluation results
- Memory change diffs (written, deleted, archived, merged)
- Expandable detail view with relative timestamps
Bug Fixes
- Heuristics blocked with
ctx_reduce_enabled: false: Whenctx_reducewas disabled, pending ops were always 0, so heuristic cleanup (tool drops, reasoning clearing) never ran on execute passes. Fixed by removing the pending-ops requirement from the heuristic gate — the scheduler already gates execute decisions properly. - Tagger UNIQUE constraint crash: Recovered gracefully from
SQLITE_CONSTRAINT_UNIQUEviolations during tag insertion, which could occur when two plugin instances shared the same DB or after partial batch failures lost in-memory state. - Dashboard "First message" mislabeling: Cache diagnostics no longer labels the oldest event in the 200-event window as "First message (new session)" — it now checks whether earlier assistant messages exist in the DB.
Dashboard Improvements
- Commit cluster trigger toggle + min clusters input in the Historian config section
- Corrected heuristic log message from
pending_ops_executetoscheduler_execute

