Skip to content

Commit 9323eae

Browse files
authored
fix(doctor): report state blocked by config errors
Closes #134036 ## What Problem This Solves Fixes an issue where `openclaw doctor --fix` could refuse an invalid config write and exit before reporting Doctor-only legacy state that still needed repair. ## Why This Change Was Made After a config write refusal, Doctor reruns its canonical legacy-state detector read-only and prints one bounded deferred-work panel. The panel includes actionable detector warnings and selects recovery text for validation or cron-owner refusal. The existing mutation order and nonzero refusal exit stay unchanged. This does not adopt the issue's broad TTY claim. Current main proves only that the config refusal stopped the later Doctor-only state report. ## User Impact Operators now see the exact pending legacy-state owners, confirmation that the listed sources remain in place, and instructions to fix the config and rerun Doctor. ## Evidence - Red on `a5490b1a5006ba05970050618200e0d14df87155`: a non-TTY repair with a validation-blocked config exited `1` without any legacy-state report; workspace and TUI sources stayed byte-identical. - Green on `99f34a51927a7a0cb9261a778c5ae56c6db4d762`: the same command exited `1` with one `Legacy state deferred` panel naming both owners and an unresolved explicit multi-agent owner; no source or config byte changed. - Rerun: after fixing only the invalid config value, Doctor exited `0`, applied the existing config-key repair, and migrated both legacy sources through their canonical owners. - Convergence: the next identical run exited `0` with no legacy-state panel. - Tests: 145 focused Doctor tests, 5 source-CLI process tests, 57 workspace/TUI/exec-approval owner tests, and the explicit Doctor session-migration test passed. Cron-owner refusal keeps its Gateway/cron-specific recovery action. - Static checks: focused Oxfmt, type-aware Oxlint, max-lines ratchet, assertion-safety ratchet, conflict-marker check, and `git diff --check` passed. - Production delta: `+51/-4`; test delta: `+204/-0`. The production growth adds the read-only refusal report, warning coverage, refusal-specific recovery, and its hard output cap. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 0e0b896 commit 9323eae

3 files changed

Lines changed: 255 additions & 4 deletions

File tree

‎src/cli/doctor-output.process.test.ts‎

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,175 @@ import { spawnNodeEvalSync } from "../test-utils/node-process.js";
88

99
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
1010

11+
function runDoctorFix(params: { root: string; configPath: string; loaderPath: string }) {
12+
const entryPath = fileURLToPath(new URL("../entry.ts", import.meta.url));
13+
return spawnSync(
14+
process.execPath,
15+
[
16+
"--import",
17+
"tsx",
18+
"--import",
19+
params.loaderPath,
20+
entryPath,
21+
"doctor",
22+
"--fix",
23+
"--non-interactive",
24+
"--no-workspace-suggestions",
25+
"--no-color",
26+
],
27+
{
28+
cwd: path.resolve("."),
29+
encoding: "utf8",
30+
env: {
31+
...process.env,
32+
HOME: params.root,
33+
USERPROFILE: params.root,
34+
NODE_DISABLE_COMPILE_CACHE: "1",
35+
NODE_ENV: undefined,
36+
OPENCLAW_CONFIG_PATH: params.configPath,
37+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
38+
OPENCLAW_HIDE_BANNER: "1",
39+
OPENCLAW_HOME: undefined,
40+
OPENCLAW_NO_RESPAWN: "1",
41+
OPENCLAW_SKIP_CHANNELS: "1",
42+
OPENCLAW_STATE_DIR: path.join(params.root, "state"),
43+
OPENCLAW_TEST_FAST: "1",
44+
VITEST: undefined,
45+
VITEST_POOL_ID: undefined,
46+
VITEST_WORKER_ID: undefined,
47+
},
48+
maxBuffer: 4 * 1024 * 1024,
49+
timeout: 60_000,
50+
},
51+
);
52+
}
53+
1154
describe("Doctor report process output", () => {
55+
it("reports deferred Doctor-only state after config refusal, then converges", () => {
56+
const root = tempDirs.make("openclaw-doctor-deferred-state-");
57+
const stateDir = path.join(root, "state");
58+
const workspaceDir = path.join(root, "workspace");
59+
const configPath = path.join(root, "openclaw.json");
60+
const workspaceSource = path.join(workspaceDir, "openclaw-workspace-state.json");
61+
const tuiSource = path.join(stateDir, "tui", "last-session.json");
62+
const agentSource = path.join(stateDir, "agent", "auth.json");
63+
const loaderPath = path.join(root, "doctor-test-loader.mjs");
64+
fs.mkdirSync(path.dirname(tuiSource), { recursive: true });
65+
fs.mkdirSync(workspaceDir, { recursive: true });
66+
fs.writeFileSync(
67+
loaderPath,
68+
`import { registerHooks } from "node:module";
69+
registerHooks({
70+
resolve(specifier, context, nextResolve) {
71+
if (specifier.endsWith("/doctor-ui.js")) {
72+
return {
73+
shortCircuit: true,
74+
url: "data:text/javascript," + encodeURIComponent(
75+
[
76+
"export async function detectUiProtocolFreshnessIssues() { return []; }",
77+
"export function uiProtocolFreshnessIssueToHealthFinding() { return {}; }",
78+
"export function uiProtocolFreshnessIssueToRepairEffects() { return []; }",
79+
"export async function maybeRepairUiProtocolFreshness() {}",
80+
].join("\\n"),
81+
),
82+
};
83+
}
84+
return nextResolve(specifier, context);
85+
},
86+
});
87+
`,
88+
);
89+
const invalidConfig = {
90+
gatway: { port: 12345 },
91+
gateway: {
92+
mode: "remote",
93+
remote: { url: "ws://127.0.0.1:1", token: "fixture-token" },
94+
},
95+
agents: {
96+
ownership: "explicit",
97+
defaults: { heartbeat: { every: 5 } },
98+
entries: {
99+
primary: { workspace: workspaceDir },
100+
secondary: {},
101+
},
102+
},
103+
};
104+
fs.writeFileSync(configPath, `${JSON.stringify(invalidConfig, null, 2)}\n`);
105+
fs.writeFileSync(
106+
workspaceSource,
107+
`${JSON.stringify({ version: 1, setupCompletedAt: "2026-08-01T00:00:00.000Z" })}\n`,
108+
);
109+
fs.writeFileSync(
110+
tuiSource,
111+
`${JSON.stringify({ global: { sessionKey: "agent:main:main", updatedAt: 1 } })}\n`,
112+
);
113+
fs.mkdirSync(path.dirname(agentSource), { recursive: true });
114+
fs.writeFileSync(agentSource, "{}\n");
115+
const configBefore = fs.readFileSync(configPath);
116+
const workspaceBefore = fs.readFileSync(workspaceSource);
117+
const tuiBefore = fs.readFileSync(tuiSource);
118+
const agentBefore = fs.readFileSync(agentSource);
119+
120+
const refused = runDoctorFix({ root, configPath, loaderPath });
121+
const refusedOutput = `${refused.stderr}\n${refused.stdout}`;
122+
123+
expect(refused.error, refusedOutput).toBeUndefined();
124+
expect(refused.signal, refusedOutput).toBeNull();
125+
expect(refused.status, refusedOutput).toBe(1);
126+
expect(refusedOutput.match(/Legacy state deferred/g) ?? [], refusedOutput).toHaveLength(1);
127+
expect(refusedOutput).toContain("Workspace setup and attestations");
128+
expect(refusedOutput).toContain("TUI last-session pointers");
129+
expect(refusedOutput).toContain(
130+
"Deferred legacy agent/session migration: select an agent owner",
131+
);
132+
expect(refusedOutput).toContain("No listed legacy source was removed.");
133+
expect(refusedOutput).toContain('rerun "openclaw doctor --fix"');
134+
expect(fs.readFileSync(configPath)).toEqual(configBefore);
135+
expect(fs.readFileSync(workspaceSource)).toEqual(workspaceBefore);
136+
expect(fs.readFileSync(tuiSource)).toEqual(tuiBefore);
137+
expect(fs.readFileSync(agentSource)).toEqual(agentBefore);
138+
expect(fs.readdirSync(workspaceDir)).toEqual(["openclaw-workspace-state.json"]);
139+
expect(fs.readdirSync(path.dirname(tuiSource))).toEqual(["last-session.json"]);
140+
141+
fs.writeFileSync(
142+
configPath,
143+
`${JSON.stringify(
144+
{
145+
...invalidConfig,
146+
agents: {
147+
...invalidConfig.agents,
148+
defaults: {
149+
heartbeat: { every: "30m" },
150+
systemAgent: { agentId: "primary" },
151+
},
152+
},
153+
},
154+
null,
155+
2,
156+
)}\n`,
157+
);
158+
const repaired = runDoctorFix({ root, configPath, loaderPath });
159+
const repairedOutput = `${repaired.stderr}\n${repaired.stdout}`;
160+
expect(repaired.error, repairedOutput).toBeUndefined();
161+
expect(repaired.signal, repairedOutput).toBeNull();
162+
expect(repaired.status, repairedOutput).toBe(0);
163+
expect(fs.existsSync(workspaceSource)).toBe(false);
164+
expect(fs.existsSync(tuiSource)).toBe(false);
165+
expect(fs.existsSync(agentSource)).toBe(false);
166+
expect(fs.existsSync(path.join(stateDir, "agents", "primary", "agent", "auth.json"))).toBe(
167+
true,
168+
);
169+
expect(JSON.parse(fs.readFileSync(configPath, "utf8"))).not.toHaveProperty("gatway");
170+
171+
const clean = runDoctorFix({ root, configPath, loaderPath });
172+
const cleanOutput = `${clean.stderr}\n${clean.stdout}`;
173+
expect(clean.error, cleanOutput).toBeUndefined();
174+
expect(clean.signal, cleanOutput).toBeNull();
175+
expect(clean.status, cleanOutput).toBe(0);
176+
expect(cleanOutput).not.toContain("Legacy state deferred");
177+
expect(cleanOutput).not.toContain("Legacy state detected");
178+
}, 180_000);
179+
12180
it("omits backup tips for Git-backed nested agent workspaces", () => {
13181
const root = tempDirs.make("openclaw-doctor-workspace-git-");
14182
const repoRoot = path.join(root, "repo");

‎src/flows/doctor-health-contributions.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1133,8 +1133,19 @@ describe("doctor health contributions", () => {
11331133
},
11341134
sourceConfigValid: false,
11351135
shouldRepair: true,
1136+
options: { nonInteractive: true, repair: true },
11361137
env: {},
11371138
});
1139+
const pendingWarnings = [
1140+
"Deferred legacy agent/session migration: select an agent owner",
1141+
"Second pending owner needs operator input",
1142+
...Array.from({ length: 20 }, (_, index) => `Test owner ${index + 1} is blocked`),
1143+
];
1144+
mocks.detectLegacyStateMigrations.mockResolvedValue({
1145+
preview: [],
1146+
warnings: pendingWarnings,
1147+
notices: [],
1148+
});
11381149
mocks.replaceConfigFile.mockRejectedValueOnce(
11391150
Object.assign(
11401151
new Error(
@@ -1179,6 +1190,16 @@ describe("doctor health contributions", () => {
11791190
expect.stringContaining("agents.defaults.heartbeat.every"),
11801191
"Doctor warnings",
11811192
);
1193+
const deferredPanels = mocks.note.mock.calls.filter(
1194+
([, title]) => title === "Legacy state deferred",
1195+
);
1196+
expect(deferredPanels).toHaveLength(1);
1197+
expect(deferredPanels[0]?.[0]).toContain(pendingWarnings[0]);
1198+
expect(deferredPanels[0]?.[0]).toContain(pendingWarnings[1]);
1199+
expect(deferredPanels[0]?.[0]).toContain("2 additional pending entries were omitted");
1200+
expect(deferredPanels[0]?.[0]).toContain("No listed legacy source was removed.");
1201+
expect(deferredPanels[0]?.[0]).toContain('rerun "openclaw doctor --fix"');
1202+
expect(mocks.runLegacyStateMigrations).not.toHaveBeenCalled();
11821203

11831204
// A later write pass must not retry the identical candidate or duplicate the warning.
11841205
mocks.note.mockClear();
@@ -1268,8 +1289,14 @@ describe("doctor health contributions", () => {
12681289
cfgForPersistence: structuredClone(cfg),
12691290
configResult: { cfg, shouldWriteConfig: true },
12701291
shouldRepair: true,
1292+
options: { repair: true },
12711293
env: {},
12721294
});
1295+
mocks.detectLegacyStateMigrations.mockResolvedValue({
1296+
preview: ["- Workspace setup and attestations: legacy files → shared SQLite state"],
1297+
warnings: [],
1298+
notices: [],
1299+
});
12731300
mocks.replaceConfigFile.mockRejectedValueOnce(
12741301
Object.assign(
12751302
new Error(
@@ -1297,6 +1324,15 @@ describe("doctor health contributions", () => {
12971324
expect.stringContaining("preserving any retained legacy owner"),
12981325
"Doctor warnings",
12991326
);
1327+
expect(mocks.note).toHaveBeenCalledWith(
1328+
expect.stringContaining("Resolve the Gateway or cron-store condition above"),
1329+
"Legacy state deferred",
1330+
);
1331+
expect(mocks.note).not.toHaveBeenCalledWith(
1332+
expect.stringContaining("Fix the config errors above"),
1333+
"Legacy state deferred",
1334+
);
1335+
expect(mocks.runLegacyStateMigrations).not.toHaveBeenCalled();
13001336
});
13011337

13021338
it("skips read-scope gateway probes when gateway health only proved reachability", async () => {

‎src/flows/doctor-health-contributions.ts‎

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,49 @@ const loadDoctorCoreChecksModule = async () => await import("./doctor-core-check
3131
const loadNoteModule = async () => await import("../../packages/terminal-core/src/note.js");
3232
const loadOnboardHelpersModule = async () => await import("../commands/onboard-helpers.js");
3333
const loadSecretTypesModule = async () => await import("../config/types.secrets.js");
34+
const MAX_DEFERRED_LEGACY_STATE_DETAILS = 20;
35+
36+
async function reportDeferredLegacyState(ctx: DoctorHealthFlowContext): Promise<void> {
37+
if (ctx.options.repair !== true && ctx.options.yes !== true) {
38+
return;
39+
}
40+
const [{ detectLegacyStateMigrations }, { prepareLegacySessionSurfaces }] = await Promise.all([
41+
import("../infra/state-migrations.doctor.js"),
42+
import("../plugins/legacy-session-surfaces.js"),
43+
]);
44+
const legacyState = await detectLegacyStateMigrations({
45+
cfg: ctx.cfg,
46+
doctorOnlyStateMigrations: true,
47+
...(ctx.env ? { env: ctx.env } : {}),
48+
legacySessionSurfaces: prepareLegacySessionSurfaces({ config: ctx.cfg }),
49+
});
50+
const pendingDetails = [
51+
...legacyState.warnings.map((warning) => (warning.startsWith("- ") ? warning : `- ${warning}`)),
52+
...legacyState.preview,
53+
];
54+
if (pendingDetails.length === 0) {
55+
return;
56+
}
57+
const { note } = await loadNoteModule();
58+
const displayedDetails = pendingDetails.slice(0, MAX_DEFERRED_LEGACY_STATE_DETAILS);
59+
const omittedDetailCount = pendingDetails.length - displayedDetails.length;
60+
const remediation =
61+
ctx.configWriteRefusal === "validation"
62+
? 'Fix the config errors above, then rerun "openclaw doctor --fix".'
63+
: 'Resolve the Gateway or cron-store condition above, then rerun "openclaw doctor --fix".';
64+
note(
65+
[
66+
"Pending owners and blockers:",
67+
...displayedDetails,
68+
...(omittedDetailCount > 0
69+
? [`${omittedDetailCount} additional pending entries were omitted from this report.`]
70+
: []),
71+
"No listed legacy source was removed.",
72+
remediation,
73+
].join("\n"),
74+
"Legacy state deferred",
75+
);
76+
}
3477

3578
async function runGatewayConfigHealth(ctx: DoctorHealthFlowContext): Promise<void> {
3679
const { formatCliCommand } = await loadCommandFormatModule();
@@ -507,13 +550,17 @@ async function runDoctorHealthContributionList(
507550
const runWithPluginMetadataSnapshot = ctx.runWithPluginMetadataSnapshot;
508551
for (const contribution of contributions) {
509552
try {
510-
if (!runWithPluginMetadataSnapshot) {
553+
const run = async () => {
511554
await contribution.run(ctx);
555+
if (ctx.configWriteRefusal) {
556+
await reportDeferredLegacyState(ctx);
557+
}
558+
};
559+
if (!runWithPluginMetadataSnapshot) {
560+
await run();
512561
} else {
513562
const workspaceDir = resolveDoctorWorkspaceDir(ctx.cfg, ctx.env);
514-
await runWithPluginMetadataSnapshot({ config: ctx.cfg, workspaceDir }, () =>
515-
contribution.run(ctx),
516-
);
563+
await runWithPluginMetadataSnapshot({ config: ctx.cfg, workspaceDir }, run);
517564
}
518565
if (ctx.configWriteRefusal) {
519566
// Later repairs consume the candidate. Stop before they persist state

0 commit comments

Comments
 (0)