@@ -53,20 +53,27 @@ const { spawn } = require("node:child_process");
5353const { createHash } = require("node:crypto");
5454const { DatabaseSync } = require("node:sqlite");
5555const fs = require("node:fs");
56+ const { withFileLockSync } = require(fileLockModule);
5657const path = require("node:path");
5758const args = process.argv.slice(2);
5859const command = args[0];
5960const statePath = (id) => path.join(engineRoot, id + ".container.json");
6061const load = (id) => JSON.parse(fs.readFileSync(statePath(id), "utf8"));
61- // Sibling shim invocations (rm/inspect/wait) read this state while another
62- // writes it. A truncating write exposes a zero-length window, so a reader
63- // parses partial JSON and the shim exits 1; rename is atomic, so readers
64- // always see either the previous or the next complete state.
65- const save = (container) => {
66- const target = statePath(container.id);
67- const pending = target + "." + process.pid + ".pending";
68- fs.writeFileSync(pending, JSON.stringify(container));
69- fs.renameSync(pending, target);
62+ // Separate CLI processes share one fake daemon. Serialize state transitions so
63+ // a delayed start or exit callback cannot recreate a removed container.
64+ const withContainerLock = (id, operation) => withFileLockSync(statePath(id), {
65+ payload: () => ({ pid: process.pid, createdAt: new Date().toISOString() }),
66+ timeoutMs: 5_000,
67+ }, operation);
68+ const save = (container) => fs.writeFileSync(statePath(container.id), JSON.stringify(container));
69+ const killWorker = (container) => {
70+ if (container.pid) {
71+ try {
72+ process.kill(process.platform === "win32" ? container.pid : -container.pid, "SIGKILL");
73+ } catch (error) {
74+ if (error.code !== "ESRCH") throw error;
75+ }
76+ }
7077};
7178const launchIdFor = (container) =>
7279 Buffer.from(container.labels["openclaw.node-worker.launch"], "base64url").toString("utf8");
@@ -155,12 +162,13 @@ if (command === "version") {
155162 const entry = args[entrypoint + 3];
156163 const workerArgs = args.slice(entrypoint + 4);
157164 const container = { id, labels, env, mounts, image, entry, workerArgs, status: "created", pid: null };
158- save(container);
165+ withContainerLock(id, () => save(container) );
159166 record({ argv: args, container, journal: journalState(launchIdFor(container)) });
160167 releaseAfterMarker("hold-create", () => process.stdout.write(id + "\n"));
161168} else if (command === "start") {
162169 void (async () => {
163- const container = readContainer(args.at(-1));
170+ const id = args.at(-1);
171+ let container = withContainerLock(id, () => readContainer(id));
164172 const journal = await waitForRunningJournal(container);
165173 record({ argv: args, journal });
166174 const persisted = journal?.container_json && JSON.parse(journal.container_json);
@@ -175,14 +183,18 @@ if (command === "version") {
175183 // A real engine leaves the container "created" until its start request lands,
176184 // so the marker lets a test hold the launch inside that startup window.
177185 await new Promise((resolve) => releaseAfterMarker("hold-start", resolve));
178- const child = spawn(process.execPath, [container.entry, ...container.workerArgs], {
179- detached: process.platform !== "win32",
180- env: container.env,
181- stdio: ["pipe", "inherit", "inherit"],
186+ const child = withContainerLock(id, () => {
187+ container = readContainer(id);
188+ const child = spawn(process.execPath, [container.entry, ...container.workerArgs], {
189+ detached: process.platform !== "win32",
190+ env: container.env,
191+ stdio: ["pipe", "inherit", "inherit"],
192+ });
193+ container.status = "running";
194+ container.pid = child.pid;
195+ save(container);
196+ return child;
182197 });
183- container.status = "running";
184- container.pid = child.pid;
185- save(container);
186198 process.stdin.pipe(child.stdin);
187199 child.stdin.on("error", (error) => {
188200 if (error.code !== "EPIPE") throw error;
@@ -192,12 +204,14 @@ if (command === "version") {
192204 process.exitCode = 1;
193205 });
194206 child.once("exit", (code, signal) => {
195- if (fs.existsSync(statePath(container.id))) {
196- const current = load(container.id);
197- current.status = "exited";
198- current.pid = null;
199- save(current);
200- }
207+ withContainerLock(container.id, () => {
208+ if (fs.existsSync(statePath(container.id))) {
209+ const current = load(container.id);
210+ current.status = "exited";
211+ current.pid = null;
212+ save(current);
213+ }
214+ });
201215 process.exit(code ?? (signal ? 137 : 0));
202216 });
203217 })().catch((error) => {
@@ -207,7 +221,7 @@ if (command === "version") {
207221} else if (command === "inspect") {
208222 const id = args.at(-1);
209223 record({ argv: args });
210- const container = readContainer(id);
224+ const container = withContainerLock(id, () => readContainer(id) );
211225 const format = args[args.indexOf("--format") + 1];
212226 const columns = [container.status];
213227 // Releasing the startup hold here proves the supervisor observed the container
@@ -223,41 +237,42 @@ if (command === "version") {
223237 }
224238 process.stdout.write(columns.join("\t") + "\n");
225239} else if (command === "kill") {
226- const container = readContainer(args.at(-1));
227- record({ argv: args, journal: journalState(launchIdFor(container)) });
228- if (container.status !== "running") {
229- process.stderr.write("container is not running\n");
230- process.exit(1);
231- }
232- container.status = "exited";
233- save(container);
234- if (container.pid) {
235- try {
236- process.kill(process.platform === "win32" ? container.pid : -container.pid, "SIGKILL");
237- } catch (error) {
238- if (error.code !== "ESRCH") throw error;
240+ const id = args.at(-1);
241+ withContainerLock(id, () => {
242+ const container = readContainer(id);
243+ record({ argv: args, journal: journalState(launchIdFor(container)) });
244+ if (container.status !== "running") {
245+ process.stderr.write("container is not running\n");
246+ process.exit(1);
239247 }
240- }
241- process.stdout.write(container.id + "\n");
248+ container.status = "exited";
249+ save(container);
250+ killWorker(container);
251+ process.stdout.write(container.id + "\n");
252+ });
242253} else if (command === "rm") {
243- const container = readContainer(args.at(-1));
254+ const id = args.at(-1);
255+ const container = withContainerLock(id, () => readContainer(id));
244256 record({ argv: args, journal: journalState(launchIdFor(container)) });
245257 if (fs.existsSync(path.join(engineRoot, "fail-removal"))) {
246258 process.stderr.write("injected container removal failure\n");
247259 process.exit(1);
248260 }
249- releaseAfterMarker("hold-removal", () => {
250- fs.unlinkSync(statePath(container.id));
251- process.stdout.write(container.id + "\n");
252- });
261+ releaseAfterMarker("hold-removal", () => withContainerLock(id, () => {
262+ const current = readContainer(id);
263+ killWorker(current);
264+ fs.unlinkSync(statePath(id));
265+ process.stdout.write(id + "\n");
266+ }));
253267} else if (command === "ps") {
254268 record({ argv: args });
255269 const ownerFilter = args.find((arg) => arg.startsWith("label=openclaw.node-worker.host="));
256270 const owner = ownerFilter?.slice("label=openclaw.node-worker.host=".length);
257271 for (const file of fs.readdirSync(engineRoot).sort()) {
258272 if (!file.endsWith(".container.json")) continue;
259- const container = JSON.parse(fs.readFileSync(path.join(engineRoot, file), "utf8"));
260- if (container.labels["openclaw.node-worker.host"] !== owner) continue;
273+ const id = file.slice(0, -".container.json".length);
274+ const container = withContainerLock(id, () => fs.existsSync(statePath(id)) ? load(id) : undefined);
275+ if (!container || container.labels["openclaw.node-worker.host"] !== owner) continue;
261276 process.stdout.write([
262277 container.id,
263278 container.labels["openclaw.node-worker.gateway"],
0 commit comments