Skip to content

Commit 6ea01ac

Browse files
committed
fix(doctor): atomically repair session transcripts
1 parent 9050d9b commit 6ea01ac

2 files changed

Lines changed: 174 additions & 42 deletions

File tree

‎src/commands/doctor-session-transcripts.test.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,31 @@ const repairCanonicalSessionKeys = vi.hoisted(() => vi.fn());
1414
const migrateLegacyMainSessionKeys = vi.hoisted(() => vi.fn());
1515
const runDoctorSessionSqlite = vi.hoisted(() => vi.fn());
1616
const withDoctorSqliteMaintenanceLock = vi.hoisted(() => vi.fn());
17+
const atomicWriteControl = vi.hoisted(() => ({
18+
beforeRename: undefined as undefined | ((filePath: string) => Promise<void>),
19+
}));
1720

1821
vi.mock("../../packages/terminal-core/src/note.js", () => ({
1922
note,
2023
}));
2124

25+
vi.mock("../infra/json-files.js", async (importOriginal) => {
26+
const actual = await importOriginal<typeof import("../infra/json-files.js")>();
27+
return {
28+
...actual,
29+
writeTextAtomic: async (...args: Parameters<typeof actual.writeTextAtomic>) => {
30+
const [filePath, content, options] = args;
31+
return await actual.writeTextAtomic(filePath, content, {
32+
...options,
33+
beforeRename: async (params) => {
34+
await options?.beforeRename?.(params);
35+
await atomicWriteControl.beforeRename?.(filePath);
36+
},
37+
});
38+
},
39+
};
40+
});
41+
2242
vi.mock("./doctor-session-sqlite.js", () => ({
2343
runDoctorSessionSqlite,
2444
}));
@@ -115,6 +135,7 @@ describe("doctor session transcript repair", () => {
115135
let root: string;
116136

117137
beforeEach(async () => {
138+
atomicWriteControl.beforeRename = undefined;
118139
note.mockClear();
119140
repairReservedIncognitoSessionKeys.mockReset().mockReturnValue({ found: 0, repaired: 0 });
120141
repairCanonicalSessionDeliveryStates
@@ -224,6 +245,94 @@ describe("doctor session transcript repair", () => {
224245
).toEqual(["parent", "plain-user", "plain-assistant"]);
225246
});
226247

248+
it.each([
249+
{
250+
name: "prompt-rewrite branch",
251+
entries: [
252+
{ type: "session", version: 3, id: "session-1", timestamp: "2026-04-25T00:00:00Z" },
253+
{
254+
type: "message",
255+
id: "parent",
256+
parentId: null,
257+
message: { role: "assistant", content: "previous" },
258+
},
259+
{
260+
type: "message",
261+
id: "runtime-user",
262+
parentId: "parent",
263+
message: {
264+
role: "user",
265+
content:
266+
"visible ask\n\n<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>\nsecret\n<<<END_OPENCLAW_INTERNAL_CONTEXT>>>",
267+
},
268+
},
269+
{
270+
type: "message",
271+
id: "runtime-assistant",
272+
parentId: "runtime-user",
273+
message: { role: "assistant", content: "stale" },
274+
},
275+
{
276+
type: "message",
277+
id: "plain-user",
278+
parentId: "parent",
279+
message: { role: "user", content: "visible ask" },
280+
},
281+
{
282+
type: "message",
283+
id: "plain-assistant",
284+
parentId: "plain-user",
285+
message: { role: "assistant", content: "answer" },
286+
},
287+
],
288+
},
289+
{
290+
name: "legacy OpenAI Codex metadata",
291+
entries: [
292+
{ type: "session", version: 3, id: "session-1", timestamp: "2026-04-25T00:00:00Z" },
293+
{
294+
type: "message",
295+
id: "legacy-assistant",
296+
parentId: null,
297+
message: {
298+
role: "assistant",
299+
provider: "openai-codex",
300+
api: "openai-codex-responses",
301+
content: [{ type: "text", text: "hello" }],
302+
},
303+
},
304+
],
305+
},
306+
])("preserves and reports $name when atomic publication fails", async ({ entries }) => {
307+
const filePath = await writeTranscript(entries);
308+
const original = await fs.readFile(filePath, "utf-8");
309+
atomicWriteControl.beforeRename = async () => {
310+
throw new Error("injected transcript rename failure");
311+
};
312+
313+
await noteSessionTranscriptHealth({
314+
sessionDirs: [path.dirname(filePath)],
315+
shouldRepair: true,
316+
});
317+
318+
expect(await fs.readFile(filePath, "utf-8")).toBe(original);
319+
const backupName = (await fs.readdir(path.dirname(filePath))).find(
320+
(entry) => entry.startsWith("session.jsonl.pre-doctor-") && entry.endsWith(".bak"),
321+
);
322+
expect(backupName).toEqual(expect.any(String));
323+
if (!backupName) {
324+
throw new Error("expected transcript repair backup");
325+
}
326+
expect(await fs.readFile(path.join(path.dirname(filePath), backupName), "utf-8")).toBe(
327+
original,
328+
);
329+
const transcriptNote = note.mock.calls.find((call) => call[1] === "Session transcripts")?.[0];
330+
expect(transcriptNote).toContain("needs repair");
331+
expect(transcriptNote).toContain("backup=");
332+
expect(transcriptNote).toContain("injected transcript rename failure");
333+
expect(transcriptNote).not.toContain("Repaired 1 transcript file");
334+
});
335+
227336
it("reports affected transcripts without rewriting outside repair mode", async () => {
228337
const filePath = await writeTranscript([
229338
{ type: "session", version: 3, id: "session-1", timestamp: "2026-04-25T00:00:00Z" },

‎src/commands/doctor-session-transcripts.ts‎

Lines changed: 65 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
} from "../config/sessions/transcript-tree.js";
2020
import type { OpenClawConfig } from "../config/types.openclaw.js";
2121
import type { HealthFinding, HealthRepairEffect } from "../flows/health-checks.js";
22+
import { writeTextAtomic } from "../infra/json-files.js";
2223
import { shortenHomePath } from "../utils.js";
2324
import {
2425
repairCanonicalSessionKeys,
@@ -255,15 +256,11 @@ async function writeActiveTranscript(params: {
255256
filePath: string;
256257
entries: TranscriptEntry[];
257258
activePath: ActiveTranscriptPath;
258-
}): Promise<string> {
259+
}): Promise<void> {
259260
const header = params.entries.find((entry) => entry.type === "session");
260261
if (!header) {
261262
throw new Error("missing session header");
262263
}
263-
const backupPath = `${params.filePath}.pre-doctor-branch-repair-${new Date()
264-
.toISOString()
265-
.replace(/[:.]/g, "-")}.bak`;
266-
await fs.copyFile(params.filePath, backupPath);
267264
const lastPersistedId = getEntryId(params.activePath.entriesToPersist.at(-1) ?? {});
268265
const terminalLeafControl = params.activePath.terminalLeafControl
269266
? {
@@ -279,21 +276,45 @@ async function writeActiveTranscript(params: {
279276
]
280277
.map((entry) => JSON.stringify(entry))
281278
.join("\n");
282-
await fs.writeFile(params.filePath, `${next}\n`, "utf-8");
283-
return backupPath;
279+
await writeTextAtomic(params.filePath, next, {
280+
tempPrefix: `${path.basename(params.filePath)}.doctor-repair`,
281+
trailingNewline: true,
282+
});
284283
}
285284

286285
async function writeTranscriptEntries(params: {
287286
filePath: string;
288287
entries: TranscriptEntry[];
289-
}): Promise<string> {
290-
const backupPath = `${params.filePath}.pre-doctor-openai-codex-repair-${new Date()
291-
.toISOString()
292-
.replace(/[:.]/g, "-")}.bak`;
293-
await fs.copyFile(params.filePath, backupPath);
288+
}): Promise<void> {
294289
const next = params.entries.map((entry) => JSON.stringify(entry)).join("\n");
295-
await fs.writeFile(params.filePath, `${next}\n`, "utf-8");
296-
return backupPath;
290+
await writeTextAtomic(params.filePath, next, {
291+
tempPrefix: `${path.basename(params.filePath)}.doctor-repair`,
292+
trailingNewline: true,
293+
});
294+
}
295+
296+
async function publishTranscriptRepair(params: {
297+
result: SessionTranscriptHealthIssue;
298+
backupLabel: "branch-repair" | "openai-codex-repair";
299+
write: () => Promise<void>;
300+
}): Promise<TranscriptRepairResult> {
301+
let backupPath: string | undefined;
302+
try {
303+
const nextBackupPath = `${params.result.filePath}.pre-doctor-${params.backupLabel}-${new Date()
304+
.toISOString()
305+
.replace(/[:.]/g, "-")}.bak`;
306+
await fs.copyFile(params.result.filePath, nextBackupPath);
307+
backupPath = nextBackupPath;
308+
await params.write();
309+
return { ...params.result, repaired: true, backupPath };
310+
} catch (err) {
311+
return {
312+
...params.result,
313+
repaired: false,
314+
...(backupPath ? { backupPath } : {}),
315+
reason: String(err),
316+
};
317+
}
297318
}
298319

299320
/** Repairs one transcript file by keeping the active branch and backing up the original file. */
@@ -308,17 +329,19 @@ async function repairBrokenSessionTranscriptFile(params: {
308329
const activePath = selectActivePath(entries);
309330
if (!activePath) {
310331
if (legacyOpenAICodexEntries > 0 && params.shouldRepair) {
311-
const backupPath = await writeTranscriptEntries({ filePath: params.filePath, entries });
312-
return {
313-
filePath: params.filePath,
314-
broken: true,
315-
repaired: true,
316-
originalEntries: entries.length,
317-
activeEntries: 0,
318-
legacyOpenAICodexEntries,
319-
backupPath,
320-
reason: "no active branch",
321-
};
332+
return await publishTranscriptRepair({
333+
result: {
334+
filePath: params.filePath,
335+
broken: true,
336+
repaired: false,
337+
originalEntries: entries.length,
338+
activeEntries: 0,
339+
legacyOpenAICodexEntries,
340+
reason: "no active branch",
341+
},
342+
backupLabel: "openai-codex-repair",
343+
write: () => writeTranscriptEntries({ filePath: params.filePath, entries }),
344+
});
322345
}
323346
return {
324347
filePath: params.filePath,
@@ -351,22 +374,21 @@ async function repairBrokenSessionTranscriptFile(params: {
351374
legacyOpenAICodexEntries,
352375
};
353376
}
354-
const backupPath = broken
355-
? await writeActiveTranscript({
356-
filePath: params.filePath,
357-
entries,
358-
activePath,
359-
})
360-
: await writeTranscriptEntries({ filePath: params.filePath, entries });
361-
return {
362-
filePath: params.filePath,
363-
broken: true,
364-
repaired: true,
365-
originalEntries: entries.length,
366-
activeEntries: activePath.entries.length,
367-
legacyOpenAICodexEntries,
368-
backupPath,
369-
};
377+
return await publishTranscriptRepair({
378+
result: {
379+
filePath: params.filePath,
380+
broken: true,
381+
repaired: false,
382+
originalEntries: entries.length,
383+
activeEntries: activePath.entries.length,
384+
legacyOpenAICodexEntries,
385+
},
386+
backupLabel: broken ? "branch-repair" : "openai-codex-repair",
387+
write: () =>
388+
broken
389+
? writeActiveTranscript({ filePath: params.filePath, entries, activePath })
390+
: writeTranscriptEntries({ filePath: params.filePath, entries }),
391+
});
370392
} catch (err) {
371393
return {
372394
filePath: params.filePath,
@@ -483,11 +505,12 @@ export async function noteSessionTranscriptHealth(params?: {
483505
...broken.slice(0, 20).map((result) => {
484506
const backup = result.backupPath ? ` backup=${shortenHomePath(result.backupPath)}` : "";
485507
const status = result.repaired ? "repaired" : "needs repair";
508+
const error = !result.repaired && result.reason ? ` error=${result.reason}` : "";
486509
const metadata =
487510
result.legacyOpenAICodexEntries > 0
488511
? ` openai-codex=${result.legacyOpenAICodexEntries}`
489512
: "";
490-
return `- ${shortenHomePath(result.filePath)} ${status} entries=${result.originalEntries}->${result.activeEntries + 1}${metadata}${backup}`;
513+
return `- ${shortenHomePath(result.filePath)} ${status} entries=${result.originalEntries}->${result.activeEntries + 1}${metadata}${backup}${error}`;
491514
}),
492515
];
493516
if (broken.length > 20) {

0 commit comments

Comments
 (0)