@h-rig/cli 0.0.6-alpha.88 → 0.0.6-alpha.89

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 (70) hide show
  1. package/dist/bin/rig.js +1159 -292
  2. package/dist/src/app/board.js +462 -48
  3. package/dist/src/app-opentui/adapters/doctor.js +458 -46
  4. package/dist/src/app-opentui/adapters/family.js +670 -147
  5. package/dist/src/app-opentui/adapters/fleet.js +477 -46
  6. package/dist/src/app-opentui/adapters/inbox.js +477 -46
  7. package/dist/src/app-opentui/adapters/init.js +497 -74
  8. package/dist/src/app-opentui/adapters/inspect.js +477 -46
  9. package/dist/src/app-opentui/adapters/pi-attach.js +484 -53
  10. package/dist/src/app-opentui/adapters/run-detail.js +477 -46
  11. package/dist/src/app-opentui/adapters/server.d.ts +26 -0
  12. package/dist/src/app-opentui/adapters/server.js +676 -59
  13. package/dist/src/app-opentui/adapters/tasks.js +539 -81
  14. package/dist/src/app-opentui/autocomplete.js +4 -2
  15. package/dist/src/app-opentui/bootstrap.js +1155 -288
  16. package/dist/src/app-opentui/command-palette.js +37 -10
  17. package/dist/src/app-opentui/index.js +566 -89
  18. package/dist/src/app-opentui/intent.js +33 -8
  19. package/dist/src/app-opentui/keymap.js +43 -29
  20. package/dist/src/app-opentui/pi-host-child.js +465 -53
  21. package/dist/src/app-opentui/react/App.js +104 -44
  22. package/dist/src/app-opentui/react/ChromeHost.js +16 -4
  23. package/dist/src/app-opentui/react/launch.js +555 -88
  24. package/dist/src/app-opentui/react/nav.js +1 -1
  25. package/dist/src/app-opentui/registry.js +1062 -237
  26. package/dist/src/app-opentui/remote-link.d.ts +10 -0
  27. package/dist/src/app-opentui/remote-link.js +47 -0
  28. package/dist/src/app-opentui/runtime.js +566 -89
  29. package/dist/src/app-opentui/scenes/doctor.js +1 -1
  30. package/dist/src/app-opentui/scenes/error.js +50 -4
  31. package/dist/src/app-opentui/scenes/family.js +60 -6
  32. package/dist/src/app-opentui/scenes/fleet.js +65 -13
  33. package/dist/src/app-opentui/scenes/help.js +4 -2
  34. package/dist/src/app-opentui/scenes/init.js +12 -12
  35. package/dist/src/app-opentui/scenes/main.js +7 -7
  36. package/dist/src/app-opentui/scenes/server.js +83 -11
  37. package/dist/src/app-opentui/scenes/tasks.js +79 -16
  38. package/dist/src/app-opentui/state.js +25 -5
  39. package/dist/src/app-opentui/surface-catalog.js +4 -2
  40. package/dist/src/app-opentui/types.d.ts +1 -1
  41. package/dist/src/commands/_cli-format.d.ts +10 -1
  42. package/dist/src/commands/_cli-format.js +5 -2
  43. package/dist/src/commands/_connection-state.d.ts +11 -1
  44. package/dist/src/commands/_connection-state.js +50 -5
  45. package/dist/src/commands/_doctor-checks.js +458 -46
  46. package/dist/src/commands/_help-catalog.js +4 -2
  47. package/dist/src/commands/_json-output.js +4 -0
  48. package/dist/src/commands/_operator-view.js +465 -53
  49. package/dist/src/commands/_pi-frontend.js +465 -53
  50. package/dist/src/commands/_preflight.js +509 -72
  51. package/dist/src/commands/_server-client.d.ts +33 -0
  52. package/dist/src/commands/_server-client.js +477 -46
  53. package/dist/src/commands/_server-events.js +446 -41
  54. package/dist/src/commands/_snapshot-upload.js +460 -48
  55. package/dist/src/commands/connect.js +620 -15
  56. package/dist/src/commands/doctor.js +458 -46
  57. package/dist/src/commands/github.js +462 -50
  58. package/dist/src/commands/inbox.js +458 -46
  59. package/dist/src/commands/init.js +497 -74
  60. package/dist/src/commands/inspect.js +458 -46
  61. package/dist/src/commands/run.js +465 -53
  62. package/dist/src/commands/server.js +647 -163
  63. package/dist/src/commands/setup.js +463 -51
  64. package/dist/src/commands/stats.js +462 -48
  65. package/dist/src/commands/task-run-driver.js +464 -52
  66. package/dist/src/commands/task.js +520 -81
  67. package/dist/src/commands.js +670 -147
  68. package/dist/src/index.js +674 -147
  69. package/dist/src/launcher.js +4 -0
  70. package/package.json +8 -8
@@ -210,16 +210,31 @@ function taskViewIntent(argv, command = "", rest = [], raw) {
210
210
  const { payload, label } = taskViewPayload(command, rest);
211
211
  return intent("tasks", argv, "refresh", payload, label, raw);
212
212
  }
213
- function routeServer(argv, command, raw, checkingLabel) {
214
- if (!command || command === "status") {
213
+ function routeServer(argv, command, rest, raw, checkingLabel) {
214
+ if (!command || command === "status" || command === "list") {
215
215
  return intent("server", argv, "refresh", undefined, command ? checkingLabel : "Loading server", raw);
216
216
  }
217
+ if (command === "use") {
218
+ const alias = firstNonOption(rest);
219
+ if (alias === "local")
220
+ return intent("server", argv, "server-use-local", undefined, "Use local server", raw);
221
+ if (alias)
222
+ return intent("server", argv, "server-use-remote", { alias }, `Use ${alias}`, raw);
223
+ return intent("server", argv, "refresh", undefined, "Select a remote alias in Server", raw);
224
+ }
225
+ if (command === "add")
226
+ return intent("server", argv, "server-add-remote", { argv: [...argv] }, "Add remote server", raw);
227
+ if (command === "repair-link")
228
+ return intent("server", argv, "remote-link-repair", undefined, "Repair remote link", raw);
217
229
  return commandRunIntent(argv, raw);
218
230
  }
219
231
  function routeGithub(argv, command, rest, raw) {
220
232
  if (command === "auth" && (rest[0]?.toLowerCase() ?? "status") === "status" && rest.length <= 1) {
221
233
  return intent("server", argv, "refresh", undefined, "Checking GitHub auth", raw);
222
234
  }
235
+ if (command === "auth" && rest[0]?.toLowerCase() === "import-gh" && rest.length <= 1) {
236
+ return intent("server", argv, "github-auth-import", undefined, "Import GitHub auth", raw);
237
+ }
223
238
  return commandRunIntent(argv, raw);
224
239
  }
225
240
  function routeDoctor(argv, command, raw) {
@@ -268,11 +283,16 @@ function intentFromArgv(argv) {
268
283
  return commandRunIntent(argv);
269
284
  }
270
285
  if (normalizedGroup === "server")
271
- return routeServer(argv, normalizedCommand, undefined, "Checking server");
286
+ return routeServer(argv, normalizedCommand, rest, undefined, "Checking server");
272
287
  if (normalizedGroup === "github")
273
288
  return routeGithub(argv, normalizedCommand, rest);
274
- if (normalizedGroup === "init")
275
- return commandRunIntent(argv);
289
+ if (normalizedGroup === "init") {
290
+ if (!normalizedCommand)
291
+ return intent("init", argv, "refresh", undefined, "Open init");
292
+ if (rest.includes("--yes") || normalizedCommand === "--yes")
293
+ return intent("init", argv, "init-start", undefined, "Run init");
294
+ return intent("init", argv, "refresh", undefined, "Open init");
295
+ }
276
296
  if (normalizedGroup === "doctor")
277
297
  return routeDoctor(argv, normalizedCommand);
278
298
  if (normalizedGroup === "inbox")
@@ -335,12 +355,17 @@ function intentFromTypeBar(value) {
335
355
  return commandRunIntent(parts, value);
336
356
  return intent("tasks", parts, "refresh", undefined, "Select a task, then press Enter; or use run next", value);
337
357
  }
338
- if (first === "init")
339
- return commandRunIntent(parts, value);
358
+ if (first === "init") {
359
+ if (!second)
360
+ return intent("init", parts, "refresh", undefined, "Open init", value);
361
+ if (parts.includes("--yes"))
362
+ return intent("init", parts, "init-start", undefined, "Run init", value);
363
+ return intent("init", parts, "refresh", undefined, "Open init", value);
364
+ }
340
365
  if (first === "doctor")
341
366
  return routeDoctor(parts, second, value);
342
367
  if (first === "server")
343
- return routeServer(parts, second, value, "Loading server");
368
+ return routeServer(parts, second, rest, value, "Loading server");
344
369
  if (first === "github")
345
370
  return routeGithub(parts, second, rest, value);
346
371
  if (first === "inbox")
@@ -727,12 +752,13 @@ var PRIMARY_GROUPS = [
727
752
  {
728
753
  name: "server",
729
754
  summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
730
- usage: ["rig server <status|list|add|use|start> [options]"],
755
+ usage: ["rig server <status|list|add|use|repair-link|start> [options]"],
731
756
  commands: [
732
- { command: "status", description: "Show the selected server for this repo.", primary: true },
757
+ { command: "status", description: "Show the selected server and remote project-root link for this repo.", primary: true },
733
758
  { command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
734
759
  { command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
735
760
  { command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
761
+ { command: "repair-link [--prepare|--backfill-only] [--repo owner/repo]", description: "Backfill or prepare the selected remote's server-host checkout link.", primary: true },
736
762
  { command: "list", description: "List saved local/remote server aliases.", primary: true },
737
763
  { command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
738
764
  ],
@@ -740,6 +766,7 @@ var PRIMARY_GROUPS = [
740
766
  "rig server status",
741
767
  "rig server add prod https://where.rig-does.work",
742
768
  "rig server use prod",
769
+ "rig server repair-link --repo owner/repo",
743
770
  "rig server use local",
744
771
  "rig server start --port 3773"
745
772
  ],
@@ -1244,12 +1271,6 @@ function cycleCompletion(value, state, candidates = commandCandidates()) {
1244
1271
  return { value: matches[nextIndex], state: { base, index: nextIndex } };
1245
1272
  }
1246
1273
 
1247
- // packages/cli/src/app-opentui/pi-pty-host.ts
1248
- function getActivePiHost() {
1249
- return null;
1250
- }
1251
- function stopActivePiHost(_reason) {}
1252
-
1253
1274
  // packages/cli/src/app-opentui/keymap.ts
1254
1275
  var autocompleteState;
1255
1276
  function clearTypeBar(context, message) {
@@ -1259,22 +1280,15 @@ function clearTypeBar(context, message) {
1259
1280
  context.emitTypeBarPatch({ value: "", mode: "nav", prompt: undefined, message });
1260
1281
  }
1261
1282
  function handleEmbeddedTerminalKey(context, key) {
1262
- const state = context.getState();
1263
- const piHost = getActivePiHost();
1264
- const commandHost = getActiveCommandHost();
1265
- const host = state.scene === "handoff" ? piHost : state.scene === "command" ? commandHost : null;
1283
+ if (context.getState().scene !== "command")
1284
+ return false;
1285
+ const host = getActiveCommandHost();
1266
1286
  if (!host)
1267
1287
  return false;
1268
1288
  if (key.ctrl && key.name === "]") {
1269
- if (state.scene === "handoff") {
1270
- stopActivePiHost("operator detach");
1271
- clearTypeBar(context, "detached from Pi");
1272
- context.runAppAction("Opening runs", () => context.runtime.runIntent({ scene: "fleet", argv: ["runs"], action: { kind: "refresh", label: "Opening runs" } }));
1273
- } else {
1274
- stopActiveCommandHost("operator detach");
1275
- clearTypeBar(context, "closed command");
1276
- context.runAppAction("Project menu", () => context.runtime.runIntent({ scene: "main", argv: ["main"], action: { kind: "none", label: "Project menu" } }));
1277
- }
1289
+ stopActiveCommandHost("operator detach");
1290
+ clearTypeBar(context, "closed command");
1291
+ context.runAppAction("Project menu", () => context.runtime.runIntent({ scene: "main", argv: ["main"], action: { kind: "none", label: "Project menu" } }));
1278
1292
  return true;
1279
1293
  }
1280
1294
  const sequence = key.raw || key.sequence;
@@ -1543,8 +1557,8 @@ import { WsTransport } from "@rig/client";
1543
1557
  import { RIG_WS_CHANNELS } from "@rig/contracts";
1544
1558
 
1545
1559
  // packages/cli/src/commands/_server-client.ts
1546
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
1547
- import { resolve as resolve2 } from "path";
1560
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
1561
+ import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
1548
1562
 
1549
1563
  // packages/cli/src/runner.ts
1550
1564
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
@@ -1636,12 +1650,28 @@ function readRepoConnection(projectRoot) {
1636
1650
  selected,
1637
1651
  project: typeof record.project === "string" ? record.project : undefined,
1638
1652
  linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
1639
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
1653
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
1654
+ serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
1655
+ serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
1640
1656
  };
1641
1657
  }
1642
1658
  function writeRepoConnection(projectRoot, state) {
1643
1659
  writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
1644
1660
  }
1661
+ function rootAllowedForSelection(repo, connection) {
1662
+ const root = repo.serverProjectRoot?.trim();
1663
+ if (!root)
1664
+ return;
1665
+ if (connection.kind === "remote") {
1666
+ if (repo.serverProjectRootAlias !== repo.selected)
1667
+ return;
1668
+ if (repo.serverProjectRootBaseUrl !== connection.baseUrl)
1669
+ return;
1670
+ } else if (repo.serverProjectRootAlias && repo.serverProjectRootAlias !== repo.selected) {
1671
+ return;
1672
+ }
1673
+ return root;
1674
+ }
1645
1675
  function resolveSelectedConnection(projectRoot, options = {}) {
1646
1676
  const repo = readRepoConnection(projectRoot);
1647
1677
  if (!repo)
@@ -1653,13 +1683,41 @@ function resolveSelectedConnection(projectRoot, options = {}) {
1653
1683
  if (!connection) {
1654
1684
  throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
1655
1685
  }
1656
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
1686
+ return { alias: repo.selected, connection, serverProjectRoot: rootAllowedForSelection(repo, connection) };
1657
1687
  }
1658
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
1688
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot, metadata = {}) {
1659
1689
  const repo = readRepoConnection(projectRoot);
1660
1690
  if (!repo)
1661
1691
  return;
1662
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
1692
+ let inferred = metadata;
1693
+ if (!inferred.alias || !inferred.baseUrl) {
1694
+ try {
1695
+ const selected = resolveSelectedConnection(projectRoot);
1696
+ if (selected?.connection.kind === "remote") {
1697
+ inferred = {
1698
+ alias: inferred.alias ?? selected.alias,
1699
+ baseUrl: inferred.baseUrl ?? selected.connection.baseUrl
1700
+ };
1701
+ }
1702
+ } catch {}
1703
+ }
1704
+ writeRepoConnection(projectRoot, {
1705
+ ...repo,
1706
+ ...metadata.project ? { project: metadata.project } : {},
1707
+ serverProjectRoot,
1708
+ ...inferred.alias ? { serverProjectRootAlias: inferred.alias } : {},
1709
+ ...inferred.baseUrl ? { serverProjectRootBaseUrl: inferred.baseUrl.replace(/\/+$/, "") } : {}
1710
+ });
1711
+ }
1712
+ function clearRepoServerProjectRoot(projectRoot) {
1713
+ const repo = readRepoConnection(projectRoot);
1714
+ if (!repo)
1715
+ return;
1716
+ writeRepoConnection(projectRoot, {
1717
+ selected: repo.selected,
1718
+ ...repo.project ? { project: repo.project } : {},
1719
+ ...repo.linkedAt ? { linkedAt: repo.linkedAt } : {}
1720
+ });
1663
1721
  }
1664
1722
 
1665
1723
  // packages/cli/src/commands/_server-client.ts
@@ -1700,11 +1758,10 @@ function readStoredGitHubAuthToken(projectRoot) {
1700
1758
  const parsed = readRemoteAuthState(projectRoot);
1701
1759
  return parsed ? cleanToken(typeof parsed.token === "string" ? parsed.token : undefined) : null;
1702
1760
  }
1703
- function inferRemoteServerProjectRootFromAuthState(projectRoot) {
1704
- const repo = readRepoConnection(projectRoot);
1705
- const slug = repo?.project?.trim();
1706
- if (!slug || !/^[^/]+\/[^/]+$/.test(slug))
1761
+ function inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug) {
1762
+ if (!/^[^/]+\/[^/]+$/.test(repoSlug))
1707
1763
  return null;
1764
+ const repo = readRepoConnection(projectRoot);
1708
1765
  const auth = readRemoteAuthState(projectRoot);
1709
1766
  const authUpdatedAt = typeof auth?.updatedAt === "string" ? Date.parse(auth.updatedAt) : Number.NaN;
1710
1767
  const repoLinkedAt = typeof repo?.linkedAt === "string" ? Date.parse(repo.linkedAt) : Number.NaN;
@@ -1713,25 +1770,413 @@ function inferRemoteServerProjectRootFromAuthState(projectRoot) {
1713
1770
  const checkoutBaseDir = typeof auth?.checkoutBaseDir === "string" && auth.checkoutBaseDir.trim() ? auth.checkoutBaseDir.trim() : null;
1714
1771
  if (!checkoutBaseDir)
1715
1772
  return null;
1716
- const inferred = `${checkoutBaseDir.replace(/\/+$/, "")}/${slug}`;
1717
- writeRepoServerProjectRoot(projectRoot, inferred);
1718
- return inferred;
1773
+ return `${checkoutBaseDir.replace(/\/+$/, "")}/${repoSlug}`;
1719
1774
  }
1720
1775
  function readLocalConnectionFallbackToken(projectRoot) {
1721
1776
  return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
1722
1777
  }
1778
+ function normalizeRepoSlug(value) {
1779
+ const slug = value?.trim();
1780
+ return slug && /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
1781
+ }
1782
+ function readProjectLinkSlug(projectRoot) {
1783
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
1784
+ if (!existsSync2(path))
1785
+ return null;
1786
+ try {
1787
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
1788
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1789
+ return null;
1790
+ return normalizeRepoSlug(typeof parsed.repoSlug === "string" ? String(parsed.repoSlug) : null);
1791
+ } catch {
1792
+ return null;
1793
+ }
1794
+ }
1795
+ function writeProjectLinkConnection(projectRoot, repoSlug, alias) {
1796
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
1797
+ mkdirSync2(dirname2(path), { recursive: true });
1798
+ writeFileSync2(path, `${JSON.stringify({ repoSlug, connection: alias, linkedAt: new Date().toISOString() }, null, 2)}
1799
+ `, "utf8");
1800
+ }
1801
+ function remoteLinkRepairCommand(repoSlug) {
1802
+ return repoSlug ? `rig server repair-link --repo ${repoSlug}` : "rig server repair-link --repo owner/repo";
1803
+ }
1804
+ function formatRemoteProjectLinkHint(resolution) {
1805
+ const repair = remoteLinkRepairCommand(resolution.repoSlug);
1806
+ if (resolution.status === "auth_required") {
1807
+ return `Authenticate the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}, then run \`${repair}\`. Use \`rig github auth import-gh\` or \`rig init --repair --server remote --github-auth device${resolution.repoSlug ? ` --repo ${resolution.repoSlug}` : ""}\`.`;
1808
+ }
1809
+ if (resolution.status === "missing_project") {
1810
+ return `Record the repo slug, then run \`${repair}\` (or \`rig init --repo owner/repo --server remote --github-auth device\`).`;
1811
+ }
1812
+ if (resolution.status === "not_remote")
1813
+ return "Select a remote server with `rig server use <alias>` before repairing a remote project link.";
1814
+ return `Run \`${repair}\` to backfill or prepare a server-host checkout for the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}.`;
1815
+ }
1816
+ function remoteProjectLinkFailure(input) {
1817
+ const partial = {
1818
+ status: input.status,
1819
+ alias: input.alias,
1820
+ baseUrl: input.baseUrl,
1821
+ repoSlug: input.repoSlug
1822
+ };
1823
+ return {
1824
+ ok: false,
1825
+ ...input,
1826
+ hint: formatRemoteProjectLinkHint(partial),
1827
+ next: remoteLinkRepairCommand(input.repoSlug)
1828
+ };
1829
+ }
1830
+ function remoteProjectLinkSuccess(input) {
1831
+ return {
1832
+ ok: true,
1833
+ status: input.status,
1834
+ alias: input.alias,
1835
+ baseUrl: input.baseUrl,
1836
+ repoSlug: input.repoSlug,
1837
+ serverProjectRoot: input.serverProjectRoot,
1838
+ source: input.source,
1839
+ prepared: input.prepared ?? input.status === "prepared",
1840
+ validated: input.validated ?? false,
1841
+ message: input.message ?? `Remote project link ready for ${input.repoSlug}.`,
1842
+ hint: "Remote-scoped task/run/status requests will send x-rig-project-root for this server-host checkout.",
1843
+ next: "rig task list"
1844
+ };
1845
+ }
1846
+ function localCheckoutPathCandidate(projectRoot, candidate) {
1847
+ try {
1848
+ const local = resolve2(projectRoot);
1849
+ const resolved = resolve2(candidate);
1850
+ return resolved === local || resolved.startsWith(`${local}/`);
1851
+ } catch {
1852
+ return false;
1853
+ }
1854
+ }
1855
+ async function requestRemoteProjectLinkJson(baseUrl, pathname, authToken, init = {}) {
1856
+ const requestUrl = new URL(`${baseUrl}${pathname}`);
1857
+ if (authToken && queryAuthFallbackEnabled())
1858
+ requestUrl.searchParams.set("rt", authToken);
1859
+ const response = await fetch(requestUrl, {
1860
+ ...init,
1861
+ headers: mergeHeaders(init.headers, authToken)
1862
+ });
1863
+ const text = await response.text();
1864
+ const payload = text.trim().length > 0 ? (() => {
1865
+ try {
1866
+ return JSON.parse(text);
1867
+ } catch {
1868
+ return null;
1869
+ }
1870
+ })() : null;
1871
+ return { ok: response.ok, status: response.status, payload, text };
1872
+ }
1873
+ function payloadError(payload, fallback) {
1874
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
1875
+ const record = payload;
1876
+ const value = record.error ?? record.message ?? record.reason;
1877
+ if (typeof value === "string" && value.trim())
1878
+ return value.trim();
1879
+ }
1880
+ return fallback;
1881
+ }
1882
+ function checkoutPathsFromProjectPayload(payload) {
1883
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
1884
+ return [];
1885
+ const project = payload.project;
1886
+ if (!project || typeof project !== "object" || Array.isArray(project))
1887
+ return [];
1888
+ const checkouts = project.checkouts;
1889
+ if (!Array.isArray(checkouts))
1890
+ return [];
1891
+ return [...checkouts].reverse().flatMap((entry) => {
1892
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
1893
+ return [];
1894
+ const path = entry.path;
1895
+ return typeof path === "string" && path.trim() ? [path.trim()] : [];
1896
+ });
1897
+ }
1898
+ function checkoutPathFromPreparePayload(payload) {
1899
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
1900
+ return null;
1901
+ const checkout = payload.checkout;
1902
+ if (!checkout || typeof checkout !== "object" || Array.isArray(checkout))
1903
+ return null;
1904
+ const path = checkout.path;
1905
+ return typeof path === "string" && path.trim() ? path.trim() : null;
1906
+ }
1907
+ async function validateAndPersistRemoteRoot(input) {
1908
+ const candidate = input.candidate.trim();
1909
+ if (!candidate || !isAbsolute(candidate)) {
1910
+ return remoteProjectLinkFailure({
1911
+ status: "invalid_root",
1912
+ alias: input.alias,
1913
+ baseUrl: input.baseUrl,
1914
+ repoSlug: input.repoSlug,
1915
+ message: `Remote project root candidate is not an absolute server-host path: ${candidate || "(empty)"}.`
1916
+ });
1917
+ }
1918
+ if (localCheckoutPathCandidate(input.projectRoot, candidate)) {
1919
+ return remoteProjectLinkFailure({
1920
+ status: "invalid_root",
1921
+ alias: input.alias,
1922
+ baseUrl: input.baseUrl,
1923
+ repoSlug: input.repoSlug,
1924
+ message: `Refusing to use local checkout path ${candidate} as a remote server project root.`
1925
+ });
1926
+ }
1927
+ let response;
1928
+ try {
1929
+ response = await requestRemoteProjectLinkJson(input.baseUrl, "/api/server/project-root", input.authToken, {
1930
+ method: "POST",
1931
+ headers: { "content-type": "application/json" },
1932
+ body: JSON.stringify({ projectRoot: candidate })
1933
+ });
1934
+ } catch (error) {
1935
+ return remoteProjectLinkFailure({
1936
+ status: "error",
1937
+ alias: input.alias,
1938
+ baseUrl: input.baseUrl,
1939
+ repoSlug: input.repoSlug,
1940
+ message: `Could not validate remote project root ${candidate}: ${error instanceof Error ? error.message : String(error)}`
1941
+ });
1942
+ }
1943
+ if (response.status === 401 || response.status === 403) {
1944
+ return remoteProjectLinkFailure({
1945
+ status: "auth_required",
1946
+ alias: input.alias,
1947
+ baseUrl: input.baseUrl,
1948
+ repoSlug: input.repoSlug,
1949
+ statusCode: response.status,
1950
+ message: `Remote server ${input.alias} requires authentication before validating project root ${candidate}.`
1951
+ });
1952
+ }
1953
+ if (!response.ok) {
1954
+ return remoteProjectLinkFailure({
1955
+ status: "invalid_root",
1956
+ alias: input.alias,
1957
+ baseUrl: input.baseUrl,
1958
+ repoSlug: input.repoSlug,
1959
+ statusCode: response.status,
1960
+ message: `Remote server rejected project root ${candidate} (${response.status}): ${payloadError(response.payload, response.text || "project-root validation failed")}`
1961
+ });
1962
+ }
1963
+ const record = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload) ? response.payload : {};
1964
+ if (record.ok !== true) {
1965
+ return remoteProjectLinkFailure({
1966
+ status: "invalid_root",
1967
+ alias: input.alias,
1968
+ baseUrl: input.baseUrl,
1969
+ repoSlug: input.repoSlug,
1970
+ message: `Remote server did not accept project root ${candidate}: ${payloadError(response.payload, "project-root validation failed")}`
1971
+ });
1972
+ }
1973
+ const accepted = typeof record.projectRoot === "string" && record.projectRoot.trim() ? record.projectRoot.trim() : typeof record.requestedProjectRoot === "string" && record.requestedProjectRoot.trim() ? record.requestedProjectRoot.trim() : candidate;
1974
+ writeRepoServerProjectRoot(input.projectRoot, accepted, { alias: input.alias, baseUrl: input.baseUrl, project: input.repoSlug });
1975
+ writeProjectLinkConnection(input.projectRoot, input.repoSlug, input.alias);
1976
+ const status = input.status ?? (input.prepared ? "prepared" : "backfilled");
1977
+ return remoteProjectLinkSuccess({
1978
+ status,
1979
+ alias: input.alias,
1980
+ baseUrl: input.baseUrl,
1981
+ repoSlug: input.repoSlug,
1982
+ serverProjectRoot: accepted,
1983
+ source: input.source,
1984
+ prepared: input.prepared,
1985
+ validated: true,
1986
+ message: status === "ready" ? `Remote project link already points to ${accepted} and was validated on ${input.alias}.` : input.prepared ? `Prepared and linked remote checkout ${accepted} for ${input.repoSlug}.` : `Backfilled remote checkout ${accepted} for ${input.repoSlug}.`
1987
+ });
1988
+ }
1989
+ async function ensureRemoteProjectRootLink(projectRoot, options = {}) {
1990
+ let selected;
1991
+ try {
1992
+ selected = resolveSelectedConnection(projectRoot);
1993
+ } catch (error) {
1994
+ return remoteProjectLinkFailure({ status: "error", message: error instanceof Error ? error.message : String(error) });
1995
+ }
1996
+ if (!selected || selected.connection.kind !== "remote") {
1997
+ return remoteProjectLinkFailure({ status: "not_remote", message: "No remote Rig server is selected for this repo." });
1998
+ }
1999
+ const repo = readRepoConnection(projectRoot);
2000
+ const explicitRepoRequested = options.repoSlug !== undefined;
2001
+ const explicitRepoSlug = explicitRepoRequested ? normalizeRepoSlug(options.repoSlug) : null;
2002
+ const repoProjectSlug = normalizeRepoSlug(repo?.project);
2003
+ const repoSlug = explicitRepoSlug ?? repoProjectSlug ?? readProjectLinkSlug(projectRoot);
2004
+ const alias = selected.alias;
2005
+ const baseUrl = selected.connection.baseUrl;
2006
+ const authToken = options.authToken === undefined ? readGitHubBearerTokenForRemote(projectRoot) : options.authToken;
2007
+ const mode = options.mode ?? "backfill-only";
2008
+ if (explicitRepoRequested && !explicitRepoSlug) {
2009
+ return remoteProjectLinkFailure({
2010
+ status: "missing_project",
2011
+ alias,
2012
+ baseUrl,
2013
+ message: `Invalid --repo value ${JSON.stringify(options.repoSlug)}. Expected owner/repo.`
2014
+ });
2015
+ }
2016
+ if (!repoSlug) {
2017
+ return remoteProjectLinkFailure({
2018
+ status: "missing_project",
2019
+ alias,
2020
+ baseUrl,
2021
+ message: `Remote server ${alias} is selected, but this checkout has no GitHub repo slug recorded.`
2022
+ });
2023
+ }
2024
+ const skippedCandidates = [];
2025
+ const storedRoot = selected.serverProjectRoot?.trim() || null;
2026
+ const storedRootMatchesResolvedRepo = repoProjectSlug === repoSlug;
2027
+ if (storedRoot && storedRootMatchesResolvedRepo) {
2028
+ if (localCheckoutPathCandidate(projectRoot, storedRoot)) {
2029
+ clearRepoServerProjectRoot(projectRoot);
2030
+ skippedCandidates.push(storedRoot);
2031
+ } else {
2032
+ const storedResult = await validateAndPersistRemoteRoot({
2033
+ projectRoot,
2034
+ alias,
2035
+ baseUrl,
2036
+ authToken,
2037
+ repoSlug,
2038
+ candidate: storedRoot,
2039
+ source: "stored",
2040
+ status: "ready"
2041
+ });
2042
+ if (storedResult.ok || storedResult.status === "auth_required" || storedResult.status === "error")
2043
+ return storedResult;
2044
+ clearRepoServerProjectRoot(projectRoot);
2045
+ skippedCandidates.push(storedRoot);
2046
+ }
2047
+ } else if (storedRoot) {
2048
+ skippedCandidates.push(storedRoot);
2049
+ }
2050
+ const authCandidate = inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug);
2051
+ if (authCandidate) {
2052
+ const authResult = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: authCandidate, source: "auth-state" });
2053
+ if (authResult.ok || authResult.status === "auth_required")
2054
+ return authResult;
2055
+ }
2056
+ let registryResponse;
2057
+ try {
2058
+ registryResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}`, authToken);
2059
+ } catch (error) {
2060
+ return remoteProjectLinkFailure({
2061
+ status: "error",
2062
+ alias,
2063
+ baseUrl,
2064
+ repoSlug,
2065
+ message: `Could not read remote project registry for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
2066
+ });
2067
+ }
2068
+ if (registryResponse.status === 401 || registryResponse.status === 403) {
2069
+ return remoteProjectLinkFailure({
2070
+ status: "auth_required",
2071
+ alias,
2072
+ baseUrl,
2073
+ repoSlug,
2074
+ statusCode: registryResponse.status,
2075
+ message: `Remote server ${alias} requires authentication before reading the ${repoSlug} project registry.`
2076
+ });
2077
+ }
2078
+ if (registryResponse.ok) {
2079
+ const candidates = checkoutPathsFromProjectPayload(registryResponse.payload);
2080
+ for (const candidate of candidates) {
2081
+ const result = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate, source: "registry" });
2082
+ if (result.ok || result.status === "auth_required")
2083
+ return result;
2084
+ skippedCandidates.push(candidate);
2085
+ }
2086
+ if (mode === "backfill-only") {
2087
+ return remoteProjectLinkFailure({
2088
+ status: candidates.length > 0 ? "invalid_root" : "no_server_checkout",
2089
+ alias,
2090
+ baseUrl,
2091
+ repoSlug,
2092
+ message: candidates.length > 0 ? `Remote registry has checkout candidates for ${repoSlug}, but none validated for ${alias}.` : `Remote registry has ${repoSlug}, but no server checkout path is linked yet.`,
2093
+ skippedCandidates
2094
+ });
2095
+ }
2096
+ } else if (registryResponse.status === 404) {
2097
+ if (mode === "backfill-only") {
2098
+ return remoteProjectLinkFailure({
2099
+ status: "project_not_registered",
2100
+ alias,
2101
+ baseUrl,
2102
+ repoSlug,
2103
+ statusCode: registryResponse.status,
2104
+ message: `Remote server ${alias} has no registered project record for ${repoSlug}.`
2105
+ });
2106
+ }
2107
+ } else {
2108
+ return remoteProjectLinkFailure({
2109
+ status: "error",
2110
+ alias,
2111
+ baseUrl,
2112
+ repoSlug,
2113
+ statusCode: registryResponse.status,
2114
+ message: `Could not backfill ${repoSlug} from remote registry (${registryResponse.status}): ${payloadError(registryResponse.payload, registryResponse.text || "registry lookup failed")}`,
2115
+ skippedCandidates
2116
+ });
2117
+ }
2118
+ let prepareResponse;
2119
+ try {
2120
+ prepareResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}/prepare-checkout`, authToken, {
2121
+ method: "POST",
2122
+ headers: { "content-type": "application/json" },
2123
+ body: JSON.stringify({ checkout: { kind: "managed-clone" }, repoUrl: `https://github.com/${repoSlug}.git` })
2124
+ });
2125
+ } catch (error) {
2126
+ return remoteProjectLinkFailure({
2127
+ status: "error",
2128
+ alias,
2129
+ baseUrl,
2130
+ repoSlug,
2131
+ message: `Could not prepare remote checkout for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
2132
+ });
2133
+ }
2134
+ if (prepareResponse.status === 401 || prepareResponse.status === 403) {
2135
+ return remoteProjectLinkFailure({
2136
+ status: "auth_required",
2137
+ alias,
2138
+ baseUrl,
2139
+ repoSlug,
2140
+ statusCode: prepareResponse.status,
2141
+ message: `Remote server ${alias} requires authentication before preparing ${repoSlug}.`
2142
+ });
2143
+ }
2144
+ if (!prepareResponse.ok) {
2145
+ return remoteProjectLinkFailure({
2146
+ status: "error",
2147
+ alias,
2148
+ baseUrl,
2149
+ repoSlug,
2150
+ statusCode: prepareResponse.status,
2151
+ message: `Remote checkout prepare failed for ${repoSlug} (${prepareResponse.status}): ${payloadError(prepareResponse.payload, prepareResponse.text || "prepare-checkout failed")}`,
2152
+ skippedCandidates
2153
+ });
2154
+ }
2155
+ const preparedPath = checkoutPathFromPreparePayload(prepareResponse.payload);
2156
+ if (!preparedPath) {
2157
+ return remoteProjectLinkFailure({
2158
+ status: "invalid_root",
2159
+ alias,
2160
+ baseUrl,
2161
+ repoSlug,
2162
+ message: `Remote checkout prepare for ${repoSlug} did not return a checkout.path.`,
2163
+ skippedCandidates
2164
+ });
2165
+ }
2166
+ return validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: preparedPath, source: "prepare", prepared: true });
2167
+ }
1723
2168
  async function ensureServerForCli(projectRoot) {
1724
2169
  try {
1725
2170
  const selected = resolveSelectedConnection(projectRoot);
1726
2171
  if (selected?.connection.kind === "remote") {
1727
2172
  reportServerPhase(`Connecting to ${selected.alias}\u2026`);
1728
2173
  const authToken = readGitHubBearerTokenForRemote(projectRoot);
1729
- const serverProjectRoot = selected.serverProjectRoot ?? inferRemoteServerProjectRootFromAuthState(projectRoot) ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
2174
+ const link = await ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only", authToken });
1730
2175
  return {
1731
2176
  baseUrl: selected.connection.baseUrl,
1732
2177
  authToken,
1733
2178
  connectionKind: "remote",
1734
- serverProjectRoot
2179
+ serverProjectRoot: link.ok ? link.serverProjectRoot ?? null : null
1735
2180
  };
1736
2181
  }
1737
2182
  reportServerPhase("Starting local Rig server\u2026");
@@ -1749,32 +2194,6 @@ async function ensureServerForCli(projectRoot) {
1749
2194
  throw error;
1750
2195
  }
1751
2196
  }
1752
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
1753
- const repo = readRepoConnection(projectRoot);
1754
- const slug = repo?.project?.trim();
1755
- if (!slug)
1756
- return null;
1757
- try {
1758
- const url = new URL(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`);
1759
- if (authToken && queryAuthFallbackEnabled())
1760
- url.searchParams.set("rt", authToken);
1761
- const response = await fetch(url, {
1762
- headers: mergeHeaders(undefined, authToken)
1763
- });
1764
- if (!response.ok)
1765
- return null;
1766
- const payload = await response.json();
1767
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
1768
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
1769
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
1770
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
1771
- if (path)
1772
- writeRepoServerProjectRoot(projectRoot, path);
1773
- return path;
1774
- } catch {
1775
- return null;
1776
- }
1777
- }
1778
2197
  function mergeCookie(existing, name, value) {
1779
2198
  const encoded = `${name}=${encodeURIComponent(value)}`;
1780
2199
  if (!existing?.trim())
@@ -3603,6 +4022,48 @@ function renderAsciiPreloaderFrame(scene, layout, tick) {
3603
4022
  };
3604
4023
  }
3605
4024
 
4025
+ // packages/cli/src/app-opentui/remote-link.ts
4026
+ var REPAIRABLE_REMOTE_LINK_STATUSES = new Set([
4027
+ "auth_required",
4028
+ "project_not_registered",
4029
+ "no_server_checkout",
4030
+ "invalid_root",
4031
+ "needs_prepare",
4032
+ "error"
4033
+ ]);
4034
+ function remoteProjectLinkError(message) {
4035
+ return /no server-host project root link|remote project(?:-root)? link|x-rig-project-root|serverProjectRoot/i.test(message ?? "");
4036
+ }
4037
+ function serverRecordForRemoteLink(state) {
4038
+ const server = state.data.server;
4039
+ return server && typeof server === "object" && !Array.isArray(server) ? server : null;
4040
+ }
4041
+ function remoteProjectLinkState(state) {
4042
+ const serverRecord = serverRecordForRemoteLink(state);
4043
+ if (!serverRecord || serverRecord.kind !== "remote")
4044
+ return null;
4045
+ const link = serverRecord.remoteProjectLink;
4046
+ if (link && typeof link === "object" && !Array.isArray(link))
4047
+ return link;
4048
+ const direct = state.data.remoteProjectLink;
4049
+ if (direct && typeof direct === "object" && !Array.isArray(direct))
4050
+ return direct;
4051
+ return null;
4052
+ }
4053
+ function shouldOfferRemoteLinkRepair(state, message) {
4054
+ const link = remoteProjectLinkState(state);
4055
+ if (link) {
4056
+ if (link.ok === true)
4057
+ return false;
4058
+ const status = link.status ?? "";
4059
+ return REPAIRABLE_REMOTE_LINK_STATUSES.has(status);
4060
+ }
4061
+ const serverRecord = serverRecordForRemoteLink(state);
4062
+ if (serverRecord && serverRecord.kind !== "remote")
4063
+ return false;
4064
+ return remoteProjectLinkError(message ?? state.error?.message);
4065
+ }
4066
+
3606
4067
  // packages/cli/src/app-opentui/selectable.ts
3607
4068
  function selectableDeckRow(deck, item) {
3608
4069
  return { ...deckRow({ ...deck, activateOnClick: true }), selectable: item };
@@ -3612,13 +4073,17 @@ function selectableDeckRow(deck, item) {
3612
4073
  var ERROR_ACTIONS = [
3613
4074
  { detail: "return to dashboard", item: { id: "main", label: "main", intent: { scene: "main", argv: [], action: { kind: "refresh", label: "Back to dashboard" } }, message: "back to dashboard" } },
3614
4075
  { detail: "run diagnostics", item: { id: "doctor", label: "doctor", intent: { scene: "doctor", argv: ["doctor"], action: { kind: "doctor-run", label: "Run doctor" } }, message: "run diagnostics" } },
3615
- { detail: "open server controls", item: { id: "server", label: "server", intent: { scene: "server", argv: ["server", "status"], action: { kind: "refresh", label: "Open server controls" } }, message: "open server controls" } },
3616
- { detail: "repair project/server/auth link", item: { id: "repair", label: "repair", intent: { scene: "command", argv: ["init", "--repair"], action: { kind: "command-run", label: "Repair project link" } }, message: "repair project link" } }
4076
+ { detail: "open server controls", item: { id: "server", label: "server", intent: { scene: "server", argv: ["server", "status"], action: { kind: "refresh", label: "Open server controls" } }, message: "open server controls" } }
3617
4077
  ];
4078
+ var ERROR_REPAIR_LINK_ACTION = { detail: "backfill or prepare selected remote project-root link", item: { id: "repair-link", label: "repair link", intent: { scene: "server", argv: ["server", "repair-link"], action: { kind: "remote-link-repair", label: "Repair remote link", payload: { returnScene: "server" } } }, message: "repair remote project link" } };
4079
+ function errorActions(state) {
4080
+ return shouldOfferRemoteLinkRepair(state, state.error?.message) ? [...ERROR_ACTIONS, ERROR_REPAIR_LINK_ACTION] : ERROR_ACTIONS;
4081
+ }
3618
4082
  function renderErrorScene(state) {
3619
4083
  const message = state.error?.message ?? "Unknown app error";
3620
4084
  const hint = state.error?.hint ?? "Use the actions below to recover.";
3621
- const selected = Math.max(0, Math.min(3, state.selection.index));
4085
+ const actions = errorActions(state);
4086
+ const selected = Math.max(0, Math.min(actions.length - 1, state.selection.index));
3622
4087
  return makeSceneFrame({
3623
4088
  scene: "error",
3624
4089
  title: "Error",
@@ -3636,7 +4101,7 @@ function renderErrorScene(state) {
3636
4101
  ...hint ? [line(hint, { fg: RIG_UI.yellow })] : [],
3637
4102
  line("", { fg: RIG_UI.ink3 }),
3638
4103
  line("ACTIONS", { fg: RIG_UI.ink3, bold: true }),
3639
- ...ERROR_ACTIONS.map(({ detail, item }, index) => selectableDeckRow({ label: item.label, detail, index, active: selected === index }, item))
4104
+ ...actions.map(({ detail, item }, index) => selectableDeckRow({ label: item.label, detail, index, active: selected === index }, item))
3640
4105
  ],
3641
4106
  backgroundColor: RIG_UI.panel,
3642
4107
  backgroundAlpha: 184,
@@ -3764,7 +4229,7 @@ function renderHelpScene(state, layout) {
3764
4229
 
3765
4230
  // packages/cli/src/app-opentui/scenes/main.ts
3766
4231
  var CONFIGURED_MENU = [
3767
- ["init", "setup, reconfigure, repair project state", { id: "init", label: "init", intent: { scene: "command", argv: ["init"], action: { kind: "command-run", label: "Run init" } }, message: "run setup/reconfigure flow" }],
4232
+ ["init", "guided setup, reconfigure, repair project state", { id: "init", label: "init", intent: { scene: "init", argv: ["init"], action: { kind: "refresh", label: "Open init" } }, message: "open native init flow" }],
3768
4233
  ["server", "local/remote target, auth, linkage", { id: "server", label: "server", intent: { scene: "server", argv: ["server", "status"], action: { kind: "refresh", label: "Checking server" } }, message: "check selected server" }],
3769
4234
  ["github", "auth, selected repo, stored token", { id: "github", label: "github", intent: { scene: "server", argv: ["github", "auth", "status"], action: { kind: "refresh", label: "Checking GitHub auth" } }, message: "check GitHub auth" }],
3770
4235
  ["tasks", "browse, filter, dispatch, attach active work", { id: "tasks", label: "tasks", intent: { scene: "tasks", argv: ["tasks"], action: { kind: "refresh", label: "Opening tasks" } }, message: "selected tasks" }],
@@ -3783,10 +4248,10 @@ var CONFIGURED_MENU = [
3783
4248
  ["help", "all actions, shortcuts, mouse controls", { id: "help", label: "help", intent: { scene: "help", argv: ["help"], action: { kind: "none", label: "Opening help" } }, message: "selected help" }]
3784
4249
  ];
3785
4250
  var ONBOARD_PRIMARY = {
3786
- id: "onboard-setup",
3787
- label: "Start guided setup",
3788
- intent: { scene: "init", argv: ["init"], action: { kind: "refresh", label: "Setup" } },
3789
- message: "open the guided setup checklist"
4251
+ id: "onboard-init",
4252
+ label: "Start guided init",
4253
+ intent: { scene: "init", argv: ["init"], action: { kind: "refresh", label: "Init" } },
4254
+ message: "open the native init checklist"
3790
4255
  };
3791
4256
  var ONBOARD_SECONDARY = [
3792
4257
  ["server", "select a local or remote target", { id: "server", label: "server", intent: { scene: "server", argv: ["server", "status"], action: { kind: "refresh", label: "Checking server" } }, message: "check selected server" }],
@@ -3849,7 +4314,7 @@ function configuredMenuRows(selectedIndex) {
3849
4314
  }));
3850
4315
  }
3851
4316
  function onboardingRows(selectedIndex) {
3852
- const primary = selectableDeckRow({ label: "setup", detail: "Start guided setup \u2014 recommended", active: selectedIndex === 0 }, ONBOARD_PRIMARY);
4317
+ const primary = selectableDeckRow({ label: "init", detail: "Start guided init \u2014 recommended", active: selectedIndex === 0 }, ONBOARD_PRIMARY);
3853
4318
  const secondary = ONBOARD_SECONDARY.map(([label, detail, item], index) => ({
3854
4319
  ...deckRow({ label, detail, index: index + 1, active: selectedIndex === index + 1, activateOnClick: true }),
3855
4320
  selectable: item
@@ -3913,7 +4378,7 @@ function renderMainScene(state, layout) {
3913
4378
  statusLine(state)
3914
4379
  ] : [
3915
4380
  line("WELCOME", { fg: RIG_UI.ink, bold: true }),
3916
- line("This project isn't set up yet. One guided flow gets you running.", { fg: RIG_UI.ink2 }),
4381
+ line("This project isn't initialized yet. One native init flow gets you running.", { fg: RIG_UI.ink2 }),
3917
4382
  blank(),
3918
4383
  line("GET STARTED", { fg: RIG_UI.ink, bold: true }),
3919
4384
  ...onboardingRows(actionSelected),
@@ -3948,6 +4413,12 @@ function renderMainScene(state, layout) {
3948
4413
  });
3949
4414
  }
3950
4415
 
4416
+ // packages/cli/src/app-opentui/pi-pty-host.ts
4417
+ function getActivePiHost() {
4418
+ return null;
4419
+ }
4420
+ function stopActivePiHost(_reason) {}
4421
+
3951
4422
  // packages/cli/src/app-opentui/runtime.ts
3952
4423
  var MAX_SCENE_LINES = 200;
3953
4424
  var MAX_SCENE_PANELS = 5;
@@ -3968,7 +4439,7 @@ var PRIMARY_NAV = [
3968
4439
  { id: "tasks", label: "Tasks", scene: "tasks", argv: ["tasks"], enterLabel: "Tasks", member: ["tasks"] },
3969
4440
  { id: "inbox", label: "Inbox", scene: "inbox", argv: ["inbox"], enterLabel: "Inbox", member: ["inbox"], badge: inboxPendingCount },
3970
4441
  { id: "stats", label: "Stats", scene: "family", argv: ["stats"], enterLabel: "Stats", member: ["family"] },
3971
- { id: "setup", label: "Setup", scene: "init", argv: ["init"], enterLabel: "Setup", member: ["init", "doctor", "server", "pi", "plugin", "repo", "workspace"] },
4442
+ { id: "init", label: "Init", scene: "init", argv: ["init"], enterLabel: "Init", member: ["init", "doctor", "server", "pi", "plugin", "repo", "workspace"] },
3972
4443
  { id: "help", label: "Help", scene: "help", argv: ["help"], enterLabel: "Help", member: ["help"] }
3973
4444
  ];
3974
4445
  function navSectionIntent(section) {
@@ -4008,7 +4479,7 @@ function entryIntentForScene(scene) {
4008
4479
  case "doctor":
4009
4480
  return { scene, argv: ["doctor"], action: { kind: "doctor-run", label: "Doctor" } };
4010
4481
  case "init":
4011
- return { scene, argv: ["init"], action: { kind: "refresh", label: "Setup" } };
4482
+ return { scene, argv: ["init"], action: { kind: "refresh", label: "Init" } };
4012
4483
  case "run-detail":
4013
4484
  return { scene, argv: ["run", "status"], action: { kind: "refresh", label: "Run" } };
4014
4485
  case "pi":
@@ -4124,7 +4595,7 @@ function sceneSectionLabel(scene) {
4124
4595
  handoff: "pi console",
4125
4596
  server: "server",
4126
4597
  doctor: "doctor",
4127
- init: "setup",
4598
+ init: "init",
4128
4599
  pi: "pi",
4129
4600
  plugin: "plugins",
4130
4601
  repo: "repo",
@@ -4584,7 +5055,7 @@ async function launchRigOpenTuiApp(options) {
4584
5055
  }
4585
5056
  for (const adapter of options.adapters ?? [])
4586
5057
  await adapter.start?.(runtime);
4587
- liveEvents = await connectRigServerEvents(options.projectRoot, {
5058
+ connectRigServerEvents(options.projectRoot, {
4588
5059
  onSnapshotInvalidated: () => refreshCurrentDataScene(),
4589
5060
  onRunLogAppended: () => {
4590
5061
  const scene = store.getState().scene;
@@ -4592,11 +5063,17 @@ async function launchRigOpenTuiApp(options) {
4592
5063
  refreshCurrentDataScene();
4593
5064
  },
4594
5065
  onStatus: (status) => store.patch({ footer: { live: liveLinkLabel(status) } })
4595
- }).catch(() => null);
4596
- if (!liveEvents)
4597
- store.patch({ footer: { live: liveLinkLabel("disconnected") } });
4598
- if (liveEvents)
5066
+ }).then((subscription) => {
5067
+ if (destroyed) {
5068
+ subscription.close();
5069
+ return;
5070
+ }
5071
+ liveEvents = subscription;
4599
5072
  resources.add(() => liveEvents?.close());
5073
+ }).catch(() => {
5074
+ if (!destroyed)
5075
+ store.patch({ footer: { live: liveLinkLabel("disconnected") } });
5076
+ });
4600
5077
  await runtime.runIntent(store.getState().intent);
4601
5078
  } catch (error) {
4602
5079
  const normalized = normalizeError(error);