Skip to content

Commit 8f19112

Browse files
committed
fix(sessions): keep reset history closed after compaction
1 parent 6b27585 commit 8f19112

6 files changed

Lines changed: 394 additions & 246 deletions

‎docs/reference/session-management-compaction.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ Per agent, on the Gateway host (resolved via `src/config/sessions.ts`):
5454
| `maxDiskBytes` | `10gb` | per-agent sessions disk budget; `false`, `0`, or `"0"` disables |
5555
| `highWaterBytes` | 80% of `maxDiskBytes` | target after cleanup; zero-resolving values use the default, and negatives are invalid |
5656

57-
Reset advances the live `sessionKey -> sessionId` mapping but keeps the previous SQLite session, transcript, trajectory, and search rows. That history remains searchable under the same session key; ordinary entry and session lists show only the new live mapping. Retained reset history is bounded by the disk budget, not by `resetArchiveRetention`, which only ages archive artifacts. Explicit deletion is different: it writes and verifies a compressed transcript archive (`*.jsonl.deleted.<timestamp>.zst` when zstd is available) before removing the deleted session's rows.
57+
Reset boundaries start a fresh history window without deleting earlier transcript rows. When session rollover advances the live `sessionKey -> sessionId` mapping, the previous SQLite session, transcript, trajectory, and search rows also remain; ordinary entry and session lists show only the live mapping. Retained reset history is bounded by the disk budget, not by `resetArchiveRetention`, which only ages archive artifacts. Explicit deletion is different: it writes and verifies a compressed transcript archive (`*.jsonl.deleted.<timestamp>.zst` when zstd is available) before removing the deleted session's rows.
5858

5959
`maxDiskBytes` enforcement uses physical bytes: the per-agent SQLite main file, its `-wal` file, and counted files in the agent sessions directory. It never estimates row JSON sizes or subtracts logical row sizes from that total.
6060

@@ -130,7 +130,7 @@ A `sessionKey` identifies which conversation bucket you are in (routing + isolat
130130

131131
Each `sessionKey` points at a current `sessionId` (the SQLite transcript identity that continues the conversation). Decision logic lives in `initSessionState()` in `src/auto-reply/reply/session.ts`.
132132

133-
- **Reset** (`/new`, `/reset`) creates a new `sessionId` for that `sessionKey`.
133+
- **Gateway reset** (`/new`, `/reset`) records a reset boundary in an existing persisted session and keeps its `sessionId`. A session that does not exist yet receives a new id.
134134
- **No automatic reset** is the default. The current `sessionId` continues while compaction keeps the active model context bounded.
135135
- **Daily reset** (`session.reset.mode: "daily"`) creates a new `sessionId` on the next message after the configured local-hour boundary (`session.reset.atHour`, default `4`).
136136
- **Idle expiry** (`session.reset.mode: "idle"` with `session.reset.idleMinutes`, or legacy `session.idleMinutes`) creates a new `sessionId` when a message arrives after the idle window. If daily and idle are both configured, whichever expires first wins.
@@ -181,8 +181,11 @@ Notable entry types:
181181
- `custom_message`: extension-injected message that _does_ enter model context (rendered in the TUI when `display: true`, hidden entirely when `display: false`)
182182
- `custom`: extension state that does _not_ enter model context (for persisting extension state across reloads)
183183
- `compaction`: persisted compaction summary with `firstKeptEntryId` and `tokensBefore`
184+
- `reset`: a fresh history window, optionally retaining messages from `firstKeptEntryId`
184185
- `branch_summary`: persisted summary when navigating a tree branch
185186

187+
History readers keep the latest reset window across later compactions: explicitly retained reset messages and messages after that reset remain visible, but older messages and compaction summaries do not reappear. Model context follows the latest reset or compaction instead, so compaction can summarize the current conversation without reopening its earlier history.
188+
186189
OpenClaw intentionally does not "fix up" transcripts; the Gateway uses `SessionManager` to read/write them.
187190

188191
## Context windows vs tracked tokens

‎src/config/sessions/session-accessor.sqlite-active-events.test.ts‎

Lines changed: 4 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -191,107 +191,6 @@ describe("SQLite active transcript event projection", () => {
191191
expect(readSessionTranscriptActiveStats(scope).sizeBytes).toBeLessThan(1_000);
192192
});
193193

194-
it("counts paired reset tool results without counting discarded orphan results", async () => {
195-
const assistantMessage = {
196-
role: "assistant" as const,
197-
api: "openai-responses" as const,
198-
provider: "openai",
199-
model: "gpt-5.6-sol",
200-
content: [{ type: "toolCall" as const, id: "call-1", name: "read", arguments: {} }],
201-
stopReason: "toolUse" as const,
202-
timestamp: Date.parse("2026-08-15T00:00:00.000Z"),
203-
usage: {
204-
input: 1,
205-
output: 1,
206-
cacheRead: 0,
207-
cacheWrite: 0,
208-
totalTokens: 2,
209-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
210-
},
211-
};
212-
await persistSessionTranscriptTurn(scope, {
213-
messages: [
214-
{
215-
eventId: "discarded-old",
216-
parentId: null,
217-
message: { role: "user", content: `discarded ${"x".repeat(12_000)}` },
218-
},
219-
{
220-
eventId: "kept-user",
221-
parentId: "discarded-old",
222-
message: { role: "user", content: "kept question" },
223-
},
224-
{ eventId: "kept-assistant", parentId: "kept-user", message: assistantMessage },
225-
{
226-
eventId: "kept-result",
227-
parentId: "kept-assistant",
228-
message: {
229-
role: "toolResult",
230-
toolCallId: "call-1",
231-
toolName: "read",
232-
content: [{ type: "text", text: `paired ${"p".repeat(3_000)}` }],
233-
isError: false,
234-
timestamp: Date.parse("2026-08-15T00:00:01.000Z"),
235-
},
236-
},
237-
{
238-
eventId: "discarded-orphan",
239-
parentId: "kept-result",
240-
message: {
241-
role: "toolResult",
242-
toolCallId: "orphan-call",
243-
toolName: "read",
244-
content: [{ type: "text", text: `orphan ${"o".repeat(20_000)}` }],
245-
isError: false,
246-
timestamp: Date.parse("2026-08-15T00:00:02.000Z"),
247-
},
248-
},
249-
],
250-
touchSessionEntry: false,
251-
});
252-
await appendTranscriptEvent(scope, {
253-
type: "reset",
254-
id: "reset-boundary",
255-
parentId: "discarded-orphan",
256-
timestamp: "2026-08-15T00:00:03.000Z",
257-
reason: "new",
258-
firstKeptEntryId: "kept-user",
259-
});
260-
await persistSessionTranscriptTurn(scope, {
261-
messages: [
262-
{
263-
eventId: "post-reset",
264-
parentId: "reset-boundary",
265-
message: { role: "user", content: "fresh turn" },
266-
},
267-
],
268-
touchSessionEntry: false,
269-
});
270-
271-
const stats = readSessionTranscriptActiveStats(scope);
272-
expect(stats.eventCount).toBe(4);
273-
expect(stats.sizeBytes).toBeGreaterThan(3_000);
274-
expect(stats.sizeBytes).toBeLessThan(8_000);
275-
276-
await persistSessionTranscriptTurn(scope, {
277-
messages: [
278-
{
279-
eventId: "second-post-reset",
280-
parentId: "post-reset",
281-
message: { role: "assistant", content: "fresh answer" },
282-
},
283-
],
284-
touchSessionEntry: false,
285-
});
286-
const parseSpy = vi.spyOn(JSON, "parse");
287-
try {
288-
expect(readSessionTranscriptActiveStats(scope).eventCount).toBe(5);
289-
expect(parseSpy).not.toHaveBeenCalled();
290-
} finally {
291-
parseSpy.mockRestore();
292-
}
293-
});
294-
295194
it("keeps counting genuinely oversized post-reset events", async () => {
296195
await appendTranscriptEvent(scope, {
297196
type: "reset",
@@ -491,8 +390,8 @@ describe("SQLite active transcript event projection", () => {
491390
id: "newer-compaction",
492391
parentId: "post-reset",
493392
timestamp: "2026-07-22T00:01:00.000Z",
494-
summary: "newer boundary shadows reset",
495-
firstKeptEntryId: "old",
393+
summary: "fresh-only summary",
394+
firstKeptEntryId: "post-reset",
496395
tokensBefore: 10,
497396
});
498397
expect(
@@ -504,8 +403,8 @@ describe("SQLite active transcript event projection", () => {
504403
).toBe("newer-compaction");
505404
expect(readSessionTranscriptActivePathEntryRelation(scope, "newer-compaction")).toBe("exact");
506405
expect(readSessionTranscriptActivePathEntryRelation(scope, "post-reset")).toBe("ancestor");
507-
expect(readSessionTranscriptMessageEventCount(scope)).toBe(5);
508-
expect(readSessionTranscriptMessageEventById(scope, "old")).toBeDefined();
406+
expect(readSessionTranscriptMessageEventCount(scope)).toBe(3);
407+
expect(readSessionTranscriptMessageEventById(scope, "old")).toBeUndefined();
509408
});
510409

511410
it("fails closed when the latest indexed reset payload is malformed", async () => {

0 commit comments

Comments
 (0)