A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(daemon): move supervisor authority records out of $TMPDIR (#1449)
Sebastian Müller26f7f1a14c3b
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor-ownership.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor-ownership.tsindex 7fbcb7620f..154be07162 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor-ownership.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor-ownership.ts@@ -9,6 +9,7 @@ import {rmSync,writeFileSync,} from "node:fs";+import { homedir } from "node:os";import { basename, dirname, join, resolve } from "node:path";import lockfile from "proper-lockfile";import { getProcessStartId } from "../../core/session-lease.js";@@ -103,8 +104,16 @@ class DaemonSupervisorAlreadyRunningError extends Error {class DaemonSupervisorOwnershipLostError extends Error {readonly code = "supervisor_generation_stale" as const;- constructor(generation: string) {- super(`Daemon supervisor generation ${generation} no longer owns its registry entry`);+ constructor(generation: string, details: { socketPath?: string; registryDir?: string } = {}) {+ const context = [+ details.socketPath ? `socket: ${details.socketPath}` : undefined,+ details.registryDir ? `registry: ${details.registryDir}` : undefined,+ ].filter((part) => part !== undefined);+ super(+ `Daemon supervisor generation ${generation} no longer owns its registry entry ` ++ `(record on disk is missing or was replaced)${context.length > 0 ? `; ${context.join("; ")}` : ""}; ` ++ "restart the daemon to recover — sessions are preserved",+ );this.name = "DaemonSupervisorOwnershipLostError";}}@@ -118,6 +127,62 @@ class DaemonShutdownAdmissionError extends Error {}}+/**+ * Owns a lease-renew loop safely: the unref()'d interval, single-flight+ * refresh dedup shared by timer-fired and direct calls, and lost-state fencing.+ */+class RenewableRegistryRecord {+ private stopped = false;+ private lost = false;+ private refreshPromise?: Promise<void>;+ private readonly refreshTimer: ReturnType<typeof setInterval>;++ constructor(+ private readonly registryDir: string,+ refreshMs: number,+ private readonly renewUnderGuard: () => void,+ private readonly createLostError: () => Error,+ ) {+ this.refreshTimer = setInterval(() => {+ void this.assertOrRenew().catch(() => undefined);+ }, refreshMs);+ this.refreshTimer.unref();+ }++ async assertOrRenew(): Promise<void> {+ if (this.stopped || this.lost) {+ throw this.createLostError();+ }+ this.refreshPromise ??= this.performRenew().finally(() => {+ this.refreshPromise = undefined;+ });+ await this.refreshPromise;+ }++ private async performRenew(): Promise<void> {+ try {+ await withDaemonSupervisorRegistryGuard(this.registryDir, () => {+ // stop() may have completed while this call waited on the guard;+ // a stopped record must never be rewritten to disk.+ if (this.stopped || this.lost) {+ throw this.createLostError();+ }+ this.renewUnderGuard();+ });+ } catch (error) {+ this.lost = true;+ clearInterval(this.refreshTimer);+ throw error;+ }+ }++ async stop(): Promise<void> {+ this.stopped = true;+ clearInterval(this.refreshTimer);+ await this.refreshPromise?.catch(() => undefined);+ }+}+class DaemonSupervisorOwnership {private released = false;@@ -129,14 +194,21 @@ class DaemonSupervisorOwnership {async assertCurrent(): Promise<void> {if (this.released) {- throw new DaemonSupervisorOwnershipLostError(this.record.generation);+ throw this.ownershipLostError();}const current = readOwnerRecord(this.ownerDirectory);if (!current || !sameOwnerRecord(current, this.record)) {- throw new DaemonSupervisorOwnershipLostError(this.record.generation);+ throw this.ownershipLostError();}}+ private ownershipLostError(): DaemonSupervisorOwnershipLostError {+ return new DaemonSupervisorOwnershipLostError(this.record.generation, {+ socketPath: this.record.socketPath,+ registryDir: this.registryDir,+ });+ }+async updatePhase(phase: DaemonSupervisorOwnerPhase): Promise<void> {if (this.released) {return;@@ -181,52 +253,44 @@ class DaemonSupervisorOwnership {class DaemonShutdownAdmission {private released = false;- private lost = false;- private refreshPromise?: Promise<void>;- private readonly refreshTimer: ReturnType<typeof setInterval>;+ private readonly renewal: RenewableRegistryRecord;constructor(private readonly record: DaemonShutdownAdmissionRecord,private readonly registryDir: string,) {- this.refreshTimer = setInterval(() => {- this.refreshPromise ??= this.assertOrRenew()- .catch(() => undefined)- .finally(() => {- this.refreshPromise = undefined;- });- }, SHUTDOWN_ADMISSION_REFRESH_MS);- this.refreshTimer.unref();+ this.renewal = new RenewableRegistryRecord(+ registryDir,+ SHUTDOWN_ADMISSION_REFRESH_MS,+ () => this.renewUnderGuard(),+ () => new DaemonShutdownAdmissionError("Daemon shutdown admission was lost"),+ );}async assertOrRenew(): Promise<void> {- if (this.released || this.lost) {+ if (this.released) {throw new DaemonShutdownAdmissionError("Daemon shutdown admission was lost");}- try {- await withDaemonSupervisorRegistryGuard(this.registryDir, () => {- const path = shutdownAdmissionPath(this.registryDir);- const current = readShutdownAdmission(path);- if (- !current ||- current.token !== this.record.token ||- current.pid !== this.record.pid ||- current.processStartId !== this.record.processStartId ||- Date.parse(current.expiresAt) <= Date.now() ||- !matchesExactProcessIdentity(this.record)- ) {- throw new DaemonShutdownAdmissionError("Daemon shutdown admission was lost");- }- const now = Date.now();- this.record.updatedAt = new Date(now).toISOString();- this.record.expiresAt = new Date(now + SHUTDOWN_ADMISSION_LEASE_MS).toISOString();- writeJsonAtomically(path, this.record);- });- } catch (error) {- this.lost = true;- clearInterval(this.refreshTimer);- throw error;+ await this.renewal.assertOrRenew();+ }++ private renewUnderGuard(): void {+ const path = shutdownAdmissionPath(this.registryDir);+ const current = readShutdownAdmission(path);+ if (+ !current ||+ current.token !== this.record.token ||+ current.pid !== this.record.pid ||+ current.processStartId !== this.record.processStartId ||+ Date.parse(current.expiresAt) <= Date.now() ||+ !matchesExactProcessIdentity(this.record)+ ) {+ throw new DaemonShutdownAdmissionError("Daemon shutdown admission was lost");}+ const now = Date.now();+ this.record.updatedAt = new Date(now).toISOString();+ this.record.expiresAt = new Date(now + SHUTDOWN_ADMISSION_LEASE_MS).toISOString();+ writeJsonAtomically(path, this.record);}async release(): Promise<void> {@@ -234,8 +298,7 @@ class DaemonShutdownAdmission {return;}this.released = true;- clearInterval(this.refreshTimer);- await this.refreshPromise;+ await this.renewal.stop();await withDaemonSupervisorRegistryGuard(this.registryDir, () => {const path = shutdownAdmissionPath(this.registryDir);const current = readShutdownAdmission(path);@@ -246,8 +309,48 @@ class DaemonShutdownAdmission {}}+/**+ * The registry is durable authority state and must be global per user so+ * ownerConflicts sees every daemon on the box; it deliberately lives outside+ * $TMPDIR (whose files macOS dirhelper deletes after 3 days) and outside the+ * per-invocation agent dir.+ */function defaultDaemonSupervisorRegistryDir(environment: NodeJS.ProcessEnv = process.env): string {- return environment[DAEMON_SUPERVISOR_REGISTRY_DIR_ENV] ?? resolve(defaultDaemonSocketDir(), "supervisor-owners");+ return environment[DAEMON_SUPERVISOR_REGISTRY_DIR_ENV] ?? join(homedir(), ".prime", "supervisor-owners");+}++/**+ * Pre-move registry location under $TMPDIR, consulted READ-ONLY while daemons+ * from before the ~/.prime move may still be running; gated off whenever the+ * registry is overridden. Remove after one release.+ */+function legacyDaemonSupervisorRegistryDir(environment: NodeJS.ProcessEnv = process.env): string | undefined {+ return environment[DAEMON_SUPERVISOR_REGISTRY_DIR_ENV]+ ? undefined+ : resolve(defaultDaemonSocketDir(), "supervisor-owners");+}++/**+ * Non-mutating legacy scan: never reclaims abandoned directories (old-build+ * daemons own that location's lifecycle) and runs without the legacy guard —+ * best-effort is acceptable because records are written rename-atomically.+ */+function readLegacyOwnersForSocket(+ legacyRegistryDir: string,+ normalizedSocketPath: string,+): DaemonSupervisorOwnerRecord[] {+ let entries: string[];+ try {+ entries = readdirSync(legacyRegistryDir);+ } catch {+ return [];+ }+ return entries+ .filter((name) => name.endsWith(".owner"))+ .flatMap((name) => {+ const owner = readOwnerRecord(resolve(legacyRegistryDir, name));+ return owner && owner.socketPath === normalizedSocketPath ? [owner] : [];+ });}async function withDaemonSupervisorRegistryGuard<T>(registryDir: string, action: () => T | Promise<T>): Promise<T> {@@ -370,9 +473,13 @@ export async function assertDaemonSupervisorOwnerCurrent(socketPath: string;},validatedFingerprint?: string,+ registryDir?: string,+ legacyRegistryDir: string | undefined = registryDir === undefined ? legacyDaemonSupervisorRegistryDir() : undefined,): Promise<string> {- const registryDir = defaultDaemonSupervisorRegistryDir();- const current = readOwnerRecord(ownerDirectoryPath(registryDir, owner.generation));+ registryDir ??= defaultDaemonSupervisorRegistryDir();+ const current =+ readOwnerRecord(ownerDirectoryPath(registryDir, owner.generation)) ??+ (legacyRegistryDir ? readOwnerRecord(ownerDirectoryPath(legacyRegistryDir, owner.generation)) : undefined);if (!current ||current.pid !== owner.pid ||@@ -380,11 +487,11 @@ export async function assertDaemonSupervisorOwnerCurrent(current.socketPath !== normalizeSocketPath(owner.socketPath) ||!isProcessAlive(current.pid)) {- throw new DaemonSupervisorOwnershipLostError(owner.generation);+ throw new DaemonSupervisorOwnershipLostError(owner.generation, { socketPath: owner.socketPath, registryDir });}const fingerprint = ownerRecordFingerprint(current);if (fingerprint !== validatedFingerprint && !isProcessIdentityAlive(current)) {- throw new DaemonSupervisorOwnershipLostError(owner.generation);+ throw new DaemonSupervisorOwnershipLostError(owner.generation, { socketPath: owner.socketPath, registryDir });}return fingerprint;}@@ -425,8 +532,10 @@ export async function isDaemonShutdownAdmissionActive(): Promise<boolean> {export async function persistDaemonStartupFenceFromOwner(socketPath: string,hello: DaemonSupervisorHelloIdentity,- registryDir: string = defaultDaemonSupervisorRegistryDir(),+ registryDir?: string,+ legacyRegistryDir: string | undefined = registryDir === undefined ? legacyDaemonSupervisorRegistryDir() : undefined,): Promise<void> {+ registryDir ??= defaultDaemonSupervisorRegistryDir();mkdirSync(registryDir, { recursive: true, mode: 0o700 });const fenceDirectory = resolve(registryDir, "startup-fences");mkdirSync(fenceDirectory, { recursive: true, mode: 0o700 });@@ -437,7 +546,14 @@ export async function persistDaemonStartupFenceFromOwner(const owner = readOwnerRecordForScope(directory, (scope) => scope.socketPath === normalizedSocketPath);return owner ? [owner] : [];});- const matchingOwners = owners.filter((owner) => owner.socketPath === normalizedSocketPath);+ let matchingOwners = owners.filter((owner) => owner.socketPath === normalizedSocketPath);+ if (matchingOwners.length === 0 && legacyRegistryDir) {+ // Stale legacy leftovers are expected; keep only records matching the+ // identity the caller already holds.+ matchingOwners = readLegacyOwnersForSocket(legacyRegistryDir, normalizedSocketPath).filter(+ (owner) => owner.token === hello.supervisorOwnerToken && owner.pid === hello.supervisorPid,+ );+ }if (matchingOwners.length === 0) {throw new Error(`Daemon supervisor owner does not match ${socketPath}`);}diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 43d550fe98..abffaf0490 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -888,7 +888,10 @@ export class DaemonSupervisor {private async assertCurrentOwnership(): Promise<void> {const ownership = this.ownership;if (!ownership) {- const error = new Error(`Daemon supervisor generation ${this.generation} no longer owns its registry entry`);+ const error = new Error(+ `Daemon supervisor generation ${this.generation} holds no registry ownership (never acquired or already released); ` ++ `socket: ${this.socketPath}; restart the daemon to recover — sessions are preserved`,+ );Object.assign(error, { code: "supervisor_generation_stale" as const });throw error;}diff --git a/packages/coding-agent/test/daemon-supervisor-ownership.test.ts b/packages/coding-agent/test/daemon-supervisor-ownership.test.tsnew file mode 100644index 0000000000..6cacc933da--- /dev/null+++ b/packages/coding-agent/test/daemon-supervisor-ownership.test.ts@@ -0,0 +1,238 @@+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import lockfile from "proper-lockfile";+import { afterEach, describe, expect, it } from "vitest";+import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";+import {+ acquireDaemonShutdownAdmission,+ acquireDaemonSupervisorOwnership,+ assertDaemonSupervisorOwnerCurrent,+ persistDaemonStartupFenceFromOwner,+} from "../src/modes/daemon/daemon-supervisor-ownership.js";++type Ownership = Awaited<ReturnType<typeof acquireDaemonSupervisorOwnership>>;++interface OwnerRecord {+ token: string;+ generation: string;+ updatedAt: string;+ [key: string]: unknown;+}++const registryDirEnv = "PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_REGISTRY_DIR";+const previousRegistryDirEnv = process.env[registryDirEnv];+const cleanupDirs: string[] = [];++afterEach(() => {+ if (previousRegistryDirEnv === undefined) {+ delete process.env[registryDirEnv];+ } else {+ process.env[registryDirEnv] = previousRegistryDirEnv;+ }+ while (cleanupDirs.length > 0) {+ const dir = cleanupDirs.pop();+ if (dir) rmSync(dir, { recursive: true, force: true });+ }+});++function createPaths(): {+ root: string;+ registryDir: string;+ socketPath: string;+ agentDir: string;+ descriptorDir: string;+} {+ const root = mkdtempSync(join(tmpdir(), "ownership-registry-"));+ cleanupDirs.push(root);+ const agentDir = join(root, "agent");+ mkdirSync(agentDir, { recursive: true });+ return {+ root,+ registryDir: join(root, "registry"),+ socketPath: join(root, "daemon.sock"),+ agentDir,+ descriptorDir: join(root, "workers"),+ };+}++async function acquire(paths: ReturnType<typeof createPaths>, generation = "registry-owner"): Promise<Ownership> {+ return acquireDaemonSupervisorOwnership({+ agentDir: paths.agentDir,+ appVersion: "test",+ descriptorDir: paths.descriptorDir,+ generation,+ registryDir: paths.registryDir,+ socketPath: paths.socketPath,+ });+}++function ownerDir(paths: ReturnType<typeof createPaths>, generation: string): string {+ return join(paths.registryDir, `${generation}.owner`);+}++function readJson(path: string): OwnerRecord {+ return JSON.parse(readFileSync(path, "utf8")) as OwnerRecord;+}++describe("daemon supervisor ownership registry", () => {+ it("finds a live pre-move owner through the legacy registry when persisting a fence", async () => {+ const paths = createPaths();+ const legacyDir = join(paths.root, "legacy-registry");+ const legacyOwner = await acquireDaemonSupervisorOwnership({+ agentDir: paths.agentDir,+ appVersion: "test",+ descriptorDir: paths.descriptorDir,+ generation: "legacy-owner",+ registryDir: legacyDir,+ socketPath: paths.socketPath,+ });+ const record = legacyOwner.record;+ expect(record.processStartId).toBeDefined();+ const hello = {+ supervisorGeneration: record.generation,+ supervisorOwnerToken: record.token,+ supervisorPid: record.pid,+ supervisorProcessStartId: record.processStartId,+ supervisorSocketPath: record.socketPath,+ };+ const legacyOwnerPath = join(legacyDir, "legacy-owner.owner", "owner.json");+ const legacyBytes = readFileSync(legacyOwnerPath, "utf8");++ await persistDaemonStartupFenceFromOwner(paths.socketPath, hello, paths.registryDir, legacyDir);++ // The fence lands in the NEW registry; the legacy record is untouched.+ expect(readdirSync(join(paths.registryDir, "startup-fences"))).toHaveLength(1);+ expect(readFileSync(legacyOwnerPath, "utf8")).toBe(legacyBytes);++ // Without a legacy dir the same scan fails: the fallback never fires for+ // an explicitly provided registry.+ await expect(persistDaemonStartupFenceFromOwner(paths.socketPath, hello, paths.registryDir)).rejects.toThrow(+ /does not match/,+ );+ await legacyOwner.release();+ });++ it("validates a pre-move owner claim through the legacy registry", async () => {+ const paths = createPaths();+ const legacyDir = join(paths.root, "legacy-registry");+ const legacyOwner = await acquireDaemonSupervisorOwnership({+ agentDir: paths.agentDir,+ appVersion: "test",+ descriptorDir: paths.descriptorDir,+ generation: "legacy-claim-owner",+ registryDir: legacyDir,+ socketPath: paths.socketPath,+ });+ const identity = {+ generation: legacyOwner.record.generation,+ pid: legacyOwner.record.pid,+ ...(legacyOwner.record.processStartId ? { processStartId: legacyOwner.record.processStartId } : {}),+ socketPath: legacyOwner.record.socketPath,+ };+ mkdirSync(paths.registryDir, { recursive: true });++ await expect(+ assertDaemonSupervisorOwnerCurrent(identity, undefined, paths.registryDir, legacyDir),+ ).resolves.toEqual(expect.any(String));++ // Without the injected legacy dir, an explicit registry never falls back.+ await expect(assertDaemonSupervisorOwnerCurrent(identity, undefined, paths.registryDir)).rejects.toMatchObject({+ code: "supervisor_generation_stale",+ });+ await legacyOwner.release();+ });++ it("legacy registry reads never reclaim abandoned legacy directories", async () => {+ const paths = createPaths();+ const legacyDir = join(paths.root, "legacy-registry");+ const abandoned = join(legacyDir, "abandoned.owner");+ mkdirSync(abandoned, { recursive: true });++ await expect(+ persistDaemonStartupFenceFromOwner(paths.socketPath, {}, paths.registryDir, legacyDir),+ ).rejects.toThrow(/does not match/);++ expect(existsSync(abandoned)).toBe(true);+ });++ it("marks ownership lost when the record is mismatched or absent", async () => {+ const paths = createPaths();+ const mismatched = await acquire(paths, "mismatched-owner");+ const mismatchedPath = join(ownerDir(paths, "mismatched-owner"), "owner.json");+ const foreign = { ...readJson(mismatchedPath), token: "successor-token" };+ writeFileSync(mismatchedPath, `${JSON.stringify(foreign, null, 2)}\n`);++ await expect(mismatched.assertCurrent()).rejects.toMatchObject({+ code: "supervisor_generation_stale",+ name: "DaemonSupervisorOwnershipLostError",+ });+ expect(readJson(mismatchedPath).token).toBe("successor-token");+ await mismatched.release();+ rmSync(ownerDir(paths, "mismatched-owner"), { recursive: true, force: true });++ const reaped = await acquire(paths, "reaped-owner");+ const reapedDir = ownerDir(paths, "reaped-owner");+ rmSync(reapedDir, { recursive: true, force: true });+ await expect(reaped.assertCurrent()).rejects.toMatchObject({ code: "supervisor_generation_stale" });+ expect(existsSync(reapedDir)).toBe(false);+ await reaped.release();+ });++ it("does not resurrect the shutdown admission when release overtakes an in-flight renew", async () => {+ const paths = createPaths();+ mkdirSync(paths.registryDir, { recursive: true, mode: 0o700 });+ process.env[registryDirEnv] = paths.registryDir;+ const admission = await acquireDaemonShutdownAdmission();+ const admissionPath = join(paths.registryDir, "shutdown-admission.json");+ expect(existsSync(admissionPath)).toBe(true);+ const dropGuard = await lockfile.lock(paths.registryDir, {+ realpath: false,+ lockfilePath: join(paths.registryDir, ".guard"),+ });+ // The direct renew is now queued behind the held guard.+ const pending = admission.assertOrRenew();+ pending.catch(() => undefined);+ const releasing = admission.release();+ await dropGuard();+ await expect(pending).rejects.toMatchObject({ code: "daemon_shutdown_in_progress" });+ await releasing;+ expect(existsSync(admissionPath)).toBe(false);+ });++ it("disambiguates never-acquired from lost-on-disk ownership errors", async () => {+ const paths = createPaths();+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype) as object, {+ ownership: undefined,+ generation: "unowned-generation",+ socketPath: paths.socketPath,+ });+ const assertCurrentOwnership = Reflect.get(supervisor, "assertCurrentOwnership") as () => Promise<void>;+ const neverAcquired = await assertCurrentOwnership+ .call(supervisor)+ .then(() => undefined)+ .catch((error: unknown) => error as Error & { code?: string });+ if (!neverAcquired) throw new Error("assertCurrentOwnership did not throw");+ expect(neverAcquired.code).toBe("supervisor_generation_stale");+ expect(neverAcquired.message).toContain("holds no registry ownership");+ expect(neverAcquired.message).toContain(paths.socketPath);+ expect(neverAcquired.message).toContain("sessions are preserved");++ const ownership = await acquire(paths);+ const ownerPath = join(ownerDir(paths, ownership.record.generation), "owner.json");+ const foreign = { ...readJson(ownerPath), token: "successor-token" };+ writeFileSync(ownerPath, `${JSON.stringify(foreign, null, 2)}\n`);+ const lostOnDisk = await ownership+ .assertCurrent()+ .then(() => undefined)+ .catch((error: unknown) => error as Error & { code?: string });+ if (!lostOnDisk) throw new Error("assertCurrent did not throw");+ expect(lostOnDisk.code).toBe("supervisor_generation_stale");+ expect(lostOnDisk.message).toContain("no longer owns its registry entry");+ expect(lostOnDisk.message).toContain(paths.socketPath);+ expect(lostOnDisk.message).toContain(paths.registryDir);+ expect(lostOnDisk.message).toContain("sessions are preserved");+ expect(lostOnDisk.message).not.toBe(neverAcquired.message);+ await ownership.release();+ });+});diff --git a/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts b/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.tsindex 48e99e71fc..6889e82776 100644--- a/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts+++ b/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts@@ -955,7 +955,10 @@ describe("ENG-4603 worker recovery convergence", () => {};expect(record.pid).toBe(process.pid);expect(record.processStartId).toBe(getProcessStartId(process.pid));- const refreshTimer = Reflect.get(first, "refreshTimer") as ReturnType<typeof setInterval> | undefined;+ const renewal = Reflect.get(first, "renewal") as object | undefined;+ const refreshTimer = renewal+ ? (Reflect.get(renewal, "refreshTimer") as ReturnType<typeof setInterval> | undefined)+ : undefined;if (!refreshTimer) throw new Error("Shutdown admission did not start its lease refresh");clearInterval(refreshTimer);let acquired = false;