---
## What is Magic Context?
You don't hire a developer to fix one bug and fire them the moment it ships. You keep the good ones. They learn the codebase, remember why decisions were made, and get sharper every week.
Coding agents work the opposite way. Every task is a fresh hire with no memory of your project, and at the end of each session you fire them and start from zero. Mid-task they even hit "compaction" pauses that break the flow and quietly drop what they knew. It is anterograde amnesia, the same thing that happens when the hippocampus is damaged.
Magic Context gives them one. It is the **hippocampus** for coding agents, the part of the brain that forms memories, consolidates them, and recalls them, entirely in the background. One session stops being a disposable contractor and becomes a long-term teammate who was there for the whole project:
- **Capture.** As the historian compresses your history, it lifts the durable knowledge (decisions, constraints, conventions) into project memory. You get a memory system for free, from work you are already doing.
- **Consolidate.** Overnight, dreamer agents do what sleep does for you: verify memories against the codebase, curate duplicates and stale entries, and promote what recurs.
- **Recall.** The right memories surface automatically every turn, and the agent can search across memories, past conversations, and git history on demand. Across sessions, and across OpenCode, Pi, and OMP.
Two promises: your agent **never stops to manage its context** (no compaction pauses, no broken flow) and it **never forgets**.
Run one session per project and keep it going for weeks, months, or years. It remembers everything you've built together.
---
## Quick start
Run the interactive setup wizard. It detects your models, configures everything, and handles compatibility.
**macOS / Linux:**
```bash
curl -fsSL https://raw.githubusercontent.com/cortexkit/magic-context/master/scripts/install.sh | bash
```
**Windows (PowerShell):**
```powershell
irm https://raw.githubusercontent.com/cortexkit/magic-context/master/scripts/install.ps1 | iex
```
**Or run directly (any OS):**
```bash
npx @cortexkit/magic-context@latest setup
```
The wizard auto-detects which harnesses you have (OpenCode, Pi, OMP, or any combination), adds the plugin, disables built-in compaction, helps you pick models for the historian and dreamer, and resolves conflicts with other context-management plugins. Target one with `--harness opencode`, `--harness pi`, or `--harness omp`.
> **Why disable built-in compaction?** Magic Context manages context itself. The host's compaction would interfere with its cache-aware deferred operations and double-compress.
### Manual setup (OpenCode)
If you cannot run the wizard, add this to `opencode.jsonc`:
```jsonc
{
"plugin": ["@cortexkit/opencode-magic-context@latest"],
"compaction": { "auto": false, "prune": false }
}
```
> **Plugin updates:** A bare plugin entry is pinned to the downloaded exact version before restart so OpenCode does not remove the active package mid-session. Magic Context records the exact spec written by its updater and advances that updater-owned pin on later checks. Any other exact spec is treated as pinned by you and is not changed. Because provenance is keyed to the exact spec string, manually changing the entry to the same spec the updater last wrote is indistinguishable from the updater's pin and will be advanced. To opt out, set `auto_update: false` or pin any other exact version. To deliberately stay unpinned, write `@latest` explicitly (OpenCode may remove an unpinned active package mid-session).
Then create `magic-context.jsonc` with the OpenCode historian setting:
```jsonc
{
"$schema": "https://raw.githubusercontent.com/cortexkit/magic-context/master/assets/magic-context.schema.json",
"historian": {
"opencode": { "model": "provider/model-id" }
}
}
```
- **Required:** `historian.opencode.model` must be a real `provider/model-id`. Without it, the plugin loads but historian runs fail, older history is not summarized, and repeated failures show a `Magic Context — history comparting needs attention` notice.
- **Optional:** the `dreamer` model/disable block. Omit it to leave periodic memory consolidation off.
- **Optional:** `embedding`. Omit it to use the local `Xenova/all-MiniLM-L6-v2`; turning embeddings off removes semantic/embedding-backed search, but keyword search and context management continue.
### Flat model-config migration (before/after)
Existing flat model settings migrate automatically on the first config read. The
flat form below is shown only as a migration **before** example; write the
per-harness **after** form for all new configuration.
**Before (flat shape — migration only):**
```jsonc
{
"historian": {
"model": "provider/model-id",
"thinking_level": "medium"
}
}
```
**After (per-harness shape):**
```jsonc
{
"historian": {
"opencode": { "model": "provider/model-id" },
"pi": {
"model": "provider/model-id",
"thinking_level": "medium"
},
"omp": {
"model": "opencode/provider-model-id",
"thinking_level": "auto"
}
}
}
```
OMP uses Pi-native `thinking_level` qualifiers. If `historian.omp` or `dreamer.omp` is absent, OMP falls back to the matching `pi` block, so existing Pi-compatible configurations need no migration. An explicit OMP block is authoritative even when it omits a model.
User-level config is `~/.config/cortexkit/magic-context.jsonc` on macOS/Linux and `%USERPROFILE%\.config\cortexkit\magic-context.jsonc` on Windows (or `$XDG_CONFIG_HOME/cortexkit/magic-context.jsonc` when set). OpenCode Desktop users can use the dashboard's config editor or hand-edit that file; Desktop does not include the CLI setup wizard.
**Pi:** `npx @cortexkit/magic-context@latest setup --harness pi` (requires Pi `>= 0.74.0`). The Pi extension shares the same database as OpenCode; project memories and embeddings pool across both.
**Oh My Pi (OMP):** `npx @cortexkit/magic-context@latest setup --harness omp` (requires OMP `>= 17.1.7`). Setup installs the Pi-compatible extension through `omp plugin`, disables OMP native compaction and automatic memory, and honors OMP profiles, `PI_CODING_AGENT_DIR`, and initialized XDG layouts.
**Troubleshooting:** `npx @cortexkit/magic-context@latest doctor` auto-detects your harnesses, checks host-specific conflicts, verifies plugin registration and database integrity, and fixes what it can. Add `--issue` to file a ready-to-submit bug report.
Works the same on a brand-new or a long-running project: install, restart the harness, and Magic Context captures context from that point forward. It does not backfill OpenCode, Pi, or OMP sessions from before it was installed.
Compatibility with other context-management plugins
Magic Context owns context management end to end, so it **disables itself** if another plugin is already doing that job. Running two context managers at once would double-compress your history and thrash the prompt cache. On startup it checks for the following; setup and `doctor` help you resolve each, and until they're resolved Magic Context stays off (fail-safe) and tells you why:
- **OpenCode built-in compaction** (`compaction.auto` / `compaction.prune`) — Magic Context replaces it. Setup turns it off.
- **OMP native compaction** (`compaction.enabled`) — Magic Context replaces it. OMP setup turns it off transactionally.
- **OMP automatic memory** (`memory.backend`) — a second memory injector duplicates recall and retention. OMP setup sets it to `off`; existing data is not deleted.
- **DCP** (`opencode-dcp`) — a separate context-pruning plugin. The two cannot run together; remove it from your `plugin` list.
- **oh-my-opencode (OMO)** — setup offers to disable the three hooks that overlap:
- `preemptive-compaction` — triggers compaction that conflicts with the historian.
- `context-window-monitor` — injects usage warnings that overlap with Magic Context's nudges.
- `anthropic-context-window-limit-recovery` — triggers emergency compaction that bypasses the historian.
Run `npx @cortexkit/magic-context@latest doctor` any time to re-check and auto-fix.
---
## Part of CortexKit
A brain isn't one organ. Neither is a capable coding agent.
**CortexKit** is a family of plugins, each modeled on a different region of the brain. Install one and your agent gets sharper. Install all three and it has a brain.
| Plugin | Region | What it does |
|---|---|---|
| **Magic Context** *(you are here)* | Hippocampus & medial temporal lobe | Self-managing context and long-term memory. Keeps sessions running with no compaction pauses while it forms, consolidates, and recalls project knowledge across them. |
| **[AFT](https://github.com/cortexkit/aft)** | Sensorimotor cortex | Perceives code structure and acts on it precisely. A proper IDE and OS for your agent. |
| **Alfonso** *(coming soon)* | Prefrontal cortex | Executive control. Plans, decomposes work, chooses agents and models, and decides when to ask, verify, and commit. |
Magic Context is **1 of the 3 plugins you'll ever need.** It remembers; AFT perceives and acts; Alfonso decides. They share one CortexKit store, so memory pools across harnesses and tools.
---
## ⚡ Context management
*An unbounded session that manages itself.* The context window fills up as you work, and the usual fix, compaction, stops the agent cold to re-read everything. Magic Context handles it continuously in the background, so the session just keeps going.
- **Historian compartmentalization**: a background historian compresses old raw history into **tiered compartments**, chronological summaries that stand in for older messages. Each carries an importance score, so the live window stays small without losing the thread. Summarizing doesn't need your primary's coding muscle, so you can run the historian on a cheap or even fully local model while your main agent stays top-tier.
- **Decay rendering**: compartments render at the right fidelity for the moment, by a deterministic, no-LLM rule that self-tunes to the model's context window. Old history fades gracefully instead of dropping off a cliff, and because it is deterministic, the same history always renders the same way.
- **The agent hints what to drop, or it doesn't**: with agent-driven reduction on, the agent calls `ctx_reduce` to mark stale tool outputs or long messages for removal. Drops are **queued and cache-aware**, applied only at cache-safe moments so reduction never thrashes the cache. Switch it off and the agent stays out of context management entirely: stale output is shed automatically by age, with optional caveman compression of the oldest text.
- **Cache-stable layout**: all of this is structured so background work never invalidates the cached prefix of your prompt. Your cache survives the whole session.
The result: one session runs for months, with no compaction pauses and low cost on cache-priced providers. You can watch it happen in OpenCode's TUI, where a live sidebar shows the context breakdown by source, historian status, and memory counts, updating after every message.
> *Optional (off by default):* **caveman text compression** progressively compresses the oldest user and assistant text by a deterministic age-tiered rule, for sessions that run with agent-driven reduction off.
---
## 🧠 Capture
*Memory, for free.* To compress your history, the historian has to read all of it. So in the same pass it lifts out the knowledge worth keeping forever, decisions, constraints, conventions, config values, and promotes it into **project memory**, categorized and carried into every future session. Your memory builds itself from the work you are already doing.
The agent can also record memories explicitly, though most are captured automatically for it:
- **`ctx_memory`**: write or delete cross-session knowledge directly, in a small category taxonomy (`PROJECT_RULES`, `ARCHITECTURE`, `CONSTRAINTS`, `CONFIG_VALUES`, `NAMING`).
```
ctx_memory(action="write", category="ARCHITECTURE", content="Event sourcing for orders.")
```
> **Temporal awareness** *(on by default)* gives the agent a sense of time, with gap markers like `+2h 15m` between messages and dated compartments, so it can reason about how long ago something happened. Set `temporal_awareness: false` to turn it off.
---
## 🌙 Consolidate
*What sleep does for memory.* An optional **dreamer** agent runs overnight to keep memory quality high, spinning up ephemeral child sessions for each task:
- **Map memories**: map each memory to the project files that back it (or mark it file-independent), so verify knows what to re-check. Mostly a one-time backfill.
- **Verify**: incrementally check memories against the current codebase (paths, configs, patterns) and fix/remove stale facts.
- **Verify broad**: re-verify the entire file-mapped pool against code, ignoring the change gate, to catch drift the incremental pass can't see.
- **Curate**: scan the whole memory pool to merge duplicates, tighten wording, and archive low-value or redundant entries.
- **Classify**: score each memory's importance, scope, and safe shareability without disturbing the live prompt cache.
- **Retrospective**: learn from moments you had to correct or re-explain, and record the durable lesson.
- **Maintain docs**: keep `ARCHITECTURE.md` and `STRUCTURE.md` current from codebase changes.
- **User memories**: promote recurring observations about how you work (communication style, review focus, working patterns) into a `` that travels with every session.
- **Promote primers**: promote recurring standing questions the historian noticed into durable primers.
- **Refresh primers**: re-investigate stale primers against current code and refresh their answers.
- **Smart notes**: evaluate deferred notes whose `surface_condition` has come true and surface the ready ones.
Because it runs during idle time, the dreamer pairs well with local models, even slow ones. Nobody is waiting. Trigger a run any time with `/ctx-dream`.
---
## 🔎 Recall
*The right memory at the right moment.* Every turn, active project memories and the compacted session history are injected automatically and cache-stably. On demand, the agent reaches for:
- **`ctx_search`**: one query across project **memories**, raw **conversation** history, indexed **git commits**, parked **notes**, and promoted **primers**. Semantic embeddings with full-text fallback.
```
ctx_search(query="why did we pick event sourcing for orders")
```
- **`ctx_expand`**: pull a compressed history range back to the original `U:`/`A:` transcript when the agent needs the exact details.
- **`ctx_note`**: a scratchpad for deferred intentions. Notes resurface at natural boundaries (after commits, after historian runs, when todos finish). **Smart notes** carry an open-ended condition the dreamer watches for.
Recall works **across sessions** (a new session inherits everything) and **across harnesses** (write a memory in OpenCode, retrieve it in Pi or OMP).
> **Auto search hints** *(on by default)* run a background `ctx_search` each turn and whisper a "vague recall" when something relevant exists — like almost remembering a note you took. It appends only compact fragments, never full content; set `memory.auto_search.enabled: false` to turn it off. **Git commit indexing** *(opt-in)* makes your project history semantically searchable as an additional `ctx_search` source — enable with `memory.git_commit_indexing.enabled: true`.
### Agent tools at a glance
| Tool | Section | What it does |
|------|-------|-------------|
| `ctx_reduce` | Context | Queue stale tagged content for removal, cache-aware |
| `ctx_memory` | Capture | Write or delete durable cross-session memories |
| `ctx_search` | Recall | Search memories, conversation history, git commits, notes, and primers |
| `ctx_expand` | Recall | Decompress a history range back to the transcript |
| `ctx_note` | Recall | Deferred intentions and dreamer-evaluated smart notes |
---
## Commands
| Command | Description |
|---------|-------------|
| `/ctx-status` | Debug view: tags, pending drops, cache TTL, nudge state, historian progress, compartment coverage, history budget |
| `/ctx-flush` | Force all queued operations immediately, bypassing cache TTL |
| `/ctx-recomp` | Rebuild compartments from raw history (accepts a `start-end` range). Use when stored state seems wrong |
| `/ctx-wrapup [messages_to_keep]` | Compact older live history while keeping the newest N messages raw; queued compaction materializes on the next model message |
| `/ctx-dream` | Run dreamer maintenance on demand: maintain memory, docs, smart notes, and user-profile review |
| `/ctx-embed` | Embedding status, or start/pause history compartment embedding (`start` \| `pause`) |
---
## Desktop app
A companion desktop app for browsing and managing Magic Context state outside the terminal.
- **Memory browser**: search, filter, and edit project memories by category and project.
- **Session history**: browse compartments and notes for any session with timeline navigation.
- **Cache diagnostics**: real-time cache hit/miss timeline and bust-cause detection.
- **Dreamer management**: view dream-run history, trigger runs, inspect task results.
- **Configuration editor**: form-based editing for every setting, including model fallback chains.
- **Log viewer**: live-tailing logs with search.
It reads directly from Magic Context's SQLite database. No extra server, no API. Auto-updates built in.
---
## Configuration
Settings live in `magic-context.jsonc`. Most settings have sensible defaults, but the active harness's historian model (`historian.opencode.model`, `historian.pi.model`, or `historian.omp.model`) is required for history compacting; project config merges on top of user-wide settings. For the full reference — cache TTL tuning, per-model execute thresholds, historian and dreamer model selection, embedding providers, memory settings, and prompt-surface presets (`full`/`light`) — see **[CONFIGURATION.md](./CONFIGURATION.md)** or the **[configuration reference on docs.cortexkit.io](https://docs.cortexkit.io/magic-context/reference/configuration/)**.
> **Note on per-model settings:** `prompt_surface.models` always routes the injected guidance block. OpenCode 1.x, Pi, and OMP register tool descriptions once per process (they follow `prompt_surface.default`). OpenCode 2 rewrites the five `ctx_*` descriptions per request from the draft model.
**Config locations** (one shared CortexKit location, project overrides user):
1. `/.cortexkit/magic-context.jsonc`
2. `~/.config/cortexkit/magic-context.jsonc`
Upgrading from an earlier version? Your existing config is moved here automatically on first run (a `.MOVED_READPLEASE` breadcrumb is left at the old path).
### Work and personal repository model profiles
If your personal repositories use one hidden-agent model set and work repositories use another, define the profiles in user config and let each work repository select its name:
```jsonc
// ~/.config/cortexkit/magic-context.jsonc
{
"profile": "personal",
"profiles": {
"personal": { "historian": { "opencode": { "model": "anthropic/claude-sonnet-4-6" } } },
"work": { "historian": { "opencode": { "model": "openai/gpt-5.2-codex" } } }
}
}
// /.cortexkit/magic-context.jsonc
{ "profile": "work" }
```
This is the work-repositories-versus-personal-repositories setup requested by kagbodji. Profiles overlay only hidden-agent model selection, preserve base settings that they do not mention, and are defined only in user config. A project can select a known user profile but cannot supply its contents. See [CONFIGURATION.md](./CONFIGURATION.md#per-repository-model-profiles) for the full OpenCode/Pi/OMP example, fallback behavior, and trust boundary.
---
## Storage
All durable state lives in a local SQLite database under the shared CortexKit store (`~/.local/share/cortexkit/magic-context/context.db`, XDG-equivalent on Windows; legacy OpenCode-folder databases are migrated forward on first boot). Set `MAGIC_CONTEXT_STORAGE_DIR` to an absolute, complete Magic Context storage directory when a host isolates `XDG_DATA_HOME`; the explicit path takes precedence over the XDG-derived path. Every process sharing the store must receive the same explicit value. Hosts propagate this variable when explicitly configured but Magic Context never originates it from its own default resolution. The override moves the harness-side database only; the per-user `subc` daemon state remains in its own shared location. Mixed-version processes continue to block migrations on a shared directory until all processes are updated. If the database can't be opened, Magic Context disables itself and notifies you. Memories are keyed to a **stable project identity** derived from the repo, so they follow a project across worktrees, clones, and forks rather than being tied to a directory path.
Magic Context also writes to a few other locations:
| Path | What | Persistence |
|---|---|---|
| `~/.local/share/cortexkit/magic-context/context.db` | SQLite database — tags, compartments, memories, all durable state (XDG-equivalent on Windows) | **Must persist.** Losing it loses your memory/history. |
| `~/.local/share/cortexkit/magic-context/models/` | Local embedding model cache (~90 MB `Xenova/all-MiniLM-L6-v2` ONNX), downloaded on first use when local embeddings are enabled | Should persist, else re-downloaded each run. Not used when `embedding.provider` is `"off"` or an `openai_compatible`/`ollama` embedding backend is configured. (`memory.enabled: false` does not avoid it: session history is still embedded.) |
| `$MAGIC_CONTEXT_LOG_PATH` (default: `${TMPDIR}/opencode/magic-context/magic-context.log`, `pi/` for Pi) | Diagnostic log. Set `MAGIC_CONTEXT_LOG_PATH` to redirect it (e.g. to a persistent path in a container). | Disposable. |
**Sandboxed / ephemeral environments (Docker, CI, disposable containers):** mount the `~/.local/share/cortexkit/magic-context/` directory on a persistent volume so the database and model cache survive between runs. If only the model cache is ephemeral, the model is simply re-downloaded; if the database is ephemeral, memory and history don't accumulate. To avoid the ~90 MB model download entirely, set `embedding.provider: "off"` or point `embedding` at a remote `openai_compatible`/`ollama` backend.
---
## Star History
---
## Development
**Requirements:** [Bun](https://bun.sh) ≥ 1.4.0
Bun 1.3.x has module-evaluation and resolver error-shape differences that can turn unrelated contributor changes into noisy parallel-test and build failures (issues [#445](https://github.com/cortexkit/magic-context/issues/445) and [#446](https://github.com/cortexkit/magic-context/issues/446)). Repository gates run a version preflight so unsupported Bun releases fail with the required version instead of unrelated test errors.
```sh
bun install # Install dependencies
bun run build # Build the plugin
bun run typecheck # Type-check without emitting
bun test # Run tests
bun run lint # Lint (Biome)
bun run format # Format (Biome)
```
Dream execution requires a live OpenCode server (the dreamer creates ephemeral child sessions). Use `/ctx-dream` inside OpenCode for on-demand maintenance.
### Mutation catalogue
A passing safety test proves little until it has been seen to fail. [`mutations.toml`](mutations.toml) is the checked-in catalogue: each row deliberately breaks one guard in production code and names the test that must fail because of it, so a guard cannot quietly stop guarding. A row earns its place by guarding a silent, costly failure: a prompt-cache bust, a refusal that must fail closed, a wire contract, crash safety, data loss, file permissions. Every exactly-once guard (a lease, a compare-and-set clear) has at least one row through the real production path. Style and cosmetics do not get rows.
The pinned [`ck-mutate`](https://github.com/cortexkit/commons/tree/7d08e73722fa3e79bbcc2607753978ab768f1c6b/crates/cortexkit-mutate) runner replays it from a clean tree: it checks that each named test passes, applies the break, requires the test to fail, and restores the source byte for byte.
```sh
cargo install --locked --git https://github.com/cortexkit/commons --rev 7d08e73722fa3e79bbcc2607753978ab768f1c6b cortexkit-mutate
bun install --frozen-lockfile
ck-mutate check # anchors match exactly once; cargo test names exist
ck-mutate run --all # every row (slow: the Rust rows rebuild mc-module)
ck-mutate run --diff origin/master # only the rows a change touches
ck-mutate run --only ts-schema-fence-refuses-newer-database
```
Every row must report CAUGHT. [`mutations.yml`](.github/workflows/mutations.yml) replays the rows a pull request (or a `train/**` push) touches, the full catalogue on every push to master, and the full catalogue with `--broad` nightly. Never `git checkout` a file while a replay runs: it removes the mutation and fakes a survivor.
To add a row:
1. Pick the production line that *is* the guard and copy `old` from the file, never from memory. Make `new` the smallest edit that removes the protection (`if (false)`, `return true`, a dropped condition), not an edit that breaks compilation.
2. Find the test that should catch it. Apply the edit by hand, run that test file, and confirm the test goes red for the guarded reason, then restore the file. If nothing goes red, that is a finding: add the missing test first, in its own commit.
3. Add the row. Bun tests are `command` rows: copy an existing row and set `expect_red` to the anchored `-t` regex of the full test name (describe names and test name joined by spaces, regex metacharacters escaped, each space written `\s`). Rust tests in mc-module are `command` rows running `cargo test --lib -- --exact`; small Rust targets are `cargo` rows with `only = true`. Add `expect_message` (a substring, or `/regex/`) whenever the test could also fail for an unrelated reason.
4. Run `ck-mutate check`, then `ck-mutate run --only `, and commit the row only once it reports CAUGHT.
A row that stops being caught is a finding to fix, not a row to delete.
---
### Cache-bust sentinel
`packages/plugin/scripts/cache-bust-sentinel.ts` audits recent OpenCode and Pi/OMP provider requests for cache busts that are not explained by Magic Context's fold, refresh, reduction, flush, force-band, or provider/system-prompt contracts. It joins each provider request to MC's nearest pass record from 30 seconds before through five seconds after the request from `transform_decisions`/`scheduler_history` in `context.db` and the rust-mode `mc_pass_trace`/decision mirror in `store.db`; requests without a matching pass are reported as `no_mc_pass_row`. It opens both databases, OpenCode's database, auth-plugin dumps, Pi/OMP JSONL, and `.pi/pi-llm-debugging`/served-array artifacts read-only. Its only local write is the high-water/dedup state file at `~/.local/share/cortexkit/magic-context/cache-bust-sentinel-state.json` (or the resolved `MAGIC_CONTEXT_STORAGE_DIR`).
Run a single dry pass from the repository root; each new unaccounted bust window is printed as one JSON line:
```sh
bun packages/plugin/scripts/cache-bust-sentinel.ts --once
```
Omit `--once` for the built-in one-minute loop, or invoke `--once` from cron/launchd every 1–5 minutes. The template at `packages/plugin/scripts/launchd/com.cortexkit.magic-context.cache-bust-sentinel.plist` uses a five-minute cadence, enables `--send`, deliberately has `RunAtLoad=false`, and is not installed automatically. Replace its `__BUN_PATH__`, `__REPO_ROOT__`, and `__LOG_DIR__` placeholders before loading it. A cron equivalent is:
```cron
*/5 * * * * cd /path/to/magic-context && /path/to/bun packages/plugin/scripts/cache-bust-sentinel.ts --once --send >> /path/to/cache-bust-sentinel.jsonl 2>> /path/to/cache-bust-sentinel.log
```
`--send` switches from JSON-line dry-run output to the `prefrontal-core` module's `agent.deliver` subc operation. It sends a high-urgency registry peer message to `agent_b613e5cf2ee55b8c` from the rendered name `mc-cache-bust-sentinel` by default; the request also stamps the sender as session `health-sentinel-mc` on harness `magic-context`. Use `--wake-agent-id` or `--wake-from-agent` to select another target or rendered sender name. Delivered and queued dispositions are counted as accepted, while a repeated committed order for the same delivery id is counted as deduplicated; sender refusals are counted without retrying the delivery id, and malformed replies or idempotency conflicts fail the run. Use `--connection-file`, `--wake-module-id`, `--wake-agent-id`, `--wake-from-agent`, `--state-file`, `--db`, or `--rust-store` only when the corresponding runtime location is non-default.
### Transform latency sentinel
`packages/plugin/scripts/transform-latency-sentinel.ts` monitors OpenCode and Pi Magic Context logs and the dated `ck-mc` module log read-only. Every invocation consumes at most 4 MiB of **new bytes per file**; inode/size watermarks handle rotation and incomplete trailing lines are retried. Its only persistent write is `transform-latency-sentinel-state.json` in the Magic Context storage directory. Per-session alerts cover a p90 above 5 seconds over ten passes within ten minutes, any pass above 12 seconds, transport/module/state-sync timeouts, Rust park transitions, refusals, and sustained module-time climbs over at least twenty passes. Repeats of the same kind require a 50% severity increase or six hours. Alerts carry session ID, peer-roster name (when available, otherwise `session_projects` project identity), pass p50/p90/max, module and plugin medians, and load average. `loadSampledAt` records when load was sampled: historical replay cannot reconstruct historical machine load.
Dry run without delivery: `bun packages/plugin/scripts/transform-latency-sentinel.ts --once`. For historical investigation use `--replay --since 2026-09-28T17:00:00Z --until 2026-09-28T18:15:00Z`; replay reads in 4 MiB chunks without writing a watermark or sending alerts. `--send` delivers one high-urgency peer message per invocation using `agent.deliver`. The five-minute launchd template at `packages/plugin/scripts/launchd/com.cortexkit.magic-context.transform-latency-sentinel.plist` uses `--once --send` and `RunAtLoad=false`; like the other sentinels it is not installed automatically. Replace `__BUN_PATH__`, `__REPO_ROOT__`, and `__LOG_DIR__` with the bun executable, repository root and log directory before bootstrapping it as a LaunchAgent. Use `--opencode-log`, `--pi-log`, `--module-log`, `--db`, `--peer-db`, `--state-file`, and `--connection-file` for non-default locations.
### Dreamer and historian failure sentinel
`packages/plugin/scripts/subagent-failure-sentinel.ts` reads completed `subagent_invocations` from `context.db` with a read-only SQLite connection and a three-second busy timeout. It treats `failed` and `timed_out` as failures; `empty` and `aborted` are separate counts. It reports a previously unseen (subagent, task, normalised error) class over seven days, a task with at least eight runs and a failure share of at least 25% over 24 hours, or a class whose count doubled against the preceding 24 hours. Errors have volatile IDs, numbers, durations, and paths folded into stable classes. Each five-minute run scans at most 501 new and 5,001 recent history rows (including boundary probes); incomplete history suppresses rules whose full window cannot be assessed. Its only local write is the watermark/dedup file `subagent-failure-sentinel-state.json` in the Magic Context storage directory. The watermark resumes by `(ended_at, id)`; a wake is suppressed for six hours unless its class count grows by 50%. It logs run start and summary, including rows examined and whether the scan was bounded. One wake per run lists each rule, task, class, class count, failure share, example error, newest session ID, and empty/aborted counts.
A dry run uses `bun packages/plugin/scripts/subagent-failure-sentinel.ts --once`; use `--db` and `--state-file` to select a fixture database and state file. Without `--once` it loops every minute. The launchd template `packages/plugin/scripts/launchd/com.cortexkit.magic-context.subagent-failure-sentinel.plist` runs every five minutes with `--once --send`, `RunAtLoad=false`, and separate JSONL/stdout and stderr logs. `--send` uses the same high-urgency `prefrontal-core` `agent.deliver` peer message to the Magic Context head as the cache-bust sentinel. To install and activate it on macOS, run **from the repository root** (this does not happen automatically):
```sh
mkdir -p "$HOME/Library/LaunchAgents" "$HOME/Library/Logs/cortexkit"
sed -e "s|__BUN_PATH__|$(command -v bun)|g" \
-e "s|__REPO_ROOT__|$(pwd -P)|g" \
-e "s|__LOG_DIR__|$HOME/Library/Logs/cortexkit|g" \
packages/plugin/scripts/launchd/com.cortexkit.magic-context.subagent-failure-sentinel.plist \
> "$HOME/Library/LaunchAgents/com.cortexkit.magic-context.subagent-failure-sentinel.plist"
launchctl bootstrap "gui/$(id -u)" "$HOME/Library/LaunchAgents/com.cortexkit.magic-context.subagent-failure-sentinel.plist"
```
---
## Contributing
Bug reports and pull requests are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) for the approved-issue and harness-coverage rules before starting.
---
## License
[MIT](LICENSE)