Skip to content

Commit b097aaa

Browse files
authored
fix: doctor --fix reports config changes that were never written when validation refuses the candidate (#124462)
* fix(doctor): never report unpersisted config fixes doctor --fix printed "Doctor changes" panels while computing candidate mutations, then crashed with a raw Error and persisted nothing when the repaired candidate still failed write validation (e.g. an unknown root key repaired alongside an unrepairable schema type error). Root cause: the compute->print->validate->persist ordering was wrong. Panels were printed at mutation time, but validation only ran inside the atomic writer, after all panels were visible. Fix at the owner boundaries: - doctor-config-flow queues repair-mode "Doctor changes" panels in a sink instead of printing them; preview panels still print immediately. Committed side-effect repair notes (SQLite/filesystem) keep printing at repair time; candidate-config notes from the repair sequence are routed through the same deferred sink. - io.write throws a typed CONFIG_VALIDATION_FAILED error (with the full issue list) via a new createConfigValidationFailedError owner in io.write-errors. - runWriteConfigHealth prints queued panels only after the atomic write commits, and renders a validation refusal as a "Doctor warnings" panel stating no config changes were written plus the exact paths to fix by hand. The contribution loop stops after refusal (same invariant as the cron-ownership deferral) and doctor exits 1 without a raw Error leak. Regression tests: pre-fix, the new validation-refusal e2e test fails on the lying "Doctor changes" panel; contribution-level tests cover the refusal note, held panels printing exactly once after commit, and no retry of the identical candidate. * fix(doctor): report partial persistence accurately after a later write refusal Post-rebase CI and ClawSweeper follow-ups: - repair-sequencing tests now assert the deferred configChangeNotes contract (candidate-only mutation notes moved out of changeNotes by the parent commit); committed side-effect notes stay in changeNotes. - formatConfigValidationFailure is module-private; its guidance formatting is covered through createConfigValidationFailedError, fixing the knip unused-export gate. - When the initial write pass committed and only the later post-repair write is refused, the warnings panel says earlier fixes were saved instead of claiming no config changes were written, and the outro says "some config fixes were not applied". New regression test covers commit-then-refusal.
1 parent 6f418b9 commit b097aaa

13 files changed

Lines changed: 454 additions & 67 deletions

‎src/commands/doctor-config-flow.test.ts‎

Lines changed: 44 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1686,10 +1686,12 @@ describe("doctor config flow", () => {
16861686
expect(result.cfg.agents?.entries).toEqual({
16871687
main: { workspace: "/tmp/migrated-main" },
16881688
});
1689-
expect(terminalNoteMock).toHaveBeenCalledWith(
1689+
// Repair panels defer to the atomic write runner; the flow itself must not
1690+
// claim the roster change happened before anything reached disk.
1691+
expect(result.pendingChangePanels).toContain(
16901692
"Prepared the canonical agent roster without retired default markers for persistence.",
1691-
"Doctor changes",
16921693
);
1694+
expect(terminalNoteMock.mock.calls.some(([, title]) => title === "Doctor changes")).toBe(false);
16931695
expect(terminalNoteMock.mock.calls.some(([message]) => message.includes("Persisted"))).toBe(
16941696
false,
16951697
);
@@ -2885,7 +2887,7 @@ describe("doctor config flow", () => {
28852887
it("sanitizes config-derived doctor warnings and changes before logging", async () => {
28862888
const noteSpy = resetTerminalNoteMock();
28872889
try {
2888-
await runDoctorConfigWithInput({
2890+
const result = await runDoctorConfigWithInput({
28892891
repair: true,
28902892
config: {
28912893
channels: {
@@ -2919,9 +2921,14 @@ describe("doctor config flow", () => {
29192921
run: loadAndMaybeMigrateDoctorConfig,
29202922
});
29212923

2922-
const outputs = noteSpy.mock.calls
2923-
.filter((call) => call[1] === "Doctor warnings" || call[1] === "Doctor changes")
2924-
.map((call) => call[0]);
2924+
// Repair-mode change panels defer to the write runner; sanitized change
2925+
// text travels through pendingChangePanels instead of immediate notes.
2926+
const outputs = [
2927+
...noteSpy.mock.calls
2928+
.filter((call) => call[1] === "Doctor warnings" || call[1] === "Doctor changes")
2929+
.map((call) => call[0]),
2930+
...(result.pendingChangePanels ?? []),
2931+
];
29252932
const joinedOutputs = outputs.join("\n");
29262933
expect(outputs.some((line) => line.includes("\u001b"))).toBe(false);
29272934
expect(outputs.some((line) => line.includes("\nforged"))).toBe(false);
@@ -3570,11 +3577,11 @@ describe("doctor config flow", () => {
35703577
});
35713578

35723579
it.each([
3573-
[false, "Doctor changes preview", false],
3574-
[true, "Doctor changes", true],
3580+
[false, false],
3581+
[true, true],
35753582
] as const)(
35763583
"previews and repairs retired internal hook registrations (repair=%s)",
3577-
async (repair, panelTitle, shouldWriteConfig) => {
3584+
async (repair, shouldWriteConfig) => {
35783585
const noteSpy = resetTerminalNoteMock();
35793586
try {
35803587
const result = await runDoctorConfigWithInput({
@@ -3595,13 +3602,21 @@ describe("doctor config flow", () => {
35953602
).toBeUndefined();
35963603
expect(result.cfg.hooks?.internal?.enabled).toBeUndefined();
35973604
expect(result.shouldWriteConfig).toBe(shouldWriteConfig);
3598-
expect(
3599-
noteSpy.mock.calls.some(
3600-
([message, title]) =>
3601-
title === panelTitle &&
3602-
message.includes("Removed retired hooks.internal.handlers registrations"),
3603-
),
3604-
).toBe(true);
3605+
const removalLine = "Removed retired hooks.internal.handlers registrations";
3606+
if (repair) {
3607+
// Repair panels defer until the atomic write commits.
3608+
expect(
3609+
(result.pendingChangePanels ?? []).some((panel) => panel.includes(removalLine)),
3610+
).toBe(true);
3611+
expect(noteSpy.mock.calls.some(([, title]) => title === "Doctor changes")).toBe(false);
3612+
} else {
3613+
expect(
3614+
noteSpy.mock.calls.some(
3615+
([message, title]) =>
3616+
title === "Doctor changes preview" && message.includes(removalLine),
3617+
),
3618+
).toBe(true);
3619+
}
36053620
} finally {
36063621
noteSpy.mockClear();
36073622
}
@@ -3633,10 +3648,10 @@ describe("doctor config flow", () => {
36333648
}
36343649
});
36353650

3636-
it("titles the legacy migration panel as applied when --fix is passed (#80817)", async () => {
3651+
it("defers the applied panel to the config write when --fix is passed (#80817)", async () => {
36373652
const noteSpy = resetTerminalNoteMock();
36383653
try {
3639-
await runDoctorConfigWithInput({
3654+
const result = await runDoctorConfigWithInput({
36403655
repair: true,
36413656
config: {
36423657
heartbeat: {
@@ -3647,8 +3662,11 @@ describe("doctor config flow", () => {
36473662
run: loadAndMaybeMigrateDoctorConfig,
36483663
});
36493664
const changeTitles = noteSpy.mock.calls.map(([, title]) => title);
3650-
expect(changeTitles).toContain("Doctor changes");
3665+
// The flow itself prints nothing as applied; the write runner reports
3666+
// "Doctor changes" only after the atomic write commits.
3667+
expect(changeTitles).not.toContain("Doctor changes");
36513668
expect(changeTitles).not.toContain("Doctor changes preview");
3669+
expect(result.pendingChangePanels?.length).toBeGreaterThan(0);
36523670
} finally {
36533671
noteSpy.mockClear();
36543672
}
@@ -3731,14 +3749,16 @@ describe("doctor config flow", () => {
37313749
});
37323750
noteSpy.mockClear();
37333751

3734-
await loadAndMaybeMigrateDoctorConfig({
3752+
const secondRun = await loadAndMaybeMigrateDoctorConfig({
37353753
options: { nonInteractive: true, repair: true },
37363754
confirm: async () => false,
37373755
});
3738-
const secondRunTalkNormalizationLines = noteSpy.mock.calls
3739-
.filter((call) => call[1] === "Doctor changes")
3740-
.map((call) => call[0])
3741-
.filter((line) => line.includes("Normalized talk.provider/providers shape"));
3756+
const secondRunTalkNormalizationLines = [
3757+
...noteSpy.mock.calls
3758+
.filter((call) => call[1] === "Doctor changes")
3759+
.map((call) => call[0]),
3760+
...(secondRun.pendingChangePanels ?? []),
3761+
].filter((line) => line.includes("Normalized talk.provider/providers shape"));
37423762
expect(secondRunTalkNormalizationLines).toStrictEqual([]);
37433763
} finally {
37443764
noteSpy.mockClear();

‎src/commands/doctor-config-flow.ts‎

Lines changed: 46 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -95,20 +95,32 @@ function collectConfiguredChannelIds(cfg: OpenClawConfig): string[] {
9595
return Object.keys(channels).filter((channelId) => channelId !== "defaults");
9696
}
9797

98-
// Past-tense "Removed X" lines must not appear under a "Doctor changes" panel
99-
// when the run did not write to disk; retitle to signal the preview state.
100-
function emitDoctorChangesPanel(
101-
changeLines: ReadonlyArray<string>,
102-
shouldRepair: boolean,
103-
options: { sanitize?: boolean } = {},
104-
): void {
105-
if (changeLines.length === 0) {
106-
return;
107-
}
108-
const body = changeLines.join("\n");
109-
const message = options.sanitize ? sanitizeDoctorNote(body) : body;
110-
const title = shouldRepair ? "Doctor changes" : "Doctor changes preview";
111-
note(message, title);
98+
// Repair-mode "Doctor changes" panels queue until the final candidate passes the
99+
// same validation the atomic writer enforces: printing "Doctor changes" and then
100+
// refusing the write would report repairs that never reached disk. Preview
101+
// panels print immediately — they promise nothing.
102+
type DoctorChangesPanelSink = {
103+
emit: (changeLines: ReadonlyArray<string>, options?: { sanitize?: boolean }) => void;
104+
drain: () => string[];
105+
};
106+
107+
function createDoctorChangesPanelSink(shouldRepair: boolean): DoctorChangesPanelSink {
108+
const pending: string[] = [];
109+
return {
110+
emit: (changeLines, options = {}) => {
111+
if (changeLines.length === 0) {
112+
return;
113+
}
114+
const body = changeLines.join("\n");
115+
const message = options.sanitize ? sanitizeDoctorNote(body) : body;
116+
if (shouldRepair) {
117+
pending.push(message);
118+
return;
119+
}
120+
note(message, "Doctor changes preview");
121+
},
122+
drain: () => pending.splice(0),
123+
};
112124
}
113125

114126
async function refreshGatewayAuthStateAfterAuthProfileRepair(): Promise<void> {
@@ -189,15 +201,12 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
189201
let shouldRepairCronCodexModelRefsAfterConfigWrite = false;
190202
let openAICodexAuthProfileIdMap: ReadonlyMap<string, string> | undefined;
191203
const doctorFixCommand = formatCliCommand("openclaw doctor --fix");
204+
const changesPanelSink = createDoctorChangesPanelSink(shouldRepair);
192205
const applyConfigMutation = (
193206
mutation: DoctorConfigMutationResult & { warnings?: string[] },
194207
options: { fixHint: string; sanitize?: boolean; emitWarnings?: boolean },
195208
): void => {
196-
emitDoctorChangesPanel(
197-
mutation.changes,
198-
shouldRepair,
199-
options.sanitize ? { sanitize: true } : {},
200-
);
209+
changesPanelSink.emit(mutation.changes, options.sanitize ? { sanitize: true } : {});
201210
if (options.emitWarnings && mutation.warnings?.length) {
202211
emitDoctorNotes({ note, warningNotes: mutation.warnings });
203212
}
@@ -337,7 +346,7 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
337346
if (legacyIssueLines.length > 0) {
338347
note(legacyIssueLines.join("\n"), "Legacy config keys detected");
339348
}
340-
emitDoctorChangesPanel(legacyStep.changeLines, shouldRepair);
349+
changesPanelSink.emit(legacyStep.changeLines);
341350
const hookTransformsDirWarnings = collectInvalidHookTransformsDirWarnings(
342351
state.cfg,
343352
snapshot.path,
@@ -482,11 +491,16 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
482491
if (repairSequence.authProfilesRepaired) {
483492
await refreshGatewayAuthStateAfterAuthProfileRepair();
484493
}
494+
// Committed side-effect repairs (SQLite/filesystem) already happened; report now.
495+
// Candidate-config mutations stay queued until the atomic write commits.
485496
emitDoctorNotes({
486497
note,
487498
changeNotes: repairSequence.changeNotes,
488499
warningNotes: repairSequence.warningNotes,
489500
});
501+
for (const configChange of repairSequence.configChangeNotes ?? []) {
502+
changesPanelSink.emit([configChange]);
503+
}
490504
} else {
491505
const { collectDoctorPreviewNotes } = await import("./doctor/shared/preview-warnings.js");
492506
const collectPreviewNotes = async () =>
@@ -529,8 +543,12 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
529543
const lines = [
530544
...unknownStep.removed.map((pathLocal) => `- ${pathLocal}`),
531545
...unknownStep.repairs.map((change) => `- ${change}`),
532-
].join("\n");
533-
note(lines, shouldRepair ? "Doctor changes" : "Unknown config keys");
546+
];
547+
if (shouldRepair) {
548+
changesPanelSink.emit(lines);
549+
} else {
550+
note(lines.join("\n"), "Unknown config keys");
551+
}
534552
}
535553
if (unknownStep.warnings.length > 0) {
536554
note(unknownStep.warnings.join("\n"), "Doctor warnings");
@@ -579,10 +597,16 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
579597
noteSandboxOriginProxyWarning(cfg);
580598
noteMcpOriginWarning(cfg);
581599

600+
// Queued repair panels describe candidate mutations; the write runner prints
601+
// them as "Doctor changes" only after the atomic write commits. A blocked
602+
// write drops them — its blocking note already states nothing was changed.
603+
const pendingChangePanels = changesPanelSink.drain();
604+
582605
return {
583606
cfg,
584607
path: snapshot.path ?? CONFIG_PATH,
585608
shouldWriteConfig,
609+
...(shouldWriteConfig && pendingChangePanels.length > 0 ? { pendingChangePanels } : {}),
586610
sourceConfigValid: snapshot.valid,
587611
...(sourceLastTouchedVersion ? { sourceLastTouchedVersion } : {}),
588612
...(legacyMigrationPartiallyValid ? { skipPluginValidationOnWrite: true } : {}),
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// Regression: doctor --fix with a repairable unknown key plus an unrepairable
2+
// schema type error must not report "Doctor changes" (nothing persists), must
3+
// not crash with a raw Error, and must leave the config byte-identical while
4+
// telling the operator exactly what to fix by hand.
5+
import fs from "node:fs/promises";
6+
import { afterEach, describe, expect, it, vi } from "vitest";
7+
import { withEnvOverride, withTempHome, writeOpenClawConfig } from "../config/test-helpers.js";
8+
import { runWriteConfigHealth } from "../flows/doctor-health-contribution-runners.config.js";
9+
import type { DoctorHealthFlowContext } from "../flows/doctor-health-contribution-types.js";
10+
import type { RuntimeEnv } from "../runtime.js";
11+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
12+
import { loadAndMaybeMigrateDoctorConfig } from "./doctor-config-flow.js";
13+
import { createDoctorPrompter, type DoctorOptions } from "./doctor-prompter.js";
14+
15+
const noteMock = vi.hoisted(() => vi.fn<(message: string, title?: string) => void>());
16+
17+
vi.mock("../../packages/terminal-core/src/note.js", () => ({
18+
note: noteMock,
19+
}));
20+
21+
describe("doctor --fix with a validation-blocked candidate", () => {
22+
afterEach(() => {
23+
noteMock.mockClear();
24+
closeOpenClawStateDatabaseForTest();
25+
});
26+
27+
it("never reports unpersisted fixes and leaves the config untouched", async () => {
28+
await withTempHome(async (home) => {
29+
await withEnvOverride({ OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1" }, async () => {
30+
const configPath = await writeOpenClawConfig(home, {
31+
gatway: { port: 12345 },
32+
agents: { defaults: { heartbeat: { every: 5 } } },
33+
});
34+
const rawBefore = await fs.readFile(configPath, "utf-8");
35+
const runtime: RuntimeEnv = { error: vi.fn(), exit: vi.fn(), log: vi.fn() };
36+
const options: DoctorOptions = { nonInteractive: true, repair: true };
37+
const prompter = createDoctorPrompter({ runtime, options });
38+
const configResult = await loadAndMaybeMigrateDoctorConfig({
39+
options,
40+
confirm: (params) => prompter.confirm(params),
41+
runtime,
42+
prompter,
43+
});
44+
45+
// The unknown-key repair is computed, but held until the write commits.
46+
expect(configResult.shouldWriteConfig).toBe(true);
47+
expect(
48+
(configResult.pendingChangePanels ?? []).some((panel) => panel.includes("gatway")),
49+
).toBe(true);
50+
expect(noteMock.mock.calls.some(([, title]) => title === "Doctor changes")).toBe(false);
51+
52+
const ctx: DoctorHealthFlowContext = {
53+
runtime,
54+
options,
55+
prompter,
56+
configResult,
57+
cfg: configResult.cfg,
58+
cfgForPersistence: structuredClone(configResult.cfg),
59+
sourceConfigValid: configResult.sourceConfigValid ?? true,
60+
configPath,
61+
stateDirExistedAtStart: true,
62+
...(configResult.runWithPluginMetadataSnapshot
63+
? { runWithPluginMetadataSnapshot: configResult.runWithPluginMetadataSnapshot }
64+
: {}),
65+
};
66+
67+
// The write must refuse gracefully — no throw, no change panel, no file write.
68+
await expect(runWriteConfigHealth(ctx)).resolves.toBeUndefined();
69+
70+
expect(ctx.configWriteBlockedByValidation).toBe(true);
71+
expect(ctx.configResultWriteCommitted).not.toBe(true);
72+
expect(noteMock.mock.calls.some(([, title]) => title === "Doctor changes")).toBe(false);
73+
const warning = noteMock.mock.calls.find(
74+
([message, title]) =>
75+
title === "Doctor warnings" && message.includes("No config changes were written"),
76+
);
77+
expect(warning).toBeDefined();
78+
expect(warning?.[0]).toContain("agents.defaults.heartbeat.every");
79+
await expect(fs.readFile(configPath, "utf-8")).resolves.toBe(rawBefore);
80+
});
81+
});
82+
});
83+
});

0 commit comments

Comments
 (0)