Skip to content

Commit 733a27a

Browse files
committed
fix(cli): keep Doctor reports complete when piped
1 parent 039187a commit 733a27a

13 files changed

Lines changed: 153 additions & 31 deletions

‎src/cli/capability-cli.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,8 @@ const mocks = vi.hoisted(() => ({
277277
modelsAuthLoginCommand: vi.fn(),
278278
}));
279279

280-
vi.mock("../runtime.js", () => ({
280+
vi.mock("../runtime.js", async (importOriginal) => ({
281+
...(await importOriginal<typeof import("../runtime.js")>()),
281282
defaultRuntime: mocks.runtime,
282283
writeRuntimeJson: (runtime: { writeJson: (value: unknown) => void }, value: unknown) =>
283284
runtime.writeJson(value),

‎src/cli/cli-utils.test.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// CLI utility tests cover shared command helpers, option parsing, and output formatting.
22
import { Command } from "commander";
33
import { describe, expect, it, vi } from "vitest";
4-
import { defaultRuntime } from "../runtime.js";
4+
import { defaultRuntime, ExitError } from "../runtime.js";
55
import { runCommandWithRuntime } from "./cli-utils.js";
66
import { registerDnsCli } from "./dns-cli.js";
77
import {
@@ -40,6 +40,33 @@ describe("waitForever", () => {
4040
});
4141

4242
describe("runCommandWithRuntime", () => {
43+
it.each(
44+
[0, 1, 2].flatMap((code) =>
45+
[false, true].map((customErrorHandler) => ({ code, customErrorHandler })),
46+
),
47+
)(
48+
"preserves completed exit $code with custom error handler $customErrorHandler",
49+
async ({ code, customErrorHandler }) => {
50+
const runtime = { error: vi.fn(), exit: vi.fn() };
51+
const onError = vi.fn();
52+
const outcome = new ExitError(code);
53+
54+
await expect(
55+
runCommandWithRuntime(
56+
runtime,
57+
async () => {
58+
throw outcome;
59+
},
60+
customErrorHandler ? onError : undefined,
61+
),
62+
).rejects.toBe(outcome);
63+
64+
expect(runtime.error).not.toHaveBeenCalled();
65+
expect(runtime.exit).not.toHaveBeenCalled();
66+
expect(onError).not.toHaveBeenCalled();
67+
},
68+
);
69+
4370
it("keeps cause chains and error codes behind debug intent", async () => {
4471
const messages: string[] = [];
4572
const exits: number[] = [];

‎src/cli/cli-utils.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Shared CLI execution wrappers and inherited Commander option lookup.
22
import type { Command } from "commander";
33
import { formatErrorMessage } from "../infra/errors.js";
4+
import { ExitError } from "../runtime.js";
45
import { formatCliOperatorError, isExpectedCliError } from "./failure-output.js";
56
import { isJsonOutputModeActive } from "./json-output-mode.js";
67

@@ -42,7 +43,12 @@ export async function runCommandWithRuntime(
4243
try {
4344
await action();
4445
} catch (err) {
45-
if (isJsonOutputModeActive(process.argv) || isExpectedCliError(err)) {
46+
// Completed commands unwind to the outer cleanup and output-drain owner.
47+
if (
48+
err instanceof ExitError ||
49+
isJsonOutputModeActive(process.argv) ||
50+
isExpectedCliError(err)
51+
) {
4652
throw err;
4753
}
4854
if (onError) {
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import path from "node:path";
2+
import { afterEach, describe, expect, it } from "vitest";
3+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
4+
import { spawnNodeEvalSync } from "../test-utils/node-process.js";
5+
6+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
7+
8+
describe("Doctor report process output", () => {
9+
it.each([
10+
{ name: "advisory JSON", args: ["--json"], exitCode: 0 },
11+
{ name: "lint JSON", args: ["--lint", "--json"], exitCode: 1 },
12+
{ name: "post-upgrade JSON", args: ["--post-upgrade", "--json"], exitCode: 1 },
13+
])("drains the whole pipe before exiting for $name", ({ args, exitCode }) => {
14+
const root = tempDirs.make("openclaw-doctor-output-");
15+
const payload = { ok: false, findings: [{ level: "error", message: "x".repeat(1024 * 1024) }] };
16+
const sourceUrl = (relative: string) => new URL(relative, import.meta.url).href;
17+
// Keep the parser, runtime, and exit lifecycle real. Synthetic report
18+
// producers exercise the output boundary without accessing operator state.
19+
const script = `
20+
import { registerHooks } from "node:module";
21+
import { Command } from "commander";
22+
registerHooks({
23+
resolve(specifier, context, nextResolve) {
24+
const producer = specifier.endsWith("/doctor-lint.js") ? "lint" :
25+
specifier.endsWith("/doctor-post-upgrade.js") ? "post-upgrade" : undefined;
26+
if (producer) {
27+
const payload = '{ ok: false, findings: [{ level: "error", message: "x".repeat(1024 * 1024) }] }';
28+
return {
29+
shortCircuit: true,
30+
url: "data:text/javascript," + encodeURIComponent(
31+
producer === "lint"
32+
? 'export async function runDoctorLintCli(runtime) { runtime.writeJson(' + payload + '); return 1; }'
33+
: 'export async function runPostUpgradeProbes() { return ' + payload + '; }'
34+
),
35+
};
36+
}
37+
return nextResolve(specifier, context);
38+
},
39+
});
40+
const { registerMaintenanceCommands } = await import(${JSON.stringify(sourceUrl("./program/register.maintenance.ts"))});
41+
const { runCliWithExitFinalization } = await import(${JSON.stringify(sourceUrl("./one-shot-exit.ts"))});
42+
process.argv = [process.execPath, "openclaw", "doctor", ...${JSON.stringify(args)}];
43+
await runCliWithExitFinalization({
44+
run: async () => {
45+
const program = new Command().name("openclaw");
46+
registerMaintenanceCommands(program);
47+
await program.parseAsync(process.argv);
48+
},
49+
onError: error => { throw error; },
50+
});
51+
`;
52+
const result = spawnNodeEvalSync(script, {
53+
imports: ["tsx"],
54+
env: {
55+
PATH: path.dirname(process.execPath),
56+
HOME: root,
57+
USERPROFILE: root,
58+
OPENCLAW_HOME: root,
59+
OPENCLAW_STATE_DIR: path.join(root, "state"),
60+
OPENCLAW_CONFIG_PATH: path.join(root, "openclaw.json"),
61+
NO_COLOR: "1",
62+
},
63+
maxBuffer: 2 * 1024 * 1024,
64+
timeout: 30_000,
65+
});
66+
67+
expect(result.error).toBeUndefined();
68+
expect(result.signal).toBeNull();
69+
expect(result.status, result.stderr).toBe(exitCode);
70+
expect(result.stderr).toBe("");
71+
const expected = `${JSON.stringify(payload, null, 2)}\n`;
72+
expect(result.stdout.length).toBe(expected.length);
73+
expect(result.stdout).toBe(expected);
74+
});
75+
});

‎src/cli/program/message/helpers.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@ const exitMock = vi.fn((_code: number): never => {
6262
});
6363
const errorMock = vi.fn();
6464
const runtimeMock = { log: vi.fn(), error: errorMock, exit: exitMock };
65-
vi.mock("../../../runtime.js", () => ({
65+
vi.mock("../../../runtime.js", async (importOriginal) => ({
66+
...(await importOriginal<typeof import("../../../runtime.js")>()),
6667
defaultRuntime: runtimeMock,
6768
}));
6869

‎src/cli/program/register.configure.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ vi.mock("../../commands/configure.commands.js", () => ({
2222
configureCommandFromSectionsArg: mocks.configureCommandFromSectionsArgMock,
2323
}));
2424

25-
vi.mock("../../runtime.js", () => ({
25+
vi.mock("../../runtime.js", async (importOriginal) => ({
26+
...(await importOriginal<typeof import("../../runtime.js")>()),
2627
defaultRuntime: mocks.runtime,
2728
}));
2829

‎src/cli/program/register.maintenance.test.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Register maintenance tests cover maintenance command registration in the CLI program.
22
import { Command } from "commander";
33
import { beforeEach, describe, expect, it, vi } from "vitest";
4+
import { ExitError } from "../../runtime.js";
45
import { registerMaintenanceCommands } from "./register.maintenance.js";
56

67
const mocks = vi.hoisted(() => ({
@@ -70,7 +71,8 @@ vi.mock("../../commands/doctor-lint.js", () => ({
7071
runDoctorLintCli: mocks.runDoctorLintCli,
7172
}));
7273

73-
vi.mock("../../runtime.js", () => ({
74+
vi.mock("../../runtime.js", async (importOriginal) => ({
75+
...(await importOriginal<typeof import("../../runtime.js")>()),
7476
defaultRuntime: mocks.runtime,
7577
}));
7678

@@ -90,7 +92,14 @@ describe("registerMaintenanceCommands doctor action", () => {
9092
async function runMaintenanceCli(args: string[]) {
9193
const program = new Command();
9294
registerMaintenanceCommands(program);
93-
await program.parseAsync(args, { from: "user" });
95+
try {
96+
await program.parseAsync(args, { from: "user" });
97+
} catch (error) {
98+
if (!(error instanceof ExitError)) {
99+
throw error;
100+
}
101+
runtime.exit(error.code);
102+
}
94103
}
95104

96105
beforeEach(() => {

‎src/cli/program/register.maintenance.ts‎

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { formatErrorMessage as formatError, runCommandWithRuntime } from "../cli
77
import { hasExplicitOptions } from "../command-options.js";
88
import { isDoctorMachineOutput } from "../doctor-output-mode.js";
99
import { formatCliJsonFailure } from "../failure-output.js";
10+
import { exitCliAfterOutput } from "../one-shot-exit.js";
1011
import { setCommandJsonMode } from "./json-mode.js";
1112

1213
const STATE_SQLITE_CONFLICTING_OPTION_NAMES = [
@@ -32,13 +33,13 @@ const STATE_SQLITE_CONFLICTING_OPTION_NAMES = [
3233
"only",
3334
] as const;
3435

35-
function exitDoctorError(message: string, json: boolean): void {
36+
function exitDoctorError(message: string, json: boolean): never {
3637
if (json) {
3738
defaultRuntime.writeJson(formatCliJsonFailure(message));
3839
} else {
3940
defaultRuntime.error(message);
4041
}
41-
defaultRuntime.exit(2);
42+
exitCliAfterOutput(defaultRuntime, 2);
4243
}
4344

4445
/** Register maintenance commands that inspect or mutate local OpenClaw state. */
@@ -151,7 +152,7 @@ export function registerMaintenanceCommands(program: Command) {
151152
);
152153
}
153154
if (lintMode) {
154-
await runCommandWithRuntime(
155+
return await runCommandWithRuntime(
155156
defaultRuntime,
156157
async () => {
157158
const { runDoctorLintCli } = await import("../../commands/doctor-lint.js");
@@ -164,11 +165,10 @@ export function registerMaintenanceCommands(program: Command) {
164165
allowExec: Boolean(opts.allowExec),
165166
deep: Boolean(opts.deep),
166167
});
167-
defaultRuntime.exit(jsonImpliesLint ? 0 : exitCode);
168+
exitCliAfterOutput(defaultRuntime, jsonImpliesLint ? 0 : exitCode);
168169
},
169170
(err) => exitDoctorError(formatError(err), opts.json === true || !process.stdout.isTTY),
170171
);
171-
return;
172172
}
173173
await runCommandWithRuntime(
174174
defaultRuntime,
@@ -201,7 +201,7 @@ export function registerMaintenanceCommands(program: Command) {
201201
sessionSqliteGithubIssue: Boolean(opts.githubIssue),
202202
json: Boolean(opts.json),
203203
});
204-
defaultRuntime.exit(0);
204+
exitCliAfterOutput(defaultRuntime, 0);
205205
},
206206
opts.json ? (err: unknown) => exitDoctorError(formatError(err), true) : undefined,
207207
);
@@ -223,7 +223,7 @@ export function registerMaintenanceCommands(program: Command) {
223223
if (opts.json === true && opts.run === true) {
224224
return exitDoctorError("triage --json cannot be combined with --run.", true);
225225
}
226-
await runCommandWithRuntime(
226+
return await runCommandWithRuntime(
227227
defaultRuntime,
228228
async () => {
229229
const { triageCommand } = await import("../../commands/triage.js");
@@ -350,8 +350,7 @@ function parseDoctorStateSqliteMode(value: unknown, json: boolean): "compact" |
350350
if (value === undefined || value === "compact") {
351351
return value;
352352
}
353-
exitDoctorError("Invalid --state-sqlite mode. Use compact.", json);
354-
throw new Error("unreachable");
353+
return exitDoctorError("Invalid --state-sqlite mode. Use compact.", json);
355354
}
356355

357356
function parseDoctorSessionSqliteMode(
@@ -370,9 +369,8 @@ function parseDoctorSessionSqliteMode(
370369
) {
371370
return value;
372371
}
373-
exitDoctorError(
372+
return exitDoctorError(
374373
"Invalid --session-sqlite mode. Use dry-run, import, validate, inspect, compact, restore, or recover.",
375374
json,
376375
);
377-
throw new Error("unreachable");
378376
}

‎src/cli/skills-cli.commands.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,8 @@ function primeCalendarUpdate(workspaceDir = "/tmp/workspace"): void {
258258
]);
259259
}
260260

261-
vi.mock("../runtime.js", () => ({
261+
vi.mock("../runtime.js", async (importOriginal) => ({
262+
...(await importOriginal<typeof import("../runtime.js")>()),
262263
defaultRuntime: mocks.defaultRuntime,
263264
}));
264265

‎src/cli/skills-cli.curator.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,10 @@ const mocks = vi.hoisted(() => {
2626
};
2727
});
2828

29-
vi.mock("../runtime.js", () => ({ defaultRuntime: mocks.defaultRuntime }));
29+
vi.mock("../runtime.js", async (importOriginal) => ({
30+
...(await importOriginal<typeof import("../runtime.js")>()),
31+
defaultRuntime: mocks.defaultRuntime,
32+
}));
3033
vi.mock("../gateway/call.js", () => ({
3134
callGateway: mocks.callGateway,
3235
isGatewayClientRequestError: (error: unknown) =>

0 commit comments

Comments
 (0)