@h-rig/cli 0.0.6-alpha.66 → 0.0.6-alpha.68

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.
@@ -1,6 +1,6 @@
1
1
  // @bun
2
2
  // packages/cli/src/commands/stats.ts
3
- import pc3 from "picocolors";
3
+ import pc4 from "picocolors";
4
4
 
5
5
  // packages/cli/src/runner.ts
6
6
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
@@ -45,10 +45,310 @@ Usage: ${usage}`);
45
45
  }
46
46
 
47
47
  // packages/cli/src/commands/stats.ts
48
- import {
49
- listAuthorityRuns,
50
- projectRunFromJournal
51
- } from "@rig/runtime/control-plane/authority-files";
48
+ import { computeRigStats } from "@rig/runtime/control-plane/native/run-stats";
49
+
50
+ // packages/cli/src/commands/_connection-state.ts
51
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
52
+ import { homedir } from "os";
53
+ import { dirname, resolve } from "path";
54
+ function resolveGlobalConnectionsPath(env = process.env) {
55
+ const explicit = env.RIG_CONNECTIONS_FILE?.trim();
56
+ if (explicit)
57
+ return resolve(explicit);
58
+ const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
59
+ if (stateDir)
60
+ return resolve(stateDir, "connections.json");
61
+ return resolve(homedir(), ".rig", "connections.json");
62
+ }
63
+ function resolveRepoConnectionPath(projectRoot) {
64
+ return resolve(projectRoot, ".rig", "state", "connection.json");
65
+ }
66
+ function readJsonFile(path) {
67
+ if (!existsSync(path))
68
+ return null;
69
+ try {
70
+ return JSON.parse(readFileSync(path, "utf8"));
71
+ } catch (error) {
72
+ throw new CliError(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1, { hint: "Fix or delete that file, then re-select a server with `rig server use <alias|local>`." });
73
+ }
74
+ }
75
+ function writeJsonFile(path, value) {
76
+ mkdirSync(dirname(path), { recursive: true });
77
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
78
+ `, "utf8");
79
+ }
80
+ function normalizeConnection(value) {
81
+ if (!value || typeof value !== "object" || Array.isArray(value))
82
+ return null;
83
+ const record = value;
84
+ if (record.kind === "local")
85
+ return { kind: "local", mode: "auto" };
86
+ if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
87
+ const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
88
+ return { kind: "remote", baseUrl };
89
+ }
90
+ return null;
91
+ }
92
+ function readGlobalConnections(options = {}) {
93
+ const path = resolveGlobalConnectionsPath(options.env ?? process.env);
94
+ const payload = readJsonFile(path);
95
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
96
+ return { connections: {} };
97
+ }
98
+ const rawConnections = payload.connections;
99
+ const connections = {};
100
+ if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
101
+ for (const [alias, raw] of Object.entries(rawConnections)) {
102
+ const connection = normalizeConnection(raw);
103
+ if (connection)
104
+ connections[alias] = connection;
105
+ }
106
+ }
107
+ return { connections };
108
+ }
109
+ function readRepoConnection(projectRoot) {
110
+ const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
111
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
112
+ return null;
113
+ const record = payload;
114
+ const selected = typeof record.selected === "string" ? record.selected.trim() : "";
115
+ if (!selected)
116
+ return null;
117
+ return {
118
+ selected,
119
+ project: typeof record.project === "string" ? record.project : undefined,
120
+ linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
121
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
122
+ };
123
+ }
124
+ function writeRepoConnection(projectRoot, state) {
125
+ writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
126
+ }
127
+ function resolveSelectedConnection(projectRoot, options = {}) {
128
+ const repo = readRepoConnection(projectRoot);
129
+ if (!repo)
130
+ return null;
131
+ if (repo.selected === "local")
132
+ return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
133
+ const global = readGlobalConnections(options);
134
+ const connection = global.connections[repo.selected];
135
+ if (!connection) {
136
+ throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
137
+ }
138
+ return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
139
+ }
140
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
141
+ const repo = readRepoConnection(projectRoot);
142
+ if (!repo)
143
+ return;
144
+ writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
145
+ }
146
+ function isRemoteConnectionSelected(projectRoot) {
147
+ return resolveSelectedConnection(projectRoot)?.connection.kind === "remote";
148
+ }
149
+
150
+ // packages/cli/src/commands/_server-client.ts
151
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
152
+ import { resolve as resolve2 } from "path";
153
+ import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
154
+ var scopedGitHubBearerTokens = new Map;
155
+ var serverPhaseListener = null;
156
+ function setServerPhaseListener(listener) {
157
+ const previous = serverPhaseListener;
158
+ serverPhaseListener = listener;
159
+ return previous;
160
+ }
161
+ function reportServerPhase(label) {
162
+ serverPhaseListener?.(label);
163
+ }
164
+ function cleanToken(value) {
165
+ const trimmed = value?.trim();
166
+ return trimmed ? trimmed : null;
167
+ }
168
+ function readPrivateRemoteSessionToken(projectRoot) {
169
+ const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
170
+ if (!existsSync2(path))
171
+ return null;
172
+ try {
173
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
174
+ return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
175
+ } catch {
176
+ return null;
177
+ }
178
+ }
179
+ function readGitHubBearerTokenForRemote(projectRoot) {
180
+ const scopedKey = resolve2(projectRoot);
181
+ if (scopedGitHubBearerTokens.has(scopedKey))
182
+ return scopedGitHubBearerTokens.get(scopedKey) ?? null;
183
+ const privateSession = readPrivateRemoteSessionToken(projectRoot);
184
+ if (privateSession)
185
+ return privateSession;
186
+ return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
187
+ }
188
+ function readStoredGitHubAuthToken(projectRoot) {
189
+ const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
190
+ if (!existsSync2(path))
191
+ return null;
192
+ try {
193
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
194
+ return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
195
+ } catch {
196
+ return null;
197
+ }
198
+ }
199
+ function readLocalConnectionFallbackToken(projectRoot) {
200
+ return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
201
+ }
202
+ async function ensureServerForCli(projectRoot) {
203
+ try {
204
+ const selected = resolveSelectedConnection(projectRoot);
205
+ if (selected?.connection.kind === "remote") {
206
+ reportServerPhase(`Connecting to ${selected.alias}\u2026`);
207
+ const authToken = readGitHubBearerTokenForRemote(projectRoot);
208
+ const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
209
+ return {
210
+ baseUrl: selected.connection.baseUrl,
211
+ authToken,
212
+ connectionKind: "remote",
213
+ serverProjectRoot
214
+ };
215
+ }
216
+ reportServerPhase("Starting local Rig server\u2026");
217
+ const connection = await ensureLocalRigServerConnection(projectRoot);
218
+ return {
219
+ baseUrl: connection.baseUrl,
220
+ authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
221
+ connectionKind: "local",
222
+ serverProjectRoot: resolve2(projectRoot)
223
+ };
224
+ } catch (error) {
225
+ if (error instanceof Error) {
226
+ throw new CliError(error.message, 1);
227
+ }
228
+ throw error;
229
+ }
230
+ }
231
+ async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
232
+ const repo = readRepoConnection(projectRoot);
233
+ const slug = repo?.project?.trim();
234
+ if (!slug)
235
+ return null;
236
+ try {
237
+ const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
238
+ headers: mergeHeaders(undefined, authToken)
239
+ });
240
+ if (!response.ok)
241
+ return null;
242
+ const payload = await response.json();
243
+ const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
244
+ const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
245
+ const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
246
+ const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
247
+ if (path)
248
+ writeRepoServerProjectRoot(projectRoot, path);
249
+ return path;
250
+ } catch {
251
+ return null;
252
+ }
253
+ }
254
+ function mergeHeaders(headers, authToken) {
255
+ const merged = new Headers(headers);
256
+ if (authToken) {
257
+ merged.set("authorization", `Bearer ${authToken}`);
258
+ }
259
+ return merged;
260
+ }
261
+ function diagnosticMessage(payload) {
262
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
263
+ return null;
264
+ const record = payload;
265
+ const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
266
+ const messages = diagnostics.flatMap((entry) => {
267
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
268
+ return [];
269
+ const diagnostic = entry;
270
+ const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
271
+ const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
272
+ return message ? [`${kind}: ${message}`] : [];
273
+ });
274
+ return messages.length > 0 ? messages.join("; ") : null;
275
+ }
276
+ var serverReachabilityCache = new Map;
277
+ async function probeServerReachability(baseUrl, authToken) {
278
+ try {
279
+ const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
280
+ headers: mergeHeaders(undefined, authToken),
281
+ signal: AbortSignal.timeout(1500)
282
+ });
283
+ return response.ok;
284
+ } catch {
285
+ return false;
286
+ }
287
+ }
288
+ function cachedServerReachability(projectRoot, baseUrl, authToken) {
289
+ const key = resolve2(projectRoot);
290
+ const cached = serverReachabilityCache.get(key);
291
+ if (cached)
292
+ return cached;
293
+ const probe = probeServerReachability(baseUrl, authToken);
294
+ serverReachabilityCache.set(key, probe);
295
+ return probe;
296
+ }
297
+ function describeSelectedServer(projectRoot, server) {
298
+ try {
299
+ const selected = resolveSelectedConnection(projectRoot);
300
+ if (selected) {
301
+ return {
302
+ alias: selected.alias,
303
+ target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
304
+ };
305
+ }
306
+ } catch {}
307
+ return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
308
+ }
309
+ async function buildServerFailureContext(projectRoot, server) {
310
+ const { alias, target } = describeSelectedServer(projectRoot, server);
311
+ const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
312
+ const reachability = reachable ? "server is reachable" : "server is unreachable";
313
+ return {
314
+ contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
315
+ hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
316
+ };
317
+ }
318
+ async function requestServerJson(context, pathname, init = {}) {
319
+ const server = await ensureServerForCli(context.projectRoot);
320
+ const headers = mergeHeaders(init.headers, server.authToken);
321
+ if (server.serverProjectRoot)
322
+ headers.set("x-rig-project-root", server.serverProjectRoot);
323
+ reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
324
+ let response;
325
+ try {
326
+ response = await fetch(`${server.baseUrl}${pathname}`, {
327
+ ...init,
328
+ headers
329
+ });
330
+ } catch (error) {
331
+ const failure = await buildServerFailureContext(context.projectRoot, server);
332
+ throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
333
+ ${failure.contextLine}`, 1, { hint: failure.hint });
334
+ }
335
+ const text = await response.text();
336
+ const payload = text.trim().length > 0 ? (() => {
337
+ try {
338
+ return JSON.parse(text);
339
+ } catch {
340
+ return null;
341
+ }
342
+ })() : null;
343
+ if (!response.ok) {
344
+ const diagnostics = diagnosticMessage(payload);
345
+ const detail = diagnostics ?? (text || response.statusText);
346
+ const failure = await buildServerFailureContext(context.projectRoot, server);
347
+ throw new CliError(`Rig server request failed (${response.status}): ${detail}
348
+ ${failure.contextLine}`, 1, { hint: failure.hint });
349
+ }
350
+ return payload;
351
+ }
52
352
 
53
353
  // packages/cli/src/commands/_cli-format.ts
54
354
  import { log, note } from "@clack/prompts";
@@ -75,9 +375,130 @@ function formatNextSteps(steps) {
75
375
  return [pc.bold("Next"), ...steps.map((step) => `${pc.dim("\u203A")} ${step}`)];
76
376
  }
77
377
 
378
+ // packages/cli/src/commands/_async-ui.ts
379
+ import pc2 from "picocolors";
380
+
381
+ // packages/cli/src/commands/_spinner.ts
382
+ var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
383
+ function createTtySpinner(input) {
384
+ const output = input.output ?? process.stdout;
385
+ const isTty = output.isTTY === true;
386
+ const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
387
+ let label = input.label;
388
+ let frame = 0;
389
+ let paused = false;
390
+ let stopped = false;
391
+ let lastPrintedLabel = "";
392
+ const render = () => {
393
+ if (stopped || paused)
394
+ return;
395
+ if (!isTty) {
396
+ if (label !== lastPrintedLabel) {
397
+ output.write(`${label}
398
+ `);
399
+ lastPrintedLabel = label;
400
+ }
401
+ return;
402
+ }
403
+ frame = (frame + 1) % frames.length;
404
+ const glyph = frames[frame] ?? frames[0] ?? "";
405
+ output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
406
+ };
407
+ const clearLine = () => {
408
+ if (isTty)
409
+ output.write("\r\x1B[2K");
410
+ };
411
+ render();
412
+ const timer = isTty ? setInterval(render, input.intervalMs ?? 120) : null;
413
+ return {
414
+ setLabel(next) {
415
+ label = next;
416
+ render();
417
+ },
418
+ pause() {
419
+ paused = true;
420
+ clearLine();
421
+ },
422
+ resume() {
423
+ if (stopped)
424
+ return;
425
+ paused = false;
426
+ render();
427
+ },
428
+ stop(finalLine) {
429
+ if (stopped)
430
+ return;
431
+ stopped = true;
432
+ if (timer)
433
+ clearInterval(timer);
434
+ clearLine();
435
+ if (finalLine)
436
+ output.write(`${finalLine}
437
+ `);
438
+ }
439
+ };
440
+ }
441
+
442
+ // packages/cli/src/commands/_async-ui.ts
443
+ var CLACK_SPINNER_FRAMES = ["\u25D2", "\u25D0", "\u25D3", "\u25D1"];
444
+ var DONE_SYMBOL = pc2.green("\u25C7");
445
+ var FAIL_SYMBOL = pc2.red("\u25A0");
446
+ var activeUpdate = null;
447
+ async function withSpinner(label, work, options = {}) {
448
+ if (options.outputMode === "json") {
449
+ return work(() => {});
450
+ }
451
+ if (activeUpdate) {
452
+ const outer = activeUpdate;
453
+ outer(label);
454
+ return work(outer);
455
+ }
456
+ const output = options.output ?? process.stderr;
457
+ const isTty = output.isTTY === true;
458
+ let lastLabel = label;
459
+ if (!isTty) {
460
+ output.write(`${label}
461
+ `);
462
+ const update2 = (next) => {
463
+ lastLabel = next;
464
+ };
465
+ activeUpdate = update2;
466
+ const previousListener2 = setServerPhaseListener(update2);
467
+ try {
468
+ return await work(update2);
469
+ } finally {
470
+ activeUpdate = null;
471
+ setServerPhaseListener(previousListener2);
472
+ }
473
+ }
474
+ const spinner = createTtySpinner({
475
+ label,
476
+ output,
477
+ frames: CLACK_SPINNER_FRAMES,
478
+ styleFrame: (frame) => pc2.magenta(frame)
479
+ });
480
+ const update = (next) => {
481
+ lastLabel = next;
482
+ spinner.setLabel(next);
483
+ };
484
+ activeUpdate = update;
485
+ const previousListener = setServerPhaseListener(update);
486
+ try {
487
+ const result = await work(update);
488
+ spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
489
+ return result;
490
+ } catch (error) {
491
+ spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
492
+ throw error;
493
+ } finally {
494
+ activeUpdate = null;
495
+ setServerPhaseListener(previousListener);
496
+ }
497
+ }
498
+
78
499
  // packages/cli/src/commands/_help-catalog.ts
79
500
  import { intro, log as log2, note as note2, outro } from "@clack/prompts";
80
- import pc2 from "picocolors";
501
+ import pc3 from "picocolors";
81
502
  var TOP_LEVEL_SECTIONS = [
82
503
  {
83
504
  title: "Start here",
@@ -359,13 +780,13 @@ var ADVANCED_GROUPS = [
359
780
  ];
360
781
  var ALL_GROUPS = [...PRIMARY_GROUPS, ...ADVANCED_GROUPS];
361
782
  function heading(title) {
362
- return pc2.bold(pc2.cyan(title));
783
+ return pc3.bold(pc3.cyan(title));
363
784
  }
364
785
  function renderRigBanner(version) {
365
- const m = (s) => pc2.bold(pc2.magenta(s));
366
- const c = (s) => pc2.bold(pc2.cyan(s));
367
- const y = (s) => pc2.yellow(s);
368
- const d = (s) => pc2.dim(s);
786
+ const m = (s) => pc3.bold(pc3.magenta(s));
787
+ const c = (s) => pc3.bold(pc3.cyan(s));
788
+ const y = (s) => pc3.yellow(s);
789
+ const d = (s) => pc3.dim(s);
369
790
  const lines = [
370
791
  m(" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 ") + d(" \u2591\u2592\u2593\u2588 "),
371
792
  m(" \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D ") + d("\u2593\u2592\u2591"),
@@ -374,7 +795,7 @@ function renderRigBanner(version) {
374
795
  y(" \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D") + d(" \u2592\u2591"),
375
796
  y(" \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D "),
376
797
  "",
377
- ` ${c("\u25E2\u25E4")} ${pc2.bold("the control rig for autonomous coding agents")} ${m("//")} ${d("you are the operator")}`,
798
+ ` ${c("\u25E2\u25E4")} ${pc3.bold("the control rig for autonomous coding agents")} ${m("//")} ${d("you are the operator")}`,
378
799
  version ? ` ${d(`v${version} \xB7 jack in: rig task run --next`)}` : ` ${d("jack in: rig task run --next")}`
379
800
  ];
380
801
  return lines.join(`
@@ -382,7 +803,7 @@ function renderRigBanner(version) {
382
803
  }
383
804
  function commandLine(command, description) {
384
805
  const commandColumn = command.length >= 38 ? `${command} ` : command.padEnd(38);
385
- return `${pc2.dim("\u2502")} ${pc2.bold(commandColumn)} ${description}`;
806
+ return `${pc3.dim("\u2502")} ${pc3.bold(commandColumn)} ${description}`;
386
807
  }
387
808
  function renderCommandBlock(commands) {
388
809
  return commands.map((entry) => commandLine(entry.command, entry.description)).join(`
@@ -392,37 +813,37 @@ function renderGroup(group) {
392
813
  const lines = [
393
814
  `${heading(`rig ${group.name}`)} \u2014 ${group.summary}`,
394
815
  "",
395
- pc2.bold("Usage"),
816
+ pc3.bold("Usage"),
396
817
  ...group.usage.map((line) => ` ${line}`),
397
818
  "",
398
- pc2.bold("Commands"),
819
+ pc3.bold("Commands"),
399
820
  ...group.commands.map((entry) => commandLine(entry.command, entry.description))
400
821
  ];
401
822
  if (group.examples?.length) {
402
- lines.push("", pc2.bold("Examples"), ...group.examples.map((line) => ` ${pc2.dim("$")} ${line}`));
823
+ lines.push("", pc3.bold("Examples"), ...group.examples.map((line) => ` ${pc3.dim("$")} ${line}`));
403
824
  }
404
825
  if (group.next?.length) {
405
- lines.push("", pc2.bold("Next steps"), ...group.next.map((line) => ` ${pc2.dim("\u203A")} ${line}`));
826
+ lines.push("", pc3.bold("Next steps"), ...group.next.map((line) => ` ${pc3.dim("\u203A")} ${line}`));
406
827
  }
407
828
  if (group.advanced?.length) {
408
- lines.push("", pc2.bold("Compatibility / advanced"), ...group.advanced.map((line) => ` ${pc2.dim("\u203A")} ${line}`));
829
+ lines.push("", pc3.bold("Compatibility / advanced"), ...group.advanced.map((line) => ` ${pc3.dim("\u203A")} ${line}`));
409
830
  }
410
831
  return lines.join(`
411
832
  `);
412
833
  }
413
834
  function renderTopLevelHelp() {
414
835
  return [
415
- `${heading("rig")} ${pc2.dim("\u2014 server-owned task/run control plane for Pi-backed engineering work")}`,
416
- pc2.dim("Current path: select a server, choose a task, submit a run, attach with native Pi, clear inbox gates."),
836
+ `${heading("rig")} ${pc3.dim("\u2014 server-owned task/run control plane for Pi-backed engineering work")}`,
837
+ pc3.dim("Current path: select a server, choose a task, submit a run, attach with native Pi, clear inbox gates."),
417
838
  "",
418
839
  ...TOP_LEVEL_SECTIONS.flatMap((section) => [
419
- `${pc2.bold(pc2.magenta(`\u25C7 ${section.title}`))} \u2014 ${pc2.dim(section.subtitle)}`,
840
+ `${pc3.bold(pc3.magenta(`\u25C7 ${section.title}`))} \u2014 ${pc3.dim(section.subtitle)}`,
420
841
  renderCommandBlock(section.commands),
421
842
  ""
422
843
  ]),
423
- pc2.dim("More: `rig help --advanced` for dev/compatibility commands; `rig <group> --help` for rich per-group help; `rig --version` for the installed version."),
844
+ pc3.dim("More: `rig help --advanced` for dev/compatibility commands; `rig <group> --help` for rich per-group help; `rig --version` for the installed version."),
424
845
  "",
425
- pc2.bold("Global options"),
846
+ pc3.bold("Global options"),
426
847
  commandLine("--project <path>", "Use a project root instead of auto-discovery."),
427
848
  commandLine("--json", "Emit structured output for scripts/agents."),
428
849
  commandLine("--dry-run", "Print the command plan without mutating state.")
@@ -512,90 +933,6 @@ function parseSinceOption(value, now = new Date) {
512
933
  }
513
934
  return new Date(parsed);
514
935
  }
515
- function median(values) {
516
- if (values.length === 0)
517
- return null;
518
- const sorted = [...values].sort((left, right) => left - right);
519
- const middle = Math.floor(sorted.length / 2);
520
- const upper = sorted[middle];
521
- if (sorted.length % 2 === 1)
522
- return upper;
523
- return (sorted[middle - 1] + upper) / 2;
524
- }
525
- function rate(part, total) {
526
- if (total === 0)
527
- return null;
528
- return part / total;
529
- }
530
- function parseTimestamp(value) {
531
- if (!value)
532
- return null;
533
- const parsed = Date.parse(value);
534
- return Number.isFinite(parsed) ? parsed : null;
535
- }
536
- function computeRigStats(projectRoot, options = {}) {
537
- const since = options.since ?? null;
538
- const sinceMs = since ? since.getTime() : null;
539
- const runs = listAuthorityRuns(projectRoot).filter((run) => {
540
- if (sinceMs === null)
541
- return true;
542
- const createdAt = parseTimestamp(run.createdAt) ?? parseTimestamp(run.updatedAt);
543
- return createdAt !== null && createdAt >= sinceMs;
544
- });
545
- const statusCounts = {};
546
- const completionDurations = [];
547
- let steeringTotal = 0;
548
- let stallTotal = 0;
549
- let approvalsApproved = 0;
550
- let approvalsRejected = 0;
551
- let approvalsPending = 0;
552
- for (const run of runs) {
553
- const status = run.status ?? "unknown";
554
- statusCounts[status] = (statusCounts[status] ?? 0) + 1;
555
- if (status === "completed") {
556
- const createdAt = parseTimestamp(run.createdAt);
557
- const completedAt = parseTimestamp(run.completedAt);
558
- if (createdAt !== null && completedAt !== null && completedAt >= createdAt) {
559
- completionDurations.push(completedAt - createdAt);
560
- }
561
- }
562
- const projection = projectRunFromJournal(projectRoot, run.runId);
563
- if (!projection)
564
- continue;
565
- steeringTotal += projection.steeringCount;
566
- stallTotal += projection.stallCount;
567
- approvalsPending += projection.pendingApprovals.length;
568
- for (const resolved of projection.resolvedApprovals) {
569
- if (resolved.decision === "approve")
570
- approvalsApproved += 1;
571
- else
572
- approvalsRejected += 1;
573
- }
574
- }
575
- const totalRuns = runs.length;
576
- const completedRuns = statusCounts["completed"] ?? 0;
577
- const failedRuns = statusCounts["failed"] ?? 0;
578
- const needsAttentionRuns = statusCounts["needs-attention"] ?? 0;
579
- return {
580
- since: since ? since.toISOString() : null,
581
- totalRuns,
582
- statusCounts,
583
- completedRuns,
584
- failedRuns,
585
- needsAttentionRuns,
586
- completionRate: rate(completedRuns, totalRuns),
587
- failureRate: rate(failedRuns, totalRuns),
588
- needsAttentionRate: rate(needsAttentionRuns, totalRuns),
589
- medianCompletionMs: median(completionDurations),
590
- steeringTotal,
591
- steeringPerRun: totalRuns === 0 ? null : steeringTotal / totalRuns,
592
- stallTotal,
593
- approvalsRequested: approvalsApproved + approvalsRejected + approvalsPending,
594
- approvalsApproved,
595
- approvalsRejected,
596
- approvalsPending
597
- };
598
- }
599
936
  function formatPercent(value) {
600
937
  if (value === null)
601
938
  return "\u2014";
@@ -630,11 +967,11 @@ function formatStatsReport(stats) {
630
967
  const keyWidth = Math.max(...rows.map(([key]) => key.length));
631
968
  const lines = [
632
969
  formatSection("Fleet stats", window),
633
- ...rows.map(([key, value]) => `${pc3.dim("\u2502")} ${pc3.dim(key.padEnd(keyWidth + 2))} ${value}`)
970
+ ...rows.map(([key, value]) => `${pc4.dim("\u2502")} ${pc4.dim(key.padEnd(keyWidth + 2))} ${value}`)
634
971
  ];
635
972
  const otherStatuses = Object.entries(stats.statusCounts).filter(([status]) => !["completed", "failed", "needs-attention"].includes(status)).sort(([, left], [, right]) => right - left);
636
973
  if (otherStatuses.length > 0) {
637
- lines.push(`${pc3.dim("\u2502")} ${pc3.dim("other".padEnd(keyWidth + 2))} ${otherStatuses.map(([status, count]) => `${status}:${count}`).join(" ")}`);
974
+ lines.push(`${pc4.dim("\u2502")} ${pc4.dim("other".padEnd(keyWidth + 2))} ${otherStatuses.map(([status, count]) => `${status}:${count}`).join(" ")}`);
638
975
  }
639
976
  lines.push("", ...formatNextSteps([
640
977
  "Inspect a run: `rig run list` then `rig run show <run-id>`",
@@ -653,7 +990,8 @@ async function executeStats(context, args) {
653
990
  const sinceResult = takeOption(pending, "--since");
654
991
  requireNoExtraArgs(sinceResult.rest, "rig stats [show] [--since <7d|30d|ISO date>]");
655
992
  const since = parseSinceOption(sinceResult.value);
656
- const stats = computeRigStats(context.projectRoot, { since });
993
+ const remoteStats = isRemoteConnectionSelected(context.projectRoot);
994
+ const stats = await withSpinner(remoteStats ? "Computing fleet stats on the server\u2026" : "Scanning local run state\u2026", async () => remoteStats ? await requestServerJson(context, `/api/stats${since ? `?since=${encodeURIComponent(since.toISOString())}` : ""}`) : computeRigStats(context.projectRoot, { since }), { outputMode: context.outputMode });
657
995
  if (context.outputMode === "text") {
658
996
  printFormattedOutput(formatStatsReport(stats));
659
997
  }
@@ -543,6 +543,10 @@ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
543
543
 
544
544
  // packages/cli/src/commands/_server-client.ts
545
545
  var scopedGitHubBearerTokens = new Map;
546
+ var serverPhaseListener = null;
547
+ function reportServerPhase(label) {
548
+ serverPhaseListener?.(label);
549
+ }
546
550
  function cleanToken(value) {
547
551
  const trimmed = value?.trim();
548
552
  return trimmed ? trimmed : null;
@@ -585,6 +589,7 @@ async function ensureServerForCli(projectRoot) {
585
589
  try {
586
590
  const selected = resolveSelectedConnection(projectRoot);
587
591
  if (selected?.connection.kind === "remote") {
592
+ reportServerPhase(`Connecting to ${selected.alias}\u2026`);
588
593
  const authToken = readGitHubBearerTokenForRemote(projectRoot);
589
594
  const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
590
595
  return {
@@ -594,6 +599,7 @@ async function ensureServerForCli(projectRoot) {
594
599
  serverProjectRoot
595
600
  };
596
601
  }
602
+ reportServerPhase("Starting local Rig server\u2026");
597
603
  const connection = await ensureLocalRigServerConnection(projectRoot);
598
604
  return {
599
605
  baseUrl: connection.baseUrl,
@@ -700,6 +706,7 @@ async function requestServerJson(context, pathname, init = {}) {
700
706
  const headers = mergeHeaders(init.headers, server.authToken);
701
707
  if (server.serverProjectRoot)
702
708
  headers.set("x-rig-project-root", server.serverProjectRoot);
709
+ reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
703
710
  let response;
704
711
  try {
705
712
  response = await fetch(`${server.baseUrl}${pathname}`, {