A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix daemon update restart coordination (#406)
kt039eba051a93
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex 29576300c9..420c77c18a 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -7,6 +7,7 @@- Changed shell commands to use discoverable agent, schedule, package, model, session, update, doctor, and full-shutdown verbs without exposing the background daemon hierarchy ([ENG-4538](https://linear.app/primeintellect/issue/ENG-4538/standardize-bash-command-conventions-and-improve-command-discovery)).- Fixed unsupported Node versions crashing before startup by requiring Node 22.8.0 or newer and showing upgrade guidance before loading the CLI ([ENG-4260](https://linear.app/primeintellect/issue/ENG-4260/incorrect-node-version-breaks-first-launch)).- Added `@` file-path autocomplete to new-agent and reply prompts in the Agents View.+- Fixed daemon-owned updates terminating their updater before the daemon restart and session restore completed ([ENG-4606](https://linear.app/primeintellect/issue/ENG-4606/benign-error-on-prime-agent-update)).- Fixed first-launch Prime login and kept onboarding visible between team and model selection ([ENG-4658](https://linear.app/primeintellect/issue/ENG-4658/fix-onboarding-login-enter-key-and-model-selector-flicker)).- Fixed active heartbeat sessions appearing under Needs Input or Completed instead of a dedicated Heartbeats section ([ENG-4654](https://linear.app/primeintellect/issue/ENG-4654/categorize-heartbeat-sessions-as-working)).- Fixed stashed prompts being lost when leaving and reopening a session from the Agents View ([ENG-4659](https://linear.app/primeintellect/issue/ENG-4659/stashed-prompts-should-persist)).diff --git a/packages/coding-agent/src/cli/daemon-launch.ts b/packages/coding-agent/src/cli/daemon-launch.tsindex 6df80083d0..7266dcfa56 100644--- a/packages/coding-agent/src/cli/daemon-launch.ts+++ b/packages/coding-agent/src/cli/daemon-launch.ts@@ -11,7 +11,8 @@ import { spawn } from "node:child_process";import { existsSync } from "node:fs";import { resolve } from "node:path";import { appendRotatingLog, expandTildePath, getClientErrorLogPath, VERSION } from "../config.js";-import { DaemonClient } from "../modes/daemon/daemon-client.js";+import { getProcessStartId } from "../core/session-lease.js";+import { DaemonClient, type DaemonHello } from "../modes/daemon/daemon-client.js";import { DAEMON_PROTOCOL_VERSION } from "../modes/daemon/daemon-protocol.js";import type { SessionSummary } from "../modes/daemon/daemon-session-list.js";import { defaultDaemonSocketPath } from "../modes/daemon/daemon-socket.js";@@ -112,12 +113,50 @@ export class StaleDaemonError extends Error {}}-async function waitForDaemonGone(socketPath: string, timeoutMs = 5000, requireSocketCleanup = false): Promise<boolean> {+interface DaemonProcessIdentity {+ pid: number;+ processStartId?: string;+}++const PROCESS_START_ID_POLL_INTERVAL_MS = 1000;++function hasProcessIdentityExited(identity: DaemonProcessIdentity | undefined, verifyProcessStartId = true): boolean {+ if (!identity) {+ return true;+ }+ try {+ process.kill(identity.pid, 0);+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === "ESRCH";+ }+ if (!identity.processStartId || !verifyProcessStartId) {+ return false;+ }+ const currentStartId = getProcessStartId(identity.pid);+ return currentStartId !== undefined && currentStartId !== identity.processStartId;+}++async function waitForDaemonGone(+ socketPath: string,+ timeoutMs = 5000,+ requireSocketCleanup = false,+ expectedIdentity?: DaemonProcessIdentity,+): Promise<boolean> {const deadline = Date.now() + timeoutMs;+ let nextProcessStartIdPollAt = 0;+ const hasExpectedProcessExited = (forceStartIdPoll = false) => {+ const now = Date.now();+ const verifyProcessStartId = forceStartIdPoll || now >= nextProcessStartIdPollAt;+ if (verifyProcessStartId) {+ nextProcessStartIdPollAt = now + PROCESS_START_ID_POLL_INTERVAL_MS;+ }+ return hasProcessIdentityExited(expectedIdentity, verifyProcessStartId);+ };while (Date.now() < deadline) {if (!(await canConnectToDaemon(socketPath, 250)) &&- (!requireSocketCleanup || process.platform === "win32" || !existsSync(socketPath))+ (!requireSocketCleanup || process.platform === "win32" || !existsSync(socketPath)) &&+ hasExpectedProcessExited()) {return true;}@@ -126,15 +165,29 @@ async function waitForDaemonGone(socketPath: string, timeoutMs = 5000, requireSo// A daemon can exit without removing its Unix socket (for example, after a crash// during shutdown). Once the cleanup grace has elapsed, a non-listening socket// is safe for the replacement daemon's guarded startup path to reclaim.- return requireSocketCleanup && !(await canConnectToDaemon(socketPath, 250));+ return requireSocketCleanup && !(await canConnectToDaemon(socketPath, 250)) && hasExpectedProcessExited(true);}-export async function shutdownDaemonAndWait(socketPath: string, timeoutMs = 5000): Promise<boolean> {- const client = new DaemonClient(socketPath);+function processIdentityFromDaemonHello(hello: DaemonHello | undefined): DaemonProcessIdentity | undefined {+ if (!hello?.supervisorPid || !Number.isInteger(hello.supervisorPid) || hello.supervisorPid <= 0) {+ return undefined;+ }+ const processStartId = hello.supervisorProcessStartId ?? getProcessStartId(hello.supervisorPid);+ return {+ pid: hello.supervisorPid,+ ...(processStartId ? { processStartId } : {}),+ };+}++export async function shutdownConnectedDaemonAndWait(+ client: DaemonClient,+ socketPath: string,+ timeoutMs = 5000,+ hello: DaemonHello | undefined = client.hello,+): Promise<boolean> {let shutdownAccepted = false;+ const expectedIdentity = processIdentityFromDaemonHello(hello);try {- await client.connect(1000);- const hello = await client.waitForHello(2000).catch(() => undefined);const request =hello && hello.protocol.version < DAEMON_PROTOCOL_VERSION? client.requestLegacy.bind(client)@@ -146,7 +199,19 @@ export async function shutdownDaemonAndWait(socketPath: string, timeoutMs = 5000} finally {client.close();}- return waitForDaemonGone(socketPath, timeoutMs, shutdownAccepted);+ return waitForDaemonGone(socketPath, timeoutMs, shutdownAccepted, expectedIdentity);+}++export async function shutdownDaemonAndWait(socketPath: string, timeoutMs = 5000): Promise<boolean> {+ const client = new DaemonClient(socketPath);+ try {+ await client.connect(1000);+ const hello = await client.waitForHello(2000).catch(() => undefined);+ return shutdownConnectedDaemonAndWait(client, socketPath, timeoutMs, hello);+ } catch {+ client.close();+ return waitForDaemonGone(socketPath, timeoutMs);+ }}// activeSessions is undefined when the daemon is reachable but its sessions couldn'tdiff --git a/packages/coding-agent/src/cli/daemon-update-restart.ts b/packages/coding-agent/src/cli/daemon-update-restart.tsnew file mode 100644index 0000000000..7dc44ed577--- /dev/null+++ b/packages/coding-agent/src/cli/daemon-update-restart.ts@@ -0,0 +1,602 @@+import { spawn } from "node:child_process";+import { createHash, randomUUID } from "node:crypto";+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { resolve } from "node:path";+import lockfile from "proper-lockfile";+import { ENV_AGENT_DIR, SELF_UPDATE_INTERACTIVE_CHILD_ENV } from "../config.js";+import { ORPHAN_PROCESS_JOURNAL_ENV } from "../core/orphan-process-journal.js";+import { getProcessStartId, SESSION_LEASE_OWNER_ID_ENV, SESSION_LEASES_ENABLED_ENV } from "../core/session-lease.js";+import { defaultDaemonSocketDir, defaultDaemonSocketPath } from "../modes/daemon/daemon-socket.js";+import {+ DAEMON_WORKER_ACTIVE_SESSION_ID_ENV,+ DAEMON_WORKER_RECOVERY_JOURNAL_ENV,+ DAEMON_WORKER_ROLE_ENV,+ DAEMON_WORKER_SUPERVISOR_SOCKET_ENV,+ DAEMON_WORKER_TOKEN_ENV,+} from "../modes/daemon/daemon-worker-protocol.js";+import { createCliSubprocessLaunchSpec } from "./subprocess-launch.js";++export const DAEMON_UPDATE_RESTART_COORDINATOR_FLAG = "--internal-update-restart-coordinator";+export const DAEMON_UPDATE_RESTART_STATUS_FLAG = "--internal-update-restart-status";+export const DAEMON_UPDATE_RESTART_ORIGIN_FLAG = "--internal-update-restart-origin";++export type DaemonUpdateRestartPhase =+ | "starting"+ | "preparing"+ | "stopping"+ | "starting_daemon"+ | "restoring"+ | "complete"+ | "skipped"+ | "failed";++export interface DaemonUpdateRestartCounts {+ total: number;+ restored: number;+ resumed: number;+ failed: number;+}++export interface DaemonUpdateRestartFailure {+ sessionFile: string;+ message: string;+}++export interface DaemonUpdateRestartProcessIdentity {+ pid: number;+ processStartId?: string;+ supervisorGeneration?: string;+ supervisorOwnerToken?: string;+}++export interface DaemonUpdateRestartStatus {+ version: 1;+ requestId: string;+ socketPath: string;+ phase: DaemonUpdateRestartPhase;+ coordinator: DaemonUpdateRestartProcessIdentity;+ predecessor?: DaemonUpdateRestartProcessIdentity;+ successor?: DaemonUpdateRestartProcessIdentity;+ counts: DaemonUpdateRestartCounts;+ failures?: DaemonUpdateRestartFailure[];+ message?: string;+ startedAt: string;+ updatedAt: string;+ heartbeatAt?: string;+}++export interface DaemonUpdateRestartReport {+ info: string[];+ warnings: string[];+}++export interface DaemonUpdateRestartCoordinatorRecord extends DaemonUpdateRestartProcessIdentity {+ version: 1;+ token: string;+ requestId: string;+ socketPath: string;+ statusPath: string;+ createdAt: string;+}++export interface LaunchDaemonUpdateRestartCoordinatorOptions {+ socketPath: string;+ agentDir: string;+ cwd?: string;+ originActiveSessionId?: string;+ timeoutMs?: number;+}++export interface AcquireDaemonUpdateRestartCoordinatorOptions {+ requestId: string;+ socketPath: string;+ statusPath: string;+ registryDir?: string;+}++export function resolveDaemonUpdateRestartSocketPath(socketPath?: string): string {+ const selectedSocketPath = socketPath ?? defaultDaemonSocketPath();+ return process.platform === "win32" ? selectedSocketPath : resolve(selectedSocketPath);+}++const TERMINAL_PHASES: ReadonlySet<DaemonUpdateRestartPhase> = new Set(["complete", "skipped", "failed"]);+const ALL_PHASES: ReadonlySet<DaemonUpdateRestartPhase> = new Set([+ "starting",+ "preparing",+ "stopping",+ "starting_daemon",+ "restoring",+ "complete",+ "skipped",+ "failed",+]);+const DEFAULT_COORDINATOR_PROGRESS_TIMEOUT_MS = 30 * 60_000;+const COORDINATOR_LIVENESS_TIMEOUT_MS = 180_000;+const COORDINATOR_STATUS_HEARTBEAT_MS = 5000;+const COORDINATOR_REGISTRY_LOCK_STALE_MS = 5000;+const COORDINATOR_REGISTRY_LOCK_UPDATE_MS = 1000;+const COORDINATOR_REGISTRY_LOCK_RETRIES = 500;+const COORDINATOR_REGISTRY_LOCK_RETRY_MS = 10;+const PROCESS_START_ID_RECHECK_MS = 1000;++export function buildDaemonUpdateRestartReport(status: DaemonUpdateRestartStatus): DaemonUpdateRestartReport {+ const report: DaemonUpdateRestartReport = { info: [], warnings: [] };+ if (status.phase === "failed") {+ report.warnings.push(`Updated, but could not restart the daemon (${status.message ?? "unknown error"}).`);+ }+ if (status.phase !== "complete" && status.phase !== "failed") {+ return report;+ }+ if (status.counts.total > 0) {+ report.info.push(`Restored ${status.counts.restored} daemon session${status.counts.restored === 1 ? "" : "s"}`);+ }+ if (status.counts.resumed > 0) {+ report.info.push(`Resumed ${status.counts.resumed} interrupted session${status.counts.resumed === 1 ? "" : "s"}`);+ }+ if (status.counts.failed > 0) {+ report.warnings.push(+ `${status.counts.failed} daemon session${status.counts.failed === 1 ? "" : "s"} could not be restored.`,+ );+ }+ for (const failure of status.failures ?? []) {+ report.warnings.push(`Could not restore ${failure.sessionFile}: ${failure.message}`);+ }+ return report;+}++function delay(ms: number): Promise<void> {+ return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));+}++function statusLivenessId(status: DaemonUpdateRestartStatus): string {+ return status.heartbeatAt ?? status.updatedAt;+}++function socketKey(socketPath: string): string {+ const normalized = process.platform === "win32" ? socketPath.toLowerCase() : resolve(socketPath);+ return createHash("sha256").update(normalized).digest("hex");+}++function writeJsonAtomically(path: string, value: unknown): void {+ const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;+ try {+ writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });+ renameSync(tempPath, path);+ } catch (error) {+ rmSync(tempPath, { force: true });+ throw error;+ }+}++function isProcessIdentity(value: unknown): value is DaemonUpdateRestartProcessIdentity {+ if (!value || typeof value !== "object") {+ return false;+ }+ const identity = value as Partial<DaemonUpdateRestartProcessIdentity>;+ return (+ Number.isInteger(identity.pid) &&+ (identity.pid ?? 0) > 0 &&+ (identity.processStartId === undefined || typeof identity.processStartId === "string") &&+ (identity.supervisorGeneration === undefined || typeof identity.supervisorGeneration === "string") &&+ (identity.supervisorOwnerToken === undefined || typeof identity.supervisorOwnerToken === "string")+ );+}++function isCounts(value: unknown): value is DaemonUpdateRestartCounts {+ if (!value || typeof value !== "object") {+ return false;+ }+ const counts = value as Partial<DaemonUpdateRestartCounts>;+ return [counts.total, counts.restored, counts.resumed, counts.failed].every(+ (entry) => Number.isInteger(entry) && (entry ?? -1) >= 0,+ );+}++function isFailures(value: unknown): value is DaemonUpdateRestartFailure[] {+ return (+ Array.isArray(value) &&+ value.every(+ (failure) =>+ failure !== null &&+ typeof failure === "object" &&+ typeof (failure as Partial<DaemonUpdateRestartFailure>).sessionFile === "string" &&+ typeof (failure as Partial<DaemonUpdateRestartFailure>).message === "string",+ )+ );+}++function isDaemonUpdateRestartStatus(value: unknown): value is DaemonUpdateRestartStatus {+ if (!value || typeof value !== "object") {+ return false;+ }+ const status = value as Partial<DaemonUpdateRestartStatus>;+ return (+ status.version === 1 &&+ typeof status.requestId === "string" &&+ typeof status.socketPath === "string" &&+ typeof status.phase === "string" &&+ ALL_PHASES.has(status.phase as DaemonUpdateRestartPhase) &&+ isProcessIdentity(status.coordinator) &&+ (status.predecessor === undefined || isProcessIdentity(status.predecessor)) &&+ (status.successor === undefined || isProcessIdentity(status.successor)) &&+ isCounts(status.counts) &&+ (status.failures === undefined || isFailures(status.failures)) &&+ (status.message === undefined || typeof status.message === "string") &&+ typeof status.startedAt === "string" &&+ typeof status.updatedAt === "string" &&+ (status.heartbeatAt === undefined || typeof status.heartbeatAt === "string")+ );+}++export function readDaemonUpdateRestartStatus(path: string): DaemonUpdateRestartStatus | undefined {+ try {+ const value = JSON.parse(readFileSync(path, "utf8")) as unknown;+ return isDaemonUpdateRestartStatus(value) ? value : undefined;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {+ return undefined;+ }+ throw error;+ }+}++function readTerminalDaemonUpdateRestartStatus(path: string): DaemonUpdateRestartStatus | undefined {+ const status = readDaemonUpdateRestartStatus(path);+ return status && TERMINAL_PHASES.has(status.phase) ? status : undefined;+}++export class DaemonUpdateRestartStatusWriter {+ private status: DaemonUpdateRestartStatus;++ constructor(+ private readonly path: string,+ requestId: string,+ socketPath: string,+ ) {+ const now = new Date().toISOString();+ const processStartId = getProcessStartId(process.pid);+ this.status = {+ version: 1,+ requestId,+ socketPath,+ phase: "starting",+ coordinator: { pid: process.pid, ...(processStartId ? { processStartId } : {}) },+ counts: { total: 0, restored: 0, resumed: 0, failed: 0 },+ startedAt: now,+ updatedAt: now,+ heartbeatAt: now,+ };+ this.persist();+ }++ update(+ update: Partial<Omit<DaemonUpdateRestartStatus, "version" | "requestId" | "socketPath" | "coordinator">>,+ ): void {+ const now = new Date().toISOString();+ this.status = {+ ...this.status,+ ...update,+ counts: update.counts ? { ...update.counts } : this.status.counts,+ failures: update.failures+ ? update.failures.map((failure) => ({ ...failure }))+ : this.status.failures?.map((failure) => ({ ...failure })),+ updatedAt: now,+ heartbeatAt: now,+ };+ this.persist();+ }++ current(): DaemonUpdateRestartStatus {+ return {+ ...this.status,+ counts: { ...this.status.counts },+ failures: this.status.failures?.map((failure) => ({ ...failure })),+ };+ }++ touch(): void {+ this.status = { ...this.status, heartbeatAt: new Date().toISOString() };+ this.persist();+ }++ startHeartbeat(): () => void {+ const heartbeat = setInterval(() => {+ try {+ this.touch();+ } catch {+ // A later phase write will retry; otherwise the parent detects the stale heartbeat.+ }+ }, COORDINATOR_STATUS_HEARTBEAT_MS);+ heartbeat.unref();+ return () => clearInterval(heartbeat);+ }++ private persist(): void {+ writeJsonAtomically(this.path, this.status);+ }+}++function defaultCoordinatorRegistryDir(): string {+ return resolve(defaultDaemonSocketDir(), "update-restart-coordinators");+}++function coordinatorRecordPath(registryDir: string, socketPath: string): string {+ return resolve(registryDir, `${socketKey(socketPath)}.json`);+}++async function withCoordinatorRegistryGuard<T>(registryDir: string, action: () => T | Promise<T>): Promise<T> {+ mkdirSync(registryDir, { recursive: true, mode: 0o700 });+ const release = await lockfile.lock(registryDir, {+ realpath: false,+ lockfilePath: resolve(registryDir, ".guard"),+ stale: COORDINATOR_REGISTRY_LOCK_STALE_MS,+ update: COORDINATOR_REGISTRY_LOCK_UPDATE_MS,+ retries: {+ retries: COORDINATOR_REGISTRY_LOCK_RETRIES,+ factor: 1,+ minTimeout: COORDINATOR_REGISTRY_LOCK_RETRY_MS,+ maxTimeout: COORDINATOR_REGISTRY_LOCK_RETRY_MS,+ },+ });+ try {+ return await action();+ } finally {+ await release();+ }+}++function isProcessAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ } catch (error) {+ return (error as NodeJS.ErrnoException).code !== "ESRCH";+ }+ return true;+}++function matchesProcessStartId(identity: DaemonUpdateRestartProcessIdentity): boolean {+ if (!identity.processStartId) {+ return true;+ }+ const observed = getProcessStartId(identity.pid);+ return observed === undefined || observed === identity.processStartId;+}++function isProcessIdentityAlive(identity: DaemonUpdateRestartProcessIdentity): boolean {+ return isProcessAlive(identity.pid) && matchesProcessStartId(identity);+}++function createProcessIdentityLivenessCheck(identity: DaemonUpdateRestartProcessIdentity): () => boolean {+ let lastStartIdCheckAt: number | undefined;+ return () => {+ if (!isProcessAlive(identity.pid)) {+ return false;+ }+ if (!identity.processStartId) {+ return true;+ }+ const now = Date.now();+ if (lastStartIdCheckAt !== undefined && now - lastStartIdCheckAt < PROCESS_START_ID_RECHECK_MS) {+ return true;+ }+ lastStartIdCheckAt = now;+ return matchesProcessStartId(identity);+ };+}++function readCoordinatorRecord(path: string): DaemonUpdateRestartCoordinatorRecord | undefined {+ try {+ const value = JSON.parse(readFileSync(path, "utf8")) as unknown;+ if (!value || typeof value !== "object") {+ return undefined;+ }+ const record = value as Partial<DaemonUpdateRestartCoordinatorRecord>;+ if (+ record.version !== 1 ||+ typeof record.token !== "string" ||+ typeof record.requestId !== "string" ||+ typeof record.socketPath !== "string" ||+ typeof record.statusPath !== "string" ||+ typeof record.createdAt !== "string" ||+ !isProcessIdentity(record)+ ) {+ return undefined;+ }+ return record as DaemonUpdateRestartCoordinatorRecord;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {+ return undefined;+ }+ throw error;+ }+}++export class DaemonUpdateRestartCoordinatorLease {+ private released = false;++ constructor(+ readonly record: DaemonUpdateRestartCoordinatorRecord,+ private readonly registryDir: string,+ private readonly path: string,+ ) {}++ async release(): Promise<void> {+ if (this.released) {+ return;+ }+ await withCoordinatorRegistryGuard(this.registryDir, () => {+ const current = readCoordinatorRecord(this.path);+ if (current?.token === this.record.token) {+ rmSync(this.path, { force: true });+ }+ });+ this.released = true;+ }+}++export class DaemonUpdateRestartCoordinatorAlreadyRunningError extends Error {+ constructor(readonly record: DaemonUpdateRestartCoordinatorRecord) {+ super(`Another daemon update restart is already running for ${record.socketPath}`);+ this.name = "DaemonUpdateRestartCoordinatorAlreadyRunningError";+ }+}++export async function acquireDaemonUpdateRestartCoordinator(+ options: AcquireDaemonUpdateRestartCoordinatorOptions,+): Promise<DaemonUpdateRestartCoordinatorLease> {+ const registryDir = options.registryDir ?? defaultCoordinatorRegistryDir();+ const path = coordinatorRecordPath(registryDir, options.socketPath);+ const token = randomUUID();+ const processStartId = getProcessStartId(process.pid);+ const record: DaemonUpdateRestartCoordinatorRecord = {+ version: 1,+ token,+ requestId: options.requestId,+ pid: process.pid,+ ...(processStartId ? { processStartId } : {}),+ socketPath: options.socketPath,+ statusPath: options.statusPath,+ createdAt: new Date().toISOString(),+ };+ await withCoordinatorRegistryGuard(registryDir, () => {+ const current = readCoordinatorRecord(path);+ if (current && isProcessIdentityAlive(current)) {+ throw new DaemonUpdateRestartCoordinatorAlreadyRunningError(current);+ }+ rmSync(path, { force: true });+ writeJsonAtomically(path, record);+ });+ return new DaemonUpdateRestartCoordinatorLease(record, registryDir, path);+}++export async function waitForActiveDaemonUpdateRestartCoordinator(+ record: DaemonUpdateRestartCoordinatorRecord,+ progressTimeoutMs = DEFAULT_COORDINATOR_PROGRESS_TIMEOUT_MS,+): Promise<DaemonUpdateRestartStatus> {+ const coordinatorIsAlive = createProcessIdentityLivenessCheck(record);+ let observedUpdatedAt: string | undefined;+ let observedLivenessId: string | undefined;+ let lastProgressAt = Date.now();+ let lastLivenessAt = Date.now();+ while (true) {+ const status = readDaemonUpdateRestartStatus(record.statusPath);+ if (status && status.updatedAt !== observedUpdatedAt) {+ observedUpdatedAt = status.updatedAt;+ lastProgressAt = Date.now();+ }+ if (status && statusLivenessId(status) !== observedLivenessId) {+ observedLivenessId = statusLivenessId(status);+ lastLivenessAt = Date.now();+ }+ if (status && TERMINAL_PHASES.has(status.phase)) {+ return status;+ }+ if (!coordinatorIsAlive()) {+ const terminalStatus = readTerminalDaemonUpdateRestartStatus(record.statusPath);+ if (terminalStatus) {+ return terminalStatus;+ }+ throw new Error(`Active daemon update restart coordinator exited for ${record.socketPath}`);+ }+ if (Date.now() - lastLivenessAt >= COORDINATOR_LIVENESS_TIMEOUT_MS) {+ throw new Error(`Active daemon update restart coordinator stopped reporting liveness on ${record.socketPath}`);+ }+ if (Date.now() - lastProgressAt >= progressTimeoutMs) {+ throw new Error(`Timed out waiting for active daemon update restart progress on ${record.socketPath}`);+ }+ await delay(50);+ }+}++function createStatusPath(agentDir: string, socketPath: string, requestId: string): string {+ const directory = resolve(agentDir, "update-restarts");+ mkdirSync(directory, { recursive: true, mode: 0o700 });+ return resolve(directory, `${socketKey(socketPath).slice(0, 16)}-${requestId}.json`);+}++function coordinatorEnvironment(agentDir: string): NodeJS.ProcessEnv {+ const environment = { ...process.env };+ environment[ENV_AGENT_DIR] = agentDir;+ delete environment[SELF_UPDATE_INTERACTIVE_CHILD_ENV];+ delete environment[DAEMON_WORKER_ROLE_ENV];+ delete environment[DAEMON_WORKER_TOKEN_ENV];+ delete environment[DAEMON_WORKER_ACTIVE_SESSION_ID_ENV];+ delete environment[DAEMON_WORKER_RECOVERY_JOURNAL_ENV];+ delete environment[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];+ delete environment[ORPHAN_PROCESS_JOURNAL_ENV];+ delete environment[SESSION_LEASES_ENABLED_ENV];+ delete environment[SESSION_LEASE_OWNER_ID_ENV];+ return environment;+}++export async function launchDaemonUpdateRestartCoordinator(+ options: LaunchDaemonUpdateRestartCoordinatorOptions,+): Promise<DaemonUpdateRestartStatus> {+ const requestId = randomUUID();+ const agentDir = resolve(options.agentDir);+ const socketPath = resolveDaemonUpdateRestartSocketPath(options.socketPath);+ const statusPath = createStatusPath(agentDir, socketPath, requestId);+ const inheritedOrigin = process.env[DAEMON_WORKER_ACTIVE_SESSION_ID_ENV];+ const originActiveSessionId = options.originActiveSessionId ?? inheritedOrigin;+ const launch = createCliSubprocessLaunchSpec([+ "update",+ DAEMON_UPDATE_RESTART_COORDINATOR_FLAG,+ "--daemon-socket",+ socketPath,+ DAEMON_UPDATE_RESTART_STATUS_FLAG,+ statusPath,+ ...(originActiveSessionId ? [DAEMON_UPDATE_RESTART_ORIGIN_FLAG, originActiveSessionId] : []),+ ]);+ const child = spawn(launch.command, launch.args, {+ cwd: options.cwd ?? process.cwd(),+ detached: true,+ env: coordinatorEnvironment(agentDir),+ stdio: "ignore",+ });+ let launchError: Error | undefined;+ let exitDescription: string | undefined;+ child.once("error", (error) => {+ launchError = error;+ });+ child.once("exit", (code, signal) => {+ exitDescription = signal ? `signal ${signal}` : `code ${code ?? "unknown"}`;+ });+ child.unref();++ const progressTimeoutMs = options.timeoutMs ?? DEFAULT_COORDINATOR_PROGRESS_TIMEOUT_MS;+ let observedUpdatedAt: string | undefined;+ let observedLivenessId: string | undefined;+ let lastProgressAt = Date.now();+ let lastLivenessAt = Date.now();+ while (true) {+ const status = readDaemonUpdateRestartStatus(statusPath);+ if (status && status.updatedAt !== observedUpdatedAt) {+ observedUpdatedAt = status.updatedAt;+ lastProgressAt = Date.now();+ }+ if (status && statusLivenessId(status) !== observedLivenessId) {+ observedLivenessId = statusLivenessId(status);+ lastLivenessAt = Date.now();+ }+ if (status && TERMINAL_PHASES.has(status.phase)) {+ return status;+ }+ if (launchError) {+ throw launchError;+ }+ if (exitDescription) {+ const terminalStatus = readTerminalDaemonUpdateRestartStatus(statusPath);+ if (terminalStatus) {+ return terminalStatus;+ }+ throw new Error(`Daemon update restart coordinator exited with ${exitDescription}`);+ }+ if (Date.now() - lastLivenessAt >= COORDINATOR_LIVENESS_TIMEOUT_MS) {+ throw new Error(`Daemon update restart coordinator stopped reporting liveness on ${socketPath}`);+ }+ if (Date.now() - lastProgressAt >= progressTimeoutMs) {+ throw new Error(`Timed out waiting for daemon update restart progress on ${socketPath}`);+ }+ await delay(50);+ }+}diff --git a/packages/coding-agent/src/cli/public-command.ts b/packages/coding-agent/src/cli/public-command.tsindex 2f561af720..a0b476cfe3 100644--- a/packages/coding-agent/src/cli/public-command.ts+++ b/packages/coding-agent/src/cli/public-command.ts@@ -1,5 +1,5 @@import chalk from "chalk";-import { APP_NAME } from "../config.js";+import { APP_NAME, SELF_UPDATE_INTERACTIVE_CHILD_ENV } from "../config.js";import { handlePackageCommand, isSelfUpdateSource } from "../package-manager-cli.js";import { INTERNAL_RUNTIME_COMMAND_MARKER, parseArgs } from "./args.js";import {@@ -14,6 +14,7 @@ import {} from "./command-registry.js";import { handleDaemonCommand } from "./daemon-command.js";import { runPs, runReap, runShutdownAll } from "./daemon-ps.js";+import { DAEMON_UPDATE_RESTART_COORDINATOR_FLAG } from "./daemon-update-restart.js";export interface PublicCommandResult {handled: boolean;@@ -49,6 +50,14 @@ async function runPublicCommand(args: string[]): Promise<PublicCommandResult> {if (!PUBLIC_COMMAND_NAMES.has(command)) {return continueWith(args);}+ if (command === "update" && process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] === "1") {+ await handlePackageCommand(args);+ return HANDLED;+ }+ if (command === "update" && args.includes(DAEMON_UPDATE_RESTART_COORDINATOR_FLAG)) {+ await handlePackageCommand(args);+ return HANDLED;+ }const separatorIndex = args.indexOf("--");const helpIndex = args.findIndex(diff --git a/packages/coding-agent/src/config.ts b/packages/coding-agent/src/config.tsindex 8eb03159ae..b94452ec21 100644--- a/packages/coding-agent/src/config.ts+++ b/packages/coding-agent/src/config.ts@@ -560,7 +560,13 @@ export function getDaemonLogPath(socketPath: string): string {return join(getLogsDir(), `${basename(socketPath)}.${hash}.log`);}-export function getDaemonUpdateRestartManifestPath(agentDir: string = getAgentDir()): string {+export function getDaemonUpdateRestartManifestPath(socketPath: string, agentDir: string = getAgentDir()): string {+ const normalizedSocketPath = process.platform === "win32" ? socketPath.toLowerCase() : resolve(socketPath);+ const socketHash = createHash("sha256").update(normalizedSocketPath).digest("hex");+ return join(agentDir, "daemon-update-restarts", `${socketHash}.json`);+}++export function getLegacyDaemonUpdateRestartManifestPath(agentDir: string = getAgentDir()): string {return join(agentDir, "daemon-update-restart.json");}diff --git a/packages/coding-agent/src/core/session-lease.ts b/packages/coding-agent/src/core/session-lease.tsindex 67ca5df058..6c4e2975cf 100644--- a/packages/coding-agent/src/core/session-lease.ts+++ b/packages/coding-agent/src/core/session-lease.ts@@ -110,7 +110,40 @@ function isProcessAlive(pid: number): boolean {}}+type ProcessQuery = (command: string, args: string[]) => string;++function runProcessQuery(command: string, args: string[]): string {+ return execFileSync(command, args, {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ });+}++export function getWindowsProcessStartId(pid: number, query: ProcessQuery = runProcessQuery): string | undefined {+ if (!Number.isInteger(pid) || pid <= 0) {+ return undefined;+ }+ try {+ const startTicks = query("powershell.exe", [+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ `([System.Diagnostics.Process]::GetProcessById(${pid})).StartTime.ToUniversalTime().Ticks`,+ ]).trim();+ return /^\d+$/.test(startTicks) ? `win:${startTicks}` : undefined;+ } catch {+ return undefined;+ }+}+export function getProcessStartId(pid: number): string | undefined {+ if (!Number.isInteger(pid) || pid <= 0) {+ return undefined;+ }+ if (process.platform === "win32") {+ return getWindowsProcessStartId(pid);+ }try {const stat = readFileSync(`/proc/${pid}/stat`, "utf8");const commandEnd = stat.lastIndexOf(")");@@ -123,17 +156,23 @@ export function getProcessStartId(pid: number): string | undefined {// Fall through to the portable process listing used on macOS and BSD.}try {- const startTime = execFileSync("ps", ["-p", String(pid), "-o", "lstart="], {- encoding: "utf8",- stdio: ["ignore", "pipe", "ignore"],- }).trim();+ const startTime = runProcessQuery("ps", ["-p", String(pid), "-o", "lstart="]).trim();return startTime ? `ps:${startTime}` : undefined;} catch {return undefined;}}-const CURRENT_PROCESS_START_ID = getProcessStartId(process.pid);+let currentProcessStartId: string | undefined;+let currentProcessStartIdRead = false;++function getCurrentProcessStartId(): string | undefined {+ if (!currentProcessStartIdRead) {+ currentProcessStartId = getProcessStartId(process.pid);+ currentProcessStartIdRead = true;+ }+ return currentProcessStartId;+}function isLeaseOwnerAlive(owner: SessionLeaseOwner): boolean {if (!isProcessAlive(owner.pid)) {@@ -211,7 +250,7 @@ export function acquireSessionLease(version: 1,token,pid: process.pid,- processStartId: CURRENT_PROCESS_START_ID,+ processStartId: getCurrentProcessStartId(),activeSessionId: environment[SESSION_LEASE_OWNER_ID_ENV],sessionPath: canonicalPath,createdAt: new Date().toISOString(),diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.tsindex 293a8278da..6c09153885 100644--- a/packages/coding-agent/src/main.ts+++ b/packages/coding-agent/src/main.ts@@ -1415,6 +1415,7 @@ export async function main(args: string[], options?: MainOptions) {const interactiveMode = new InteractiveMode({agentConnection,+ daemonSocketPath,uiServices: daemonUiServices,promptStashStore,promptStashSessionId: summary.sessionId,diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.tsindex bd748a576a..18218af6d8 100644--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts@@ -379,6 +379,7 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promiseconst uiServices = await resolveAgentsViewSessionUiServices(options, opened.summary);const interactiveMode = new InteractiveMode({agentConnection: opened.connection,+ daemonSocketPath: options.socketPath,uiServices,promptStashStore,promptStashSessionId: opened.summary.sessionId,diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex b11c60321e..2c2969fbbc 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -207,6 +207,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["steer","follow_up","restore_next_turn",+ "append_custom_message","resume_queue","send_message","agent_messages_status",@@ -2843,6 +2844,12 @@ export class AgentDaemon {return success(command.id, "restore_next_turn");}+ case "append_custom_message": {+ const state = this.getSessionState(command.activeSessionId);+ await state.runtime.session.sendCustomMessage(command.message);+ return success(command.id, "append_custom_message");+ }+case "resume_queue": {const state = this.getSessionState(command.activeSessionId);let checkedStart = false;@@ -4173,7 +4180,7 @@ export class AgentDaemon {}private writeUpdateRestartManifest(manifest: DaemonUpdateRestartManifest): void {- const path = getDaemonUpdateRestartManifestPath(this.agentDir);+ const path = getDaemonUpdateRestartManifestPath(this.socketPath, this.agentDir);mkdirSync(dirname(path), { recursive: true });writeFileSync(path, `${JSON.stringify(manifest)}\n`);}diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex 689293cc6f..0090c211dc 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -335,6 +335,12 @@ export type DaemonCommand =prefixMessages?: CustomMessage[];}| { id?: string; type: "restore_next_turn"; activeSessionId: string; messages: CustomMessage[] }+ | {+ id?: string;+ type: "append_custom_message";+ activeSessionId: string;+ message: Pick<CustomMessage, "customType" | "content" | "display" | "details">;+ }| { id?: string; type: "resume_queue"; activeSessionId: string }| {id?: string;diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex b33454def4..361d9195c6 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -115,6 +115,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["steer","follow_up","restore_next_turn",+ "append_custom_message","resume_queue","send_message","agent_messages_status",@@ -3128,7 +3129,7 @@ export class DaemonSupervisor {if (!agentDir) {throw new Error("Daemon supervisor config is missing agentDir");}- const path = getDaemonUpdateRestartManifestPath(agentDir);+ const path = getDaemonUpdateRestartManifestPath(this.socketPath, agentDir);mkdirSync(dirname(path), { recursive: true, mode: 0o700 });const tempPath = `${path}.${process.pid}.tmp`;writeFileSync(tempPath, `${JSON.stringify(manifest)}\n`, { mode: 0o600 });diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex a96068bf54..dd9b9e71b0 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -49,6 +49,11 @@ import {visibleWidth,} from "@earendil-works/pi-tui";import { spawn, spawnSync } from "child_process";+import {+ buildDaemonUpdateRestartReport,+ launchDaemonUpdateRestartCoordinator,+ resolveDaemonUpdateRestartSocketPath,+} from "../../cli/daemon-update-restart.js";import {APP_NAME,APP_TITLE,@@ -565,9 +570,10 @@ function getPayloadWorkingIndicatorOptions(};}-function updateArgsIncludeSelf(args: readonly string[]): boolean {+export function updateArgsIncludeSelf(args: readonly string[]): boolean {let selfFlag = false;let extensionsOnlyFlag = false;+ let positional: string | undefined;for (let index = 0; index < args.length; index++) {const arg = args[index];if (arg === "--self") {@@ -577,6 +583,10 @@ function updateArgsIncludeSelf(args: readonly string[]): boolean {} else if (arg === "--extension") {extensionsOnlyFlag = true;index++;+ } else if (arg === "--daemon-socket") {+ index++;+ } else if (arg && !arg.startsWith("-") && positional === undefined) {+ positional = arg;}}if (selfFlag) {@@ -585,7 +595,6 @@ function updateArgsIncludeSelf(args: readonly string[]): boolean {if (extensionsOnlyFlag) {return false;}- const positional = args.find((arg) => !arg.startsWith("-"));if (!positional) {return true;}@@ -610,6 +619,18 @@ export function buildUpdateRelaunchArgs(args: readonly string[], sessionFile: streturn relaunchArgs;}+export function buildUpdateChildArgs(args: readonly string[], daemonSocketPath: string): string[] {+ return args.includes("--daemon-socket") ? [...args] : [...args, "--daemon-socket", daemonSocketPath];+}++export function resolveInteractiveUpdateDaemonSocketPath(+ args: readonly string[],+ activeDaemonSocketPath: string,+): string {+ const socketFlagIndex = args.indexOf("--daemon-socket");+ return socketFlagIndex === -1 ? activeDaemonSocketPath : (args[socketFlagIndex + 1] ?? activeDaemonSocketPath);+}+/*** Options for InteractiveMode initialization.*/@@ -630,6 +651,8 @@ export interface InteractiveModeOptions {verbose?: boolean;/** Agent execution boundary. InteractiveMode never talks directly to AgentSession for core execution. */agentConnection: AgentConnection;+ /** Exact daemon socket to preserve across an interactive self-update restart. */+ daemonSocketPath?: string;/*** Local-only host for in-process extension binding and callback-bearing session operations.* This must remain optional adapter glue, not a generic execution dependency.@@ -7872,16 +7895,25 @@ export class InteractiveMode {const updateArgs = parseCommandArgs(args);const includesSelf = updateArgsIncludeSelf(updateArgs);const updateCwd = this.getCurrentCwd();+ const daemonSocketPath = resolveInteractiveUpdateDaemonSocketPath(+ updateArgs,+ resolveDaemonUpdateRestartSocketPath(this.options.daemonSocketPath),+ );+ const updateChildArgs = includesSelf ? buildUpdateChildArgs(updateArgs, daemonSocketPath) : updateArgs;this.stopWorkingLoader();await this.ui.terminal.drainInput(1000).catch(() => undefined);this.ui.stop();const updateEnv = includesSelf ? { ...process.env, [SELF_UPDATE_INTERACTIVE_CHILD_ENV]: "1" } : process.env;- const updateResult = spawnSync(process.execPath, [...process.execArgv, entrypoint, "update", ...updateArgs], {- stdio: "inherit",- cwd: updateCwd,- env: updateEnv,- });+ const updateResult = spawnSync(+ process.execPath,+ [...process.execArgv, entrypoint, "update", ...updateChildArgs],+ {+ stdio: "inherit",+ cwd: updateCwd,+ env: updateEnv,+ },+ );const updateExitCode = updateResult.status ?? (updateResult.signal ? 1 : 0);const selfUpdateNotAttempted =includesSelf && !updateResult.error && updateExitCode === SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE;@@ -7906,6 +7938,27 @@ export class InteractiveMode {} catch {// The update already completed; do not block relaunch on local teardown.}+ if (!updateResult.error && updateExitCode === 0) {+ try {+ const status = await launchDaemonUpdateRestartCoordinator({+ socketPath: daemonSocketPath,+ agentDir: getAgentDir(),+ cwd: updateCwd,+ originActiveSessionId: this.connectionState?.activeSessionId,+ });+ const report = buildDaemonUpdateRestartReport(status);+ for (const message of report.info) {+ console.log(message);+ }+ for (const warning of report.warnings) {+ console.error(`Warning: ${warning}`);+ }+ } catch (error: unknown) {+ console.error(+ `Warning: updated, but could not coordinate the daemon restart (${error instanceof Error ? error.message : String(error)}).`,+ );+ }+ }const relaunchResult = spawnSync(process.execPath, [...process.execArgv, entrypoint, ...relaunchArgs], {stdio: "inherit",cwd: updateCwd,diff --git a/packages/coding-agent/src/package-manager-cli.ts b/packages/coding-agent/src/package-manager-cli.tsindex 3e133230df..5df6a7aae8 100644--- a/packages/coding-agent/src/package-manager-cli.ts+++ b/packages/coding-agent/src/package-manager-cli.ts@@ -1,6 +1,7 @@import chalk from "chalk";import { spawn } from "child_process";import { readFileSync, rmSync, statSync } from "fs";+import { resolve, sep } from "path";import { selectConfig } from "./cli/config-selector.js";import {ensureInteractiveDaemonRunning,@@ -8,14 +9,30 @@ import {isSessionBusy,probeRunningDaemonSessions,type RunningDaemonProbe,- shutdownDaemonAndWait,+ shutdownConnectedDaemonAndWait,} from "./cli/daemon-launch.js";import { confirmDaemonSessionLoss, type DaemonSessionLossCopy, pluralizeSessions } from "./cli/daemon-stop-confirm.js";+import {+ acquireDaemonUpdateRestartCoordinator,+ buildDaemonUpdateRestartReport,+ DAEMON_UPDATE_RESTART_COORDINATOR_FLAG,+ DAEMON_UPDATE_RESTART_ORIGIN_FLAG,+ DAEMON_UPDATE_RESTART_STATUS_FLAG,+ DaemonUpdateRestartCoordinatorAlreadyRunningError,+ type DaemonUpdateRestartCounts,+ type DaemonUpdateRestartFailure,+ type DaemonUpdateRestartProcessIdentity,+ type DaemonUpdateRestartStatus,+ DaemonUpdateRestartStatusWriter,+ launchDaemonUpdateRestartCoordinator,+ waitForActiveDaemonUpdateRestartCoordinator,+} from "./cli/daemon-update-restart.js";import {APP_NAME,CONFIG_DIR_NAME,getAgentDir,getDaemonUpdateRestartManifestPath,+ getLegacyDaemonUpdateRestartManifestPath,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,PACKAGE_NAME,@@ -29,7 +46,7 @@ import type { AgentSessionRuntimeMetadata } from "./core/agent-session-runtime.jimport type { CustomMessage } from "./core/messages.js";import { DefaultPackageManager } from "./core/package-manager.js";import { SettingsManager } from "./core/settings-manager.js";-import { DaemonClient } from "./modes/daemon/daemon-client.js";+import { DaemonClient, type DaemonHello } from "./modes/daemon/daemon-client.js";import {DAEMON_PROTOCOL_VERSION,type DaemonUpdateRestartManifest,@@ -38,12 +55,22 @@ import {isUnknownDaemonCommandError,} from "./modes/daemon/daemon-protocol.js";import { defaultDaemonSocketPath } from "./modes/daemon/daemon-socket.js";-import { persistDaemonStartupFenceFromOwner } from "./modes/daemon/daemon-supervisor-ownership.js";+import {+ acquireDaemonShutdownAdmission,+ persistDaemonStartupFenceFromOwner,+ waitForDaemonStartupFence,+} from "./modes/daemon/daemon-supervisor-ownership.js";+import {+ DAEMON_WORKER_ACTIVE_SESSION_ID_ENV,+ DAEMON_WORKER_SUPERVISOR_SOCKET_ENV,+} from "./modes/daemon/daemon-worker-protocol.js";import { shouldUseWindowsShell } from "./utils/child-process.js";import { getLatestPiRelease, isNewerPackageVersion } from "./utils/version-check.js";export type PackageCommand = "install" | "remove" | "update" | "list";+const UPDATE_RESTART_PREDECESSOR_FENCE_TIMEOUT_MS = 60_000;+type UpdateTarget = { type: "all" } | { type: "self" } | { type: "extensions"; source?: string };export function isSelfUpdateSource(source: string): boolean {@@ -57,6 +84,10 @@ interface PackageCommandOptions {local: boolean;force: boolean;help: boolean;+ daemonSocketPath?: string;+ restartCoordinator: boolean;+ restartStatusPath?: string;+ restartOriginActiveSessionId?: string;invalidOption?: string;invalidArgument?: string;missingOptionValue?: string;@@ -132,6 +163,7 @@ Options:--extensions Update installed packages only--extension <source> Update one package only--force Reinstall ${APP_NAME} even if the current version is latest+ --daemon-socket <path> Restart the daemon listening on this exact socketCommands:${APP_NAME} update Update ${APP_NAME}@@ -173,6 +205,10 @@ function parsePackageCommand(args: string[]): PackageCommandOptions | undefinedlet selfFlag = false;let extensionsFlag = false;let extensionFlagSource: string | undefined;+ let daemonSocketPath: string | undefined;+ let restartCoordinator = false;+ let restartStatusPath: string | undefined;+ let restartOriginActiveSessionId: string | undefined;for (let index = 0; index < rest.length; index++) {const arg = rest[index];@@ -217,6 +253,52 @@ function parsePackageCommand(args: string[]): PackageCommandOptions | undefinedcontinue;}+ if (arg === "--daemon-socket") {+ if (command !== "update") {+ invalidOption = invalidOption ?? arg;+ continue;+ }+ const value = rest[index + 1];+ if (!value || value.startsWith("-")) {+ missingOptionValue = missingOptionValue ?? arg;+ } else if (daemonSocketPath) {+ conflictingOptions = conflictingOptions ?? "--daemon-socket can only be provided once";+ index++;+ } else {+ daemonSocketPath = value;+ index++;+ }+ continue;+ }++ if (arg === DAEMON_UPDATE_RESTART_COORDINATOR_FLAG) {+ if (command === "update") {+ restartCoordinator = true;+ } else {+ invalidOption = invalidOption ?? arg;+ }+ continue;+ }++ if (arg === DAEMON_UPDATE_RESTART_STATUS_FLAG || arg === DAEMON_UPDATE_RESTART_ORIGIN_FLAG) {+ if (command !== "update") {+ invalidOption = invalidOption ?? arg;+ continue;+ }+ const value = rest[index + 1];+ if (!value || value.startsWith("-")) {+ missingOptionValue = missingOptionValue ?? arg;+ continue;+ }+ if (arg === DAEMON_UPDATE_RESTART_STATUS_FLAG) {+ restartStatusPath = value;+ } else {+ restartOriginActiveSessionId = value;+ }+ index++;+ continue;+ }+if (arg === "--extension") {if (command !== "update") {invalidOption = invalidOption ?? arg;@@ -287,6 +369,10 @@ function parsePackageCommand(args: string[]): PackageCommandOptions | undefinedlocal,force,help,+ daemonSocketPath,+ restartCoordinator,+ restartStatusPath,+ restartOriginActiveSessionId,invalidOption,invalidArgument,missingOptionValue,@@ -302,6 +388,20 @@ function updateTargetIncludesExtensions(target: UpdateTarget): boolean {return target.type === "all" || target.type === "extensions";}+export function resolveUpdateDaemonSocketPath(explicitSocketPath?: string): string {+ return explicitSocketPath ?? process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] ?? defaultDaemonSocketPath();+}++function reportDaemonUpdateRestartStatus(status: DaemonUpdateRestartStatus): void {+ const report = buildDaemonUpdateRestartReport(status);+ for (const message of report.info) {+ console.log(chalk.green(message));+ }+ for (const warning of report.warnings) {+ console.error(chalk.yellow(`Warning: ${warning}`));+ }+}+function printSelfUpdateUnavailable(npmCommand?: string[],updateSpec = PACKAGE_NAME,@@ -652,35 +752,49 @@ function parseDaemonUpdateRestartManifest(value: unknown): DaemonUpdateRestartMa};}-function clearPreparedDaemonUpdateRestartManifest(agentDir: string): void {- try {- rmSync(getDaemonUpdateRestartManifestPath(agentDir), { force: true });- } catch {- // Best effort only; the mtime guard below prevents stale fallback use.+function clearPreparedDaemonUpdateRestartManifest(socketPath: string, agentDir: string): void {+ for (const manifestPath of [+ getDaemonUpdateRestartManifestPath(socketPath, agentDir),+ getLegacyDaemonUpdateRestartManifestPath(agentDir),+ ]) {+ try {+ rmSync(manifestPath, { force: true });+ } catch {+ // Best effort only; the mtime guard below prevents stale fallback use.+ }}}function readPreparedDaemonUpdateRestartManifest(+ socketPath: string,agentDir: string,notBeforeMs?: number,): DaemonUpdateRestartManifest | undefined {- const manifestPath = getDaemonUpdateRestartManifestPath(agentDir);- let modifiedAt: number;- try {- modifiedAt = statSync(manifestPath).mtimeMs;- } catch {- return undefined;- }- if (notBeforeMs !== undefined && modifiedAt < notBeforeMs - 1000) {- return undefined;+ for (const manifestPath of [+ getDaemonUpdateRestartManifestPath(socketPath, agentDir),+ getLegacyDaemonUpdateRestartManifestPath(agentDir),+ ]) {+ let modifiedAt: number;+ try {+ modifiedAt = statSync(manifestPath).mtimeMs;+ } catch {+ continue;+ }+ if (notBeforeMs !== undefined && modifiedAt < notBeforeMs - 1000) {+ continue;+ }+ const parsed = JSON.parse(readFileSync(manifestPath, "utf-8")) as unknown;+ return parseDaemonUpdateRestartManifest(parsed);}- const parsed = JSON.parse(readFileSync(manifestPath, "utf-8")) as unknown;- return parseDaemonUpdateRestartManifest(parsed);+ return undefined;}-function tryReadPreparedDaemonUpdateRestartManifest(agentDir: string): DaemonUpdateRestartManifest | undefined {+function tryReadPreparedDaemonUpdateRestartManifest(+ socketPath: string,+ agentDir: string,+): DaemonUpdateRestartManifest | undefined {try {- return readPreparedDaemonUpdateRestartManifest(agentDir);+ return readPreparedDaemonUpdateRestartManifest(socketPath, agentDir);} catch {return undefined;}@@ -719,13 +833,13 @@ function hasFixedDaemonSupervisorOwnerIdentity(value: unknown): value is FixedDa);}-export async function prepareDaemonUpdateRestart(+async function prepareConnectedDaemonUpdateRestart(+ client: DaemonClient,socketPath: string,agentDir: string,+ hello: DaemonHello | undefined,): Promise<DaemonUpdateRestartManifest> {- const pendingManifest = tryReadPreparedDaemonUpdateRestartManifest(agentDir);- const client = new DaemonClient(socketPath);- let connected = false;+ const pendingManifest = tryReadPreparedDaemonUpdateRestartManifest(socketPath, agentDir);let startedAt: number | undefined;let fixedOwnerIdentity: FixedDaemonSupervisorOwnerIdentity | undefined;let fencePersistenceStarted = false;@@ -741,9 +855,6 @@ export async function prepareDaemonUpdateRestart(await persistDaemonStartupFenceFromOwner(socketPath, fixedOwnerIdentity);};try {- await client.connect(1000);- connected = true;- const hello = await client.waitForHello(2000).catch(() => undefined);if (hasFixedDaemonSupervisorOwnerIdentity(hello)) {fixedOwnerIdentity = hello;}@@ -757,7 +868,7 @@ export async function prepareDaemonUpdateRestart(return pendingManifest;}}- clearPreparedDaemonUpdateRestartManifest(agentDir);+ clearPreparedDaemonUpdateRestartManifest(socketPath, agentDir);startedAt = Date.now();const response = useLegacyProtocol? await client.requestLegacy({ type: "prepare_update_restart" }, 120000)@@ -773,12 +884,29 @@ export async function prepareDaemonUpdateRestart(throw error;}if (startedAt !== undefined) {- const fallback = readPreparedDaemonUpdateRestartManifest(agentDir, startedAt);+ const fallback = readPreparedDaemonUpdateRestartManifest(socketPath, agentDir, startedAt);if (fallback) {await persistPreparedRestartFence();return fallback;}}+ throw error;+ }+}++export async function prepareDaemonUpdateRestart(+ socketPath: string,+ agentDir: string,+): Promise<DaemonUpdateRestartManifest> {+ const pendingManifest = tryReadPreparedDaemonUpdateRestartManifest(socketPath, agentDir);+ const client = new DaemonClient(socketPath);+ let connected = false;+ try {+ await client.connect(1000);+ connected = true;+ const hello = await client.waitForHello(2000).catch(() => undefined);+ return await prepareConnectedDaemonUpdateRestart(client, socketPath, agentDir, hello);+ } catch (error) {if (!connected && pendingManifest && pendingManifest.sessions.length > 0) {return pendingManifest;}@@ -818,6 +946,11 @@ async function restoreNextTurnMessages(interface RestoreDaemonUpdateRestartSessionResult {restored: boolean;resumed: boolean;+ failureMessage?: string;+}++interface RestoreDaemonUpdateRestartResult extends DaemonUpdateRestartCounts {+ failures: DaemonUpdateRestartFailure[];}function remapDaemonUpdateRestartRuntimeMetadata(@@ -845,6 +978,7 @@ async function restoreDaemonUpdateRestartSession(client: DaemonClient,session: DaemonUpdateRestartSession,restoredActiveSessionIds: Map<string, string>,+ restartOriginActiveSessionId?: string,): Promise<RestoreDaemonUpdateRestartSessionResult> {const runtimeMetadata = remapDaemonUpdateRestartRuntimeMetadata(session, restoredActiveSessionIds);const createResponse = await client.request(@@ -859,10 +993,40 @@ async function restoreDaemonUpdateRestartSession();if (!createResponse.success) {console.error(chalk.yellow(`Warning: could not restore ${session.sessionFile}: ${createResponse.error}`));- return { restored: false, resumed: false };+ return { restored: false, resumed: false, failureMessage: createResponse.error };}const activeSessionId = readCreatedActiveSessionId(createResponse.data);restoredActiveSessionIds.set(session.activeSessionId, activeSessionId);+ if (session.activeSessionId === restartOriginActiveSessionId) {+ try {+ const noticeResponse = await client.request(+ {+ type: "append_custom_message",+ activeSessionId,+ message: {+ customType: "prime-agent.update_complete",+ content: `Prime Agent updated to v${VERSION}. This daemon session was restored after the update.`,+ display: true,+ details: { version: VERSION },+ },+ },+ 30000,+ );+ if (!noticeResponse.success) {+ console.error(+ chalk.yellow(+ `Warning: could not record update completion in ${session.sessionFile}: ${noticeResponse.error}`,+ ),+ );+ }+ } catch (error: unknown) {+ console.error(+ chalk.yellow(+ `Warning: could not record update completion in ${session.sessionFile}: ${formatUnknownError(error)}`,+ ),+ );+ }+ }const acceptedPrompt = session.queue.acceptedPrompt;if (!session.shouldResume) {await restoreNextTurnMessages(client, activeSessionId, session.sessionFile, session.queue.nextTurn);@@ -984,30 +1148,54 @@ async function restoreDaemonUpdateRestartSession(return { restored: true, resumed: resumedSession };}-async function restoreDaemonUpdateRestart(socketPath: string, manifest: DaemonUpdateRestartManifest): Promise<void> {+async function restoreDaemonUpdateRestart(+ socketPath: string,+ manifest: DaemonUpdateRestartManifest,+ restartOriginActiveSessionId?: string,+ onProgress?: (progress: RestoreDaemonUpdateRestartResult) => void,+): Promise<RestoreDaemonUpdateRestartResult> {+ const restoredActiveSessionIds = new Map<string, string>();if (manifest.sessions.length === 0) {- return;+ return { total: 0, restored: 0, resumed: 0, failed: 0, failures: [] };}const client = new DaemonClient(socketPath);let restored = 0;let resumed = 0;- const restoredActiveSessionIds = new Map<string, string>();+ const failures: DaemonUpdateRestartFailure[] = [];try {await client.connect(10000);for (const session of manifest.sessions) {try {- const result = await restoreDaemonUpdateRestartSession(client, session, restoredActiveSessionIds);+ const result = await restoreDaemonUpdateRestartSession(+ client,+ session,+ restoredActiveSessionIds,+ restartOriginActiveSessionId,+ );if (result.restored) {restored++;}if (result.resumed) {resumed++;}+ if (!result.restored) {+ failures.push({+ sessionFile: session.sessionFile,+ message: result.failureMessage ?? "unknown restore error",+ });+ }} catch (error: unknown) {- console.error(- chalk.yellow(`Warning: could not restore ${session.sessionFile}: ${formatUnknownError(error)}`),- );+ const message = formatUnknownError(error);+ console.error(chalk.yellow(`Warning: could not restore ${session.sessionFile}: ${message}`));+ failures.push({ sessionFile: session.sessionFile, message });}+ onProgress?.({+ total: manifest.sessions.length,+ restored,+ resumed,+ failed: failures.length,+ failures: [...failures],+ });}} finally {client.close();@@ -1016,89 +1204,235 @@ async function restoreDaemonUpdateRestart(socketPath: string, manifest: DaemonUpif (resumed > 0) {console.log(chalk.green(`Resumed ${resumed} interrupted session${resumed === 1 ? "" : "s"}`));}+ return {+ total: manifest.sessions.length,+ restored,+ resumed,+ failed: manifest.sessions.length - restored,+ failures,+ };}function formatUnknownError(error: unknown): string {return error instanceof Error ? error.message : String(error);}-async function tryRestoreDaemonUpdateRestart(- socketPath: string,- agentDir: string,- manifest: DaemonUpdateRestartManifest | undefined,- failureContext: string,-): Promise<boolean> {- if (!manifest) {- return false;+function processIdentityFromDaemonHello(+ hello: DaemonHello | undefined,+): DaemonUpdateRestartProcessIdentity | undefined {+ if (!hello?.supervisorPid || !Number.isInteger(hello.supervisorPid) || hello.supervisorPid <= 0) {+ return undefined;}- try {- await restoreDaemonUpdateRestart(socketPath, manifest);- clearPreparedDaemonUpdateRestartManifest(agentDir);- return true;- } catch (error: unknown) {- console.error(- chalk.yellow(`Warning: could not restore agent sessions ${failureContext}: ${formatUnknownError(error)}`),+ return {+ pid: hello.supervisorPid,+ ...(hello.supervisorProcessStartId ? { processStartId: hello.supervisorProcessStartId } : {}),+ ...(hello.supervisorGeneration ? { supervisorGeneration: hello.supervisorGeneration } : {}),+ ...(hello.supervisorOwnerToken ? { supervisorOwnerToken: hello.supervisorOwnerToken } : {}),+ };+}++function normalizedSocketPath(socketPath: string): string {+ return process.platform === "win32" ? socketPath.toLowerCase() : resolve(socketPath);+}++function validateReplacementDaemon(+ socketPath: string,+ hello: DaemonHello,+ predecessor: DaemonUpdateRestartProcessIdentity | undefined,+): DaemonUpdateRestartProcessIdentity {+ if (hello.protocol.version !== DAEMON_PROTOCOL_VERSION || hello.appVersion !== VERSION) {+ throw new Error(+ `Replacement daemon is v${hello.appVersion}/proto${hello.protocol.version}, expected v${VERSION}/proto${DAEMON_PROTOCOL_VERSION}`,);- return false;}+ if (+ !hello.supervisorSocketPath ||+ normalizedSocketPath(hello.supervisorSocketPath) !== normalizedSocketPath(socketPath)+ ) {+ throw new Error(`Replacement daemon identity does not match ${socketPath}`);+ }+ const successor = processIdentityFromDaemonHello(hello);+ if (!successor?.supervisorGeneration || !successor.supervisorOwnerToken) {+ throw new Error(`Replacement daemon on ${socketPath} did not provide an identity fence`);+ }+ if (+ predecessor &&+ ((predecessor.supervisorGeneration !== undefined &&+ successor.supervisorGeneration === predecessor.supervisorGeneration) ||+ (predecessor.supervisorOwnerToken !== undefined &&+ successor.supervisorOwnerToken === predecessor.supervisorOwnerToken) ||+ (successor.pid === predecessor.pid &&+ predecessor.processStartId !== undefined &&+ successor.processStartId === predecessor.processStartId))+ ) {+ throw new Error(`Replacement daemon on ${socketPath} still has the predecessor identity`);+ }+ return successor;}-async function restartDaemonAfterSelfUpdate(socketPath: string, agentDir: string): Promise<void> {- const daemonProbe = await probeRunningDaemonSessions(socketPath);+export async function runDaemonUpdateRestartCoordinator(options: {+ socketPath: string;+ agentDir: string;+ statusPath: string;+ originActiveSessionId?: string;+}): Promise<DaemonUpdateRestartStatus> {+ const statusWriter = new DaemonUpdateRestartStatusWriter(+ options.statusPath,+ `${process.pid}-${Date.now()}`,+ options.socketPath,+ );+ const stopStatusHeartbeat = statusWriter.startHeartbeat();+ let lease: Awaited<ReturnType<typeof acquireDaemonUpdateRestartCoordinator>> | undefined;+ let shutdownAdmission: Awaited<ReturnType<typeof acquireDaemonShutdownAdmission>> | undefined;+ let connectedClient: DaemonClient | undefined;let manifest: DaemonUpdateRestartManifest | undefined;- let oldDaemonAlreadyStopped = false;- if (daemonProbe.reachable) {+ try {try {- manifest = await prepareDaemonUpdateRestart(socketPath, agentDir);+ lease = await acquireDaemonUpdateRestartCoordinator({+ requestId: statusWriter.current().requestId,+ socketPath: options.socketPath,+ statusPath: options.statusPath,+ });} catch (error: unknown) {- const message = formatUnknownError(error);- const daemonLacksPrepareCommand = isUnknownDaemonCommandError(error, "prepare_update_restart");- if (daemonProbeMayHaveBusySessions(daemonProbe) || !daemonLacksPrepareCommand) {- console.error(- chalk.yellow(- `Warning: updated, but could not prepare agent sessions for automatic resume (${message}); leaving the background service on the previous version.`,- ),+ if (!(error instanceof DaemonUpdateRestartCoordinatorAlreadyRunningError)) {+ throw error;+ }+ const activeStatus = await waitForActiveDaemonUpdateRestartCoordinator(error.record);+ statusWriter.update({+ phase: activeStatus.phase,+ counts: activeStatus.counts,+ ...(activeStatus.predecessor ? { predecessor: activeStatus.predecessor } : {}),+ ...(activeStatus.successor ? { successor: activeStatus.successor } : {}),+ ...(activeStatus.failures ? { failures: activeStatus.failures } : {}),+ ...(activeStatus.message ? { message: activeStatus.message } : {}),+ });+ return statusWriter.current();+ }+ shutdownAdmission = await acquireDaemonShutdownAdmission();+ const daemonProbe = await probeRunningDaemonSessions(options.socketPath);+ const reportRestoreProgress = (progress: RestoreDaemonUpdateRestartResult) => {+ const { failures, ...counts } = progress;+ statusWriter.update({ counts, failures });+ };+ let predecessor: DaemonUpdateRestartProcessIdentity | undefined;+ if (daemonProbe.reachable) {+ connectedClient = new DaemonClient(options.socketPath);+ await connectedClient.connect(1000);+ const hello = await connectedClient.waitForHello(2000);+ predecessor = processIdentityFromDaemonHello(hello);+ statusWriter.update({ phase: "preparing", ...(predecessor ? { predecessor } : {}) });+ try {+ manifest = await prepareConnectedDaemonUpdateRestart(+ connectedClient,+ options.socketPath,+ options.agentDir,+ hello,);- return;+ } catch (error: unknown) {+ const daemonLacksPrepareCommand = isUnknownDaemonCommandError(error, "prepare_update_restart");+ if (daemonProbeMayHaveBusySessions(daemonProbe) || !daemonLacksPrepareCommand) {+ throw new Error(+ `Could not prepare daemon sessions for automatic resume; the previous daemon is still running (${formatUnknownError(error)})`,+ );+ }}- console.error(- chalk.yellow(- `Warning: the old background service cannot prepare idle sessions for automatic resume (${message}); restarting without restored sessions.`,- ),+ statusWriter.update({+ phase: "stopping",+ counts: {+ total: manifest?.sessions.length ?? 0,+ restored: 0,+ resumed: 0,+ failed: 0,+ },+ });+ await shutdownAdmission.assertOrRenew();+ const stopped = await shutdownConnectedDaemonAndWait(connectedClient, options.socketPath, 10000, hello);+ connectedClient = undefined;+ if (!stopped) {+ const remainingDaemon = await probeRunningDaemonSessions(options.socketPath);+ if (remainingDaemon.reachable) {+ if (manifest) {+ try {+ const restoreResult = await restoreDaemonUpdateRestart(+ options.socketPath,+ manifest,+ options.originActiveSessionId,+ reportRestoreProgress,+ );+ const { failures: restoreFailures, ...counts } = restoreResult;+ clearPreparedDaemonUpdateRestartManifest(options.socketPath, options.agentDir);+ statusWriter.update({+ counts,+ ...(restoreFailures.length > 0 ? { failures: restoreFailures } : {}),+ });+ } catch {+ // Keep the manifest for a later recovery attempt when fallback restoration fails.+ }+ }+ throw new Error(`Could not stop the predecessor daemon on ${options.socketPath}`);+ }+ }+ } else {+ manifest = tryReadPreparedDaemonUpdateRestartManifest(options.socketPath, options.agentDir);+ if (!hasRestorableDaemonUpdateRestart(manifest)) {+ statusWriter.update({ phase: "skipped", message: "No running daemon needed to be restarted" });+ return statusWriter.current();+ }+ }++ statusWriter.update({ phase: "starting_daemon" });+ await waitForDaemonStartupFence(options.socketPath, UPDATE_RESTART_PREDECESSOR_FENCE_TIMEOUT_MS);+ await shutdownAdmission.assertOrRenew();+ await shutdownAdmission.release();+ shutdownAdmission = undefined;+ await ensureInteractiveDaemonRunning(options.socketPath);+ const successorClient = new DaemonClient(options.socketPath);+ let successor: DaemonUpdateRestartProcessIdentity;+ try {+ await successorClient.connect(1000);+ const successorHello = await successorClient.waitForHello(60000);+ successor = validateReplacementDaemon(options.socketPath, successorHello, predecessor);+ } finally {+ successorClient.close();+ }+ statusWriter.update({ phase: "restoring", successor });++ let counts: DaemonUpdateRestartCounts = { total: 0, restored: 0, resumed: 0, failed: 0 };+ let failures: DaemonUpdateRestartFailure[] = [];+ if (manifest) {+ const restoreResult = await restoreDaemonUpdateRestart(+ options.socketPath,+ manifest,+ options.originActiveSessionId,+ reportRestoreProgress,);+ counts = {+ total: restoreResult.total,+ restored: restoreResult.restored,+ resumed: restoreResult.resumed,+ failed: restoreResult.failed,+ };+ failures = restoreResult.failures;+ clearPreparedDaemonUpdateRestartManifest(options.socketPath, options.agentDir);}- } else {- manifest = tryReadPreparedDaemonUpdateRestartManifest(agentDir);- oldDaemonAlreadyStopped = hasRestorableDaemonUpdateRestart(manifest);- }- if (!daemonProbe.reachable && !hasRestorableDaemonUpdateRestart(manifest)) {- return;- }- const stopped = oldDaemonAlreadyStopped || (await shutdownDaemonAndWait(socketPath));- if (!stopped) {- console.error(- chalk.yellow(- `Warning: could not stop the old background service on ${socketPath}; it will be replaced on next launch.`,- ),- );- await tryRestoreDaemonUpdateRestart(socketPath, agentDir, manifest, "after daemon stop failed");- return;- }- try {- await ensureInteractiveDaemonRunning(socketPath);+ statusWriter.update({+ phase: "complete",+ counts,+ ...(failures.length > 0 ? { failures } : {}),+ message:+ counts.failed > 0+ ? `Restarted the daemon with ${counts.failed} session restore failure${counts.failed === 1 ? "" : "s"}`+ : "Restarted the daemon after the update",+ });} catch (error: unknown) {- const message = formatUnknownError(error);- console.error(- chalk.yellow(- `Warning: updated, but could not relaunch the background service (${message}); it will start on next launch.`,- ),- );- await tryRestoreDaemonUpdateRestart(socketPath, agentDir, manifest, "after relaunch failed");- return;- }- if (manifest) {- await tryRestoreDaemonUpdateRestart(socketPath, agentDir, manifest, "after relaunch");+ statusWriter.update({ phase: "failed", message: formatUnknownError(error) });+ } finally {+ stopStatusHeartbeat();+ connectedClient?.close();+ await shutdownAdmission?.release();+ await lease?.release();}+ return statusWriter.current();}export async function handleConfigCommand(args: string[]): Promise<boolean> {@@ -1167,6 +1501,34 @@ export async function handlePackageCommand(args: string[]): Promise<boolean> {return true;}+ if (options.restartCoordinator) {+ const agentDir = getAgentDir();+ const statusPath = options.restartStatusPath;+ const daemonSocketPath = options.daemonSocketPath;+ const restartDirectory = resolve(agentDir, "update-restarts");+ if (!statusPath || !daemonSocketPath || !resolve(statusPath).startsWith(`${restartDirectory}${sep}`)) {+ console.error(chalk.red("Invalid daemon update restart coordinator invocation."));+ process.exitCode = 1;+ return true;+ }+ const status = await runDaemonUpdateRestartCoordinator({+ socketPath: daemonSocketPath,+ agentDir,+ statusPath,+ originActiveSessionId: options.restartOriginActiveSessionId,+ });+ if (status.phase === "failed") {+ process.exitCode = 1;+ }+ return true;+ }++ if (options.restartStatusPath || options.restartOriginActiveSessionId) {+ console.error(chalk.red("Invalid daemon update restart coordinator invocation."));+ process.exitCode = 1;+ return true;+ }+const source = options.source;if ((options.command === "install" || options.command === "remove") && !source) {console.error(chalk.red(`Missing ${options.command} source.`));@@ -1276,7 +1638,7 @@ export async function handlePackageCommand(args: string[]): Promise<boolean> {return true;}// Confirm before the install, since upgrading the daemon afterward stops and resumes busy work.- const daemonSocketPath = defaultDaemonSocketPath();+ const daemonSocketPath = resolveUpdateDaemonSocketPath(options.daemonSocketPath);const daemonProbe = await probeRunningDaemonSessions(daemonSocketPath);if (!(await confirmDaemonSessionLossBeforeUpdate(daemonProbe, options.force))) {if (process.stdin.isTTY) {@@ -1295,7 +1657,24 @@ export async function handlePackageCommand(args: string[]): Promise<boolean> {return true;}console.log(chalk.green(`Updated ${APP_NAME}`));- await restartDaemonAfterSelfUpdate(daemonSocketPath, agentDir);+ if (process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] === "1") {+ return true;+ }+ try {+ const status = await launchDaemonUpdateRestartCoordinator({+ socketPath: daemonSocketPath,+ agentDir,+ cwd,+ originActiveSessionId: process.env[DAEMON_WORKER_ACTIVE_SESSION_ID_ENV],+ });+ reportDaemonUpdateRestartStatus(status);+ } catch (error: unknown) {+ console.error(+ chalk.yellow(+ `Warning: updated, but could not coordinate the daemon restart (${formatUnknownError(error)}).`,+ ),+ );+ }}return true;}diff --git a/packages/coding-agent/test/fixtures/eng-4606-update-launcher.ts b/packages/coding-agent/test/fixtures/eng-4606-update-launcher.tsnew file mode 100644index 0000000000..1e7b693882--- /dev/null+++ b/packages/coding-agent/test/fixtures/eng-4606-update-launcher.ts@@ -0,0 +1,31 @@+import { writeFileSync } from "node:fs";+import { launchDaemonUpdateRestartCoordinator } from "../../src/cli/daemon-update-restart.js";++function requireEnvironment(name: string): string {+ const value = process.env[name];+ if (!value) {+ throw new Error(`Missing ${name}`);+ }+ return value;+}++const agentDir = requireEnvironment("ENG_4606_AGENT_DIR");+const cliPath = requireEnvironment("ENG_4606_CLI_PATH");+const completionPath = requireEnvironment("ENG_4606_COMPLETION_PATH");+const pidPath = requireEnvironment("ENG_4606_PID_PATH");+const socketPath = requireEnvironment("ENG_4606_SOCKET_PATH");+const tsxPath = requireEnvironment("ENG_4606_TSX_PATH");+const originActiveSessionId = requireEnvironment("PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID");++process.argv[1] = cliPath;+process.execArgv.splice(0, process.execArgv.length, tsxPath);+writeFileSync(pidPath, `${process.pid}\n`);++await launchDaemonUpdateRestartCoordinator({+ socketPath,+ agentDir,+ cwd: agentDir,+ originActiveSessionId,+});++writeFileSync(completionPath, "launcher survived\n");diff --git a/packages/coding-agent/test/interactive-update-relaunch.test.ts b/packages/coding-agent/test/interactive-update-relaunch.test.tsindex ceb690303f..1228efa3cd 100644--- a/packages/coding-agent/test/interactive-update-relaunch.test.ts+++ b/packages/coding-agent/test/interactive-update-relaunch.test.ts@@ -1,5 +1,11 @@import { describe, expect, it } from "vitest";-import { buildUpdateRelaunchArgs } from "../src/modes/interactive/interactive-mode.js";+import { buildDaemonUpdateRestartReport } from "../src/cli/daemon-update-restart.js";+import {+ buildUpdateChildArgs,+ buildUpdateRelaunchArgs,+ resolveInteractiveUpdateDaemonSocketPath,+ updateArgsIncludeSelf,+} from "../src/modes/interactive/interactive-mode.js";describe("buildUpdateRelaunchArgs", () => {it("relaunches the current session with the supported resume flag", () => {@@ -27,3 +33,53 @@ describe("buildUpdateRelaunchArgs", () => {]);});});++describe("buildUpdateChildArgs", () => {+ it("passes the active custom socket to the deferred self-update child", () => {+ expect(buildUpdateChildArgs(["--self", "--force"], "/tmp/custom-daemon.sock")).toEqual([+ "--self",+ "--force",+ "--daemon-socket",+ "/tmp/custom-daemon.sock",+ ]);+ });++ it("keeps an explicitly selected update socket", () => {+ expect(buildUpdateChildArgs(["--self", "--daemon-socket", "/tmp/explicit.sock"], "/tmp/active.sock")).toEqual([+ "--self",+ "--daemon-socket",+ "/tmp/explicit.sock",+ ]);+ expect(+ resolveInteractiveUpdateDaemonSocketPath(+ ["--self", "--daemon-socket", "/tmp/explicit.sock"],+ "/tmp/active.sock",+ ),+ ).toBe("/tmp/explicit.sock");+ expect(updateArgsIncludeSelf(["--daemon-socket", "/tmp/explicit.sock"])).toBe(true);+ });+});++describe("buildDaemonUpdateRestartReport", () => {+ it("reports recovery results when the daemon restart fails", () => {+ const report = buildDaemonUpdateRestartReport({+ version: 1,+ requestId: "test-request",+ socketPath: "/tmp/custom-daemon.sock",+ phase: "failed",+ coordinator: { pid: process.pid },+ counts: { total: 3, restored: 2, resumed: 1, failed: 1 },+ failures: [{ sessionFile: "/tmp/failed.jsonl", message: "create failed" }],+ message: "could not stop predecessor",+ startedAt: "2026-07-14T00:00:00.000Z",+ updatedAt: "2026-07-14T00:00:01.000Z",+ });++ expect(report.info).toEqual(["Restored 2 daemon sessions", "Resumed 1 interrupted session"]);+ expect(report.warnings).toEqual([+ "Updated, but could not restart the daemon (could not stop predecessor).",+ "1 daemon session could not be restored.",+ "Could not restore /tmp/failed.jsonl: create failed",+ ]);+ });+});diff --git a/packages/coding-agent/test/package-command-paths.test.ts b/packages/coding-agent/test/package-command-paths.test.tsindex 594946a3e0..3ddb7055a4 100644--- a/packages/coding-agent/test/package-command-paths.test.ts+++ b/packages/coding-agent/test/package-command-paths.test.ts@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSynimport { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { APP_NAME, ENV_AGENT_DIR, PACKAGE_NAME, VERSION } from "../src/config.js";+import { APP_NAME, ENV_AGENT_DIR, PACKAGE_NAME, SELF_UPDATE_INTERACTIVE_CHILD_ENV, VERSION } from "../src/config.js";import { main } from "../src/main.js";function restoreEnv(name: string, value: string | undefined): void {@@ -13,6 +13,16 @@ function restoreEnv(name: string, value: string | undefined): void {process.env[name] = value;}+async function runSelfUpdateInstallChild(args: string[]): Promise<void> {+ const previousValue = process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV];+ process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] = "1";+ try {+ await main(args);+ } finally {+ restoreEnv(SELF_UPDATE_INTERACTIVE_CHILD_ENV, previousValue);+ }+}+describe("package commands", () => {let tempDir: string;let agentDir: string;@@ -207,7 +217,7 @@ else fs.writeFileSync(${JSON.stringify(recordPath)},JSON.stringify(args));const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {- await expect(main(["update", "--force"])).resolves.toBeUndefined();+ await expect(runSelfUpdateInstallChild(["update", "--self", "--force"])).resolves.toBeUndefined();expect(process.exitCode).toBeUndefined();expect(errorSpy).not.toHaveBeenCalled();@@ -251,7 +261,7 @@ else fs.writeFileSync(${JSON.stringify(recordPath)},JSON.stringify(args));const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {- await expect(main(["update"])).resolves.toBeUndefined();+ await expect(runSelfUpdateInstallChild(["update", "--self"])).resolves.toBeUndefined();expect(process.exitCode).toBeUndefined();expect(errorSpy).not.toHaveBeenCalled();@@ -300,7 +310,7 @@ else {const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {- await expect(main(["update"])).resolves.toBeUndefined();+ await expect(runSelfUpdateInstallChild(["update", "--self"])).resolves.toBeUndefined();expect(process.exitCode).toBeUndefined();expect(errorSpy).not.toHaveBeenCalled();@@ -353,7 +363,7 @@ else {const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});try {- await expect(main(["update"])).resolves.toBeUndefined();+ await expect(runSelfUpdateInstallChild(["update", "--self"])).resolves.toBeUndefined();expect(process.exitCode).toBeUndefined();expect(errorSpy).not.toHaveBeenCalled();diff --git a/packages/coding-agent/test/package-self-update-daemon.test.ts b/packages/coding-agent/test/package-self-update-daemon.test.tsindex 9ddb1f82d6..cfe9783242 100644--- a/packages/coding-agent/test/package-self-update-daemon.test.ts+++ b/packages/coding-agent/test/package-self-update-daemon.test.ts@@ -1,18 +1,31 @@-import { mkdirSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type * as DaemonUpdateRestartModule from "../src/cli/daemon-update-restart.js";+import {+ acquireDaemonUpdateRestartCoordinator,+ type DaemonUpdateRestartStatus,+ DaemonUpdateRestartStatusWriter,+ waitForActiveDaemonUpdateRestartCoordinator,+} from "../src/cli/daemon-update-restart.js";import {ENV_AGENT_DIR,getDaemonUpdateRestartManifestPath,+ getLegacyDaemonUpdateRestartManifestPath,PACKAGE_NAME,SELF_UPDATE_INTERACTIVE_CHILD_ENV,SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE,+ VERSION,} from "../src/config.js";import type { AgentSessionRuntimeMetadata } from "../src/core/agent-session-runtime.js";import { DAEMON_PROTOCOL_VERSION } from "../src/modes/daemon/daemon-protocol.js";import type * as DaemonSocketModule from "../src/modes/daemon/daemon-socket.js";-import { handlePackageCommand, prepareDaemonUpdateRestart } from "../src/package-manager-cli.js";+import {+ handlePackageCommand,+ prepareDaemonUpdateRestart,+ runDaemonUpdateRestartCoordinator,+} from "../src/package-manager-cli.js";interface MockSessionSummary {id: string;@@ -91,6 +104,7 @@ const mockState = vi.hoisted(() => ({createActiveSessionIds: [] as string[],createThrowSessionPaths: [] as string[],daemonProbe: { reachable: true, activeSessions: [] } as MockRunningDaemonProbe,+ daemonProbeAfterShutdown: undefined as MockRunningDaemonProbe | undefined,globalPackageRoot: "",hello: { protocol: { version: 0 } } as {protocol: { version: number };@@ -100,15 +114,25 @@ const mockState = vi.hoisted(() => ({supervisorProcessStartId?: string;supervisorSocketPath?: string;},+ helloCount: 0,+ lastCoordinatorStatus: undefined as DaemonUpdateRestartStatus | undefined,listResponse: undefined as MockDaemonResponse | undefined,+ noticeError: undefined as string | undefined,+ prepareError: undefined as string | undefined,prepareManifest: { createdAt: "2026-07-07T00:00:00.000Z", sessions: [] } as MockUpdateRestartManifest,+ preparedManifestPath: "",prepareResponse: undefined as MockDaemonResponse | undefined,promptFailures: 0,+ probeSocketPaths: [] as string[],requestThrowTypes: [] as string[],+ disconnectRequestTypes: [] as string[],+ disconnectAfterPersistRequestTypes: [] as string[],requestPayloads: [] as MockDaemonRequest[],helloWaitFailures: 0,restoreNextTurnFailures: 0,socketPath: "",+ successorProcessStartId: "replacement-start" as string | undefined,+ successorSocketPath: undefined as string | undefined,spawnExitCodes: [] as number[],shutdownResult: true,}));@@ -147,15 +171,49 @@ vi.mock("child_process", () => ({})),}));+vi.mock("../src/cli/daemon-update-restart.js", async (importOriginal) => {+ const original = await importOriginal<typeof DaemonUpdateRestartModule>();+ return {+ ...original,+ launchDaemonUpdateRestartCoordinator: vi.fn(async (options: { socketPath: string }) => {+ mockState.calls.push(`launch-coordinator:${options.socketPath}`);+ return {+ version: 1,+ requestId: "test-request",+ socketPath: options.socketPath,+ phase: "complete",+ coordinator: { pid: process.pid },+ counts: { total: 0, restored: 0, resumed: 0, failed: 0 },+ startedAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ };+ }),+ };+});+vi.mock("../src/modes/daemon/daemon-socket.js", async (importOriginal) => ({...(await importOriginal<typeof DaemonSocketModule>()),defaultDaemonSocketPath: () => mockState.socketPath,}));vi.mock("../src/modes/daemon/daemon-supervisor-ownership.js", () => ({+ acquireDaemonShutdownAdmission: vi.fn(async () => {+ mockState.calls.push("acquire-daemon-shutdown-admission");+ return {+ assertOrRenew: vi.fn(async () => {+ mockState.calls.push("renew-daemon-shutdown-admission");+ }),+ release: vi.fn(async () => {+ mockState.calls.push("release-daemon-shutdown-admission");+ }),+ };+ }),persistDaemonStartupFenceFromOwner: vi.fn(async () => {mockState.calls.push("persist-daemon-startup-fence");}),+ waitForDaemonStartupFence: vi.fn(async () => {+ mockState.calls.push("wait-daemon-startup-fence");+ }),}));vi.mock("../src/cli/daemon-launch.js", () => ({@@ -175,18 +233,23 @@ vi.mock("../src/cli/daemon-launch.js", () => ({summary.isBashRunning === true ||summary.hasRunningRlmChildren === true ||summary.pendingMessageCount > 0,- probeRunningDaemonSessions: vi.fn(async () => {+ probeRunningDaemonSessions: vi.fn(async (socketPath: string) => {mockState.calls.push("probe-daemon");+ mockState.probeSocketPaths.push(socketPath);return mockState.daemonProbe;}),- shutdownDaemonAndWait: vi.fn(async () => {+ shutdownConnectedDaemonAndWait: vi.fn(async () => {mockState.calls.push("shutdown-daemon");+ if (mockState.daemonProbeAfterShutdown) {+ mockState.daemonProbe = mockState.daemonProbeAfterShutdown;+ }return mockState.shutdownResult;}),}));vi.mock("../src/modes/daemon/daemon-client.js", () => ({DaemonClient: class {+ private connected = false;private observedHello: typeof mockState.hello | undefined;constructor(readonly socketPath: string) {}@@ -197,29 +260,82 @@ vi.mock("../src/modes/daemon/daemon-client.js", () => ({async connect(): Promise<void> {mockState.calls.push(`daemon-connect:${this.socketPath}`);+ this.connected = true;}- async waitForHello(): Promise<typeof mockState.hello> {+ get isConnected(): boolean {+ return this.connected;+ }++ async waitForHello(): Promise<{+ protocol: { version: number };+ appVersion: string;+ supervisorGeneration?: string;+ supervisorOwnerToken?: string;+ supervisorPid?: number;+ supervisorProcessStartId?: string;+ supervisorSocketPath?: string;+ }> {if (mockState.helloWaitFailures > 0) {mockState.helloWaitFailures--;throw new Error("hello timed out");}- this.observedHello = mockState.hello;- return mockState.hello;+ const helloCount = mockState.helloCount++;+ const hello =+ helloCount === 0+ ? {+ appVersion: VERSION,+ ...mockState.hello,+ }+ : {+ protocol: { version: DAEMON_PROTOCOL_VERSION },+ appVersion: VERSION,+ supervisorPid: 1002,+ supervisorGeneration: "replacement-generation",+ supervisorOwnerToken: "replacement-owner-token",+ ...(mockState.successorProcessStartId+ ? { supervisorProcessStartId: mockState.successorProcessStartId }+ : {}),+ supervisorSocketPath: mockState.successorSocketPath ?? mockState.socketPath,+ };+ this.observedHello = hello;+ return hello;+ }++ async requestLegacy(request: MockDaemonRequest): Promise<MockDaemonResponse> {+ return this.request(request);}async request(request: MockDaemonRequest): Promise<MockDaemonResponse> {this.observedHello ??= mockState.hello;mockState.calls.push(`daemon-request:${request.type}`);mockState.requestPayloads.push(request);+ if (mockState.disconnectRequestTypes.includes(request.type)) {+ this.connected = false;+ throw new Error(`${request.type} disconnected`);+ }if (mockState.requestThrowTypes.includes(request.type)) {throw new Error(`${request.type} failed`);}+ if (request.type === "append_custom_message" && mockState.noticeError) {+ throw new Error(mockState.noticeError);+ }if (request.type === "list" && mockState.listResponse) {return mockState.listResponse;}if (request.type === "prepare_update_restart") {- return mockState.prepareResponse ?? { success: true, data: mockState.prepareManifest };+ if (mockState.prepareError) {+ return { success: false, error: mockState.prepareError };+ }+ const response = mockState.prepareResponse ?? { success: true, data: mockState.prepareManifest };+ if (response.success) {+ writeFileSync(mockState.preparedManifestPath, `${JSON.stringify(response.data)}\n`);+ if (mockState.disconnectAfterPersistRequestTypes.includes(request.type)) {+ this.connected = false;+ throw new Error(`${request.type} disconnected after persist`);+ }+ }+ return response;}if (request.type === "create") {if (request.sessionPath && mockState.createThrowSessionPaths.includes(request.sessionPath)) {@@ -239,7 +355,9 @@ vi.mock("../src/modes/daemon/daemon-client.js", () => ({return { success: true };}- close(): void {}+ close(): void {+ this.connected = false;+ }},}));@@ -254,6 +372,18 @@ describe("self-update daemon restart", () => {let originalExecPath: string;let originalExitCode: typeof process.exitCode;+ async function performUpdateAndRunCoordinator(originActiveSessionId?: string): Promise<void> {+ await handlePackageCommand(["update", "--self", "--daemon-socket", mockState.socketPath]);+ const restartDirectory = join(agentDir, "update-restarts");+ mkdirSync(restartDirectory, { recursive: true });+ mockState.lastCoordinatorStatus = await runDaemonUpdateRestartCoordinator({+ socketPath: mockState.socketPath,+ agentDir,+ statusPath: join(restartDirectory, "test-status.json"),+ originActiveSessionId,+ });+ }+beforeEach(() => {tempDir = join(tmpdir(), `pi-self-update-daemon-${Date.now()}-${Math.random().toString(36).slice(2)}`);agentDir = join(tempDir, "agent");@@ -261,22 +391,34 @@ describe("self-update daemon restart", () => {packageDir = join(tempDir, "global-prefix", "lib", "node_modules", PACKAGE_NAME);mockState.globalPackageRoot = join(tempDir, "global-prefix", "lib", "node_modules");mockState.hello = { protocol: { version: DAEMON_PROTOCOL_VERSION } };+ mockState.helloCount = 0;+ mockState.lastCoordinatorStatus = undefined;mockState.listResponse = undefined;+ mockState.noticeError = undefined;+ mockState.prepareError = undefined;mockState.socketPath = join(tempDir, "daemon.sock");+ mockState.successorProcessStartId = "replacement-start";+ mockState.successorSocketPath = undefined;mockState.calls = [];mockState.createActiveSessionIds = [];mockState.createThrowSessionPaths = [];mockState.daemonProbe = { reachable: true, activeSessions: [] };+ mockState.daemonProbeAfterShutdown = undefined;+ mockState.disconnectAfterPersistRequestTypes = [];+ mockState.disconnectRequestTypes = [];mockState.prepareManifest = { createdAt: "2026-07-07T00:00:00.000Z", sessions: [] };+ mockState.preparedManifestPath = getDaemonUpdateRestartManifestPath(mockState.socketPath, agentDir);mockState.prepareResponse = undefined;mockState.helloWaitFailures = 0;mockState.promptFailures = 0;+ mockState.probeSocketPaths = [];mockState.requestThrowTypes = [];mockState.requestPayloads = [];mockState.restoreNextTurnFailures = 0;mockState.spawnExitCodes = [];mockState.shutdownResult = true;mkdirSync(agentDir, { recursive: true });+ mkdirSync(join(agentDir, "daemon-update-restarts"), { recursive: true });mkdirSync(projectDir, { recursive: true });mkdirSync(packageDir, { recursive: true });@@ -319,6 +461,14 @@ describe("self-update daemon restart", () => {rmSync(tempDir, { recursive: true, force: true });});+ it("scopes prepared restart manifests to the exact daemon socket", () => {+ const otherSocketPath = join(tempDir, "other-daemon.sock");++ expect(getDaemonUpdateRestartManifestPath(mockState.socketPath, agentDir)).not.toBe(+ getDaemonUpdateRestartManifestPath(otherSocketPath, agentDir),+ );+ });+it("uses the interactive no-change sentinel only when self-update is unchanged", async () => {process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] = "1";vi.stubGlobal(@@ -376,25 +526,301 @@ describe("self-update daemon restart", () => {}});+ it("defers the exact custom-socket restart to the interactive parent", async () => {+ process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] = "1";+ const customSocketPath = join(tempDir, "custom", "daemon.sock");++ await expect(handlePackageCommand(["update", "--self", "--daemon-socket", customSocketPath])).resolves.toBe(true);++ expect(mockState.probeSocketPaths).toEqual([customSocketPath]);+ expect(mockState.calls.some((call) => call.startsWith("spawn:npm "))).toBe(true);+ expect(mockState.calls.some((call) => call.startsWith("launch-coordinator:"))).toBe(false);+ });++ it("serializes coordinators per exact socket", async () => {+ const registryDir = join(tempDir, "restart-registry");+ const first = await acquireDaemonUpdateRestartCoordinator({+ requestId: "first",+ socketPath: mockState.socketPath,+ statusPath: join(agentDir, "first.json"),+ registryDir,+ });+ try {+ await expect(+ acquireDaemonUpdateRestartCoordinator({+ requestId: "second",+ socketPath: mockState.socketPath,+ statusPath: join(agentDir, "second.json"),+ registryDir,+ }),+ ).rejects.toThrow("already running");+ } finally {+ await first.release();+ }+ });++ it("waits for the active coordinator before a concurrent loser completes", async () => {+ const activeStatusPath = join(agentDir, "active-status.json");+ const activeStatus = new DaemonUpdateRestartStatusWriter(+ activeStatusPath,+ "active-request",+ mockState.socketPath,+ );+ activeStatus.update({ phase: "preparing" });+ const activeLease = await acquireDaemonUpdateRestartCoordinator({+ requestId: "active-request",+ socketPath: mockState.socketPath,+ statusPath: activeStatusPath,+ });+ let settled = false;+ try {+ const loser = runDaemonUpdateRestartCoordinator({+ socketPath: mockState.socketPath,+ agentDir,+ statusPath: join(agentDir, "loser-status.json"),+ }).finally(() => {+ settled = true;+ });++ await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));+ expect(settled).toBe(false);+ activeStatus.update({+ phase: "complete",+ counts: { total: 1, restored: 1, resumed: 0, failed: 0 },+ message: "active coordinator completed",+ });++ await expect(loser).resolves.toMatchObject({+ phase: "complete",+ counts: { total: 1, restored: 1, resumed: 0, failed: 0 },+ message: "active coordinator completed",+ });+ expect(mockState.calls).not.toContain("probe-daemon");+ } finally {+ await activeLease.release();+ }+ });++ it("returns a terminal status written immediately before coordinator exit", async () => {+ const statusPath = join(agentDir, "exit-race-status.json");+ const statusWriter = new DaemonUpdateRestartStatusWriter(statusPath, "exit-race", mockState.socketPath);+ statusWriter.update({ phase: "preparing" });+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => {+ statusWriter.update({ phase: "complete" });+ const error = new Error("process exited") as NodeJS.ErrnoException;+ error.code = "ESRCH";+ throw error;+ });++ try {+ await expect(+ waitForActiveDaemonUpdateRestartCoordinator({+ version: 1,+ token: "exit-race-token",+ requestId: "exit-race",+ pid: 999_999,+ socketPath: mockState.socketPath,+ statusPath,+ createdAt: new Date().toISOString(),+ }),+ ).resolves.toMatchObject({ phase: "complete" });+ } finally {+ killSpy.mockRestore();+ }+ });++ it("rejects a successor that answers for another socket", async () => {+ mockState.successorSocketPath = join(tempDir, "wrong-daemon.sock");++ await performUpdateAndRunCoordinator();++ expect(mockState.lastCoordinatorStatus).toMatchObject({+ phase: "failed",+ message: expect.stringContaining("does not match"),+ });+ expect(mockState.requestPayloads.some((request) => request.type === "create")).toBe(false);+ });++ it("accepts a fixed replacement owner when process start ids are unavailable", async () => {+ mockState.hello = {+ protocol: { version: 2 },+ supervisorGeneration: "predecessor-generation",+ supervisorOwnerToken: "predecessor-owner-token",+ supervisorPid: 1001,+ supervisorSocketPath: mockState.socketPath,+ };+ mockState.successorProcessStartId = undefined;++ await performUpdateAndRunCoordinator();++ expect(mockState.lastCoordinatorStatus).toMatchObject({+ phase: "complete",+ successor: {+ pid: 1002,+ supervisorGeneration: "replacement-generation",+ supervisorOwnerToken: "replacement-owner-token",+ },+ });+ });++ it("clears the prepared manifest after fallback restoration when shutdown fails", async () => {+ mockState.shutdownResult = false;+ mockState.prepareManifest = {+ createdAt: "2026-07-07T00:00:00.000Z",+ sessions: [+ {+ activeSessionId: "old-active",+ sessionId: "session-id",+ sessionFile: join(tempDir, "session.jsonl"),+ cwd: tempDir,+ config: {},+ queue: { steering: [], followUp: [], nextTurn: [] },+ shouldResume: false,+ wasStreaming: false,+ wasCompacting: false,+ wasBashRunning: false,+ hadRunningRlmChildren: false,+ wasRetrying: false,+ hadAcceptedPromptInFlight: false,+ },+ ],+ };++ await performUpdateAndRunCoordinator();++ expect(mockState.lastCoordinatorStatus).toMatchObject({+ phase: "failed",+ counts: { total: 1, restored: 1, resumed: 0, failed: 0 },+ });+ expect(existsSync(mockState.preparedManifestPath)).toBe(false);+ });++ it("starts a successor when shutdown identity confirmation times out after the socket is gone", async () => {+ mockState.shutdownResult = false;+ mockState.daemonProbeAfterShutdown = { reachable: false };+ mockState.prepareManifest = {+ createdAt: "2026-07-07T00:00:00.000Z",+ sessions: [+ {+ activeSessionId: "old-active",+ sessionId: "session-id",+ sessionFile: join(tempDir, "session.jsonl"),+ cwd: tempDir,+ config: {},+ queue: { steering: [], followUp: [], nextTurn: [] },+ shouldResume: false,+ wasStreaming: false,+ wasCompacting: false,+ wasBashRunning: false,+ hadRunningRlmChildren: false,+ wasRetrying: false,+ hadAcceptedPromptInFlight: false,+ },+ ],+ };++ await performUpdateAndRunCoordinator();++ expect(mockState.lastCoordinatorStatus).toMatchObject({+ phase: "complete",+ counts: { total: 1, restored: 1, resumed: 0, failed: 0 },+ });+ expect(mockState.calls).toContain("ensure-daemon");+ expect(existsSync(mockState.preparedManifestPath)).toBe(false);+ });++ it("continues queued-work restoration when the update notice request rejects", async () => {+ mockState.noticeError = "socket closed";+ mockState.prepareManifest = {+ createdAt: "2026-07-07T00:00:00.000Z",+ sessions: [+ {+ activeSessionId: "old-active",+ sessionId: "session-id",+ sessionFile: join(tempDir, "session.jsonl"),+ cwd: tempDir,+ config: {},+ queue: {+ steering: [],+ followUp: [],+ nextTurn: [+ {+ role: "custom",+ customType: "queued-context",+ content: "preserve me",+ display: false,+ timestamp: 1,+ },+ ],+ },+ shouldResume: false,+ wasStreaming: false,+ wasCompacting: false,+ wasBashRunning: false,+ hadRunningRlmChildren: false,+ wasRetrying: false,+ hadAcceptedPromptInFlight: false,+ },+ ],+ };+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});++ try {+ await performUpdateAndRunCoordinator("old-active");++ expect(mockState.lastCoordinatorStatus).toMatchObject({+ phase: "complete",+ counts: { total: 1, restored: 1, resumed: 0, failed: 0 },+ });+ expect(mockState.requestPayloads.map((request) => request.type)).toContain("restore_next_turn");+ } finally {+ errorSpy.mockRestore();+ }+ });++ it("restarts an idle legacy daemon without a restorable manifest", async () => {+ mockState.hello = { protocol: { version: 1 } };+ mockState.prepareError = "Unknown daemon command: prepare_update_restart";++ await performUpdateAndRunCoordinator();++ expect(mockState.lastCoordinatorStatus).toMatchObject({+ phase: "complete",+ counts: { total: 0, restored: 0, resumed: 0, failed: 0 },+ });+ expect(mockState.calls).toContain("shutdown-daemon");+ expect(mockState.calls).toContain("ensure-daemon");+ });+it("restarts the daemon only after the package update succeeds", async () => {useFixedOwnerHello();const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});try {- await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);+ await expect(performUpdateAndRunCoordinator()).resolves.toBeUndefined();expect(process.exitCode).toBeUndefined();const spawnIndex = mockState.calls.findIndex((call) => call.startsWith("spawn:npm "));+ const launchIndex = mockState.calls.indexOf(`launch-coordinator:${mockState.socketPath}`);const fenceIndex = mockState.calls.indexOf("persist-daemon-startup-fence");const prepareIndex = mockState.calls.indexOf("daemon-request:prepare_update_restart");+ const admissionIndex = mockState.calls.indexOf("acquire-daemon-shutdown-admission");const shutdownIndex = mockState.calls.indexOf("shutdown-daemon");+ const startupFenceIndex = mockState.calls.indexOf("wait-daemon-startup-fence");+ const releaseAdmissionIndex = mockState.calls.indexOf("release-daemon-shutdown-admission");const ensureIndex = mockState.calls.indexOf("ensure-daemon");expect(spawnIndex).toBeGreaterThanOrEqual(0);- expect(prepareIndex).toBeGreaterThan(spawnIndex);+ expect(launchIndex).toBeGreaterThan(spawnIndex);+ expect(admissionIndex).toBeGreaterThan(launchIndex);+ expect(prepareIndex).toBeGreaterThan(admissionIndex);expect(fenceIndex).toBeGreaterThan(prepareIndex);expect(shutdownIndex).toBeGreaterThan(fenceIndex);+ expect(startupFenceIndex).toBeGreaterThan(shutdownIndex);+ expect(releaseAdmissionIndex).toBeGreaterThan(startupFenceIndex);+ expect(ensureIndex).toBeGreaterThan(releaseAdmissionIndex);expect(ensureIndex).toBeGreaterThan(shutdownIndex);+ expect(statSync(join(agentDir, "update-restarts", "test-status.json")).mode & 0o777).toBe(0o600);} finally {errorSpy.mockRestore();logSpy.mockRestore();@@ -430,6 +856,43 @@ describe("self-update daemon restart", () => {expect(fenceIndex).toBeGreaterThan(prepareIndex);});+ it("recovers and clears a legacy manifest when the predecessor disconnects after persisting it", async () => {+ useFixedOwnerHello();+ const legacyManifestPath = getLegacyDaemonUpdateRestartManifestPath(agentDir);+ mockState.preparedManifestPath = legacyManifestPath;+ mockState.disconnectAfterPersistRequestTypes = ["prepare_update_restart"];+ mockState.prepareManifest = {+ createdAt: "2026-07-07T00:00:00.000Z",+ sessions: [+ {+ activeSessionId: "old-active",+ sessionId: "session-id",+ sessionFile: join(tempDir, "session.jsonl"),+ cwd: tempDir,+ config: { apiKey: "legacy-secret" },+ queue: { steering: [], followUp: [], nextTurn: [] },+ shouldResume: false,+ wasStreaming: false,+ wasCompacting: false,+ wasBashRunning: false,+ hadRunningRlmChildren: false,+ wasRetrying: false,+ hadAcceptedPromptInFlight: false,+ },+ ],+ };++ await performUpdateAndRunCoordinator();++ expect(mockState.lastCoordinatorStatus).toMatchObject({+ phase: "complete",+ counts: { total: 1, restored: 1, resumed: 0, failed: 0 },+ });+ expect(mockState.calls).toContain("persist-daemon-startup-fence");+ expect(existsSync(legacyManifestPath)).toBe(false);+ expect(existsSync(getDaemonUpdateRestartManifestPath(mockState.socketPath, agentDir))).toBe(false);+ });+it("fences a pending prepared restart only after verifying the live daemon is empty", async () => {useFixedOwnerHello();const pendingManifest: MockUpdateRestartManifest = {@@ -452,7 +915,10 @@ describe("self-update daemon restart", () => {},],};- writeFileSync(getDaemonUpdateRestartManifestPath(agentDir), JSON.stringify(pendingManifest));+ writeFileSync(+ getDaemonUpdateRestartManifestPath(mockState.socketPath, agentDir),+ JSON.stringify(pendingManifest),+ );mockState.requestThrowTypes = ["list"];await expect(prepareDaemonUpdateRestart(mockState.socketPath, agentDir)).rejects.toThrow("list failed");@@ -467,6 +933,31 @@ describe("self-update daemon restart", () => {expect(listIndex).toBeGreaterThanOrEqual(0);expect(fenceIndex).toBeGreaterThan(listIndex);expect(mockState.calls).not.toContain("daemon-request:prepare_update_restart");++ mockState.calls = [];+ mockState.listResponse = {+ success: true,+ data: {+ sessions: [+ {+ id: "live-active",+ isStreaming: false,+ isCompacting: false,+ pendingMessageCount: 0,+ },+ ],+ },+ };+ mockState.disconnectRequestTypes = ["prepare_update_restart"];+ writeFileSync(+ getDaemonUpdateRestartManifestPath(mockState.socketPath, agentDir),+ JSON.stringify(pendingManifest),+ );++ await expect(prepareDaemonUpdateRestart(mockState.socketPath, agentDir)).rejects.toThrow(+ "prepare_update_restart disconnected",+ );+ expect(existsSync(getDaemonUpdateRestartManifestPath(mockState.socketPath, agentDir))).toBe(false);});it("skips predecessor fencing when the daemon hello has no fixed-owner identity", async () => {@@ -474,7 +965,7 @@ describe("self-update daemon restart", () => {const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});try {- await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);+ await expect(performUpdateAndRunCoordinator()).resolves.toBeUndefined();expect(mockState.calls).not.toContain("persist-daemon-startup-fence");expect(mockState.calls).toContain("daemon-request:prepare_update_restart");@@ -536,7 +1027,7 @@ describe("self-update daemon restart", () => {const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});try {- await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);+ await expect(performUpdateAndRunCoordinator("old-active")).resolves.toBeUndefined();const promptRequests = mockState.requestPayloads.filter((request) => request.type === "prompt");expect(promptRequests).toEqual([@@ -546,7 +1037,12 @@ describe("self-update daemon restart", () => {agentMessageId: "agentmsg_accepted",}),]);+ const noticeIndex = mockState.requestPayloads.findIndex(+ (request) => request.type === "append_custom_message" && request.activeSessionId === "restored-active",+ );const promptIndex = mockState.requestPayloads.findIndex((request) => request.type === "prompt");+ expect(noticeIndex).toBeGreaterThanOrEqual(0);+ expect(promptIndex).toBeGreaterThan(noticeIndex);const subsequentNextTurnIndex = mockState.requestPayloads.findIndex((request) =>request.type === "restore_next_turn" &&@@ -603,7 +1099,7 @@ describe("self-update daemon restart", () => {const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});try {- await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);+ await expect(performUpdateAndRunCoordinator()).resolves.toBeUndefined();expect(mockState.requestPayloads@@ -615,6 +1111,15 @@ describe("self-update daemon restart", () => {(request) => request.type === "prompt" && request.activeSessionId === "restored-active",),).toBe(true);+ expect(mockState.lastCoordinatorStatus?.counts).toEqual({+ total: 2,+ restored: 1,+ resumed: 1,+ failed: 1,+ });+ expect(mockState.lastCoordinatorStatus?.failures).toEqual([+ { sessionFile: failedSessionFile, message: "create failed" },+ ]);} finally {errorSpy.mockRestore();logSpy.mockRestore();@@ -674,7 +1179,7 @@ describe("self-update daemon restart", () => {const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});try {- await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);+ await expect(performUpdateAndRunCoordinator()).resolves.toBeUndefined();const createRequests = mockState.requestPayloads.filter((request) => request.type === "create");expect(createRequests).toHaveLength(2);@@ -751,7 +1256,7 @@ describe("self-update daemon restart", () => {const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});try {- await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);+ await expect(performUpdateAndRunCoordinator()).resolves.toBeUndefined();expect(mockState.requestPayloads).toContainEqual(expect.objectContaining({@@ -805,7 +1310,7 @@ describe("self-update daemon restart", () => {const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});try {- await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);+ await expect(performUpdateAndRunCoordinator()).resolves.toBeUndefined();expect(mockState.requestPayloads.some((request) => request.type === "follow_up")).toBe(true);expect(mockState.requestPayloads.some((request) => request.type === "resume_queue")).toBe(false);diff --git a/packages/coding-agent/test/public-command.test.ts b/packages/coding-agent/test/public-command.test.tsindex a28a67b407..1d184d1c90 100644--- a/packages/coding-agent/test/public-command.test.ts+++ b/packages/coding-agent/test/public-command.test.ts@@ -1,4 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SELF_UPDATE_INTERACTIVE_CHILD_ENV } from "../src/config.js";const mocks = vi.hoisted(() => ({daemonCommands: [] as string[][],@@ -37,6 +38,7 @@ vi.mock("../src/cli/daemon-ps.js", () => ({import { INTERNAL_RUNTIME_COMMAND_MARKER } from "../src/cli/args.js";import { formatTopLevelHelp } from "../src/cli/command-registry.js";+import { DAEMON_UPDATE_RESTART_COORDINATOR_FLAG } from "../src/cli/daemon-update-restart.js";import { handlePublicCommand } from "../src/cli/public-command.js";describe("public command routing", () => {@@ -113,6 +115,32 @@ describe("public command routing", () => {]);});+ it("forwards hidden update restart coordinator invocations", async () => {+ const args = ["update", DAEMON_UPDATE_RESTART_COORDINATOR_FLAG, "--daemon-socket", "custom-daemon.sock"];++ await handlePublicCommand(args);++ expect(mocks.packageCommands).toEqual([args]);+ });++ it("preserves the internal interactive self-update command", async () => {+ const previousValue = process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV];+ const args = ["update", "--self", "--force", "--daemon-socket", "custom-daemon.sock"];+ process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] = "1";++ try {+ await handlePublicCommand(args);+ } finally {+ if (previousValue === undefined) {+ delete process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV];+ } else {+ process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] = previousValue;+ }+ }++ expect(mocks.packageCommands).toEqual([args]);+ });+it("gives legacy update targets explicit migration guidance", async () => {for (const target of ["self", "--self", "prime-agent"]) {await handlePublicCommand(["update", target]);diff --git a/packages/coding-agent/test/session-lease.test.ts b/packages/coding-agent/test/session-lease.test.tsindex 9b232243a9..87338b6866 100644--- a/packages/coding-agent/test/session-lease.test.ts+++ b/packages/coding-agent/test/session-lease.test.ts@@ -7,6 +7,7 @@ import { afterEach, describe, expect, it } from "vitest";import {acquireSessionLease,canonicalSessionPath,+ getWindowsProcessStartId,SESSION_LEASE_OWNER_ID_ENV,SESSION_LEASES_ENABLED_ENV,SessionAlreadyActiveError,@@ -34,6 +35,40 @@ function enabledEnvironment(owner: string): NodeJS.ProcessEnv {}describe("session leases", () => {+ it("reads an invariant process start identity on Windows", () => {+ const calls: Array<{ command: string; args: string[] }> = [];+ const processStartId = getWindowsProcessStartId(42, (command, args) => {+ calls.push({ command, args });+ return "638880485801234567\r\n";+ });++ expect(processStartId).toBe("win:638880485801234567");+ expect(calls).toEqual([+ {+ command: "powershell.exe",+ args: [+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ "([System.Diagnostics.Process]::GetProcessById(42)).StartTime.ToUniversalTime().Ticks",+ ],+ },+ ]);+ });++ it("rejects invalid Windows process start identities", () => {+ let queryCount = 0;+ const query = () => {+ queryCount++;+ return "not-a-start-time";+ };++ expect(getWindowsProcessStartId(42, query)).toBeUndefined();+ expect(getWindowsProcessStartId(0, query)).toBeUndefined();+ expect(queryCount).toBe(1);+ });+it("rejects a second live owner with a typed active-session error", () => {const agentDir = createTempDir();const sessionPath = join(agentDir, "session.jsonl");diff --git a/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts b/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.tsindex fd17cd323e..5d45e26c20 100644--- a/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts+++ b/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts@@ -210,13 +210,17 @@ describe("issue #4257 update restart resume", () => {wasBashRunning: true,});const persistedManifest = JSON.parse(- readFileSync(getDaemonUpdateRestartManifestPath(harness.tempDir), "utf-8"),+ readFileSync(getDaemonUpdateRestartManifestPath(`${harness.tempDir}/daemon.sock`, harness.tempDir), "utf-8"),) as DaemonUpdateRestartManifest;expect(persistedManifest).toEqual(manifest);- writeFileSync(getDaemonUpdateRestartManifestPath(harness.tempDir), JSON.stringify(manifest));+ writeFileSync(+ getDaemonUpdateRestartManifestPath(`${harness.tempDir}/missing.sock`, harness.tempDir),+ JSON.stringify(manifest),+ );await expect(prepareDaemonUpdateRestart(`${harness.tempDir}/missing.sock`, harness.tempDir)).resolves.toEqual(manifest,);+ await expect(prepareDaemonUpdateRestart(`${harness.tempDir}/unrelated.sock`, harness.tempDir)).rejects.toThrow();expect(hasArchivedState(harness)).toBe(false);expect(harness.sessionManagerdiff --git a/packages/coding-agent/test/suite/regressions/4606-update-restart-coordinator.test.ts b/packages/coding-agent/test/suite/regressions/4606-update-restart-coordinator.test.tsnew file mode 100644index 0000000000..4beae8dc3f--- /dev/null+++ b/packages/coding-agent/test/suite/regressions/4606-update-restart-coordinator.test.ts@@ -0,0 +1,433 @@+import { type ChildProcess, spawn } from "node:child_process";+import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";+import { join, relative, resolve } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ DaemonUpdateRestartStatusWriter,+ launchDaemonUpdateRestartCoordinator,+ readDaemonUpdateRestartStatus,+} from "../../../src/cli/daemon-update-restart.js";+import { ENV_AGENT_DIR } from "../../../src/config.js";+import { DaemonAgentConnection } from "../../../src/modes/agent-connection/daemon-agent-connection.js";+import { DaemonClient } from "../../../src/modes/daemon/daemon-client.js";+import type { DaemonResponse } from "../../../src/modes/daemon/daemon-protocol.js";+import type { SessionSummary } from "../../../src/modes/daemon/daemon-session-list.js";+import { createHarness, type Harness } from "../harness.js";++interface SupervisorHandle {+ child: ChildProcess;+ stdout: string;+ stderr: string;+}++interface SupervisorOwnerRecord {+ pid: number;+ processStartId?: string;+ socketPath: string;+}++const cliPath = resolve(__dirname, "../../../src/cli.ts");+const fauxExtensionPath = resolve(__dirname, "../../fixtures/eng-4600-faux-extension.ts");+const launcherFixturePath = resolve(__dirname, "../../fixtures/eng-4606-update-launcher.ts");+const tsxPath = resolve(__dirname, "../../../../../node_modules/tsx/dist/cli.mjs");+const tsconfigPath = resolve(__dirname, "../../../../../tsconfig.json");+const supervisorRegistryDirEnv = "PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_REGISTRY_DIR";+const supervisors = new Set<SupervisorHandle>();+const harnesses: Harness[] = [];+const sockets = new Set<string>();++function delay(ms: number): Promise<void> {+ return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));+}++function spawnSupervisor(paths: {+ agentDir: string;+ completionPath: string;+ pidPath: string;+ registryDir: string;+ socketPath: string;+}): SupervisorHandle {+ const child = spawn(+ process.execPath,+ [tsxPath, cliPath, "--mode", "daemon", "--daemon-socket", paths.socketPath, "--offline"],+ {+ cwd: paths.agentDir,+ env: {+ ...process.env,+ [supervisorRegistryDirEnv]: paths.registryDir,+ [ENV_AGENT_DIR]: paths.agentDir,+ ENG_4606_AGENT_DIR: paths.agentDir,+ ENG_4606_CLI_PATH: cliPath,+ ENG_4606_COMPLETION_PATH: paths.completionPath,+ ENG_4606_PID_PATH: paths.pidPath,+ ENG_4606_SOCKET_PATH: paths.socketPath,+ ENG_4606_TSX_PATH: tsxPath,+ PI_OFFLINE: "1",+ TSX_TSCONFIG_PATH: tsconfigPath,+ },+ stdio: ["ignore", "pipe", "pipe"],+ },+ );+ const handle: SupervisorHandle = { child, stdout: "", stderr: "" };+ supervisors.add(handle);+ child.stdout?.on("data", (chunk: Buffer) => {+ handle.stdout += chunk.toString("utf8");+ });+ child.stderr?.on("data", (chunk: Buffer) => {+ handle.stderr += chunk.toString("utf8");+ });+ return handle;+}++async function connectEventually(socketPath: string, timeoutMs = 60_000): Promise<DaemonClient> {+ const deadline = Date.now() + timeoutMs;+ let lastError: unknown;+ while (Date.now() < deadline) {+ const client = new DaemonClient(socketPath);+ try {+ await client.connect(500);+ await client.waitForHello(2000);+ return client;+ } catch (error) {+ lastError = error;+ client.close();+ await delay(25);+ }+ }+ throw new Error(`Timed out connecting to ${socketPath}: ${String(lastError)}`);+}++async function waitForExit(child: ChildProcess, timeoutMs = 60_000): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) {+ return;+ }+ await new Promise<void>((resolveExit, rejectExit) => {+ const timeout = setTimeout(+ () => rejectExit(new Error(`Timed out waiting for process ${child.pid} to exit`)),+ timeoutMs,+ );+ child.once("exit", () => {+ clearTimeout(timeout);+ resolveExit();+ });+ });+}++async function waitForFile(path: string, timeoutMs = 30_000): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (existsSync(path)) {+ return;+ }+ await delay(25);+ }+ throw new Error(`Timed out waiting for ${path}`);+}++async function waitForTerminalStatus(agentDir: string, timeoutMs = 120_000) {+ const directory = join(agentDir, "update-restarts");+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (existsSync(directory)) {+ for (const name of readdirSync(directory)) {+ const path = join(directory, name);+ const status = readDaemonUpdateRestartStatus(path);+ if (status && (status.phase === "complete" || status.phase === "failed" || status.phase === "skipped")) {+ return { path, status };+ }+ }+ }+ await delay(50);+ }+ throw new Error(`Timed out waiting for update restart status in ${directory}`);+}++function requireSessionSummary(response: DaemonResponse): SessionSummary {+ if (!response.success) {+ throw new Error(response.error);+ }+ if (!response.data || typeof response.data !== "object") {+ throw new Error("Daemon returned an invalid session summary");+ }+ const summary = response.data as Partial<SessionSummary>;+ if (typeof summary.id !== "string" || typeof summary.sessionId !== "string") {+ throw new Error("Daemon returned an invalid session summary");+ }+ return summary as SessionSummary;+}++function requireSessionList(response: DaemonResponse): SessionSummary[] {+ if (!response.success) {+ throw new Error(response.error);+ }+ if (!response.data || typeof response.data !== "object" || !("sessions" in response.data)) {+ throw new Error("Daemon returned an invalid session list");+ }+ const sessions = (response.data as { sessions: unknown }).sessions;+ if (!Array.isArray(sessions)) {+ throw new Error("Daemon returned an invalid session list");+ }+ return sessions as SessionSummary[];+}++function shellQuote(value: string): string {+ return `'${value.replaceAll("'", `'"'"'`)}'`;+}++async function withSourceCliEntrypoint<T>(action: () => Promise<T>): Promise<T> {+ const previousEntrypoint = process.argv[1];+ if (!previousEntrypoint) {+ throw new Error("Test process has no CLI entrypoint");+ }+ const previousExecArgv = [...process.execArgv];+ const previousTsconfigPath = process.env.TSX_TSCONFIG_PATH;+ process.argv[1] = cliPath;+ process.execArgv.splice(0, process.execArgv.length, tsxPath);+ process.env.TSX_TSCONFIG_PATH = tsconfigPath;+ try {+ return await action();+ } finally {+ process.argv[1] = previousEntrypoint;+ process.execArgv.splice(0, process.execArgv.length, ...previousExecArgv);+ if (previousTsconfigPath === undefined) {+ delete process.env.TSX_TSCONFIG_PATH;+ } else {+ process.env.TSX_TSCONFIG_PATH = previousTsconfigPath;+ }+ }+}++function isProcessAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException).code !== "ESRCH";+ }+}++function listSupervisorOwnerRecords(registryDir: string): SupervisorOwnerRecord[] {+ if (!existsSync(registryDir)) {+ return [];+ }+ return readdirSync(registryDir)+ .filter((name) => name.endsWith(".owner"))+ .map((name) => JSON.parse(readFileSync(join(registryDir, name, "owner.json"), "utf8")) as SupervisorOwnerRecord);+}++async function stopDaemon(socketPath: string): Promise<void> {+ const client = new DaemonClient(socketPath);+ try {+ await client.connect(500);+ await client.waitForHello(2000);+ await client.request({ type: "shutdown", force: true }, 5000).catch(() => undefined);+ } catch {+ return;+ } finally {+ client.close();+ }+ const deadline = Date.now() + 30_000;+ while (Date.now() < deadline) {+ const probe = new DaemonClient(socketPath);+ try {+ await probe.connect(250);+ } catch {+ probe.close();+ return;+ }+ probe.close();+ await delay(25);+ }+}++afterEach(async () => {+ for (const socketPath of sockets) {+ await stopDaemon(socketPath).catch(() => undefined);+ }+ sockets.clear();+ for (const supervisor of supervisors) {+ if (supervisor.child.exitCode === null && supervisor.child.signalCode === null) {+ supervisor.child.kill("SIGKILL");+ await waitForExit(supervisor.child).catch(() => undefined);+ }+ }+ supervisors.clear();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+});++describe("ENG-4606 update restart coordinator", () => {+ it("refreshes coordinator liveness without changing restart state", async () => {+ const harness = await createHarness();+ harnesses.push(harness);+ const statusPath = join(harness.tempDir, "restart-status.json");++ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date("2026-07-14T00:00:00.000Z"));+ const writer = new DaemonUpdateRestartStatusWriter(statusPath, "test-request", "/tmp/daemon.sock");+ const stopHeartbeat = writer.startHeartbeat();+ vi.advanceTimersByTime(5000);+ stopHeartbeat();++ expect(readDaemonUpdateRestartStatus(statusPath)).toMatchObject({+ phase: "starting",+ startedAt: "2026-07-14T00:00:00.000Z",+ updatedAt: "2026-07-14T00:00:00.000Z",+ heartbeatAt: "2026-07-14T00:00:05.000Z",+ });+ } finally {+ vi.useRealTimers();+ }+ });++ it("rejects coordinator spawn errors without terminating the updater", async () => {+ const harness = await createHarness();+ harnesses.push(harness);++ await expect(+ launchDaemonUpdateRestartCoordinator({+ socketPath: join(harness.tempDir, "missing-daemon.sock"),+ agentDir: harness.tempDir,+ cwd: join(harness.tempDir, "missing-cwd"),+ timeoutMs: 5000,+ }),+ ).rejects.toThrow();+ });++ it("keeps a relative agent directory stable across coordinator cwd changes", async () => {+ const harness = await createHarness();+ harnesses.push(harness);+ const agentDir = join(harness.tempDir, "relative-agent");+ const coordinatorCwd = join(harness.tempDir, "coordinator-cwd");+ mkdirSync(agentDir, { recursive: true });+ mkdirSync(coordinatorCwd, { recursive: true });+ const socketPath = join(harness.tempDir, "missing-daemon.sock");++ const status = await withSourceCliEntrypoint(() =>+ launchDaemonUpdateRestartCoordinator({+ socketPath,+ agentDir: relative(process.cwd(), agentDir),+ cwd: coordinatorCwd,+ timeoutMs: 30_000,+ }),+ );++ expect(status).toMatchObject({ phase: "skipped", socketPath });+ });++ it("resolves a relative custom socket before changing coordinator cwd", async () => {+ const harness = await createHarness();+ harnesses.push(harness);+ const coordinatorCwd = join(harness.tempDir, "coordinator-cwd");+ mkdirSync(coordinatorCwd, { recursive: true });+ const socketPath = join(harness.tempDir, "missing-daemon.sock");++ const status = await withSourceCliEntrypoint(() =>+ launchDaemonUpdateRestartCoordinator({+ socketPath: relative(process.cwd(), socketPath),+ agentDir: harness.tempDir,+ cwd: coordinatorCwd,+ timeoutMs: 30_000,+ }),+ );++ expect(status).toMatchObject({ phase: "skipped", socketPath });+ });++ it("outlives a daemon-owned updater and restores the exact custom socket", async () => {+ if (process.platform === "win32") {+ return;+ }+ const harness = await createHarness();+ harnesses.push(harness);+ const paths = {+ agentDir: harness.tempDir,+ completionPath: join(harness.tempDir, "updater-completed"),+ pidPath: join(harness.tempDir, "updater.pid"),+ registryDir: join(harness.tempDir, "supervisor-registry"),+ socketPath: join(harness.tempDir, "custom-daemon.sock"),+ };+ sockets.add(paths.socketPath);+ const predecessor = spawnSupervisor(paths);+ const client = await connectEventually(paths.socketPath);+ const predecessorHello = await client.waitForHello(2000);+ const created = requireSessionSummary(+ await client.request(+ {+ type: "create",+ config: {+ agentDir: paths.agentDir,+ apiKey: "faux-key",+ cwd: paths.agentDir,+ extensions: [fauxExtensionPath],+ model: "faux",+ noContextFiles: true,+ noExtensions: false,+ noSkills: true,+ noTools: true,+ provider: "faux",+ },+ },+ 60_000,+ ),+ );+ const originalActiveSessionId = created.activeSessionId ?? created.id;+ const updateCommand = [process.execPath, tsxPath, launcherFixturePath].map(shellQuote).join(" ");+ const executeResponse = await client.request(+ { type: "execute_bash", activeSessionId: originalActiveSessionId, command: updateCommand },+ 5000,+ );+ expect(executeResponse.success).toBe(true);+ await waitForFile(paths.pidPath);+ const updaterPid = Number(readFileSync(paths.pidPath, "utf8").trim());+ expect(Number.isInteger(updaterPid)).toBe(true);++ const { status } = await waitForTerminalStatus(paths.agentDir);+ if (status.phase === "failed") {+ throw new Error(+ `Coordinator failed: ${status.message}\npredecessor stderr:\n${predecessor.stderr}\npredecessor stdout:\n${predecessor.stdout}`,+ );+ }+ expect(status).toMatchObject({+ phase: "complete",+ socketPath: paths.socketPath,+ counts: { total: 1, restored: 1, resumed: 1, failed: 0 },+ });+ expect(status.predecessor?.pid).toBe(predecessorHello.supervisorPid);+ expect(status.successor?.pid).not.toBe(status.predecessor?.pid);+ expect(existsSync(paths.completionPath)).toBe(false);+ expect(isProcessAlive(updaterPid)).toBe(false);+ client.close();+ await waitForExit(predecessor.child);++ const replacementClient = await connectEventually(paths.socketPath);+ const replacementHello = await replacementClient.waitForHello(2000);+ expect(replacementHello.supervisorSocketPath).toBe(resolve(paths.socketPath));+ const sessions = requireSessionList(await replacementClient.request({ type: "list" }, 30_000));+ expect(sessions).toHaveLength(1);+ const restored = sessions[0];+ if (!restored) {+ throw new Error("Restored session was not listed");+ }+ const restoredActiveSessionId = restored.activeSessionId ?? restored.id;+ const connection = await DaemonAgentConnection.attach(replacementClient, restoredActiveSessionId, {+ closeClientOnDispose: true,+ });+ await connection.getInitialSnapshot();+ await connection.waitForIdle();+ expect(await connection.getMessages()).toContainEqual(+ expect.objectContaining({+ role: "custom",+ customType: "prime-agent.update_complete",+ display: true,+ }),+ );+ await connection.dispose();++ const owners = listSupervisorOwnerRecords(paths.registryDir);+ expect(owners).toHaveLength(1);+ expect(owners[0]).toMatchObject({ pid: status.successor?.pid, socketPath: resolve(paths.socketPath) });+ }, 180_000);+});