@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
@@ -17,6 +17,25 @@
17
17
  * meant a shutdown that hung — and it hung whenever a client was attached —
18
18
  * removed the room from the registry while the process kept running and kept
19
19
  * the port. The room became invisible while still being served.
20
+ *
21
+ * Two more properties, found by an audit rather than by observed failure —
22
+ * `cleanup` is `deregisterRoom`, which writes a file under a lock and can
23
+ * throw (a lock timeout, a corrupt registry):
24
+ *
25
+ * - **A throwing `cleanup` must not swallow `exit`.** The old code ran both
26
+ * inside one `.finally()`, so a throw there replaced the `exit()` after it.
27
+ * The rejection went unhandled, the process did not die, and a SIGTERM left
28
+ * the server running — the one outcome shutdown may not have. `cleanup` is
29
+ * now wrapped in its own try/catch that logs and falls through to `exit`
30
+ * regardless.
31
+ * - **A rejected `close` must not exit 0.** The exit code is the only thing a
32
+ * supervisor reads; reporting success for a shutdown that could not release
33
+ * the port sends whatever restarts it straight into `EADDRINUSE` with
34
+ * nothing in the registry left to explain it. `cleanup` still runs on this
35
+ * path — the entry is removed the same as a clean shutdown, matching the
36
+ * `SIGHUP`/`SIGTERM`/`SIGINT` handlers that already treat "told to stop" as
37
+ * reason enough to deregister, whether or not the port actually let go.
38
+ * Only the exit code now tells the difference.
20
39
  */
21
40
  export function createServerShutdown(
22
41
  close: () => Promise<void>,
@@ -27,13 +46,20 @@ export function createServerShutdown(
27
46
  return (): void => {
28
47
  if (shuttingDown) return;
29
48
  shuttingDown = true;
30
- void close()
31
- .catch((error: unknown) => {
32
- console.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
33
- })
34
- .finally(() => {
49
+ const finish = (code: number): void => {
50
+ try {
35
51
  cleanup();
36
- exit(0);
37
- });
52
+ } catch (error: unknown) {
53
+ console.error(`cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
54
+ }
55
+ exit(code);
56
+ };
57
+ void close().then(
58
+ () => finish(0),
59
+ (error: unknown) => {
60
+ console.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
61
+ finish(1);
62
+ },
63
+ );
38
64
  };
39
65
  }
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
+ import { z } from "zod";
4
5
 
5
6
  /**
6
7
  * Who is holding the pen on a room log, as a fact rather than an inference.
@@ -17,6 +18,15 @@ import { createHash, randomUUID } from "node:crypto";
17
18
  * `roomyx room append` never holds one: it would be expired by the time anyone
18
19
  * could read it, which is the state a lease exists to distinguish.
19
20
  *
21
+ * That last sentence was a comment and not code until the 2026-09-27 audit.
22
+ * `room append --take-over` *acquired* a lease and then exited, so it left a
23
+ * fresh hold owned by a pid that no longer existed — read as `held` for the next
24
+ * `LEASE_STALE_MS` and as `stale` (i.e. "pass `--take-over`") forever after.
25
+ * Each recovery re-armed the refusal it was recovering from. A one-shot writer
26
+ * now leaves a **tombstone** instead: a record that replaces the displaced token
27
+ * without claiming a live hold (`tombstoneWriterLease`), which is the one thing
28
+ * the take-over actually needed the write for.
29
+ *
20
30
  * Two rules copied deliberately from `lockfile.ts` rather than re-derived:
21
31
  *
22
32
  * - **Release checks the token.** A holder that finishes late must not unlink
@@ -44,29 +54,57 @@ export const LEASE_HEARTBEAT_MS = 5_000;
44
54
  */
45
55
  export const LEASE_STALE_MS = 30_000;
46
56
 
47
- export interface WriterLease {
48
- token: string;
49
- pid: number;
57
+ /**
58
+ * The lease record on disk, described once so it cannot be narrowed by accident.
59
+ *
60
+ * `parseLease` used to rebuild `{token, pid, at}` by hand and dropped
61
+ * `takenOverFrom`, so the first heartbeat after a take-over — five seconds later
62
+ * — wrote the narrowed object back and erased the provenance the field exists to
63
+ * carry. A schema is used rather than a hand-written check precisely because the
64
+ * hand-written one silently omitted a field: adding one here makes it
65
+ * round-trip, and a reader that forgets it can no longer be the reason it is
66
+ * lost.
67
+ */
68
+ const writerLeaseSchema = z.object({
69
+ token: z.string().min(1),
70
+ pid: z.number(),
50
71
  /** Epoch ms of the last heartbeat, so staleness needs no file mtime. */
51
- at: number;
72
+ at: z.number(),
73
+ /**
74
+ * A tombstone: the token is replaced, and nobody is holding what replaced it.
75
+ * Written by a writer that has finished (a one-shot `room append --take-over`)
76
+ * rather than by one that is still there.
77
+ */
78
+ released: z.literal(true).optional(),
52
79
  /**
53
80
  * Set when a writer took this lease over from one that had stopped — the pid
54
81
  * that did it, and when. It is why the token is replaced on take-over: the
55
82
  * previous holder's heartbeat has to fail, or a writer that was merely paused
56
83
  * revives the lease it lost and two processes write the same log.
57
84
  */
58
- takenOverFrom?: { pid: number; at: number };
59
- }
85
+ takenOverFrom: z.object({ pid: z.number(), at: z.number() }).optional(),
86
+ });
87
+
88
+ export type WriterLease = z.infer<typeof writerLeaseSchema>;
60
89
 
61
90
  export type LeaseState =
62
91
  | { held: true; lease: WriterLease }
63
92
  /**
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.
93
+ * `stale` and `released` carry the lease they found, because "a writer stopped
94
+ * here, pid N, at T" is the fact a take-over needs to record — and reading the
95
+ * file only to discard who was in it leaves the log unable to say what it
96
+ * displaced.
67
97
  */
68
98
  | { held: false; reason: "absent" }
69
- | { held: false; reason: "stale"; last: WriterLease };
99
+ | { held: false; reason: "stale"; last: WriterLease }
100
+ /**
101
+ * Nobody holds it and nobody is expected to: a writer wrote, invalidated the
102
+ * token it displaced, and finished. Distinct from `stale`, which means a
103
+ * writer stopped **without** saying so — the case `--take-over` exists for. A
104
+ * tombstone read as `stale` is how one deliberate recovery turned into a
105
+ * permanent demand to keep recovering.
106
+ */
107
+ | { held: false; reason: "released"; last: WriterLease };
70
108
 
71
109
  /**
72
110
  * One lease file per room, under a directory beside the registry.
@@ -82,15 +120,39 @@ export function writerLeasePathFor(registryPath: string, logPath: string): strin
82
120
 
83
121
  function parseLease(raw: string): WriterLease | undefined {
84
122
  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 };
123
+ const parsed = writerLeaseSchema.safeParse(JSON.parse(raw));
124
+ return parsed.success ? parsed.data : undefined;
89
125
  } catch {
90
126
  return undefined;
91
127
  }
92
128
  }
93
129
 
130
+ /**
131
+ * Whether the process named by a lease still exists.
132
+ *
133
+ * A held lease is a claim, not a fact: the claim is only worth anything while the
134
+ * process that made it is running. Without this check a lease left behind by a
135
+ * process that is gone refused every write to the room for the whole stale
136
+ * window, naming a pid the operator could not find.
137
+ *
138
+ * The rule is deliberately the same as `registry.ts`'s own pid check, including
139
+ * the "no pid recorded, so do not decide from this" fallback: an unusable pid
140
+ * means this signal abstains, never that it fabricates an answer. It is
141
+ * reimplemented rather than imported because that copy is private to the
142
+ * registry and this module has no dependency on `installer/` — the audit's
143
+ * structural item wants the two moved together, not coupled where they sit.
144
+ */
145
+ export function isLeaseHolderAlive(pid: number): boolean {
146
+ if (!Number.isInteger(pid) || pid <= 0) return true;
147
+ try {
148
+ process.kill(pid, 0);
149
+ return true;
150
+ } catch (error) {
151
+ // EPERM means a process exists and is not ours to signal — still alive.
152
+ return (error as NodeJS.ErrnoException).code !== "ESRCH";
153
+ }
154
+ }
155
+
94
156
  /**
95
157
  * A corrupt or half-written lease reads as **no lease**, never as a held one.
96
158
  *
@@ -109,6 +171,10 @@ export function readWriterLease(path: string, options: { now?: number } = {}): L
109
171
  }
110
172
  const lease = parseLease(raw);
111
173
  if (lease === undefined) return { held: false, reason: "absent" };
174
+ // Released BEFORE stale, and it stays `released` however old it gets: a
175
+ // tombstone is a statement that nobody is holding this, and ageing does not
176
+ // turn it into "a writer stopped here without saying so".
177
+ if (lease.released === true) return { held: false, reason: "released", last: lease };
112
178
  const now = options.now ?? Date.now();
113
179
  if (now - lease.at > LEASE_STALE_MS) return { held: false, reason: "stale", last: lease };
114
180
  return { held: true, lease };
@@ -130,6 +196,35 @@ export function acquireWriterLease(
130
196
  return lease;
131
197
  }
132
198
 
199
+ /**
200
+ * Records a write that has already finished: a new token, held by nobody.
201
+ *
202
+ * This is what a one-shot `room append --take-over` leaves behind. It has to
203
+ * write *something* — the point of replacing the token is that a writer which was
204
+ * merely paused cannot refresh the lease it lost and start writing again beside
205
+ * whoever displaced it — but it must not claim a hold, because the process making
206
+ * the claim is about to exit and nothing would ever release it.
207
+ *
208
+ * `takeOverFrom` is kept on the record rather than only in the transcript: the
209
+ * displaced holder's own heartbeat reads this file, and "you were taken over by
210
+ * pid N" is the difference between reporting a displacement and guessing at one.
211
+ */
212
+ export function tombstoneWriterLease(
213
+ path: string,
214
+ options: { pid: number; now?: number; takeOverFrom?: { pid: number; at: number } },
215
+ ): WriterLease {
216
+ mkdirSync(dirname(path), { recursive: true });
217
+ const lease: WriterLease = {
218
+ token: randomUUID(),
219
+ pid: options.pid,
220
+ at: options.now ?? Date.now(),
221
+ released: true,
222
+ };
223
+ if (options.takeOverFrom !== undefined) lease.takenOverFrom = options.takeOverFrom;
224
+ writeFileSync(path, JSON.stringify(lease));
225
+ return lease;
226
+ }
227
+
133
228
  /** Returns false when the lease is gone, expired, or now someone else's. */
134
229
  export function refreshWriterLease(path: string, token: string, options: { now?: number } = {}): boolean {
135
230
  const state = readWriterLease(path, options);
@@ -138,6 +233,58 @@ export function refreshWriterLease(path: string, token: string, options: { now?:
138
233
  return true;
139
234
  }
140
235
 
236
+ /**
237
+ * What a live holder's heartbeat learns, which is not one bit of information.
238
+ *
239
+ * `refreshWriterLease` answers `false` to two completely different facts: "your
240
+ * lease expired while you were not scheduled" and "someone else holds this now".
241
+ * A holder that cannot tell them apart has to assume the worse one, so a
242
+ * thirty-second stall — a suspended laptop, a stopped container, a long GC — was
243
+ * reported as a take-over that never happened, and the heartbeat was cleared
244
+ * permanently. The process went on writing with nothing refreshing its lease, and
245
+ * its room became take-over-able while it was still the writer.
246
+ *
247
+ * - `refreshed` — still ours, deadline moved.
248
+ * - `reacquired` — nothing and nobody else claims it, so we take it back with a
249
+ * fresh token. Falling behind is recoverable; it is not a displacement.
250
+ * - `displaced` — the record belongs to someone else. This one is real, and the
251
+ * caller must stop being a writer rather than print advice about it.
252
+ */
253
+ export type LeaseRenewal =
254
+ | { outcome: "refreshed"; lease: WriterLease }
255
+ | { outcome: "reacquired"; lease: WriterLease; staleFor: number }
256
+ | { outcome: "displaced"; by: WriterLease };
257
+
258
+ export function renewWriterLease(
259
+ path: string,
260
+ token: string,
261
+ options: { pid: number; now?: number },
262
+ ): LeaseRenewal {
263
+ const now = options.now ?? Date.now();
264
+ const state = readWriterLease(path, { now });
265
+
266
+ if (state.held) {
267
+ if (state.lease.token !== token) return { outcome: "displaced", by: state.lease };
268
+ const lease = { ...state.lease, at: now };
269
+ writeFileSync(path, JSON.stringify(lease));
270
+ return { outcome: "refreshed", lease };
271
+ }
272
+
273
+ // A tombstone is always a displacement, whoever wrote it: somebody took this
274
+ // room over deliberately and said so. A holder that re-acquired over it would
275
+ // undo the one act the tombstone exists to make stick.
276
+ if (state.reason === "released") return { outcome: "displaced", by: state.last };
277
+ if (state.reason === "stale" && state.last.token !== token) {
278
+ return { outcome: "displaced", by: state.last };
279
+ }
280
+
281
+ // Absent, or expired and still ours: no other writer is claiming this log, so
282
+ // re-arming the lease cannot produce a second one. The token is fresh, so a
283
+ // reader that saw the expired one cannot refresh it back to life.
284
+ const staleFor = state.reason === "stale" ? now - state.last.at : 0;
285
+ return { outcome: "reacquired", lease: acquireWriterLease(path, { pid: options.pid, now }), staleFor };
286
+ }
287
+
141
288
  /** Unlinks only the lease this token wrote — see the note above. */
142
289
  export function releaseWriterLease(path: string, token: string): void {
143
290
  try {