Skip to content

Commit f2cc4f1

Browse files
PollyBot13obviyus
andauthored
fix(runtime): bind diagnostics to loaded build (#132854)
Bind Gateway diagnostics to one process-lifetime loaded-build commit. Status output, SQLite schema-refusal errors, and restart validation now keep reporting the artifact that the Gateway loaded after its source checkout moves. Conflicting build metadata fails closed instead of guessing from live Git state. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 8423dcd commit f2cc4f1

14 files changed

Lines changed: 238 additions & 37 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3133,7 +3133,7 @@ src/infra/fs-safe-remove.ts 4
31333133
src/infra/gateway-lock.ts 4
31343134
src/infra/gateway-processes.ts 1
31353135
src/infra/gemini-auth.ts 1
3136-
src/infra/git-commit.ts 2
3136+
src/infra/git-commit.ts 1
31373137
src/infra/heartbeat-outcome-store.ts 1
31383138
src/infra/heartbeat-runner-config.ts 1
31393139
src/infra/heartbeat-visibility.ts 1

‎docs/reference/database-schemas.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ A newer OpenClaw build wrote your databases, and the running build is older. The
260260

261261
Act on the install root, not the version. One release version string spans many `main` commits, schema levels, and same-version schema shapes, so two installs can both call themselves `2026.7.2` and still disagree about a database. A prerelease version may not exist on the `latest` npm tag at all: check `npm view openclaw dist-tags` before reinstalling, because the tag carrying the schema you need may be `beta`, and reinstalling from `latest` can move you further away.
262262

263-
A linked source checkout is the case where the commit misleads: `openclaw --version` reports the checkout's git HEAD, but the code actually executing is whatever `dist/` was last built. If the install root is a checkout, rebuild it (`pnpm build`) before concluding the version is wrong.
263+
When a Gateway runs from a linked source checkout, its status and schema-refusal diagnostics report the commit captured when `dist/` was built, not the checkout's current Git HEAD. If that build identity is unknown, rebuild the checkout (`pnpm build`) before concluding the version is wrong.
264264

265265
Open the database with a build that supports its schema, or point the older build at a separate `OPENCLAW_STATE_DIR`. Do not edit the database to silence the error.
266266

‎src/cli/run-main.exit.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,7 @@ vi.mock("./command-execution-startup.js", () => ({
258258

259259
vi.mock("../version.js", () => ({
260260
VERSION: "9.9.9-test",
261+
resolveRuntimeServiceCommit: () => null,
261262
}));
262263

263264
vi.mock("./banner.js", () => ({

‎src/infra/git-commit.test.ts‎

Lines changed: 90 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,13 +76,14 @@ function limitPositionalReads(maxBytes: number) {
7676

7777
describe("git commit resolution", () => {
7878
let resolveCommitHash: (typeof import("./git-commit.js"))["resolveCommitHash"];
79+
let resolveLoadedCommitHash: (typeof import("./git-commit.js"))["resolveLoadedCommitHash"];
7980

8081
beforeEach(async () => {
8182
vi.restoreAllMocks();
8283
vi.doUnmock("node:fs");
8384
vi.doUnmock("node:module");
8485
vi.resetModules();
85-
({ resolveCommitHash } = await import("./git-commit.js"));
86+
({ resolveCommitHash, resolveLoadedCommitHash } = await import("./git-commit.js"));
8687
});
8788

8889
afterEach(async () => {
@@ -129,6 +130,94 @@ describe("git commit resolution", () => {
129130
).toBe(repoCommit.slice(0, 7));
130131
});
131132

133+
it.each([
134+
{
135+
name: "uses matching local build stamps",
136+
buildCommit: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
137+
runtimeCommit: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
138+
expected: "aaaaaaa",
139+
},
140+
{
141+
name: "rejects conflicting local build stamps",
142+
buildCommit: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
143+
runtimeCommit: "cccccccccccccccccccccccccccccccccccccccc",
144+
expected: null,
145+
},
146+
])(
147+
"$name instead of mutable checkout metadata",
148+
async ({ buildCommit, runtimeCommit, expected }) => {
149+
const root = await makeTempDir("git-commit-loaded-build");
150+
const dist = path.join(root, "dist");
151+
await makeFakeGitRepo(root, {
152+
head: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n",
153+
});
154+
await fs.mkdir(dist, { recursive: true });
155+
await fs.writeFile(path.join(dist, ".buildstamp"), JSON.stringify({ head: buildCommit }));
156+
await fs.writeFile(
157+
path.join(dist, ".runtime-postbuildstamp"),
158+
JSON.stringify({ head: runtimeCommit }),
159+
);
160+
161+
expect(
162+
resolveLoadedCommitHash({
163+
env: { GIT_COMMIT: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" },
164+
moduleUrl: pathToFileURL(path.join(dist, "version-chunk.js")).href,
165+
}),
166+
).toBe(expected);
167+
},
168+
);
169+
170+
it("uses build info when source-archive stamps have no Git head", async () => {
171+
const root = await makeTempDir("git-commit-headless-build");
172+
const dist = path.join(root, "dist");
173+
await fs.mkdir(dist, { recursive: true });
174+
await fs.writeFile(path.join(dist, ".buildstamp"), JSON.stringify({ head: null }));
175+
await fs.writeFile(path.join(dist, ".runtime-postbuildstamp"), JSON.stringify({}));
176+
await fs.writeFile(
177+
path.join(dist, "build-info.json"),
178+
JSON.stringify({ commit: "0123456789abcdef0123456789abcdef01234567" }),
179+
);
180+
181+
expect(
182+
resolveLoadedCommitHash({
183+
env: {},
184+
moduleUrl: pathToFileURL(path.join(dist, "version-chunk.js")).href,
185+
}),
186+
).toBe("0123456");
187+
});
188+
189+
it("does not guess when commitless build stamps lack build info", async () => {
190+
const root = await makeTempDir("git-commit-headless-build-no-info");
191+
const dist = path.join(root, "dist");
192+
await makeFakeGitRepo(root, {
193+
head: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n",
194+
});
195+
await fs.mkdir(dist, { recursive: true });
196+
await fs.writeFile(path.join(dist, ".buildstamp"), JSON.stringify({ head: null }));
197+
await fs.writeFile(path.join(dist, ".runtime-postbuildstamp"), JSON.stringify({}));
198+
199+
expect(
200+
resolveLoadedCommitHash({
201+
env: { GIT_COMMIT: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" },
202+
moduleUrl: pathToFileURL(path.join(dist, "version-chunk.js")).href,
203+
}),
204+
).toBeNull();
205+
});
206+
207+
it("falls back to Git for true source execution without build metadata", async () => {
208+
const root = await makeTempDir("git-commit-source-runtime");
209+
await makeFakeGitRepo(root, {
210+
head: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n",
211+
});
212+
213+
expect(
214+
resolveLoadedCommitHash({
215+
env: {},
216+
moduleUrl: pathToFileURL(path.join(root, "src", "version.ts")).href,
217+
}),
218+
).toBe("bbbbbbb");
219+
});
220+
132221
it("caches build-info fallback results per resolved search directory", async () => {
133222
const temp = await makeTempDir("git-commit-build-info-cache");
134223
const readBuildInfoCommit = vi.fn(() => "deadbee");

‎src/infra/git-commit.ts‎

Lines changed: 51 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import fs from "node:fs";
33
import { createRequire } from "node:module";
44
import path from "node:path";
55
import { fileURLToPath } from "node:url";
6+
import { asNullableRecord } from "@openclaw/normalization-core/record-coerce";
67
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
78
import { isMissingPathError } from "./errors.js";
89
import { readFileWindowFullySync } from "./file-read.js";
@@ -184,27 +185,54 @@ const readCommitFromPackageJson = () => {
184185
}
185186
};
186187

187-
const readCommitFromBuildInfo = () => {
188+
const readCommitProbe = (
189+
moduleUrl: string,
190+
candidates: readonly string[],
191+
field: "commit" | "head",
192+
): string | null | undefined => {
188193
try {
189-
const require = createRequire(import.meta.url);
190-
const candidates = ["../build-info.json", "./build-info.json"];
191194
for (const candidate of candidates) {
195+
const filePath = fileURLToPath(new URL(candidate, moduleUrl));
196+
let raw: string;
192197
try {
193-
const info = require(candidate) as {
194-
commit?: string | null;
195-
};
196-
const formatted = formatCommit(info.commit ?? null);
197-
if (formatted) {
198-
return formatted;
198+
raw = safeReadFilePrefix(filePath, 1024);
199+
} catch (error) {
200+
if (isMissingPathError(error)) {
201+
continue;
199202
}
203+
return null;
204+
}
205+
try {
206+
const value = asNullableRecord(JSON.parse(raw))?.[field];
207+
return typeof value === "string" ? formatCommit(value) : null;
200208
} catch {
201-
// ignore missing candidate
209+
return null;
202210
}
203211
}
204-
return null;
205212
} catch {
206-
return null;
213+
// Invalid module URL means no loaded build metadata is available.
207214
}
215+
return undefined;
216+
};
217+
218+
const readCommitFromBuildInfo = (moduleUrl = import.meta.url) => {
219+
return readCommitProbe(moduleUrl, ["../build-info.json", "./build-info.json"], "commit") ?? null;
220+
};
221+
222+
const readLoadedCommit = (moduleUrl: string): string | null | undefined => {
223+
const buildStamp = readCommitProbe(moduleUrl, ["../.buildstamp", "./.buildstamp"], "head");
224+
const runtimeStamp = readCommitProbe(
225+
moduleUrl,
226+
["../.runtime-postbuildstamp", "./.runtime-postbuildstamp"],
227+
"head",
228+
);
229+
if (buildStamp !== undefined || runtimeStamp !== undefined) {
230+
if (buildStamp || runtimeStamp) {
231+
return buildStamp && buildStamp === runtimeStamp ? buildStamp : null;
232+
}
233+
return readCommitFromBuildInfo(moduleUrl);
234+
}
235+
return readCommitProbe(moduleUrl, ["../build-info.json", "./build-info.json"], "commit");
208236
};
209237

210238
export const resolveCommitHash = (
@@ -258,3 +286,14 @@ export const resolveCommitHash = (
258286
return cacheGitCommit(searchDir, null);
259287
}
260288
};
289+
290+
/** Resolve the commit that produced the loaded artifact, not the checkout's current revision. */
291+
export function resolveLoadedCommitHash(
292+
options: { env?: NodeJS.ProcessEnv; moduleUrl?: string } = {},
293+
): string | null {
294+
const moduleUrl = options.moduleUrl ?? import.meta.url;
295+
const loaded = readLoadedCommit(moduleUrl);
296+
return loaded === undefined
297+
? resolveCommitHash({ moduleUrl, ...(options.env ? { env: options.env } : {}) })
298+
: loaded;
299+
}

‎src/infra/restart-sentinel.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ vi.mock("../state/openclaw-state-db.js", async (importOriginal) => {
3030
};
3131
});
3232

33+
vi.mock("../version.js", async (importOriginal) => {
34+
const actual = await importOriginal<typeof import("../version.js")>();
35+
return { ...actual, resolveRuntimeServiceCommit: () => "aaaaaaa" };
36+
});
37+
3338
import type { DB as OpenClawStateKyselyDatabase } from "../state/openclaw-state-db.generated.js";
3439
import {
3540
closeOpenClawStateDatabaseForTest,
@@ -510,6 +515,27 @@ describe("restart sentinel", () => {
510515
});
511516
});
512517

518+
it("uses the loaded build commit when finalizing an update", async () => {
519+
await withRestartSentinelStateDir(async () => {
520+
await writeRestartSentinel({
521+
kind: "update",
522+
status: "ok",
523+
ts: Date.now(),
524+
stats: {
525+
mode: "git",
526+
root: process.cwd(),
527+
after: { sha: "aaaaaaa", version: "actual-version" },
528+
},
529+
});
530+
531+
await finalizeUpdateRestartSentinelRunningVersion("actual-version");
532+
533+
await expect(readRestartSentinel()).resolves.toMatchObject({
534+
payload: { status: "ok" },
535+
});
536+
});
537+
});
538+
513539
it("does not rewrite update sentinels when the running version is already current", async () => {
514540
await withRestartSentinelStateDir(async () => {
515541
const ts = Date.now();

‎src/infra/restart-sentinel.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@ import {
88
openOpenClawStateDatabase,
99
runOpenClawStateWriteTransaction,
1010
} from "../state/openclaw-state-db.js";
11-
import { resolveRuntimeServiceVersion } from "../version.js";
11+
import { resolveRuntimeServiceCommit, resolveRuntimeServiceVersion } from "../version.js";
1212
import { formatErrorMessage } from "./errors.js";
13-
import { resolveCommitHash } from "./git-commit.js";
1413
import { resolveOpenClawPackageRoot } from "./openclaw-root.js";
1514
import {
1615
deleteRestartSentinelRowSync,
@@ -97,7 +96,7 @@ function commitsMatch(expected: string, actual: string): boolean {
9796
export async function finalizeUpdateRestartSentinelRunningVersion(
9897
version = resolveRuntimeServiceVersion(process.env),
9998
env: NodeJS.ProcessEnv = process.env,
100-
commit = resolveCommitHash({ env, moduleUrl: import.meta.url }),
99+
commit = resolveRuntimeServiceCommit(),
101100
runningRoot?: string | null,
102101
): Promise<RestartSentinel | null> {
103102
const snapshot = await readRestartSentinel(env);

‎src/infra/sqlite-user-version.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
// Tests for SQLite user_version pragma helper.
2-
import { describe, expect, it } from "vitest";
2+
import { describe, expect, it, vi } from "vitest";
3+
4+
vi.mock("../version.js", async (importOriginal) => {
5+
const actual = await importOriginal<typeof import("../version.js")>();
6+
return { ...actual, resolveRuntimeServiceCommit: () => "aaaaaaa" };
7+
});
38
import { VERSION } from "../version.js";
49
import {
510
createNewerSqliteSchemaVersionError,
@@ -85,4 +90,8 @@ describe("describeRunningOpenClawBuild", () => {
8590
expect(described).toContain(VERSION);
8691
expect(described).toContain("installed at ");
8792
});
93+
94+
it("reports the loaded build commit", () => {
95+
expect(describeRunningOpenClawBuild()).toContain("(aaaaaaa)");
96+
});
8897
});

‎src/infra/sqlite-user-version.ts‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { OPENCLAW_DATABASE_SCHEMA_DOCS_URL } from "../state/openclaw-state-db-contract.js";
2-
import { VERSION } from "../version.js";
3-
import { resolveCommitHash } from "./git-commit.js";
2+
import { resolveRuntimeServiceCommit, VERSION } from "../version.js";
43
import { resolveOpenClawPackageRootSync } from "./openclaw-root.js";
54

65
type SqliteUserVersionReader = {
@@ -26,15 +25,12 @@ export function readSqliteUserVersion(db: SqliteUserVersionReader): number {
2625
}
2726

2827
/**
29-
* Name the refusing install the way `--version` does, plus the root it runs from.
30-
* The path is the only part an operator can always act on: one release version
31-
* string spans many commits, and a linked source checkout reports its git HEAD
32-
* even when the built output actually executing is older.
28+
* Name the refusing build from immutable loaded metadata, plus its install root.
29+
* The path remains actionable when multiple installs share a version or build.
3330
*/
3431
export function describeRunningOpenClawBuild(): string {
35-
const moduleUrl = import.meta.url;
36-
const commit = resolveCommitHash({ moduleUrl });
37-
const root = resolveOpenClawPackageRootSync({ moduleUrl });
32+
const commit = resolveRuntimeServiceCommit();
33+
const root = resolveOpenClawPackageRootSync({ moduleUrl: import.meta.url });
3834
const identity = commit ? `OpenClaw ${VERSION} (${commit})` : `OpenClaw ${VERSION}`;
3935
return root ? `${identity} installed at ${root}` : identity;
4036
}
@@ -48,7 +44,7 @@ export function createNewerSqliteSchemaVersionError(
4844
return new SqliteSchemaVersionError(
4945
`${databaseLabel} ${pathname} uses newer schema version ${schemaVersion}; this build supports ${supportedVersion}. ` +
5046
`Refused by ${describeRunningOpenClawBuild()}. ` +
51-
"Identify installs by that path: one version string spans many builds, and a linked source checkout reports its git HEAD even when its built output is older. " +
47+
"Identify installs by that path when multiple installs share a version or build. " +
5248
`Run a build that supports schema ${schemaVersion} or newer against this state directory — rebuild or update the install above — or point this build at a different OPENCLAW_STATE_DIR. ` +
5349
`See ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}.`,
5450
);

‎src/status/status-message.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
// Status message tests cover status message formatting and persistence.
2-
import { afterEach, describe, expect, it } from "vitest";
2+
import { afterEach, describe, expect, it, vi } from "vitest";
33
import { testing as cliBackendsTesting } from "../agents/cli-backends.test-support.js";
44
import { SESSION_TOTAL_TOKENS_VERSION } from "../config/sessions/types.js";
55
import type { ModelDefinitionConfig } from "../config/types.models.js";
6+
7+
vi.mock("../version.js", async (importOriginal) => {
8+
const actual = await importOriginal<typeof import("../version.js")>();
9+
return { ...actual, resolveRuntimeServiceCommit: () => "aaaaaaa" };
10+
});
611
import { buildStatusMessage, buildStatusMessageParts } from "./status-message.js";
712

813
function statusTestModel(id: string, name: string, contextWindow: number): ModelDefinitionConfig {
@@ -42,6 +47,20 @@ describe("buildStatusMessage current time", () => {
4247
});
4348

4449
describe("buildStatusMessageParts presentation", () => {
50+
it("reports the loaded build commit", () => {
51+
const parts = buildStatusMessageParts({
52+
now: 1_751_529_600_000,
53+
config: { agents: { defaults: { userTimezone: "UTC", timeFormat: "24" } } },
54+
agent: { model: "anthropic/claude-haiku-4-5" },
55+
sessionKey: "agent:main:main",
56+
sessionScope: "per-sender",
57+
queue: { mode: "steer", depth: 0 },
58+
modelAuth: "api-key",
59+
});
60+
61+
expect(parts.presentation.title).toContain("(aaaaaaa)");
62+
});
63+
4564
it("mirrors the text body as a titled status table with context lines", () => {
4665
const parts = buildStatusMessageParts({
4766
now: 1_751_529_600_000,

0 commit comments

Comments
 (0)