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3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import type { ServiceCall } from "@earendil-works/chord";
import { BACKGROUND_CONTEXT, type SessionMetadata } from "@earendil-works/pi-agent-core";
import { afterEach, describe, expect, test } from "vitest";
import type { ByteConnection, ByteConnectionHandler } from "../src/connection.ts";
import { SessionAmbiguousError } from "../src/errors.ts";
import { Server } from "../src/server.ts";
import {
	createTestServerServices,
	Deferred,
	ProtocolTestClient,
	TestServerHost,
	type WireChannel,
} from "../src/testing/index.ts";
import type { ServerHost } from "../src/types.ts";

const serverId = "00000000-0000-4000-8000-000000000001";
const servers = new Set<Server>();

function createServer(host: ServerHost, id = serverId): Server {
	const server = new Server(host, { listeners: [], serverId: id });
	servers.add(server);
	return server;
}

function connect(server: Server): ProtocolTestClient {
	let handler: ByteConnectionHandler;
	let client: ProtocolTestClient;
	let closed = false;
	const connection: ByteConnection = {
		get closed() {
			return closed;
		},
		async send(chunk) {
			client.receive(chunk);
		},
		close(finalChunk) {
			if (finalChunk) client.receive(finalChunk);
			closed = true;
			client.markClosed();
		},
	};
	const channel: WireChannel = {
		async send(chunk) {
			handler.onData(chunk);
		},
		async sendFragmented(chunk, splitAt) {
			handler.onData(chunk.subarray(0, splitAt));
			handler.onData(chunk.subarray(splitAt));
		},
		async close() {
			if (closed) return;
			closed = true;
			handler.onClose();
			client.markClosed();
		},
	};
	client = new ProtocolTestClient(channel);
	handler = server.accept(connection);
	return client;
}

function sessionCall(member: string, args: ServiceCall["args"] = []): ServiceCall {
	return { serviceId: "test.session", member, args };
}

function latestAttachmentId(client: ProtocolTestClient, sessionId: string): string {
	for (const message of [...client.messages].reverse()) {
		if (message.type === "attachment" && message.attachment?.sessionId === sessionId) {
			return message.attachment.attachmentId;
		}
	}
	throw new Error(`Missing attachment for ${sessionId}`);
}

afterEach(async () => {
	await Promise.all([...servers].map((server) => server.close()));
	servers.clear();
});

describe("Session protocol", () => {
	test("handshake identifies the logical server without listing sessions", async () => {
		const host = new TestServerHost();
		await host.seed();
		const client = connect(createServer(host));

		expect(await client.hello()).toMatchObject({ type: "hello", serverId });
		expect(host.harnesses.size).toBe(0);
	});

	test("rejects a semantically invalid service call after envelope decoding", async () => {
		const host = new TestServerHost();
		const client = connect(createServer(host));
		await client.hello();
		const response = client.next((message) => message.type === "response" && message.id === "invalid-call");
		await client.sendMessage({
			type: "request",
			id: "invalid-call",
			target: { serverId },
			call: { arbitrary: true },
		});
		expect(await response).toMatchObject({ ok: false, error: { code: "invalid_request" } });
	});

	test("attach passes concrete repository metadata to the Harness host", async () => {
		type BackendMetadata = SessionMetadata & { path: string; modifiedAt: number };
		const metadata: BackendMetadata = {
			id: "session-1",
			createdAt: 1,
			storageVersion: 1,
			cwd: "/workspace",
			path: "/sessions/session-1.jsonl",
			modifiedAt: 2,
		};
		let received: BackendMetadata | undefined;
		const host: ServerHost<BackendMetadata> = {
			serverServices: createTestServerServices(),
			resolveSession: async () => metadata,
			openSession: async (candidate) => {
				received = candidate;
				return {
					attachClient: () => ({ invokeService: async () => undefined, release() {} }),
					close: async () => {},
				};
			},
		};
		const client = connect(createServer(host));
		await client.hello();

		await expect(client.attach(serverId, "session-1")).resolves.toMatchObject({ ok: true });
		expect(received).toBe(metadata);
	});

	test("routes opaque server services and publishes attachment changes out of band", async () => {
		const backing = new TestServerHost();
		await backing.seed("session-1");
		let releaseCount = 0;
		const host: ServerHost = {
			resolveSession: (sessionId, context) => backing.resolveSession(sessionId, context),
			openSession: (metadata, context) => backing.openSession(metadata, context),
			serverServices: {
				attachClient(presentation) {
					return {
						async invokeService(call, _publish, context) {
							if (call.serviceId !== "pi.session-management") throw new Error("Unexpected service");
							if (call.member === "attach" && typeof call.args[0] === "string") {
								await presentation.attachSession(call.args[0], context);
								return null;
							}
							if (call.member === "detach") {
								await presentation.detachSession(context);
								return null;
							}
							throw new Error("Unexpected service member");
						},
						release() {
							releaseCount += 1;
						},
					};
				},
			},
		};
		const client = connect(createServer(host));
		await client.hello();
		const attached = client.next((message) => message.type === "attachment" && message.attachment !== null);
		await expect(client.attach(serverId, "session-1")).resolves.toMatchObject({ ok: true });
		await expect(attached).resolves.toMatchObject({
			type: "attachment",
			attachment: { sessionId: "session-1", attachmentId: expect.any(String) },
		});
		expect(backing.latestHarness("session-1").attachedClients).toBe(1);

		const detached = client.next((message) => message.type === "attachment" && message.attachment === null);
		await expect(
			client.requestService({ serverId }, { serviceId: "pi.session-management", member: "detach", args: [] }),
		).resolves.toMatchObject({ ok: true });
		await expect(detached).resolves.toMatchObject({ type: "attachment", attachment: null });
		expect(backing.latestHarness("session-1").attachedClients).toBe(0);
		await client.close();
		await expect.poll(() => releaseCount).toBe(1);
	});

	test("permits multiple client attachments per Session", async () => {
		const host = new TestServerHost();
		await host.seed("session-1");
		const server = createServer(host);
		const first = connect(server);
		const second = connect(server);
		await Promise.all([first.hello(), second.hello()]);

		await expect(first.attach(serverId, "session-1")).resolves.toMatchObject({ ok: true });
		await expect(first.attach(serverId, "session-1")).resolves.toMatchObject({ ok: true });
		expect(host.latestHarness("session-1").attachedClients).toBe(1);
		await expect(second.attach(serverId, "session-1")).resolves.toMatchObject({ ok: true });
		expect(host.harnesses.get("session-1")).toHaveLength(1);
		expect(host.latestHarness("session-1").attachedClients).toBe(2);

		await first.close();
		await expect.poll(() => host.latestHarness("session-1").attachedClients).toBe(1);
		await expect(second.attach(serverId, "session-1")).resolves.toMatchObject({ ok: true });
	});

	test("clears connection ownership when attachment release fails", async () => {
		const host = new TestServerHost();
		await host.seed("session-1");
		const errors: Error[] = [];
		const server = new Server(host, { listeners: [], serverId, onError: (error) => errors.push(error) });
		servers.add(server);
		const first = connect(server);
		const second = connect(server);
		await Promise.all([first.hello(), second.hello()]);
		await first.attach(serverId, "session-1");
		const harness = host.latestHarness("session-1");
		const releaseError = new Error("release failed");
		harness.failAttachmentRelease = releaseError;

		await first.close();
		await expect.poll(() => harness.attachmentReleaseCount).toBe(1);
		await expect.poll(() => errors).toContain(releaseError);
		harness.failAttachmentRelease = undefined;
		await expect(second.attach(serverId, "session-1")).resolves.toMatchObject({ ok: true });
	});

	test("requires the requesting client to hold the targeted Session attachment", async () => {
		const host = new TestServerHost();
		await Promise.all([host.seed("session-1"), host.seed("session-2")]);
		const server = createServer(host);
		const attached = connect(server);
		const unattached = connect(server);
		await Promise.all([attached.hello(), unattached.hello()]);

		await expect(unattached.requestSessionService(serverId, "session-1", sessionCall("run"))).resolves.toMatchObject({
			ok: false,
			error: { code: "session_not_attached" },
		});
		await attached.attach(serverId, "session-1");
		await expect(attached.requestSessionService(serverId, "session-2", sessionCall("run"))).resolves.toMatchObject({
			ok: false,
			error: { code: "session_not_attached" },
		});
		await expect(
			attached.requestSessionService(serverId, "session-1", sessionCall("run", ["Hello"])),
		).resolves.toMatchObject({ ok: true, result: { ok: true } });
		expect(host.latestHarness("session-1").serviceCalls).toEqual([sessionCall("run", ["Hello"])]);
	});

	test("rejects a stale attachment route after switching Sessions", async () => {
		const host = new TestServerHost();
		await Promise.all([host.seed("session-1"), host.seed("session-2")]);
		const client = connect(createServer(host));
		await client.hello();
		await client.attach(serverId, "session-1");
		const firstAttachmentId = latestAttachmentId(client, "session-1");
		await client.attach(serverId, "session-2");

		await expect(
			client.requestService(
				{ serverId, sessionId: "session-1", attachmentId: firstAttachmentId },
				sessionCall("run", ["stale"]),
			),
		).resolves.toMatchObject({ ok: false, error: { code: "session_not_attached" } });
		expect(host.latestHarness("session-1").serviceCalls).toEqual([]);
	});

	test("preserves opaque service results and bounds adapter defects", async () => {
		const host = new TestServerHost();
		await host.seed("session-1");
		const client = connect(createServer(host));
		await client.hello();
		await client.attach(serverId, "session-1");
		const harness = host.latestHarness("session-1");
		harness.nextServiceResult = { accepted: false, reason: "closed" };
		await expect(client.requestSessionService(serverId, "session-1", sessionCall("run"))).resolves.toMatchObject({
			ok: true,
			result: { accepted: false, reason: "closed" },
		});

		harness.nextServiceError = new Error("private adapter detail");
		await expect(client.requestSessionService(serverId, "session-1", sessionCall("run"))).resolves.toMatchObject({
			ok: false,
			error: { code: "internal_error", message: "Internal server error" },
		});
	});

	test("admits concurrent service calls to the attached Session", async () => {
		const host = new TestServerHost();
		await host.seed("session-1");
		const client = connect(createServer(host));
		await client.hello();
		await client.attach(serverId, "session-1");
		const harness = host.latestHarness("session-1");
		const gate = harness.gateNextServiceCall();
		const first = client.requestSessionService(serverId, "session-1", sessionCall("run", ["first"]));
		await gate.entered.promise;
		const second = client.requestSessionService(serverId, "session-1", sessionCall("run", ["second"]));

		await expect(second).resolves.toMatchObject({ ok: true });
		expect(harness.serviceCalls).toEqual([sessionCall("run", ["first"]), sessionCall("run", ["second"])]);
		gate.release.resolve(undefined);
		await expect(first).resolves.toMatchObject({ ok: true });
	});

	test("keeps attachment demand until an accepted service call settles after disconnect", async () => {
		const host = new TestServerHost();
		await host.seed("session-1");
		const client = connect(createServer(host));
		await client.hello();
		await client.attach(serverId, "session-1");
		const harness = host.latestHarness("session-1");
		const gate = harness.gateNextServiceCall();
		const calling = client.requestSessionService(serverId, "session-1", sessionCall("run"));
		const disconnectedCall = expect(calling).rejects.toThrow(/closed/i);
		await gate.entered.promise;

		await client.close();
		expect(harness.attachedClients).toBe(1);
		gate.release.resolve(undefined);
		await disconnectedCall;
		await expect.poll(() => harness.attachedClients).toBe(0);
	});

	test("rejects requests addressed to another server before repository access", async () => {
		const host = new TestServerHost();
		await host.seed("session-1");
		const client = connect(createServer(host));
		await client.hello();

		await expect(client.attach("00000000-0000-4000-8000-000000000002", "session-1")).resolves.toMatchObject({
			ok: false,
			error: { code: "wrong_server" },
		});
		expect(host.harnesses.size).toBe(0);
	});

	test("reports an unknown session without creating a Harness", async () => {
		const host = new TestServerHost();
		const client = connect(createServer(host));
		await client.hello();

		await expect(client.attach(serverId, "missing")).resolves.toMatchObject({
			ok: false,
			error: { code: "session_not_found" },
		});
		expect(host.harnesses.size).toBe(0);
	});

	test("rejects an ambiguous session ID without creating a Harness", async () => {
		type BackendMetadata = SessionMetadata & { path: string };
		const host: ServerHost<BackendMetadata> = {
			serverServices: createTestServerServices(),
			resolveSession: async () => {
				throw new SessionAmbiguousError();
			},
			openSession: async () => {
				throw new Error("must not create a Harness for an ambiguous session");
			},
		};
		const client = connect(createServer(host));
		await client.hello();

		await expect(client.attach(serverId, "duplicate")).resolves.toMatchObject({
			ok: false,
			error: { code: "session_ambiguous" },
		});
	});

	test("invalidates a terminated Harness handle and allows a later attach", async () => {
		const host = new TestServerHost();
		await host.seed("session-1");
		const client = connect(createServer(host));
		await client.hello();
		await client.attach(serverId, "session-1");
		const firstHarness = host.latestHarness("session-1");

		await firstHarness.terminate(new Error("worker crashed"));
		await firstHarness.terminated;
		await expect.poll(() => firstHarness.attachedClients).toBe(0);
		expect(firstHarness.attachmentReleaseCount).toBe(1);

		await expect(client.attach(serverId, "session-1")).resolves.toMatchObject({ ok: true });
		expect(host.harnesses.get("session-1")).toHaveLength(2);
	});

	test("connection loss releases its attachment, while server shutdown closes the Harness", async () => {
		const host = new TestServerHost();
		await host.seed("session-1");
		const server = createServer(host);
		const client = connect(server);
		await client.hello();
		await client.attach(serverId, "session-1");
		const harness = host.latestHarness("session-1");

		await client.close();
		await expect.poll(() => harness.attachedClients).toBe(0);
		expect(harness.closeCount).toBe(0);
		await server.close();
		expect(harness.closeCount).toBe(1);
	});
});

describe("routed Session acquisition failures", () => {
	test("releases a lease acquired concurrently with Harness termination", async () => {
		const metadata: SessionMetadata = { id: "session-1", createdAt: 1, storageVersion: 1 };
		const acquiring = new Deferred<void>();
		const continueAcquiring = new Deferred<void>();
		const terminated = new Deferred<Error | undefined>();
		let releaseCount = 0;
		const host: ServerHost = {
			serverServices: createTestServerServices(),
			resolveSession: async () => metadata,
			openSession: async () => ({
				terminated: terminated.promise,
				attachClient: async () => {
					acquiring.resolve(undefined);
					await continueAcquiring.promise;
					return {
						invokeService: async () => undefined,
						release: () => {
							releaseCount += 1;
						},
					};
				},
				close: async () => {},
			}),
		};
		const client = connect(createServer(host));
		await client.hello();
		const attach = client.attach(serverId, "session-1");
		await acquiring.promise;

		terminated.resolve(new Error("worker crashed"));
		continueAcquiring.resolve(undefined);
		await expect(attach).resolves.toMatchObject({ ok: false, error: { code: "server_draining" } });
		expect(releaseCount).toBe(1);
	});

	test("shares a Harness creation failure, releases the Session, and allows a later retry", async () => {
		const host = new TestServerHost();
		await host.seed("session-1");
		host.nextOpenSessionError = new Error("Harness creation failed");
		const server = createServer(host);
		const first = connect(server);
		const second = connect(server);
		await Promise.all([first.hello(), second.hello()]);
		const gate = host.gateNextOpenSession();

		const firstAttach = first.attach(serverId, "session-1");
		await gate.entered.promise;
		const secondAttach = second.attach(serverId, "session-1");
		gate.release.resolve(undefined);

		await expect(Promise.all([firstAttach, secondAttach])).resolves.toMatchObject([
			{ ok: false, error: { code: "internal_error" } },
			{ ok: false, error: { code: "internal_error" } },
		]);
		expect(host.openSessionCount).toBe(1);

		await expect(first.attach(serverId, "session-1")).resolves.toMatchObject({ ok: true });
		expect(host.openSessionCount).toBe(2);
		expect(host.harnesses.get("session-1")).toHaveLength(1);
	});

	test("closes a Harness acquired while server shutdown is in progress", async () => {
		const host = new TestServerHost();
		await host.seed("session-1");
		const server = createServer(host);
		const client = connect(server);
		await client.hello();
		const gate = host.gateNextOpenSession();
		const attach = client.attach(serverId, "session-1");
		await gate.entered.promise;
		const closing = server.close();
		gate.release.resolve(undefined);

		await closing;
		await expect(attach).rejects.toThrow(/closed/i);
		expect(host.latestHarness("session-1").closeCount).toBe(1);
	});

	test("fails shutdown when an in-flight acquisition cannot release its Harness", async () => {
		const host = new TestServerHost();
		await host.seed("session-1");
		const cleanupError = new Error("close failed");
		host.nextHarnessCloseError = cleanupError;
		const server = createServer(host);
		const client = connect(server);
		await client.hello();
		const gate = host.gateNextOpenSession();
		const attach = client.attach(serverId, "session-1");
		await gate.entered.promise;

		const closing = server.close();
		gate.release.resolve(undefined);

		await expect(closing).rejects.toThrow(/Failed to close routed Sessions/);
		await expect(server.closed).rejects.toThrow(/Failed to close routed Sessions/);
		await expect(attach).rejects.toThrow(/closed/i);
		expect(host.latestHarness("session-1").closeCount).toBe(1);

		servers.delete(server);
		await host.latestHarness("session-1").close(BACKGROUND_CONTEXT);
	});
});