@mrciphersmith/roomyx 0.12.1 → 0.12.3

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +140 -12
  3. package/package.json +11 -10
  4. package/src/bin/launch.mjs +1 -1
  5. package/src/bundled-personas/groups.md +3 -3
  6. package/src/bundled-skills/startup-room/reference/roomyx.md +5 -0
  7. package/src/cli/client.ts +12 -0
  8. package/src/cli/experiment.ts +67 -0
  9. package/src/cli/init.ts +149 -0
  10. package/src/cli/mcp.ts +54 -0
  11. package/src/cli/personas.ts +40 -0
  12. package/src/cli/room-append.ts +357 -0
  13. package/src/cli/room.ts +91 -0
  14. package/src/cli/rooms.ts +65 -0
  15. package/src/cli/serve.ts +84 -0
  16. package/src/cli/shared.ts +71 -0
  17. package/src/cli/skills.ts +58 -0
  18. package/src/cli/specs.ts +1 -0
  19. package/src/cli.ts +29 -884
  20. package/src/client/index.ts +16 -3
  21. package/src/client/mcp-client.ts +106 -7
  22. package/src/client/shutdown.ts +29 -6
  23. package/src/experiment/manifest.ts +151 -0
  24. package/src/installer/init-apply.ts +38 -7
  25. package/src/installer/init.ts +5 -2
  26. package/src/installer/registry.ts +38 -6
  27. package/src/installer/resolve-connection.ts +54 -8
  28. package/src/installer/room-tool.ts +6 -3
  29. package/src/installer/skill-sync.ts +86 -3
  30. package/src/installer/skill-targets.ts +7 -3
  31. package/src/lockfile.ts +13 -2
  32. package/src/log/schema.ts +108 -38
  33. package/src/log/store.ts +1 -0
  34. package/src/log/types.ts +8 -1
  35. package/src/log/write.ts +115 -6
  36. package/src/mcp-management/server.ts +30 -4
  37. package/src/room-token.ts +129 -0
  38. package/src/server/http-transport.ts +43 -0
  39. package/src/server/index.ts +76 -3
  40. package/src/server/log-watcher.ts +80 -0
  41. package/src/server/owner-queue.ts +7 -1
  42. package/src/server/serve.ts +112 -30
  43. package/src/server/shutdown.ts +33 -7
  44. package/src/writer-lease.ts +161 -14
@@ -1,13 +1,19 @@
1
- import { listLiveRooms, type RoomRegistryEntry } from "./registry";
1
+ import { listLiveRooms, listRooms, type RoomRegistryEntry } from "./registry";
2
2
 
3
3
  export interface ResolveConnectionOptions {
4
4
  connect?: string;
5
5
  room?: string;
6
6
  registryPath: string;
7
+ /**
8
+ * An explicitly supplied per-room token, for the one case the registry cannot
9
+ * answer: `--connect` naming a room on another machine, or one this machine
10
+ * never registered. It wins over anything found in the registry.
11
+ */
12
+ token?: string;
7
13
  }
8
14
 
9
15
  export type ResolveConnectionResult =
10
- | { ok: true; url: string }
16
+ | { ok: true; url: string; token?: string }
11
17
  | { ok: false; reason: "no-rooms" | "multiple-rooms" | "room-not-found"; candidates?: RoomRegistryEntry[] };
12
18
 
13
19
  function urlFor(room: RoomRegistryEntry): string {
@@ -15,25 +21,65 @@ function urlFor(room: RoomRegistryEntry): string {
15
21
  }
16
22
 
17
23
  /**
18
- * Decides which roomyx server `roomyx-client` should connect to.
19
- * `--connect` always wins outright (explicit URL, registry not consulted).
20
- * `--room <id>` looks up that specific room among the LIVE ones (a
24
+ * The token for an explicitly-given URL, found by its port.
25
+ *
26
+ * `--connect` is documented as "the registry is not consulted", and the URL is
27
+ * still not looked up — it is used exactly as given. What is looked up is the
28
+ * *credential* for a port the caller has already named, which is the ordinary
29
+ * case: someone who read a port out of `rooms list` and pasted it. Without this,
30
+ * `--connect` would be the one client path the token silently broke, and its
31
+ * symptom would be a client retrying against a room that is running.
32
+ *
33
+ * `listRooms`, not `listLiveRooms`: no liveness probe. A probe here would be a
34
+ * round trip the flag exists to skip, and the answer is wanted whether or not the
35
+ * room has answered yet.
36
+ */
37
+ function tokenForUrl(connect: string, registryPath: string): string | undefined {
38
+ let port: string;
39
+ try {
40
+ port = new URL(connect).port;
41
+ } catch {
42
+ // Not a URL we can read. The transport will say so in its own words; there
43
+ // is nothing to look up.
44
+ return undefined;
45
+ }
46
+ if (port === "") return undefined;
47
+ return listRooms(registryPath).find((room) => String(room.port) === port)?.token;
48
+ }
49
+
50
+ /**
51
+ * Decides which roomyx server `roomyx-client` should connect to, and with which
52
+ * token.
53
+ *
54
+ * `--connect` always wins outright for the *address* (explicit URL, never
55
+ * looked up). `--room <id>` looks up that specific room among the LIVE ones (a
21
56
  * registered-but-dead id is treated the same as unknown, not a stale
22
57
  * false-positive). No args: auto-attach only when exactly one room is live.
58
+ *
59
+ * The token travels with the URL rather than being resolved separately by the
60
+ * caller, because "which room" and "the credential for that room" are one
61
+ * answer: a caller that could get one without the other is a caller that can
62
+ * connect to a room it cannot talk to.
23
63
  */
24
64
  export async function resolveConnectionUrl(options: ResolveConnectionOptions): Promise<ResolveConnectionResult> {
25
65
  if (options.connect) {
26
- return { ok: true, url: options.connect };
66
+ const token = options.token ?? tokenForUrl(options.connect, options.registryPath);
67
+ return { ok: true, url: options.connect, ...(token === undefined ? {} : { token }) };
27
68
  }
28
69
 
29
70
  const live = await listLiveRooms(options.registryPath);
30
71
 
72
+ const found = (room: RoomRegistryEntry): ResolveConnectionResult => {
73
+ const token = options.token ?? room.token;
74
+ return { ok: true, url: urlFor(room), ...(token === undefined ? {} : { token }) };
75
+ };
76
+
31
77
  if (options.room) {
32
78
  const match = live.find((r) => r.id === options.room);
33
- return match ? { ok: true, url: urlFor(match) } : { ok: false, reason: "room-not-found" };
79
+ return match ? found(match) : { ok: false, reason: "room-not-found" };
34
80
  }
35
81
 
36
82
  if (live.length === 0) return { ok: false, reason: "no-rooms" };
37
83
  if (live.length > 1) return { ok: false, reason: "multiple-rooms", candidates: live };
38
- return { ok: true, url: urlFor(live[0] as RoomRegistryEntry) };
84
+ return found(live[0] as RoomRegistryEntry);
39
85
  }
@@ -1,5 +1,5 @@
1
1
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
2
+ import { roomTransport } from "../room-token";
3
3
 
4
4
  /**
5
5
  * Calls one tool on a room's own MCP server and returns its parsed result.
@@ -18,7 +18,10 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/
18
18
  * a session behind on the server.
19
19
  */
20
20
  export async function callRoomTool(
21
- room: { port: number; host?: string },
21
+ // Shaped to accept a `RoomRegistryEntry` as-is, which is what every caller
22
+ // passes: `servingRoomFor` hands the whole entry over, so the token arrives
23
+ // with the port rather than having to be threaded separately and forgotten.
24
+ room: { port: number; host?: string; token?: string },
22
25
  name: string,
23
26
  args: Record<string, unknown> = {},
24
27
  timeoutMs = 10_000,
@@ -28,7 +31,7 @@ export async function callRoomTool(
28
31
  // push, and the finding is noise every time.
29
32
  const host = room.host ?? [127, 0, 0, 1].join(".");
30
33
  const client = new Client({ name: "roomyx-cli", version: "0.1.0" });
31
- const transport = new StreamableHTTPClientTransport(new URL(`http://${host}:${room.port}/mcp`));
34
+ const transport = roomTransport(`http://${host}:${room.port}/mcp`, room.token);
32
35
  const timeout = new Promise<never>((_, reject) => {
33
36
  setTimeout(() => reject(new Error(`${name} timed out after ${timeoutMs}ms`)), timeoutMs);
34
37
  });
@@ -1,7 +1,54 @@
1
1
  import { createHash } from "node:crypto";
2
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
2
+ import {
3
+ closeSync,
4
+ constants as fsConstants,
5
+ copyFileSync,
6
+ existsSync,
7
+ lstatSync,
8
+ mkdirSync,
9
+ openSync,
10
+ readFileSync,
11
+ readdirSync,
12
+ statSync,
13
+ writeFileSync,
14
+ writeSync,
15
+ } from "node:fs";
3
16
  import { dirname, join, relative } from "node:path";
4
17
 
18
+ /** `lstatSync`, but a missing path (or a broken symlink — lstat still succeeds on those) is `null`, not a throw. */
19
+ function lstatIfPresent(path: string): ReturnType<typeof lstatSync> | null {
20
+ try {
21
+ return lstatSync(path);
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+
27
+ /**
28
+ * A refusal shaped like `syncSkill`'s other refusals (never-synced-but-pre-existing,
29
+ * hand-edited-since-last-sync): a returned result, not a thrown error, and gated
30
+ * by nothing — `yes: true` does not open this one (D-11 is about the *content*
31
+ * gate; a symlink on a write path is a different failure and stays refused).
32
+ */
33
+ function symlinkRefusal(path: string, verb: "back up" | "write"): SyncResult {
34
+ return {
35
+ wouldWrite: true,
36
+ written: false,
37
+ backedUpTo: null,
38
+ warnings: [`${path} is a symlink — refusing to ${verb} through it (AC9).`],
39
+ upToDate: false,
40
+ };
41
+ }
42
+
43
+ function isSymlinkRaceError(error: unknown): boolean {
44
+ return (
45
+ typeof error === "object" &&
46
+ error !== null &&
47
+ "code" in error &&
48
+ (error as NodeJS.ErrnoException).code === "ELOOP"
49
+ );
50
+ }
51
+
5
52
  export interface SyncOptions {
6
53
  bundledSkillPath: string;
7
54
  targetPath: string;
@@ -55,6 +102,15 @@ export function syncSkill(options: SyncOptions): SyncResult {
55
102
  const config = readConfig(options.configPath);
56
103
  const lastSyncedHash = config.lastSyncedHashes?.[options.targetPath];
57
104
 
105
+ // AC9: a symlink planted at the target refuses outright, before anything reads
106
+ // or writes through it. Checked via `lstat`, not `existsSync` — `existsSync`
107
+ // follows the link (so a *broken* symlink at the target reads as "doesn't
108
+ // exist" and would otherwise sail past this check straight into `mkdirSync` +
109
+ // `writeFileSync`, which follows it just the same as a live one).
110
+ if (lstatIfPresent(options.targetPath)?.isSymbolicLink()) {
111
+ return symlinkRefusal(options.targetPath, "write");
112
+ }
113
+
58
114
  const targetExists = existsSync(options.targetPath);
59
115
  const targetContent = targetExists ? readFileSync(options.targetPath, "utf8") : null;
60
116
 
@@ -124,7 +180,14 @@ export function syncSkill(options: SyncOptions): SyncResult {
124
180
  // differed — a no-op sync does not touch it.
125
181
  let backedUpTo: string | null = null;
126
182
  if (targetExists) {
127
- backedUpTo = `${options.targetPath}.bak`;
183
+ const candidateBackupPath = `${options.targetPath}.bak`;
184
+ // The backup destination is as much a write path as the target: a symlink
185
+ // planted there makes `copyFileSync` overwrite whatever it points at
186
+ // instead of ever touching an actual backup file (AC9).
187
+ if (lstatIfPresent(candidateBackupPath)?.isSymbolicLink()) {
188
+ return symlinkRefusal(candidateBackupPath, "back up");
189
+ }
190
+ backedUpTo = candidateBackupPath;
128
191
  copyFileSync(options.targetPath, backedUpTo);
129
192
  }
130
193
 
@@ -133,7 +196,27 @@ export function syncSkill(options: SyncOptions): SyncResult {
133
196
  // registry had: the write is ready for a missing file but not a missing
134
197
  // directory.
135
198
  mkdirSync(dirname(options.targetPath), { recursive: true });
136
- writeFileSync(options.targetPath, bundledContent);
199
+ // `O_NOFOLLOW` closes the gap between the `lstat` check above and this write:
200
+ // if a symlink is planted at the target in that window, `open` fails with
201
+ // `ELOOP` instead of writing through it. `writeFileSync`'s `flag` option is
202
+ // typed as a string, so the numeric flag combination goes through
203
+ // `openSync`/`writeSync`/`closeSync` instead.
204
+ try {
205
+ const fd = openSync(
206
+ options.targetPath,
207
+ fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC | fsConstants.O_NOFOLLOW,
208
+ );
209
+ try {
210
+ writeSync(fd, bundledContent, null, "utf8");
211
+ } finally {
212
+ closeSync(fd);
213
+ }
214
+ } catch (error) {
215
+ if (isSymlinkRaceError(error)) {
216
+ return symlinkRefusal(options.targetPath, "write");
217
+ }
218
+ throw error;
219
+ }
137
220
  writeConfig(options.configPath, {
138
221
  ...config,
139
222
  lastSyncedHashes: { ...config.lastSyncedHashes, [options.targetPath]: hashOf(bundledContent) },
@@ -121,11 +121,15 @@ export function pathForNamedTarget(target: string, cwd: string = process.cwd()):
121
121
  * does without the caller asking, so it ships in the minor position (D-13),
122
122
  * not quietly in a patch.
123
123
  */
124
- export function resolveTargets(target: string, cwd: string = process.cwd()): { name: string; path: string }[] {
124
+ export function resolveTargets(
125
+ target: string,
126
+ cwd: string = process.cwd(),
127
+ home?: string,
128
+ ): { name: string; path: string }[] {
125
129
  if (target === "all") {
126
- return SKILL_RUNTIMES.map((runtime) => ({ name: runtime.name, path: runtime.path(cwd) }));
130
+ return SKILL_RUNTIMES.map((runtime) => ({ name: runtime.name, path: runtime.path(cwd, home) }));
127
131
  }
128
132
  const runtime = runtimeByName(target);
129
- if (runtime) return [{ name: runtime.name, path: runtime.path(cwd) }];
133
+ if (runtime) return [{ name: runtime.name, path: runtime.path(cwd, home) }];
130
134
  return [{ name: target, path: target }];
131
135
  }
package/src/lockfile.ts CHANGED
@@ -51,7 +51,14 @@ export function releaseLockIfOwned(lockPath: string, token: string): void {
51
51
  export function withLock<T>(targetPath: string, fn: () => T): T {
52
52
  const lockPath = `${targetPath}.lock`;
53
53
  const token = `${process.pid}-${Math.random().toString(36).slice(2)}`;
54
- const deadline = Date.now() + 5000;
54
+ // Computed once, from the age of whichever lock is first observed — not
55
+ // re-derived on every iteration. A waiter must survive long enough to reach
56
+ // the stale reclaim it is entitled to, which can take longer than the 5s
57
+ // default when the lock is young. Re-deriving from a fresh stat each loop
58
+ // would let a deadline that keeps extending as new holders arrive: if the
59
+ // lock changed hands mid-wait, the new holder's younger age would push the
60
+ // deadline out again, and again, which is a hang, not a fix.
61
+ let deadline: number | undefined;
55
62
  for (;;) {
56
63
  try {
57
64
  writeFileSync(lockPath, token, { flag: "wx" });
@@ -59,7 +66,11 @@ export function withLock<T>(targetPath: string, fn: () => T): T {
59
66
  } catch (error) {
60
67
  if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
61
68
  try {
62
- if (Date.now() - statSync(lockPath).mtimeMs > STALE_LOCK_MS) {
69
+ const lockAge = Date.now() - statSync(lockPath).mtimeMs;
70
+ if (deadline === undefined) {
71
+ deadline = Date.now() + Math.max(5000, STALE_LOCK_MS - lockAge);
72
+ }
73
+ if (lockAge > STALE_LOCK_MS) {
63
74
  try {
64
75
  unlinkSync(lockPath);
65
76
  } catch {
package/src/log/schema.ts CHANGED
@@ -54,10 +54,26 @@ export const goalContractSchema = z.object({
54
54
 
55
55
  export const messageKindSchema = z.enum(MESSAGE_KINDS);
56
56
 
57
+ /**
58
+ * D-22: which experiment cell this room is, recorded where it cannot be
59
+ * rewritten. Optional, so a header written by an earlier version still validates.
60
+ */
61
+ export const experimentSchema = z.object({
62
+ name: z.string().min(1),
63
+ cell: z.number().int().min(0),
64
+ cells: z.number().int().min(1),
65
+ manifest_sha256: z.string().length(64),
66
+ variables: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])),
67
+ model: z.string().optional(),
68
+ seed: z.number().int().optional(),
69
+ repeat: z.number().int().min(0).optional(),
70
+ });
71
+
57
72
  export const stateLineSchema = z.object({
58
73
  type: z.literal("state"),
59
74
  goal_contract: goalContractSchema,
60
75
  roster: z.array(rosterEntrySchema),
76
+ experiment: experimentSchema.optional(),
61
77
  });
62
78
 
63
79
  /**
@@ -74,6 +90,68 @@ export const messageChangeSchema = z.discriminatedUnion("type", [
74
90
 
75
91
  export type MessageChange = z.infer<typeof messageChangeSchema>;
76
92
 
93
+ /**
94
+ * The largest `seq` this project will ever write.
95
+ *
96
+ * `Number.MAX_SAFE_INTEGER`: the point past which an integer no longer
97
+ * survives a JSON round-trip, which is the one property a `seq` cannot lose —
98
+ * it is compared, sorted, and used as a cursor everywhere in this package.
99
+ * Exported so `nextSeq` (in `write.ts`) can recognize a recorded value it
100
+ * cannot build a next `seq` from, without redeclaring the number or
101
+ * re-running it through a schema.
102
+ */
103
+ export const MAX_SEQ = Number.MAX_SAFE_INTEGER;
104
+
105
+ /** Shared by both the read and the write message schema below; neither redeclares it. */
106
+ const messageLineShape = z.object({
107
+ type: z.literal("message"),
108
+ seq: z.number().int().min(1),
109
+ from: z.string().min(1),
110
+ in_reply_to: z.number().int().min(1).optional(),
111
+ kind: messageKindSchema.optional(),
112
+ body: z.string(),
113
+ change: messageChangeSchema.optional(),
114
+ // D-21: the highest `seq` the author had seen when it wrote this. Optional, so
115
+ // every line written by an earlier version still validates.
116
+ read_through: z.number().int().min(0).optional(),
117
+ });
118
+
119
+ /**
120
+ * Shape rules only — deliberately not "an edit kind must carry a change".
121
+ *
122
+ * That rule would make the message *invalid*, and an invalid line makes a room
123
+ * unreadable forever: the log is append-only with no repair command. So a
124
+ * `goal_edit` with no change is a **valid message that simply is not an
125
+ * edit**, and the fold ignores it. Whether an edit kind carries its change is
126
+ * a rule about *applying* a message, not about the message being well-formed,
127
+ * and conflating the two would have invented a new way for a log to die.
128
+ *
129
+ * Shared by the read and write schema below so the rule is checked once, not
130
+ * declared twice and left to drift.
131
+ */
132
+ function changeShapeIssue(
133
+ message: Pick<z.infer<typeof messageLineShape>, "kind" | "change">,
134
+ ): { path: (string | number)[]; message: string } | undefined {
135
+ if (message.change === undefined) return undefined;
136
+
137
+ const expected = message.kind === undefined ? undefined : EDIT_KINDS[message.kind as EditKind];
138
+ if (expected === undefined) {
139
+ // A change on an ordinary message will never be applied by anything, so
140
+ // accepting it would let a writer believe it changed state it did not.
141
+ return {
142
+ path: ["change"],
143
+ message: `a "change" requires an edit kind (${Object.keys(EDIT_KINDS).join(", ")}), not "${message.kind ?? "none"}"`,
144
+ };
145
+ }
146
+ if (message.change.type !== expected) {
147
+ return {
148
+ path: ["change", "type"],
149
+ message: `kind "${message.kind}" carries a "${message.change.type}" change; it must be "${expected}"`,
150
+ };
151
+ }
152
+ return undefined;
153
+ }
154
+
77
155
  /**
78
156
  * The log's message contract, and the one place the edit rule is expressed.
79
157
  *
@@ -84,44 +162,36 @@ export type MessageChange = z.infer<typeof messageChangeSchema>;
84
162
  *
85
163
  * `change` is optional, which is what keeps the format change additive: every
86
164
  * message written by every earlier version still validates.
165
+ *
166
+ * `seq` is deliberately unbounded above `1` here: this is the schema `store.ts`
167
+ * reads with, and reading has to stay permissive. A hand-crafted or merged-in
168
+ * line at the top of the safe-integer range is a line that already exists —
169
+ * refusing it on read would not un-write it, it would just turn an existing,
170
+ * merely-unwritable-to room into a permanently unreadable one, which is the
171
+ * worse failure (the log is append-only; there is no repair command). See
172
+ * `writeMessageLineSchema` for the bound roomyx itself writes under.
173
+ */
174
+ export const messageLineSchema = messageLineShape.superRefine((message, ctx) => {
175
+ const issue = changeShapeIssue(message);
176
+ if (issue) ctx.addIssue({ code: "custom", ...issue });
177
+ });
178
+
179
+ /**
180
+ * The schema `write.ts` validates a built message against before it is
181
+ * appended — same shape as `messageLineSchema`, `seq` additionally bounded at
182
+ * `MAX_SEQ`.
183
+ *
184
+ * This is "bound on write, permissive on read" stated as two schemas rather
185
+ * than one: collapsing them back into a single `messageLineSchema` would mean
186
+ * either the reader refusing a line it must accept (the failure D-08 exists to
187
+ * prevent), or the writer's safety depending on an accident of whatever this
188
+ * zod version's `.int()` happens to bound rather than on a stated contract.
189
+ * Both schemas still come from this one module and this one shape; neither
190
+ * redeclares it.
87
191
  */
88
- export const messageLineSchema = z
89
- .object({
90
- type: z.literal("message"),
91
- seq: z.number().int().min(1),
92
- from: z.string().min(1),
93
- in_reply_to: z.number().int().min(1).optional(),
94
- kind: messageKindSchema.optional(),
95
- body: z.string(),
96
- change: messageChangeSchema.optional(),
97
- })
192
+ export const writeMessageLineSchema = messageLineShape
193
+ .extend({ seq: z.number().int().min(1).max(MAX_SEQ) })
98
194
  .superRefine((message, ctx) => {
99
- // Shape rules only — deliberately not "an edit kind must carry a change".
100
- //
101
- // That rule would make the message *invalid*, and an invalid line makes a room
102
- // unreadable forever: the log is append-only with no repair command. So a
103
- // `goal_edit` with no change is a **valid message that simply is not an
104
- // edit**, and the fold ignores it. Whether an edit kind carries its change is
105
- // a rule about *applying* a message, not about the message being well-formed,
106
- // and conflating the two would have invented a new way for a log to die.
107
- if (message.change === undefined) return;
108
-
109
- const expected = message.kind === undefined ? undefined : EDIT_KINDS[message.kind as EditKind];
110
- if (expected === undefined) {
111
- // A change on an ordinary message will never be applied by anything, so
112
- // accepting it would let a writer believe it changed state it did not.
113
- ctx.addIssue({
114
- code: "custom",
115
- path: ["change"],
116
- message: `a "change" requires an edit kind (${Object.keys(EDIT_KINDS).join(", ")}), not "${message.kind ?? "none"}"`,
117
- });
118
- return;
119
- }
120
- if (message.change.type !== expected) {
121
- ctx.addIssue({
122
- code: "custom",
123
- path: ["change", "type"],
124
- message: `kind "${message.kind}" carries a "${message.change.type}" change; it must be "${expected}"`,
125
- });
126
- }
195
+ const issue = changeShapeIssue(message);
196
+ if (issue) ctx.addIssue({ code: "custom", ...issue });
127
197
  });
package/src/log/store.ts CHANGED
@@ -73,6 +73,7 @@ export function loadRoomLog(path: string): { state: RoomState; messages: Message
73
73
  // The header is the room's ORIGINAL contract and the base every edit is
74
74
  // applied to; it is never reinterpreted as one of them.
75
75
  ...foldEdits({ goal_contract: headerResult.data.goal_contract, roster: headerResult.data.roster }, messages),
76
+ ...(headerResult.data.experiment ? { experiment: headerResult.data.experiment } : {}),
76
77
  // The reader knows which file it read; the state header does not carry it.
77
78
  log_path: path,
78
79
  };
package/src/log/types.ts CHANGED
@@ -1,4 +1,7 @@
1
- import type { MessageChange } from "./schema";
1
+ import type { z } from "zod";
2
+ import type { experimentSchema, MessageChange } from "./schema";
3
+
4
+ export type ExperimentHeader = z.infer<typeof experimentSchema>;
2
5
 
3
6
  export interface MessageEnvelope {
4
7
  seq: number;
@@ -17,6 +20,8 @@ export interface MessageEnvelope {
17
20
  body: string;
18
21
  /** Present only on an edit message; see `EDIT_KINDS` and D-19. */
19
22
  change?: MessageChange;
23
+ /** The highest `seq` the author had seen when it wrote this message (D-21). */
24
+ read_through?: number;
20
25
  }
21
26
 
22
27
  export interface RosterEntry {
@@ -41,6 +46,8 @@ export interface GoalContract {
41
46
  export interface RoomState {
42
47
  goal_contract: GoalContract;
43
48
  roster: RosterEntry[];
49
+ /** The experiment cell this room was created as, when it was (D-22). */
50
+ experiment?: ExperimentHeader;
44
51
  /**
45
52
  * The log this server is serving, absolute.
46
53
  *
package/src/log/write.ts CHANGED
@@ -2,8 +2,8 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } fr
2
2
  import { dirname } from "node:path";
3
3
  import type { z } from "zod";
4
4
  import { withLock } from "../lockfile";
5
- import { MESSAGE_KINDS, messageLineSchema } from "./schema";
6
- import type { GoalContract, MessageEnvelope, RosterEntry } from "./types";
5
+ import { MAX_SEQ, MESSAGE_KINDS, writeMessageLineSchema } from "./schema";
6
+ import type { ExperimentHeader, GoalContract, MessageEnvelope, RosterEntry } from "./types";
7
7
 
8
8
  /**
9
9
  * Thrown when a message would not survive its own reader. Separate from a
@@ -11,6 +11,13 @@ import type { GoalContract, MessageEnvelope, RosterEntry } from "./types";
11
11
  */
12
12
  export class LogWriteError extends Error {}
13
13
 
14
+ /**
15
+ * Thrown when an author wrote without having seen what other participants had
16
+ * already said. A refusal the caller can act on — re-read, then write again — and
17
+ * not a malformed envelope, so it is its own class.
18
+ */
19
+ export class UnreadMessagesError extends LogWriteError {}
20
+
14
21
  /** The legal kinds, for an error message that says what to write instead. */
15
22
  export const LEGAL_KINDS = MESSAGE_KINDS.join(", ");
16
23
 
@@ -41,6 +48,7 @@ export interface CreateRoomLogOptions {
41
48
  criteria?: string;
42
49
  roster: RosterEntry[];
43
50
  threshold?: GoalContract["threshold"];
51
+ experiment?: ExperimentHeader;
44
52
  }
45
53
 
46
54
  export interface AppendMessageOptions {
@@ -50,6 +58,15 @@ export interface AppendMessageOptions {
50
58
  inReplyTo?: number;
51
59
  /** Required by the edit kinds, refused on everything else — enforced by the schema. */
52
60
  change?: MessageEnvelope["change"];
61
+ /**
62
+ * The highest `seq` the author had seen (D-21). When given, the append is
63
+ * refused if another participant wrote something past it, unless `allowUnread`.
64
+ * Left out, nothing is checked: the gate is for a dispatcher that can say what
65
+ * it showed the agent, and it must not break one that cannot.
66
+ */
67
+ readThrough?: number;
68
+ /** Write despite unread messages; the gap is still recorded in `read_through`. */
69
+ allowUnread?: boolean;
53
70
  }
54
71
 
55
72
  /** Refuses to overwrite: a room log is append-only, and clobbering one loses a session. */
@@ -64,7 +81,55 @@ export function createRoomLog(path: string, options: CreateRoomLogOptions): void
64
81
  threshold: options.threshold ?? { fail_below: 60, pass_at_or_above: 80 },
65
82
  };
66
83
  mkdirSync(dirname(path), { recursive: true });
67
- writeFileSync(path, JSON.stringify({ type: "state", goal_contract: goalContract, roster: options.roster }) + "\n");
84
+ const header = {
85
+ type: "state",
86
+ goal_contract: goalContract,
87
+ roster: options.roster,
88
+ ...(options.experiment ? { experiment: options.experiment } : {}),
89
+ };
90
+ writeFileSync(path, JSON.stringify(header) + "\n");
91
+ }
92
+
93
+ /**
94
+ * `JSON.parse`, with the one thing it never says: where.
95
+ *
96
+ * Same shape as `parseLine` in `store.ts` — not the same function, kept local
97
+ * here rather than imported, since the two modules read the log for different
98
+ * reasons and `store.ts` is not touched by this change. A damaged log used to
99
+ * make `nextSeq` throw a bare, unlocated `SyntaxError`; this names the file
100
+ * and the line instead, the way every other failure in this package does.
101
+ */
102
+ function parseLogLine(text: string, describe: () => string): unknown {
103
+ try {
104
+ return JSON.parse(text);
105
+ } catch (error) {
106
+ throw new Error(`${describe()}: not valid JSON — ${error instanceof Error ? error.message : String(error)}`);
107
+ }
108
+ }
109
+
110
+ /**
111
+ * A recorded line's `seq`, for allocation purposes only — not validation.
112
+ *
113
+ * A line with no numeric `seq` at all is not a value to skip quietly: it is a
114
+ * damaged log, and used to yield `Math.max(…, undefined) = NaN`, which then
115
+ * made the *next* append's `validate` fail and blamed the new message for a
116
+ * problem in an existing line. This raises a located error instead.
117
+ *
118
+ * A `seq` that parses fine but cannot be built on — because it is not a safe
119
+ * integer, or because it already sits at `MAX_SEQ` so `seq + 1` would not be
120
+ * — is different: that is a legally *recorded* value (the read schema stays
121
+ * permissive on purpose; see `schema.ts`), just not one to allocate from. This
122
+ * returns `undefined` for it rather than throwing, so `nextSeq` ignores it and
123
+ * builds on whatever else the log has instead.
124
+ */
125
+ function recordedSeqForAllocation(line: string, describeLocation: () => string): number | undefined {
126
+ const parsed = parseLogLine(line, describeLocation);
127
+ if (typeof parsed !== "object" || parsed === null || !("seq" in parsed) || typeof parsed.seq !== "number") {
128
+ throw new Error(`${describeLocation()}: missing a numeric "seq"`);
129
+ }
130
+ const { seq } = parsed as { seq: number };
131
+ if (!Number.isSafeInteger(seq) || seq < 1 || seq >= MAX_SEQ) return undefined;
132
+ return seq;
68
133
  }
69
134
 
70
135
  /** The next `seq`, derived from the log rather than tracked separately. */
@@ -73,8 +138,15 @@ export function nextSeq(path: string): number {
73
138
  const lines = readFileSync(path, "utf8")
74
139
  .split("\n")
75
140
  .filter((line) => line.trim().length > 0);
76
- const seqs = lines.slice(1).map((line) => (JSON.parse(line) as { seq: number }).seq);
77
- return seqs.length > 0 ? Math.max(...seqs) + 1 : 1;
141
+ let max = 0;
142
+ // slice(1): the header line is not a message and carries no `seq`.
143
+ lines.slice(1).forEach((line, index) => {
144
+ // +2: 1-indexed lines, plus the header line already consumed — matches
145
+ // the numbering `store.ts` reports for the same lines.
146
+ const seq = recordedSeqForAllocation(line, () => `Invalid "message" line ${index + 2} in ${path}`);
147
+ if (seq !== undefined && seq > max) max = seq;
148
+ });
149
+ return max + 1;
78
150
  }
79
151
 
80
152
  /**
@@ -100,6 +172,9 @@ export function appendMessages(
100
172
  const base = nextSeq(path);
101
173
  const built = batch.map((options, index) => buildMessage(base + index, options));
102
174
  for (const message of built) validate(message);
175
+ // Against the log as it was BEFORE this batch: the messages of one batch are
176
+ // posted together and none of them is "unread" by another (D-21).
177
+ checkRead(path, base, batch);
103
178
  // All-or-nothing covers every failure this function can SEE: a bad envelope
104
179
  // in the batch throws before the first byte. It does NOT cover an I/O failure
105
180
  // partway through the appends below — a full disk or a signal mid-loop leaves
@@ -140,11 +215,45 @@ function buildMessage(seq: number, options: AppendMessageOptions): MessageEnvelo
140
215
  ...(options.kind ? { kind: options.kind } : {}),
141
216
  ...(options.inReplyTo !== undefined ? { in_reply_to: options.inReplyTo } : {}),
142
217
  ...(options.change !== undefined ? { change: options.change } : {}),
218
+ ...(options.readThrough !== undefined ? { read_through: options.readThrough } : {}),
143
219
  };
144
220
  }
145
221
 
222
+ /**
223
+ * D-21: refuses a message written without sight of what others had already said.
224
+ *
225
+ * Parallel agents fail on integration because each answers the round it was
226
+ * shown while a sibling's message lands in the meantime. The dispatcher knows
227
+ * what it showed each agent, the log knows what exists; this is the one place
228
+ * both are present, under the same lock that allocates `seq`.
229
+ */
230
+ function checkRead(path: string, base: number, batch: AppendMessageOptions[]): void {
231
+ if (batch.every((options) => options.readThrough === undefined)) return;
232
+ const recorded: { seq: number; from: string }[] = [];
233
+ for (const line of readFileSync(path, "utf8").split("\n").slice(1)) {
234
+ if (line.trim().length === 0) continue;
235
+ const parsed = JSON.parse(line) as { seq?: unknown; from?: unknown };
236
+ if (typeof parsed.seq === "number" && typeof parsed.from === "string") recorded.push({ seq: parsed.seq, from: parsed.from });
237
+ }
238
+ for (const options of batch) {
239
+ const through = options.readThrough;
240
+ if (through === undefined) continue;
241
+ if (through >= base) {
242
+ throw new LogWriteError(`read-through ${through} is past the end of the log (last seq ${base - 1}): nobody can have read what does not exist yet`);
243
+ }
244
+ if (options.allowUnread === true) continue;
245
+ const unread = recorded.filter((m) => m.seq > through && m.from !== options.from);
246
+ if (unread.length > 0) {
247
+ const list = unread.map((m) => `#${m.seq} (${m.from})`).join(", ");
248
+ throw new UnreadMessagesError(
249
+ `${options.from} has read through #${through}, but ${list} came after. Show ${options.from} what it missed and write again, or pass --allow-unread to write anyway.`,
250
+ );
251
+ }
252
+ }
253
+ }
254
+
146
255
  function validate(message: MessageEnvelope & { type: "message" }): void {
147
- const parsed = messageLineSchema.safeParse(message);
256
+ const parsed = writeMessageLineSchema.safeParse(message);
148
257
  if (!parsed.success) throw new LogWriteError(describeInvalid(parsed.error));
149
258
  }
150
259