@h-rig/cli 0.0.6-alpha.24 → 0.0.6-alpha.240

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 (51) hide show
  1. package/README.md +6 -28
  2. package/package.json +13 -28
  3. package/dist/bin/build-rig-binaries.js +0 -107
  4. package/dist/bin/rig.js +0 -11112
  5. package/dist/src/commands/_authority-runs.js +0 -111
  6. package/dist/src/commands/_cli-format.js +0 -106
  7. package/dist/src/commands/_connection-state.js +0 -123
  8. package/dist/src/commands/_doctor-checks.js +0 -507
  9. package/dist/src/commands/_operator-surface.js +0 -204
  10. package/dist/src/commands/_operator-view.js +0 -1147
  11. package/dist/src/commands/_parsers.js +0 -107
  12. package/dist/src/commands/_paths.js +0 -50
  13. package/dist/src/commands/_pi-frontend.js +0 -843
  14. package/dist/src/commands/_pi-install.js +0 -185
  15. package/dist/src/commands/_pi-worker-bridge-extension.js +0 -761
  16. package/dist/src/commands/_policy.js +0 -79
  17. package/dist/src/commands/_preflight.js +0 -403
  18. package/dist/src/commands/_probes.js +0 -13
  19. package/dist/src/commands/_run-driver-helpers.js +0 -289
  20. package/dist/src/commands/_server-client.js +0 -514
  21. package/dist/src/commands/_snapshot-upload.js +0 -318
  22. package/dist/src/commands/_task-picker.js +0 -76
  23. package/dist/src/commands/agent.js +0 -499
  24. package/dist/src/commands/browser.js +0 -890
  25. package/dist/src/commands/connect.js +0 -180
  26. package/dist/src/commands/dist.js +0 -402
  27. package/dist/src/commands/doctor.js +0 -517
  28. package/dist/src/commands/github.js +0 -281
  29. package/dist/src/commands/inbox.js +0 -160
  30. package/dist/src/commands/init.js +0 -1563
  31. package/dist/src/commands/inspect.js +0 -174
  32. package/dist/src/commands/inspector.js +0 -256
  33. package/dist/src/commands/plugin.js +0 -167
  34. package/dist/src/commands/profile-and-review.js +0 -178
  35. package/dist/src/commands/queue.js +0 -198
  36. package/dist/src/commands/remote.js +0 -507
  37. package/dist/src/commands/repo-git-harness.js +0 -221
  38. package/dist/src/commands/run.js +0 -1674
  39. package/dist/src/commands/server.js +0 -373
  40. package/dist/src/commands/setup.js +0 -687
  41. package/dist/src/commands/task-report-bug.js +0 -1083
  42. package/dist/src/commands/task-run-driver.js +0 -2600
  43. package/dist/src/commands/task.js +0 -2178
  44. package/dist/src/commands/test.js +0 -39
  45. package/dist/src/commands/workspace.js +0 -123
  46. package/dist/src/commands.js +0 -10791
  47. package/dist/src/index.js +0 -11130
  48. package/dist/src/launcher.js +0 -133
  49. package/dist/src/report-bug.js +0 -260
  50. package/dist/src/runner.js +0 -273
  51. package/dist/src/withMutedConsole.js +0 -42
@@ -1,507 +0,0 @@
1
- // @bun
2
- var __require = import.meta.require;
3
-
4
- // packages/cli/src/commands/_doctor-checks.ts
5
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
6
- import { resolve as resolve4 } from "path";
7
-
8
- // packages/cli/src/runner.ts
9
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
10
- import { CliError } from "@rig/runtime/control-plane/errors";
11
- 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
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
15
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
16
-
17
- // packages/cli/src/commands/_doctor-checks.ts
18
- import { isSupportedBunVersion, MIN_SUPPORTED_BUN_VERSION } from "@rig/runtime/control-plane/setup-version";
19
-
20
- // packages/cli/src/commands/_connection-state.ts
21
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
22
- import { homedir } from "os";
23
- import { dirname, resolve } from "path";
24
- function resolveGlobalConnectionsPath(env = process.env) {
25
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
26
- if (explicit)
27
- return resolve(explicit);
28
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
29
- if (stateDir)
30
- return resolve(stateDir, "connections.json");
31
- return resolve(homedir(), ".rig", "connections.json");
32
- }
33
- function resolveRepoConnectionPath(projectRoot) {
34
- return resolve(projectRoot, ".rig", "state", "connection.json");
35
- }
36
- function readJsonFile(path) {
37
- if (!existsSync(path))
38
- return null;
39
- try {
40
- return JSON.parse(readFileSync(path, "utf8"));
41
- } catch (error) {
42
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
43
- }
44
- }
45
- function normalizeConnection(value) {
46
- if (!value || typeof value !== "object" || Array.isArray(value))
47
- return null;
48
- const record = value;
49
- if (record.kind === "local")
50
- return { kind: "local", mode: "auto" };
51
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
52
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
53
- return { kind: "remote", baseUrl };
54
- }
55
- return null;
56
- }
57
- function readGlobalConnections(options = {}) {
58
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
59
- const payload = readJsonFile(path);
60
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
61
- return { connections: {} };
62
- }
63
- const rawConnections = payload.connections;
64
- const connections = {};
65
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
66
- for (const [alias, raw] of Object.entries(rawConnections)) {
67
- const connection = normalizeConnection(raw);
68
- if (connection)
69
- connections[alias] = connection;
70
- }
71
- }
72
- return { connections };
73
- }
74
- function readRepoConnection(projectRoot) {
75
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
76
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
77
- return null;
78
- const record = payload;
79
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
80
- if (!selected)
81
- return null;
82
- return {
83
- selected,
84
- project: typeof record.project === "string" ? record.project : undefined,
85
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
86
- };
87
- }
88
- function resolveSelectedConnection(projectRoot, options = {}) {
89
- const repo = readRepoConnection(projectRoot);
90
- if (!repo)
91
- return null;
92
- if (repo.selected === "local")
93
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
94
- const global = readGlobalConnections(options);
95
- const connection = global.connections[repo.selected];
96
- if (!connection) {
97
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
98
- }
99
- return { alias: repo.selected, connection };
100
- }
101
-
102
- // packages/cli/src/commands/_server-client.ts
103
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
104
- import { resolve as resolve2 } from "path";
105
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
106
- var scopedGitHubBearerTokens = new Map;
107
- function cleanToken(value) {
108
- const trimmed = value?.trim();
109
- return trimmed ? trimmed : null;
110
- }
111
- function readPrivateRemoteSessionToken(projectRoot) {
112
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
113
- if (!existsSync2(path))
114
- return null;
115
- try {
116
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
117
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
118
- } catch {
119
- return null;
120
- }
121
- }
122
- function readGitHubBearerTokenForRemote(projectRoot) {
123
- const scopedKey = resolve2(projectRoot);
124
- if (scopedGitHubBearerTokens.has(scopedKey))
125
- return scopedGitHubBearerTokens.get(scopedKey) ?? null;
126
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
127
- if (privateSession)
128
- return privateSession;
129
- return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
130
- }
131
- async function ensureServerForCli(projectRoot) {
132
- try {
133
- const selected = resolveSelectedConnection(projectRoot);
134
- if (selected?.connection.kind === "remote") {
135
- return {
136
- baseUrl: selected.connection.baseUrl,
137
- authToken: readGitHubBearerTokenForRemote(projectRoot),
138
- connectionKind: "remote"
139
- };
140
- }
141
- const connection = await ensureLocalRigServerConnection(projectRoot);
142
- return {
143
- baseUrl: connection.baseUrl,
144
- authToken: connection.authToken,
145
- connectionKind: "local"
146
- };
147
- } catch (error) {
148
- if (error instanceof Error) {
149
- throw new CliError2(error.message, 1);
150
- }
151
- throw error;
152
- }
153
- }
154
- function mergeHeaders(headers, authToken) {
155
- const merged = new Headers(headers);
156
- if (authToken) {
157
- merged.set("authorization", `Bearer ${authToken}`);
158
- }
159
- return merged;
160
- }
161
- function diagnosticMessage(payload) {
162
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
163
- return null;
164
- const record = payload;
165
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
166
- const messages = diagnostics.flatMap((entry) => {
167
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
168
- return [];
169
- const diagnostic = entry;
170
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
171
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
172
- return message ? [`${kind}: ${message}`] : [];
173
- });
174
- return messages.length > 0 ? messages.join("; ") : null;
175
- }
176
- async function requestServerJson(context, pathname, init = {}) {
177
- const server = await ensureServerForCli(context.projectRoot);
178
- const response = await fetch(`${server.baseUrl}${pathname}`, {
179
- ...init,
180
- headers: mergeHeaders(init.headers, server.authToken)
181
- });
182
- const text = await response.text();
183
- const payload = text.trim().length > 0 ? (() => {
184
- try {
185
- return JSON.parse(text);
186
- } catch {
187
- return null;
188
- }
189
- })() : null;
190
- if (!response.ok) {
191
- const diagnostics = diagnosticMessage(payload);
192
- const detail = diagnostics ?? (text || response.statusText);
193
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
194
- }
195
- return payload;
196
- }
197
-
198
- // packages/cli/src/commands/_parsers.ts
199
- async function loadRigConfigOrNull(projectRoot) {
200
- try {
201
- const { loadConfig } = await import("@rig/core/load-config");
202
- return await loadConfig(projectRoot);
203
- } catch {
204
- return null;
205
- }
206
- }
207
-
208
- // packages/cli/src/commands/_pi-install.ts
209
- import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync } from "fs";
210
- import { homedir as homedir2 } from "os";
211
- import { resolve as resolve3 } from "path";
212
- var PI_RIG_PACKAGE_NAME = "@h-rig/pi-rig";
213
- var LEGACY_PI_RIG_PACKAGE_NAME = "@rig/pi-rig";
214
- async function defaultCommandRunner(command, options = {}) {
215
- const proc = Bun.spawn(command, { cwd: options.cwd, stdout: "pipe", stderr: "pipe" });
216
- const [stdout, stderr, exitCode] = await Promise.all([
217
- new Response(proc.stdout).text(),
218
- new Response(proc.stderr).text(),
219
- proc.exited
220
- ]);
221
- return { exitCode, stdout, stderr };
222
- }
223
- function resolvePiRigExtensionPath(homeDir) {
224
- return resolve3(homeDir, ".pi", "agent", "extensions", "pi-rig");
225
- }
226
- function resolvePiHomeDir(inputHomeDir) {
227
- return inputHomeDir ?? process.env.RIG_PI_HOME_DIR?.trim() ?? homedir2();
228
- }
229
- function piListContainsPiRig(output) {
230
- return output.split(/\r?\n/).some((line) => {
231
- const normalized = line.trim();
232
- return normalized.includes(PI_RIG_PACKAGE_NAME) || normalized.includes(LEGACY_PI_RIG_PACKAGE_NAME) || /(?:^|[\\/])packages[\\/]pi-rig(?:$|\s)/.test(normalized);
233
- });
234
- }
235
- async function safeRun(runner, command, options) {
236
- try {
237
- return await runner(command, options);
238
- } catch (error) {
239
- return { exitCode: 1, stdout: "", stderr: error instanceof Error ? error.message : String(error) };
240
- }
241
- }
242
- async function checkPiRigInstall(input = {}) {
243
- const home = resolvePiHomeDir(input.homeDir);
244
- const extensionPath = resolvePiRigExtensionPath(home);
245
- if (process.env.RIG_TEST_FAKE_PI_INSTALL === "1") {
246
- return {
247
- extensionPath,
248
- pi: { ok: true, label: "pi", detail: "fake-pi" },
249
- piRig: { ok: true, label: "pi-rig global extension", detail: extensionPath }
250
- };
251
- }
252
- const exists = input.exists ?? existsSync3;
253
- const runner = input.commandRunner ?? defaultCommandRunner;
254
- const piResult = await safeRun(runner, ["pi", "--version"]);
255
- const piListResult = piResult.exitCode === 0 ? await safeRun(runner, ["pi", "list"]) : { exitCode: 1, stdout: "", stderr: "" };
256
- const listedPiRig = piListResult.exitCode === 0 && piListContainsPiRig(`${piListResult.stdout}
257
- ${piListResult.stderr}`);
258
- const legacyBridge = exists(resolve3(extensionPath, "index.ts"));
259
- const hasPiRig = listedPiRig;
260
- return {
261
- extensionPath,
262
- pi: {
263
- ok: piResult.exitCode === 0,
264
- label: "pi",
265
- detail: (piResult.stdout || piResult.stderr).trim() || undefined,
266
- hint: piResult.exitCode === 0 ? undefined : "Install Pi or run `rig init --yes` to install/update the Pi runtime."
267
- },
268
- piRig: {
269
- ok: hasPiRig,
270
- label: "pi-rig global extension",
271
- detail: hasPiRig ? piListResult.stdout.trim() || PI_RIG_PACKAGE_NAME : legacyBridge ? `${extensionPath} (legacy bridge; reinstall required)` : undefined,
272
- hint: hasPiRig ? undefined : "Run `rig init --yes` to install/enable the global pi-rig package with `pi install`."
273
- }
274
- };
275
- }
276
- async function buildPiSetupChecks(input = {}) {
277
- const status = await checkPiRigInstall(input);
278
- return [status.pi, status.piRig];
279
- }
280
-
281
- // packages/cli/src/commands/_doctor-checks.ts
282
- function check(id, label, status, detail, remediation) {
283
- return {
284
- id,
285
- label,
286
- status,
287
- ...detail ? { detail } : {},
288
- ...remediation ? { remediation } : {}
289
- };
290
- }
291
- function errorMessage(error) {
292
- return error instanceof Error ? error.message : String(error);
293
- }
294
- function isAuthenticated(payload) {
295
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
296
- return false;
297
- const record = payload;
298
- return record.signedIn === true || record.authenticated === true || record.status === "authenticated" || record.ok === true && typeof record.login === "string" && record.login.trim().length > 0;
299
- }
300
- function repoSlugFromConfig(config) {
301
- const project = config?.project;
302
- if (project && typeof project === "object" && !Array.isArray(project)) {
303
- const record = project;
304
- if (typeof record.repo === "string" && /^([^/\s]+)\/([^/\s]+)$/.test(record.repo))
305
- return record.repo;
306
- if (typeof record.name === "string" && /^([^/\s]+)\/([^/\s]+)$/.test(record.name))
307
- return record.name;
308
- }
309
- const taskSource = config?.taskSource;
310
- if (taskSource && typeof taskSource === "object" && !Array.isArray(taskSource)) {
311
- const source = taskSource;
312
- if (typeof source.owner === "string" && typeof source.repo === "string")
313
- return `${source.owner}/${source.repo}`;
314
- }
315
- return null;
316
- }
317
- function loadFallbackConfig(projectRoot) {
318
- const candidates = ["rig.config.ts", "rig.config.mts", "rig.config.json"];
319
- for (const name of candidates) {
320
- const path = resolve4(projectRoot, name);
321
- if (!existsSync4(path))
322
- continue;
323
- try {
324
- const source = readFileSync4(path, "utf8");
325
- if (name.endsWith(".json"))
326
- return JSON.parse(source);
327
- const owner = source.match(/owner\s*:\s*["']([^"']+)["']/)?.[1];
328
- const repo = source.match(/repo\s*:\s*["']([^"']+)["']/)?.[1];
329
- const projectRepo = source.match(/project\s*:\s*\{[^}]*repo\s*:\s*["']([^"']+)["']/s)?.[1] ?? (owner && repo ? `${owner}/${repo}` : undefined);
330
- const taskKind = source.match(/taskSource\s*:\s*\{[^}]*kind\s*:\s*["']([^"']+)["']/s)?.[1];
331
- if (projectRepo || taskKind) {
332
- return {
333
- ...projectRepo ? { project: { name: projectRepo, repo: projectRepo } } : {},
334
- ...taskKind ? { taskSource: { kind: taskKind, ...owner ? { owner } : {}, ...repo ? { repo } : {} } } : {}
335
- };
336
- }
337
- } catch {
338
- return null;
339
- }
340
- }
341
- return null;
342
- }
343
- function projectStatusSlug(projectRoot, config) {
344
- return readRepoConnection(projectRoot)?.project ?? repoSlugFromConfig(config);
345
- }
346
- function githubProjectsCheck(config) {
347
- const github = config?.github;
348
- const projects = github?.projects;
349
- if (!projects?.enabled) {
350
- return check("github-projects", "GitHub Projects status sync", "warn", "disabled or not configured", "Run `rig init --github-project <project>` or configure github.projects when Project status sync should be authoritative.");
351
- }
352
- if (projects.projectId && projects.statusFieldId) {
353
- return check("github-projects", "GitHub Projects status sync", "pass", `project ${projects.projectId}`);
354
- }
355
- return check("github-projects", "GitHub Projects status sync", "fail", "enabled but projectId/statusFieldId is incomplete", "Configure github.projects.projectId and github.projects.statusFieldId, or disable github.projects.enabled.");
356
- }
357
- function permissionAllowsPr(payload) {
358
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
359
- return null;
360
- const record = payload;
361
- if (record.canOpenPullRequest === true || record.pullRequests === true || record.push === true || record.maintain === true || record.admin === true)
362
- return true;
363
- if (record.canOpenPullRequest === false || record.pullRequests === false || record.push === false)
364
- return false;
365
- const permissions = record.permissions;
366
- if (permissions && typeof permissions === "object" && !Array.isArray(permissions)) {
367
- const p = permissions;
368
- if (p.push === true || p.maintain === true || p.admin === true)
369
- return true;
370
- if (p.push === false && p.maintain !== true && p.admin !== true)
371
- return false;
372
- }
373
- return null;
374
- }
375
- function labelsReady(payload) {
376
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
377
- return null;
378
- const record = payload;
379
- if (record.ok === true || record.ready === true || record.labelsReady === true)
380
- return true;
381
- if (record.ok === false || record.ready === false || record.labelsReady === false)
382
- return false;
383
- return null;
384
- }
385
- function prMergeCheck(config) {
386
- const pr = config?.pr;
387
- const merge = config?.merge;
388
- if (pr?.mode === "off" || merge?.mode === "off") {
389
- return check("pr-merge", "PR/merge automation", "warn", "automatic PR or merge is disabled", "Set pr.mode and merge.mode to auto for autonomous YOLO runs.");
390
- }
391
- return check("pr-merge", "PR/merge automation", "pass", `pr=${pr?.mode ?? "auto"}, merge=${merge?.mode ?? "auto"}, method=${merge?.method ?? "repo-default"}`);
392
- }
393
- async function runRigDoctorChecks(options) {
394
- const projectRoot = options.projectRoot;
395
- const checks = [];
396
- const which = options.which ?? ((binary) => Bun.which(binary));
397
- const bunVersion = options.bunVersion ?? Bun.version;
398
- const request = options.requestJson ?? ((pathname, init) => requestServerJson({ projectRoot }, pathname, init));
399
- const loadConfig = options.loadConfig ?? loadRigConfigOrNull;
400
- checks.push(check("bun", `bun >= ${MIN_SUPPORTED_BUN_VERSION}`, isSupportedBunVersion(bunVersion) ? "pass" : "fail", `found ${bunVersion}`, `Install Bun ${MIN_SUPPORTED_BUN_VERSION} or newer.`), check("git", "git", which("git") ? "pass" : "fail", which("git") ?? undefined, "Install git and ensure it is on PATH."), check("jq", "jq", which("jq") ? "pass" : "warn", which("jq") ?? undefined, "Install jq (for example `brew install jq`)."));
401
- const loadedConfig = await loadConfig(projectRoot).catch(() => null);
402
- const config = loadedConfig ?? loadFallbackConfig(projectRoot);
403
- const hasConfigFile = ["rig.config.ts", "rig.config.mts", "rig.config.json"].some((name) => existsSync4(resolve4(projectRoot, name)));
404
- checks.push(config ? check("config", "rig.config loadable", "pass") : check("config", "rig.config loadable", hasConfigFile ? "fail" : "fail", hasConfigFile ? "config file exists but failed to load" : "missing rig.config.ts/json", "Run `rig init` or fix the config error."));
405
- const taskSourceKind = config?.taskSource?.kind;
406
- checks.push(taskSourceKind ? check("task-source", "task source configured", "pass", taskSourceKind) : check("task-source", "task source configured", "fail", "missing taskSource", "Configure taskSource in rig.config.ts."));
407
- const repo = readRepoConnection(projectRoot);
408
- checks.push(repo ? check("project-link", "repo selected Rig connection", repo.project ? "pass" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : ""}`, "Run `rig init --yes --repo owner/repo` to link this checkout to a GitHub repo slug.") : check("project-link", "repo selected Rig connection", "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig connect use <alias|local>`."));
409
- const selected = (() => {
410
- try {
411
- return resolveSelectedConnection(projectRoot);
412
- } catch {
413
- return null;
414
- }
415
- })();
416
- checks.push(selected ? check("connection", "selected server connection", "pass", selected.connection.kind === "remote" ? selected.connection.baseUrl : "local auto") : check("connection", "selected server connection", repo ? "fail" : "warn", repo ? "selected alias is missing" : "will auto-start local server", repo ? "Run `rig connect list` and `rig connect use <alias|local>`." : undefined));
417
- let server = null;
418
- try {
419
- server = await (options.resolveServer ?? ensureServerForCli)(projectRoot);
420
- checks.push(check("server", "Rig server reachable", "pass", `${server.connectionKind} ${server.baseUrl}`));
421
- } catch (error) {
422
- checks.push(check("server", "Rig server reachable", "fail", errorMessage(error), "Start the local Rig server or fix the selected remote connection."));
423
- }
424
- if (server || options.requestJson) {
425
- try {
426
- const status = await request("/api/server/status");
427
- checks.push(check("server-status", "server project status", "pass", JSON.stringify(status).slice(0, 180)));
428
- } catch (error) {
429
- checks.push(check("server-status", "server project status", "fail", errorMessage(error), "Run `rig doctor` after the selected server is reachable."));
430
- }
431
- try {
432
- const auth = await request("/api/github/auth/status");
433
- checks.push(isAuthenticated(auth) ? check("github-auth", "GitHub auth", "pass") : check("github-auth", "GitHub auth", "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
434
- } catch (error) {
435
- checks.push(check("github-auth", "GitHub auth", "fail", errorMessage(error), "Authenticate GitHub through Rig and ensure the server exposes auth status."));
436
- }
437
- try {
438
- const permissions = await request("/api/github/repo/permissions");
439
- const allowed = permissionAllowsPr(permissions);
440
- checks.push(allowed === true ? check("github-repo-permissions", "GitHub repo PR permissions", "pass", JSON.stringify(permissions).slice(0, 180)) : allowed === false ? check("github-repo-permissions", "GitHub repo PR permissions", "fail", JSON.stringify(permissions).slice(0, 180), "Grant the selected GitHub token permission to push branches, open PRs, and merge according to repo rules.") : check("github-repo-permissions", "GitHub repo PR permissions", "warn", JSON.stringify(permissions).slice(0, 180), "Confirm the selected token can push branches and open PRs."));
441
- } catch (error) {
442
- checks.push(check("github-repo-permissions", "GitHub repo PR permissions", "warn", errorMessage(error), "Ensure the server exposes repo permission checks and the token can open PRs."));
443
- }
444
- try {
445
- const labels = await request("/api/workspace/task-labels");
446
- const ready = labelsReady(labels);
447
- checks.push(ready === false ? check("task-labels", "GitHub issue labels", "fail", JSON.stringify(labels).slice(0, 180), "Let Rig create required labels or create the configured lifecycle labels manually.") : check("task-labels", "GitHub issue labels", ready === true ? "pass" : "warn", JSON.stringify(labels).slice(0, 180), "Confirm required Rig lifecycle labels exist."));
448
- } catch (error) {
449
- checks.push(check("task-labels", "GitHub issue labels", "warn", errorMessage(error), "Run `rig init`/`rig doctor` after label setup is wired on the server."));
450
- }
451
- try {
452
- const projection = await request("/api/workspace/task-projection");
453
- checks.push(check("task-projection", "task projection", "pass", JSON.stringify(projection).slice(0, 180)));
454
- } catch (error) {
455
- checks.push(check("task-projection", "task projection", "warn", errorMessage(error), "Refresh task projection with `rig task list` or fix the task source."));
456
- }
457
- const slug = projectStatusSlug(projectRoot, config);
458
- if (slug) {
459
- try {
460
- const project = await request(`/api/projects/${encodeURIComponent(slug)}`);
461
- checks.push(check("remote-checkout", "server project checkout", "pass", JSON.stringify(project).slice(0, 180)));
462
- } catch (error) {
463
- checks.push(check("remote-checkout", "server project checkout", "warn", errorMessage(error), "Run `rig init --yes --repo owner/repo` to register/link the server project checkout."));
464
- }
465
- } else {
466
- checks.push(check("remote-checkout", "server project checkout", "warn", "repo slug unknown", "Set project.repo or run `rig init --repo owner/repo`."));
467
- }
468
- }
469
- if (taskSourceKind === "github-issues") {
470
- checks.push(check("gh", "gh CLI fallback", which("gh") ? "pass" : "warn", which("gh") ?? undefined, "Install gh for local/dev GitHub fallback operations."));
471
- }
472
- checks.push(githubProjectsCheck(config));
473
- checks.push(prMergeCheck(config));
474
- const piChecks = await (options.piChecks ?? (() => buildPiSetupChecks()))().catch((error) => [{
475
- ok: false,
476
- label: "pi/pi-rig checks",
477
- hint: errorMessage(error)
478
- }]);
479
- for (const pi of piChecks) {
480
- checks.push(check(pi.label === "pi" ? "pi" : "pi-rig", pi.label, pi.ok ? "pass" : "warn", pi.detail, pi.hint ?? (pi.ok ? undefined : "Run `rig init --yes` to install/update Pi and enable pi-rig.")));
481
- }
482
- return checks;
483
- }
484
- function formatDoctorChecks(checks) {
485
- return checks.map((entry) => {
486
- const prefix = entry.status.toUpperCase();
487
- const detail = entry.detail ? ` \u2014 ${entry.detail}` : "";
488
- const remediation = entry.remediation && entry.status !== "pass" ? ` (${entry.remediation})` : "";
489
- return `${prefix}: ${entry.label}${detail}${remediation}`;
490
- }).join(`
491
- `);
492
- }
493
- function countDoctorFailures(checks) {
494
- return checks.filter((entry) => entry.status === "fail").length;
495
- }
496
- function throwIfDoctorFailed(checks) {
497
- const failures = countDoctorFailures(checks);
498
- if (failures > 0) {
499
- throw new CliError2(`Doctor failed (${failures} failing check${failures === 1 ? "" : "s"}).`, 1);
500
- }
501
- }
502
- export {
503
- throwIfDoctorFailed,
504
- runRigDoctorChecks,
505
- formatDoctorChecks,
506
- countDoctorFailures
507
- };