Files
openclaw/docker-entrypoint.mjs
Peter Steinberger 2a1402cd3e fix(startup): keep legacy state repair in Doctor (#151025)
* fix(startup): keep legacy state repair in doctor

Separate current-state startup readiness from explicit Doctor migrations.
Preserve current config recovery, quarantine, device identity checks,
lease fencing and updater completion ownership.

Remove automatic startup migration/checkpoint and node-host import paths.
Keep shipped read-only context and roster projections unchanged.

* test(doctor): align proof callers with repair ownership

Keep survivor fixture setup in caller order and select the shared Doctor
flow separately from the channel-specific proof. Include the complete
isolated diagnostics dependency closure.

Prove ordinary startup preserves legacy directories before explicit
Doctor repair, and await SQLite worker closure before test cleanup.

* test(startup): verify index repair through gateway maintenance

* test(doctor): align cutover fixtures with state owners

Reacquire the database after Doctor retires its generation, retain real session history for startup refusal, and keep pending reads at their actual owners. Distinguish the reused readonly reader from independent snapshot-token children and verify every child settles.

* fix(doctor): preserve image activation and published migration receipts

Run the shared noninteractive Doctor owner before default and Compose Gateway
activation so retained Docker volumes keep their published upgrade path while
ordinary Gateway startup stays readiness-only. Preserve root selectors and
settle interrupted repair before executing the original command.

Retain the path-wide tombstones emitted by the published restart-sentinel
importer, including consumed notices, and validate completed source decisions
before retiring recreated inputs. Add the root-image activation lane and causal
receipt coverage without introducing a schema, option, or second importer.

* test(docker): preserve release state pairs in upgrade proof

Use the existing synthetic v2026.9.2 corpus instead of combining a July shared database with a later agent schema. Preserve its deletion journal, registry, both transcript payloads, paired backups, and unsafe-state controls. Register the two shell-launched helpers with Knip.

* test(docker): normalize persisted schema snapshot rows

Compare node:sqlite schema rows using the same plain-object representation as the saved JSON preimage. Keep strict schema, row, and value-type assertions intact.

* fix(models): retain discovered models after refresh failures

Record successful legacy catalog results at the producer boundary so unavailable refreshes retain the accepted inventory. Preserve explicit outcomes, advisory SDK fallback behavior, and first-discovery starter policy.

* fix(models): preserve skipped catalog outcome semantics

Mark bundled static, configured, and advisory catalog projections with
explicit empty outcomes so legacy success inference cannot promote them
to observed account inventory. Preserve live outcomes and helper types.

Keep exact auth provenance histories and move existing fixture/policy
code into focused owners where required by the line-cap ratchet.

Validation: 447 producer and sibling cases, 56 shared self-hosted cases,
95 auth/policy cases, causal missing-outcome failures, maintained checks,
and independent review.

* test(plugin-sdk): keep discovery loader types acyclic

Move the shared loader type into a leaf consumed by both discovery
contract helpers. Preserve its public provider-test-contracts export
without a child-to-parent type import cycle.

Validation: maintained Madge check reports zero cycles; core, all core
test graphs, extension test types, lint, formatting and independent
review pass. Runtime behavior and previous catalog proof are unchanged.

* fix(plugin-sdk): mark generated static catalogs explicitly

Keep the generated non-live, non-strict catalog adapter from claiming
successful acquisition for manifest or configured rows. Preserve null,
errors, strict and custom callbacks, static catalogs, and public types.

Validation: three existing controls fail before the correction; all49
owner and sibling cases pass afterward, with types, lint, line caps and
fresh independent review clean.

* test(gateway): cover restart import during state retirement

Exercise canonical database close while a legacy notice read is paused. Verify admission rejection, retained canonical and source bytes, no migration receipt, and joined maintenance custody without changing the accepted sidecar-stop drain contract.

* fix(test): drain sharing fixtures before removing state

* test: bind retirement regression to its own worker

* docs(docker): clarify automatic Doctor activation

* test(doctor): keep readiness fixture runtime private

* test: stabilize shared skill watcher fixture roots

(cherry picked from commit 15606be10e)

* perf(tooling): share indexed scope parsing for artifact scans

(cherry picked from commit 6e6eef9f5b)

* fix(team-reports): use source owners in scheduler tests

The source barrel retired in #157819, but the scheduler tests still imported
it, breaking the extension test typecheck on main. Import the Discord and
GitHub owners directly, matching the production caller.

Validated the original TS2307/TS7006 failure, the corrected extension type
graph, all 36 scheduler tests, changed checks, and independent P2 review.

(cherry picked from commit 7c4866c73b)

* test(install): isolate global npm configuration in version fixtures

Use a controlled absent global config inside the fixture home so the
release helper does not query the deliberately narrow npm stub. Keep
predecessor selection, fresh-install behavior, and expected exits intact.

(cherry picked from commit 0a9eefc76c)

* test(docker): verify the complete image activation entrypoint
2026-09-25 13:43:40 -07:00

123 lines
3.8 KiB
JavaScript

// Image activation owns unattended retained-volume repair; ordinary CLI startup only admits state.
import { spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { getCommandOptionsWithRootOptions } from "./cli-root-options.mjs";
import {
GATEWAY_RUN_BOOLEAN_FLAGS,
GATEWAY_RUN_VALUE_FLAGS,
isForegroundGatewayRunArgv,
} from "./gateway-run-argv.mjs";
const root = path.dirname(fileURLToPath(import.meta.url));
const command = process.argv.slice(2);
function executable(name) {
const candidates = name.includes(path.sep)
? [path.resolve(name)]
: (process.env.PATH ?? "").split(path.delimiter).map((dir) => path.resolve(dir, name));
for (const candidate of candidates) {
try {
fs.accessSync(candidate, fs.constants.X_OK);
if (fs.statSync(candidate).isFile()) {
return fs.realpathSync(candidate);
}
} catch {
// Match normal PATH lookup; exec reports an unavailable command below.
}
}
return undefined;
}
function gatewayInvocation(program) {
if (!command.length) {
throw new Error("Docker entrypoint requires a command");
}
let argv;
if (program === fs.realpathSync(process.execPath) && command[1]) {
let entry;
try {
entry = fs.realpathSync(command[1]);
} catch {
return undefined;
}
if (
!["openclaw.mjs", "dist/index.js", "dist/entry.js", "dist/entry.mjs"].some(
(file) => entry === path.join(root, file),
)
) {
return undefined;
}
argv = [process.execPath, entry, ...command.slice(2)];
} else if (program === path.join(root, "openclaw.mjs")) {
argv = [process.execPath, program, ...command.slice(1)];
} else {
return undefined;
}
if (!isForegroundGatewayRunArgv(argv)) {
return undefined;
}
const options = getCommandOptionsWithRootOptions(argv, {
commandPath: ["gateway"],
booleanFlags: [...GATEWAY_RUN_BOOLEAN_FLAGS],
valueFlags: [...GATEWAY_RUN_VALUE_FLAGS],
mode: "command-path",
});
// Reset owns deletion before initialization; do not migrate state it will discard.
return options && !options.commandOptions.includes("--reset") ? options : undefined;
}
try {
const program = command[0] && executable(command[0]);
if (!program) {
console.error("OpenClaw container activation command was not found");
process.exit(127);
}
const invocation = gatewayInvocation(program);
if (invocation) {
let interrupted;
let child;
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT"]) {
process.on(signal, () => {
interrupted ??= signal;
// Doctor's maintenance barriers own INT/TERM; HUP/QUIT must use that drain too.
child?.kill(signal === "SIGHUP" || signal === "SIGQUIT" ? "SIGTERM" : signal);
});
}
child = spawn(
process.execPath,
[
path.join(root, "openclaw.mjs"),
...invocation.rootOptions,
"doctor",
"--fix",
"--non-interactive",
],
{ stdio: "inherit", env: process.env },
);
let failure;
child.on("error", (error) => {
failure = error;
});
const outcome = await new Promise((resolve) =>
child.once("close", (code, signal) => resolve({ code, signal })),
);
if (failure) {
throw failure;
}
const signal = interrupted ?? outcome.signal;
if (signal || outcome.code !== 0) {
process.exit(signal ? 128 + os.constants.signals[signal] : (outcome.code ?? 1));
}
}
// Replace the adapter so tini continues to supervise the original command directly.
process.execve(program, command, process.env);
} catch (error) {
console.error(
`OpenClaw container activation failed: ${error instanceof Error ? error.message : String(error)}`,
);
process.exitCode = 1;
}