@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
@@ -245,12 +245,28 @@ function readRepoConnection(projectRoot) {
245
245
  selected,
246
246
  project: typeof record.project === "string" ? record.project : undefined,
247
247
  linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
248
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
248
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
249
+ serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
250
+ serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
249
251
  };
250
252
  }
251
253
  function writeRepoConnection(projectRoot, state) {
252
254
  writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
253
255
  }
256
+ function rootAllowedForSelection(repo, connection) {
257
+ const root = repo.serverProjectRoot?.trim();
258
+ if (!root)
259
+ return;
260
+ if (connection.kind === "remote") {
261
+ if (repo.serverProjectRootAlias !== repo.selected)
262
+ return;
263
+ if (repo.serverProjectRootBaseUrl !== connection.baseUrl)
264
+ return;
265
+ } else if (repo.serverProjectRootAlias && repo.serverProjectRootAlias !== repo.selected) {
266
+ return;
267
+ }
268
+ return root;
269
+ }
254
270
  function resolveSelectedConnection(projectRoot, options = {}) {
255
271
  const repo = readRepoConnection(projectRoot);
256
272
  if (!repo)
@@ -262,13 +278,41 @@ function resolveSelectedConnection(projectRoot, options = {}) {
262
278
  if (!connection) {
263
279
  throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
264
280
  }
265
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
281
+ return { alias: repo.selected, connection, serverProjectRoot: rootAllowedForSelection(repo, connection) };
266
282
  }
267
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
283
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot, metadata = {}) {
268
284
  const repo = readRepoConnection(projectRoot);
269
285
  if (!repo)
270
286
  return;
271
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
287
+ let inferred = metadata;
288
+ if (!inferred.alias || !inferred.baseUrl) {
289
+ try {
290
+ const selected = resolveSelectedConnection(projectRoot);
291
+ if (selected?.connection.kind === "remote") {
292
+ inferred = {
293
+ alias: inferred.alias ?? selected.alias,
294
+ baseUrl: inferred.baseUrl ?? selected.connection.baseUrl
295
+ };
296
+ }
297
+ } catch {}
298
+ }
299
+ writeRepoConnection(projectRoot, {
300
+ ...repo,
301
+ ...metadata.project ? { project: metadata.project } : {},
302
+ serverProjectRoot,
303
+ ...inferred.alias ? { serverProjectRootAlias: inferred.alias } : {},
304
+ ...inferred.baseUrl ? { serverProjectRootBaseUrl: inferred.baseUrl.replace(/\/+$/, "") } : {}
305
+ });
306
+ }
307
+ function clearRepoServerProjectRoot(projectRoot) {
308
+ const repo = readRepoConnection(projectRoot);
309
+ if (!repo)
310
+ return;
311
+ writeRepoConnection(projectRoot, {
312
+ selected: repo.selected,
313
+ ...repo.project ? { project: repo.project } : {},
314
+ ...repo.linkedAt ? { linkedAt: repo.linkedAt } : {}
315
+ });
272
316
  }
273
317
  var init__connection_state = __esm(() => {
274
318
  init_runner();
@@ -292,12 +336,16 @@ __export(exports__server_client, {
292
336
  respondRunPiExtensionUiViaServer: () => respondRunPiExtensionUiViaServer,
293
337
  resolveServerConnectionLabel: () => resolveServerConnectionLabel,
294
338
  requestServerJson: () => requestServerJson,
339
+ repairRemoteProjectRootLink: () => repairRemoteProjectRootLink,
295
340
  registerProjectViaServer: () => registerProjectViaServer,
296
341
  prepareRemoteCheckoutViaServer: () => prepareRemoteCheckoutViaServer,
297
342
  postGitHubTokenViaServer: () => postGitHubTokenViaServer,
343
+ normalizeRepoSlug: () => normalizeRepoSlug,
298
344
  listWorkspaceTasksViaServer: () => listWorkspaceTasksViaServer,
299
345
  listRunsViaServer: () => listRunsViaServer,
300
346
  listGitHubProjectsViaServer: () => listGitHubProjectsViaServer,
347
+ isRemoteProjectRootLinkError: () => isRemoteProjectRootLinkError,
348
+ inspectRemoteProjectLink: () => inspectRemoteProjectLink,
301
349
  getWorkspaceTaskViaServer: () => getWorkspaceTaskViaServer,
302
350
  getRunTimelineViaServer: () => getRunTimelineViaServer,
303
351
  getRunPiStatusViaServer: () => getRunPiStatusViaServer,
@@ -309,13 +357,15 @@ __export(exports__server_client, {
309
357
  getRunDetailsViaServer: () => getRunDetailsViaServer,
310
358
  getGitHubProjectStatusFieldViaServer: () => getGitHubProjectStatusFieldViaServer,
311
359
  getGitHubAuthStatusViaServer: () => getGitHubAuthStatusViaServer,
360
+ formatRemoteProjectLinkHint: () => formatRemoteProjectLinkHint,
312
361
  ensureTaskLabelsViaServer: () => ensureTaskLabelsViaServer,
313
362
  ensureServerForCli: () => ensureServerForCli,
363
+ ensureRemoteProjectRootLink: () => ensureRemoteProjectRootLink,
314
364
  buildRunPiEventsWebSocketUrl: () => buildRunPiEventsWebSocketUrl,
315
365
  abortRunPiViaServer: () => abortRunPiViaServer
316
366
  });
317
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
318
- import { resolve as resolve2 } from "path";
367
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
368
+ import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
319
369
  import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
320
370
  function setServerPhaseListener(listener) {
321
371
  const previous = serverPhaseListener;
@@ -361,11 +411,10 @@ function readStoredGitHubAuthToken(projectRoot) {
361
411
  const parsed = readRemoteAuthState(projectRoot);
362
412
  return parsed ? cleanToken(typeof parsed.token === "string" ? parsed.token : undefined) : null;
363
413
  }
364
- function inferRemoteServerProjectRootFromAuthState(projectRoot) {
365
- const repo = readRepoConnection(projectRoot);
366
- const slug = repo?.project?.trim();
367
- if (!slug || !/^[^/]+\/[^/]+$/.test(slug))
414
+ function inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug) {
415
+ if (!/^[^/]+\/[^/]+$/.test(repoSlug))
368
416
  return null;
417
+ const repo = readRepoConnection(projectRoot);
369
418
  const auth = readRemoteAuthState(projectRoot);
370
419
  const authUpdatedAt = typeof auth?.updatedAt === "string" ? Date.parse(auth.updatedAt) : Number.NaN;
371
420
  const repoLinkedAt = typeof repo?.linkedAt === "string" ? Date.parse(repo.linkedAt) : Number.NaN;
@@ -374,25 +423,426 @@ function inferRemoteServerProjectRootFromAuthState(projectRoot) {
374
423
  const checkoutBaseDir = typeof auth?.checkoutBaseDir === "string" && auth.checkoutBaseDir.trim() ? auth.checkoutBaseDir.trim() : null;
375
424
  if (!checkoutBaseDir)
376
425
  return null;
377
- const inferred = `${checkoutBaseDir.replace(/\/+$/, "")}/${slug}`;
378
- writeRepoServerProjectRoot(projectRoot, inferred);
379
- return inferred;
426
+ return `${checkoutBaseDir.replace(/\/+$/, "")}/${repoSlug}`;
380
427
  }
381
428
  function readLocalConnectionFallbackToken(projectRoot) {
382
429
  return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
383
430
  }
431
+ function normalizeRepoSlug(value) {
432
+ const slug = value?.trim();
433
+ return slug && /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
434
+ }
435
+ function readProjectLinkSlug(projectRoot) {
436
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
437
+ if (!existsSync2(path))
438
+ return null;
439
+ try {
440
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
441
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
442
+ return null;
443
+ return normalizeRepoSlug(typeof parsed.repoSlug === "string" ? String(parsed.repoSlug) : null);
444
+ } catch {
445
+ return null;
446
+ }
447
+ }
448
+ function writeProjectLinkConnection(projectRoot, repoSlug, alias) {
449
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
450
+ mkdirSync2(dirname2(path), { recursive: true });
451
+ writeFileSync2(path, `${JSON.stringify({ repoSlug, connection: alias, linkedAt: new Date().toISOString() }, null, 2)}
452
+ `, "utf8");
453
+ }
454
+ function remoteLinkRepairCommand(repoSlug) {
455
+ return repoSlug ? `rig server repair-link --repo ${repoSlug}` : "rig server repair-link --repo owner/repo";
456
+ }
457
+ function isRemoteProjectRootLinkError(error) {
458
+ const text = error instanceof Error ? error.message : String(error ?? "");
459
+ return /no server-host project root link|remote project(?:-root)? link|x-rig-project-root|serverProjectRoot/i.test(text);
460
+ }
461
+ function formatRemoteProjectLinkHint(resolution) {
462
+ const repair = remoteLinkRepairCommand(resolution.repoSlug);
463
+ if (resolution.status === "auth_required") {
464
+ 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}` : ""}\`.`;
465
+ }
466
+ if (resolution.status === "missing_project") {
467
+ return `Record the repo slug, then run \`${repair}\` (or \`rig init --repo owner/repo --server remote --github-auth device\`).`;
468
+ }
469
+ if (resolution.status === "not_remote")
470
+ return "Select a remote server with `rig server use <alias>` before repairing a remote project link.";
471
+ return `Run \`${repair}\` to backfill or prepare a server-host checkout for the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}.`;
472
+ }
473
+ function remoteProjectLinkFailure(input) {
474
+ const partial = {
475
+ status: input.status,
476
+ alias: input.alias,
477
+ baseUrl: input.baseUrl,
478
+ repoSlug: input.repoSlug
479
+ };
480
+ return {
481
+ ok: false,
482
+ ...input,
483
+ hint: formatRemoteProjectLinkHint(partial),
484
+ next: remoteLinkRepairCommand(input.repoSlug)
485
+ };
486
+ }
487
+ function remoteProjectLinkSuccess(input) {
488
+ return {
489
+ ok: true,
490
+ status: input.status,
491
+ alias: input.alias,
492
+ baseUrl: input.baseUrl,
493
+ repoSlug: input.repoSlug,
494
+ serverProjectRoot: input.serverProjectRoot,
495
+ source: input.source,
496
+ prepared: input.prepared ?? input.status === "prepared",
497
+ validated: input.validated ?? false,
498
+ message: input.message ?? `Remote project link ready for ${input.repoSlug}.`,
499
+ hint: "Remote-scoped task/run/status requests will send x-rig-project-root for this server-host checkout.",
500
+ next: "rig task list"
501
+ };
502
+ }
503
+ function localCheckoutPathCandidate(projectRoot, candidate) {
504
+ try {
505
+ const local = resolve2(projectRoot);
506
+ const resolved = resolve2(candidate);
507
+ return resolved === local || resolved.startsWith(`${local}/`);
508
+ } catch {
509
+ return false;
510
+ }
511
+ }
512
+ async function requestRemoteProjectLinkJson(baseUrl, pathname, authToken, init = {}) {
513
+ const requestUrl = new URL(`${baseUrl}${pathname}`);
514
+ if (authToken && queryAuthFallbackEnabled())
515
+ requestUrl.searchParams.set("rt", authToken);
516
+ const response = await fetch(requestUrl, {
517
+ ...init,
518
+ headers: mergeHeaders(init.headers, authToken)
519
+ });
520
+ const text = await response.text();
521
+ const payload = text.trim().length > 0 ? (() => {
522
+ try {
523
+ return JSON.parse(text);
524
+ } catch {
525
+ return null;
526
+ }
527
+ })() : null;
528
+ return { ok: response.ok, status: response.status, payload, text };
529
+ }
530
+ function payloadError(payload, fallback) {
531
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
532
+ const record = payload;
533
+ const value = record.error ?? record.message ?? record.reason;
534
+ if (typeof value === "string" && value.trim())
535
+ return value.trim();
536
+ }
537
+ return fallback;
538
+ }
539
+ function checkoutPathsFromProjectPayload(payload) {
540
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
541
+ return [];
542
+ const project = payload.project;
543
+ if (!project || typeof project !== "object" || Array.isArray(project))
544
+ return [];
545
+ const checkouts = project.checkouts;
546
+ if (!Array.isArray(checkouts))
547
+ return [];
548
+ return [...checkouts].reverse().flatMap((entry) => {
549
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
550
+ return [];
551
+ const path = entry.path;
552
+ return typeof path === "string" && path.trim() ? [path.trim()] : [];
553
+ });
554
+ }
555
+ function checkoutPathFromPreparePayload(payload) {
556
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
557
+ return null;
558
+ const checkout = payload.checkout;
559
+ if (!checkout || typeof checkout !== "object" || Array.isArray(checkout))
560
+ return null;
561
+ const path = checkout.path;
562
+ return typeof path === "string" && path.trim() ? path.trim() : null;
563
+ }
564
+ async function validateAndPersistRemoteRoot(input) {
565
+ const candidate = input.candidate.trim();
566
+ if (!candidate || !isAbsolute(candidate)) {
567
+ return remoteProjectLinkFailure({
568
+ status: "invalid_root",
569
+ alias: input.alias,
570
+ baseUrl: input.baseUrl,
571
+ repoSlug: input.repoSlug,
572
+ message: `Remote project root candidate is not an absolute server-host path: ${candidate || "(empty)"}.`
573
+ });
574
+ }
575
+ if (localCheckoutPathCandidate(input.projectRoot, candidate)) {
576
+ return remoteProjectLinkFailure({
577
+ status: "invalid_root",
578
+ alias: input.alias,
579
+ baseUrl: input.baseUrl,
580
+ repoSlug: input.repoSlug,
581
+ message: `Refusing to use local checkout path ${candidate} as a remote server project root.`
582
+ });
583
+ }
584
+ let response;
585
+ try {
586
+ response = await requestRemoteProjectLinkJson(input.baseUrl, "/api/server/project-root", input.authToken, {
587
+ method: "POST",
588
+ headers: { "content-type": "application/json" },
589
+ body: JSON.stringify({ projectRoot: candidate })
590
+ });
591
+ } catch (error) {
592
+ return remoteProjectLinkFailure({
593
+ status: "error",
594
+ alias: input.alias,
595
+ baseUrl: input.baseUrl,
596
+ repoSlug: input.repoSlug,
597
+ message: `Could not validate remote project root ${candidate}: ${error instanceof Error ? error.message : String(error)}`
598
+ });
599
+ }
600
+ if (response.status === 401 || response.status === 403) {
601
+ return remoteProjectLinkFailure({
602
+ status: "auth_required",
603
+ alias: input.alias,
604
+ baseUrl: input.baseUrl,
605
+ repoSlug: input.repoSlug,
606
+ statusCode: response.status,
607
+ message: `Remote server ${input.alias} requires authentication before validating project root ${candidate}.`
608
+ });
609
+ }
610
+ if (!response.ok) {
611
+ return remoteProjectLinkFailure({
612
+ status: "invalid_root",
613
+ alias: input.alias,
614
+ baseUrl: input.baseUrl,
615
+ repoSlug: input.repoSlug,
616
+ statusCode: response.status,
617
+ message: `Remote server rejected project root ${candidate} (${response.status}): ${payloadError(response.payload, response.text || "project-root validation failed")}`
618
+ });
619
+ }
620
+ const record = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload) ? response.payload : {};
621
+ if (record.ok !== true) {
622
+ return remoteProjectLinkFailure({
623
+ status: "invalid_root",
624
+ alias: input.alias,
625
+ baseUrl: input.baseUrl,
626
+ repoSlug: input.repoSlug,
627
+ message: `Remote server did not accept project root ${candidate}: ${payloadError(response.payload, "project-root validation failed")}`
628
+ });
629
+ }
630
+ const accepted = typeof record.projectRoot === "string" && record.projectRoot.trim() ? record.projectRoot.trim() : typeof record.requestedProjectRoot === "string" && record.requestedProjectRoot.trim() ? record.requestedProjectRoot.trim() : candidate;
631
+ writeRepoServerProjectRoot(input.projectRoot, accepted, { alias: input.alias, baseUrl: input.baseUrl, project: input.repoSlug });
632
+ writeProjectLinkConnection(input.projectRoot, input.repoSlug, input.alias);
633
+ const status = input.status ?? (input.prepared ? "prepared" : "backfilled");
634
+ return remoteProjectLinkSuccess({
635
+ status,
636
+ alias: input.alias,
637
+ baseUrl: input.baseUrl,
638
+ repoSlug: input.repoSlug,
639
+ serverProjectRoot: accepted,
640
+ source: input.source,
641
+ prepared: input.prepared,
642
+ validated: true,
643
+ 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}.`
644
+ });
645
+ }
646
+ async function ensureRemoteProjectRootLink(projectRoot, options = {}) {
647
+ let selected;
648
+ try {
649
+ selected = resolveSelectedConnection(projectRoot);
650
+ } catch (error) {
651
+ return remoteProjectLinkFailure({ status: "error", message: error instanceof Error ? error.message : String(error) });
652
+ }
653
+ if (!selected || selected.connection.kind !== "remote") {
654
+ return remoteProjectLinkFailure({ status: "not_remote", message: "No remote Rig server is selected for this repo." });
655
+ }
656
+ const repo = readRepoConnection(projectRoot);
657
+ const explicitRepoRequested = options.repoSlug !== undefined;
658
+ const explicitRepoSlug = explicitRepoRequested ? normalizeRepoSlug(options.repoSlug) : null;
659
+ const repoProjectSlug = normalizeRepoSlug(repo?.project);
660
+ const repoSlug = explicitRepoSlug ?? repoProjectSlug ?? readProjectLinkSlug(projectRoot);
661
+ const alias = selected.alias;
662
+ const baseUrl = selected.connection.baseUrl;
663
+ const authToken = options.authToken === undefined ? readGitHubBearerTokenForRemote(projectRoot) : options.authToken;
664
+ const mode = options.mode ?? "backfill-only";
665
+ if (explicitRepoRequested && !explicitRepoSlug) {
666
+ return remoteProjectLinkFailure({
667
+ status: "missing_project",
668
+ alias,
669
+ baseUrl,
670
+ message: `Invalid --repo value ${JSON.stringify(options.repoSlug)}. Expected owner/repo.`
671
+ });
672
+ }
673
+ if (!repoSlug) {
674
+ return remoteProjectLinkFailure({
675
+ status: "missing_project",
676
+ alias,
677
+ baseUrl,
678
+ message: `Remote server ${alias} is selected, but this checkout has no GitHub repo slug recorded.`
679
+ });
680
+ }
681
+ const skippedCandidates = [];
682
+ const storedRoot = selected.serverProjectRoot?.trim() || null;
683
+ const storedRootMatchesResolvedRepo = repoProjectSlug === repoSlug;
684
+ if (storedRoot && storedRootMatchesResolvedRepo) {
685
+ if (localCheckoutPathCandidate(projectRoot, storedRoot)) {
686
+ clearRepoServerProjectRoot(projectRoot);
687
+ skippedCandidates.push(storedRoot);
688
+ } else {
689
+ const storedResult = await validateAndPersistRemoteRoot({
690
+ projectRoot,
691
+ alias,
692
+ baseUrl,
693
+ authToken,
694
+ repoSlug,
695
+ candidate: storedRoot,
696
+ source: "stored",
697
+ status: "ready"
698
+ });
699
+ if (storedResult.ok || storedResult.status === "auth_required" || storedResult.status === "error")
700
+ return storedResult;
701
+ clearRepoServerProjectRoot(projectRoot);
702
+ skippedCandidates.push(storedRoot);
703
+ }
704
+ } else if (storedRoot) {
705
+ skippedCandidates.push(storedRoot);
706
+ }
707
+ const authCandidate = inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug);
708
+ if (authCandidate) {
709
+ const authResult = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: authCandidate, source: "auth-state" });
710
+ if (authResult.ok || authResult.status === "auth_required")
711
+ return authResult;
712
+ }
713
+ let registryResponse;
714
+ try {
715
+ registryResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}`, authToken);
716
+ } catch (error) {
717
+ return remoteProjectLinkFailure({
718
+ status: "error",
719
+ alias,
720
+ baseUrl,
721
+ repoSlug,
722
+ message: `Could not read remote project registry for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
723
+ });
724
+ }
725
+ if (registryResponse.status === 401 || registryResponse.status === 403) {
726
+ return remoteProjectLinkFailure({
727
+ status: "auth_required",
728
+ alias,
729
+ baseUrl,
730
+ repoSlug,
731
+ statusCode: registryResponse.status,
732
+ message: `Remote server ${alias} requires authentication before reading the ${repoSlug} project registry.`
733
+ });
734
+ }
735
+ if (registryResponse.ok) {
736
+ const candidates = checkoutPathsFromProjectPayload(registryResponse.payload);
737
+ for (const candidate of candidates) {
738
+ const result = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate, source: "registry" });
739
+ if (result.ok || result.status === "auth_required")
740
+ return result;
741
+ skippedCandidates.push(candidate);
742
+ }
743
+ if (mode === "backfill-only") {
744
+ return remoteProjectLinkFailure({
745
+ status: candidates.length > 0 ? "invalid_root" : "no_server_checkout",
746
+ alias,
747
+ baseUrl,
748
+ repoSlug,
749
+ 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.`,
750
+ skippedCandidates
751
+ });
752
+ }
753
+ } else if (registryResponse.status === 404) {
754
+ if (mode === "backfill-only") {
755
+ return remoteProjectLinkFailure({
756
+ status: "project_not_registered",
757
+ alias,
758
+ baseUrl,
759
+ repoSlug,
760
+ statusCode: registryResponse.status,
761
+ message: `Remote server ${alias} has no registered project record for ${repoSlug}.`
762
+ });
763
+ }
764
+ } else {
765
+ return remoteProjectLinkFailure({
766
+ status: "error",
767
+ alias,
768
+ baseUrl,
769
+ repoSlug,
770
+ statusCode: registryResponse.status,
771
+ message: `Could not backfill ${repoSlug} from remote registry (${registryResponse.status}): ${payloadError(registryResponse.payload, registryResponse.text || "registry lookup failed")}`,
772
+ skippedCandidates
773
+ });
774
+ }
775
+ let prepareResponse;
776
+ try {
777
+ prepareResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}/prepare-checkout`, authToken, {
778
+ method: "POST",
779
+ headers: { "content-type": "application/json" },
780
+ body: JSON.stringify({ checkout: { kind: "managed-clone" }, repoUrl: `https://github.com/${repoSlug}.git` })
781
+ });
782
+ } catch (error) {
783
+ return remoteProjectLinkFailure({
784
+ status: "error",
785
+ alias,
786
+ baseUrl,
787
+ repoSlug,
788
+ message: `Could not prepare remote checkout for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
789
+ });
790
+ }
791
+ if (prepareResponse.status === 401 || prepareResponse.status === 403) {
792
+ return remoteProjectLinkFailure({
793
+ status: "auth_required",
794
+ alias,
795
+ baseUrl,
796
+ repoSlug,
797
+ statusCode: prepareResponse.status,
798
+ message: `Remote server ${alias} requires authentication before preparing ${repoSlug}.`
799
+ });
800
+ }
801
+ if (!prepareResponse.ok) {
802
+ return remoteProjectLinkFailure({
803
+ status: "error",
804
+ alias,
805
+ baseUrl,
806
+ repoSlug,
807
+ statusCode: prepareResponse.status,
808
+ message: `Remote checkout prepare failed for ${repoSlug} (${prepareResponse.status}): ${payloadError(prepareResponse.payload, prepareResponse.text || "prepare-checkout failed")}`,
809
+ skippedCandidates
810
+ });
811
+ }
812
+ const preparedPath = checkoutPathFromPreparePayload(prepareResponse.payload);
813
+ if (!preparedPath) {
814
+ return remoteProjectLinkFailure({
815
+ status: "invalid_root",
816
+ alias,
817
+ baseUrl,
818
+ repoSlug,
819
+ message: `Remote checkout prepare for ${repoSlug} did not return a checkout.path.`,
820
+ skippedCandidates
821
+ });
822
+ }
823
+ return validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: preparedPath, source: "prepare", prepared: true });
824
+ }
825
+ async function inspectRemoteProjectLink(projectRoot) {
826
+ return ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only" });
827
+ }
828
+ async function repairRemoteProjectRootLink(context, options = {}) {
829
+ const resolution = await ensureRemoteProjectRootLink(context.projectRoot, { mode: options.mode ?? "prepare-if-missing", repoSlug: options.repoSlug });
830
+ if (!resolution.ok)
831
+ throw new CliError(resolution.message, 1, { hint: resolution.hint });
832
+ return resolution;
833
+ }
384
834
  async function ensureServerForCli(projectRoot) {
385
835
  try {
386
836
  const selected = resolveSelectedConnection(projectRoot);
387
837
  if (selected?.connection.kind === "remote") {
388
838
  reportServerPhase(`Connecting to ${selected.alias}\u2026`);
389
839
  const authToken = readGitHubBearerTokenForRemote(projectRoot);
390
- const serverProjectRoot = selected.serverProjectRoot ?? inferRemoteServerProjectRootFromAuthState(projectRoot) ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
840
+ const link = await ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only", authToken });
391
841
  return {
392
842
  baseUrl: selected.connection.baseUrl,
393
843
  authToken,
394
844
  connectionKind: "remote",
395
- serverProjectRoot
845
+ serverProjectRoot: link.ok ? link.serverProjectRoot ?? null : null
396
846
  };
397
847
  }
398
848
  reportServerPhase("Starting local Rig server\u2026");
@@ -410,32 +860,6 @@ async function ensureServerForCli(projectRoot) {
410
860
  throw error;
411
861
  }
412
862
  }
413
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
414
- const repo = readRepoConnection(projectRoot);
415
- const slug = repo?.project?.trim();
416
- if (!slug)
417
- return null;
418
- try {
419
- const url = new URL(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`);
420
- if (authToken && queryAuthFallbackEnabled())
421
- url.searchParams.set("rt", authToken);
422
- const response = await fetch(url, {
423
- headers: mergeHeaders(undefined, authToken)
424
- });
425
- if (!response.ok)
426
- return null;
427
- const payload = await response.json();
428
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
429
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
430
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
431
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
432
- if (path)
433
- writeRepoServerProjectRoot(projectRoot, path);
434
- return path;
435
- } catch {
436
- return null;
437
- }
438
- }
439
863
  function appendTaskFilterParams(url, filters) {
440
864
  if (filters.assignee)
441
865
  url.searchParams.set("assignee", filters.assignee);
@@ -536,13 +960,20 @@ function canUseRemoteWithoutProjectRoot(pathname) {
536
960
  async function requestServerJson(context, pathname, init = {}) {
537
961
  const server = await ensureServerForCli(context.projectRoot);
538
962
  const requestUrl = new URL(`${server.baseUrl}${pathname}`);
539
- if (server.connectionKind === "remote" && !server.serverProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
540
- const repo = readRepoConnection(context.projectRoot);
541
- 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." });
963
+ let scopedServerProjectRoot = server.serverProjectRoot;
964
+ if (server.connectionKind === "remote" && !scopedServerProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
965
+ const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: server.authToken });
966
+ if (link.ok && link.serverProjectRoot) {
967
+ scopedServerProjectRoot = link.serverProjectRoot;
968
+ } else {
969
+ const repo = readRepoConnection(context.projectRoot);
970
+ const target = link.alias && link.baseUrl ? `${link.alias} (${link.baseUrl})` : server.baseUrl;
971
+ 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 });
972
+ }
542
973
  }
543
974
  const headers = mergeHeaders(init.headers, server.authToken);
544
- if (server.serverProjectRoot)
545
- headers.set("x-rig-project-root", server.serverProjectRoot);
975
+ if (scopedServerProjectRoot)
976
+ headers.set("x-rig-project-root", scopedServerProjectRoot);
546
977
  if (server.connectionKind === "remote" && server.authToken && queryAuthFallbackEnabled()) {
547
978
  requestUrl.searchParams.set("rt", server.authToken);
548
979
  }
@@ -1204,6 +1635,14 @@ function permissionAllowsPr(payload) {
1204
1635
  function isNotFoundError(error) {
1205
1636
  return /\b(404|not found)\b/i.test(message(error));
1206
1637
  }
1638
+ function isLoopbackBaseUrl(baseUrl) {
1639
+ try {
1640
+ const host = new URL(baseUrl).hostname.toLowerCase();
1641
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
1642
+ } catch {
1643
+ return false;
1644
+ }
1645
+ }
1207
1646
  function projectCheckoutReady(payload) {
1208
1647
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
1209
1648
  return null;
@@ -1258,25 +1697,37 @@ async function runFastTaskRunPreflight(context, options = {}) {
1258
1697
  }
1259
1698
  const repo = readRepoConnection(context.projectRoot);
1260
1699
  const remoteWithoutProjectLink = selectedServer?.connectionKind === "remote" && !repo?.project;
1261
- checks.push(repo ? preflightCheck("project-link", "project linked to selected server", repo.project ? "pass" : remoteWithoutProjectLink ? "fail" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : " (missing project link)"}`, remoteWithoutProjectLink ? "Run `rig init --repair` or `rig init --yes --repo owner/repo --server remote` to restore the remote project link." : "Run `rig init --yes --repo owner/repo` to record the GitHub repo slug.") : preflightCheck("project-link", "project linked to selected server", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
1700
+ let remoteRootBlocked = false;
1701
+ checks.push(repo ? preflightCheck("project-link", "project linked to selected server", repo.project ? "pass" : remoteWithoutProjectLink ? "fail" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : " (missing project link)"}`, remoteWithoutProjectLink ? "Run `rig server repair-link --repo owner/repo` or `rig init --repo owner/repo --server remote` to restore the remote project link." : "Run `rig init --yes --repo owner/repo` to record the GitHub repo slug.") : preflightCheck("project-link", "project linked to selected server", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
1702
+ if (selectedServer?.connectionKind === "remote" && repo?.project && !selectedServer.serverProjectRoot) {
1703
+ const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: selectedServer.authToken });
1704
+ const loopbackDevRemote = !selectedServer.authToken && isLoopbackBaseUrl(selectedServer.baseUrl);
1705
+ checks.push(preflightCheck("remote-project-root-link", "remote server checkout/root linked", link.ok ? "pass" : loopbackDevRemote ? "warn" : "fail", link.ok ? `${link.repoSlug} -> ${link.serverProjectRoot}` : link.message, link.ok ? undefined : loopbackDevRemote ? "Loopback development remotes may continue without x-rig-project-root; production remotes must run `rig server repair-link`." : link.hint));
1706
+ remoteRootBlocked = !link.ok && !loopbackDevRemote;
1707
+ }
1262
1708
  try {
1263
1709
  const auth = await request("/api/github/auth/status");
1264
1710
  checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
1265
1711
  } catch (error) {
1266
1712
  checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
1267
1713
  }
1268
- try {
1269
- const projection = await request("/api/workspace/task-projection");
1270
- checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
1271
- } catch (error) {
1272
- checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
1273
- }
1274
- try {
1275
- const permissions = await request("/api/github/repo/permissions");
1276
- const allowed = permissionAllowsPr(permissions);
1277
- checks.push(allowed === false ? preflightCheck("github-repo-permissions", "GitHub PR permissions", "fail", JSON.stringify(permissions).slice(0, 120), "Grant the selected GitHub token permission to push branches and open PRs.") : preflightCheck("github-repo-permissions", "GitHub PR permissions", allowed === true ? "pass" : "warn", JSON.stringify(permissions).slice(0, 120), "Confirm the selected token can push branches and open PRs."));
1278
- } catch (error) {
1279
- checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
1714
+ if (!remoteRootBlocked) {
1715
+ try {
1716
+ const projection = await request("/api/workspace/task-projection");
1717
+ checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
1718
+ } catch (error) {
1719
+ checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
1720
+ }
1721
+ try {
1722
+ const permissions = await request("/api/github/repo/permissions");
1723
+ const allowed = permissionAllowsPr(permissions);
1724
+ checks.push(allowed === false ? preflightCheck("github-repo-permissions", "GitHub PR permissions", "fail", JSON.stringify(permissions).slice(0, 120), "Grant the selected GitHub token permission to push branches and open PRs.") : preflightCheck("github-repo-permissions", "GitHub PR permissions", allowed === true ? "pass" : "warn", JSON.stringify(permissions).slice(0, 120), "Confirm the selected token can push branches and open PRs."));
1725
+ } catch (error) {
1726
+ checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
1727
+ }
1728
+ } else {
1729
+ checks.push(preflightCheck("task-projection", "task projection ready", "warn", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
1730
+ checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
1280
1731
  }
1281
1732
  if (repo?.project) {
1282
1733
  try {
@@ -1288,19 +1739,24 @@ async function runFastTaskRunPreflight(context, options = {}) {
1288
1739
  }
1289
1740
  }
1290
1741
  if (taskId) {
1291
- try {
1292
- const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
1293
- const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
1294
- checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
1295
- } catch (error) {
1296
- checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
1297
- }
1298
- try {
1299
- const runs = await request("/api/runs?limit=200");
1300
- const duplicate = activeDuplicateRun(runs, taskId);
1301
- checks.push(duplicate ? preflightCheck("duplicate-active-run", "one active run per task", "fail", String(duplicate.runId ?? taskId), "Attach to or stop the existing run before starting another one for this task.") : preflightCheck("duplicate-active-run", "one active run per task", "pass", taskId));
1302
- } catch (error) {
1303
- checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", message(error), "Could not list active runs; the server will still reject conflicting runs if configured."));
1742
+ if (!remoteRootBlocked) {
1743
+ try {
1744
+ const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
1745
+ const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
1746
+ checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
1747
+ } catch (error) {
1748
+ checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
1749
+ }
1750
+ try {
1751
+ const runs = await request("/api/runs?limit=200");
1752
+ const duplicate = activeDuplicateRun(runs, taskId);
1753
+ checks.push(duplicate ? preflightCheck("duplicate-active-run", "one active run per task", "fail", String(duplicate.runId ?? taskId), "Attach to or stop the existing run before starting another one for this task.") : preflightCheck("duplicate-active-run", "one active run per task", "pass", taskId));
1754
+ } catch (error) {
1755
+ checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", message(error), "Could not list active runs; the server will still reject conflicting runs if configured."));
1756
+ }
1757
+ } else {
1758
+ checks.push(preflightCheck("issue", "task/issue accessible", "fail", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
1759
+ checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
1304
1760
  }
1305
1761
  }
1306
1762
  if ((options.runtimeAdapter ?? "pi") === "pi") {
@@ -1737,7 +2193,7 @@ __export(exports__pi_frontend, {
1737
2193
  buildOperatorPiEnv: () => buildOperatorPiEnv,
1738
2194
  attachRunBundledPiFrontend: () => attachRunBundledPiFrontend
1739
2195
  });
1740
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "fs";
2196
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync3 } from "fs";
1741
2197
  import { homedir as homedir2, tmpdir } from "os";
1742
2198
  import { join } from "path";
1743
2199
  import { main as runPiMain } from "@earendil-works/pi-coding-agent";
@@ -1789,7 +2245,7 @@ function statusFromRunDetails(run) {
1789
2245
  async function prepareOperatorConsole(context, runId, tempSessionDir) {
1790
2246
  const server = await ensureServerForCli(context.projectRoot);
1791
2247
  const localCwd = join(homedir2(), ".rig", "drones", runId.slice(0, 8));
1792
- mkdirSync2(localCwd, { recursive: true });
2248
+ mkdirSync3(localCwd, { recursive: true });
1793
2249
  trustDroneCwd(localCwd);
1794
2250
  installRigPiTheme();
1795
2251
  let sessionFileArg = [];
@@ -1811,7 +2267,7 @@ async function prepareOperatorConsole(context, runId, tempSessionDir) {
1811
2267
  return line;
1812
2268
  }).join(`
1813
2269
  `);
1814
- writeFileSync2(localSessionPath, content);
2270
+ writeFileSync3(localSessionPath, content);
1815
2271
  sessionFileArg = ["--session", localSessionPath];
1816
2272
  }
1817
2273
  } catch {}
@@ -1827,12 +2283,12 @@ async function prepareOperatorConsole(context, runId, tempSessionDir) {
1827
2283
  function trustDroneCwd(localCwd) {
1828
2284
  try {
1829
2285
  const agentDir = join(homedir2(), ".pi", "agent");
1830
- mkdirSync2(agentDir, { recursive: true });
2286
+ mkdirSync3(agentDir, { recursive: true });
1831
2287
  const trustPath = join(agentDir, "trust.json");
1832
2288
  const store = existsSync3(trustPath) ? JSON.parse(readFileSync3(trustPath, "utf8")) : {};
1833
2289
  if (store[localCwd] !== true) {
1834
2290
  store[localCwd] = true;
1835
- writeFileSync2(trustPath, `${JSON.stringify(store, null, "\t")}
2291
+ writeFileSync3(trustPath, `${JSON.stringify(store, null, "\t")}
1836
2292
  `);
1837
2293
  }
1838
2294
  } catch {}
@@ -1840,12 +2296,12 @@ function trustDroneCwd(localCwd) {
1840
2296
  function installRigPiTheme() {
1841
2297
  try {
1842
2298
  const themesDir = join(homedir2(), ".pi", "agent", "themes");
1843
- mkdirSync2(themesDir, { recursive: true });
2299
+ mkdirSync3(themesDir, { recursive: true });
1844
2300
  const themePath = join(themesDir, "rig.json");
1845
2301
  const next = `${JSON.stringify(RIG_PI_THEME, null, "\t")}
1846
2302
  `;
1847
2303
  if (!existsSync3(themePath) || readFileSync3(themePath, "utf8") !== next) {
1848
- writeFileSync2(themePath, next);
2304
+ writeFileSync3(themePath, next);
1849
2305
  }
1850
2306
  } catch {}
1851
2307
  }
@@ -2446,12 +2902,13 @@ var init__help_catalog = __esm(() => {
2446
2902
  {
2447
2903
  name: "server",
2448
2904
  summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
2449
- usage: ["rig server <status|list|add|use|start> [options]"],
2905
+ usage: ["rig server <status|list|add|use|repair-link|start> [options]"],
2450
2906
  commands: [
2451
- { command: "status", description: "Show the selected server for this repo.", primary: true },
2907
+ { command: "status", description: "Show the selected server and remote project-root link for this repo.", primary: true },
2452
2908
  { command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
2453
2909
  { command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
2454
2910
  { command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
2911
+ { command: "repair-link [--prepare|--backfill-only] [--repo owner/repo]", description: "Backfill or prepare the selected remote's server-host checkout link.", primary: true },
2455
2912
  { command: "list", description: "List saved local/remote server aliases.", primary: true },
2456
2913
  { command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
2457
2914
  ],
@@ -2459,6 +2916,7 @@ var init__help_catalog = __esm(() => {
2459
2916
  "rig server status",
2460
2917
  "rig server add prod https://where.rig-does.work",
2461
2918
  "rig server use prod",
2919
+ "rig server repair-link --repo owner/repo",
2462
2920
  "rig server use local",
2463
2921
  "rig server start --port 3773"
2464
2922
  ],