> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch17-system-prompts-and-context-assembly/17.5-context-engine-plugin-system.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 17.5 The Context Engine Plugin System

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~264,000 tokens, Output \~9,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

## 17.5.1 Why a Context Engine

§17.4 showed how **compaction** solves context overflow in long conversations. But that mechanism is fundamentally **reactive trimming**: compaction only begins once the context actually exceeds, or is close to exceeding, what the model can take. It works well, but it assumes message history still lives in the original session structure and that compaction is a remedial action bolted on top.

`v2026.3.9` introduced the **Context Engine** (`src/context-engine/`). This module lifts "how messages are stored, retrieved, assembled, and when they're compacted" out of the runtime flow and turns it into a **pluggable framework**. Developers aren't limited to tuning compaction parameters — they can replace the entire context-management strategy.

The value is immediate. You can sync messages to a database for durability, plug in **vector retrieval** before the model call to select only the most relevant history, or design your own summarization strategy so different message types compact differently. For anyone turning OpenClaw into a research platform or a product substrate, this abstraction layer is essential.

> **Sidebar — pluggable framework**
>
> A pluggable framework means the host program defines a set of stable interfaces and the real implementation can be swapped at runtime. The benefit isn't merely "cleaner code" — it's isolating change at a boundary. Context-management strategy tends to change together with the model, the storage layer, and the retrieval approach; making it a plugin suits long-term evolution far better than hard-coding the logic into the main loop.

## 17.5.2 The ContextEngine Interface

The core is a set of interface methods defined in `src/context-engine/types.ts`. It doesn't expose only a `compact()` — it covers session initialization, message ingestion, context assembly, compaction, and subagent lifecycle.

```ts
// src/context-engine/types.ts (excerpt)
export interface ContextEngine {
  /** Engine identifier and metadata */
  readonly info: ContextEngineInfo;

  /** Initialize engine state for a session, optionally importing historical context. */
  bootstrap?(params: { sessionId: string; sessionFile: string }): Promise<BootstrapResult>;

  /** Ingest a single message into the engine's store. */
  ingest(params: {
    sessionId: string;
    message: AgentMessage;
    isHeartbeat?: boolean;
  }): Promise<IngestResult>;

  /** Ingest a completed turn batch as a single unit. */
  ingestBatch?(params: { ... }): Promise<IngestBatchResult>;

  /** Post-turn lifecycle work: persist canonical context, decide on background compaction. */
  afterTurn?(params: { ... }): Promise<void>;

  /** Assemble model context under a token budget. */
  assemble(params: {
    sessionId: string;
    messages: AgentMessage[];
    tokenBudget?: number;
  }): Promise<AssembleResult>;

  /** Compact context to reduce token usage. */
  compact(params: {
    sessionId: string;
    sessionFile: string;
    tokenBudget?: number;
    force?: boolean;
    currentTokenCount?: number;
    compactionTarget?: "budget" | "threshold";
    customInstructions?: string;
  }): Promise<CompactResult>;
}
```

### Required vs. optional

The interface has a deliberate shape: **only `ingest`, `assemble`, and `compact` are required; everything else is optional.**

| Method             | Required | Purpose                                                  |
| ------------------ | -------- | -------------------------------------------------------- |
| `ingest`           | ✅        | Message goes in                                          |
| `assemble`         | ✅        | Context comes out (under a token budget)                 |
| `compact`          | ✅        | Shrink                                                   |
| `bootstrap`        | —        | Session initialization, optionally importing history     |
| `ingestBatch`      | —        | Whole-turn batch ingestion                               |
| `afterTurn`        | —        | Post-turn hook: persist, decide on background compaction |
| subagent lifecycle | —        | Pre-spawn preparation with a `rollback` handle           |

**In → out → shrink** is the minimum viable set. Everything else is a capability an engine may offer.

> That split is what makes the interface implementable. A required surface with a dozen methods discourages anyone from writing an alternative engine; three required methods means a prototype can be written in an afternoon.

### One flag worth noting

```ts
export type ContextEngineInfo = {
  id: string;
  name: string;
  version?: string;
  /** True when the engine manages its own compaction lifecycle. */
  ownsCompaction?: boolean;
};
```

`ownsCompaction` tells the runtime **"I handle compaction timing myself; don't trigger it for me."**

Without it, an engine doing proactive background compaction would collide with the runtime's overflow-triggered compaction. This is the standard way to hand off control of a lifecycle: **a declared flag, not an implicit convention.**

### The subagent rollback handle

```ts
export type SubagentSpawnPreparation = {
  /** Roll back pre-spawn setup when subagent launch fails. */
  rollback: () => void | Promise<void>;
};
```

An engine that sets up state before a subagent spawns (allocating a namespace, forking a context) must be able to undo it if the spawn fails. Returning a `rollback` closure is cleaner than a separate `cleanupSubagent(id)` method: **the rollback logic sits right next to the setup logic that created the state.**

## 17.5.3 Registration and Resolution

Context engines occupy an **exclusive slot** — unlike tools or hooks, a session has exactly one.

Registration goes through the plugin API's `registerContextEngine` (§21.5.5); resolution lives in `src/context-engine/registry.ts`. The runtime asks the registry for the active engine and falls back to the built-in one if none is registered.

The exclusivity is inherent: two engines both claiming to own "how messages are stored and assembled" would produce two conflicting views of the same session.

## 17.5.4 LegacyContextEngine: Backward Compatibility

`src/context-engine/legacy.ts` wraps the pre-existing behavior — JSONL transcript plus the compaction path from §17.4 — in the `ContextEngine` interface.

This matters for two reasons:

1. **Existing sessions keep working unchanged.** The abstraction was introduced without a data migration.
2. **It's the reference implementation.** Anyone writing a custom engine can read `legacy.ts` to see what a complete, working implementation of the contract looks like.

> Shipping the legacy behavior *as an implementation of the new interface* is the right way to introduce an abstraction layer. The alternative — a new interface alongside an untouched old code path — leaves two systems to maintain and lets the interface drift out of alignment with reality.

## 17.5.5 Runtime Integration

`src/context-engine/init.ts` handles startup wiring. During an agent run:

```
session start        → bootstrap?()      import historical context
message arrives      → ingest()          into the engine's store
before the model call→ assemble()        select context under the token budget
turn completes       → afterTurn?()      persist, decide on background compaction
context pressure     → compact()         shrink
```

Note where `assemble()` sits: **before the model call, not at storage time.** That's what enables retrieval-style engines — a vector-retrieval engine stores everything, then picks only the relevant fragments at assembly time.

## 17.5.6 Writing Your Own Context Engine

The minimum path:

1. **Implement the three required methods** (`ingest` / `assemble` / `compact`);
2. **Declare `info`**, setting `ownsCompaction` if you manage compaction timing yourself;
3. **Register via `registerContextEngine`** in a plugin (see Chapter 21);
4. **Read `legacy.ts`** for the reference implementation of the full contract.

Useful directions to explore:

| Idea                      | What it changes                                                                |
| ------------------------- | ------------------------------------------------------------------------------ |
| Database-backed storage   | Durability and cross-process sharing                                           |
| Vector retrieval assembly | `assemble()` returns only the most relevant history instead of the most recent |
| Typed compaction          | Different summarization for code, decisions, and small talk                    |
| Layered budgets           | Reserve a fixed share for bootstrap files and give the rest to history         |

> A caution: an engine controls **what the model sees**, which makes it a security-relevant component. The review heuristic from §32.5.2 applies — a mechanism that replaces a security-relevant input at runtime is an attack surface. Treat a third-party context engine with the same care as a plugin (§21.5.6).

***

## Section Summary

1. **The Context Engine turns "how messages are stored, retrieved, assembled, and compacted" into a pluggable framework**, going beyond §17.4's reactive compaction to allow replacing the whole strategy.
2. **Only three methods are required** (`ingest` / `assemble` / `compact`) — in, out, shrink. Keeping the required surface small is what makes alternative engines practical to write.
3. **`ownsCompaction` declares lifecycle ownership** so a proactive engine doesn't collide with runtime-triggered compaction — **a declared flag, not an implicit convention**.
4. **The subagent `rollback` handle** keeps undo logic next to the setup that created the state.
5. **The engine slot is exclusive** — two engines owning the same session's storage and assembly would produce conflicting views.
6. **`LegacyContextEngine` wraps existing behavior in the new interface**, so no data migration was needed and the reference implementation stays honest.
7. **`assemble()` runs before the model call, not at storage time** — which is what makes retrieval-style engines possible.
8. A context engine controls what the model sees, so **treat a third-party engine with the same care as a plugin**.

***

> ### 🔬 Going Deeper: 17.6 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**17.6 Source Deep Dive: Four Lines of Context Defense**](https://www.openclawbook.xyz/en/ch17-system-prompts-and-context-assembly/17.6-source-deep-dive-four-lines-of-context-defense.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
