@mrciphersmith/roomyx 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,9 +4,95 @@ Notable changes to `@mrciphersmith/roomyx`. Generated release notes say what
4
4
  changed; this file exists for the two things they cannot say — **why**, and
5
5
  **what to do if you were relying on the old behaviour**.
6
6
 
7
- Format loosely follows [Keep a Changelog](https://keepachangelog.com). Versions
8
- are [semantic](https://semver.org), with the `0.x` convention that breaking
9
- changes land in the minor position.
7
+ Format loosely follows [Keep a Changelog](https://keepachangelog.com).
8
+
9
+ **Versioning:** in `0.x` the minor position is the breaking position, and the
10
+ patch position carries everything else — bug fixes *and* backward-compatible
11
+ additions. That is what `^0.6.0` already promises a consumer: it receives every
12
+ patch and never a minor. The rule, the reason, and an audit of the four of seven
13
+ releases that followed it are in
14
+ [`docs/roomyx/versioning.md`](docs/roomyx/versioning.md) and decision D-13.
15
+
16
+ ## [0.6.1] — 2026-09-10
17
+
18
+ **A patch, and the first release numbered by the rule rather than by feel.**
19
+ Nothing here is breaking — no export, command, flag or tool parameter is gone,
20
+ no default changed under a caller — so it takes the patch position and every
21
+ `^0.6.0` dependant gets it automatically. Under the old habit this would have
22
+ been `0.7.0`, which would have reached nobody without a manual bump. See
23
+ [`docs/roomyx/versioning.md`](docs/roomyx/versioning.md) and D-13.
24
+
25
+ Everything below is a defect that 0.6.0's own fixes introduced, or a
26
+ verification claim about them that turned out to be false. Both classes were
27
+ found by review rounds run *against the fixes* rather than against the code
28
+ they fixed — the class that is systematically under-found, because a fix
29
+ arrives framed as an answer and gets read as one. Full record in
30
+ [`docs/roomyx/fix-round-2026-09-09.md`](docs/roomyx/fix-round-2026-09-09.md).
31
+
32
+ ### Fixed — regressions 0.6.0 introduced
33
+
34
+ - **`roomyx mcp` worked once and then went dead.** The idle session sweeper
35
+ reasoned from roomyx's own TUI, which polls every second, and applied that to
36
+ clients whose next call comes when a model decides to. Measured: connect, call
37
+ a tool, idle 95 seconds, and the next call fails permanently — the SDK client
38
+ never clears its session id on a 404 and never re-initialises. Eviction is
39
+ one-way, so the window now means *certainly* gone, not probably.
40
+ - **A persistent tool error was appended to the transcript once per poll** —
41
+ about eighty identical lines a minute, each allocating a renderable that was
42
+ never freed, which is the pool exhaustion 0.6.0 fixed elsewhere arriving
43
+ through a different door. Reported once per distinct message now.
44
+ - **A request carrying no session id still minted an untracked transport.** The
45
+ 404 added in 0.6.0 closed the half where a *wrong* id was supplied and the
46
+ comment claimed both. (The unbounded memory growth this was filed under does
47
+ not reproduce — 400 such requests retain the same heap either way. The
48
+ mechanism was real; the leak was not.)
49
+ - **A stopped client could not be restarted.** `stop()` cancelled the pending
50
+ reconnect but left the handle set, and that handle is the single-flight token.
51
+ - **Every transcript export was refused in a container with no working
52
+ directory.** The containment check compared a value to the expression that had
53
+ produced it, and its other half inverted at the filesystem root — so the
54
+ message said the working directory had been escaped when nothing had.
55
+
56
+ ### Fixed — the rest of the review
57
+
58
+ - `--acknowledge-non-loopback` binds a host the rebinding guard will now accept.
59
+ It bound the address and then refused every request arriving at it.
60
+ - The unknown-session 404 is Host- and Origin-checked like every other response.
61
+ - `roomyx.rooms.list` no longer prunes the registry, so the MCP surface only
62
+ reads. It is a network-triggered write with a load-sensitive 500 ms probe
63
+ behind it.
64
+ - Liveness identifies the room. `room.get_state` carries `log_path` and the
65
+ probe compares it, so a recycled port can no longer resurrect a dead room. A
66
+ server without the field is treated as *not shown to be a different room*,
67
+ because wrongly pruning a live room costs more than keeping a stale one.
68
+ - `roomyx init` no longer clobbers a hand-edited staged skill; the duplicate
69
+ `ManagementServeOptions` is gone; `--toString` is refused like any other
70
+ unknown flag; the search counter no longer prints `0/N`.
71
+
72
+ ### Fixed — tests that were not holding what they claimed
73
+
74
+ Found by mutation: remove the fix, require the test to fail.
75
+
76
+ - The first-message fix, the client's shutdown ordering, the roster
77
+ skip-rebuild, the client's session release, and the server's shutdown
78
+ re-entry guard **all survived their own deletion** with the suite green. Each
79
+ is pinned now, and each pin was itself checked by mutation.
80
+ - Two testable units came out of code no test could reach — `runClient` and
81
+ `cli.ts` both refuse to be imported — so the ordering and the re-entry guard
82
+ are asserted directly rather than inferred from a subprocess.
83
+ - A raw NUL byte made one test file binary to git and invisible to ripgrep, so
84
+ the project's own mandated search path reported a fix as untested.
85
+ - Fixed sleeps standing in for conditions are predicate waits, through one
86
+ shared helper. The four that remain are two hang detectors and two assertions
87
+ about absence, where a duration is the right instrument.
88
+
89
+ ### Known
90
+
91
+ - **Neither reconnect mechanism is pinned by a test.** The generation counter
92
+ and the single-flight check can both be deleted with the suite green, and the
93
+ test written to close that gap does not: the full pre-fix shape passes it. It
94
+ is kept for a cheap invariant and labelled in its own header as *not* a
95
+ barrier, because a test that reads as one and is not is worse than none.
10
96
 
11
97
  ## [0.6.0] — 2026-09-09
12
98
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrciphersmith/roomyx",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "MCP server + terminal UI for startup-room: live room status, chat, per-agent modal, an installable room registry, and skill-sync.",
5
5
  "publishConfig": {
6
6
  "access": "public"
package/src/cli.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { join, resolve } from "node:path";
4
4
  import { serve } from "./server/serve";
5
+ import { createServerShutdown } from "./server/shutdown";
5
6
  import { init } from "./installer/init";
6
7
  import { registerRoom, deregisterRoom, listLiveRooms } from "./installer/registry";
7
8
  import { syncSkill } from "./installer/skill-sync";
@@ -40,7 +41,8 @@ function bundledSkillPath(): string {
40
41
  const REGISTRY_FLAG = { type: "string", describe: "Registry file (default .roomyx/rooms/registry.json)" } as const;
41
42
 
42
43
  /**
43
- * Runs a long-lived server until a signal, then shuts it down once.
44
+ * Wires the signals. The shutdown itself lives in `./server/shutdown`, where a
45
+ * test can reach it — this module runs its entry point on import.
44
46
  *
45
47
  * Written once because there were three copies and they had drifted: the two
46
48
  * here handled SIGINT and SIGTERM and guarded nothing, while the client handled
@@ -54,19 +56,7 @@ const REGISTRY_FLAG = { type: "string", describe: "Registry file (default .roomy
54
56
  * the port. The room became invisible while still being served.
55
57
  */
56
58
  function runUntilSignal(close: () => Promise<void>, cleanup: () => void = () => undefined): void {
57
- let shuttingDown = false;
58
- const shutdown = (): void => {
59
- if (shuttingDown) return;
60
- shuttingDown = true;
61
- void close()
62
- .catch((error: unknown) => {
63
- console.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
64
- })
65
- .finally(() => {
66
- cleanup();
67
- process.exit(0);
68
- });
69
- };
59
+ const shutdown = createServerShutdown(close, cleanup);
70
60
  for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, shutdown);
71
61
  }
72
62
 
@@ -20,6 +20,11 @@ import type { RosterEntry } from "../../log/types";
20
20
  * drawn at all.
21
21
  */
22
22
  function clip(label: string, width: number): string {
23
+ // Unreachable from `ChatView`, which constructs this with a hardcoded width
24
+ // of 24 — a mutation pass confirmed deleting it changes nothing. Kept as a
25
+ // total function rather than as a guard: `clip` is exported-shaped and a
26
+ // caller with a narrower gutter is exactly what the deferred resize work will
27
+ // introduce. Recorded so it is not read as protection it does not provide.
23
28
  if (width <= 0) return "";
24
29
  if (label.length <= width) return label;
25
30
  return width === 1 ? "…" : `${label.slice(0, width - 1)}…`;
@@ -1,4 +1,4 @@
1
- import { join, resolve, sep } from "node:path";
1
+ import { dirname, resolve } from "node:path";
2
2
 
3
3
  /**
4
4
  * Where a transcript export is allowed to land, and under what name.
@@ -46,11 +46,21 @@ export function nextFreeExportPath(cwd: string, base: string, exists: (path: str
46
46
  const root = resolve(cwd);
47
47
  for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
48
48
  const name = `${base}${attempt === 0 ? "" : `-${attempt}`}.txt`;
49
- const path = join(root, name);
50
- // The fact, checked after the transformation rather than instead of it.
51
- if (path !== join(root, name) || !resolve(path).startsWith(root + sep)) {
52
- return { ok: false, reason: "escapes-cwd" };
53
- }
49
+ const path = resolve(root, name);
50
+ // The fact, checked after the transformation rather than instead of it —
51
+ // and this time it is actually a check. The first version compared `path`
52
+ // against the identical expression that had produced it one line earlier,
53
+ // which is unsatisfiable, and paired it with a `startsWith(root + sep)`
54
+ // test that inverted to always-false when `root` was `/`: started in a
55
+ // container with no working directory, every export was refused with
56
+ // "refusing to write outside the working directory", which is the opposite
57
+ // of what had happened.
58
+ //
59
+ // `dirname` equality holds at the filesystem root and is genuinely
60
+ // falsifiable the moment `name` regains a separator or a `..` segment —
61
+ // which is what the sanitiser above is for, and what this is here to catch
62
+ // if that sanitiser is ever loosened.
63
+ if (dirname(path) !== resolve(root)) return { ok: false, reason: "escapes-cwd" };
54
64
  if (!exists(path)) return { ok: true, path, name };
55
65
  }
56
66
  return { ok: false, reason: "exhausted" };
@@ -85,6 +85,8 @@ export class RoomClient {
85
85
  * from a single malformed log line: one connection became 510 in ten seconds.
86
86
  */
87
87
  private generation = 0;
88
+ /** The last tool-error text reported, so a persistent fault is said once. */
89
+ private lastToolError: string | undefined;
88
90
 
89
91
  constructor(options: RoomClientOptions, events: RoomClientEvents) {
90
92
  this.url = options.url;
@@ -105,6 +107,11 @@ export class RoomClient {
105
107
  clearTimeout(this.stateTimer);
106
108
  clearTimeout(this.transcriptTimer);
107
109
  clearTimeout(this.reconnectTimer);
110
+ // Cleared, not just cancelled: `scheduleConnect` uses this field as its
111
+ // single-flight token, so a client stopped with a reconnect pending could
112
+ // never schedule another one — `start()` returned immediately and the
113
+ // client was inert for good.
114
+ this.reconnectTimer = undefined;
108
115
  await endSession(this.client, this.transport);
109
116
  this.client = undefined;
110
117
  this.transport = undefined;
@@ -199,7 +206,16 @@ export class RoomClient {
199
206
  */
200
207
  private handleToolError(error: unknown, resume: () => void): boolean {
201
208
  if (!(error instanceof ToolError)) return false;
202
- this.events.onToolError?.(error.message);
209
+ // Reported once per distinct message, not once per poll. A tool error is
210
+ // usually a property of the file rather than a transient — a log line the
211
+ // reader's schema refuses stays refused — so the loop reported the same
212
+ // sentence about eighty times a minute, each one a transcript entry
213
+ // allocating a renderable it never freed. That is the pool exhaustion this
214
+ // same round fixed elsewhere, re-entered through a different door.
215
+ if (error.message !== this.lastToolError) {
216
+ this.lastToolError = error.message;
217
+ this.events.onToolError?.(error.message);
218
+ }
203
219
  resume();
204
220
  return true;
205
221
  }
@@ -212,6 +228,7 @@ export class RoomClient {
212
228
  this.callTool<RoomState>("room.get_state", {})
213
229
  .then((state) => {
214
230
  if (this.isStale(generation)) return;
231
+ this.lastToolError = undefined;
215
232
  this.events.onStateUpdate?.(state);
216
233
  again();
217
234
  })
@@ -113,7 +113,11 @@ export function listRooms(registryPath: string): RoomRegistryEntry[] {
113
113
  * answers). Dead entries are pruned from the persisted file, not just
114
114
  * omitted from the returned list.
115
115
  */
116
- export async function listLiveRooms(registryPath: string): Promise<RoomRegistryEntry[]> {
116
+ export async function listLiveRooms(
117
+ registryPath: string,
118
+ options: { prune?: boolean } = {},
119
+ ): Promise<RoomRegistryEntry[]> {
120
+ const prune = options.prune ?? true;
117
121
  if (hasNoRegistry(registryPath)) return [];
118
122
  const rooms = withLock(registryPath, () => readRegistryUnlocked(registryPath).rooms);
119
123
  const checks = await Promise.all(
@@ -123,7 +127,12 @@ export async function listLiveRooms(registryPath: string): Promise<RoomRegistryE
123
127
  }),
124
128
  );
125
129
  const live = checks.filter((c) => c.alive).map((c) => c.room);
126
- if (live.length !== rooms.length) {
130
+ // The MCP surface passes `prune: false`. It is the one place a network caller
131
+ // could cause a filesystem write, and the content is not caller-controlled —
132
+ // but "the MCP surface only reads" is worth being exactly true rather than
133
+ // nearly, and the 500ms probe is load-sensitive enough that a busy machine
134
+ // could prune a live-but-slow room on someone else's call.
135
+ if (prune && live.length !== rooms.length) {
127
136
  // Re-take the lock for the write: another process may have registered or
128
137
  // deregistered a room while the (network) liveness checks above were in
129
138
  // flight. Re-read under the lock and only remove entries this pass
@@ -177,7 +186,20 @@ async function isRoomLive(room: RoomRegistryEntry, timeoutMs = 500): Promise<boo
177
186
  });
178
187
  try {
179
188
  await Promise.race([client.connect(transport), timeout]);
180
- return true;
189
+ // Connecting proves something MCP-speaking answers on that port. Asking it
190
+ // which log it serves is what proves it is *this* room — the pid check
191
+ // above narrows the window and does not close it, because a pid can be
192
+ // recycled and every serve defaults to the same port.
193
+ const result = await Promise.race([client.callTool({ name: "room.get_state", arguments: {} }), timeout]);
194
+ const content = result.content as Array<{ type: string; text: string }> | undefined;
195
+ const text = content?.[0]?.text;
196
+ if (text === undefined) return false;
197
+ const state = JSON.parse(text) as { log_path?: string };
198
+ // An older server that predates `log_path` answers without it. Treat that
199
+ // as "cannot be shown to be a different room" rather than as dead: failing
200
+ // toward the previous behaviour is the safe direction here, because the
201
+ // cost of wrongly pruning a live room is higher than of keeping a stale one.
202
+ return state.log_path === undefined || state.log_path === room.logPath;
181
203
  } catch {
182
204
  return false;
183
205
  } finally {
package/src/log/store.ts CHANGED
@@ -26,6 +26,8 @@ export function loadRoomLog(path: string): { state: RoomState; messages: Message
26
26
  const state: RoomState = {
27
27
  goal_contract: headerResult.data.goal_contract,
28
28
  roster: headerResult.data.roster,
29
+ // The reader knows which file it read; the state header does not carry it.
30
+ log_path: path,
29
31
  };
30
32
 
31
33
  const messages: MessageEnvelope[] = rest.map((line, index) => {
package/src/log/types.ts CHANGED
@@ -28,6 +28,25 @@ export interface GoalContract {
28
28
  export interface RoomState {
29
29
  goal_contract: GoalContract;
30
30
  roster: RosterEntry[];
31
+ /**
32
+ * The log this server is serving, absolute.
33
+ *
34
+ * Present so a liveness probe can ask *which room is this*, not merely
35
+ * *does anything answer here*. Every `roomyx serve` defaults to port 4319, so
36
+ * without it a room that died without deregistering was resurrected as live
37
+ * by the next room to bind the port — and `roomyx-client --room <dead-id>`
38
+ * then rendered a different room's transcript under the dead room's id.
39
+ *
40
+ * It exposes a filesystem path to a caller that can already read the whole
41
+ * transcript, which is a smaller disclosure than the one it prevents.
42
+ *
43
+ * Optional, and that is a versioning decision rather than a hedge: making it
44
+ * required would break anyone constructing a `RoomState`, which would put
45
+ * this release in the minor position under D-13. The probe already treats an
46
+ * absent value as "cannot be shown to be a different room", because that is
47
+ * what an older server returns.
48
+ */
49
+ log_path?: string;
31
50
  }
32
51
 
33
52
  export type AgentDetail =
@@ -45,7 +45,7 @@ export function createManagementMcpServer(options: ManagementOptions): McpServer
45
45
  description: "Rooms currently registered and confirmed live (liveness-checked, not just registry presence).",
46
46
  },
47
47
  async () => ({
48
- content: [{ type: "text", text: JSON.stringify(await listLiveRooms(options.registryPath)) }],
48
+ content: [{ type: "text", text: JSON.stringify(await listLiveRooms(options.registryPath, { prune: false })) }],
49
49
  }),
50
50
  );
51
51
 
@@ -1,4 +1,5 @@
1
1
  import { createServer as createHttpServer } from "node:http";
2
+ import type { IncomingMessage } from "node:http";
2
3
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
4
  import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
5
 
@@ -74,6 +75,25 @@ export async function serveMcpOverHttp(
74
75
  // which matters because the allowlists below cannot be built without it.
75
76
  let boundPort = 0;
76
77
 
78
+ /**
79
+ * The Host values this server will answer to.
80
+ *
81
+ * The loopback three, plus the bound host when the operator has explicitly
82
+ * acknowledged binding a non-loopback one. Without that last part the escape
83
+ * hatch bound the address and the rebinding guard then refused every request
84
+ * that arrived at it — measured, 403 `Invalid Host header` against the very
85
+ * address `--acknowledge-non-loopback` had just permitted. A flag that
86
+ * appears to work and does not is worse than one that refuses.
87
+ *
88
+ * This does not widen the guard for anyone who did not ask: without the flag
89
+ * the server will not bind a non-loopback host at all.
90
+ */
91
+ function allowedHosts(): string[] {
92
+ const loopback = [`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`];
93
+ if (LOOPBACK_HOSTS.has(host)) return loopback;
94
+ return [...loopback, `${host}:${boundPort}`];
95
+ }
96
+
77
97
  async function createSession(): Promise<StreamableHTTPServerTransport> {
78
98
  const transport = new StreamableHTTPServerTransport({
79
99
  sessionIdGenerator: () => crypto.randomUUID(),
@@ -96,7 +116,7 @@ export async function serveMcpOverHttp(
96
116
  // the Origin check when the header is absent, so the list below exists
97
117
  // to be matched by nothing.
98
118
  enableDnsRebindingProtection: true,
99
- allowedHosts: [`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`],
119
+ allowedHosts: allowedHosts(),
100
120
  allowedOrigins: [`http://127.0.0.1:${boundPort}`, `http://localhost:${boundPort}`],
101
121
  onsessioninitialized: (sessionId) => {
102
122
  sessions.set(sessionId, { transport, lastSeenMs: Date.now() });
@@ -105,8 +125,15 @@ export async function serveMcpOverHttp(
105
125
  sessions.delete(sessionId);
106
126
  },
107
127
  });
108
- // The DELETE is one way a session can end; the transport closing for any
109
- // other reason is another, and only the first was being listened for.
128
+ // The DELETE is one way a session can end; the transport closing for its
129
+ // own reasons is another, and only the first was being listened for.
130
+ //
131
+ // Measured, so the scope is not overstated: this does NOT fire when a
132
+ // client simply calls `close()` — such a session still answers 200 after
133
+ // three seconds, because the server never learns the client went away. An
134
+ // abandoned session is the sweeper's job. This is belt-and-braces for a
135
+ // transport that closes itself, and it is deliberately not pinned by a
136
+ // test, because no test can reach it from outside.
110
137
  transport.onclose = () => {
111
138
  const id = transport.sessionId;
112
139
  if (id !== undefined) sessions.delete(id);
@@ -117,14 +144,28 @@ export async function serveMcpOverHttp(
117
144
  }
118
145
 
119
146
  /**
120
- * Closes sessions nothing has touched for a while.
147
+ * Closes sessions nothing has touched for a long time.
148
+ *
149
+ * The first version of this used a minute, reasoning that a well-behaved
150
+ * client polls every second or three. That is true of roomyx's own TUI and
151
+ * false of every other consumer: `roomyx mcp` is documented for Claude Code,
152
+ * Codex and keryx, whose clients call a tool when a model decides to, and a
153
+ * minute of think-time is ordinary. Measured — connect, call a tool, idle 95
154
+ * seconds, and the next call fails permanently, because the SDK client never
155
+ * clears its session id on a 404 and never re-initializes. So the fix broke
156
+ * the product's primary integration surface: `roomyx mcp` worked once and was
157
+ * dead for the rest of the host's lifetime.
121
158
  *
122
- * A well-behaved client polls every second or three, so a minute of silence
123
- * means it is gone — and the ones that are gone are precisely the ones that
124
- * never sent the DELETE that would have said so. `unref()` so an idle sweeper
125
- * cannot be the reason a process stays alive.
159
+ * **Eviction is one-way, so the window has to mean "certainly gone", not
160
+ * "probably gone".** Thirty minutes is past any plausible think-time while
161
+ * still bounding what a crashed client can leave behind. The ordinary case is
162
+ * not this sweeper's job at all — it is `terminateSession()` at every client
163
+ * close and `transport.onclose`; this only catches a client that died without
164
+ * being able to say so.
165
+ *
166
+ * `unref()` so an idle sweeper cannot be the reason a process stays alive.
126
167
  */
127
- const IDLE_SESSION_MS = 60_000;
168
+ const IDLE_SESSION_MS = 30 * 60_000;
128
169
  const sweeper = setInterval(() => {
129
170
  const cutoff = Date.now() - IDLE_SESSION_MS;
130
171
  for (const [id, entry] of sessions) {
@@ -136,6 +177,28 @@ export async function serveMcpOverHttp(
136
177
  }, IDLE_SESSION_MS / 2);
137
178
  sweeper.unref();
138
179
 
180
+ /**
181
+ * The same Host/Origin decision the SDK makes, applied to the one response we
182
+ * write ourselves. Returns the rejection message, or null to proceed.
183
+ *
184
+ * Deliberately mirrors rather than reuses: the SDK's check is private to the
185
+ * transport, and a transport is exactly what this branch exists to avoid
186
+ * creating.
187
+ */
188
+ function rebindingRejection(req: IncomingMessage): string | null {
189
+ const origin = req.headers.origin;
190
+ if (typeof origin === "string" && origin.length > 0) {
191
+ if (![`http://127.0.0.1:${boundPort}`, `http://localhost:${boundPort}`].includes(origin)) {
192
+ return `Invalid Origin header: ${origin}`;
193
+ }
194
+ }
195
+ const hostHeader = req.headers.host;
196
+ if (typeof hostHeader === "string" && !allowedHosts().includes(hostHeader)) {
197
+ return `Invalid Host header: ${hostHeader}`;
198
+ }
199
+ return null;
200
+ }
201
+
139
202
  const httpServer = createHttpServer((req, res) => {
140
203
  const sessionIdHeader = req.headers["mcp-session-id"];
141
204
  const sessionId = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
@@ -147,6 +210,19 @@ export async function serveMcpOverHttp(
147
210
  // entered `sessions`, so it could not be closed even by `closeSessions` on
148
211
  // shutdown — a leak reachable by anyone sending a random header.
149
212
  if (sessionId !== undefined && existing === undefined) {
213
+ // Validated first. `handleRequest` is where the SDK checks Host and
214
+ // Origin, so returning before it made this the one response path the
215
+ // rebinding guard never saw: measured, `Host: evil.example` alone got
216
+ // 403 and the same Host plus an unknown session id got a roomyx-authored
217
+ // 404. Nothing was exploitable — session ids are 122-bit random, so the
218
+ // oracle is worthless — but "every path except one" is the property that
219
+ // stops being true quietly the next time a branch is added up here.
220
+ const rejection = rebindingRejection(req);
221
+ if (rejection) {
222
+ res.writeHead(403, { "content-type": "application/json" });
223
+ res.end(JSON.stringify({ error: rejection }));
224
+ return;
225
+ }
150
226
  res.writeHead(404, { "content-type": "application/json" });
151
227
  res.end(JSON.stringify({ error: `Unknown session ${sessionId}` }));
152
228
  return;
@@ -154,7 +230,18 @@ export async function serveMcpOverHttp(
154
230
 
155
231
  const transportPromise = existing ? Promise.resolve(existing.transport) : createSession();
156
232
  transportPromise
157
- .then((transport) => transport.handleRequest(req, res))
233
+ .then(async (transport) => {
234
+ await transport.handleRequest(req, res);
235
+ // The 404 above closed one half of this class and the comment claimed
236
+ // both. A request carrying *no* session id still reaches `createSession`
237
+ // — it has to, because that is how `initialize` arrives — but if it was
238
+ // not an initialize, `onsessioninitialized` never fires and the
239
+ // transport never enters `sessions`: unsweepable, and invisible to
240
+ // `closeSessions` on shutdown. Measured: 15 session-less `tools/list`
241
+ // POSTs minted 15 transports and tracked 0. Anything that did not
242
+ // become a session is closed here.
243
+ if (transport.sessionId === undefined) await transport.close().catch(() => undefined);
244
+ })
158
245
  .catch((error) => {
159
246
  if (!res.headersSent) {
160
247
  res.writeHead(500, { "content-type": "application/json" });
@@ -0,0 +1,39 @@
1
+ /**
2
+ * A long-lived server's ordered exit, as a unit that can be tested.
3
+ *
4
+ * It lived in `cli.ts`, which no test can import: that module runs its entry
5
+ * point on import and prints usage. The consequence was measured rather than
6
+ * suspected — a post-fix verifier deleted the re-entry guard below and all 265
7
+ * tests stayed green, including the subprocess case written to pin it. From
8
+ * outside the process the two behaviours are identical: without the guard the
9
+ * teardown simply runs three times and the first `exit` wins, so three
10
+ * deregistrations of one room look exactly like one.
11
+ *
12
+ * Two properties, and both were once wrong in one of the three copies of this
13
+ * logic that existed before it was written down once:
14
+ *
15
+ * - **Re-entry.** A second signal arriving mid-teardown must not start another.
16
+ * - **Order.** `cleanup` runs *after* the close resolves. Deregistering first
17
+ * meant a shutdown that hung — and it hung whenever a client was attached —
18
+ * removed the room from the registry while the process kept running and kept
19
+ * the port. The room became invisible while still being served.
20
+ */
21
+ export function createServerShutdown(
22
+ close: () => Promise<void>,
23
+ cleanup: () => void = () => undefined,
24
+ exit: (code: number) => void = (code) => process.exit(code),
25
+ ): () => void {
26
+ let shuttingDown = false;
27
+ return (): void => {
28
+ if (shuttingDown) return;
29
+ shuttingDown = true;
30
+ void close()
31
+ .catch((error: unknown) => {
32
+ console.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
33
+ })
34
+ .finally(() => {
35
+ cleanup();
36
+ exit(0);
37
+ });
38
+ };
39
+ }
@@ -1,7 +1,7 @@
1
1
  import { loadRoomLog } from "../../log/store";
2
2
  import type { RoomState } from "../../log/types";
3
3
 
4
- /** MCP tool `room.get_state`: roster + current goal contract. Read-only. */
4
+ /** MCP tool `room.get_state`: roster, goal contract, and which log this is. Read-only. */
5
5
  export function getStateTool(logPath: string): RoomState {
6
6
  const { state } = loadRoomLog(logPath);
7
7
  return state;