Skip to content

Commit e918e5f

Browse files
committed
fix: hide runtime context from submitted prompts
1 parent edb618c commit e918e5f

22 files changed

Lines changed: 1102 additions & 218 deletions

‎.github/workflows/openclaw-live-and-e2e-checks-reusable.yml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,11 @@ jobs:
430430
command: pnpm test:docker:doctor-switch
431431
timeout_minutes: 60
432432
release_path: true
433+
- suite_id: docker-session-runtime-context
434+
label: Session Runtime Context Docker E2E
435+
command: pnpm test:docker:session-runtime-context
436+
timeout_minutes: 60
437+
release_path: true
433438
- suite_id: docker-qr
434439
label: QR Import Docker E2E
435440
command: pnpm test:docker:qr

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,10 @@ Docs: https://docs.openclaw.ai
7979
metadata when callers request the model without the provider prefix, so custom
8080
image models keep their `input: ["text", "image"]` capability. Fixes #33185.
8181
Thanks @Kobe9312 and @vincentkoc.
82+
- Sessions: keep embedded runtime context out of the visible user prompt by
83+
sending it as a hidden next-turn custom message, and teach doctor to repair
84+
affected 2026.4.24 transcripts with duplicated prompt-rewrite branches.
85+
Fixes #71761.
8286
- Gateway/subagents: keep direct-loopback backend RPCs authenticated with the
8387
shared gateway token/password off stale CLI paired-device scope baselines, so
8488
internal calls no longer hit `scope-upgrade` pairing prompts while remote,

‎docs/gateway/doctor.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ cat ~/.openclaw/openclaw.json
7070
- Legacy plugin manifest contract key migration (`speechProviders`, `realtimeTranscriptionProviders`, `realtimeVoiceProviders`, `mediaUnderstandingProviders`, `imageGenerationProviders`, `videoGenerationProviders`, `webFetchProviders`, `webSearchProviders` → `contracts`).
7171
- Legacy cron store migration (`jobId`, `schedule.cron`, top-level delivery/payload fields, payload `provider`, simple `notify: true` webhook fallback jobs).
7272
- Session lock file inspection and stale lock cleanup.
73+
- Session transcript repair for duplicated prompt-rewrite branches created by affected 2026.4.24 builds.
7374
- State integrity and permissions checks (sessions, transcripts, state dir).
7475
- Config file permission checks (chmod 600) when running locally.
7576
- Model auth health: checks OAuth expiry, can refresh expiring tokens, and reports auth-profile cooldown/disabled states.
@@ -317,6 +318,15 @@ considered stale (dead PID or older than 30 minutes). In `--fix` / `--repair`
317318
mode it removes stale lock files automatically; otherwise it prints a note and
318319
instructs you to rerun with `--fix`.
319320

321+
### 3d) Session transcript branch repair
322+
323+
Doctor scans agent session JSONL files for the duplicated branch shape created
324+
by the 2026.4.24 prompt transcript rewrite bug: an abandoned user turn with
325+
OpenClaw internal runtime context plus an active sibling containing the same
326+
visible user prompt. In `--fix` / `--repair` mode, doctor backs up each affected
327+
file next to the original and rewrites the transcript to the active branch so
328+
gateway history and memory readers no longer see duplicate turns.
329+
320330
### 4) State integrity checks (session persistence, routing, and safety)
321331

322332
The state directory is the operational brainstem. If it vanishes, you lose

‎docs/help/testing.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,12 @@ runs the same lanes before release approval.
120120
endpoint.
121121
- Use `OPENCLAW_NPM_ONBOARD_CHANNEL=discord` to run the same packaged-install
122122
lane with Discord.
123+
- `pnpm test:docker:session-runtime-context`
124+
- Runs a deterministic built-app Docker smoke for embedded runtime context
125+
transcripts. It verifies hidden OpenClaw runtime context is persisted as a
126+
non-display custom message instead of leaking into the visible user turn,
127+
then seeds an affected broken session JSONL and verifies
128+
`openclaw doctor --fix` rewrites it to the active branch with a backup.
123129
- `pnpm test:docker:npm-telegram-live`
124130
- Installs a published OpenClaw package in Docker, runs installed-package
125131
onboarding, configures Telegram through the installed CLI, then reuses the
@@ -587,7 +593,7 @@ These Docker runners split into two buckets:
587593
`OPENCLAW_LIVE_GATEWAY_MODEL_TIMEOUT_MS=90000`. Override those env vars when you
588594
explicitly want the larger exhaustive scan.
589595
- `test:docker:all` builds the live Docker image once via `test:docker:live-build`, then reuses it for the live Docker lanes. It also builds one shared `scripts/e2e/Dockerfile` image via `test:docker:e2e-build` and reuses it for the E2E container smoke runners that exercise the built app. The aggregate uses a weighted local scheduler: `OPENCLAW_DOCKER_ALL_PARALLELISM` controls process slots, while resource caps keep heavy live, npm-install, and multi-service lanes from all starting at once. Defaults are 10 slots, `OPENCLAW_DOCKER_ALL_LIVE_LIMIT=6`, `OPENCLAW_DOCKER_ALL_NPM_LIMIT=8`, and `OPENCLAW_DOCKER_ALL_SERVICE_LIMIT=7`; tune `OPENCLAW_DOCKER_ALL_WEIGHT_LIMIT` or `OPENCLAW_DOCKER_ALL_DOCKER_LIMIT` only when the Docker host has more headroom. The runner performs a Docker preflight by default, removes stale OpenClaw E2E containers, prints status every 30 seconds, stores successful lane timings in `.artifacts/docker-tests/lane-timings.json`, and uses those timings to start longer lanes first on later runs. Use `OPENCLAW_DOCKER_ALL_DRY_RUN=1` to print the weighted lane manifest without building or running Docker.
590-
- Container smoke runners: `test:docker:openwebui`, `test:docker:onboard`, `test:docker:npm-onboard-channel-agent`, `test:docker:agents-delete-shared-workspace`, `test:docker:gateway-network`, `test:docker:mcp-channels`, `test:docker:pi-bundle-mcp-tools`, `test:docker:cron-mcp-cleanup`, `test:docker:plugins`, `test:docker:plugin-update`, and `test:docker:config-reload` boot one or more real containers and verify higher-level integration paths.
596+
- Container smoke runners: `test:docker:openwebui`, `test:docker:onboard`, `test:docker:npm-onboard-channel-agent`, `test:docker:session-runtime-context`, `test:docker:agents-delete-shared-workspace`, `test:docker:gateway-network`, `test:docker:mcp-channels`, `test:docker:pi-bundle-mcp-tools`, `test:docker:cron-mcp-cleanup`, `test:docker:plugins`, `test:docker:plugin-update`, and `test:docker:config-reload` boot one or more real containers and verify higher-level integration paths.
591597
592598
The live-model Docker runners also bind-mount only the needed CLI auth homes (or all supported ones when the run is not narrowed), then copy them into the container home before the run so external-CLI OAuth can refresh tokens without mutating the host auth store:
593599
@@ -599,6 +605,7 @@ The live-model Docker runners also bind-mount only the needed CLI auth homes (or
599605
- Open WebUI live smoke: `pnpm test:docker:openwebui` (script: `scripts/e2e/openwebui-docker.sh`)
600606
- Onboarding wizard (TTY, full scaffolding): `pnpm test:docker:onboard` (script: `scripts/e2e/onboard-docker.sh`)
601607
- Npm tarball onboarding/channel/agent smoke: `pnpm test:docker:npm-onboard-channel-agent` installs the packed OpenClaw tarball globally in Docker, configures OpenAI via env-ref onboarding plus Telegram by default, verifies doctor repairs activated plugin runtime deps, and runs one mocked OpenAI agent turn. Reuse a prebuilt tarball with `OPENCLAW_NPM_ONBOARD_PACKAGE_TGZ=/path/to/openclaw-*.tgz`, skip the host rebuild with `OPENCLAW_NPM_ONBOARD_HOST_BUILD=0`, or switch channel with `OPENCLAW_NPM_ONBOARD_CHANNEL=discord`.
608+
- Session runtime context smoke: `pnpm test:docker:session-runtime-context` verifies hidden runtime context transcript persistence plus doctor repair of affected duplicated prompt-rewrite branches.
602609
- Bun global install smoke: `bash scripts/e2e/bun-global-install-smoke.sh` packs the current tree, installs it with `bun install -g` in an isolated home, and verifies `openclaw infer image providers --json` returns bundled image providers instead of hanging. Reuse a prebuilt tarball with `OPENCLAW_BUN_GLOBAL_SMOKE_PACKAGE_TGZ=/path/to/openclaw-*.tgz`, skip the host build with `OPENCLAW_BUN_GLOBAL_SMOKE_HOST_BUILD=0`, or copy `dist/` from a built Docker image with `OPENCLAW_BUN_GLOBAL_SMOKE_DIST_IMAGE=openclaw-dockerfile-smoke:local`.
603610
- Installer Docker smoke: `bash scripts/test-install-sh-docker.sh` shares one npm cache across its root, update, and direct-npm containers. Update smoke defaults to npm `latest` as the stable baseline before upgrading to the candidate tarball. Non-root installer checks keep an isolated npm cache so root-owned cache entries do not mask user-local install behavior. Set `OPENCLAW_INSTALL_SMOKE_NPM_CACHE_DIR=/path/to/cache` to reuse the root/update/direct-npm cache across local reruns.
604611
- Install Smoke CI skips the duplicate direct-npm global update with `OPENCLAW_INSTALL_SMOKE_SKIP_NPM_GLOBAL=1`; run the script locally without that env when direct `npm install -g` coverage is needed.

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1531,6 +1531,7 @@
15311531
"test:docker:plugin-update": "bash scripts/e2e/plugin-update-unchanged-docker.sh",
15321532
"test:docker:plugins": "bash scripts/e2e/plugins-docker.sh",
15331533
"test:docker:qr": "bash scripts/e2e/qr-import-docker.sh",
1534+
"test:docker:session-runtime-context": "bash scripts/e2e/session-runtime-context-docker.sh",
15341535
"test:e2e": "node scripts/run-vitest.mjs run --config test/vitest/vitest.e2e.config.ts",
15351536
"test:e2e:openshell": "OPENCLAW_E2E_OPENSHELL=1 node scripts/run-vitest.mjs run --config test/vitest/vitest.e2e.config.ts extensions/openshell/src/backend.e2e.test.ts",
15361537
"test:extension": "node scripts/test-extension.mjs",
Lines changed: 260 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,260 @@
1+
import { spawnSync } from "node:child_process";
2+
import fs from "node:fs/promises";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import { SessionManager } from "@mariozechner/pi-coding-agent";
6+
import {
7+
queueRuntimeContextForNextTurn,
8+
resolveRuntimeContextPromptParts,
9+
} from "../../src/agents/pi-embedded-runner/run/runtime-context-prompt.js";
10+
11+
type TranscriptEntry = {
12+
type?: string;
13+
customType?: string;
14+
content?: string;
15+
display?: boolean;
16+
message?: {
17+
role?: string;
18+
content?: unknown;
19+
};
20+
};
21+
22+
function assert(condition: unknown, message: string): asserts condition {
23+
if (!condition) {
24+
throw new Error(message);
25+
}
26+
}
27+
28+
async function readJsonl(filePath: string): Promise<TranscriptEntry[]> {
29+
const raw = await fs.readFile(filePath, "utf-8");
30+
return raw
31+
.split(/\r?\n/)
32+
.filter(Boolean)
33+
.map((line) => JSON.parse(line) as TranscriptEntry);
34+
}
35+
36+
function messageText(content: unknown): string {
37+
if (typeof content === "string") {
38+
return content;
39+
}
40+
if (!Array.isArray(content)) {
41+
return "";
42+
}
43+
return content
44+
.map((part) =>
45+
part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string"
46+
? (part as { text: string }).text
47+
: "",
48+
)
49+
.join("");
50+
}
51+
52+
async function verifyRuntimeContextTranscriptShape(root: string) {
53+
const sessionFile = path.join(root, ".openclaw", "agents", "main", "sessions", "runtime.jsonl");
54+
await fs.mkdir(path.dirname(sessionFile), { recursive: true });
55+
const sessionManager = SessionManager.open(sessionFile);
56+
const effectivePrompt = [
57+
"visible ask",
58+
"",
59+
"<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>",
60+
"secret docker context",
61+
"<<<END_OPENCLAW_INTERNAL_CONTEXT>>>",
62+
].join("\n");
63+
const promptSubmission = resolveRuntimeContextPromptParts({
64+
effectivePrompt,
65+
transcriptPrompt: "visible ask",
66+
});
67+
68+
assert(promptSubmission.prompt === "visible ask", "visible prompt was not preserved");
69+
assert(
70+
promptSubmission.runtimeContext?.includes("secret docker context"),
71+
"runtime context was not extracted",
72+
);
73+
74+
await queueRuntimeContextForNextTurn({
75+
runtimeContext: promptSubmission.runtimeContext,
76+
session: {
77+
sendCustomMessage: async (message, options) => {
78+
assert(options?.deliverAs === "nextTurn", "runtime context was not queued for next turn");
79+
sessionManager.appendCustomMessageEntry(
80+
message.customType,
81+
message.content,
82+
message.display,
83+
message.details,
84+
);
85+
},
86+
},
87+
});
88+
sessionManager.appendMessage({
89+
role: "user",
90+
content: promptSubmission.prompt,
91+
timestamp: Date.now(),
92+
});
93+
sessionManager.appendMessage({
94+
role: "assistant",
95+
content: "done",
96+
timestamp: Date.now() + 1,
97+
});
98+
99+
const entries = await readJsonl(sessionFile);
100+
const customEntry = entries.find((entry) => entry.type === "custom_message");
101+
assert(customEntry, "hidden runtime custom message was not persisted");
102+
assert(customEntry.customType === "openclaw.runtime-context", "unexpected custom message type");
103+
assert(customEntry.display === false, "runtime custom message should be hidden");
104+
assert(
105+
customEntry.content?.includes("secret docker context"),
106+
"runtime custom message lost context",
107+
);
108+
109+
const userEntries = entries.filter((entry) => entry.message?.role === "user");
110+
assert(userEntries.length === 1, `expected one visible user message, got ${userEntries.length}`);
111+
const userText = messageText(userEntries[0]?.message?.content);
112+
assert(userText === "visible ask", `unexpected visible user text: ${JSON.stringify(userText)}`);
113+
assert(
114+
!userText.includes("OPENCLAW_INTERNAL_CONTEXT") && !userText.includes("secret docker context"),
115+
"visible user transcript leaked runtime context",
116+
);
117+
}
118+
119+
async function seedBrokenSession(stateDir: string): Promise<string> {
120+
const sessionsDir = path.join(stateDir, "agents", "main", "sessions");
121+
const sessionFile = path.join(sessionsDir, "broken.jsonl");
122+
await fs.mkdir(sessionsDir, { recursive: true });
123+
const entries = [
124+
{ type: "session", version: 3, id: "broken-session" },
125+
{
126+
type: "message",
127+
id: "parent",
128+
parentId: null,
129+
message: { role: "assistant", content: "previous" },
130+
},
131+
{
132+
type: "message",
133+
id: "runtime-user",
134+
parentId: "parent",
135+
message: {
136+
role: "user",
137+
content: [
138+
"visible ask",
139+
"",
140+
"<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>",
141+
"secret doctor context",
142+
"<<<END_OPENCLAW_INTERNAL_CONTEXT>>>",
143+
].join("\n"),
144+
},
145+
},
146+
{
147+
type: "message",
148+
id: "runtime-assistant",
149+
parentId: "runtime-user",
150+
message: { role: "assistant", content: "stale branch" },
151+
},
152+
{
153+
type: "message",
154+
id: "plain-user",
155+
parentId: "parent",
156+
message: { role: "user", content: "visible ask" },
157+
},
158+
{
159+
type: "message",
160+
id: "plain-assistant",
161+
parentId: "plain-user",
162+
message: { role: "assistant", content: "active answer" },
163+
},
164+
];
165+
await fs.writeFile(
166+
sessionFile,
167+
`${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`,
168+
"utf-8",
169+
);
170+
await fs.writeFile(
171+
path.join(sessionsDir, "sessions.json"),
172+
JSON.stringify(
173+
{
174+
"agent:main:qa:docker-runtime-context": {
175+
sessionId: "broken",
176+
sessionFile: "broken.jsonl",
177+
updatedAt: Date.now(),
178+
displayName: "Docker runtime context repair",
179+
},
180+
},
181+
null,
182+
2,
183+
),
184+
"utf-8",
185+
);
186+
return sessionFile;
187+
}
188+
189+
async function verifyDoctorRepair(root: string) {
190+
const stateDir = path.join(root, ".openclaw");
191+
const configPath = path.join(stateDir, "openclaw.json");
192+
const sessionFile = await seedBrokenSession(stateDir);
193+
await fs.mkdir(path.dirname(configPath), { recursive: true });
194+
await fs.writeFile(configPath, JSON.stringify({ plugins: { enabled: false } }, null, 2));
195+
196+
const entry = await fs.stat("dist/index.mjs").then(
197+
() => "dist/index.mjs",
198+
() => "dist/index.js",
199+
);
200+
const result = spawnSync(process.execPath, [entry, "doctor", "--fix", "--yes", "--force"], {
201+
cwd: process.cwd(),
202+
env: {
203+
...process.env,
204+
HOME: root,
205+
OPENCLAW_CONFIG_PATH: configPath,
206+
OPENCLAW_DISABLE_BONJOUR: "1",
207+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
208+
OPENCLAW_NO_ONBOARD: "1",
209+
OPENCLAW_STATE_DIR: stateDir,
210+
OPENCLAW_SKIP_CANVAS_HOST: "1",
211+
OPENCLAW_SKIP_CHANNELS: "1",
212+
OPENCLAW_SKIP_CRON: "1",
213+
OPENCLAW_SKIP_GMAIL_WATCHER: "1",
214+
},
215+
encoding: "utf-8",
216+
timeout: 120_000,
217+
});
218+
219+
assert(
220+
result.status === 0,
221+
`doctor --fix failed\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`,
222+
);
223+
const entries = await readJsonl(sessionFile);
224+
const ids = entries.map((entry) => (entry as { id?: string }).id).filter(Boolean);
225+
assert(
226+
JSON.stringify(ids) ===
227+
JSON.stringify(["broken-session", "parent", "plain-user", "plain-assistant"]),
228+
`doctor kept wrong active branch: ${JSON.stringify(ids)}`,
229+
);
230+
assert(
231+
entries.every(
232+
(entry) => !messageText(entry.message?.content).includes("secret doctor context"),
233+
),
234+
"doctor repair left runtime context in active transcript",
235+
);
236+
const backups = (await fs.readdir(path.dirname(sessionFile))).filter((name) =>
237+
name.includes(".pre-doctor-branch-repair-"),
238+
);
239+
assert(backups.length === 1, `expected one doctor backup, got ${backups.length}`);
240+
}
241+
242+
async function main() {
243+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-session-runtime-context-"));
244+
process.env.HOME = root;
245+
process.env.OPENCLAW_STATE_DIR = path.join(root, ".openclaw");
246+
process.env.OPENCLAW_CONFIG_PATH = path.join(process.env.OPENCLAW_STATE_DIR, "openclaw.json");
247+
try {
248+
await verifyRuntimeContextTranscriptShape(root);
249+
await verifyDoctorRepair(root);
250+
console.log("session runtime context Docker E2E passed");
251+
} finally {
252+
if (process.env.OPENCLAW_SESSION_RUNTIME_CONTEXT_KEEP_ARTIFACTS !== "1") {
253+
await fs.rm(root, { recursive: true, force: true });
254+
} else {
255+
console.error(`kept artifacts: ${root}`);
256+
}
257+
}
258+
}
259+
260+
await main();
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#!/usr/bin/env bash
2+
set -euo pipefail
3+
4+
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
5+
source "$ROOT_DIR/scripts/lib/docker-e2e-image.sh"
6+
7+
IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-session-runtime-context-e2e" OPENCLAW_SESSION_RUNTIME_CONTEXT_E2E_IMAGE)"
8+
CONTAINER_NAME="openclaw-session-runtime-context-e2e-$$"
9+
RUN_LOG="$(mktemp -t openclaw-session-runtime-context-log.XXXXXX)"
10+
11+
cleanup() {
12+
docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true
13+
rm -f "$RUN_LOG"
14+
}
15+
trap cleanup EXIT
16+
17+
docker_e2e_build_or_reuse "$IMAGE_NAME" session-runtime-context
18+
19+
echo "Running session runtime context Docker E2E..."
20+
set +e
21+
docker run --rm \
22+
--name "$CONTAINER_NAME" \
23+
-e COREPACK_ENABLE_DOWNLOAD_PROMPT=0 \
24+
"$IMAGE_NAME" \
25+
bash -lc 'set -euo pipefail; node --import tsx scripts/e2e/session-runtime-context-docker-client.ts' \
26+
>"$RUN_LOG" 2>&1
27+
status=$?
28+
set -e
29+
30+
if [ "$status" -ne 0 ]; then
31+
echo "Docker session runtime context smoke failed"
32+
cat "$RUN_LOG"
33+
exit "$status"
34+
fi
35+
36+
echo "OK"

‎scripts/test-docker-all.mjs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,10 @@ const lanes = [
254254
"crestodian-first-run",
255255
"OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:crestodian-first-run",
256256
),
257+
lane(
258+
"session-runtime-context",
259+
"OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:session-runtime-context",
260+
),
257261
lane("qr", "pnpm test:docker:qr"),
258262
];
259263

0 commit comments

Comments
 (0)