Skip to content

Commit 6c81253

Browse files
authored
feat(node-host): migrate retired state before connecting (#115495)
* feat(node-host): run doctor-owned state migrations at startup * fix(node-host): satisfy startup migration lint
1 parent a8f1e03 commit 6c81253

5 files changed

Lines changed: 307 additions & 0 deletions

File tree

‎src/node-host/runner.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const mocks = vi.hoisted(() => ({
2727
normalizedPath: null as string | null,
2828
resolvedExecutables: new Map<string, string>(),
2929
closeMcpManager: vi.fn(async () => undefined),
30+
runStartupMigrations: vi.fn(async () => undefined),
3031
configureNodeHost: vi.fn(async (params: Parameters<typeof configureNodeHost>[0]) => {
3132
mocks.capturedConfiguredGatewayConfigs.push(params.gateway);
3233
return {
@@ -145,6 +146,10 @@ vi.mock("./skills.js", () => ({
145146
scanNodeHostedSkills: vi.fn(() => mocks.nodeSkillDescriptors),
146147
}));
147148

149+
vi.mock("./startup-state-migrations.js", () => ({
150+
runStartupMigrations: mocks.runStartupMigrations,
151+
}));
152+
148153
vi.mock("./runtime.js", async (importOriginal) => {
149154
const actual = await importOriginal<typeof import("./runtime.js")>();
150155
return {
@@ -200,6 +205,17 @@ describe("runNodeHost", () => {
200205
});
201206
});
202207

208+
it("runs startup state migrations before constructing node-host state", async () => {
209+
await expect(runNodeHost({ gatewayHost: "127.0.0.1", gatewayPort: 18789 })).rejects.toThrow(
210+
"event loop readiness timeout",
211+
);
212+
213+
expect(mocks.runStartupMigrations).toHaveBeenCalledTimes(1);
214+
expect(mocks.runStartupMigrations.mock.invocationCallOrder[0]).toBeLessThan(
215+
mocks.configureNodeHost.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
216+
);
217+
});
218+
203219
it.each([
204220
{ runtime: "darwin", platform: "macos", deviceFamily: "Mac" },
205221
{ runtime: "win32", platform: "windows", deviceFamily: "Windows" },

‎src/node-host/runner.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
coerceNodeInvokePayload,
2323
} from "./invoke-payload.js";
2424
import { prepareNodeHostRuntime, type NodeHostInventory } from "./runtime.js";
25+
import { runStartupMigrations } from "./startup-state-migrations.js";
2526

2627
type NodeHostRunOptions = {
2728
gatewayHost: string;
@@ -176,6 +177,9 @@ function buildNodeHostLocalAuthConfig(config: OpenClawConfig): OpenClawConfig {
176177
}
177178

178179
export async function runNodeHost(opts: NodeHostRunOptions): Promise<void> {
180+
// Operator-approved startup is a second authorized entry point for Doctor-owned
181+
// state migrators. Runtime invokes those owners here and never migrates inline.
182+
await runStartupMigrations({ log: { info: writeStderrLine, warn: writeStderrLine } });
179183
const plannedGateway: NodeHostGatewayConfig = {
180184
host: opts.gatewayHost,
181185
port: opts.gatewayPort,
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
import fs from "node:fs";
2+
import fsp from "node:fs/promises";
3+
import path from "node:path";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
6+
import { loadDeviceAuthToken } from "../infra/device-auth-store.js";
7+
import { generateStoredDeviceIdentity } from "../infra/device-identity-store.js";
8+
import { loadDeviceIdentityIfPresent } from "../infra/device-identity.js";
9+
import { resolveExecApprovalsPath } from "../infra/exec-approvals-config.js";
10+
import { loadExecApprovals } from "../infra/exec-approvals-store.js";
11+
import { testing as execApprovalsStoreTesting } from "../infra/exec-approvals-store.test-support.js";
12+
import { acquireGatewayLock } from "../infra/gateway-lock.js";
13+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
14+
import { captureEnv, setTestEnvValue } from "../test-utils/env.js";
15+
import { runStartupMigrations } from "./startup-state-migrations.js";
16+
17+
describe("node-host startup state migrations", () => {
18+
const envSnapshot = captureEnv(["OPENCLAW_STATE_DIR"]);
19+
const log = {
20+
info: vi.fn<(message: string) => void>(),
21+
warn: vi.fn<(message: string) => void>(),
22+
};
23+
const tempDirs = useAutoCleanupTempDirTracker((cleanup) => {
24+
afterEach(() => {
25+
closeOpenClawStateDatabaseForTest();
26+
execApprovalsStoreTesting.reset();
27+
envSnapshot.restore();
28+
cleanup();
29+
});
30+
});
31+
32+
beforeEach(() => {
33+
vi.clearAllMocks();
34+
});
35+
36+
function useStateDir(): { env: NodeJS.ProcessEnv; stateDir: string } {
37+
const stateDir = fs.realpathSync(tempDirs.make("openclaw-node-host-migrations-"));
38+
return {
39+
env: { ...process.env, HOME: stateDir, OPENCLAW_STATE_DIR: stateDir },
40+
stateDir,
41+
};
42+
}
43+
44+
async function writeDeviceAuth(stateDir: string): Promise<string> {
45+
const sourcePath = path.join(stateDir, "identity", "device-auth.json");
46+
await fsp.mkdir(path.dirname(sourcePath), { recursive: true });
47+
await fsp.writeFile(
48+
sourcePath,
49+
JSON.stringify({
50+
version: 1,
51+
deviceId: "device-1",
52+
tokens: {
53+
operator: {
54+
token: "legacy-token",
55+
scopes: ["operator.write"],
56+
updatedAtMs: 10,
57+
},
58+
},
59+
}),
60+
);
61+
return sourcePath;
62+
}
63+
64+
async function writeDeviceIdentity(stateDir: string): Promise<{
65+
deviceId: string;
66+
sourcePath: string;
67+
}> {
68+
const identity = generateStoredDeviceIdentity(1_700_000_000_000);
69+
const sourcePath = path.join(stateDir, "identity", "device.json");
70+
await fsp.mkdir(path.dirname(sourcePath), { recursive: true });
71+
await fsp.writeFile(sourcePath, JSON.stringify({ version: 1, ...identity }));
72+
return { deviceId: identity.deviceId, sourcePath };
73+
}
74+
75+
async function writeExecApprovals(env: NodeJS.ProcessEnv): Promise<string> {
76+
const sourcePath = resolveExecApprovalsPath(env);
77+
await fsp.writeFile(
78+
sourcePath,
79+
`${JSON.stringify({
80+
version: 1,
81+
defaults: { security: "deny" },
82+
agents: {},
83+
})}\n`,
84+
);
85+
return sourcePath;
86+
}
87+
88+
it("migrates device auth before the runtime gate reads it", async () => {
89+
const { env, stateDir } = useStateDir();
90+
const sourcePath = await writeDeviceAuth(stateDir);
91+
92+
await runStartupMigrations({ env, log });
93+
94+
expect(fs.existsSync(sourcePath)).toBe(false);
95+
expect(loadDeviceAuthToken({ deviceId: "device-1", role: "operator", env })).toMatchObject({
96+
token: "legacy-token",
97+
scopes: ["operator.read", "operator.write"],
98+
});
99+
expect(log.info).toHaveBeenCalledWith("Migrated 1 device-auth token to SQLite.");
100+
expect(log.warn).not.toHaveBeenCalled();
101+
});
102+
103+
it("migrates legacy exec approvals into the canonical store", async () => {
104+
const { env, stateDir } = useStateDir();
105+
const sourcePath = await writeExecApprovals(env);
106+
setTestEnvValue("OPENCLAW_STATE_DIR", stateDir);
107+
execApprovalsStoreTesting.reset();
108+
109+
await runStartupMigrations({ env, log });
110+
111+
expect(fs.existsSync(sourcePath)).toBe(false);
112+
expect(loadExecApprovals().defaults?.security).toBe("deny");
113+
expect(log.info).toHaveBeenCalledWith(
114+
"Imported legacy exec approvals into shared SQLite state.",
115+
);
116+
expect(log.warn).not.toHaveBeenCalled();
117+
});
118+
119+
it("migrates a legacy device identity", async () => {
120+
const { env, stateDir } = useStateDir();
121+
const { deviceId, sourcePath } = await writeDeviceIdentity(stateDir);
122+
123+
await runStartupMigrations({ env, log });
124+
125+
expect(fs.existsSync(sourcePath)).toBe(false);
126+
expect(loadDeviceIdentityIfPresent({ env })?.deviceId).toBe(deviceId);
127+
expect(log.info).toHaveBeenCalledWith("Migrated primary device identity to SQLite.");
128+
expect(log.warn).not.toHaveBeenCalled();
129+
});
130+
131+
it("preserves a pending native device identity claim and continues", async () => {
132+
const { env, stateDir } = useStateDir();
133+
const { sourcePath } = await writeDeviceIdentity(stateDir);
134+
const nativeClaimPath = `${sourcePath}.native-importing`;
135+
await fsp.rename(sourcePath, nativeClaimPath);
136+
137+
await expect(runStartupMigrations({ env, log })).resolves.toBeUndefined();
138+
139+
expect(fs.existsSync(nativeClaimPath)).toBe(true);
140+
expect(log.info).not.toHaveBeenCalled();
141+
expect(log.warn).toHaveBeenCalledWith(
142+
"Native device identity import is pending; restart the native app before running Doctor.",
143+
);
144+
});
145+
146+
it("warns and leaves every legacy file untouched when the state lock is held", async () => {
147+
const { env, stateDir } = useStateDir();
148+
const deviceAuthPath = await writeDeviceAuth(stateDir);
149+
const { sourcePath: deviceIdentityPath } = await writeDeviceIdentity(stateDir);
150+
const execApprovalsPath = await writeExecApprovals(env);
151+
const gatewayLock = await acquireGatewayLock({
152+
allowInTests: true,
153+
env,
154+
pollIntervalMs: 10,
155+
port: 18_792,
156+
timeoutMs: 100,
157+
});
158+
if (!gatewayLock) {
159+
throw new Error("expected test Gateway lock");
160+
}
161+
162+
try {
163+
await expect(runStartupMigrations({ env, log })).resolves.toBeUndefined();
164+
} finally {
165+
await gatewayLock.release();
166+
}
167+
168+
expect(fs.existsSync(deviceAuthPath)).toBe(true);
169+
expect(fs.existsSync(deviceIdentityPath)).toBe(true);
170+
expect(fs.existsSync(execApprovalsPath)).toBe(true);
171+
expect(log.info).not.toHaveBeenCalled();
172+
expect(log.warn).toHaveBeenCalledTimes(3);
173+
});
174+
175+
it("is silent when no retired state is present", async () => {
176+
const { env } = useStateDir();
177+
178+
await runStartupMigrations({ env, log });
179+
180+
expect(log.info).not.toHaveBeenCalled();
181+
expect(log.warn).not.toHaveBeenCalled();
182+
});
183+
});
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/** Runs the Doctor-owned retired state-store migrations required by node-host startup. */
2+
import { resolveStateDir } from "../config/paths.js";
3+
import { formatErrorMessage } from "../infra/errors.js";
4+
import {
5+
detectLegacyDeviceAuth,
6+
migrateLegacyDeviceAuth,
7+
} from "../infra/state-migrations.device-auth.js";
8+
import {
9+
detectLegacyDeviceIdentity,
10+
migrateLegacyDeviceIdentity,
11+
} from "../infra/state-migrations.device-identity.js";
12+
import {
13+
detectLegacyExecApprovals,
14+
migrateLegacyExecApprovals,
15+
} from "../infra/state-migrations.exec-approvals.js";
16+
import type { MigrationLogger, MigrationMessages } from "../infra/state-migrations.types.js";
17+
import { createSubsystemLogger } from "../logging/subsystem.js";
18+
19+
async function reportMigration(
20+
label: string,
21+
run: () => Promise<MigrationMessages | undefined>,
22+
log: MigrationLogger,
23+
): Promise<void> {
24+
try {
25+
const result = await run();
26+
for (const change of result?.changes ?? []) {
27+
log.info(change);
28+
}
29+
for (const warning of result?.warnings ?? []) {
30+
log.warn(warning);
31+
}
32+
} catch (error) {
33+
// Startup auto-migration is best-effort by operator decision. Existing store
34+
// gates remain the fail-closed authority when a Doctor-owned migrator throws.
35+
log.warn(`Failed running ${label} startup migration: ${formatErrorMessage(error)}`);
36+
}
37+
}
38+
39+
/** Invoke the Doctor-owned state migrators authorized for node-host startup. */
40+
export async function runStartupMigrations(params?: {
41+
env?: NodeJS.ProcessEnv;
42+
log?: MigrationLogger;
43+
}): Promise<void> {
44+
const stateDir = resolveStateDir(params?.env);
45+
const env = { ...(params?.env ?? process.env), OPENCLAW_STATE_DIR: stateDir };
46+
const log = params?.log ?? createSubsystemLogger("node-host/startup-migrations");
47+
48+
await reportMigration(
49+
"device auth",
50+
async () => {
51+
const detected = detectLegacyDeviceAuth({
52+
stateDir,
53+
doctorOnlyStateMigrations: true,
54+
});
55+
if (!detected.hasLegacy) {
56+
return undefined;
57+
}
58+
return await migrateLegacyDeviceAuth({ detected, env, stateDir });
59+
},
60+
log,
61+
);
62+
await reportMigration(
63+
"device identity",
64+
async () => {
65+
const detected = detectLegacyDeviceIdentity({
66+
stateDir,
67+
env,
68+
doctorOnlyStateMigrations: true,
69+
});
70+
if (!detected.hasLegacy) {
71+
return undefined;
72+
}
73+
return await migrateLegacyDeviceIdentity({
74+
detected,
75+
env,
76+
stateDir,
77+
doctorOnlyStateMigrations: true,
78+
});
79+
},
80+
log,
81+
);
82+
await reportMigration(
83+
"exec approvals",
84+
async () => {
85+
const detected = detectLegacyExecApprovals({
86+
stateDir,
87+
doctorOnlyStateMigrations: true,
88+
});
89+
if (!detected.hasLegacy) {
90+
return undefined;
91+
}
92+
return await migrateLegacyExecApprovals({ detected, env, stateDir });
93+
},
94+
log,
95+
);
96+
}

‎src/node-host/worker.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { createInterface } from "node:readline";
33
import { VERSION } from "../version.js";
44
import { loadNodeHostConfig } from "./config.js";
55
import { prepareNodeHostRuntime, type NodeHostInventory } from "./runtime.js";
6+
import { runStartupMigrations } from "./startup-state-migrations.js";
67
import {
78
NodeHostWorkerBridgeClient,
89
parseNodeHostWorkerInput,
@@ -13,11 +14,18 @@ function writeMessage(message: unknown): void {
1314
process.stdout.write(`${JSON.stringify(message)}\n`);
1415
}
1516

17+
function writeStderrLine(message: string): void {
18+
process.stderr.write(`${message}\n`);
19+
}
20+
1621
function emitInventory(inventory: NodeHostInventory): void {
1722
writeMessage({ type: "inventory", inventory });
1823
}
1924

2025
export async function runNodeHostWorker(): Promise<void> {
26+
// Operator-approved startup is a second authorized entry point for Doctor-owned
27+
// state migrators. Runtime invokes those owners here and never migrates inline.
28+
await runStartupMigrations({ log: { info: writeStderrLine, warn: writeStderrLine } });
2129
const nodeConfig = await loadNodeHostConfig();
2230
const prepared = await prepareNodeHostRuntime({
2331
enableDuplexPluginCommands: true,

0 commit comments

Comments
 (0)