@h-rig/cli 0.0.6-alpha.2 → 0.0.6-alpha.200

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 (47) hide show
  1. package/README.md +6 -28
  2. package/package.json +9 -27
  3. package/dist/bin/build-rig-binaries.js +0 -107
  4. package/dist/bin/rig.js +0 -9470
  5. package/dist/src/commands/_authority-runs.js +0 -110
  6. package/dist/src/commands/_connection-state.js +0 -123
  7. package/dist/src/commands/_doctor-checks.js +0 -519
  8. package/dist/src/commands/_operator-view.js +0 -340
  9. package/dist/src/commands/_parsers.js +0 -107
  10. package/dist/src/commands/_paths.js +0 -50
  11. package/dist/src/commands/_pi-install.js +0 -184
  12. package/dist/src/commands/_policy.js +0 -79
  13. package/dist/src/commands/_preflight.js +0 -478
  14. package/dist/src/commands/_probes.js +0 -13
  15. package/dist/src/commands/_run-driver-helpers.js +0 -289
  16. package/dist/src/commands/_server-client.js +0 -382
  17. package/dist/src/commands/_snapshot-upload.js +0 -331
  18. package/dist/src/commands/_task-picker.js +0 -48
  19. package/dist/src/commands/agent.js +0 -497
  20. package/dist/src/commands/browser.js +0 -890
  21. package/dist/src/commands/connect.js +0 -180
  22. package/dist/src/commands/dist.js +0 -402
  23. package/dist/src/commands/doctor.js +0 -529
  24. package/dist/src/commands/github.js +0 -294
  25. package/dist/src/commands/inbox.js +0 -160
  26. package/dist/src/commands/init.js +0 -1334
  27. package/dist/src/commands/inspect.js +0 -174
  28. package/dist/src/commands/inspector.js +0 -256
  29. package/dist/src/commands/plugin.js +0 -167
  30. package/dist/src/commands/profile-and-review.js +0 -178
  31. package/dist/src/commands/queue.js +0 -197
  32. package/dist/src/commands/remote.js +0 -507
  33. package/dist/src/commands/repo-git-harness.js +0 -221
  34. package/dist/src/commands/run.js +0 -771
  35. package/dist/src/commands/server.js +0 -386
  36. package/dist/src/commands/setup.js +0 -699
  37. package/dist/src/commands/task-report-bug.js +0 -1083
  38. package/dist/src/commands/task-run-driver.js +0 -1994
  39. package/dist/src/commands/task.js +0 -1343
  40. package/dist/src/commands/test.js +0 -39
  41. package/dist/src/commands/workspace.js +0 -123
  42. package/dist/src/commands.js +0 -9152
  43. package/dist/src/index.js +0 -9488
  44. package/dist/src/launcher.js +0 -131
  45. package/dist/src/report-bug.js +0 -260
  46. package/dist/src/runner.js +0 -272
  47. package/dist/src/withMutedConsole.js +0 -42
@@ -1,771 +0,0 @@
1
- // @bun
2
- // packages/cli/src/commands/run.ts
3
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
4
- import { resolve as resolve3 } from "path";
5
- import { createInterface as createInterface2 } from "readline/promises";
6
-
7
- // packages/cli/src/runner.ts
8
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
9
- import { CliError } from "@rig/runtime/control-plane/errors";
10
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
11
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
12
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
13
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
14
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
15
- function takeFlag(args, flag) {
16
- const rest = [];
17
- let value = false;
18
- for (const arg of args) {
19
- if (arg === flag) {
20
- value = true;
21
- continue;
22
- }
23
- rest.push(arg);
24
- }
25
- return { value, rest };
26
- }
27
- function takeOption(args, option) {
28
- const rest = [];
29
- let value;
30
- for (let index = 0;index < args.length; index += 1) {
31
- const current = args[index];
32
- if (current === option) {
33
- const next = args[index + 1];
34
- if (!next || next.startsWith("-")) {
35
- throw new CliError(`Missing value for ${option}`);
36
- }
37
- value = next;
38
- index += 1;
39
- continue;
40
- }
41
- if (current !== undefined) {
42
- rest.push(current);
43
- }
44
- }
45
- return { value, rest };
46
- }
47
- function requireNoExtraArgs(args, usage) {
48
- if (args.length > 0) {
49
- throw new CliError(`Unexpected arguments: ${args.join(" ")}
50
- Usage: ${usage}`);
51
- }
52
- }
53
-
54
- // packages/cli/src/commands/run.ts
55
- import {
56
- listAuthorityRuns,
57
- readAuthorityRun,
58
- readJsonlFile,
59
- resolveAuthorityRunDir
60
- } from "@rig/runtime/control-plane/authority-files";
61
- import {
62
- cleanupRunState,
63
- deleteRunState,
64
- listOpenEpics,
65
- resolveDefaultEpic,
66
- runResume,
67
- runStatus,
68
- runStop,
69
- startRun,
70
- defaultStartRunOptions
71
- } from "@rig/runtime/control-plane/native/run-ops";
72
- import { loadRuntimeContextFromEnv as loadRuntimeContextFromEnv2 } from "@rig/runtime/control-plane/runtime/context";
73
-
74
- // packages/cli/src/commands/_parsers.ts
75
- function parsePositiveInt(value, option, fallback) {
76
- if (!value) {
77
- return fallback;
78
- }
79
- const parsed = Number.parseInt(value, 10);
80
- if (!Number.isFinite(parsed) || parsed <= 0) {
81
- throw new CliError2(`Invalid ${option} value: ${value}`);
82
- }
83
- return parsed;
84
- }
85
-
86
- // packages/cli/src/commands/_server-client.ts
87
- import { spawnSync } from "child_process";
88
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
89
- import { resolve as resolve2 } from "path";
90
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
91
-
92
- // packages/cli/src/commands/_connection-state.ts
93
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
94
- import { homedir } from "os";
95
- import { dirname, resolve } from "path";
96
- function resolveGlobalConnectionsPath(env = process.env) {
97
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
98
- if (explicit)
99
- return resolve(explicit);
100
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
101
- if (stateDir)
102
- return resolve(stateDir, "connections.json");
103
- return resolve(homedir(), ".rig", "connections.json");
104
- }
105
- function resolveRepoConnectionPath(projectRoot) {
106
- return resolve(projectRoot, ".rig", "state", "connection.json");
107
- }
108
- function readJsonFile(path) {
109
- if (!existsSync(path))
110
- return null;
111
- try {
112
- return JSON.parse(readFileSync(path, "utf8"));
113
- } catch (error) {
114
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
115
- }
116
- }
117
- function normalizeConnection(value) {
118
- if (!value || typeof value !== "object" || Array.isArray(value))
119
- return null;
120
- const record = value;
121
- if (record.kind === "local")
122
- return { kind: "local", mode: "auto" };
123
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
124
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
125
- return { kind: "remote", baseUrl };
126
- }
127
- return null;
128
- }
129
- function readGlobalConnections(options = {}) {
130
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
131
- const payload = readJsonFile(path);
132
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
133
- return { connections: {} };
134
- }
135
- const rawConnections = payload.connections;
136
- const connections = {};
137
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
138
- for (const [alias, raw] of Object.entries(rawConnections)) {
139
- const connection = normalizeConnection(raw);
140
- if (connection)
141
- connections[alias] = connection;
142
- }
143
- }
144
- return { connections };
145
- }
146
- function readRepoConnection(projectRoot) {
147
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
148
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
149
- return null;
150
- const record = payload;
151
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
152
- if (!selected)
153
- return null;
154
- return {
155
- selected,
156
- project: typeof record.project === "string" ? record.project : undefined,
157
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
158
- };
159
- }
160
- function resolveSelectedConnection(projectRoot, options = {}) {
161
- const repo = readRepoConnection(projectRoot);
162
- if (!repo)
163
- return null;
164
- if (repo.selected === "local")
165
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
166
- const global = readGlobalConnections(options);
167
- const connection = global.connections[repo.selected];
168
- if (!connection) {
169
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
170
- }
171
- return { alias: repo.selected, connection };
172
- }
173
-
174
- // packages/cli/src/commands/_server-client.ts
175
- var cachedGitHubBearerToken;
176
- function cleanToken(value) {
177
- const trimmed = value?.trim();
178
- return trimmed ? trimmed : null;
179
- }
180
- function readPrivateRemoteSessionToken(projectRoot) {
181
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
182
- if (!existsSync2(path))
183
- return null;
184
- try {
185
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
186
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
187
- } catch {
188
- return null;
189
- }
190
- }
191
- function readGitHubBearerTokenForRemote(projectRoot) {
192
- if (cachedGitHubBearerToken !== undefined)
193
- return cachedGitHubBearerToken;
194
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
195
- if (privateSession) {
196
- cachedGitHubBearerToken = privateSession;
197
- return cachedGitHubBearerToken;
198
- }
199
- const envToken = cleanToken(process.env.RIG_GITHUB_TOKEN) ?? cleanToken(process.env.GITHUB_TOKEN) ?? cleanToken(process.env.GH_TOKEN);
200
- if (envToken) {
201
- cachedGitHubBearerToken = envToken;
202
- return cachedGitHubBearerToken;
203
- }
204
- const result = spawnSync("gh", ["auth", "token"], {
205
- encoding: "utf8",
206
- timeout: 5000,
207
- stdio: ["ignore", "pipe", "ignore"]
208
- });
209
- cachedGitHubBearerToken = result.status === 0 ? cleanToken(result.stdout) : null;
210
- return cachedGitHubBearerToken;
211
- }
212
- async function ensureServerForCli(projectRoot) {
213
- try {
214
- const selected = resolveSelectedConnection(projectRoot);
215
- if (selected?.connection.kind === "remote") {
216
- return {
217
- baseUrl: selected.connection.baseUrl,
218
- authToken: readGitHubBearerTokenForRemote(projectRoot),
219
- connectionKind: "remote"
220
- };
221
- }
222
- const connection = await ensureLocalRigServerConnection(projectRoot);
223
- return {
224
- baseUrl: connection.baseUrl,
225
- authToken: connection.authToken,
226
- connectionKind: "local"
227
- };
228
- } catch (error) {
229
- if (error instanceof Error) {
230
- throw new CliError2(error.message, 1);
231
- }
232
- throw error;
233
- }
234
- }
235
- function mergeHeaders(headers, authToken) {
236
- const merged = new Headers(headers);
237
- if (authToken) {
238
- merged.set("authorization", `Bearer ${authToken}`);
239
- }
240
- return merged;
241
- }
242
- function diagnosticMessage(payload) {
243
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
244
- return null;
245
- const record = payload;
246
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
247
- const messages = diagnostics.flatMap((entry) => {
248
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
249
- return [];
250
- const diagnostic = entry;
251
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
252
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
253
- return message ? [`${kind}: ${message}`] : [];
254
- });
255
- return messages.length > 0 ? messages.join("; ") : null;
256
- }
257
- async function requestServerJson(context, pathname, init = {}) {
258
- const server = await ensureServerForCli(context.projectRoot);
259
- const response = await fetch(`${server.baseUrl}${pathname}`, {
260
- ...init,
261
- headers: mergeHeaders(init.headers, server.authToken)
262
- });
263
- const text = await response.text();
264
- const payload = text.trim().length > 0 ? (() => {
265
- try {
266
- return JSON.parse(text);
267
- } catch {
268
- return null;
269
- }
270
- })() : null;
271
- if (!response.ok) {
272
- const diagnostics = diagnosticMessage(payload);
273
- const detail = diagnostics ?? (text || response.statusText);
274
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
275
- }
276
- return payload;
277
- }
278
- async function getRunDetailsViaServer(context, runId) {
279
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
280
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
281
- }
282
- async function getRunLogsViaServer(context, runId, options = {}) {
283
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
284
- if (options.limit !== undefined)
285
- url.searchParams.set("limit", String(options.limit));
286
- if (options.cursor)
287
- url.searchParams.set("cursor", options.cursor);
288
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
289
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
290
- }
291
- async function stopRunViaServer(context, runId) {
292
- const payload = await requestServerJson(context, "/api/runs/stop", {
293
- method: "POST",
294
- headers: { "content-type": "application/json" },
295
- body: JSON.stringify({ runId })
296
- });
297
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
298
- }
299
- async function steerRunViaServer(context, runId, message) {
300
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
301
- method: "POST",
302
- headers: { "content-type": "application/json" },
303
- body: JSON.stringify({ message })
304
- });
305
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
306
- }
307
-
308
- // packages/cli/src/commands/_operator-view.ts
309
- import { createInterface } from "readline";
310
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
311
- var CANONICAL_STAGES = [
312
- "Connect",
313
- "GitHub/task sync",
314
- "Prepare workspace",
315
- "Launch Pi",
316
- "Plan",
317
- "Implement",
318
- "Validate",
319
- "Commit",
320
- "Open PR",
321
- "Review/CI",
322
- "Merge",
323
- "Complete"
324
- ];
325
- function renderOperatorSnapshot(snapshot) {
326
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
327
- const runId = String(run.runId ?? run.id ?? "run");
328
- const status = String(run.status ?? "unknown");
329
- const logs = snapshot.logs ?? [];
330
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
331
- const match = logs.find((log) => String(log.title ?? "").toLowerCase() === stage.toLowerCase() || String(log.stage ?? "").toLowerCase() === stage.toLowerCase());
332
- return match ? [`${stage}: ${String(match.status ?? status)}`] : [];
333
- });
334
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
335
- `);
336
- }
337
- function runStatusFromPayload(payload) {
338
- const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
339
- return String(run.status ?? "unknown").toLowerCase();
340
- }
341
- async function applyOperatorCommand(context, input, deps = {}) {
342
- const line = input.line.trim();
343
- if (!line)
344
- return { action: "ignored" };
345
- if (line === "/detach" || line === "/quit" || line === "/q") {
346
- return { action: "detach", message: "Detached from run." };
347
- }
348
- if (line === "/stop") {
349
- await (deps.stop ?? stopRunViaServer)(context, input.runId);
350
- return { action: "stopped", message: "Stop requested." };
351
- }
352
- const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
353
- if (!userMessage)
354
- return { action: "ignored" };
355
- await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
356
- return { action: "continue", message: "Steering message queued." };
357
- }
358
- async function readOperatorSnapshot(context, runId) {
359
- const run = await getRunDetailsViaServer(context, runId);
360
- const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
361
- const entries = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
362
- return { run, logs: entries, rendered: renderOperatorSnapshot({ run, logs: entries }) };
363
- }
364
- async function attachRunOperatorView(context, input) {
365
- let steered = false;
366
- if (input.message?.trim()) {
367
- await steerRunViaServer(context, input.runId, input.message.trim());
368
- steered = true;
369
- }
370
- let snapshot = await readOperatorSnapshot(context, input.runId);
371
- if (context.outputMode === "text") {
372
- console.log(snapshot.rendered);
373
- if (steered)
374
- console.log("Steering message queued.");
375
- }
376
- let detached = false;
377
- let rl = null;
378
- if (input.follow && !input.once && context.outputMode === "text") {
379
- if (input.interactive !== false && process.stdin.isTTY) {
380
- console.log("Controls: /user <message>, /stop, /detach");
381
- rl = createInterface({ input: process.stdin, output: process.stdout, terminal: false });
382
- rl.on("line", (line) => {
383
- applyOperatorCommand(context, { runId: input.runId, line }).then((result) => {
384
- if (result.message)
385
- console.log(result.message);
386
- if (result.action === "detach" || result.action === "stopped") {
387
- detached = true;
388
- rl?.close();
389
- }
390
- }).catch((error) => console.log(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
391
- });
392
- }
393
- let lastRendered = snapshot.rendered;
394
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
395
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
396
- await Bun.sleep(pollMs);
397
- snapshot = await readOperatorSnapshot(context, input.runId);
398
- if (snapshot.rendered !== lastRendered) {
399
- console.log(snapshot.rendered);
400
- lastRendered = snapshot.rendered;
401
- }
402
- }
403
- rl?.close();
404
- }
405
- return { ...snapshot, steered, detached };
406
- }
407
-
408
- // packages/cli/src/commands/run.ts
409
- function shouldPromptForEpicSelection(context, command, promptEpic, noEpicPrompt) {
410
- if (noEpicPrompt) {
411
- return false;
412
- }
413
- if (promptEpic) {
414
- return true;
415
- }
416
- if (command !== "start-serial") {
417
- return false;
418
- }
419
- return context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY;
420
- }
421
- async function promptForEpicSelection(projectRoot, command) {
422
- const epics = listOpenEpics(projectRoot);
423
- const defaultEpic = await resolveDefaultEpic(projectRoot);
424
- const options = epics.map((epic) => epic.id);
425
- if (defaultEpic && !options.includes(defaultEpic)) {
426
- options.unshift(defaultEpic);
427
- }
428
- if (options.length === 0) {
429
- throw new CliError2("No open epic found. Pass --epic <id>.");
430
- }
431
- console.log(`Select epic for run ${command}:`);
432
- options.forEach((id, index) => {
433
- const metadata = epics.find((epic) => epic.id === id);
434
- const details = [
435
- metadata?.priority !== undefined ? `priority:${metadata.priority}` : "",
436
- metadata?.createdAt ? `created:${metadata.createdAt.slice(0, 10)}` : "",
437
- id === defaultEpic ? "default" : ""
438
- ].filter(Boolean).join(" ");
439
- const suffix = details ? ` (${details})` : "";
440
- console.log(` ${index + 1}. ${id}${suffix}`);
441
- });
442
- const fallback = defaultEpic || options[0];
443
- const rl = createInterface2({ input: process.stdin, output: process.stdout });
444
- try {
445
- while (true) {
446
- const answer = (await rl.question(`Epic [1-${options.length}] or id (Enter for ${fallback}, q to cancel): `)).trim();
447
- if (!answer) {
448
- return fallback ?? options[0];
449
- }
450
- if (answer === "q" || answer === "quit") {
451
- throw new CliError2("Run cancelled by user.");
452
- }
453
- if (/^\d+$/.test(answer)) {
454
- const index = Number.parseInt(answer, 10) - 1;
455
- if (index >= 0 && index < options.length) {
456
- return options[index];
457
- }
458
- }
459
- if (options.includes(answer)) {
460
- return answer;
461
- }
462
- console.log("Invalid selection. Choose a listed number, exact epic id, or q to cancel.");
463
- }
464
- } finally {
465
- rl.close();
466
- }
467
- }
468
- async function executeRun(context, args) {
469
- const [command = "status", ...rest] = args;
470
- const runtimeContext = loadRuntimeContextFromEnv2() ?? undefined;
471
- switch (command) {
472
- case "list": {
473
- requireNoExtraArgs(rest, "bun run rig run list");
474
- const runs = listAuthorityRuns(context.projectRoot);
475
- if (context.outputMode === "text") {
476
- if (runs.length === 0) {
477
- console.log("No runs recorded in .rig/runs.");
478
- } else {
479
- for (const run of runs) {
480
- console.log(`- ${run.runId} \xB7 ${run.status} \xB7 ${run.title}`);
481
- }
482
- }
483
- }
484
- return { ok: true, group: "run", command, details: { runs } };
485
- }
486
- case "delete": {
487
- let pending = rest;
488
- const run = takeOption(pending, "--run");
489
- pending = run.rest;
490
- const purgeArtifacts = takeFlag(pending, "--purge-artifacts");
491
- pending = purgeArtifacts.rest;
492
- requireNoExtraArgs(pending, "bun run rig run delete --run <id> [--purge-artifacts]");
493
- if (!run.value) {
494
- throw new CliError2("run delete requires --run <id>.");
495
- }
496
- const result = await deleteRunState(context.projectRoot, {
497
- runId: run.value,
498
- purgeRuntime: true,
499
- purgeTaskArtifacts: purgeArtifacts.value
500
- });
501
- if (context.outputMode === "text") {
502
- console.log(`Deleted run ${result.runId}`);
503
- if (result.runtimeIds.length > 0) {
504
- console.log(`Cleaned runtimes: ${result.runtimeIds.join(", ")}`);
505
- }
506
- if (result.taskArtifactsDeleted) {
507
- console.log(`Cleared task artifacts for ${result.taskId}`);
508
- }
509
- }
510
- return { ok: true, group: "run", command, details: result };
511
- }
512
- case "cleanup": {
513
- let pending = rest;
514
- const all = takeFlag(pending, "--all");
515
- pending = all.rest;
516
- const keepArtifacts = takeFlag(pending, "--keep-artifacts");
517
- pending = keepArtifacts.rest;
518
- const keepRuntimes = takeFlag(pending, "--keep-runtimes");
519
- pending = keepRuntimes.rest;
520
- const keepQueue = takeFlag(pending, "--keep-queue");
521
- pending = keepQueue.rest;
522
- requireNoExtraArgs(pending, "bun run rig run cleanup --all [--keep-artifacts] [--keep-runtimes] [--keep-queue]");
523
- if (!all.value) {
524
- throw new CliError2("run cleanup currently requires --all.");
525
- }
526
- const result = await cleanupRunState(context.projectRoot, {
527
- includeArtifacts: !keepArtifacts.value,
528
- includeRuntimes: !keepRuntimes.value,
529
- includeQueue: !keepQueue.value
530
- });
531
- if (context.outputMode === "text") {
532
- console.log(`Deleted runs: ${result.runIds.length}`);
533
- console.log(`Cleaned runtimes: ${result.runtimeIds.length}`);
534
- console.log(`Artifacts cleared: ${result.artifactsCleared ? "yes" : "no"}`);
535
- console.log(`Queue cleared: ${result.queueCleared ? "yes" : "no"}`);
536
- }
537
- return { ok: true, group: "run", command, details: result };
538
- }
539
- case "show": {
540
- let pending = rest;
541
- const run = takeOption(pending, "--run");
542
- pending = run.rest;
543
- requireNoExtraArgs(pending, "bun run rig run show --run <id>");
544
- if (!run.value) {
545
- throw new CliError2("run show requires --run <id>.");
546
- }
547
- const record = readAuthorityRun(context.projectRoot, run.value);
548
- if (!record) {
549
- throw new CliError2(`Run not found: ${run.value}`, 2);
550
- }
551
- if (context.outputMode === "text") {
552
- console.log(JSON.stringify(record, null, 2));
553
- }
554
- return { ok: true, group: "run", command, details: record };
555
- }
556
- case "timeline": {
557
- let pending = rest;
558
- const run = takeOption(pending, "--run");
559
- pending = run.rest;
560
- const follow = takeFlag(pending, "--follow");
561
- pending = follow.rest;
562
- requireNoExtraArgs(pending, "bun run rig run timeline --run <id> [--follow]");
563
- if (!run.value) {
564
- throw new CliError2("run timeline requires --run <id>.");
565
- }
566
- const timelinePath = resolve3(resolveAuthorityRunDir(context.projectRoot, run.value), "timeline.jsonl");
567
- const printEvents = () => {
568
- const events2 = readJsonlFile(timelinePath);
569
- if (context.outputMode === "text") {
570
- for (const event of events2) {
571
- console.log(JSON.stringify(event));
572
- }
573
- }
574
- return events2;
575
- };
576
- const events = printEvents();
577
- if (follow.value && context.outputMode === "text") {
578
- let lastLength = existsSync3(timelinePath) ? readFileSync3(timelinePath, "utf8").length : 0;
579
- while (true) {
580
- await Bun.sleep(1000);
581
- if (!existsSync3(timelinePath))
582
- continue;
583
- const next = readFileSync3(timelinePath, "utf8");
584
- if (next.length <= lastLength)
585
- continue;
586
- const delta = next.slice(lastLength);
587
- lastLength = next.length;
588
- for (const line of delta.split(/\r?\n/).map((entry) => entry.trim()).filter(Boolean)) {
589
- console.log(line);
590
- }
591
- }
592
- }
593
- return { ok: true, group: "run", command, details: { runId: run.value, events } };
594
- }
595
- case "attach": {
596
- let pending = rest;
597
- const runOption = takeOption(pending, "--run");
598
- pending = runOption.rest;
599
- const messageOption = takeOption(pending, "--message");
600
- pending = messageOption.rest;
601
- const once = takeFlag(pending, "--once");
602
- pending = once.rest;
603
- const follow = takeFlag(pending, "--follow");
604
- pending = follow.rest;
605
- const pollMs = takeOption(pending, "--poll-ms");
606
- pending = pollMs.rest;
607
- const positionalRunId = pending.length > 0 ? pending[0] : undefined;
608
- const extra = positionalRunId ? pending.slice(1) : pending;
609
- requireNoExtraArgs(extra, "bun run rig run attach <run-id>|--run <run-id> [--message <text>] [--once|--follow] [--poll-ms <ms>]");
610
- const runId = runOption.value ?? positionalRunId;
611
- if (!runId) {
612
- throw new CliError2("run attach requires a run id.", 2);
613
- }
614
- const attached = await attachRunOperatorView(context, {
615
- runId,
616
- message: messageOption.value ?? null,
617
- once: once.value,
618
- follow: follow.value,
619
- pollMs: parsePositiveInt(pollMs.value, "--poll-ms", 2000)
620
- });
621
- return { ok: true, group: "run", command, details: attached };
622
- }
623
- case "status": {
624
- requireNoExtraArgs(rest, "bun run rig run status");
625
- if (context.dryRun) {
626
- if (context.outputMode === "text") {
627
- console.log("[dry-run] rig run status");
628
- }
629
- return { ok: true, group: "run", command };
630
- }
631
- const summary = runStatus(context.projectRoot, runtimeContext);
632
- if (context.outputMode === "text") {
633
- console.log(`Active runs: ${summary.activeRuns.length}`);
634
- for (const run of summary.activeRuns) {
635
- console.log(`- ${run.runId} \xB7 ${run.status} \xB7 ${run.taskId ?? run.title}`);
636
- }
637
- if (summary.recentRuns.length > 0) {
638
- console.log("");
639
- console.log("Recent runs:");
640
- for (const run of summary.recentRuns) {
641
- console.log(`- ${run.runId} \xB7 ${run.status} \xB7 ${run.taskId ?? run.title}`);
642
- }
643
- }
644
- }
645
- return { ok: true, group: "run", command, details: summary };
646
- }
647
- case "start":
648
- case "start-serial":
649
- case "start-parallel": {
650
- let pending = rest;
651
- const epicResult = takeOption(pending, "--epic");
652
- pending = epicResult.rest;
653
- const promptEpicResult = takeFlag(pending, "--prompt-epic");
654
- pending = promptEpicResult.rest;
655
- const noEpicPromptResult = takeFlag(pending, "--no-epic-prompt");
656
- pending = noEpicPromptResult.rest;
657
- const wsPortResult = takeOption(pending, "--ws-port");
658
- pending = wsPortResult.rest;
659
- const serverHostResult = takeOption(pending, "--server-host");
660
- pending = serverHostResult.rest;
661
- const serverPortResult = takeOption(pending, "--server-port");
662
- pending = serverPortResult.rest;
663
- const pollResult = takeOption(pending, "--poll-ms");
664
- pending = pollResult.rest;
665
- const noServerResult = takeFlag(pending, "--no-server");
666
- pending = noServerResult.rest;
667
- requireNoExtraArgs(pending, "bun run rig run start [--epic <id>] [--prompt-epic|--no-epic-prompt] [--ws-port <n>] [--server-host <host>] [--server-port <n>] [--poll-ms <n>] [--no-server]");
668
- if (promptEpicResult.value && noEpicPromptResult.value) {
669
- throw new CliError2("Cannot use --prompt-epic and --no-epic-prompt together.");
670
- }
671
- if (promptEpicResult.value && (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY)) {
672
- throw new CliError2("--prompt-epic requires an interactive terminal (TTY) in text mode.");
673
- }
674
- let resolvedEpicId = epicResult.value || undefined;
675
- if (!resolvedEpicId && shouldPromptForEpicSelection(context, command, promptEpicResult.value, noEpicPromptResult.value)) {
676
- resolvedEpicId = await promptForEpicSelection(context.projectRoot, command);
677
- }
678
- const defaults = defaultStartRunOptions(command === "start-parallel" ? "parallel" : "serial");
679
- const result = await startRun(context.projectRoot, {
680
- mode: command === "start-parallel" ? "parallel" : "serial",
681
- workers: defaults.workers,
682
- epicId: resolvedEpicId,
683
- wsPort: parsePositiveInt(wsPortResult.value, "--ws-port", defaults.wsPort),
684
- startEventServer: noServerResult.value ? false : defaults.startEventServer,
685
- serverHost: serverHostResult.value || defaults.serverHost,
686
- serverPort: parsePositiveInt(serverPortResult.value, "--server-port", defaults.serverPort),
687
- serverPollMs: parsePositiveInt(pollResult.value, "--poll-ms", defaults.serverPollMs),
688
- dryRun: context.dryRun,
689
- runtimeContext
690
- });
691
- if (context.outputMode === "text") {
692
- console.log(`Epic: ${result.epicId}`);
693
- console.log(`Server: ${result.baseUrl}`);
694
- if (result.eventServerUrl) {
695
- console.log(`Events: ${result.eventServerUrl}`);
696
- }
697
- console.log(`Runs: ${result.runIds.join(", ")}`);
698
- }
699
- if (result.exitCode !== 0) {
700
- throw new CliError2(`run ${command} failed with exit code ${result.exitCode}.`, result.exitCode);
701
- }
702
- return {
703
- ok: true,
704
- group: "run",
705
- command,
706
- details: {
707
- epicId: result.epicId,
708
- baseUrl: result.baseUrl,
709
- runIds: result.runIds,
710
- eventServerUrl: result.eventServerUrl || null
711
- }
712
- };
713
- }
714
- case "resume": {
715
- requireNoExtraArgs(rest, "bun run rig run resume");
716
- if (context.dryRun) {
717
- if (context.outputMode === "text") {
718
- console.log("[dry-run] rig run resume");
719
- }
720
- return { ok: true, group: "run", command };
721
- }
722
- const resumed = await runResume(context.projectRoot, runtimeContext);
723
- if (context.outputMode === "text") {
724
- console.log(`Resumed run: ${resumed.runId}`);
725
- }
726
- return { ok: true, group: "run", command, details: resumed };
727
- }
728
- case "stop": {
729
- const runOption = takeOption(rest, "--run");
730
- const positionalRunId = runOption.rest.length > 0 ? runOption.rest[0] : undefined;
731
- const extra = positionalRunId ? runOption.rest.slice(1) : runOption.rest;
732
- requireNoExtraArgs(extra, "bun run rig run stop [<run-id>|--run <id>]");
733
- const runId = runOption.value ?? positionalRunId;
734
- if (context.dryRun) {
735
- return {
736
- ok: true,
737
- group: "run",
738
- command,
739
- details: runId ? { runId, accepted: true } : { stopped: 0, remaining: [] }
740
- };
741
- }
742
- if (runId) {
743
- const stopped = await stopRunViaServer(context, runId);
744
- if (context.outputMode === "text")
745
- console.log(`Stop requested: ${runId}`);
746
- return { ok: true, group: "run", command, details: stopped };
747
- }
748
- const result = await runStop(context.projectRoot);
749
- if (result.remaining.length > 0) {
750
- throw new CliError2(`Failed to stop run(s): ${result.remaining.join(", ")}`, 1);
751
- }
752
- if (context.outputMode === "text") {
753
- console.log(`Stopped process count: ${result.stopped}`);
754
- }
755
- return {
756
- ok: true,
757
- group: "run",
758
- command,
759
- details: {
760
- stopped: result.stopped,
761
- remaining: result.remaining
762
- }
763
- };
764
- }
765
- default:
766
- throw new CliError2(`Unknown run command: ${command}`);
767
- }
768
- }
769
- export {
770
- executeRun
771
- };