Skip to content

Commit c406ef4

Browse files
authored
test: consolidate prompt snapshot deltas (#129295)
1 parent 971feb5 commit c406ef4

13 files changed

Lines changed: 433 additions & 1467 deletions

‎scripts/generate-prompt-snapshots.ts‎

Lines changed: 150 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,19 @@
11
// Generate Prompt Snapshots script supports OpenClaw repository automation.
22
import { execFile } from "node:child_process";
3+
import { createHash } from "node:crypto";
34
import fs from "node:fs/promises";
45
import os from "node:os";
56
import path from "node:path";
67
import { fileURLToPath, pathToFileURL } from "node:url";
78
import { promisify } from "node:util";
9+
import { applyPatch, createTwoFilesPatch, FILE_HEADERS_ONLY, parsePatch } from "diff";
810
import { createHappyPathPromptSnapshotFiles } from "../test/helpers/agents/happy-path-prompt-snapshots.js";
9-
import { CODEX_RUNTIME_HAPPY_PATH_PROMPT_SNAPSHOT_DIR } from "../test/helpers/agents/prompt-snapshot-paths.js";
11+
import {
12+
CODEX_PROMPT_SNAPSHOT_BASE_SCENARIO,
13+
CODEX_PROMPT_SNAPSHOT_FILES,
14+
CODEX_RUNTIME_HAPPY_PATH_PROMPT_SNAPSHOT_DIR,
15+
type CodexPromptSnapshotScenario,
16+
} from "../test/helpers/agents/prompt-snapshot-paths.js";
1017
import { coerceErrorMessage as describeError } from "./lib/error-format.mts";
1118
import {
1219
deleteStalePromptSnapshotFiles,
@@ -31,6 +38,116 @@ type CodexDynamicToolSnapshotOverrides = {
3138

3239
const CODEX_DYNAMIC_TOOL_SNAPSHOT_PREFIX = "codex-dynamic-tools.";
3340
const CODEX_DYNAMIC_TOOL_BASE_SNAPSHOT = `${CODEX_DYNAMIC_TOOL_SNAPSHOT_PREFIX}telegram-direct.json`;
41+
const SHA256_HEADER_PATTERN = /^sha256=([a-f0-9]{64})$/u;
42+
43+
function promptSnapshotEntries(): Array<[CodexPromptSnapshotScenario, string]> {
44+
return Object.entries(CODEX_PROMPT_SNAPSHOT_FILES) as Array<
45+
[CodexPromptSnapshotScenario, string]
46+
>;
47+
}
48+
49+
function resolvePromptSnapshotFileName(scenario: string): string {
50+
if (!Object.hasOwn(CODEX_PROMPT_SNAPSHOT_FILES, scenario)) {
51+
throw new Error(`Unknown Codex prompt snapshot scenario: ${scenario}`);
52+
}
53+
return CODEX_PROMPT_SNAPSHOT_FILES[scenario as CodexPromptSnapshotScenario];
54+
}
55+
56+
function sha256(content: string): string {
57+
return createHash("sha256").update(content).digest("hex");
58+
}
59+
60+
function readSha256Header(header: string | undefined, label: string): string {
61+
const hash = SHA256_HEADER_PATTERN.exec(header ?? "")?.[1];
62+
if (!hash) {
63+
throw new Error(`Invalid Codex prompt snapshot ${label} hash header`);
64+
}
65+
return hash;
66+
}
67+
68+
function createCodexPromptSnapshotDelta(scenario: string, base: string, target: string): string {
69+
const targetFileName = resolvePromptSnapshotFileName(scenario);
70+
const baseFileName = CODEX_PROMPT_SNAPSHOT_FILES[CODEX_PROMPT_SNAPSHOT_BASE_SCENARIO];
71+
if (targetFileName === baseFileName) {
72+
throw new Error("The canonical Codex prompt snapshot does not use a delta");
73+
}
74+
return createTwoFilesPatch(
75+
baseFileName,
76+
targetFileName,
77+
base,
78+
target,
79+
`sha256=${sha256(base)}`,
80+
`sha256=${sha256(target)}`,
81+
{ context: 0, headerOptions: FILE_HEADERS_ONLY },
82+
);
83+
}
84+
85+
/** Strictly materialize one SHA-bound, zero-context prompt snapshot delta. */
86+
export function materializeCodexPromptSnapshotDelta(params: {
87+
scenario: string;
88+
base: string;
89+
delta: string;
90+
}): string {
91+
const targetFileName = resolvePromptSnapshotFileName(params.scenario);
92+
const baseFileName = CODEX_PROMPT_SNAPSHOT_FILES[CODEX_PROMPT_SNAPSHOT_BASE_SCENARIO];
93+
let patches;
94+
try {
95+
patches = parsePatch(params.delta);
96+
} catch (error) {
97+
throw new Error("Invalid Codex prompt snapshot delta", { cause: error });
98+
}
99+
const patch = patches[0];
100+
if (patches.length !== 1 || !patch) {
101+
throw new Error("Codex prompt snapshot delta must contain exactly one patch");
102+
}
103+
if (patch.oldFileName !== baseFileName || patch.newFileName !== targetFileName) {
104+
throw new Error("Codex prompt snapshot delta file names do not match the scenario");
105+
}
106+
const sourceHash = readSha256Header(patch.oldHeader, "source");
107+
const targetHash = readSha256Header(patch.newHeader, "target");
108+
if (sha256(params.base) !== sourceHash) {
109+
throw new Error("Codex prompt snapshot delta source hash does not match the canonical base");
110+
}
111+
const materialized = applyPatch(params.base, patch, {
112+
fuzzFactor: 0,
113+
autoConvertLineEndings: false,
114+
});
115+
if (materialized === false || sha256(materialized) !== targetHash) {
116+
throw new Error("Codex prompt snapshot delta did not materialize its target hash");
117+
}
118+
if (createCodexPromptSnapshotDelta(params.scenario, params.base, materialized) !== params.delta) {
119+
throw new Error("Codex prompt snapshot delta is not canonical zero-context output");
120+
}
121+
return materialized;
122+
}
123+
124+
function factorCodexPromptSnapshotFiles(files: PromptSnapshotFile[]): PromptSnapshotFile[] {
125+
const byFileName = new Map(files.map((file) => [path.basename(file.path), file]));
126+
const baseFileName = CODEX_PROMPT_SNAPSHOT_FILES[CODEX_PROMPT_SNAPSHOT_BASE_SCENARIO];
127+
const base = byFileName.get(baseFileName);
128+
if (!base) {
129+
throw new Error(`Missing canonical Codex prompt snapshot: ${baseFileName}`);
130+
}
131+
return files.map((file) => {
132+
const scenario = promptSnapshotEntries().find(
133+
([, fileName]) => fileName === path.basename(file.path),
134+
);
135+
if (!scenario || scenario[0] === CODEX_PROMPT_SNAPSHOT_BASE_SCENARIO) {
136+
return file;
137+
}
138+
const delta = createCodexPromptSnapshotDelta(scenario[0], base.content, file.content);
139+
if (
140+
materializeCodexPromptSnapshotDelta({
141+
scenario: scenario[0],
142+
base: base.content,
143+
delta,
144+
}) !== file.content
145+
) {
146+
throw new Error(`Codex prompt snapshot delta roundtrip failed: ${scenario[0]}`);
147+
}
148+
return { path: `${file.path}.diff`, content: delta };
149+
});
150+
}
34151

35152
async function writeSnapshotFiles(root: string, files: PromptSnapshotFile[]) {
36153
await Promise.all(
@@ -118,7 +235,26 @@ async function formatPromptSnapshotFiles(
118235

119236
async function createFormattedPromptSnapshotFiles(): Promise<PromptSnapshotFile[]> {
120237
const files = await createHappyPathPromptSnapshotFiles();
121-
return await formatPromptSnapshotFiles(factorCodexDynamicToolSnapshotFiles(files));
238+
const formatted = await formatPromptSnapshotFiles(factorCodexDynamicToolSnapshotFiles(files));
239+
return factorCodexPromptSnapshotFiles(formatted);
240+
}
241+
242+
/** Materialize one complete, formatted Codex prompt snapshot for human review. */
243+
export async function materializeCodexPromptSnapshot(scenario: string): Promise<string> {
244+
const targetFileName = resolvePromptSnapshotFileName(scenario);
245+
const baseFileName = CODEX_PROMPT_SNAPSHOT_FILES[CODEX_PROMPT_SNAPSHOT_BASE_SCENARIO];
246+
const base = await fs.readFile(
247+
path.resolve(repoRoot, CODEX_RUNTIME_HAPPY_PATH_PROMPT_SNAPSHOT_DIR, baseFileName),
248+
"utf8",
249+
);
250+
if (targetFileName === baseFileName) {
251+
return base;
252+
}
253+
const delta = await fs.readFile(
254+
path.resolve(repoRoot, CODEX_RUNTIME_HAPPY_PATH_PROMPT_SNAPSHOT_DIR, `${targetFileName}.diff`),
255+
"utf8",
256+
);
257+
return materializeCodexPromptSnapshotDelta({ scenario, base, delta });
122258
}
123259

124260
/** Materialize one complete, formatted Codex dynamic-tool catalog for human review. */
@@ -211,6 +347,18 @@ async function checkSnapshots() {
211347
}
212348

213349
async function runPromptSnapshotGenerator(argv = process.argv.slice(2)) {
350+
if (argv[0] === "--materialize-prompt") {
351+
const scenario = argv[1];
352+
if (!scenario || argv.length !== 2) {
353+
console.error(
354+
"Usage: node --import tsx scripts/generate-prompt-snapshots.ts --materialize-prompt <scenario>",
355+
);
356+
process.exitCode = 2;
357+
return;
358+
}
359+
process.stdout.write(await materializeCodexPromptSnapshot(scenario));
360+
return;
361+
}
214362
if (argv[0] === "--materialize") {
215363
const scenario = argv[1];
216364
if (!scenario || argv.length !== 2) {

‎scripts/prompt-snapshot-files.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export async function listCommittedSnapshotArtifactPaths(root: string): Promise<
2020
committedEntries = [];
2121
}
2222
return committedEntries
23-
.filter((entry) => entry.endsWith(".md") || entry.endsWith(".json"))
23+
.filter((entry) => /\.(?:json|md(?:\.(?:diff|patch))?)$/u.test(entry))
2424
.map((entry) => path.join(CODEX_RUNTIME_HAPPY_PATH_PROMPT_SNAPSHOT_DIR, entry));
2525
}
2626

‎scripts/test-projects.test-support.mts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3046,7 +3046,9 @@ function shouldRouteChangedTargetWithoutImportGraph(changedPath: string) {
30463046
}
30473047

30483048
function resolvePromptSnapshotFixtureTargets(changedPath: string) {
3049-
if (!/^test\/fixtures\/agents\/prompt-snapshots\/.+\.(?:json|md)$/u.test(changedPath)) {
3049+
if (
3050+
!/^test\/fixtures\/agents\/prompt-snapshots\/.+\.(?:json|md(?:\.diff)?)$/u.test(changedPath)
3051+
) {
30503052
return null;
30513053
}
30523054
return ["test/scripts/prompt-snapshots.test.ts"];

‎test/fixtures/agents/prompt-snapshots/codex-runtime-happy-path/README.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@ These fixtures capture the default OpenAI/Codex happy path for prompt review:
88
- Codex harness default coverage for tool-only visible source replies.
99
- Telegram direct chat, Discord group chat, and a heartbeat turn with `heartbeat_respond` available through searchable dynamic tools.
1010

11-
The Markdown files show selected app-server thread/turn params plus a reconstructed model-bound prompt layer stack: Codex `gpt-5.5` model instructions from a pinned Codex model catalog fixture, Codex permission developer instructions for the happy-path yolo profile, OpenClaw developer instructions, turn input with simulated OpenClaw workspace bootstrap runtime context, and references to the complete dynamic tool catalog.
11+
The materialized Markdown snapshots show selected app-server thread/turn params plus a reconstructed model-bound prompt layer stack: Codex `gpt-5.5` model instructions from a pinned Codex model catalog fixture, Codex permission developer instructions for the happy-path yolo profile, OpenClaw developer instructions, turn input with simulated OpenClaw workspace bootstrap runtime context, and references to the complete dynamic tool catalog.
1212

1313
The workspace bootstrap simulation includes dummy workspace contents so prompt reviewers can see how OpenClaw routes stable profile files into Codex developer instructions and keeps `MEMORY.md` in turn input. `AGENTS.md` is intentionally not repeated here because Codex loads it natively.
1414

1515
The tool catalog is pinned to the canonical happy-path OpenClaw tools so optional locally installed plugin tools do not create fixture churn.
1616

17+
The Telegram Markdown file is the complete canonical prompt snapshot. Discord and heartbeat are readable, SHA-bound zero-context `.md.diff` files with complete lossless differences from that base. Materialize one with `node --import tsx scripts/generate-prompt-snapshots.ts --materialize-prompt discord-group`; replace the scenario with `heartbeat-turn` or `telegram-direct` as needed.
18+
1719
The Telegram JSON is the complete shared tool catalog. Discord and heartbeat JSON fixtures contain readable, complete replacements for their changed top-level tools or namespaces; their `base` field points to the Telegram catalog.
1820

1921
Materialize the complete, formatted tool catalog for a scenario with:
@@ -47,8 +49,8 @@ pnpm prompt:snapshots:check
4749
Snapshots:
4850

4951
- telegram-direct-codex-message-tool.md
50-
- discord-group-codex-message-tool.md
51-
- telegram-heartbeat-codex-tool.md
52+
- discord-group-codex-message-tool.md.diff
53+
- telegram-heartbeat-codex-tool.md.diff
5254
- codex-dynamic-tools.telegram-direct.json
5355
- codex-dynamic-tools.discord-group.json
5456
- codex-dynamic-tools.heartbeat-turn.json

0 commit comments

Comments
 (0)