@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
@@ -270,12 +270,28 @@ function readRepoConnection(projectRoot) {
270
270
  selected,
271
271
  project: typeof record.project === "string" ? record.project : undefined,
272
272
  linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
273
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
273
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
274
+ serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
275
+ serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
274
276
  };
275
277
  }
276
278
  function writeRepoConnection(projectRoot, state) {
277
279
  writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
278
280
  }
281
+ function rootAllowedForSelection(repo, connection) {
282
+ const root = repo.serverProjectRoot?.trim();
283
+ if (!root)
284
+ return;
285
+ if (connection.kind === "remote") {
286
+ if (repo.serverProjectRootAlias !== repo.selected)
287
+ return;
288
+ if (repo.serverProjectRootBaseUrl !== connection.baseUrl)
289
+ return;
290
+ } else if (repo.serverProjectRootAlias && repo.serverProjectRootAlias !== repo.selected) {
291
+ return;
292
+ }
293
+ return root;
294
+ }
279
295
  function resolveSelectedConnection(projectRoot, options = {}) {
280
296
  const repo = readRepoConnection(projectRoot);
281
297
  if (!repo)
@@ -287,13 +303,41 @@ function resolveSelectedConnection(projectRoot, options = {}) {
287
303
  if (!connection) {
288
304
  throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
289
305
  }
290
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
306
+ return { alias: repo.selected, connection, serverProjectRoot: rootAllowedForSelection(repo, connection) };
307
+ }
308
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot, metadata = {}) {
309
+ const repo = readRepoConnection(projectRoot);
310
+ if (!repo)
311
+ return;
312
+ let inferred = metadata;
313
+ if (!inferred.alias || !inferred.baseUrl) {
314
+ try {
315
+ const selected = resolveSelectedConnection(projectRoot);
316
+ if (selected?.connection.kind === "remote") {
317
+ inferred = {
318
+ alias: inferred.alias ?? selected.alias,
319
+ baseUrl: inferred.baseUrl ?? selected.connection.baseUrl
320
+ };
321
+ }
322
+ } catch {}
323
+ }
324
+ writeRepoConnection(projectRoot, {
325
+ ...repo,
326
+ ...metadata.project ? { project: metadata.project } : {},
327
+ serverProjectRoot,
328
+ ...inferred.alias ? { serverProjectRootAlias: inferred.alias } : {},
329
+ ...inferred.baseUrl ? { serverProjectRootBaseUrl: inferred.baseUrl.replace(/\/+$/, "") } : {}
330
+ });
291
331
  }
292
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
332
+ function clearRepoServerProjectRoot(projectRoot) {
293
333
  const repo = readRepoConnection(projectRoot);
294
334
  if (!repo)
295
335
  return;
296
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
336
+ writeRepoConnection(projectRoot, {
337
+ selected: repo.selected,
338
+ ...repo.project ? { project: repo.project } : {},
339
+ ...repo.linkedAt ? { linkedAt: repo.linkedAt } : {}
340
+ });
297
341
  }
298
342
 
299
343
  // packages/cli/src/commands/_cli-format.ts
@@ -350,137 +394,26 @@ function formatConnectionList(connections) {
350
394
  return [formatSection("Rig servers", `${rows.length} available`), `${pc.bold(pad("ALIAS", aliasWidth))} ${pc.bold("KIND")} ${pc.bold("TARGET")}`, ...lines, "", ...formatNextSteps(["Select one: `rig server use <alias|local>`"])].join(`
351
395
  `);
352
396
  }
353
- function formatConnectionStatus(selected, connections) {
397
+ function formatConnectionStatus(selected, connections, repo, remoteProjectLink) {
354
398
  const connection = selected === "local" ? { kind: "local", mode: "auto" } : connections[selected];
355
399
  const target = !connection ? "not configured" : connection.kind === "remote" ? connection.baseUrl : "local";
400
+ const rootLabel = remoteProjectLink ? remoteProjectLink.ok ? `ready \xB7 ${remoteProjectLink.serverProjectRoot ?? repo?.serverProjectRoot ?? "linked"}` : `${remoteProjectLink.status ?? "needs repair"} \xB7 ${remoteProjectLink.hint ?? remoteProjectLink.message ?? "run rig server repair-link"}` : repo?.serverProjectRoot ? repo.serverProjectRoot : "not required";
356
401
  return [
357
402
  formatSection("Rig server", "selected for this repo"),
358
403
  `${themeFaint("\u2502")} ${themeDim("selected ")} ${pc.bold(selected)}`,
359
404
  `${themeFaint("\u2502")} ${themeDim("kind ")} ${formatStatusPill(connection?.kind ?? "unknown")}`,
360
405
  `${themeFaint("\u2502")} ${themeDim("target ")} ${target ?? "not configured"}`,
406
+ ...repo?.project ? [`${themeFaint("\u2502")} ${themeDim("project ")} ${repo.project}`] : [],
407
+ ...connection?.kind === "remote" ? [`${themeFaint("\u2502")} ${themeDim("root ")} ${rootLabel}`] : [],
361
408
  "",
362
- ...formatNextSteps(["Change: `rig server use <alias|local>`", "List saved servers: `rig server list`"])
409
+ ...formatNextSteps(remoteProjectLink && !remoteProjectLink.ok ? ["Repair remote link: `rig server repair-link`", "Authenticate first if needed: `rig github auth import-gh`"] : ["Change: `rig server use <alias|local>`", "List saved servers: `rig server list`"])
363
410
  ].join(`
364
411
  `);
365
412
  }
366
413
 
367
- // packages/cli/src/commands/connect.ts
368
- function usageName(options) {
369
- return `rig ${options.group}`;
370
- }
371
- function parseConnection(alias, value, options) {
372
- if (alias === "local" && !value)
373
- return { kind: "local", mode: "auto" };
374
- if (!value)
375
- throw new CliError(`Missing remote server URL. Usage: ${usageName(options)} add <alias> <url>`, 1);
376
- let parsed;
377
- try {
378
- parsed = new URL(value);
379
- } catch {
380
- throw new CliError(`Invalid Rig server URL: ${value}`, 1, { hint: "Pass a full http(s) URL, e.g. `rig server add prod https://rig.example.com`." });
381
- }
382
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
383
- throw new CliError("Rig remote server URL must be http(s).", 1, { hint: "Use an http:// or https:// URL, e.g. `rig server add prod https://rig.example.com`." });
384
- }
385
- return { kind: "remote", baseUrl: parsed.toString().replace(/\/+$/, "") };
386
- }
387
- function printJsonOrText(context, payload, text) {
388
- if (context.outputMode === "json") {
389
- console.log(JSON.stringify(payload, null, 2));
390
- } else {
391
- console.log(text);
392
- }
393
- }
394
- async function promptForConnectionAlias(context) {
395
- const state = readGlobalConnections();
396
- const repo = readRepoConnection(context.projectRoot);
397
- const options = [
398
- { value: "local", label: "local", hint: "Use/start a local Rig server" },
399
- ...Object.entries(state.connections).map(([alias, connection]) => ({
400
- value: alias,
401
- label: alias,
402
- hint: connection.kind === "remote" ? connection.baseUrl : "local"
403
- }))
404
- ].filter((option, index, all) => all.findIndex((candidate) => candidate.value === option.value) === index);
405
- const answer = await droneSelect({
406
- message: "Select Rig server for this repo",
407
- initialValue: repo?.selected ?? "local",
408
- options
409
- });
410
- if (answer === null) {
411
- droneCancel("No server selected.");
412
- throw new CliError("No server selected.", 3);
413
- }
414
- return String(answer);
415
- }
416
- async function executeConnectionCommand(context, args, options) {
417
- const [command, ...rest] = args;
418
- switch (command ?? "status") {
419
- case "list": {
420
- requireNoExtraArgs(rest, `${usageName(options)} list`);
421
- const state = readGlobalConnections();
422
- printJsonOrText(context, state, formatConnectionList(state.connections));
423
- return { ok: true, group: options.group, command: "list", details: state };
424
- }
425
- case "add": {
426
- const [alias, url, ...extra] = rest;
427
- if (!alias)
428
- throw new CliError(`Missing alias. Usage: ${usageName(options)} add <alias> <url>`, 1);
429
- requireNoExtraArgs(extra, `${usageName(options)} add <alias> <url>`);
430
- const connection = parseConnection(alias, url, options);
431
- const state = upsertGlobalConnection(alias, connection);
432
- printJsonOrText(context, { alias, connection }, formatSuccessCard("Rig server saved", [
433
- ["alias", alias],
434
- ["target", connection.kind === "remote" ? connection.baseUrl : "local"],
435
- ["next", `${usageName(options)} use ${alias}`]
436
- ]));
437
- return { ok: true, group: options.group, command: "add", details: { alias, connection, count: Object.keys(state.connections).length } };
438
- }
439
- case "use": {
440
- let [alias, ...extra] = rest;
441
- requireNoExtraArgs(extra, `${usageName(options)} use <alias|local>`);
442
- if (!alias && options.interactiveUse && context.outputMode === "text" && process.stdin.isTTY) {
443
- alias = await promptForConnectionAlias(context);
444
- }
445
- if (!alias)
446
- throw new CliError(`Missing alias. Usage: ${usageName(options)} use <alias|local>`, 1);
447
- if (alias !== "local") {
448
- const state = readGlobalConnections();
449
- if (!state.connections[alias])
450
- throw new CliError(`Unknown Rig server: ${alias}`, 1, { hint: "Run `rig server list` to see saved aliases, or save one with `rig server add <alias> <url>`." });
451
- }
452
- const previousRepo = readRepoConnection(context.projectRoot);
453
- const repoState = {
454
- selected: alias,
455
- ...previousRepo?.project ? { project: previousRepo.project } : {},
456
- linkedAt: new Date().toISOString(),
457
- ...previousRepo?.serverProjectRoot && previousRepo.selected === alias ? { serverProjectRoot: previousRepo.serverProjectRoot } : {}
458
- };
459
- writeRepoConnection(context.projectRoot, repoState);
460
- printJsonOrText(context, repoState, formatSuccessCard("Rig server selected", [
461
- ["selected", alias],
462
- ["scope", "this repo"],
463
- ["next", "rig task list"]
464
- ]));
465
- return { ok: true, group: options.group, command: "use", details: repoState };
466
- }
467
- case "status": {
468
- requireNoExtraArgs(rest, `${usageName(options)} status`);
469
- const repo = readRepoConnection(context.projectRoot);
470
- const global = readGlobalConnections();
471
- const details = { selected: repo?.selected ?? "local", repo, connections: global.connections };
472
- printJsonOrText(context, details, formatConnectionStatus(details.selected, global.connections));
473
- return { ok: true, group: options.group, command: "status", details };
474
- }
475
- default:
476
- throw new CliError(`Unknown ${options.group} command: ${String(command)}
477
- Usage: ${usageName(options)} <list|add|use|status>`, 1);
478
- }
479
- }
480
-
481
414
  // packages/cli/src/commands/_server-client.ts
482
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
483
- import { resolve as resolve2 } from "path";
415
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
416
+ import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
484
417
  import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
485
418
  var scopedGitHubBearerTokens = new Map;
486
419
  var serverPhaseListener = null;
@@ -519,11 +452,10 @@ function readStoredGitHubAuthToken(projectRoot) {
519
452
  const parsed = readRemoteAuthState(projectRoot);
520
453
  return parsed ? cleanToken(typeof parsed.token === "string" ? parsed.token : undefined) : null;
521
454
  }
522
- function inferRemoteServerProjectRootFromAuthState(projectRoot) {
523
- const repo = readRepoConnection(projectRoot);
524
- const slug = repo?.project?.trim();
525
- if (!slug || !/^[^/]+\/[^/]+$/.test(slug))
455
+ function inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug) {
456
+ if (!/^[^/]+\/[^/]+$/.test(repoSlug))
526
457
  return null;
458
+ const repo = readRepoConnection(projectRoot);
527
459
  const auth = readRemoteAuthState(projectRoot);
528
460
  const authUpdatedAt = typeof auth?.updatedAt === "string" ? Date.parse(auth.updatedAt) : Number.NaN;
529
461
  const repoLinkedAt = typeof repo?.linkedAt === "string" ? Date.parse(repo.linkedAt) : Number.NaN;
@@ -532,25 +464,419 @@ function inferRemoteServerProjectRootFromAuthState(projectRoot) {
532
464
  const checkoutBaseDir = typeof auth?.checkoutBaseDir === "string" && auth.checkoutBaseDir.trim() ? auth.checkoutBaseDir.trim() : null;
533
465
  if (!checkoutBaseDir)
534
466
  return null;
535
- const inferred = `${checkoutBaseDir.replace(/\/+$/, "")}/${slug}`;
536
- writeRepoServerProjectRoot(projectRoot, inferred);
537
- return inferred;
467
+ return `${checkoutBaseDir.replace(/\/+$/, "")}/${repoSlug}`;
538
468
  }
539
469
  function readLocalConnectionFallbackToken(projectRoot) {
540
470
  return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
541
471
  }
472
+ function normalizeRepoSlug(value) {
473
+ const slug = value?.trim();
474
+ return slug && /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
475
+ }
476
+ function readProjectLinkSlug(projectRoot) {
477
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
478
+ if (!existsSync2(path))
479
+ return null;
480
+ try {
481
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
482
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
483
+ return null;
484
+ return normalizeRepoSlug(typeof parsed.repoSlug === "string" ? String(parsed.repoSlug) : null);
485
+ } catch {
486
+ return null;
487
+ }
488
+ }
489
+ function writeProjectLinkConnection(projectRoot, repoSlug, alias) {
490
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
491
+ mkdirSync2(dirname2(path), { recursive: true });
492
+ writeFileSync2(path, `${JSON.stringify({ repoSlug, connection: alias, linkedAt: new Date().toISOString() }, null, 2)}
493
+ `, "utf8");
494
+ }
495
+ function remoteLinkRepairCommand(repoSlug) {
496
+ return repoSlug ? `rig server repair-link --repo ${repoSlug}` : "rig server repair-link --repo owner/repo";
497
+ }
498
+ function formatRemoteProjectLinkHint(resolution) {
499
+ const repair = remoteLinkRepairCommand(resolution.repoSlug);
500
+ if (resolution.status === "auth_required") {
501
+ 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}` : ""}\`.`;
502
+ }
503
+ if (resolution.status === "missing_project") {
504
+ return `Record the repo slug, then run \`${repair}\` (or \`rig init --repo owner/repo --server remote --github-auth device\`).`;
505
+ }
506
+ if (resolution.status === "not_remote")
507
+ return "Select a remote server with `rig server use <alias>` before repairing a remote project link.";
508
+ return `Run \`${repair}\` to backfill or prepare a server-host checkout for the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}.`;
509
+ }
510
+ function remoteProjectLinkFailure(input) {
511
+ const partial = {
512
+ status: input.status,
513
+ alias: input.alias,
514
+ baseUrl: input.baseUrl,
515
+ repoSlug: input.repoSlug
516
+ };
517
+ return {
518
+ ok: false,
519
+ ...input,
520
+ hint: formatRemoteProjectLinkHint(partial),
521
+ next: remoteLinkRepairCommand(input.repoSlug)
522
+ };
523
+ }
524
+ function remoteProjectLinkSuccess(input) {
525
+ return {
526
+ ok: true,
527
+ status: input.status,
528
+ alias: input.alias,
529
+ baseUrl: input.baseUrl,
530
+ repoSlug: input.repoSlug,
531
+ serverProjectRoot: input.serverProjectRoot,
532
+ source: input.source,
533
+ prepared: input.prepared ?? input.status === "prepared",
534
+ validated: input.validated ?? false,
535
+ message: input.message ?? `Remote project link ready for ${input.repoSlug}.`,
536
+ hint: "Remote-scoped task/run/status requests will send x-rig-project-root for this server-host checkout.",
537
+ next: "rig task list"
538
+ };
539
+ }
540
+ function localCheckoutPathCandidate(projectRoot, candidate) {
541
+ try {
542
+ const local = resolve2(projectRoot);
543
+ const resolved = resolve2(candidate);
544
+ return resolved === local || resolved.startsWith(`${local}/`);
545
+ } catch {
546
+ return false;
547
+ }
548
+ }
549
+ async function requestRemoteProjectLinkJson(baseUrl, pathname, authToken, init = {}) {
550
+ const requestUrl = new URL(`${baseUrl}${pathname}`);
551
+ if (authToken && queryAuthFallbackEnabled())
552
+ requestUrl.searchParams.set("rt", authToken);
553
+ const response = await fetch(requestUrl, {
554
+ ...init,
555
+ headers: mergeHeaders(init.headers, authToken)
556
+ });
557
+ const text = await response.text();
558
+ const payload = text.trim().length > 0 ? (() => {
559
+ try {
560
+ return JSON.parse(text);
561
+ } catch {
562
+ return null;
563
+ }
564
+ })() : null;
565
+ return { ok: response.ok, status: response.status, payload, text };
566
+ }
567
+ function payloadError(payload, fallback) {
568
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
569
+ const record = payload;
570
+ const value = record.error ?? record.message ?? record.reason;
571
+ if (typeof value === "string" && value.trim())
572
+ return value.trim();
573
+ }
574
+ return fallback;
575
+ }
576
+ function checkoutPathsFromProjectPayload(payload) {
577
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
578
+ return [];
579
+ const project = payload.project;
580
+ if (!project || typeof project !== "object" || Array.isArray(project))
581
+ return [];
582
+ const checkouts = project.checkouts;
583
+ if (!Array.isArray(checkouts))
584
+ return [];
585
+ return [...checkouts].reverse().flatMap((entry) => {
586
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
587
+ return [];
588
+ const path = entry.path;
589
+ return typeof path === "string" && path.trim() ? [path.trim()] : [];
590
+ });
591
+ }
592
+ function checkoutPathFromPreparePayload(payload) {
593
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
594
+ return null;
595
+ const checkout = payload.checkout;
596
+ if (!checkout || typeof checkout !== "object" || Array.isArray(checkout))
597
+ return null;
598
+ const path = checkout.path;
599
+ return typeof path === "string" && path.trim() ? path.trim() : null;
600
+ }
601
+ async function validateAndPersistRemoteRoot(input) {
602
+ const candidate = input.candidate.trim();
603
+ if (!candidate || !isAbsolute(candidate)) {
604
+ return remoteProjectLinkFailure({
605
+ status: "invalid_root",
606
+ alias: input.alias,
607
+ baseUrl: input.baseUrl,
608
+ repoSlug: input.repoSlug,
609
+ message: `Remote project root candidate is not an absolute server-host path: ${candidate || "(empty)"}.`
610
+ });
611
+ }
612
+ if (localCheckoutPathCandidate(input.projectRoot, candidate)) {
613
+ return remoteProjectLinkFailure({
614
+ status: "invalid_root",
615
+ alias: input.alias,
616
+ baseUrl: input.baseUrl,
617
+ repoSlug: input.repoSlug,
618
+ message: `Refusing to use local checkout path ${candidate} as a remote server project root.`
619
+ });
620
+ }
621
+ let response;
622
+ try {
623
+ response = await requestRemoteProjectLinkJson(input.baseUrl, "/api/server/project-root", input.authToken, {
624
+ method: "POST",
625
+ headers: { "content-type": "application/json" },
626
+ body: JSON.stringify({ projectRoot: candidate })
627
+ });
628
+ } catch (error) {
629
+ return remoteProjectLinkFailure({
630
+ status: "error",
631
+ alias: input.alias,
632
+ baseUrl: input.baseUrl,
633
+ repoSlug: input.repoSlug,
634
+ message: `Could not validate remote project root ${candidate}: ${error instanceof Error ? error.message : String(error)}`
635
+ });
636
+ }
637
+ if (response.status === 401 || response.status === 403) {
638
+ return remoteProjectLinkFailure({
639
+ status: "auth_required",
640
+ alias: input.alias,
641
+ baseUrl: input.baseUrl,
642
+ repoSlug: input.repoSlug,
643
+ statusCode: response.status,
644
+ message: `Remote server ${input.alias} requires authentication before validating project root ${candidate}.`
645
+ });
646
+ }
647
+ if (!response.ok) {
648
+ return remoteProjectLinkFailure({
649
+ status: "invalid_root",
650
+ alias: input.alias,
651
+ baseUrl: input.baseUrl,
652
+ repoSlug: input.repoSlug,
653
+ statusCode: response.status,
654
+ message: `Remote server rejected project root ${candidate} (${response.status}): ${payloadError(response.payload, response.text || "project-root validation failed")}`
655
+ });
656
+ }
657
+ const record = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload) ? response.payload : {};
658
+ if (record.ok !== true) {
659
+ return remoteProjectLinkFailure({
660
+ status: "invalid_root",
661
+ alias: input.alias,
662
+ baseUrl: input.baseUrl,
663
+ repoSlug: input.repoSlug,
664
+ message: `Remote server did not accept project root ${candidate}: ${payloadError(response.payload, "project-root validation failed")}`
665
+ });
666
+ }
667
+ const accepted = typeof record.projectRoot === "string" && record.projectRoot.trim() ? record.projectRoot.trim() : typeof record.requestedProjectRoot === "string" && record.requestedProjectRoot.trim() ? record.requestedProjectRoot.trim() : candidate;
668
+ writeRepoServerProjectRoot(input.projectRoot, accepted, { alias: input.alias, baseUrl: input.baseUrl, project: input.repoSlug });
669
+ writeProjectLinkConnection(input.projectRoot, input.repoSlug, input.alias);
670
+ const status = input.status ?? (input.prepared ? "prepared" : "backfilled");
671
+ return remoteProjectLinkSuccess({
672
+ status,
673
+ alias: input.alias,
674
+ baseUrl: input.baseUrl,
675
+ repoSlug: input.repoSlug,
676
+ serverProjectRoot: accepted,
677
+ source: input.source,
678
+ prepared: input.prepared,
679
+ validated: true,
680
+ 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}.`
681
+ });
682
+ }
683
+ async function ensureRemoteProjectRootLink(projectRoot, options = {}) {
684
+ let selected;
685
+ try {
686
+ selected = resolveSelectedConnection(projectRoot);
687
+ } catch (error) {
688
+ return remoteProjectLinkFailure({ status: "error", message: error instanceof Error ? error.message : String(error) });
689
+ }
690
+ if (!selected || selected.connection.kind !== "remote") {
691
+ return remoteProjectLinkFailure({ status: "not_remote", message: "No remote Rig server is selected for this repo." });
692
+ }
693
+ const repo = readRepoConnection(projectRoot);
694
+ const explicitRepoRequested = options.repoSlug !== undefined;
695
+ const explicitRepoSlug = explicitRepoRequested ? normalizeRepoSlug(options.repoSlug) : null;
696
+ const repoProjectSlug = normalizeRepoSlug(repo?.project);
697
+ const repoSlug = explicitRepoSlug ?? repoProjectSlug ?? readProjectLinkSlug(projectRoot);
698
+ const alias = selected.alias;
699
+ const baseUrl = selected.connection.baseUrl;
700
+ const authToken = options.authToken === undefined ? readGitHubBearerTokenForRemote(projectRoot) : options.authToken;
701
+ const mode = options.mode ?? "backfill-only";
702
+ if (explicitRepoRequested && !explicitRepoSlug) {
703
+ return remoteProjectLinkFailure({
704
+ status: "missing_project",
705
+ alias,
706
+ baseUrl,
707
+ message: `Invalid --repo value ${JSON.stringify(options.repoSlug)}. Expected owner/repo.`
708
+ });
709
+ }
710
+ if (!repoSlug) {
711
+ return remoteProjectLinkFailure({
712
+ status: "missing_project",
713
+ alias,
714
+ baseUrl,
715
+ message: `Remote server ${alias} is selected, but this checkout has no GitHub repo slug recorded.`
716
+ });
717
+ }
718
+ const skippedCandidates = [];
719
+ const storedRoot = selected.serverProjectRoot?.trim() || null;
720
+ const storedRootMatchesResolvedRepo = repoProjectSlug === repoSlug;
721
+ if (storedRoot && storedRootMatchesResolvedRepo) {
722
+ if (localCheckoutPathCandidate(projectRoot, storedRoot)) {
723
+ clearRepoServerProjectRoot(projectRoot);
724
+ skippedCandidates.push(storedRoot);
725
+ } else {
726
+ const storedResult = await validateAndPersistRemoteRoot({
727
+ projectRoot,
728
+ alias,
729
+ baseUrl,
730
+ authToken,
731
+ repoSlug,
732
+ candidate: storedRoot,
733
+ source: "stored",
734
+ status: "ready"
735
+ });
736
+ if (storedResult.ok || storedResult.status === "auth_required" || storedResult.status === "error")
737
+ return storedResult;
738
+ clearRepoServerProjectRoot(projectRoot);
739
+ skippedCandidates.push(storedRoot);
740
+ }
741
+ } else if (storedRoot) {
742
+ skippedCandidates.push(storedRoot);
743
+ }
744
+ const authCandidate = inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug);
745
+ if (authCandidate) {
746
+ const authResult = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: authCandidate, source: "auth-state" });
747
+ if (authResult.ok || authResult.status === "auth_required")
748
+ return authResult;
749
+ }
750
+ let registryResponse;
751
+ try {
752
+ registryResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}`, authToken);
753
+ } catch (error) {
754
+ return remoteProjectLinkFailure({
755
+ status: "error",
756
+ alias,
757
+ baseUrl,
758
+ repoSlug,
759
+ message: `Could not read remote project registry for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
760
+ });
761
+ }
762
+ if (registryResponse.status === 401 || registryResponse.status === 403) {
763
+ return remoteProjectLinkFailure({
764
+ status: "auth_required",
765
+ alias,
766
+ baseUrl,
767
+ repoSlug,
768
+ statusCode: registryResponse.status,
769
+ message: `Remote server ${alias} requires authentication before reading the ${repoSlug} project registry.`
770
+ });
771
+ }
772
+ if (registryResponse.ok) {
773
+ const candidates = checkoutPathsFromProjectPayload(registryResponse.payload);
774
+ for (const candidate of candidates) {
775
+ const result = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate, source: "registry" });
776
+ if (result.ok || result.status === "auth_required")
777
+ return result;
778
+ skippedCandidates.push(candidate);
779
+ }
780
+ if (mode === "backfill-only") {
781
+ return remoteProjectLinkFailure({
782
+ status: candidates.length > 0 ? "invalid_root" : "no_server_checkout",
783
+ alias,
784
+ baseUrl,
785
+ repoSlug,
786
+ 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.`,
787
+ skippedCandidates
788
+ });
789
+ }
790
+ } else if (registryResponse.status === 404) {
791
+ if (mode === "backfill-only") {
792
+ return remoteProjectLinkFailure({
793
+ status: "project_not_registered",
794
+ alias,
795
+ baseUrl,
796
+ repoSlug,
797
+ statusCode: registryResponse.status,
798
+ message: `Remote server ${alias} has no registered project record for ${repoSlug}.`
799
+ });
800
+ }
801
+ } else {
802
+ return remoteProjectLinkFailure({
803
+ status: "error",
804
+ alias,
805
+ baseUrl,
806
+ repoSlug,
807
+ statusCode: registryResponse.status,
808
+ message: `Could not backfill ${repoSlug} from remote registry (${registryResponse.status}): ${payloadError(registryResponse.payload, registryResponse.text || "registry lookup failed")}`,
809
+ skippedCandidates
810
+ });
811
+ }
812
+ let prepareResponse;
813
+ try {
814
+ prepareResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}/prepare-checkout`, authToken, {
815
+ method: "POST",
816
+ headers: { "content-type": "application/json" },
817
+ body: JSON.stringify({ checkout: { kind: "managed-clone" }, repoUrl: `https://github.com/${repoSlug}.git` })
818
+ });
819
+ } catch (error) {
820
+ return remoteProjectLinkFailure({
821
+ status: "error",
822
+ alias,
823
+ baseUrl,
824
+ repoSlug,
825
+ message: `Could not prepare remote checkout for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
826
+ });
827
+ }
828
+ if (prepareResponse.status === 401 || prepareResponse.status === 403) {
829
+ return remoteProjectLinkFailure({
830
+ status: "auth_required",
831
+ alias,
832
+ baseUrl,
833
+ repoSlug,
834
+ statusCode: prepareResponse.status,
835
+ message: `Remote server ${alias} requires authentication before preparing ${repoSlug}.`
836
+ });
837
+ }
838
+ if (!prepareResponse.ok) {
839
+ return remoteProjectLinkFailure({
840
+ status: "error",
841
+ alias,
842
+ baseUrl,
843
+ repoSlug,
844
+ statusCode: prepareResponse.status,
845
+ message: `Remote checkout prepare failed for ${repoSlug} (${prepareResponse.status}): ${payloadError(prepareResponse.payload, prepareResponse.text || "prepare-checkout failed")}`,
846
+ skippedCandidates
847
+ });
848
+ }
849
+ const preparedPath = checkoutPathFromPreparePayload(prepareResponse.payload);
850
+ if (!preparedPath) {
851
+ return remoteProjectLinkFailure({
852
+ status: "invalid_root",
853
+ alias,
854
+ baseUrl,
855
+ repoSlug,
856
+ message: `Remote checkout prepare for ${repoSlug} did not return a checkout.path.`,
857
+ skippedCandidates
858
+ });
859
+ }
860
+ return validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: preparedPath, source: "prepare", prepared: true });
861
+ }
862
+ async function repairRemoteProjectRootLink(context, options = {}) {
863
+ const resolution = await ensureRemoteProjectRootLink(context.projectRoot, { mode: options.mode ?? "prepare-if-missing", repoSlug: options.repoSlug });
864
+ if (!resolution.ok)
865
+ throw new CliError(resolution.message, 1, { hint: resolution.hint });
866
+ return resolution;
867
+ }
542
868
  async function ensureServerForCli(projectRoot) {
543
869
  try {
544
870
  const selected = resolveSelectedConnection(projectRoot);
545
871
  if (selected?.connection.kind === "remote") {
546
872
  reportServerPhase(`Connecting to ${selected.alias}\u2026`);
547
873
  const authToken = readGitHubBearerTokenForRemote(projectRoot);
548
- const serverProjectRoot = selected.serverProjectRoot ?? inferRemoteServerProjectRootFromAuthState(projectRoot) ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
874
+ const link = await ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only", authToken });
549
875
  return {
550
876
  baseUrl: selected.connection.baseUrl,
551
877
  authToken,
552
878
  connectionKind: "remote",
553
- serverProjectRoot
879
+ serverProjectRoot: link.ok ? link.serverProjectRoot ?? null : null
554
880
  };
555
881
  }
556
882
  reportServerPhase("Starting local Rig server\u2026");
@@ -568,32 +894,6 @@ async function ensureServerForCli(projectRoot) {
568
894
  throw error;
569
895
  }
570
896
  }
571
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
572
- const repo = readRepoConnection(projectRoot);
573
- const slug = repo?.project?.trim();
574
- if (!slug)
575
- return null;
576
- try {
577
- const url = new URL(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`);
578
- if (authToken && queryAuthFallbackEnabled())
579
- url.searchParams.set("rt", authToken);
580
- const response = await fetch(url, {
581
- headers: mergeHeaders(undefined, authToken)
582
- });
583
- if (!response.ok)
584
- return null;
585
- const payload = await response.json();
586
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
587
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
588
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
589
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
590
- if (path)
591
- writeRepoServerProjectRoot(projectRoot, path);
592
- return path;
593
- } catch {
594
- return null;
595
- }
596
- }
597
897
  function mergeCookie(existing, name, value) {
598
898
  const encoded = `${name}=${encodeURIComponent(value)}`;
599
899
  if (!existing?.trim())
@@ -685,13 +985,20 @@ function canUseRemoteWithoutProjectRoot(pathname) {
685
985
  async function requestServerJson(context, pathname, init = {}) {
686
986
  const server = await ensureServerForCli(context.projectRoot);
687
987
  const requestUrl = new URL(`${server.baseUrl}${pathname}`);
688
- if (server.connectionKind === "remote" && !server.serverProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
689
- const repo = readRepoConnection(context.projectRoot);
690
- throw new CliError(`Remote server is selected for ${repo?.project ?? "this repo"}, but this checkout has no server-host project root link.`, 1, { hint: "Run `rig init --repair` or `rig init --yes --repo owner/repo --server remote` to repair the remote project link before task/run commands." });
988
+ let scopedServerProjectRoot = server.serverProjectRoot;
989
+ if (server.connectionKind === "remote" && !scopedServerProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
990
+ const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: server.authToken });
991
+ if (link.ok && link.serverProjectRoot) {
992
+ scopedServerProjectRoot = link.serverProjectRoot;
993
+ } else {
994
+ const repo = readRepoConnection(context.projectRoot);
995
+ const target = link.alias && link.baseUrl ? `${link.alias} (${link.baseUrl})` : server.baseUrl;
996
+ throw new CliError(`Remote server ${target} is selected for ${link.repoSlug ?? repo?.project ?? "this repo"}, but this checkout has no server-host project root link. ${link.message}`, 1, { hint: link.hint });
997
+ }
691
998
  }
692
999
  const headers = mergeHeaders(init.headers, server.authToken);
693
- if (server.serverProjectRoot)
694
- headers.set("x-rig-project-root", server.serverProjectRoot);
1000
+ if (scopedServerProjectRoot)
1001
+ headers.set("x-rig-project-root", scopedServerProjectRoot);
695
1002
  if (server.connectionKind === "remote" && server.authToken && queryAuthFallbackEnabled()) {
696
1003
  requestUrl.searchParams.set("rt", server.authToken);
697
1004
  }
@@ -769,10 +1076,187 @@ async function submitTaskRunViaServer(context, input) {
769
1076
  return { runId };
770
1077
  }
771
1078
 
1079
+ // packages/cli/src/commands/connect.ts
1080
+ function usageName(options) {
1081
+ return `rig ${options.group}`;
1082
+ }
1083
+ function parseConnection(alias, value, options) {
1084
+ if (alias === "local" && !value)
1085
+ return { kind: "local", mode: "auto" };
1086
+ if (!value)
1087
+ throw new CliError(`Missing remote server URL. Usage: ${usageName(options)} add <alias> <url>`, 1);
1088
+ let parsed;
1089
+ try {
1090
+ parsed = new URL(value);
1091
+ } catch {
1092
+ throw new CliError(`Invalid Rig server URL: ${value}`, 1, { hint: "Pass a full http(s) URL, e.g. `rig server add prod https://rig.example.com`." });
1093
+ }
1094
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
1095
+ throw new CliError("Rig remote server URL must be http(s).", 1, { hint: "Use an http:// or https:// URL, e.g. `rig server add prod https://rig.example.com`." });
1096
+ }
1097
+ return { kind: "remote", baseUrl: parsed.toString().replace(/\/+$/, "") };
1098
+ }
1099
+ function printJsonOrText(context, _payload, text) {
1100
+ if (context.outputMode !== "json") {
1101
+ console.log(text);
1102
+ }
1103
+ }
1104
+ function formatRemoteProjectLinkText(result) {
1105
+ return formatSuccessCard(result.ok ? "Remote project link ready" : "Remote project link needs repair", [
1106
+ ["selected", result.alias ?? "remote"],
1107
+ ["target", result.baseUrl ?? "unknown"],
1108
+ ["repo", result.repoSlug ?? "owner/repo"],
1109
+ ["status", result.status],
1110
+ ...result.serverProjectRoot ? [["server root", result.serverProjectRoot]] : [],
1111
+ ["next", result.ok ? result.next ?? "rig task list" : result.hint]
1112
+ ]);
1113
+ }
1114
+ function parseRepairLinkArgs(rest, usage) {
1115
+ let repoSlug;
1116
+ let mode = "prepare-if-missing";
1117
+ const pending = [...rest];
1118
+ while (pending.length > 0) {
1119
+ const token = pending.shift();
1120
+ if (token === "--repo") {
1121
+ const value = pending.shift()?.trim();
1122
+ if (!value)
1123
+ throw new CliError(`Missing --repo value. Usage: ${usage}`, 1);
1124
+ const normalized = normalizeRepoSlug(value);
1125
+ if (!normalized)
1126
+ throw new CliError(`Invalid --repo value: ${value}`, 1, { hint: "Use the canonical owner/repo slug, e.g. `--repo humanity-org/humanwork`." });
1127
+ repoSlug = normalized;
1128
+ } else if (token === "--backfill-only") {
1129
+ mode = "backfill-only";
1130
+ } else if (token === "--prepare") {
1131
+ mode = "prepare-if-missing";
1132
+ } else {
1133
+ throw new CliError(`Unexpected argument: ${String(token)}
1134
+ Usage: ${usage}`, 1);
1135
+ }
1136
+ }
1137
+ return { repoSlug, mode };
1138
+ }
1139
+ async function promptForConnectionAlias(context) {
1140
+ const state = readGlobalConnections();
1141
+ const repo = readRepoConnection(context.projectRoot);
1142
+ const options = [
1143
+ { value: "local", label: "local", hint: "Use/start a local Rig server" },
1144
+ ...Object.entries(state.connections).map(([alias, connection]) => ({
1145
+ value: alias,
1146
+ label: alias,
1147
+ hint: connection.kind === "remote" ? connection.baseUrl : "local"
1148
+ }))
1149
+ ].filter((option, index, all) => all.findIndex((candidate) => candidate.value === option.value) === index);
1150
+ const answer = await droneSelect({
1151
+ message: "Select Rig server for this repo",
1152
+ initialValue: repo?.selected ?? "local",
1153
+ options
1154
+ });
1155
+ if (answer === null) {
1156
+ droneCancel("No server selected.");
1157
+ throw new CliError("No server selected.", 3);
1158
+ }
1159
+ return String(answer);
1160
+ }
1161
+ async function executeConnectionCommand(context, args, options) {
1162
+ const [command, ...rest] = args;
1163
+ switch (command ?? "status") {
1164
+ case "list": {
1165
+ requireNoExtraArgs(rest, `${usageName(options)} list`);
1166
+ const state = readGlobalConnections();
1167
+ printJsonOrText(context, state, formatConnectionList(state.connections));
1168
+ return { ok: true, group: options.group, command: "list", details: state };
1169
+ }
1170
+ case "add": {
1171
+ const [alias, url, ...extra] = rest;
1172
+ if (!alias)
1173
+ throw new CliError(`Missing alias. Usage: ${usageName(options)} add <alias> <url>`, 1);
1174
+ requireNoExtraArgs(extra, `${usageName(options)} add <alias> <url>`);
1175
+ const connection = parseConnection(alias, url, options);
1176
+ const state = upsertGlobalConnection(alias, connection);
1177
+ printJsonOrText(context, { alias, connection }, formatSuccessCard("Rig server saved", [
1178
+ ["alias", alias],
1179
+ ["target", connection.kind === "remote" ? connection.baseUrl : "local"],
1180
+ ["next", `${usageName(options)} use ${alias}`]
1181
+ ]));
1182
+ return { ok: true, group: options.group, command: "add", details: { alias, connection, count: Object.keys(state.connections).length } };
1183
+ }
1184
+ case "use": {
1185
+ let [alias, ...extra] = rest;
1186
+ requireNoExtraArgs(extra, `${usageName(options)} use <alias|local>`);
1187
+ if (!alias && options.interactiveUse && context.outputMode === "text" && process.stdin.isTTY) {
1188
+ alias = await promptForConnectionAlias(context);
1189
+ }
1190
+ if (!alias)
1191
+ throw new CliError(`Missing alias. Usage: ${usageName(options)} use <alias|local>`, 1);
1192
+ let selectedConnection = { kind: "local", mode: "auto" };
1193
+ if (alias !== "local") {
1194
+ const state = readGlobalConnections();
1195
+ const connection = state.connections[alias];
1196
+ if (!connection)
1197
+ throw new CliError(`Unknown Rig server: ${alias}`, 1, { hint: "Run `rig server list` to see saved aliases, or save one with `rig server add <alias> <url>`." });
1198
+ selectedConnection = connection;
1199
+ }
1200
+ const previousRepo = readRepoConnection(context.projectRoot);
1201
+ const preserveRemoteRoot = Boolean(previousRepo?.serverProjectRoot && previousRepo.selected === alias && selectedConnection.kind === "remote" && previousRepo.serverProjectRootAlias === alias && previousRepo.serverProjectRootBaseUrl === selectedConnection.baseUrl);
1202
+ const repoState = {
1203
+ selected: alias,
1204
+ ...previousRepo?.project ? { project: previousRepo.project } : {},
1205
+ linkedAt: new Date().toISOString(),
1206
+ ...preserveRemoteRoot ? {
1207
+ serverProjectRoot: previousRepo.serverProjectRoot,
1208
+ serverProjectRootAlias: previousRepo.serverProjectRootAlias,
1209
+ serverProjectRootBaseUrl: previousRepo.serverProjectRootBaseUrl
1210
+ } : {}
1211
+ };
1212
+ writeRepoConnection(context.projectRoot, repoState);
1213
+ const remoteProjectLink = alias !== "local" ? await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only" }).catch((error) => ({
1214
+ ok: false,
1215
+ status: "error",
1216
+ message: error instanceof Error ? error.message : String(error),
1217
+ hint: "Run `rig server repair-link` after authenticating the selected remote."
1218
+ })) : null;
1219
+ const latestRepo = readRepoConnection(context.projectRoot);
1220
+ const details = { selected: latestRepo?.selected ?? alias, repo: latestRepo, remoteProjectLink };
1221
+ printJsonOrText(context, details, formatSuccessCard("Rig server selected", [
1222
+ ["selected", alias],
1223
+ ["scope", "this repo"],
1224
+ ...remoteProjectLink ? [["remote link", remoteProjectLink.ok ? `ready (${remoteProjectLink.serverProjectRoot ?? "linked"})` : `${remoteProjectLink.status}: ${remoteProjectLink.hint}`]] : [],
1225
+ ["next", remoteProjectLink && !remoteProjectLink.ok ? "rig server repair-link" : "rig task list"]
1226
+ ]));
1227
+ return { ok: true, group: options.group, command: "use", details };
1228
+ }
1229
+ case "repair-link": {
1230
+ const parsed = parseRepairLinkArgs(rest, `${usageName(options)} repair-link [--prepare|--backfill-only] [--repo owner/repo]`);
1231
+ const result = await repairRemoteProjectRootLink(context, parsed);
1232
+ printJsonOrText(context, result, formatRemoteProjectLinkText(result));
1233
+ return { ok: true, group: options.group, command: "repair-link", details: result };
1234
+ }
1235
+ case "status": {
1236
+ requireNoExtraArgs(rest, `${usageName(options)} status`);
1237
+ const repo = readRepoConnection(context.projectRoot);
1238
+ const global = readGlobalConnections();
1239
+ const remoteProjectLink = repo?.selected && repo.selected !== "local" ? await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only" }).catch((error) => ({
1240
+ ok: false,
1241
+ status: "error",
1242
+ message: error instanceof Error ? error.message : String(error),
1243
+ hint: "Run `rig server repair-link` after authenticating the selected remote."
1244
+ })) : null;
1245
+ const latestRepo = readRepoConnection(context.projectRoot) ?? repo;
1246
+ const details = { selected: latestRepo?.selected ?? "local", repo: latestRepo, connections: global.connections, remoteProjectLink };
1247
+ printJsonOrText(context, details, formatConnectionStatus(details.selected, global.connections, latestRepo ?? null, remoteProjectLink));
1248
+ return { ok: true, group: options.group, command: "status", details };
1249
+ }
1250
+ default:
1251
+ throw new CliError(`Unknown ${options.group} command: ${String(command)}
1252
+ Usage: ${usageName(options)} <list|add|use|status|repair-link>`, 1);
1253
+ }
1254
+ }
1255
+
772
1256
  // packages/cli/src/commands/server.ts
773
1257
  async function executeServer(context, args, options) {
774
1258
  const [command = "status", ...rest] = args;
775
- if (["status", "list", "add", "use"].includes(command)) {
1259
+ if (["status", "list", "add", "use", "repair-link"].includes(command)) {
776
1260
  return executeConnectionCommand(context, [command, ...rest], { group: "server", interactiveUse: true });
777
1261
  }
778
1262
  switch (command) {