Skip to content

feat(agents): add mid-turn compaction precheck - #73499

Merged
yaozheng-fang merged 1 commit into
openclaw:mainfrom
marchpure:feat/midturn-precheck
Apr 30, 2026
Merged

yaozheng-fang merged 1 commit into
openclaw:mainfrom
marchpure:feat/midturn-precheck

Conversation

@marchpure

Copy link
Copy Markdown
Contributor

Summary

  • Add an opt-in agents.defaults.compaction.midTurnPrecheck.enabled setting for embedded Pi runs.
  • Check context pressure after tool results are appended and before the next model call.
  • Reuse the existing precheck recovery path to truncate oversized tool results or trigger compaction and retry.

Validation

  • node scripts/test-projects.mjs src/agents/pi-embedded-runner/tool-result-context-guard.test.ts src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-engine.test.ts src/config/config.compaction-settings.test.ts src/config/zod-schema.agent-defaults.test.ts src/config/schema.help.quality.test.ts

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L labels Apr 28, 2026
@clawsweeper

clawsweeper Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes:

Keep open. Current main still lacks the PR's intended opt-in agents.defaults.compaction.midTurnPrecheck.enabled config surface and the structured post-tool-result precheck path. The PR is active implementation work, not obsolete or implemented on main, and the latest discussion still points to maintainer review around maxActiveTranscriptBytes composition, observability, and private SessionManager persistence behavior.

Maintainer follow-up before merge:

Keep this PR open for maintainer and author iteration. A mergeable version should add the opt-in config/schema/help/docs surface, route post-tool-result pressure through the existing recovery path, document its relationship to maxActiveTranscriptBytes, include the requested observability fields, and resolve or explicitly guard the private SessionManager persistence behavior.

Best possible solution:

Keep this PR open for maintainer and author iteration. A mergeable version should add the opt-in config/schema/help/docs surface, route post-tool-result pressure through the existing recovery path, document its relationship to maxActiveTranscriptBytes, include the requested observability fields, and resolve or explicitly guard the private SessionManager persistence behavior.

Acceptance criteria:

  • node scripts/test-projects.mjs src/agents/pi-embedded-runner/tool-result-context-guard.test.ts src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-engine.test.ts src/config/config.compaction-settings.test.ts src/config/zod-schema.agent-defaults.test.ts src/config/schema.help.quality.test.ts
  • Targeted maintainer review against @mariozechner/pi-coding-agent SessionManager 0.70.5 persistence behavior
  • pnpm check:changed in Testbox before merge because the PR touches runtime, config schema/generated help, docs, and tests

What I checked:

  • Current main lacks config schema surface: AgentDefaultsSchema defines agents.defaults.compaction as a strict object with existing fields such as qualityGuard, postIndexSync, memoryFlush, truncateAfterCompaction, maxActiveTranscriptBytes, and notifyUser; there is no midTurnPrecheck object or enabled property. (src/config/zod-schema.agent-defaults.ts:164, 1dac6ac4c601)
  • Current main lacks typed config/docs surface: AgentCompactionConfig has no midTurnPrecheck type/property, and the compaction docs/config examples document maxActiveTranscriptBytes but not a mid-turn Pi tool-loop precheck option. (src/config/types.agent-defaults.ts:433, 1dac6ac4c601)
  • Current main tool-loop guard is still generic: installToolResultContextGuard only accepts agent and contextWindowTokens; after optional per-message truncation it throws the generic PREEMPTIVE_CONTEXT_OVERFLOW_MESSAGE from transformContext, with no mid-turn request object or callback into the precheck recovery path. (src/agents/pi-embedded-runner/tool-result-context-guard.ts:295, 1dac6ac4c601)
  • Current main precheck recovery remains prompt-boundary behavior: runEmbeddedAttempt installs the generic guard without mid-turn options, while shouldPreemptivelyCompactBeforePrompt(...) is invoked later against activeSession.messages at the prompt boundary. That does not implement the proposed post-tool-result, pre-next-model-call signal path. (src/agents/pi-embedded-runner/run/attempt.ts:1466, 1dac6ac4c601)
  • PR remains distinct active implementation work: Provided GitHub context shows the latest PR head is 23264c6255b2cb3c578a48e3030d60bf78b9fa08, with 19 changed files adding docs, config schema/help/types, runtime wiring, and tests. The PR is open, ready for review, unmerged, and not represented on current main. (23264c6255b2)
  • Security/dependency review focus: The supplied PR file list does not add workflows, action refs, package metadata, lockfiles, release scripts, or dependency sources. The security-sensitive/runtime risk is transcript persistence: the proposed cleanup reaches into @mariozechner/pi-coding-agent 0.70.5 SessionManager internals such as fileEntries, byId, leafId, and _rewriteFile, which exist in the current package source but are not an OpenClaw-owned public contract.

Likely related people:

  • steipete: Current-main blame/log for the compaction config schema, docs, prompt precheck helper, and tool-result guard routes through Peter Steinberger's release snapshot and recent adjacent config/docs commits. (role: recent maintainer and adjacent compaction/config owner; confidence: medium; commits: 6350dd5ace95, be8c24633aaa, f5e7557c70c1; files: src/config/zod-schema.agent-defaults.ts, src/config/types.agent-defaults.ts, src/agents/pi-embedded-runner/tool-result-context-guard.ts)
  • stainlu: PR discussion from stainlu asks the key maintainer questions for this change: how the proposed mid-turn precheck composes with maxActiveTranscriptBytes and which observability fields should be logged. (role: active reviewer and likely follow-up reviewer; confidence: low; files: docs/reference/session-management-compaction.md, src/agents/pi-embedded-runner/run/attempt.ts, src/agents/pi-embedded-runner/tool-result-context-guard.ts)

Remaining risk / open question:

  • The PR's proposed cleanup path relies on private SessionManager runtime fields/methods; if the dependency internals drift, in-memory cleanup and persisted JSONL cleanup could diverge on session resume.
  • The proposed mid-turn route selection needs maintainer review for how it composes with existing per-message truncation and maxActiveTranscriptBytes so users do not see double compaction or confusing logs.
  • The PR touches runtime, config schema/generated help, docs, and tests, so it needs targeted validation plus changed-lane validation before merge.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 1dac6ac4c601.

@marchpure marchpure changed the title [codex] Add mid-turn compaction precheck feat(agents): add mid-turn compaction precheck Apr 28, 2026
@stainlu

stainlu commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

seems valid — the opt-in flag + reuse of the existing precheck recovery path keeps the surface tight.

one thing I'd want to understand: how does this compose with agents.defaults.compaction.maxActiveTranscriptBytes (the byte-size preflight that landed in 2026.4.26)? both live under agents.defaults.compaction.*, both gate optional triggers that ultimately call the configured compaction path. the docs change here makes them sound like complementary axes (turn-level token pressure vs JSONL byte growth), but in practice if a user enables both, can they fire on the same turn? the recovery path coalesce them, or do we end up paying compaction cost twice?

if the answer is "they're orthogonal and never compose because the byte-size guard already fired before the turn started," a one-line note in session-management-compaction.md would help (something like "this option is independent of maxActiveTranscriptBytes; the byte preflight gates turn-start while this gates mid-turn"). otherwise it'd be useful to know which takes precedence.

separate small thing: [context-overflow-midturn-precheck] log line includes estimatedPromptTokens and overflowTokens which is good for observability. would it be cheap to also emit the model id and prePromptMessageCount there? the existing preemptive-compaction logs include those and it'd help correlate when this fires across providers.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: XL triage: dirty-candidate Candidate: broad unrelated surfaces; may need splitting or cleanup. and removed size: L labels Apr 29, 2026
@marchpure
marchpure force-pushed the feat/midturn-precheck branch from 1830b18 to 562e679 Compare April 29, 2026 04:23
@marchpure
marchpure marked this pull request as ready for review April 29, 2026 07:36
@greptile-apps

greptile-apps Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds an opt-in agents.defaults.compaction.midTurnPrecheck.enabled guard for embedded Pi runs. After tool results are appended and before the next model call, the guard estimates prompt pressure using the existing preflight budget logic and either truncates oversized tool results in-place or signals the outer run loop to trigger compaction and retry. The feature is disabled by default and integrates cleanly with both default and safeguard compaction modes.

Confidence Score: 4/5

Safe to merge; the feature is opt-in and the two P2 findings only affect observability and edge-case route accuracy, not correctness of the happy path.

Both findings are P2: one is a silent failure mode that only manifests on session resume after a specific SDK internals mismatch, and the other is a minor estimation imprecision in route selection. No P0/P1 issues found in core logic, config schema, or test coverage.

src/agents/pi-embedded-runner/run/attempt.ts — specifically removeTrailingMidTurnPrecheckAssistantError which relies on private SessionManager internals without any fallback diagnostic.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/run/attempt.ts
Line: 503-533

Comment:
**Silent failure when `SessionManager` internals are unavailable**

`removeTrailingMidTurnPrecheckAssistantError` accesses private `SessionManager` fields (`fileEntries`, `byId`, `leafId`, `_rewriteFile`) using optional chaining. If the `@mariozechner/pi-coding-agent` SDK changes these internal property names, the function silently exits after updating in-memory `agent.state.messages` (line 509) but without flushing the change to the JSONL file (`_rewriteFile?.()` is a no-op). On the next session resume the synthetic `"stopReason": "error"` message would still be present in the persisted transcript, which could confuse the model or cause a second unexpected error during session reload. There is no warning or metric emitted when this partial cleanup occurs.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/tool-result-context-guard.ts
Line: 377-416

Comment:
**Mid-turn precheck runs on per-message-truncated messages, inflating `toolResultReducibleChars`**

The guard first applies per-message truncation (lines 365–376) to a clone of `sourceMessages`, producing `contextMessages`. The mid-turn precheck then calls `shouldPreemptivelyCompactBeforePrompt` with these already-truncated messages (line 394). If the per-message pass already brought individual results within the single-message cap, the `toolResultReducibleChars` estimate returned by the precheck may over-estimate the remaining reduction potential, because the recovery path in `handleMidTurnPrecheckRequest` operates on the untouched `activeSessionManager` entries rather than on `contextMessages`.

In practice the downstream truncation-recovery code re-applies `maxCharsOverride` against the session manager, so the outcome should still be correct, but the route decision (`truncate_tool_results_only` vs. `compact_only`) could be made on a lower-pressure estimate than reality. A comment explaining why the precheck intentionally uses the post-truncation view would improve maintainability.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "test(agents): add live mid-turn loop ver..." | Re-trigger Greptile

Comment on lines +503 to +533
function removeTrailingMidTurnPrecheckAssistantError(params: {
activeSession: { agent: { state: { messages: AgentMessage[] } } };
sessionManager: ReturnType<typeof guardSessionManager>;
}): void {
const messages = params.activeSession.agent.state.messages;
if (isMidTurnPrecheckAssistantError(messages.at(-1))) {
params.activeSession.agent.state.messages = messages.slice(0, -1);
}

const mutableSessionManager = params.sessionManager as unknown as {
fileEntries?: Array<{
type?: string;
id?: string;
parentId?: string | null;
message?: AgentMessage;
}>;
byId?: Map<string, unknown>;
leafId?: string | null;
_rewriteFile?: () => void;
};
const lastEntry = mutableSessionManager.fileEntries?.at(-1);
if (lastEntry?.type !== "message" || !isMidTurnPrecheckAssistantError(lastEntry.message)) {
return;
}
mutableSessionManager.fileEntries?.pop();
if (lastEntry.id) {
mutableSessionManager.byId?.delete(lastEntry.id);
}
mutableSessionManager.leafId = lastEntry.parentId ?? null;
mutableSessionManager._rewriteFile?.();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Silent failure when SessionManager internals are unavailable

removeTrailingMidTurnPrecheckAssistantError accesses private SessionManager fields (fileEntries, byId, leafId, _rewriteFile) using optional chaining. If the @mariozechner/pi-coding-agent SDK changes these internal property names, the function silently exits after updating in-memory agent.state.messages (line 509) but without flushing the change to the JSONL file (_rewriteFile?.() is a no-op). On the next session resume the synthetic "stopReason": "error" message would still be present in the persisted transcript, which could confuse the model or cause a second unexpected error during session reload. There is no warning or metric emitted when this partial cleanup occurs.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/run/attempt.ts
Line: 503-533

Comment:
**Silent failure when `SessionManager` internals are unavailable**

`removeTrailingMidTurnPrecheckAssistantError` accesses private `SessionManager` fields (`fileEntries`, `byId`, `leafId`, `_rewriteFile`) using optional chaining. If the `@mariozechner/pi-coding-agent` SDK changes these internal property names, the function silently exits after updating in-memory `agent.state.messages` (line 509) but without flushing the change to the JSONL file (`_rewriteFile?.()` is a no-op). On the next session resume the synthetic `"stopReason": "error"` message would still be present in the persisted transcript, which could confuse the model or cause a second unexpected error during session reload. There is no warning or metric emitted when this partial cleanup occurs.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +377 to +416
if (params.midTurnPrecheck?.enabled) {
const prePromptMessageCount = Math.max(
0,
Math.min(
contextMessages.length,
lastSeenLength ??
params.midTurnPrecheck.getPrePromptMessageCount?.() ??
contextMessages.length,
),
);
lastSeenLength = prePromptMessageCount;
if (
hasNewToolResultAfterFence({
messages: contextMessages,
prePromptMessageCount,
})
) {
const precheck = shouldPreemptivelyCompactBeforePrompt({
messages: contextMessages,
systemPrompt: params.midTurnPrecheck.getSystemPrompt?.(),
// During a tool loop, the active user prompt is already part of messages.
prompt: "",
contextTokenBudget: params.midTurnPrecheck.contextTokenBudget,
reserveTokens: params.midTurnPrecheck.reserveTokens(),
toolResultMaxChars: params.midTurnPrecheck.toolResultMaxChars,
});
const request = toMidTurnPrecheckRequest(precheck);
log.debug(
`[context-overflow-midturn-precheck] tool-result-guard check route=${precheck.route} ` +
`messages=${contextMessages.length} prePromptMessageCount=${prePromptMessageCount} ` +
`estimatedPromptTokens=${precheck.estimatedPromptTokens} ` +
`promptBudgetBeforeReserve=${precheck.promptBudgetBeforeReserve} ` +
`overflowTokens=${precheck.overflowTokens}`,
);
if (request) {
params.midTurnPrecheck.onMidTurnPrecheck?.(request);
throw new MidTurnPrecheckSignal(request);
}
}
lastSeenLength = contextMessages.length;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Mid-turn precheck runs on per-message-truncated messages, inflating toolResultReducibleChars

The guard first applies per-message truncation (lines 365–376) to a clone of sourceMessages, producing contextMessages. The mid-turn precheck then calls shouldPreemptivelyCompactBeforePrompt with these already-truncated messages (line 394). If the per-message pass already brought individual results within the single-message cap, the toolResultReducibleChars estimate returned by the precheck may over-estimate the remaining reduction potential, because the recovery path in handleMidTurnPrecheckRequest operates on the untouched activeSessionManager entries rather than on contextMessages.

In practice the downstream truncation-recovery code re-applies maxCharsOverride against the session manager, so the outcome should still be correct, but the route decision (truncate_tool_results_only vs. compact_only) could be made on a lower-pressure estimate than reality. A comment explaining why the precheck intentionally uses the post-truncation view would improve maintainability.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/tool-result-context-guard.ts
Line: 377-416

Comment:
**Mid-turn precheck runs on per-message-truncated messages, inflating `toolResultReducibleChars`**

The guard first applies per-message truncation (lines 365–376) to a clone of `sourceMessages`, producing `contextMessages`. The mid-turn precheck then calls `shouldPreemptivelyCompactBeforePrompt` with these already-truncated messages (line 394). If the per-message pass already brought individual results within the single-message cap, the `toolResultReducibleChars` estimate returned by the precheck may over-estimate the remaining reduction potential, because the recovery path in `handleMidTurnPrecheckRequest` operates on the untouched `activeSessionManager` entries rather than on `contextMessages`.

In practice the downstream truncation-recovery code re-applies `maxCharsOverride` against the session manager, so the outcome should still be correct, but the route decision (`truncate_tool_results_only` vs. `compact_only`) could be made on a lower-pressure estimate than reality. A comment explaining why the precheck intentionally uses the post-truncation view would improve maintainability.

How can I resolve this? If you propose a fix, please make it concise.

@openclaw-barnacle openclaw-barnacle Bot added channel: bluebubbles Channel integration: bluebubbles channel: discord Channel integration: discord channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: msteams Channel integration: msteams channel: nextcloud-talk Channel integration: nextcloud-talk channel: nostr Channel integration: nostr channel: signal Channel integration: signal channel: slack Channel integration: slack channel: telegram Channel integration: telegram channel: tlon Channel integration: tlon channel: voice-call Channel integration: voice-call labels Apr 29, 2026
@marchpure

marchpure commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor Author

seems valid — the opt-in flag + reuse of the existing precheck recovery path keeps the surface tight.

one thing I'd want to understand: how does this compose with agents.defaults.compaction.maxActiveTranscriptBytes (the byte-size preflight that landed in 2026.4.26)? both live under agents.defaults.compaction.*, both gate optional triggers that ultimately call the configured compaction path. the docs change here makes them sound like complementary axes (turn-level token pressure vs JSONL byte growth), but in practice if a user enables both, can they fire on the same turn? the recovery path coalesce them, or do we end up paying compaction cost twice?

if the answer is "they're orthogonal and never compose because the byte-size guard already fired before the turn started," a one-line note in session-management-compaction.md would help (something like "this option is independent of maxActiveTranscriptBytes; the byte preflight gates turn-start while this gates mid-turn"). otherwise it'd be useful to know which takes precedence.

separate small thing: [context-overflow-midturn-precheck] log line includes estimatedPromptTokens and overflowTokens which is good for observability. would it be cheap to also emit the model id and prePromptMessageCount there? the existing preemptive-compaction logs include those and it'd help correlate when this fires across providers.

@stainlu stainluThanks, this is the intended split:

maxActiveTranscriptBytes is a turn-start JSONL byte-size preflight. It can compact/rotate the active transcript before the run starts.

midTurnPrecheck is later in the embedded Pi tool loop: after new tool results are appended and before the next model call. It only detects token-pressure created mid-turn and then routes into the same existing precheck recovery path.

So they are complementary checkpoints rather than two competing triggers at the same point. If the byte guard already compacted before the turn, mid-turn precheck sees that resulting session state. If tool results later push the prompt over budget, mid-turn precheck can still fire later in the same user turn. It does not compact inside the Pi transform hook.

I also added the doc note to make that distinction explicit. The recovery log already includes provider/model; I added prePromptMessageCount to the mid-turn recovery log as well so it is easier to correlate with the guard-side check.

@marchpure

Copy link
Copy Markdown
Contributor Author

@stainlu
实际代码语义可以这样判断:

maxActiveTranscriptBytes:

  • 触发点是 turn start / run open 前。
  • 看的是 active JSONL transcript 的 byte size。
  • 目标是控制本地 transcript reopen / file growth 成本。
  • 如果触发,会在本轮真正进入 agent loop 前先 compact/rotate。

midTurnPrecheck:

  • 触发点是 embedded Pi tool loop 中。
  • 发生在 tool result append 后、下一次 model call 前。
  • 看的是 prompt token pressure。
  • 不直接在 Pi hook 里 compact,而是把压力转成 existing precheck
    recovery request。

所以它们不是同一个 checkpoint 上的两个 competing trigger。

  • 可以在同一个 user turn 的不同阶段都发生。
  • 如果 maxActiveTranscriptBytes 在 turn-start 已经 compact,midTurnPrecheck 后续看到的是 compact 后的 session state。
  • 如果本轮工具调用又产生大量结果,midTurnPrecheck 仍可能在同一个turn 后半段触发。
  • 这不是“同一压力点重复 compact 两次”,而是“turn-start 文件大小guard + mid-turn token pressure guard”两个不同阶段。
  • 但确实存在“同一个 user turn 内先 byte guard compact,后 mid-turn token pressure 又触发 recovery”的情况。这是合理行为,因为后者处理的是本轮新增 tool result 带来的新压力。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime size: L triage: dirty-candidate Candidate: broad unrelated surfaces; may need splitting or cleanup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants