File size: 10,385 Bytes
eb3f11e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import fs from "node:fs/promises";
import path from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
import { readConfigFileSnapshot } from "../../config/config.js";
import {
  createNpmTarget,
  writePackageRoot,
} from "../../infra/package-update-steps.test-support.js";
import * as repairAgent from "../../infra/update-repair-agent.js";
import { createUpdateRun, getUpdateRun } from "../../infra/update-run-ledger.js";
import * as processRunner from "../../process/exec.js";
import { defaultRuntime } from "../../runtime.js";
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
import { executeMutableUpdate } from "./update-command-execution.js";
import { finishUpdate } from "./update-command-post-update.js";
import { withUpdateFailureTriage } from "./update-command-triage.js";

const mocks = vi.hoisted(() => ({
  captureManagedPreflight:
    vi.fn<
      typeof import("./update-command-managed-context.js").captureOwnedManagedUpdatePreflightContext
    >(),
  captureSchemaContext:
    vi.fn<typeof import("./schema-preflight.js").captureTargetDatabaseSchemaContext>(),
  inspectService:
    vi.fn<
      typeof import("./update-command-service.js").maybeStopManagedServiceBeforeMutableUpdate
    >(),
  validateCanary:
    vi.fn<typeof import("../../infra/update-candidate-canary.js").validateUpdateCandidateCanary>(),
}));

vi.mock("../../infra/update-candidate-canary.js", () => ({
  validateUpdateCandidateCanary: mocks.validateCanary,
}));
vi.mock("./schema-preflight.js", async (original) => ({
  ...(await original<typeof import("./schema-preflight.js")>()),
  captureTargetDatabaseSchemaContext: mocks.captureSchemaContext,
  checkTargetDatabaseSchemasForContexts: async () => ({ incompatible: [], indeterminate: [] }),
}));
vi.mock("./update-command-managed-context.js", async (original) => ({
  ...(await original<typeof import("./update-command-managed-context.js")>()),
  captureOwnedManagedUpdateContext: async () => undefined,
  captureOwnedManagedUpdatePreflightContext: mocks.captureManagedPreflight,
  revalidateUpdateDatabaseContext: async (context: unknown) => context,
}));
vi.mock("./update-command-service.js", async (original) => ({
  ...(await original<typeof import("./update-command-service.js")>()),
  maybeStopManagedServiceBeforeMutableUpdate: mocks.inspectService,
  maybeRestartServiceAfterFailedMutableUpdate: async () => undefined,
}));
vi.mock("../../infra/update-triage.js", () => ({
  prepareUpdateFailureTriage: async () => async () => ({ status: "completed", hint: "" }),
}));

const dirs = useAutoCleanupTempDirTracker(afterEach);
afterEach(() => {
  closeOpenClawStateDatabaseForTest();
  vi.restoreAllMocks();
  vi.unstubAllEnvs();
});

it("keeps successful candidate repair separate from a failed update and its process exit", async () => {
  const base = dirs.make("candidate-repair-exit-");
  const stateDir = path.join(base, "state");
  const configPath = path.join(stateDir, "openclaw.json");
  await fs.mkdir(stateDir);
  await fs.writeFile(configPath, "{}");
  vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
  vi.stubEnv("OPENCLAW_CONFIG_PATH", configPath);
  vi.stubEnv("OPENCLAW_UPDATE_RUN_HANDOFF", "");
  const env = { ...process.env };
  const globalRoot = path.join(base, "prefix", "lib", "node_modules");
  const target = createNpmTarget(globalRoot);
  const root = path.join(globalRoot, "openclaw");
  await writePackageRoot(root, "2026.9.3");
  const launcher = path.join(base, "prefix", "bin", "openclaw");
  await fs.mkdir(path.dirname(launcher), { recursive: true });
  await fs.writeFile(launcher, "original launcher");
  const run = { runId: createUpdateRun({ trigger: "cli" }, { env }).runId, env };
  const events: string[] = [];
  vi.spyOn(processRunner, "runCommandWithTimeout").mockImplementation(async (argv) => {
    let stdout = "";
    if (argv.join(" ") === "npm --version") {
      stdout = "12.0.0\n";
    } else if (argv.join(" ") === "npm root -g") {
      stdout = `${globalRoot}\n`;
    } else if (argv.includes("--prefix") && (argv.includes("install") || argv.includes("i"))) {
      const prefix = argv[argv.indexOf("--prefix") + 1];
      if (!prefix) {
        throw new Error("Missing stage prefix");
      }
      await writePackageRoot(path.join(prefix, "lib", "node_modules", "openclaw"), "2026.9.4");
      await fs.mkdir(path.join(prefix, "bin"), { recursive: true });
      await fs.writeFile(path.join(prefix, "bin", "openclaw"), "candidate launcher");
    } else {
      throw new Error(`Unexpected package command: ${argv.join(" ")}`);
    }
    return { stdout, stderr: "", code: 0, signal: null, killed: false, termination: "exit" };
  });
  const failure = (candidateRoot: string) => ({
    status: "error" as const,
    reason: "runtime-verification-failed" as const,
    phase: "snapshot" as const,
    steps: [
      {
        name: "candidate snapshot",
        command: "candidate validation",
        cwd: candidateRoot,
        durationMs: 1,
        exitCode: 1,
        stderrTail: "ENOSPC: no space left on device",
      },
    ],
    durationMs: 1,
    logTail: ["ENOSPC: no space left on device"],
  });
  mocks.validateCanary.mockImplementation(
    async ({ root: candidateRoot, rehearsal }: { root: string; rehearsal?: unknown }) => {
      events.push(rehearsal ? "rehearsal passes" : "fresh snapshot fails");
      return rehearsal
        ? { status: "ok", phase: "readiness", steps: [], durationMs: 1, logTail: [] }
        : failure(candidateRoot);
    },
  );
  vi.spyOn(repairAgent, "prepareUnattendedUpdateRepair").mockImplementation(async (repair) => {
    const validation = await repair.validate(new AbortController().signal);
    expect(validation.ok).toBe(true);
    repair.onEvent?.({ type: "stopped", status: "repaired" });
    return { status: "repaired", attempts: [], finalValidation: validation };
  });
  const configSnapshot = await readConfigFileSnapshot({
    pluginValidation: "core-only",
    observe: false,
  });
  const context = { env, readEnv: env, config: configSnapshot.config, configSnapshot };
  mocks.captureSchemaContext.mockResolvedValue(context);
  mocks.captureManagedPreflight.mockResolvedValue(context);
  mocks.inspectService.mockResolvedValue({
    stopped: false,
    inspected: true,
    runtimeInspected: true,
    running: true,
    serviceEnv: env,
  });
  const execution = await executeMutableUpdate({
    root,
    installKind: "package",
    updateInstallKind: "package",
    switchToGit: false,
    timeoutMs: 30_000,
    updateStepTimeoutMs: 30_000,
    startedAt: Date.now(),
    progress: {},
    stop: () => {},
    channel: "stable",
    tag: "2026.9.4",
    shouldRestart: false,
    managedServiceRootRedirect: null,
    recoveryState: { triageTarget: { env } },
    prepareMutableUpdate: async () => {},
    packageTargetSchemaVersions: { state: 15, agent: 19 },
    packageInstallSpec: "openclaw@2026.9.4",
    packageTargetVersion: "2026.9.4",
    packageInstallTarget: target,
    opts: { json: true, yes: true, run },
  });
  expect(execution).not.toBeNull();
  if (!execution) {
    throw new Error("Missing execution result");
  }
  expect(events, JSON.stringify(execution.result)).toEqual([
    "fresh snapshot fails",
    "rehearsal passes",
    "fresh snapshot fails",
  ]);
  expect(execution.result).toMatchObject({
    status: "error",
    reason: "runtime-verification-failed",
    before: { version: "2026.9.3" },
    after: { version: null },
  });
  expect(await fs.readFile(launcher, "utf8")).toBe("original launcher");
  expect(JSON.parse(await fs.readFile(path.join(root, "package.json"), "utf8")).version).toBe(
    "2026.9.3",
  );
  const output = vi.spyOn(defaultRuntime, "writeJson").mockImplementation(() => undefined);
  await expect(
    withUpdateFailureTriage({ json: true, yes: true, run }, { root, env }, async () => {
      await finishUpdate({
        ...execution,
        root,
        installKindChanged: false,
        configSnapshot,
        requestedChannel: null,
        storedChannel: "stable",
        channel: "stable",
        downgradeRisk: false,
        shouldRestart: false,
        preUpdatePluginInstallRecords: {},
        updateStepTimeoutMs: 1000,
        opts: { json: true, yes: true, run },
        startedAt: Date.now(),
        controlPlaneUpdateSentinelMeta: null,
        ownedManagedUpdateEnv: env,
      });
    }),
  ).rejects.toMatchObject({ name: "ExitError", code: 1 });
  expect(output).toHaveBeenCalledWith(
    expect.objectContaining({ status: "error", reason: "runtime-verification-failed" }),
  );
  expect(getUpdateRun(run.runId, { env })).toMatchObject({
    status: "failed",
    reason: "runtime-verification-failed",
    repair: [expect.objectContaining({ status: "succeeded" })],
  });
  const childSource = path.join(base, "exit-proof.mjs");
  await fs.writeFile(
    childSource,
    `
      import fs from "node:fs/promises";
      import { runCliWithExitFinalization } from ${JSON.stringify(new URL("../one-shot-exit.ts", import.meta.url).href)};
      import { withUpdateFailureTriage } from ${JSON.stringify(new URL("./update-command-triage.ts", import.meta.url).href)};
      import { UpdateCommandFailure } from ${JSON.stringify(new URL("./update-command-result.ts", import.meta.url).href)};
      const result = JSON.parse(await fs.readFile(process.argv[2], "utf8"));
      await runCliWithExitFinalization({
        run: () => withUpdateFailureTriage({ yes: true, json: true, dryRun: true }, { env: process.env }, async () => {
          process.stdout.write("observed-failed-update:" + result.reason + "\\n");
          throw new UpdateCommandFailure(result);
        }),
        onError: (error) => { process.stderr.write(String(error)); process.exitCode = 19; },
      });
    `,
  );
  const childResultPath = path.join(base, "failed-result.json");
  await fs.writeFile(childResultPath, JSON.stringify(execution.result));
  const child = await processRunner.runCommandBuffered(
    [process.execPath, "--import", path.resolve("scripts/tsx.mjs"), childSource, childResultPath],
    { baseEnv: env, timeoutMs: 30_000 },
  );
  expect(child.stdout.toString()).toContain("observed-failed-update:runtime-verification-failed");
  expect(child.code, child.stderr.toString()).toBe(1);
});