Skip to content

Commit 659e381

Browse files
committed
fix(sessions): bound history acquisition and preserve fork provenance
1 parent ace8a13 commit 659e381

29 files changed

Lines changed: 1339 additions & 776 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,6 @@ extensions/codex/src/app-server/reasoning-effort.ts 1
207207
extensions/codex/src/app-server/remote-workspace-media.ts 6
208208
extensions/codex/src/app-server/request.ts 2
209209
extensions/codex/src/app-server/run-attempt-context.ts 2
210-
extensions/codex/src/app-server/run-attempt-prompt.ts 2
211210
extensions/codex/src/app-server/run-attempt-resources.ts 13
212211
extensions/codex/src/app-server/run-attempt-runtime.ts 1
213212
extensions/codex/src/app-server/run-attempt-server-requests.ts 2
@@ -223,8 +222,7 @@ extensions/codex/src/app-server/sandbox-exec-server/processes.ts 1
223222
extensions/codex/src/app-server/sandbox-guard.ts 2
224223
extensions/codex/src/app-server/scheduled-app-authority.ts 5
225224
extensions/codex/src/app-server/session-binding.ts 4
226-
extensions/codex/src/app-server/session-history.ts 4
227-
extensions/codex/src/app-server/settled-turn-context.ts 3
225+
extensions/codex/src/app-server/settled-turn-context.ts 2
228226
extensions/codex/src/app-server/shared-client.ts 4
229227
extensions/codex/src/app-server/side-question.ts 8
230228
extensions/codex/src/app-server/startup-binding.ts 2
@@ -236,7 +234,7 @@ extensions/codex/src/app-server/transcript-history-projection.ts 2
236234
extensions/codex/src/app-server/transcript-mirror-attestation.ts 2
237235
extensions/codex/src/app-server/transcript-mirror.ts 4
238236
extensions/codex/src/app-server/transport-stdio.ts 1
239-
extensions/codex/src/app-server/upstream-fork-boundary.ts 2
237+
extensions/codex/src/app-server/upstream-fork-boundary.ts 1
240238
extensions/codex/src/app-server/usage-limit-error.ts 2
241239
extensions/codex/src/app-server/user-prompt-message.ts 1
242240
extensions/codex/src/command-handlers.ts 3
@@ -1459,7 +1457,6 @@ packages/agent-core/src/agent-loop.ts 3
14591457
packages/agent-core/src/harness/compaction/branch-summarization.ts 1
14601458
packages/agent-core/src/harness/compaction/compaction.ts 2
14611459
packages/agent-core/src/harness/messages.ts 3
1462-
packages/agent-core/src/harness/session/session.ts 1
14631460
packages/agent-core/src/harness/session/tool-result-pairing.ts 17
14641461
packages/agent-core/src/harness/session/uuid.ts 1
14651462
packages/agent-core/src/harness/utils/truncate.ts 1
@@ -1791,7 +1788,7 @@ src/agents/embedded-agent-runner/run/attempt-finalize.ts 3
17911788
src/agents/embedded-agent-runner/run/attempt-history.ts 17
17921789
src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts 19
17931790
src/agents/embedded-agent-runner/run/attempt-normalization.ts 1
1794-
src/agents/embedded-agent-runner/run/attempt-prompt-build.ts 2
1791+
src/agents/embedded-agent-runner/run/attempt-prompt-build.ts 1
17951792
src/agents/embedded-agent-runner/run/attempt-prompt-helpers.ts 4
17961793
src/agents/embedded-agent-runner/run/attempt-prompt-submit.ts 2
17971794
src/agents/embedded-agent-runner/run/attempt-queue-message.ts 3

‎docs/plugins/sdk-agent-harness.md‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -775,14 +775,23 @@ rejects canonical failure, tool, delivery, replay, and lifecycle evidence, then
775775
projects only the narrow result. It is defense in depth after native isolation,
776776
not a substitute for removing the native capability surface.
777777

778-
A projection-backed harness must put the complete context on
779-
`settledAttempt.settledTurnFinalizationContext` with
780-
`source: "openclaw-transcript"`. It must capture the active branch after the
781-
settled turn is mirrored, prove that the current prompt and every current tool
782-
call/result are present through that boundary, and freeze the resulting message
783-
array before returning the attempt. The finalizer must reject a missing,
778+
A projection-backed harness must capture the active branch after the settled
779+
turn is mirrored and prove that the current prompt and every current tool
780+
call/result are present through that boundary. Put the frozen evidence on
781+
`settledAttempt.settledTurnFinalizationContext` as either:
782+
783+
- `source: "openclaw-transcript"` with `messages`: the complete application
784+
transcript through the boundary.
785+
- `source: "harness"` with `data`: an immutable, bounded projection interpreted
786+
only by the owning harness. Core passes this opaque value through; the
787+
finalizer must verify its own context type before using it.
788+
789+
Enforce projection limits while acquiring messages, rather than cloning the
790+
whole transcript before checking its size. Successful capture must finish all
791+
identity and source-evidence checks before returning the attempt. Do not retain
792+
an open transcript reader in `data`. The finalizer must reject a missing,
784793
unsupported, ambiguous, or oversized context. It must not truncate messages,
785-
drop earlier history, or describe this application transcript as exact native
794+
drop earlier history, or describe an application projection as exact native
786795
history. Harnesses that resume one restricted native session do not need this
787796
projection field.
788797

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

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ Each `sessionKey` points at a current `sessionId` (the SQLite transcript identit
156156
- **System events** (heartbeat, cron wakeups, exec notifications, gateway bookkeeping) may mutate the session row but never extend daily/idle reset freshness. Reset rollover discards queued system-event notices for the previous session before the fresh prompt is built.
157157
- **Automatic parent fork policy** uses OpenClaw's active branch when creating a thread or subagent fork. If that branch is too large (over a fixed internal cap, currently 100K tokens), OpenClaw starts the child with isolated context instead of failing or inheriting unusable history. Sizing is automatic and not configurable; legacy `session.parentForkMaxTokens` config is removed by `openclaw doctor --fix`.
158158
- **Operator forks**: `sessions.create { parentSessionKey, fork: true }` branches from the parent's current state. Admission uses the selected child model's effective usable input capacity, falling back to the 100K safety cap when model capacity is unavailable. A normal fork is refused while the parent has an active run; adding `forkFrom: "last-completed"` copies only through the last completed assistant message, excluding the in-progress tail. Unlike automatic parent forks, an operator fork over its capacity limit is rejected rather than accepted with isolated context. The child inherits the parent's model selection unless one is passed explicitly. The response marks it `forkedFromParent`, and token counters start fresh.
159-
- **Message forks**: `sessions.fork { sessionKey, entryId }` creates a child from the active-path prefix before the selected user message and returns that message to the composer for editing. The parent remains unchanged. Incognito forks retain the parent's in-memory storage class; restarting the Gateway removes both sessions. See [Control UI](/web/control-ui) for fork and rewind actions.
159+
- **Message forks**: `sessions.fork { sessionKey, entryId }` creates a child from the active-path prefix before the selected user message and returns that message to the composer for editing. The parent remains unchanged. Incognito forks retain the parent's in-memory storage class; restarting the Gateway removes both sessions. Codex fork verification compares complete attested submitted prompts, including whitespace; the bounded display-import projection is not a substitute for that evidence. See [Control UI](/web/control-ui) for fork and rewind actions.
160160

161161
## Session store schema
162162

@@ -206,6 +206,18 @@ History readers keep the latest reset window across later compactions: explicitl
206206

207207
Model-only callers can use `SessionManager.openModelContext()` to create a detached, non-persisting view. The reader selects payloads in SQLite and retains lightweight navigation outside the model window, without introducing a history size cutoff. Storage-only native prompt text and tool-result details stay out of that view; mirror identity, sender and media facts, tool content, and valid provider replay state remain available. Native fork verification, replay, exports, and doctor operations continue to use full-fidelity evidence readers.
208208

209+
`SessionManager.readSessionContext(target, read, { admission? })` lets a synchronous
210+
consumer process full-fidelity context messages inside one read-only snapshot.
211+
The callback receives `(messages, header)`: a lazy message iterable and the
212+
unvalidated stored header. Missing stores supply an empty iterable and no header
213+
without creating a database. An optional admission excludes the current admitted
214+
user row and later events. Callback errors propagate, and the iterator closes
215+
when the callback returns or throws; it cannot be retained for later reads.
216+
This lets replay consumers enforce their existing limits during acquisition
217+
without silently dropping earlier history. Navigation still scales with the
218+
transcript, and individual selected rows are decoded whole; this is not a fixed
219+
process-memory ceiling.
220+
209221
OpenClaw intentionally does not "fix up" transcripts; the Gateway uses `SessionManager` to read/write them.
210222

211223
## Context windows vs tracked tokens

‎extensions/codex/src/app-server/run-attempt-prompt.ts‎

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ import {
3232
codexDynamicToolsFingerprint,
3333
codexLegacyDynamicToolsFingerprint,
3434
} from "./thread-lifecycle.js";
35-
36-
const CODEX_META_KEY = "__openclaw";
35+
import { hasCodexMirrorOrigin } from "./transcript-mirror-attestation.js";
36+
import { readMirrorIdentity } from "./upstream-prompt-provenance.js";
3737

3838
function isRestrictivePromptToolsAllow(toolsAllow: string[] | undefined): boolean {
3939
return toolsAllow !== undefined && !toolsAllow.some((name) => name.trim() === "*");
@@ -343,15 +343,7 @@ export async function prepareCodexAttemptPrompt(context: CodexAttemptContext) {
343343
if (message.role !== "user" && message.role !== "assistant") {
344344
return false;
345345
}
346-
const meta = CODEX_META_KEY in message ? message[CODEX_META_KEY] : undefined;
347-
const mirrorIdentity =
348-
meta && typeof meta === "object" && !Array.isArray(meta)
349-
? (meta as Record<string, unknown>).mirrorIdentity
350-
: undefined;
351-
const mirrorOrigin =
352-
meta && typeof meta === "object" && !Array.isArray(meta)
353-
? (meta as Record<string, unknown>).mirrorOrigin
354-
: undefined;
346+
const mirrorIdentity = readMirrorIdentity(message);
355347
const timestamp =
356348
typeof message.timestamp === "number"
357349
? message.timestamp
@@ -364,8 +356,8 @@ export async function prepareCodexAttemptPrompt(context: CodexAttemptContext) {
364356
typeof message.idempotencyKey === "string" &&
365357
message.idempotencyKey.startsWith("codex-app-server:")
366358
) &&
367-
mirrorOrigin !== "codex-app-server" &&
368-
!(typeof mirrorIdentity === "string" && mirrorIdentity.startsWith("codex-app-server:")) &&
359+
!hasCodexMirrorOrigin(message) &&
360+
!mirrorIdentity?.startsWith("codex-app-server:") &&
369361
Number.isFinite(timestamp) &&
370362
timestamp > (Number.isFinite(cutoff) ? cutoff : 0)
371363
);

‎extensions/codex/src/app-server/run-attempt.test.ts‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4854,14 +4854,14 @@ describe("runCodexAppServerAttempt", () => {
48544854
expect(Boolean(result.settledTurnFinalizationContext)).toBe(expectedContext);
48554855
if (result.settledTurnFinalizationContext) {
48564856
expect(result.settledTurnFinalizationContext).toMatchObject({
4857-
source: "openclaw-transcript",
4858-
messages: [
4857+
source: "harness",
4858+
data: [
48594859
expect.objectContaining({ role: "user" }),
4860-
expect.objectContaining({ role: "assistant" }),
4861-
expect.objectContaining({ role: "toolResult", toolCallId: "tool-settled" }),
4860+
expect.objectContaining({ type: "function_call" }),
4861+
expect.objectContaining({ type: "function_call_output", call_id: "tool-settled" }),
48624862
],
48634863
});
4864-
expect(Object.isFrozen(result.settledTurnFinalizationContext.messages)).toBe(true);
4864+
expect(Object.isFrozen(result.settledTurnFinalizationContext)).toBe(true);
48654865
}
48664866
},
48674867
);
@@ -4933,14 +4933,14 @@ describe("runCodexAppServerAttempt", () => {
49334933
});
49344934
expect(result.itemLifecycle).toEqual({ startedCount: 1, completedCount: 1, activeCount: 0 });
49354935
expect(result.settledTurnFinalizationContext).toMatchObject({
4936-
source: "openclaw-transcript",
4937-
messages: [
4936+
source: "harness",
4937+
data: [
49384938
expect.objectContaining({ role: "user" }),
4939-
expect.objectContaining({ role: "assistant" }),
4940-
expect.objectContaining({ role: "toolResult", toolCallId: "tool-settled" }),
4939+
expect.objectContaining({ type: "function_call" }),
4940+
expect.objectContaining({ type: "function_call_output", call_id: "tool-settled" }),
49414941
],
49424942
});
4943-
expect(Object.isFrozen(result.settledTurnFinalizationContext?.messages)).toBe(true);
4943+
expect(Object.isFrozen(result.settledTurnFinalizationContext)).toBe(true);
49444944
});
49454945
it("preserves every command failure from official app-server events", async () => {
49464946
const sessionFile = path.join(tempDir, "session-multi-command-failure.jsonl");

‎extensions/codex/src/app-server/session-history.test.ts‎

Lines changed: 73 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,18 @@ import { createHash } from "node:crypto";
33
import fs from "node:fs/promises";
44
import os from "node:os";
55
import path from "node:path";
6+
import type { AgentMessage } from "openclaw/plugin-sdk/agent-harness-runtime";
67
import { CURRENT_SESSION_VERSION } from "openclaw/plugin-sdk/agent-sessions";
78
import { upsertSessionEntry } from "openclaw/plugin-sdk/session-store-runtime";
89
import { appendSessionTranscriptMessageByIdentity } from "openclaw/plugin-sdk/session-transcript-runtime";
9-
import { afterEach, describe, expect, it } from "vitest";
10+
import { afterEach, describe, expect, it, vi } from "vitest";
1011
import { readCodexMirroredSessionHistoryMessages } from "./session-history.js";
11-
import { readMirrorIdentity, readUpstreamUserText } from "./upstream-prompt-provenance.js";
12+
import { captureCodexSettledTurnFinalizationContext } from "./settled-turn-context.js";
13+
import {
14+
attachCodexMirrorIdentity,
15+
readMirrorIdentity,
16+
readUpstreamUserText,
17+
} from "./upstream-prompt-provenance.js";
1218

1319
const tempDirs: string[] = [];
1420

@@ -132,6 +138,71 @@ async function writeSqliteSession(params: { storedSessionFile?: string } = {}):
132138
}
133139

134140
describe("readCodexMirroredSessionHistoryMessages", () => {
141+
it("rejects oversized settled history before acquiring later transcript payloads", async () => {
142+
const { marker, sessionTarget } = await writeSqliteSession();
143+
for (let index = 0; index < 201; index += 1) {
144+
await appendSessionTranscriptMessageByIdentity({
145+
...sessionTarget,
146+
message: { role: "user", content: `prior-${index}`, timestamp: index + 3 },
147+
});
148+
}
149+
const unreadMarker = "synthetic-unread-settled-payload:";
150+
await appendSessionTranscriptMessageByIdentity({
151+
...sessionTarget,
152+
message: { role: "user", content: unreadMarker + "x".repeat(1024 * 1024), timestamp: 205 },
153+
});
154+
const settledMessages = [
155+
attachCodexMirrorIdentity(
156+
{ role: "user", content: "Send the synthetic update.", timestamp: 206 },
157+
"settled:prompt",
158+
),
159+
attachCodexMirrorIdentity(
160+
{
161+
role: "assistant",
162+
content: [{ type: "toolCall", id: "sent", name: "message", arguments: {} }],
163+
timestamp: 207,
164+
} as AgentMessage,
165+
"settled:tool:sent:call",
166+
),
167+
attachCodexMirrorIdentity(
168+
{
169+
role: "toolResult",
170+
toolCallId: "sent",
171+
toolName: "message",
172+
isError: false,
173+
content: [{ type: "text", text: "Synthetic update sent." }],
174+
timestamp: 208,
175+
},
176+
"settled:tool:sent:result",
177+
),
178+
];
179+
for (const message of settledMessages) {
180+
await appendSessionTranscriptMessageByIdentity({ ...sessionTarget, message });
181+
}
182+
const originalParse = JSON.parse;
183+
let laterPayloadReads = 0;
184+
const parse = vi.spyOn(JSON, "parse").mockImplementation((text, reviver) => {
185+
if (typeof text === "string" && text.includes(unreadMarker)) {
186+
laterPayloadReads += 1;
187+
}
188+
return originalParse(text, reviver);
189+
});
190+
try {
191+
const captured = await captureCodexSettledTurnFinalizationContext({
192+
...sessionTarget,
193+
sessionTarget,
194+
sessionFile: marker,
195+
settledMessages,
196+
mirroredMessages: settledMessages,
197+
turnId: "settled",
198+
});
199+
expect(captured === undefined).toBe(true);
200+
expect(laterPayloadReads).toBe(0);
201+
} finally {
202+
parse.mockRestore();
203+
}
204+
});
205+
135206
it("preserves native prompt evidence across explicit model-only reads", async () => {
136207
const { marker, sessionTarget } = await writeSqliteSession();
137208
const upstreamUserText = "synthetic-native-prompt:" + "x".repeat(1024 * 1024);

0 commit comments

Comments
 (0)