|
| 1 | +// Process regressions for pristine startup eligibility and deferred config observation. |
| 2 | +import fs from "node:fs"; |
| 3 | +import path from "node:path"; |
| 4 | +import { pathToFileURL } from "node:url"; |
| 5 | +import { afterAll, describe, expect, it } from "vitest"; |
| 6 | +import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js"; |
| 7 | +import type { OpenClawConfig } from "../config/types.openclaw.js"; |
| 8 | +import { hasActiveStartupMigrationLease } from "../infra/startup-migration-checkpoint.js"; |
| 9 | +import { |
| 10 | + createSourceRuntime, |
| 11 | + runIsolatedModuleScript, |
| 12 | +} from "./doctor-config-preflight.process.test-support.js"; |
| 13 | + |
| 14 | +const tempDirs = useAutoCleanupTempDirTracker(afterAll); |
| 15 | + |
| 16 | +describe("gateway startup-migration refusal", () => { |
| 17 | + it("skips state-only checkpoint work when config and state remain absent", async () => { |
| 18 | + const root = await fs.promises.realpath(tempDirs.make("openclaw-configless-checkpoint-")); |
| 19 | + const runtimeRoot = createSourceRuntime(root); |
| 20 | + const stateDir = path.join(root, "state"); |
| 21 | + const configPath = path.join(root, "openclaw.json"); |
| 22 | + const env: NodeJS.ProcessEnv = { |
| 23 | + ...process.env, |
| 24 | + HOME: root, |
| 25 | + USERPROFILE: root, |
| 26 | + OPENCLAW_BUNDLED_PLUGINS_DIR: path.join(root, "bundled"), |
| 27 | + OPENCLAW_CONFIG_PATH: configPath, |
| 28 | + OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1", |
| 29 | + OPENCLAW_STATE_DIR: stateDir, |
| 30 | + OPENCLAW_TEST_FAST: "1", |
| 31 | + NO_COLOR: "1", |
| 32 | + }; |
| 33 | + delete env.NODE_ENV; |
| 34 | + delete env.OPENCLAW_HOME; |
| 35 | + delete env.VITEST; |
| 36 | + delete env.VITEST_POOL_ID; |
| 37 | + delete env.VITEST_WORKER_ID; |
| 38 | + |
| 39 | + const preflightUrl = pathToFileURL( |
| 40 | + path.join(runtimeRoot, "src", "commands", "doctor-config-preflight.ts"), |
| 41 | + ).href; |
| 42 | + const checkpointUrl = pathToFileURL( |
| 43 | + path.join(runtimeRoot, "src", "infra", "startup-migration-checkpoint.ts"), |
| 44 | + ).href; |
| 45 | + const script = ` |
| 46 | + const steps = []; |
| 47 | + const { runDoctorConfigPreflight } = await import(${JSON.stringify(preflightUrl)}); |
| 48 | + const { hasActiveStartupMigrationLease } = await import(${JSON.stringify(checkpointUrl)}); |
| 49 | + await runDoctorConfigPreflight({ |
| 50 | + migrateLegacyConfig: false, |
| 51 | + invalidConfigNote: false, |
| 52 | + observe: false, |
| 53 | + requireStateMigrationCheckpoint: true, |
| 54 | + measure: async (name, run) => { |
| 55 | + steps.push(name); |
| 56 | + return await run(); |
| 57 | + }, |
| 58 | + }); |
| 59 | + console.log("__RESULT__" + JSON.stringify({ |
| 60 | + activeLease: hasActiveStartupMigrationLease({ env: process.env }), |
| 61 | + stateMigrationsImported: steps.includes( |
| 62 | + "doctor.config-preflight.state-migrations-import", |
| 63 | + ), |
| 64 | + })); |
| 65 | + `; |
| 66 | + const run = () => |
| 67 | + runIsolatedModuleScript(env, script, { |
| 68 | + runtimeRoot, |
| 69 | + timeoutMs: 60_000, |
| 70 | + }); |
| 71 | + const readResult = (result: Awaited<ReturnType<typeof runIsolatedModuleScript>>) => { |
| 72 | + const resultLine = result.stdout.split("\n").find((line) => line.startsWith("__RESULT__")); |
| 73 | + expect(resultLine, `${result.stderr}\n${result.stdout}`).toBeDefined(); |
| 74 | + return JSON.parse(resultLine!.slice("__RESULT__".length)) as { |
| 75 | + activeLease: boolean; |
| 76 | + stateMigrationsImported: boolean; |
| 77 | + }; |
| 78 | + }; |
| 79 | + |
| 80 | + const first = readResult(await run()); |
| 81 | + const second = readResult(await run()); |
| 82 | + |
| 83 | + // This direct preflight is state-only. Gateway refusal coverage remains in |
| 84 | + // doctor-config-preflight.process.test.ts and still requires the readiness checkpoint. |
| 85 | + expect(first).toEqual({ activeLease: false, stateMigrationsImported: false }); |
| 86 | + expect(second).toEqual({ activeLease: false, stateMigrationsImported: false }); |
| 87 | + expect(fs.existsSync(configPath)).toBe(false); |
| 88 | + expect(fs.existsSync(stateDir)).toBe(false); |
| 89 | + }, 150_000); |
| 90 | +}); |
| 91 | + |
| 92 | +describe("CLI pristine startup after early config observation", () => { |
| 93 | + it.each([ |
| 94 | + { name: "explicit Gateway target", explicit: true, existingState: false, stateful: false }, |
| 95 | + { name: "configured Gateway target", explicit: false, existingState: false, stateful: false }, |
| 96 | + { name: "existing shared state", explicit: true, existingState: true, stateful: false }, |
| 97 | + { name: "stateful authored config", explicit: true, existingState: false, stateful: true }, |
| 98 | + ])( |
| 99 | + "preserves the migration decision for $name", |
| 100 | + async ({ explicit, existingState, stateful }) => { |
| 101 | + const root = fs.realpathSync(tempDirs.make("openclaw-cli-pristine-observation-")); |
| 102 | + const runtimeRoot = createSourceRuntime(root); |
| 103 | + const stateDir = path.join(root, "state"); |
| 104 | + const configPath = path.join(root, "openclaw.json"); |
| 105 | + const timelinePath = path.join(root, "timeline.jsonl"); |
| 106 | + const config = { |
| 107 | + gateway: { mode: "local", port: 19876, auth: { mode: "token", token: "test-token" } }, |
| 108 | + agents: { defaults: { workspace: path.join(root, "workspace") } }, |
| 109 | + logging: { file: path.join(root, "openclaw.log") }, |
| 110 | + // Inherited plugin selectors must not add unrelated convergence work to this fixture. |
| 111 | + plugins: { enabled: false }, |
| 112 | + ...(stateful ? { messages: { ackReaction: "ok" } } : {}), |
| 113 | + } satisfies OpenClawConfig; |
| 114 | + const configRaw = JSON.stringify(config); |
| 115 | + fs.writeFileSync(configPath, configRaw); |
| 116 | + const env: NodeJS.ProcessEnv = { |
| 117 | + ...process.env, |
| 118 | + OPENCLAW_STATE_DIR: stateDir, |
| 119 | + OPENCLAW_CONFIG_PATH: configPath, |
| 120 | + OPENCLAW_DIAGNOSTICS: "1", |
| 121 | + OPENCLAW_DIAGNOSTICS_TIMELINE_PATH: timelinePath, |
| 122 | + OPENCLAW_HIDE_BANNER: "1", |
| 123 | + XDG_CONFIG_HOME: path.join(root, "xdg-config"), |
| 124 | + XDG_DATA_HOME: path.join(root, "xdg-data"), |
| 125 | + XDG_STATE_HOME: path.join(root, "xdg-state"), |
| 126 | + XDG_CACHE_HOME: path.join(root, "cache"), |
| 127 | + TMPDIR: root, |
| 128 | + NO_COLOR: "1", |
| 129 | + }; |
| 130 | + delete env.NODE_ENV; |
| 131 | + delete env.VITEST; |
| 132 | + delete env.VITEST_POOL_ID; |
| 133 | + delete env.VITEST_WORKER_ID; |
| 134 | + delete env.OPENCLAW_PROFILE; |
| 135 | + delete env.OPENCLAW_CONTAINER; |
| 136 | + delete env.OPENCLAW_GATEWAY_URL; |
| 137 | + delete env.OPENCLAW_GATEWAY_TOKEN; |
| 138 | + delete env.OPENCLAW_GATEWAY_PASSWORD; |
| 139 | + // Check the authored input without warming the CLI child's startup graph. |
| 140 | + const { planPristineStartupConfigMigrations } = |
| 141 | + await import("./doctor/shared/pristine-startup-state.js"); |
| 142 | + expect(planPristineStartupConfigMigrations(config, env)).toEqual({ |
| 143 | + skipAllStateMigrations: !stateful, |
| 144 | + skipCoreStateMigrations: !stateful, |
| 145 | + }); |
| 146 | + const sourceUrl = (relative: string) => |
| 147 | + pathToFileURL(path.join(runtimeRoot, "src", relative)).href; |
| 148 | + const args = [ |
| 149 | + "attach", |
| 150 | + "movies-a1166b81", |
| 151 | + ...(explicit ? ["--url", "ws://127.0.0.1:19877", "--token", "test-token"] : []), |
| 152 | + ]; |
| 153 | + const rpcSource = ` |
| 154 | + export * from ${JSON.stringify(sourceUrl("gateway/call.ts"))}; |
| 155 | + export async function callGateway(options) { |
| 156 | + if (options.method !== "sessions.resolve") throw new Error("Unexpected RPC: " + options.method); |
| 157 | + globalThis[Symbol.for("openclaw.test.pristineStartupRpcCalls")].push({ |
| 158 | + method: options.method, params: options.params, url: options.url ?? null, |
| 159 | + configMode: options.config?.gateway?.mode, configPort: options.config?.gateway?.port, |
| 160 | + }); |
| 161 | + return { ok: false, candidates: [ |
| 162 | + { key: "agent:main:task:a1166b81-1111-4111-8111-111111111111", displayName: "first" }, |
| 163 | + { key: "agent:main:task:a1166b81-2222-4222-8222-222222222222", displayName: "second" }, |
| 164 | + ] }; |
| 165 | + } |
| 166 | + `; |
| 167 | + // Exercise the real early read, Commander preaction and Doctor decision. Only the |
| 168 | + // resolution RPC is synthetic; ambiguity stops before grants or an external client. |
| 169 | + const script = ` |
| 170 | + import fs from "node:fs"; |
| 171 | + import path from "node:path"; |
| 172 | + import { DatabaseSync } from "node:sqlite"; |
| 173 | + import { registerHooks } from "node:module"; |
| 174 | + const calls = globalThis[Symbol.for("openclaw.test.pristineStartupRpcCalls")] = []; |
| 175 | + registerHooks({ |
| 176 | + resolve(specifier, context, nextResolve) { |
| 177 | + const parent = context.parentURL ?? ""; |
| 178 | + if (specifier.endsWith("/gateway/call.js") && |
| 179 | + (parent.endsWith("/cli/session-target.ts") || parent.endsWith("/cli/session-target.js"))) { |
| 180 | + return { shortCircuit: true, |
| 181 | + url: "data:text/javascript," + encodeURIComponent(${JSON.stringify(rpcSource)}) }; |
| 182 | + } |
| 183 | + return nextResolve(specifier, context); |
| 184 | + }, |
| 185 | + }); |
| 186 | + if (${existingState}) { |
| 187 | + const { openOpenClawStateDatabase, closeOpenClawStateDatabase } = |
| 188 | + await import(${JSON.stringify(sourceUrl("state/openclaw-state-db.ts"))}); |
| 189 | + openOpenClawStateDatabase({ env: process.env }); |
| 190 | + closeOpenClawStateDatabase(); |
| 191 | + } |
| 192 | + const databasePath = path.join(process.env.OPENCLAW_STATE_DIR, "state", "openclaw.sqlite"); |
| 193 | + const databaseExistedBefore = fs.existsSync(databasePath); |
| 194 | + const { runCli } = await import(${JSON.stringify(sourceUrl("cli/run-main.ts"))}); |
| 195 | + process.argv = [process.execPath, "openclaw", ...${JSON.stringify(args)}]; |
| 196 | + let message; |
| 197 | + try { await runCli(process.argv); } |
| 198 | + catch (error) { message = error instanceof Error ? error.message : String(error); } |
| 199 | + const { flushDiagnosticsTimeline } = |
| 200 | + await import(${JSON.stringify(sourceUrl("infra/diagnostics-timeline.ts"))}); |
| 201 | + flushDiagnosticsTimeline(); |
| 202 | + const events = fs.readFileSync(process.env.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH, "utf8") |
| 203 | + .trim().split("\\n").map(line => JSON.parse(line)); |
| 204 | + const stages = events.filter(event => event.type === "span.end" && |
| 205 | + event.name === "cli.command-startup").map(event => event.attributes?.stage); |
| 206 | + const database = new DatabaseSync(databasePath, { readOnly: true }); |
| 207 | + let health; |
| 208 | + try { health = database.prepare("SELECT last_known_good_json FROM config_health_entries WHERE config_path = ?") |
| 209 | + .get(process.env.OPENCLAW_CONFIG_PATH); } |
| 210 | + finally { database.close(); } |
| 211 | + process.stdout.write("__RESULT__" + JSON.stringify({ |
| 212 | + message, calls, stages, databaseExistedBefore, |
| 213 | + observedConfigMode: health ? JSON.parse(health.last_known_good_json).gatewayMode : null, |
| 214 | + }) + "\\n"); |
| 215 | + `; |
| 216 | + const result = await runIsolatedModuleScript(env, script, { runtimeRoot, timeoutMs: 60_000 }); |
| 217 | + const output = `${result.stderr}\n${result.stdout}`; |
| 218 | + const resultLines = result.stdout.split("\n").filter((line) => line.startsWith("__RESULT__")); |
| 219 | + expect(resultLines, output).toHaveLength(1); |
| 220 | + const observed = JSON.parse(resultLines[0]!.slice("__RESULT__".length)); |
| 221 | + expect(observed.message).toContain("Session reference is ambiguous:"); |
| 222 | + expect(observed.message).toContain("first"); |
| 223 | + expect(observed.message).toContain("second"); |
| 224 | + expect(observed.calls).toEqual([ |
| 225 | + { |
| 226 | + method: "sessions.resolve", |
| 227 | + params: { shortId: "a1166b81", slugHint: "movies" }, |
| 228 | + url: explicit ? "ws://127.0.0.1:19877" : null, |
| 229 | + configMode: "local", |
| 230 | + configPort: 19876, |
| 231 | + }, |
| 232 | + ]); |
| 233 | + expect(observed.databaseExistedBefore).toBe(existingState); |
| 234 | + expect(observed.observedConfigMode).toBe("local"); |
| 235 | + expect(observed.stages).toContain("config-ready"); |
| 236 | + expect(observed.stages).toContain("doctor.config-preflight.config-snapshot"); |
| 237 | + expect(observed.stages.includes("doctor.config-preflight.state-migrations-import")).toBe( |
| 238 | + existingState || stateful, |
| 239 | + ); |
| 240 | + expect(fs.readFileSync(configPath, "utf8")).toBe(configRaw); |
| 241 | + expect(hasActiveStartupMigrationLease({ env })).toBe(false); |
| 242 | + }, |
| 243 | + 75_000, |
| 244 | + ); |
| 245 | +}); |
0 commit comments