The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 17:15 UTC
fix(server): reap recorded Linux Claude survivors before recovery (#22834)
Julius Marminge committed
Nov 12, 2026 at 23:59 UTC
e4025c8528fce4c62615aaeded33b8c78ef33e5e
6 files changed
+384
-23
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+26
-2
@@ -82,6 +82,7 @@ import {
82
mcpAppToolResourceUri,
83
} from "@t3tools/shared/mcpApp";
84
import { AgentScope } from "@t3tools/shared/AgentScope";
85
+import * as ProviderProcesses from "../../process/providerProcesses.ts";
86
import * as HostProcess from "@t3tools/shared/HostProcess";
87
import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
88
import { compareSemverVersions } from "@t3tools/shared/semver";
@@ -372,7 +373,10 @@ const CLAUDE_DESCENDANT_POLL = "1 second";
373
const CLAUDE_ROOT_REFUSAL =
374
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
375
376
+// fd 4 gates the launch until the server has recorded the process it is about to become.
377
const CLAUDE_GROUP_WATCH_SCRIPT = [
378
+ "read -r _ <&4 || exit 1",
379
+ "exec 4<&-",
380
"{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } </dev/null >/dev/null 2>&1 &",
381
'exec "$@" 3<&-',
382
].join("\n");
@@ -380,13 +384,15 @@ const CLAUDE_GROUP_WATCH_SCRIPT = [
384
/**
385
* Kill the CLI's group on exit to stop MCP grandchildren; `onExit` stops its agent scope for
386
* setsid daemons. The CLI keeps working after its pipes close, so a watcher stops the group on
383
- * EOF from a pipe only this server holds, including when the server crashes.
387
+ * EOF from a pipe only this server holds, including when the server crashes. `register` records
388
+ * the CLI before it may run, so a restarted server can reap it if the watcher did not.
389
*/
390
export function spawnClaudeProcessGroup(
391
options: ClaudeSpawnOptions,
392
onExit?: () => void,
393
onStderr: (text: string) => void = () => {},
394
onStderrClose: () => void = () => {},
395
+ register?: (pid: number) => () => void,
396
): ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid"> {
397
const child = NodeChildProcess.spawn(
398
"/bin/sh",
@@ -395,18 +401,34 @@ export function spawnClaudeProcessGroup(
401
cwd: options.cwd,
402
env: options.env,
403
signal: options.signal,
398
- stdio: ["pipe", "pipe", "pipe", "pipe"],
404
+ stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"],
405
detached: true,
406
},
407
);
408
+ let forget: (() => void) | undefined;
409
// Always drained, so a chatty CLI never blocks on a full stderr pipe.
410
child.stderr?.setEncoding("utf8").on("data", onStderr).once("close", onStderrClose);
411
child.once("exit", () => {
412
try {
413
signalProcessGroup(child.pid ?? 0, "SIGKILL");
414
} catch {}
415
+ try {
416
+ forget?.();
417
+ } catch {}
418
onExit?.();
419
});
420
+ const gate = child.stdio[4];
421
+ if (child.pid !== undefined && gate !== null && gate !== undefined && "end" in gate) {
422
+ try {
423
+ forget = register?.(child.pid);
424
+ gate.on("error", () => child.kill("SIGKILL"));
425
+ gate.end("ready\n");
426
+ } catch (cause) {
427
+ child.kill("SIGKILL");
428
+ gate.destroy();
429
+ throw cause;
430
+ }
431
+ }
432
// Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes.
433
return child as ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid">;
434
}
@@ -1256,6 +1278,7 @@ export const layerQueryRunner: Layer.Layer<
1278
const path = yield* Path.Path;
1279
const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
1280
const agentScope = yield* AgentScope;
1281
+ const providerProcesses = yield* ProviderProcesses.ProviderProcesses;
1282
const platform = yield* HostProcess.Platform;
1283
const runFork = Effect.runForkWith(yield* Effect.context<never>());
1284
const hostEnvironment = yield* HostProcess.Environment;
@@ -1372,6 +1395,7 @@ export const layerQueryRunner: Layer.Layer<
1395
stopScope,
1396
appendStderr,
1397
stderrDone,
1398
+ providerProcesses.register,
1399
);
1400
if (unit === undefined && child.pid !== undefined) {
1401
const tracker = trackDescendants(child.pid);
apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+41
@@ -748,6 +748,47 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
748
}),
749
);
750
751
+ // A restarted server reaps recorded CLIs, so a CLI must never run before its record exists.
752
+ it.effect("records the CLI before it runs and forgets it once it exits", () =>
753
+ Effect.gen(function* () {
754
+ const cli = fakeClaudeCli(
755
+ ['dir=$(dirname "$0")', 'printf \'%s %s\' "$$" "$(cat "$dir/record")" > "$dir/seen"'].join(
756
+ "\n",
757
+ ),
758
+ );
759
+ const dir = NodePath.dirname(cli);
760
+ NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "seen")]);
761
+ yield* Effect.addFinalizer(() =>
762
+ Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })),
763
+ );
764
+ const forgotten = yield* Deferred.make<void>();
765
+ let registered = 0;
766
+ spawnClaudeProcessGroup(
767
+ {
768
+ command: cli,
769
+ args: [],
770
+ cwd: dir,
771
+ env: process.env,
772
+ // @effect-diagnostics-next-line abortControllerInEffect:off - The CLI exits on its own.
773
+ signal: new AbortController().signal,
774
+ },
775
+ undefined,
776
+ undefined,
777
+ undefined,
778
+ (pid) => {
779
+ registered = pid;
780
+ NodeFS.writeFileSync(NodePath.join(dir, "record"), String(pid));
781
+ return () => Deferred.doneUnsafe(forgotten, Effect.void);
782
+ },
783
+ );
784
+ const seen = yield* Effect.promise(() =>
785
+ NodeFS.promises.readFile(NodePath.join(dir, "seen"), "utf8"),
786
+ );
787
+ assert.equal(seen, `${registered} ${registered}`);
788
+ yield* Deferred.await(forgotten);
789
+ }),
790
+ );
791
+
792
it.effect("marks the CLI's jobs with its thread and counts it as an agent until it exits", () => {
793
let runningAgents = 0;
794
let releaseAgent!: () => void;
apps/server/src/process/agentScope.test.ts
+39
-20
@@ -16,6 +16,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process";
16
import * as ServerConfig from "../config.ts";
17
import { makeCodexAppServerSpawnCommand } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
18
import * as ProcessRunner from "../processRunner.ts";
19
+import * as ProviderProcesses from "./providerProcesses.ts";
20
import { classifyScope, make, ownedAgentSlice, type ScopeState } from "./agentScope.ts";
21
22
const running: ScopeState = {
@@ -55,7 +56,14 @@ const withFakeSystemd = <A, E>(
56
{
57
oomPolicy = true,
58
stopFails = false,
58
- }: { readonly oomPolicy?: boolean; readonly stopFails?: boolean } = {},
59
+ leftovers = false,
60
+ liveOwner = false,
61
+ }: {
62
+ readonly oomPolicy?: boolean;
63
+ readonly stopFails?: boolean;
64
+ readonly leftovers?: boolean;
65
+ readonly liveOwner?: boolean;
66
+ } = {},
67
) =>
68
Effect.gen(function* () {
69
const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));
@@ -102,7 +110,12 @@ const withFakeSystemd = <A, E>(
110
}),
111
});
112
const fileSystem = yield* FileSystem.FileSystem;
113
+ const { stateDir } = yield* ServerConfig.ServerConfig;
114
+ if (leftovers) {
115
+ units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" });
116
+ }
117
const scope = yield* make.pipe(
118
+ Effect.provideService(ProviderProcesses.ProviderProcesses, { hasOtherLiveOwner: liveOwner }),
119
Effect.provideService(ProcessRunner.ProcessRunner, runner),
120
Effect.provideService(HostProcess.Platform, "linux"),
121
Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }),
@@ -114,7 +127,6 @@ const withFakeSystemd = <A, E>(
127
fileSystem.writeFileString(path.replace("/sys/fs/cgroup", cgroupRoot), data, options),
128
}),
129
);
117
- const { stateDir } = yield* ServerConfig.ServerConfig;
130
return yield* body({ scope, units, calls, stateDir, cgroupRoot }).pipe(
131
Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))),
132
);
@@ -308,27 +320,34 @@ describe("AgentScope service", () => {
320
),
321
);
322
311
- it.effect("stops agents a killed server left before the first launch", () =>
312
- withFakeSystemd(({ scope, units, calls, stateDir }) =>
313
- Effect.gen(function* () {
314
- units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" });
315
- const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
316
- const stops = calls.filter(([, verb]) => verb === "stop");
317
- expect(stops).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]);
318
- expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir));
319
- expect(agent.args).toContain("--property=TimeoutStopSec=10s");
320
- const terminal = yield* scope.wrap({
321
- command: "agent",
322
- args: [],
323
- name: "terminal",
324
- survivesRestart: true,
325
- });
326
- expect(sliceOf(terminal)).toBe("app-t3code-agents.slice");
327
- expect(calls.filter(([, verb]) => verb === "stop")).toHaveLength(1);
328
- }),
323
+ it.effect("stops agents a killed server left before startup completes", () =>
324
+ withFakeSystemd(
325
+ ({ scope, calls, stateDir }) =>
326
+ Effect.gen(function* () {
327
+ expect(stopsOf(calls)).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]);
328
+ const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
329
+ expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir));
330
+ expect(agent.args).toContain("--property=TimeoutStopSec=10s");
331
+ const terminal = yield* scope.wrap({
332
+ command: "agent",
333
+ args: [],
334
+ name: "terminal",
335
+ survivesRestart: true,
336
+ });
337
+ expect(sliceOf(terminal)).toBe("app-t3code-agents.slice");
338
+ expect(stopsOf(calls)).toHaveLength(1);
339
+ }),
340
+ { leftovers: true },
341
),
342
);
343
344
+ it.effect("leaves the slice to another live server sharing this home", () =>
345
+ withFakeSystemd(({ calls }) => Effect.sync(() => expect(stopsOf(calls)).toEqual([])), {
346
+ leftovers: true,
347
+ liveOwner: true,
348
+ }),
349
+ );
350
+
351
it.effect("stops leftover processes only in an active agent scope", () =>
352
withFakeSystemd(({ scope, units, calls, cgroupRoot }) =>
353
Effect.gen(function* () {
apps/server/src/process/agentScope.ts
+11
-1
@@ -17,6 +17,7 @@ import * as Path from "effect/Path";
17
18
import * as ServerConfig from "../config.ts";
19
import * as ProcessRunner from "../processRunner.ts";
20
+import * as ProviderProcesses from "./providerProcesses.ts";
21
22
const AGENT_SLICE = "app-t3code-agents.slice";
23
// Owns every agent slice and competes with the server's unit or scope under app.slice.
@@ -106,6 +107,7 @@ export const make = Effect.gen(function* () {
107
const path = yield* Path.Path;
108
const hostEnvironment = yield* HostProcess.Environment;
109
const { stateDir } = yield* ServerConfig.ServerConfig;
110
+ const { hasOtherLiveOwner } = yield* ProviderProcesses.ProviderProcesses;
111
const ownedSlice = ownedAgentSlice(stateDir);
112
const layerScope = yield* Effect.scope;
113
@@ -130,6 +132,7 @@ export const make = Effect.gen(function* () {
132
const stopLeftoverAgents = Effect.fn("agentScope.stopLeftoverAgents")(function* (
133
systemctl: string,
134
) {
135
+ if (hasOtherLiveOwner) return;
136
const shown = yield* run(systemctl, [
137
"--user",
138
"show",
@@ -215,6 +218,10 @@ export const make = Effect.gen(function* () {
218
}),
219
);
220
221
+ // Layer acquisition is the startup barrier: recovery must not terminalize or
222
+ // continue old runs while a previous server's providers can still execute.
223
+ yield* systemd;
224
+
225
// `shared` scopes serve other threads too: tracked only for OOM diagnosis on old systemd.
226
const scopeByThread = new Map<string, { unit: string; oomKilled: boolean; shared: boolean }>();
227
@@ -427,4 +434,7 @@ export const make = Effect.gen(function* () {
434
} satisfies AgentScopeShape;
435
});
436
430
-export const layer = Layer.effect(AgentScope, make).pipe(Layer.provide(ProcessRunner.layer));
437
+export const layer = Layer.effect(AgentScope, make).pipe(
438
+ Layer.provide(ProcessRunner.layer),
439
+ Layer.provideMerge(ProviderProcesses.layer),
440
+);
apps/server/src/process/providerProcesses.test.ts
new
+127
@@ -0,0 +1,127 @@
1
+// @effect-diagnostics nodeBuiltinImport:off -- real processes stand in for servers and CLIs.
2
+import * as NodeChildProcess from "node:child_process";
3
+import * as NodeCrypto from "node:crypto";
4
+import * as NodeFS from "node:fs";
5
+import * as NodeOS from "node:os";
6
+import * as NodePath from "node:path";
7
+
8
+import * as NodeServices from "@effect/platform-node/NodeServices";
9
+import { assert, describe, expect, it } from "@effect/vitest";
10
+import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
11
+import * as HostProcess from "@t3tools/shared/HostProcess";
12
+import * as Context from "effect/Context";
13
+import * as Deferred from "effect/Deferred";
14
+import * as Effect from "effect/Effect";
15
+import * as Layer from "effect/Layer";
16
+
17
+import * as ServerConfig from "../config.ts";
18
+import * as ProviderProcesses from "./providerProcesses.ts";
19
+
20
+// Real child processes stand in for servers and CLIs; only PIDs captured at spawn are signalled.
21
+const ownedProcess = Effect.gen(function* () {
22
+ const ready = yield* Deferred.make<void>();
23
+ const exited = yield* Deferred.make<void>();
24
+ const child = yield* Effect.acquireRelease(
25
+ Effect.sync(() => {
26
+ const child = NodeChildProcess.spawn(
27
+ process.execPath,
28
+ ["-e", 'process.stdin.resume(); process.send("ready");'],
29
+ { stdio: ["pipe", "ignore", "ignore", "ipc"] },
30
+ );
31
+ child.once("message", () => Deferred.doneUnsafe(ready, Effect.void));
32
+ child.once("error", (error) => Deferred.doneUnsafe(ready, Effect.die(error)));
33
+ child.once("exit", () => Deferred.doneUnsafe(exited, Effect.void));
34
+ return child;
35
+ }),
36
+ (child) =>
37
+ Effect.sync(() => child.kill("SIGKILL")).pipe(Effect.andThen(Deferred.await(exited))),
38
+ );
39
+ yield* Deferred.await(ready);
40
+ const pid = child.pid;
41
+ assert(pid !== undefined);
42
+ const controller = AcpSessionRuntime.makePosixProcessTreeController("linux");
43
+ const identity = controller.identity(pid);
44
+ assert(identity !== undefined);
45
+ const boot = NodeFS.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
46
+ return {
47
+ pid,
48
+ startTime: `${boot}:${identity.startTime}`,
49
+ pgid: 0,
50
+ running: () => {
51
+ const observed = controller.identity(pid);
52
+ return observed !== undefined && !AcpSessionRuntime.posixProcessIsZombie(observed);
53
+ },
54
+ stop: Effect.sync(() => child.kill("SIGKILL")).pipe(Effect.andThen(Deferred.await(exited))),
55
+ };
56
+});
57
+
58
+describe.runIf(HostProcess.Platform.defaultValue() === "linux")("ProviderProcesses", () => {
59
+ it.live("reaps only recorded CLIs of dead servers before startup completes", () =>
60
+ Effect.gen(function* () {
61
+ const config = yield* ServerConfig.ServerConfig;
62
+ const directory = NodePath.join(config.stateDir, "provider-processes");
63
+ NodeFS.mkdirSync(directory, { recursive: true });
64
+ type Identity = { readonly pid: number; readonly startTime: string };
65
+ const record = (owner: Identity, processes: ReadonlyArray<Identity>) => {
66
+ const instanceId = NodeCrypto.randomUUID();
67
+ NodeFS.writeFileSync(
68
+ NodePath.join(directory, `${instanceId}.json`),
69
+ JSON.stringify({
70
+ version: 1,
71
+ instanceId,
72
+ hostname: NodeOS.hostname(),
73
+ stateDir: config.stateDir,
74
+ owner: { pid: owner.pid, startTime: owner.startTime },
75
+ processes: processes.map(({ pid, startTime }) => ({ pid, startTime, pgid: 0 })),
76
+ }),
77
+ );
78
+ };
79
+ const reused = (identity: Identity) => ({
80
+ ...identity,
81
+ startTime: identity.startTime.replace(/:\d+$/, ":1"),
82
+ });
83
+ const deadOwner = yield* ownedProcess;
84
+ const liveOwner = yield* ownedProcess;
85
+ const reusedOwner = yield* ownedProcess;
86
+ const liveProvider = yield* ownedProcess;
87
+ const reusedProvider = yield* ownedProcess;
88
+ const orphan = yield* ownedProcess;
89
+ const orphanOfReusedOwner = yield* ownedProcess;
90
+ const unrecorded = yield* ownedProcess;
91
+ record(liveOwner, [liveProvider]);
92
+ record(deadOwner, [reused(reusedProvider)]);
93
+ record(deadOwner, [orphan]);
94
+ record(reused(reusedOwner), [orphanOfReusedOwner]);
95
+ yield* deadOwner.stop;
96
+
97
+ const context = yield* Layer.build(ProviderProcesses.layer);
98
+ expect(Context.get(context, ProviderProcesses.ProviderProcesses).hasOtherLiveOwner).toBe(
99
+ true,
100
+ );
101
+
102
+ expect({
103
+ orphan: orphan.running(),
104
+ orphanOfReusedOwner: orphanOfReusedOwner.running(),
105
+ liveProvider: liveProvider.running(),
106
+ reusedProvider: reusedProvider.running(),
107
+ reusedOwner: reusedOwner.running(),
108
+ unrecorded: unrecorded.running(),
109
+ }).toEqual({
110
+ orphan: false,
111
+ orphanOfReusedOwner: false,
112
+ liveProvider: true,
113
+ reusedProvider: true,
114
+ reusedOwner: true,
115
+ unrecorded: true,
116
+ });
117
+ }).pipe(
118
+ Effect.scoped,
119
+ Effect.provideService(HostProcess.Platform, "linux"),
120
+ Effect.provide(
121
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-restart-ownership-" }).pipe(
122
+ Layer.provideMerge(NodeServices.layer),
123
+ ),
124
+ ),
125
+ ),
126
+ );
127
+});
apps/server/src/process/providerProcesses.ts
new
+140
@@ -0,0 +1,140 @@
1
+// @effect-diagnostics nodeBuiltinImport:off -- the SDK's synchronous spawn callback must record ownership before releasing the child.
2
+import * as NodeCrypto from "node:crypto";
3
+import * as NodeFS from "node:fs";
4
+import * as NodeOS from "node:os";
5
+import * as NodePath from "node:path";
6
+
7
+import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
8
+import * as HostProcess from "@t3tools/shared/HostProcess";
9
+import * as Context from "effect/Context";
10
+import * as Effect from "effect/Effect";
11
+import * as Layer from "effect/Layer";
12
+import * as Schema from "effect/Schema";
13
+
14
+import * as ServerConfig from "../config.ts";
15
+
16
+const ProcessIdentity = Schema.Struct({
17
+ pid: Schema.Int.check(Schema.isBetween({ minimum: 2, maximum: Number.MAX_SAFE_INTEGER })),
18
+ startTime: Schema.String,
19
+});
20
+const OwnershipRecord = Schema.Struct({
21
+ version: Schema.Literal(1),
22
+ instanceId: Schema.String,
23
+ hostname: Schema.String,
24
+ stateDir: Schema.String,
25
+ owner: ProcessIdentity,
26
+ processes: Schema.Array(Schema.Struct({ ...ProcessIdentity.fields, pgid: Schema.Int })),
27
+});
28
+const decodeRecord = Schema.decodeUnknownSync(Schema.fromJsonString(OwnershipRecord));
29
+
30
+// A concurrent exit can remove the record. Incomplete/unknown records never authorize a signal.
31
+const readRecord = (recordPath: string) => {
32
+ try {
33
+ return decodeRecord(NodeFS.readFileSync(recordPath, "utf8"));
34
+ } catch {
35
+ return undefined;
36
+ }
37
+};
38
+
39
+export const ProviderProcesses = Context.Reference<{
40
+ readonly register?: (pid: number) => () => void;
41
+ readonly hasOtherLiveOwner: boolean;
42
+}>("t3/process/ProviderProcesses", { defaultValue: () => ({ hasOtherLiveOwner: false }) });
43
+
44
+const make = Effect.gen(function* () {
45
+ const platform = yield* HostProcess.Platform;
46
+ if (platform !== "linux") return { hasOtherLiveOwner: false };
47
+ const { stateDir } = yield* ServerConfig.ServerConfig;
48
+ const directory = NodePath.join(stateDir, "provider-processes");
49
+ const hostname = NodeOS.hostname();
50
+ const boot = NodeFS.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
51
+ const controller = AcpSessionRuntime.makePosixProcessTreeController(platform);
52
+ const identity = (pid: number) => {
53
+ const observed = controller.identity(pid);
54
+ if (observed === undefined || AcpSessionRuntime.posixProcessIsZombie(observed))
55
+ return undefined;
56
+ return { ...observed, startTime: `${boot}:${observed.startTime}` };
57
+ };
58
+ const matches = (expected: typeof ProcessIdentity.Type) =>
59
+ identity(expected.pid)?.startTime === expected.startTime;
60
+ const kill = (survivor: typeof ProcessIdentity.Type) => {
61
+ try {
62
+ controller.signalProcess(survivor.pid, "SIGKILL");
63
+ } catch {}
64
+ };
65
+ const owner = identity(process.pid);
66
+ if (owner === undefined) return yield* Effect.die(new Error("Cannot identify provider owner"));
67
+ NodeFS.mkdirSync(directory, { recursive: true });
68
+
69
+ const writeRecord = (processes: (typeof OwnershipRecord.Type)["processes"]) => {
70
+ const instanceId = NodeCrypto.randomUUID();
71
+ const recordPath = NodePath.join(directory, `${instanceId}.json`);
72
+ const pendingPath = `${recordPath}.pending`;
73
+ NodeFS.writeFileSync(
74
+ pendingPath,
75
+ JSON.stringify({
76
+ version: 1,
77
+ instanceId,
78
+ hostname,
79
+ stateDir,
80
+ owner: { pid: owner.pid, startTime: owner.startTime },
81
+ processes,
82
+ } satisfies typeof OwnershipRecord.Type),
83
+ );
84
+ NodeFS.renameSync(pendingPath, recordPath);
85
+ return () => NodeFS.rmSync(recordPath, { force: true });
86
+ };
87
+ // Publish the server identity even before its first provider. Another server
88
+ // using this home must not stop the shared systemd slice while we are alive.
89
+ const forgetOwner = writeRecord([]);
90
+ yield* Effect.addFinalizer(() => Effect.sync(forgetOwner));
91
+ let hasOtherLiveOwner = false;
92
+
93
+ // Only immutable per-launch records are shared between server instances. A
94
+ // live owner's records belong to that server, even when it uses this home.
95
+ for (const file of NodeFS.readdirSync(directory)) {
96
+ if (!file.endsWith(".json")) continue;
97
+ const recordPath = NodePath.join(directory, file);
98
+ const record = readRecord(recordPath);
99
+ if (record === undefined) continue;
100
+ if (record.hostname !== hostname || record.stateDir !== stateDir) continue;
101
+ if (matches(record.owner)) {
102
+ if (record.owner.pid !== process.pid) hasOtherLiveOwner = true;
103
+ continue;
104
+ }
105
+ let survived = false;
106
+ for (const survivor of record.processes) {
107
+ if (survivor.pid === process.pid || !matches(survivor)) continue;
108
+ // Never infer ownership from argv, executable names, or group membership.
109
+ // As in the ACP controller, starttime blocks reuse between observations.
110
+ // Node has no pidfd_send_signal, so the final read-to-signal race remains.
111
+ kill(survivor);
112
+ for (let attempt = 0; matches(survivor) && !survived; attempt++) {
113
+ survived = attempt === 100;
114
+ if (!survived) yield* Effect.sleep("10 millis");
115
+ }
116
+ }
117
+ // Like a failed slice stop, an unkillable CLI must not keep the server down;
118
+ // its record stays so the next start retries.
119
+ if (survived) {
120
+ yield* Effect.logWarning("Could not stop a provider left by a previous server", { file });
121
+ continue;
122
+ }
123
+ NodeFS.rmSync(recordPath, { force: true });
124
+ }
125
+
126
+ return {
127
+ hasOtherLiveOwner,
128
+ register: (pid: number) => {
129
+ const provider = identity(pid);
130
+ if (provider === undefined || provider.ppid !== process.pid) {
131
+ throw new Error("Cannot identify spawned provider");
132
+ }
133
+ // A rename keeps startup from seeing a partial write. The child is gated
134
+ // until this returns, so an abrupt death cannot leave an unrecorded CLI.
135
+ return writeRecord([{ pid, startTime: provider.startTime, pgid: provider.pgid }]);
136
+ },
137
+ };
138
+});
139
+
140
+export const layer = Layer.effect(ProviderProcesses, make);