Skip to content

Commit be67a8b

Browse files
Finn763obviyus
andauthored
fix(agents): preserve exec retention loss through session caps (#128997)
Exec and process results placed their aggregate-retention disclosure after retained output, so the SQLite session result cap could hide the earlier unrecoverable loss. Own the disclosure once and place it first across foreground exec, process poll, and process log. Preserve the separate poll omission and log paging semantics, and cover the composed persistence boundary with a red-to-green regression. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent d708507 commit be67a8b

6 files changed

Lines changed: 67 additions & 27 deletions

‎src/agents/bash-tools.exec-output.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ export const EXEC_NO_OUTPUT_PLACEHOLDER = "(no output)";
99
const EXEC_TIMEOUT_RETRY_GUIDANCE =
1010
"The command was terminated, but external side effects may already have completed. Verify the resulting state before retrying. Do not automatically rerun non-idempotent commands. Use a higher timeout only when the command is known to be safe to retry.";
1111

12+
// Irreversible loss leads model-visible output so later head-preserving caps retain it.
13+
export const EXEC_RETENTION_CAP_NOTE =
14+
"[earlier output was discarded at the retention cap and cannot be recovered]\n\n";
15+
1216
/** Render command output with a stable placeholder for empty output. */
1317
export function renderExecOutputText(value: string | undefined): string {
1418
return value || EXEC_NO_OUTPUT_PLACEHOLDER;

‎src/agents/bash-tools.exec-support.test.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,15 @@ describe("exec foreground retention", () => {
1212
aggregated: "retained output",
1313
timedOut: false,
1414
},
15+
warningText: "w".repeat(80_000),
1516
aggregateOutputDropped: true,
1617
});
1718

18-
expect(result.content[0]).toMatchObject({
19-
type: "text",
20-
text: expect.stringContaining("discarded at the retention cap and cannot be recovered"),
21-
});
19+
const content = result.content[0];
20+
expect(content).toMatchObject({ type: "text" });
21+
expect(content?.type === "text" ? content.text : "").toMatch(
22+
/^\[earlier output was discarded at the retention cap and cannot be recovered\]/,
23+
);
2224
expect((result.details as { aggregated?: string }).aggregated).toBe("retained output");
2325
});
2426
});

‎src/agents/bash-tools.exec-support.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { ExecHost } from "../infra/exec-approvals.js";
22
import { requireValidExecTarget } from "../infra/exec-approvals.js";
33
import { normalizeAgentId } from "../routing/session-key.js";
44
import { resolveAgentConfig } from "./agent-scope-config.js";
5-
import { renderExecOutputText } from "./bash-tools.exec-output.js";
5+
import { EXEC_RETENTION_CAP_NOTE, renderExecOutputText } from "./bash-tools.exec-output.js";
66
import type { ExecToolArgs } from "./bash-tools.exec-request-preparation.js";
77
import { type ExecProcessOutcome, resolveExecTarget } from "./bash-tools.exec-runtime.js";
88
import type {
@@ -31,9 +31,7 @@ export function buildExecForegroundResult(params: {
3131
aggregateOutputDropped?: boolean;
3232
}): AgentToolResult<ExecToolDetails> {
3333
const warningText = params.warningText?.trim() ? `${params.warningText}\n\n` : "";
34-
const retentionCapNote = params.aggregateOutputDropped
35-
? "\n\n[earlier output was discarded at the retention cap and cannot be recovered]"
36-
: "";
34+
const retentionCapNote = params.aggregateOutputDropped ? EXEC_RETENTION_CAP_NOTE : "";
3735
if (params.outcome.status === "failed") {
3836
const linuxOomGuidance =
3937
params.outcome.failureKind === "signal" &&
@@ -44,7 +42,7 @@ export function buildExecForegroundResult(params: {
4442
"SIGKILL alone does not identify whether the Linux OOM killer, an operator, or another process sent it. " +
4543
"Check cgroup memory events or kernel logs. If they show memory pressure, narrow the command or adjust memory, concurrency, or resource limits."
4644
: "";
47-
const outputText = `${warningText}${params.outcome.reason}${linuxOomGuidance}${retentionCapNote}`;
45+
const outputText = `${retentionCapNote}${warningText}${params.outcome.reason}${linuxOomGuidance}`;
4846
return failedTextResult(outputText, {
4947
status: "failed",
5048
exitCode: params.outcome.exitCode ?? null,
@@ -58,7 +56,7 @@ export function buildExecForegroundResult(params: {
5856
cwd: params.cwd,
5957
});
6058
}
61-
const outputText = `${warningText}${renderExecOutputText(params.outcome.aggregated)}${retentionCapNote}`;
59+
const outputText = `${retentionCapNote}${warningText}${renderExecOutputText(params.outcome.aggregated)}`;
6260
return textResult(outputText, {
6361
status: "completed",
6462
exitCode: params.outcome.exitCode,

‎src/agents/bash-tools.process.poll-timeout.test.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -456,24 +456,24 @@ test("terminal polls compact tiny stream chunks and never reopen frozen output",
456456
const terminal = await pollSession(processTool, "compact-first", sessionId);
457457
expect(terminal.content[0]).toMatchObject({
458458
text:
459+
"[earlier output was discarded at the retention cap and cannot be recovered]\n\n" +
460+
"[earlier output is omitted from this poll; use action=log with offset and limit to inspect retained output]\n\n" +
459461
"oe".repeat(1_000) +
460-
"\n\n[earlier output was discarded at the retention cap and cannot be recovered]" +
461-
"\n\n[earlier output is omitted from this poll; use action=log with offset and limit to inspect retained output]" +
462462
"\n\nProcess exited with code 0.",
463463
});
464464
appendOutput(session, "stderr", "late".repeat(1_000));
465465
const repeated = await pollSession(processTool, "compact-second", sessionId);
466466
expect(repeated.content[0]).toMatchObject({
467-
text: "(no new output)\n\n[earlier output was discarded at the retention cap and cannot be recovered]\n\nProcess exited with code 0.",
467+
text: "[earlier output was discarded at the retention cap and cannot be recovered]\n\n(no new output)\n\nProcess exited with code 0.",
468468
});
469469
expect(session.totalOutputChars).toBe(4_000);
470470
expect(session.pendingOutput).toBe("");
471471
expect(session.pendingOutputDropped).toBe(false);
472472
const log = await processTool.execute("compact-log", { action: "log", sessionId });
473473
expect(log.content[0]).toMatchObject({
474474
text:
475-
"oe".repeat(1_500) +
476-
"\n\n[earlier output was discarded at the retention cap and cannot be recovered]",
475+
"[earlier output was discarded at the retention cap and cannot be recovered]\n\n" +
476+
"oe".repeat(1_500),
477477
});
478478
});
479479

@@ -753,6 +753,11 @@ test.each([
753753
expect(runningLogText).toContain("discarded at the retention cap and cannot be recovered");
754754
expect(runningPollText).toContain("discarded at the retention cap and cannot be recovered");
755755
expect(finishedLogText).toContain("discarded at the retention cap and cannot be recovered");
756+
for (const resultText of [text, runningLogText, runningPollText, finishedLogText]) {
757+
expect(resultText).toMatch(
758+
/^\[earlier output was discarded at the retention cap and cannot be recovered\]/,
759+
);
760+
}
756761
expect(text).not.toContain("action=log with offset and limit");
757762
},
758763
);

‎src/agents/bash-tools.process.ts‎

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,11 @@ import {
2424
setJobTtlMs,
2525
} from "./bash-process-registry.js";
2626
import { describeProcessTool } from "./bash-tools.descriptions.js";
27-
import { appendExecTimeoutRetryGuidance, renderExecExitLabel } from "./bash-tools.exec-output.js";
27+
import {
28+
EXEC_RETENTION_CAP_NOTE,
29+
appendExecTimeoutRetryGuidance,
30+
renderExecExitLabel,
31+
} from "./bash-tools.exec-output.js";
2832
import {
2933
handleProcessSendKeys,
3034
type WritableStdin,
@@ -100,9 +104,7 @@ function defaultTailNote(totalLines: number, usingDefaultTail: boolean) {
100104
}
101105

102106
function retentionCapNote(session: Pick<ProcessSession, "totalOutputChars" | "aggregated">) {
103-
return session.totalOutputChars > session.aggregated.length
104-
? "\n\n[earlier output was discarded at the retention cap and cannot be recovered]"
105-
: "";
107+
return session.totalOutputChars > session.aggregated.length ? EXEC_RETENTION_CAP_NOTE : "";
106108
}
107109

108110
const MAX_POLL_WAIT_MS = 30_000;
@@ -215,18 +217,18 @@ function finishedPollResult(
215217
// the exact process; a reused slug must never point the model at successor logs.
216218
const retainedOutputNote = outputDropped
217219
? getFinishedSession(sessionId) === finished
218-
? "\n\n[earlier output is omitted from this poll; use action=log with offset and limit to inspect retained output]"
219-
: "\n\n[earlier output is omitted from this poll; omitted output is no longer available through action=log]"
220+
? "[earlier output is omitted from this poll; use action=log with offset and limit to inspect retained output]\n\n"
221+
: "[earlier output is omitted from this poll; omitted output is no longer available through action=log]\n\n"
220222
: "";
221223
return attachInternalToolResultAcknowledgement(
222224
{
223225
content: [
224226
{
225227
type: "text",
226228
text: appendExecTimeoutRetryGuidance(
227-
(output || "(no new output)") +
228-
retentionCapNote(finished) +
229+
retentionCapNote(finished) +
229230
retainedOutputNote +
231+
(output || "(no new output)") +
230232
`\n\nProcess exited with ${renderExecExitLabel(finished)}.`,
231233
finished.exitReason,
232234
),
@@ -484,7 +486,7 @@ export function createProcessTool(
484486
const output = unreadOutput.trim();
485487
const aggregateOutputNote = retentionCapNote(scopedSession);
486488
const retainedOutputNote = outputDropped
487-
? "\n\n[earlier output is omitted from this poll; use action=log with offset and limit to inspect retained output]"
489+
? "[earlier output is omitted from this poll; use action=log with offset and limit to inspect retained output]\n\n"
488490
: "";
489491
const hasNewOutput = output.length > 0;
490492
const retryInMs = recordPollRetrySuggestion(params.sessionId, hasNewOutput);
@@ -495,9 +497,9 @@ export function createProcessTool(
495497
{
496498
type: "text",
497499
text:
498-
(output || "(no new output)") +
499500
aggregateOutputNote +
500501
retainedOutputNote +
502+
(output || "(no new output)") +
501503
(buildInputWaitHint(runtime) || "\n\nProcess still running."),
502504
},
503505
],
@@ -530,9 +532,9 @@ export function createProcessTool(
530532
);
531533
const runtime = scopedSession ? describeRunningSession(scopedSession) : undefined;
532534
const text =
535+
retentionCapNote(record) +
533536
(slice || (scopedSession ? "(no output yet)" : "(no output recorded)")) +
534-
defaultTailNote(totalLines, window.usingDefaultTail) +
535-
retentionCapNote(record);
537+
defaultTailNote(totalLines, window.usingDefaultTail);
536538
return {
537539
content: [
538540
{

‎src/agents/session-tool-result-guard.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { SessionManager } from "openclaw/plugin-sdk/agent-sessions";
66
import { Type } from "typebox";
77
import { describe, expect, it } from "vitest";
88
import { createOpenClawReadTool } from "./agent-tools.read.js";
9+
import { buildExecForegroundResult } from "./bash-tools.exec-support.js";
910
import { installSessionToolResultGuard } from "./session-tool-result-guard.js";
1011
import { castAgentMessage } from "./test-helpers/agent-message-fixtures.js";
1112
import { redactTranscriptMessage } from "./transcript-redact.js";
@@ -193,6 +194,34 @@ describe("installSessionToolResultGuard", () => {
193194
);
194195
});
195196

197+
it("keeps the exec retention-loss disclosure through the session result cap", () => {
198+
const sm = SessionManager.inMemory();
199+
installSessionToolResultGuard(sm, { maxToolResultChars: 4_000 });
200+
const result = buildExecForegroundResult({
201+
outcome: {
202+
status: "completed",
203+
exitCode: 0,
204+
exitSignal: null,
205+
durationMs: 1,
206+
aggregated: "x".repeat(80_000),
207+
timedOut: false,
208+
},
209+
aggregateOutputDropped: true,
210+
});
211+
const content = result.content[0];
212+
if (!content || content.type !== "text") {
213+
throw new Error("expected text result");
214+
}
215+
216+
appendToolResultText(sm, content.text);
217+
218+
const text = getToolResultText(getPersistedMessages(sm));
219+
expect(text).toMatch(
220+
/^\[earlier output was discarded at the retention cap and cannot be recovered\]/,
221+
);
222+
expect(text).toMatch(/\[\.\.\. \d+ more characters truncated/);
223+
});
224+
196225
it("honors tiny configured tool-result caps truthfully", () => {
197226
const sm = SessionManager.inMemory();
198227
installSessionToolResultGuard(sm, {

0 commit comments

Comments
 (0)