@mrciphersmith/roomyx 0.3.0 → 0.5.0

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/src/cli.ts CHANGED
@@ -1,40 +1,28 @@
1
1
  #!/usr/bin/env bun
2
- import { existsSync } from "node:fs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
3
  import { join, resolve } from "node:path";
4
4
  import { serve } from "./server/serve";
5
5
  import { init } from "./installer/init";
6
6
  import { registerRoom, deregisterRoom, listLiveRooms } from "./installer/registry";
7
7
  import { syncSkill } from "./installer/skill-sync";
8
+ import { appendMessage, createRoomLog, parseRoster } from "./log/write";
8
9
  import { NAMED_TARGETS, resolveTargets } from "./installer/skill-targets";
9
10
  import { serveManagement } from "./mcp-management/server";
11
+ import { ArgError, parseArgs, renderFlags } from "./cli/args";
12
+ import type { FlagSpecs, ParsedArgs } from "./cli/args";
13
+ import { CLIENT_FLAGS } from "./cli/specs";
10
14
 
11
15
  /**
12
- * `roomyx init` / `roomyx serve` / `roomyx rooms list` / `roomyx mcp` /
13
- * `roomyx skills sync`.
14
- * The TUI is primarily `roomyx-client` (its own binary over src/client/index.ts)
15
- * so the orchestrator and the TUI stay independent processes (decisions.md
16
- * D-06). `roomyx client` is a thin alias that starts that same TUI in this
17
- * process — a separate invocation from `serve`/`mcp`, not a shared lifetime.
16
+ * The TUI is primarily `roomyx-client` (its own binary over
17
+ * src/client/index.ts) so the orchestrator and the TUI stay independent
18
+ * processes (decisions.md D-06). `roomyx client` is a thin alias that starts
19
+ * that same TUI in this process — a separate invocation from `serve`/`mcp`,
20
+ * not a shared lifetime.
21
+ *
22
+ * Every command declares its flags rather than scanning argv by hand. See
23
+ * `./cli/args` for what that fixes and why it was one defect rather than six.
18
24
  */
19
25
 
20
- function parseFlags(args: string[]): Record<string, string | boolean> {
21
- const flags: Record<string, string | boolean> = {};
22
- for (let i = 0; i < args.length; i++) {
23
- const arg = args[i];
24
- if (arg?.startsWith("--")) {
25
- const key = arg.slice(2);
26
- const next = args[i + 1];
27
- if (next !== undefined && !next.startsWith("--")) {
28
- flags[key] = next;
29
- i++;
30
- } else {
31
- flags[key] = true;
32
- }
33
- }
34
- }
35
- return flags;
36
- }
37
-
38
26
  function defaultRegistryPath(): string {
39
27
  return join(process.cwd(), ".roomyx", "rooms", "registry.json");
40
28
  }
@@ -47,152 +35,327 @@ function bundledSkillPath(): string {
47
35
  return join(import.meta.dir, "bundled-skills", "startup-room", "SKILL.md");
48
36
  }
49
37
 
50
- const USAGE =
51
- "Usage: roomyx <init|serve <logPath>|client|mcp|rooms list|skills sync --target <claude|codex|keryx|all|path>>";
38
+ const REGISTRY_FLAG = { type: "string", describe: "Registry file (default .roomyx/rooms/registry.json)" } as const;
52
39
 
53
- async function runInit(): Promise<void> {
54
- const result = init({ cwd: process.cwd(), bundledSkillPath: bundledSkillPath() });
55
- console.log(result.created ? `Created ${result.roomyxDir}` : `${result.roomyxDir} already initialized`);
40
+ interface Command {
41
+ usage: string;
42
+ summary: string;
43
+ /** Extra lines under the flag table. */
44
+ notes?: string;
45
+ flags: FlagSpecs;
46
+ run: (args: ParsedArgs) => Promise<void>;
56
47
  }
57
48
 
58
- async function runServe(logPath: string | undefined, rest: string[]): Promise<void> {
59
- if (!logPath) {
60
- console.error("Missing <logPath>. Usage: roomyx serve <logPath> [--port N]");
61
- process.exit(1);
62
- }
63
- const flags = parseFlags(rest);
64
- // Absolute, because the registry outlives this process's working directory:
65
- // `roomyx-client` resolves rooms from wherever the person happened to run it,
66
- // and a relative logPath means nothing there. The specification's registry
67
- // example has always shown an absolute path; only the code disagreed.
68
- const absoluteLogPath = resolve(logPath);
69
- const handle = await serve(absoluteLogPath, {
70
- port: flags.port !== undefined ? Number(flags.port) : undefined,
71
- host: typeof flags.host === "string" ? flags.host : undefined,
72
- acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
73
- });
74
-
75
- const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
76
- const entry = registerRoom(registryPath, {
77
- port: handle.port,
78
- logPath: absoluteLogPath,
79
- pid: process.pid,
80
- });
81
-
82
- console.log(`roomyx serving ${absoluteLogPath} at ${handle.url}`);
83
- console.log(`room ID: ${entry.id} — attach with \`roomyx-client --room ${entry.id}\``);
84
-
85
- const shutdown = () => {
86
- deregisterRoom(registryPath, entry.id);
87
- void handle.close().then(() => process.exit(0));
88
- };
89
- process.on("SIGINT", shutdown);
90
- process.on("SIGTERM", shutdown);
91
- }
49
+ const COMMANDS: Record<string, Command> = {
50
+ init: {
51
+ usage: "roomyx init",
52
+ summary: "scaffold .roomyx/ in this project",
53
+ flags: {},
54
+ run: async () => {
55
+ const result = init({ cwd: process.cwd(), bundledSkillPath: bundledSkillPath() });
56
+ console.log(result.created ? `Created ${result.roomyxDir}` : `${result.roomyxDir} already initialized`);
57
+ },
58
+ },
92
59
 
93
- async function runRoomsList(): Promise<void> {
94
- const rooms = await listLiveRooms(defaultRegistryPath());
95
- if (rooms.length === 0) {
96
- console.log("No live rooms.");
97
- return;
98
- }
99
- for (const room of rooms) {
100
- console.log(`${room.id} port=${room.port} log=${room.logPath} started=${room.startedAt}`);
101
- }
102
- }
60
+ "room new": {
61
+ usage: "roomyx room new <path> --goal <statement> [flags]",
62
+ summary: "create a room log",
63
+ notes: "Refuses to overwrite an existing log — a room log is append-only.",
64
+ flags: {
65
+ goal: { type: "string", describe: "Required. What the room is for, in one sentence" },
66
+ criteria: { type: "string", describe: "Success criteria, stored in the goal contract" },
67
+ roster: { type: "string", describe: "Participants, as id:Name,id2:Name2" },
68
+ },
69
+ run: async ({ positionals, flags }) => {
70
+ const path = positionals[0];
71
+ if (!path) throw new ArgError("Missing <path>.");
72
+ const goalStatement = flags.goal;
73
+ if (typeof goalStatement !== "string") {
74
+ throw new ArgError("Missing --goal. A room without a stated goal has nothing to converge on.");
75
+ }
76
+ const absolute = resolve(path);
77
+ createRoomLog(absolute, {
78
+ goalStatement,
79
+ criteria: typeof flags.criteria === "string" ? flags.criteria : undefined,
80
+ roster: typeof flags.roster === "string" ? parseRoster(flags.roster) : [],
81
+ });
82
+ console.log(`Created ${absolute}`);
83
+ console.log(`serve it with \`roomyx serve ${path}\``);
84
+ },
85
+ },
103
86
 
104
- /**
105
- * `roomyx skills sync --target <claude|codex|keryx|all|path> [--dry-run] [--yes]`.
106
- *
107
- * Without `--yes` this reports what it would do and writes nothing — the
108
- * specification's wording, and D-02's requirement that landing on a real skill
109
- * file be a separate, deliberate act rather than a side effect of the
110
- * mechanism existing. `--dry-run` is then the same thing said explicitly.
111
- */
112
- async function runSkillsSync(rest: string[]): Promise<void> {
113
- const flags = parseFlags(rest);
114
- const target = typeof flags.target === "string" ? flags.target : undefined;
115
- if (!target) {
116
- console.error(`Missing --target. Expected one of ${NAMED_TARGETS.join(", ")}, all, or a path.`);
117
- process.exit(1);
118
- }
87
+ "room append": {
88
+ usage: "roomyx room append <path> --from <id> --body <text> [flags]",
89
+ summary: "append a message to a room log",
90
+ notes:
91
+ "Refuses when a live room is serving that log: its dispatcher is the\n single writer (D-01a). --force overrides if you know the room is gone.",
92
+ flags: {
93
+ from: { type: "string", describe: "Required. Participant id" },
94
+ body: { type: "string", describe: "Required. The message" },
95
+ kind: { type: "string", describe: "Message kind, e.g. challenge" },
96
+ "in-reply-to": { type: "number", describe: "seq of the message replied to" },
97
+ force: { type: "boolean", describe: "Append even if a live room serves this log" },
98
+ registry: REGISTRY_FLAG,
99
+ },
100
+ run: async ({ positionals, flags }) => {
101
+ const path = positionals[0];
102
+ if (!path) throw new ArgError("Missing <path>.");
103
+ const from = flags.from;
104
+ const body = flags.body;
105
+ if (typeof from !== "string" || typeof body !== "string") {
106
+ throw new ArgError("Both --from and --body are required.");
107
+ }
119
108
 
120
- const yes = flags.yes === true;
121
- const dryRun = flags["dry-run"] === true || !yes;
122
- const configPath = typeof flags.config === "string" ? flags.config : defaultConfigPath();
109
+ const absolute = resolve(path);
110
+ if (flags.force !== true) {
111
+ const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
112
+ const serving = (await listLiveRooms(registryPath)).find((room) => room.logPath === absolute);
113
+ if (serving) {
114
+ throw new ArgError(
115
+ `A live room (${serving.id}) is serving this log; its dispatcher is the single writer (D-01). Pass --force if you know it isn't.`,
116
+ );
117
+ }
118
+ }
123
119
 
124
- if (!existsSync(configPath)) {
125
- console.error(`No ${configPath}. Run \`roomyx init\` first.`);
126
- process.exit(1);
127
- }
120
+ const message = appendMessage(absolute, {
121
+ from,
122
+ body,
123
+ kind: typeof flags.kind === "string" ? (flags.kind as never) : undefined,
124
+ inReplyTo: typeof flags["in-reply-to"] === "number" ? flags["in-reply-to"] : undefined,
125
+ });
126
+ console.log(`Appended seq ${message.seq} from ${message.from}.`);
127
+ },
128
+ },
128
129
 
129
- for (const { name, path } of resolveTargets(target)) {
130
- const result = syncSkill({
131
- bundledSkillPath: bundledSkillPath(),
132
- targetPath: path,
133
- configPath,
134
- dryRun,
135
- yes,
136
- });
137
- console.log(name === path ? path : `${name}: ${path}`);
138
- for (const warning of result.warnings) console.log(` warning: ${warning}`);
139
- if (result.written) {
140
- console.log(result.backedUpTo ? ` written (backup: ${result.backedUpTo})` : " written");
141
- } else {
142
- console.log(dryRun ? " would write (pass --yes to apply)" : " not written");
143
- }
144
- }
145
- }
130
+ serve: {
131
+ usage: "roomyx serve <logPath> [flags]",
132
+ summary: "serve a room log over MCP",
133
+ flags: {
134
+ port: { type: "number", describe: "Listen port (default 4319; 0 picks an ephemeral one)" },
135
+ host: { type: "string", describe: "Bind address (default 127.0.0.1)" },
136
+ "acknowledge-non-loopback": { type: "boolean", describe: "Required to bind a non-loopback host" },
137
+ registry: REGISTRY_FLAG,
138
+ },
139
+ run: async ({ positionals, flags }) => {
140
+ const logPath = positionals[0];
141
+ if (!logPath) throw new ArgError("Missing <logPath>.");
142
+
143
+ // Absolute, because the registry outlives this process's working
144
+ // directory: `roomyx-client` resolves rooms from wherever the person
145
+ // happened to run it, and a relative logPath means nothing there.
146
+ const absoluteLogPath = resolve(logPath);
147
+ const handle = await serve(absoluteLogPath, {
148
+ port: typeof flags.port === "number" ? flags.port : undefined,
149
+ host: typeof flags.host === "string" ? flags.host : undefined,
150
+ acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
151
+ });
152
+
153
+ const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
154
+ const entry = registerRoom(registryPath, {
155
+ port: handle.port,
156
+ logPath: absoluteLogPath,
157
+ pid: process.pid,
158
+ });
159
+
160
+ console.log(`roomyx serving ${absoluteLogPath} at ${handle.url}`);
161
+ console.log(`room ID: ${entry.id} — attach with \`roomyx-client --room ${entry.id}\``);
146
162
 
147
- async function runMcp(rest: string[]): Promise<void> {
148
- const flags = parseFlags(rest);
149
- const handle = await serveManagement(
150
- {
151
- registryPath: typeof flags.registry === "string" ? flags.registry : defaultRegistryPath(),
152
- bundledSkillPath: bundledSkillPath(),
153
- configPath: typeof flags.config === "string" ? flags.config : defaultConfigPath(),
163
+ const shutdown = () => {
164
+ deregisterRoom(registryPath, entry.id);
165
+ void handle.close().then(() => process.exit(0));
166
+ };
167
+ process.on("SIGINT", shutdown);
168
+ process.on("SIGTERM", shutdown);
154
169
  },
155
- {
156
- port: flags.port !== undefined ? Number(flags.port) : undefined,
157
- host: typeof flags.host === "string" ? flags.host : undefined,
158
- acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
170
+ },
171
+
172
+ "rooms list": {
173
+ usage: "roomyx rooms list [flags]",
174
+ summary: "live rooms, confirmed by a real call rather than by the file",
175
+ flags: { registry: REGISTRY_FLAG },
176
+ run: async ({ flags }) => {
177
+ // `--registry` used to be accepted here and silently ignored: this
178
+ // command took no arguments at all and read the default path, so
179
+ // `rooms list --registry /nonexistent.json` printed "No live rooms"
180
+ // about a different file.
181
+ const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
182
+ const rooms = await listLiveRooms(registryPath);
183
+ if (rooms.length === 0) {
184
+ console.log("No live rooms.");
185
+ return;
186
+ }
187
+ for (const room of rooms) {
188
+ console.log(`${room.id} port=${room.port} log=${room.logPath} started=${room.startedAt}`);
189
+ }
190
+ },
191
+ },
192
+
193
+ client: {
194
+ usage: "roomyx client [flags]",
195
+ summary: "attach the terminal UI (same as the roomyx-client binary)",
196
+ flags: CLIENT_FLAGS,
197
+ run: async ({ flags }) => {
198
+ const { runClient } = await import("./client/index");
199
+ await runClient(flags);
200
+ },
201
+ },
202
+
203
+ mcp: {
204
+ usage: "roomyx mcp [flags]",
205
+ summary: "start the management MCP server",
206
+ notes: "Default port 4320, so it does not collide with `roomyx serve`.",
207
+ flags: {
208
+ port: { type: "number", describe: "Listen port (default 4320; 0 picks an ephemeral one)" },
209
+ host: { type: "string", describe: "Bind address (default 127.0.0.1)" },
210
+ "acknowledge-non-loopback": { type: "boolean", describe: "Required to bind a non-loopback host" },
211
+ registry: REGISTRY_FLAG,
212
+ config: { type: "string", describe: "Config file (default .roomyx/config.json)" },
213
+ },
214
+ run: async ({ flags }) => {
215
+ const handle = await serveManagement(
216
+ {
217
+ registryPath: typeof flags.registry === "string" ? flags.registry : defaultRegistryPath(),
218
+ bundledSkillPath: bundledSkillPath(),
219
+ configPath: typeof flags.config === "string" ? flags.config : defaultConfigPath(),
220
+ },
221
+ {
222
+ port: typeof flags.port === "number" ? flags.port : undefined,
223
+ host: typeof flags.host === "string" ? flags.host : undefined,
224
+ acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
225
+ },
226
+ );
227
+
228
+ console.log(`roomyx mcp listening at ${handle.url}`);
229
+ console.log("tools: roomyx.rooms.list, roomyx.skills.sync");
230
+
231
+ const shutdown = () => {
232
+ void handle.close().then(() => process.exit(0));
233
+ };
234
+ process.on("SIGINT", shutdown);
235
+ process.on("SIGTERM", shutdown);
159
236
  },
160
- );
237
+ },
161
238
 
162
- console.log(`roomyx mcp listening at ${handle.url}`);
163
- console.log("tools: roomyx.rooms.list, roomyx.skills.sync");
239
+ "skills sync": {
240
+ usage: "roomyx skills sync --target <claude|codex|keryx|all|path> [flags]",
241
+ summary: "install the bundled startup-room skill",
242
+ notes:
243
+ "Without --yes nothing is written: the run reports what it would do and\n stops. D-02 — landing on a real skill file is a deliberate act, not a\n side effect of the mechanism existing.",
244
+ flags: {
245
+ target: { type: "string", describe: `Required. ${NAMED_TARGETS.join(", ")}, all, or a literal path` },
246
+ yes: { type: "boolean", describe: "Actually write" },
247
+ "dry-run": { type: "boolean", describe: "Report only (the default)" },
248
+ config: { type: "string", describe: "Config file the sync records hashes in" },
249
+ },
250
+ run: async ({ flags }) => {
251
+ const target = flags.target;
252
+ if (typeof target !== "string") {
253
+ throw new ArgError(`Missing --target. Expected one of ${NAMED_TARGETS.join(", ")}, all, or a path.`);
254
+ }
255
+
256
+ const yes = flags.yes === true;
257
+ const dryRun = flags["dry-run"] === true || !yes;
258
+ const configPath = typeof flags.config === "string" ? flags.config : defaultConfigPath();
259
+ if (!existsSync(configPath)) {
260
+ throw new ArgError(`No ${configPath}. Run \`roomyx init\` first.`);
261
+ }
164
262
 
165
- const shutdown = () => {
166
- void handle.close().then(() => process.exit(0));
263
+ for (const { name, path } of resolveTargets(target)) {
264
+ const result = syncSkill({
265
+ bundledSkillPath: bundledSkillPath(),
266
+ targetPath: path,
267
+ configPath,
268
+ dryRun,
269
+ yes,
270
+ });
271
+ console.log(name === path ? path : `${name}: ${path}`);
272
+ for (const warning of result.warnings) console.log(` warning: ${warning}`);
273
+ if (result.written) {
274
+ console.log(result.backedUpTo ? ` written (backup: ${result.backedUpTo})` : " written");
275
+ } else {
276
+ console.log(dryRun ? " would write (pass --yes to apply)" : " not written");
277
+ }
278
+ }
279
+ },
280
+ },
281
+ };
282
+
283
+ /** package.json ships in the tarball (see `files`), so this resolves for an installed copy too. */
284
+ function version(): string {
285
+ const manifest = JSON.parse(readFileSync(join(import.meta.dir, "..", "package.json"), "utf8")) as {
286
+ version: string;
167
287
  };
168
- process.on("SIGINT", shutdown);
169
- process.on("SIGTERM", shutdown);
288
+ return manifest.version;
289
+ }
290
+
291
+ function topLevelHelp(): string {
292
+ const names = Object.keys(COMMANDS);
293
+ const width = Math.max(...names.map((n) => n.length));
294
+ return [
295
+ "Usage: roomyx <command> [flags]",
296
+ "",
297
+ ...names.map((n) => ` ${n.padEnd(width)} ${COMMANDS[n]!.summary}`),
298
+ "",
299
+ " --version",
300
+ "",
301
+ "`roomyx <command> --help` describes one command.",
302
+ "The terminal UI is also a separate binary: roomyx-client [--room <id>]",
303
+ ].join("\n");
304
+ }
305
+
306
+ function commandHelp(name: string, command: Command): string {
307
+ const table = renderFlags(command.flags);
308
+ return [
309
+ command.usage,
310
+ "",
311
+ ` ${command.summary}`,
312
+ ...(command.notes ? ["", ` ${command.notes}`] : []),
313
+ ...(table ? ["", table] : []),
314
+ ].join("\n");
315
+ }
316
+
317
+ /** Longest command name first, so "room new" wins over a hypothetical "room". */
318
+ function matchCommand(argv: string[]): { name: string; command: Command; rest: string[] } | undefined {
319
+ for (const name of Object.keys(COMMANDS).sort((a, b) => b.split(" ").length - a.split(" ").length)) {
320
+ const words = name.split(" ");
321
+ if (words.every((word, i) => argv[i] === word)) {
322
+ return { name, command: COMMANDS[name]!, rest: argv.slice(words.length) };
323
+ }
324
+ }
325
+ return undefined;
170
326
  }
171
327
 
172
328
  async function main(): Promise<void> {
173
- const [command, ...rest] = process.argv.slice(2);
174
-
175
- if (command === "init") {
176
- await runInit();
177
- } else if (command === "serve") {
178
- await runServe(rest[0], rest.slice(1));
179
- } else if (command === "client") {
180
- const { runClient } = await import("./client/index");
181
- await runClient(rest);
182
- } else if (command === "mcp") {
183
- await runMcp(rest);
184
- } else if (command === "rooms" && rest[0] === "list") {
185
- await runRoomsList();
186
- } else if (command === "skills" && rest[0] === "sync") {
187
- await runSkillsSync(rest.slice(1));
188
- } else {
189
- console.error(USAGE);
190
- console.error("The terminal UI is also a separate binary: roomyx-client [--room <id>]");
191
- process.exit(1);
329
+ const argv = process.argv.slice(2);
330
+
331
+ if (argv[0] === "--version" || argv[0] === "-v") {
332
+ console.log(version());
333
+ return;
334
+ }
335
+
336
+ const matched = matchCommand(argv);
337
+ if (!matched) {
338
+ // `--help` is a request and exits 0. A bare `roomyx`, or a command that
339
+ // isn't one, is a usage error and exits 1 — the convention git follows,
340
+ // and the distinction a shell script or an agent actually reads.
341
+ const askedForHelp = argv[0] === "--help" || argv[0] === "-h";
342
+ console[askedForHelp ? "log" : "error"](topLevelHelp());
343
+ process.exit(askedForHelp ? 0 : 1);
344
+ }
345
+
346
+ const parsed = parseArgs(matched.rest, matched.command.flags);
347
+ if (parsed.help) {
348
+ console.log(commandHelp(matched.name, matched.command));
349
+ return;
192
350
  }
351
+ await matched.command.run(parsed);
193
352
  }
194
353
 
195
354
  main().catch((error) => {
355
+ if (error instanceof ArgError) {
356
+ console.error(error.message);
357
+ process.exit(1);
358
+ }
196
359
  console.error(error instanceof Error ? error.message : String(error));
197
360
  process.exit(1);
198
361
  });
@@ -8,6 +8,8 @@ export class StatusBar {
8
8
  readonly node: TextRenderable;
9
9
  private goalStatement = "";
10
10
  private status: ConnectionStatus = "connecting";
11
+ /** Takes over the line while an owner command is being composed or answered. */
12
+ private notice: string | null = null;
11
13
 
12
14
  constructor(ctx: RenderContext) {
13
15
  this.node = new TextRenderable(ctx, { content: "", height: 1 });
@@ -24,7 +26,17 @@ export class StatusBar {
24
26
  this.render();
25
27
  }
26
28
 
29
+ /** Pass null to hand the line back to the goal statement. */
30
+ setNotice(notice: string | null): void {
31
+ this.notice = notice;
32
+ this.render();
33
+ }
34
+
27
35
  private render(): void {
36
+ if (this.notice !== null) {
37
+ this.node.content = this.notice;
38
+ return;
39
+ }
28
40
  const statusLabel = { connecting: "connecting…", connected: "connected", disconnected: "disconnected — retrying" }[
29
41
  this.status
30
42
  ];