Skip to content

Commit 993c975

Browse files
authored
fix(heartbeat): bound HEARTBEAT.md file read size (#101775)
* fix(heartbeat): bound HEARTBEAT.md file read size * fix(heartbeat): follow symlinked HEARTBEAT.md while bounding reads * fix(heartbeat): warn operators when oversized HEARTBEAT.md is skipped
1 parent 94e1cc9 commit 993c975

2 files changed

Lines changed: 129 additions & 1 deletion

File tree

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// Regression test for bounded HEARTBEAT.md reads.
2+
import fs from "node:fs/promises";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import type { OpenClawConfig } from "../config/types.openclaw.js";
6+
import { resetLogger, setLoggerOverride } from "../logging/logger.js";
7+
import { loggingState } from "../logging/state.js";
8+
import { runHeartbeatOnce } from "./heartbeat-runner.js";
9+
import { installHeartbeatRunnerTestRuntime } from "./heartbeat-runner.test-harness.js";
10+
import { seedMainSessionStore, withTempHeartbeatSandbox } from "./heartbeat-runner.test-utils.js";
11+
12+
installHeartbeatRunnerTestRuntime({ includeSlack: true });
13+
14+
afterEach(() => {
15+
loggingState.rawConsole = null;
16+
setLoggerOverride(null);
17+
resetLogger();
18+
});
19+
20+
describe("runHeartbeatOnce oversized HEARTBEAT.md", () => {
21+
it("follows a symlinked HEARTBEAT.md to a regular file", async () => {
22+
if (process.platform === "win32") {
23+
// Symlink support in unit tests is not guaranteed on Windows CI runners.
24+
return;
25+
}
26+
await withTempHeartbeatSandbox(async ({ tmpDir, storePath, replySpy }) => {
27+
const cfg: OpenClawConfig = {
28+
agents: {
29+
defaults: {
30+
workspace: tmpDir,
31+
heartbeat: { every: "5m", target: "slack", to: "channel:C123" },
32+
},
33+
},
34+
channels: { slack: { heartbeat: { showOk: false } } },
35+
session: { store: storePath },
36+
};
37+
await seedMainSessionStore(storePath, cfg, {
38+
lastChannel: "slack",
39+
lastProvider: "slack",
40+
lastTo: "channel:C123",
41+
});
42+
const heartbeatPath = path.join(tmpDir, "HEARTBEAT.md");
43+
const targetPath = path.join(tmpDir, "real-HEARTBEAT.md");
44+
await fs.writeFile(targetPath, "- Check status\n", "utf-8");
45+
await fs.rm(heartbeatPath, { force: true });
46+
await fs.symlink(targetPath, heartbeatPath);
47+
48+
replySpy.mockResolvedValue({ text: "ok" });
49+
const sendSlack = vi.fn().mockResolvedValue({ messageId: "m1", channelId: "C123" });
50+
51+
const res = await runHeartbeatOnce({
52+
cfg,
53+
deps: {
54+
getReplyFromConfig: replySpy,
55+
slack: sendSlack,
56+
getQueueSize: () => 0,
57+
nowMs: () => 0,
58+
},
59+
});
60+
61+
expect(res.status).toBe("ran");
62+
expect(sendSlack).toHaveBeenCalledTimes(1);
63+
});
64+
});
65+
66+
it("treats an oversized HEARTBEAT.md like a missing file and continues the run", async () => {
67+
await withTempHeartbeatSandbox(async ({ tmpDir, storePath, replySpy }) => {
68+
const cfg: OpenClawConfig = {
69+
agents: {
70+
defaults: {
71+
workspace: tmpDir,
72+
heartbeat: { every: "5m", target: "slack", to: "channel:C123" },
73+
},
74+
},
75+
channels: { slack: { heartbeat: { showOk: false } } },
76+
session: { store: storePath },
77+
};
78+
await seedMainSessionStore(storePath, cfg, {
79+
lastChannel: "slack",
80+
lastProvider: "slack",
81+
lastTo: "channel:C123",
82+
});
83+
// Overwrite the default heartbeat file with content larger than the 16 MB cap.
84+
const oversizedContent = Buffer.alloc(16 * 1024 * 1024 + 1, "x");
85+
await fs.writeFile(path.join(tmpDir, "HEARTBEAT.md"), oversizedContent);
86+
87+
const warn = vi.fn();
88+
loggingState.rawConsole = { log: vi.fn(), info: vi.fn(), warn, error: vi.fn() };
89+
setLoggerOverride({ level: "silent", consoleLevel: "warn" });
90+
91+
replySpy.mockResolvedValue({ text: "needs attention" });
92+
const sendSlack = vi.fn().mockResolvedValue({ messageId: "m1", channelId: "C123" });
93+
94+
const res = await runHeartbeatOnce({
95+
cfg,
96+
deps: {
97+
getReplyFromConfig: replySpy,
98+
slack: sendSlack,
99+
getQueueSize: () => 0,
100+
nowMs: () => 0,
101+
},
102+
});
103+
104+
expect(res.status).toBe("ran");
105+
expect(sendSlack).toHaveBeenCalledTimes(1);
106+
// Operators must see why their oversized heartbeat file no longer applies.
107+
expect(
108+
warn.mock.calls.some((call) => String(call[0]).includes("skipping oversized HEARTBEAT.md")),
109+
).toBe(true);
110+
});
111+
});
112+
});

‎src/infra/heartbeat-runner.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@ import {
178178
resolveHeartbeatDeliveryTargetWithSessionRoute,
179179
resolveHeartbeatSenderContext,
180180
} from "./outbound/targets.js";
181+
import { readRegularFile } from "./regular-file.js";
181182
import {
182183
consumeSelectedSystemEventEntries,
183184
peekSystemEventEntries,
@@ -985,9 +986,18 @@ async function resolveHeartbeatPreflight(params: {
985986

986987
const workspaceDir = resolveAgentWorkspaceDir(params.cfg, params.agentId);
987988
const heartbeatFilePath = path.join(workspaceDir, DEFAULT_HEARTBEAT_FILENAME);
989+
const MAX_HEARTBEAT_FILE_BYTES = 16 * 1024 * 1024;
988990
let heartbeatFileContent: string | undefined;
989991
try {
990-
heartbeatFileContent = await fs.readFile(heartbeatFilePath, "utf-8");
992+
// Resolve symlinks so a HEARTBEAT.md pointing to a regular file keeps
993+
// working; missing/broken symlinks still surface as ENOENT below.
994+
const resolvedHeartbeatFilePath = await fs.realpath(heartbeatFilePath);
995+
heartbeatFileContent = (
996+
await readRegularFile({
997+
filePath: resolvedHeartbeatFilePath,
998+
maxBytes: MAX_HEARTBEAT_FILE_BYTES,
999+
})
1000+
).buffer.toString("utf-8");
9911001
const tasks = parseHeartbeatTasks(heartbeatFileContent);
9921002
if (
9931003
isHeartbeatContentEffectivelyEmpty(heartbeatFileContent) &&
@@ -1014,6 +1024,12 @@ async function resolveHeartbeatPreflight(params: {
10141024
// The heartbeat prompt already says "if it exists".
10151025
return basePreflight;
10161026
}
1027+
// Oversized files loaded in full before the cap existed, so tell the
1028+
// operator why their heartbeat instructions no longer apply instead of
1029+
// dropping them silently. Other read errors keep proceeding as before.
1030+
if (err instanceof Error && err.message.startsWith("File exceeds")) {
1031+
log.warn(`heartbeat: skipping oversized ${DEFAULT_HEARTBEAT_FILENAME}: ${err.message}`);
1032+
}
10171033
// For other read errors, proceed with heartbeat as before.
10181034
}
10191035

0 commit comments

Comments
 (0)