fix(agents): keep the prompt series when the bounded window drops an old compaction (#201655)

## What was wrong

OpenClaw ties a session's system prompt series to the newest compaction or reset in its hydrated transcript window. When a chat grew long after a compaction, that compaction fell out of the bounded window, causing the history ID to flip to `null`, restart the prompt series (`restarted:history`), and miss the entire provider cache. Compaction summaries were also re-reading every accumulated `System prompt update` message even though compaction starts a fresh prompt series.

## Example

You compact a chat, then edit `AGENTS.md` several times with follow-up turns until the compaction scrolls out of the bounded transcript window:

- **Before:** the next turn stopped seeing the compaction, triggered `restarted:history`, and missed the cache (OpenAI: **0 / 11096**; Claude: **1394 / 16782**).
- **Now:** the latest prompt checkpoint identifies the current history using its boundary count, so the series stays pinned and hits cache (OpenAI: **12336 / 484**; Claude: **18263 / 988**).

## The fix

- Use the newest `openclaw.system-prompt` checkpoint in the window to name the history when the compaction boundary has scrolled out of view (`session-prompt-history-id.ts`, `session-prompt-state.ts`, porting the first commit with its original author).
- Record `sessionManager.getBoundaryCount()` on each checkpoint so a stale checkpoint from before a later compaction or reset cannot spoof the current history. When neither a visible boundary nor a matching checkpoint is in view, use `unknown:<boundaryCount>` so the series restarts at most once.
- Exclude `System prompt update` messages from compaction summary input (`src/agents/compaction-planning.ts`), since compaction starts a new series with fresh rendered sections.
- Production diff vs main: +102 / -34 (compaction change: +33 / -14). Existing compacted sessions without a boundary count restart at most once after deploy if the compaction is already out of window.

## Proof

Isolated scratch Gateways on merge base `b4ddf4b30fc5` vs head `af7ee63f5b61` (final head `dfb4d5bce649` only reshapes a test fixture; OpenAI Responses `gpt-6.2-astra`, `contextTokens: 24000`, `maxTokens: 2048`, numbers are `cacheRead / cacheWrite`):

| Metric (long workspace rules, 2 runs per side) | Base (`b4ddf4b30fc5`) | Head (`af7ee63f5b61`) |
|---|---|---|
| Req 13/14 after window drops compaction | `restarted:history`, **0 / 11096** (run 2); **0 / 11459** at req 14 (run 1) | pinned, **12336 / 484** (run 2); **12332 / 484** (run 1) |
| History restarts without a compaction | 2 and 3 | **0** and **0** |
| Live prompt updates at compaction (peak) | 34 KB | 88 KB in history, none in summary input |

Earlier real-route run (`3df7c5332e81` / re-run `3677e9f`) on cliproxy Claude (`claude-opus-5-5`, `contextTokens: 30000`): req 15 went from `restarted:history` (**1394 / 16782**) on base to pinned (**18263 / 988**) on head (1 → 0 uncompacted restarts).

- **UI and side effects:** Control UI on the head scratch Gateway renders history across both compactions and answers every turn after Gateway restart (screenshots in PR comments). Concurrent chat (`gate-other`), short-rules control, cron/tool/session paths, and upgrade from legacy checkpoints all passed.
- **Tests and gates:** `attempt-session-runtime-prepare.history-boundary.test.ts`, `prepared-compaction-plan.test.ts`, `session-prompt-state.test.ts`, `pnpm tsgo:core`, `pnpm check:test-types`, oxlint, oxfmt, and all baseline ratchets pass.

<details><summary>Full test details</summary>

### Boundary-count and upgrade details

- A checkpoint is evidence of the current history only when its recorded `sessionManager.getBoundaryCount()` matches the current count. A checkpoint whose count matches names the history even when the boundary is also in the window. Otherwise the visible boundary names it; with neither, the history is `unknown:<boundaryCount>`.
- `null` stays valid only for a session that never compacted or reset. A restored checkpoint without a count is rewritten with the count on the next persist.
- Existing checkpoints do not record a boundary count. In a session that has compacted, the first run after deploy whose window does not contain the compaction restarts the series once. A legacy checkpoint read while the compaction is in the window is rewritten with the count instead. Never-compacted sessions are not affected.
- Provider requests outside compaction are unchanged.

### E2E details (`af7ee63f5b61` vs merge base `b4ddf4b30fc5`; `dfb4d5bce649` only reshapes a test fixture)

Isolated scratch Gateways from source (`env -i`, own state, random ports), same driver on both sides, OpenAI Responses (`gpt-6.2-astra`, `contextTokens: 24000`, `maxTokens: 2048`). Journey `gate-h`: three story turns, `/compact` asking for a very long summary, then workspace `AGENTS.md` edits each followed by a follow-up turn (the history after the compaction outgrows the bounded window), then a **Gateway restart** on the same state and three more edit/follow-up pairs. An unrelated chat (`gate-other`) runs ordinary turns and `/compact` every second turn throughout.

- **Automatic compaction after the restart:** base run 2 had 1 failed attempt then succeeded, and one turn failed ("Couldn't finish this reply"). Head run 2 had 2 failed attempts then succeeded, and every turn answered; head run 1 answered every turn.
- Before the compaction change (head `dd58eb1`, two runs), the same journey failed automatic compaction three times in a row after the restart and the last turn failed in both runs. The remaining failed attempts on both sides are `summary truncated at the output token limit` and come from the journey itself: the `/compact` message asks for "at least 3000 words" and stays in the history the next automatic compaction summarizes. With a plain `/compact`, base and head match request for request and both compact twice without a failure.
- **Short workspace rules (control, 9 edits):** neither window loses the compaction, so both sides stay pinned and match (req 22: 14398 / 664 head, 14336 / 662 base); both compact automatically after the restart and every turn answers.
- **Side effects:**
  - Ordinary chat (`gate-other`): every turn and every `/compact` returned `ok` on both sides in all runs.
  - Cron, tool and session paths (run on head `dd58eb1`, unchanged by the compaction commit except the summary input): cron starting a chat, exec background wake, subagent completion, steer, `sessions_send`, cron surviving new/reset/edited chats, Stop and reset gave identical results on base and head, then a Gateway restart.

### Earlier real-route run (`3df7c5332e81` vs merge base; re-run on `3677e9f`)

On `3677e9f`: OpenAI requests 13/15 pinned at 9474/484 and 12048/484, 0 history restarts without a compaction; Claude request 15 pinned at 18150/988, only restart at a real compaction with `boundaryCount: 2`.

OpenAI Responses (`gpt-6.2-astra`, minimal tool profile, `contextTokens: 24000`):

| Request | Base series, cacheRead / cacheWrite | Head series, cacheRead / cacheWrite |
|---|---|---|
| 13 | `restarted:history` (historyId -> null), **2700 / 3876** | pinned, 9432 / 484 |
| 15 | pinned, 7061 / 484 | pinned, 12005 / 484 |
| 16 | `restarted:history` (flips back), 7545 / 485 | real automatic compaction (allowed rebuild) |
| History restarts without a compaction | 2 | 0 |

cliproxy Claude (`claude-opus-5-5`, `contextTokens: 30000`):

| Request | Base series, cacheRead / cacheWrite | Head series, cacheRead / cacheWrite |
|---|---|---|
| 15 | `restarted:history` (historyId -> null), **1394 / 16782** | pinned, 18263 / 988 |
| 20/21 | restart at a real automatic compaction | restart at a real automatic compaction (checkpoint `boundaryCount: 2`) |
| History restarts without a compaction | 1 | 0 |

### Upgrade test (one state dir: base then head, OpenAI route)

- Target chat: one `restarted:history` on the first turn after the upgrade, then pinned through 6 edit/follow-up pairs (cacheRead 2432 -> 10213); `/compact` on head restarts once and writes `boundaryCount: 2`; later checkpoints stay pinned at count 2.
- Never-compacted chat: pinned across the upgrade (legacy checkpoint `historyId: null`, then `boundaryCount: 0`).
- Unrelated chat: restarts only at its own compactions (counts 2-5 recorded).
- Cron created on base: still enabled on head and fired on schedule in the target chat; with the scratch model at `maxTokens: 2048`, that turn failed in automatic compaction (summary output budget exhausted); the merge base fails the same way on the same setup. With `maxTokens: 8192` the cron turn passes on head, the target chat restarts once after the upgrade and then stays pinned (cacheRead 2297 -> 10078), and `/compact` restarts once with `boundaryCount: 3`.

### Unit and integration tests (merge base vs head)

- `attempt-session-runtime-prepare.history-boundary.test.ts` (real SQLite hydration, one bounded view per run; every case pushes the boundary out of the window so it reaches the count rule):
  - three runs whose byte window includes, then drops, then includes an old compaction keep one series (base: `restarted:history` on run 2);
  - eviction: the newest checkpoint leaves the window with the compaction, the series restarts once as `unknown:1`, then stays pinned when the boundary returns beside that checkpoint (previous head `3df7c53`: second restart);
  - a legacy checkpoint that names the visible boundary is rewritten with the count and stays pinned when the boundary leaves (previous head: two restarts);
  - a legacy checkpoint with `historyId: null` restarts once, then stays pinned (base: pinned on the wrong history);
  - rewind to a checkpoint written at count 1 (stored as `unknown:1`, `boundaryCount: 1`) past a later compaction: the series stays pinned to that checkpoint (fails if the count were store-wide);
  - a counted reset restarts the series although the window holds a checkpoint of the earlier history (fails if resets were not counted);
  - a visible compaction after a counted checkpoint restarts the series (fails if any counted checkpoint outranked the visible boundary).
  - Each of the last three cases was checked with a local mutation of the behavior it guards (store-wide count, uncounted reset, checkpoint always outranking the boundary): each fails under its mutation and passes after revert.
- `prepared-compaction-plan.test.ts`: prompt updates between turns are left out of the summary selection, the turns stay (red on `7a698fb`: the updates were selected).
- The rewind case reads the same SQLite bounded context through `SessionManager.openBoundedAsync`; the separate SQLite reader case was dropped after main grew that file past the line cap.
- `session-prompt-state.test.ts`:
  - a checkpoint that predates a compaction outside the window restarts the series, and the request carries the re-rendered prompt (base: pinned);
  - a never-compacted session stays pinned (passes on both);
  - the ported unit test for a window that starts after the compaction, now passing the boundary count as production does (base: restart).
- The earlier prefix-stability journey step was removed: it passed on the merge base, so it could not catch this defect.

### Follow-ups (not blockers) and gates

- A session fork loses its pinned prefix while the source series is `unknown:N` (the fork view carries no checkpoint data); this costs cache until the next compaction.
- `removeTrailingEntries` can delete a boundary through the plugin compatibility surface; core does not reach that path today.
- A legacy session gets one extra checkpoint append after the upgrade, when its count is first written.
- Gates on `af7ee63`, plus lint, format, the touched test and test-lines on `dfb4d5b`: `pnpm tsgo:core`, `pnpm check:test-types`, oxlint and oxfmt on touched files, the baseline ratchets (mock-exports, test-lines +400 of 400, line-cap, max-lines, database-worker), the focused tests above, the prompt-cache prefix-stability suites, and the compaction, safeguard and memory-flush tests.

</details>

<!-- openclaw-publication:650c2283-6d98-83fb-aa93-9135a86a193d -->

Co-authored-by: Ayaan Zaidi <hi@obviy.us>