@mrciphersmith/roomyx 0.5.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.
@@ -0,0 +1,124 @@
1
+ import type { MessageEnvelope } from "../log/types";
2
+
3
+ /**
4
+ * What the transcript pane is showing, as data.
5
+ *
6
+ * The view used to append renderables straight into the scroll box and keep no
7
+ * record of what it had drawn, which made a filter or a search impossible to
8
+ * write: there was nothing to filter or search. Splitting the model out also
9
+ * means the interesting behaviour — which messages are visible, which ones a
10
+ * query matches, where "next match" goes — is testable without a renderer, a
11
+ * terminal or a server.
12
+ *
13
+ * A system line (a connection change) is part of the transcript too, because a
14
+ * reader scrolling back needs to see where the room went quiet. It carries no
15
+ * speaker, so a participant filter hides it: while you are reading one
16
+ * person's turns, the room's plumbing is not what you asked for.
17
+ */
18
+ export interface SystemEntry {
19
+ kind: "system";
20
+ text: string;
21
+ }
22
+
23
+ export interface MessageEntry {
24
+ kind: "message";
25
+ message: MessageEnvelope;
26
+ /** Resolved display name, so the model can be searched by what is on screen. */
27
+ fromName: string;
28
+ }
29
+
30
+ export type Entry = MessageEntry | SystemEntry;
31
+
32
+ export class Transcript {
33
+ private entries: Entry[] = [];
34
+ private filterId: string | null = null;
35
+ private query = "";
36
+
37
+ append(entry: Entry): void {
38
+ this.entries.push(entry);
39
+ }
40
+
41
+ /** Null clears the filter. */
42
+ setFilter(participantId: string | null): void {
43
+ this.filterId = participantId;
44
+ }
45
+
46
+ filter(): string | null {
47
+ return this.filterId;
48
+ }
49
+
50
+ /** Empty clears the search. */
51
+ setQuery(query: string): void {
52
+ this.query = query;
53
+ }
54
+
55
+ currentQuery(): string {
56
+ return this.query;
57
+ }
58
+
59
+ visible(): Entry[] {
60
+ if (this.filterId === null) return this.entries;
61
+ return this.entries.filter((entry) => entry.kind === "message" && entry.message.from === this.filterId);
62
+ }
63
+
64
+ /**
65
+ * Indices into `visible()` that contain the query, matched case-insensitively
66
+ * against what a reader can actually see — the speaker's display name, the
67
+ * kind tag and the body — rather than against the raw envelope. Searching for
68
+ * "Ann" should find messages headed `Ann`, not messages from the id `a`.
69
+ */
70
+ matches(): number[] {
71
+ if (this.query === "") return [];
72
+ const needle = this.query.toLowerCase();
73
+ return this.visible()
74
+ .map((entry, index) => {
75
+ const haystack =
76
+ entry.kind === "system"
77
+ ? entry.text
78
+ : `${entry.fromName} ${entry.message.kind ?? ""} ${entry.message.body}`;
79
+ return haystack.toLowerCase().includes(needle) ? index : -1;
80
+ })
81
+ .filter((index) => index >= 0);
82
+ }
83
+
84
+ /**
85
+ * The match at or after `from`, wrapping to the first. Returns null when
86
+ * nothing matches, so the caller can say so rather than silently doing
87
+ * nothing — a search that finds nothing and looks identical to a search that
88
+ * found something is the failure this whole pane keeps repeating.
89
+ */
90
+ nextMatch(from: number): number | null {
91
+ const all = this.matches();
92
+ if (all.length === 0) return null;
93
+ return all.find((index) => index > from) ?? all[0] ?? null;
94
+ }
95
+
96
+ previousMatch(from: number): number | null {
97
+ const all = this.matches();
98
+ if (all.length === 0) return null;
99
+ const earlier = all.filter((index) => index < from);
100
+ return earlier[earlier.length - 1] ?? all[all.length - 1] ?? null;
101
+ }
102
+
103
+ /** True when a message at `index` in `visible()` starts a new speaker's run. */
104
+ startsRun(index: number): boolean {
105
+ const entries = this.visible();
106
+ const entry = entries[index];
107
+ if (entry === undefined || entry.kind !== "message") return false;
108
+ const previous = entries[index - 1];
109
+ return previous === undefined || previous.kind !== "message" || previous.message.from !== entry.message.from;
110
+ }
111
+
112
+ /** Plain text of everything currently visible, for writing out of the TUI. */
113
+ toText(): string {
114
+ return this.visible()
115
+ .map((entry) => {
116
+ if (entry.kind === "system") return `— ${entry.text} —`;
117
+ const tag = [entry.message.kind, entry.message.in_reply_to === undefined ? null : `re #${entry.message.in_reply_to}`]
118
+ .filter((part): part is string => Boolean(part))
119
+ .join(" ");
120
+ return `${entry.fromName}${tag ? ` ${tag}` : ""}\n ${entry.message.body}`;
121
+ })
122
+ .join("\n\n");
123
+ }
124
+ }
@@ -7,7 +7,11 @@ export interface InitOptions {
7
7
  }
8
8
 
9
9
  export interface InitResult {
10
- /** false when .roomyx/rooms/registry.json already existed and was left untouched. */
10
+ /**
11
+ * false only when the registry already lists at least one room. An existing
12
+ * but empty `.roomyx` still reports as created — the comment here used to
13
+ * claim otherwise, and `cli.ts` prints this straight to the operator.
14
+ */
11
15
  created: boolean;
12
16
  roomyxDir: string;
13
17
  }
@@ -41,7 +45,13 @@ export function init(options: InitOptions): InitResult {
41
45
  if (!existsSync(registryPath)) {
42
46
  writeFileSync(registryPath, JSON.stringify({ schemaVersion: 1, rooms: [] }, null, 2));
43
47
  }
44
- copyFileSync(options.bundledSkillPath, join(skillDir, "SKILL.md"));
48
+ // Guarded like the config and the registry beside it. This copy used to be
49
+ // unconditional — no hash check, no backup, no gate — which is the operation
50
+ // `syncSkill` refuses outright, while this function's own comment promises
51
+ // "explicit, never-clobbering". Re-running `roomyx init` silently discarded
52
+ // hand edits to the staged copy.
53
+ const stagedSkill = join(skillDir, "SKILL.md");
54
+ if (!existsSync(stagedSkill)) copyFileSync(options.bundledSkillPath, stagedSkill);
45
55
 
46
56
  return { created: !registryAlreadyHasRooms, roomyxDir };
47
57
  }
@@ -1,8 +1,12 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { z } from "zod";
4
4
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
5
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
6
+ import { withLock } from "../lockfile";
7
+
8
+ /** Re-exported: the registry's own tests reach for it, and it lives in ../lockfile now. */
9
+ export { releaseLockIfOwned } from "../lockfile";
6
10
 
7
11
  const registryEntrySchema = z.object({
8
12
  id: z.string().min(1),
@@ -19,81 +23,6 @@ const registryFileSchema = z.object({
19
23
 
20
24
  export type RoomRegistryEntry = z.infer<typeof registryEntrySchema>;
21
25
 
22
- /** A lock older than this could only mean its holder crashed — the critical
23
- * sections here are a few synchronous file ops, never anywhere close to 30s. */
24
- const STALE_LOCK_MS = 30_000;
25
-
26
- /**
27
- * Blocks (synchronously) until an exclusive lockfile can be created, runs
28
- * `fn`, then always releases the lock. Reproduced concretely by an
29
- * independent review: without this, concurrent `roomyx serve` processes
30
- * lose registrations (read-modify-write race) and can crash each other with
31
- * a JSON parse error on a torn read of a non-atomic write. `Atomics.wait` is
32
- * used for the retry backoff because registerRoom/deregisterRoom are
33
- * synchronous APIs (matching how cli.ts already calls them) — an async lock
34
- * would leak into every caller's signature for no benefit here.
35
- *
36
- * A process that crashes mid-critical-section leaves the lockfile behind
37
- * forever — a second independent review caught that this would otherwise
38
- * block the registry permanently for every future caller, not just the one
39
- * racing the crash. A lock older than STALE_LOCK_MS is reclaimed instead of
40
- * waited on.
41
- *
42
- * The lockfile's content is an owner token (pid + random), not empty: a
43
- * third review caught that reclaiming by mtime alone is not enough — if the
44
- * original holder was merely slow (not crashed) and finishes after being
45
- * reclaimed, its unconditional release would delete whichever *other*
46
- * process's lock now legitimately occupies that path. Release only unlinks
47
- * when the file still holds the token this call itself wrote.
48
- */
49
- /** Exported narrowly so the ownership check can be unit-tested directly,
50
- * without needing to choreograph real inter-process timing to hit it. */
51
- export function releaseLockIfOwned(lockPath: string, token: string): void {
52
- try {
53
- if (readFileSync(lockPath, "utf8") === token) {
54
- unlinkSync(lockPath);
55
- }
56
- } catch {
57
- // Already gone, or unreadable — nothing more to do.
58
- }
59
- }
60
-
61
- function withLock<T>(registryPath: string, fn: () => T): T {
62
- const lockPath = `${registryPath}.lock`;
63
- const token = `${process.pid}-${Math.random().toString(36).slice(2)}`;
64
- const deadline = Date.now() + 5000;
65
- for (;;) {
66
- try {
67
- writeFileSync(lockPath, token, { flag: "wx" });
68
- break;
69
- } catch (error) {
70
- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
71
- try {
72
- if (Date.now() - statSync(lockPath).mtimeMs > STALE_LOCK_MS) {
73
- try {
74
- unlinkSync(lockPath);
75
- } catch {
76
- // Another process already reclaimed it first; just retry.
77
- }
78
- continue;
79
- }
80
- } catch {
81
- // Lock vanished between the failed open and this stat; retry.
82
- continue;
83
- }
84
- if (Date.now() > deadline) {
85
- throw new Error(`Timed out waiting for the room registry lock at ${lockPath}`);
86
- }
87
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
88
- }
89
- }
90
- try {
91
- return fn();
92
- } finally {
93
- releaseLockIfOwned(lockPath, token);
94
- }
95
- }
96
-
97
26
  /**
98
27
  * True when there is provably nothing to read: no registry file. Callers that
99
28
  * only read use this to skip the lock entirely, because taking the lock means
@@ -184,7 +113,11 @@ export function listRooms(registryPath: string): RoomRegistryEntry[] {
184
113
  * answers). Dead entries are pruned from the persisted file, not just
185
114
  * omitted from the returned list.
186
115
  */
187
- 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;
188
121
  if (hasNoRegistry(registryPath)) return [];
189
122
  const rooms = withLock(registryPath, () => readRegistryUnlocked(registryPath).rooms);
190
123
  const checks = await Promise.all(
@@ -194,7 +127,12 @@ export async function listLiveRooms(registryPath: string): Promise<RoomRegistryE
194
127
  }),
195
128
  );
196
129
  const live = checks.filter((c) => c.alive).map((c) => c.room);
197
- 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) {
198
136
  // Re-take the lock for the write: another process may have registered or
199
137
  // deregistered a room while the (network) liveness checks above were in
200
138
  // flight. Re-read under the lock and only remove entries this pass
@@ -212,20 +150,63 @@ export async function listLiveRooms(registryPath: string): Promise<RoomRegistryE
212
150
  return live;
213
151
  }
214
152
 
153
+ /**
154
+ * Is the process that registered this room still running?
155
+ *
156
+ * Signal 0 performs the permission and existence checks without delivering
157
+ * anything. ESRCH means no such process; EPERM means it exists and belongs to
158
+ * someone else, which is still "alive" for our purposes.
159
+ */
160
+ function isPidAlive(pid: number): boolean {
161
+ if (!Number.isInteger(pid) || pid <= 0) return true; // no pid recorded — fall back to the probe
162
+ try {
163
+ process.kill(pid, 0);
164
+ return true;
165
+ } catch (error) {
166
+ return (error as NodeJS.ErrnoException).code !== "ESRCH";
167
+ }
168
+ }
169
+
215
170
  async function isRoomLive(room: RoomRegistryEntry, timeoutMs = 500): Promise<boolean> {
171
+ // The probe below proves that *something* MCP-speaking answers on that port,
172
+ // never that it is this room. Every `roomyx serve` defaults to 4319, so a
173
+ // room that died without deregistering was resurrected as live by the next
174
+ // room to bind the port — and then `roomyx-client --room <dead-id>` silently
175
+ // rendered a different room's transcript under the dead room's id, while
176
+ // `room append` refused a log nothing was serving.
177
+ //
178
+ // The pid has been in the registry all along and was never read. Checking it
179
+ // first also skips a 500 ms network probe per dead entry.
180
+ if (!isPidAlive(room.pid)) return false;
181
+
216
182
  const client = new Client({ name: "roomyx-registry-check", version: "0.1.0" });
183
+ const transport = new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${room.port}/mcp`));
217
184
  const timeout = new Promise<never>((_, reject) => {
218
185
  setTimeout(() => reject(new Error("liveness check timed out")), timeoutMs);
219
186
  });
220
187
  try {
221
- await Promise.race([
222
- client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${room.port}/mcp`))),
223
- timeout,
224
- ]);
225
- return true;
188
+ await Promise.race([client.connect(transport), timeout]);
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;
226
203
  } catch {
227
204
  return false;
228
205
  } finally {
206
+ // This probe runs for every registered room on every `rooms list`, every
207
+ // `room append` and every client start. Closing without terminating left
208
+ // one abandoned server-side session behind each time.
209
+ await transport.terminateSession().catch(() => undefined);
229
210
  await client.close().catch(() => undefined);
230
211
  }
231
212
  }
@@ -59,8 +59,6 @@ export function syncSkill(options: SyncOptions): SyncResult {
59
59
  const neverSyncedButPreExisting = targetExists && lastSyncedHash === undefined;
60
60
  const handEditedSinceLastSync =
61
61
  targetExists && lastSyncedHash !== undefined && hashOf(targetContent as string) !== lastSyncedHash;
62
- const targetHasIndependentChanges = neverSyncedButPreExisting || handEditedSinceLastSync;
63
-
64
62
  const warnings: string[] = [];
65
63
  if (neverSyncedButPreExisting) {
66
64
  warnings.push(
@@ -72,10 +70,19 @@ export function syncSkill(options: SyncOptions): SyncResult {
72
70
  );
73
71
  }
74
72
 
75
- if (options.dryRun) {
76
- return { wouldWrite: true, written: false, backedUpTo: null, warnings };
77
- }
78
- if (targetHasIndependentChanges && !options.yes) {
73
+ // Gated by default, and the default lives here rather than in each caller.
74
+ // It used to be computed per surface, and the two surfaces disagreed: the CLI
75
+ // did `dryRun = flags["dry-run"] === true || !yes`, while the MCP tool passed
76
+ // both through as `undefined` — so a call carrying only `target` wrote a real
77
+ // skill file over an unauthenticated loopback port, with no confirmation,
78
+ // while the CLI's own help said "Without --yes nothing is written". D-02
79
+ // exists to make landing on a real skill file a deliberate act; a default
80
+ // computed twice is a default that will differ once.
81
+ // `yes` now gates every write, not only a write over independent changes, so
82
+ // the old second guard (`targetHasIndependentChanges && !options.yes`) is
83
+ // subsumed: nothing reaches here without `yes: true`. The warnings above are
84
+ // still built, so a refusal still says which target had unrecorded content.
85
+ if (options.dryRun === true || options.yes !== true) {
79
86
  return { wouldWrite: true, written: false, backedUpTo: null, warnings };
80
87
  }
81
88
 
@@ -0,0 +1,85 @@
1
+ import { readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+
3
+ /**
4
+ * A lock older than this could only mean its holder crashed — the critical
5
+ * sections here are a few synchronous file ops, never anywhere close to 30s.
6
+ */
7
+ const STALE_LOCK_MS = 30_000;
8
+
9
+ /**
10
+ * Exported narrowly so the ownership check can be unit-tested directly, without
11
+ * needing to choreograph real inter-process timing to hit it.
12
+ */
13
+ export function releaseLockIfOwned(lockPath: string, token: string): void {
14
+ try {
15
+ if (readFileSync(lockPath, "utf8") === token) {
16
+ unlinkSync(lockPath);
17
+ }
18
+ } catch {
19
+ // Already gone, or unreadable — nothing more to do.
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Blocks (synchronously) until an exclusive lockfile can be created, runs `fn`,
25
+ * then always releases the lock.
26
+ *
27
+ * Three rounds of independent review are baked into this, which is why it was
28
+ * worth extracting rather than writing a second one. Without a lock at all,
29
+ * concurrent writers lose updates to a read-modify-write race and can crash
30
+ * each other with a JSON parse error on a torn read. `Atomics.wait` is used for
31
+ * the retry backoff because the callers are synchronous APIs; an async lock
32
+ * would leak into every caller's signature for no benefit.
33
+ *
34
+ * A process that crashes mid-critical-section would otherwise leave the
35
+ * lockfile behind forever, blocking every future caller rather than only the
36
+ * one racing the crash — so a lock older than `STALE_LOCK_MS` is reclaimed
37
+ * instead of waited on.
38
+ *
39
+ * The lockfile's content is an owner token (pid + random), not empty: reclaiming
40
+ * by mtime alone is not enough, because a holder that was merely slow rather
41
+ * than crashed would, on finishing, unconditionally delete whichever *other*
42
+ * process's lock now legitimately occupies that path. Release only unlinks when
43
+ * the file still holds the token this call itself wrote.
44
+ *
45
+ * It guarded the registry for three rounds while the room log — the actual
46
+ * data — had nothing: three concurrent `roomyx room append` calls all allocated
47
+ * `seq: 1` and all three landed on disk. `seq` is the transcript cursor, so a
48
+ * client polling between two colliding writes advances past both and never
49
+ * receives the second message, which is on disk and invisible forever.
50
+ */
51
+ export function withLock<T>(targetPath: string, fn: () => T): T {
52
+ const lockPath = `${targetPath}.lock`;
53
+ const token = `${process.pid}-${Math.random().toString(36).slice(2)}`;
54
+ const deadline = Date.now() + 5000;
55
+ for (;;) {
56
+ try {
57
+ writeFileSync(lockPath, token, { flag: "wx" });
58
+ break;
59
+ } catch (error) {
60
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
61
+ try {
62
+ if (Date.now() - statSync(lockPath).mtimeMs > STALE_LOCK_MS) {
63
+ try {
64
+ unlinkSync(lockPath);
65
+ } catch {
66
+ // Another process already reclaimed it first; just retry.
67
+ }
68
+ continue;
69
+ }
70
+ } catch {
71
+ // Lock vanished between the failed open and this stat; retry.
72
+ continue;
73
+ }
74
+ if (Date.now() > deadline) {
75
+ throw new Error(`Timed out waiting for the lock at ${lockPath}`);
76
+ }
77
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
78
+ }
79
+ }
80
+ try {
81
+ return fn();
82
+ } finally {
83
+ releaseLockIfOwned(lockPath, token);
84
+ }
85
+ }
@@ -0,0 +1,59 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * The room log's on-disk contract, owned here and depended on by **both**
5
+ * directions.
6
+ *
7
+ * It used to live in `store.ts` and be applied only on read, while `write.ts`
8
+ * had nothing but TypeScript types — which are erased at the CLI boundary,
9
+ * where `--kind` was cast with `as never`. So the writer admitted values the
10
+ * reader refused, and the log is append-only with no repair command: one
11
+ * `roomyx room append --kind bogus-kind` exited 0, wrote the line, and made
12
+ * every subsequent read of that room throw forever. The server kept binding and
13
+ * kept registering, so `rooms list` still called the room live while the
14
+ * attached client sat on "disconnected" against a healthy server.
15
+ *
16
+ * A writer whose output its own reader rejects is the thing this module exists
17
+ * to make impossible. Both sides import from here; neither redeclares.
18
+ */
19
+
20
+ export const MESSAGE_KINDS = [
21
+ "pitch",
22
+ "question",
23
+ "challenge",
24
+ "answer",
25
+ "vote",
26
+ "status",
27
+ "research",
28
+ ] as const;
29
+
30
+ export const rosterEntrySchema = z.object({ id: z.string(), name: z.string() });
31
+
32
+ export const goalContractSchema = z.object({
33
+ version: z.number().int().min(1),
34
+ updated_in_round: z.number().int().min(0).optional(),
35
+ updated_by: z.literal("owner").optional(),
36
+ goal_statement: z.string(),
37
+ criteria: z.string(),
38
+ threshold: z.object({
39
+ fail_below: z.number(),
40
+ pass_at_or_above: z.number(),
41
+ }),
42
+ });
43
+
44
+ export const messageKindSchema = z.enum(MESSAGE_KINDS);
45
+
46
+ export const stateLineSchema = z.object({
47
+ type: z.literal("state"),
48
+ goal_contract: goalContractSchema,
49
+ roster: z.array(rosterEntrySchema),
50
+ });
51
+
52
+ export const messageLineSchema = z.object({
53
+ type: z.literal("message"),
54
+ seq: z.number().int().min(1),
55
+ from: z.string().min(1),
56
+ in_reply_to: z.number().int().min(1).optional(),
57
+ kind: messageKindSchema.optional(),
58
+ body: z.string(),
59
+ });
package/src/log/store.ts CHANGED
@@ -1,46 +1,7 @@
1
1
  import { readFileSync } from "node:fs";
2
- import { z } from "zod";
2
+ import { messageLineSchema, stateLineSchema } from "./schema";
3
3
  import type { AgentDetail, MessageEnvelope, RoomState, RosterEntry } from "./types";
4
4
 
5
- const rosterEntrySchema = z.object({ id: z.string(), name: z.string() });
6
-
7
- const goalContractSchema = z.object({
8
- version: z.number().int().min(1),
9
- updated_in_round: z.number().int().min(0).optional(),
10
- updated_by: z.literal("owner").optional(),
11
- goal_statement: z.string(),
12
- criteria: z.string(),
13
- threshold: z.object({
14
- fail_below: z.number(),
15
- pass_at_or_above: z.number(),
16
- }),
17
- });
18
-
19
- const messageKindSchema = z.enum([
20
- "pitch",
21
- "question",
22
- "challenge",
23
- "answer",
24
- "vote",
25
- "status",
26
- "research",
27
- ]);
28
-
29
- const stateLineSchema = z.object({
30
- type: z.literal("state"),
31
- goal_contract: goalContractSchema,
32
- roster: z.array(rosterEntrySchema),
33
- });
34
-
35
- const messageLineSchema = z.object({
36
- type: z.literal("message"),
37
- seq: z.number().int().min(1),
38
- from: z.string().min(1),
39
- in_reply_to: z.number().int().min(1).optional(),
40
- kind: messageKindSchema.optional(),
41
- body: z.string(),
42
- });
43
-
44
5
  /**
45
6
  * Reads the room log (see roomyx/README.md for the on-disk format) without
46
7
  * ever writing to it. The first line is the state header; every following
@@ -65,6 +26,8 @@ export function loadRoomLog(path: string): { state: RoomState; messages: Message
65
26
  const state: RoomState = {
66
27
  goal_contract: headerResult.data.goal_contract,
67
28
  roster: headerResult.data.roster,
29
+ // The reader knows which file it read; the state header does not carry it.
30
+ log_path: path,
68
31
  };
69
32
 
70
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 =
package/src/log/write.ts CHANGED
@@ -1,8 +1,30 @@
1
- import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import { mkdirSync } from "node:fs";
1
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
2
  import { dirname } from "node:path";
3
+ import type { z } from "zod";
4
+ import { withLock } from "../lockfile";
5
+ import { MESSAGE_KINDS, messageLineSchema } from "./schema";
4
6
  import type { GoalContract, MessageEnvelope, RosterEntry } from "./types";
5
7
 
8
+ /**
9
+ * Thrown when a message would not survive its own reader. Separate from a
10
+ * generic Error so the CLI can report it as a refusal rather than a crash.
11
+ */
12
+ export class LogWriteError extends Error {}
13
+
14
+ /** The legal kinds, for an error message that says what to write instead. */
15
+ export const LEGAL_KINDS = MESSAGE_KINDS.join(", ");
16
+
17
+ function describeInvalid(error: z.ZodError): string {
18
+ return error.issues
19
+ .map((issue) => {
20
+ const field = issue.path.join(".") || "message";
21
+ if (field === "kind") return `kind must be one of: ${LEGAL_KINDS}`;
22
+ if (field === "in_reply_to") return "in-reply-to must be a whole number of at least 1";
23
+ return `${field}: ${issue.message}`;
24
+ })
25
+ .join("; ");
26
+ }
27
+
6
28
  /**
7
29
  * The write side of a room log, which `store.ts` reads.
8
30
  *
@@ -56,6 +78,20 @@ export function appendMessage(path: string, options: AppendMessageOptions): Mess
56
78
  if (!existsSync(path)) {
57
79
  throw new Error(`${path} does not exist. Create it with \`roomyx room new\` first.`);
58
80
  }
81
+ // Allocating `seq` and writing the line is one critical section, not two.
82
+ // `nextSeq` reads the whole file and returns max+1, and nothing stood between
83
+ // that and the append: three concurrent `roomyx room append` calls all
84
+ // allocated `seq: 1` and all three landed on disk. `seq` is the transcript
85
+ // cursor, so a client polling between two colliding writes advances past both
86
+ // and never receives the second message — on disk, invisible in the TUI,
87
+ // permanently.
88
+ //
89
+ // The registry has had this discipline for three rounds of review. The data
90
+ // did not.
91
+ return withLock(path, () => writeMessage(path, options));
92
+ }
93
+
94
+ function writeMessage(path: string, options: AppendMessageOptions): MessageEnvelope & { type: "message" } {
59
95
  const message: MessageEnvelope & { type: "message" } = {
60
96
  type: "message",
61
97
  seq: nextSeq(path),
@@ -64,6 +100,17 @@ export function appendMessage(path: string, options: AppendMessageOptions): Mess
64
100
  ...(options.kind ? { kind: options.kind } : {}),
65
101
  ...(options.inReplyTo !== undefined ? { in_reply_to: options.inReplyTo } : {}),
66
102
  };
103
+
104
+ // Validated against the reader's own schema, before the write rather than
105
+ // after it. The log is append-only and roomyx ships no repair command, so a
106
+ // line the reader refuses is not a failed write — it is a room nobody can
107
+ // open again. Types alone did not hold this: they are erased at the CLI
108
+ // 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
+
67
114
  appendFileSync(path, JSON.stringify(message) + "\n");
68
115
  return message;
69
116
  }