> 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.6-source-deep-dive-four-lines-of-context-defense.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 17.6 Source Deep Dive: Four Lines of Context Defense

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~262,000 tokens, Output \~12,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

§17.4 covered compaction conceptually. This section goes to the source: **how many lines of defense OpenClaw actually deploys, when each intervenes, and what happens when they fail.**

The conclusion first: **four lines, ordered by when they intervene, and only when all four fail does the user see an error.**

```
Line 0  Entry guard          decide before running whether the window is adequate
Line 1  In-request pruning   modifies memory, never disk
Line 2  Compaction           rewrites the JSONL
Line 3  Tool-result truncation  destructively rewrites oversized results
   ↓ all four fail
"Context overflow: try /reset"
```

## 17.6.1 Line 0: The Entry Guard

Before issuing any request, decide: is this model's context window big enough?

`resolveContextWindowInfo` + `evaluateContextWindowGuard` (`run.ts:377-408`):

* Window below the warning threshold → warn;
* Window below the hard floor → **throw `FailoverError` outright**, handing off to the model degradation chain to pick something with a bigger window.

There's a clever move here worth calling out:

```ts
// run.ts:386-389 semantics
// write the configured contextTokens ceiling back onto the model object
```

**Why write it back?** Because the pi engine has its own auto-compaction logic, and its trigger threshold is computed from the window size on the model object. If the user set `contextTokens` in config to something *smaller* than the model's native window (to save money, say), pi wouldn't know — it would still reason from the native window and only compact after the user's budget had already been exceeded.

Writing the effective ceiling back onto the model object makes **pi's auto-compaction respect the user's setting rather than the model's native window**. It's a textbook external-adaptation move: don't change upstream code, change the data you feed upstream.

## 17.6.2 Line 1: In-Request Pruning (No Disk Writes)

`pi-extensions/context-pruning/` implements **microcompaction**.

Its essential difference from compaction: **it only modifies the in-memory request; it never rewrites the JSONL.**

```
real session history (JSONL, fully preserved)
        │
        │ on each request
        ↓
  pruned request copy  →  sent to the model
```

Not a word is removed from the session file. If you later switch to a model with a larger window, the complete history is still there.

### Two intensity levels

| Trigger                                   | Action                                                                   |
| ----------------------------------------- | ------------------------------------------------------------------------ |
| Estimated context exceeds `softTrimRatio` | **Soft-trim** old tool results to "first N chars + `...` + last M chars" |
| Still above `hardClearRatio`              | Replace the whole segment with a **placeholder**                         |

Keeping head *and* tail rather than head alone matters, because key information in tool output frequently lives at the end — exit codes, error summaries, total lines.

### Two protective rules

The first is written with notable restraint:

```ts
// src/agents/pi-extensions/context-pruning/pruner.ts:270-274
// Bootstrap safety: never prune anything before the first user message. This protects initial
// "identity" reads (SOUL.md, USER.md, etc.) which typically happen before the first inbound user
// message exists in the session transcript.
const firstUserIndex = findFirstUserIndex(messages);
```

**Nothing before the first user message is ever pruned.** That region is where the agent reads `SOUL.md` / `USER.md` to establish identity — prune it and the agent has amnesia.

The second is `keepLastAssistants`: protect everything after the most recent N assistant messages. Recent context is the most relevant and must not be touched.

### Trigger timing: factoring cache billing into the decision

This is the single most instructive cost optimization in the book.

Anthropic's prompt cache has a **5-minute TTL**. Once the cache expires, the next request has to be fully recomputed (and the cache rewritten) anyway — **so that's exactly the moment to prune for free.**

What happens if you prune while the cache is still valid? The request content changes → the cache is invalidated → full recomputation. **The pruning saves less than the recomputation costs.**

So `appendCacheTtlTimestamp` records a timestamp into the session after each turn (`attempt.ts:1853-1864`), and the pruning logic uses it to decide whether the cache has already expired.

> **This is cost-aware context management** — folding the downstream billing model into your own scheduling decisions. It's rare among comparable systems.

Incidentally, the **insertion position** of that timestamp entry was itself the subject of a double-compaction timing bug (#9282). Inserted in the wrong place, it caused compaction to misjudge which range to compact.

## 17.6.3 Line 2: Compaction (Disk Writes)

Once context genuinely overflows, `run.ts`'s recovery sequence (`run.ts:986-1131`) has an explicit priority:

```ts
// src/agents/pi-embedded-runner/run.ts:999-1011 (excerpt)
// If this attempt already compacted (SDK auto-compaction), avoid immediately
// running another explicit compaction for the same overflow trigger.
if (!isCompactionFailure && hadAttemptLevelCompaction &&
    overflowCompactionAttempts < MAX_OVERFLOW_COMPACTION_ATTEMPTS) {
  overflowCompactionAttempts++;
  continue;  // just retry; don't stack another compaction
}
```

The logic:

| Situation                                     | Action                                                                             |
| --------------------------------------------- | ---------------------------------------------------------------------------------- |
| pi already auto-compacted during this attempt | **Retry directly; don't stack another compaction**                                 |
| No compaction yet                             | Explicitly call `contextEngine.compact()` (forced, targeting the budget) and retry |

Three attempts maximum, and the comment states that **the counter is never reset** (OC-65: preventing unbounded compaction loops).

"Never reset" is important. If the counter reset on success, a session that keeps overflowing would fall into "compact → one good turn → overflow → compact again," destroying its history repeatedly.

## 17.6.4 compaction-safeguard: Defending Against Compaction Itself

Compaction's biggest risk isn't failure — it's **succeeding at producing a bad summary**. History gets replaced, key information is gone, and the agent works from a false understanding from then on.

`pi-extensions/compaction-safeguard.ts` (\~1,000 lines) exists for exactly that risk, hooked onto pi's `session_before_compact`:

```ts
// src/agents/pi-extensions/compaction-safeguard.ts:698-706
export default function compactionSafeguardExtension(api: ExtensionAPI): void {
  api.on("session_before_compact", async (event, ctx) => {
    const { preparation, customInstructions, signal } = event;
    if (!preparation.messagesToSummarize.some(isRealConversationMessage)) {
      log.warn("Compaction safeguard: cancelling compaction with no real conversation messages...");
      return { cancel: true };
    }
```

It does five things:

**1. Cancel when cancelling is right.** With no real conversation content, or when an API key can't be obtained, it **cancels compaction outright**.

Better to let the context overflow (the user sees a clear error and can `/reset`) than to produce an empty summary that destroys the history. **This is the origin of §45.1's seventh pattern: for irreversible operations, preserve the status quo on failure rather than degrading.**

**2. Attach the critical inventories.** Tool-failure lists (up to 8 entries × 240 characters) and read/modified file lists get attached to the summary. These are the parts of "current working state" most likely to be lost in a summary.

**3. Force structured sections.** The summary must contain `## Decisions`, `## Open TODOs`, `## Exact identifiers`, and similar. **A structured format loses information less readily than free text** — with section headings present, the model is less likely to drop an entire category.

**4. Preserve identifiers verbatim.** With `identifierPolicy: "strict"`, IDs / URLs / paths / ports must be **reproduced verbatim, never generalized or rewritten**.

This explains why test files like `compaction.identifier-preservation.test.ts` exist — a summary that turns `/Users/foo/project/src/handler.ts` into "some handler file" breaks every subsequent operation.

**5. Budgets and estimation-error margins.**

| Mechanism                                                | Effect                                                                  |
| -------------------------------------------------------- | ----------------------------------------------------------------------- |
| `maxHistoryShare` (default 0.5)                          | When history's share exceeds the limit, drop older content in chunks    |
| `SAFETY_MARGIN = 1.2` (`src/agents/compaction.ts:12-14`) | All token estimates are multiplied by 1.2 to absorb estimation error    |
| `computeAdaptiveChunkRatio`                              | Shrink the summarization chunk ratio when average message size is large |

That 1.2 safety factor is worth remembering: **token estimation is never accurate** (tokenizer differences, multilingual text, special characters), and leaving 20% headroom is much cheaper than handling overflow after the fact.

## 17.6.5 Line 3: Tool-Result Truncation

There's one situation compaction can't save: **a single tool result larger than the entire window.**

For instance, the agent `cat`s a 50 MB log file. That one result doesn't fit in the context, and summarizing it is impossible (the summarizer would have to read it into context first).

The backstop is `truncateOversizedToolResultsInSession()` (`run.ts:1095`) — **rewriting the oversized tool result directly in the JSONL.**

This is the only line that destructively modifies the history file, which is why it comes last.

When all four fail, the user-visible error appears: "Context overflow: try /reset".

## 17.6.6 An Easy Accounting Mistake: usage Statistics

One last detail, closely related to context governance and extremely easy to get wrong.

Across multiple tool calls in one turn, **each API call reports a `cacheRead` roughly equal to the current context size.**

If you naively sum `cacheRead` across calls, you get a context-occupancy figure inflated N-fold — ten tool calls in a turn and your number is ten times reality.

`toNormalizedUsage` (`run.ts:179-205`) handles it:

| Field                | Treatment                           |
| -------------------- | ----------------------------------- |
| cache-related fields | **Take only the last call's value** |
| output               | Keep the cumulative sum             |

This was the fix for issue #13698.

**In context engineering, "how you count" matters as much as "how you save"** — get the accounting wrong and every decision built on it (when to prune, when to compact, what number to show the user) is wrong too.

***

## Section Summary

1. **Four lines of defense ordered by intervention time**: entry guard (refuse before running) → in-request pruning (memory only) → compaction (rewrites JSONL) → tool-result truncation (destructive rewrite). Only when all fail does the user see an error.
2. **The entry guard writes the configured `contextTokens` back onto the model object** so pi's auto-compaction respects the user's setting rather than the model's native window — don't change upstream code, change the data you feed it.
3. **In-request pruning never touches disk**, with two intensity levels (soft-trim keeping head and tail / placeholder replacement) and two protective rules (**never prune before the first user message**, protecting identity reads; `keepLastAssistants` protecting recent context).
4. **Pruning timing factors in Anthropic's 5-minute cache TTL** — after expiry a full recomputation happens anyway, making that the only moment pruning is free. Rare cost-aware context management.
5. **compaction-safeguard defends against "successfully producing a bad summary"**: cancel when no API key (better to overflow than destroy history), structured sections, **verbatim identifier preservation**, and a uniform 1.2× safety factor on token estimates.
6. **The compaction counter is never reset** (OC-65), preventing an unbounded loop from repeatedly destroying history.
7. **The usage accounting trap**: `cacheRead` must not be summed across a multi-tool turn (it inflates N-fold) — take only the last call's value; keep output cumulative.
