Skip to content

Commit 9d97e68

Browse files
authored
feat(doctor): add disk space health check
Add a Doctor health contribution that checks free space on the partition containing the active OpenClaw state directory. Doctor now warns below 500 MB and reports critical below 100 MB so disk pressure is visible before config writes, session transcripts, or log rotation start failing. The contribution reuses the shared `src/infra/disk-space.ts` probe, runs before state integrity, and is registered in the Doctor health conversion plan with focused coverage for thresholds, formatting, and note behavior. PR: #59196 Proof: `pnpm test src/commands/doctor-disk-space.test.ts src/flows/doctor-health-conversion-plan.test.ts`; `git diff --check origin/main...HEAD`; `git merge-tree --write-tree origin/main refs/remotes/pr/59196`; GitHub CI run `26720861380`; Real behavior proof run `26720996848`. Co-authored-by: alkor2000 <[email protected]>
1 parent e2c745f commit 9d97e68

4 files changed

Lines changed: 294 additions & 0 deletions

File tree

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import {
3+
buildDiskSpaceWarnings,
4+
formatBytes,
5+
noteDiskSpace,
6+
} from "./doctor-disk-space.js";
7+
8+
vi.mock("../../packages/terminal-core/src/note.js", () => ({
9+
note: vi.fn(),
10+
}));
11+
12+
describe("formatBytes", () => {
13+
it("formats zero bytes", () => {
14+
expect(formatBytes(0)).toBe("0 B");
15+
});
16+
17+
it("formats bytes below 1 KB", () => {
18+
expect(formatBytes(512)).toBe("512 B");
19+
});
20+
21+
it("formats kilobytes", () => {
22+
expect(formatBytes(2048)).toBe("2 KB");
23+
});
24+
25+
it("formats megabytes", () => {
26+
expect(formatBytes(50 * 1024 * 1024)).toBe("50 MB");
27+
});
28+
29+
it("floors megabytes to avoid crossing a threshold (99.6 MB -> 99 MB)", () => {
30+
expect(formatBytes(Math.floor(99.6 * 1024 * 1024))).toBe("99 MB");
31+
});
32+
33+
it("formats gigabytes with one decimal", () => {
34+
expect(formatBytes(2.5 * 1024 * 1024 * 1024)).toBe("2.5 GB");
35+
});
36+
37+
it("returns unknown for negative values", () => {
38+
expect(formatBytes(-1)).toBe("unknown");
39+
});
40+
41+
it("returns unknown for NaN", () => {
42+
expect(formatBytes(Number.NaN)).toBe("unknown");
43+
});
44+
45+
it("returns unknown for Infinity", () => {
46+
expect(formatBytes(Number.POSITIVE_INFINITY)).toBe("unknown");
47+
});
48+
});
49+
50+
describe("buildDiskSpaceWarnings", () => {
51+
it("returns empty array when space is sufficient", () => {
52+
const warnings = buildDiskSpaceWarnings({
53+
availableBytes: 10 * 1024 * 1024 * 1024,
54+
displayStateDir: "~/.openclaw",
55+
});
56+
expect(warnings).toEqual([]);
57+
});
58+
59+
it("returns warning lines when space is low (below 500 MB)", () => {
60+
const warnings = buildDiskSpaceWarnings({
61+
availableBytes: 300 * 1024 * 1024,
62+
displayStateDir: "~/.openclaw",
63+
});
64+
expect(warnings).toHaveLength(2);
65+
expect(warnings[0]).toContain("Low disk space");
66+
expect(warnings[0]).toContain("300 MB");
67+
expect(warnings[0]).toContain("~/.openclaw");
68+
});
69+
70+
it("returns critical lines when space is very low (below 100 MB)", () => {
71+
const warnings = buildDiskSpaceWarnings({
72+
availableBytes: 50 * 1024 * 1024,
73+
displayStateDir: "~/.openclaw",
74+
});
75+
expect(warnings).toHaveLength(3);
76+
expect(warnings[0]).toContain("CRITICAL");
77+
expect(warnings[0]).toContain("50 MB");
78+
});
79+
80+
it("returns critical at exactly 0 bytes", () => {
81+
const warnings = buildDiskSpaceWarnings({
82+
availableBytes: 0,
83+
displayStateDir: "~/.openclaw",
84+
});
85+
expect(warnings).toHaveLength(3);
86+
expect(warnings[0]).toContain("CRITICAL");
87+
});
88+
89+
it("returns empty at exactly 500 MB (boundary)", () => {
90+
const warnings = buildDiskSpaceWarnings({
91+
availableBytes: 500 * 1024 * 1024,
92+
displayStateDir: "~/.openclaw",
93+
});
94+
expect(warnings).toEqual([]);
95+
});
96+
97+
it("returns warning at 499 MB (just below boundary)", () => {
98+
const warnings = buildDiskSpaceWarnings({
99+
availableBytes: 499 * 1024 * 1024,
100+
displayStateDir: "~/.openclaw",
101+
});
102+
expect(warnings).toHaveLength(2);
103+
expect(warnings[0]).toContain("Low disk space");
104+
});
105+
106+
it("returns critical at exactly 99 MB (just below critical)", () => {
107+
const warnings = buildDiskSpaceWarnings({
108+
availableBytes: 99 * 1024 * 1024,
109+
displayStateDir: "~/.openclaw",
110+
});
111+
expect(warnings).toHaveLength(3);
112+
expect(warnings[0]).toContain("CRITICAL");
113+
});
114+
});
115+
116+
describe("noteDiskSpace", () => {
117+
it("calls note when space is below warning threshold", async () => {
118+
const { note: mockNote } = await import("../../packages/terminal-core/src/note.js");
119+
vi.mocked(mockNote).mockClear();
120+
121+
noteDiskSpace({ gateway: { mode: "local" } } as never, {
122+
env: { HOME: "/home/test" },
123+
readDiskSpace: () => ({ availableBytes: 300 * 1024 * 1024 }),
124+
});
125+
126+
expect(mockNote).toHaveBeenCalledOnce();
127+
const [message, title] = vi.mocked(mockNote).mock.calls[0];
128+
expect(title).toBe("Disk space");
129+
expect(message).toContain("Low disk space");
130+
});
131+
132+
it("calls note with CRITICAL when space is very low", async () => {
133+
const { note: mockNote } = await import("../../packages/terminal-core/src/note.js");
134+
vi.mocked(mockNote).mockClear();
135+
136+
noteDiskSpace({ gateway: { mode: "local" } } as never, {
137+
env: { HOME: "/home/test" },
138+
readDiskSpace: () => ({ availableBytes: 50 * 1024 * 1024 }),
139+
});
140+
141+
expect(mockNote).toHaveBeenCalledOnce();
142+
const [message] = vi.mocked(mockNote).mock.calls[0];
143+
expect(message).toContain("CRITICAL");
144+
});
145+
146+
it("does not call note when space is sufficient", async () => {
147+
const { note: mockNote } = await import("../../packages/terminal-core/src/note.js");
148+
vi.mocked(mockNote).mockClear();
149+
150+
noteDiskSpace({ gateway: { mode: "local" } } as never, {
151+
env: { HOME: "/home/test" },
152+
readDiskSpace: () => ({ availableBytes: 10 * 1024 * 1024 * 1024 }),
153+
});
154+
155+
expect(mockNote).not.toHaveBeenCalled();
156+
});
157+
158+
it("does not call note when disk space cannot be read", async () => {
159+
const { note: mockNote } = await import("../../packages/terminal-core/src/note.js");
160+
vi.mocked(mockNote).mockClear();
161+
162+
noteDiskSpace({ gateway: { mode: "local" } } as never, {
163+
env: { HOME: "/home/test" },
164+
readDiskSpace: () => null,
165+
});
166+
167+
expect(mockNote).not.toHaveBeenCalled();
168+
});
169+
});

‎src/commands/doctor-disk-space.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import os from "node:os";
2+
import type { OpenClawConfig } from "../config/config.js";
3+
import { resolveStateDir } from "../config/paths.js";
4+
import { resolveRequiredHomeDir } from "../infra/home-dir.js";
5+
import { tryReadDiskSpace } from "../infra/disk-space.js";
6+
import { note } from "../../packages/terminal-core/src/note.js";
7+
import { shortenHomePath } from "../utils.js";
8+
9+
// 100 MB — below this, config writes and session transcripts are likely to
10+
// fail silently, causing data loss.
11+
const CRITICAL_BYTES = 100 * 1024 * 1024;
12+
13+
// 500 MB — enough headroom for normal operation but worth a heads-up so
14+
// operators can free space before it becomes critical.
15+
const WARNING_BYTES = 500 * 1024 * 1024;
16+
17+
/**
18+
* Format a byte count into a human-readable string (B / KB / MB / GB).
19+
* Uses Math.floor for MB/KB values to avoid rounding up past a decision
20+
* threshold (e.g. 99.6 MB should display as "99 MB", not "100 MB").
21+
* Exported for testing.
22+
*/
23+
export function formatBytes(bytes: number): string {
24+
if (bytes < 0 || !Number.isFinite(bytes)) {
25+
return "unknown";
26+
}
27+
if (bytes >= 1024 * 1024 * 1024) {
28+
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
29+
}
30+
if (bytes >= 1024 * 1024) {
31+
return `${Math.floor(bytes / (1024 * 1024))} MB`;
32+
}
33+
if (bytes >= 1024) {
34+
return `${Math.floor(bytes / 1024)} KB`;
35+
}
36+
return `${bytes} B`;
37+
}
38+
39+
/**
40+
* Build warning lines based on available disk space.
41+
* Pure function — exported for testing without FS side effects.
42+
*/
43+
export function buildDiskSpaceWarnings(params: {
44+
availableBytes: number;
45+
displayStateDir: string;
46+
}): string[] {
47+
const { availableBytes, displayStateDir } = params;
48+
const displayFreeSpace = formatBytes(availableBytes);
49+
const warnings: string[] = [];
50+
51+
if (availableBytes < CRITICAL_BYTES) {
52+
warnings.push(
53+
`- CRITICAL: only ${displayFreeSpace} free on the partition containing ${displayStateDir}.`,
54+
);
55+
warnings.push("- Config writes, session transcripts, and log rotation may fail silently.");
56+
warnings.push("- Free up disk space immediately to avoid data loss.");
57+
} else if (availableBytes < WARNING_BYTES) {
58+
warnings.push(
59+
`- Low disk space: ${displayFreeSpace} free on the partition containing ${displayStateDir}.`,
60+
);
61+
warnings.push("- Consider freeing space to prevent future config/session write failures.");
62+
}
63+
64+
return warnings;
65+
}
66+
67+
/**
68+
* Doctor health contribution: check free disk space on the partition that
69+
* holds the state directory and warn when it drops below safe thresholds.
70+
*
71+
* This catches a common operational failure mode where OpenClaw silently
72+
* fails to write config, sessions, or logs because the disk is full.
73+
*
74+
* Disk-space probing (statfs + nearest-existing-ancestor resolution) is
75+
* delegated to the shared src/infra/disk-space.ts helper so this Doctor
76+
* check and the install/update diagnostics stay on one implementation.
77+
* The two-tier warning/critical thresholds and Doctor-facing formatting
78+
* are specific to this health contribution.
79+
*/
80+
export function noteDiskSpace(
81+
_cfg: OpenClawConfig, // reserved for API consistency with other Doctor contributions
82+
deps?: {
83+
env?: NodeJS.ProcessEnv;
84+
readDiskSpace?: (targetPath: string) => { availableBytes: number } | null;
85+
},
86+
): void {
87+
const env = deps?.env ?? process.env;
88+
const homedir = () => resolveRequiredHomeDir(env, os.homedir);
89+
const stateDir = resolveStateDir(env, homedir);
90+
91+
const readDiskSpace = deps?.readDiskSpace ?? tryReadDiskSpace;
92+
const snapshot = readDiskSpace(stateDir);
93+
// If we cannot determine free space (no existing ancestor, unsupported FS,
94+
// or permission error), skip silently — other contributions already
95+
// handle missing directories.
96+
if (!snapshot) {
97+
return;
98+
}
99+
100+
const displayStateDir = shortenHomePath(stateDir);
101+
const warnings = buildDiskSpaceWarnings({
102+
availableBytes: snapshot.availableBytes,
103+
displayStateDir,
104+
});
105+
106+
if (warnings.length > 0) {
107+
note(warnings.join("\n"), "Disk space");
108+
}
109+
}

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,11 @@ async function runReleaseConfiguredPluginInstallsHealth(
446446
};
447447
}
448448

449+
async function runDiskSpaceHealth(ctx: DoctorHealthFlowContext): Promise<void> {
450+
const { noteDiskSpace } = await import("../commands/doctor-disk-space.js");
451+
noteDiskSpace(ctx.cfg);
452+
}
453+
449454
async function runStateIntegrityHealth(ctx: DoctorHealthFlowContext): Promise<void> {
450455
const { noteStateIntegrity } = await loadDoctorStateIntegrityModule();
451456
await noteStateIntegrity(ctx.cfg, ctx.prompter, ctx.configPath);
@@ -1064,6 +1069,11 @@ export function resolveDoctorHealthContributions(): DoctorHealthContribution[] {
10641069
label: "Plugin registry",
10651070
run: runPluginRegistryHealth,
10661071
}),
1072+
createDoctorHealthContribution({
1073+
id: "doctor:disk-space",
1074+
label: "Disk space",
1075+
run: runDiskSpaceHealth,
1076+
}),
10671077
createDoctorHealthContribution({
10681078
id: "doctor:state-integrity",
10691079
label: "State integrity",

‎src/flows/doctor-health-conversion-plan.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,12 @@ export const doctorHealthConversionRules = [
8181
target: ["core/doctor/plugin-registry"],
8282
rule: "Detect stale plugin registry state and let repair return the next config.",
8383
},
84+
{
85+
contributionId: "doctor:disk-space",
86+
conversion: "terminal-side-effect",
87+
target: ["doctor-run/disk-space"],
88+
rule: "Currently emits low/critical free-space warnings via note(); convert to a path-scoped read-only finding (no repair) when the disk-space check gains a structured detector.",
89+
},
8490
{
8591
contributionId: "doctor:state-integrity",
8692
conversion: "repair-backed-detect",

0 commit comments

Comments
 (0)