@h-rig/cli 0.0.6-alpha.90 → 0.0.6-alpha.91

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 (118) hide show
  1. package/README.md +18 -19
  2. package/dist/bin/build-rig-binaries.js +22 -10
  3. package/dist/bin/rig.d.ts +71 -1
  4. package/dist/bin/rig.js +15078 -11169
  5. package/dist/config/rig-default-config.yml +5 -0
  6. package/dist/src/app/drone-ui.d.ts +11 -14
  7. package/dist/src/app/drone-ui.js +70 -86
  8. package/dist/src/commands/_async-ui.d.ts +1 -4
  9. package/dist/src/commands/_async-ui.js +9 -111
  10. package/dist/src/commands/_cli-format.d.ts +16 -9
  11. package/dist/src/commands/_cli-format.js +167 -295
  12. package/dist/src/commands/_connection-state.d.ts +11 -1
  13. package/dist/src/commands/_connection-state.js +50 -5
  14. package/dist/src/commands/_doctor-checks.d.ts +0 -6
  15. package/dist/src/commands/_doctor-checks.js +79 -382
  16. package/dist/src/commands/_help-catalog.d.ts +1 -1
  17. package/dist/src/commands/_help-catalog.js +217 -157
  18. package/dist/src/commands/_inprocess-services.d.ts +33 -0
  19. package/dist/src/commands/_inprocess-services.js +102 -0
  20. package/dist/src/commands/_json-output.js +4 -0
  21. package/dist/src/commands/_lazy-reconcile.d.ts +34 -0
  22. package/dist/src/commands/_lazy-reconcile.js +102 -0
  23. package/dist/src/commands/_paths.js +1 -1
  24. package/dist/src/commands/_pi-frontend.d.ts +18 -10
  25. package/dist/src/commands/_pi-frontend.js +37 -715
  26. package/dist/src/commands/_pi-install.js +18 -36
  27. package/dist/src/commands/_policy.d.ts +1 -1
  28. package/dist/src/commands/_policy.js +56 -15
  29. package/dist/src/commands/_run-bridge.d.ts +114 -0
  30. package/dist/src/commands/_run-bridge.js +387 -0
  31. package/dist/src/commands/_run-diagnostics.d.ts +9 -0
  32. package/dist/src/commands/_run-diagnostics.js +51 -0
  33. package/dist/src/commands/_run-driver-helpers.d.ts +8 -81
  34. package/dist/src/commands/_run-driver-helpers.js +79 -283
  35. package/dist/src/commands/_run-projection.d.ts +50 -0
  36. package/dist/src/commands/_run-projection.js +349 -0
  37. package/dist/src/commands/_run-subcommands.d.ts +3 -0
  38. package/dist/src/commands/_run-subcommands.js +31 -0
  39. package/dist/src/commands/_spinner.js +1 -1
  40. package/dist/src/commands/agent.d.ts +1 -1
  41. package/dist/src/commands/agent.js +8559 -239
  42. package/dist/src/commands/dist.d.ts +1 -1
  43. package/dist/src/commands/dist.js +27 -19
  44. package/dist/src/commands/doctor.d.ts +1 -1
  45. package/dist/src/commands/doctor.js +93 -475
  46. package/dist/src/commands/github.d.ts +1 -1
  47. package/dist/src/commands/github.js +113 -387
  48. package/dist/src/commands/inbox.d.ts +22 -24
  49. package/dist/src/commands/inbox.js +420 -691
  50. package/dist/src/commands/init.d.ts +6 -16
  51. package/dist/src/commands/init.js +334 -971
  52. package/dist/src/commands/inspect.d.ts +19 -2
  53. package/dist/src/commands/inspect.js +644 -610
  54. package/dist/src/commands/pi.d.ts +1 -1
  55. package/dist/src/commands/plugin.d.ts +1 -1
  56. package/dist/src/commands/plugin.js +486 -7
  57. package/dist/src/commands/profile-and-review.d.ts +1 -1
  58. package/dist/src/commands/profile-and-review.js +94 -56
  59. package/dist/src/commands/queue.js +1 -21
  60. package/dist/src/commands/remote.d.ts +1 -1
  61. package/dist/src/commands/remote.js +837 -14
  62. package/dist/src/commands/repo-git-harness.d.ts +1 -1
  63. package/dist/src/commands/repo-git-harness.js +57 -14
  64. package/dist/src/commands/run.d.ts +20 -2
  65. package/dist/src/commands/run.js +17579 -1759
  66. package/dist/src/commands/server.d.ts +2 -6
  67. package/dist/src/commands/server.js +141 -723
  68. package/dist/src/commands/setup.d.ts +1 -1
  69. package/dist/src/commands/setup.js +102 -484
  70. package/dist/src/commands/stats.d.ts +13 -10
  71. package/dist/src/commands/stats.js +689 -761
  72. package/dist/src/commands/task-run-driver.d.ts +50 -88
  73. package/dist/src/commands/task-run-driver.js +116 -2717
  74. package/dist/src/commands/task.d.ts +34 -13
  75. package/dist/src/commands/task.js +668 -2523
  76. package/dist/src/commands/test.d.ts +1 -1
  77. package/dist/src/commands/triage.d.ts +11 -0
  78. package/dist/src/commands/triage.js +227 -0
  79. package/dist/src/commands/workspace.d.ts +1 -1
  80. package/dist/src/commands.d.ts +0 -16
  81. package/dist/src/commands.js +16657 -12250
  82. package/dist/src/index.js +16528 -12497
  83. package/dist/src/launcher.js +4 -0
  84. package/dist/src/operator-cli.d.ts +2 -0
  85. package/dist/src/operator-cli.js +17837 -0
  86. package/dist/src/operator-entry.d.ts +1 -0
  87. package/dist/src/operator-entry.js +3 -0
  88. package/package.json +18 -12
  89. package/dist/src/app/board.d.ts +0 -23
  90. package/dist/src/app/board.js +0 -1786
  91. package/dist/src/app/theme.d.ts +0 -47
  92. package/dist/src/app/theme.js +0 -150
  93. package/dist/src/commands/_authority-runs.d.ts +0 -22
  94. package/dist/src/commands/_authority-runs.js +0 -110
  95. package/dist/src/commands/_operator-surface.d.ts +0 -34
  96. package/dist/src/commands/_operator-surface.js +0 -220
  97. package/dist/src/commands/_operator-view.d.ts +0 -30
  98. package/dist/src/commands/_operator-view.js +0 -1070
  99. package/dist/src/commands/_preflight.d.ts +0 -22
  100. package/dist/src/commands/_preflight.js +0 -540
  101. package/dist/src/commands/_run-replay.d.ts +0 -24
  102. package/dist/src/commands/_run-replay.js +0 -142
  103. package/dist/src/commands/_server-client.d.ts +0 -186
  104. package/dist/src/commands/_server-client.js +0 -681
  105. package/dist/src/commands/_snapshot-upload.d.ts +0 -39
  106. package/dist/src/commands/_snapshot-upload.js +0 -455
  107. package/dist/src/commands/_task-picker.d.ts +0 -9
  108. package/dist/src/commands/_task-picker.js +0 -201
  109. package/dist/src/commands/browser.d.ts +0 -65
  110. package/dist/src/commands/browser.js +0 -1173
  111. package/dist/src/commands/connect.d.ts +0 -7
  112. package/dist/src/commands/connect.js +0 -419
  113. package/dist/src/commands/inspector.d.ts +0 -3
  114. package/dist/src/commands/inspector.js +0 -263
  115. package/dist/src/commands/task-report-bug.d.ts +0 -19
  116. package/dist/src/commands/task-report-bug.js +0 -1281
  117. package/dist/src/report-bug.d.ts +0 -44
  118. package/dist/src/report-bug.js +0 -260
@@ -1,284 +1,9 @@
1
1
  // @bun
2
- // packages/cli/src/commands/task.ts
3
- import { readFileSync as readFileSync4 } from "fs";
4
- import { spawnSync } from "child_process";
5
- import { resolve as resolve3 } from "path";
6
-
7
- // packages/cli/src/app/drone-ui.ts
8
- import { ProcessTerminal, TUI, Text, Input, SelectList, matchesKey } from "@earendil-works/pi-tui";
9
-
10
- // packages/cli/src/app/theme.ts
11
- var RIG_PALETTE = {
12
- ink: "#f2f3f6",
13
- ink2: "#aeb0ba",
14
- ink3: "#6c6e79",
15
- ink4: "#44464f",
16
- accent: "#ccff4d",
17
- accentDim: "#a9d63f",
18
- cyan: "#56d8ff",
19
- red: "#ff5d5d",
20
- yellow: "#ffd24d"
21
- };
22
- function hexToRgb(hex) {
23
- const value = hex.replace("#", "");
24
- return [
25
- Number.parseInt(value.slice(0, 2), 16),
26
- Number.parseInt(value.slice(2, 4), 16),
27
- Number.parseInt(value.slice(4, 6), 16)
28
- ];
29
- }
30
- function fg(hex) {
31
- const [r, g, b] = hexToRgb(hex);
32
- return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
33
- }
34
- var ink = fg(RIG_PALETTE.ink);
35
- var ink2 = fg(RIG_PALETTE.ink2);
36
- var ink3 = fg(RIG_PALETTE.ink3);
37
- var ink4 = fg(RIG_PALETTE.ink4);
38
- var accent = fg(RIG_PALETTE.accent);
39
- var accentDim = fg(RIG_PALETTE.accentDim);
40
- var cyan = fg(RIG_PALETTE.cyan);
41
- var red = fg(RIG_PALETTE.red);
42
- var yellow = fg(RIG_PALETTE.yellow);
43
- function bold(text) {
44
- return `\x1B[1m${text}\x1B[22m`;
45
- }
46
- var DRONE_ART = [
47
- " .-=-. .-=-. ",
48
- " ( !!! ) ( !!! ) ",
49
- " '-=-'._ _.'-=-' ",
50
- " '._ _.' ",
51
- " '=$$$$$$$=.' ",
52
- " =$$$$$$$$$$$= ",
53
- " $$$@@@@@@@@@@$$$ ",
54
- " $$$@@ @@$$$ ",
55
- " $$@ ? @$$$ ",
56
- " $$$@ '-' @$$$ ",
57
- " $$$@@ @@$$$ ",
58
- " $$$@@@@@@@@@@$$$ ",
59
- " =$$$$$$$$$$$= ",
60
- " '=$$$$$$$=.' ",
61
- " _.' '._ ",
62
- " .-=-.' '.-=-. ",
63
- " ( !!! ) ( !!! ) ",
64
- " '-=-' '-=-' "
65
- ];
66
- var EYE_FRAMES = ["@", "o", "."];
67
- var DRONE_WIDTH = DRONE_ART[0].length;
68
- var DRONE_HEIGHT = DRONE_ART.length;
69
- var MICRO_BLADES = ["---", "\\\\\\", "|||", "///"];
70
- function microDroneFrame(tick) {
71
- const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
72
- const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
73
- return `(${blade})${eye}(${blade})`;
74
- }
75
- var MICRO_DRONE_FRAMES = Array.from({ length: 12 }, (_, index) => microDroneFrame(index));
76
- function renderMicroDroneFrame(tick) {
77
- const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
78
- const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
79
- return `${ink4("(")}${cyan(blade)}${ink4(")")}${bold(accent(eye))}${ink4("(")}${cyan(blade)}${ink4(")")}`;
80
- }
81
-
82
- // packages/cli/src/commands/_spinner.ts
83
- var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
84
- function createTtySpinner(input) {
85
- const output = input.output ?? process.stdout;
86
- const isTty = output.isTTY === true;
87
- const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
88
- let label = input.label;
89
- let frame = 0;
90
- let paused = false;
91
- let stopped = false;
92
- let lastPrintedLabel = "";
93
- const render = () => {
94
- if (stopped || paused)
95
- return;
96
- if (!isTty) {
97
- if (label !== lastPrintedLabel) {
98
- output.write(`${label}
99
- `);
100
- lastPrintedLabel = label;
101
- }
102
- return;
103
- }
104
- frame = (frame + 1) % frames.length;
105
- const glyph = frames[frame] ?? frames[0] ?? "";
106
- output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
107
- };
108
- const clearLine = () => {
109
- if (isTty)
110
- output.write("\r\x1B[2K");
111
- };
112
- render();
113
- const timer = isTty ? setInterval(render, input.intervalMs ?? 120) : null;
114
- return {
115
- setLabel(next) {
116
- label = next;
117
- render();
118
- },
119
- pause() {
120
- paused = true;
121
- clearLine();
122
- },
123
- resume() {
124
- if (stopped)
125
- return;
126
- paused = false;
127
- render();
128
- },
129
- stop(finalLine) {
130
- if (stopped)
131
- return;
132
- stopped = true;
133
- if (timer)
134
- clearInterval(timer);
135
- clearLine();
136
- if (finalLine)
137
- output.write(`${finalLine}
138
- `);
139
- }
140
- };
141
- }
142
-
143
- // packages/cli/src/app/drone-ui.ts
144
- var isTty = () => Boolean(process.stdout.isTTY);
145
- function droneNote(message, title) {
146
- if (title)
147
- console.log(` ${accentDim("\u25C7")} ${bold(ink2(title))}`);
148
- for (const line of message.split(`
149
- `)) {
150
- console.log(` ${ink4("\u2502")} ${line}`);
151
- }
152
- }
153
- function droneCancel(text) {
154
- console.log(` ${red("\u2716")} ${ink3(text)}`);
155
- }
156
- var SELECT_THEME = {
157
- selectedPrefix: (text) => accent(text),
158
- selectedText: (text) => bold(ink(text)),
159
- description: (text) => ink3(text),
160
- scrollInfo: (text) => ink4(text),
161
- noMatch: (text) => ink3(text)
162
- };
163
- async function runMiniTui(build) {
164
- const terminal = new ProcessTerminal;
165
- const tui = new TUI(terminal);
166
- let settled = false;
167
- return await new Promise((resolve) => {
168
- const finish = (result) => {
169
- if (settled)
170
- return;
171
- settled = true;
172
- tui.stop();
173
- resolve(result);
174
- };
175
- build(tui, finish);
176
- tui.start();
177
- });
178
- }
179
- async function droneSelect(input) {
180
- if (!isTty() || input.options.length === 0) {
181
- return input.initialValue ?? input.options[0]?.value ?? null;
182
- }
183
- return runMiniTui((tui, finish) => {
184
- tui.addChild(new Text(` ${accent("\u258D")}${bold(ink(input.message))}`));
185
- const items = input.options.map((option) => ({
186
- value: option.value,
187
- label: option.label,
188
- ...option.hint ? { description: option.hint } : {}
189
- }));
190
- const list = new SelectList(items, Math.min(items.length, 12), SELECT_THEME);
191
- const initialIndex = input.initialValue ? items.findIndex((item) => item.value === input.initialValue) : -1;
192
- if (initialIndex > 0)
193
- list.setSelectedIndex(initialIndex);
194
- list.onSelect = (item) => finish(item.value);
195
- list.onCancel = () => finish(null);
196
- tui.addChild(list);
197
- tui.addChild(new Text(ink4(" \u2191\u2193 navigate \xB7 enter select \xB7 esc cancel")));
198
- tui.setFocus(list);
199
- tui.addInputListener((data) => {
200
- if (matchesKey(data, "ctrl+c") || matchesKey(data, "escape")) {
201
- finish(null);
202
- return { consume: true };
203
- }
204
- return;
205
- });
206
- });
207
- }
208
- async function droneConfirm(input) {
209
- const answer = await droneSelect({
210
- message: input.message,
211
- options: [
212
- { value: "yes", label: "Yes" },
213
- { value: "no", label: "No" }
214
- ],
215
- initialValue: input.initialValue === false ? "no" : "yes"
216
- });
217
- return answer === null ? null : answer === "yes";
218
- }
219
-
220
- // packages/cli/src/runner.ts
221
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
222
- import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
223
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
224
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
225
-
226
- class CliError extends RuntimeCliError {
227
- hint;
228
- constructor(message, exitCode = 1, options = {}) {
229
- super(message, exitCode);
230
- if (options.hint?.trim()) {
231
- this.hint = options.hint.trim();
232
- }
233
- }
234
- }
235
- function takeFlag(args, flag) {
236
- const rest = [];
237
- let value = false;
238
- for (const arg of args) {
239
- if (arg === flag) {
240
- value = true;
241
- continue;
242
- }
243
- rest.push(arg);
244
- }
245
- return { value, rest };
246
- }
247
- function takeOption(args, option) {
248
- const rest = [];
249
- let value;
250
- for (let index = 0;index < args.length; index += 1) {
251
- const current = args[index];
252
- if (current === option) {
253
- const next = args[index + 1];
254
- if (!next || next.startsWith("-")) {
255
- throw new CliError(`Missing value for ${option}`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} <value>\`.` });
256
- }
257
- value = next;
258
- index += 1;
259
- continue;
260
- }
261
- if (current !== undefined) {
262
- rest.push(current);
263
- }
264
- }
265
- return { value, rest };
266
- }
267
- function requireNoExtraArgs(args, usage) {
268
- if (args.length > 0) {
269
- throw new CliError(`Unexpected arguments: ${args.join(" ")}
270
- Usage: ${usage}`);
271
- }
272
- }
273
- function requireTask(taskId, usage) {
274
- if (!taskId) {
275
- throw new CliError(`Missing --task option.
276
- Usage: ${usage}`);
277
- }
278
- return taskId;
279
- }
2
+ var __require = import.meta.require;
280
3
 
281
4
  // packages/cli/src/commands/task.ts
5
+ import { createPluginHost as createPluginHost2, selectNextReadyTaskByPriority } from "@rig/core";
6
+ import { loadConfig as loadConfig2 } from "@rig/core/load-config";
282
7
  import {
283
8
  taskArtifactDir,
284
9
  taskArtifacts,
@@ -290,1911 +15,394 @@ import {
290
15
  taskRecord,
291
16
  taskReopen,
292
17
  taskScope,
293
- taskStatus as taskStatus2,
18
+ taskStatus,
294
19
  taskValidate,
295
20
  taskVerify
296
21
  } from "@rig/runtime/control-plane/native/task-ops";
297
22
 
298
- // packages/cli/src/commands/_authority-runs.ts
299
- import {
300
- readAuthorityRun,
301
- readJsonlFile,
302
- writeAuthorityRunRecord
303
- } from "@rig/runtime/control-plane/authority-files";
304
-
305
- // packages/cli/src/commands/_paths.ts
306
- import { resolveMonorepoRoot } from "@rig/runtime/control-plane/native/utils";
307
-
308
- // packages/cli/src/commands/_authority-runs.ts
309
- function normalizeRuntimeAdapter(value) {
310
- const normalized = value?.trim().toLowerCase();
311
- if (!normalized) {
312
- return "pi";
313
- }
314
- if (normalized === "codex" || normalized === "codex-cli" || normalized === "codex-app-server" || normalized === "gpt-codex") {
315
- return "codex";
316
- }
317
- if (normalized === "pi" || normalized === "rig-pi" || normalized === "@rig/pi") {
318
- return "pi";
319
- }
320
- return "claude-code";
321
- }
322
-
323
- // packages/cli/src/commands/_preflight.ts
324
- import { ensureProjectMainFreshBeforeRun } from "@rig/runtime/control-plane/project-main-pre-run-sync";
325
-
326
- // packages/cli/src/commands/_connection-state.ts
327
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
328
- import { homedir } from "os";
329
- import { dirname, resolve } from "path";
330
- function resolveGlobalConnectionsPath(env = process.env) {
331
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
332
- if (explicit)
333
- return resolve(explicit);
334
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
335
- if (stateDir)
336
- return resolve(stateDir, "connections.json");
337
- return resolve(homedir(), ".rig", "connections.json");
338
- }
339
- function resolveRepoConnectionPath(projectRoot) {
340
- return resolve(projectRoot, ".rig", "state", "connection.json");
341
- }
342
- function readJsonFile(path) {
343
- if (!existsSync(path))
344
- return null;
345
- try {
346
- return JSON.parse(readFileSync(path, "utf8"));
347
- } catch (error) {
348
- throw new CliError(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1, { hint: "Fix or delete that file, then re-select a server with `rig server use <alias|local>`." });
349
- }
350
- }
351
- function writeJsonFile(path, value) {
352
- mkdirSync(dirname(path), { recursive: true });
353
- writeFileSync(path, `${JSON.stringify(value, null, 2)}
354
- `, "utf8");
355
- }
356
- function normalizeConnection(value) {
357
- if (!value || typeof value !== "object" || Array.isArray(value))
358
- return null;
359
- const record = value;
360
- if (record.kind === "local")
361
- return { kind: "local", mode: "auto" };
362
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
363
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
364
- return { kind: "remote", baseUrl };
365
- }
366
- return null;
367
- }
368
- function readGlobalConnections(options = {}) {
369
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
370
- const payload = readJsonFile(path);
371
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
372
- return { connections: {} };
373
- }
374
- const rawConnections = payload.connections;
375
- const connections = {};
376
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
377
- for (const [alias, raw] of Object.entries(rawConnections)) {
378
- const connection = normalizeConnection(raw);
379
- if (connection)
380
- connections[alias] = connection;
381
- }
382
- }
383
- return { connections };
384
- }
385
- function readRepoConnection(projectRoot) {
386
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
387
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
388
- return null;
389
- const record = payload;
390
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
391
- if (!selected)
392
- return null;
393
- return {
394
- selected,
395
- project: typeof record.project === "string" ? record.project : undefined,
396
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
397
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
398
- };
399
- }
400
- function writeRepoConnection(projectRoot, state) {
401
- writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
402
- }
403
- function resolveSelectedConnection(projectRoot, options = {}) {
404
- const repo = readRepoConnection(projectRoot);
405
- if (!repo)
406
- return null;
407
- if (repo.selected === "local")
408
- return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
409
- const global = readGlobalConnections(options);
410
- const connection = global.connections[repo.selected];
411
- if (!connection) {
412
- throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
413
- }
414
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
415
- }
416
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
417
- const repo = readRepoConnection(projectRoot);
418
- if (!repo)
419
- return;
420
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
421
- }
422
-
423
- // packages/cli/src/commands/_server-client.ts
424
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
425
- import { resolve as resolve2 } from "path";
426
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
427
- var scopedGitHubBearerTokens = new Map;
428
- var serverPhaseListener = null;
429
- function setServerPhaseListener(listener) {
430
- const previous = serverPhaseListener;
431
- serverPhaseListener = listener;
432
- return previous;
433
- }
434
- function reportServerPhase(label) {
435
- serverPhaseListener?.(label);
436
- }
437
- function cleanToken(value) {
438
- const trimmed = value?.trim();
439
- return trimmed ? trimmed : null;
440
- }
441
- function readPrivateRemoteSessionToken(projectRoot) {
442
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
443
- if (!existsSync2(path))
444
- return null;
445
- try {
446
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
447
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
448
- } catch {
449
- return null;
450
- }
451
- }
452
- function readGitHubBearerTokenForRemote(projectRoot) {
453
- const scopedKey = resolve2(projectRoot);
454
- if (scopedGitHubBearerTokens.has(scopedKey))
455
- return scopedGitHubBearerTokens.get(scopedKey) ?? null;
456
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
457
- if (privateSession)
458
- return privateSession;
459
- return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
460
- }
461
- function readStoredGitHubAuthToken(projectRoot) {
462
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
463
- if (!existsSync2(path))
464
- return null;
465
- try {
466
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
467
- return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
468
- } catch {
469
- return null;
470
- }
471
- }
472
- function readLocalConnectionFallbackToken(projectRoot) {
473
- return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
474
- }
475
- async function ensureServerForCli(projectRoot) {
476
- try {
477
- const selected = resolveSelectedConnection(projectRoot);
478
- if (selected?.connection.kind === "remote") {
479
- reportServerPhase(`Connecting to ${selected.alias}\u2026`);
480
- const authToken = readGitHubBearerTokenForRemote(projectRoot);
481
- const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
482
- return {
483
- baseUrl: selected.connection.baseUrl,
484
- authToken,
485
- connectionKind: "remote",
486
- serverProjectRoot
487
- };
488
- }
489
- reportServerPhase("Starting local Rig server\u2026");
490
- const connection = await ensureLocalRigServerConnection(projectRoot);
491
- return {
492
- baseUrl: connection.baseUrl,
493
- authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
494
- connectionKind: "local",
495
- serverProjectRoot: resolve2(projectRoot)
496
- };
497
- } catch (error) {
498
- if (error instanceof Error) {
499
- throw new CliError(error.message, 1);
500
- }
501
- throw error;
502
- }
503
- }
504
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
505
- const repo = readRepoConnection(projectRoot);
506
- const slug = repo?.project?.trim();
507
- if (!slug)
508
- return null;
509
- try {
510
- const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
511
- headers: mergeHeaders(undefined, authToken)
512
- });
513
- if (!response.ok)
514
- return null;
515
- const payload = await response.json();
516
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
517
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
518
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
519
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
520
- if (path)
521
- writeRepoServerProjectRoot(projectRoot, path);
522
- return path;
523
- } catch {
524
- return null;
525
- }
526
- }
527
- function appendTaskFilterParams(url, filters) {
528
- if (filters.assignee)
529
- url.searchParams.set("assignee", filters.assignee);
530
- if (filters.state)
531
- url.searchParams.set("state", filters.state);
532
- if (filters.status)
533
- url.searchParams.set("status", filters.status);
534
- if (filters.limit !== undefined)
535
- url.searchParams.set("limit", String(filters.limit));
536
- }
537
- function mergeHeaders(headers, authToken) {
538
- const merged = new Headers(headers);
539
- if (authToken) {
540
- merged.set("authorization", `Bearer ${authToken}`);
541
- }
542
- return merged;
543
- }
544
- function diagnosticMessage(payload) {
545
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
546
- return null;
547
- const record = payload;
548
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
549
- const messages = diagnostics.flatMap((entry) => {
550
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
551
- return [];
552
- const diagnostic = entry;
553
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
554
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
555
- return message ? [`${kind}: ${message}`] : [];
556
- });
557
- return messages.length > 0 ? messages.join("; ") : null;
558
- }
559
- var serverReachabilityCache = new Map;
560
- async function probeServerReachability(baseUrl, authToken) {
561
- try {
562
- const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
563
- headers: mergeHeaders(undefined, authToken),
564
- signal: AbortSignal.timeout(1500)
565
- });
566
- return response.ok;
567
- } catch {
568
- return false;
569
- }
570
- }
571
- function cachedServerReachability(projectRoot, baseUrl, authToken) {
572
- const key = resolve2(projectRoot);
573
- const cached = serverReachabilityCache.get(key);
574
- if (cached)
575
- return cached;
576
- const probe = probeServerReachability(baseUrl, authToken);
577
- serverReachabilityCache.set(key, probe);
578
- return probe;
579
- }
580
- function describeSelectedServer(projectRoot, server) {
581
- try {
582
- const selected = resolveSelectedConnection(projectRoot);
583
- if (selected) {
584
- return {
585
- alias: selected.alias,
586
- target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
587
- };
588
- }
589
- } catch {}
590
- return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
591
- }
592
- async function buildServerFailureContext(projectRoot, server) {
593
- const { alias, target } = describeSelectedServer(projectRoot, server);
594
- const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
595
- const reachability = reachable ? "server is reachable" : "server is unreachable";
596
- return {
597
- contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
598
- hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
599
- };
600
- }
601
- async function requestServerJson(context, pathname, init = {}) {
602
- const server = await ensureServerForCli(context.projectRoot);
603
- const headers = mergeHeaders(init.headers, server.authToken);
604
- if (server.serverProjectRoot)
605
- headers.set("x-rig-project-root", server.serverProjectRoot);
606
- reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
607
- let response;
608
- try {
609
- response = await fetch(`${server.baseUrl}${pathname}`, {
610
- ...init,
611
- headers
612
- });
613
- } catch (error) {
614
- const failure = await buildServerFailureContext(context.projectRoot, server);
615
- throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
616
- ${failure.contextLine}`, 1, { hint: failure.hint });
617
- }
618
- const text = await response.text();
619
- const payload = text.trim().length > 0 ? (() => {
620
- try {
621
- return JSON.parse(text);
622
- } catch {
623
- return null;
624
- }
625
- })() : null;
626
- if (!response.ok) {
627
- const diagnostics = diagnosticMessage(payload);
628
- const rawDetail = diagnostics ?? (text || response.statusText);
629
- const detail = diagnostics ? rawDetail : rawDetail.split(`
630
- `).map((line) => line.trim()).find((line) => line.length > 0)?.slice(0, 200) ?? response.statusText;
631
- const failure = await buildServerFailureContext(context.projectRoot, server);
632
- throw new CliError(`Rig server request failed (${response.status}): ${detail}
633
- ${failure.contextLine}`, 1, { hint: failure.hint });
634
- }
635
- return payload;
636
- }
637
- async function listWorkspaceTasksViaServer(context, filters = {}) {
638
- const url = new URL("http://rig.local/api/workspace/tasks");
639
- appendTaskFilterParams(url, filters);
640
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
641
- if (!Array.isArray(payload)) {
642
- throw new CliError("Rig server returned an invalid task list payload.", 1, { hint: "Check the selected server with `rig server status`; mixed CLI/server versions can mismatch \u2014 try `rig doctor`." });
643
- }
644
- return payload.flatMap((entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? [entry] : []);
645
- }
646
- async function getWorkspaceTaskViaServer(context, taskId) {
647
- const payload = await requestServerJson(context, `/api/workspace/tasks/${encodeURIComponent(taskId)}`);
648
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
649
- return null;
650
- const task = payload.task;
651
- return task && typeof task === "object" && !Array.isArray(task) ? task : null;
652
- }
653
- async function selectNextWorkspaceTaskViaServer(context, filters = {}) {
654
- const url = new URL("http://rig.local/api/workspace/tasks/next");
655
- appendTaskFilterParams(url, filters);
656
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
657
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
658
- throw new CliError("Rig server returned an invalid next-task payload.", 1, { hint: "Check the selected server with `rig server status`; try `rig task list` to see the raw task set." });
659
- }
660
- const record = payload;
661
- const rawTask = record.task;
662
- const task = rawTask && typeof rawTask === "object" && !Array.isArray(rawTask) ? rawTask : null;
663
- const count = typeof record.count === "number" && Number.isFinite(record.count) ? record.count : task ? 1 : 0;
664
- return { task, count };
665
- }
666
- async function getRunDetailsViaServer(context, runId) {
667
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
668
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
669
- }
670
- async function getRunLogsViaServer(context, runId, options = {}) {
671
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
672
- if (options.limit !== undefined)
673
- url.searchParams.set("limit", String(options.limit));
674
- if (options.cursor)
675
- url.searchParams.set("cursor", options.cursor);
676
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
677
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
678
- }
679
- async function getRunTimelineViaServer(context, runId, options = {}) {
680
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
681
- if (options.limit !== undefined)
682
- url.searchParams.set("limit", String(options.limit));
683
- if (options.cursor)
684
- url.searchParams.set("cursor", options.cursor);
685
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
686
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
687
- }
688
- var RESUMABLE_RUN_STATUSES = new Set([
689
- "created",
690
- "preparing",
691
- "running",
692
- "validating",
693
- "reviewing",
694
- "stopped",
695
- "failed",
696
- "needs-attention",
697
- "needs_attention"
698
- ]);
699
- async function stopRunViaServer(context, runId) {
700
- const payload = await requestServerJson(context, "/api/runs/stop", {
701
- method: "POST",
702
- headers: { "content-type": "application/json" },
703
- body: JSON.stringify({ runId })
704
- });
705
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
706
- }
707
- async function steerRunViaServer(context, runId, message) {
708
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
709
- method: "POST",
710
- headers: { "content-type": "application/json" },
711
- body: JSON.stringify({ message })
712
- });
713
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
714
- }
715
- async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
716
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
717
- method: "POST",
718
- headers: { "content-type": "application/json" },
719
- body: JSON.stringify({ text, streamingBehavior })
720
- });
721
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
722
- }
723
- async function submitTaskRunViaServer(context, input) {
724
- const isTaskRun = Boolean(input.taskId);
725
- const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
726
- const payload = await requestServerJson(context, endpoint, {
727
- method: "POST",
728
- headers: {
729
- "content-type": "application/json"
730
- },
731
- body: JSON.stringify({
732
- runId: input.runId,
733
- taskId: input.taskId,
734
- title: input.title,
735
- runtimeAdapter: input.runtimeAdapter,
736
- model: input.model,
737
- runtimeMode: input.runtimeMode,
738
- interactionMode: input.interactionMode,
739
- initialPrompt: input.initialPrompt,
740
- baselineMode: input.baselineMode,
741
- prMode: input.prMode,
742
- executionTarget: "local"
743
- })
744
- });
745
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
746
- throw new CliError("Rig server returned an invalid run submission payload.", 1, { hint: "Check `rig server status` and retry; `rig run list` shows whether the run was created anyway." });
747
- }
748
- const runId = payload.runId;
749
- if (typeof runId !== "string" || runId.trim().length === 0) {
750
- throw new CliError("Rig server returned no runId for the submitted run.", 1, { hint: "Check `rig run list` \u2014 the run may still have been created; otherwise retry the submission." });
751
- }
752
- return { runId };
753
- }
754
-
755
- // packages/cli/src/commands/_preflight.ts
756
- function preflightCheck(id, label, status, detail, remediation) {
757
- return {
758
- id,
759
- label,
760
- status,
761
- ...detail ? { detail } : {},
762
- ...remediation ? { remediation } : {}
763
- };
764
- }
765
- function message(error) {
766
- return error instanceof Error ? error.message : String(error);
767
- }
768
- function isAuthenticated(payload) {
769
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
770
- return false;
771
- const record = payload;
772
- return record.signedIn === true || record.authenticated === true || record.status === "authenticated" || record.ok === true && typeof record.login === "string" && record.login.trim().length > 0;
773
- }
774
- function taskMatchesId(entry, taskId) {
775
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
776
- return false;
777
- const record = entry;
778
- if (record.id === taskId || record.taskId === taskId)
779
- return true;
780
- const raw = record.raw;
781
- if (raw && typeof raw === "object" && !Array.isArray(raw)) {
782
- const rawRecord = raw;
783
- if (String(rawRecord.number ?? "") === taskId.replace(/^#/, ""))
784
- return true;
785
- }
786
- return false;
787
- }
788
- function isActiveRunStatus(status) {
789
- const normalized = String(status ?? "running").toLowerCase();
790
- return !["completed", "complete", "done", "merged", "closed", "failed", "cancelled", "canceled", "needs_attention", "needs-attention", "stopped"].includes(normalized);
791
- }
792
- function permissionAllowsPr(payload) {
793
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
794
- return null;
795
- const record = payload;
796
- if (record.canOpenPullRequest === true || record.pullRequests === true || record.push === true || record.maintain === true || record.admin === true)
797
- return true;
798
- if (record.canOpenPullRequest === false || record.pullRequests === false || record.push === false)
799
- return false;
800
- const permissions = record.permissions;
801
- if (permissions && typeof permissions === "object" && !Array.isArray(permissions)) {
802
- const p = permissions;
803
- if (p.push === true || p.maintain === true || p.admin === true)
804
- return true;
805
- if (p.push === false && p.maintain !== true && p.admin !== true)
806
- return false;
807
- }
808
- return null;
809
- }
810
- function isNotFoundError(error) {
811
- return /\b(404|not found)\b/i.test(message(error));
812
- }
813
- function projectCheckoutReady(payload) {
814
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
815
- return null;
816
- const record = payload;
817
- if (record.checkoutReady === true || record.ready === true)
818
- return true;
819
- if (record.checkoutReady === false || record.ready === false)
820
- return false;
821
- const project = record.project;
822
- if (project && typeof project === "object" && !Array.isArray(project)) {
823
- const checkouts = project.checkouts;
824
- if (Array.isArray(checkouts))
825
- return checkouts.length > 0;
826
- }
827
- return null;
828
- }
829
- function activeDuplicateRun(runs, taskId) {
830
- if (!Array.isArray(runs))
831
- return null;
832
- for (const run of runs) {
833
- if (!run || typeof run !== "object" || Array.isArray(run))
834
- continue;
835
- const record = run;
836
- if ((record.taskId === taskId || record.task === taskId) && isActiveRunStatus(record.status))
837
- return record;
838
- }
839
- return null;
840
- }
841
- async function runFastTaskRunPreflight(context, options = {}) {
842
- const checks = [];
843
- const request = options.requestJson ?? ((pathname, init) => requestServerJson(context, pathname, init));
844
- const taskId = options.taskId?.trim() || null;
845
- const requiresCurrentRunApi = Boolean(taskId);
846
- const selectedServer = options.requestJson ? null : await ensureServerForCli(context.projectRoot).catch(() => null);
847
- const allowLocalLegacyTaskRunCompatibility = selectedServer?.connectionKind === "local";
848
- let legacyServerCompatibility = false;
849
- try {
850
- await request("/api/server/status");
851
- checks.push(preflightCheck("server", "Rig server reachable", "pass"));
852
- } catch (error) {
853
- if (isNotFoundError(error)) {
854
- try {
855
- await request("/health");
856
- legacyServerCompatibility = !requiresCurrentRunApi || allowLocalLegacyTaskRunCompatibility;
857
- checks.push(requiresCurrentRunApi && !allowLocalLegacyTaskRunCompatibility ? preflightCheck("server", "Rig server reachable", "fail", "legacy /health endpoint only; current task-run APIs are required", "Upgrade/select the Rig server before launching a task run.") : preflightCheck("server", "Rig server reachable", "pass", allowLocalLegacyTaskRunCompatibility ? "local legacy /health endpoint; submit endpoint will be authoritative" : "legacy /health endpoint"));
858
- } catch (healthError) {
859
- checks.push(preflightCheck("server", "Rig server reachable", "fail", message(healthError), "Start or select a reachable Rig server."));
860
- }
861
- } else {
862
- checks.push(preflightCheck("server", "Rig server reachable", "fail", message(error), "Start or select a reachable Rig server."));
863
- }
864
- }
865
- const repo = readRepoConnection(context.projectRoot);
866
- checks.push(repo ? preflightCheck("project-link", "project linked to Rig server", repo.project ? "pass" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : ""}`, "Run `rig init --yes --repo owner/repo` to record the GitHub repo slug.") : preflightCheck("project-link", "project linked to Rig server", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
867
- try {
868
- const auth = await request("/api/github/auth/status");
869
- checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
870
- } catch (error) {
871
- checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
872
- }
873
- try {
874
- const projection = await request("/api/workspace/task-projection");
875
- checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
876
- } catch (error) {
877
- checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
878
- }
879
- try {
880
- const permissions = await request("/api/github/repo/permissions");
881
- const allowed = permissionAllowsPr(permissions);
882
- checks.push(allowed === false ? preflightCheck("github-repo-permissions", "GitHub PR permissions", "fail", JSON.stringify(permissions).slice(0, 120), "Grant the selected GitHub token permission to push branches and open PRs.") : preflightCheck("github-repo-permissions", "GitHub PR permissions", allowed === true ? "pass" : "warn", JSON.stringify(permissions).slice(0, 120), "Confirm the selected token can push branches and open PRs."));
883
- } catch (error) {
884
- checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
885
- }
886
- if (repo?.project) {
887
- try {
888
- const project = await request(`/api/projects/${encodeURIComponent(repo.project)}`);
889
- const ready = projectCheckoutReady(project);
890
- checks.push(ready === false ? preflightCheck("remote-checkout", "execution checkout ready", "fail", JSON.stringify(project).slice(0, 120), "Repair the server checkout or rerun `rig init` with a valid checkout strategy.") : preflightCheck("remote-checkout", "execution checkout ready", ready === true ? "pass" : "warn", JSON.stringify(project).slice(0, 120), "Confirm the selected server has a prepared execution checkout."));
891
- } catch (error) {
892
- checks.push(preflightCheck("remote-checkout", "execution checkout ready", "warn", message(error), "Run `rig init` or repair the server checkout before launch."));
893
- }
894
- }
895
- if (taskId) {
896
- try {
897
- const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
898
- const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
899
- checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
900
- } catch (error) {
901
- checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
902
- }
903
- try {
904
- const runs = await request("/api/runs?limit=200");
905
- const duplicate = activeDuplicateRun(runs, taskId);
906
- checks.push(duplicate ? preflightCheck("duplicate-active-run", "one active run per task", "fail", String(duplicate.runId ?? taskId), "Attach to or stop the existing run before starting another one for this task.") : preflightCheck("duplicate-active-run", "one active run per task", "pass", taskId));
907
- } catch (error) {
908
- checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", message(error), "Could not list active runs; the server will still reject conflicting runs if configured."));
909
- }
910
- }
911
- if ((options.runtimeAdapter ?? "pi") === "pi") {
912
- checks.push(preflightCheck("runtime", "worker Pi SDK session daemon", "pass", selectedServer?.connectionKind === "remote" ? "remote worker-owned runtime" : "bundled server-owned runtime"));
913
- } else {
914
- checks.push(preflightCheck("runtime", "runtime adapter", "pass", options.runtimeAdapter));
915
- }
916
- const failures = checks.filter((check) => check.status === "fail");
917
- if (failures.length > 0) {
918
- const summary = failures.map((check) => `${check.label}${check.detail ? `: ${check.detail}` : ""}`).join("; ");
919
- if (failures.some((check) => check.id === "duplicate-active-run") && taskId) {
920
- throw new CliError(`Task ${taskId} already has an active Rig run. ${summary}`, 1, { hint: `Attach to it with \`rig run attach <run-id> --follow\`, or stop it first with \`rig run stop <run-id>\`.` });
921
- }
922
- throw new CliError(`Task run preflight failed: ${summary}`, 1, { hint: "Run `rig doctor` to diagnose, then retry `rig task run`." });
923
- }
924
- return { ok: true, checks };
925
- }
926
- async function runProjectMainSyncPreflight(context, options) {
927
- if (context.dryRun) {
928
- if (context.outputMode === "text" && !options.disabled) {
929
- console.log("[dry-run] project-rig pre-run sync check");
930
- }
931
- return;
932
- }
933
- const result = await ensureProjectMainFreshBeforeRun({
934
- projectRoot: context.projectRoot,
935
- disabled: options.disabled,
936
- runBootstrap: async () => {
937
- const bootstrap = await context.runCommand(["bun", "run", "bootstrap"]);
938
- if (bootstrap.exitCode !== 0) {
939
- throw new CliError(bootstrap.stderr || bootstrap.stdout || "bun run bootstrap failed during project pre-run sync", bootstrap.exitCode || 1);
940
- }
941
- }
942
- });
943
- if (context.outputMode !== "text") {
944
- return;
945
- }
946
- switch (result.status) {
947
- case "disabled":
948
- console.log("Project pre-run sync skipped (--skip-project-sync).");
949
- break;
950
- case "skipped_not_main":
951
- console.log(`Project pre-run sync skipped (current branch: ${result.branch}).`);
952
- break;
953
- case "up_to_date":
954
- break;
955
- case "local_ahead":
956
- console.log(`Project pre-run sync skipped (local main ahead by ${result.localAhead} commit(s)).`);
957
- break;
958
- case "updated":
959
- console.log(`Project pre-run sync updated local main from origin/main (+${result.remoteAhead}) and bootstrapped.`);
960
- break;
961
- }
962
- }
963
-
964
- // packages/cli/src/withMutedConsole.ts
965
- function isPromise(value) {
966
- if (typeof value !== "object" && typeof value !== "function") {
967
- return false;
968
- }
969
- return value !== null && typeof value.then === "function";
970
- }
971
- function withMutedConsole(mute, fn) {
972
- if (!mute) {
973
- return fn();
974
- }
975
- const originalLog = console.log;
976
- const originalWarn = console.warn;
977
- const originalInfo = console.info;
978
- const restore = () => {
979
- console.log = originalLog;
980
- console.warn = originalWarn;
981
- console.info = originalInfo;
982
- };
983
- console.log = () => {};
984
- console.warn = () => {};
985
- console.info = () => {};
986
- try {
987
- const result = fn();
988
- if (isPromise(result)) {
989
- return result.finally(restore);
990
- }
991
- restore();
992
- return result;
993
- } catch (error) {
994
- restore();
995
- throw error;
996
- } finally {
997
- if (console.log === originalLog) {
998
- restore();
999
- }
1000
- }
1001
- }
1002
-
1003
- // packages/cli/src/commands/_operator-surface.ts
1004
- import { createInterface } from "readline";
1005
- import { createInterface as createPromptInterface } from "readline/promises";
1006
- var CANONICAL_STAGES = [
1007
- "Connect",
1008
- "GitHub/task sync",
1009
- "Prepare workspace",
1010
- "Launch Pi",
1011
- "Plan",
1012
- "Implement",
1013
- "Validate",
1014
- "Commit",
1015
- "Open PR",
1016
- "Review/CI",
1017
- "Merge",
1018
- "Complete"
1019
- ];
1020
- function logDetail(log) {
1021
- return typeof log.detail === "string" ? log.detail.trim() : "";
1022
- }
1023
- function parseProviderProtocolLog(title, detail) {
1024
- if (title.trim().toLowerCase() !== "agent output")
1025
- return null;
1026
- if (!detail.startsWith("{") || !detail.endsWith("}"))
1027
- return null;
1028
- try {
1029
- const record = JSON.parse(detail);
1030
- if (!record || typeof record !== "object" || Array.isArray(record))
1031
- return null;
1032
- const type = record.type;
1033
- return typeof type === "string" && [
1034
- "assistant",
1035
- "message_start",
1036
- "message_update",
1037
- "message_end",
1038
- "stream_event",
1039
- "tool_result",
1040
- "tool_execution_start",
1041
- "tool_execution_update",
1042
- "tool_execution_end",
1043
- "turn_start",
1044
- "turn_end"
1045
- ].includes(type) ? record : null;
1046
- } catch {
1047
- return null;
1048
- }
1049
- }
1050
- function renderProviderProtocolLog(record) {
1051
- const type = typeof record.type === "string" ? record.type : "";
1052
- if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
1053
- const toolName = String(record.toolName ?? record.name ?? "tool");
1054
- const status = type === "tool_execution_start" ? "started" : type === "tool_execution_end" ? record.isError === true || record.result && typeof record.result === "object" && !Array.isArray(record.result) && record.result.isError === true ? "failed" : "completed" : "running";
1055
- return `[Pi tool] ${toolName} ${status}`;
1056
- }
1057
- return null;
1058
- }
1059
- function entryId(entry, fallback) {
1060
- return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
1061
- }
1062
- function renderOperatorSnapshot(snapshot) {
1063
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
1064
- const runId = String(run.runId ?? run.id ?? "run");
1065
- const status = String(run.status ?? "unknown");
1066
- const logs = snapshot.logs ?? [];
1067
- const latestByStage = new Map;
1068
- for (const log of logs) {
1069
- const title = String(log.title ?? "").toLowerCase();
1070
- const stageName = String(log.stage ?? "").toLowerCase();
1071
- const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
1072
- if (stage)
1073
- latestByStage.set(stage, log);
1074
- }
1075
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
1076
- const match = latestByStage.get(stage);
1077
- return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
1078
- });
1079
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
1080
- `);
1081
- }
1082
- function createPiRunStreamRenderer(output = process.stdout) {
1083
- let lastSnapshot = "";
1084
- const assistantTextById = new Map;
1085
- const seenTimeline = new Set;
1086
- const seenLogs = new Set;
1087
- const writeLine = (line) => output.write(`${line}
1088
- `);
1089
- return {
1090
- renderSnapshot(snapshot) {
1091
- const rendered = renderOperatorSnapshot(snapshot);
1092
- if (rendered && rendered !== lastSnapshot) {
1093
- writeLine(rendered);
1094
- lastSnapshot = rendered;
1095
- }
1096
- },
1097
- renderTimeline(entries) {
1098
- for (const [index, entry] of entries.entries()) {
1099
- const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
1100
- if (entry.type === "assistant_message" && typeof entry.text === "string") {
1101
- const text = entry.text;
1102
- const previousText = assistantTextById.get(id) ?? "";
1103
- if (!previousText && text.trim()) {
1104
- writeLine("[Pi assistant]");
1105
- }
1106
- if (text.startsWith(previousText)) {
1107
- const delta = text.slice(previousText.length);
1108
- if (delta)
1109
- output.write(delta);
1110
- } else if (text.trim() && text !== previousText) {
1111
- if (previousText)
1112
- writeLine(`
1113
- [Pi assistant]`);
1114
- output.write(text);
1115
- }
1116
- assistantTextById.set(id, text);
1117
- continue;
1118
- }
1119
- if (seenTimeline.has(id))
1120
- continue;
1121
- seenTimeline.add(id);
1122
- if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
1123
- writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
1124
- continue;
1125
- }
1126
- if (entry.type === "timeline_warning") {
1127
- writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
1128
- continue;
1129
- }
1130
- if (entry.type === "action") {
1131
- const text = String(entry.detail ?? entry.message ?? entry.title ?? "").trim();
1132
- if (text)
1133
- writeLine(`[Rig action] ${text}`);
1134
- continue;
1135
- }
1136
- if (entry.type === "user_message") {
1137
- const text = String(entry.text ?? entry.message ?? entry.detail ?? "").trim();
1138
- if (text)
1139
- writeLine(`[Operator] ${text}`);
1140
- continue;
1141
- }
1142
- const fallback = String(entry.detail ?? entry.message ?? entry.text ?? entry.title ?? "").trim();
1143
- if (fallback)
1144
- writeLine(`[${String(entry.type ?? "timeline")}] ${fallback}`);
1145
- }
1146
- },
1147
- renderLogs(entries) {
1148
- for (const [index, entry] of entries.entries()) {
1149
- const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
1150
- if (seenLogs.has(id))
1151
- continue;
1152
- seenLogs.add(id);
1153
- const title = String(entry.title ?? "");
1154
- if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
1155
- continue;
1156
- const detail = logDetail(entry);
1157
- if (!detail)
1158
- continue;
1159
- const protocolRecord = parseProviderProtocolLog(title, detail);
1160
- if (protocolRecord) {
1161
- const protocolLine = renderProviderProtocolLog(protocolRecord);
1162
- if (protocolLine)
1163
- writeLine(protocolLine);
1164
- continue;
1165
- }
1166
- writeLine(`[${title || "Rig log"}] ${detail}`);
1167
- }
1168
- }
1169
- };
1170
- }
1171
- function createOperatorSurface(options = {}) {
1172
- const input = options.input ?? process.stdin;
1173
- const output = options.output ?? process.stdout;
1174
- const errorOutput = options.errorOutput ?? process.stderr;
1175
- const renderer = createPiRunStreamRenderer(output);
1176
- const writeLine = (line) => output.write(`${line}
1177
- `);
1178
- return {
1179
- mode: "pi-compatible-text",
1180
- ...renderer,
1181
- info: writeLine,
1182
- error: (message2) => errorOutput.write(`${message2}
1183
- `),
1184
- attachCommandInput(handler) {
1185
- if (options.interactive === false || !input.isTTY)
1186
- return null;
1187
- const rl = createInterface({ input, output: process.stdout, terminal: false });
1188
- rl.on("line", (line) => {
1189
- Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
1190
- });
1191
- return { close: () => rl.close() };
1192
- }
1193
- };
1194
- }
1195
- function taskId(task) {
1196
- return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
1197
- }
1198
- function taskTitle(task) {
1199
- return typeof task.title === "string" && task.title.trim() ? task.title : "Untitled task";
1200
- }
1201
- function taskStatus(task) {
1202
- return typeof task.status === "string" && task.status.trim() ? task.status : "unknown";
1203
- }
1204
- function renderTaskPickerRows(tasks) {
1205
- return tasks.map((task, index) => `${index + 1}. ${taskId(task)} \xB7 ${taskStatus(task)} \xB7 ${taskTitle(task)}`);
1206
- }
1207
- async function promptForTaskSelection(question) {
1208
- const rl = createPromptInterface({ input: process.stdin, output: process.stdout });
1209
- try {
1210
- return await rl.question(question);
1211
- } finally {
1212
- rl.close();
1213
- }
1214
- }
1215
-
1216
- // packages/cli/src/commands/_task-picker.ts
1217
- function taskId2(task) {
1218
- return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
1219
- }
1220
- async function selectTaskWithTextPicker(tasks, io = {}) {
1221
- if (tasks.length === 0)
1222
- return null;
1223
- if (tasks.length === 1)
1224
- return tasks[0];
1225
- const isTty2 = io.isTty ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
1226
- if (!isTty2) {
1227
- throw new Error("task run requires an interactive terminal to pick a task; pass --task <id>, --next, or --detach with a task id.");
1228
- }
1229
- if (io.prompt || io.renderer) {
1230
- const prompt = io.prompt ?? promptForTaskSelection;
1231
- const renderer = io.renderer ?? { writeLine: (line) => process.stdout.write(`${line}
1232
- `) };
1233
- renderer.writeLine("Select Rig task:");
1234
- for (const row of renderTaskPickerRows(tasks))
1235
- renderer.writeLine(` ${row}`);
1236
- const answer2 = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
1237
- if (!answer2)
1238
- return null;
1239
- if (/^\d+$/.test(answer2)) {
1240
- const index2 = Number.parseInt(answer2, 10) - 1;
1241
- return tasks[index2] ?? null;
1242
- }
1243
- return tasks.find((task) => taskId2(task) === answer2) ?? null;
1244
- }
1245
- const options = tasks.map((task, index2) => ({
1246
- value: `${index2}`,
1247
- label: `${taskId2(task)} \xB7 ${typeof task.title === "string" && task.title.trim() ? task.title.trim() : "Untitled task"}`,
1248
- hint: typeof task.status === "string" && task.status.trim() ? task.status.trim() : undefined
1249
- }));
1250
- const answer = await droneSelect({
1251
- message: "Select Rig task",
1252
- options
1253
- });
1254
- if (answer === null) {
1255
- droneCancel("No task selected.");
1256
- return null;
1257
- }
1258
- const index = Number.parseInt(String(answer), 10);
1259
- return Number.isFinite(index) ? tasks[index] ?? null : null;
1260
- }
1261
-
1262
- // packages/cli/src/commands/_async-ui.ts
1263
- import pc from "picocolors";
1264
- var DONE_SYMBOL = pc.green("\u25C7");
1265
- var FAIL_SYMBOL = pc.red("\u25A0");
1266
- var activeUpdate = null;
1267
- async function withSpinner(label, work, options = {}) {
1268
- if (options.outputMode === "json") {
1269
- return work(() => {});
1270
- }
1271
- if (activeUpdate) {
1272
- const outer = activeUpdate;
1273
- outer(label);
1274
- return work(outer);
1275
- }
1276
- const output = options.output ?? process.stderr;
1277
- const isTty2 = output.isTTY === true;
1278
- let lastLabel = label;
1279
- if (!isTty2) {
1280
- output.write(`${label}
1281
- `);
1282
- const update2 = (next) => {
1283
- lastLabel = next;
1284
- };
1285
- activeUpdate = update2;
1286
- const previousListener2 = setServerPhaseListener(update2);
1287
- try {
1288
- return await work(update2);
1289
- } finally {
1290
- activeUpdate = null;
1291
- setServerPhaseListener(previousListener2);
1292
- }
1293
- }
1294
- const spinner = createTtySpinner({
1295
- label,
1296
- output,
1297
- frames: MICRO_DRONE_FRAMES,
1298
- styleFrame: (frame) => renderMicroDroneFrame(Math.max(0, MICRO_DRONE_FRAMES.indexOf(frame)))
1299
- });
1300
- const update = (next) => {
1301
- lastLabel = next;
1302
- spinner.setLabel(next);
1303
- };
1304
- activeUpdate = update;
1305
- const previousListener = setServerPhaseListener(update);
1306
- try {
1307
- const result = await work(update);
1308
- spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
1309
- return result;
1310
- } catch (error) {
1311
- spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
1312
- throw error;
1313
- } finally {
1314
- activeUpdate = null;
1315
- setServerPhaseListener(previousListener);
1316
- }
1317
- }
23
+ // packages/cli/src/runner.ts
24
+ import { EventBus } from "@rig/runtime/control-plane/runtime/events";
25
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
26
+ import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
27
+ import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
1318
28
 
1319
- // packages/cli/src/commands/_pi-frontend.ts
1320
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "fs";
1321
- import { homedir as homedir2, tmpdir } from "os";
1322
- import { join } from "path";
1323
- import { main as runPiMain } from "@earendil-works/pi-coding-agent";
1324
- import createPiRigExtension from "@rig/pi-rig";
1325
- function setTemporaryEnv(updates) {
1326
- const previous = new Map;
1327
- for (const [key, value] of Object.entries(updates)) {
1328
- previous.set(key, process.env[key]);
1329
- process.env[key] = value;
1330
- }
1331
- return () => {
1332
- for (const [key, value] of previous) {
1333
- if (value === undefined)
1334
- delete process.env[key];
1335
- else
1336
- process.env[key] = value;
1337
- }
1338
- };
1339
- }
1340
- function buildOperatorPiEnv(input) {
1341
- return {
1342
- PI_CODING_AGENT_SESSION_DIR: input.sessionDir,
1343
- PI_SKIP_VERSION_CHECK: "1",
1344
- PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust",
1345
- RIG_PI_OPERATOR_SESSION: "1",
1346
- RIG_RUN_ID: input.runId,
1347
- RIG_SERVER_URL: input.serverUrl,
1348
- ...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {},
1349
- ...input.serverProjectRoot ? { RIG_PROJECT_ROOT: input.serverProjectRoot } : {}
1350
- };
1351
- }
1352
- async function prepareOperatorConsole(context, runId, tempSessionDir) {
1353
- const server = await ensureServerForCli(context.projectRoot);
1354
- const localCwd = join(homedir2(), ".rig", "drones", runId.slice(0, 8));
1355
- mkdirSync2(localCwd, { recursive: true });
1356
- trustDroneCwd(localCwd);
1357
- installRigPiTheme();
1358
- let sessionFileArg = [];
1359
- try {
1360
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/session-file`);
1361
- if (payload?.ok && typeof payload.content === "string" && payload.content.trim()) {
1362
- const fileName = typeof payload.fileName === "string" && payload.fileName.trim() ? payload.fileName.replace(/[^A-Za-z0-9._-]/g, "_") : `rig-run-${runId}.jsonl`;
1363
- const localSessionPath = join(tempSessionDir, fileName);
1364
- const content = payload.content.split(`
1365
- `).map((line, index) => {
1366
- if (index > 0 || !line.trim())
1367
- return line;
1368
- try {
1369
- const header = JSON.parse(line);
1370
- if (header.type === "session" && typeof header.cwd === "string") {
1371
- return JSON.stringify({ ...header, cwd: localCwd });
1372
- }
1373
- } catch {}
1374
- return line;
1375
- }).join(`
1376
- `);
1377
- writeFileSync2(localSessionPath, content);
1378
- sessionFileArg = ["--session", localSessionPath];
1379
- }
1380
- } catch {}
1381
- return { server, sessionFileArg };
1382
- }
1383
- var RIG_PI_THEME = {
1384
- $schema: "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
1385
- name: "rig",
1386
- vars: {
1387
- acid: "#ccff4d",
1388
- acidDim: "#a9d63f",
1389
- cyan: "#56d8ff",
1390
- red: "#ff5d5d",
1391
- yellow: "#ffd24d",
1392
- ink: "#f2f3f6",
1393
- ink2: "#aeb0ba",
1394
- ink3: "#6c6e79",
1395
- ink4: "#44464f",
1396
- panel: "#101115",
1397
- panelUser: "#14161b",
1398
- toolPending: "#0e1013",
1399
- toolSuccess: "#10150c",
1400
- toolError: "#1a0f0f",
1401
- customMsg: "#0f1410"
1402
- },
1403
- colors: {
1404
- accent: "acid",
1405
- border: "ink4",
1406
- borderAccent: "acid",
1407
- borderMuted: "ink4",
1408
- success: "acid",
1409
- error: "red",
1410
- warning: "yellow",
1411
- muted: "ink3",
1412
- dim: "ink4",
1413
- text: "ink",
1414
- thinkingText: "ink3",
1415
- selectedBg: "panel",
1416
- userMessageBg: "panelUser",
1417
- userMessageText: "ink",
1418
- customMessageBg: "customMsg",
1419
- customMessageText: "ink2",
1420
- customMessageLabel: "acidDim",
1421
- toolPendingBg: "toolPending",
1422
- toolSuccessBg: "toolSuccess",
1423
- toolErrorBg: "toolError",
1424
- toolTitle: "ink",
1425
- toolOutput: "ink3",
1426
- mdHeading: "acid",
1427
- mdLink: "cyan",
1428
- mdLinkUrl: "ink4",
1429
- mdCode: "acidDim",
1430
- mdCodeBlock: "ink2",
1431
- mdCodeBlockBorder: "ink4",
1432
- mdQuote: "ink3",
1433
- mdQuoteBorder: "ink4",
1434
- mdHr: "ink4",
1435
- mdListBullet: "acid",
1436
- toolDiffAdded: "acid",
1437
- toolDiffRemoved: "red",
1438
- toolDiffContext: "ink3",
1439
- syntaxComment: "ink3",
1440
- syntaxKeyword: "cyan",
1441
- syntaxFunction: "acid",
1442
- syntaxVariable: "ink",
1443
- syntaxString: "acidDim",
1444
- syntaxNumber: "yellow",
1445
- syntaxType: "cyan",
1446
- syntaxOperator: "ink2",
1447
- syntaxPunctuation: "ink3",
1448
- thinkingOff: "ink4",
1449
- thinkingMinimal: "ink3",
1450
- thinkingLow: "ink2",
1451
- thinkingMedium: "cyan",
1452
- thinkingHigh: "acidDim",
1453
- thinkingXhigh: "acid",
1454
- bashMode: "cyan"
1455
- }
1456
- };
1457
- function trustDroneCwd(localCwd) {
1458
- try {
1459
- const agentDir = join(homedir2(), ".pi", "agent");
1460
- mkdirSync2(agentDir, { recursive: true });
1461
- const trustPath = join(agentDir, "trust.json");
1462
- const store = existsSync3(trustPath) ? JSON.parse(readFileSync3(trustPath, "utf8")) : {};
1463
- if (store[localCwd] !== true) {
1464
- store[localCwd] = true;
1465
- writeFileSync2(trustPath, `${JSON.stringify(store, null, "\t")}
1466
- `);
29
+ class CliError extends RuntimeCliError {
30
+ hint;
31
+ constructor(message, exitCode = 1, options = {}) {
32
+ super(message, exitCode);
33
+ if (options.hint?.trim()) {
34
+ this.hint = options.hint.trim();
1467
35
  }
1468
- } catch {}
36
+ }
1469
37
  }
1470
- function installRigPiTheme() {
1471
- try {
1472
- const themesDir = join(homedir2(), ".pi", "agent", "themes");
1473
- mkdirSync2(themesDir, { recursive: true });
1474
- const themePath = join(themesDir, "rig.json");
1475
- const next = `${JSON.stringify(RIG_PI_THEME, null, "\t")}
1476
- `;
1477
- if (!existsSync3(themePath) || readFileSync3(themePath, "utf8") !== next) {
1478
- writeFileSync2(themePath, next);
38
+ function takeFlag(args, flag) {
39
+ const rest = [];
40
+ let value = false;
41
+ for (const arg of args) {
42
+ if (arg === flag) {
43
+ value = true;
44
+ continue;
1479
45
  }
1480
- } catch {}
1481
- }
1482
- async function attachRunBundledPiFrontend(context, input) {
1483
- const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
1484
- const { server, sessionFileArg } = await withSpinner(`Opening Pi console for run ${input.runId}\u2026`, () => prepareOperatorConsole(context, input.runId, tempSessionDir), { outputMode: context.outputMode });
1485
- const restoreEnv = setTemporaryEnv(buildOperatorPiEnv({
1486
- runId: input.runId,
1487
- serverUrl: server.baseUrl,
1488
- authToken: server.authToken,
1489
- serverProjectRoot: server.serverProjectRoot,
1490
- sessionDir: tempSessionDir
1491
- }));
1492
- const piRigExtensionFactory = (pi) => {
1493
- createPiRigExtension(pi);
1494
- };
1495
- let detached = false;
1496
- try {
1497
- await runPiMain([
1498
- "--no-extensions",
1499
- "--no-skills",
1500
- "--no-prompt-templates",
1501
- "--no-context-files",
1502
- ...sessionFileArg
1503
- ], {
1504
- extensionFactories: [piRigExtensionFactory]
1505
- });
1506
- detached = true;
1507
- } finally {
1508
- restoreEnv();
1509
- rmSync(tempSessionDir, { recursive: true, force: true });
46
+ rest.push(arg);
1510
47
  }
1511
- let run = { runId: input.runId, status: "unknown" };
1512
- try {
1513
- run = await getRunDetailsViaServer(context, input.runId);
1514
- } catch {}
1515
- return {
1516
- run,
1517
- logs: [],
1518
- timeline: [],
1519
- timelineCursor: null,
1520
- steered: input.steered === true,
1521
- detached,
1522
- rendered: "stock Pi operator console with the pi-rig extension"
1523
- };
48
+ return { value, rest };
1524
49
  }
1525
-
1526
- // packages/cli/src/commands/_operator-view.ts
1527
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
1528
- function runStatusFromPayload(payload) {
1529
- const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
1530
- return String(run.status ?? "unknown").toLowerCase();
1531
- }
1532
- async function applyOperatorCommand(context, input, deps = {}) {
1533
- const line = input.line.trim();
1534
- if (!line)
1535
- return { action: "ignored" };
1536
- if (line === "/detach" || line === "/quit" || line === "/q") {
1537
- return { action: "detach", message: "Detached from run." };
1538
- }
1539
- if (line === "/stop") {
1540
- await (deps.stop ?? stopRunViaServer)(context, input.runId);
1541
- return { action: "stopped", message: "Stop requested." };
1542
- }
1543
- const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
1544
- if (!userMessage)
1545
- return { action: "ignored" };
1546
- await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
1547
- return { action: "continue", message: "Steering message queued." };
1548
- }
1549
- async function readOperatorSnapshot(context, runId, options = {}) {
1550
- const run = await getRunDetailsViaServer(context, runId);
1551
- const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
1552
- const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
1553
- entries: [{
1554
- id: `timeline-unavailable:${runId}`,
1555
- type: "timeline_warning",
1556
- detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
1557
- createdAt: new Date().toISOString()
1558
- }],
1559
- nextCursor: options.timelineCursor ?? null
1560
- }));
1561
- const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
1562
- const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1563
- const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
1564
- return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
1565
- }
1566
- async function attachRunOperatorView(context, input) {
1567
- let steered = false;
1568
- const attachMessage = input.message?.trim();
1569
- if (attachMessage) {
1570
- await withSpinner("Queueing steering message\u2026", () => sendRunPiPromptViaServer(context, input.runId, attachMessage, "steer").catch(() => steerRunViaServer(context, input.runId, attachMessage)), { outputMode: context.outputMode });
1571
- steered = true;
1572
- }
1573
- if (!input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
1574
- return attachRunBundledPiFrontend(context, {
1575
- runId: input.runId,
1576
- steered
1577
- });
1578
- }
1579
- const surface = createOperatorSurface({ interactive: input.interactive !== false });
1580
- let snapshot = await withSpinner(`Connecting to run ${input.runId}\u2026`, () => readOperatorSnapshot(context, input.runId), { outputMode: context.outputMode });
1581
- if (context.outputMode === "text") {
1582
- surface.renderSnapshot(snapshot);
1583
- surface.renderTimeline(snapshot.timeline);
1584
- surface.renderLogs(snapshot.logs);
1585
- if (steered)
1586
- surface.info("Message submitted to worker Pi.");
1587
- }
1588
- let detached = false;
1589
- let commandInput = null;
1590
- if (input.follow && !input.once && context.outputMode === "text") {
1591
- if (input.interactive !== false && process.stdin.isTTY) {
1592
- surface.info("Controls: /user <message>, /stop, /detach");
1593
- commandInput = surface.attachCommandInput(async (line) => {
1594
- const result = await applyOperatorCommand(context, { runId: input.runId, line });
1595
- if (result.message)
1596
- surface.info(result.message);
1597
- if (result.action === "detach" || result.action === "stopped") {
1598
- detached = true;
1599
- commandInput?.close();
1600
- }
1601
- });
50
+ function takeOption(args, option) {
51
+ const rest = [];
52
+ let value;
53
+ for (let index = 0;index < args.length; index += 1) {
54
+ const current = args[index];
55
+ if (current === option) {
56
+ const next = args[index + 1];
57
+ if (!next || next.startsWith("-")) {
58
+ throw new CliError(`Missing value for ${option}`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} <value>\`.` });
59
+ }
60
+ value = next;
61
+ index += 1;
62
+ continue;
1602
63
  }
1603
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
1604
- let timelineCursor = snapshot.timelineCursor;
1605
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
1606
- await Bun.sleep(pollMs);
1607
- snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
1608
- timelineCursor = snapshot.timelineCursor;
1609
- surface.renderSnapshot(snapshot);
1610
- surface.renderTimeline(snapshot.timeline);
1611
- surface.renderLogs(snapshot.logs);
64
+ if (current !== undefined) {
65
+ rest.push(current);
1612
66
  }
1613
- commandInput?.close();
1614
67
  }
1615
- return { ...snapshot, steered, detached };
68
+ return { value, rest };
1616
69
  }
1617
-
1618
- // packages/cli/src/commands/_cli-format.ts
1619
- import pc2 from "picocolors";
1620
- var themeDim = (value) => ink3(value);
1621
- var themeFaint = (value) => ink4(value);
1622
- function stringField(record, key, fallback = "") {
1623
- const value = record[key];
1624
- return typeof value === "string" && value.trim() ? value.trim() : fallback;
70
+ function requireNoExtraArgs(args, usage) {
71
+ if (args.length > 0) {
72
+ throw new CliError(`Unexpected arguments: ${args.join(" ")}
73
+ Usage: ${usage}`);
74
+ }
1625
75
  }
1626
- function numberField(record, key) {
1627
- const value = record[key];
1628
- return typeof value === "number" && Number.isFinite(value) ? value : null;
76
+ function requireTask(taskId, usage) {
77
+ if (!taskId) {
78
+ throw new CliError(`Missing --task option.
79
+ Usage: ${usage}`);
80
+ }
81
+ return taskId;
1629
82
  }
83
+
84
+ // packages/cli/src/commands/_cli-format.ts
85
+ import pc from "picocolors";
86
+ var dim = pc.dim;
87
+ var faintBar = pc.dim("\u2502");
88
+ var accent = pc.cyan;
1630
89
  function arrayField(record, key) {
1631
90
  const value = record[key];
1632
- return Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() ? [entry.trim()] : []) : [];
91
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string" && entry.trim().length > 0) : [];
1633
92
  }
1634
93
  function rawObject(record) {
1635
- const raw = record.raw;
1636
- return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
94
+ const value = record.raw;
95
+ return value && typeof value === "object" && !Array.isArray(value) ? value : record;
1637
96
  }
1638
97
  function truncate(value, width) {
1639
- if (value.length <= width)
1640
- return value;
1641
- if (width <= 1)
1642
- return "\u2026";
1643
- return `${value.slice(0, width - 1)}\u2026`;
98
+ return value.length <= width ? value : `${value.slice(0, Math.max(0, width - 1))}\u2026`;
1644
99
  }
1645
100
  function pad(value, width) {
1646
101
  return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
1647
102
  }
1648
103
  function statusColor(status) {
1649
- const normalized = status.toLowerCase();
1650
- if (["completed", "merged", "closed", "done", "accepted", "pass", "selected", "approved", "running"].includes(normalized))
1651
- return accent;
1652
- if (["failed", "needs_attention", "needs-attention", "blocked", "error", "rejected"].includes(normalized))
1653
- return red;
1654
- if (["reviewing", "validating", "in_progress", "in-progress", "remote", "preparing", "closing-out"].includes(normalized))
1655
- return cyan;
1656
- if (["ready", "open", "queued", "created", "local", "pending"].includes(normalized))
1657
- return yellow;
1658
- return themeDim;
1659
- }
1660
- function compactValue(value) {
1661
- if (value === null || value === undefined)
1662
- return "";
1663
- if (typeof value === "string")
1664
- return value;
1665
- if (typeof value === "number" || typeof value === "boolean")
1666
- return String(value);
1667
- if (Array.isArray(value))
1668
- return value.map(compactValue).filter(Boolean).join(", ");
1669
- return JSON.stringify(value);
1670
- }
1671
- function shouldUseClackOutput() {
1672
- return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
1673
- }
1674
- function printFormattedOutput(message2, options = {}) {
1675
- if (!shouldUseClackOutput()) {
1676
- console.log(message2);
1677
- return;
1678
- }
1679
- droneNote(message2, options.title);
1680
- }
1681
- function formatStatusPill(status) {
1682
- const label = status || "unknown";
1683
- return statusColor(label)(`\u25CF ${label}`);
104
+ const normalized = status.trim().toLowerCase();
105
+ if (["done", "completed", "ready", "healthy", "open", "approved"].includes(normalized))
106
+ return pc.green;
107
+ if (["failed", "error", "blocked", "rejected", "stopped"].includes(normalized))
108
+ return pc.red;
109
+ if (["running", "in_progress", "in-progress", "active", "booting"].includes(normalized))
110
+ return pc.cyan;
111
+ if (["pending", "queued", "created", "local"].includes(normalized))
112
+ return pc.yellow;
113
+ return pc.dim;
114
+ }
115
+ function firstString(record, keys, fallback = "") {
116
+ for (const key of keys) {
117
+ const value = record[key];
118
+ if (typeof value === "string" && value.trim())
119
+ return value;
120
+ }
121
+ return fallback;
122
+ }
123
+ function printFormattedOutput(message) {
124
+ console.log(message);
1684
125
  }
1685
126
  function formatSection(title, subtitle) {
1686
- return `${pc2.bold(accent("\u25C6"))} ${pc2.bold(title)}${subtitle ? themeDim(` \u2014 ${subtitle}`) : ""}`;
127
+ return `${pc.bold(accent("\u25C6"))} ${pc.bold(title)}${subtitle ? dim(` \u2014 ${subtitle}`) : ""}`;
1687
128
  }
1688
129
  function formatSuccessCard(title, rows = []) {
1689
- const body = rows.filter(([, value]) => value !== undefined && value !== null && String(value).length > 0).map(([key, value]) => `${themeFaint("\u2502")} ${themeDim(key.padEnd(12))} ${value}`);
130
+ const body = rows.filter(([, value]) => value !== undefined && value !== null && String(value).length > 0).map(([key, value]) => `${faintBar} ${dim(key.padEnd(12))} ${value}`);
1690
131
  return [formatSection(title), ...body].join(`
1691
132
  `);
1692
133
  }
1693
134
  function formatNextSteps(steps) {
1694
135
  if (steps.length === 0)
1695
136
  return [];
1696
- return [pc2.bold("Next"), ...steps.map((step) => `${accent("\u203A")} ${step}`)];
137
+ return [pc.bold("Next"), ...steps.map((step) => `${accent("\u203A")} ${step}`)];
1697
138
  }
1698
139
  function formatTaskList(tasks, options = {}) {
1699
- if (options.raw)
1700
- return tasks.map((task) => JSON.stringify(task)).join(`
1701
- `);
1702
- if (tasks.length === 0)
1703
- return [formatSection("Tasks", "none found"), ...formatNextSteps(["Try `rig server status` to confirm the selected server.", "Relax filters or run `rig task run --title ... --initial-prompt ...` for ad hoc work."])].join(`
140
+ if (tasks.length === 0) {
141
+ return [formatSection("Tasks", "empty"), dim("No tasks available."), "", ...formatNextSteps(["Refresh: `rig task list`", "Pick next: `rig task next`"])].join(`
1704
142
  `);
1705
- const rows = tasks.map((task) => {
1706
- const raw = rawObject(task);
1707
- const id = stringField(task, "id", "<unknown>");
1708
- const status = stringField(task, "status", "unknown");
1709
- const title = stringField(task, "title", "Untitled task");
1710
- const source = stringField(task, "source", stringField(raw, "source", ""));
1711
- const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
1712
- return { id, status, title, source, labels };
1713
- });
1714
- const idWidth = Math.min(18, Math.max(4, ...rows.map((row) => row.id.length)));
1715
- const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
1716
- const header = `${pc2.bold(pad("TASK", idWidth))} ${pc2.bold(pad("STATUS", statusWidth))} ${pc2.bold("TITLE")}`;
143
+ }
144
+ if (options.raw) {
145
+ return JSON.stringify(tasks, null, 2);
146
+ }
147
+ const rows = tasks.map((task) => summarizeTaskRow(task));
148
+ const idWidth = Math.max(2, ...rows.map((row) => row.id.length));
149
+ const statusWidth = Math.max(6, ...rows.map((row) => row.status.length));
1717
150
  const body = rows.map((row) => {
1718
- const labels = row.labels.length > 0 ? themeDim(` ${row.labels.slice(0, 4).map((label) => `#${label}`).join(" ")}`) : "";
1719
- const source = row.source ? themeDim(` ${row.source}`) : "";
151
+ const labels = row.labels.length > 0 ? dim(` ${row.labels.slice(0, 4).map((label) => `#${label}`).join(" ")}`) : "";
152
+ const source = row.source ? dim(` ${row.source}`) : "";
1720
153
  return [
1721
- pc2.bold(pad(truncate(row.id, idWidth), idWidth)),
154
+ pc.bold(pad(truncate(row.id, idWidth), idWidth)),
1722
155
  statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
1723
156
  `${row.title}${labels}${source}`
1724
157
  ].join(" ");
1725
158
  });
1726
- return [formatSection("Tasks", `${rows.length} shown`), header, ...body, "", ...formatNextSteps(["Run one: `rig task run <id>` or `rig task run --next`", "Attach later: `rig run attach <run-id> --follow`"])].join(`
159
+ return [formatSection("Tasks", `${tasks.length}`), ...body].join(`
1727
160
  `);
1728
161
  }
162
+ function summarizeTaskRow(task) {
163
+ const raw = rawObject(task);
164
+ return {
165
+ id: firstString(task, ["id", "taskId"], "(unknown-task)"),
166
+ title: firstString(task, ["title", "summary", "name"], "(untitled)"),
167
+ status: firstString(task, ["status"], "unknown"),
168
+ labels: arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels"),
169
+ source: firstString(task, ["source"], "")
170
+ };
171
+ }
1729
172
  function formatTaskCard(task, options = {}) {
1730
173
  const raw = rawObject(task);
1731
- const id = stringField(task, "id", stringField(raw, "id", "<unknown>"));
1732
- const status = stringField(task, "status", stringField(raw, "status", "unknown"));
1733
- const title = stringField(task, "title", stringField(raw, "title", "Untitled task"));
1734
- const source = stringField(task, "source", stringField(raw, "source", ""));
1735
- const url = stringField(task, "url", stringField(raw, "url", ""));
1736
- const number = numberField(task, "number") ?? numberField(raw, "number");
1737
- const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
1738
- const assignees = arrayField(task, "assignees").length > 0 ? arrayField(task, "assignees") : arrayField(raw, "assignees");
1739
- const readiness = compactValue(task.readiness ?? raw.readiness);
1740
- const validators = compactValue(task.validators ?? raw.validators ?? task.validation ?? raw.validation);
1741
- const rows = [
1742
- ["task", pc2.bold(id)],
1743
- ["status", formatStatusPill(status)],
1744
- ["title", title],
1745
- ["source", source],
1746
- ["number", number],
1747
- ["labels", labels.length ? labels.map((label) => `#${label}`).join(" ") : ""],
1748
- ["assignees", assignees.join(", ")],
1749
- ["readiness", readiness],
1750
- ["validators", validators],
1751
- ["url", url]
1752
- ];
1753
- return [
1754
- formatSuccessCard(options.title ?? (options.selected ? "Selected task" : "Task"), rows),
1755
- "",
1756
- ...formatNextSteps([`Start: \`rig task run ${id}\``, `Details: \`rig task show ${id} --raw\``])
1757
- ].join(`
174
+ const lines = [formatSection(options.title ?? (options.selected ? "Selected task" : "Task"))];
175
+ for (const [label, value] of [
176
+ ["id", firstString(task, ["id", "taskId"], "(unknown-task)")],
177
+ ["title", firstString(task, ["title", "summary", "name"], "(untitled)")],
178
+ ["status", firstString(task, ["status"], "unknown")],
179
+ ["source", firstString(task, ["source"], "")],
180
+ ["url", firstString(raw, ["url"], "")]
181
+ ]) {
182
+ if (value)
183
+ lines.push(`${faintBar} ${dim(label.padEnd(12))} ${value}`);
184
+ }
185
+ const labels = arrayField(task, "labels");
186
+ if (labels.length > 0)
187
+ lines.push(`${faintBar} ${dim("labels".padEnd(12))} ${labels.map((label) => `#${label}`).join(" ")}`);
188
+ return lines.join(`
1758
189
  `);
1759
190
  }
1760
191
  function formatTaskDetails(task) {
1761
192
  return formatTaskCard(task, { title: "Task details" });
1762
193
  }
1763
194
  function formatSubmittedRun(input) {
1764
- const rows = [["run", pc2.bold(input.runId)]];
1765
- if (input.task) {
1766
- const id = stringField(input.task, "id", "<unknown>");
1767
- const status = stringField(input.task, "status", "unknown");
1768
- const title = stringField(input.task, "title", "Untitled task");
1769
- rows.push(["task", `${pc2.bold(id)} ${formatStatusPill(status)} ${title}`]);
1770
- }
1771
- const runtime = [input.runtimeAdapter || "pi", input.runtimeMode || "full-access", input.interactionMode || "default"].filter(Boolean).join(" \xB7 ");
1772
- rows.push(["runtime", runtime]);
1773
- return [
1774
- formatSuccessCard("Run submitted", rows),
1775
- "",
1776
- ...formatNextSteps([
1777
- `Attach: \`rig run attach ${input.runId} --follow\``,
1778
- `Inspect: \`rig run show ${input.runId}\``,
1779
- input.detached ? "Submitted detached; attach when you are ready." : "Interactive mode opens the enriched bundled Pi (native UI + Rig layers, worker brain)."
1780
- ])
1781
- ].join(`
1782
- `);
195
+ return formatSuccessCard("Run submitted", [
196
+ ["run", input.runId],
197
+ ["task", input.taskId ?? undefined],
198
+ ["title", input.title ?? undefined],
199
+ ["queue", input.queuePosition ?? undefined]
200
+ ]);
1783
201
  }
1784
202
 
1785
- // packages/cli/src/commands/inbox.ts
1786
- async function listInboxRecords(context, kind, filters) {
1787
- const params = new URLSearchParams;
1788
- if (filters.run)
1789
- params.set("runId", filters.run);
1790
- if (filters.task)
1791
- params.set("taskId", filters.task);
1792
- const query = params.size > 0 ? `?${params.toString()}` : "";
1793
- const payload = await requestServerJson(context, `/api/inbox/${kind}${query}`);
1794
- const records = Array.isArray(payload) ? payload : [];
1795
- return filters.pendingOnly ? records.filter((entry) => (entry.status ?? "pending") !== "resolved") : records;
1796
- }
1797
- async function readPendingInboxCounts(context) {
203
+ // packages/cli/src/commands/_run-bridge.ts
204
+ import { randomUUID } from "crypto";
205
+ import { spawn as nodeSpawn } from "child_process";
206
+ import { existsSync, readdirSync, readFileSync } from "fs";
207
+ import { dirname, resolve } from "path";
208
+ import { fileURLToPath } from "url";
209
+ import { CUSTOM_TYPE_FOR, sessionIdFromSessionFile } from "@rig/contracts";
210
+ import { createPluginHost } from "@rig/core";
211
+ import { loadConfig } from "@rig/core/load-config";
212
+ import { resolveOwnerNamespaceKey, resolveRegistryBaseUrl, resolveRegistrySecret, resolveSelectedRemote } from "@rig/runtime/control-plane/remote";
213
+ import { listAgentRuntimes } from "@rig/runtime/control-plane/runtime/isolation";
214
+ import { createRegistryClient } from "@rig/relay-registry";
215
+ import {
216
+ listActiveCollabSessions as ompListActiveCollabSessions
217
+ } from "@oh-my-pi/pi-coding-agent/collab/api";
218
+ function stringField(value) {
219
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
220
+ }
221
+ function githubUserId(value) {
222
+ if (typeof value === "number" && Number.isInteger(value))
223
+ return String(value);
224
+ return stringField(value);
225
+ }
226
+ function readJsonRecord(path) {
227
+ if (!existsSync(path))
228
+ return null;
1798
229
  try {
1799
- const [approvals, inputs] = await Promise.all([
1800
- listInboxRecords(context, "approvals", { pendingOnly: true }),
1801
- listInboxRecords(context, "inputs", { pendingOnly: true })
1802
- ]);
1803
- return { approvals: approvals.length, inputs: inputs.length };
230
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
231
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
1804
232
  } catch {
1805
233
  return null;
1806
234
  }
1807
235
  }
1808
- async function printPendingInboxFooter(context) {
1809
- if (context.outputMode !== "text")
1810
- return;
1811
- const counts = await readPendingInboxCounts(context);
1812
- if (!counts || counts.approvals === 0 && counts.inputs === 0)
1813
- return;
1814
- const parts = [];
1815
- if (counts.approvals > 0)
1816
- parts.push(`${counts.approvals} approval${counts.approvals === 1 ? "" : "s"}`);
1817
- if (counts.inputs > 0)
1818
- parts.push(`${counts.inputs} input request${counts.inputs === 1 ? "" : "s"}`);
1819
- console.log(`
1820
- \u26A0 ${parts.join(" and ")} pending \u2014 run \`rig inbox\` to review.`);
1821
- }
1822
-
1823
- // packages/cli/src/commands/_help-catalog.ts
1824
- import pc3 from "picocolors";
1825
- var TOP_LEVEL_SECTIONS = [
1826
- {
1827
- title: "Pi console",
1828
- subtitle: "the operator surface \u2014 every attach opens the run's FULL Pi session",
1829
- commands: [
1830
- { command: "rig run attach <run-id>", description: "Open the run's Pi console: complete transcript (live AND finished runs), worker turns streaming in live." },
1831
- { command: "type a message", description: "Inside the console, plain text steers the worker mid-turn \u2014 it lands in the agent's context, not a local model." },
1832
- { command: "!<command>", description: "Inside the console, runs shell in the WORKER's workspace; output streams back into the transcript." },
1833
- { command: "/<command>", description: "The palette includes the WORKER session's slash commands ([worker]-tagged) next to /rig." },
1834
- { command: "/rig abort | /rig stop", description: "Abort the worker's current turn, or stop the whole run, from inside the console." },
1835
- { command: "rig run steer <id> --message <text>", description: "Steer without attaching \u2014 queue a message; the worker picks it up within seconds." }
1836
- ]
1837
- },
1838
- {
1839
- title: "Start here",
1840
- subtitle: "one-time setup, pick a server",
1841
- commands: [
1842
- { command: "rig init", description: "Wizard: config, GitHub auth, task source, server, Pi wiring." },
1843
- { command: "rig server use <alias|local>", description: "Pick which Rig server owns this repo (`rig server list` to see them)." },
1844
- { command: "rig server status", description: "Show the selected server for this repo." }
1845
- ]
1846
- },
1847
- {
1848
- title: "Work",
1849
- subtitle: "find a task, put an agent on it, answer what it asks",
1850
- commands: [
1851
- { command: "rig task list", description: "What's on the board (from the selected source/server)." },
1852
- { command: "rig task run --next", description: "Dispatch an agent on the next ready task; interactive mode drops you into its Pi console." },
1853
- { command: "rig run status", description: "Active and recent runs at a glance." },
1854
- { command: "rig run attach <id> --follow", description: "Same as plain attach \u2014 the Pi console is always the interactive surface." },
1855
- { command: "rig inbox approvals", description: "Approvals workers are waiting on (then `rig inbox approve \u2026`)." }
1856
- ]
1857
- },
1858
- {
1859
- title: "Watch",
1860
- subtitle: "fleet metrics and per-task forensics",
1861
- commands: [
1862
- { command: "rig stats [--since 7d]", description: "Fleet metrics: completion/failure rates, median run time, steering, stalls." },
1863
- { command: "rig inspect logs --task <id>", description: "Latest run log for a task." },
1864
- { command: "rig inspect diff --task <id>", description: "Changed files for a task." }
1865
- ]
1866
- },
1867
- {
1868
- title: "Unblock",
1869
- subtitle: "diagnose wiring, fix auth",
1870
- commands: [
1871
- { command: "rig doctor", description: "Check every part of the wiring \u2014 run this when anything feels off." },
1872
- { command: "rig github auth status", description: "GitHub auth state on the selected server." }
1873
- ]
1874
- },
1875
- {
1876
- title: "Extend",
1877
- subtitle: "plugins contribute validators, hooks, task sources, commands",
1878
- commands: [
1879
- { command: "rig plugin list", description: "What the rig.config.ts plugins contribute." },
1880
- { command: "rig plugin run <command-id>", description: "Execute a plugin-contributed CLI command." }
1881
- ]
1882
- }
1883
- ];
1884
- var PRIMARY_GROUPS = [
1885
- {
1886
- name: "server",
1887
- summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
1888
- usage: ["rig server <status|list|add|use|start> [options]"],
1889
- commands: [
1890
- { command: "status", description: "Show the selected server for this repo.", primary: true },
1891
- { command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
1892
- { command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
1893
- { command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
1894
- { command: "list", description: "List saved local/remote server aliases.", primary: true },
1895
- { command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
1896
- ],
1897
- examples: [
1898
- "rig server status",
1899
- "rig server add prod https://where.rig-does.work",
1900
- "rig server use prod",
1901
- "rig server use local",
1902
- "rig server start --port 3773"
1903
- ],
1904
- next: ["Use `rig task list` to see server-owned work.", "Use `rig run list` or `rig run attach <id> --follow` to monitor runs."]
1905
- },
1906
- {
1907
- name: "task",
1908
- summary: "Find work, start Pi-backed runs, and validate task results.",
1909
- usage: ["rig task <list|next|show|run> [options]"],
1910
- commands: [
1911
- { command: "list [--assignee <login|me|@me>] [--state open|closed]", description: "List tasks from the selected server/source.", primary: true },
1912
- { command: "next [filters]", description: "Render the next matching task as a selected-task card.", primary: true },
1913
- { command: "show <id>|--task <id> [--raw]", description: "Show a human task summary; --raw prints the full payload.", primary: true },
1914
- { command: "run [#<issue>|<task-id>|--next|--task <id>]", description: "Submit a task run; interactive follows with bundled Pi.", primary: true },
1915
- { command: "ready", description: "List task IDs that are runnable now." },
1916
- { command: "validate|verify [--task <id>]", description: "Run configured task checks/review gates." },
1917
- { command: "details --task <id>", description: "Show full task info from the configured source." },
1918
- { command: "reopen [--task <id> | --all] [--reason <text>]", description: "Reopen closed task(s) in the configured source." },
1919
- { command: "artifacts|artifact-dir|artifact-write", description: "Inspect or write task artifacts." },
1920
- { command: "report-bug", description: "Create a structured bug report/task." }
1921
- ],
1922
- examples: [
1923
- "rig task list --assignee @me --limit 20",
1924
- "rig task next",
1925
- "rig task show 123 --raw",
1926
- "rig task run --next",
1927
- "rig task run #123 --runtime-adapter pi",
1928
- "rig task run --title 'Investigate deploy drift' --initial-prompt 'Check server health'"
1929
- ],
1930
- next: ["Use `--detach` to submit without attaching.", "Use `rig run attach <run-id> --follow` to rejoin a live run."]
1931
- },
1932
- {
1933
- name: "run",
1934
- summary: "Observe, attach to, and control Rig runs. `attach` opens the Pi console \u2014 the full worker session, live.",
1935
- usage: ["rig run <list|status|show|attach|steer|stop|resume|restart> [options]"],
1936
- commands: [
1937
- { command: "list", description: "List recent runs from the selected server or local state.", primary: true },
1938
- { command: "status", description: "Render active and recent run groups.", primary: true },
1939
- { command: "show <id>|--run <id> [--raw]", description: "Show a human run summary; --raw prints the full payload.", primary: true },
1940
- { command: "attach <run-id>|--run <id>", description: "Open the run's Pi console \u2014 see 'Inside the console' below. Works on live AND finished runs.", primary: true },
1941
- { command: "steer <run-id> --message <text>", description: "Queue a steering message into a live worker without attaching \u2014 delivered into the agent's context within seconds.", primary: true },
1942
- { command: "stop [<run-id>|--run <id>]", description: "Request stop for one run or local active runs.", primary: true },
1943
- { command: "resume [<run-id>]", description: "Resume an interrupted run on the selected server (defaults to the most recent resumable)." },
1944
- { command: "restart [<run-id>]", description: "Re-dispatch a run from a clean runtime, reopening its Pi session where possible." },
1945
- { command: "timeline --run <id> [--follow]", description: "Stream raw run timeline events (scripts; humans should attach)." },
1946
- { command: "replay <run-id>|--run <id> [--with-session]", description: "Print the run's consolidated run.jsonl as a merged timeline; --with-session interleaves the Pi session log." },
1947
- { command: "delete|cleanup", description: "Remove completed run records/artifacts." }
1948
- ],
1949
- examples: [
1950
- "rig run attach <run-id> # full session console \u2014 live mirror, steering, worker shell",
1951
- "rig run steer <run-id> --message 'focus on the failing test first'",
1952
- "rig run list",
1953
- "rig run show <run-id>",
1954
- "rig run stop <run-id>"
1955
- ],
1956
- next: [
1957
- "Inside the console: the run's COMPLETE transcript loads on open (finished runs too), and new worker turns stream in live.",
1958
- "Inside the console: plain text = steering into the worker's context \xB7 !<cmd> = shell in the WORKER workspace \xB7 /<cmd> includes the worker session's commands \xB7 /rig abort stops the current turn.",
1959
- "The console is read-write but remote-only: nothing runs on your machine; the worker keeps running when you exit.",
1960
- "Use `rig task run --next` to create a new run; interactive mode drops you straight into its console.",
1961
- "Use `--json` when scripts need the full structured record."
1962
- ]
1963
- },
1964
- {
1965
- name: "inbox",
1966
- summary: "Review approval and user-input requests that block worker runs.",
1967
- usage: ["rig inbox <approvals|approve|inputs|respond> [options]"],
1968
- commands: [
1969
- { command: "approvals [--run <id>] [--task <id>]", description: "List pending approvals.", primary: true },
1970
- { command: "inputs [--run <id>] [--task <id>]", description: "List pending user-input requests.", primary: true },
1971
- { command: "approve --run <id> --request <id> --decision approve|reject", description: "Resolve an approval request." },
1972
- { command: "respond --run <id> --request <id> --answer key=value", description: "Answer a user-input request." }
1973
- ],
1974
- examples: [
1975
- "rig inbox approvals",
1976
- "rig inbox inputs --run <run-id>",
1977
- "rig inbox approve --run <run-id> --request <request-id> --decision approve"
1978
- ],
1979
- next: ["Rejoin the run after resolving a block: `rig run attach <run-id> --follow`."]
1980
- },
1981
- {
1982
- name: "stats",
1983
- summary: "Fleet metrics computed from on-disk run journals (no server required).",
1984
- usage: ["rig stats [show] [--since <7d|30d|ISO date>]"],
1985
- commands: [
1986
- { command: "show [--since <window>]", description: "Total runs, completion/failure/needs-attention rates, median run time, steering, stalls, approvals.", primary: true }
1987
- ],
1988
- examples: [
1989
- "rig stats",
1990
- "rig stats --since 7d",
1991
- "rig stats --since 2026-06-01 --json"
1992
- ],
1993
- next: ["Inspect outliers with `rig run list` and `rig run show <run-id>`.", "Use `--json` for the schema'd envelope (see docs/cli-json.md)."]
1994
- },
1995
- {
1996
- name: "inspect",
1997
- summary: "Inspect logs, artifacts, graphs, failures for a task.",
1998
- usage: ["rig inspect <logs|artifacts|failures|graph|audit|diff> --task <id>"],
1999
- commands: [
2000
- { command: "logs --task <id>", description: "Latest run log for a task (local or selected server).", primary: true },
2001
- { command: "artifacts --task <id>", description: "List the task's completion artifacts.", primary: true },
2002
- { command: "failures --task <id>", description: "Recorded failures for a task.", primary: true },
2003
- { command: "diff --task <id>", description: "Changed files for a task.", primary: true },
2004
- { command: "graph", description: "Task dependency graph." },
2005
- { command: "audit", description: "Controlled-command audit trail." }
2006
- ],
2007
- examples: ["rig inspect logs --task <id>", "rig inspect diff --task <id>"],
2008
- next: ["Use `rig stats` for fleet-level metrics across runs."]
2009
- },
2010
- {
2011
- name: "repo",
2012
- summary: "Repository sync/baseline helpers for the Rig-managed checkout.",
2013
- usage: ["rig repo <sync|reset-baseline>"],
2014
- commands: [
2015
- { command: "sync", description: "Sync project repository state.", primary: true },
2016
- { command: "reset-baseline", description: "Reset the managed baseline for the repo." }
2017
- ],
2018
- examples: ["rig repo sync"]
2019
- },
2020
- {
2021
- name: "plugin",
2022
- summary: "Plugin listing, validation, and plugin-contributed commands.",
2023
- usage: ["rig plugin <list|validate|run> [options]"],
2024
- commands: [
2025
- { command: "list", description: "List plugins declared in rig.config.ts and their contributions.", primary: true },
2026
- { command: "validate --task <id>", description: "Run plugin-contributed validators for a task.", primary: true },
2027
- { command: "run <command-id> [args...]", description: "Execute a plugin-contributed CLI command (also callable as `rig <command-id>`)." }
2028
- ],
2029
- examples: ["rig plugin list", "rig plugin run <command-id>"]
2030
- },
2031
- {
2032
- name: "init",
2033
- summary: "Set up Rig for this repo: server, GitHub auth, checkout strategy, task source, and Pi wiring.",
2034
- usage: ["rig init [--yes] [--server local|remote] [--repo owner/repo] [--remote-url <url>]"],
2035
- commands: [
2036
- { command: "init", description: "Interactive setup wizard for a new or existing Rig repo.", primary: true },
2037
- { command: "init --demo", description: "Offline demo project: files task source + 3 sample tasks, zero GitHub.", primary: true },
2038
- { command: "init --yes", description: "Non-interactive setup using detected/default settings.", primary: true },
2039
- { command: "init --server remote --remote-url <url>", description: "Link this repo to a remote Rig server.", primary: true },
2040
- { command: "init --repair", description: "Repair missing private state without replacing project config." }
2041
- ],
2042
- examples: [
2043
- "rig init",
2044
- "rig init --demo",
2045
- "rig init --yes --repo humanity-org/humanwork",
2046
- "rig init --server remote --remote-url https://where.rig-does.work --repo owner/repo"
2047
- ],
2048
- next: ["After init, run `rig server status`.", "Then use `rig task list` and `rig task run --next` for day-to-day work."]
2049
- },
2050
- {
2051
- name: "doctor",
2052
- summary: "Diagnostics for project/server/GitHub/Pi state.",
2053
- usage: ["rig doctor"],
2054
- commands: [
2055
- { command: "doctor", description: "Run setup and runtime diagnostics.", primary: true },
2056
- { command: "check", description: "Compatibility spelling for diagnostics." }
2057
- ],
2058
- examples: ["rig doctor", "rig doctor --json"],
2059
- next: ["Use `rig server status` and `rig github auth status` to inspect common failure points."]
2060
- },
2061
- {
2062
- name: "github",
2063
- summary: "GitHub auth helpers for the selected Rig server.",
2064
- usage: ["rig github auth <status|import-gh|token>"],
2065
- commands: [
2066
- { command: "auth status", description: "Show GitHub auth state.", primary: true },
2067
- { command: "auth import-gh", description: "Import the current `gh` token into the selected server." },
2068
- { command: "auth token --token <token>", description: "Store a token on the selected server." }
2069
- ],
2070
- examples: ["rig github auth status", "rig github auth import-gh"],
2071
- next: ["After auth is valid, use `rig task run --next`."]
2072
- }
2073
- ];
2074
- var ADVANCED_GROUPS = [
2075
- { name: "setup", summary: "Bootstrap/check local setup.", usage: ["rig setup <bootstrap|check|preflight>"], commands: [{ command: "bootstrap|check|preflight", description: "Setup helpers." }] },
2076
- { name: "profile", summary: "Runtime profile/model defaults.", usage: ["rig profile <show|set>"], commands: [{ command: "show", description: "Show active profile." }] },
2077
- {
2078
- name: "review",
2079
- summary: "Inspect or change completion review gate policy.",
2080
- usage: ["rig review <show|set>"],
2081
- commands: [
2082
- { command: "show", description: "Show current review gate settings." },
2083
- { command: "set <off|advisory|required> [--provider greptile]", description: "Change review strictness/provider." }
2084
- ],
2085
- examples: ["rig review show", "rig review set required --provider greptile"],
2086
- next: ["Use `rig inbox approvals` for blocked run handoffs."]
2087
- },
2088
- {
2089
- name: "browser",
2090
- summary: "Browser/app diagnostics for browser-required tasks.",
2091
- usage: ["rig browser <help|explain|demo|app|hp-next> [options]"],
2092
- commands: [
2093
- { command: "help", description: "Rich browser command help (canonical: `rig browser help`)." },
2094
- { command: "explain", description: "Explain the browser-required task contract." },
2095
- { command: "demo", description: "Run browser demo flows against a local page." },
2096
- { command: "app", description: "Launch the Rig Browser workstation app." },
2097
- { command: "hp-next <dev|check|e2e|reset>", description: "Drive the hp-next browser test harness." }
2098
- ]
2099
- },
2100
- {
2101
- name: "pi",
2102
- summary: "Manage Pi extension packages for this project (community extensions from npm/git).",
2103
- usage: ["rig pi <list|add|remove|search> [args]"],
2104
- commands: [
2105
- { command: "list", description: "Show project and user Pi extension packages." },
2106
- { command: "add <source>", description: "Add an npm/git Pi extension to .pi/settings.json (auto-installs at next session)." },
2107
- { command: "remove <source>", description: "Remove an operator-added Pi extension." },
2108
- { command: "search [term]", description: "Discover Pi extension packages on the npm registry." }
2109
- ],
2110
- examples: ["rig pi search subagents", "rig pi add pi-subagents", "rig pi list"],
2111
- next: ["Config-managed extensions: declare `runtime: { pi: { packages: [...] } }` in rig.config.ts \u2014 workers pick them up automatically."]
2112
- },
2113
- { name: "queue", summary: "Run task queues locally.", usage: ["rig queue run [options]"], commands: [{ command: "run", description: "Process queue work." }] },
2114
- { name: "agent", summary: "Runtime agent workspace helpers.", usage: ["rig agent <list|prepare|run|cleanup>"], commands: [{ command: "list", description: "List prepared agents." }] },
2115
- { name: "inspector", summary: "Event stream and drift scanners.", usage: ["rig inspector <stream|scan-upstream-drift>"], commands: [{ command: "stream", description: "Stream events." }] },
2116
- { name: "dist", summary: "Build/install packaged Rig CLI.", usage: ["rig dist <build|install|doctor>"], commands: [{ command: "build", description: "Build distribution." }] },
2117
- { name: "workspace", summary: "Workspace topology/service helpers.", usage: ["rig workspace <summary|topology|remote-hosts>"], commands: [{ command: "summary", description: "Show workspace summary." }] },
2118
- { name: "remote", summary: "Compatibility remote orchestration controls.", usage: ["rig remote <status|watch|pause|resume|...>"], commands: [{ command: "status", description: "Show remote state." }] },
2119
- { name: "git", summary: "Pass through to Rig git-flow helper.", usage: ["rig git <args...>"], commands: [{ command: "<args...>", description: "Advanced git flow operations." }] },
2120
- { name: "harness", summary: "Pass through to runtime harness CLI.", usage: ["rig harness <args...>"], commands: [{ command: "<args...>", description: "Advanced harness operations." }] },
2121
- { name: "test", summary: "Project test wrappers.", usage: ["rig test <unit|e2e|all>"], commands: [{ command: "all", description: "Run configured project tests." }] }
2122
- ];
2123
- var ALL_GROUPS = [...PRIMARY_GROUPS, ...ADVANCED_GROUPS];
2124
- function heading(title) {
2125
- return pc3.bold(pc3.cyan(title));
2126
- }
2127
- function commandLine(command, description) {
2128
- const commandColumn = command.length >= 38 ? `${command} ` : command.padEnd(38);
2129
- return `${pc3.dim("\u2502")} ${pc3.bold(commandColumn)} ${description}`;
2130
- }
2131
- function renderCommandBlock(commands) {
2132
- return commands.map((entry) => commandLine(entry.command, entry.description)).join(`
2133
- `);
236
+ function publicIdentityEnv(projectRoot) {
237
+ const auth = readJsonRecord(resolve(projectRoot, ".rig", "state", "github-auth.json"));
238
+ const connection = readJsonRecord(resolve(projectRoot, ".rig", "state", "connection.json"));
239
+ const values = {};
240
+ const selectedRepo = stringField(auth?.selectedRepo) ?? stringField(connection?.project);
241
+ const userId = githubUserId(auth?.userId);
242
+ const login = stringField(auth?.login);
243
+ const namespaceKey = stringField(auth?.userNamespaceKey) ?? resolveOwnerNamespaceKey(projectRoot);
244
+ if (selectedRepo)
245
+ values.RIG_SELECTED_REPO = selectedRepo;
246
+ if (userId)
247
+ values.RIG_GITHUB_USER_ID = userId;
248
+ if (login)
249
+ values.RIG_GITHUB_LOGIN = login;
250
+ if (namespaceKey)
251
+ values.RIG_GITHUB_NAMESPACE_KEY = namespaceKey;
252
+ return values;
253
+ }
254
+ function taskText(value) {
255
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
256
+ }
257
+ function taskUrl(record) {
258
+ const metadata = record;
259
+ return taskText(metadata.url) ?? taskText(metadata.html_url) ?? taskText(metadata.webUrl);
260
+ }
261
+ function taskBody(record) {
262
+ const metadata = record;
263
+ return taskText(metadata.body) ?? taskText(metadata.description);
264
+ }
265
+ function taskTitle(record) {
266
+ const metadata = record;
267
+ return taskText(metadata.title) ?? taskText(metadata.name) ?? record.id;
268
+ }
269
+ function toExtensionTask(record, sourceKind) {
270
+ return {
271
+ id: record.id,
272
+ title: taskTitle(record),
273
+ status: typeof record.status === "string" ? record.status : null,
274
+ source: sourceKind,
275
+ url: taskUrl(record),
276
+ body: taskBody(record)
277
+ };
2134
278
  }
2135
- function renderGroup(group) {
2136
- const lines = [
2137
- `${heading(`rig ${group.name}`)} \u2014 ${group.summary}`,
2138
- "",
2139
- pc3.bold("Usage"),
2140
- ...group.usage.map((line) => ` ${line}`),
2141
- "",
2142
- pc3.bold("Commands"),
2143
- ...group.commands.map((entry) => commandLine(entry.command, entry.description))
2144
- ];
2145
- if (group.examples?.length) {
2146
- lines.push("", pc3.bold("Examples"), ...group.examples.map((line) => ` ${pc3.dim("$")} ${line}`));
2147
- }
2148
- if (group.next?.length) {
2149
- lines.push("", pc3.bold("Next steps"), ...group.next.map((line) => ` ${pc3.dim("\u203A")} ${line}`));
279
+ async function loadConfiguredTaskSource(projectRoot) {
280
+ const normalizedRoot = resolve(projectRoot);
281
+ const config = await loadConfig(normalizedRoot);
282
+ const pluginHost = createPluginHost(config.plugins);
283
+ const taskSourceFactory = pluginHost.resolveTaskSourceFactoryByKind(config.taskSource.kind);
284
+ if (!taskSourceFactory) {
285
+ const kinds = pluginHost.listExecutableTaskSources().map((entry) => entry.kind).join(", ") || "none";
286
+ throw new Error(`No task source factory registered for kind "${config.taskSource.kind}". Registered kinds: ${kinds}.`);
2150
287
  }
2151
- if (group.advanced?.length) {
2152
- lines.push("", pc3.bold("Compatibility / advanced"), ...group.advanced.map((line) => ` ${pc3.dim("\u203A")} ${line}`));
2153
- }
2154
- return lines.join(`
2155
- `);
288
+ return {
289
+ kind: config.taskSource.kind,
290
+ source: taskSourceFactory.factory(config.taskSource, { projectRoot: normalizedRoot })
291
+ };
2156
292
  }
2157
- function renderTopLevelHelp() {
2158
- return [
2159
- `${heading("rig")} ${pc3.dim("\u2014 server-owned task/run control plane for Pi-backed engineering work")}`,
2160
- pc3.dim("The loop: pick a task, dispatch an agent, open its Pi console (`rig run attach <id>`) to watch and steer it live, clear inbox gates, merge."),
2161
- "",
2162
- ...TOP_LEVEL_SECTIONS.flatMap((section) => [
2163
- `${pc3.bold(pc3.magenta(`\u25C7 ${section.title}`))} \u2014 ${pc3.dim(section.subtitle)}`,
2164
- renderCommandBlock(section.commands),
2165
- ""
2166
- ]),
2167
- pc3.dim("More: `rig help --advanced` for dev/compatibility commands; `rig <group> --help` for rich per-group help; `rig --version` for the installed version."),
2168
- "",
2169
- pc3.bold("Global options"),
2170
- commandLine("--project <path>", "Use a project root instead of auto-discovery."),
2171
- commandLine("--json", "Emit structured output for scripts/agents."),
2172
- commandLine("--dry-run", "Print the command plan without mutating state.")
2173
- ].join(`
2174
- `).trimEnd();
2175
- }
2176
- function renderGroupHelp(groupName) {
2177
- const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
2178
- return group ? renderGroup(group) : null;
2179
- }
2180
- function printGroupHelpDocument(groupName) {
2181
- console.log(renderGroupHelp(groupName) ?? renderTopLevelHelp());
293
+ async function listTasksFromSource(projectRoot, deps = {}) {
294
+ const { kind, source } = await (deps.loadTaskSource ?? loadConfiguredTaskSource)(projectRoot);
295
+ return (await source.list()).map((task) => toExtensionTask(task, kind));
296
+ }
297
+ async function getTaskFromSource(projectRoot, taskId, deps = {}) {
298
+ const tasks = await listTasksFromSource(projectRoot, deps);
299
+ return tasks.find((task) => task.id === taskId) ?? null;
300
+ }
301
+ function runningFromCompiledBinary() {
302
+ return import.meta.url.includes("$bunfs");
303
+ }
304
+ function resolveRigRunBin() {
305
+ if (runningFromCompiledBinary())
306
+ return resolve(dirname(process.execPath), "rig-run");
307
+ return resolve(dirname(fileURLToPath(import.meta.url)), "../../../rig-host/bin/rig-run.ts");
308
+ }
309
+ async function defaultRunRunProcess(input) {
310
+ const { runRunProcess } = await import("@rig/rig-host");
311
+ return await runRunProcess(input);
312
+ }
313
+ function shellQuote(value) {
314
+ return `'${value.replace(/'/g, "'\\''")}'`;
315
+ }
316
+ function readProjectSlug(projectRoot) {
317
+ const connection = readJsonRecord(resolve(projectRoot, ".rig", "state", "connection.json"));
318
+ return stringField(connection?.project) ?? null;
319
+ }
320
+ function resolveProjectOriginUrl(projectRoot) {
321
+ const slug = readProjectSlug(projectRoot);
322
+ return slug && /^[^/]+\/[^/]+$/.test(slug) ? `https://github.com/${slug}.git` : null;
323
+ }
324
+ async function spawnRunProcess(input, deps = {}) {
325
+ const runId = (deps.uuid ?? randomUUID)();
326
+ const env = deps.env ?? process.env;
327
+ const identityEnv = publicIdentityEnv(input.projectRoot);
328
+ const selected = resolveSelectedRemote(input.projectRoot, env);
329
+ const sshTarget = selected?.sshTarget ?? env.RIG_REMOTE_ALIAS?.trim();
330
+ if (sshTarget) {
331
+ const namespaceKey = identityEnv.RIG_GITHUB_NAMESPACE_KEY ?? resolveOwnerNamespaceKey(input.projectRoot, env) ?? "";
332
+ const sh = shellQuote;
333
+ const originUrl = resolveProjectOriginUrl(input.projectRoot);
334
+ const repoName = (readProjectSlug(input.projectRoot)?.split("/").pop() ?? "project").replace(/[^A-Za-z0-9._-]/g, "-");
335
+ const checkoutExpr = selected?.checkout ? sh(selected.checkout) : `"$HOME/.rig/checkouts/${repoName}"`;
336
+ const identityAssignments = Object.entries(identityEnv).map(([k, v]) => `${k}=${sh(v)}`);
337
+ if (namespaceKey && !identityEnv.RIG_GITHUB_NAMESPACE_KEY)
338
+ identityAssignments.push(`RIG_GITHUB_NAMESPACE_KEY=${sh(namespaceKey)}`);
339
+ const runInvocation = [
340
+ `RIG_RUN_ID=${sh(runId)}`,
341
+ `RIG_TASK_ID=${sh(input.taskId)}`,
342
+ ...identityAssignments,
343
+ selected?.registryBaseUrl ? `RIG_REGISTRY_URL=${sh(selected.registryBaseUrl)}` : "",
344
+ `rig run start --task ${sh(input.taskId)}`
345
+ ].filter(Boolean).join(" ");
346
+ const provisionAndRun = [
347
+ "set -e",
348
+ `CHECKOUT=${checkoutExpr}`,
349
+ originUrl ? `[ -d "$CHECKOUT/.git" ] || git clone ${sh(originUrl)} "$CHECKOUT"` : `[ -d "$CHECKOUT/.git" ] || { echo "rig: remote checkout $CHECKOUT missing and no origin to clone" >&2; exit 1; }`,
350
+ `cd "$CHECKOUT"`,
351
+ "git fetch origin --prune --quiet || true",
352
+ runInvocation
353
+ ].join("; ");
354
+ const child = (deps.spawn ?? nodeSpawn)("ssh", [sshTarget, `bash -lc ${sh(provisionAndRun)}`], {
355
+ cwd: input.projectRoot,
356
+ env: { ...env, ...identityEnv },
357
+ detached: true,
358
+ stdio: "ignore"
359
+ });
360
+ child.unref();
361
+ return { runId };
362
+ }
363
+ await (deps.runRunProcess ?? defaultRunRunProcess)({
364
+ projectRoot: input.projectRoot,
365
+ taskId: input.taskId,
366
+ runId,
367
+ title: input.title,
368
+ rigRunBin: (deps.resolveRigRunBin ?? resolveRigRunBin)()
369
+ });
370
+ return { runId };
2182
371
  }
2183
372
 
2184
373
  // packages/cli/src/commands/task.ts
2185
- import { buildPluginHostContext } from "@rig/runtime/control-plane/plugin-host-context";
2186
- import { loadConfig } from "@rig/core/load-config";
2187
- async function readStdin() {
2188
- const chunks = [];
2189
- for await (const chunk of process.stdin) {
2190
- chunks.push(Buffer.from(chunk));
2191
- }
2192
- return Buffer.concat(chunks).toString("utf-8");
374
+ var CLOSED_STATUSES = {
375
+ closed: true,
376
+ completed: true,
377
+ complete: true,
378
+ done: true,
379
+ cancelled: true,
380
+ canceled: true,
381
+ merged: true,
382
+ resolved: true
383
+ };
384
+ var NOT_READY_STATUSES = {
385
+ ...CLOSED_STATUSES,
386
+ blocked: true,
387
+ in_progress: true,
388
+ "in-progress": true,
389
+ running: true,
390
+ active: true
391
+ };
392
+ function normalizeTaskId(value) {
393
+ const trimmed = value?.trim();
394
+ if (!trimmed)
395
+ return;
396
+ return trimmed.startsWith("#") && /^#\d+$/.test(trimmed) ? trimmed.slice(1) : trimmed;
2193
397
  }
2194
- function normalizeAssigneeAlias(value) {
2195
- if (!value)
398
+ function parsePositiveLimit(value) {
399
+ if (value === undefined)
2196
400
  return;
2197
- return value.trim().toLowerCase() === "me" ? "@me" : value;
401
+ const parsed = Number.parseInt(value, 10);
402
+ if (!Number.isFinite(parsed) || parsed <= 0 || String(parsed) !== value.trim()) {
403
+ throw new CliError("--limit must be a positive integer.", 1, { hint: "Re-run with a positive number, e.g. `rig task list --limit 20`." });
404
+ }
405
+ return parsed;
2198
406
  }
2199
407
  function parseTaskFilters(args) {
2200
408
  let pending = args;
@@ -2202,472 +410,409 @@ function parseTaskFilters(args) {
2202
410
  pending = assigneeResult.rest;
2203
411
  const stateResult = takeOption(pending, "--state");
2204
412
  pending = stateResult.rest;
2205
- const statusResult = takeOption(pending, "--status");
2206
- pending = statusResult.rest;
2207
413
  const limitResult = takeOption(pending, "--limit");
2208
414
  pending = limitResult.rest;
2209
- const assignee = normalizeAssigneeAlias(assigneeResult.value);
2210
- const limit = (() => {
2211
- if (!limitResult.value)
2212
- return;
2213
- const parsed = Number.parseInt(limitResult.value, 10);
2214
- if (!Number.isFinite(parsed) || parsed < 1) {
2215
- throw new CliError("--limit must be a positive integer.", 2, { hint: "Re-run with a positive number, e.g. `rig task list --limit 20`." });
2216
- }
2217
- return parsed;
2218
- })();
2219
- const filters = {
2220
- ...assignee ? { assignee } : {},
2221
- ...stateResult.value ? { state: stateResult.value } : {},
2222
- ...statusResult.value ? { status: statusResult.value } : {},
2223
- ...limit !== undefined ? { limit } : {}
415
+ const searchResult = takeOption(pending, "--search");
416
+ pending = searchResult.rest;
417
+ const state = stateResult.value?.trim().toLowerCase();
418
+ if (state !== undefined && state !== "open" && state !== "closed") {
419
+ throw new CliError(`Invalid --state value: ${stateResult.value}.`, 1, { hint: "Use `--state open` or `--state closed`." });
420
+ }
421
+ const assignee = normalizeAssigneeFilter(assigneeResult.value);
422
+ const limit = parsePositiveLimit(limitResult.value);
423
+ const search = searchResult.value?.trim();
424
+ return {
425
+ filters: {
426
+ ...assignee ? { assignee } : {},
427
+ ...state ? { state } : {},
428
+ ...limit !== undefined ? { limit } : {},
429
+ ...search ? { search } : {}
430
+ },
431
+ rest: pending
2224
432
  };
2225
- return { filters, rest: pending };
2226
433
  }
2227
- function mapConfiguredRuntimeMode(mode) {
2228
- if (!mode)
434
+ function normalizeAssigneeFilter(value) {
435
+ const trimmed = value?.trim();
436
+ if (!trimmed)
2229
437
  return;
2230
- return mode === "yolo" ? "full-access" : mode;
438
+ const lowered = trimmed.toLowerCase();
439
+ if (lowered === "me" || lowered === "@me") {
440
+ return currentLogin() ?? "@me";
441
+ }
442
+ return trimmed.startsWith("@") ? trimmed.slice(1) : trimmed;
2231
443
  }
2232
- async function loadTaskRunProjectDefaults(projectRoot) {
2233
- try {
2234
- const config = await loadConfig(projectRoot);
2235
- return {
2236
- runtimeAdapter: config.runtime?.harness,
2237
- model: config.runtime?.model,
2238
- runtimeMode: mapConfiguredRuntimeMode(config.runtime?.mode),
2239
- prMode: config.pr?.mode
2240
- };
2241
- } catch {
2242
- return {};
444
+ function currentLogin() {
445
+ for (const key of ["RIG_GITHUB_LOGIN", "GITHUB_ACTOR", "GH_USER", "USER", "USERNAME"]) {
446
+ const value = process.env[key]?.trim();
447
+ if (value)
448
+ return value;
2243
449
  }
450
+ return;
2244
451
  }
2245
- function normalizePrMode(value) {
2246
- if (!value)
2247
- return;
2248
- if (value === "auto" || value === "ask" || value === "off")
2249
- return value;
2250
- throw new CliError("--pr must be auto, ask, or off.", 2, { hint: "Re-run with `--pr auto|ask|off`, or pass `--no-pr` to disable the PR." });
2251
- }
2252
- function detectLocalDirtyState(projectRoot) {
2253
- const result = spawnSync("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
2254
- if (result.status !== 0)
2255
- return { dirty: false, modified: 0, untracked: 0, lines: [] };
2256
- const lines = result.stdout.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean);
2257
- return {
2258
- dirty: lines.length > 0,
2259
- modified: lines.filter((line) => !line.startsWith("?? ")).length,
2260
- untracked: lines.filter((line) => line.startsWith("?? ")).length,
2261
- lines
2262
- };
452
+ function isRecord(value) {
453
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2263
454
  }
2264
- function selectedServerKind(projectRoot) {
2265
- try {
2266
- return resolveSelectedConnection(projectRoot)?.connection.kind === "remote" ? "remote" : "local";
2267
- } catch {
2268
- return "local";
2269
- }
455
+ function readTaskStatus(task) {
456
+ const value = task.status;
457
+ return typeof value === "string" ? value.trim().toLowerCase() : "";
2270
458
  }
2271
- async function resolveDirtyBaselineForTaskRun(context, explicit) {
2272
- if (explicit && explicit !== "head" && explicit !== "dirty-snapshot") {
2273
- throw new CliError("--dirty-baseline must be head or dirty-snapshot.", 2, { hint: "Re-run with `--dirty-baseline head` or `--dirty-baseline dirty-snapshot`." });
2274
- }
2275
- if (selectedServerKind(context.projectRoot) !== "local") {
2276
- return { mode: explicit === "dirty-snapshot" ? "dirty-snapshot" : "head", state: null };
2277
- }
2278
- const state = detectLocalDirtyState(context.projectRoot);
2279
- if (!state.dirty)
2280
- return { mode: "head", state };
2281
- if (context.outputMode === "text") {
2282
- console.log(`Repo state: dirty (${state.modified} modified, ${state.untracked} untracked).`);
2283
- }
2284
- if (explicit)
2285
- return { mode: explicit, state };
2286
- if (context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY) {
2287
- const answer = await droneConfirm({
2288
- message: "Include current uncommitted changes in run baseline?",
2289
- initialValue: false
2290
- });
2291
- if (answer === null) {
2292
- droneCancel("Run cancelled.");
2293
- throw new CliError("Run cancelled by user.", 1);
2294
- }
2295
- return { mode: answer ? "dirty-snapshot" : "head", state };
459
+ function taskMatchesState(task, state) {
460
+ if (!state)
461
+ return true;
462
+ const closed = CLOSED_STATUSES[readTaskStatus(task)] === true;
463
+ return state === "closed" ? closed : !closed;
464
+ }
465
+ function taskMatchesSearch(task, search) {
466
+ const needle = search?.trim().toLowerCase();
467
+ if (!needle)
468
+ return true;
469
+ const title = typeof task.title === "string" ? task.title : "";
470
+ const body = typeof task.body === "string" ? task.body : "";
471
+ const description = typeof task.description === "string" ? task.description : "";
472
+ return `${task.id}
473
+ ${title}
474
+ ${body}
475
+ ${description}`.toLowerCase().includes(needle);
476
+ }
477
+ function collectAssigneeLogins(value) {
478
+ if (typeof value === "string")
479
+ return [value];
480
+ if (Array.isArray(value))
481
+ return value.flatMap((entry) => collectAssigneeLogins(entry));
482
+ if (isRecord(value)) {
483
+ return [value.login, value.username, value.name, value.id].flatMap((entry) => collectAssigneeLogins(entry));
2296
484
  }
2297
- return { mode: "head", state };
485
+ return [];
2298
486
  }
2299
- function normalizeTaskRunTaskId(value) {
2300
- const trimmed = value?.trim() ?? "";
2301
- if (!trimmed)
2302
- return null;
2303
- const issueNumber = trimmed.match(/^#(\d+)$/)?.[1];
2304
- return issueNumber ?? trimmed;
487
+ function taskAssignees(task) {
488
+ const raw = isRecord(task.raw) ? task.raw : null;
489
+ return [
490
+ task.assignee,
491
+ task.assignees,
492
+ task.assignedTo,
493
+ task.owner,
494
+ raw?.assignee,
495
+ raw?.assignees,
496
+ raw?.assignedTo,
497
+ raw?.owner
498
+ ].flatMap((value) => collectAssigneeLogins(value));
499
+ }
500
+ function taskMatchesAssignee(task, assignee) {
501
+ if (!assignee)
502
+ return true;
503
+ const needle = assignee.startsWith("@") ? assignee.slice(1) : assignee;
504
+ return taskAssignees(task).some((login) => {
505
+ const normalized = login.startsWith("@") ? login.slice(1) : login;
506
+ return normalized.localeCompare(needle, undefined, { sensitivity: "accent" }) === 0;
507
+ });
2305
508
  }
2306
- function readTaskId(task) {
2307
- return typeof task.id === "string" && task.id.trim().length > 0 ? task.id : null;
509
+ function applyFilters(tasks, filters) {
510
+ const filtered = tasks.filter((task) => taskMatchesAssignee(task, filters.assignee)).filter((task) => taskMatchesState(task, filters.state)).filter((task) => taskMatchesSearch(task, filters.search));
511
+ return filters.limit === undefined ? filtered : filtered.slice(0, filters.limit);
2308
512
  }
2309
- function readTaskString(task, key) {
2310
- const value = task[key];
2311
- return typeof value === "string" && value.trim().length > 0 ? value : null;
513
+ function isReadyTask(task) {
514
+ const status = readTaskStatus(task);
515
+ return status.length === 0 || NOT_READY_STATUSES[status] !== true;
2312
516
  }
2313
- function summarizeTask(task, options = {}) {
2314
- const raw = task.raw && typeof task.raw === "object" && !Array.isArray(task.raw) ? task.raw : null;
517
+ function asDependencyProjection(task) {
518
+ const record = task;
2315
519
  return {
2316
- id: readTaskId(task),
2317
- title: readTaskString(task, "title"),
2318
- status: readTaskString(task, "status"),
2319
- source: typeof task.source === "string" ? task.source : undefined,
2320
- url: typeof raw?.url === "string" ? raw.url : undefined,
2321
- number: typeof raw?.number === "number" ? raw.number : undefined,
2322
- labels: Array.isArray(task.labels) ? task.labels : Array.isArray(raw?.labels) ? raw.labels : undefined,
2323
- assignees: Array.isArray(raw?.assignees) ? raw.assignees : undefined,
2324
- readiness: typeof task.readiness === "string" || typeof task.readiness === "boolean" ? task.readiness : undefined,
2325
- validators: Array.isArray(task.validators) ? task.validators : Array.isArray(task.validation) ? task.validation : undefined,
2326
- ...options.raw ? { raw: raw ?? task } : {}
520
+ ...record,
521
+ status: typeof record.status === "string" && record.status.trim() ? record.status : "open",
522
+ priority: record.priority ?? "P2",
523
+ metadata: isRecord(record.metadata) ? record.metadata : {}
2327
524
  };
2328
525
  }
2329
- async function validatorRegistryForTaskCommands(projectRoot) {
2330
- return buildPluginHostContext(projectRoot).then((ctx) => ctx?.validatorRegistry ?? undefined).catch(() => {
2331
- return;
526
+ function selectNextTask(tasks, filters) {
527
+ const matching = applyFilters(tasks, { ...filters, limit: undefined }).filter(isReadyTask);
528
+ const selected = selectNextReadyTaskByPriority(matching.map(asDependencyProjection), {
529
+ filter: (task) => isReadyTask(task)
2332
530
  });
531
+ return selected ?? matching[0] ?? null;
2333
532
  }
2334
- async function executeTask(context, args, options) {
2335
- if (args.length === 0) {
2336
- if (context.outputMode === "text") {
2337
- printGroupHelpDocument("task");
2338
- }
2339
- return { ok: true, group: "task", command: "help" };
533
+ function readTaskTitle(task) {
534
+ if (!task)
535
+ return null;
536
+ for (const key of ["title", "summary", "name"]) {
537
+ const value = task[key];
538
+ if (typeof value === "string" && value.trim())
539
+ return value.trim();
540
+ }
541
+ return null;
542
+ }
543
+ function printText(context, message) {
544
+ if (context.outputMode === "text") {
545
+ printFormattedOutput(message);
546
+ }
547
+ }
548
+ async function listTasksForCommand(projectRoot, deps) {
549
+ if (deps.listTasks)
550
+ return deps.listTasks(projectRoot);
551
+ if (deps.loadTaskSource) {
552
+ const { kind, source } = await deps.loadTaskSource(projectRoot);
553
+ return (await source.list()).map((task) => ({ ...task, source: kind }));
554
+ }
555
+ return listTasksFromSource(projectRoot);
556
+ }
557
+ async function getTaskForCommand(projectRoot, taskId, deps) {
558
+ if (deps.getTask)
559
+ return deps.getTask(projectRoot, taskId);
560
+ if (deps.loadTaskSource) {
561
+ const { kind, source } = await deps.loadTaskSource(projectRoot);
562
+ const task = source.get ? await source.get(taskId) : (await source.list()).find((entry) => entry.id === taskId);
563
+ return task ? { ...task, source: kind } : null;
564
+ }
565
+ return getTaskFromSource(projectRoot, taskId);
566
+ }
567
+ async function defaultLoadTaskSource(projectRoot) {
568
+ const config = await loadConfig2(projectRoot);
569
+ const pluginHost = createPluginHost2(config.plugins);
570
+ const factory = pluginHost.resolveTaskSourceFactoryByKind(config.taskSource.kind);
571
+ if (!factory) {
572
+ const kinds = pluginHost.listExecutableTaskSources().map((entry) => entry.kind).join(", ") || "none";
573
+ throw new CliError(`No task source factory registered for kind ${config.taskSource.kind}.`, 1, { hint: `Registered task sources: ${kinds}.` });
574
+ }
575
+ return { kind: config.taskSource.kind, source: factory.factory(config.taskSource, { projectRoot }) };
576
+ }
577
+ function getTaskCreator(source) {
578
+ const record = source;
579
+ if (typeof record.createTask === "function")
580
+ return record.createTask.bind(source);
581
+ if (typeof record.create === "function")
582
+ return record.create.bind(source);
583
+ return null;
584
+ }
585
+ async function executeReportBug(context, args, deps) {
586
+ let pending = args;
587
+ const titleResult = takeOption(pending, "--title");
588
+ pending = titleResult.rest;
589
+ const bodyResult = takeOption(pending, "--body");
590
+ pending = bodyResult.rest;
591
+ requireNoExtraArgs(pending, "rig task report-bug --title <text> [--body <text>]");
592
+ const title = titleResult.value?.trim();
593
+ if (!title) {
594
+ throw new CliError("rig task report-bug requires --title.", 1, { hint: 'Re-run with `rig task report-bug --title "Short bug title"`.' });
595
+ }
596
+ const { kind, source } = await (deps.loadTaskSource ?? defaultLoadTaskSource)(context.projectRoot);
597
+ const creator = getTaskCreator(source);
598
+ if (!creator) {
599
+ throw new CliError(`The configured ${kind} task source does not expose a task creation API, so rig task report-bug cannot create a bug task.`, 1, {
600
+ hint: "Create the bug in the configured task source directly, or install a task source that supports createTask/create."
601
+ });
602
+ }
603
+ const created = await creator({
604
+ title,
605
+ body: bodyResult.value ?? "Bug reported via `rig task report-bug`.",
606
+ status: "open",
607
+ labels: ["bug"],
608
+ type: "bug"
609
+ });
610
+ const taskId = typeof created === "string" ? created : isRecord(created) && typeof created.id === "string" ? created.id : undefined;
611
+ printText(context, taskId ? `Created bug task ${taskId}.` : "Created bug task.");
612
+ return { ok: true, group: "task", command: "report-bug", details: { taskId: taskId ?? null, source: kind } };
613
+ }
614
+ async function resolveRunTask(context, rawTaskId, useNext, filters, deps) {
615
+ if (useNext) {
616
+ const tasks = await listTasksForCommand(context.projectRoot, deps);
617
+ const task = selectNextTask(tasks, filters);
618
+ const taskId2 = normalizeTaskId(task?.id);
619
+ if (!task || !taskId2)
620
+ throw new CliError("No ready task found.", 1, { hint: "Run `rig task list` to inspect available tasks." });
621
+ return { taskId: taskId2, task };
622
+ }
623
+ const taskId = normalizeTaskId(rawTaskId);
624
+ if (!taskId) {
625
+ throw new CliError("Missing task id for rig task run.", 1, { hint: "Use `rig task run <task-id>`, `rig task run --task <id>`, or `rig task run --next`." });
2340
626
  }
627
+ return { taskId, task: await getTaskForCommand(context.projectRoot, taskId, deps) };
628
+ }
629
+ async function executeTask(context, args, deps = {}) {
2341
630
  const [command = "help", ...rest] = args;
2342
631
  switch (command) {
632
+ case "help":
633
+ printText(context, "Usage: rig task <list|next|show|details|info|scope|deps|status|lookup|record|run|ready|validate|verify|reopen|artifacts|artifact-dir|artifact-write|report-bug> [options]");
634
+ return { ok: true, group: "task", command: "help" };
2343
635
  case "list": {
2344
- let pending = rest;
2345
- const rawResult = takeFlag(pending, "--raw");
2346
- pending = rawResult.rest;
2347
- const { filters, rest: remaining } = parseTaskFilters(pending);
2348
- requireNoExtraArgs(remaining, "rig task list [--raw] [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
2349
- const tasks = await withSpinner("Reading tasks from server\u2026", () => listWorkspaceTasksViaServer(context, filters), { outputMode: context.outputMode });
2350
- if (context.outputMode === "text") {
2351
- const renderedTasks = rawResult.value ? tasks.map((task) => summarizeTask(task, { raw: true })) : tasks.map((task) => summarizeTask(task));
2352
- printFormattedOutput(formatTaskList(renderedTasks, { raw: rawResult.value }));
2353
- await printPendingInboxFooter(context);
636
+ const parsed = parseTaskFilters(rest);
637
+ requireNoExtraArgs(parsed.rest, "rig task list [--assignee <login|me|@me>] [--state open|closed] [--search <text>] [--limit <n>]");
638
+ const tasks = applyFilters(await listTasksForCommand(context.projectRoot, deps), parsed.filters);
639
+ printText(context, formatTaskList(tasks));
640
+ return { ok: true, group: "task", command, details: { tasks, count: tasks.length } };
641
+ }
642
+ case "next": {
643
+ const parsed = parseTaskFilters(rest);
644
+ requireNoExtraArgs(parsed.rest, "rig task next [--assignee <login|me|@me>] [--state open|closed] [--search <text>] [--limit <n>]");
645
+ const tasks = await listTasksForCommand(context.projectRoot, deps);
646
+ const task = selectNextTask(tasks, parsed.filters);
647
+ if (!task) {
648
+ printText(context, formatTaskList([]));
649
+ return { ok: true, group: "task", command, details: { task: null } };
2354
650
  }
2355
- return {
2356
- ok: true,
2357
- group: "task",
2358
- command,
2359
- details: { count: tasks.length, filters, raw: rawResult.value, tasks: tasks.map((task) => summarizeTask(task, { raw: rawResult.value })) }
2360
- };
651
+ printText(context, formatTaskCard(task, { selected: true }));
652
+ return { ok: true, group: "task", command, details: { task } };
2361
653
  }
2362
654
  case "show": {
2363
655
  let pending = rest;
2364
656
  const rawResult = takeFlag(pending, "--raw");
2365
657
  pending = rawResult.rest;
2366
- const taskOption = takeOption(pending, "--task");
2367
- const positional = taskOption.rest.length > 0 && taskOption.rest[0] && !taskOption.rest[0].startsWith("-") ? taskOption.rest[0] : undefined;
2368
- const remaining = positional ? taskOption.rest.slice(1) : taskOption.rest;
2369
- requireNoExtraArgs(remaining, "rig task show <id>|--task <id> [--raw]");
2370
- const taskId3 = normalizeTaskRunTaskId(taskOption.value ?? positional);
2371
- if (!taskId3)
2372
- throw new CliError("task show requires a task id.", 2, { hint: "Run `rig task list` to find ids, then `rig task show <id>`." });
2373
- const task = await withSpinner(`Reading task ${taskId3} from server\u2026`, () => getWorkspaceTaskViaServer(context, taskId3), { outputMode: context.outputMode });
658
+ const taskResult = takeOption(pending, "--task");
659
+ pending = taskResult.rest;
660
+ const positional = pending[0]?.startsWith("-") ? undefined : pending[0];
661
+ requireNoExtraArgs(positional ? pending.slice(1) : pending, "rig task show <id>|--task <id> [--raw]");
662
+ const taskId = requireTask(normalizeTaskId(taskResult.value ?? positional), "rig task show <id>|--task <id> [--raw]");
663
+ const task = await getTaskForCommand(context.projectRoot, taskId, deps);
2374
664
  if (!task)
2375
- throw new CliError(`Task not found: ${taskId3}`, 3, { hint: "Run `rig task list` to see available tasks." });
2376
- const summary = summarizeTask(task, { raw: true });
2377
- if (context.outputMode === "text") {
2378
- printFormattedOutput(rawResult.value ? JSON.stringify(summary, null, 2) : formatTaskDetails(summary));
2379
- }
2380
- return { ok: true, group: "task", command, details: { task: summary, raw: rawResult.value } };
2381
- }
2382
- case "next": {
2383
- const { filters, rest: remaining } = parseTaskFilters(rest);
2384
- requireNoExtraArgs(remaining, "rig task next [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
2385
- const selected = await withSpinner("Selecting next ready task\u2026", () => selectNextWorkspaceTaskViaServer(context, filters), { outputMode: context.outputMode });
2386
- if (context.outputMode === "text") {
2387
- if (selected.task) {
2388
- printFormattedOutput(formatTaskCard(summarizeTask(selected.task, { raw: true }), { title: "Selected task", selected: true }));
2389
- } else {
2390
- printFormattedOutput("No matching tasks.\n\nNext\n\u203A Try `rig task list` to inspect available work.\n\u203A Check server: `rig server status`");
2391
- }
2392
- }
2393
- return {
2394
- ok: true,
2395
- group: "task",
2396
- command,
2397
- details: {
2398
- count: selected.count,
2399
- filters,
2400
- task: selected.task ? summarizeTask(selected.task) : null
2401
- }
2402
- };
2403
- }
2404
- case "info": {
2405
- const { value: task, rest: remaining } = takeOption(rest, "--task");
2406
- requireNoExtraArgs(remaining, "rig task info [--task <task-id>]");
2407
- await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, task || undefined));
2408
- return { ok: true, group: "task", command, details: { task: task || null } };
2409
- }
2410
- case "scope": {
2411
- const filesFlag = takeFlag(rest, "--files");
2412
- const { value: task, rest: remaining } = takeOption(filesFlag.rest, "--task");
2413
- requireNoExtraArgs(remaining, "rig task scope [--task <id>] [--files]");
2414
- await withMutedConsole(context.outputMode === "json", () => taskScope(context.projectRoot, filesFlag.value, task || undefined));
2415
- return { ok: true, group: "task", command, details: { files: filesFlag.value, task: task || null } };
2416
- }
2417
- case "deps":
2418
- requireNoExtraArgs(rest, "rig task deps");
2419
- await withMutedConsole(context.outputMode === "json", () => taskDeps(context.projectRoot));
2420
- return { ok: true, group: "task", command };
2421
- case "status":
2422
- requireNoExtraArgs(rest, "rig task status");
2423
- withMutedConsole(context.outputMode === "json", () => taskStatus2(context.projectRoot));
2424
- return { ok: true, group: "task", command };
2425
- case "artifacts":
2426
- requireNoExtraArgs(rest, "rig task artifacts");
2427
- withMutedConsole(context.outputMode === "json", () => taskArtifacts(context.projectRoot));
2428
- return { ok: true, group: "task", command };
2429
- case "artifact-dir": {
2430
- requireNoExtraArgs(rest, "rig task artifact-dir");
2431
- const path = taskArtifactDir(context.projectRoot);
2432
- if (context.outputMode === "text") {
2433
- console.log(path);
2434
- }
2435
- return { ok: true, group: "task", command, details: { path } };
2436
- }
2437
- case "artifact-write": {
2438
- if (rest.length < 1) {
2439
- throw new CliError(`Usage: rig task artifact-write <filename> [--file <path>]
2440
- ` + ` Reads content from stdin (or --file), writes to the active task artifact dir.
2441
- ` + " Example: echo '...' | rig task artifact-write collection-audit.md");
2442
- }
2443
- const artifactFilename = rest[0];
2444
- const fileFlag = takeOption(rest.slice(1), "--file");
2445
- let content;
2446
- if (fileFlag.value) {
2447
- content = readFileSync4(resolve3(context.projectRoot, fileFlag.value), "utf-8");
2448
- } else {
2449
- content = await readStdin();
2450
- }
2451
- if (!artifactFilename) {
2452
- throw new CliError("Usage: rig task artifact-write <filename> [--file path]");
2453
- }
2454
- withMutedConsole(context.outputMode === "json", () => taskArtifactWrite(context.projectRoot, artifactFilename, content));
2455
- return { ok: true, group: "task", command, details: { filename: artifactFilename } };
2456
- }
2457
- case "report-bug":
2458
- return options.executeTaskReportBug(context, rest);
2459
- case "lookup": {
2460
- if (rest.length !== 1) {
2461
- throw new CliError("Usage: rig task lookup <task-id>");
2462
- }
2463
- const lookupId = rest[0];
2464
- if (!lookupId) {
2465
- throw new CliError("Usage: rig task lookup <task-id>");
2466
- }
2467
- const result = taskLookup(context.projectRoot, lookupId);
2468
- if (context.outputMode === "text") {
2469
- console.log(result);
2470
- }
2471
- return { ok: true, group: "task", command, details: { id: lookupId, result } };
665
+ throw new CliError(`Task not found: ${taskId}`, 1, { hint: "Run `rig task list` to see available task ids." });
666
+ printText(context, rawResult.value ? JSON.stringify(task, null, 2) : formatTaskCard(task));
667
+ return { ok: true, group: "task", command, details: task };
2472
668
  }
2473
- case "record": {
2474
- if (rest.length < 2) {
2475
- throw new CliError("Usage: rig task record <decision|failure> <text>");
2476
- }
2477
- const type = rest[0];
2478
- if (type !== "decision" && type !== "failure") {
2479
- throw new CliError("Usage: rig task record <decision|failure> <text>");
2480
- }
2481
- withMutedConsole(context.outputMode === "json", () => taskRecord(context.projectRoot, type, rest.slice(1).join(" ")));
2482
- return { ok: true, group: "task", command, details: { type: rest[0] } };
669
+ case "details": {
670
+ const taskResult = takeOption(rest, "--task");
671
+ requireNoExtraArgs(taskResult.rest, "rig task details --task <id>");
672
+ const taskId = requireTask(normalizeTaskId(taskResult.value), "rig task details --task <id>");
673
+ const task = await getTaskForCommand(context.projectRoot, taskId, deps);
674
+ if (!task)
675
+ throw new CliError(`Task not found: ${taskId}`, 1, { hint: "Run `rig task list` to see available task ids." });
676
+ printText(context, formatTaskDetails(task));
677
+ return { ok: true, group: "task", command, details: task };
2483
678
  }
2484
- case "ready":
2485
- requireNoExtraArgs(rest, "rig task ready");
2486
- await withMutedConsole(context.outputMode === "json", () => taskReady(context.projectRoot));
2487
- return { ok: true, group: "task", command };
2488
679
  case "run": {
2489
680
  let pending = rest;
2490
681
  const nextResult = takeFlag(pending, "--next");
2491
682
  pending = nextResult.rest;
683
+ const detachResult = takeFlag(pending, "--detach");
684
+ pending = detachResult.rest;
2492
685
  const taskResult = takeOption(pending, "--task");
2493
686
  pending = taskResult.rest;
2494
687
  const titleResult = takeOption(pending, "--title");
2495
688
  pending = titleResult.rest;
2496
- const runtimeAdapterResult = takeOption(pending, "--runtime-adapter");
2497
- pending = runtimeAdapterResult.rest;
2498
689
  const modelResult = takeOption(pending, "--model");
2499
690
  pending = modelResult.rest;
2500
- const runtimeModeResult = takeOption(pending, "--runtime-mode");
2501
- pending = runtimeModeResult.rest;
2502
- const interactionModeResult = takeOption(pending, "--interaction-mode");
2503
- pending = interactionModeResult.rest;
691
+ const promptResult = takeOption(pending, "--prompt");
692
+ pending = promptResult.rest;
2504
693
  const initialPromptResult = takeOption(pending, "--initial-prompt");
2505
694
  pending = initialPromptResult.rest;
2506
- const prResult = takeOption(pending, "--pr");
2507
- pending = prResult.rest;
2508
- const noPrResult = takeFlag(pending, "--no-pr");
2509
- pending = noPrResult.rest;
2510
- const dirtyBaselineResult = takeOption(pending, "--dirty-baseline");
2511
- pending = dirtyBaselineResult.rest;
2512
- const skipProjectSyncResult = takeFlag(pending, "--skip-project-sync");
2513
- pending = skipProjectSyncResult.rest;
2514
- const detachResult = takeFlag(pending, "--detach");
2515
- pending = detachResult.rest;
2516
- const filterResult = parseTaskFilters(pending);
2517
- pending = filterResult.rest;
2518
- const positionalTaskId = pending.length > 0 && pending[0] && !pending[0].startsWith("-") ? normalizeTaskRunTaskId(pending[0]) : null;
2519
- if (positionalTaskId) {
2520
- pending = pending.slice(1);
2521
- }
2522
- requireNoExtraArgs(pending, "rig task run [#<issue>|<task-id>] [--next] [--task <id>] [--detach] [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>] [--title <text>] [--runtime-adapter claude-code|codex|pi] [--model <model>] [--runtime-mode <mode>] [--interaction-mode <mode>] [--initial-prompt <text>] [--pr auto|ask|off] [--no-pr] [--dirty-baseline head|dirty-snapshot] [--skip-project-sync]");
2523
- if (nextResult.value && (taskResult.value || positionalTaskId)) {
2524
- throw new CliError("task run cannot combine --next with an explicit task id.", 2, { hint: "Use either `rig task run --next` or `rig task run <id>`." });
2525
- }
2526
- if (taskResult.value && positionalTaskId) {
2527
- throw new CliError("task run cannot combine positional task id with --task <id>.", 2, { hint: "Pass the id once, e.g. `rig task run <id>`." });
2528
- }
2529
- if (prResult.value && noPrResult.value) {
2530
- throw new CliError("task run cannot combine --pr with --no-pr.", 2, { hint: "Use `--pr auto|ask|off` or `--no-pr`, not both." });
2531
- }
2532
- let selectedTask = null;
2533
- let selectedTaskId = normalizeTaskRunTaskId(taskResult.value) ?? positionalTaskId;
2534
- if (nextResult.value) {
2535
- const selected = await withSpinner("Selecting next ready task\u2026", () => selectNextWorkspaceTaskViaServer(context, filterResult.filters), { outputMode: context.outputMode });
2536
- selectedTask = selected.task;
2537
- selectedTaskId = selected.task ? readTaskId(selected.task) : null;
2538
- if (!selectedTaskId) {
2539
- throw new CliError("No matching task found for task run --next.", 3, { hint: "Run `rig task list` to inspect available work, or relax the filters." });
2540
- }
2541
- }
2542
- if (!selectedTaskId && !initialPromptResult.value && !titleResult.value) {
2543
- if (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY) {
2544
- throw new CliError("task run requires an interactive terminal to pick a task; pass --next, --task <id>, or --initial-prompt/--title for an ad hoc run.", 2);
2545
- }
2546
- const tasks = await withSpinner("Reading tasks from server\u2026", () => listWorkspaceTasksViaServer(context, filterResult.filters), { outputMode: context.outputMode });
2547
- selectedTask = await selectTaskWithTextPicker(tasks);
2548
- selectedTaskId = selectedTask ? readTaskId(selectedTask) : null;
2549
- if (!selectedTaskId) {
2550
- throw new CliError("No task selected.", 3, { hint: "Run `rig task run --next` for the next ready task, or `rig task run --task <id>`." });
2551
- }
2552
- }
2553
- await runProjectMainSyncPreflight(context, { disabled: skipProjectSyncResult.value });
2554
- const projectDefaults = await loadTaskRunProjectDefaults(context.projectRoot);
2555
- const runtimeAdapter = normalizeRuntimeAdapter(runtimeAdapterResult.value ?? projectDefaults.runtimeAdapter);
2556
- await withSpinner("Running task-run preflight\u2026", () => runFastTaskRunPreflight(context, {
2557
- taskId: selectedTaskId,
2558
- runtimeAdapter
2559
- }), { outputMode: context.outputMode });
2560
- const dirtyBaseline = await resolveDirtyBaselineForTaskRun(context, dirtyBaselineResult.value);
2561
- const prMode = noPrResult.value ? "off" : normalizePrMode(prResult.value) ?? projectDefaults.prMode;
2562
- const submitted = await withSpinner("Dispatching run\u2026", () => submitTaskRunViaServer(context, {
2563
- runId: context.runId,
2564
- taskId: selectedTaskId ?? undefined,
2565
- title: titleResult.value ?? undefined,
2566
- runtimeAdapter,
2567
- model: modelResult.value ?? projectDefaults.model,
2568
- runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
2569
- interactionMode: interactionModeResult.value || "default",
2570
- initialPrompt: initialPromptResult.value ?? undefined,
2571
- baselineMode: dirtyBaseline.mode,
2572
- prMode
2573
- }), { outputMode: context.outputMode });
2574
- let attachDetails = null;
2575
- if (!detachResult.value && context.outputMode === "text") {
2576
- printFormattedOutput(formatSubmittedRun({
2577
- runId: submitted.runId,
2578
- task: selectedTask ? summarizeTask(selectedTask) : null,
2579
- runtimeAdapter,
2580
- runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
2581
- interactionMode: interactionModeResult.value || "default",
2582
- detached: false
2583
- }));
2584
- attachDetails = await attachRunOperatorView(context, { runId: submitted.runId, follow: true });
2585
- } else if (context.outputMode === "text") {
2586
- printFormattedOutput(formatSubmittedRun({
2587
- runId: submitted.runId,
2588
- task: selectedTask ? summarizeTask(selectedTask) : null,
2589
- runtimeAdapter,
2590
- runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
2591
- interactionMode: interactionModeResult.value || "default",
2592
- detached: true
2593
- }));
2594
- }
2595
- return {
2596
- ok: true,
2597
- group: "task",
2598
- command,
2599
- details: {
2600
- runId: submitted.runId,
2601
- taskId: selectedTaskId,
2602
- title: titleResult.value ?? null,
2603
- selectedTask: selectedTask ? summarizeTask(selectedTask) : null,
2604
- filters: nextResult.value ? filterResult.filters : undefined,
2605
- attached: Boolean(attachDetails),
2606
- attach: attachDetails,
2607
- runtimeAdapter,
2608
- model: modelResult.value ?? projectDefaults.model ?? null,
2609
- runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
2610
- prMode: prMode ?? null,
2611
- dirtyBaseline: { mode: dirtyBaseline.mode, dirty: dirtyBaseline.state?.dirty ?? false }
2612
- }
2613
- };
2614
- }
2615
- case "validate": {
2616
- const { value: task, rest: remaining } = takeOption(rest, "--task");
2617
- requireNoExtraArgs(remaining, "rig task validate [--task <task-id>]");
2618
- if (context.dryRun) {
2619
- await context.runCommand(["rig", "task", "validate", ...task ? ["--task", task] : []]);
2620
- return { ok: true, group: "task", command, details: { task: task || "active" } };
2621
- }
2622
- const ok = await withMutedConsole(context.outputMode === "json", async () => taskValidate(context.projectRoot, task || undefined, await validatorRegistryForTaskCommands(context.projectRoot)));
2623
- if (!ok) {
2624
- throw new CliError(`Validation failed for ${task || "active task"}.`, 2, { hint: "Inspect failures with `rig inspect failures --task <id>`, fix, then re-run `rig task validate --task <id>`." });
2625
- }
2626
- return { ok: true, group: "task", command, details: { task: task || "active" } };
695
+ const parsed = parseTaskFilters(pending);
696
+ pending = parsed.rest;
697
+ const positional = pending[0]?.startsWith("-") ? undefined : pending[0];
698
+ requireNoExtraArgs(positional ? pending.slice(1) : pending, "rig task run [#<issue>|<task-id>|--next|--task <id>] [--title <t>] [--model <m>] [--prompt <p>] [--initial-prompt <p>] [--detach] [--search <text>]");
699
+ const { taskId, task } = await resolveRunTask(context, taskResult.value ?? positional, nextResult.value, parsed.filters, deps);
700
+ const title = titleResult.value ?? readTaskTitle(task);
701
+ const submitted = await (deps.spawnRun ?? spawnRunProcess)({ projectRoot: context.projectRoot, taskId, title });
702
+ const note = detachResult.value ? `
703
+
704
+ Note: --detach is the default; the run was submitted detached.` : "";
705
+ printText(context, `${formatSubmittedRun({ runId: submitted.runId, taskId, title })}
706
+
707
+ Next: rig run attach ${submitted.runId}${note}`);
708
+ return { ok: true, group: "task", command, details: { runId: submitted.runId, taskId, title: title ?? null, detached: true } };
2627
709
  }
710
+ case "ready":
711
+ requireNoExtraArgs(rest, "rig task ready");
712
+ await (deps.taskReady ?? taskReady)(context.projectRoot);
713
+ return { ok: true, group: "task", command };
714
+ case "validate":
2628
715
  case "verify": {
2629
- const { value: task, rest: remaining } = takeOption(rest, "--task");
2630
- requireNoExtraArgs(remaining, "rig task verify [--task <task-id>]");
2631
- if (context.dryRun) {
2632
- await context.runCommand(["rig", "task", "verify", ...task ? ["--task", task] : []]);
2633
- return { ok: true, group: "task", command, details: { task: task || "active" } };
2634
- }
2635
- const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, task || undefined));
2636
- if (!ok) {
2637
- throw new CliError(`Verification rejected for ${task || "active task"}.`, 2, { hint: "Check `rig inspect logs --task <id>`, address the rejection, then re-run `rig task verify --task <id>`." });
716
+ const taskResult = takeOption(rest, "--task");
717
+ requireNoExtraArgs(taskResult.rest, `rig task ${command} [--task <id>]`);
718
+ const taskId = normalizeTaskId(taskResult.value);
719
+ const ok = command === "validate" ? await (deps.taskValidate ?? taskValidate)(context.projectRoot, taskId) : await (deps.taskVerify ?? taskVerify)(context.projectRoot, taskId);
720
+ return { ok, group: "task", command, details: { taskId: taskId ?? null } };
721
+ }
722
+ case "reopen": {
723
+ let pending = rest;
724
+ const allResult = takeFlag(pending, "--all");
725
+ pending = allResult.rest;
726
+ const taskResult = takeOption(pending, "--task");
727
+ pending = taskResult.rest;
728
+ const reasonResult = takeOption(pending, "--reason");
729
+ pending = reasonResult.rest;
730
+ requireNoExtraArgs(pending, "rig task reopen [--task <id> | --all] [--reason <text>]");
731
+ const taskId = normalizeTaskId(taskResult.value);
732
+ if (allResult.value && taskId)
733
+ throw new CliError("Pass only one of --task or --all.", 1, { hint: "Use `rig task reopen --task <id>` or `rig task reopen --all`." });
734
+ const summary = (deps.taskReopen ?? taskReopen)(context.projectRoot, {
735
+ all: allResult.value,
736
+ dryRun: context.dryRun,
737
+ ...taskId ? { taskId } : {}
738
+ });
739
+ return { ok: true, group: "task", command, details: { ...summary, reason: reasonResult.value ?? null } };
740
+ }
741
+ case "artifacts": {
742
+ const taskResult = takeOption(rest, "--task");
743
+ requireNoExtraArgs(taskResult.rest, "rig task artifacts [--task <id>]");
744
+ const taskId = normalizeTaskId(taskResult.value);
745
+ (deps.taskArtifacts ?? taskArtifacts)(context.projectRoot, taskId);
746
+ return { ok: true, group: "task", command, details: { taskId: taskId ?? null } };
747
+ }
748
+ case "artifact-dir": {
749
+ const taskResult = takeOption(rest, "--task");
750
+ requireNoExtraArgs(taskResult.rest, "rig task artifact-dir [--task <id>]");
751
+ const taskId = normalizeTaskId(taskResult.value);
752
+ const dir = (deps.taskArtifactDir ?? taskArtifactDir)(context.projectRoot, taskId);
753
+ printText(context, dir);
754
+ return { ok: true, group: "task", command, details: { taskId: taskId ?? null, dir } };
755
+ }
756
+ case "artifact-write": {
757
+ const taskResult = takeOption(rest, "--task");
758
+ const [filename, content, ...extra] = taskResult.rest;
759
+ requireNoExtraArgs(extra, "rig task artifact-write <filename> <content> [--task <id>]");
760
+ if (!filename || content === undefined) {
761
+ throw new CliError("Missing artifact filename or content.", 1, { hint: "Use `rig task artifact-write <filename> <content> [--task <id>]`." });
2638
762
  }
2639
- return { ok: true, group: "task", command, details: { task: task || "active" } };
763
+ const taskId = normalizeTaskId(taskResult.value);
764
+ (deps.taskArtifactWrite ?? taskArtifactWrite)(context.projectRoot, filename, content, taskId);
765
+ return { ok: true, group: "task", command, details: { taskId: taskId ?? null, filename } };
2640
766
  }
2641
- case "details": {
2642
- const { value: task, rest: remaining } = takeOption(rest, "--task");
2643
- requireNoExtraArgs(remaining, "rig task details --task <task-id>");
2644
- const requiredTask = requireTask(task, "rig task details --task <task-id>");
2645
- await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, requiredTask));
2646
- return { ok: true, group: "task", command, details: { task: requiredTask } };
767
+ case "report-bug":
768
+ return executeReportBug(context, rest, deps);
769
+ case "info": {
770
+ const taskResult = takeOption(rest, "--task");
771
+ requireNoExtraArgs(taskResult.rest, "rig task info [--task <id>]");
772
+ await taskInfo(context.projectRoot, normalizeTaskId(taskResult.value));
773
+ return { ok: true, group: "task", command };
2647
774
  }
2648
- case "reopen": {
2649
- const { value: task, rest: rest1 } = takeOption(rest, "--task");
2650
- const allFlag = takeFlag(rest1, "--all");
2651
- const { rest: remaining } = takeOption(allFlag.rest, "--reason");
2652
- requireNoExtraArgs(remaining, "rig task reopen [--task <id> | --all] [--reason <text>]");
2653
- if (!allFlag.value && !task) {
2654
- throw new CliError("Usage: rig task reopen [--task <id> | --all] [--reason <text>]");
775
+ case "scope": {
776
+ const filesFlag = takeFlag(rest, "--files");
777
+ const taskResult = takeOption(filesFlag.rest, "--task");
778
+ requireNoExtraArgs(taskResult.rest, "rig task scope [--files] [--task <id>]");
779
+ await taskScope(context.projectRoot, Boolean(filesFlag.value), normalizeTaskId(taskResult.value));
780
+ return { ok: true, group: "task", command };
781
+ }
782
+ case "deps": {
783
+ const taskResult = takeOption(rest, "--task");
784
+ requireNoExtraArgs(taskResult.rest, "rig task deps [--task <id>]");
785
+ await taskDeps(context.projectRoot, normalizeTaskId(taskResult.value));
786
+ return { ok: true, group: "task", command };
787
+ }
788
+ case "status":
789
+ requireNoExtraArgs(rest, "rig task status");
790
+ taskStatus(context.projectRoot);
791
+ return { ok: true, group: "task", command };
792
+ case "lookup": {
793
+ const [rawId, ...extra] = rest;
794
+ requireNoExtraArgs(extra, "rig task lookup <id>");
795
+ const lookupId = requireTask(normalizeTaskId(rawId), "rig task lookup <id>");
796
+ const resolved = taskLookup(context.projectRoot, lookupId);
797
+ printText(context, resolved);
798
+ return { ok: true, group: "task", command, details: { id: lookupId, resolved } };
799
+ }
800
+ case "record": {
801
+ const taskResult = takeOption(rest, "--task");
802
+ const [type, ...textParts] = taskResult.rest;
803
+ const text = textParts.join(" ").trim();
804
+ if (type !== "decision" && type !== "failure") {
805
+ throw new CliError("rig task record requires a type: decision|failure.", 1, { hint: "rig task record <decision|failure> <text> [--task <id>]" });
2655
806
  }
2656
- const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
2657
- all: allFlag.value,
2658
- taskId: task || undefined,
2659
- dryRun: false
2660
- }));
2661
- return { ok: true, group: "task", command, details: summary };
807
+ if (!text)
808
+ throw new CliError("rig task record requires text.", 1, { hint: "rig task record <decision|failure> <text> [--task <id>]" });
809
+ taskRecord(context.projectRoot, type, text, normalizeTaskId(taskResult.value));
810
+ return { ok: true, group: "task", command, details: { type, text } };
2662
811
  }
2663
812
  default:
2664
- if (command === "reset") {
2665
- throw new CliError("Unknown task command: reset", 1, { hint: "Use `rig task reopen --task <id>`." });
2666
- }
2667
- throw new CliError(`Unknown task command: ${command}`, 1, { hint: "Run `rig task --help` to list available task commands." });
813
+ throw new CliError(`Unknown task command: ${command}`, 1, { hint: "Run `rig task --help`." });
2668
814
  }
2669
815
  }
2670
816
  export {
2671
- loadTaskRunProjectDefaults,
2672
817
  executeTask
2673
818
  };