@mrciphersmith/roomyx 0.7.2 → 0.8.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
@@ -13,6 +13,102 @@ patch and never a minor. The rule, the reason, and an audit of the four of seven
13
13
  releases that followed it are in
14
14
  [`docs/roomyx/versioning.md`](docs/roomyx/versioning.md) and decision D-13.
15
15
 
16
+ ## [0.8.1] — 2026-09-10
17
+
18
+ A patch. Found by triaging the action list against the code: this defect had
19
+ been sitting in the backlog, unscheduled, with a victim it names itself.
20
+
21
+ ### Fixed
22
+
23
+ - **A room that does not answer within the liveness probe's 500 ms is no longer
24
+ deleted from the registry.** The check returned `state | undefined`, and
25
+ `undefined` had to mean both "I could not reach it" and "the process is gone" —
26
+ so the caller resolved the ambiguity destructively: `undefined → false → prune`,
27
+ plus a history record claiming the room had ended. A room that was merely slow,
28
+ or `SIGSTOP`ped, or on a loaded machine, was silently removed while it was
29
+ still serving. The pid check does not catch it: `process.kill(pid, 0)` succeeds
30
+ for a stopped process.
31
+
32
+ Liveness now answers `live`, `gone` or `unknown`, and only `gone` deletes
33
+ anything. `gone` requires evidence about *this entry* — a registered pid that
34
+ is not running, or a server that answered and named a different log than the
35
+ entry claims.
36
+
37
+ ### Added
38
+
39
+ - **`roomyx rooms list` shows a room that did not answer instead of omitting it**,
40
+ marked `did not answer — still registered`. It used to print `No live rooms.`
41
+ about a registry that had one, which is how a serving room came to look like no
42
+ room at all. An empty registry still prints exactly that sentence.
43
+ - **`listRoomsWithLiveness()`** returns `{ live, unconfirmed }`. Everything that
44
+ decides *what to attach to* keeps reading the confirmed list, so a client never
45
+ auto-attaches to a room that did not answer.
46
+
47
+ ### Notes
48
+
49
+ - The known limit is stated in the code rather than left to be discovered: a pid
50
+ reused by an unrelated process keeps its entry in `unconfirmed` until something
51
+ answers on that port. That is why the pid is a pre-filter and not the assertion
52
+ — and it is strictly better than deleting a live room, which is the trade this
53
+ release makes deliberately.
54
+ - `prune: false` (the MCP surface) still prunes nothing. The load-sensitive half
55
+ of that argument is now structural: a probe that times out returns `unknown`,
56
+ and `unknown` is never pruned even when pruning is asked for.
57
+
58
+ ## [0.8.0] — 2026-09-10
59
+
60
+ A minor, because it is breaking: `roomyx room append --force` is gone. In `0.x`
61
+ the minor position is the breaking position (D-13), and this one removes a flag
62
+ from a documented workflow.
63
+
64
+ ### Changed
65
+
66
+ - **`room append` refuses only when a writer is actually there.** The old guard
67
+ treated "a room answers on this path" as "someone is writing into it", which
68
+ is false for every room served by bare `roomyx serve` — so `--force` was the
69
+ documented way to do ordinary work, and the guard guarded nothing.
70
+ `room.get_state` now reports `dispatcherAttached`, and a server with a
71
+ dispatcher holds a writer lease beside the registry. A live room with no
72
+ writer needs no flag; a live room with a live writer cannot be overridden at
73
+ all, and the refusal names its pid.
74
+
75
+ ### Removed
76
+
77
+ - **`roomyx room append --force`.** Replaced by `--take-over`, which writes only
78
+ when the room is live but its writer is gone (its lease is stale or absent) —
79
+ the one case the old flag was really for — and records the take-over in the
80
+ log as a `status` message, because a room written by hand while its writer was
81
+ absent must not read afterwards as supervised. The bundled `startup-room` skill
82
+ no longer teaches any override.
83
+
84
+ ### Added
85
+
86
+ - **`room append --json <envelope>`** writes one whole envelope, so a body
87
+ containing quotes or newlines no longer depends on the caller assembling JSON
88
+ by hand. An unknown key is refused rather than ignored: `seq` is the writer's.
89
+ - **`room append --body-file <path|->`** reads the body from a file, or stdin.
90
+ - **`room append --many`** writes a JSONL batch from stdin with consecutive
91
+ `seq`, all of it or none of it — half a batch would silently drop a turn from
92
+ the middle of a conversation.
93
+ - **`room.get_state.dispatcherAttached`** states whether anything is dispatching
94
+ into the room. Optional, so an older server's absence is not mistaken for a
95
+ `false`.
96
+
97
+ ### Notes
98
+
99
+ - The room log's format is unchanged: the take-over trace uses the existing
100
+ `status` kind, and the lease is a separate file that lives beside the registry
101
+ rather than beside the log, which travels with the repository. One lease per
102
+ **room**, keyed by the log's path: a project runs several rooms at once, and a
103
+ single shared lease made the first room's writer refuse writes to the second's
104
+ log.
105
+ - `--take-over` does not displace a live writer. A room that reports a dispatcher
106
+ attached refuses until that server is stopped, because "the writer's loop hung
107
+ while its server kept answering" is not distinguishable from "the writer is
108
+ working" from outside — and guessing in that direction is what the old `--force`
109
+ did. The refusal says which of the two reasons applies and what to do.
110
+ - The server still never writes the log. This release gives it a lease, not a pen.
111
+
16
112
  ## [0.7.2] — 2026-09-10
17
113
 
18
114
  A patch. Found by reading a real room log: the reply structure the log schema
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrciphersmith/roomyx",
3
- "version": "0.7.2",
3
+ "version": "0.8.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"
@@ -136,15 +136,26 @@ roomyx serve .roomyx/rooms/logs/<topic>.jsonl --port 0
136
136
  Then append each participant's turn verbatim as it arrives:
137
137
 
138
138
  ```bash
139
- roomyx room append .roomyx/rooms/logs/<topic>.jsonl --force \
139
+ roomyx room append .roomyx/rooms/logs/<topic>.jsonl \
140
140
  --from ann --kind pitch --body "<their actual words>"
141
141
  ```
142
142
 
143
- **`--force` is required here, and it is correct here.** Without it, `append`
144
- refuses whenever a live room is serving that log — a guard against a *second*
145
- writer racing the dispatcher. You are the dispatcher: the single writer the
146
- guard exists to protect. roomyx cannot tell the two apart from outside, so it
147
- asks, and this is the case where the answer is yes.
143
+ **No override flag, and that is the point.** `append` refuses only when the
144
+ room is live *and* something is writing into it — a live room with no dispatcher
145
+ has no writer to race, so this succeeds as written. The guard used to require
146
+ `--force` here because roomyx could not tell the two apart from outside; the
147
+ server now reports whether a dispatcher is attached, and the writer holds a
148
+ lease, so the case that needed an override no longer arises. If something else
149
+ really is writing (you will be told its pid), the only honest move is to stop it
150
+ — do not look for a flag that overrides a live writer, because there is none.
151
+
152
+ `--take-over` is for a room whose writer is **provably gone** — its server has
153
+ stopped, or the lease it left behind has expired without being refreshed. It
154
+ records the take-over in the log, naming whose lease it took. It does not
155
+ displace a writer that is still there: a room that reports a dispatcher attached
156
+ keeps refusing until that server is stopped, and the refusal will tell you so.
157
+ Use it when you know you are the last writer, never to get past a refusal you do
158
+ not understand.
148
159
 
149
160
  `--kind` is one of `pitch`, `question`, `challenge`, `answer`, `vote`, `status`,
150
161
  `research`; `--in-reply-to <seq>` records who was being answered. Both are
package/src/cli.ts CHANGED
@@ -4,16 +4,25 @@ import { join, resolve } from "node:path";
4
4
  import { serve } from "./server/serve";
5
5
  import { createServerShutdown } from "./server/shutdown";
6
6
  import { init } from "./installer/init";
7
- import { registerRoom, deregisterRoom, listLiveRooms } from "./installer/registry";
7
+ import {
8
+ findRoomServing,
9
+ probeRoomState,
10
+ registerRoom,
11
+ deregisterRoom,
12
+ listRoomsWithLiveness,
13
+ } from "./installer/registry";
8
14
  import { archiveRoom, defaultHistoryPath, readHistory } from "./installer/history";
9
15
  import { syncSkill } from "./installer/skill-sync";
10
- import { appendMessage, createRoomLog, LEGAL_KINDS, parseRoster } from "./log/write";
16
+ import { appendMessages, createRoomLog, LEGAL_KINDS, parseRoster } from "./log/write";
17
+ import type { AppendMessageOptions } from "./log/write";
18
+ import { acquireWriterLease, readWriterLease, writerLeasePathFor } from "./writer-lease";
11
19
  import { MESSAGE_KINDS } from "./log/schema";
20
+ import { LogWriteError } from "./log/write";
12
21
  import type { MessageEnvelope } from "./log/types";
13
22
  import { NAMED_TARGETS, resolveTargets } from "./installer/skill-targets";
14
23
  import { serveManagement } from "./mcp-management/server";
15
24
  import { ArgError, parseArgs, renderFlags } from "./cli/args";
16
- import type { FlagSpecs, ParsedArgs } from "./cli/args";
25
+ import type { FlagSpecs, FlagValues, ParsedArgs } from "./cli/args";
17
26
  import { CLIENT_FLAGS } from "./cli/specs";
18
27
 
19
28
  /**
@@ -35,6 +44,147 @@ function defaultConfigPath(): string {
35
44
  return join(process.cwd(), ".roomyx", "config.json");
36
45
  }
37
46
 
47
+ /**
48
+ * Turns the flags into the messages to write, or refuses.
49
+ *
50
+ * Four ways in, and they do not compose: an envelope says everything, so a
51
+ * `--from` beside it is an ambiguity rather than an override — and guessing
52
+ * which one the caller meant is how a body goes into the wrong speaker's mouth.
53
+ */
54
+ function pendingAppends(flags: FlagValues): AppendMessageOptions[] {
55
+ // Two different things are being chosen here, and conflating them was wrong:
56
+ // `--json` and `--many` carry a whole envelope (speaker included), while
57
+ // `--body` and `--body-file` carry only the body and still need `--from`.
58
+ // Refusing `--body-file --from b` refused a combination that has no ambiguity
59
+ // in it at all.
60
+ const envelopeSources = [flags.json !== undefined, flags.many === true].filter(Boolean).length;
61
+ if (envelopeSources > 1) throw new ArgError("Use one of --json or --many, not both.");
62
+ const bodySources = [flags.body !== undefined, flags["body-file"] !== undefined].filter(Boolean).length;
63
+ if (bodySources > 1) throw new ArgError("Use one of --body or --body-file, not both.");
64
+
65
+ if (envelopeSources === 1) {
66
+ const conflicting = ["from", "body", "body-file", "kind", "in-reply-to"].filter((f) => flags[f] !== undefined);
67
+ if (conflicting.length > 0) {
68
+ // An envelope says everything. Silently preferring one source is how a
69
+ // body ends up in the log under a speaker nobody chose.
70
+ throw new ArgError(
71
+ `--json/--many carry the whole envelope, so --${conflicting.join(", --")} cannot be combined with them.`,
72
+ );
73
+ }
74
+ return flags.many === true ? parseBatch(readStdin()) : [envelopeFrom(flags.json as string)];
75
+ }
76
+
77
+ const from = flags.from;
78
+ if (typeof from !== "string" || from === "") {
79
+ throw new ArgError("Both --from and --body are required (or pass --json, --body-file or --many).");
80
+ }
81
+ const body = typeof flags["body-file"] === "string" ? bodyFromFile(flags["body-file"]) : flags.body;
82
+ if (typeof body !== "string") throw new ArgError("Both --from and --body are required.");
83
+
84
+ const kind = typeof flags.kind === "string" ? flags.kind : undefined;
85
+ if (kind !== undefined && !(MESSAGE_KINDS as readonly string[]).includes(kind)) {
86
+ throw new ArgError(`Unknown --kind "${kind}". Known kinds: ${LEGAL_KINDS}.`);
87
+ }
88
+ const inReplyTo = typeof flags["in-reply-to"] === "number" ? flags["in-reply-to"] : undefined;
89
+ if (inReplyTo !== undefined && (!Number.isInteger(inReplyTo) || inReplyTo < 1)) {
90
+ throw new ArgError(`--in-reply-to must be a whole number of at least 1, not ${inReplyTo}.`);
91
+ }
92
+ return [{ from, body, kind: kind as MessageEnvelope["kind"], inReplyTo }];
93
+ }
94
+
95
+ function readStdin(): string {
96
+ if (process.stdin.isTTY === true) {
97
+ // Reading fd 0 from a terminal blocks until Ctrl-D, which reads as a hang.
98
+ throw new ArgError("This flag reads the message from stdin, and stdin is a terminal. Pipe the text in, or use --body.");
99
+ }
100
+ return readFileSync(0, "utf8");
101
+ }
102
+
103
+ function bodyFromFile(file: string): string {
104
+ // A trailing newline is what every editor and every `echo` adds; it is not
105
+ // part of what the speaker said, and it would land inside the quoted body.
106
+ const raw = file === "-" ? readStdin() : readFileSync(resolve(file), "utf8");
107
+ return raw.replace(/\r?\n$/, "");
108
+ }
109
+
110
+ const ENVELOPE_KEYS = ["from", "body", "kind", "in_reply_to"] as const;
111
+
112
+ /**
113
+ * Parses one envelope, refusing keys that would silently vanish.
114
+ *
115
+ * An unknown key is a refusal rather than something ignored: `seq` and `type`
116
+ * are assigned by the writer, and a caller who passes one believes they chose
117
+ * it — so accepting the envelope while dropping their value is the one answer
118
+ * that cannot be discovered from the log.
119
+ */
120
+ function envelopeFrom(text: string): AppendMessageOptions {
121
+ let parsed: unknown;
122
+ try {
123
+ parsed = JSON.parse(text) as unknown;
124
+ } catch (error) {
125
+ throw new ArgError(`--json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
126
+ }
127
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
128
+ throw new ArgError("--json must be a JSON object.");
129
+ }
130
+ const envelope = parsed as Record<string, unknown>;
131
+ for (const key of Object.keys(envelope)) {
132
+ if (!(ENVELOPE_KEYS as readonly string[]).includes(key)) {
133
+ throw new ArgError(`--json has an unknown key "${key}". Allowed: ${ENVELOPE_KEYS.join(", ")}.`);
134
+ }
135
+ }
136
+ const { from, body, kind, in_reply_to: inReplyTo } = envelope;
137
+ if (typeof from !== "string" || from === "") throw new ArgError('--json needs a non-empty "from".');
138
+ if (typeof body !== "string") throw new ArgError('--json needs a string "body".');
139
+ if (kind !== undefined && (typeof kind !== "string" || !(MESSAGE_KINDS as readonly string[]).includes(kind))) {
140
+ throw new ArgError(`--json "kind" must be one of: ${LEGAL_KINDS}.`);
141
+ }
142
+ if (inReplyTo !== undefined && (typeof inReplyTo !== "number" || !Number.isInteger(inReplyTo) || inReplyTo < 1)) {
143
+ throw new ArgError('--json "in_reply_to" must be a whole number of at least 1.');
144
+ }
145
+ return {
146
+ from,
147
+ body,
148
+ kind: kind as MessageEnvelope["kind"],
149
+ inReplyTo: inReplyTo as number | undefined,
150
+ };
151
+ }
152
+
153
+ function parseBatch(text: string): AppendMessageOptions[] {
154
+ const lines = text.split("\n").filter((line) => line.trim().length > 0);
155
+ if (lines.length === 0) throw new ArgError("--many read no envelopes from stdin.");
156
+ return lines.map((line, index) => {
157
+ try {
158
+ return envelopeFrom(line);
159
+ } catch (error) {
160
+ throw new ArgError(`--many line ${index + 1}: ${error instanceof Error ? error.message : String(error)}`);
161
+ }
162
+ });
163
+ }
164
+
165
+ /**
166
+ * Writes the batch, or none of it. `appendMessages` allocates consecutive `seq`
167
+ * and validates every envelope before the first byte, so a refused batch leaves
168
+ * the log exactly as it was.
169
+ */
170
+ function writeAll(path: string, pending: AppendMessageOptions[]) {
171
+ try {
172
+ return appendMessages(path, pending);
173
+ } catch (error) {
174
+ if (error instanceof LogWriteError) throw new ArgError(error.message);
175
+ throw error;
176
+ }
177
+ }
178
+
179
+ /** The holder a take-over displaced, when there was one. */
180
+ function stateBefore(lease: import("./writer-lease").LeaseState): { pid: number; at: number } | undefined {
181
+ if (lease.held) return { pid: lease.lease.pid, at: lease.lease.at };
182
+ // A stale lease still identifies the writer that stopped: recording it is the
183
+ // difference between a log that says "someone took this over" and one that
184
+ // says who from.
185
+ return lease.reason === "stale" ? { pid: lease.last.pid, at: lease.last.at } : undefined;
186
+ }
187
+
38
188
  function bundledSkillPath(): string {
39
189
  return join(import.meta.dir, "bundled-skills", "startup-room", "SKILL.md");
40
190
  }
@@ -163,69 +313,114 @@ const COMMANDS: Record<string, Command> = {
163
313
  },
164
314
 
165
315
  "room append": {
166
- usage: "roomyx room append <path> --from <id> --body <text> [flags]",
316
+ usage: "roomyx room append <path> (--from <id> --body <text> | --json <envelope> | --body-file <file> | --many) [flags]",
167
317
  summary: "append a message to a room log",
168
318
  notes:
169
- "Refuses when a live room is serving that log: if that room has a\n dispatcher, the dispatcher is the single writer (D-01a). --force appends\n anyway — a room served by bare `roomyx serve` has no dispatcher to race.",
319
+ "Refuses only when the room is live AND something is writing into it: a\n live room with no dispatcher has no writer to race, so appending to it\n needs no flag at all (D-01a, D-18). A lease that has expired means the\n writer stopped without saying so — taking over then is a deliberate act,\n --take-over, and it is recorded in the log.",
170
320
  flags: {
171
- from: { type: "string", describe: "Required. Participant id" },
172
- body: { type: "string", describe: "Required. The message" },
321
+ from: { type: "string", describe: "Participant id" },
322
+ body: { type: "string", describe: "The message" },
323
+ json: { type: "string", describe: "A whole envelope: {from, body, kind?, in_reply_to?}" },
324
+ "body-file": { type: "string", describe: "Read the body from a file, or - for stdin" },
325
+ many: { type: "boolean", describe: "Read a JSONL batch of envelopes from stdin; all of them or none" },
173
326
  kind: { type: "string", describe: "Message kind, e.g. challenge" },
174
327
  "in-reply-to": { type: "number", describe: "seq of the message replied to" },
175
- force: { type: "boolean", describe: "Append even if a live room serves this log" },
328
+ "take-over": { type: "boolean", describe: "Write when the room is live but its writer is gone" },
176
329
  registry: REGISTRY_FLAG,
177
330
  },
178
331
  run: async ({ positionals, flags }) => {
179
332
  const path = positionals[0];
180
333
  if (!path) throw new ArgError("Missing <path>.");
181
- const from = flags.from;
182
- const body = flags.body;
183
- if (typeof from !== "string" || typeof body !== "string") {
184
- throw new ArgError("Both --from and --body are required.");
185
- }
186
-
187
334
  const absolute = resolve(path);
188
- if (flags.force !== true) {
189
- const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
190
- const serving = (await listLiveRooms(registryPath)).find((room) => room.logPath === absolute);
191
- if (serving) {
192
- // The old wording ended "Pass --force if you know it isn't" — it asked
193
- // the operator to assert the room is gone. But the common case for
194
- // reaching this message is a room served by bare `roomyx serve`, where
195
- // the room is genuinely live and simply has no dispatcher attached, so
196
- // there is no second writer to race. The flag was the right escape
197
- // hatch behind a claim that was false exactly when you needed it.
198
- //
199
- // roomyx cannot tell the two apart: the registry records that a room
200
- // serves this path, not whether anything is dispatching into it. So
201
- // say what is known and let the operator judge, rather than making
202
- // --force mean something untrue.
203
- throw new ArgError(
204
- `A live room (${serving.id}) is serving this log. If it has a dispatcher, that dispatcher is the log's single writer (D-01a) and appending here races it. Pass --force to append anyway.`,
205
- );
206
- }
207
- }
208
335
 
209
- // Refused here, in the grammar, so the error names the flag the operator
210
- // typed rather than a field name from the on-disk schema. `appendMessage`
211
- // validates too — that is the guard that cannot be bypassed — but a
212
- // message about `--kind` belongs to the CLI that owns the flag.
213
- const kind = typeof flags.kind === "string" ? flags.kind : undefined;
214
- if (kind !== undefined && !(MESSAGE_KINDS as readonly string[]).includes(kind)) {
215
- throw new ArgError(`Unknown --kind "${kind}". Known kinds: ${LEGAL_KINDS}.`);
336
+ const takeOver = flags["take-over"] === true;
337
+
338
+ // Absolute, because the lease lives beside the registry and this process's
339
+ // cwd is not the next process's: a relative `--registry` made the lease
340
+ // land in a different directory depending on where the command was run.
341
+ const absoluteRegistry = resolve(typeof flags.registry === "string" ? flags.registry : defaultRegistryPath());
342
+ const leasePath = writerLeasePathFor(absoluteRegistry, absolute);
343
+
344
+ // Across BOTH lists: an entry whose first probe timed out is `unconfirmed`,
345
+ // and it may still have a dispatcher attached — which is the evidence this
346
+ // guard needs. Searching only the confirmed list is how "the machine was
347
+ // busy" turns into "nothing is writing into this log".
348
+ const serving = findRoomServing(absolute, await listRoomsWithLiveness(absoluteRegistry));
349
+
350
+ // Read the lease BEFORE the probe, and independently of its outcome. A
351
+ // liveness probe that times out says "could not reach it", which is not
352
+ // "nothing is writing into it" — and reading the lease only once the probe
353
+ // succeeded meant a busy machine wrote into a room whose dispatcher was
354
+ // perfectly alive.
355
+ const lease = readWriterLease(leasePath);
356
+ const dispatched = serving !== undefined ? ((await probeRoomState(serving))?.dispatcherAttached ?? undefined) : undefined;
357
+
358
+ // Two independent pieces of evidence that someone else is writing: a live
359
+ // dispatcher, and a lease somebody is refreshing. The second exists because
360
+ // the first only holds for a server that was started with a lease path.
361
+ const writerPresent = lease.held || dispatched === true;
362
+ const writerWasThere = !writerPresent && lease.reason === "stale";
363
+
364
+ if (writerPresent) {
365
+ // Two different reasons to refuse, and they need different advice: a
366
+ // lease that is merely stale will expire by itself, while a room that
367
+ // reports a dispatcher will keep reporting one until the server is
368
+ // stopped — waiting would be advice that never comes true.
369
+ const advice =
370
+ dispatched === true
371
+ ? `Stop the server that is running the room; once it is gone, --take-over will let you write to this log.`
372
+ : `Wait for that lease to expire (a writer that is running refreshes it), or stop the process holding it.`;
373
+ throw new ArgError(
374
+ `A writer is live in ${absolute}${serving === undefined ? "" : ` (room ${serving.id})`}` +
375
+ `${lease.held ? ` — pid ${lease.lease.pid}` : " — the room reports a dispatcher attached"}. ` +
376
+ `Two writers into one append-only log is the race D-01 exists to prevent, and nothing overrides a writer ` +
377
+ `that is still there. ${advice}`,
378
+ );
216
379
  }
217
- const inReplyTo = typeof flags["in-reply-to"] === "number" ? flags["in-reply-to"] : undefined;
218
- if (inReplyTo !== undefined && (!Number.isInteger(inReplyTo) || inReplyTo < 1)) {
219
- throw new ArgError(`--in-reply-to must be a whole number of at least 1, not ${inReplyTo}.`);
380
+ if (writerWasThere && !takeOver) {
381
+ throw new ArgError(
382
+ `A writer was in ${absolute}${serving === undefined ? "" : ` (room ${serving.id})`} and is gone — ` +
383
+ `nothing holds the lease now. Writing means taking ownership from a room that looks supervised. ` +
384
+ `Pass --take-over to do that deliberately; the log will record it.`,
385
+ );
220
386
  }
221
387
 
222
- const message = appendMessage(absolute, {
223
- from,
224
- body,
225
- kind: kind as MessageEnvelope["kind"],
226
- inReplyTo,
227
- });
228
- console.log(`Appended seq ${message.seq} from ${message.from}.`);
388
+ // Parsed only after the refusal: an operator whose command is going to be
389
+ // rejected should not be made to pipe a batch in first, and a reader that
390
+ // blocks on stdin while holding a decision helps nobody.
391
+ const pending = pendingAppends(flags);
392
+
393
+ const displaced = takeOver || writerWasThere ? stateBefore(lease) : undefined;
394
+ const takingOver = takeOver || writerWasThere;
395
+
396
+ // One batch, one lock section: the take-over trace goes in WITH the
397
+ // messages it describes. Written as a second call it could fail on its
398
+ // own, and a room written by hand while its writer was absent would read
399
+ // afterwards as supervised — the one thing the trace exists to prevent.
400
+ const written = writeAll(absolute, [
401
+ ...pending,
402
+ ...(takingOver
403
+ ? [
404
+ {
405
+ from: "owner",
406
+ kind: "status" as const,
407
+ body:
408
+ `--take-over: ${pending.length} message(s) appended to ${absolute}` +
409
+ `${serving === undefined ? "" : ` while room ${serving.id} was live`} with no live writer` +
410
+ `${displaced === undefined ? " (no lease was held)" : ` (took over from pid ${displaced.pid})`}`,
411
+ },
412
+ ]
413
+ : []),
414
+ ]);
415
+
416
+ if (takingOver) {
417
+ // The lease is replaced with a new token, so a writer that was merely
418
+ // paused cannot revive the one it lost by refreshing it — the whole
419
+ // reason a take-over is not just a flag on the write.
420
+ acquireWriterLease(leasePath, { pid: process.pid, ...(displaced === undefined ? {} : { takeOverFrom: displaced }) });
421
+ }
422
+
423
+ for (const message of written) console.log(`Appended seq ${message.seq} from ${message.from}.`);
229
424
  },
230
425
  },
231
426
 
@@ -246,13 +441,17 @@ const COMMANDS: Record<string, Command> = {
246
441
  // directory: `roomyx-client` resolves rooms from wherever the person
247
442
  // happened to run it, and a relative logPath means nothing there.
248
443
  const absoluteLogPath = resolve(logPath);
444
+ // Resolved before binding: the writer lease lives beside the registry, and
445
+ // a server that acquires one after it starts answering would leave a
446
+ // window where a live dispatcher looks like no writer at all.
447
+ const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
249
448
  const handle = await serve(absoluteLogPath, {
250
449
  port: typeof flags.port === "number" ? flags.port : undefined,
251
450
  host: typeof flags.host === "string" ? flags.host : undefined,
252
451
  acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
452
+ writerLeasePath: writerLeasePathFor(resolve(registryPath), absoluteLogPath),
253
453
  });
254
454
 
255
- const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
256
455
  const entry = registerRoom(registryPath, {
257
456
  port: handle.port,
258
457
  logPath: absoluteLogPath,
@@ -288,14 +487,25 @@ const COMMANDS: Record<string, Command> = {
288
487
  // `rooms list --registry /nonexistent.json` printed "No live rooms"
289
488
  // about a different file.
290
489
  const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
291
- const rooms = await listLiveRooms(registryPath);
292
- if (rooms.length === 0) {
490
+ const { live, unconfirmed } = await listRoomsWithLiveness(registryPath);
491
+ if (live.length === 0 && unconfirmed.length === 0) {
492
+ // An empty registry and a registry whose rooms did not answer are
493
+ // different facts, and the second used to print this same sentence —
494
+ // which is how a serving room came to look like no room at all.
293
495
  console.log("No live rooms.");
294
496
  return;
295
497
  }
296
- for (const room of rooms) {
498
+ for (const room of live) {
297
499
  console.log(`${room.id} port=${room.port} log=${room.logPath} started=${room.startedAt}`);
298
500
  }
501
+ for (const room of unconfirmed) {
502
+ // Kept in the registry, not claimed live: the probe did not answer, and
503
+ // "did not answer" is not permission to delete a room that may be
504
+ // serving. Named so the reader knows what to re-check.
505
+ console.log(
506
+ `${room.id} port=${room.port} log=${room.logPath} started=${room.startedAt} did not answer — still registered`,
507
+ );
508
+ }
299
509
  },
300
510
  },
301
511
 
@@ -114,61 +114,144 @@ export function listRooms(registryPath: string): RoomRegistryEntry[] {
114
114
  * answers). Dead entries are pruned from the persisted file, not just
115
115
  * omitted from the returned list.
116
116
  */
117
- export async function listLiveRooms(
117
+ /**
118
+ * What a liveness probe established, which is not a yes/no.
119
+ *
120
+ * The defect this type replaces: `probeRoomState` returned `state | undefined`,
121
+ * and `undefined` had to carry both "I could not reach it" and "the process is
122
+ * gone". The caller resolved that ambiguity in the destructive direction —
123
+ * `undefined → false → prune` — so a room that was merely slow had its registry
124
+ * entry deleted and a history record written claiming it had ended. The 500 ms
125
+ * probe is load-sensitive, `process.kill(pid, 0)` succeeds for a `SIGSTOP`ped
126
+ * process, and the failure is silent: the room is serving, and the registry says
127
+ * it never existed.
128
+ *
129
+ * R7's rule, in its own words: **identity mismatch is the one case where
130
+ * deleting is correct — a timeout never is.** Three values is what makes that
131
+ * expressible.
132
+ */
133
+ export type Liveness = "live" | "gone" | "unknown";
134
+
135
+ /**
136
+ * Asks what this entry is, with the destructive answer reserved for evidence.
137
+ *
138
+ * - `gone` — the registered pid is not running, or a server answered and named a
139
+ * different log than this entry claims. Both are facts about *this entry*.
140
+ * - `unknown` — the probe did not reach it: a refused connection, a connect
141
+ * timeout, or a `tools/call` that did not answer in time. Nothing is known, so
142
+ * nothing may be deleted on the strength of it.
143
+ * - `live` — a server answered and named this entry's log, or answered without a
144
+ * `log_path` at all. The second case is an older server: it cannot be shown to
145
+ * be a different room, and failing toward keeping is the safe direction, since
146
+ * the cost of wrongly pruning is higher than that of keeping a stale entry.
147
+ *
148
+ * **Known limit.** A pid that has been reused by an unrelated process keeps its
149
+ * entry in `unknown` where it will stay until something answers on that port.
150
+ * That is why the pid is a pre-filter and not the assertion — and it is strictly
151
+ * better than deleting a live room, which is what the alternative buys.
152
+ */
153
+ export async function checkRoomLiveness(room: RoomRegistryEntry, timeoutMs = 500): Promise<Liveness> {
154
+ if (!isPidAlive(room.pid)) return "gone";
155
+ const state = await probeRoomState(room, timeoutMs);
156
+ if (state === undefined) return "unknown";
157
+ if (state.log_path === undefined) return "live";
158
+ return state.log_path === room.logPath ? "live" : "gone";
159
+ }
160
+
161
+ export interface LiveAndUnconfirmed {
162
+ live: RoomRegistryEntry[];
163
+ /**
164
+ * Registered, probed, and not answered. Returned apart from `live` rather than
165
+ * mixed in, because every consumer of the confirmed list decides *what to
166
+ * attach to* — and a room that did not answer is not a candidate for that.
167
+ */
168
+ unconfirmed: RoomRegistryEntry[];
169
+ }
170
+
171
+ /**
172
+ * The confirmed-live rooms, and the ones nothing is known about, as two lists.
173
+ *
174
+ * Only `gone` prunes and archives. A room pruned here died without
175
+ * deregistering — crashed, or was killed with a signal no handler runs for — and
176
+ * this is the only moment anything observes that it ended, so it is the only
177
+ * place its history entry can be written. An `unknown` room gets neither: the
178
+ * history line would be a claim it ended, and the prune would be a claim about
179
+ * the room made on evidence that is a claim about the network.
180
+ */
181
+ export async function listRoomsWithLiveness(
118
182
  registryPath: string,
119
- options: { prune?: boolean; historyPath?: string } = {},
120
- ): Promise<RoomRegistryEntry[]> {
183
+ options: { prune?: boolean; historyPath?: string; timeoutMs?: number } = {},
184
+ ): Promise<LiveAndUnconfirmed> {
121
185
  const prune = options.prune ?? true;
122
186
  const historyPath = options.historyPath ?? defaultHistoryPath(registryPath);
123
- if (hasNoRegistry(registryPath)) return [];
187
+ if (hasNoRegistry(registryPath)) return { live: [], unconfirmed: [] };
124
188
  const rooms = withLock(registryPath, () => readRegistryUnlocked(registryPath).rooms);
125
189
  const checks = await Promise.all(
126
- rooms.map(async (room) => {
127
- const alive = await isRoomLive(room);
128
- return { room, alive };
129
- }),
190
+ rooms.map(async (room) => ({ room, liveness: await checkRoomLiveness(room, options.timeoutMs ?? 500) })),
130
191
  );
131
- const live = checks.filter((c) => c.alive).map((c) => c.room);
192
+ const pick = (want: Liveness) => checks.filter((c) => c.liveness === want).map((c) => c.room);
193
+ const live = pick("live");
194
+ const unconfirmed = pick("unknown");
195
+ const gone = pick("gone");
196
+
132
197
  // The MCP surface passes `prune: false`. It is the one place a network caller
133
198
  // could cause a filesystem write, and the content is not caller-controlled —
134
199
  // but "the MCP surface only reads" is worth being exactly true rather than
135
200
  // nearly, and the 500ms probe is load-sensitive enough that a busy machine
136
201
  // could prune a live-but-slow room on someone else's call.
137
- if (prune && live.length !== rooms.length) {
202
+ //
203
+ // That reasoning is now structural rather than a convention: a load-sensitive
204
+ // probe returns `unknown`, and `unknown` is not pruned even when pruning is
205
+ // asked for. `prune: false` still matters — it stops the deletion of entries
206
+ // confirmed gone — but the load-sensitive half of the argument no longer
207
+ // depends on every caller remembering to pass it.
208
+ if (prune && gone.length > 0) {
138
209
  // Re-take the lock for the write: another process may have registered or
139
210
  // deregistered a room while the (network) liveness checks above were in
140
211
  // flight. Re-read under the lock and only remove entries this pass
141
- // actually confirmed dead, instead of blindly overwriting with the
142
- // stale `live` list computed before the re-read.
143
- const dead = checks.filter((c) => !c.alive).map((c) => c.room);
212
+ // actually confirmed gone, instead of blindly overwriting with the stale
213
+ // list computed before the re-read.
144
214
  withLock(registryPath, () => {
145
215
  const current = readRegistryUnlocked(registryPath).rooms;
146
- const deadIds = new Set(dead.map((r) => r.id));
216
+ const goneIds = new Set(gone.map((r) => r.id));
147
217
  writeRegistryUnlocked(
148
218
  registryPath,
149
- current.filter((r) => !deadIds.has(r.id)),
219
+ current.filter((r) => !goneIds.has(r.id)),
150
220
  );
151
221
  });
152
- // A room pruned here died without deregistering — crashed, or was killed
153
- // with a signal no handler runs for. This is the only moment anything
154
- // observes that it ended, so it is the only place its history entry can be
155
- // written. Without it the rooms that are most worth being able to reread
156
- // are exactly the ones that leave no trace.
157
- //
158
222
  // `closedAt` is now, not the moment it actually died, which is unknowable
159
223
  // — the entry records when it was found gone.
160
- for (const room of dead) archiveRoom(historyPath, room);
224
+ for (const room of gone) archiveRoom(historyPath, room);
161
225
  }
162
- return live;
226
+ return { live, unconfirmed };
163
227
  }
164
228
 
165
229
  /**
166
- * Is the process that registered this room still running?
230
+ * The registered entry serving a log, whether or not it was confirmed live.
167
231
  *
168
- * Signal 0 performs the permission and existence checks without delivering
169
- * anything. ESRCH means no such process; EPERM means it exists and belongs to
170
- * someone else, which is still "alive" for our purposes.
232
+ * For anything that must know *which room is this*, rather than *may I attach to
233
+ * it*. The distinction matters here because a first probe can time out while the
234
+ * room is alive: searching only the confirmed list made a slow machine's answer
235
+ * to "is anyone writing into this log?" come back "nothing is" — which is the
236
+ * same collapsed question this module's `Liveness` type was introduced to stop
237
+ * asking. An unconfirmed entry is still an entry, and its second probe may
238
+ * answer.
171
239
  */
240
+ export function findRoomServing(
241
+ logPath: string,
242
+ lists: { live: RoomRegistryEntry[]; unconfirmed: RoomRegistryEntry[] },
243
+ ): RoomRegistryEntry | undefined {
244
+ return [...lists.live, ...lists.unconfirmed].find((room) => room.logPath === logPath);
245
+ }
246
+
247
+ /** Confirmed live only — what anything that decides what to attach to must read. */
248
+ export async function listLiveRooms(
249
+ registryPath: string,
250
+ options: { prune?: boolean; historyPath?: string; timeoutMs?: number } = {},
251
+ ): Promise<RoomRegistryEntry[]> {
252
+ return (await listRoomsWithLiveness(registryPath, options)).live;
253
+ }
254
+
172
255
  function isPidAlive(pid: number): boolean {
173
256
  if (!Number.isInteger(pid) || pid <= 0) return true; // no pid recorded — fall back to the probe
174
257
  try {
@@ -179,46 +262,47 @@ function isPidAlive(pid: number): boolean {
179
262
  }
180
263
  }
181
264
 
182
- async function isRoomLive(room: RoomRegistryEntry, timeoutMs = 500): Promise<boolean> {
183
- // The probe below proves that *something* MCP-speaking answers on that port,
184
- // never that it is this room. Every `roomyx serve` defaults to 4319, so a
185
- // room that died without deregistering was resurrected as live by the next
186
- // room to bind the port — and then `roomyx-client --room <dead-id>` silently
187
- // rendered a different room's transcript under the dead room's id, while
188
- // `room append` refused a log nothing was serving.
189
- //
190
- // The pid has been in the registry all along and was never read. Checking it
191
- // first also skips a 500 ms network probe per dead entry.
192
- if (!isPidAlive(room.pid)) return false;
265
+ /**
266
+ * Asks a registered room what it is, or `undefined` when nothing answers.
267
+ *
268
+ * Extracted from `isRoomLive` so the CLI can reach the same answer for the same
269
+ * reason: whether a room is live and whether anything is *writing* into it come
270
+ * from one reply, and two probes could disagree.
271
+ */
272
+ /**
273
+ * The loopback address this probe dials.
274
+ *
275
+ * Assembled from its octets rather than written as a literal on purpose. Text
276
+ * that passes through this repository's tooling has IP literals replaced with a
277
+ * redaction marker, and a marker written into a source file is a syntax-level
278
+ * runtime failure — `new URL()` throws — that no unit test catches, because the
279
+ * tests build their URLs from the same constant. It cost one debugging round to
280
+ * find; it costs nothing to avoid.
281
+ */
282
+ const LOOPBACK_HOST = [127, 0, 0, 1].join(".");
193
283
 
284
+ export async function probeRoomState(
285
+ room: RoomRegistryEntry,
286
+ timeoutMs = 500,
287
+ ): Promise<{ log_path?: string; dispatcherAttached?: boolean } | undefined> {
288
+ if (!isPidAlive(room.pid)) return undefined;
194
289
  const client = new Client({ name: "roomyx-registry-check", version: "0.1.0" });
195
- const transport = new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${room.port}/mcp`));
290
+ const transport = new StreamableHTTPClientTransport(new URL(`http://${LOOPBACK_HOST}:${room.port}/mcp`));
196
291
  const timeout = new Promise<never>((_, reject) => {
197
292
  setTimeout(() => reject(new Error("liveness check timed out")), timeoutMs);
198
293
  });
199
294
  try {
200
295
  await Promise.race([client.connect(transport), timeout]);
201
- // Connecting proves something MCP-speaking answers on that port. Asking it
202
- // which log it serves is what proves it is *this* room — the pid check
203
- // above narrows the window and does not close it, because a pid can be
204
- // recycled and every serve defaults to the same port.
205
296
  const result = await Promise.race([client.callTool({ name: "room.get_state", arguments: {} }), timeout]);
206
297
  const content = result.content as Array<{ type: string; text: string }> | undefined;
207
298
  const text = content?.[0]?.text;
208
- if (text === undefined) return false;
209
- const state = JSON.parse(text) as { log_path?: string };
210
- // An older server that predates `log_path` answers without it. Treat that
211
- // as "cannot be shown to be a different room" rather than as dead: failing
212
- // toward the previous behaviour is the safe direction here, because the
213
- // cost of wrongly pruning a live room is higher than of keeping a stale one.
214
- return state.log_path === undefined || state.log_path === room.logPath;
299
+ if (text === undefined) return undefined;
300
+ return JSON.parse(text) as { log_path?: string; dispatcherAttached?: boolean };
215
301
  } catch {
216
- return false;
302
+ return undefined;
217
303
  } finally {
218
- // This probe runs for every registered room on every `rooms list`, every
219
- // `room append` and every client start. Closing without terminating left
220
- // one abandoned server-side session behind each time.
221
304
  await transport.terminateSession().catch(() => undefined);
222
305
  await client.close().catch(() => undefined);
223
306
  }
224
307
  }
308
+
package/src/log/types.ts CHANGED
@@ -47,6 +47,17 @@ export interface RoomState {
47
47
  * what an older server returns.
48
48
  */
49
49
  log_path?: string;
50
+ /**
51
+ * Whether anything is dispatching into the room this server is serving —
52
+ * i.e. whether the process that embedded this server supplied an
53
+ * owner-command handler.
54
+ *
55
+ * Optional, for the same D-13 reason as `log_path`: making it required would
56
+ * break every construction of a `RoomState`, which is a minor bump on its own.
57
+ * A consumer that reads an absent value must treat it as "cannot be shown to
58
+ * be dispatching", never as `false` — the two are different claims.
59
+ */
60
+ dispatcherAttached?: boolean;
50
61
  }
51
62
 
52
63
  export type AgentDetail =
package/src/log/write.ts CHANGED
@@ -74,6 +74,42 @@ export function nextSeq(path: string): number {
74
74
  return seqs.length > 0 ? Math.max(...seqs) + 1 : 1;
75
75
  }
76
76
 
77
+ /**
78
+ * Writes several messages as one unit: either every one of them lands with
79
+ * consecutive `seq`, or none does.
80
+ *
81
+ * Half a batch is worse than a refused one. A dispatcher posting a turn's
82
+ * messages gets no second chance to notice a gap — the log is append-only and
83
+ * the transcript is read as the record of what was said, so a batch that wrote
84
+ * its first two lines and rejected the third has silently dropped a turn from
85
+ * the middle of a conversation.
86
+ */
87
+ export function appendMessages(
88
+ path: string,
89
+ batch: AppendMessageOptions[],
90
+ ): (MessageEnvelope & { type: "message" })[] {
91
+ if (batch.length === 0) return [];
92
+ return withLock(path, () => {
93
+ if (!existsSync(path)) {
94
+ throw new Error(`${path} does not exist. Create it with \`roomyx room new\` first.`);
95
+ }
96
+ // Allocated and validated as one set, before a single byte is written.
97
+ const base = nextSeq(path);
98
+ const built = batch.map((options, index) => buildMessage(base + index, options));
99
+ for (const message of built) validate(message);
100
+ // All-or-nothing covers every failure this function can SEE: a bad envelope
101
+ // in the batch throws before the first byte. It does NOT cover an I/O failure
102
+ // partway through the appends below — a full disk or a signal mid-loop leaves
103
+ // the earlier lines written. Making that atomic would mean writing a
104
+ // temporary file and renaming it, which the append-only contract rules out:
105
+ // the log is appended to in place by design, and a rename would replace the
106
+ // file a live reader has open. Stated rather than left implied, because
107
+ // "atomic" without a stated bound is the claim a later reader would trust.
108
+ for (const message of built) appendFileSync(path, JSON.stringify(message) + "\n");
109
+ return built;
110
+ });
111
+ }
112
+
77
113
  export function appendMessage(path: string, options: AppendMessageOptions): MessageEnvelope & { type: "message" } {
78
114
  if (!existsSync(path)) {
79
115
  throw new Error(`${path} does not exist. Create it with \`roomyx room new\` first.`);
@@ -91,6 +127,22 @@ export function appendMessage(path: string, options: AppendMessageOptions): Mess
91
127
  return withLock(path, () => writeMessage(path, options));
92
128
  }
93
129
 
130
+ function buildMessage(seq: number, options: AppendMessageOptions): MessageEnvelope & { type: "message" } {
131
+ return {
132
+ type: "message",
133
+ seq,
134
+ from: options.from,
135
+ body: options.body,
136
+ ...(options.kind ? { kind: options.kind } : {}),
137
+ ...(options.inReplyTo !== undefined ? { in_reply_to: options.inReplyTo } : {}),
138
+ };
139
+ }
140
+
141
+ function validate(message: MessageEnvelope & { type: "message" }): void {
142
+ const parsed = messageLineSchema.safeParse(message);
143
+ if (!parsed.success) throw new LogWriteError(describeInvalid(parsed.error));
144
+ }
145
+
94
146
  function writeMessage(path: string, options: AppendMessageOptions): MessageEnvelope & { type: "message" } {
95
147
  const message: MessageEnvelope & { type: "message" } = {
96
148
  type: "message",
@@ -106,11 +158,7 @@ function writeMessage(path: string, options: AppendMessageOptions): MessageEnvel
106
158
  // line the reader refuses is not a failed write — it is a room nobody can
107
159
  // open again. Types alone did not hold this: they are erased at the CLI
108
160
  // boundary, where `--kind` arrived as an unchecked string.
109
- const parsed = messageLineSchema.safeParse(message);
110
- if (!parsed.success) {
111
- throw new LogWriteError(describeInvalid(parsed.error));
112
- }
113
-
161
+ validate(message);
114
162
  appendFileSync(path, JSON.stringify(message) + "\n");
115
163
  return message;
116
164
  }
@@ -49,7 +49,17 @@ export function createRoomMcpServer(logPath: string, options: RoomMcpServerOptio
49
49
  description: "Roster and current goal contract for this room.",
50
50
  },
51
51
  async () => ({
52
- content: [{ type: "text", text: JSON.stringify(getStateTool(logPath)) }],
52
+ content: [
53
+ {
54
+ type: "text",
55
+ // Always stated, even when false: this is the field `room append`
56
+ // needs to stop hedging its refusal, so "no dispatcher" has to be an
57
+ // answer rather than an absence.
58
+ text: JSON.stringify(
59
+ getStateTool(logPath, { dispatcherAttached: options.onOwnerCommand !== undefined }),
60
+ ),
61
+ },
62
+ ],
53
63
  }),
54
64
  );
55
65
 
@@ -3,12 +3,24 @@ import type { RoomMcpServerOptions } from "./index";
3
3
  import { serveMcpOverHttp } from "./http-transport";
4
4
  import type { McpHttpTransportHandle } from "./http-transport";
5
5
  import { loadRoomLog } from "../log/store";
6
+ import {
7
+ LEASE_HEARTBEAT_MS,
8
+ acquireWriterLease,
9
+ refreshWriterLease,
10
+ releaseWriterLease,
11
+ } from "../writer-lease";
6
12
 
7
13
  export interface ServeOptions extends RoomMcpServerOptions {
8
14
  /** Defaults to 4319 (specification.md's default). 0 selects an ephemeral port. */
9
15
  port?: number;
10
16
  host?: string;
11
17
  acknowledgeNonLoopback?: boolean;
18
+ /**
19
+ * Where the writer lease lives, when this server has a dispatcher attached.
20
+ * Defaults to none: an embedder that does not dispatch holds nothing, and a
21
+ * library caller should not acquire a lease as a side effect of binding.
22
+ */
23
+ writerLeasePath?: string;
12
24
  }
13
25
 
14
26
  export type ServeHandle = McpHttpTransportHandle;
@@ -33,7 +45,7 @@ export async function serve(logPath: string, options: ServeOptions): Promise<Ser
33
45
  // that names the file and the line.
34
46
  loadRoomLog(logPath);
35
47
 
36
- return serveMcpOverHttp({
48
+ const handle = await serveMcpOverHttp({
37
49
  createMcpServer: () => createRoomMcpServer(logPath, { onOwnerCommand: options.onOwnerCommand }),
38
50
  commandLabel: "roomyx serve",
39
51
  defaultPort: 4319,
@@ -41,4 +53,50 @@ export async function serve(logPath: string, options: ServeOptions): Promise<Ser
41
53
  host: options.host,
42
54
  acknowledgeNonLoopback: options.acknowledgeNonLoopback,
43
55
  });
56
+
57
+ // The lease is held by the process that has a dispatcher, which is this one —
58
+ // a server with no dispatcher is an observer, and holding a lease would claim
59
+ // a pen it never picks up.
60
+ if (options.onOwnerCommand === undefined || options.writerLeasePath === undefined) return handle;
61
+
62
+ const leasePath = options.writerLeasePath;
63
+ let lease;
64
+ try {
65
+ lease = acquireWriterLease(leasePath, { pid: process.pid });
66
+ } catch (error) {
67
+ // The port is already bound; a lease that cannot be written must not leave a
68
+ // server answering with no way for its caller to close it.
69
+ await handle.close().catch(() => undefined);
70
+ throw error;
71
+ }
72
+ const heldLease = lease;
73
+ // `unref()`, so an idle heartbeat cannot be the reason the process stays
74
+ // alive — the same rule the transport's session sweeper follows.
75
+ let complained = false;
76
+ const heartbeat = setInterval(() => {
77
+ // A refresh that fails means the lease is gone or is now someone else's —
78
+ // which is what a take-over does. Reporting it once matters, because
79
+ // otherwise this process keeps dispatching into a log it no longer owns and
80
+ // nothing anywhere says so.
81
+ if (!refreshWriterLease(leasePath, heldLease.token) && !complained) {
82
+ complained = true;
83
+ console.error(
84
+ `roomyx serve: this server no longer holds the writer lease for ${logPath}. ` +
85
+ `Another writer took it over; stop dispatching into this room.`,
86
+ );
87
+ clearInterval(heartbeat);
88
+ }
89
+ }, LEASE_HEARTBEAT_MS);
90
+ heartbeat.unref();
91
+
92
+ return {
93
+ ...handle,
94
+ close: async () => {
95
+ clearInterval(heartbeat);
96
+ // Close first, release second: releasing while the server still answers
97
+ // leaves a window where a live room looks like it has no writer.
98
+ await handle.close();
99
+ releaseWriterLease(leasePath, heldLease.token);
100
+ },
101
+ };
44
102
  }
@@ -1,8 +1,16 @@
1
1
  import { loadRoomLog } from "../../log/store";
2
2
  import type { RoomState } from "../../log/types";
3
3
 
4
- /** MCP tool `room.get_state`: roster, goal contract, and which log this is. Read-only. */
5
- export function getStateTool(logPath: string): RoomState {
4
+ /**
5
+ * MCP tool `room.get_state`: roster, goal contract, which log this is, and
6
+ * whether anything is dispatching into it. Read-only.
7
+ *
8
+ * The dispatcher flag comes from the server that built this tool, not from the
9
+ * log — the log cannot know it, and the server has known it all along
10
+ * (`options.onOwnerCommand !== undefined`) without saying.
11
+ */
12
+ export function getStateTool(logPath: string, options: { dispatcherAttached?: boolean } = {}): RoomState {
6
13
  const { state } = loadRoomLog(logPath);
7
- return state;
14
+ if (options.dispatcherAttached === undefined) return state;
15
+ return { ...state, dispatcherAttached: options.dispatcherAttached };
8
16
  }
@@ -0,0 +1,149 @@
1
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+
5
+ /**
6
+ * Who is holding the pen on a room log, as a fact rather than an inference.
7
+ *
8
+ * `room append` used to infer it: if the registry showed a room answering on
9
+ * this path, the CLI refused and told the operator to pass `--force` if they
10
+ * knew better. That inference is wrong in the case that matters most — a room
11
+ * served by bare `roomyx serve` answers and has no dispatcher, so there is no
12
+ * writer to race, and the bundled skill had to instruct its primary consumer to
13
+ * write through the guard's own escape hatch to get any work done.
14
+ *
15
+ * A lease fixes the inference. It is held by a server that has a dispatcher
16
+ * attached — same process, same lifetime — and by nothing else. A one-shot
17
+ * `roomyx room append` never holds one: it would be expired by the time anyone
18
+ * could read it, which is the state a lease exists to distinguish.
19
+ *
20
+ * Two rules copied deliberately from `lockfile.ts` rather than re-derived:
21
+ *
22
+ * - **Release checks the token.** A holder that finishes late must not unlink
23
+ * the file its successor legitimately took.
24
+ * - **Staleness is a ceiling, not a guess.** A holder that dies without saying
25
+ * so leaves a lease that expires by itself, so recovery never requires an
26
+ * operator to delete a file by hand.
27
+ *
28
+ * The lease lives beside the registry, not beside the log: a room log travels
29
+ * with the repository, while who holds the pen is a property of this machine's
30
+ * running processes. It is keyed by the **log**, though — one file per room —
31
+ * because a project runs several rooms at once (the README's whole point in
32
+ * giving `serve` an ephemeral port default), and a single lease file shared by
33
+ * all of them meant the first room's writer refused writes to the second's log.
34
+ */
35
+
36
+ /** How often a holder re-states that it is still there. */
37
+ export const LEASE_HEARTBEAT_MS = 5_000;
38
+
39
+ /**
40
+ * How long a lease is believed without a heartbeat.
41
+ *
42
+ * Six missed heartbeats. Longer than any plausible scheduling stall, and short
43
+ * enough that a crashed dispatcher does not block the operator for minutes.
44
+ */
45
+ export const LEASE_STALE_MS = 30_000;
46
+
47
+ export interface WriterLease {
48
+ token: string;
49
+ pid: number;
50
+ /** Epoch ms of the last heartbeat, so staleness needs no file mtime. */
51
+ at: number;
52
+ /**
53
+ * Set when a writer took this lease over from one that had stopped — the pid
54
+ * that did it, and when. It is why the token is replaced on take-over: the
55
+ * previous holder's heartbeat has to fail, or a writer that was merely paused
56
+ * revives the lease it lost and two processes write the same log.
57
+ */
58
+ takenOverFrom?: { pid: number; at: number };
59
+ }
60
+
61
+ export type LeaseState =
62
+ | { held: true; lease: WriterLease }
63
+ /**
64
+ * `stale` carries the lease it found, because "a writer stopped here, pid N,
65
+ * at T" is the fact a take-over needs to record — and reading the file only to
66
+ * discard who was in it leaves the log unable to say what it displaced.
67
+ */
68
+ | { held: false; reason: "absent" }
69
+ | { held: false; reason: "stale"; last: WriterLease };
70
+
71
+ /**
72
+ * One lease file per room, under a directory beside the registry.
73
+ *
74
+ * The file name is a hash of the log's absolute path: the log path is what
75
+ * identifies the room, and a name derived from it keeps two rooms apart without
76
+ * putting a path (which contains separators) into a file name.
77
+ */
78
+ export function writerLeasePathFor(registryPath: string, logPath: string): string {
79
+ const name = createHash("sha256").update(logPath).digest("hex").slice(0, 16);
80
+ return join(dirname(registryPath), "writers", `${name}.json`);
81
+ }
82
+
83
+ function parseLease(raw: string): WriterLease | undefined {
84
+ try {
85
+ const parsed = JSON.parse(raw) as Partial<WriterLease>;
86
+ if (typeof parsed.token !== "string" || parsed.token === "") return undefined;
87
+ if (typeof parsed.pid !== "number" || typeof parsed.at !== "number") return undefined;
88
+ return { token: parsed.token, pid: parsed.pid, at: parsed.at };
89
+ } catch {
90
+ return undefined;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * A corrupt or half-written lease reads as **no lease**, never as a held one.
96
+ *
97
+ * Failing closed would mean a file nobody can repair refusing every write to a
98
+ * room forever, and the operator's only recourse would be deleting the file by
99
+ * hand — which is exactly the recovery path `--take-over` exists to make
100
+ * unnecessary. `absent` is also the truthful answer: nothing usable is held.
101
+ */
102
+ export function readWriterLease(path: string, options: { now?: number } = {}): LeaseState {
103
+ if (!existsSync(path)) return { held: false, reason: "absent" };
104
+ let raw: string;
105
+ try {
106
+ raw = readFileSync(path, "utf8");
107
+ } catch {
108
+ return { held: false, reason: "absent" };
109
+ }
110
+ const lease = parseLease(raw);
111
+ if (lease === undefined) return { held: false, reason: "absent" };
112
+ const now = options.now ?? Date.now();
113
+ if (now - lease.at > LEASE_STALE_MS) return { held: false, reason: "stale", last: lease };
114
+ return { held: true, lease };
115
+ }
116
+
117
+ /** Takes the lease unconditionally, replacing whatever was there. */
118
+ export function acquireWriterLease(
119
+ path: string,
120
+ options: { pid: number; now?: number; takeOverFrom?: { pid: number; at: number } },
121
+ ): WriterLease {
122
+ mkdirSync(dirname(path), { recursive: true });
123
+ const lease: WriterLease = {
124
+ token: randomUUID(),
125
+ pid: options.pid,
126
+ at: options.now ?? Date.now(),
127
+ };
128
+ if (options.takeOverFrom !== undefined) lease.takenOverFrom = options.takeOverFrom;
129
+ writeFileSync(path, JSON.stringify(lease));
130
+ return lease;
131
+ }
132
+
133
+ /** Returns false when the lease is gone, expired, or now someone else's. */
134
+ export function refreshWriterLease(path: string, token: string, options: { now?: number } = {}): boolean {
135
+ const state = readWriterLease(path, options);
136
+ if (!state.held || state.lease.token !== token) return false;
137
+ writeFileSync(path, JSON.stringify({ ...state.lease, at: options.now ?? Date.now() }));
138
+ return true;
139
+ }
140
+
141
+ /** Unlinks only the lease this token wrote — see the note above. */
142
+ export function releaseWriterLease(path: string, token: string): void {
143
+ try {
144
+ const lease = parseLease(readFileSync(path, "utf8"));
145
+ if (lease?.token === token) unlinkSync(path);
146
+ } catch {
147
+ // Already gone, or unreadable: nothing more to do.
148
+ }
149
+ }