@h-rig/cli 0.0.6-alpha.87 → 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 (78) hide show
  1. package/dist/bin/rig.js +1380 -865
  2. package/dist/src/app/board.js +462 -48
  3. package/dist/src/app-opentui/adapters/common.d.ts +3 -0
  4. package/dist/src/app-opentui/adapters/common.js +4 -0
  5. package/dist/src/app-opentui/adapters/doctor.js +458 -46
  6. package/dist/src/app-opentui/adapters/family.js +701 -151
  7. package/dist/src/app-opentui/adapters/fleet.js +477 -46
  8. package/dist/src/app-opentui/adapters/inbox.js +477 -46
  9. package/dist/src/app-opentui/adapters/init.js +497 -74
  10. package/dist/src/app-opentui/adapters/inspect.js +477 -46
  11. package/dist/src/app-opentui/adapters/pi-attach.d.ts +7 -0
  12. package/dist/src/app-opentui/adapters/pi-attach.js +1004 -519
  13. package/dist/src/app-opentui/adapters/run-detail.js +477 -46
  14. package/dist/src/app-opentui/adapters/server.d.ts +26 -0
  15. package/dist/src/app-opentui/adapters/server.js +676 -59
  16. package/dist/src/app-opentui/adapters/tasks.js +621 -549
  17. package/dist/src/app-opentui/autocomplete.js +4 -2
  18. package/dist/src/app-opentui/bootstrap.js +1376 -861
  19. package/dist/src/app-opentui/command-palette.js +37 -10
  20. package/dist/src/app-opentui/index.js +632 -528
  21. package/dist/src/app-opentui/intent.js +33 -8
  22. package/dist/src/app-opentui/keymap.js +43 -414
  23. package/dist/src/app-opentui/pi-host-child.js +496 -57
  24. package/dist/src/app-opentui/pi-pty-host.d.ts +14 -64
  25. package/dist/src/app-opentui/pi-pty-host.js +3 -397
  26. package/dist/src/app-opentui/react/App.js +144 -469
  27. package/dist/src/app-opentui/react/ChromeHost.js +44 -415
  28. package/dist/src/app-opentui/react/launch.js +659 -552
  29. package/dist/src/app-opentui/react/nav.js +1 -1
  30. package/dist/src/app-opentui/registry.js +1181 -742
  31. package/dist/src/app-opentui/remote-link.d.ts +10 -0
  32. package/dist/src/app-opentui/remote-link.js +47 -0
  33. package/dist/src/app-opentui/render/terminal-handoff.d.ts +16 -0
  34. package/dist/src/app-opentui/render/terminal-handoff.js +14 -0
  35. package/dist/src/app-opentui/runtime.js +632 -528
  36. package/dist/src/app-opentui/scenes/doctor.js +1 -1
  37. package/dist/src/app-opentui/scenes/error.js +50 -4
  38. package/dist/src/app-opentui/scenes/family.js +60 -6
  39. package/dist/src/app-opentui/scenes/fleet.js +65 -13
  40. package/dist/src/app-opentui/scenes/help.js +4 -2
  41. package/dist/src/app-opentui/scenes/init.js +12 -12
  42. package/dist/src/app-opentui/scenes/main.js +7 -7
  43. package/dist/src/app-opentui/scenes/server.js +83 -11
  44. package/dist/src/app-opentui/scenes/tasks.js +79 -16
  45. package/dist/src/app-opentui/state.js +25 -5
  46. package/dist/src/app-opentui/surface-catalog.js +4 -2
  47. package/dist/src/app-opentui/types.d.ts +1 -1
  48. package/dist/src/commands/_cli-format.d.ts +10 -1
  49. package/dist/src/commands/_cli-format.js +5 -2
  50. package/dist/src/commands/_connection-state.d.ts +11 -1
  51. package/dist/src/commands/_connection-state.js +50 -5
  52. package/dist/src/commands/_doctor-checks.js +458 -46
  53. package/dist/src/commands/_help-catalog.js +4 -2
  54. package/dist/src/commands/_json-output.js +4 -0
  55. package/dist/src/commands/_operator-view.js +496 -57
  56. package/dist/src/commands/_pi-frontend.d.ts +25 -0
  57. package/dist/src/commands/_pi-frontend.js +497 -57
  58. package/dist/src/commands/_preflight.js +509 -72
  59. package/dist/src/commands/_server-client.d.ts +33 -0
  60. package/dist/src/commands/_server-client.js +477 -46
  61. package/dist/src/commands/_server-events.js +446 -41
  62. package/dist/src/commands/_snapshot-upload.js +460 -48
  63. package/dist/src/commands/connect.js +620 -15
  64. package/dist/src/commands/doctor.js +458 -46
  65. package/dist/src/commands/github.js +462 -50
  66. package/dist/src/commands/inbox.js +458 -46
  67. package/dist/src/commands/init.js +497 -74
  68. package/dist/src/commands/inspect.js +458 -46
  69. package/dist/src/commands/run.js +496 -57
  70. package/dist/src/commands/server.js +647 -163
  71. package/dist/src/commands/setup.js +463 -51
  72. package/dist/src/commands/stats.js +462 -48
  73. package/dist/src/commands/task-run-driver.js +464 -52
  74. package/dist/src/commands/task.js +551 -85
  75. package/dist/src/commands.js +701 -151
  76. package/dist/src/index.js +705 -151
  77. package/dist/src/launcher.js +4 -0
  78. package/package.json +8 -8
package/dist/src/index.js CHANGED
@@ -1053,12 +1053,28 @@ function readRepoConnection(projectRoot) {
1053
1053
  selected,
1054
1054
  project: typeof record.project === "string" ? record.project : undefined,
1055
1055
  linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
1056
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
1056
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
1057
+ serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
1058
+ serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
1057
1059
  };
1058
1060
  }
1059
1061
  function writeRepoConnection(projectRoot, state) {
1060
1062
  writeJsonFile2(resolveRepoConnectionPath(projectRoot), state);
1061
1063
  }
1064
+ function rootAllowedForSelection(repo, connection) {
1065
+ const root = repo.serverProjectRoot?.trim();
1066
+ if (!root)
1067
+ return;
1068
+ if (connection.kind === "remote") {
1069
+ if (repo.serverProjectRootAlias !== repo.selected)
1070
+ return;
1071
+ if (repo.serverProjectRootBaseUrl !== connection.baseUrl)
1072
+ return;
1073
+ } else if (repo.serverProjectRootAlias && repo.serverProjectRootAlias !== repo.selected) {
1074
+ return;
1075
+ }
1076
+ return root;
1077
+ }
1062
1078
  function resolveSelectedConnection(projectRoot, options = {}) {
1063
1079
  const repo = readRepoConnection(projectRoot);
1064
1080
  if (!repo)
@@ -1070,13 +1086,41 @@ function resolveSelectedConnection(projectRoot, options = {}) {
1070
1086
  if (!connection) {
1071
1087
  throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
1072
1088
  }
1073
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
1089
+ return { alias: repo.selected, connection, serverProjectRoot: rootAllowedForSelection(repo, connection) };
1090
+ }
1091
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot, metadata = {}) {
1092
+ const repo = readRepoConnection(projectRoot);
1093
+ if (!repo)
1094
+ return;
1095
+ let inferred = metadata;
1096
+ if (!inferred.alias || !inferred.baseUrl) {
1097
+ try {
1098
+ const selected = resolveSelectedConnection(projectRoot);
1099
+ if (selected?.connection.kind === "remote") {
1100
+ inferred = {
1101
+ alias: inferred.alias ?? selected.alias,
1102
+ baseUrl: inferred.baseUrl ?? selected.connection.baseUrl
1103
+ };
1104
+ }
1105
+ } catch {}
1106
+ }
1107
+ writeRepoConnection(projectRoot, {
1108
+ ...repo,
1109
+ ...metadata.project ? { project: metadata.project } : {},
1110
+ serverProjectRoot,
1111
+ ...inferred.alias ? { serverProjectRootAlias: inferred.alias } : {},
1112
+ ...inferred.baseUrl ? { serverProjectRootBaseUrl: inferred.baseUrl.replace(/\/+$/, "") } : {}
1113
+ });
1074
1114
  }
1075
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
1115
+ function clearRepoServerProjectRoot(projectRoot) {
1076
1116
  const repo = readRepoConnection(projectRoot);
1077
1117
  if (!repo)
1078
1118
  return;
1079
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
1119
+ writeRepoConnection(projectRoot, {
1120
+ selected: repo.selected,
1121
+ ...repo.project ? { project: repo.project } : {},
1122
+ ...repo.linkedAt ? { linkedAt: repo.linkedAt } : {}
1123
+ });
1080
1124
  }
1081
1125
  function isRemoteConnectionSelected(projectRoot) {
1082
1126
  return resolveSelectedConnection(projectRoot)?.connection.kind === "remote";
@@ -1086,8 +1130,8 @@ var init__connection_state = __esm(() => {
1086
1130
  });
1087
1131
 
1088
1132
  // packages/cli/src/commands/_server-client.ts
1089
- import { existsSync as existsSync7, readFileSync as readFileSync4 } from "fs";
1090
- import { resolve as resolve11 } from "path";
1133
+ import { existsSync as existsSync7, mkdirSync as mkdirSync7, readFileSync as readFileSync4, writeFileSync as writeFileSync5 } from "fs";
1134
+ import { dirname as dirname3, isAbsolute, resolve as resolve11 } from "path";
1091
1135
  import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
1092
1136
  function setServerPhaseListener(listener) {
1093
1137
  const previous = serverPhaseListener;
@@ -1133,11 +1177,10 @@ function readStoredGitHubAuthToken(projectRoot) {
1133
1177
  const parsed = readRemoteAuthState(projectRoot);
1134
1178
  return parsed ? cleanToken(typeof parsed.token === "string" ? parsed.token : undefined) : null;
1135
1179
  }
1136
- function inferRemoteServerProjectRootFromAuthState(projectRoot) {
1137
- const repo = readRepoConnection(projectRoot);
1138
- const slug = repo?.project?.trim();
1139
- if (!slug || !/^[^/]+\/[^/]+$/.test(slug))
1180
+ function inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug) {
1181
+ if (!/^[^/]+\/[^/]+$/.test(repoSlug))
1140
1182
  return null;
1183
+ const repo = readRepoConnection(projectRoot);
1141
1184
  const auth = readRemoteAuthState(projectRoot);
1142
1185
  const authUpdatedAt = typeof auth?.updatedAt === "string" ? Date.parse(auth.updatedAt) : Number.NaN;
1143
1186
  const repoLinkedAt = typeof repo?.linkedAt === "string" ? Date.parse(repo.linkedAt) : Number.NaN;
@@ -1146,25 +1189,419 @@ function inferRemoteServerProjectRootFromAuthState(projectRoot) {
1146
1189
  const checkoutBaseDir = typeof auth?.checkoutBaseDir === "string" && auth.checkoutBaseDir.trim() ? auth.checkoutBaseDir.trim() : null;
1147
1190
  if (!checkoutBaseDir)
1148
1191
  return null;
1149
- const inferred = `${checkoutBaseDir.replace(/\/+$/, "")}/${slug}`;
1150
- writeRepoServerProjectRoot(projectRoot, inferred);
1151
- return inferred;
1192
+ return `${checkoutBaseDir.replace(/\/+$/, "")}/${repoSlug}`;
1152
1193
  }
1153
1194
  function readLocalConnectionFallbackToken(projectRoot) {
1154
1195
  return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
1155
1196
  }
1197
+ function normalizeRepoSlug(value) {
1198
+ const slug = value?.trim();
1199
+ return slug && /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
1200
+ }
1201
+ function readProjectLinkSlug(projectRoot) {
1202
+ const path = resolve11(projectRoot, ".rig", "state", "project-link.json");
1203
+ if (!existsSync7(path))
1204
+ return null;
1205
+ try {
1206
+ const parsed = JSON.parse(readFileSync4(path, "utf8"));
1207
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1208
+ return null;
1209
+ return normalizeRepoSlug(typeof parsed.repoSlug === "string" ? String(parsed.repoSlug) : null);
1210
+ } catch {
1211
+ return null;
1212
+ }
1213
+ }
1214
+ function writeProjectLinkConnection(projectRoot, repoSlug, alias) {
1215
+ const path = resolve11(projectRoot, ".rig", "state", "project-link.json");
1216
+ mkdirSync7(dirname3(path), { recursive: true });
1217
+ writeFileSync5(path, `${JSON.stringify({ repoSlug, connection: alias, linkedAt: new Date().toISOString() }, null, 2)}
1218
+ `, "utf8");
1219
+ }
1220
+ function remoteLinkRepairCommand(repoSlug) {
1221
+ return repoSlug ? `rig server repair-link --repo ${repoSlug}` : "rig server repair-link --repo owner/repo";
1222
+ }
1223
+ function formatRemoteProjectLinkHint(resolution) {
1224
+ const repair = remoteLinkRepairCommand(resolution.repoSlug);
1225
+ if (resolution.status === "auth_required") {
1226
+ 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}` : ""}\`.`;
1227
+ }
1228
+ if (resolution.status === "missing_project") {
1229
+ return `Record the repo slug, then run \`${repair}\` (or \`rig init --repo owner/repo --server remote --github-auth device\`).`;
1230
+ }
1231
+ if (resolution.status === "not_remote")
1232
+ return "Select a remote server with `rig server use <alias>` before repairing a remote project link.";
1233
+ return `Run \`${repair}\` to backfill or prepare a server-host checkout for the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}.`;
1234
+ }
1235
+ function remoteProjectLinkFailure(input) {
1236
+ const partial = {
1237
+ status: input.status,
1238
+ alias: input.alias,
1239
+ baseUrl: input.baseUrl,
1240
+ repoSlug: input.repoSlug
1241
+ };
1242
+ return {
1243
+ ok: false,
1244
+ ...input,
1245
+ hint: formatRemoteProjectLinkHint(partial),
1246
+ next: remoteLinkRepairCommand(input.repoSlug)
1247
+ };
1248
+ }
1249
+ function remoteProjectLinkSuccess(input) {
1250
+ return {
1251
+ ok: true,
1252
+ status: input.status,
1253
+ alias: input.alias,
1254
+ baseUrl: input.baseUrl,
1255
+ repoSlug: input.repoSlug,
1256
+ serverProjectRoot: input.serverProjectRoot,
1257
+ source: input.source,
1258
+ prepared: input.prepared ?? input.status === "prepared",
1259
+ validated: input.validated ?? false,
1260
+ message: input.message ?? `Remote project link ready for ${input.repoSlug}.`,
1261
+ hint: "Remote-scoped task/run/status requests will send x-rig-project-root for this server-host checkout.",
1262
+ next: "rig task list"
1263
+ };
1264
+ }
1265
+ function localCheckoutPathCandidate(projectRoot, candidate) {
1266
+ try {
1267
+ const local = resolve11(projectRoot);
1268
+ const resolved = resolve11(candidate);
1269
+ return resolved === local || resolved.startsWith(`${local}/`);
1270
+ } catch {
1271
+ return false;
1272
+ }
1273
+ }
1274
+ async function requestRemoteProjectLinkJson(baseUrl, pathname, authToken, init = {}) {
1275
+ const requestUrl = new URL(`${baseUrl}${pathname}`);
1276
+ if (authToken && queryAuthFallbackEnabled())
1277
+ requestUrl.searchParams.set("rt", authToken);
1278
+ const response = await fetch(requestUrl, {
1279
+ ...init,
1280
+ headers: mergeHeaders(init.headers, authToken)
1281
+ });
1282
+ const text = await response.text();
1283
+ const payload = text.trim().length > 0 ? (() => {
1284
+ try {
1285
+ return JSON.parse(text);
1286
+ } catch {
1287
+ return null;
1288
+ }
1289
+ })() : null;
1290
+ return { ok: response.ok, status: response.status, payload, text };
1291
+ }
1292
+ function payloadError(payload, fallback) {
1293
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
1294
+ const record = payload;
1295
+ const value = record.error ?? record.message ?? record.reason;
1296
+ if (typeof value === "string" && value.trim())
1297
+ return value.trim();
1298
+ }
1299
+ return fallback;
1300
+ }
1301
+ function checkoutPathsFromProjectPayload(payload) {
1302
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
1303
+ return [];
1304
+ const project = payload.project;
1305
+ if (!project || typeof project !== "object" || Array.isArray(project))
1306
+ return [];
1307
+ const checkouts = project.checkouts;
1308
+ if (!Array.isArray(checkouts))
1309
+ return [];
1310
+ return [...checkouts].reverse().flatMap((entry) => {
1311
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
1312
+ return [];
1313
+ const path = entry.path;
1314
+ return typeof path === "string" && path.trim() ? [path.trim()] : [];
1315
+ });
1316
+ }
1317
+ function checkoutPathFromPreparePayload(payload) {
1318
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
1319
+ return null;
1320
+ const checkout = payload.checkout;
1321
+ if (!checkout || typeof checkout !== "object" || Array.isArray(checkout))
1322
+ return null;
1323
+ const path = checkout.path;
1324
+ return typeof path === "string" && path.trim() ? path.trim() : null;
1325
+ }
1326
+ async function validateAndPersistRemoteRoot(input) {
1327
+ const candidate = input.candidate.trim();
1328
+ if (!candidate || !isAbsolute(candidate)) {
1329
+ return remoteProjectLinkFailure({
1330
+ status: "invalid_root",
1331
+ alias: input.alias,
1332
+ baseUrl: input.baseUrl,
1333
+ repoSlug: input.repoSlug,
1334
+ message: `Remote project root candidate is not an absolute server-host path: ${candidate || "(empty)"}.`
1335
+ });
1336
+ }
1337
+ if (localCheckoutPathCandidate(input.projectRoot, candidate)) {
1338
+ return remoteProjectLinkFailure({
1339
+ status: "invalid_root",
1340
+ alias: input.alias,
1341
+ baseUrl: input.baseUrl,
1342
+ repoSlug: input.repoSlug,
1343
+ message: `Refusing to use local checkout path ${candidate} as a remote server project root.`
1344
+ });
1345
+ }
1346
+ let response;
1347
+ try {
1348
+ response = await requestRemoteProjectLinkJson(input.baseUrl, "/api/server/project-root", input.authToken, {
1349
+ method: "POST",
1350
+ headers: { "content-type": "application/json" },
1351
+ body: JSON.stringify({ projectRoot: candidate })
1352
+ });
1353
+ } catch (error) {
1354
+ return remoteProjectLinkFailure({
1355
+ status: "error",
1356
+ alias: input.alias,
1357
+ baseUrl: input.baseUrl,
1358
+ repoSlug: input.repoSlug,
1359
+ message: `Could not validate remote project root ${candidate}: ${error instanceof Error ? error.message : String(error)}`
1360
+ });
1361
+ }
1362
+ if (response.status === 401 || response.status === 403) {
1363
+ return remoteProjectLinkFailure({
1364
+ status: "auth_required",
1365
+ alias: input.alias,
1366
+ baseUrl: input.baseUrl,
1367
+ repoSlug: input.repoSlug,
1368
+ statusCode: response.status,
1369
+ message: `Remote server ${input.alias} requires authentication before validating project root ${candidate}.`
1370
+ });
1371
+ }
1372
+ if (!response.ok) {
1373
+ return remoteProjectLinkFailure({
1374
+ status: "invalid_root",
1375
+ alias: input.alias,
1376
+ baseUrl: input.baseUrl,
1377
+ repoSlug: input.repoSlug,
1378
+ statusCode: response.status,
1379
+ message: `Remote server rejected project root ${candidate} (${response.status}): ${payloadError(response.payload, response.text || "project-root validation failed")}`
1380
+ });
1381
+ }
1382
+ const record = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload) ? response.payload : {};
1383
+ if (record.ok !== true) {
1384
+ return remoteProjectLinkFailure({
1385
+ status: "invalid_root",
1386
+ alias: input.alias,
1387
+ baseUrl: input.baseUrl,
1388
+ repoSlug: input.repoSlug,
1389
+ message: `Remote server did not accept project root ${candidate}: ${payloadError(response.payload, "project-root validation failed")}`
1390
+ });
1391
+ }
1392
+ const accepted = typeof record.projectRoot === "string" && record.projectRoot.trim() ? record.projectRoot.trim() : typeof record.requestedProjectRoot === "string" && record.requestedProjectRoot.trim() ? record.requestedProjectRoot.trim() : candidate;
1393
+ writeRepoServerProjectRoot(input.projectRoot, accepted, { alias: input.alias, baseUrl: input.baseUrl, project: input.repoSlug });
1394
+ writeProjectLinkConnection(input.projectRoot, input.repoSlug, input.alias);
1395
+ const status = input.status ?? (input.prepared ? "prepared" : "backfilled");
1396
+ return remoteProjectLinkSuccess({
1397
+ status,
1398
+ alias: input.alias,
1399
+ baseUrl: input.baseUrl,
1400
+ repoSlug: input.repoSlug,
1401
+ serverProjectRoot: accepted,
1402
+ source: input.source,
1403
+ prepared: input.prepared,
1404
+ validated: true,
1405
+ 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}.`
1406
+ });
1407
+ }
1408
+ async function ensureRemoteProjectRootLink(projectRoot, options = {}) {
1409
+ let selected;
1410
+ try {
1411
+ selected = resolveSelectedConnection(projectRoot);
1412
+ } catch (error) {
1413
+ return remoteProjectLinkFailure({ status: "error", message: error instanceof Error ? error.message : String(error) });
1414
+ }
1415
+ if (!selected || selected.connection.kind !== "remote") {
1416
+ return remoteProjectLinkFailure({ status: "not_remote", message: "No remote Rig server is selected for this repo." });
1417
+ }
1418
+ const repo = readRepoConnection(projectRoot);
1419
+ const explicitRepoRequested = options.repoSlug !== undefined;
1420
+ const explicitRepoSlug = explicitRepoRequested ? normalizeRepoSlug(options.repoSlug) : null;
1421
+ const repoProjectSlug = normalizeRepoSlug(repo?.project);
1422
+ const repoSlug = explicitRepoSlug ?? repoProjectSlug ?? readProjectLinkSlug(projectRoot);
1423
+ const alias = selected.alias;
1424
+ const baseUrl = selected.connection.baseUrl;
1425
+ const authToken = options.authToken === undefined ? readGitHubBearerTokenForRemote(projectRoot) : options.authToken;
1426
+ const mode = options.mode ?? "backfill-only";
1427
+ if (explicitRepoRequested && !explicitRepoSlug) {
1428
+ return remoteProjectLinkFailure({
1429
+ status: "missing_project",
1430
+ alias,
1431
+ baseUrl,
1432
+ message: `Invalid --repo value ${JSON.stringify(options.repoSlug)}. Expected owner/repo.`
1433
+ });
1434
+ }
1435
+ if (!repoSlug) {
1436
+ return remoteProjectLinkFailure({
1437
+ status: "missing_project",
1438
+ alias,
1439
+ baseUrl,
1440
+ message: `Remote server ${alias} is selected, but this checkout has no GitHub repo slug recorded.`
1441
+ });
1442
+ }
1443
+ const skippedCandidates = [];
1444
+ const storedRoot = selected.serverProjectRoot?.trim() || null;
1445
+ const storedRootMatchesResolvedRepo = repoProjectSlug === repoSlug;
1446
+ if (storedRoot && storedRootMatchesResolvedRepo) {
1447
+ if (localCheckoutPathCandidate(projectRoot, storedRoot)) {
1448
+ clearRepoServerProjectRoot(projectRoot);
1449
+ skippedCandidates.push(storedRoot);
1450
+ } else {
1451
+ const storedResult = await validateAndPersistRemoteRoot({
1452
+ projectRoot,
1453
+ alias,
1454
+ baseUrl,
1455
+ authToken,
1456
+ repoSlug,
1457
+ candidate: storedRoot,
1458
+ source: "stored",
1459
+ status: "ready"
1460
+ });
1461
+ if (storedResult.ok || storedResult.status === "auth_required" || storedResult.status === "error")
1462
+ return storedResult;
1463
+ clearRepoServerProjectRoot(projectRoot);
1464
+ skippedCandidates.push(storedRoot);
1465
+ }
1466
+ } else if (storedRoot) {
1467
+ skippedCandidates.push(storedRoot);
1468
+ }
1469
+ const authCandidate = inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug);
1470
+ if (authCandidate) {
1471
+ const authResult = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: authCandidate, source: "auth-state" });
1472
+ if (authResult.ok || authResult.status === "auth_required")
1473
+ return authResult;
1474
+ }
1475
+ let registryResponse;
1476
+ try {
1477
+ registryResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}`, authToken);
1478
+ } catch (error) {
1479
+ return remoteProjectLinkFailure({
1480
+ status: "error",
1481
+ alias,
1482
+ baseUrl,
1483
+ repoSlug,
1484
+ message: `Could not read remote project registry for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
1485
+ });
1486
+ }
1487
+ if (registryResponse.status === 401 || registryResponse.status === 403) {
1488
+ return remoteProjectLinkFailure({
1489
+ status: "auth_required",
1490
+ alias,
1491
+ baseUrl,
1492
+ repoSlug,
1493
+ statusCode: registryResponse.status,
1494
+ message: `Remote server ${alias} requires authentication before reading the ${repoSlug} project registry.`
1495
+ });
1496
+ }
1497
+ if (registryResponse.ok) {
1498
+ const candidates = checkoutPathsFromProjectPayload(registryResponse.payload);
1499
+ for (const candidate of candidates) {
1500
+ const result = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate, source: "registry" });
1501
+ if (result.ok || result.status === "auth_required")
1502
+ return result;
1503
+ skippedCandidates.push(candidate);
1504
+ }
1505
+ if (mode === "backfill-only") {
1506
+ return remoteProjectLinkFailure({
1507
+ status: candidates.length > 0 ? "invalid_root" : "no_server_checkout",
1508
+ alias,
1509
+ baseUrl,
1510
+ repoSlug,
1511
+ 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.`,
1512
+ skippedCandidates
1513
+ });
1514
+ }
1515
+ } else if (registryResponse.status === 404) {
1516
+ if (mode === "backfill-only") {
1517
+ return remoteProjectLinkFailure({
1518
+ status: "project_not_registered",
1519
+ alias,
1520
+ baseUrl,
1521
+ repoSlug,
1522
+ statusCode: registryResponse.status,
1523
+ message: `Remote server ${alias} has no registered project record for ${repoSlug}.`
1524
+ });
1525
+ }
1526
+ } else {
1527
+ return remoteProjectLinkFailure({
1528
+ status: "error",
1529
+ alias,
1530
+ baseUrl,
1531
+ repoSlug,
1532
+ statusCode: registryResponse.status,
1533
+ message: `Could not backfill ${repoSlug} from remote registry (${registryResponse.status}): ${payloadError(registryResponse.payload, registryResponse.text || "registry lookup failed")}`,
1534
+ skippedCandidates
1535
+ });
1536
+ }
1537
+ let prepareResponse;
1538
+ try {
1539
+ prepareResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}/prepare-checkout`, authToken, {
1540
+ method: "POST",
1541
+ headers: { "content-type": "application/json" },
1542
+ body: JSON.stringify({ checkout: { kind: "managed-clone" }, repoUrl: `https://github.com/${repoSlug}.git` })
1543
+ });
1544
+ } catch (error) {
1545
+ return remoteProjectLinkFailure({
1546
+ status: "error",
1547
+ alias,
1548
+ baseUrl,
1549
+ repoSlug,
1550
+ message: `Could not prepare remote checkout for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
1551
+ });
1552
+ }
1553
+ if (prepareResponse.status === 401 || prepareResponse.status === 403) {
1554
+ return remoteProjectLinkFailure({
1555
+ status: "auth_required",
1556
+ alias,
1557
+ baseUrl,
1558
+ repoSlug,
1559
+ statusCode: prepareResponse.status,
1560
+ message: `Remote server ${alias} requires authentication before preparing ${repoSlug}.`
1561
+ });
1562
+ }
1563
+ if (!prepareResponse.ok) {
1564
+ return remoteProjectLinkFailure({
1565
+ status: "error",
1566
+ alias,
1567
+ baseUrl,
1568
+ repoSlug,
1569
+ statusCode: prepareResponse.status,
1570
+ message: `Remote checkout prepare failed for ${repoSlug} (${prepareResponse.status}): ${payloadError(prepareResponse.payload, prepareResponse.text || "prepare-checkout failed")}`,
1571
+ skippedCandidates
1572
+ });
1573
+ }
1574
+ const preparedPath = checkoutPathFromPreparePayload(prepareResponse.payload);
1575
+ if (!preparedPath) {
1576
+ return remoteProjectLinkFailure({
1577
+ status: "invalid_root",
1578
+ alias,
1579
+ baseUrl,
1580
+ repoSlug,
1581
+ message: `Remote checkout prepare for ${repoSlug} did not return a checkout.path.`,
1582
+ skippedCandidates
1583
+ });
1584
+ }
1585
+ return validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: preparedPath, source: "prepare", prepared: true });
1586
+ }
1587
+ async function repairRemoteProjectRootLink(context, options = {}) {
1588
+ const resolution = await ensureRemoteProjectRootLink(context.projectRoot, { mode: options.mode ?? "prepare-if-missing", repoSlug: options.repoSlug });
1589
+ if (!resolution.ok)
1590
+ throw new CliError(resolution.message, 1, { hint: resolution.hint });
1591
+ return resolution;
1592
+ }
1156
1593
  async function ensureServerForCli(projectRoot) {
1157
1594
  try {
1158
1595
  const selected = resolveSelectedConnection(projectRoot);
1159
1596
  if (selected?.connection.kind === "remote") {
1160
1597
  reportServerPhase(`Connecting to ${selected.alias}\u2026`);
1161
1598
  const authToken = readGitHubBearerTokenForRemote(projectRoot);
1162
- const serverProjectRoot = selected.serverProjectRoot ?? inferRemoteServerProjectRootFromAuthState(projectRoot) ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
1599
+ const link = await ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only", authToken });
1163
1600
  return {
1164
1601
  baseUrl: selected.connection.baseUrl,
1165
1602
  authToken,
1166
1603
  connectionKind: "remote",
1167
- serverProjectRoot
1604
+ serverProjectRoot: link.ok ? link.serverProjectRoot ?? null : null
1168
1605
  };
1169
1606
  }
1170
1607
  reportServerPhase("Starting local Rig server\u2026");
@@ -1182,32 +1619,6 @@ async function ensureServerForCli(projectRoot) {
1182
1619
  throw error;
1183
1620
  }
1184
1621
  }
1185
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
1186
- const repo = readRepoConnection(projectRoot);
1187
- const slug = repo?.project?.trim();
1188
- if (!slug)
1189
- return null;
1190
- try {
1191
- const url = new URL(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`);
1192
- if (authToken && queryAuthFallbackEnabled())
1193
- url.searchParams.set("rt", authToken);
1194
- const response = await fetch(url, {
1195
- headers: mergeHeaders(undefined, authToken)
1196
- });
1197
- if (!response.ok)
1198
- return null;
1199
- const payload = await response.json();
1200
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
1201
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
1202
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
1203
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
1204
- if (path)
1205
- writeRepoServerProjectRoot(projectRoot, path);
1206
- return path;
1207
- } catch {
1208
- return null;
1209
- }
1210
- }
1211
1622
  function appendTaskFilterParams(url, filters) {
1212
1623
  if (filters.assignee)
1213
1624
  url.searchParams.set("assignee", filters.assignee);
@@ -1308,13 +1719,20 @@ function canUseRemoteWithoutProjectRoot(pathname) {
1308
1719
  async function requestServerJson(context, pathname, init = {}) {
1309
1720
  const server = await ensureServerForCli(context.projectRoot);
1310
1721
  const requestUrl = new URL(`${server.baseUrl}${pathname}`);
1311
- if (server.connectionKind === "remote" && !server.serverProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
1312
- const repo = readRepoConnection(context.projectRoot);
1313
- 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." });
1722
+ let scopedServerProjectRoot = server.serverProjectRoot;
1723
+ if (server.connectionKind === "remote" && !scopedServerProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
1724
+ const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: server.authToken });
1725
+ if (link.ok && link.serverProjectRoot) {
1726
+ scopedServerProjectRoot = link.serverProjectRoot;
1727
+ } else {
1728
+ const repo = readRepoConnection(context.projectRoot);
1729
+ const target = link.alias && link.baseUrl ? `${link.alias} (${link.baseUrl})` : server.baseUrl;
1730
+ 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 });
1731
+ }
1314
1732
  }
1315
1733
  const headers = mergeHeaders(init.headers, server.authToken);
1316
- if (server.serverProjectRoot)
1317
- headers.set("x-rig-project-root", server.serverProjectRoot);
1734
+ if (scopedServerProjectRoot)
1735
+ headers.set("x-rig-project-root", scopedServerProjectRoot);
1318
1736
  if (server.connectionKind === "remote" && server.authToken && queryAuthFallbackEnabled()) {
1319
1737
  requestUrl.searchParams.set("rt", server.authToken);
1320
1738
  }
@@ -1680,6 +2098,14 @@ function permissionAllowsPr(payload) {
1680
2098
  function isNotFoundError(error) {
1681
2099
  return /\b(404|not found)\b/i.test(message(error));
1682
2100
  }
2101
+ function isLoopbackBaseUrl(baseUrl) {
2102
+ try {
2103
+ const host = new URL(baseUrl).hostname.toLowerCase();
2104
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
2105
+ } catch {
2106
+ return false;
2107
+ }
2108
+ }
1683
2109
  function projectCheckoutReady(payload) {
1684
2110
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
1685
2111
  return null;
@@ -1734,25 +2160,37 @@ async function runFastTaskRunPreflight(context, options = {}) {
1734
2160
  }
1735
2161
  const repo = readRepoConnection(context.projectRoot);
1736
2162
  const remoteWithoutProjectLink = selectedServer?.connectionKind === "remote" && !repo?.project;
1737
- 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>`."));
2163
+ let remoteRootBlocked = false;
2164
+ 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>`."));
2165
+ if (selectedServer?.connectionKind === "remote" && repo?.project && !selectedServer.serverProjectRoot) {
2166
+ const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: selectedServer.authToken });
2167
+ const loopbackDevRemote = !selectedServer.authToken && isLoopbackBaseUrl(selectedServer.baseUrl);
2168
+ 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));
2169
+ remoteRootBlocked = !link.ok && !loopbackDevRemote;
2170
+ }
1738
2171
  try {
1739
2172
  const auth = await request("/api/github/auth/status");
1740
2173
  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>`."));
1741
2174
  } catch (error) {
1742
2175
  checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
1743
2176
  }
1744
- try {
1745
- const projection = await request("/api/workspace/task-projection");
1746
- checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
1747
- } catch (error) {
1748
- checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
1749
- }
1750
- try {
1751
- const permissions = await request("/api/github/repo/permissions");
1752
- const allowed = permissionAllowsPr(permissions);
1753
- 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."));
1754
- } catch (error) {
1755
- checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
2177
+ if (!remoteRootBlocked) {
2178
+ try {
2179
+ const projection = await request("/api/workspace/task-projection");
2180
+ checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
2181
+ } catch (error) {
2182
+ checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
2183
+ }
2184
+ try {
2185
+ const permissions = await request("/api/github/repo/permissions");
2186
+ const allowed = permissionAllowsPr(permissions);
2187
+ 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."));
2188
+ } catch (error) {
2189
+ checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
2190
+ }
2191
+ } else {
2192
+ checks.push(preflightCheck("task-projection", "task projection ready", "warn", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
2193
+ 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."));
1756
2194
  }
1757
2195
  if (repo?.project) {
1758
2196
  try {
@@ -1764,19 +2202,24 @@ async function runFastTaskRunPreflight(context, options = {}) {
1764
2202
  }
1765
2203
  }
1766
2204
  if (taskId) {
1767
- try {
1768
- const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
1769
- const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
1770
- 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."));
1771
- } catch (error) {
1772
- checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
1773
- }
1774
- try {
1775
- const runs = await request("/api/runs?limit=200");
1776
- const duplicate = activeDuplicateRun(runs, taskId);
1777
- 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));
1778
- } catch (error) {
1779
- 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."));
2205
+ if (!remoteRootBlocked) {
2206
+ try {
2207
+ const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
2208
+ const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
2209
+ 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."));
2210
+ } catch (error) {
2211
+ checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
2212
+ }
2213
+ try {
2214
+ const runs = await request("/api/runs?limit=200");
2215
+ const duplicate = activeDuplicateRun(runs, taskId);
2216
+ 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));
2217
+ } catch (error) {
2218
+ 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."));
2219
+ }
2220
+ } else {
2221
+ checks.push(preflightCheck("issue", "task/issue accessible", "fail", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
2222
+ 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."));
1780
2223
  }
1781
2224
  }
1782
2225
  if ((options.runtimeAdapter ?? "pi") === "pi") {
@@ -2260,16 +2703,19 @@ function formatConnectionList(connections) {
2260
2703
  return [formatSection("Rig servers", `${rows.length} available`), `${pc3.bold(pad("ALIAS", aliasWidth))} ${pc3.bold("KIND")} ${pc3.bold("TARGET")}`, ...lines, "", ...formatNextSteps(["Select one: `rig server use <alias|local>`"])].join(`
2261
2704
  `);
2262
2705
  }
2263
- function formatConnectionStatus(selected, connections) {
2706
+ function formatConnectionStatus(selected, connections, repo, remoteProjectLink) {
2264
2707
  const connection = selected === "local" ? { kind: "local", mode: "auto" } : connections[selected];
2265
2708
  const target = !connection ? "not configured" : connection.kind === "remote" ? connection.baseUrl : "local";
2709
+ 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";
2266
2710
  return [
2267
2711
  formatSection("Rig server", "selected for this repo"),
2268
2712
  `${themeFaint("\u2502")} ${themeDim("selected ")} ${pc3.bold(selected)}`,
2269
2713
  `${themeFaint("\u2502")} ${themeDim("kind ")} ${formatStatusPill(connection?.kind ?? "unknown")}`,
2270
2714
  `${themeFaint("\u2502")} ${themeDim("target ")} ${target ?? "not configured"}`,
2715
+ ...repo?.project ? [`${themeFaint("\u2502")} ${themeDim("project ")} ${repo.project}`] : [],
2716
+ ...connection?.kind === "remote" ? [`${themeFaint("\u2502")} ${themeDim("root ")} ${rootLabel}`] : [],
2271
2717
  "",
2272
- ...formatNextSteps(["Change: `rig server use <alias|local>`", "List saved servers: `rig server list`"])
2718
+ ...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`"])
2273
2719
  ].join(`
2274
2720
  `);
2275
2721
  }
@@ -2768,7 +3214,7 @@ var init__operator_surface = __esm(() => {
2768
3214
  });
2769
3215
 
2770
3216
  // packages/cli/src/commands/_pi-frontend.ts
2771
- import { existsSync as existsSync15, mkdirSync as mkdirSync10, mkdtempSync, readFileSync as readFileSync10, rmSync as rmSync5, writeFileSync as writeFileSync7 } from "fs";
3217
+ import { existsSync as existsSync15, mkdirSync as mkdirSync11, mkdtempSync, readFileSync as readFileSync10, rmSync as rmSync5, writeFileSync as writeFileSync8 } from "fs";
2772
3218
  import { homedir as homedir6, tmpdir } from "os";
2773
3219
  import { join as join3 } from "path";
2774
3220
  import { main as runPiMain } from "@earendil-works/pi-coding-agent";
@@ -2820,7 +3266,7 @@ function statusFromRunDetails(run) {
2820
3266
  async function prepareOperatorConsole(context, runId, tempSessionDir) {
2821
3267
  const server = await ensureServerForCli(context.projectRoot);
2822
3268
  const localCwd = join3(homedir6(), ".rig", "drones", runId.slice(0, 8));
2823
- mkdirSync10(localCwd, { recursive: true });
3269
+ mkdirSync11(localCwd, { recursive: true });
2824
3270
  trustDroneCwd(localCwd);
2825
3271
  installRigPiTheme();
2826
3272
  let sessionFileArg = [];
@@ -2842,7 +3288,7 @@ async function prepareOperatorConsole(context, runId, tempSessionDir) {
2842
3288
  return line;
2843
3289
  }).join(`
2844
3290
  `);
2845
- writeFileSync7(localSessionPath, content);
3291
+ writeFileSync8(localSessionPath, content);
2846
3292
  sessionFileArg = ["--session", localSessionPath];
2847
3293
  }
2848
3294
  } catch {}
@@ -2858,12 +3304,12 @@ async function prepareOperatorConsole(context, runId, tempSessionDir) {
2858
3304
  function trustDroneCwd(localCwd) {
2859
3305
  try {
2860
3306
  const agentDir = join3(homedir6(), ".pi", "agent");
2861
- mkdirSync10(agentDir, { recursive: true });
3307
+ mkdirSync11(agentDir, { recursive: true });
2862
3308
  const trustPath = join3(agentDir, "trust.json");
2863
3309
  const store = existsSync15(trustPath) ? JSON.parse(readFileSync10(trustPath, "utf8")) : {};
2864
3310
  if (store[localCwd] !== true) {
2865
3311
  store[localCwd] = true;
2866
- writeFileSync7(trustPath, `${JSON.stringify(store, null, "\t")}
3312
+ writeFileSync8(trustPath, `${JSON.stringify(store, null, "\t")}
2867
3313
  `);
2868
3314
  }
2869
3315
  } catch {}
@@ -2871,15 +3317,38 @@ function trustDroneCwd(localCwd) {
2871
3317
  function installRigPiTheme() {
2872
3318
  try {
2873
3319
  const themesDir = join3(homedir6(), ".pi", "agent", "themes");
2874
- mkdirSync10(themesDir, { recursive: true });
3320
+ mkdirSync11(themesDir, { recursive: true });
2875
3321
  const themePath = join3(themesDir, "rig.json");
2876
3322
  const next = `${JSON.stringify(RIG_PI_THEME, null, "\t")}
2877
3323
  `;
2878
3324
  if (!existsSync15(themePath) || readFileSync10(themePath, "utf8") !== next) {
2879
- writeFileSync7(themePath, next);
3325
+ writeFileSync8(themePath, next);
2880
3326
  }
2881
3327
  } catch {}
2882
3328
  }
3329
+ async function runWithProcessExitGuard(body) {
3330
+ const realExit = process.exit;
3331
+ let exitCode = 0;
3332
+ let signalQuit = () => {};
3333
+ const quit = new Promise((resolve23) => {
3334
+ signalQuit = resolve23;
3335
+ });
3336
+ const guardedExit = (code) => {
3337
+ exitCode = typeof code === "number" ? code : 0;
3338
+ signalQuit();
3339
+ return;
3340
+ };
3341
+ process.exit = guardedExit;
3342
+ try {
3343
+ await Promise.race([Promise.resolve().then(body), quit]);
3344
+ } finally {
3345
+ process.exit = realExit;
3346
+ }
3347
+ return exitCode;
3348
+ }
3349
+ function runPiMainReturningOnQuit(args, options) {
3350
+ return runWithProcessExitGuard(() => runPiMain(args, options));
3351
+ }
2883
3352
  async function attachRunBundledPiFrontend(context, input) {
2884
3353
  const tempSessionDir = mkdtempSync(join3(tmpdir(), "rig-pi-frontend-sessions-"));
2885
3354
  const { server, sessionFileArg } = await withSpinner(`Opening Pi console for run ${input.runId}\u2026`, () => prepareOperatorConsole(context, input.runId, tempSessionDir), { outputMode: context.outputMode });
@@ -2895,16 +3364,20 @@ async function attachRunBundledPiFrontend(context, input) {
2895
3364
  };
2896
3365
  let detached = false;
2897
3366
  try {
2898
- await runPiMain([
3367
+ const piArgs = [
2899
3368
  "--offline",
2900
3369
  "--no-extensions",
2901
3370
  "--no-skills",
2902
3371
  "--no-prompt-templates",
2903
3372
  "--no-context-files",
2904
3373
  ...sessionFileArg
2905
- ], {
2906
- extensionFactories: [piRigExtensionFactory]
2907
- });
3374
+ ];
3375
+ const piOptions = { extensionFactories: [piRigExtensionFactory] };
3376
+ if (input.returnOnQuit) {
3377
+ await runPiMainReturningOnQuit(piArgs, piOptions);
3378
+ } else {
3379
+ await runPiMain(piArgs, piOptions);
3380
+ }
2908
3381
  detached = true;
2909
3382
  } finally {
2910
3383
  restoreEnv();
@@ -3277,12 +3750,13 @@ var init__help_catalog = __esm(() => {
3277
3750
  {
3278
3751
  name: "server",
3279
3752
  summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
3280
- usage: ["rig server <status|list|add|use|start> [options]"],
3753
+ usage: ["rig server <status|list|add|use|repair-link|start> [options]"],
3281
3754
  commands: [
3282
- { command: "status", description: "Show the selected server for this repo.", primary: true },
3755
+ { command: "status", description: "Show the selected server and remote project-root link for this repo.", primary: true },
3283
3756
  { command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
3284
3757
  { command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
3285
3758
  { command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
3759
+ { command: "repair-link [--prepare|--backfill-only] [--repo owner/repo]", description: "Backfill or prepare the selected remote's server-host checkout link.", primary: true },
3286
3760
  { command: "list", description: "List saved local/remote server aliases.", primary: true },
3287
3761
  { command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
3288
3762
  ],
@@ -3290,6 +3764,7 @@ var init__help_catalog = __esm(() => {
3290
3764
  "rig server status",
3291
3765
  "rig server add prod https://where.rig-does.work",
3292
3766
  "rig server use prod",
3767
+ "rig server repair-link --repo owner/repo",
3293
3768
  "rig server use local",
3294
3769
  "rig server start --port 3773"
3295
3770
  ],
@@ -7618,7 +8093,7 @@ import {
7618
8093
  chmodSync,
7619
8094
  copyFileSync as copyFileSync2,
7620
8095
  existsSync as existsSync9,
7621
- mkdirSync as mkdirSync7,
8096
+ mkdirSync as mkdirSync8,
7622
8097
  readdirSync,
7623
8098
  readlinkSync,
7624
8099
  rmSync as rmSync3,
@@ -7735,7 +8210,7 @@ async function executeDist(context, args) {
7735
8210
  requireNoExtraArgs(pending, "rig dist install [--scope user|system] [--path <dir>]");
7736
8211
  const scope = parseInstallScope(scopeResult.value);
7737
8212
  const installDir = resolveInstallDir(scope, pathResult.value);
7738
- mkdirSync7(installDir, { recursive: true });
8213
+ mkdirSync8(installDir, { recursive: true });
7739
8214
  let source = await findLatestDistBinary(context.projectRoot);
7740
8215
  let buildDir = null;
7741
8216
  if (!source) {
@@ -7790,7 +8265,7 @@ async function executeDist(context, args) {
7790
8265
  const fp = await computeRuntimeImageFingerprint(context.projectRoot);
7791
8266
  const currentId = computeRuntimeImageId(fp);
7792
8267
  const imagesDir = resolve14(resolveControlPlaneMonorepoRuntimeDir(context.projectRoot), "images");
7793
- mkdirSync7(imagesDir, { recursive: true });
8268
+ mkdirSync8(imagesDir, { recursive: true });
7794
8269
  let pruned = 0;
7795
8270
  for (const entry of readdirSync(imagesDir, { withFileTypes: true })) {
7796
8271
  if (entry.isDirectory() && entry.name !== currentId) {
@@ -7802,9 +8277,9 @@ async function executeDist(context, args) {
7802
8277
  console.log(`Pruned ${pruned} stale image(s).`);
7803
8278
  }
7804
8279
  const imageDir = resolve14(imagesDir, currentId);
7805
- mkdirSync7(resolve14(imageDir, "bin/hooks"), { recursive: true });
7806
- mkdirSync7(resolve14(imageDir, "bin/plugins"), { recursive: true });
7807
- mkdirSync7(resolve14(imageDir, "bin/validators"), { recursive: true });
8280
+ mkdirSync8(resolve14(imageDir, "bin/hooks"), { recursive: true });
8281
+ mkdirSync8(resolve14(imageDir, "bin/plugins"), { recursive: true });
8282
+ mkdirSync8(resolve14(imageDir, "bin/validators"), { recursive: true });
7808
8283
  const hookNames = [
7809
8284
  "scope-guard",
7810
8285
  "import-guard",
@@ -7829,8 +8304,8 @@ async function executeDist(context, args) {
7829
8304
  const binPluginsDir = resolve14(resolveControlPlaneHostBinDir(context.projectRoot), "plugins");
7830
8305
  const validatorsRoot = resolve14(hostProjectRoot, "packages/runtime/src/control-plane/validators");
7831
8306
  const binValidatorsDir = resolve14(resolveControlPlaneHostBinDir(context.projectRoot), "validators");
7832
- mkdirSync7(binPluginsDir, { recursive: true });
7833
- mkdirSync7(binValidatorsDir, { recursive: true });
8307
+ mkdirSync8(binPluginsDir, { recursive: true });
8308
+ mkdirSync8(binValidatorsDir, { recursive: true });
7834
8309
  if (existsSync9(pluginsDir)) {
7835
8310
  for (const entry of readdirSync(pluginsDir, { withFileTypes: true })) {
7836
8311
  const m = entry.name.match(/^(.+)\.plugin\.(ts|js|mjs|cjs)$/);
@@ -7937,7 +8412,7 @@ init_inbox();
7937
8412
  init_runner();
7938
8413
  init__connection_state();
7939
8414
  init__server_client();
7940
- import { appendFileSync as appendFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync8, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
8415
+ import { appendFileSync as appendFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync9, readFileSync as readFileSync7, writeFileSync as writeFileSync6 } from "fs";
7941
8416
  import { spawnSync } from "child_process";
7942
8417
  import { basename as basename2, resolve as resolve18 } from "path";
7943
8418
  import { buildRigInitConfigSource } from "@rig/core";
@@ -8123,7 +8598,7 @@ async function buildPiSetupChecks(input = {}) {
8123
8598
  // packages/cli/src/commands/_snapshot-upload.ts
8124
8599
  init__server_client();
8125
8600
  import { mkdir, readdir, readFile, writeFile } from "fs/promises";
8126
- import { dirname as dirname3, resolve as resolve16, relative, sep } from "path";
8601
+ import { dirname as dirname4, resolve as resolve16, relative, sep } from "path";
8127
8602
  var SNAPSHOT_ARCHIVE_VERSION = 1;
8128
8603
  var SNAPSHOT_ARCHIVE_CONTENT_TYPE = "application/vnd.rig.snapshot+json";
8129
8604
  var DEFAULT_EXCLUDED_DIRECTORIES = new Set([
@@ -8472,14 +8947,14 @@ function parseRepoSlug(value) {
8472
8947
  }
8473
8948
  function ensureRigPrivateDirs(projectRoot) {
8474
8949
  const rigDir = resolve18(projectRoot, ".rig");
8475
- mkdirSync8(resolve18(rigDir, "state"), { recursive: true });
8476
- mkdirSync8(resolve18(rigDir, "logs"), { recursive: true });
8477
- mkdirSync8(resolve18(rigDir, "runs"), { recursive: true });
8478
- mkdirSync8(resolve18(rigDir, "tmp"), { recursive: true });
8479
- mkdirSync8(resolve18(projectRoot, "artifacts"), { recursive: true });
8950
+ mkdirSync9(resolve18(rigDir, "state"), { recursive: true });
8951
+ mkdirSync9(resolve18(rigDir, "logs"), { recursive: true });
8952
+ mkdirSync9(resolve18(rigDir, "runs"), { recursive: true });
8953
+ mkdirSync9(resolve18(rigDir, "tmp"), { recursive: true });
8954
+ mkdirSync9(resolve18(projectRoot, "artifacts"), { recursive: true });
8480
8955
  const taskConfigPath = resolve18(rigDir, "task-config.json");
8481
8956
  if (!existsSync12(taskConfigPath))
8482
- writeFileSync5(taskConfigPath, `{}
8957
+ writeFileSync6(taskConfigPath, `{}
8483
8958
  `, "utf-8");
8484
8959
  }
8485
8960
  function ensureGitignoreEntries(projectRoot) {
@@ -8507,7 +8982,7 @@ function ensureRigConfigPackageDependencies(projectRoot) {
8507
8982
  ...existsSync12(path) ? existing : { name: "rig-project", private: true },
8508
8983
  devDependencies
8509
8984
  };
8510
- writeFileSync5(path, `${JSON.stringify(next, null, 2)}
8985
+ writeFileSync6(path, `${JSON.stringify(next, null, 2)}
8511
8986
  `, "utf8");
8512
8987
  }
8513
8988
  function applyGitHubProjectConfig(source, options) {
@@ -8533,9 +9008,9 @@ function checkoutForInit(projectRoot, serverKind, strategy) {
8533
9008
  const selected = strategy ?? { kind: "managed-clone" };
8534
9009
  switch (selected.kind) {
8535
9010
  case "managed-clone":
8536
- return { kind: "managed-clone", path: projectRoot };
9011
+ return { kind: "managed-clone" };
8537
9012
  case "current-ref":
8538
- return { kind: "current-ref", path: projectRoot, ...selected.ref ? { ref: selected.ref } : {} };
9013
+ return { kind: "current-ref", ...selected.ref ? { ref: selected.ref } : {} };
8539
9014
  case "uploaded-snapshot":
8540
9015
  return { kind: "uploaded-snapshot", path: projectRoot, source: "local-working-tree" };
8541
9016
  case "existing-path":
@@ -8805,7 +9280,7 @@ function remoteGitHubAuthMetadata(payload) {
8805
9280
  };
8806
9281
  }
8807
9282
  function writeRemoteGitHubAuthState(projectRoot, input) {
8808
- writeFileSync5(resolve18(projectRoot, ".rig", "state", "github-auth.json"), `${JSON.stringify({
9283
+ writeFileSync6(resolve18(projectRoot, ".rig", "state", "github-auth.json"), `${JSON.stringify({
8809
9284
  authenticated: true,
8810
9285
  source: input.source,
8811
9286
  storedOnServer: true,
@@ -8853,7 +9328,7 @@ function runLocalFilesInit(context, options) {
8853
9328
  console.log("rig.config already exists; leaving it unchanged. Pass --repair to rewrite it.");
8854
9329
  } else {
8855
9330
  const projectName = basename2(projectRoot) || "rig-project";
8856
- writeFileSync5(configTsPath, buildRigInitConfigSource({
9331
+ writeFileSync6(configTsPath, buildRigInitConfigSource({
8857
9332
  projectName,
8858
9333
  taskSource: { kind: "files", path: "tasks" },
8859
9334
  useStandardPlugin: true
@@ -8862,8 +9337,8 @@ function runLocalFilesInit(context, options) {
8862
9337
  ensureRigConfigPackageDependencies(projectRoot);
8863
9338
  const tasksDir = resolve18(projectRoot, "tasks");
8864
9339
  if (!existsSync12(tasksDir)) {
8865
- mkdirSync8(tasksDir, { recursive: true });
8866
- writeFileSync5(resolve18(tasksDir, "T-1.json"), `${JSON.stringify({ id: "T-1", title: "My first Rig task", body: "Describe the change you want an agent to make." }, null, 2)}
9340
+ mkdirSync9(tasksDir, { recursive: true });
9341
+ writeFileSync6(resolve18(tasksDir, "T-1.json"), `${JSON.stringify({ id: "T-1", title: "My first Rig task", body: "Describe the change you want an agent to make." }, null, 2)}
8867
9342
  `, "utf-8");
8868
9343
  }
8869
9344
  if (context.outputMode !== "json") {
@@ -8926,7 +9401,7 @@ function runDemoInit(context, options) {
8926
9401
  console.log("rig.config already exists; leaving it unchanged. Pass --repair to rewrite it for the demo.");
8927
9402
  }
8928
9403
  } else {
8929
- writeFileSync5(configTsPath, buildRigInitConfigSource({
9404
+ writeFileSync6(configTsPath, buildRigInitConfigSource({
8930
9405
  projectName: basename2(projectRoot) || "rig-demo",
8931
9406
  taskSource: { kind: "files", path: DEMO_TASKS_RELATIVE_DIR },
8932
9407
  useStandardPlugin: true
@@ -8935,14 +9410,14 @@ function runDemoInit(context, options) {
8935
9410
  }
8936
9411
  ensureRigConfigPackageDependencies(projectRoot);
8937
9412
  const demoTasksDir = resolve18(projectRoot, DEMO_TASKS_RELATIVE_DIR);
8938
- mkdirSync8(demoTasksDir, { recursive: true });
9413
+ mkdirSync9(demoTasksDir, { recursive: true });
8939
9414
  const taskIds = [];
8940
9415
  for (const task of DEMO_TASKS) {
8941
9416
  const id = String(task.id);
8942
9417
  taskIds.push(id);
8943
9418
  const taskPath = resolve18(demoTasksDir, `${id}.json`);
8944
9419
  if (!existsSync12(taskPath)) {
8945
- writeFileSync5(taskPath, `${JSON.stringify(task, null, 2)}
9420
+ writeFileSync6(taskPath, `${JSON.stringify(task, null, 2)}
8946
9421
  `, "utf-8");
8947
9422
  }
8948
9423
  }
@@ -8970,21 +9445,32 @@ function runDemoInit(context, options) {
8970
9445
  }
8971
9446
  async function runControlPlaneInit(context, options) {
8972
9447
  const projectRoot = context.projectRoot;
8973
- const detectedSlug = options.repoSlug ?? detectOriginRepoSlug(projectRoot);
9448
+ const existingRepoConnection = readRepoConnection(projectRoot);
9449
+ const selectedConnection = (() => {
9450
+ try {
9451
+ return resolveSelectedConnection(projectRoot);
9452
+ } catch {
9453
+ return null;
9454
+ }
9455
+ })();
9456
+ const selectedRemote = selectedConnection?.connection.kind === "remote" ? { alias: selectedConnection.alias, connection: selectedConnection.connection } : null;
9457
+ const detectedSlug = options.repoSlug ?? existingRepoConnection?.project ?? detectOriginRepoSlug(projectRoot);
9458
+ const serverKind = options.server ?? (selectedRemote ? "remote" : "local");
8974
9459
  if (!detectedSlug) {
8975
9460
  const authMethod2 = options.githubAuthMethod ?? (options.githubToken ? "token" : "skip");
8976
- if ((options.server ?? "local") === "local" && authMethod2 === "skip") {
9461
+ if (serverKind === "local" && authMethod2 === "skip") {
8977
9462
  return runLocalFilesInit(context, options);
8978
9463
  }
8979
9464
  throw new CliError("Could not detect GitHub repo slug from origin. Pass --repo owner/repo \u2014 or run `rig init --yes --server local --github-auth skip` for a local files-source project without GitHub.", 1);
8980
9465
  }
8981
9466
  const repo = parseRepoSlug(detectedSlug);
8982
- const serverKind = options.server ?? "local";
8983
- const connectionAlias = options.connectionAlias ?? (serverKind === "local" ? "local" : "remote");
9467
+ const connectionAlias = options.connectionAlias ?? (serverKind === "local" ? "local" : selectedRemote?.alias ?? "remote");
9468
+ const selectedRemoteUrl = selectedRemote && (!options.connectionAlias || options.connectionAlias === selectedRemote.alias) ? selectedRemote.connection.baseUrl : undefined;
9469
+ const remoteUrl = serverKind === "remote" ? (options.remoteUrl ?? selectedRemoteUrl)?.replace(/\/+$/, "") : undefined;
8984
9470
  if (serverKind === "remote") {
8985
- if (!options.remoteUrl)
8986
- throw new CliError("Missing --remote-url for --server remote.", 1, { hint: "Re-run as `rig init --server remote --remote-url https://your-rig-server`." });
8987
- upsertGlobalConnection(connectionAlias, { kind: "remote", baseUrl: options.remoteUrl });
9471
+ if (!remoteUrl)
9472
+ throw new CliError("Missing --remote-url for --server remote.", 1, { hint: "Re-run as `rig init --server remote --remote-url https://your-rig-server`, or first select a saved remote with `rig server use <alias>`." });
9473
+ upsertGlobalConnection(connectionAlias, { kind: "remote", baseUrl: remoteUrl });
8988
9474
  }
8989
9475
  writeRepoConnection(projectRoot, {
8990
9476
  selected: connectionAlias,
@@ -9007,11 +9493,11 @@ async function runControlPlaneInit(context, options) {
9007
9493
  taskSource: { kind: "github-issues", owner: repo.owner, repo: repo.repo },
9008
9494
  useStandardPlugin: true
9009
9495
  }), options);
9010
- writeFileSync5(configTsPath, source, "utf-8");
9496
+ writeFileSync6(configTsPath, source, "utf-8");
9011
9497
  }
9012
9498
  ensureRigConfigPackageDependencies(projectRoot);
9013
9499
  }
9014
- writeFileSync5(resolve18(projectRoot, ".rig", "state", "project-link.json"), `${JSON.stringify({ repoSlug: repo.slug, connection: connectionAlias, linkedAt: new Date().toISOString() }, null, 2)}
9500
+ writeFileSync6(resolve18(projectRoot, ".rig", "state", "project-link.json"), `${JSON.stringify({ repoSlug: repo.slug, connection: connectionAlias, linkedAt: new Date().toISOString() }, null, 2)}
9015
9501
  `, "utf8");
9016
9502
  const checkout = checkoutForInit(projectRoot, serverKind, options.remoteCheckout);
9017
9503
  let uploadedSnapshot = null;
@@ -9026,7 +9512,7 @@ async function runControlPlaneInit(context, options) {
9026
9512
  let githubAuth = null;
9027
9513
  let deviceAuth = null;
9028
9514
  const authMethod = options.githubAuthMethod ?? (options.githubToken ? "token" : "skip");
9029
- const remoteGhTokenWarning = serverKind === "remote" && authMethod === "gh" ? `This sends a GitHub token from this machine to ${options.remoteUrl ?? "the remote Rig server"}.` : null;
9515
+ const remoteGhTokenWarning = serverKind === "remote" && authMethod === "gh" ? `This sends a GitHub token from this machine to ${remoteUrl ?? "the remote Rig server"}.` : null;
9030
9516
  if (remoteGhTokenWarning && !options.yes) {
9031
9517
  throw new CliError(`${remoteGhTokenWarning} Re-run with --yes to confirm this explicit token transfer.`, 1);
9032
9518
  }
@@ -9342,8 +9828,8 @@ init__server_client();
9342
9828
  init__connection_state();
9343
9829
  init__async_ui();
9344
9830
  import { spawnSync as spawnSync2 } from "child_process";
9345
- import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync6 } from "fs";
9346
- import { dirname as dirname4, resolve as resolve19 } from "path";
9831
+ import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync7 } from "fs";
9832
+ import { dirname as dirname5, resolve as resolve19 } from "path";
9347
9833
  function printPayload(context, payload, fallback) {
9348
9834
  if (context.outputMode === "json")
9349
9835
  console.log(JSON.stringify(payload, null, 2));
@@ -9382,8 +9868,8 @@ function persistRemoteAuthSession(context, source, result, fallbackToken) {
9382
9868
  return;
9383
9869
  const repo = readRepoConnection(context.projectRoot);
9384
9870
  const path = resolve19(context.projectRoot, ".rig", "state", "github-auth.json");
9385
- mkdirSync9(dirname4(path), { recursive: true });
9386
- writeFileSync6(path, `${JSON.stringify({
9871
+ mkdirSync10(dirname5(path), { recursive: true });
9872
+ writeFileSync7(path, `${JSON.stringify({
9387
9873
  authenticated: true,
9388
9874
  source,
9389
9875
  storedOnServer: true,
@@ -11163,6 +11649,7 @@ init_drone_ui();
11163
11649
  init_runner();
11164
11650
  init__connection_state();
11165
11651
  init__cli_format();
11652
+ init__server_client();
11166
11653
  function usageName(options) {
11167
11654
  return `rig ${options.group}`;
11168
11655
  }
@@ -11182,13 +11669,46 @@ function parseConnection(alias, value, options) {
11182
11669
  }
11183
11670
  return { kind: "remote", baseUrl: parsed.toString().replace(/\/+$/, "") };
11184
11671
  }
11185
- function printJsonOrText(context, payload, text2) {
11186
- if (context.outputMode === "json") {
11187
- console.log(JSON.stringify(payload, null, 2));
11188
- } else {
11672
+ function printJsonOrText(context, _payload, text2) {
11673
+ if (context.outputMode !== "json") {
11189
11674
  console.log(text2);
11190
11675
  }
11191
11676
  }
11677
+ function formatRemoteProjectLinkText(result) {
11678
+ return formatSuccessCard(result.ok ? "Remote project link ready" : "Remote project link needs repair", [
11679
+ ["selected", result.alias ?? "remote"],
11680
+ ["target", result.baseUrl ?? "unknown"],
11681
+ ["repo", result.repoSlug ?? "owner/repo"],
11682
+ ["status", result.status],
11683
+ ...result.serverProjectRoot ? [["server root", result.serverProjectRoot]] : [],
11684
+ ["next", result.ok ? result.next ?? "rig task list" : result.hint]
11685
+ ]);
11686
+ }
11687
+ function parseRepairLinkArgs(rest, usage) {
11688
+ let repoSlug;
11689
+ let mode = "prepare-if-missing";
11690
+ const pending = [...rest];
11691
+ while (pending.length > 0) {
11692
+ const token = pending.shift();
11693
+ if (token === "--repo") {
11694
+ const value = pending.shift()?.trim();
11695
+ if (!value)
11696
+ throw new CliError(`Missing --repo value. Usage: ${usage}`, 1);
11697
+ const normalized = normalizeRepoSlug(value);
11698
+ if (!normalized)
11699
+ throw new CliError(`Invalid --repo value: ${value}`, 1, { hint: "Use the canonical owner/repo slug, e.g. `--repo humanity-org/humanwork`." });
11700
+ repoSlug = normalized;
11701
+ } else if (token === "--backfill-only") {
11702
+ mode = "backfill-only";
11703
+ } else if (token === "--prepare") {
11704
+ mode = "prepare-if-missing";
11705
+ } else {
11706
+ throw new CliError(`Unexpected argument: ${String(token)}
11707
+ Usage: ${usage}`, 1);
11708
+ }
11709
+ }
11710
+ return { repoSlug, mode };
11711
+ }
11192
11712
  async function promptForConnectionAlias(context) {
11193
11713
  const state = readGlobalConnections();
11194
11714
  const repo = readRepoConnection(context.projectRoot);
@@ -11242,37 +11762,67 @@ async function executeConnectionCommand(context, args, options) {
11242
11762
  }
11243
11763
  if (!alias)
11244
11764
  throw new CliError(`Missing alias. Usage: ${usageName(options)} use <alias|local>`, 1);
11765
+ let selectedConnection = { kind: "local", mode: "auto" };
11245
11766
  if (alias !== "local") {
11246
11767
  const state = readGlobalConnections();
11247
- if (!state.connections[alias])
11768
+ const connection = state.connections[alias];
11769
+ if (!connection)
11248
11770
  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>`." });
11771
+ selectedConnection = connection;
11249
11772
  }
11250
11773
  const previousRepo = readRepoConnection(context.projectRoot);
11774
+ const preserveRemoteRoot = Boolean(previousRepo?.serverProjectRoot && previousRepo.selected === alias && selectedConnection.kind === "remote" && previousRepo.serverProjectRootAlias === alias && previousRepo.serverProjectRootBaseUrl === selectedConnection.baseUrl);
11251
11775
  const repoState = {
11252
11776
  selected: alias,
11253
11777
  ...previousRepo?.project ? { project: previousRepo.project } : {},
11254
11778
  linkedAt: new Date().toISOString(),
11255
- ...previousRepo?.serverProjectRoot && previousRepo.selected === alias ? { serverProjectRoot: previousRepo.serverProjectRoot } : {}
11779
+ ...preserveRemoteRoot ? {
11780
+ serverProjectRoot: previousRepo.serverProjectRoot,
11781
+ serverProjectRootAlias: previousRepo.serverProjectRootAlias,
11782
+ serverProjectRootBaseUrl: previousRepo.serverProjectRootBaseUrl
11783
+ } : {}
11256
11784
  };
11257
11785
  writeRepoConnection(context.projectRoot, repoState);
11258
- printJsonOrText(context, repoState, formatSuccessCard("Rig server selected", [
11786
+ const remoteProjectLink = alias !== "local" ? await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only" }).catch((error) => ({
11787
+ ok: false,
11788
+ status: "error",
11789
+ message: error instanceof Error ? error.message : String(error),
11790
+ hint: "Run `rig server repair-link` after authenticating the selected remote."
11791
+ })) : null;
11792
+ const latestRepo = readRepoConnection(context.projectRoot);
11793
+ const details = { selected: latestRepo?.selected ?? alias, repo: latestRepo, remoteProjectLink };
11794
+ printJsonOrText(context, details, formatSuccessCard("Rig server selected", [
11259
11795
  ["selected", alias],
11260
11796
  ["scope", "this repo"],
11261
- ["next", "rig task list"]
11797
+ ...remoteProjectLink ? [["remote link", remoteProjectLink.ok ? `ready (${remoteProjectLink.serverProjectRoot ?? "linked"})` : `${remoteProjectLink.status}: ${remoteProjectLink.hint}`]] : [],
11798
+ ["next", remoteProjectLink && !remoteProjectLink.ok ? "rig server repair-link" : "rig task list"]
11262
11799
  ]));
11263
- return { ok: true, group: options.group, command: "use", details: repoState };
11800
+ return { ok: true, group: options.group, command: "use", details };
11801
+ }
11802
+ case "repair-link": {
11803
+ const parsed = parseRepairLinkArgs(rest, `${usageName(options)} repair-link [--prepare|--backfill-only] [--repo owner/repo]`);
11804
+ const result = await repairRemoteProjectRootLink(context, parsed);
11805
+ printJsonOrText(context, result, formatRemoteProjectLinkText(result));
11806
+ return { ok: true, group: options.group, command: "repair-link", details: result };
11264
11807
  }
11265
11808
  case "status": {
11266
11809
  requireNoExtraArgs(rest, `${usageName(options)} status`);
11267
11810
  const repo = readRepoConnection(context.projectRoot);
11268
11811
  const global = readGlobalConnections();
11269
- const details = { selected: repo?.selected ?? "local", repo, connections: global.connections };
11270
- printJsonOrText(context, details, formatConnectionStatus(details.selected, global.connections));
11812
+ const remoteProjectLink = repo?.selected && repo.selected !== "local" ? await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only" }).catch((error) => ({
11813
+ ok: false,
11814
+ status: "error",
11815
+ message: error instanceof Error ? error.message : String(error),
11816
+ hint: "Run `rig server repair-link` after authenticating the selected remote."
11817
+ })) : null;
11818
+ const latestRepo = readRepoConnection(context.projectRoot) ?? repo;
11819
+ const details = { selected: latestRepo?.selected ?? "local", repo: latestRepo, connections: global.connections, remoteProjectLink };
11820
+ printJsonOrText(context, details, formatConnectionStatus(details.selected, global.connections, latestRepo ?? null, remoteProjectLink));
11271
11821
  return { ok: true, group: options.group, command: "status", details };
11272
11822
  }
11273
11823
  default:
11274
11824
  throw new CliError(`Unknown ${options.group} command: ${String(command)}
11275
- Usage: ${usageName(options)} <list|add|use|status>`, 1);
11825
+ Usage: ${usageName(options)} <list|add|use|status|repair-link>`, 1);
11276
11826
  }
11277
11827
  }
11278
11828
 
@@ -11280,7 +11830,7 @@ Usage: ${usageName(options)} <list|add|use|status>`, 1);
11280
11830
  init__server_client();
11281
11831
  async function executeServer(context, args, options) {
11282
11832
  const [command = "status", ...rest] = args;
11283
- if (["status", "list", "add", "use"].includes(command)) {
11833
+ if (["status", "list", "add", "use", "repair-link"].includes(command)) {
11284
11834
  return executeConnectionCommand(context, [command, ...rest], { group: "server", interactiveUse: true });
11285
11835
  }
11286
11836
  switch (command) {
@@ -11488,7 +12038,7 @@ init_task();
11488
12038
 
11489
12039
  // packages/cli/src/commands/task-run-driver.ts
11490
12040
  init_runner();
11491
- import { copyFileSync as copyFileSync3, existsSync as existsSync16, mkdirSync as mkdirSync11, readFileSync as readFileSync12, statSync as statSync2, writeFileSync as writeFileSync8 } from "fs";
12041
+ import { copyFileSync as copyFileSync3, existsSync as existsSync16, mkdirSync as mkdirSync12, readFileSync as readFileSync12, statSync as statSync2, writeFileSync as writeFileSync9 } from "fs";
11492
12042
  import { resolve as resolve24 } from "path";
11493
12043
  import { spawn as spawn2, spawnSync as spawnSync4 } from "child_process";
11494
12044
  import { createInterface as createLineInterface } from "readline";
@@ -11593,7 +12143,7 @@ function copyUntrackedDirtyFiles(sourceRoot, targetRoot) {
11593
12143
  try {
11594
12144
  if (!statSync2(sourcePath).isFile())
11595
12145
  continue;
11596
- mkdirSync11(resolve24(targetPath, ".."), { recursive: true });
12146
+ mkdirSync12(resolve24(targetPath, ".."), { recursive: true });
11597
12147
  copyFileSync3(sourcePath, targetPath);
11598
12148
  copied += 1;
11599
12149
  } catch {}
@@ -12485,8 +13035,8 @@ async function executeRigOwnedTaskRun(context, input) {
12485
13035
  artifactPath: planningClassification.planningRequired ? planningArtifactPath : null,
12486
13036
  classifiedAt: new Date().toISOString()
12487
13037
  };
12488
- mkdirSync11(resolve24(context.projectRoot, ".rig", "runs", input.runId), { recursive: true });
12489
- writeFileSync8(resolve24(context.projectRoot, ".rig", "runs", input.runId, "planning-classification.json"), `${JSON.stringify(persistedPlanning, null, 2)}
13038
+ mkdirSync12(resolve24(context.projectRoot, ".rig", "runs", input.runId), { recursive: true });
13039
+ writeFileSync9(resolve24(context.projectRoot, ".rig", "runs", input.runId, "planning-classification.json"), `${JSON.stringify(persistedPlanning, null, 2)}
12490
13040
  `, "utf8");
12491
13041
  patchAuthorityRun(context.projectRoot, input.runId, { planning: persistedPlanning });
12492
13042
  prompt = `${prompt}
@@ -12633,8 +13183,8 @@ ${planningClassification.planningRequired ? `Before implementing, write a concis
12633
13183
  const dirty = applyDirtyBaselineSnapshot({ sourceRoot: context.projectRoot, targetRoot: latestRuntimeWorkspace });
12634
13184
  const readyFile = childEnv.RIG_DIRTY_BASELINE_READY_FILE;
12635
13185
  if (readyFile) {
12636
- mkdirSync11(resolve24(readyFile, ".."), { recursive: true });
12637
- writeFileSync8(readyFile, `${JSON.stringify({ ...dirty, workspaceDir: latestRuntimeWorkspace, appliedAt: new Date().toISOString() }, null, 2)}
13186
+ mkdirSync12(resolve24(readyFile, ".."), { recursive: true });
13187
+ writeFileSync9(readyFile, `${JSON.stringify({ ...dirty, workspaceDir: latestRuntimeWorkspace, appliedAt: new Date().toISOString() }, null, 2)}
12638
13188
  `, "utf8");
12639
13189
  }
12640
13190
  appendRunLog(context.projectRoot, input.runId, {
@@ -13554,7 +14104,7 @@ async function executeTest(context, args) {
13554
14104
  init_runner();
13555
14105
  init__parsers();
13556
14106
  init__paths();
13557
- import { existsSync as existsSync17, mkdirSync as mkdirSync12, readdirSync as readdirSync3, writeFileSync as writeFileSync9 } from "fs";
14107
+ import { existsSync as existsSync17, mkdirSync as mkdirSync13, readdirSync as readdirSync3, writeFileSync as writeFileSync10 } from "fs";
13558
14108
  import { resolve as resolve25 } from "path";
13559
14109
  import { createPluginHost } from "@rig/core";
13560
14110
  import {
@@ -13610,12 +14160,12 @@ function runSetupInit(projectRoot) {
13610
14160
  const stateDir = resolveControlPlaneHostStateDir(projectRoot);
13611
14161
  const logsDir = resolveControlPlaneHostLogsDir(projectRoot);
13612
14162
  const artifactsDir = resolveControlPlaneArtifactsDir(projectRoot);
13613
- mkdirSync12(stateDir, { recursive: true });
13614
- mkdirSync12(logsDir, { recursive: true });
13615
- mkdirSync12(artifactsDir, { recursive: true });
14163
+ mkdirSync13(stateDir, { recursive: true });
14164
+ mkdirSync13(logsDir, { recursive: true });
14165
+ mkdirSync13(artifactsDir, { recursive: true });
13616
14166
  const failuresPath = resolve25(stateDir, "failed_approaches.md");
13617
14167
  if (!existsSync17(failuresPath)) {
13618
- writeFileSync9(failuresPath, `# Failed Approaches
14168
+ writeFileSync10(failuresPath, `# Failed Approaches
13619
14169
 
13620
14170
  `, "utf-8");
13621
14171
  }
@@ -14080,7 +14630,9 @@ import {
14080
14630
  RigInboxInputsOutput,
14081
14631
  RigRunListOutput,
14082
14632
  RigRunShowOutput,
14633
+ RigServerRepairLinkOutput,
14083
14634
  RigServerStatusOutput,
14635
+ RigServerUseOutput,
14084
14636
  RigStatsOutput,
14085
14637
  RigTaskListOutput,
14086
14638
  RigTaskShowOutput
@@ -14090,7 +14642,9 @@ var CLI_OUTPUT_SCHEMAS = {
14090
14642
  "task show": RigTaskShowOutput,
14091
14643
  "run list": RigRunListOutput,
14092
14644
  "run show": RigRunShowOutput,
14645
+ "server use": RigServerUseOutput,
14093
14646
  "server status": RigServerStatusOutput,
14647
+ "server repair-link": RigServerRepairLinkOutput,
14094
14648
  "inbox approvals": RigInboxApprovalsOutput,
14095
14649
  "inbox inputs": RigInboxInputsOutput,
14096
14650
  "doctor check": RigDoctorCheckOutput,