> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wednesdayai.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Compaction

# Context Window & Compaction

Every model has a **context window** (max tokens it can see). Long-running chats accumulate messages and tool results; once the window is tight, WednesdayAI **compacts** older history to stay within limits.

## What compaction is

Compaction **summarizes older conversation** into a compact summary entry and keeps recent messages intact. The summary is stored in the session history, so future requests use:

* The compaction summary
* Recent messages after the compaction point

Compaction **appends** its summary to SQL session history; it does not rewrite or delete earlier entries.

## Configuration

Use the `agents.defaults.compaction` object in your `openclaw.json` to control compaction behavior.

### Fields

| Field | Type | Default | Description |
| - | - | - | - |
| `enabled` | boolean | `true` | Master switch. Set to `false` to skip both safeguard and direct compaction entirely. |
| `mode` | `"default"` \| `"safeguard"` | `"safeguard"` | Compaction strategy. `"safeguard"` applies stricter guardrails to preserve recent context. |
| `reserveTokens` | number | — | Token headroom reserved for reply generation after compaction. |
| `keepRecentTokens` | number | — | Minimum token budget preserved from the most recent conversation window. |
| `reserveTokensFloor` | number | — | Minimum floor enforced for `reserveTokens` in the Pi compaction path (0 disables). |
| `maxHistoryShare` | number (0.1–0.9) | `0.5` | Maximum fraction of the context budget allowed for retained history. |
| `identifierPolicy` | `"strict"` \| `"off"` \| `"custom"` | `"strict"` | Controls whether compaction summaries include opaque-identifier preservation instructions. `"strict"` prepends built-in guidance, `"off"` omits it, `"custom"` uses `identifierInstructions`. |
| `identifierInstructions` | string | — | Custom preservation text used when `identifierPolicy` is `"custom"`. |
| `summaryTimeoutMs` | number | `300000` | `safeguard` mode: per-call timeout (ms) for each summarization request. A stalled provider stream cancels the compaction instead of holding the run until its timeout. Raise it for slow local models. |
| `memoryFlush.enabled` | boolean | `true` | Run a silent pre-compaction memory flush turn before heavy context reduction. |
| `memoryFlush.softThresholdTokens` | number | — | How close to the compaction threshold (in tokens) to trigger the flush. |
| `memoryFlush.forceFlushTranscriptBytes` | number \| string | — | Force flush when serialized conversation entries in SQL reach this size (e.g. `"2mb"`). Set to `0` to disable. |
| `memoryFlush.prompt` | string | — | Custom user-prompt for the memory flush turn. |
| `memoryFlush.systemPrompt` | string | — | System-prompt override for the memory flush turn. |

### Examples

Disable compaction entirely:

```json5 theme={"dark"}
{
  agents: {
    defaults: {
      compaction: { enabled: false },
    },
  },
}
```

Switch identifier preservation off:

```json5 theme={"dark"}
{
  agents: {
    defaults: {
      compaction: { identifierPolicy: "off" },
    },
  },
}
```

Provide custom identifier preservation instructions:

```json5 theme={"dark"}
{
  agents: {
    defaults: {
      compaction: {
        identifierPolicy: "custom",
        identifierInstructions: "Preserve all ticket IDs (e.g. PROJ-1234) and branch names exactly as written.",
      },
    },
  },
}
```

## Auto-compaction (default on)

When a session nears or exceeds the model’s context window, WednesdayAI triggers auto-compaction and may retry the original request using the compacted context.

You’ll see:

* `🧹 Auto-compaction complete` in verbose mode
* `/status` showing `🧹 Compactions: <count>`

Before compaction, WednesdayAI can run a **silent memory flush** turn to store
durable notes to disk. See [Memory](https://docs.wednesdayai.dev/next/developers/concepts/memory.md) for details and config.

The memory-flush size check reads a stored byte total and the latest usable token
usage from SQL, rather than loading the transcript into the agent process. The first
check aggregates existing rows; later checks aggregate only newly appended rows.
Existing history contributes immediately after an upgrade, without waiting for
background token-column backfills. Entries with no usable prompt or output usage
do not hide the last usable usage record.
`memoryFlush.forceFlushTranscriptBytes` measures serialized UTF-8 bytes, including
one newline per entry, without changing the configured threshold behavior.

## Manual compaction

Use `/compact` (optionally with instructions) to force a compaction pass:

```
/compact Focus on decisions and open questions
```

## Compaction ownership

Sessions claimed by a **compaction-stage context owner** suppress core compaction: the owner's
`session_before_compact` hook cancels SDK auto-compaction (including run-loop overflow recovery)
and core `/compact` for the claimed session, so the owner — not WednesdayAI — decides when and how
history is compacted.

For operators:

* Do not expect `🧹 Auto-compaction complete` or the `/compact` command to fire on sessions owned
  by a compaction-stage owner. The owner is responsible for keeping that session under its window.
* A claimed session can still hit its context window if the owner never compacts; monitor owned
  sessions through the owner's own reporting rather than WednesdayAI's compaction counters.
* Unclaimed (core-owned) sessions behave exactly as described in the sections above.

## Context window source

Context window is model-specific. WednesdayAI uses the model definition from the configured provider catalog to determine limits.

## Compaction vs pruning

* **Compaction**: summarises and **appends** the summary to SQL history.
* **Session pruning**: trims old **tool results** only, **in-memory**, per request.

See [/concepts/session-pruning](https://docs.wednesdayai.dev/next/developers/concepts/session-pruning.md) for pruning details.

## OpenAI server-side compaction

WednesdayAI also supports OpenAI Responses server-side compaction hints for
compatible direct OpenAI models. This is separate from local WednesdayAI
compaction and can run alongside it.

* Local compaction: WednesdayAI summarizes and appends the summary to SQL session history.
* Server-side compaction: OpenAI compacts context on the provider side when
  `store` + `context_management` are enabled.

See [OpenAI provider](https://docs.wednesdayai.dev/next/admin/providers/openai.md) for model params and overrides.

## Tool output is capped before it accumulates

Tool results are capped **in memory** at `400,000` text characters at the tool seam and again
when a session hydrates from storage. Oversized results keep a head-and-tail excerpt plus a size
note. When database write-through is enabled, the full raw bytes are stored out-of-band, so the
storage layer still holds the original output even though the model view is capped. Long sessions
do not accumulate multi-megabyte tool output in memory.

If a prune or compaction decision cannot be replayed from its stored ledger row, the session logs
`prompt ledger unavailable; recomputing projections` and repairs itself by recomputing the
projection from stored history. This is a one-time, self-repairing warning — not a data loss.

## Tips

* Use `/compact` when sessions feel stale or context is bloated.
* Large tool outputs are already truncated (tool results are capped at 400k chars in memory);
  pruning can further reduce tool-result buildup in the request view.
* If you need a fresh slate, `/new` or `/reset` starts a new session id.

## Troubleshooting

**Compaction triggers but the session still hits context limits**
The summary may be larger than expected, or recent messages alone already exceed the window. Check your `keepRecentTokens` and `reserveTokens` settings. If recent messages are unavoidably large (for example, huge tool outputs), combine compaction with session pruning (`contextPruning`) to trim tool results before the LLM call.

**Identifier (ticket ID, branch name) lost after compaction**
The default `identifierPolicy: "strict"` adds built-in guidance, but identifiers buried deep in tool output may not survive. Switch to `"custom"` and provide explicit `identifierInstructions` naming the identifier patterns you care about (for example `"Preserve all PROJ-* ticket IDs exactly"`). Confirm with `/compact Focus on ticket IDs and branch names`.

**`enabled: false` still seems to compact**
Config is read at gateway start. Restart the gateway after changing `compaction.enabled`. Also verify the config is under `agents.defaults.compaction`, not a top-level key.

**Memory flush runs unexpectedly or too often**
The flush fires when serialized conversation entries in SQL reach `memoryFlush.forceFlushTranscriptBytes`. Set it to `0` to disable size-based triggers, or increase the value. Set `memoryFlush.enabled: false` to turn off pre-compaction memory flushes entirely.

*Related: [Session pruning](https://docs.wednesdayai.dev/next/developers/concepts/session-pruning.md) · [Memory](https://docs.wednesdayai.dev/next/developers/concepts/memory.md) · [Session management](https://docs.wednesdayai.dev/next/developers/concepts/session.md) · [OpenAI provider](https://docs.wednesdayai.dev/next/admin/providers/openai.md)*


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.