openclaw/scripts/run-with-env.mts
Peter Steinberger 799ddbd35d
refactor(comments): deslop production narration
## What Problem This Solves

Production code still carries duplicated narration over function names, types, branches and CSS selectors. Some of that prose has drifted: Zalo polling is described as development-only even though it is the default production route, and a joined hook helper is called fire-and-forget.

## User Impact

No user-visible behavior changes. Runtime logic, templates, CSS declarations, configuration, persisted state, wire formats, public API documentation, licenses and lint-suppression reasons remain intact.

## Why This Change Was Made

This maintainer-requested cleanup removes redundant internal helper/registrar summaries, repeated section labels, and obsolete inline font-size history. Existing declarations and shared owners already express these facts; no new abstraction is needed. Comments explaining authority, lifecycle, ordering, cleanup, platform constraints, dependencies and public contracts stay.

The measured reduction is 696 net production/tooling lines: 604 standalone comment lines and 92 adjacent blank lines, plus 59 inline comment removals without net line savings. No tests or generated files changed. This is a bounded contextual sweep, not a claim of exhaustive repository coverage; the local census records exact findings, retained candidates, and unread files. Filename-header cleanup from #161768 is excluded.

## Evidence

Independent review completed; all accepted documentation findings were addressed by restoring base comments. The remaining changed files are byte-identical to the reviewed and remotely frozen candidate.

Blacksmith Testbox validation:
- Parser comparison: identical non-comment TypeScript tokens and CSS structure.
- Both import-cycle checks: 0 cycles.
- Focused existing tests: 40 Vitest shards passed (521.71 seconds).
- Plugin contracts: 48 files / 1,153 tests passed.
- Plugin, source-to-extension, and SDK/package import-boundary checks passed.
- Feishu asset hook check: no build hooks; no plugin browser/control-UI source changed.

SDK API comparison passed with no API changes. The full changed-file gate passed remotely. The lowered-threshold duplicate census (12 lines / 80 tokens) completed; its raw 155 records include deliberate probe/fixture matches and are not claimed as removable production code. No tests were added or changed.

Public JSDoc was audited independently: the SDK API comparison strips comments, while shipped declarations can preserve them, so API-shape equality alone would not prove documentation preservation.


### Inherited hosted CI failure

Exact-head [CI run 36815106181](https://github.com/openclaw/openclaw/actions/runs/36815106181) tested `ff26a4c05d3b41d25477df41cb94010c6cac5cb0` merged with main `75d1f82c18`. The only failing test job was `checks-node-compact-small-19`: `test/helpers/openclaw-test-instance.acquisition.test.ts:33`, “keeps an absent Gateway unreachable while retaining its port claims,” expected `free` but received `busy`. The other failure is the aggregate CI gate. This attempt has 84 successful jobs, 16 skipped jobs, and 88 collateral cancellations; cancelled coverage is not counted as passing.

The identical assertion and error were independently verified in [job 110052175838](https://github.com/openclaw/openclaw/actions/runs/36763489663/job/110052175838), the latest attempt (1) for unrelated PR #162070's final head `d07a6981d4`. The acquisition test, instance helper, cleanup wrapper, isolated-state writer, port allocator, claim owner, claim-lock owner and TCP probe are byte-identical between that head and this PR. No changed file participates in the failing acquisition/probe path. The failure precedes Gateway startup; the logs do not identify the competing listener, so no root-cause repair is claimed.

Landing uses the maintainer-authorized inherited-failure exception pinned to this exact head, backed by the passing remote gates above. The fixture defect remains with the main-CI coordinator. No workflow rerun, test weakening, timeout increase, or source repush was used to obtain green. GitHub's GraphQL writer rejected auto-merge because its quota was exhausted; the request was reconciled as absent before selecting the supported REST squash path.
2026-09-30 22:28:36 -07:00

221 lines
6.2 KiB
TypeScript

// Runs a command with inline KEY=value assignments while preserving signal behavior.
import { spawn } from "node:child_process";
import { terminateManagedChild } from "./lib/managed-child-process.mts";
import { parsePositiveInt } from "./lib/numeric-options.mjs";
const ENV_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/u;
const USAGE =
"Usage: node --import tsx scripts/run-with-env.mts KEY=value [KEY=value ...] -- command [args...]";
const MAX_TIMER_TIMEOUT_MS = 2_147_000_000;
type ForwardedSignal = "SIGHUP" | "SIGINT" | "SIGTERM";
/**
* Detects help requests before the command separator.
*/
export function isRunWithEnvHelpRequest(argv: readonly string[]) {
for (const arg of argv) {
if (arg === "--") {
return false;
}
if (arg === "--help" || arg === "-h") {
return true;
}
}
return false;
}
/**
* Parses KEY=value assignments and the command following --.
*/
export function parseRunWithEnvArgs(argv: string[]) {
const separatorIndex = argv.indexOf("--");
if (separatorIndex <= 0 || separatorIndex === argv.length - 1) {
throw new Error(USAGE);
}
const assignments = argv.slice(0, separatorIndex);
const env: Record<string, string> = {};
for (const assignment of assignments) {
if (!ENV_ASSIGNMENT_RE.test(assignment)) {
throw new Error(`invalid environment assignment: ${assignment}`);
}
const equalsIndex = assignment.indexOf("=");
env[assignment.slice(0, equalsIndex)] = assignment.slice(equalsIndex + 1);
}
const [command, ...args] = argv.slice(separatorIndex + 1);
if (command === undefined) {
throw new Error(USAGE);
}
return { env, command, args };
}
/**
* Resolves bare Node command names to the current executable so wrapper and child use the same
* runtime. Windows command lookup is case-insensitive; explicit paths remain caller-owned.
*/
export function resolveSpawnCommand(
command: string,
args: string[],
execPath = process.execPath,
platform: NodeJS.Platform = process.platform,
) {
const normalizedCommand = platform === "win32" ? command.toLowerCase() : command;
const isNodeCommand =
normalizedCommand === "node" || (platform === "win32" && normalizedCommand === "node.exe");
if (isNodeCommand) {
return {
command: execPath,
args,
};
}
return {
command,
args,
};
}
export function resolveForceKillDelayMs(env: NodeJS.ProcessEnv = process.env) {
const raw = env.OPENCLAW_RUN_WITH_ENV_FORCE_KILL_MS;
const text = raw?.trim();
if (!text) {
return 5_000;
}
const parsed = parsePositiveInt(text, "OPENCLAW_RUN_WITH_ENV_FORCE_KILL_MS");
return Math.min(parsed, MAX_TIMER_TIMEOUT_MS);
}
/**
* Signals the wrapped command tree when this small parent wrapper is stopped.
*/
function main(argv: string[] = process.argv.slice(2)) {
if (isRunWithEnvHelpRequest(argv)) {
console.log(USAGE);
return;
}
let parsed: ReturnType<typeof parseRunWithEnvArgs>;
try {
parsed = parseRunWithEnvArgs(argv);
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exit(2);
}
let forceKillDelayMs;
try {
forceKillDelayMs = resolveForceKillDelayMs();
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exit(2);
}
const spawnCommand = resolveSpawnCommand(parsed.command, parsed.args);
const useChildProcessGroup = process.platform !== "win32" && !process.stdin.isTTY;
const child = spawn(spawnCommand.command, spawnCommand.args, {
detached: useChildProcessGroup,
env: {
...process.env,
...parsed.env,
},
stdio: "inherit",
});
let forwardedSignal: ForwardedSignal | undefined;
let forceKillTimer: ReturnType<typeof setTimeout> | undefined;
// Keep the child in the foreground process group so TTY signals such as
// Ctrl-C, Ctrl-Z, and window resizes stay native. Forward direct wrapper
// shutdown signals that would otherwise only kill this small parent process.
const forwardedSignals: ForwardedSignal[] = useChildProcessGroup
? ["SIGTERM", "SIGHUP", "SIGINT"]
: ["SIGTERM", "SIGHUP"];
const signalChild = (signal: NodeJS.Signals) =>
terminateManagedChild(child, signal, { useProcessGroup: useChildProcessGroup });
const childProcessGroupAlive = () => {
if (!useChildProcessGroup || typeof child.pid !== "number") {
return false;
}
try {
process.kill(-child.pid, 0);
return true;
} catch {
return false;
}
};
const exitWithForwardedSignal = () => {
const signal = forwardedSignal;
if (!signal) {
return;
}
const finish = () => {
if (forceKillTimer) {
clearTimeout(forceKillTimer);
}
process.kill(process.pid, signal);
};
if (!childProcessGroupAlive()) {
finish();
return;
}
const deadline = Date.now() + forceKillDelayMs;
const drainTimer = setInterval(() => {
if (!childProcessGroupAlive()) {
clearInterval(drainTimer);
finish();
return;
}
if (Date.now() >= deadline) {
clearInterval(drainTimer);
signalChild("SIGKILL");
finish();
}
}, 50);
};
const cleanupSignalHandlers = () => {
for (const [signal, handler] of signalHandlers) {
process.off(signal, handler);
}
};
const signalHandlers = new Map<ForwardedSignal, () => void>(
forwardedSignals.map((signal) => [
signal,
() => {
forwardedSignal ??= signal;
signalChild(signal);
forceKillTimer ??= setTimeout(() => signalChild("SIGKILL"), forceKillDelayMs);
},
]),
);
for (const [signal, handler] of signalHandlers) {
process.on(signal, handler);
}
child.on("exit", (code, signal) => {
cleanupSignalHandlers();
if (forwardedSignal) {
exitWithForwardedSignal();
return;
}
if (forceKillTimer) {
clearTimeout(forceKillTimer);
}
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 1);
});
child.on("error", (error) => {
cleanupSignalHandlers();
if (forceKillTimer) {
clearTimeout(forceKillTimer);
}
console.error(error);
process.exit(1);
});
}
if (import.meta.main) {
main();
}