Repository navigation
Description
Bug type
Behavior bug (incorrect output/state without crash)
Beta release blocker
No
Summary
In the embedded runner's deferred context-engine tool loop, replay normalization can shorten history after prePromptMessageCount was captured; the stale boundary can then classify the current user/runtime input and new tool results as history and drop them when reassembling the next model call.
This report isolates the message-preservation failure with a deterministic, no-network fixture using functions extracted from the installed release. It does not require a particular model or access to private conversations.
Steps to reproduce
- Use an existing npm installation of OpenClaw 2026.9.3, on a supported Node version.
- Save the executable fixture below as
repro.mjsand runnode repro.mjs /absolute/path/to/node_modules/openclaw. It reads the installed JavaScript modules; it does not start a Gateway, call a model, or modify installation/config/session data. - The fixture builds 84 historical messages: 78 ordinary entries and six removable
NO_REPLYassistant entries. The installednormalizeAssistantReplayContentreduces this to 78. - Preserve the pre-normalization boundary (84), as the observed source ordering permits. Append a synthetic current runtime item and user request, then two call/result rounds.
- The installed
installContextEngineLoopHookreceives a synthetic deferred context engine that returns only committed history. Check the hook's returned model context after each round. - Repeat with the boundary computed from the normalized history (78). This is a boundary-rebased control, not a full integration test of the proposed source patch.
Expected behavior
Current input and newly produced tool call/result pairs remain in the model context across tool-loop reassembly. The existing hook implements this contract by reserving tokens for pendingMessages and appending them after the engine's assembled history. The rebased control preserves the current runtime/user and both tool results.
Actual behavior
The executable fixture completes successfully only if it detects the faulty behavior and the preserving control. Observed output:
| Case | Iteration | Source messages | Engine input messages | Current user/runtime preserved | New tool results preserved |
|---|---|---|---|---|---|
| Stale boundary = 84 | Initial | 80 | Not called | Yes | N/A |
| Stale boundary = 84 | After tool round 1 | 82 | 82 | No | None |
| Stale boundary = 84 | After tool round 2 | 84 | 84 | No | None |
| Rebased boundary = 78 | Initial | 80 | 78 | Yes | N/A |
| Rebased boundary = 78 | After tool round 1 | 82 | 78 | Yes | Round 1 |
| Rebased boundary = 78 | After tool round 2 | 84 | 78 | Yes | Rounds 1 and 2 |
With the stale boundary, the engine returns the same 84-entry history after each tool round, and the pending suffix is empty. With the rebased boundary, output grows to 86, 88, and 90 messages. There is no context-budget pressure in this fixture.
OpenClaw version
Executed against npm release 2026.9.3, build commit 1391f7cd2d40ab5bbcf2f5f831d3a64f520e72d7.
Also inspected current main at 9233c9dd07bf91ca43a41551c669a4a4be618d9d: the relevant ordering and slice remain present. No full test suite or end-to-end reproduction on main is claimed.
Operating system
Ubuntu 24.04.4 LTS; Node.js v26.8.1.
Install method
Global npm installation.
Model
None for the deterministic reproduction. The motivating user report involved meta/muse-spark-1.3 with an external context engine, but the fixture does not establish complete historical causality or model-specific prevalence.
Provider / routing chain
Reproduction: installed replay normalizer -> installed embedded context-engine loop hook -> synthetic history-only deferred context engine. Zero provider requests.
Additional provider/model setup details
The failure requires a shortened replay history and a stale pre-prompt boundary in the deferred-turn path. The fake engine models a committed-history-only result; the host is responsible for retaining the uncommitted active tail. No external plugin source or credentials are needed to run the fixture.
Source evidence
At the inspected main revision:
prepareEmbeddedAttemptPromptContextfilters heartbeat artifacts and then capturessessionMessages.lengthasprePromptMessageCount(line 432).runEmbeddedAttemptPromptPhasecopies that count into runtime state.submitEmbeddedAttemptPromptsubsequently callsnormalizeAssistantReplayContentand replaces the history without rebasing that count.installContextEngineLoopHookobtainshistoryLengthfrom the stored getter and runsproviderMessages.slice(historyLength). A shortened prefix can make that suffix empty or incomplete.
The earlier length clamp in the hook controls whether to reassemble; it does not rebase the later history/pending split.
Proposed fix (not deployed)
Move replay normalization into prepareEmbeddedAttemptPromptContext, before capturing the boundary and building hook/precheck views:
let sessionMessages = normalizeAssistantReplayContent(
filterHeartbeatTranscriptArtifacts(
input.messages,
input.prompt.heartbeatSummary?.ackMaxChars,
input.prompt.heartbeatSummary?.prompt,
),
);
if (sessionMessages !== input.messages) {
input.replaceSessionMessages(sessionMessages);
}
// Reconcile provider projections using this same normalized history.
const prePromptMessageCount = sessionMessages.length;Remove the subsequent length-changing normalization in submitEmbeddedAttemptPrompt and use the already normalized history there, including any snapshot references. This keeps the fence and its message array in the same coordinate system, before current runtime/user/tool messages are inserted. The raw durable transcript should remain unchanged.
Do not hard-code a subtraction of six, clamp the fence to the current array length, or recalculate it after appending the current turn. Those approaches can still classify active messages as history.
Suggested regression coverage for the integrated patch:
- Removable replay artifacts followed by new user/runtime input and two tool rounds: preserve every active item exactly once and in order.
- A no-op normalization control and normalization that changes content without changing count.
- Pre-persisted user/replay/recovery paths: neither duplicate nor drop the current user.
- Runtime-only/finalization turns and parallel tool call/result pairs.
- Deferred context-engine and standalone paths; preserve ingestion/checkpoint behavior.
Longer-term hardening could use stable active-turn identities/anchors and a preservation invariant before provider submission. That is distinct from this minimal ordering fix, and must not rewrite immutable durable transcript anchors.
Screenshots, recordings, and evidence
The following executable fixture is synthetic and version-pinned because it extracts functions from a published bundle with hashed filenames. It deliberately fails if an unexpected dependency branch is reached. It is not a replacement for a repository integration regression test.
Executable reproduction (save as repro.mjs)
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { isDeepStrictEqual } from 'node:util';
import vm from 'node:vm';
import assert from 'node:assert/strict';
if (!process.argv[2]) throw new Error('Usage: node repro.mjs /absolute/path/to/node_modules/openclaw');
const root=process.argv[2];
const source=await readFile(`${root}/dist/builtin-openclaw-FlPOnMHc.mjs`,'utf8');
const require=createRequire(`${root}/package.json`);
const transports=await import(require.resolve('@openclaw/ai/transports'));
const imports=await Promise.all([
import(`${root}/dist/record-coerce-DItp3I4t.mjs`),
import(`${root}/dist/display-text-sanitize-J8UnEavN.mjs`),
import(`${root}/dist/tokens-DwD7c00a.mjs`),
import(`${root}/dist/ai-transport-runtime-host-BvhFsKp5.mjs`),
import(`${root}/dist/stream-message-shared-sKH7NjHK.mjs`),
import(`${root}/dist/transcript-only-openclaw-assistant-CVgy4bjA.mjs`),
import(`${root}/dist/usage-BpC2Ujh-.mjs`),
import(`${root}/dist/tool-call-id-CnwowhSs.mjs`),
import(`${root}/dist/compaction-B8syZLTn.mjs`),
]);
const sandbox={
isDeepStrictEqual,
asOptionalRecord:imports[0].a,
stripInternalMetadataForDisplay:imports[1].t,
isSilentReplyPayloadText:imports[2].i,
isReasoningOnlyLengthAssistantTurn:imports[3].i,
hasOnlyAssistantReasoningContent:imports[3].r,
isStreamErrorFallbackContent:imports[4].a,
isTranscriptOnlyOpenClawAssistantMessage:imports[5].s,
hasNonzeroUsage:imports[6].a,
normalizeUsage:imports[6].c,
extractToolCallsFromAssistant:imports[7].t,
estimateTokens:imports[8].u,
replaceCompactionReplayOwnerContent:transports.replaceCompactionReplayOwnerContent,
// These are never reached by this synthetic fixture; fail rather than simulate them.
hasPersistedMedia(){throw new Error('fixture unexpectedly requires persisted media');},
isZeroUsageEmptyStopAssistantTurn(){throw new Error('fixture unexpectedly requires zero-usage branch');},
};
const between=(a,b)=>source.slice(source.indexOf(a),source.indexOf(b,source.indexOf(a)));
const extracted=[
'const TRANSCRIPT_PROMPT_TEXT_KEY = "__openclawTranscriptPromptText";',
'const MANAGED_DISPLAY_BLOCK_TYPES = new Set(["attachment","attachment_error","audio","image","video"]);',
between('function getTranscriptPromptText(', 'function replaceToolResultContent('),
between('function sanitizeUserReplayContent(', 'function normalizeAssistantUsageSnapshot('),
between('function installContextEngineLoopHook(', 'function installToolResultContextGuard('),
'globalThis.audit={normalizeAssistantReplayContent,installContextEngineLoopHook};',
].join('\n');
// Guard extraction end boundary; source is installed code, not reimplemented logic.
assert(extracted.length<25000);
vm.runInNewContext(extracted,sandbox);
const {normalizeAssistantReplayContent,installContextEngineLoopHook}=sandbox.audit;
const history=Array.from({length:78},(_,i)=>({role:i%2?'assistant':'user',content:`Historical item ${i}`,timestamp:i}));
const assembled=[...history,...Array.from({length:6},(_,i)=>({role:'assistant',content:'NO_REPLY',timestamp:100+i}))];
const normalized=normalizeAssistantReplayContent(assembled);
assert.equal(assembled.length,84);
assert.equal(normalized.length,78);
const runtime={role:'custom',customType:'openclaw.runtime-context',content:'CURRENT_RUNTIME_MARKER',timestamp:200};
const user={role:'user',content:'CURRENT_USER: summarize NEW_TOPIC',timestamp:201};
const toolRound=i=>[{role:'assistant',content:[{type:'toolCall',id:`call${i}`,name:'read_fixture',arguments:{id:i}}],timestamp:202+i*2},{role:'toolResult',toolCallId:`call${i}`,toolName:'read_fixture',content:[{type:'text',text:`CURRENT_TOOL_RESULT_${i}`}],timestamp:203+i*2}];
async function run(label,fence){
const calls=[];
const agent={};
const remove=installContextEngineLoopHook({agent,sessionId:'synthetic',sessionKey:'synthetic',tokenBudget:1048576,modelId:'synthetic',getPrePromptMessageCount:()=>fence,deferredTurn:{prompt:'CURRENT_USER: summarize NEW_TOPIC'},contextEngine:{async assemble(p){calls.push({inputMessages:p.messages.length,tokenBudget:p.tokenBudget});return {messages:assembled};}}});
let messages=[...normalized,runtime,user];
const rows=[];
for(let i=0;i<3;i++){
if(i)messages=[...messages,...toolRound(i)];
const output=await agent.transformContext(messages);
const serialized=JSON.stringify(output);
rows.push({iteration:i,sourceMessages:messages.length,assembled:calls.at(-1)??null,outputMessages:output.length,currentUser:serialized.includes('CURRENT_USER:'),currentRuntime:serialized.includes('CURRENT_RUNTIME_MARKER'),toolResults:[1,2].filter(j=>serialized.includes(`CURRENT_TOOL_RESULT_${j}`))});
}
remove();
return {label,fence,rows};
}
const stale=await run('installed ordering: count before normalization',assembled.length);
const rebased=await run('control: count from same normalized coordinate system',normalized.length);
assert(stale.rows[0].currentUser);
assert(!stale.rows[1].currentUser);
assert(!stale.rows[2].currentUser);
assert(stale.rows[1].assembled.inputMessages===82&&stale.rows[2].assembled.inputMessages===84);
assert(stale.rows[1].assembled.tokenBudget===1048576);
assert.deepEqual(stale.rows[1].toolResults,[]);
assert(rebased.rows.every(x=>x.currentUser&&x.currentRuntime));
assert.deepEqual(rebased.rows[2].toolResults,[1,2]);
console.log(JSON.stringify({testedRelease:'2026.9.3',extractedModule:'dist/builtin-openclaw-FlPOnMHc.mjs',synthetic:true,providerRequests:0,normalization:{before:assembled.length,after:normalized.length},stale,rebased},null,2));Impact and severity
Affected tested path: embedded deferred context-engine tool loop with a history-shrinking replay normalization. Deterministic for the provided fixture. Practical consequence: a valid tool result and current task can be absent from the next model call without an error, allowing an answer to revert to an older topic. Population frequency and all-model/channel prevalence: NOT_ENOUGH_INFO.
Additional information
No production patch, restart, provider request, or private transcript publication was performed for this report. Last known good release: NOT_ENOUGH_INFO.
Searched existing issues/PRs for prePromptMessageCount, normalizeAssistantReplayContent, and context-loss terms. Related coordinate discussion #128509 concerns durable commitTurn anchors and payload semantics; this report concerns an in-memory pending-tail boundary and does not propose altering that contract.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
clawsweeper commentedon Sep 12, 2026
Thanks for the context here. I did a careful shell check against current
main, and this is already implemented.The reported loss of current input and tool results is fixed on current
mainby the merged repair at #147531. That commit is included in v2026.9.5, and current regression coverage checks multiple tool rounds.Root-cause cluster
Relationship:
fixed_by_candidateCanonical: #147531
Summary: The merged repair addresses the issue's replay-boundary failure; earlier proposed fixes were closed without merging.
Members:
canonical: fix(agents): retain the current task after replay cleanup #147531 - Merged repair explicitly names this issue and preserves the current task and tool results after replay cleanup.superseded: fix(agent): rebase pre-prompt turn boundary during replay normalization #146595 - Closed unmerged; the merged repair explicitly says it supersedes this proposal.superseded: fix(agents): fence the deferred history slice to the messages present #146518 - Closed unmerged after proposing a repair for the same boundary failure.Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.
So I’m closing this as already implemented rather than keeping a duplicate issue open.
Review details
Best possible solution:
Keep the shipped boundary ordering and its multi-round preservation regression in place.
Do we have a high-confidence way to reproduce the issue?
Yes, the issue and merged repair document a failing pre-fix deferred tool loop with removable replay entries and multiple model requests. Current
maincontains the fix, so this review did not establish a current-main failure.Is this the best way to solve the issue?
Yes. Normalizing replay before recording the boundary keeps the history array and boundary in one coordinate system; current tests cover the resulting model requests.
Security review:
Security review: This is issue triage; no proposed patch is under security review.
AGENTS.md: found and applied where relevant.
What I checked:
src/agents/embedded-agent-runner/run/attempt-prompt-build.ts:437, 4d1c5d19ecc8)src/agents/embedded-agent-runner/run/attempt-prompt-phase.ts:214, 4d1c5d19ecc8)src/agents/embedded-agent-runner/run/attempt-context-advancement.test.ts:239, 4d1c5d19ecc8)src/agents/embedded-agent-runner/run/attempt-prompt-build.ts:437, 24425bfdc1cd)docs/releases/2026.9.5.md. (docs/releases/2026.9.5.md:8192, 4d1c5d19ecc8)Likely related people:
Codex review notes: model internal, reasoning medium; reviewed against 4d1c5d19ecc8; fix evidence: release v2026.9.5, commit 24425bfdc1cd.
clawsweeper commentedon Sep 12, 2026
🦞⚠️
Automatic implementation stopped before completion.
Reason: The automatic implementation worker stopped before all deterministic gates completed. Open the workflow run for the exact blocker.
Worker: https://github.com/openclaw/clawsweeper/actions/runs/34713199486
Automatic implementation progress:
clawsweeper:manual-onlyorclawsweeper:human-review.MertBasar0 commentedon Sep 12, 2026
Picking this up — I have the failure reproduced against current
main(9b59fe4ef7d) with the real modules, so posting the mechanism before opening a PR.The boundary does get clamped, but not at the slice that matters.
installContextEngineLoopHookcomputes a fenced copy:and then the deferred branch re-reads the raw getter, unclamped:
src/agents/embedded-agent-runner/tool-result-context-guard.ts:420.Ordering confirmed in source:
prepareEmbeddedAttemptPromptContextcapturesprePromptMessageCount = sessionMessages.length(attempt-prompt-build.ts:432), andsubmitEmbeddedAttemptPromptlater replacesactiveSession.agent.state.messageswithnormalizeAssistantReplayContent(...)(attempt-prompt-submit.ts:107).attempt-prompt-phase.tscalls them in that order (181, then 395), so the captured count can outrun the messages that remain.One note for anyone writing coverage: a single-call fixture never reaches the defect. When the getter exceeds the array, the fenced copy clamps to the array length and the
transcriptMessages.length <= prePromptMessageCountearly-return fires, soassembleis never called and the raw messages come back looking correct. The stale value only reaches the slice on a later call, oncelastSeenLengthwas seeded while the array was shorter.deferredTurnalso has no coverage intool-result-context-guard.test.tstoday, which is consistent with this surviving.With a deferred engine that serves only committed history, the failing assertion on current
mainis the message loss itself:i.e. the current user request is absent from the next model call. Reusing the already-fenced count for the deferred slice turns that green; 80/80 across both guard suites. PR shortly.
fix(agents): retain the current task after replay cleanup (#147531)
fix(agents): retain the current task after replay cleanup (openclaw#1…