Skip to content

Commit 015546c

Browse files
authored
fix(cli): read session history from the canonical store, not a retired file (#132185)
* fix(cli): read session history from the canonical store, not a retired file `transcript-file-resolve` returns the session key as a process-local routing token, but CLI history still treated it as a filesystem path: it resolved a JSONL file, ran a runtime migration over it, and suppressed ENOENT by returning an empty list. A session that lives only in SQLite therefore projected as an empty conversation, and the runner fell back to the current prompt alone. Hook history, reseed history, context-engine bootstrap, and the embedded fallback marker all inherited that silent emptiness. All five CLI callers now pass the session target they had already selected, and the embedded attempt passes its own; cron shares its explicit per-prompt target across user persistence and the CLI path. Presence comes from the transcript watermark rather than a file's existence, and history comes from the canonical bounded active-context reader, preserving raw-reseed eligibility, summary pinning, and truncation notices. The retired JSONL reader, its path resolution, and its runtime migration are deleted rather than kept as a fallback: runtime consumes only the canonical shape. Net production -348 lines. * test(cli): assert the context engine receives the forwarded session target The lifecycle test still encoded the retired storage premise, asserting the loader was called with sessionFile/sessionKey/agentId. It now supplies a real session target on the prepared fixture and asserts that exact target is forwarded, which is the invariant the repair actually establishes. * test(cli): name the synthetic fallback-history model fixture Use vaporeon-alpha under the existing test provider in the persisted assistant-message fixture. Production behavior and assertions are unchanged. Validation: 59 attempt-execution tests passed, including SQLite assistant history detection, abandoned branches, and reset boundaries. * fix(cli): preserve canonical targets across dispatch and lifecycle Carry the selected SQLite transcript target through embedded CLI dispatch and context-engine bootstrap/finalization. Keep custom-store transcript mirrors with that owner and retain the post-admission writer claim. Extend real SQLite and lifecycle regressions for PR #132185. Local behavioral tests and autoreview pass. The full changed-files gate is blocked by missing playwright-core; the additional fault-sequence E2E setup is blocked by missing @lit/context.
1 parent 4ecc93f commit 015546c

26 files changed

Lines changed: 844 additions & 1600 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1728,7 +1728,7 @@ src/agents/cli-runner/execute-node-claude.ts 5
17281728
src/agents/cli-runner/execute.ts 3
17291729
src/agents/cli-runner/helpers.ts 1
17301730
src/agents/cli-runner/prepare.ts 5
1731-
src/agents/cli-runner/session-history.ts 21
1731+
src/agents/cli-runner/session-history.ts 3
17321732
src/agents/code-mode-bridge.ts 1
17331733
src/agents/code-mode-namespaces.ts 5
17341734
src/agents/code-mode-runtime.ts 4

‎docs/gateway/cli-backends.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -185,13 +185,13 @@ register a small wrapper backend plugin.
185185
- `none`: never send a session id.
186186
- `claude-cli` defaults to `liveSession: "claude-stdio"`, `output: "jsonl"`, and `input: "stdin"`. The owning Anthropic plugin keeps one official Agent SDK query and Claude Code subprocess warm for compatible consecutive agent turns. If the gateway restarts or the idle process exits, OpenClaw resumes from the stored Claude session id. Stored session ids are verified against a readable project transcript before resume; a missing transcript clears the binding (logged as `reason=transcript-missing`) instead of silently starting a fresh session under `--resume`.
187187
- Stored CLI sessions are provider-owned continuity. Automatic reset is disabled by default; `/reset` and explicit daily or idle `session.reset` policies still cut them.
188-
- Fresh CLI sessions normally reseed only from OpenClaw's compaction summary plus the post-compaction tail. To recover short sessions invalidated before compaction, a backend can opt in with `reseedFromRawTranscriptWhenUncompacted: true`. Raw transcript reseed stays bounded and limited to safe invalidations, such as a missing CLI transcript, an orphaned tool-use tail, message-policy/system-prompt/cwd/MCP changes, or a session-expired retry; auth profile or credential-epoch changes never reseed raw transcript history.
188+
- Fresh CLI sessions normally reseed from OpenClaw's latest compaction summary, the messages retained by that compaction, and subsequent turns on the active branch. OpenClaw reads this history from the canonical session SQLite database; it does not require an OpenClaw JSONL transcript file. To recover short sessions invalidated before compaction, a backend can opt in with `reseedFromRawTranscriptWhenUncompacted: true`. Raw transcript reseed stays bounded and limited to safe invalidations, such as a missing CLI transcript, an orphaned tool-use tail, message-policy/system-prompt/cwd/MCP changes, or a session-expired retry; auth profile or credential-epoch changes never reseed raw transcript history.
189189

190190
Serialization: `serialize: true` keeps same-lane runs ordered (most CLIs serialize on one provider lane). OpenClaw also drops stored CLI session reuse when the selected auth identity changes, including a changed auth profile id, static API key, static token, or OAuth account identity when the CLI exposes one; OAuth access/refresh token rotation alone does not cut the session. If a CLI has no stable OAuth account id, OpenClaw lets that CLI enforce its own resume permissions.
191191

192192
## Fallback prelude from claude-cli sessions
193193

194-
When a `claude-cli` attempt fails over to a non-CLI candidate in [`agents.defaults.model.fallbacks`](/concepts/model-failover), OpenClaw seeds the next attempt with a context prelude harvested from Claude Code's local JSONL transcript (under `~/.claude/projects/`, keyed per workspace). Without this seed the fallback provider starts cold, since OpenClaw's own session transcript is empty for `claude-cli` runs.
194+
When a `claude-cli` attempt fails over to a non-CLI candidate in [`agents.defaults.model.fallbacks`](/concepts/model-failover), OpenClaw seeds the next attempt with a context prelude harvested from Claude Code's local JSONL transcript (under `~/.claude/projects/`, keyed per workspace). This supplies CLI-owned context that may not be present in OpenClaw's SQLite session transcript.
195195

196196
- The prelude prefers the latest `/compact` summary or `compact_boundary` marker, then appends the most recent post-boundary turns up to a char budget. Pre-boundary turns are dropped because the summary already represents them.
197197
- Tool blocks are coalesced to compact `(tool call: name)` and `(tool result: …)` hints to keep the prompt budget honest; an oversized summary is truncated and labeled `(truncated)`.

‎src/agents/agent-command.live-model-switch.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ vi.mock("./command/attempt-execution.runtime.js", () => ({
211211
.filter(Boolean)
212212
.join("\n\n") ?? "",
213213
runAgentAttempt: (...args: unknown[]) => state.runAgentAttemptMock(...args),
214-
sessionFileHasContent: vi.fn(async () => false),
214+
sessionTranscriptHasContent: vi.fn(async () => false),
215215
}));
216216

217217
vi.mock("./command/attempt-execution.shared.js", async () => {

‎src/agents/cli-runner.context-engine.test.ts‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,15 @@ function createMaintenanceResult() {
7878
};
7979
}
8080

81+
// The context engine reads history from the canonical store, so the runner must forward
82+
// the exact target it was given rather than re-deriving one from a session file token.
83+
const CONTEXT_ENGINE_SESSION_TARGET = {
84+
agentId: "main",
85+
sessionId: "openclaw-session-1",
86+
sessionKey: "agent:main:main",
87+
storePath: "/tmp/openclaw-cli-context-engine-test/openclaw-agent.sqlite",
88+
} as const;
89+
8190
function buildPreparedContext(contextEngine: ContextEngine): PreparedCliRunContext {
8291
// Prepared contexts mirror the shape produced by prepare.runtime without
8392
// loading full backend setup in every lifecycle assertion.
@@ -97,6 +106,7 @@ function buildPreparedContext(contextEngine: ContextEngine): PreparedCliRunConte
97106
sessionKey: "agent:main:main",
98107
agentId: "main",
99108
sessionFile: "session.jsonl",
109+
sessionTarget: CONTEXT_ENGINE_SESSION_TARGET,
100110
workspaceDir: "/tmp/openclaw-cli-context-engine-test",
101111
prompt: "visible ask",
102112
transcriptPrompt: "transcript visible ask",
@@ -296,18 +306,15 @@ describe("runPreparedCliAgent context engine lifecycle", () => {
296306
diagnosticUsage: { input: 21, output: 9, total: 30 },
297307
});
298308
expect(loadCliSessionContextEngineMessagesMock).toHaveBeenCalledWith({
299-
sessionId: "openclaw-session-1",
300-
sessionFile: "session.jsonl",
301-
sessionKey: "agent:main:main",
302-
agentId: "main",
303-
config: undefined,
309+
sessionTarget: CONTEXT_ENGINE_SESSION_TARGET,
304310
});
305311
expect(loadCliSessionHistoryMessagesMock).not.toHaveBeenCalled();
306312
expect(bootstrap).toHaveBeenCalledTimes(1);
307313
const bootstrapParams = bootstrap.mock.calls[0]?.[0];
308-
expect(bootstrapParams).toMatchObject({
314+
expect.soft(bootstrapParams).toMatchObject({
309315
sessionId: "openclaw-session-1",
310316
sessionKey: "agent:main:main",
317+
sessionTarget: CONTEXT_ENGINE_SESSION_TARGET,
311318
sessionFile: "session.jsonl",
312319
runtimeSettings: {
313320
schemaVersion: 1,
@@ -329,9 +336,10 @@ describe("runPreparedCliAgent context engine lifecycle", () => {
329336
});
330337
expect(afterTurn).toHaveBeenCalledTimes(1);
331338
const afterTurnParams = afterTurn.mock.calls[0]?.[0];
332-
expect(afterTurnParams).toMatchObject({
339+
expect.soft(afterTurnParams).toMatchObject({
333340
sessionId: "openclaw-session-1",
334341
sessionKey: "agent:main:main",
342+
sessionTarget: CONTEXT_ENGINE_SESSION_TARGET,
335343
sessionFile: "session.jsonl",
336344
prePromptMessageCount: 2,
337345
isHeartbeat: false,
@@ -352,9 +360,13 @@ describe("runPreparedCliAgent context engine lifecycle", () => {
352360
usage: { input: 11, output: 7, total: 18 },
353361
});
354362
expect(maintain).toHaveBeenCalledTimes(2);
355-
expect(maintain.mock.calls[1]?.[0]).toMatchObject({
363+
expect.soft(maintain.mock.calls[0]?.[0]).toMatchObject({
364+
sessionTarget: CONTEXT_ENGINE_SESSION_TARGET,
365+
});
366+
expect.soft(maintain.mock.calls[1]?.[0]).toMatchObject({
356367
sessionId: "openclaw-session-1",
357368
sessionKey: "agent:main:main",
369+
sessionTarget: CONTEXT_ENGINE_SESSION_TARGET,
358370
sessionFile: "session.jsonl",
359371
runtimeContext: {
360372
rewriteTranscriptEntries: expect.any(Function),

0 commit comments

Comments
 (0)