A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
make snapshot transfers idempotent and non-fatal (#397)
kt190a738ceeb6
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex 2fcf755a37..46040701be 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -13,6 +13,7 @@- Fixed empty prompt placeholders hiding the input caret.- Fixed automatic model selection preferring other configured providers over Prime Inference's GLM 5.2 default.- Fixed missing ripgrep blocking subagents and added actionable installation guidance for the optional search helper ([ENG-4572](https://linear.app/primeintellect/issue/ENG-4572/ripgrep-not-installed)).+- Fixed snapshot transfers terminating resident workers, stranding partial readers, or rejecting identical retries ([ENG-4602](https://linear.app/primeintellect/issue/ENG-4602/make-snapshot-transfers-idempotent-and-non-fatal)).- Fixed the resume picker opening on an older session instead of the newest session ([ENG-4630](https://linear.app/primeintellect/issue/ENG-4630/show-latest-sessions-first-in-resume-list)).- Fixed tool-only responses rendering directly against the preceding user prompt.diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex d4dd658773..6a0f32d3c4 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -1722,7 +1722,9 @@ export class AgentDaemon {socket.on("error", cleanup);socket.on("drain", () => {if (!client.snapshotStreaming) {- void this.catchUpBackpressuredClient(client);+ void this.catchUpBackpressuredClient(client).catch((error) =>+ this.log(`could not catch up snapshot client ${client.id}: ${String(error)}`),+ );}});}@@ -2035,7 +2037,11 @@ export class AgentDaemon {targetChunkBytes: transcript.targetChunkBytes,},};- setImmediate(() => void this.streamWorkerSnapshot(client, streamedResult, transcript, "attach", true));+ setImmediate(() => {+ void this.streamWorkerSnapshot(client, streamedResult, transcript, "attach", true).catch((error) =>+ this.log(`could not stream attach snapshot: ${String(error)}`),+ );+ });return success(command.id, "attach", streamedResult);}// Slim clients consume only the command response; legacy clients (e.g.@@ -2865,11 +2871,19 @@ export class AgentDaemon {},purpose,);+ } catch (error) {+ const streamError = error instanceof Error ? error : new Error(String(error));+ transcript.markFailed(streamError);+ transcript.dispose();+ client.socket.destroy(streamError);+ throw streamError;} finally {finishClientSnapshotStreaming(client, result.activeSessionId);transcript.dispose();if (!client.snapshotStreaming && client.catchupActiveSessionIds?.size) {- void this.catchUpBackpressuredClient(client);+ void this.catchUpBackpressuredClient(client).catch((error) =>+ this.log(`could not catch up snapshot client ${client.id}: ${String(error)}`),+ );}}}diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 4913dab3cc..abe731a4e0 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -176,12 +176,28 @@ interface ResidentWorker {snapshotCache: Map<string, DaemonAttachResult>;transcriptCaches: Map<string, SnapshotTranscriptCache>;incomingTranscriptActiveSessionIds: Set<string>;+ duplicateIncomingTranscriptChunkIndexes: Map<string, number>;+ snapshotTransferFrames: Map<+ string,+ {+ begin: Buffer;+ end?: Buffer;+ duplicateResult?: DaemonAttachResult;+ validation?: SnapshotDuplicateValidation;+ }+ >;snapshotLoads: Map<string, Promise<DaemonAttachResult>>;recovery?: Promise<void>;intentionalStop: boolean;stopRevision: number;}+interface SnapshotDuplicateValidation {+ promise: Promise<void>;+ resolve: () => void;+ reject: (error: Error) => void;+}+interface DaemonSupervisorOptions {socketPath?: string;defaultSessionConfig: AgentSessionRuntimeConfig;@@ -432,6 +448,10 @@ export class DaemonSupervisor {private readonly commandJournal: CommandRecoveryJournal;private readonly streamReconstructor = new CompactAssistantStreamReconstructor();private readonly compactCatchupInProgress = new Set<string>();+ private readonly pendingReplacementSnapshots = new WeakMap<+ DaemonSocketClient,+ Map<string, { worker: ResidentWorker; result: DaemonAttachResult; transcript: SnapshotTranscriptCache }>+ >();private agentPeerSyncQueue: Promise<void> = Promise.resolve();private readonly catalog: DaemonCatalogClient;@@ -538,6 +558,8 @@ export class DaemonSupervisor {snapshotCache: new Map(),transcriptCaches: new Map(),incomingTranscriptActiveSessionIds: new Set(),+ duplicateIncomingTranscriptChunkIndexes: new Map(),+ snapshotTransferFrames: new Map(),snapshotLoads: new Map(),intentionalStop: descriptor.stopRequestedAt !== undefined,stopRevision: 0,@@ -649,6 +671,7 @@ export class DaemonSupervisor {}cleaned = true;client.detachInput();+ this.dropPendingReplacementSnapshot(client);this.clients.delete(client);for (const activeSessionId of [...client.attachedActiveSessionIds]) {client.attachedActiveSessionIds.delete(activeSessionId);@@ -659,7 +682,9 @@ export class DaemonSupervisor {socket.on("error", cleanup);socket.on("drain", () => {if (!client.snapshotStreaming) {- void this.catchUpClient(client);+ void this.catchUpClient(client).catch((error) =>+ this.log(`Failed to catch up client ${client.id}: ${String(error)}`),+ );}});}@@ -761,7 +786,7 @@ export class DaemonSupervisor {const transcript = this.getOrCreateTranscriptCache(attached.worker, attached.result);const streamedResult = this.createStreamedAttachResult(attached.result, transcript);this.write(client, success(command.id, "attach", streamedResult));- void this.streamSnapshot(client, streamedResult, transcript).catch((error) =>+ void this.streamSnapshot(client, attached.worker, streamedResult, transcript).catch((error) =>this.log(`Failed to stream attach snapshot for ${streamedResult.activeSessionId}: ${String(error)}`),);return undefined;@@ -1117,6 +1142,8 @@ export class DaemonSupervisor {snapshotCache: new Map(),transcriptCaches: new Map(),incomingTranscriptActiveSessionIds: new Set(),+ duplicateIncomingTranscriptChunkIndexes: new Map(),+ snapshotTransferFrames: new Map(),snapshotLoads: new Map(),intentionalStop: false,stopRevision: 0,@@ -1261,12 +1288,20 @@ export class DaemonSupervisor {return;}worker.client = undefined;- for (const activeSessionId of worker.incomingTranscriptActiveSessionIds) {- worker.transcriptCaches- .get(activeSessionId)- ?.markFailed(new Error("Session worker disconnected during snapshot transfer"));+ this.dropPendingReplacementSnapshotsForWorker(worker);+ const interrupted = new Set(worker.incomingTranscriptActiveSessionIds);+ for (const [activeSessionId, transcript] of worker.transcriptCaches) {+ if (!transcript.complete) {+ interrupted.add(activeSessionId);+ }+ }+ for (const activeSessionId of interrupted) {+ this.failWorkerSnapshotCache(+ worker,+ activeSessionId,+ new Error("Session worker disconnected during snapshot transfer"),+ );}- worker.incomingTranscriptActiveSessionIds.clear();if (this.shuttingDown || worker.intentionalStop) {return;}@@ -1277,6 +1312,58 @@ export class DaemonSupervisor {void this.recoverWorker(worker);}+ private failWorkerSnapshotCache(+ worker: ResidentWorker,+ activeSessionId: string,+ error: Error,+ closeWorkerChannel = false,+ ): void {+ const transcript = worker.transcriptCaches.get(activeSessionId);+ if (transcript) {+ transcript.markFailed(error);+ worker.transcriptCaches.delete(activeSessionId);+ transcript.dispose();+ }+ worker.snapshotCache.delete(activeSessionId);+ worker.incomingTranscriptActiveSessionIds.delete(activeSessionId);+ worker.duplicateIncomingTranscriptChunkIndexes.delete(activeSessionId);+ this.settleSnapshotDuplicateValidation(worker, activeSessionId, error);+ worker.snapshotTransferFrames.delete(activeSessionId);+ this.dropPendingReplacementSnapshotsForWorker(worker, activeSessionId);+ if (closeWorkerChannel) {+ const client = worker.client;+ if (client) {+ this.handleWorkerClose(worker, client, error);+ client.close();+ }+ }+ }++ private createSnapshotDuplicateValidation(): SnapshotDuplicateValidation {+ let resolve!: () => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<void>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ void promise.catch(() => undefined);+ return { promise, resolve, reject };+ }++ private settleSnapshotDuplicateValidation(worker: ResidentWorker, activeSessionId: string, error?: Error): void {+ const frames = worker.snapshotTransferFrames.get(activeSessionId);+ if (!frames?.validation) {+ return;+ }+ const { validation, ...settledFrames } = frames;+ worker.snapshotTransferFrames.set(activeSessionId, settledFrames);+ if (error) {+ validation.reject(error);+ } else {+ validation.resolve();+ }+ }+private async recoverWorker(worker: ResidentWorker): Promise<void> {if (this.isWorkerRecoveryCancelled(worker)) {return;@@ -1603,6 +1690,10 @@ export class DaemonSupervisor {): Promise<WorkerAttachData> {const match = await this.findWorker(command.activeSessionId);const activeSessionId = match.summary.activeSessionId ?? match.summary.id;+ const duplicateValidation = match.worker.snapshotTransferFrames.get(activeSessionId)?.validation;+ if (duplicateValidation) {+ await duplicateValidation.promise;+ }if (command.clientId) {client.id = command.clientId;}@@ -1650,7 +1741,6 @@ export class DaemonSupervisor {});match.worker.transcriptCaches.set(activeSessionId, transcript);}- match.worker.incomingTranscriptActiveSessionIds.add(activeSessionId);}match.worker.snapshotCache.set(activeSessionId, loaded);return loaded;@@ -1749,6 +1839,7 @@ export class DaemonSupervisor {private async streamSnapshot(client: DaemonSocketClient,+ worker: ResidentWorker,result: DaemonAttachResult,transcript: SnapshotTranscriptCache,purpose: "attach" | "replacement" | "resync" = "attach",@@ -1797,15 +1888,23 @@ export class DaemonSupervisor {lastEventSequence: result.lastEventSequence,lastEventCursor: result.lastEventCursor,});+ } catch (error) {+ const streamError = error instanceof Error ? error : new Error(String(error));+ this.failWorkerSnapshotCache(worker, result.activeSessionId, streamError);+ client.socket.destroy(streamError);+ throw streamError;} finally {client.snapshotActiveSessionIds?.delete(result.activeSessionId);client.snapshotStreaming = (client.snapshotActiveSessionIds?.size ?? 0) > 0;if (!client.snapshotStreaming) {client.backpressured = false;}+ this.flushPendingReplacementSnapshot(client, result.activeSessionId);releaseTranscript();if (!client.snapshotStreaming && client.catchupActiveSessionIds?.size) {- void this.catchUpClient(client);+ void this.catchUpClient(client).catch((error) =>+ this.log(`Failed to catch up client ${client.id}: ${String(error)}`),+ );}}}@@ -1849,6 +1948,7 @@ export class DaemonSupervisor {if (!client.attachedActiveSessionIds.delete(resolvedId)) {continue;}+ this.dropPendingReplacementSnapshot(client, resolvedId);this.write(client, { type: "session_detached", activeSessionId: resolvedId });void this.syncWorkerExtensionUi(resolvedId);}@@ -1864,6 +1964,98 @@ export class DaemonSupervisor {);}+ private streamReplacementSnapshot(+ worker: ResidentWorker,+ activeSessionId: string,+ result: DaemonAttachResult,+ transcript: SnapshotTranscriptCache,+ ): void {+ for (const client of this.clients) {+ if (!client.attachedActiveSessionIds.has(activeSessionId) || !client.capabilities.has("chunked_snapshot")) {+ continue;+ }+ if (client.snapshotActiveSessionIds?.has(activeSessionId)) {+ const pending = this.pendingReplacementSnapshots.get(client) ?? new Map();+ pending.set(activeSessionId, { worker, result, transcript });+ this.pendingReplacementSnapshots.set(client, pending);+ continue;+ }+ this.startReplacementSnapshot(client, worker, activeSessionId, result, transcript);+ }+ }++ private startReplacementSnapshot(+ client: DaemonSocketClient,+ worker: ResidentWorker,+ activeSessionId: string,+ result: DaemonAttachResult,+ transcript: SnapshotTranscriptCache,+ ): void {+ void this.streamSnapshot(client, worker, result, transcript, "replacement").catch((error) =>+ this.log(`Failed to stream replacement snapshot for ${activeSessionId}: ${String(error)}`),+ );+ }++ private flushPendingReplacementSnapshot(client: DaemonSocketClient, activeSessionId: string): void {+ const pending = this.pendingReplacementSnapshots.get(client);+ const replacement = pending?.get(activeSessionId);+ if (!pending || !replacement) {+ return;+ }+ if (+ client.socket.destroyed ||+ !client.attachedActiveSessionIds.has(activeSessionId) ||+ !client.capabilities.has("chunked_snapshot") ||+ replacement.worker.transcriptCaches.get(activeSessionId) !== replacement.transcript+ ) {+ this.dropPendingReplacementSnapshot(client, activeSessionId);+ return;+ }+ if (!replacement.transcript.complete || client.snapshotActiveSessionIds?.has(activeSessionId)) {+ return;+ }+ this.dropPendingReplacementSnapshot(client, activeSessionId);+ this.startReplacementSnapshot(+ client,+ replacement.worker,+ activeSessionId,+ replacement.result,+ replacement.transcript,+ );+ }++ private dropPendingReplacementSnapshot(client: DaemonSocketClient, activeSessionId?: string): void {+ const pending = this.pendingReplacementSnapshots.get(client);+ if (!pending || activeSessionId === undefined) {+ this.pendingReplacementSnapshots.delete(client);+ return;+ }+ pending.delete(activeSessionId);+ if (pending.size === 0) {+ this.pendingReplacementSnapshots.delete(client);+ }+ }++ private dropPendingReplacementSnapshotsForWorker(worker: ResidentWorker, targetActiveSessionId?: string): void {+ for (const client of this.clients) {+ const pending = this.pendingReplacementSnapshots.get(client);+ if (!pending) {+ continue;+ }+ for (const [activeSessionId, replacement] of pending) {+ if (+ replacement.worker === worker &&+ (targetActiveSessionId === undefined || activeSessionId === targetActiveSessionId)+ ) {+ pending.delete(activeSessionId);+ }+ }+ if (pending.size === 0) {+ this.pendingReplacementSnapshots.delete(client);+ }+ }+ }+private handleWorkerFrame(worker: ResidentWorker, frame: PrivateFrame<DaemonWorkerFrameHeader>): void {if (frame.header.kind !== "outbound") {return;@@ -1885,10 +2077,61 @@ export class DaemonSupervisor {) {throw new Error("Worker returned an invalid snapshot begin frame");}- const existing = worker.transcriptCaches.get(activeSessionId);+ let existing = worker.transcriptCaches.get(activeSessionId);+ if (+ worker.incomingTranscriptActiveSessionIds.has(activeSessionId) &&+ existing?.snapshotId === begin.snapshotId+ ) {+ this.failWorkerSnapshotCache(+ worker,+ activeSessionId,+ new Error(`Snapshot ${begin.snapshotId} restarted before completion`),+ true,+ );+ return;+ }+ if (worker.incomingTranscriptActiveSessionIds.has(activeSessionId)) {+ this.settleSnapshotDuplicateValidation(worker, activeSessionId);+ this.failWorkerSnapshotCache(+ worker,+ activeSessionId,+ new Error(`Snapshot ${existing?.snapshotId ?? "unknown"} was superseded`),+ );+ existing = undefined;+ }+ const transferFrames = worker.snapshotTransferFrames.get(activeSessionId);+ const sameSnapshotId = existing?.snapshotId === begin.snapshotId;+ const duplicate =+ existing?.complete === true &&+ sameSnapshotId &&+ transferFrames?.end !== undefined &&+ transferFrames.begin.equals(frame.payload);+ if (existing?.complete && sameSnapshotId && !duplicate) {+ this.failWorkerSnapshotCache(+ worker,+ activeSessionId,+ new Error(`Snapshot ${begin.snapshotId} did not match the cached transfer`),+ true,+ );+ return;+ }+ if (existing?.complete && !duplicate) {+ this.failWorkerSnapshotCache(+ worker,+ activeSessionId,+ new Error(`Snapshot ${existing.snapshotId} was replaced`),+ );+ existing = undefined;+ }let transcript = existing;if (!existing || existing.snapshotId !== begin.snapshotId) {- existing?.dispose();+ if (existing) {+ this.failWorkerSnapshotCache(+ worker,+ activeSessionId,+ new Error(`Snapshot ${begin.snapshotId} replaced stale cache data`),+ );+ }transcript = new SnapshotTranscriptCache({activeSessionId,snapshotId: begin.snapshotId,@@ -1924,23 +2167,31 @@ export class DaemonSupervisor {},client: { id: "supervisor", capabilities: ["chunked_snapshot"] },};- worker.snapshotCache.set(activeSessionId, result);worker.incomingTranscriptActiveSessionIds.add(activeSessionId);- if (snapshotPurpose === "replacement") {- for (const client of this.clients) {- if (- !client.attachedActiveSessionIds.has(activeSessionId) ||- !client.capabilities.has("chunked_snapshot")- ) {- continue;- }- void this.streamSnapshot(client, result, transcript, "replacement").catch((error) =>- this.log(`Failed to stream replacement snapshot for ${activeSessionId}: ${String(error)}`),- );- }+ if (duplicate) {+ worker.duplicateIncomingTranscriptChunkIndexes.set(activeSessionId, 0);+ worker.snapshotTransferFrames.set(activeSessionId, {+ ...transferFrames,+ duplicateResult: result,+ validation: this.createSnapshotDuplicateValidation(),+ });+ worker.snapshotCache.delete(activeSessionId);+ } else {+ worker.duplicateIncomingTranscriptChunkIndexes.delete(activeSessionId);+ worker.snapshotTransferFrames.set(activeSessionId, { begin: Buffer.from(frame.payload) });+ worker.snapshotCache.set(activeSessionId, result);+ }+ if (snapshotPurpose === "replacement" && !duplicate) {+ this.streamReplacementSnapshot(worker, activeSessionId, result, transcript);}} catch (error) {this.log(`Invalid worker snapshot begin frame: ${String(error)}`);+ this.failWorkerSnapshotCache(+ worker,+ activeSessionId,+ error instanceof Error ? error : new Error(String(error)),+ true,+ );}return;}@@ -1948,23 +2199,111 @@ export class DaemonSupervisor {const transcript = worker.transcriptCaches.get(activeSessionId);if (transcript && worker.incomingTranscriptActiveSessionIds.has(activeSessionId)) {try {- transcript.appendEncodedChunk(Buffer.from(frame.payload));+ const duplicateIndex = worker.duplicateIncomingTranscriptChunkIndexes.get(activeSessionId);+ if (duplicateIndex === undefined) {+ transcript.appendEncodedChunk(Buffer.from(frame.payload));+ } else {+ const chunk = JSON.parse(frame.payload.toString("utf8")) as Extract<+ DaemonOutbound,+ { type: "session_snapshot_chunk" }+ >;+ if (+ chunk.type !== "session_snapshot_chunk" ||+ chunk.activeSessionId !== activeSessionId ||+ chunk.snapshotId !== transcript.snapshotId ||+ chunk.index !== duplicateIndex ||+ !transcript.readChunk(duplicateIndex).equals(Buffer.from(frame.payload))+ ) {+ throw new Error(`Duplicate snapshot ${transcript.snapshotId} did not match cached bytes`);+ }+ worker.duplicateIncomingTranscriptChunkIndexes.set(activeSessionId, duplicateIndex + 1);+ }} catch (error) {- transcript.markFailed(error instanceof Error ? error : new Error(String(error)));- worker.incomingTranscriptActiveSessionIds.delete(activeSessionId);+ this.failWorkerSnapshotCache(+ worker,+ activeSessionId,+ error instanceof Error ? error : new Error(String(error)),+ true,+ );}}return;}if (outboundType === "session_snapshot_end" && activeSessionId) {- worker.transcriptCaches.get(activeSessionId)?.markComplete();- worker.incomingTranscriptActiveSessionIds.delete(activeSessionId);+ const transcript = worker.transcriptCaches.get(activeSessionId);+ if (!transcript || !worker.incomingTranscriptActiveSessionIds.has(activeSessionId)) {+ return;+ }+ let completedDuplicate = false;+ try {+ const duplicateChunkCount = worker.duplicateIncomingTranscriptChunkIndexes.get(activeSessionId);+ if (duplicateChunkCount === undefined) {+ transcript.markComplete();+ const begin = worker.snapshotTransferFrames.get(activeSessionId)?.begin;+ if (!begin) {+ throw new Error(`Snapshot ${transcript.snapshotId} has no begin frame`);+ }+ worker.snapshotTransferFrames.set(activeSessionId, {+ begin,+ end: Buffer.from(frame.payload),+ });+ } else {+ const transferFrames = worker.snapshotTransferFrames.get(activeSessionId);+ const end = JSON.parse(frame.payload.toString("utf8")) as Extract<+ DaemonOutbound,+ { type: "session_snapshot_end" }+ >;+ if (+ end.type !== "session_snapshot_end" ||+ end.activeSessionId !== activeSessionId ||+ end.snapshotId !== transcript.snapshotId ||+ end.chunkCount !== duplicateChunkCount ||+ end.chunkCount !== transcript.chunkCount ||+ !transferFrames?.end?.equals(frame.payload)+ ) {+ throw new Error(`Duplicate snapshot ${transcript.snapshotId} ended with different metadata`);+ }+ if (!transferFrames.duplicateResult) {+ throw new Error(`Duplicate snapshot ${transcript.snapshotId} has no result`);+ }+ worker.snapshotCache.set(activeSessionId, transferFrames.duplicateResult);+ this.settleSnapshotDuplicateValidation(worker, activeSessionId);+ worker.snapshotTransferFrames.set(activeSessionId, {+ begin: transferFrames.begin,+ end: transferFrames.end,+ });+ completedDuplicate = true;+ }+ worker.incomingTranscriptActiveSessionIds.delete(activeSessionId);+ worker.duplicateIncomingTranscriptChunkIndexes.delete(activeSessionId);+ } catch (error) {+ this.failWorkerSnapshotCache(+ worker,+ activeSessionId,+ error instanceof Error ? error : new Error(String(error)),+ true,+ );+ return;+ }+ if (snapshotPurpose === "replacement" && completedDuplicate) {+ const result = worker.snapshotCache.get(activeSessionId);+ if (result) {+ this.streamReplacementSnapshot(worker, activeSessionId, result, transcript);+ }+ }+ if (snapshotPurpose === "replacement") {+ for (const client of this.clients) {+ this.flushPendingReplacementSnapshot(client, activeSessionId);+ }+ }if (snapshotPurpose === "replacement" || snapshotPurpose === "catchup") {for (const client of this.clients) {if (!client.attachedActiveSessionIds.has(activeSessionId)) continue;if (snapshotPurpose === "replacement" && client.capabilities.has("chunked_snapshot")) continue;this.queueCatchup(client, activeSessionId, snapshotPurpose === "replacement" ? "replacement" : "resync");- void this.catchUpClient(client);+ void this.catchUpClient(client).catch((error) =>+ this.log(`Failed to catch up client ${client.id}: ${String(error)}`),+ );}}return;@@ -2082,6 +2421,13 @@ export class DaemonSupervisor {worker.transcriptCaches.delete(activeSessionId);}worker.incomingTranscriptActiveSessionIds.delete(activeSessionId);+ worker.duplicateIncomingTranscriptChunkIndexes.delete(activeSessionId);+ this.settleSnapshotDuplicateValidation(+ worker,+ activeSessionId,+ new Error(`Snapshot ${activeSessionId} was invalidated`),+ );+ worker.snapshotTransferFrames.delete(activeSessionId);}private scheduleCompactCatchup(worker: ResidentWorker, activeSessionId: string): void {@@ -2094,9 +2440,11 @@ export class DaemonSupervisor {for (const client of clients) {this.queueCatchup(client, activeSessionId);}- void Promise.all(clients.map((client) => this.catchUpClient(client))).finally(() => {- this.compactCatchupInProgress.delete(activeSessionId);- });+ void Promise.all(clients.map((client) => this.catchUpClient(client)))+ .catch((error) => this.log(`Failed compact catch-up for ${activeSessionId}: ${String(error)}`))+ .finally(() => {+ this.compactCatchupInProgress.delete(activeSessionId);+ });}private queueCatchup(@@ -2153,6 +2501,7 @@ export class DaemonSupervisor {}await this.streamSnapshot(client,+ attached.worker,this.createStreamedAttachResult(attached.result, transcript),transcript,purpose,@@ -2307,11 +2656,32 @@ export class DaemonSupervisor {worker.descriptor.lifecycle = "recovering";this.persistWorker(worker);}+ this.dropPendingReplacementSnapshotsForWorker(worker);+ const interruptedSnapshots = new Set([+ ...worker.incomingTranscriptActiveSessionIds,+ ...worker.duplicateIncomingTranscriptChunkIndexes.keys(),+ ...[...worker.transcriptCaches]+ .filter(([, transcript]) => !transcript.complete)+ .map(([activeSessionId]) => activeSessionId),+ ...[...worker.snapshotTransferFrames]+ .filter(([, transfer]) => transfer.validation !== undefined)+ .map(([activeSessionId]) => activeSessionId),+ ]);+ for (const activeSessionId of interruptedSnapshots) {+ this.failWorkerSnapshotCache(+ worker,+ activeSessionId,+ new Error("Session worker stopped during snapshot transfer"),+ );+ }for (const transcript of worker.transcriptCaches.values()) {transcript.dispose();}worker.transcriptCaches.clear();worker.snapshotCache.clear();+ worker.incomingTranscriptActiveSessionIds.clear();+ worker.duplicateIncomingTranscriptChunkIndexes.clear();+ worker.snapshotTransferFrames.clear();if (worker.client) {if (archiveSession) {await worker.client@@ -2466,6 +2836,7 @@ export class DaemonSupervisor {}await this.catalog.stop();for (const client of this.clients) {+ this.dropPendingReplacementSnapshot(client);client.detachInput();client.socket.end();}diff --git a/packages/coding-agent/src/modes/daemon/snapshot-transcript-cache.ts b/packages/coding-agent/src/modes/daemon/snapshot-transcript-cache.tsindex e51c9c649b..5996c63118 100644--- a/packages/coding-agent/src/modes/daemon/snapshot-transcript-cache.ts+++ b/packages/coding-agent/src/modes/daemon/snapshot-transcript-cache.ts@@ -50,6 +50,10 @@ export class SnapshotTranscriptCache {return this.chunks.length;}+ get complete(): boolean {+ return this.completed && !this.failure && !this.disposed;+ }+get bytes(): number {return this.totalBytes;}@@ -73,13 +77,19 @@ export class SnapshotTranscriptCache {}appendEncodedChunk(buffer: Buffer): void {- if (this.completed) {- throw new Error(`Snapshot transcript ${this.snapshotId} is already complete`);+ if (this.completed || this.failure || this.disposed) {+ throw new Error(`Snapshot transcript ${this.snapshotId} is not writable`);}this.storeChunk(buffer);}markComplete(): void {+ if (this.completed) {+ return;+ }+ if (this.failure || this.disposed) {+ throw new Error(`Snapshot transcript ${this.snapshotId} cannot be completed`);+ }this.completed = true;for (const [index, waiters] of this.chunkWaiters) {if (index < this.chunks.length) {@@ -93,6 +103,9 @@ export class SnapshotTranscriptCache {}markFailed(error: Error): void {+ if (this.failure) {+ return;+ }this.failure = error;for (const waiters of this.chunkWaiters.values()) {for (const waiter of waiters) {@@ -103,12 +116,12 @@ export class SnapshotTranscriptCache {}waitForChunk(index: number): Promise<Buffer | undefined> {- if (index < this.chunks.length) {- return Promise.resolve(this.readChunk(index));- }if (this.failure) {return Promise.reject(this.failure);}+ if (index < this.chunks.length) {+ return Promise.resolve(this.readChunk(index));+ }if (this.completed) {return Promise.resolve(undefined);}diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.tsindex 269cb2860d..7fd72e5586 100644--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts@@ -345,6 +345,7 @@ describe("daemon worker supervisor monitoring", () => {descriptor: { workerId: "worker-1", lifecycle: "ready", pid: 1234 },summaries: new Map([[activeSessionId, summary]]),snapshotCache: new Map([[activeSessionId, result]]),+ snapshotTransferFrames: new Map(),snapshotLoads: new Map(),};const client = {@@ -430,6 +431,7 @@ describe("daemon worker supervisor monitoring", () => {snapshotCache: new Map(),transcriptCaches: new Map(),incomingTranscriptActiveSessionIds: new Set(),+ snapshotTransferFrames: new Map(),snapshotLoads: new Map(),};const client: AttachClient = {diff --git a/packages/coding-agent/test/snapshot-transcript-cache.test.ts b/packages/coding-agent/test/snapshot-transcript-cache.test.tsindex 02b102d3fc..287ee5301c 100644--- a/packages/coding-agent/test/snapshot-transcript-cache.test.ts+++ b/packages/coding-agent/test/snapshot-transcript-cache.test.ts@@ -97,4 +97,38 @@ describe("snapshot transcript cache", () => {release();expect(() => cache.readChunk(0)).toThrow("Unknown snapshot transcript chunk");});++ it("fails pending readers before deferred disposal", async () => {+ const cache = new SnapshotTranscriptCache({+ activeSessionId: "active-e",+ snapshotId: "snapshot-e",+ cacheRoot: tempDir(),+ });+ const release = cache.retain();+ const pending = cache.waitForChunk(0);+ const failure = new Error("snapshot source failed");++ cache.markFailed(failure);+ cache.dispose();++ await expect(pending).rejects.toBe(failure);+ release();+ expect(cache.complete).toBe(false);+ });++ it("completes repeated endings idempotently", () => {+ const cache = new SnapshotTranscriptCache({+ activeSessionId: "active-f",+ snapshotId: "snapshot-f",+ cacheRoot: tempDir(),+ });+ cache.appendEncodedChunk(Buffer.from("chunk"));++ cache.markComplete();+ cache.markComplete();++ expect(cache.complete).toBe(true);+ expect(() => cache.appendEncodedChunk(Buffer.from("stale"))).toThrow("is not writable");+ cache.dispose();+ });});diff --git a/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts b/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.tsnew file mode 100644index 0000000000..65697ce3a5--- /dev/null+++ b/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts@@ -0,0 +1,743 @@+import type { Socket } from "node:net";+import { PassThrough } from "node:stream";+import type { AgentMessage } from "@earendil-works/pi-agent-core";+import { describe, expect, it, vi } from "vitest";+import type { ActiveSessionState, DaemonSocketClient } from "../../../src/modes/daemon/active-session-state.js";+import { AgentDaemon } from "../../../src/modes/daemon/daemon-mode.js";+import {+ DAEMON_PROTOCOL_INFO,+ type DaemonAttachResult,+ type DaemonCommand,+ type DaemonOutbound,+} from "../../../src/modes/daemon/daemon-protocol.js";+import type { SessionSummary } from "../../../src/modes/daemon/daemon-session-list.js";+import { DaemonSupervisor } from "../../../src/modes/daemon/daemon-supervisor.js";+import type { DaemonWorkerFrameHeader } from "../../../src/modes/daemon/daemon-worker-protocol.js";+import { SnapshotTranscriptCache } from "../../../src/modes/daemon/snapshot-transcript-cache.js";+import type { PrivateFrame } from "../../../src/modes/session-worker/private-framing.js";++const activeSessionId = "active-4602";+const snapshotId = "snapshot-4602";++interface WorkerHarness {+ descriptor: { workerId: string; lifecycle: "ready" | "recovering"; pid: number };+ client?: { close: ReturnType<typeof vi.fn>; request: ReturnType<typeof vi.fn> };+ summaries: Map<string, SessionSummary>;+ snapshotCache: Map<string, DaemonAttachResult>;+ transcriptCaches: Map<string, SnapshotTranscriptCache>;+ incomingTranscriptActiveSessionIds: Set<string>;+ duplicateIncomingTranscriptChunkIndexes: Map<string, number>;+ snapshotTransferFrames: Map<+ string,+ {+ begin: Buffer;+ end?: Buffer;+ duplicateResult?: DaemonAttachResult;+ validation?: { promise: Promise<void>; resolve: () => void; reject: (error: Error) => void };+ }+ >;+ snapshotLoads: Map<string, Promise<DaemonAttachResult>>;+ intentionalStop: boolean;+ stopRevision: number;+}++function summary(): SessionSummary {+ return {+ id: activeSessionId,+ activeSessionId,+ lifecycle: "live",+ activity: "idle",+ sessionId: "session-4602",+ cwd: "/tmp",+ isStreaming: false,+ isCompacting: false,+ attachedClients: 0,+ messageCount: 1,+ pendingMessageCount: 0,+ };+}++function streamedResult(messages: AgentMessage[]): DaemonAttachResult {+ return {+ protocol: DAEMON_PROTOCOL_INFO,+ activeSessionId,+ snapshot: {+ activeSessionId,+ summary: summary(),+ state: { activeSessionId, sessionId: "session-4602" } as DaemonAttachResult["snapshot"]["state"],+ messages,+ lastEventSequence: 1,+ },+ replay: { status: "complete", toSequence: 1 },+ lastEventSequence: 1,+ snapshotStream: { id: snapshotId, messageCount: messages.length, targetChunkBytes: 512 * 1024 },+ client: { id: "worker", capabilities: ["chunked_snapshot"] },+ };+}++function frame(+ message: DaemonOutbound,+ snapshotPurpose?: "attach" | "replacement" | "catchup",+): PrivateFrame<DaemonWorkerFrameHeader> {+ return {+ header: {+ kind: "outbound",+ outboundType: message.type,+ ...("activeSessionId" in message ? { activeSessionId: message.activeSessionId } : {}),+ payloadEncoding: "jsonl",+ ...(snapshotPurpose ? { snapshotPurpose } : {}),+ },+ payload: Buffer.from(JSON.stringify(message)),+ };+}++function workerHarness() {+ const close = vi.fn();+ const request = vi.fn(async (command: { type: string }) => {+ if (command.type === "shutdown") {+ return { success: true };+ }+ throw new Error("unexpected snapshot reload");+ });+ const worker: WorkerHarness = {+ descriptor: { workerId: "worker-4602", lifecycle: "ready", pid: 987_654_321 },+ client: { close, request },+ summaries: new Map([[activeSessionId, summary()]]),+ snapshotCache: new Map(),+ transcriptCaches: new Map<string, SnapshotTranscriptCache>(),+ incomingTranscriptActiveSessionIds: new Set<string>(),+ duplicateIncomingTranscriptChunkIndexes: new Map<string, number>(),+ snapshotTransferFrames: new Map(),+ snapshotLoads: new Map(),+ intentionalStop: false,+ stopRevision: 0,+ };+ return { close, request, worker };+}++function socketClient(id: string, socket: PassThrough): DaemonSocketClient {+ return {+ id,+ socket: socket as unknown as Socket,+ attachedActiveSessionIds: new Set([activeSessionId]),+ catchupActiveSessionIds: new Set<string>(),+ detachInput: () => {},+ supportsExtensionUi: false,+ capabilities: new Set(["chunked_snapshot"]),+ } as DaemonSocketClient;+}++function snapshotFrames(messages: AgentMessage[]) {+ const result = streamedResult([]);+ const { messages: _messages, ...snapshot } = result.snapshot;+ return {+ begin: {+ type: "session_snapshot_begin",+ activeSessionId,+ snapshotId,+ snapshot,+ messageCount: messages.length,+ targetChunkBytes: 512 * 1024,+ } satisfies DaemonOutbound,+ chunk: {+ type: "session_snapshot_chunk",+ activeSessionId,+ snapshotId,+ index: 0,+ messages,+ } satisfies DaemonOutbound,+ end: {+ type: "session_snapshot_end",+ activeSessionId,+ snapshotId,+ chunkCount: 1,+ lastEventSequence: 1,+ } satisfies DaemonOutbound,+ };+}++describe("ENG-4602 snapshot transfer containment", () => {+ it("observes the deferred attach snapshot promise", async () => {+ const daemon = new AgentDaemon("/tmp/eng-4602-worker.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const state = {+ activeSessionId,+ clients: new Set<DaemonSocketClient>(),+ eventGeneration: "generation-4602",+ lastEventSequence: 1,+ runtime: { metadata: { kind: "top-level", createdAt: 1 } },+ } as unknown as ActiveSessionState;+ const socket = new PassThrough();+ const client = {+ id: "supervisor",+ socket: socket as unknown as Socket,+ transport: "private-framed",+ attachedActiveSessionIds: new Set<string>(),+ detachInput: () => {},+ supportsExtensionUi: false,+ capabilities: new Set<string>(),+ } as DaemonSocketClient;+ const streamError = new Error("encoder failed after begin");+ const log = vi.fn();+ const streamWorkerSnapshot = vi.fn(async () => {+ throw streamError;+ });+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAttachResult(): DaemonAttachResult;+ streamWorkerSnapshot: typeof streamWorkerSnapshot;+ log: typeof log;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ };+ internals.sessions.set(activeSessionId, state);+ internals.createAttachResult = () => streamedResult([]);+ internals.streamWorkerSnapshot = streamWorkerSnapshot;+ internals.log = log;+ const unhandled = vi.fn();+ process.on("unhandledRejection", unhandled);+ try {+ await internals.handleCommand(client, {+ type: "attach",+ activeSessionId,+ capabilities: ["attach_snapshot", "event_sequence", "slim_attach", "chunked_snapshot"],+ });+ await new Promise<void>((resolve) => setImmediate(resolve));+ await new Promise<void>((resolve) => setImmediate(resolve));+ } finally {+ process.off("unhandledRejection", unhandled);+ socket.destroy();+ }++ expect(streamWorkerSnapshot).toHaveBeenCalledOnce();+ expect(log).toHaveBeenCalledWith(`could not stream attach snapshot: ${String(streamError)}`);+ expect(unhandled).not.toHaveBeenCalled();+ });++ it("fails the cache and worker channel when streaming rejects after begin", async () => {+ const daemon = new AgentDaemon("/tmp/eng-4602-stream.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const transcript = new SnapshotTranscriptCache({+ activeSessionId,+ snapshotId,+ messages: [{ role: "user", content: "message", timestamp: 1 }],+ cacheRoot: "/tmp",+ });+ const streamError = new Error("chunk read failed");+ transcript.readChunk = vi.fn(() => {+ throw streamError;+ });+ const markFailed = vi.spyOn(transcript, "markFailed");+ const dispose = vi.spyOn(transcript, "dispose");+ const socket = new PassThrough();+ socket.on("error", () => {});+ const destroy = vi.spyOn(socket, "destroy");+ const client = {+ id: "supervisor",+ socket: socket as unknown as Socket,+ transport: "private-framed",+ attachedActiveSessionIds: new Set([activeSessionId]),+ catchupActiveSessionIds: new Set<string>(),+ detachInput: () => {},+ supportsExtensionUi: false,+ capabilities: new Set(["chunked_snapshot"]),+ } as DaemonSocketClient;+ const internals = daemon as unknown as {+ streamWorkerSnapshot(+ client: DaemonSocketClient,+ result: DaemonAttachResult,+ transcript: SnapshotTranscriptCache,+ ): Promise<void>;+ };++ await expect(internals.streamWorkerSnapshot(client, streamedResult([]), transcript)).rejects.toBe(streamError);+ expect(socket.destroyed).toBe(true);+ expect(transcript.complete).toBe(false);+ expect(client.snapshotStreaming).toBe(false);+ expect(markFailed.mock.invocationCallOrder[0]).toBeLessThan(dispose.mock.invocationCallOrder[0]!);+ expect(dispose.mock.invocationCallOrder[0]).toBeLessThan(destroy.mock.invocationCallOrder[0]!);+ });++ it("quarantines a completed duplicate until exact replacement validation", () => {+ const supervisor = new DaemonSupervisor("/tmp/eng-4602-supervisor.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: "/tmp/eng-4602-supervisor-state",+ });+ const { close, worker } = workerHarness();+ worker.intentionalStop = true;+ const client = socketClient("public", new PassThrough());+ const streamSnapshot = vi.fn(async () => {});+ const internals = supervisor as unknown as {+ clients: Set<DaemonSocketClient>;+ streamSnapshot: typeof streamSnapshot;+ handleWorkerFrame(worker: WorkerHarness, frame: PrivateFrame<DaemonWorkerFrameHeader>): void;+ };+ internals.clients.add(client);+ internals.streamSnapshot = streamSnapshot;+ const messages: AgentMessage[] = [{ role: "user", content: "stable", timestamp: 1 }];+ const frames = snapshotFrames(messages);++ for (const message of [frames.begin, frames.chunk, frames.end]) {+ internals.handleWorkerFrame(worker, frame(message));+ }++ expect(worker.transcriptCaches.get(activeSessionId)?.complete).toBe(true);+ expect(worker.transcriptCaches.get(activeSessionId)?.chunkCount).toBe(1);+ expect(close).not.toHaveBeenCalled();++ internals.handleWorkerFrame(worker, frame(frames.begin, "replacement"));+ internals.handleWorkerFrame(worker, frame(frames.chunk, "replacement"));+ expect(worker.snapshotCache.has(activeSessionId)).toBe(false);+ expect(streamSnapshot).not.toHaveBeenCalled();++ internals.handleWorkerFrame(worker, frame(frames.end, "replacement"));+ expect(worker.snapshotCache.has(activeSessionId)).toBe(true);+ expect(streamSnapshot).toHaveBeenCalledOnce();+ expect(close).not.toHaveBeenCalled();+ streamSnapshot.mockClear();++ internals.handleWorkerFrame(worker, frame(frames.begin, "replacement"));+ internals.handleWorkerFrame(+ worker,+ frame(+ {+ ...frames.chunk,+ messages: [{ role: "user", content: "stale", timestamp: 2 }],+ },+ "replacement",+ ),+ );++ expect(worker.transcriptCaches.has(activeSessionId)).toBe(false);+ expect(worker.snapshotCache.has(activeSessionId)).toBe(false);+ expect(streamSnapshot).not.toHaveBeenCalled();+ expect(close).toHaveBeenCalledOnce();+ });++ it("queues a replacement until the active client snapshot finishes", async () => {+ const supervisor = new DaemonSupervisor("/tmp/eng-4602-supervisor-ordered-replacement.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: "/tmp/eng-4602-supervisor-ordered-replacement-state",+ });+ const { worker } = workerHarness();+ const client = socketClient("public", new PassThrough());+ const messages: AgentMessage[] = [{ role: "user", content: "stable", timestamp: 1 }];+ const result = streamedResult(messages);+ const transcript = new SnapshotTranscriptCache({+ activeSessionId,+ snapshotId,+ messages,+ cacheRoot: "/tmp",+ });+ worker.transcriptCaches.set(activeSessionId, transcript);+ const written: DaemonOutbound[] = [];+ let releaseFirstWrite!: (accepted: boolean) => void;+ const firstWrite = new Promise<boolean>((resolve) => {+ releaseFirstWrite = resolve;+ });+ const writeSnapshotBuffer = vi.fn((_client: DaemonSocketClient, buffer: Uint8Array) => {+ written.push(JSON.parse(Buffer.from(buffer).toString("utf8")) as DaemonOutbound);+ return written.length === 1 ? firstWrite : Promise.resolve(true);+ });+ const internals = supervisor as unknown as {+ clients: Set<DaemonSocketClient>;+ pendingReplacementSnapshots: WeakMap<DaemonSocketClient, Map<string, unknown>>;+ writeSnapshotBuffer: typeof writeSnapshotBuffer;+ streamSnapshot(+ client: DaemonSocketClient,+ worker: WorkerHarness,+ result: DaemonAttachResult,+ transcript: SnapshotTranscriptCache,+ purpose: "attach" | "replacement" | "resync",+ ): Promise<void>;+ streamReplacementSnapshot(+ worker: WorkerHarness,+ activeSessionId: string,+ result: DaemonAttachResult,+ transcript: SnapshotTranscriptCache,+ ): void;+ };+ internals.clients.add(client);+ internals.writeSnapshotBuffer = writeSnapshotBuffer;++ const activeStream = internals.streamSnapshot(client, worker, result, transcript, "resync");+ await Promise.resolve();+ internals.streamReplacementSnapshot(worker, activeSessionId, result, transcript);+ await Promise.resolve();++ expect(written).toHaveLength(1);+ expect(written[0]).toMatchObject({ type: "session_snapshot_begin", purpose: "resync" });+ expect(client.snapshotActiveSessionIds?.has(activeSessionId)).toBe(true);++ releaseFirstWrite(true);+ await activeStream;+ await new Promise<void>((resolve) => setImmediate(resolve));++ expect(written.map((message) => message.type)).toEqual([+ "session_snapshot_begin",+ "session_snapshot_chunk",+ "session_snapshot_end",+ "session_snapshot_begin",+ "session_snapshot_chunk",+ "session_snapshot_end",+ ]);+ expect(written.filter((message) => message.type === "session_snapshot_begin")).toMatchObject([+ { purpose: "resync" },+ { purpose: "replacement" },+ ]);+ expect(client.snapshotActiveSessionIds?.has(activeSessionId)).toBe(false);+ expect(client.snapshotStreaming).toBe(false);+ expect(internals.pendingReplacementSnapshots.get(client)?.size ?? 0).toBe(0);+ });++ it("retains a queued replacement until its worker transcript completes", async () => {+ const supervisor = new DaemonSupervisor("/tmp/eng-4602-supervisor-pending-replacement.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: "/tmp/eng-4602-supervisor-pending-replacement-state",+ });+ const { worker } = workerHarness();+ const client = socketClient("public", new PassThrough());+ const firstMessages: AgentMessage[] = [{ role: "user", content: "first", timestamp: 1 }];+ const firstResult = streamedResult(firstMessages);+ const firstTranscript = new SnapshotTranscriptCache({+ activeSessionId,+ snapshotId,+ messages: firstMessages,+ cacheRoot: "/tmp",+ });+ worker.transcriptCaches.set(activeSessionId, firstTranscript);+ const written: DaemonOutbound[] = [];+ let releaseActiveEnd!: (accepted: boolean) => void;+ const activeEnd = new Promise<boolean>((resolve) => {+ releaseActiveEnd = resolve;+ });+ let markActiveEndStarted!: () => void;+ const activeEndStarted = new Promise<void>((resolve) => {+ markActiveEndStarted = resolve;+ });+ const writeSnapshotBuffer = vi.fn((_client: DaemonSocketClient, buffer: Uint8Array) => {+ const message = JSON.parse(Buffer.from(buffer).toString("utf8")) as DaemonOutbound;+ written.push(message);+ if (message.type === "session_snapshot_end" && written.length === 3) {+ markActiveEndStarted();+ return activeEnd;+ }+ return Promise.resolve(true);+ });+ const internals = supervisor as unknown as {+ clients: Set<DaemonSocketClient>;+ pendingReplacementSnapshots: WeakMap<DaemonSocketClient, Map<string, unknown>>;+ writeSnapshotBuffer: typeof writeSnapshotBuffer;+ streamSnapshot(+ client: DaemonSocketClient,+ worker: WorkerHarness,+ result: DaemonAttachResult,+ transcript: SnapshotTranscriptCache,+ purpose: "attach" | "replacement" | "resync",+ ): Promise<void>;+ handleWorkerFrame(worker: WorkerHarness, frame: PrivateFrame<DaemonWorkerFrameHeader>): void;+ };+ internals.clients.add(client);+ internals.writeSnapshotBuffer = writeSnapshotBuffer;++ const activeStream = internals.streamSnapshot(client, worker, firstResult, firstTranscript, "resync");+ await activeEndStarted;+ const frames = snapshotFrames([{ role: "user", content: "replacement", timestamp: 2 }]);+ const replacementSnapshotId = "snapshot-4602-replacement";+ const replacementBegin = { ...frames.begin, snapshotId: replacementSnapshotId };+ const replacementChunk = { ...frames.chunk, snapshotId: replacementSnapshotId };+ const replacementEnd = { ...frames.end, snapshotId: replacementSnapshotId };+ internals.handleWorkerFrame(worker, frame(replacementBegin, "replacement"));++ expect(worker.transcriptCaches.get(activeSessionId)?.complete).toBe(false);+ expect(internals.pendingReplacementSnapshots.get(client)?.size).toBe(1);++ releaseActiveEnd(true);+ await activeStream;+ await new Promise<void>((resolve) => setImmediate(resolve));++ expect(written.filter((message) => message.type === "session_snapshot_begin")).toHaveLength(1);+ expect(internals.pendingReplacementSnapshots.get(client)?.size).toBe(1);++ internals.handleWorkerFrame(worker, frame(replacementChunk, "replacement"));+ internals.handleWorkerFrame(worker, frame(replacementEnd, "replacement"));+ await new Promise<void>((resolve) => setImmediate(resolve));++ expect(written.map((message) => message.type)).toEqual([+ "session_snapshot_begin",+ "session_snapshot_chunk",+ "session_snapshot_end",+ "session_snapshot_begin",+ "session_snapshot_chunk",+ "session_snapshot_end",+ ]);+ expect(written.filter((message) => message.type === "session_snapshot_begin")).toMatchObject([+ { purpose: "resync", snapshotId },+ { purpose: "replacement", snapshotId: replacementSnapshotId },+ ]);+ expect(internals.pendingReplacementSnapshots.get(client)?.size ?? 0).toBe(0);+ });++ it("holds catch-up behind duplicate validation and rejects it on mismatch", async () => {+ const supervisor = new DaemonSupervisor("/tmp/eng-4602-supervisor-gate.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: "/tmp/eng-4602-supervisor-gate-state",+ });+ const { close, request, worker } = workerHarness();+ worker.intentionalStop = true;+ const client = socketClient("catchup", new PassThrough());+ const streamSnapshot = vi.fn(async () => {});+ const internals = supervisor as unknown as {+ clients: Set<DaemonSocketClient>;+ workers: Map<string, WorkerHarness>;+ streamSnapshot: typeof streamSnapshot;+ catchUpClient(client: DaemonSocketClient): Promise<void>;+ handleWorkerFrame(worker: WorkerHarness, frame: PrivateFrame<DaemonWorkerFrameHeader>): void;+ };+ internals.clients.add(client);+ internals.workers.set(worker.descriptor.workerId, worker);+ internals.streamSnapshot = streamSnapshot;+ const frames = snapshotFrames([{ role: "user", content: "stable", timestamp: 1 }]);+ for (const message of [frames.begin, frames.chunk, frames.end]) {+ internals.handleWorkerFrame(worker, frame(message));+ }++ internals.handleWorkerFrame(worker, frame(frames.begin));+ client.catchupActiveSessionIds?.add(activeSessionId);+ const catchup = internals.catchUpClient(client);+ await Promise.resolve();+ await Promise.resolve();++ expect(worker.snapshotCache.has(activeSessionId)).toBe(false);+ expect(request).not.toHaveBeenCalled();+ expect(streamSnapshot).not.toHaveBeenCalled();++ internals.handleWorkerFrame(worker, frame(frames.chunk));+ internals.handleWorkerFrame(worker, frame(frames.end));+ await catchup;++ expect(worker.snapshotCache.has(activeSessionId)).toBe(true);+ expect(request).not.toHaveBeenCalled();+ expect(streamSnapshot).toHaveBeenCalledOnce();+ streamSnapshot.mockClear();++ internals.handleWorkerFrame(worker, frame(frames.begin));+ client.catchupActiveSessionIds?.add(activeSessionId);+ const failedCatchup = internals.catchUpClient(client);+ await Promise.resolve();+ await Promise.resolve();+ internals.handleWorkerFrame(+ worker,+ frame({+ ...frames.chunk,+ messages: [{ role: "user", content: "mismatch", timestamp: 2 }],+ }),+ );+ await failedCatchup;++ expect(request).not.toHaveBeenCalled();+ expect(streamSnapshot).not.toHaveBeenCalled();+ expect(worker.snapshotCache.has(activeSessionId)).toBe(false);+ expect(worker.transcriptCaches.has(activeSessionId)).toBe(false);+ expect(close).toHaveBeenCalledOnce();+ });++ it("rejects a quarantined catch-up before intentional worker stop", async () => {+ const supervisor = new DaemonSupervisor("/tmp/eng-4602-supervisor-stop.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: "/tmp/eng-4602-supervisor-stop-state",+ });+ const { close, request, worker } = workerHarness();+ const client = socketClient("catchup", new PassThrough());+ const streamSnapshot = vi.fn(async () => {});+ const persistWorker = vi.fn();+ const internals = supervisor as unknown as {+ clients: Set<DaemonSocketClient>;+ workers: Map<string, WorkerHarness>;+ shuttingDown: boolean;+ streamSnapshot: typeof streamSnapshot;+ persistWorker: typeof persistWorker;+ catchUpClient(client: DaemonSocketClient): Promise<void>;+ handleWorkerFrame(worker: WorkerHarness, frame: PrivateFrame<DaemonWorkerFrameHeader>): void;+ stopWorker(worker: WorkerHarness, removeDescriptor: boolean): Promise<void>;+ };+ internals.clients.add(client);+ internals.workers.set(worker.descriptor.workerId, worker);+ internals.shuttingDown = true;+ internals.streamSnapshot = streamSnapshot;+ internals.persistWorker = persistWorker;+ const frames = snapshotFrames([{ role: "user", content: "stable", timestamp: 1 }]);+ for (const message of [frames.begin, frames.chunk, frames.end, frames.begin]) {+ internals.handleWorkerFrame(worker, frame(message));+ }+ const validation = worker.snapshotTransferFrames.get(activeSessionId)?.validation?.promise;+ if (!validation) {+ throw new Error("duplicate validation was not created");+ }+ client.catchupActiveSessionIds?.add(activeSessionId);+ const catchup = internals.catchUpClient(client);+ await Promise.resolve();+ await Promise.resolve();+ expect(request).not.toHaveBeenCalled();+ expect(streamSnapshot).not.toHaveBeenCalled();++ const unhandled = vi.fn();+ process.on("unhandledRejection", unhandled);+ try {+ const validationFailure = expect(validation).rejects.toThrow("stopped during snapshot transfer");+ await internals.stopWorker(worker, false);+ await validationFailure;+ await catchup;+ await new Promise<void>((resolve) => setImmediate(resolve));+ } finally {+ process.off("unhandledRejection", unhandled);+ }++ expect(request.mock.calls.some(([command]) => command.type === "attach")).toBe(false);+ expect(request.mock.calls.some(([command]) => command.type === "shutdown")).toBe(true);+ expect(streamSnapshot).not.toHaveBeenCalled();+ expect(close).toHaveBeenCalledOnce();+ expect(worker.snapshotCache.size).toBe(0);+ expect(worker.transcriptCaches.size).toBe(0);+ expect(worker.incomingTranscriptActiveSessionIds.size).toBe(0);+ expect(worker.duplicateIncomingTranscriptChunkIndexes.size).toBe(0);+ expect(worker.snapshotTransferFrames.size).toBe(0);+ expect(unhandled).not.toHaveBeenCalled();+ });++ it("lets a retained completed snapshot reader finish during intentional worker stop", async () => {+ const supervisor = new DaemonSupervisor("/tmp/eng-4602-supervisor-reader-stop.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: "/tmp/eng-4602-supervisor-reader-stop-state",+ });+ const { worker } = workerHarness();+ const persistWorker = vi.fn();+ const internals = supervisor as unknown as {+ persistWorker: typeof persistWorker;+ handleWorkerFrame(worker: WorkerHarness, frame: PrivateFrame<DaemonWorkerFrameHeader>): void;+ stopWorker(worker: WorkerHarness, removeDescriptor: boolean): Promise<void>;+ };+ internals.persistWorker = persistWorker;+ const frames = snapshotFrames([{ role: "user", content: "stable", timestamp: 1 }]);+ for (const message of [frames.begin, frames.chunk, frames.end]) {+ internals.handleWorkerFrame(worker, frame(message));+ }+ const transcript = worker.transcriptCaches.get(activeSessionId);+ if (!transcript) {+ throw new Error("completed transcript was not cached");+ }+ const release = transcript.retain();++ await internals.stopWorker(worker, false);++ await expect(transcript.waitForChunk(0)).resolves.toEqual(frame(frames.chunk).payload);+ await expect(transcript.waitForChunk(1)).resolves.toBeUndefined();+ release();+ expect(worker.transcriptCaches.size).toBe(0);+ expect(worker.snapshotCache.size).toBe(0);+ expect(worker.snapshotTransferFrames.size).toBe(0);+ });++ it("rejects same-ID reentrant begins and mismatched duplicate metadata", () => {+ const supervisor = new DaemonSupervisor("/tmp/eng-4602-supervisor-invalid.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: "/tmp/eng-4602-supervisor-invalid-state",+ });+ const recoverWorker = vi.fn(async () => {});+ const persistWorker = vi.fn();+ const syncAgentPeers = vi.fn(async () => {});+ const internals = supervisor as unknown as {+ recoverWorker: typeof recoverWorker;+ persistWorker: typeof persistWorker;+ syncAgentPeers: typeof syncAgentPeers;+ handleWorkerFrame(worker: WorkerHarness, frame: PrivateFrame<DaemonWorkerFrameHeader>): void;+ };+ internals.recoverWorker = recoverWorker;+ internals.persistWorker = persistWorker;+ internals.syncAgentPeers = syncAgentPeers;+ const frames = snapshotFrames([{ role: "user", content: "stable", timestamp: 1 }]);++ const reentrant = workerHarness();+ internals.handleWorkerFrame(reentrant.worker, frame(frames.begin));+ internals.handleWorkerFrame(reentrant.worker, frame(frames.begin));+ expect(reentrant.close).toHaveBeenCalledOnce();+ expect(reentrant.worker.transcriptCaches.has(activeSessionId)).toBe(false);+ expect(reentrant.worker.client).toBeUndefined();+ expect(reentrant.worker.descriptor.lifecycle).toBe("recovering");+ expect(recoverWorker).toHaveBeenCalledWith(reentrant.worker);++ const completed = workerHarness();+ for (const message of [frames.begin, frames.chunk, frames.end]) {+ internals.handleWorkerFrame(completed.worker, frame(message));+ }+ internals.handleWorkerFrame(completed.worker, frame({ ...frames.begin, messageCount: 2 }));+ expect(completed.close).toHaveBeenCalledOnce();+ expect(completed.worker.transcriptCaches.has(activeSessionId)).toBe(false);++ const mismatchedEnd = workerHarness();+ for (const message of [frames.begin, frames.chunk, frames.end, frames.begin, frames.chunk]) {+ internals.handleWorkerFrame(mismatchedEnd.worker, frame(message));+ }+ internals.handleWorkerFrame(mismatchedEnd.worker, frame({ ...frames.end, lastEventSequence: 2 }));+ expect(mismatchedEnd.close).toHaveBeenCalledOnce();+ expect(mismatchedEnd.worker.transcriptCaches.has(activeSessionId)).toBe(false);++ const replaced = workerHarness();+ internals.handleWorkerFrame(replaced.worker, frame(frames.begin));+ internals.handleWorkerFrame(replaced.worker, frame({ ...frames.begin, snapshotId: "snapshot-4602-new" }));+ expect(replaced.close).not.toHaveBeenCalled();+ expect(replaced.worker.transcriptCaches.get(activeSessionId)?.snapshotId).toBe("snapshot-4602-new");+ });++ it("isolates a public snapshot read failure to its destination", async () => {+ const supervisor = new DaemonSupervisor("/tmp/eng-4602-supervisor-public.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: "/tmp/eng-4602-supervisor-public-state",+ });+ const result = streamedResult([]);+ const transcript = new SnapshotTranscriptCache({+ activeSessionId,+ snapshotId,+ messages: [{ role: "user", content: "message", timestamp: 1 }],+ cacheRoot: "/tmp",+ });+ const streamError = new Error("cached chunk read failed");+ transcript.readChunk = vi.fn(() => {+ throw streamError;+ });+ const failedSocket = new PassThrough();+ failedSocket.on("error", () => {});+ const siblingSocket = new PassThrough();+ const failedClient = socketClient("failed", failedSocket);+ const siblingClient = socketClient("sibling", siblingSocket);+ const { close, worker } = workerHarness();+ worker.snapshotCache.set(activeSessionId, result);+ worker.transcriptCaches.set(activeSessionId, transcript);+ const internals = supervisor as unknown as {+ clients: Set<DaemonSocketClient>;+ streamSnapshot(+ client: DaemonSocketClient,+ worker: WorkerHarness,+ result: DaemonAttachResult,+ transcript: SnapshotTranscriptCache,+ ): Promise<void>;+ };+ internals.clients.add(failedClient);+ internals.clients.add(siblingClient);++ await expect(internals.streamSnapshot(failedClient, worker, result, transcript)).rejects.toBe(streamError);++ expect(failedSocket.destroyed).toBe(true);+ expect(siblingSocket.destroyed).toBe(false);+ expect(close).not.toHaveBeenCalled();+ expect(worker.snapshotCache.has(activeSessionId)).toBe(false);+ expect(worker.transcriptCaches.has(activeSessionId)).toBe(false);+ });+});