@h-rig/cli 0.0.6-alpha.1 → 0.0.6-alpha.100

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