@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
@@ -89,12 +89,28 @@ function readRepoConnection(projectRoot) {
89
89
  selected,
90
90
  project: typeof record.project === "string" ? record.project : undefined,
91
91
  linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
92
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
92
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
93
+ serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
94
+ serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
93
95
  };
94
96
  }
95
97
  function writeRepoConnection(projectRoot, state) {
96
98
  writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
97
99
  }
100
+ function rootAllowedForSelection(repo, connection) {
101
+ const root = repo.serverProjectRoot?.trim();
102
+ if (!root)
103
+ return;
104
+ if (connection.kind === "remote") {
105
+ if (repo.serverProjectRootAlias !== repo.selected)
106
+ return;
107
+ if (repo.serverProjectRootBaseUrl !== connection.baseUrl)
108
+ return;
109
+ } else if (repo.serverProjectRootAlias && repo.serverProjectRootAlias !== repo.selected) {
110
+ return;
111
+ }
112
+ return root;
113
+ }
98
114
  function resolveSelectedConnection(projectRoot, options = {}) {
99
115
  const repo = readRepoConnection(projectRoot);
100
116
  if (!repo)
@@ -106,18 +122,46 @@ function resolveSelectedConnection(projectRoot, options = {}) {
106
122
  if (!connection) {
107
123
  throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
108
124
  }
109
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
125
+ return { alias: repo.selected, connection, serverProjectRoot: rootAllowedForSelection(repo, connection) };
110
126
  }
111
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
127
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot, metadata = {}) {
112
128
  const repo = readRepoConnection(projectRoot);
113
129
  if (!repo)
114
130
  return;
115
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
131
+ let inferred = metadata;
132
+ if (!inferred.alias || !inferred.baseUrl) {
133
+ try {
134
+ const selected = resolveSelectedConnection(projectRoot);
135
+ if (selected?.connection.kind === "remote") {
136
+ inferred = {
137
+ alias: inferred.alias ?? selected.alias,
138
+ baseUrl: inferred.baseUrl ?? selected.connection.baseUrl
139
+ };
140
+ }
141
+ } catch {}
142
+ }
143
+ writeRepoConnection(projectRoot, {
144
+ ...repo,
145
+ ...metadata.project ? { project: metadata.project } : {},
146
+ serverProjectRoot,
147
+ ...inferred.alias ? { serverProjectRootAlias: inferred.alias } : {},
148
+ ...inferred.baseUrl ? { serverProjectRootBaseUrl: inferred.baseUrl.replace(/\/+$/, "") } : {}
149
+ });
150
+ }
151
+ function clearRepoServerProjectRoot(projectRoot) {
152
+ const repo = readRepoConnection(projectRoot);
153
+ if (!repo)
154
+ return;
155
+ writeRepoConnection(projectRoot, {
156
+ selected: repo.selected,
157
+ ...repo.project ? { project: repo.project } : {},
158
+ ...repo.linkedAt ? { linkedAt: repo.linkedAt } : {}
159
+ });
116
160
  }
117
161
 
118
162
  // packages/cli/src/commands/_server-client.ts
119
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
120
- import { resolve as resolve2 } from "path";
163
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
164
+ import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
121
165
  import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
122
166
  var scopedGitHubBearerTokens = new Map;
123
167
  var serverPhaseListener = null;
@@ -156,11 +200,10 @@ function readStoredGitHubAuthToken(projectRoot) {
156
200
  const parsed = readRemoteAuthState(projectRoot);
157
201
  return parsed ? cleanToken(typeof parsed.token === "string" ? parsed.token : undefined) : null;
158
202
  }
159
- function inferRemoteServerProjectRootFromAuthState(projectRoot) {
160
- const repo = readRepoConnection(projectRoot);
161
- const slug = repo?.project?.trim();
162
- if (!slug || !/^[^/]+\/[^/]+$/.test(slug))
203
+ function inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug) {
204
+ if (!/^[^/]+\/[^/]+$/.test(repoSlug))
163
205
  return null;
206
+ const repo = readRepoConnection(projectRoot);
164
207
  const auth = readRemoteAuthState(projectRoot);
165
208
  const authUpdatedAt = typeof auth?.updatedAt === "string" ? Date.parse(auth.updatedAt) : Number.NaN;
166
209
  const repoLinkedAt = typeof repo?.linkedAt === "string" ? Date.parse(repo.linkedAt) : Number.NaN;
@@ -169,25 +212,413 @@ function inferRemoteServerProjectRootFromAuthState(projectRoot) {
169
212
  const checkoutBaseDir = typeof auth?.checkoutBaseDir === "string" && auth.checkoutBaseDir.trim() ? auth.checkoutBaseDir.trim() : null;
170
213
  if (!checkoutBaseDir)
171
214
  return null;
172
- const inferred = `${checkoutBaseDir.replace(/\/+$/, "")}/${slug}`;
173
- writeRepoServerProjectRoot(projectRoot, inferred);
174
- return inferred;
215
+ return `${checkoutBaseDir.replace(/\/+$/, "")}/${repoSlug}`;
175
216
  }
176
217
  function readLocalConnectionFallbackToken(projectRoot) {
177
218
  return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
178
219
  }
220
+ function normalizeRepoSlug(value) {
221
+ const slug = value?.trim();
222
+ return slug && /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
223
+ }
224
+ function readProjectLinkSlug(projectRoot) {
225
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
226
+ if (!existsSync2(path))
227
+ return null;
228
+ try {
229
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
230
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
231
+ return null;
232
+ return normalizeRepoSlug(typeof parsed.repoSlug === "string" ? String(parsed.repoSlug) : null);
233
+ } catch {
234
+ return null;
235
+ }
236
+ }
237
+ function writeProjectLinkConnection(projectRoot, repoSlug, alias) {
238
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
239
+ mkdirSync2(dirname2(path), { recursive: true });
240
+ writeFileSync2(path, `${JSON.stringify({ repoSlug, connection: alias, linkedAt: new Date().toISOString() }, null, 2)}
241
+ `, "utf8");
242
+ }
243
+ function remoteLinkRepairCommand(repoSlug) {
244
+ return repoSlug ? `rig server repair-link --repo ${repoSlug}` : "rig server repair-link --repo owner/repo";
245
+ }
246
+ function formatRemoteProjectLinkHint(resolution) {
247
+ const repair = remoteLinkRepairCommand(resolution.repoSlug);
248
+ if (resolution.status === "auth_required") {
249
+ 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}` : ""}\`.`;
250
+ }
251
+ if (resolution.status === "missing_project") {
252
+ return `Record the repo slug, then run \`${repair}\` (or \`rig init --repo owner/repo --server remote --github-auth device\`).`;
253
+ }
254
+ if (resolution.status === "not_remote")
255
+ return "Select a remote server with `rig server use <alias>` before repairing a remote project link.";
256
+ return `Run \`${repair}\` to backfill or prepare a server-host checkout for the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}.`;
257
+ }
258
+ function remoteProjectLinkFailure(input) {
259
+ const partial = {
260
+ status: input.status,
261
+ alias: input.alias,
262
+ baseUrl: input.baseUrl,
263
+ repoSlug: input.repoSlug
264
+ };
265
+ return {
266
+ ok: false,
267
+ ...input,
268
+ hint: formatRemoteProjectLinkHint(partial),
269
+ next: remoteLinkRepairCommand(input.repoSlug)
270
+ };
271
+ }
272
+ function remoteProjectLinkSuccess(input) {
273
+ return {
274
+ ok: true,
275
+ status: input.status,
276
+ alias: input.alias,
277
+ baseUrl: input.baseUrl,
278
+ repoSlug: input.repoSlug,
279
+ serverProjectRoot: input.serverProjectRoot,
280
+ source: input.source,
281
+ prepared: input.prepared ?? input.status === "prepared",
282
+ validated: input.validated ?? false,
283
+ message: input.message ?? `Remote project link ready for ${input.repoSlug}.`,
284
+ hint: "Remote-scoped task/run/status requests will send x-rig-project-root for this server-host checkout.",
285
+ next: "rig task list"
286
+ };
287
+ }
288
+ function localCheckoutPathCandidate(projectRoot, candidate) {
289
+ try {
290
+ const local = resolve2(projectRoot);
291
+ const resolved = resolve2(candidate);
292
+ return resolved === local || resolved.startsWith(`${local}/`);
293
+ } catch {
294
+ return false;
295
+ }
296
+ }
297
+ async function requestRemoteProjectLinkJson(baseUrl, pathname, authToken, init = {}) {
298
+ const requestUrl = new URL(`${baseUrl}${pathname}`);
299
+ if (authToken && queryAuthFallbackEnabled())
300
+ requestUrl.searchParams.set("rt", authToken);
301
+ const response = await fetch(requestUrl, {
302
+ ...init,
303
+ headers: mergeHeaders(init.headers, authToken)
304
+ });
305
+ const text = await response.text();
306
+ const payload = text.trim().length > 0 ? (() => {
307
+ try {
308
+ return JSON.parse(text);
309
+ } catch {
310
+ return null;
311
+ }
312
+ })() : null;
313
+ return { ok: response.ok, status: response.status, payload, text };
314
+ }
315
+ function payloadError(payload, fallback) {
316
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
317
+ const record = payload;
318
+ const value = record.error ?? record.message ?? record.reason;
319
+ if (typeof value === "string" && value.trim())
320
+ return value.trim();
321
+ }
322
+ return fallback;
323
+ }
324
+ function checkoutPathsFromProjectPayload(payload) {
325
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
326
+ return [];
327
+ const project = payload.project;
328
+ if (!project || typeof project !== "object" || Array.isArray(project))
329
+ return [];
330
+ const checkouts = project.checkouts;
331
+ if (!Array.isArray(checkouts))
332
+ return [];
333
+ return [...checkouts].reverse().flatMap((entry) => {
334
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
335
+ return [];
336
+ const path = entry.path;
337
+ return typeof path === "string" && path.trim() ? [path.trim()] : [];
338
+ });
339
+ }
340
+ function checkoutPathFromPreparePayload(payload) {
341
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
342
+ return null;
343
+ const checkout = payload.checkout;
344
+ if (!checkout || typeof checkout !== "object" || Array.isArray(checkout))
345
+ return null;
346
+ const path = checkout.path;
347
+ return typeof path === "string" && path.trim() ? path.trim() : null;
348
+ }
349
+ async function validateAndPersistRemoteRoot(input) {
350
+ const candidate = input.candidate.trim();
351
+ if (!candidate || !isAbsolute(candidate)) {
352
+ return remoteProjectLinkFailure({
353
+ status: "invalid_root",
354
+ alias: input.alias,
355
+ baseUrl: input.baseUrl,
356
+ repoSlug: input.repoSlug,
357
+ message: `Remote project root candidate is not an absolute server-host path: ${candidate || "(empty)"}.`
358
+ });
359
+ }
360
+ if (localCheckoutPathCandidate(input.projectRoot, candidate)) {
361
+ return remoteProjectLinkFailure({
362
+ status: "invalid_root",
363
+ alias: input.alias,
364
+ baseUrl: input.baseUrl,
365
+ repoSlug: input.repoSlug,
366
+ message: `Refusing to use local checkout path ${candidate} as a remote server project root.`
367
+ });
368
+ }
369
+ let response;
370
+ try {
371
+ response = await requestRemoteProjectLinkJson(input.baseUrl, "/api/server/project-root", input.authToken, {
372
+ method: "POST",
373
+ headers: { "content-type": "application/json" },
374
+ body: JSON.stringify({ projectRoot: candidate })
375
+ });
376
+ } catch (error) {
377
+ return remoteProjectLinkFailure({
378
+ status: "error",
379
+ alias: input.alias,
380
+ baseUrl: input.baseUrl,
381
+ repoSlug: input.repoSlug,
382
+ message: `Could not validate remote project root ${candidate}: ${error instanceof Error ? error.message : String(error)}`
383
+ });
384
+ }
385
+ if (response.status === 401 || response.status === 403) {
386
+ return remoteProjectLinkFailure({
387
+ status: "auth_required",
388
+ alias: input.alias,
389
+ baseUrl: input.baseUrl,
390
+ repoSlug: input.repoSlug,
391
+ statusCode: response.status,
392
+ message: `Remote server ${input.alias} requires authentication before validating project root ${candidate}.`
393
+ });
394
+ }
395
+ if (!response.ok) {
396
+ return remoteProjectLinkFailure({
397
+ status: "invalid_root",
398
+ alias: input.alias,
399
+ baseUrl: input.baseUrl,
400
+ repoSlug: input.repoSlug,
401
+ statusCode: response.status,
402
+ message: `Remote server rejected project root ${candidate} (${response.status}): ${payloadError(response.payload, response.text || "project-root validation failed")}`
403
+ });
404
+ }
405
+ const record = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload) ? response.payload : {};
406
+ if (record.ok !== true) {
407
+ return remoteProjectLinkFailure({
408
+ status: "invalid_root",
409
+ alias: input.alias,
410
+ baseUrl: input.baseUrl,
411
+ repoSlug: input.repoSlug,
412
+ message: `Remote server did not accept project root ${candidate}: ${payloadError(response.payload, "project-root validation failed")}`
413
+ });
414
+ }
415
+ const accepted = typeof record.projectRoot === "string" && record.projectRoot.trim() ? record.projectRoot.trim() : typeof record.requestedProjectRoot === "string" && record.requestedProjectRoot.trim() ? record.requestedProjectRoot.trim() : candidate;
416
+ writeRepoServerProjectRoot(input.projectRoot, accepted, { alias: input.alias, baseUrl: input.baseUrl, project: input.repoSlug });
417
+ writeProjectLinkConnection(input.projectRoot, input.repoSlug, input.alias);
418
+ const status = input.status ?? (input.prepared ? "prepared" : "backfilled");
419
+ return remoteProjectLinkSuccess({
420
+ status,
421
+ alias: input.alias,
422
+ baseUrl: input.baseUrl,
423
+ repoSlug: input.repoSlug,
424
+ serverProjectRoot: accepted,
425
+ source: input.source,
426
+ prepared: input.prepared,
427
+ validated: true,
428
+ 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}.`
429
+ });
430
+ }
431
+ async function ensureRemoteProjectRootLink(projectRoot, options = {}) {
432
+ let selected;
433
+ try {
434
+ selected = resolveSelectedConnection(projectRoot);
435
+ } catch (error) {
436
+ return remoteProjectLinkFailure({ status: "error", message: error instanceof Error ? error.message : String(error) });
437
+ }
438
+ if (!selected || selected.connection.kind !== "remote") {
439
+ return remoteProjectLinkFailure({ status: "not_remote", message: "No remote Rig server is selected for this repo." });
440
+ }
441
+ const repo = readRepoConnection(projectRoot);
442
+ const explicitRepoRequested = options.repoSlug !== undefined;
443
+ const explicitRepoSlug = explicitRepoRequested ? normalizeRepoSlug(options.repoSlug) : null;
444
+ const repoProjectSlug = normalizeRepoSlug(repo?.project);
445
+ const repoSlug = explicitRepoSlug ?? repoProjectSlug ?? readProjectLinkSlug(projectRoot);
446
+ const alias = selected.alias;
447
+ const baseUrl = selected.connection.baseUrl;
448
+ const authToken = options.authToken === undefined ? readGitHubBearerTokenForRemote(projectRoot) : options.authToken;
449
+ const mode = options.mode ?? "backfill-only";
450
+ if (explicitRepoRequested && !explicitRepoSlug) {
451
+ return remoteProjectLinkFailure({
452
+ status: "missing_project",
453
+ alias,
454
+ baseUrl,
455
+ message: `Invalid --repo value ${JSON.stringify(options.repoSlug)}. Expected owner/repo.`
456
+ });
457
+ }
458
+ if (!repoSlug) {
459
+ return remoteProjectLinkFailure({
460
+ status: "missing_project",
461
+ alias,
462
+ baseUrl,
463
+ message: `Remote server ${alias} is selected, but this checkout has no GitHub repo slug recorded.`
464
+ });
465
+ }
466
+ const skippedCandidates = [];
467
+ const storedRoot = selected.serverProjectRoot?.trim() || null;
468
+ const storedRootMatchesResolvedRepo = repoProjectSlug === repoSlug;
469
+ if (storedRoot && storedRootMatchesResolvedRepo) {
470
+ if (localCheckoutPathCandidate(projectRoot, storedRoot)) {
471
+ clearRepoServerProjectRoot(projectRoot);
472
+ skippedCandidates.push(storedRoot);
473
+ } else {
474
+ const storedResult = await validateAndPersistRemoteRoot({
475
+ projectRoot,
476
+ alias,
477
+ baseUrl,
478
+ authToken,
479
+ repoSlug,
480
+ candidate: storedRoot,
481
+ source: "stored",
482
+ status: "ready"
483
+ });
484
+ if (storedResult.ok || storedResult.status === "auth_required" || storedResult.status === "error")
485
+ return storedResult;
486
+ clearRepoServerProjectRoot(projectRoot);
487
+ skippedCandidates.push(storedRoot);
488
+ }
489
+ } else if (storedRoot) {
490
+ skippedCandidates.push(storedRoot);
491
+ }
492
+ const authCandidate = inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug);
493
+ if (authCandidate) {
494
+ const authResult = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: authCandidate, source: "auth-state" });
495
+ if (authResult.ok || authResult.status === "auth_required")
496
+ return authResult;
497
+ }
498
+ let registryResponse;
499
+ try {
500
+ registryResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}`, authToken);
501
+ } catch (error) {
502
+ return remoteProjectLinkFailure({
503
+ status: "error",
504
+ alias,
505
+ baseUrl,
506
+ repoSlug,
507
+ message: `Could not read remote project registry for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
508
+ });
509
+ }
510
+ if (registryResponse.status === 401 || registryResponse.status === 403) {
511
+ return remoteProjectLinkFailure({
512
+ status: "auth_required",
513
+ alias,
514
+ baseUrl,
515
+ repoSlug,
516
+ statusCode: registryResponse.status,
517
+ message: `Remote server ${alias} requires authentication before reading the ${repoSlug} project registry.`
518
+ });
519
+ }
520
+ if (registryResponse.ok) {
521
+ const candidates = checkoutPathsFromProjectPayload(registryResponse.payload);
522
+ for (const candidate of candidates) {
523
+ const result = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate, source: "registry" });
524
+ if (result.ok || result.status === "auth_required")
525
+ return result;
526
+ skippedCandidates.push(candidate);
527
+ }
528
+ if (mode === "backfill-only") {
529
+ return remoteProjectLinkFailure({
530
+ status: candidates.length > 0 ? "invalid_root" : "no_server_checkout",
531
+ alias,
532
+ baseUrl,
533
+ repoSlug,
534
+ 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.`,
535
+ skippedCandidates
536
+ });
537
+ }
538
+ } else if (registryResponse.status === 404) {
539
+ if (mode === "backfill-only") {
540
+ return remoteProjectLinkFailure({
541
+ status: "project_not_registered",
542
+ alias,
543
+ baseUrl,
544
+ repoSlug,
545
+ statusCode: registryResponse.status,
546
+ message: `Remote server ${alias} has no registered project record for ${repoSlug}.`
547
+ });
548
+ }
549
+ } else {
550
+ return remoteProjectLinkFailure({
551
+ status: "error",
552
+ alias,
553
+ baseUrl,
554
+ repoSlug,
555
+ statusCode: registryResponse.status,
556
+ message: `Could not backfill ${repoSlug} from remote registry (${registryResponse.status}): ${payloadError(registryResponse.payload, registryResponse.text || "registry lookup failed")}`,
557
+ skippedCandidates
558
+ });
559
+ }
560
+ let prepareResponse;
561
+ try {
562
+ prepareResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}/prepare-checkout`, authToken, {
563
+ method: "POST",
564
+ headers: { "content-type": "application/json" },
565
+ body: JSON.stringify({ checkout: { kind: "managed-clone" }, repoUrl: `https://github.com/${repoSlug}.git` })
566
+ });
567
+ } catch (error) {
568
+ return remoteProjectLinkFailure({
569
+ status: "error",
570
+ alias,
571
+ baseUrl,
572
+ repoSlug,
573
+ message: `Could not prepare remote checkout for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
574
+ });
575
+ }
576
+ if (prepareResponse.status === 401 || prepareResponse.status === 403) {
577
+ return remoteProjectLinkFailure({
578
+ status: "auth_required",
579
+ alias,
580
+ baseUrl,
581
+ repoSlug,
582
+ statusCode: prepareResponse.status,
583
+ message: `Remote server ${alias} requires authentication before preparing ${repoSlug}.`
584
+ });
585
+ }
586
+ if (!prepareResponse.ok) {
587
+ return remoteProjectLinkFailure({
588
+ status: "error",
589
+ alias,
590
+ baseUrl,
591
+ repoSlug,
592
+ statusCode: prepareResponse.status,
593
+ message: `Remote checkout prepare failed for ${repoSlug} (${prepareResponse.status}): ${payloadError(prepareResponse.payload, prepareResponse.text || "prepare-checkout failed")}`,
594
+ skippedCandidates
595
+ });
596
+ }
597
+ const preparedPath = checkoutPathFromPreparePayload(prepareResponse.payload);
598
+ if (!preparedPath) {
599
+ return remoteProjectLinkFailure({
600
+ status: "invalid_root",
601
+ alias,
602
+ baseUrl,
603
+ repoSlug,
604
+ message: `Remote checkout prepare for ${repoSlug} did not return a checkout.path.`,
605
+ skippedCandidates
606
+ });
607
+ }
608
+ return validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: preparedPath, source: "prepare", prepared: true });
609
+ }
179
610
  async function ensureServerForCli(projectRoot) {
180
611
  try {
181
612
  const selected = resolveSelectedConnection(projectRoot);
182
613
  if (selected?.connection.kind === "remote") {
183
614
  reportServerPhase(`Connecting to ${selected.alias}\u2026`);
184
615
  const authToken = readGitHubBearerTokenForRemote(projectRoot);
185
- const serverProjectRoot = selected.serverProjectRoot ?? inferRemoteServerProjectRootFromAuthState(projectRoot) ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
616
+ const link = await ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only", authToken });
186
617
  return {
187
618
  baseUrl: selected.connection.baseUrl,
188
619
  authToken,
189
620
  connectionKind: "remote",
190
- serverProjectRoot
621
+ serverProjectRoot: link.ok ? link.serverProjectRoot ?? null : null
191
622
  };
192
623
  }
193
624
  reportServerPhase("Starting local Rig server\u2026");
@@ -205,32 +636,6 @@ async function ensureServerForCli(projectRoot) {
205
636
  throw error;
206
637
  }
207
638
  }
208
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
209
- const repo = readRepoConnection(projectRoot);
210
- const slug = repo?.project?.trim();
211
- if (!slug)
212
- return null;
213
- try {
214
- const url = new URL(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`);
215
- if (authToken && queryAuthFallbackEnabled())
216
- url.searchParams.set("rt", authToken);
217
- const response = await fetch(url, {
218
- headers: mergeHeaders(undefined, authToken)
219
- });
220
- if (!response.ok)
221
- return null;
222
- const payload = await response.json();
223
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
224
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
225
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
226
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
227
- if (path)
228
- writeRepoServerProjectRoot(projectRoot, path);
229
- return path;
230
- } catch {
231
- return null;
232
- }
233
- }
234
639
  function mergeCookie(existing, name, value) {
235
640
  const encoded = `${name}=${encodeURIComponent(value)}`;
236
641
  if (!existing?.trim())
@@ -322,13 +727,20 @@ function canUseRemoteWithoutProjectRoot(pathname) {
322
727
  async function requestServerJson(context, pathname, init = {}) {
323
728
  const server = await ensureServerForCli(context.projectRoot);
324
729
  const requestUrl = new URL(`${server.baseUrl}${pathname}`);
325
- if (server.connectionKind === "remote" && !server.serverProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
326
- const repo = readRepoConnection(context.projectRoot);
327
- 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." });
730
+ let scopedServerProjectRoot = server.serverProjectRoot;
731
+ if (server.connectionKind === "remote" && !scopedServerProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
732
+ const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: server.authToken });
733
+ if (link.ok && link.serverProjectRoot) {
734
+ scopedServerProjectRoot = link.serverProjectRoot;
735
+ } else {
736
+ const repo = readRepoConnection(context.projectRoot);
737
+ const target = link.alias && link.baseUrl ? `${link.alias} (${link.baseUrl})` : server.baseUrl;
738
+ 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 });
739
+ }
328
740
  }
329
741
  const headers = mergeHeaders(init.headers, server.authToken);
330
- if (server.serverProjectRoot)
331
- headers.set("x-rig-project-root", server.serverProjectRoot);
742
+ if (scopedServerProjectRoot)
743
+ headers.set("x-rig-project-root", scopedServerProjectRoot);
332
744
  if (server.connectionKind === "remote" && server.authToken && queryAuthFallbackEnabled()) {
333
745
  requestUrl.searchParams.set("rt", server.authToken);
334
746
  }
@@ -433,6 +845,14 @@ function permissionAllowsPr(payload) {
433
845
  function isNotFoundError(error) {
434
846
  return /\b(404|not found)\b/i.test(message(error));
435
847
  }
848
+ function isLoopbackBaseUrl(baseUrl) {
849
+ try {
850
+ const host = new URL(baseUrl).hostname.toLowerCase();
851
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
852
+ } catch {
853
+ return false;
854
+ }
855
+ }
436
856
  function projectCheckoutReady(payload) {
437
857
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
438
858
  return null;
@@ -487,25 +907,37 @@ async function runFastTaskRunPreflight(context, options = {}) {
487
907
  }
488
908
  const repo = readRepoConnection(context.projectRoot);
489
909
  const remoteWithoutProjectLink = selectedServer?.connectionKind === "remote" && !repo?.project;
490
- 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>`."));
910
+ let remoteRootBlocked = false;
911
+ 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>`."));
912
+ if (selectedServer?.connectionKind === "remote" && repo?.project && !selectedServer.serverProjectRoot) {
913
+ const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: selectedServer.authToken });
914
+ const loopbackDevRemote = !selectedServer.authToken && isLoopbackBaseUrl(selectedServer.baseUrl);
915
+ 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));
916
+ remoteRootBlocked = !link.ok && !loopbackDevRemote;
917
+ }
491
918
  try {
492
919
  const auth = await request("/api/github/auth/status");
493
920
  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>`."));
494
921
  } catch (error) {
495
922
  checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
496
923
  }
497
- try {
498
- const projection = await request("/api/workspace/task-projection");
499
- checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
500
- } catch (error) {
501
- checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
502
- }
503
- try {
504
- const permissions = await request("/api/github/repo/permissions");
505
- const allowed = permissionAllowsPr(permissions);
506
- 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."));
507
- } catch (error) {
508
- checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
924
+ if (!remoteRootBlocked) {
925
+ try {
926
+ const projection = await request("/api/workspace/task-projection");
927
+ checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
928
+ } catch (error) {
929
+ checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
930
+ }
931
+ try {
932
+ const permissions = await request("/api/github/repo/permissions");
933
+ const allowed = permissionAllowsPr(permissions);
934
+ 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."));
935
+ } catch (error) {
936
+ checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
937
+ }
938
+ } else {
939
+ checks.push(preflightCheck("task-projection", "task projection ready", "warn", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
940
+ 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."));
509
941
  }
510
942
  if (repo?.project) {
511
943
  try {
@@ -517,19 +949,24 @@ async function runFastTaskRunPreflight(context, options = {}) {
517
949
  }
518
950
  }
519
951
  if (taskId) {
520
- try {
521
- const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
522
- const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
523
- 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."));
524
- } catch (error) {
525
- checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
526
- }
527
- try {
528
- const runs = await request("/api/runs?limit=200");
529
- const duplicate = activeDuplicateRun(runs, taskId);
530
- 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));
531
- } catch (error) {
532
- 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."));
952
+ if (!remoteRootBlocked) {
953
+ try {
954
+ const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
955
+ const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
956
+ 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."));
957
+ } catch (error) {
958
+ checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
959
+ }
960
+ try {
961
+ const runs = await request("/api/runs?limit=200");
962
+ const duplicate = activeDuplicateRun(runs, taskId);
963
+ 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));
964
+ } catch (error) {
965
+ 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."));
966
+ }
967
+ } else {
968
+ checks.push(preflightCheck("issue", "task/issue accessible", "fail", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
969
+ 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."));
533
970
  }
534
971
  }
535
972
  if ((options.runtimeAdapter ?? "pi") === "pi") {