@h-rig/cli 0.0.6-alpha.11 → 0.0.6-alpha.111

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