@h-rig/cli 0.0.6-alpha.64 → 0.0.6-alpha.65

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 (46) hide show
  1. package/dist/bin/rig.js +1349 -1599
  2. package/dist/src/commands/_connection-state.js +14 -5
  3. package/dist/src/commands/_doctor-checks.js +71 -11
  4. package/dist/src/commands/_help-catalog.js +99 -60
  5. package/dist/src/commands/_json-output.js +56 -0
  6. package/dist/src/commands/_operator-view.js +97 -784
  7. package/dist/src/commands/_parsers.js +18 -9
  8. package/dist/src/commands/_pi-frontend.js +96 -788
  9. package/dist/src/commands/_policy.js +12 -3
  10. package/dist/src/commands/_preflight.js +73 -13
  11. package/dist/src/commands/_run-driver-helpers.js +31 -5
  12. package/dist/src/commands/_run-replay.js +2 -2
  13. package/dist/src/commands/_server-client.js +76 -16
  14. package/dist/src/commands/_snapshot-upload.js +70 -10
  15. package/dist/src/commands/agent.js +21 -11
  16. package/dist/src/commands/browser.js +24 -15
  17. package/dist/src/commands/connect.js +22 -17
  18. package/dist/src/commands/dist.js +15 -6
  19. package/dist/src/commands/doctor.js +70 -10
  20. package/dist/src/commands/github.js +79 -19
  21. package/dist/src/commands/inbox.js +215 -131
  22. package/dist/src/commands/init.js +202 -35
  23. package/dist/src/commands/inspect.js +77 -17
  24. package/dist/src/commands/inspector.js +18 -9
  25. package/dist/src/commands/pi.js +18 -9
  26. package/dist/src/commands/plugin.js +19 -10
  27. package/dist/src/commands/profile-and-review.js +22 -13
  28. package/dist/src/commands/queue.js +19 -9
  29. package/dist/src/commands/remote.js +25 -16
  30. package/dist/src/commands/repo-git-harness.js +18 -9
  31. package/dist/src/commands/run.js +158 -805
  32. package/dist/src/commands/server.js +85 -25
  33. package/dist/src/commands/setup.js +73 -13
  34. package/dist/src/commands/stats.js +681 -0
  35. package/dist/src/commands/task-report-bug.js +24 -15
  36. package/dist/src/commands/task-run-driver.js +121 -49
  37. package/dist/src/commands/task.js +254 -893
  38. package/dist/src/commands/test.js +12 -3
  39. package/dist/src/commands/workspace.js +14 -5
  40. package/dist/src/commands.js +1339 -1650
  41. package/dist/src/index.js +1349 -1599
  42. package/dist/src/launcher.js +72 -10
  43. package/dist/src/runner.js +14 -5
  44. package/package.json +10 -7
  45. package/dist/src/commands/_pi-remote-session.js +0 -771
  46. package/dist/src/commands/_pi-worker-bridge-extension.js +0 -834
@@ -0,0 +1,681 @@
1
+ // @bun
2
+ // packages/cli/src/commands/stats.ts
3
+ import pc3 from "picocolors";
4
+
5
+ // packages/cli/src/runner.ts
6
+ import { EventBus } from "@rig/runtime/control-plane/runtime/events";
7
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
8
+ import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
9
+ import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
10
+
11
+ class CliError extends RuntimeCliError {
12
+ hint;
13
+ constructor(message, exitCode = 1, options = {}) {
14
+ super(message, exitCode);
15
+ if (options.hint?.trim()) {
16
+ this.hint = options.hint.trim();
17
+ }
18
+ }
19
+ }
20
+ function takeOption(args, option) {
21
+ const rest = [];
22
+ let value;
23
+ for (let index = 0;index < args.length; index += 1) {
24
+ const current = args[index];
25
+ if (current === option) {
26
+ const next = args[index + 1];
27
+ if (!next || next.startsWith("-")) {
28
+ throw new CliError(`Missing value for ${option}`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} <value>\`.` });
29
+ }
30
+ value = next;
31
+ index += 1;
32
+ continue;
33
+ }
34
+ if (current !== undefined) {
35
+ rest.push(current);
36
+ }
37
+ }
38
+ return { value, rest };
39
+ }
40
+ function requireNoExtraArgs(args, usage) {
41
+ if (args.length > 0) {
42
+ throw new CliError(`Unexpected arguments: ${args.join(" ")}
43
+ Usage: ${usage}`);
44
+ }
45
+ }
46
+
47
+ // packages/cli/src/commands/stats.ts
48
+ import {
49
+ listAuthorityRuns,
50
+ projectRunFromJournal
51
+ } from "@rig/runtime/control-plane/authority-files";
52
+
53
+ // packages/cli/src/commands/_cli-format.ts
54
+ import { log, note } from "@clack/prompts";
55
+ import pc from "picocolors";
56
+ function shouldUseClackOutput() {
57
+ return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
58
+ }
59
+ function printFormattedOutput(message, options = {}) {
60
+ if (!shouldUseClackOutput()) {
61
+ console.log(message);
62
+ return;
63
+ }
64
+ if (options.title)
65
+ note(message, options.title);
66
+ else
67
+ log.message(message);
68
+ }
69
+ function formatSection(title, subtitle) {
70
+ return `${pc.bold(pc.cyan("\u25C6"))} ${pc.bold(title)}${subtitle ? pc.dim(` \u2014 ${subtitle}`) : ""}`;
71
+ }
72
+ function formatNextSteps(steps) {
73
+ if (steps.length === 0)
74
+ return [];
75
+ return [pc.bold("Next"), ...steps.map((step) => `${pc.dim("\u203A")} ${step}`)];
76
+ }
77
+
78
+ // packages/cli/src/commands/_help-catalog.ts
79
+ import { intro, log as log2, note as note2, outro } from "@clack/prompts";
80
+ import pc2 from "picocolors";
81
+ var TOP_LEVEL_SECTIONS = [
82
+ {
83
+ title: "Start here",
84
+ subtitle: "one-time setup, pick a server",
85
+ commands: [
86
+ { command: "rig init", description: "Wizard: config, GitHub auth, task source, server, Pi wiring." },
87
+ { command: "rig server use <alias|local>", description: "Pick which Rig server owns this repo (`rig server list` to see them)." },
88
+ { command: "rig server status", description: "Show the selected server for this repo." }
89
+ ]
90
+ },
91
+ {
92
+ title: "Work",
93
+ subtitle: "find a task, put an agent on it, answer what it asks",
94
+ commands: [
95
+ { command: "rig task list", description: "What's on the board (from the selected source/server)." },
96
+ { command: "rig task run --next", description: "Dispatch an agent; interactive mode opens the native Pi session." },
97
+ { command: "rig run status", description: "Active and recent runs at a glance." },
98
+ { command: "rig run attach <id> --follow", description: "Join the live Pi session (worker keeps running if you /detach)." },
99
+ { command: "rig inbox approvals", description: "Approvals workers are waiting on (then `rig inbox approve \u2026`)." }
100
+ ]
101
+ },
102
+ {
103
+ title: "Watch",
104
+ subtitle: "fleet metrics and per-task forensics",
105
+ commands: [
106
+ { command: "rig stats [--since 7d]", description: "Fleet metrics: completion/failure rates, median run time, steering, stalls." },
107
+ { command: "rig inspect logs --task <id>", description: "Latest run log for a task." },
108
+ { command: "rig inspect diff --task <id>", description: "Changed files for a task." }
109
+ ]
110
+ },
111
+ {
112
+ title: "Unblock",
113
+ subtitle: "diagnose wiring, fix auth",
114
+ commands: [
115
+ { command: "rig doctor", description: "Check every part of the wiring \u2014 run this when anything feels off." },
116
+ { command: "rig github auth status", description: "GitHub auth state on the selected server." }
117
+ ]
118
+ },
119
+ {
120
+ title: "Extend",
121
+ subtitle: "plugins contribute validators, hooks, task sources, commands",
122
+ commands: [
123
+ { command: "rig plugin list", description: "What the rig.config.ts plugins contribute." },
124
+ { command: "rig plugin run <command-id>", description: "Execute a plugin-contributed CLI command." }
125
+ ]
126
+ }
127
+ ];
128
+ var PRIMARY_GROUPS = [
129
+ {
130
+ name: "server",
131
+ summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
132
+ usage: ["rig server <status|list|add|use|start> [options]"],
133
+ commands: [
134
+ { command: "status", description: "Show the selected server for this repo.", primary: true },
135
+ { command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
136
+ { command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
137
+ { command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
138
+ { command: "list", description: "List saved local/remote server aliases.", primary: true },
139
+ { command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
140
+ ],
141
+ examples: [
142
+ "rig server status",
143
+ "rig server add prod https://where.rig-does.work",
144
+ "rig server use prod",
145
+ "rig server use local",
146
+ "rig server start --port 3773"
147
+ ],
148
+ next: ["Use `rig task list` to see server-owned work.", "Use `rig run list` or `rig run attach <id> --follow` to monitor runs."]
149
+ },
150
+ {
151
+ name: "task",
152
+ summary: "Find work, start Pi-backed runs, and validate task results.",
153
+ usage: ["rig task <list|next|show|run> [options]"],
154
+ commands: [
155
+ { command: "list [--assignee <login|me|@me>] [--state open|closed]", description: "List tasks from the selected server/source.", primary: true },
156
+ { command: "next [filters]", description: "Render the next matching task as a selected-task card.", primary: true },
157
+ { command: "show <id>|--task <id> [--raw]", description: "Show a human task summary; --raw prints the full payload.", primary: true },
158
+ { command: "run [#<issue>|<task-id>|--next|--task <id>]", description: "Submit a task run; interactive follows with bundled Pi.", primary: true },
159
+ { command: "validate|verify [--task <id>]", description: "Run configured task checks/review gates." },
160
+ { command: "details --task <id>", description: "Show full task info from the configured source." },
161
+ { command: "reopen [--task <id> | --all] [--reason <text>]", description: "Reopen closed task(s) in the configured source." },
162
+ { command: "artifacts|artifact-dir|artifact-write", description: "Inspect or write task artifacts." },
163
+ { command: "report-bug", description: "Create a structured bug report/task." }
164
+ ],
165
+ examples: [
166
+ "rig task list --assignee @me --limit 20",
167
+ "rig task next",
168
+ "rig task show 123 --raw",
169
+ "rig task run --next",
170
+ "rig task run #123 --runtime-adapter pi",
171
+ "rig task run --title 'Investigate deploy drift' --initial-prompt 'Check server health'"
172
+ ],
173
+ next: ["Use `--detach` to submit without attaching.", "Use `rig run attach <run-id> --follow` to rejoin a live run."]
174
+ },
175
+ {
176
+ name: "run",
177
+ summary: "Observe, attach to, and control Rig runs.",
178
+ usage: ["rig run <list|status|show|attach|stop> [options]"],
179
+ commands: [
180
+ { command: "list", description: "List recent runs from the selected server or local state.", primary: true },
181
+ { command: "status", description: "Render active and recent run groups.", primary: true },
182
+ { command: "show <id>|--run <id> [--raw]", description: "Show a human run summary; --raw prints the full payload.", primary: true },
183
+ { command: "attach <run-id>|--run <id> [--follow]", description: "Attach to the run; --follow opens the enriched bundled Pi (worker brain).", primary: true },
184
+ { command: "stop [<run-id>|--run <id>]", description: "Request stop for one run or local active runs.", primary: true },
185
+ { command: "steer <run-id> --message <text>", description: "Queue a steering message into a live worker without attaching." },
186
+ { command: "timeline --run <id> [--follow]", description: "Stream raw run timeline events." },
187
+ { command: "replay <run-id>|--run <id> [--with-session]", description: "Print the run's consolidated run.jsonl as a merged timeline; --with-session interleaves the Pi session log." },
188
+ { command: "resume", description: "Resume the most recent interrupted local run." },
189
+ { command: "restart", description: "Restart the most recent local run from a clean runtime." },
190
+ { command: "delete|cleanup", description: "Remove completed run records/artifacts." }
191
+ ],
192
+ examples: [
193
+ "rig run list",
194
+ "rig run status",
195
+ "rig run show <run-id>",
196
+ "rig run attach <run-id> --follow",
197
+ "rig run stop <run-id>"
198
+ ],
199
+ next: ["Use `rig task run --next` to create a new run.", "Use `--json` when scripts need the full structured record."]
200
+ },
201
+ {
202
+ name: "inbox",
203
+ summary: "Review approval and user-input requests that block worker runs.",
204
+ usage: ["rig inbox <approvals|approve|inputs|respond> [options]"],
205
+ commands: [
206
+ { command: "approvals [--run <id>] [--task <id>]", description: "List pending approvals.", primary: true },
207
+ { command: "inputs [--run <id>] [--task <id>]", description: "List pending user-input requests.", primary: true },
208
+ { command: "approve --run <id> --request <id> --decision approve|reject", description: "Resolve an approval request." },
209
+ { command: "respond --run <id> --request <id> --answer key=value", description: "Answer a user-input request." }
210
+ ],
211
+ examples: [
212
+ "rig inbox approvals",
213
+ "rig inbox inputs --run <run-id>",
214
+ "rig inbox approve --run <run-id> --request <request-id> --decision approve"
215
+ ],
216
+ next: ["Rejoin the run after resolving a block: `rig run attach <run-id> --follow`."]
217
+ },
218
+ {
219
+ name: "stats",
220
+ summary: "Fleet metrics computed from on-disk run journals (no server required).",
221
+ usage: ["rig stats [show] [--since <7d|30d|ISO date>]"],
222
+ commands: [
223
+ { command: "show [--since <window>]", description: "Total runs, completion/failure/needs-attention rates, median run time, steering, stalls, approvals.", primary: true }
224
+ ],
225
+ examples: [
226
+ "rig stats",
227
+ "rig stats --since 7d",
228
+ "rig stats --since 2026-06-01 --json"
229
+ ],
230
+ next: ["Inspect outliers with `rig run list` and `rig run show <run-id>`.", "Use `--json` for the schema'd envelope (see docs/cli-json.md)."]
231
+ },
232
+ {
233
+ name: "inspect",
234
+ summary: "Inspect logs, artifacts, graphs, failures for a task.",
235
+ usage: ["rig inspect <logs|artifacts|failures|graph|audit|diff> --task <id>"],
236
+ commands: [
237
+ { command: "logs --task <id>", description: "Latest run log for a task (local or selected server).", primary: true },
238
+ { command: "artifacts --task <id>", description: "List the task's completion artifacts.", primary: true },
239
+ { command: "failures --task <id>", description: "Recorded failures for a task.", primary: true },
240
+ { command: "diff --task <id>", description: "Changed files for a task.", primary: true },
241
+ { command: "graph", description: "Task dependency graph." },
242
+ { command: "audit", description: "Controlled-command audit trail." }
243
+ ],
244
+ examples: ["rig inspect logs --task <id>", "rig inspect diff --task <id>"],
245
+ next: ["Use `rig stats` for fleet-level metrics across runs."]
246
+ },
247
+ {
248
+ name: "repo",
249
+ summary: "Repository sync/baseline helpers for the Rig-managed checkout.",
250
+ usage: ["rig repo <sync|reset-baseline>"],
251
+ commands: [
252
+ { command: "sync", description: "Sync project repository state.", primary: true },
253
+ { command: "reset-baseline", description: "Reset the managed baseline for the repo." }
254
+ ],
255
+ examples: ["rig repo sync"]
256
+ },
257
+ {
258
+ name: "plugin",
259
+ summary: "Plugin listing, validation, and plugin-contributed commands.",
260
+ usage: ["rig plugin <list|validate|run> [options]"],
261
+ commands: [
262
+ { command: "list", description: "List plugins declared in rig.config.ts and their contributions.", primary: true },
263
+ { command: "validate --task <id>", description: "Run plugin-contributed validators for a task.", primary: true },
264
+ { command: "run <command-id> [args...]", description: "Execute a plugin-contributed CLI command (also callable as `rig <command-id>`)." }
265
+ ],
266
+ examples: ["rig plugin list", "rig plugin run <command-id>"]
267
+ },
268
+ {
269
+ name: "init",
270
+ summary: "Set up Rig for this repo: server, GitHub auth, checkout strategy, task source, and Pi wiring.",
271
+ usage: ["rig init [--yes] [--server local|remote] [--repo owner/repo] [--remote-url <url>]"],
272
+ commands: [
273
+ { command: "init", description: "Interactive setup wizard for a new or existing Rig repo.", primary: true },
274
+ { command: "init --demo", description: "Offline demo project: files task source + 3 sample tasks, zero GitHub.", primary: true },
275
+ { command: "init --yes", description: "Non-interactive setup using detected/default settings.", primary: true },
276
+ { command: "init --server remote --remote-url <url>", description: "Link this repo to a remote Rig server.", primary: true },
277
+ { command: "init --repair", description: "Repair missing private state without replacing project config." }
278
+ ],
279
+ examples: [
280
+ "rig init",
281
+ "rig init --demo",
282
+ "rig init --yes --repo humanity-org/humanwork",
283
+ "rig init --server remote --remote-url https://where.rig-does.work --repo owner/repo"
284
+ ],
285
+ next: ["After init, run `rig server status`.", "Then use `rig task list` and `rig task run --next` for day-to-day work."]
286
+ },
287
+ {
288
+ name: "doctor",
289
+ summary: "Diagnostics for project/server/GitHub/Pi state.",
290
+ usage: ["rig doctor"],
291
+ commands: [
292
+ { command: "doctor", description: "Run setup and runtime diagnostics.", primary: true },
293
+ { command: "check", description: "Compatibility spelling for diagnostics." }
294
+ ],
295
+ examples: ["rig doctor", "rig doctor --json"],
296
+ next: ["Use `rig server status` and `rig github auth status` to inspect common failure points."]
297
+ },
298
+ {
299
+ name: "github",
300
+ summary: "GitHub auth helpers for the selected Rig server.",
301
+ usage: ["rig github auth <status|import-gh|token>"],
302
+ commands: [
303
+ { command: "auth status", description: "Show GitHub auth state.", primary: true },
304
+ { command: "auth import-gh", description: "Import the current `gh` token into the selected server." },
305
+ { command: "auth token --token <token>", description: "Store a token on the selected server." }
306
+ ],
307
+ examples: ["rig github auth status", "rig github auth import-gh"],
308
+ next: ["After auth is valid, use `rig task run --next`."]
309
+ }
310
+ ];
311
+ var ADVANCED_GROUPS = [
312
+ { name: "setup", summary: "Bootstrap/check local setup.", usage: ["rig setup <bootstrap|check|preflight>"], commands: [{ command: "bootstrap|check|preflight", description: "Setup helpers." }] },
313
+ { name: "profile", summary: "Runtime profile/model defaults.", usage: ["rig profile <show|set>"], commands: [{ command: "show", description: "Show active profile." }] },
314
+ {
315
+ name: "review",
316
+ summary: "Inspect or change completion review gate policy.",
317
+ usage: ["rig review <show|set>"],
318
+ commands: [
319
+ { command: "show", description: "Show current review gate settings." },
320
+ { command: "set <off|advisory|required> [--provider greptile]", description: "Change review strictness/provider." }
321
+ ],
322
+ examples: ["rig review show", "rig review set required --provider greptile"],
323
+ next: ["Use `rig inbox approvals` for blocked run handoffs."]
324
+ },
325
+ {
326
+ name: "browser",
327
+ summary: "Browser/app diagnostics for browser-required tasks.",
328
+ usage: ["rig browser <help|explain|demo|app|hp-next> [options]"],
329
+ commands: [
330
+ { command: "help", description: "Rich browser command help (canonical: `rig browser help`)." },
331
+ { command: "explain", description: "Explain the browser-required task contract." },
332
+ { command: "demo", description: "Run browser demo flows against a local page." },
333
+ { command: "app", description: "Launch the Rig Browser workstation app." },
334
+ { command: "hp-next <dev|check|e2e|reset>", description: "Drive the hp-next browser test harness." }
335
+ ]
336
+ },
337
+ {
338
+ name: "pi",
339
+ summary: "Manage Pi extension packages for this project (community extensions from npm/git).",
340
+ usage: ["rig pi <list|add|remove|search> [args]"],
341
+ commands: [
342
+ { command: "list", description: "Show project and user Pi extension packages." },
343
+ { command: "add <source>", description: "Add an npm/git Pi extension to .pi/settings.json (auto-installs at next session)." },
344
+ { command: "remove <source>", description: "Remove an operator-added Pi extension." },
345
+ { command: "search [term]", description: "Discover Pi extension packages on the npm registry." }
346
+ ],
347
+ examples: ["rig pi search subagents", "rig pi add pi-subagents", "rig pi list"],
348
+ next: ["Config-managed extensions: declare `runtime: { pi: { packages: [...] } }` in rig.config.ts \u2014 workers pick them up automatically."]
349
+ },
350
+ { name: "queue", summary: "Run task queues locally.", usage: ["rig queue run [options]"], commands: [{ command: "run", description: "Process queue work." }] },
351
+ { name: "agent", summary: "Runtime agent workspace helpers.", usage: ["rig agent <list|prepare|run|cleanup>"], commands: [{ command: "list", description: "List prepared agents." }] },
352
+ { name: "inspector", summary: "Event stream and drift scanners.", usage: ["rig inspector <stream|scan-upstream-drift>"], commands: [{ command: "stream", description: "Stream events." }] },
353
+ { name: "dist", summary: "Build/install packaged Rig CLI.", usage: ["rig dist <build|install|doctor>"], commands: [{ command: "build", description: "Build distribution." }] },
354
+ { name: "workspace", summary: "Workspace topology/service helpers.", usage: ["rig workspace <summary|topology|remote-hosts>"], commands: [{ command: "summary", description: "Show workspace summary." }] },
355
+ { name: "remote", summary: "Compatibility remote orchestration controls.", usage: ["rig remote <status|watch|pause|resume|...>"], commands: [{ command: "status", description: "Show remote state." }] },
356
+ { name: "git", summary: "Pass through to Rig git-flow helper.", usage: ["rig git <args...>"], commands: [{ command: "<args...>", description: "Advanced git flow operations." }] },
357
+ { name: "harness", summary: "Pass through to runtime harness CLI.", usage: ["rig harness <args...>"], commands: [{ command: "<args...>", description: "Advanced harness operations." }] },
358
+ { name: "test", summary: "Project test wrappers.", usage: ["rig test <unit|e2e|all>"], commands: [{ command: "all", description: "Run configured project tests." }] }
359
+ ];
360
+ var ALL_GROUPS = [...PRIMARY_GROUPS, ...ADVANCED_GROUPS];
361
+ function heading(title) {
362
+ return pc2.bold(pc2.cyan(title));
363
+ }
364
+ 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);
369
+ const lines = [
370
+ m(" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 ") + d(" \u2591\u2592\u2593\u2588 "),
371
+ m(" \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D ") + d("\u2593\u2592\u2591"),
372
+ c(" \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557") + d(" \u2591\u2592"),
373
+ c(" \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551") + d(" \u2588\u2593\u2591"),
374
+ y(" \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D") + d(" \u2592\u2591"),
375
+ y(" \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D "),
376
+ "",
377
+ ` ${c("\u25E2\u25E4")} ${pc2.bold("the control rig for autonomous coding agents")} ${m("//")} ${d("you are the operator")}`,
378
+ version ? ` ${d(`v${version} \xB7 jack in: rig task run --next`)}` : ` ${d("jack in: rig task run --next")}`
379
+ ];
380
+ return lines.join(`
381
+ `);
382
+ }
383
+ function commandLine(command, description) {
384
+ const commandColumn = command.length >= 38 ? `${command} ` : command.padEnd(38);
385
+ return `${pc2.dim("\u2502")} ${pc2.bold(commandColumn)} ${description}`;
386
+ }
387
+ function renderCommandBlock(commands) {
388
+ return commands.map((entry) => commandLine(entry.command, entry.description)).join(`
389
+ `);
390
+ }
391
+ function renderGroup(group) {
392
+ const lines = [
393
+ `${heading(`rig ${group.name}`)} \u2014 ${group.summary}`,
394
+ "",
395
+ pc2.bold("Usage"),
396
+ ...group.usage.map((line) => ` ${line}`),
397
+ "",
398
+ pc2.bold("Commands"),
399
+ ...group.commands.map((entry) => commandLine(entry.command, entry.description))
400
+ ];
401
+ if (group.examples?.length) {
402
+ lines.push("", pc2.bold("Examples"), ...group.examples.map((line) => ` ${pc2.dim("$")} ${line}`));
403
+ }
404
+ if (group.next?.length) {
405
+ lines.push("", pc2.bold("Next steps"), ...group.next.map((line) => ` ${pc2.dim("\u203A")} ${line}`));
406
+ }
407
+ if (group.advanced?.length) {
408
+ lines.push("", pc2.bold("Compatibility / advanced"), ...group.advanced.map((line) => ` ${pc2.dim("\u203A")} ${line}`));
409
+ }
410
+ return lines.join(`
411
+ `);
412
+ }
413
+ function renderTopLevelHelp() {
414
+ 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."),
417
+ "",
418
+ ...TOP_LEVEL_SECTIONS.flatMap((section) => [
419
+ `${pc2.bold(pc2.magenta(`\u25C7 ${section.title}`))} \u2014 ${pc2.dim(section.subtitle)}`,
420
+ renderCommandBlock(section.commands),
421
+ ""
422
+ ]),
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."),
424
+ "",
425
+ pc2.bold("Global options"),
426
+ commandLine("--project <path>", "Use a project root instead of auto-discovery."),
427
+ commandLine("--json", "Emit structured output for scripts/agents."),
428
+ commandLine("--dry-run", "Print the command plan without mutating state.")
429
+ ].join(`
430
+ `).trimEnd();
431
+ }
432
+ function renderGroupHelp(groupName) {
433
+ const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
434
+ return group ? renderGroup(group) : null;
435
+ }
436
+ function shouldUseClackOutput2() {
437
+ return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
438
+ }
439
+ function printTopLevelHelp(state = {}) {
440
+ if (!shouldUseClackOutput2()) {
441
+ console.log(renderTopLevelHelp());
442
+ return;
443
+ }
444
+ console.log(renderRigBanner(state.version));
445
+ console.log("");
446
+ if (state.projectInitialized === false) {
447
+ intro("no rig project in this directory");
448
+ note2([
449
+ commandLine("rig init", "Set this repo up: config, GitHub auth, task source, server, Pi."),
450
+ commandLine("rig init --yes", "Same, non-interactive, sensible defaults."),
451
+ commandLine("rig doctor", "Already initialized somewhere else? Check the wiring.")
452
+ ].join(`
453
+ `), "Get started");
454
+ outro("After init: rig task run --next puts an agent on your next task.");
455
+ return;
456
+ }
457
+ intro(state.selectedServer ? `server: ${state.selectedServer}` : "rig");
458
+ for (const section of TOP_LEVEL_SECTIONS) {
459
+ note2(renderCommandBlock(section.commands), `${section.title} \u2014 ${section.subtitle}`);
460
+ }
461
+ log2.info("More: rig help --advanced \xB7 rig <group> --help \xB7 rig --version");
462
+ note2([
463
+ commandLine("--project <path>", "Use a project root instead of auto-discovery."),
464
+ commandLine("--json", "Emit structured output for scripts/agents."),
465
+ commandLine("--dry-run", "Print the command plan without mutating state.")
466
+ ].join(`
467
+ `), "Global options");
468
+ outro("init \u2192 task run \u2192 watch \u2192 inbox \u2192 merged.");
469
+ }
470
+ function printGroupHelpDocument(groupName) {
471
+ const rendered = renderGroupHelp(groupName) ?? renderTopLevelHelp();
472
+ if (!shouldUseClackOutput2()) {
473
+ console.log(rendered);
474
+ return;
475
+ }
476
+ const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
477
+ if (!group) {
478
+ printTopLevelHelp();
479
+ return;
480
+ }
481
+ intro(`rig ${group.name}`);
482
+ note2(group.summary, "Purpose");
483
+ note2(group.usage.join(`
484
+ `), "Usage");
485
+ note2(group.commands.map((entry) => commandLine(entry.command, entry.description)).join(`
486
+ `), "Commands");
487
+ if (group.examples?.length)
488
+ note2(group.examples.map((line) => `$ ${line}`).join(`
489
+ `), "Examples");
490
+ if (group.next?.length)
491
+ note2(group.next.map((line) => `\u203A ${line}`).join(`
492
+ `), "Next steps");
493
+ if (group.advanced?.length)
494
+ log2.info(group.advanced.join(`
495
+ `));
496
+ outro("Run with --json when scripts need structured output.");
497
+ }
498
+
499
+ // packages/cli/src/commands/stats.ts
500
+ var DAY_MS = 24 * 60 * 60 * 1000;
501
+ function parseSinceOption(value, now = new Date) {
502
+ if (!value?.trim())
503
+ return null;
504
+ const trimmed = value.trim();
505
+ const relative = trimmed.match(/^(\d+)d$/i);
506
+ if (relative?.[1]) {
507
+ return new Date(now.getTime() - Number.parseInt(relative[1], 10) * DAY_MS);
508
+ }
509
+ const parsed = Date.parse(trimmed);
510
+ if (!Number.isFinite(parsed)) {
511
+ throw new CliError(`Invalid --since value: ${trimmed}. Use <n>d (e.g. 7d, 30d) or an ISO date (e.g. 2026-06-01).`, 2, { hint: "Re-run with a valid window, e.g. `rig stats --since 7d` or `rig stats --since 2026-06-01`." });
512
+ }
513
+ return new Date(parsed);
514
+ }
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
+ function formatPercent(value) {
600
+ if (value === null)
601
+ return "\u2014";
602
+ return `${(value * 100).toFixed(1)}%`;
603
+ }
604
+ function formatDuration(ms) {
605
+ if (ms === null)
606
+ return "\u2014";
607
+ if (ms < 1000)
608
+ return `${Math.round(ms)}ms`;
609
+ const seconds = ms / 1000;
610
+ if (seconds < 60)
611
+ return `${seconds.toFixed(0)}s`;
612
+ const minutes = seconds / 60;
613
+ if (minutes < 60)
614
+ return `${Math.floor(minutes)}m ${Math.round(seconds % 60)}s`;
615
+ const hours = Math.floor(minutes / 60);
616
+ return `${hours}h ${Math.round(minutes % 60)}m`;
617
+ }
618
+ function formatStatsReport(stats) {
619
+ const window = stats.since ? `since ${stats.since}` : "all time";
620
+ const rows = [
621
+ ["runs", String(stats.totalRuns)],
622
+ ["completed", `${stats.completedRuns} (${formatPercent(stats.completionRate)})`],
623
+ ["failed", `${stats.failedRuns} (${formatPercent(stats.failureRate)})`],
624
+ ["needs attn", `${stats.needsAttentionRuns} (${formatPercent(stats.needsAttentionRate)})`],
625
+ ["median time", formatDuration(stats.medianCompletionMs)],
626
+ ["steering", `${stats.steeringTotal} total \xB7 ${stats.steeringPerRun === null ? "\u2014" : stats.steeringPerRun.toFixed(2)}/run`],
627
+ ["stalls", String(stats.stallTotal)],
628
+ ["approvals", `${stats.approvalsRequested} requested \xB7 ${stats.approvalsApproved} approved \xB7 ${stats.approvalsRejected} rejected \xB7 ${stats.approvalsPending} pending`]
629
+ ];
630
+ const keyWidth = Math.max(...rows.map(([key]) => key.length));
631
+ const lines = [
632
+ formatSection("Fleet stats", window),
633
+ ...rows.map(([key, value]) => `${pc3.dim("\u2502")} ${pc3.dim(key.padEnd(keyWidth + 2))} ${value}`)
634
+ ];
635
+ const otherStatuses = Object.entries(stats.statusCounts).filter(([status]) => !["completed", "failed", "needs-attention"].includes(status)).sort(([, left], [, right]) => right - left);
636
+ if (otherStatuses.length > 0) {
637
+ lines.push(`${pc3.dim("\u2502")} ${pc3.dim("other".padEnd(keyWidth + 2))} ${otherStatuses.map(([status, count]) => `${status}:${count}`).join(" ")}`);
638
+ }
639
+ lines.push("", ...formatNextSteps([
640
+ "Inspect a run: `rig run list` then `rig run show <run-id>`",
641
+ "Narrow the window: `rig stats --since 7d`"
642
+ ]));
643
+ return lines.join(`
644
+ `);
645
+ }
646
+ async function executeStats(context, args) {
647
+ const [first, ...rest] = args;
648
+ const isImplicitShow = first === undefined || first.startsWith("-");
649
+ const command = isImplicitShow ? "show" : first;
650
+ const pending = isImplicitShow ? args : rest;
651
+ switch (command) {
652
+ case "show": {
653
+ const sinceResult = takeOption(pending, "--since");
654
+ requireNoExtraArgs(sinceResult.rest, "rig stats [show] [--since <7d|30d|ISO date>]");
655
+ const since = parseSinceOption(sinceResult.value);
656
+ const stats = computeRigStats(context.projectRoot, { since });
657
+ if (context.outputMode === "text") {
658
+ printFormattedOutput(formatStatsReport(stats));
659
+ }
660
+ return {
661
+ ok: true,
662
+ group: "stats",
663
+ command: "show",
664
+ details: stats
665
+ };
666
+ }
667
+ case "help": {
668
+ if (context.outputMode === "text")
669
+ printGroupHelpDocument("stats");
670
+ return { ok: true, group: "stats", command: "help" };
671
+ }
672
+ default:
673
+ throw new CliError(`Unknown stats command: ${command}. Use \`rig stats\` or \`rig stats show [--since <7d|30d|ISO date>]\`.`, 2, { hint: "Run `rig stats --since 7d` for the last week, or `rig stats --help` for usage." });
674
+ }
675
+ }
676
+ export {
677
+ parseSinceOption,
678
+ formatStatsReport,
679
+ executeStats,
680
+ computeRigStats
681
+ };