@h-rig/cli 0.0.6-alpha.9 → 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 (116) hide show
  1. package/README.md +18 -19
  2. package/dist/bin/build-rig-binaries.d.ts +2 -0
  3. package/dist/bin/build-rig-binaries.js +22 -10
  4. package/dist/bin/rig.d.ts +72 -0
  5. package/dist/bin/rig.js +15637 -7344
  6. package/dist/config/rig-default-config.yml +5 -0
  7. package/dist/src/app/drone-ui.d.ts +34 -0
  8. package/dist/src/app/drone-ui.js +278 -0
  9. package/dist/src/commands/_async-ui.d.ts +10 -0
  10. package/dist/src/commands/_async-ui.js +121 -0
  11. package/dist/src/commands/_cli-format.d.ts +56 -0
  12. package/dist/src/commands/_cli-format.js +319 -0
  13. package/dist/src/commands/_connection-state.d.ts +54 -0
  14. package/dist/src/commands/_connection-state.js +75 -11
  15. package/dist/src/commands/_doctor-checks.d.ts +46 -0
  16. package/dist/src/commands/_doctor-checks.js +100 -267
  17. package/dist/src/commands/_help-catalog.d.ts +51 -0
  18. package/dist/src/commands/_help-catalog.js +502 -0
  19. package/dist/src/commands/_inprocess-services.d.ts +33 -0
  20. package/dist/src/commands/_inprocess-services.js +102 -0
  21. package/dist/src/commands/_json-output.d.ts +11 -0
  22. package/dist/src/commands/_json-output.js +60 -0
  23. package/dist/src/commands/_lazy-reconcile.d.ts +34 -0
  24. package/dist/src/commands/_lazy-reconcile.js +102 -0
  25. package/dist/src/commands/_parsers.d.ts +15 -0
  26. package/dist/src/commands/_parsers.js +18 -11
  27. package/dist/src/commands/_paths.d.ts +11 -0
  28. package/dist/src/commands/_paths.js +1 -1
  29. package/dist/src/commands/_pi-frontend.d.ts +35 -0
  30. package/dist/src/commands/_pi-frontend.js +64 -0
  31. package/dist/src/commands/_pi-install.d.ts +42 -0
  32. package/dist/src/commands/_pi-install.js +19 -36
  33. package/dist/src/commands/_policy.d.ts +8 -0
  34. package/dist/src/commands/_policy.js +67 -19
  35. package/dist/src/commands/_probes.d.ts +1 -0
  36. package/dist/src/commands/_run-bridge.d.ts +114 -0
  37. package/dist/src/commands/_run-bridge.js +387 -0
  38. package/dist/src/commands/_run-diagnostics.d.ts +9 -0
  39. package/dist/src/commands/_run-diagnostics.js +51 -0
  40. package/dist/src/commands/_run-driver-helpers.d.ts +26 -0
  41. package/dist/src/commands/_run-driver-helpers.js +79 -230
  42. package/dist/src/commands/_run-projection.d.ts +50 -0
  43. package/dist/src/commands/_run-projection.js +349 -0
  44. package/dist/src/commands/_run-subcommands.d.ts +3 -0
  45. package/dist/src/commands/_run-subcommands.js +31 -0
  46. package/dist/src/commands/_spinner.d.ts +25 -0
  47. package/dist/src/commands/_spinner.js +65 -0
  48. package/dist/src/commands/agent.d.ts +3 -0
  49. package/dist/src/commands/agent.js +8575 -236
  50. package/dist/src/commands/dist.d.ts +28 -0
  51. package/dist/src/commands/dist.js +44 -29
  52. package/dist/src/commands/doctor.d.ts +3 -0
  53. package/dist/src/commands/doctor.js +219 -268
  54. package/dist/src/commands/github.d.ts +3 -0
  55. package/dist/src/commands/github.js +236 -188
  56. package/dist/src/commands/inbox.d.ts +28 -0
  57. package/dist/src/commands/inbox.js +530 -111
  58. package/dist/src/commands/init.d.ts +64 -0
  59. package/dist/src/commands/init.js +912 -705
  60. package/dist/src/commands/inspect.d.ts +20 -0
  61. package/dist/src/commands/inspect.js +709 -119
  62. package/dist/src/commands/pi.d.ts +3 -0
  63. package/dist/src/commands/pi.js +177 -0
  64. package/dist/src/commands/plugin.d.ts +16 -0
  65. package/dist/src/commands/plugin.js +576 -29
  66. package/dist/src/commands/profile-and-review.d.ts +4 -0
  67. package/dist/src/commands/profile-and-review.js +112 -67
  68. package/dist/src/commands/queue.d.ts +3 -0
  69. package/dist/src/commands/queue.js +20 -20
  70. package/dist/src/commands/remote.d.ts +3 -0
  71. package/dist/src/commands/remote.js +880 -50
  72. package/dist/src/commands/repo-git-harness.d.ts +5 -0
  73. package/dist/src/commands/repo-git-harness.js +78 -28
  74. package/dist/src/commands/run.d.ts +21 -0
  75. package/dist/src/commands/run.js +17701 -661
  76. package/dist/src/commands/server.d.ts +3 -0
  77. package/dist/src/commands/server.js +166 -303
  78. package/dist/src/commands/setup.d.ts +16 -0
  79. package/dist/src/commands/setup.js +244 -299
  80. package/dist/src/commands/stats.d.ts +15 -0
  81. package/dist/src/commands/stats.js +979 -0
  82. package/dist/src/commands/task-run-driver.d.ts +94 -0
  83. package/dist/src/commands/task-run-driver.js +116 -1961
  84. package/dist/src/commands/task.d.ts +35 -0
  85. package/dist/src/commands/task.js +676 -1201
  86. package/dist/src/commands/test.d.ts +3 -0
  87. package/dist/src/commands/test.js +15 -8
  88. package/dist/src/commands/triage.d.ts +11 -0
  89. package/dist/src/commands/triage.js +227 -0
  90. package/dist/src/commands/workspace.d.ts +3 -0
  91. package/dist/src/commands/workspace.js +18 -11
  92. package/dist/src/commands.d.ts +13 -0
  93. package/dist/src/commands.js +16792 -8055
  94. package/dist/src/index.d.ts +4 -0
  95. package/dist/src/index.js +16862 -8450
  96. package/dist/src/launcher.d.ts +61 -0
  97. package/dist/src/launcher.js +81 -13
  98. package/dist/src/operator-cli.d.ts +2 -0
  99. package/dist/src/operator-cli.js +17837 -0
  100. package/dist/src/operator-entry.d.ts +1 -0
  101. package/dist/src/operator-entry.js +3 -0
  102. package/dist/src/runner.d.ts +47 -0
  103. package/dist/src/runner.js +16 -22
  104. package/dist/src/withMutedConsole.d.ts +2 -0
  105. package/package.json +21 -8
  106. package/dist/src/commands/_authority-runs.js +0 -111
  107. package/dist/src/commands/_operator-view.js +0 -340
  108. package/dist/src/commands/_preflight.js +0 -478
  109. package/dist/src/commands/_server-client.js +0 -382
  110. package/dist/src/commands/_snapshot-upload.js +0 -331
  111. package/dist/src/commands/_task-picker.js +0 -48
  112. package/dist/src/commands/browser.js +0 -890
  113. package/dist/src/commands/connect.js +0 -180
  114. package/dist/src/commands/inspector.js +0 -256
  115. package/dist/src/commands/task-report-bug.js +0 -1083
  116. package/dist/src/report-bug.js +0 -260
@@ -1,18 +1,40 @@
1
1
  // @bun
2
+ var __require = import.meta.require;
3
+
2
4
  // packages/cli/src/commands/task.ts
3
- import { readFileSync as readFileSync4 } from "fs";
4
- import { spawnSync as spawnSync2 } from "child_process";
5
- import { createInterface as createInterface3 } from "readline/promises";
6
- import { resolve as resolve4 } from "path";
5
+ import { createPluginHost as createPluginHost2, selectNextReadyTaskByPriority } from "@rig/core";
6
+ import { loadConfig as loadConfig2 } from "@rig/core/load-config";
7
+ import {
8
+ taskArtifactDir,
9
+ taskArtifacts,
10
+ taskArtifactWrite,
11
+ taskDeps,
12
+ taskInfo,
13
+ taskLookup,
14
+ taskReady,
15
+ taskRecord,
16
+ taskReopen,
17
+ taskScope,
18
+ taskStatus,
19
+ taskValidate,
20
+ taskVerify
21
+ } from "@rig/runtime/control-plane/native/task-ops";
7
22
 
8
23
  // packages/cli/src/runner.ts
9
24
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
10
- import { CliError } from "@rig/runtime/control-plane/errors";
25
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
11
26
  import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
12
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
13
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
14
27
  import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
15
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
28
+
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();
35
+ }
36
+ }
37
+ }
16
38
  function takeFlag(args, flag) {
17
39
  const rest = [];
18
40
  let value = false;
@@ -33,7 +55,7 @@ function takeOption(args, option) {
33
55
  if (current === option) {
34
56
  const next = args[index + 1];
35
57
  if (!next || next.startsWith("-")) {
36
- throw new CliError(`Missing value for ${option}`);
58
+ throw new CliError(`Missing value for ${option}`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} <value>\`.` });
37
59
  }
38
60
  value = next;
39
61
  index += 1;
@@ -59,1283 +81,736 @@ Usage: ${usage}`);
59
81
  return taskId;
60
82
  }
61
83
 
62
- // packages/cli/src/commands/task.ts
63
- import {
64
- taskArtifactDir,
65
- taskArtifacts,
66
- taskArtifactWrite,
67
- taskDeps,
68
- taskInfo,
69
- taskLookup,
70
- taskReady,
71
- taskRecord,
72
- taskReopen,
73
- taskScope,
74
- taskStatus as taskStatus2,
75
- taskValidate,
76
- taskVerify
77
- } from "@rig/runtime/control-plane/native/task-ops";
78
-
79
- // packages/cli/src/commands/_authority-runs.ts
80
- import {
81
- readAuthorityRun,
82
- readJsonlFile,
83
- resolveAuthorityRunDir,
84
- writeJsonFile
85
- } from "@rig/runtime/control-plane/authority-files";
86
-
87
- // packages/cli/src/commands/_paths.ts
88
- import { resolveMonorepoRoot } from "@rig/runtime/control-plane/native/utils";
89
-
90
- // packages/cli/src/commands/_authority-runs.ts
91
- function normalizeRuntimeAdapter(value) {
92
- const normalized = value?.trim().toLowerCase();
93
- if (!normalized) {
94
- return "pi";
95
- }
96
- if (normalized === "codex" || normalized === "codex-cli" || normalized === "codex-app-server" || normalized === "gpt-codex") {
97
- return "codex";
98
- }
99
- if (normalized === "pi" || normalized === "rig-pi" || normalized === "@rig/pi") {
100
- return "pi";
101
- }
102
- return "claude-code";
103
- }
104
-
105
- // packages/cli/src/commands/_preflight.ts
106
- import { ensureProjectMainFreshBeforeRun } from "@rig/runtime/control-plane/project-main-pre-run-sync";
107
-
108
- // packages/cli/src/commands/_connection-state.ts
109
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
110
- import { homedir } from "os";
111
- import { dirname, resolve } from "path";
112
- function resolveGlobalConnectionsPath(env = process.env) {
113
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
114
- if (explicit)
115
- return resolve(explicit);
116
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
117
- if (stateDir)
118
- return resolve(stateDir, "connections.json");
119
- return resolve(homedir(), ".rig", "connections.json");
120
- }
121
- function resolveRepoConnectionPath(projectRoot) {
122
- return resolve(projectRoot, ".rig", "state", "connection.json");
123
- }
124
- function readJsonFile(path) {
125
- if (!existsSync(path))
126
- return null;
127
- try {
128
- return JSON.parse(readFileSync(path, "utf8"));
129
- } catch (error) {
130
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
131
- }
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;
89
+ function arrayField(record, key) {
90
+ const value = record[key];
91
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string" && entry.trim().length > 0) : [];
92
+ }
93
+ function rawObject(record) {
94
+ const value = record.raw;
95
+ return value && typeof value === "object" && !Array.isArray(value) ? value : record;
96
+ }
97
+ function truncate(value, width) {
98
+ return value.length <= width ? value : `${value.slice(0, Math.max(0, width - 1))}\u2026`;
99
+ }
100
+ function pad(value, width) {
101
+ return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
102
+ }
103
+ function statusColor(status) {
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);
125
+ }
126
+ function formatSection(title, subtitle) {
127
+ return `${pc.bold(accent("\u25C6"))} ${pc.bold(title)}${subtitle ? dim(` \u2014 ${subtitle}`) : ""}`;
128
+ }
129
+ function formatSuccessCard(title, rows = []) {
130
+ const body = rows.filter(([, value]) => value !== undefined && value !== null && String(value).length > 0).map(([key, value]) => `${faintBar} ${dim(key.padEnd(12))} ${value}`);
131
+ return [formatSection(title), ...body].join(`
132
+ `);
132
133
  }
133
- function normalizeConnection(value) {
134
- if (!value || typeof value !== "object" || Array.isArray(value))
135
- return null;
136
- const record = value;
137
- if (record.kind === "local")
138
- return { kind: "local", mode: "auto" };
139
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
140
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
141
- return { kind: "remote", baseUrl };
142
- }
143
- return null;
134
+ function formatNextSteps(steps) {
135
+ if (steps.length === 0)
136
+ return [];
137
+ return [pc.bold("Next"), ...steps.map((step) => `${accent("\u203A")} ${step}`)];
144
138
  }
145
- function readGlobalConnections(options = {}) {
146
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
147
- const payload = readJsonFile(path);
148
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
149
- return { connections: {} };
150
- }
151
- const rawConnections = payload.connections;
152
- const connections = {};
153
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
154
- for (const [alias, raw] of Object.entries(rawConnections)) {
155
- const connection = normalizeConnection(raw);
156
- if (connection)
157
- connections[alias] = connection;
158
- }
139
+ function formatTaskList(tasks, options = {}) {
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(`
142
+ `);
159
143
  }
160
- return { connections };
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));
150
+ const body = rows.map((row) => {
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}`) : "";
153
+ return [
154
+ pc.bold(pad(truncate(row.id, idWidth), idWidth)),
155
+ statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
156
+ `${row.title}${labels}${source}`
157
+ ].join(" ");
158
+ });
159
+ return [formatSection("Tasks", `${tasks.length}`), ...body].join(`
160
+ `);
161
161
  }
162
- function readRepoConnection(projectRoot) {
163
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
164
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
165
- return null;
166
- const record = payload;
167
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
168
- if (!selected)
169
- return null;
162
+ function summarizeTaskRow(task) {
163
+ const raw = rawObject(task);
170
164
  return {
171
- selected,
172
- project: typeof record.project === "string" ? record.project : undefined,
173
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
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"], "")
174
170
  };
175
171
  }
176
- function resolveSelectedConnection(projectRoot, options = {}) {
177
- const repo = readRepoConnection(projectRoot);
178
- if (!repo)
179
- return null;
180
- if (repo.selected === "local")
181
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
182
- const global = readGlobalConnections(options);
183
- const connection = global.connections[repo.selected];
184
- if (!connection) {
185
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
186
- }
187
- return { alias: repo.selected, connection };
188
- }
189
-
190
- // packages/cli/src/commands/_server-client.ts
191
- import { spawnSync } from "child_process";
192
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
193
- import { resolve as resolve2 } from "path";
194
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
195
- var cachedGitHubBearerToken;
196
- function cleanToken(value) {
197
- const trimmed = value?.trim();
198
- return trimmed ? trimmed : null;
199
- }
200
- function readPrivateRemoteSessionToken(projectRoot) {
201
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
202
- if (!existsSync2(path))
203
- return null;
204
- try {
205
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
206
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
207
- } catch {
208
- return null;
209
- }
210
- }
211
- function readGitHubBearerTokenForRemote(projectRoot) {
212
- if (cachedGitHubBearerToken !== undefined)
213
- return cachedGitHubBearerToken;
214
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
215
- if (privateSession) {
216
- cachedGitHubBearerToken = privateSession;
217
- return cachedGitHubBearerToken;
218
- }
219
- const envToken = cleanToken(process.env.RIG_GITHUB_TOKEN) ?? cleanToken(process.env.GITHUB_TOKEN) ?? cleanToken(process.env.GH_TOKEN);
220
- if (envToken) {
221
- cachedGitHubBearerToken = envToken;
222
- return cachedGitHubBearerToken;
223
- }
224
- const result = spawnSync("gh", ["auth", "token"], {
225
- encoding: "utf8",
226
- timeout: 5000,
227
- stdio: ["ignore", "pipe", "ignore"]
228
- });
229
- cachedGitHubBearerToken = result.status === 0 ? cleanToken(result.stdout) : null;
230
- return cachedGitHubBearerToken;
231
- }
232
- async function ensureServerForCli(projectRoot) {
233
- try {
234
- const selected = resolveSelectedConnection(projectRoot);
235
- if (selected?.connection.kind === "remote") {
236
- return {
237
- baseUrl: selected.connection.baseUrl,
238
- authToken: readGitHubBearerTokenForRemote(projectRoot),
239
- connectionKind: "remote"
240
- };
241
- }
242
- const connection = await ensureLocalRigServerConnection(projectRoot);
243
- return {
244
- baseUrl: connection.baseUrl,
245
- authToken: connection.authToken,
246
- connectionKind: "local"
247
- };
248
- } catch (error) {
249
- if (error instanceof Error) {
250
- throw new CliError2(error.message, 1);
251
- }
252
- throw error;
253
- }
254
- }
255
- function appendTaskFilterParams(url, filters) {
256
- if (filters.assignee)
257
- url.searchParams.set("assignee", filters.assignee);
258
- if (filters.state)
259
- url.searchParams.set("state", filters.state);
260
- if (filters.status)
261
- url.searchParams.set("status", filters.status);
262
- if (filters.limit !== undefined)
263
- url.searchParams.set("limit", String(filters.limit));
264
- }
265
- function mergeHeaders(headers, authToken) {
266
- const merged = new Headers(headers);
267
- if (authToken) {
268
- merged.set("authorization", `Bearer ${authToken}`);
269
- }
270
- return merged;
271
- }
272
- function diagnosticMessage(payload) {
273
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
274
- return null;
275
- const record = payload;
276
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
277
- const messages = diagnostics.flatMap((entry) => {
278
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
279
- return [];
280
- const diagnostic = entry;
281
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
282
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
283
- return message ? [`${kind}: ${message}`] : [];
284
- });
285
- return messages.length > 0 ? messages.join("; ") : null;
286
- }
287
- async function requestServerJson(context, pathname, init = {}) {
288
- const server = await ensureServerForCli(context.projectRoot);
289
- const response = await fetch(`${server.baseUrl}${pathname}`, {
290
- ...init,
291
- headers: mergeHeaders(init.headers, server.authToken)
292
- });
293
- const text = await response.text();
294
- const payload = text.trim().length > 0 ? (() => {
295
- try {
296
- return JSON.parse(text);
297
- } catch {
298
- return null;
299
- }
300
- })() : null;
301
- if (!response.ok) {
302
- const diagnostics = diagnosticMessage(payload);
303
- const detail = diagnostics ?? (text || response.statusText);
304
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
305
- }
306
- return payload;
307
- }
308
- async function listWorkspaceTasksViaServer(context, filters = {}) {
309
- const url = new URL("http://rig.local/api/workspace/tasks");
310
- appendTaskFilterParams(url, filters);
311
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
312
- if (!Array.isArray(payload)) {
313
- throw new CliError2("Rig server returned an invalid task list payload.", 1);
314
- }
315
- return payload.flatMap((entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? [entry] : []);
316
- }
317
- async function getWorkspaceTaskViaServer(context, taskId) {
318
- const payload = await requestServerJson(context, `/api/workspace/tasks/${encodeURIComponent(taskId)}`);
319
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
320
- return null;
321
- const task = payload.task;
322
- return task && typeof task === "object" && !Array.isArray(task) ? task : null;
323
- }
324
- async function selectNextWorkspaceTaskViaServer(context, filters = {}) {
325
- const url = new URL("http://rig.local/api/workspace/tasks/next");
326
- appendTaskFilterParams(url, filters);
327
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
328
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
329
- throw new CliError2("Rig server returned an invalid next-task payload.", 1);
330
- }
331
- const record = payload;
332
- const rawTask = record.task;
333
- const task = rawTask && typeof rawTask === "object" && !Array.isArray(rawTask) ? rawTask : null;
334
- const count = typeof record.count === "number" && Number.isFinite(record.count) ? record.count : task ? 1 : 0;
335
- return { task, count };
336
- }
337
- async function getRunDetailsViaServer(context, runId) {
338
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
339
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
340
- }
341
- async function getRunLogsViaServer(context, runId, options = {}) {
342
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
343
- if (options.limit !== undefined)
344
- url.searchParams.set("limit", String(options.limit));
345
- if (options.cursor)
346
- url.searchParams.set("cursor", options.cursor);
347
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
348
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
349
- }
350
- async function stopRunViaServer(context, runId) {
351
- const payload = await requestServerJson(context, "/api/runs/stop", {
352
- method: "POST",
353
- headers: { "content-type": "application/json" },
354
- body: JSON.stringify({ runId })
355
- });
356
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
172
+ function formatTaskCard(task, options = {}) {
173
+ const raw = rawObject(task);
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(`
189
+ `);
357
190
  }
358
- async function steerRunViaServer(context, runId, message) {
359
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
360
- method: "POST",
361
- headers: { "content-type": "application/json" },
362
- body: JSON.stringify({ message })
363
- });
364
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
365
- }
366
- async function submitTaskRunViaServer(context, input) {
367
- const isTaskRun = Boolean(input.taskId);
368
- const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
369
- const payload = await requestServerJson(context, endpoint, {
370
- method: "POST",
371
- headers: {
372
- "content-type": "application/json"
373
- },
374
- body: JSON.stringify({
375
- runId: input.runId,
376
- taskId: input.taskId,
377
- title: input.title,
378
- runtimeAdapter: input.runtimeAdapter,
379
- model: input.model,
380
- runtimeMode: input.runtimeMode,
381
- interactionMode: input.interactionMode,
382
- initialPrompt: input.initialPrompt,
383
- baselineMode: input.baselineMode,
384
- prMode: input.prMode,
385
- executionTarget: "local"
386
- })
387
- });
388
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
389
- throw new CliError2("Rig server returned an invalid run submission payload.", 1);
390
- }
391
- const runId = payload.runId;
392
- if (typeof runId !== "string" || runId.trim().length === 0) {
393
- throw new CliError2("Rig server returned no runId for the submitted run.", 1);
394
- }
395
- return { runId };
191
+ function formatTaskDetails(task) {
192
+ return formatTaskCard(task, { title: "Task details" });
396
193
  }
397
-
398
- // packages/cli/src/commands/_pi-install.ts
399
- import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync } from "fs";
400
- import { homedir as homedir2 } from "os";
401
- import { resolve as resolve3 } from "path";
402
- var PI_RIG_PACKAGE_NAME = "@rig/pi-rig";
403
- async function defaultCommandRunner(command, options = {}) {
404
- const proc = Bun.spawn(command, { cwd: options.cwd, stdout: "pipe", stderr: "pipe" });
405
- const [stdout, stderr, exitCode] = await Promise.all([
406
- new Response(proc.stdout).text(),
407
- new Response(proc.stderr).text(),
408
- proc.exited
194
+ function formatSubmittedRun(input) {
195
+ return formatSuccessCard("Run submitted", [
196
+ ["run", input.runId],
197
+ ["task", input.taskId ?? undefined],
198
+ ["title", input.title ?? undefined],
199
+ ["queue", input.queuePosition ?? undefined]
409
200
  ]);
410
- return { exitCode, stdout, stderr };
411
- }
412
- function resolvePiRigExtensionPath(homeDir) {
413
- return resolve3(homeDir, ".pi", "agent", "extensions", "pi-rig");
414
- }
415
- function resolvePiHomeDir(inputHomeDir) {
416
- return inputHomeDir ?? process.env.RIG_PI_HOME_DIR?.trim() ?? homedir2();
417
- }
418
- function piListContainsPiRig(output) {
419
- return output.split(/\r?\n/).some((line) => {
420
- const normalized = line.trim();
421
- return normalized.includes(PI_RIG_PACKAGE_NAME) || /(?:^|[\\/])packages[\\/]pi-rig(?:$|\s)/.test(normalized);
422
- });
423
- }
424
- async function safeRun(runner, command, options) {
425
- try {
426
- return await runner(command, options);
427
- } catch (error) {
428
- return { exitCode: 1, stdout: "", stderr: error instanceof Error ? error.message : String(error) };
429
- }
430
- }
431
- async function checkPiRigInstall(input = {}) {
432
- const home = resolvePiHomeDir(input.homeDir);
433
- const extensionPath = resolvePiRigExtensionPath(home);
434
- if (process.env.RIG_TEST_FAKE_PI_INSTALL === "1") {
435
- return {
436
- extensionPath,
437
- pi: { ok: true, label: "pi", detail: "fake-pi" },
438
- piRig: { ok: true, label: "pi-rig global extension", detail: extensionPath }
439
- };
440
- }
441
- const exists = input.exists ?? existsSync3;
442
- const runner = input.commandRunner ?? defaultCommandRunner;
443
- const piResult = await safeRun(runner, ["pi", "--version"]);
444
- const piListResult = piResult.exitCode === 0 ? await safeRun(runner, ["pi", "list"]) : { exitCode: 1, stdout: "", stderr: "" };
445
- const listedPiRig = piListResult.exitCode === 0 && piListContainsPiRig(`${piListResult.stdout}
446
- ${piListResult.stderr}`);
447
- const legacyBridge = exists(resolve3(extensionPath, "index.ts"));
448
- const hasPiRig = listedPiRig;
449
- return {
450
- extensionPath,
451
- pi: {
452
- ok: piResult.exitCode === 0,
453
- label: "pi",
454
- detail: (piResult.stdout || piResult.stderr).trim() || undefined,
455
- hint: piResult.exitCode === 0 ? undefined : "Install Pi or run `rig init --yes` to install/update the Pi runtime."
456
- },
457
- piRig: {
458
- ok: hasPiRig,
459
- label: "pi-rig global extension",
460
- detail: hasPiRig ? piListResult.stdout.trim() || PI_RIG_PACKAGE_NAME : legacyBridge ? `${extensionPath} (legacy bridge; reinstall required)` : undefined,
461
- hint: hasPiRig ? undefined : "Run `rig init --yes` to install/enable the global pi-rig package with `pi install`."
462
- }
463
- };
464
- }
465
- async function buildPiSetupChecks(input = {}) {
466
- const status = await checkPiRigInstall(input);
467
- return [status.pi, status.piRig];
468
201
  }
469
202
 
470
- // packages/cli/src/commands/_preflight.ts
471
- function preflightCheck(id, label, status, detail, remediation) {
472
- return {
473
- id,
474
- label,
475
- status,
476
- ...detail ? { detail } : {},
477
- ...remediation ? { remediation } : {}
478
- };
479
- }
480
- function message(error) {
481
- return error instanceof Error ? error.message : String(error);
482
- }
483
- function isAuthenticated(payload) {
484
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
485
- return false;
486
- const record = payload;
487
- return record.signedIn === true || record.authenticated === true || record.status === "authenticated" || record.ok === true && typeof record.login === "string" && record.login.trim().length > 0;
488
- }
489
- function taskMatchesId(entry, taskId) {
490
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
491
- return false;
492
- const record = entry;
493
- if (record.id === taskId || record.taskId === taskId)
494
- return true;
495
- const raw = record.raw;
496
- if (raw && typeof raw === "object" && !Array.isArray(raw)) {
497
- const rawRecord = raw;
498
- if (String(rawRecord.number ?? "") === taskId.replace(/^#/, ""))
499
- return true;
500
- }
501
- return false;
502
- }
503
- function isActiveRunStatus(status) {
504
- const normalized = String(status ?? "running").toLowerCase();
505
- return !["completed", "complete", "done", "merged", "closed", "failed", "cancelled", "canceled", "needs_attention", "needs-attention", "stopped"].includes(normalized);
506
- }
507
- function permissionAllowsPr(payload) {
508
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
509
- return null;
510
- const record = payload;
511
- if (record.canOpenPullRequest === true || record.pullRequests === true || record.push === true || record.maintain === true || record.admin === true)
512
- return true;
513
- if (record.canOpenPullRequest === false || record.pullRequests === false || record.push === false)
514
- return false;
515
- const permissions = record.permissions;
516
- if (permissions && typeof permissions === "object" && !Array.isArray(permissions)) {
517
- const p = permissions;
518
- if (p.push === true || p.maintain === true || p.admin === true)
519
- return true;
520
- if (p.push === false && p.maintain !== true && p.admin !== true)
521
- return false;
522
- }
523
- return null;
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;
524
220
  }
525
- function projectCheckoutReady(payload) {
526
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
527
- return null;
528
- const record = payload;
529
- if (record.checkoutReady === true || record.ready === true)
530
- return true;
531
- if (record.checkoutReady === false || record.ready === false)
532
- return false;
533
- const project = record.project;
534
- if (project && typeof project === "object" && !Array.isArray(project)) {
535
- const checkouts = project.checkouts;
536
- if (Array.isArray(checkouts))
537
- return checkouts.length > 0;
538
- }
539
- return null;
221
+ function githubUserId(value) {
222
+ if (typeof value === "number" && Number.isInteger(value))
223
+ return String(value);
224
+ return stringField(value);
540
225
  }
541
- function activeDuplicateRun(runs, taskId) {
542
- if (!Array.isArray(runs))
226
+ function readJsonRecord(path) {
227
+ if (!existsSync(path))
543
228
  return null;
544
- for (const run of runs) {
545
- if (!run || typeof run !== "object" || Array.isArray(run))
546
- continue;
547
- const record = run;
548
- if ((record.taskId === taskId || record.task === taskId) && isActiveRunStatus(record.status))
549
- return record;
550
- }
551
- return null;
552
- }
553
- async function runFastTaskRunPreflight(context, options = {}) {
554
- const checks = [];
555
- const request = options.requestJson ?? ((pathname, init) => requestServerJson(context, pathname, init));
556
- const taskId = options.taskId?.trim() || null;
557
- try {
558
- await request("/api/server/status");
559
- checks.push(preflightCheck("server", "Rig server reachable", "pass"));
560
- } catch (error) {
561
- checks.push(preflightCheck("server", "Rig server reachable", "fail", message(error), "Start or select a reachable Rig server."));
562
- }
563
- const repo = readRepoConnection(context.projectRoot);
564
- checks.push(repo ? preflightCheck("project-link", "project linked to Rig connection", 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 connection", "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig connect use <alias|local>`."));
565
- try {
566
- const auth = await request("/api/github/auth/status");
567
- checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
568
- } catch (error) {
569
- checks.push(preflightCheck("github-auth", "GitHub auth valid", "fail", message(error), "Fix GitHub auth on the selected Rig server."));
570
- }
571
229
  try {
572
- const projection = await request("/api/workspace/task-projection");
573
- checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
574
- } catch (error) {
575
- checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
576
- }
577
- try {
578
- const permissions = await request("/api/github/repo/permissions");
579
- const allowed = permissionAllowsPr(permissions);
580
- 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."));
581
- } catch (error) {
582
- checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
583
- }
584
- if (repo?.project) {
585
- try {
586
- const project = await request(`/api/projects/${encodeURIComponent(repo.project)}`);
587
- const ready = projectCheckoutReady(project);
588
- 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."));
589
- } catch (error) {
590
- checks.push(preflightCheck("remote-checkout", "execution checkout ready", "warn", message(error), "Run `rig init` or repair the server checkout before launch."));
591
- }
592
- }
593
- if (taskId) {
594
- try {
595
- const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
596
- const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
597
- checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
598
- } catch (error) {
599
- checks.push(preflightCheck("issue", "task/issue accessible", "fail", message(error), "Fix the task source before launching a run."));
600
- }
601
- try {
602
- const runs = await request("/api/runs?limit=200");
603
- const duplicate = activeDuplicateRun(runs, taskId);
604
- 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));
605
- } catch (error) {
606
- 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."));
607
- }
608
- }
609
- if ((options.runtimeAdapter ?? "pi") === "pi") {
610
- const piChecks = await (options.piChecks ?? (() => buildPiSetupChecks()))().catch((error) => [{
611
- ok: false,
612
- label: "pi/pi-rig checks",
613
- hint: message(error)
614
- }]);
615
- for (const pi of piChecks) {
616
- checks.push(preflightCheck(pi.label === "pi" ? "pi" : "pi-rig", pi.label, pi.ok ? "pass" : "fail", pi.detail, pi.hint ?? (pi.ok ? undefined : "Run `rig init --yes` to install/update Pi and enable pi-rig.")));
617
- }
618
- } else {
619
- checks.push(preflightCheck("runtime", "runtime adapter", "pass", options.runtimeAdapter));
620
- }
621
- const failures = checks.filter((check) => check.status === "fail");
622
- if (failures.length > 0) {
623
- const summary = failures.map((check) => `${check.label}${check.detail ? `: ${check.detail}` : ""}`).join("; ");
624
- if (failures.some((check) => check.id === "duplicate-active-run") && taskId) {
625
- throw new CliError2(`Task ${taskId} already has an active Rig run. ${summary}`, 1);
626
- }
627
- throw new CliError2(`Task run preflight failed: ${summary}`, 1);
628
- }
629
- return { ok: true, checks };
630
- }
631
- async function runProjectMainSyncPreflight(context, options) {
632
- if (context.dryRun) {
633
- if (context.outputMode === "text" && !options.disabled) {
634
- console.log("[dry-run] project-rig pre-run sync check");
635
- }
636
- return;
637
- }
638
- const result = await ensureProjectMainFreshBeforeRun({
639
- projectRoot: context.projectRoot,
640
- disabled: options.disabled,
641
- runBootstrap: async () => {
642
- const bootstrap = await context.runCommand(["bun", "run", "bootstrap"]);
643
- if (bootstrap.exitCode !== 0) {
644
- throw new CliError2(bootstrap.stderr || bootstrap.stdout || "bun run bootstrap failed during project pre-run sync", bootstrap.exitCode || 1);
645
- }
646
- }
647
- });
648
- if (context.outputMode !== "text") {
649
- return;
650
- }
651
- switch (result.status) {
652
- case "disabled":
653
- console.log("Project pre-run sync skipped (--skip-project-sync).");
654
- break;
655
- case "skipped_not_main":
656
- console.log(`Project pre-run sync skipped (current branch: ${result.branch}).`);
657
- break;
658
- case "up_to_date":
659
- break;
660
- case "local_ahead":
661
- console.log(`Project pre-run sync skipped (local main ahead by ${result.localAhead} commit(s)).`);
662
- break;
663
- case "updated":
664
- console.log(`Project pre-run sync updated local main from origin/main (+${result.remoteAhead}) and bootstrapped.`);
665
- break;
666
- }
667
- }
668
-
669
- // packages/cli/src/withMutedConsole.ts
670
- function isPromise(value) {
671
- if (typeof value !== "object" && typeof value !== "function") {
672
- return false;
230
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
231
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
232
+ } catch {
233
+ return null;
673
234
  }
674
- return value !== null && typeof value.then === "function";
675
235
  }
676
- function withMutedConsole(mute, fn) {
677
- if (!mute) {
678
- return fn();
679
- }
680
- const originalLog = console.log;
681
- const originalWarn = console.warn;
682
- const originalInfo = console.info;
683
- const restore = () => {
684
- console.log = originalLog;
685
- console.warn = originalWarn;
686
- console.info = originalInfo;
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)
687
277
  };
688
- console.log = () => {};
689
- console.warn = () => {};
690
- console.info = () => {};
691
- try {
692
- const result = fn();
693
- if (isPromise(result)) {
694
- return result.finally(restore);
695
- }
696
- restore();
697
- return result;
698
- } catch (error) {
699
- restore();
700
- throw error;
701
- } finally {
702
- if (console.log === originalLog) {
703
- restore();
704
- }
705
- }
706
- }
707
-
708
- // packages/cli/src/commands/_task-picker.ts
709
- import { createInterface } from "readline/promises";
710
- function taskId(task) {
711
- return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
712
- }
713
- function taskTitle(task) {
714
- return typeof task.title === "string" && task.title.trim() ? task.title : "Untitled task";
715
- }
716
- function taskStatus(task) {
717
- return typeof task.status === "string" && task.status.trim() ? task.status : "unknown";
718
- }
719
- function renderTaskPickerRows(tasks) {
720
- return tasks.map((task, index) => `${index + 1}. ${taskId(task)} \xB7 ${taskStatus(task)} \xB7 ${taskTitle(task)}`);
721
278
  }
722
- async function selectTaskWithTextPicker(tasks, io = {}) {
723
- if (tasks.length === 0)
724
- return null;
725
- if (tasks.length === 1)
726
- return tasks[0];
727
- const isTty = io.isTty ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
728
- if (!isTty) {
729
- throw new Error("task run requires an interactive terminal to pick a task; pass --task <id>, --next, or --detach with a task id.");
730
- }
731
- const prompt = io.prompt ?? (async (question) => {
732
- const rl = createInterface({ input: process.stdin, output: process.stdout });
733
- try {
734
- return await rl.question(question);
735
- } finally {
736
- rl.close();
737
- }
738
- });
739
- console.log("Select Rig task:");
740
- for (const row of renderTaskPickerRows(tasks))
741
- console.log(` ${row}`);
742
- const answer = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
743
- if (!answer)
744
- return null;
745
- if (/^\d+$/.test(answer)) {
746
- const index = Number.parseInt(answer, 10) - 1;
747
- return tasks[index] ?? null;
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}.`);
748
287
  }
749
- return tasks.find((task) => taskId(task) === answer) ?? null;
288
+ return {
289
+ kind: config.taskSource.kind,
290
+ source: taskSourceFactory.factory(config.taskSource, { projectRoot: normalizedRoot })
291
+ };
750
292
  }
751
-
752
- // packages/cli/src/commands/_operator-view.ts
753
- import { createInterface as createInterface2 } from "readline";
754
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
755
- var CANONICAL_STAGES = [
756
- "Connect",
757
- "GitHub/task sync",
758
- "Prepare workspace",
759
- "Launch Pi",
760
- "Plan",
761
- "Implement",
762
- "Validate",
763
- "Commit",
764
- "Open PR",
765
- "Review/CI",
766
- "Merge",
767
- "Complete"
768
- ];
769
- function renderOperatorSnapshot(snapshot) {
770
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
771
- const runId = String(run.runId ?? run.id ?? "run");
772
- const status = String(run.status ?? "unknown");
773
- const logs = snapshot.logs ?? [];
774
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
775
- const match = logs.find((log) => String(log.title ?? "").toLowerCase() === stage.toLowerCase() || String(log.stage ?? "").toLowerCase() === stage.toLowerCase());
776
- return match ? [`${stage}: ${String(match.status ?? status)}`] : [];
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)()
777
369
  });
778
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
779
- `);
780
- }
781
- function runStatusFromPayload(payload) {
782
- const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
783
- return String(run.status ?? "unknown").toLowerCase();
784
- }
785
- async function applyOperatorCommand(context, input, deps = {}) {
786
- const line = input.line.trim();
787
- if (!line)
788
- return { action: "ignored" };
789
- if (line === "/detach" || line === "/quit" || line === "/q") {
790
- return { action: "detach", message: "Detached from run." };
791
- }
792
- if (line === "/stop") {
793
- await (deps.stop ?? stopRunViaServer)(context, input.runId);
794
- return { action: "stopped", message: "Stop requested." };
795
- }
796
- const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
797
- if (!userMessage)
798
- return { action: "ignored" };
799
- await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
800
- return { action: "continue", message: "Steering message queued." };
801
- }
802
- async function readOperatorSnapshot(context, runId) {
803
- const run = await getRunDetailsViaServer(context, runId);
804
- const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
805
- const entries = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
806
- return { run, logs: entries, rendered: renderOperatorSnapshot({ run, logs: entries }) };
807
- }
808
- async function attachRunOperatorView(context, input) {
809
- let steered = false;
810
- if (input.message?.trim()) {
811
- await steerRunViaServer(context, input.runId, input.message.trim());
812
- steered = true;
813
- }
814
- let snapshot = await readOperatorSnapshot(context, input.runId);
815
- if (context.outputMode === "text") {
816
- console.log(snapshot.rendered);
817
- if (steered)
818
- console.log("Steering message queued.");
819
- }
820
- let detached = false;
821
- let rl = null;
822
- if (input.follow && !input.once && context.outputMode === "text") {
823
- if (input.interactive !== false && process.stdin.isTTY) {
824
- console.log("Controls: /user <message>, /stop, /detach");
825
- rl = createInterface2({ input: process.stdin, output: process.stdout, terminal: false });
826
- rl.on("line", (line) => {
827
- applyOperatorCommand(context, { runId: input.runId, line }).then((result) => {
828
- if (result.message)
829
- console.log(result.message);
830
- if (result.action === "detach" || result.action === "stopped") {
831
- detached = true;
832
- rl?.close();
833
- }
834
- }).catch((error) => console.log(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
835
- });
836
- }
837
- let lastRendered = snapshot.rendered;
838
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
839
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
840
- await Bun.sleep(pollMs);
841
- snapshot = await readOperatorSnapshot(context, input.runId);
842
- if (snapshot.rendered !== lastRendered) {
843
- console.log(snapshot.rendered);
844
- lastRendered = snapshot.rendered;
845
- }
846
- }
847
- rl?.close();
848
- }
849
- return { ...snapshot, steered, detached };
370
+ return { runId };
850
371
  }
851
372
 
852
373
  // packages/cli/src/commands/task.ts
853
- import { buildPluginHostContext } from "@rig/runtime/control-plane/plugin-host-context";
854
- import { loadConfig } from "@rig/core/load-config";
855
- async function readStdin() {
856
- const chunks = [];
857
- for await (const chunk of process.stdin) {
858
- chunks.push(Buffer.from(chunk));
859
- }
860
- 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;
861
397
  }
862
- function normalizeAssignedToAlias(value) {
863
- if (!value)
398
+ function parsePositiveLimit(value) {
399
+ if (value === undefined)
864
400
  return;
865
- 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;
866
406
  }
867
407
  function parseTaskFilters(args) {
868
408
  let pending = args;
869
409
  const assigneeResult = takeOption(pending, "--assignee");
870
410
  pending = assigneeResult.rest;
871
- const assignedToResult = takeOption(pending, "--assigned-to");
872
- pending = assignedToResult.rest;
873
411
  const stateResult = takeOption(pending, "--state");
874
412
  pending = stateResult.rest;
875
- const statusResult = takeOption(pending, "--status");
876
- pending = statusResult.rest;
877
413
  const limitResult = takeOption(pending, "--limit");
878
414
  pending = limitResult.rest;
879
- const normalizedAssignedTo = normalizeAssignedToAlias(assignedToResult.value);
880
- if (assigneeResult.value && normalizedAssignedTo && assigneeResult.value !== normalizedAssignedTo) {
881
- throw new CliError2("--assignee and --assigned-to cannot specify different assignees.", 2);
882
- }
883
- const assignee = normalizedAssignedTo ?? assigneeResult.value;
884
- const limit = (() => {
885
- if (!limitResult.value)
886
- return;
887
- const parsed = Number.parseInt(limitResult.value, 10);
888
- if (!Number.isFinite(parsed) || parsed < 1) {
889
- throw new CliError2("--limit must be a positive integer.", 2);
890
- }
891
- return parsed;
892
- })();
893
- const filters = {
894
- ...assignee ? { assignee } : {},
895
- ...stateResult.value ? { state: stateResult.value } : {},
896
- ...statusResult.value ? { status: statusResult.value } : {},
897
- ...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
898
432
  };
899
- return { filters, rest: pending };
900
433
  }
901
- function mapConfiguredRuntimeMode(mode) {
902
- if (!mode)
434
+ function normalizeAssigneeFilter(value) {
435
+ const trimmed = value?.trim();
436
+ if (!trimmed)
903
437
  return;
904
- 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;
905
443
  }
906
- async function loadTaskRunProjectDefaults(projectRoot) {
907
- try {
908
- const config = await loadConfig(projectRoot);
909
- return {
910
- runtimeAdapter: config.runtime?.harness,
911
- model: config.runtime?.model,
912
- runtimeMode: mapConfiguredRuntimeMode(config.runtime?.mode),
913
- prMode: config.pr?.mode
914
- };
915
- } catch {
916
- 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;
917
449
  }
450
+ return;
918
451
  }
919
- function normalizePrMode(value) {
920
- if (!value)
921
- return;
922
- if (value === "auto" || value === "ask" || value === "off")
923
- return value;
924
- throw new CliError2("--pr must be auto, ask, or off.", 2);
925
- }
926
- function detectLocalDirtyState(projectRoot) {
927
- const result = spawnSync2("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
928
- if (result.status !== 0)
929
- return { dirty: false, modified: 0, untracked: 0, lines: [] };
930
- const lines = result.stdout.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean);
931
- return {
932
- dirty: lines.length > 0,
933
- modified: lines.filter((line) => !line.startsWith("?? ")).length,
934
- untracked: lines.filter((line) => line.startsWith("?? ")).length,
935
- lines
936
- };
452
+ function isRecord(value) {
453
+ return typeof value === "object" && value !== null && !Array.isArray(value);
937
454
  }
938
- function selectedServerKind(projectRoot) {
939
- try {
940
- return resolveSelectedConnection(projectRoot)?.connection.kind === "remote" ? "remote" : "local";
941
- } catch {
942
- return "local";
943
- }
455
+ function readTaskStatus(task) {
456
+ const value = task.status;
457
+ return typeof value === "string" ? value.trim().toLowerCase() : "";
944
458
  }
945
- async function resolveDirtyBaselineForTaskRun(context, explicit) {
946
- if (explicit && explicit !== "head" && explicit !== "dirty-snapshot") {
947
- throw new CliError2("--dirty-baseline must be head or dirty-snapshot.", 2);
948
- }
949
- if (selectedServerKind(context.projectRoot) !== "local") {
950
- return { mode: explicit === "dirty-snapshot" ? "dirty-snapshot" : "head", state: null };
951
- }
952
- const state = detectLocalDirtyState(context.projectRoot);
953
- if (!state.dirty)
954
- return { mode: "head", state };
955
- if (context.outputMode === "text") {
956
- console.log(`Repo state: dirty (${state.modified} modified, ${state.untracked} untracked).`);
957
- }
958
- if (explicit)
959
- return { mode: explicit, state };
960
- if (context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY) {
961
- const rl = createInterface3({ input: process.stdin, output: process.stdout });
962
- try {
963
- const answer = (await rl.question("Include current uncommitted changes in run baseline? [y/N] ")).trim().toLowerCase();
964
- return { mode: answer === "y" || answer === "yes" ? "dirty-snapshot" : "head", state };
965
- } finally {
966
- rl.close();
967
- }
968
- }
969
- return { mode: "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;
970
464
  }
971
- function normalizeTaskRunTaskId(value) {
972
- const trimmed = value?.trim() ?? "";
973
- if (!trimmed)
974
- return null;
975
- const issueNumber = trimmed.match(/^#(\d+)$/)?.[1];
976
- return issueNumber ?? trimmed;
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));
484
+ }
485
+ return [];
486
+ }
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
+ });
977
508
  }
978
- function readTaskId(task) {
979
- 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);
980
512
  }
981
- function readTaskString(task, key) {
982
- const value = task[key];
983
- 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;
984
516
  }
985
- function summarizeTask(task, options = {}) {
986
- const raw = task.raw && typeof task.raw === "object" && !Array.isArray(task.raw) ? task.raw : null;
517
+ function asDependencyProjection(task) {
518
+ const record = task;
987
519
  return {
988
- id: readTaskId(task),
989
- title: readTaskString(task, "title"),
990
- status: readTaskString(task, "status"),
991
- source: typeof task.source === "string" ? task.source : undefined,
992
- url: typeof raw?.url === "string" ? raw.url : undefined,
993
- number: typeof raw?.number === "number" ? raw.number : undefined,
994
- labels: Array.isArray(task.labels) ? task.labels : Array.isArray(raw?.labels) ? raw.labels : undefined,
995
- assignees: Array.isArray(raw?.assignees) ? raw.assignees : undefined,
996
- readiness: typeof task.readiness === "string" || typeof task.readiness === "boolean" ? task.readiness : undefined,
997
- validators: Array.isArray(task.validators) ? task.validators : Array.isArray(task.validation) ? task.validation : undefined,
998
- ...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 : {}
999
524
  };
1000
525
  }
1001
- function printTaskSummary(task) {
1002
- const id = readTaskId(task) ?? "<unknown>";
1003
- const title = readTaskString(task, "title") ?? "Untitled task";
1004
- const status = readTaskString(task, "status") ?? "unknown";
1005
- console.log(`- ${id} \xB7 ${status} \xB7 ${title}`);
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)
530
+ });
531
+ return selected ?? matching[0] ?? null;
1006
532
  }
1007
- async function validatorRegistryForTaskCommands(projectRoot) {
1008
- return buildPluginHostContext(projectRoot).then((ctx) => ctx?.validatorRegistry ?? undefined).catch(() => {
1009
- return;
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"
1010
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`." });
626
+ }
627
+ return { taskId, task: await getTaskForCommand(context.projectRoot, taskId, deps) };
1011
628
  }
1012
- async function executeTask(context, args, options) {
1013
- const [command = "info", ...rest] = args;
629
+ async function executeTask(context, args, deps = {}) {
630
+ const [command = "help", ...rest] = args;
1014
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" };
1015
635
  case "list": {
1016
- let pending = rest;
1017
- const rawResult = takeFlag(pending, "--raw");
1018
- pending = rawResult.rest;
1019
- const { filters, rest: remaining } = parseTaskFilters(pending);
1020
- requireNoExtraArgs(remaining, "bun run rig task list [--raw] [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
1021
- const tasks = await listWorkspaceTasksViaServer(context, filters);
1022
- if (context.outputMode === "text") {
1023
- if (tasks.length === 0) {
1024
- console.log("No matching tasks.");
1025
- } else {
1026
- for (const task of tasks) {
1027
- if (rawResult.value)
1028
- console.log(JSON.stringify(summarizeTask(task, { raw: true })));
1029
- else
1030
- printTaskSummary(task);
1031
- }
1032
- }
1033
- }
1034
- return {
1035
- ok: true,
1036
- group: "task",
1037
- command,
1038
- details: { count: tasks.length, filters, raw: rawResult.value, tasks: tasks.map((task) => summarizeTask(task, { raw: rawResult.value })) }
1039
- };
1040
- }
1041
- case "show": {
1042
- const taskOption = takeOption(rest, "--task");
1043
- const positional = taskOption.rest.length > 0 && taskOption.rest[0] && !taskOption.rest[0].startsWith("-") ? taskOption.rest[0] : undefined;
1044
- const remaining = positional ? taskOption.rest.slice(1) : taskOption.rest;
1045
- requireNoExtraArgs(remaining, "bun run rig task show <id>|--task <id>");
1046
- const taskId2 = normalizeTaskRunTaskId(taskOption.value ?? positional);
1047
- if (!taskId2)
1048
- throw new CliError2("task show requires a task id.", 2);
1049
- const task = await getWorkspaceTaskViaServer(context, taskId2);
1050
- if (!task)
1051
- throw new CliError2(`Task not found: ${taskId2}`, 3);
1052
- const summary = summarizeTask(task, { raw: true });
1053
- if (context.outputMode === "text")
1054
- console.log(JSON.stringify(summary, null, 2));
1055
- return { ok: true, group: "task", command, details: { task: summary } };
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 } };
1056
641
  }
1057
642
  case "next": {
1058
- const { filters, rest: remaining } = parseTaskFilters(rest);
1059
- requireNoExtraArgs(remaining, "bun run rig task next [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
1060
- const selected = await selectNextWorkspaceTaskViaServer(context, filters);
1061
- if (context.outputMode === "text") {
1062
- if (selected.task) {
1063
- printTaskSummary(selected.task);
1064
- } else {
1065
- console.log("No matching tasks.");
1066
- }
1067
- }
1068
- return {
1069
- ok: true,
1070
- group: "task",
1071
- command,
1072
- details: {
1073
- count: selected.count,
1074
- filters,
1075
- task: selected.task ? summarizeTask(selected.task) : null
1076
- }
1077
- };
1078
- }
1079
- case "info": {
1080
- const { value: task, rest: remaining } = takeOption(rest, "--task");
1081
- requireNoExtraArgs(remaining, "bun run rig task info [--task <beads-id>]");
1082
- await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, task || undefined));
1083
- return { ok: true, group: "task", command, details: { task: task || null } };
1084
- }
1085
- case "scope": {
1086
- const filesFlag = takeFlag(rest, "--files");
1087
- const { value: task, rest: remaining } = takeOption(filesFlag.rest, "--task");
1088
- requireNoExtraArgs(remaining, "bun run rig task scope [--task <id>] [--files]");
1089
- await withMutedConsole(context.outputMode === "json", () => taskScope(context.projectRoot, filesFlag.value, task || undefined));
1090
- return { ok: true, group: "task", command, details: { files: filesFlag.value, task: task || null } };
1091
- }
1092
- case "deps":
1093
- requireNoExtraArgs(rest, "bun run rig task deps");
1094
- await withMutedConsole(context.outputMode === "json", () => taskDeps(context.projectRoot));
1095
- return { ok: true, group: "task", command };
1096
- case "status":
1097
- requireNoExtraArgs(rest, "bun run rig task status");
1098
- withMutedConsole(context.outputMode === "json", () => taskStatus2(context.projectRoot));
1099
- return { ok: true, group: "task", command };
1100
- case "artifacts":
1101
- requireNoExtraArgs(rest, "bun run rig task artifacts");
1102
- withMutedConsole(context.outputMode === "json", () => taskArtifacts(context.projectRoot));
1103
- return { ok: true, group: "task", command };
1104
- case "artifact-dir": {
1105
- requireNoExtraArgs(rest, "bun run rig task artifact-dir");
1106
- const path = taskArtifactDir(context.projectRoot);
1107
- if (context.outputMode === "text") {
1108
- console.log(path);
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 } };
1109
650
  }
1110
- return { ok: true, group: "task", command, details: { path } };
651
+ printText(context, formatTaskCard(task, { selected: true }));
652
+ return { ok: true, group: "task", command, details: { task } };
1111
653
  }
1112
- case "artifact-write": {
1113
- if (rest.length < 1) {
1114
- throw new CliError2(`Usage: bun run rig task artifact-write <filename> [--file <path>]
1115
- ` + ` Reads content from stdin (or --file), writes to the active task artifact dir.
1116
- ` + " Example: echo '...' | rig task artifact-write collection-audit.md");
1117
- }
1118
- const artifactFilename = rest[0];
1119
- const fileFlag = takeOption(rest.slice(1), "--file");
1120
- let content;
1121
- if (fileFlag.value) {
1122
- content = readFileSync4(resolve4(context.projectRoot, fileFlag.value), "utf-8");
1123
- } else {
1124
- content = await readStdin();
1125
- }
1126
- if (!artifactFilename) {
1127
- throw new CliError2("Usage: bun run rig task artifact-write <filename> [--file path]");
1128
- }
1129
- withMutedConsole(context.outputMode === "json", () => taskArtifactWrite(context.projectRoot, artifactFilename, content));
1130
- return { ok: true, group: "task", command, details: { filename: artifactFilename } };
1131
- }
1132
- case "report-bug":
1133
- return options.executeTaskReportBug(context, rest);
1134
- case "lookup": {
1135
- if (rest.length !== 1) {
1136
- throw new CliError2("Usage: bun run rig task lookup <beads-id>");
1137
- }
1138
- const lookupId = rest[0];
1139
- if (!lookupId) {
1140
- throw new CliError2("Usage: bun run rig task lookup <beads-id>");
1141
- }
1142
- const result = taskLookup(context.projectRoot, lookupId);
1143
- if (context.outputMode === "text") {
1144
- console.log(result);
1145
- }
1146
- return { ok: true, group: "task", command, details: { id: lookupId, result } };
654
+ case "show": {
655
+ let pending = rest;
656
+ const rawResult = takeFlag(pending, "--raw");
657
+ pending = rawResult.rest;
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);
664
+ if (!task)
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 };
1147
668
  }
1148
- case "record": {
1149
- if (rest.length < 2) {
1150
- throw new CliError2("Usage: bun run rig task record <decision|failure> <text>");
1151
- }
1152
- const type = rest[0];
1153
- if (type !== "decision" && type !== "failure") {
1154
- throw new CliError2("Usage: bun run rig task record <decision|failure> <text>");
1155
- }
1156
- withMutedConsole(context.outputMode === "json", () => taskRecord(context.projectRoot, type, rest.slice(1).join(" ")));
1157
- 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 };
1158
678
  }
1159
- case "ready":
1160
- requireNoExtraArgs(rest, "bun run rig task ready");
1161
- await withMutedConsole(context.outputMode === "json", () => taskReady(context.projectRoot));
1162
- return { ok: true, group: "task", command };
1163
679
  case "run": {
1164
680
  let pending = rest;
1165
681
  const nextResult = takeFlag(pending, "--next");
1166
682
  pending = nextResult.rest;
683
+ const detachResult = takeFlag(pending, "--detach");
684
+ pending = detachResult.rest;
1167
685
  const taskResult = takeOption(pending, "--task");
1168
686
  pending = taskResult.rest;
1169
687
  const titleResult = takeOption(pending, "--title");
1170
688
  pending = titleResult.rest;
1171
- const runtimeAdapterResult = takeOption(pending, "--runtime-adapter");
1172
- pending = runtimeAdapterResult.rest;
1173
689
  const modelResult = takeOption(pending, "--model");
1174
690
  pending = modelResult.rest;
1175
- const runtimeModeResult = takeOption(pending, "--runtime-mode");
1176
- pending = runtimeModeResult.rest;
1177
- const interactionModeResult = takeOption(pending, "--interaction-mode");
1178
- pending = interactionModeResult.rest;
691
+ const promptResult = takeOption(pending, "--prompt");
692
+ pending = promptResult.rest;
1179
693
  const initialPromptResult = takeOption(pending, "--initial-prompt");
1180
694
  pending = initialPromptResult.rest;
1181
- const prResult = takeOption(pending, "--pr");
1182
- pending = prResult.rest;
1183
- const noPrResult = takeFlag(pending, "--no-pr");
1184
- pending = noPrResult.rest;
1185
- const dirtyBaselineResult = takeOption(pending, "--dirty-baseline");
1186
- pending = dirtyBaselineResult.rest;
1187
- const skipProjectSyncResult = takeFlag(pending, "--skip-project-sync");
1188
- pending = skipProjectSyncResult.rest;
1189
- const detachResult = takeFlag(pending, "--detach");
1190
- pending = detachResult.rest;
1191
- const filterResult = parseTaskFilters(pending);
1192
- pending = filterResult.rest;
1193
- const positionalTaskId = pending.length > 0 && pending[0] && !pending[0].startsWith("-") ? normalizeTaskRunTaskId(pending[0]) : null;
1194
- if (positionalTaskId) {
1195
- pending = pending.slice(1);
1196
- }
1197
- requireNoExtraArgs(pending, "bun run rig task run [#<issue>|<task-id>] [--next] [--task <id>] [--detach] [--assignee <login|@me>] [--assigned-to <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]");
1198
- if (nextResult.value && (taskResult.value || positionalTaskId)) {
1199
- throw new CliError2("task run cannot combine --next with an explicit task id.", 2);
1200
- }
1201
- if (taskResult.value && positionalTaskId) {
1202
- throw new CliError2("task run cannot combine positional task id with --task <id>.", 2);
1203
- }
1204
- if (prResult.value && noPrResult.value) {
1205
- throw new CliError2("task run cannot combine --pr with --no-pr.", 2);
1206
- }
1207
- let selectedTask = null;
1208
- let selectedTaskId = normalizeTaskRunTaskId(taskResult.value) ?? positionalTaskId;
1209
- if (nextResult.value) {
1210
- const selected = await selectNextWorkspaceTaskViaServer(context, filterResult.filters);
1211
- selectedTask = selected.task;
1212
- selectedTaskId = selected.task ? readTaskId(selected.task) : null;
1213
- if (!selectedTaskId) {
1214
- throw new CliError2("No matching task found for task run --next.", 3);
1215
- }
1216
- }
1217
- if (!selectedTaskId && !initialPromptResult.value && !titleResult.value) {
1218
- if (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY) {
1219
- throw new CliError2("task run requires an interactive terminal to pick a task; pass --next, --task <id>, or --initial-prompt/--title for an ad hoc run.", 2);
1220
- }
1221
- const tasks = await listWorkspaceTasksViaServer(context, filterResult.filters);
1222
- selectedTask = await selectTaskWithTextPicker(tasks);
1223
- selectedTaskId = selectedTask ? readTaskId(selectedTask) : null;
1224
- if (!selectedTaskId) {
1225
- throw new CliError2("No task selected.", 3);
1226
- }
1227
- }
1228
- await runProjectMainSyncPreflight(context, { disabled: skipProjectSyncResult.value });
1229
- const projectDefaults = await loadTaskRunProjectDefaults(context.projectRoot);
1230
- const runtimeAdapter = normalizeRuntimeAdapter(runtimeAdapterResult.value ?? projectDefaults.runtimeAdapter);
1231
- await runFastTaskRunPreflight(context, {
1232
- taskId: selectedTaskId,
1233
- runtimeAdapter
1234
- });
1235
- const dirtyBaseline = await resolveDirtyBaselineForTaskRun(context, dirtyBaselineResult.value);
1236
- const prMode = noPrResult.value ? "off" : normalizePrMode(prResult.value) ?? projectDefaults.prMode;
1237
- const submitted = await submitTaskRunViaServer(context, {
1238
- runId: context.runId,
1239
- taskId: selectedTaskId ?? undefined,
1240
- title: titleResult.value ?? undefined,
1241
- runtimeAdapter,
1242
- model: modelResult.value ?? projectDefaults.model,
1243
- runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
1244
- interactionMode: interactionModeResult.value || "default",
1245
- initialPrompt: initialPromptResult.value ?? undefined,
1246
- baselineMode: dirtyBaseline.mode,
1247
- prMode
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 } };
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":
715
+ case "verify": {
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 } : {}
1248
738
  });
1249
- let attachDetails = null;
1250
- if (!detachResult.value && context.outputMode === "text") {
1251
- console.log(`Run submitted: ${submitted.runId}`);
1252
- if (selectedTask) {
1253
- printTaskSummary(selectedTask);
1254
- }
1255
- attachDetails = await attachRunOperatorView(context, { runId: submitted.runId, follow: true });
1256
- } else if (context.outputMode === "text") {
1257
- console.log(`Run submitted: ${submitted.runId}`);
1258
- if (selectedTask) {
1259
- printTaskSummary(selectedTask);
1260
- }
1261
- }
1262
- return {
1263
- ok: true,
1264
- group: "task",
1265
- command,
1266
- details: {
1267
- runId: submitted.runId,
1268
- taskId: selectedTaskId,
1269
- title: titleResult.value ?? null,
1270
- selectedTask: selectedTask ? summarizeTask(selectedTask) : null,
1271
- filters: nextResult.value ? filterResult.filters : undefined,
1272
- attached: Boolean(attachDetails),
1273
- attach: attachDetails,
1274
- runtimeAdapter,
1275
- model: modelResult.value ?? projectDefaults.model ?? null,
1276
- runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
1277
- prMode: prMode ?? null,
1278
- dirtyBaseline: { mode: dirtyBaseline.mode, dirty: dirtyBaseline.state?.dirty ?? false }
1279
- }
1280
- };
739
+ return { ok: true, group: "task", command, details: { ...summary, reason: reasonResult.value ?? null } };
1281
740
  }
1282
- case "validate": {
1283
- const { value: task, rest: remaining } = takeOption(rest, "--task");
1284
- requireNoExtraArgs(remaining, "bun run rig task validate [--task <beads-id>]");
1285
- if (context.dryRun) {
1286
- await context.runCommand(["rig", "task", "validate", ...task ? ["--task", task] : []]);
1287
- return { ok: true, group: "task", command, details: { task: task || "active" } };
1288
- }
1289
- const ok = await withMutedConsole(context.outputMode === "json", async () => taskValidate(context.projectRoot, task || undefined, await validatorRegistryForTaskCommands(context.projectRoot)));
1290
- if (!ok) {
1291
- throw new CliError2(`Validation failed for ${task || "active task"}.`, 2);
1292
- }
1293
- return { ok: true, group: "task", command, details: { task: task || "active" } };
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 } };
1294
747
  }
1295
- case "verify": {
1296
- const { value: task, rest: remaining } = takeOption(rest, "--task");
1297
- requireNoExtraArgs(remaining, "bun run rig task verify [--task <beads-id>]");
1298
- if (context.dryRun) {
1299
- await context.runCommand(["rig", "task", "verify", ...task ? ["--task", task] : []]);
1300
- return { ok: true, group: "task", command, details: { task: task || "active" } };
1301
- }
1302
- const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, context.plugins, task || undefined));
1303
- if (!ok) {
1304
- throw new CliError2(`Verification rejected for ${task || "active task"}.`, 2);
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>]`." });
1305
762
  }
1306
- 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 } };
1307
766
  }
1308
- case "reset": {
1309
- const { value: task, rest: remaining } = takeOption(rest, "--task");
1310
- requireNoExtraArgs(remaining, "bun run rig task reset --task <beads-id>");
1311
- const requiredTask = requireTask(task, "bun run rig task reset --task <beads-id>");
1312
- await context.runCommand(["br", "--no-db", "update", requiredTask, "--status", "open"]);
1313
- 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 };
1314
774
  }
1315
- case "details": {
1316
- const { value: task, rest: remaining } = takeOption(rest, "--task");
1317
- requireNoExtraArgs(remaining, "bun run rig task details --task <beads-id>");
1318
- const requiredTask = requireTask(task, "bun run rig task details --task <beads-id>");
1319
- await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, requiredTask));
1320
- return { ok: true, group: "task", command, details: { task: requiredTask } };
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 };
1321
781
  }
1322
- case "reopen": {
1323
- const { value: task, rest: rest1 } = takeOption(rest, "--task");
1324
- const allFlag = takeFlag(rest1, "--all");
1325
- const { rest: remaining } = takeOption(allFlag.rest, "--reason");
1326
- requireNoExtraArgs(remaining, "bun run rig task reopen [--task <id> | --all] [--reason <text>]");
1327
- if (!allFlag.value && !task) {
1328
- throw new CliError2("Usage: bun run rig task reopen [--task <id> | --all] [--reason <text>]");
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>]" });
1329
806
  }
1330
- const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
1331
- all: allFlag.value,
1332
- taskId: task || undefined,
1333
- dryRun: false
1334
- }));
1335
- 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 } };
1336
811
  }
1337
812
  default:
1338
- throw new CliError2(`Unknown task command: ${command}`);
813
+ throw new CliError(`Unknown task command: ${command}`, 1, { hint: "Run `rig task --help`." });
1339
814
  }
1340
815
  }
1341
816
  export {