File size: 19,267 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// Shared update command primitives for channel resolution, install roots, and subprocess steps.
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { parseStrictPositiveInteger } from "@openclaw/normalization-core/number-coercion";
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
import { theme } from "../../../packages/terminal-core/src/theme.js";
import { hasErrnoCode } from "../../infra/errors.js";
import { resolveRequiredHomeDir } from "../../infra/home-dir.js";
import { resolveOpenClawPackageRoot } from "../../infra/openclaw-root.js";
import { readPackageName, readPackageVersion } from "../../infra/package-json.js";
import { normalizePackageTagInput } from "../../infra/package-tag.js";
import { parseSemver } from "../../infra/runtime-guard.js";
import { fetchNpmTagVersion } from "../../infra/update-check.js";
import {
  normalizeUpdateFailureFacts,
  type UpdateFailureFact,
} from "../../infra/update-failure-facts.js";
import {
  createFreeBsdPkgOwnershipInspection,
  type FreeBsdPkgOwnershipInspection,
} from "../../infra/update-freebsd-pkg-ownership.js";
import {
  canResolveRegistryVersionForPackageTarget,
  createGlobalInstallEnv,
  detectGlobalInstallManagerByPresence,
  detectGlobalInstallManagerForRoot,
  type GlobalInstallManager,
} from "../../infra/update-global.js";
import type { UpdateRequesterAuthority } from "../../infra/update-requester-authority.js";
import type { UpdateRecoveryFence } from "../../infra/update-run-recovery.js";
import { runStep } from "../../infra/update-runner-command.js";
import { resolveUnmanagedUpdateInstallReason } from "../../infra/update-runner-install-surface.js";
import type { UpdateStepProgress, UpdateStepResult } from "../../infra/update-runner.js";
import { runCommandWithTimeout } from "../../process/exec.js";
import { defaultRuntime } from "../../runtime.js";
import { UPDATE_INSTALL_SKIP_GUIDANCE } from "../../shared/update-outcome.js";
import { pathExists } from "../../utils.js";
import { COMPLETION_SKIP_PLUGIN_COMMANDS_ENV } from "../completion-runtime.js";
import { isJsonOutputModeActive } from "../json-output-mode.js";

export type UpdateCommandOptions = {
  /** In-process executor only; workers must reacquire authority, never deserialize this. */
  /** Legacy live context is unsupported; its presence is refusal-only. */
  recovery?: unknown;
  reapplyLocalOverrides?: boolean;
  /** Internal orchestration context, shared across update phases and child processes. */
  run?: {
    runId: string;
    defaultStepTimeoutMs?: number;
    activationTimeoutMs?: number;
    env: NodeJS.ProcessEnv;
    /** Prepared before replacement; never load the old authority graph after activation. */
    requesterAuthority?: UpdateRequesterAuthority;
    /** Live local executor only. A child must independently acquire its owner. */
    executorFence?: UpdateRecoveryFence;
  };
  acceptCapabilities?: boolean;
  json?: boolean;
  restart?: boolean;
  dryRun?: boolean;
  channel?: string;
  tag?: string;
  timeout?: string;
  yes?: boolean;
};

export type UpdateStatusOptions = {
  json?: boolean;
  timeout?: string;
};

export type UpdateFinalizeOptions = {
  acceptCapabilities?: boolean;
  json?: boolean;
  channel?: string;
  timeout?: string;
  yes?: boolean;
  restart?: boolean;
  /** Internal external-supervisor handshake; public repair always leaves this false. */
  deferCompletionCache?: boolean;
};

export type UpdateWizardOptions = {
  acceptCapabilities?: boolean;
  timeout?: string;
};

export class UpdatePreMutationError extends Error {
  readonly failureFacts: UpdateFailureFact[];

  constructor(
    readonly reason: string,
    message: string,
    options?: ErrorOptions & { failureFacts?: readonly UpdateFailureFact[] },
  ) {
    super(message, options);
    this.name = "UpdatePreMutationError";
    this.failureFacts = normalizeUpdateFailureFacts(
      options?.failureFacts ?? [{ check: reason, code: reason, message }],
    );
  }
}

const INVALID_TIMEOUT_ERROR = "--timeout must be a positive integer (seconds)";
const MAX_SAFE_TIMEOUT_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1000);

/** Parse the shared timeout contract without exiting an owning operation. */
export function parseUpdateTimeoutMs(timeout?: string): number | undefined {
  if (timeout === undefined) {
    return undefined;
  }
  const trimmed = timeout.trim();
  const seconds = parseStrictPositiveInteger(trimmed);
  if (seconds === undefined || seconds > MAX_SAFE_TIMEOUT_SECONDS) {
    throw new Error(INVALID_TIMEOUT_ERROR);
  }
  return seconds * 1000;
}

/** Parse a CLI timeout in seconds, exiting through the runtime on invalid input. */
export function parseTimeoutMsOrExit(timeout?: string): number | undefined | null {
  try {
    return parseUpdateTimeoutMs(timeout);
  } catch (error) {
    if (isJsonOutputModeActive(process.argv)) {
      throw error;
    }
    defaultRuntime.error(INVALID_TIMEOUT_ERROR);
    defaultRuntime.exit(1);
    return null;
  }
}

const UPSTREAM_REPOSITORY_URL = "https://github.com/openclaw/openclaw.git";
// Keep the full commit graph for dev ref switching while deferring historical blobs.
// A shallow clone would make older or non-default dev targets unreachable.
const GIT_CLONE_BLOB_FILTER = "--filter=blob:none";

export const DEFAULT_PACKAGE_NAME = "openclaw";
const CORE_PACKAGE_NAMES = new Set([DEFAULT_PACKAGE_NAME]);

/** Normalize a CLI tag/version/spec into the npm target form accepted by update flows. */
export function normalizeTag(value?: string | null): string | null {
  return normalizePackageTagInput(value, ["openclaw", DEFAULT_PACKAGE_NAME]);
}

function normalizeVersionTag(tag: string): string | null {
  const trimmed = tag.trim();
  if (!trimmed) {
    return null;
  }
  const cleaned = trimmed.startsWith("v") ? trimmed.slice(1) : trimmed;
  return parseSemver(cleaned) ? cleaned : null;
}

export { readPackageName, readPackageVersion };

/** Resolve an npm dist-tag or explicit version into a concrete package version. */
export async function resolveTargetVersion(
  tag: string,
  timeoutMs?: number,
  options: { spec?: string; command?: string; cwd?: string; env?: NodeJS.ProcessEnv } = {},
): Promise<string | null> {
  if (!canResolveRegistryVersionForPackageTarget(tag)) {
    return null;
  }
  const direct = normalizeVersionTag(tag);
  if (direct) {
    return direct;
  }
  const res = await fetchNpmTagVersion({
    tag,
    timeoutMs,
    spec: options.spec,
    command: options.command,
    cwd: options.cwd,
    env: options.env,
  });
  return res.version ?? null;
}

/** Return true when `root` is a local git checkout directory. */
export async function isGitCheckout(root: string): Promise<boolean> {
  try {
    await fs.stat(path.join(root, ".git"));
    return true;
  } catch {
    return false;
  }
}

async function isCorePackage(root: string): Promise<boolean> {
  const name = await readPackageName(root);
  return Boolean(name && CORE_PACKAGE_NAMES.has(name));
}

/** Return true only for existing directories with no entries. */
export async function isEmptyDir(targetPath: string): Promise<boolean> {
  try {
    const entries = await fs.readdir(targetPath);
    return entries.length === 0;
  } catch {
    return false;
  }
}

/** Resolve the checkout path used by source-based self-update. */
export function resolveGitInstallDir(): string {
  const override = process.env.OPENCLAW_GIT_DIR?.trim();
  if (override) {
    return path.resolve(override);
  }
  return resolveDefaultGitDir();
}

function resolveDefaultGitDir(): string {
  const home = resolveRequiredHomeDir(process.env, os.homedir);
  if (home.startsWith("/")) {
    return path.posix.join(home, "openclaw");
  }
  return path.join(home, "openclaw");
}

/** Prefer the current Node executable, falling back to `node` when run through another shim. */
export function resolveNodeRunner(): string {
  const base = normalizeLowercaseStringOrEmpty(path.basename(process.execPath));
  if (base === "node" || base === "node.exe") {
    return process.execPath;
  }
  return "node";
}

export function tryResolveInvocationCwd(): string | undefined {
  try {
    return process.cwd();
  } catch {
    return undefined;
  }
}

/** Locate the installed OpenClaw package root that should receive update operations. */
export async function resolveUpdateRoot(): Promise<string> {
  // Preserve the lexical package path from the invoking shim. pnpm 11 package
  // modules realpath into a shared store, which is not the install owner.
  const invocationRoot = process.argv[1]
    ? await resolveOpenClawPackageRoot({ cwd: path.dirname(path.resolve(process.argv[1])) })
    : null;
  return (
    invocationRoot ??
    (await resolveOpenClawPackageRoot({ moduleUrl: import.meta.url, cwd: process.cwd() })) ??
    process.cwd()
  );
}

/** Run one update subprocess and report bounded stdout/stderr tails to progress listeners. */
export async function runUpdateStep(params: {
  name: string;
  argv: string[];
  cwd?: string;
  timeoutMs: number;
  progress?: UpdateStepProgress;
  env?: NodeJS.ProcessEnv;
  runCommand?: Parameters<typeof runStep>[0]["runCommand"];
}): Promise<UpdateStepResult> {
  return await runStep({
    ...params,
    cwd: params.cwd ?? process.cwd(),
    runCommand: params.runCommand ?? runCommandWithTimeout,
    stepIndex: 0,
    totalSteps: 0,
  });
}

type GitCheckoutResult = {
  checkoutDir: string;
  step: UpdateStepResult | null;
};

type StagedGitCheckout = (
  root: string,
  publish: () => Promise<string>,
  targetRoot: string,
) => Promise<void>;

async function cloneGitCheckoutTransactionally(params: {
  dir: string;
  timeoutMs: number;
  progress?: UpdateStepProgress;
  env?: NodeJS.ProcessEnv;
  useStagedCheckout?: StagedGitCheckout;
}): Promise<GitCheckoutResult> {
  const parentDir = path.dirname(params.dir);
  await fs.mkdir(parentDir, { recursive: true });
  const canonicalParentDir = await fs.realpath(parentDir);
  const preserveDir = (await pathExists(params.dir)) && (await isEmptyDir(params.dir));
  const targetDir = preserveDir
    ? await fs.realpath(params.dir)
    : path.join(canonicalParentDir, path.basename(params.dir));
  const stagingParent = preserveDir ? targetDir : canonicalParentDir;
  const stagingDir = await fs.mkdtemp(path.join(stagingParent, ".openclaw-clone-"));
  let cleanupStaging = true;

  try {
    const result = await runUpdateStep({
      name: "git clone",
      argv: ["git", "clone", GIT_CLONE_BLOB_FILTER, UPSTREAM_REPOSITORY_URL, stagingDir],
      env: params.env,
      timeoutMs: params.timeoutMs,
      progress: params.progress,
    });
    if (result.exitCode !== 0) {
      return { checkoutDir: targetDir, step: result };
    }

    const publish = async (): Promise<string> => {
      if (!preserveDir) {
        try {
          await fs.lstat(targetDir);
        } catch (error) {
          if (!hasErrnoCode(error, "ENOENT")) {
            throw error;
          }
          await fs.rename(stagingDir, targetDir);
          return targetDir;
        }
      }

      if (!preserveDir) {
        throw new Error(
          `OPENCLAW_GIT_DIR appeared while cloning: ${params.dir}. The existing path was left unchanged; move it or choose another OPENCLAW_GIT_DIR, then retry.`,
        );
      }

      const expectedEntries = preserveDir ? [path.basename(stagingDir)] : [];
      const destinationEntries = await fs.readdir(targetDir);
      if (destinationEntries.toSorted().join("\0") !== expectedEntries.toSorted().join("\0")) {
        throw new Error(
          `OPENCLAW_GIT_DIR appeared while cloning: ${params.dir}. The existing path was left unchanged; move it or choose another OPENCLAW_GIT_DIR, then retry.`,
        );
      }

      const entries = (await fs.readdir(stagingDir)).toSorted((a, b) =>
        a === ".git" ? 1 : b === ".git" ? -1 : 0,
      );
      const moved: string[] = [];
      let publishError: { value: unknown } | undefined;
      try {
        for (const entry of entries) {
          await fs.rename(path.join(stagingDir, entry), path.join(targetDir, entry));
          moved.push(entry);
        }
      } catch (error) {
        publishError = { value: error };
      }
      if (publishError) {
        const rollbackErrors: unknown[] = [];
        for (const entry of moved.toReversed()) {
          try {
            await fs.rename(path.join(targetDir, entry), path.join(stagingDir, entry));
          } catch (rollbackError) {
            rollbackErrors.push(rollbackError);
          }
        }
        if (rollbackErrors.length > 0) {
          cleanupStaging = false;
          throw new AggregateError(
            [publishError.value, ...rollbackErrors],
            `Could not publish or fully roll back the cloned checkout at ${targetDir}; recovery files remain at ${stagingDir}`,
          );
        }
        throw publishError.value;
      }
      return targetDir;
    };
    if (params.useStagedCheckout) {
      await params.useStagedCheckout(stagingDir, publish, targetDir);
    } else {
      await publish();
    }
    return { checkoutDir: targetDir, step: result };
  } finally {
    if (cleanupStaging) {
      await fs.rm(stagingDir, { recursive: true, force: true });
    }
  }
}

/** Ensure the configured source-update directory exists and points at an OpenClaw checkout. */
export async function ensureGitCheckout(params: {
  dir: string;
  timeoutMs: number;
  progress?: UpdateStepProgress;
  env?: NodeJS.ProcessEnv;
  useStagedCheckout?: StagedGitCheckout;
}): Promise<GitCheckoutResult> {
  const gitEnv = params.env ?? (await createGlobalInstallEnv());
  const dirExists = await pathExists(params.dir);
  if (!dirExists) {
    return await cloneGitCheckoutTransactionally({
      dir: params.dir,
      env: gitEnv,
      timeoutMs: params.timeoutMs,
      progress: params.progress,
      useStagedCheckout: params.useStagedCheckout,
    });
  }

  if (!(await isGitCheckout(params.dir))) {
    const empty = await isEmptyDir(params.dir);
    if (!empty) {
      throw new UpdatePreMutationError(
        "invalid-git-directory",
        `OPENCLAW_GIT_DIR points at a non-git directory: ${params.dir}. Set OPENCLAW_GIT_DIR to an empty folder or an openclaw checkout.`,
      );
    }

    return await cloneGitCheckoutTransactionally({
      dir: params.dir,
      env: gitEnv,
      timeoutMs: params.timeoutMs,
      progress: params.progress,
      useStagedCheckout: params.useStagedCheckout,
    });
  }

  if (!(await isCorePackage(params.dir))) {
    throw new UpdatePreMutationError(
      "invalid-git-directory",
      `OPENCLAW_GIT_DIR does not look like a core checkout: ${params.dir}.`,
    );
  }

  return { checkoutDir: await fs.realpath(params.dir), step: null };
}

/** Detect the package manager that owns a global/package OpenClaw install. */
export async function resolveGlobalManager(params: {
  root: string;
  installKind: "git" | "package" | "unknown";
  timeoutMs: number;
  pkgOwnership?: FreeBsdPkgOwnershipInspection;
}): Promise<GlobalInstallManager> {
  await (
    params.pkgOwnership ?? createFreeBsdPkgOwnershipInspection(params.timeoutMs)
  ).assertUnowned(params.root);
  if (params.installKind === "package") {
    const diagnostics: string[] = [];
    const detected = await detectGlobalInstallManagerForRoot(
      runCommandWithTimeout,
      params.root,
      params.timeoutMs,
      diagnostics,
    );
    if (!detected) {
      const reason = resolveUnmanagedUpdateInstallReason();
      throw new UpdatePreMutationError(
        reason,
        `${UPDATE_INSTALL_SKIP_GUIDANCE[reason]} Inspected: ${diagnostics.join("; ")}.`,
      );
    }
    return detected;
  }

  const byPresence = await detectGlobalInstallManagerByPresence(
    runCommandWithTimeout,
    params.timeoutMs,
  );
  return byPresence ?? "npm";
}

const COMPLETION_CACHE_WRITE_TIMEOUT_MS = 30_000;
const COMPLETION_CACHE_MANUAL_REFRESH_HINT =
  "Shell tab-completion may be stale; refresh manually with: openclaw completion --write-state";

/** Best-effort refresh of shell completion state after a successful update. */
export async function tryWriteCompletionCache(
  root: string,
  jsonMode: boolean,
  timeoutMs = COMPLETION_CACHE_WRITE_TIMEOUT_MS,
): Promise<"completed" | "failed" | "skipped"> {
  const binPath = path.join(root, "openclaw.mjs");
  if (!(await pathExists(binPath))) {
    return "skipped";
  }

  let failure: string;
  try {
    const result = await runCommandWithTimeout(
      [resolveNodeRunner(), binPath, "completion", "--write-state"],
      {
        cwd: root,
        env: { ...process.env, [COMPLETION_SKIP_PLUGIN_COMMANDS_ENV]: "1" },
        input: "",
        timeoutMs,
        killProcessTree: true,
      },
    );
    if (result.code === 0) {
      return "completed";
    }
    failure =
      result.termination === "timeout"
        ? `timed out after ${timeoutMs / 1000}s`
        : result.stderr.trim();
  } catch (error) {
    failure = String(error);
  }
  if (!jsonMode) {
    defaultRuntime.log(
      theme.warn(
        `Completion cache update failed${failure ? `: ${failure}` : ""}. ${COMPLETION_CACHE_MANUAL_REFRESH_HINT}`,
      ),
    );
  }
  return "failed";
}

export async function requestUpdateDowngradeConfirmation(params: {
  json: boolean;
  currentVersion: string | null;
  targetVersion: string | null;
  tag: string;
}): Promise<"confirmed" | "cancelled" | "confirmation-required"> {
  if (!process.stdin.isTTY || params.json) {
    return "confirmation-required";
  }
  const { confirm, isCancel } = await import("@clack/prompts");
  const { stylePromptMessage } =
    await import("../../../packages/terminal-core/src/prompt-style.js");
  const targetLabel = params.targetVersion ?? `${params.tag} (unknown)`;
  const message = `Downgrading from ${params.currentVersion} to ${targetLabel} can break configuration. Continue?`;
  const ok = await confirm({ message: stylePromptMessage(message), initialValue: false });
  return isCancel(ok) || !ok ? "cancelled" : "confirmed";
}

export async function confirmUpdateDowngrade(params: {
  opts: UpdateCommandOptions;
  currentVersion: string | null;
  targetVersion: string | null;
  tag: string;
}): Promise<boolean> {
  const { finishUpdateRun } = await import("../../infra/update-run-ledger.js");
  const { opts, currentVersion, targetVersion, tag } = params;
  const decision = await requestUpdateDowngradeConfirmation({
    json: Boolean(opts.json),
    currentVersion,
    targetVersion,
    tag,
  });
  const run = opts.run!;
  if (decision === "confirmation-required") {
    finishUpdateRun(
      run.runId,
      { status: "skipped", reason: "downgrade-confirmation-required" },
      { env: run.env },
    );
    defaultRuntime.error(
      "Downgrade confirmation required.\nDowngrading can break configuration. Re-run in a TTY to confirm.",
    );
    defaultRuntime.exit(1);
    return false;
  }
  if (decision === "cancelled") {
    finishUpdateRun(run.runId, { status: "skipped", reason: "cancelled" }, { env: run.env });
    if (!opts.json) {
      defaultRuntime.log(theme.muted("Update cancelled."));
    }
    defaultRuntime.exit(0);
    return false;
  }
  return true;
}