@h-rig/cli 0.0.6-alpha.28 → 0.0.6-alpha.281
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.
- package/README.md +6 -28
- package/package.json +11 -28
- package/dist/bin/build-rig-binaries.js +0 -107
- package/dist/bin/rig.js +0 -11739
- package/dist/src/commands/_authority-runs.js +0 -111
- package/dist/src/commands/_cli-format.js +0 -369
- package/dist/src/commands/_connection-state.js +0 -123
- package/dist/src/commands/_doctor-checks.js +0 -507
- package/dist/src/commands/_help-catalog.js +0 -364
- package/dist/src/commands/_operator-surface.js +0 -204
- package/dist/src/commands/_operator-view.js +0 -1147
- package/dist/src/commands/_parsers.js +0 -107
- package/dist/src/commands/_paths.js +0 -50
- package/dist/src/commands/_pi-frontend.js +0 -843
- package/dist/src/commands/_pi-install.js +0 -185
- package/dist/src/commands/_pi-worker-bridge-extension.js +0 -761
- package/dist/src/commands/_policy.js +0 -79
- package/dist/src/commands/_preflight.js +0 -403
- package/dist/src/commands/_probes.js +0 -13
- package/dist/src/commands/_run-driver-helpers.js +0 -289
- package/dist/src/commands/_server-client.js +0 -514
- package/dist/src/commands/_snapshot-upload.js +0 -318
- package/dist/src/commands/_task-picker.js +0 -76
- package/dist/src/commands/agent.js +0 -499
- package/dist/src/commands/browser.js +0 -890
- package/dist/src/commands/connect.js +0 -289
- package/dist/src/commands/dist.js +0 -402
- package/dist/src/commands/doctor.js +0 -517
- package/dist/src/commands/github.js +0 -281
- package/dist/src/commands/inbox.js +0 -482
- package/dist/src/commands/init.js +0 -1563
- package/dist/src/commands/inspect.js +0 -174
- package/dist/src/commands/inspector.js +0 -256
- package/dist/src/commands/plugin.js +0 -167
- package/dist/src/commands/profile-and-review.js +0 -178
- package/dist/src/commands/queue.js +0 -198
- package/dist/src/commands/remote.js +0 -507
- package/dist/src/commands/repo-git-harness.js +0 -221
- package/dist/src/commands/run.js +0 -1808
- package/dist/src/commands/server.js +0 -572
- package/dist/src/commands/setup.js +0 -687
- package/dist/src/commands/task-report-bug.js +0 -1083
- package/dist/src/commands/task-run-driver.js +0 -2600
- package/dist/src/commands/task.js +0 -2606
- package/dist/src/commands/test.js +0 -39
- package/dist/src/commands/workspace.js +0 -123
- package/dist/src/commands.js +0 -11418
- package/dist/src/index.js +0 -11757
- package/dist/src/launcher.js +0 -133
- package/dist/src/report-bug.js +0 -260
- package/dist/src/runner.js +0 -273
- package/dist/src/withMutedConsole.js +0 -42
|
@@ -1,1563 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
var __require = import.meta.require;
|
|
3
|
-
|
|
4
|
-
// packages/cli/src/commands/init.ts
|
|
5
|
-
import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "fs";
|
|
6
|
-
import { spawnSync } from "child_process";
|
|
7
|
-
import { resolve as resolve6 } from "path";
|
|
8
|
-
|
|
9
|
-
// packages/cli/src/runner.ts
|
|
10
|
-
import { EventBus } from "@rig/runtime/control-plane/runtime/events";
|
|
11
|
-
import { CliError } from "@rig/runtime/control-plane/errors";
|
|
12
|
-
import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
|
|
13
|
-
import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
|
|
14
|
-
import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
|
|
15
|
-
import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
|
|
16
|
-
import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
|
|
17
|
-
function takeFlag(args, flag) {
|
|
18
|
-
const rest = [];
|
|
19
|
-
let value = false;
|
|
20
|
-
for (const arg of args) {
|
|
21
|
-
if (arg === flag) {
|
|
22
|
-
value = true;
|
|
23
|
-
continue;
|
|
24
|
-
}
|
|
25
|
-
rest.push(arg);
|
|
26
|
-
}
|
|
27
|
-
return { value, rest };
|
|
28
|
-
}
|
|
29
|
-
function takeOption(args, option) {
|
|
30
|
-
const rest = [];
|
|
31
|
-
let value;
|
|
32
|
-
for (let index = 0;index < args.length; index += 1) {
|
|
33
|
-
const current = args[index];
|
|
34
|
-
if (current === option) {
|
|
35
|
-
const next = args[index + 1];
|
|
36
|
-
if (!next || next.startsWith("-")) {
|
|
37
|
-
throw new CliError(`Missing value for ${option}`);
|
|
38
|
-
}
|
|
39
|
-
value = next;
|
|
40
|
-
index += 1;
|
|
41
|
-
continue;
|
|
42
|
-
}
|
|
43
|
-
if (current !== undefined) {
|
|
44
|
-
rest.push(current);
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
return { value, rest };
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// packages/cli/src/commands/init.ts
|
|
51
|
-
import { buildRigInitConfigSource } from "@rig/core";
|
|
52
|
-
import { listGitHubProjects as listGitHubProjectsDirect, resolveProjectStatusField as resolveProjectStatusFieldDirect } from "@rig/server";
|
|
53
|
-
|
|
54
|
-
// packages/cli/src/commands/_connection-state.ts
|
|
55
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
56
|
-
import { homedir } from "os";
|
|
57
|
-
import { dirname, resolve } from "path";
|
|
58
|
-
function resolveGlobalConnectionsPath(env = process.env) {
|
|
59
|
-
const explicit = env.RIG_CONNECTIONS_FILE?.trim();
|
|
60
|
-
if (explicit)
|
|
61
|
-
return resolve(explicit);
|
|
62
|
-
const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
|
|
63
|
-
if (stateDir)
|
|
64
|
-
return resolve(stateDir, "connections.json");
|
|
65
|
-
return resolve(homedir(), ".rig", "connections.json");
|
|
66
|
-
}
|
|
67
|
-
function resolveRepoConnectionPath(projectRoot) {
|
|
68
|
-
return resolve(projectRoot, ".rig", "state", "connection.json");
|
|
69
|
-
}
|
|
70
|
-
function readJsonFile(path) {
|
|
71
|
-
if (!existsSync(path))
|
|
72
|
-
return null;
|
|
73
|
-
try {
|
|
74
|
-
return JSON.parse(readFileSync(path, "utf8"));
|
|
75
|
-
} catch (error) {
|
|
76
|
-
throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
function writeJsonFile(path, value) {
|
|
80
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
81
|
-
writeFileSync(path, `${JSON.stringify(value, null, 2)}
|
|
82
|
-
`, "utf8");
|
|
83
|
-
}
|
|
84
|
-
function normalizeConnection(value) {
|
|
85
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
86
|
-
return null;
|
|
87
|
-
const record = value;
|
|
88
|
-
if (record.kind === "local")
|
|
89
|
-
return { kind: "local", mode: "auto" };
|
|
90
|
-
if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
|
|
91
|
-
const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
|
|
92
|
-
return { kind: "remote", baseUrl };
|
|
93
|
-
}
|
|
94
|
-
return null;
|
|
95
|
-
}
|
|
96
|
-
function readGlobalConnections(options = {}) {
|
|
97
|
-
const path = resolveGlobalConnectionsPath(options.env ?? process.env);
|
|
98
|
-
const payload = readJsonFile(path);
|
|
99
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
100
|
-
return { connections: {} };
|
|
101
|
-
}
|
|
102
|
-
const rawConnections = payload.connections;
|
|
103
|
-
const connections = {};
|
|
104
|
-
if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
|
|
105
|
-
for (const [alias, raw] of Object.entries(rawConnections)) {
|
|
106
|
-
const connection = normalizeConnection(raw);
|
|
107
|
-
if (connection)
|
|
108
|
-
connections[alias] = connection;
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
return { connections };
|
|
112
|
-
}
|
|
113
|
-
function writeGlobalConnections(state, options = {}) {
|
|
114
|
-
writeJsonFile(resolveGlobalConnectionsPath(options.env ?? process.env), state);
|
|
115
|
-
}
|
|
116
|
-
function upsertGlobalConnection(alias, connection, options = {}) {
|
|
117
|
-
const cleanAlias = alias.trim();
|
|
118
|
-
if (!cleanAlias)
|
|
119
|
-
throw new CliError2("Connection alias is required.", 1);
|
|
120
|
-
const state = readGlobalConnections(options);
|
|
121
|
-
state.connections[cleanAlias] = connection;
|
|
122
|
-
writeGlobalConnections(state, options);
|
|
123
|
-
return state;
|
|
124
|
-
}
|
|
125
|
-
function readRepoConnection(projectRoot) {
|
|
126
|
-
const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
|
|
127
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
128
|
-
return null;
|
|
129
|
-
const record = payload;
|
|
130
|
-
const selected = typeof record.selected === "string" ? record.selected.trim() : "";
|
|
131
|
-
if (!selected)
|
|
132
|
-
return null;
|
|
133
|
-
return {
|
|
134
|
-
selected,
|
|
135
|
-
project: typeof record.project === "string" ? record.project : undefined,
|
|
136
|
-
linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
function writeRepoConnection(projectRoot, state) {
|
|
140
|
-
writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
|
|
141
|
-
}
|
|
142
|
-
function resolveSelectedConnection(projectRoot, options = {}) {
|
|
143
|
-
const repo = readRepoConnection(projectRoot);
|
|
144
|
-
if (!repo)
|
|
145
|
-
return null;
|
|
146
|
-
if (repo.selected === "local")
|
|
147
|
-
return { alias: "local", connection: { kind: "local", mode: "auto" } };
|
|
148
|
-
const global = readGlobalConnections(options);
|
|
149
|
-
const connection = global.connections[repo.selected];
|
|
150
|
-
if (!connection) {
|
|
151
|
-
throw new CliError2(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
|
|
152
|
-
}
|
|
153
|
-
return { alias: repo.selected, connection };
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
// packages/cli/src/commands/_server-client.ts
|
|
157
|
-
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
158
|
-
import { resolve as resolve2 } from "path";
|
|
159
|
-
import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
|
|
160
|
-
var scopedGitHubBearerTokens = new Map;
|
|
161
|
-
function cleanToken(value) {
|
|
162
|
-
const trimmed = value?.trim();
|
|
163
|
-
return trimmed ? trimmed : null;
|
|
164
|
-
}
|
|
165
|
-
function setGitHubBearerTokenForCurrentProcess(token, projectRoot) {
|
|
166
|
-
const scopedKey = resolve2(projectRoot ?? process.cwd());
|
|
167
|
-
scopedGitHubBearerTokens.set(scopedKey, cleanToken(token ?? undefined));
|
|
168
|
-
}
|
|
169
|
-
function readPrivateRemoteSessionToken(projectRoot) {
|
|
170
|
-
const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
|
|
171
|
-
if (!existsSync2(path))
|
|
172
|
-
return null;
|
|
173
|
-
try {
|
|
174
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
175
|
-
return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
|
|
176
|
-
} catch {
|
|
177
|
-
return null;
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
function readGitHubBearerTokenForRemote(projectRoot) {
|
|
181
|
-
const scopedKey = resolve2(projectRoot);
|
|
182
|
-
if (scopedGitHubBearerTokens.has(scopedKey))
|
|
183
|
-
return scopedGitHubBearerTokens.get(scopedKey) ?? null;
|
|
184
|
-
const privateSession = readPrivateRemoteSessionToken(projectRoot);
|
|
185
|
-
if (privateSession)
|
|
186
|
-
return privateSession;
|
|
187
|
-
return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
|
|
188
|
-
}
|
|
189
|
-
async function ensureServerForCli(projectRoot) {
|
|
190
|
-
try {
|
|
191
|
-
const selected = resolveSelectedConnection(projectRoot);
|
|
192
|
-
if (selected?.connection.kind === "remote") {
|
|
193
|
-
return {
|
|
194
|
-
baseUrl: selected.connection.baseUrl,
|
|
195
|
-
authToken: readGitHubBearerTokenForRemote(projectRoot),
|
|
196
|
-
connectionKind: "remote"
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
const connection = await ensureLocalRigServerConnection(projectRoot);
|
|
200
|
-
return {
|
|
201
|
-
baseUrl: connection.baseUrl,
|
|
202
|
-
authToken: connection.authToken,
|
|
203
|
-
connectionKind: "local"
|
|
204
|
-
};
|
|
205
|
-
} catch (error) {
|
|
206
|
-
if (error instanceof Error) {
|
|
207
|
-
throw new CliError2(error.message, 1);
|
|
208
|
-
}
|
|
209
|
-
throw error;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
function mergeHeaders(headers, authToken) {
|
|
213
|
-
const merged = new Headers(headers);
|
|
214
|
-
if (authToken) {
|
|
215
|
-
merged.set("authorization", `Bearer ${authToken}`);
|
|
216
|
-
}
|
|
217
|
-
return merged;
|
|
218
|
-
}
|
|
219
|
-
function diagnosticMessage(payload) {
|
|
220
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
221
|
-
return null;
|
|
222
|
-
const record = payload;
|
|
223
|
-
const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
|
|
224
|
-
const messages = diagnostics.flatMap((entry) => {
|
|
225
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
226
|
-
return [];
|
|
227
|
-
const diagnostic = entry;
|
|
228
|
-
const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
|
|
229
|
-
const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
|
|
230
|
-
return message ? [`${kind}: ${message}`] : [];
|
|
231
|
-
});
|
|
232
|
-
return messages.length > 0 ? messages.join("; ") : null;
|
|
233
|
-
}
|
|
234
|
-
async function requestServerJson(context, pathname, init = {}) {
|
|
235
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
236
|
-
const response = await fetch(`${server.baseUrl}${pathname}`, {
|
|
237
|
-
...init,
|
|
238
|
-
headers: mergeHeaders(init.headers, server.authToken)
|
|
239
|
-
});
|
|
240
|
-
const text = await response.text();
|
|
241
|
-
const payload = text.trim().length > 0 ? (() => {
|
|
242
|
-
try {
|
|
243
|
-
return JSON.parse(text);
|
|
244
|
-
} catch {
|
|
245
|
-
return null;
|
|
246
|
-
}
|
|
247
|
-
})() : null;
|
|
248
|
-
if (!response.ok) {
|
|
249
|
-
const diagnostics = diagnosticMessage(payload);
|
|
250
|
-
const detail = diagnostics ?? (text || response.statusText);
|
|
251
|
-
throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
|
|
252
|
-
}
|
|
253
|
-
return payload;
|
|
254
|
-
}
|
|
255
|
-
async function postGitHubTokenViaServer(context, token, options = {}) {
|
|
256
|
-
const payload = await requestServerJson(context, "/api/github/auth/token", {
|
|
257
|
-
method: "POST",
|
|
258
|
-
headers: { "content-type": "application/json" },
|
|
259
|
-
body: JSON.stringify({ token, selectedRepo: options.selectedRepo, projectRoot: options.projectRoot })
|
|
260
|
-
});
|
|
261
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
262
|
-
}
|
|
263
|
-
async function prepareRemoteCheckoutViaServer(context, input) {
|
|
264
|
-
const payload = await requestServerJson(context, `/api/projects/${encodeURIComponent(input.repoSlug)}/prepare-checkout`, {
|
|
265
|
-
method: "POST",
|
|
266
|
-
headers: { "content-type": "application/json" },
|
|
267
|
-
body: JSON.stringify({ checkout: input.checkout, repoUrl: input.repoUrl, baseDir: input.baseDir })
|
|
268
|
-
});
|
|
269
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
270
|
-
}
|
|
271
|
-
async function registerProjectViaServer(context, input) {
|
|
272
|
-
const payload = await requestServerJson(context, "/api/projects", {
|
|
273
|
-
method: "POST",
|
|
274
|
-
headers: { "content-type": "application/json" },
|
|
275
|
-
body: JSON.stringify(input)
|
|
276
|
-
});
|
|
277
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
278
|
-
}
|
|
279
|
-
function sleep(ms) {
|
|
280
|
-
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
281
|
-
}
|
|
282
|
-
function isRetryableProjectRootSwitchError(error) {
|
|
283
|
-
if (!(error instanceof Error))
|
|
284
|
-
return false;
|
|
285
|
-
const message = error.message.toLowerCase();
|
|
286
|
-
return message.includes("rig server request failed (401): auth-required") || message.includes("rig server request failed (401): github-token-required") || message.includes("rig server request failed (502)") || message.includes("rig server request failed (503)") || message.includes("bad gateway") || message.includes("fetch failed") || message.includes("econnrefused") || message.includes("connection refused");
|
|
287
|
-
}
|
|
288
|
-
async function switchServerProjectRootViaServer(context, projectRoot, options = {}) {
|
|
289
|
-
const timeoutMs = options.timeoutMs ?? 30000;
|
|
290
|
-
const pollMs = options.pollMs ?? 1000;
|
|
291
|
-
const deadline = Date.now() + timeoutMs;
|
|
292
|
-
let lastError;
|
|
293
|
-
let switched = null;
|
|
294
|
-
while (Date.now() < deadline) {
|
|
295
|
-
try {
|
|
296
|
-
switched = await requestServerJson(context, "/api/server/project-root", {
|
|
297
|
-
method: "POST",
|
|
298
|
-
headers: { "content-type": "application/json" },
|
|
299
|
-
body: JSON.stringify({ projectRoot })
|
|
300
|
-
});
|
|
301
|
-
break;
|
|
302
|
-
} catch (error) {
|
|
303
|
-
lastError = error;
|
|
304
|
-
if (!isRetryableProjectRootSwitchError(error))
|
|
305
|
-
throw error;
|
|
306
|
-
await sleep(pollMs);
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
if (!switched) {
|
|
310
|
-
throw new CliError2(`Rig server did not accept project-root switch to ${projectRoot} before timeout (${lastError instanceof Error ? lastError.message : String(lastError ?? "no response")}).`, 1);
|
|
311
|
-
}
|
|
312
|
-
while (Date.now() < deadline) {
|
|
313
|
-
try {
|
|
314
|
-
const status = await requestServerJson(context, "/api/server/status");
|
|
315
|
-
if (status && typeof status === "object" && !Array.isArray(status)) {
|
|
316
|
-
const record = status;
|
|
317
|
-
if (record.projectRoot === projectRoot) {
|
|
318
|
-
return { ok: true, switched, status: record };
|
|
319
|
-
}
|
|
320
|
-
lastError = `server projectRoot=${String(record.projectRoot ?? "unknown")}`;
|
|
321
|
-
}
|
|
322
|
-
} catch (error) {
|
|
323
|
-
lastError = error;
|
|
324
|
-
}
|
|
325
|
-
await sleep(pollMs);
|
|
326
|
-
}
|
|
327
|
-
throw new CliError2(`Rig server did not switch to ${projectRoot} before timeout (${lastError instanceof Error ? lastError.message : String(lastError ?? "no status")}).`, 1);
|
|
328
|
-
}
|
|
329
|
-
async function ensureTaskLabelsViaServer(context) {
|
|
330
|
-
const payload = await requestServerJson(context, "/api/workspace/task-labels", { method: "POST" });
|
|
331
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
332
|
-
}
|
|
333
|
-
async function listGitHubProjectsViaServer(context, owner) {
|
|
334
|
-
const url = new URL("http://rig.local/api/github/projects");
|
|
335
|
-
url.searchParams.set("owner", owner);
|
|
336
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
337
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { projects: [] };
|
|
338
|
-
}
|
|
339
|
-
async function getGitHubProjectStatusFieldViaServer(context, projectId) {
|
|
340
|
-
const payload = await requestServerJson(context, `/api/github/projects/${encodeURIComponent(projectId)}/status-field`);
|
|
341
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
// packages/cli/src/commands/_pi-install.ts
|
|
345
|
-
import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync } from "fs";
|
|
346
|
-
import { homedir as homedir2 } from "os";
|
|
347
|
-
import { resolve as resolve3 } from "path";
|
|
348
|
-
var PI_RIG_PACKAGE_NAME = "@h-rig/pi-rig";
|
|
349
|
-
var LEGACY_PI_RIG_PACKAGE_NAME = "@rig/pi-rig";
|
|
350
|
-
var LEGACY_PI_RIG_MARKER = `// Managed by Rig. Source package: @rig/pi-rig.
|
|
351
|
-
export { default } from '@rig/pi-rig';
|
|
352
|
-
`;
|
|
353
|
-
async function defaultCommandRunner(command, options = {}) {
|
|
354
|
-
const proc = Bun.spawn(command, { cwd: options.cwd, stdout: "pipe", stderr: "pipe" });
|
|
355
|
-
const [stdout, stderr, exitCode] = await Promise.all([
|
|
356
|
-
new Response(proc.stdout).text(),
|
|
357
|
-
new Response(proc.stderr).text(),
|
|
358
|
-
proc.exited
|
|
359
|
-
]);
|
|
360
|
-
return { exitCode, stdout, stderr };
|
|
361
|
-
}
|
|
362
|
-
function resolvePiRigExtensionPath(homeDir) {
|
|
363
|
-
return resolve3(homeDir, ".pi", "agent", "extensions", "pi-rig");
|
|
364
|
-
}
|
|
365
|
-
function resolvePiRigPackageSource(projectRoot, exists = existsSync3) {
|
|
366
|
-
const localPackage = resolve3(projectRoot, "packages", "pi-rig");
|
|
367
|
-
if (exists(resolve3(localPackage, "package.json")))
|
|
368
|
-
return localPackage;
|
|
369
|
-
return `npm:${PI_RIG_PACKAGE_NAME}`;
|
|
370
|
-
}
|
|
371
|
-
function resolvePiHomeDir(inputHomeDir) {
|
|
372
|
-
return inputHomeDir ?? process.env.RIG_PI_HOME_DIR?.trim() ?? homedir2();
|
|
373
|
-
}
|
|
374
|
-
function piListContainsPiRig(output) {
|
|
375
|
-
return output.split(/\r?\n/).some((line) => {
|
|
376
|
-
const normalized = line.trim();
|
|
377
|
-
return normalized.includes(PI_RIG_PACKAGE_NAME) || normalized.includes(LEGACY_PI_RIG_PACKAGE_NAME) || /(?:^|[\\/])packages[\\/]pi-rig(?:$|\s)/.test(normalized);
|
|
378
|
-
});
|
|
379
|
-
}
|
|
380
|
-
async function safeRun(runner, command, options) {
|
|
381
|
-
try {
|
|
382
|
-
return await runner(command, options);
|
|
383
|
-
} catch (error) {
|
|
384
|
-
return { exitCode: 1, stdout: "", stderr: error instanceof Error ? error.message : String(error) };
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
function splitInstallCommand(value) {
|
|
388
|
-
return value.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)?.map((part) => part.replace(/^['"]|['"]$/g, "")) ?? [];
|
|
389
|
-
}
|
|
390
|
-
async function ensurePiBinaryAvailable(input) {
|
|
391
|
-
const current = await safeRun(input.runner, ["pi", "--version"]);
|
|
392
|
-
if (current.exitCode === 0) {
|
|
393
|
-
const updateCommand = process.env.RIG_PI_UPDATE_COMMAND?.trim();
|
|
394
|
-
if (updateCommand) {
|
|
395
|
-
const parts2 = splitInstallCommand(updateCommand);
|
|
396
|
-
if (parts2.length > 0)
|
|
397
|
-
await safeRun(input.runner, parts2, input.projectRoot ? { cwd: input.projectRoot } : undefined);
|
|
398
|
-
}
|
|
399
|
-
return { ok: true, detail: (current.stdout || current.stderr).trim() || undefined };
|
|
400
|
-
}
|
|
401
|
-
const installCommand = process.env.RIG_PI_INSTALL_COMMAND?.trim() || "bunx @earendil-works/pi@latest install";
|
|
402
|
-
const parts = splitInstallCommand(installCommand);
|
|
403
|
-
if (parts.length === 0) {
|
|
404
|
-
return { ok: false, error: (current.stderr || current.stdout).trim() || "pi --version failed" };
|
|
405
|
-
}
|
|
406
|
-
const install = await safeRun(input.runner, parts, input.projectRoot ? { cwd: input.projectRoot } : undefined);
|
|
407
|
-
if (install.exitCode !== 0) {
|
|
408
|
-
return { ok: false, installedOrUpdated: true, error: (install.stderr || install.stdout).trim() || `Pi install command failed (${install.exitCode})` };
|
|
409
|
-
}
|
|
410
|
-
const next = await safeRun(input.runner, ["pi", "--version"]);
|
|
411
|
-
return {
|
|
412
|
-
ok: next.exitCode === 0,
|
|
413
|
-
installedOrUpdated: true,
|
|
414
|
-
detail: (next.stdout || next.stderr).trim() || undefined,
|
|
415
|
-
...next.exitCode === 0 ? {} : { error: (next.stderr || next.stdout).trim() || "pi --version failed after install" }
|
|
416
|
-
};
|
|
417
|
-
}
|
|
418
|
-
function removeManagedLegacyPiRigBridge(homeDir, exists = existsSync3) {
|
|
419
|
-
const extensionPath = resolvePiRigExtensionPath(homeDir);
|
|
420
|
-
const indexPath = resolve3(extensionPath, "index.ts");
|
|
421
|
-
if (!exists(indexPath))
|
|
422
|
-
return;
|
|
423
|
-
try {
|
|
424
|
-
const content = readFileSync3(indexPath, "utf8");
|
|
425
|
-
if (content === LEGACY_PI_RIG_MARKER || content.includes("Managed by Rig. Source package: @rig/pi-rig")) {
|
|
426
|
-
rmSync(extensionPath, { recursive: true, force: true });
|
|
427
|
-
}
|
|
428
|
-
} catch {}
|
|
429
|
-
}
|
|
430
|
-
async function checkPiRigInstall(input = {}) {
|
|
431
|
-
const home = resolvePiHomeDir(input.homeDir);
|
|
432
|
-
const extensionPath = resolvePiRigExtensionPath(home);
|
|
433
|
-
if (process.env.RIG_TEST_FAKE_PI_INSTALL === "1") {
|
|
434
|
-
return {
|
|
435
|
-
extensionPath,
|
|
436
|
-
pi: { ok: true, label: "pi", detail: "fake-pi" },
|
|
437
|
-
piRig: { ok: true, label: "pi-rig global extension", detail: extensionPath }
|
|
438
|
-
};
|
|
439
|
-
}
|
|
440
|
-
const exists = input.exists ?? existsSync3;
|
|
441
|
-
const runner = input.commandRunner ?? defaultCommandRunner;
|
|
442
|
-
const piResult = await safeRun(runner, ["pi", "--version"]);
|
|
443
|
-
const piListResult = piResult.exitCode === 0 ? await safeRun(runner, ["pi", "list"]) : { exitCode: 1, stdout: "", stderr: "" };
|
|
444
|
-
const listedPiRig = piListResult.exitCode === 0 && piListContainsPiRig(`${piListResult.stdout}
|
|
445
|
-
${piListResult.stderr}`);
|
|
446
|
-
const legacyBridge = exists(resolve3(extensionPath, "index.ts"));
|
|
447
|
-
const hasPiRig = listedPiRig;
|
|
448
|
-
return {
|
|
449
|
-
extensionPath,
|
|
450
|
-
pi: {
|
|
451
|
-
ok: piResult.exitCode === 0,
|
|
452
|
-
label: "pi",
|
|
453
|
-
detail: (piResult.stdout || piResult.stderr).trim() || undefined,
|
|
454
|
-
hint: piResult.exitCode === 0 ? undefined : "Install Pi or run `rig init --yes` to install/update the Pi runtime."
|
|
455
|
-
},
|
|
456
|
-
piRig: {
|
|
457
|
-
ok: hasPiRig,
|
|
458
|
-
label: "pi-rig global extension",
|
|
459
|
-
detail: hasPiRig ? piListResult.stdout.trim() || PI_RIG_PACKAGE_NAME : legacyBridge ? `${extensionPath} (legacy bridge; reinstall required)` : undefined,
|
|
460
|
-
hint: hasPiRig ? undefined : "Run `rig init --yes` to install/enable the global pi-rig package with `pi install`."
|
|
461
|
-
}
|
|
462
|
-
};
|
|
463
|
-
}
|
|
464
|
-
async function ensurePiRigInstalled(input) {
|
|
465
|
-
const home = resolvePiHomeDir(input.homeDir);
|
|
466
|
-
if (process.env.RIG_TEST_FAKE_PI_INSTALL === "1") {
|
|
467
|
-
const status2 = await checkPiRigInstall({ homeDir: home, commandRunner: input.commandRunner });
|
|
468
|
-
return { ...status2, installedPath: status2.extensionPath };
|
|
469
|
-
}
|
|
470
|
-
const runner = input.commandRunner ?? defaultCommandRunner;
|
|
471
|
-
const piAvailable = await ensurePiBinaryAvailable({ runner, projectRoot: input.projectRoot });
|
|
472
|
-
const status = piAvailable.ok ? await checkPiRigInstall({ homeDir: home, commandRunner: runner }) : {
|
|
473
|
-
extensionPath: resolvePiRigExtensionPath(home),
|
|
474
|
-
pi: { ok: false, label: "pi", detail: piAvailable.error, hint: "Install/update Pi with RIG_PI_INSTALL_COMMAND or install Pi manually." },
|
|
475
|
-
piRig: { ok: false, label: "pi-rig global extension", hint: "Pi is required before pi-rig can be installed." }
|
|
476
|
-
};
|
|
477
|
-
if (!piAvailable.ok) {
|
|
478
|
-
throw new Error(`Pi install/update failed: ${piAvailable.error ?? "pi unavailable"}`);
|
|
479
|
-
}
|
|
480
|
-
const packageSource = resolvePiRigPackageSource(input.projectRoot);
|
|
481
|
-
removeManagedLegacyPiRigBridge(home);
|
|
482
|
-
const install = await runner(["pi", "install", packageSource], { cwd: input.projectRoot });
|
|
483
|
-
if (install.exitCode !== 0) {
|
|
484
|
-
throw new Error(`pi-rig install failed: ${(install.stderr || install.stdout).trim() || `exit ${install.exitCode}`}`);
|
|
485
|
-
}
|
|
486
|
-
const next = await checkPiRigInstall({ homeDir: home, commandRunner: runner });
|
|
487
|
-
return { ...next, installedPath: packageSource };
|
|
488
|
-
}
|
|
489
|
-
async function ensureRemotePiRigInstalled(input) {
|
|
490
|
-
const payload = await input.requestJson("/api/pi-rig/install", {
|
|
491
|
-
method: "POST",
|
|
492
|
-
headers: { "content-type": "application/json" },
|
|
493
|
-
body: JSON.stringify({ package: PI_RIG_PACKAGE_NAME, scope: "global" })
|
|
494
|
-
});
|
|
495
|
-
const record = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
496
|
-
const piOk = record.piOk === true || record.ok === true;
|
|
497
|
-
const piRigOk = record.piRigOk === true || record.installed === true || record.ok === true;
|
|
498
|
-
const extensionPath = typeof record.extensionPath === "string" ? record.extensionPath : "remote:~/.pi/agent/extensions/pi-rig";
|
|
499
|
-
return {
|
|
500
|
-
remote: true,
|
|
501
|
-
extensionPath,
|
|
502
|
-
pi: {
|
|
503
|
-
ok: piOk,
|
|
504
|
-
label: "pi",
|
|
505
|
-
detail: typeof record.piVersion === "string" ? record.piVersion : undefined,
|
|
506
|
-
hint: piOk ? undefined : "Install/update Pi on the selected remote Rig server."
|
|
507
|
-
},
|
|
508
|
-
piRig: {
|
|
509
|
-
ok: piRigOk,
|
|
510
|
-
label: "pi-rig global extension",
|
|
511
|
-
detail: extensionPath,
|
|
512
|
-
hint: piRigOk ? undefined : "Install/enable pi-rig on the selected remote Rig server."
|
|
513
|
-
}
|
|
514
|
-
};
|
|
515
|
-
}
|
|
516
|
-
async function buildPiSetupChecks(input = {}) {
|
|
517
|
-
const status = await checkPiRigInstall(input);
|
|
518
|
-
return [status.pi, status.piRig];
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
// packages/cli/src/commands/_snapshot-upload.ts
|
|
522
|
-
import { mkdir, readdir, readFile, writeFile } from "fs/promises";
|
|
523
|
-
import { dirname as dirname2, resolve as resolve4, relative, sep } from "path";
|
|
524
|
-
var SNAPSHOT_ARCHIVE_VERSION = 1;
|
|
525
|
-
var SNAPSHOT_ARCHIVE_CONTENT_TYPE = "application/vnd.rig.snapshot+json";
|
|
526
|
-
var DEFAULT_EXCLUDED_DIRECTORIES = new Set([
|
|
527
|
-
".git",
|
|
528
|
-
".rig",
|
|
529
|
-
"node_modules",
|
|
530
|
-
".turbo",
|
|
531
|
-
".next",
|
|
532
|
-
".cache",
|
|
533
|
-
"coverage",
|
|
534
|
-
"dist",
|
|
535
|
-
"build",
|
|
536
|
-
"out"
|
|
537
|
-
]);
|
|
538
|
-
function toPosixPath(path) {
|
|
539
|
-
return path.split(sep).join("/");
|
|
540
|
-
}
|
|
541
|
-
function assertManifestPath(root, relativePath) {
|
|
542
|
-
if (!relativePath || relativePath.startsWith("/") || relativePath.includes("\x00")) {
|
|
543
|
-
throw new Error(`Invalid snapshot path: ${relativePath}`);
|
|
544
|
-
}
|
|
545
|
-
const resolved = resolve4(root, relativePath);
|
|
546
|
-
const relativeToRoot = relative(root, resolved);
|
|
547
|
-
if (relativeToRoot.startsWith("..") || relativeToRoot === ".." || resolve4(relativeToRoot) === resolved) {
|
|
548
|
-
throw new Error(`Snapshot path escapes project root: ${relativePath}`);
|
|
549
|
-
}
|
|
550
|
-
return resolved;
|
|
551
|
-
}
|
|
552
|
-
async function buildSnapshotUploadManifest(projectRoot, options = {}) {
|
|
553
|
-
const root = resolve4(projectRoot);
|
|
554
|
-
const excludedDirectories = [...new Set([
|
|
555
|
-
...DEFAULT_EXCLUDED_DIRECTORIES,
|
|
556
|
-
...options.excludedDirectories ?? []
|
|
557
|
-
])];
|
|
558
|
-
const excludedSet = new Set(excludedDirectories);
|
|
559
|
-
const files = [];
|
|
560
|
-
async function visit(dir) {
|
|
561
|
-
const entries = await readdir(dir, { withFileTypes: true });
|
|
562
|
-
for (const entry of entries) {
|
|
563
|
-
if (entry.isDirectory() && excludedSet.has(entry.name))
|
|
564
|
-
continue;
|
|
565
|
-
const fullPath = resolve4(dir, entry.name);
|
|
566
|
-
if (entry.isDirectory()) {
|
|
567
|
-
await visit(fullPath);
|
|
568
|
-
continue;
|
|
569
|
-
}
|
|
570
|
-
if (!entry.isFile())
|
|
571
|
-
continue;
|
|
572
|
-
files.push(toPosixPath(relative(root, fullPath)));
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
await visit(root);
|
|
576
|
-
files.sort();
|
|
577
|
-
return { root, files, excludedDirectories };
|
|
578
|
-
}
|
|
579
|
-
async function createSnapshotUploadArchive(projectRoot, options = {}) {
|
|
580
|
-
const manifest = await buildSnapshotUploadManifest(projectRoot, options);
|
|
581
|
-
const files = await Promise.all(manifest.files.map(async (path) => {
|
|
582
|
-
const fullPath = assertManifestPath(manifest.root, path);
|
|
583
|
-
return {
|
|
584
|
-
path,
|
|
585
|
-
contentBase64: (await readFile(fullPath)).toString("base64")
|
|
586
|
-
};
|
|
587
|
-
}));
|
|
588
|
-
return {
|
|
589
|
-
version: SNAPSHOT_ARCHIVE_VERSION,
|
|
590
|
-
root: manifest.root,
|
|
591
|
-
files,
|
|
592
|
-
excludedDirectories: manifest.excludedDirectories,
|
|
593
|
-
createdAt: (options.now?.() ?? new Date).toISOString()
|
|
594
|
-
};
|
|
595
|
-
}
|
|
596
|
-
function encodeSnapshotUploadArchive(archive) {
|
|
597
|
-
return Buffer.from(JSON.stringify(archive), "utf8").toString("base64");
|
|
598
|
-
}
|
|
599
|
-
async function uploadSnapshotArchiveViaServer(context, input) {
|
|
600
|
-
const payload = await requestServerJson(context, `/api/projects/${encodeURIComponent(input.repoSlug)}/upload-snapshot`, {
|
|
601
|
-
method: "POST",
|
|
602
|
-
headers: { "content-type": "application/json" },
|
|
603
|
-
body: JSON.stringify({
|
|
604
|
-
archiveContentBase64: encodeSnapshotUploadArchive(input.archive),
|
|
605
|
-
contentType: SNAPSHOT_ARCHIVE_CONTENT_TYPE,
|
|
606
|
-
baseDir: input.baseDir
|
|
607
|
-
})
|
|
608
|
-
});
|
|
609
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
610
|
-
}
|
|
611
|
-
|
|
612
|
-
// packages/cli/src/commands/_doctor-checks.ts
|
|
613
|
-
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
|
|
614
|
-
import { resolve as resolve5 } from "path";
|
|
615
|
-
import { isSupportedBunVersion, MIN_SUPPORTED_BUN_VERSION } from "@rig/runtime/control-plane/setup-version";
|
|
616
|
-
|
|
617
|
-
// packages/cli/src/commands/_parsers.ts
|
|
618
|
-
async function loadRigConfigOrNull(projectRoot) {
|
|
619
|
-
try {
|
|
620
|
-
const { loadConfig } = await import("@rig/core/load-config");
|
|
621
|
-
return await loadConfig(projectRoot);
|
|
622
|
-
} catch {
|
|
623
|
-
return null;
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
// packages/cli/src/commands/_doctor-checks.ts
|
|
628
|
-
function check(id, label, status, detail, remediation) {
|
|
629
|
-
return {
|
|
630
|
-
id,
|
|
631
|
-
label,
|
|
632
|
-
status,
|
|
633
|
-
...detail ? { detail } : {},
|
|
634
|
-
...remediation ? { remediation } : {}
|
|
635
|
-
};
|
|
636
|
-
}
|
|
637
|
-
function errorMessage(error) {
|
|
638
|
-
return error instanceof Error ? error.message : String(error);
|
|
639
|
-
}
|
|
640
|
-
function isAuthenticated(payload) {
|
|
641
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
642
|
-
return false;
|
|
643
|
-
const record = payload;
|
|
644
|
-
return record.signedIn === true || record.authenticated === true || record.status === "authenticated" || record.ok === true && typeof record.login === "string" && record.login.trim().length > 0;
|
|
645
|
-
}
|
|
646
|
-
function repoSlugFromConfig(config) {
|
|
647
|
-
const project = config?.project;
|
|
648
|
-
if (project && typeof project === "object" && !Array.isArray(project)) {
|
|
649
|
-
const record = project;
|
|
650
|
-
if (typeof record.repo === "string" && /^([^/\s]+)\/([^/\s]+)$/.test(record.repo))
|
|
651
|
-
return record.repo;
|
|
652
|
-
if (typeof record.name === "string" && /^([^/\s]+)\/([^/\s]+)$/.test(record.name))
|
|
653
|
-
return record.name;
|
|
654
|
-
}
|
|
655
|
-
const taskSource = config?.taskSource;
|
|
656
|
-
if (taskSource && typeof taskSource === "object" && !Array.isArray(taskSource)) {
|
|
657
|
-
const source = taskSource;
|
|
658
|
-
if (typeof source.owner === "string" && typeof source.repo === "string")
|
|
659
|
-
return `${source.owner}/${source.repo}`;
|
|
660
|
-
}
|
|
661
|
-
return null;
|
|
662
|
-
}
|
|
663
|
-
function loadFallbackConfig(projectRoot) {
|
|
664
|
-
const candidates = ["rig.config.ts", "rig.config.mts", "rig.config.json"];
|
|
665
|
-
for (const name of candidates) {
|
|
666
|
-
const path = resolve5(projectRoot, name);
|
|
667
|
-
if (!existsSync4(path))
|
|
668
|
-
continue;
|
|
669
|
-
try {
|
|
670
|
-
const source = readFileSync4(path, "utf8");
|
|
671
|
-
if (name.endsWith(".json"))
|
|
672
|
-
return JSON.parse(source);
|
|
673
|
-
const owner = source.match(/owner\s*:\s*["']([^"']+)["']/)?.[1];
|
|
674
|
-
const repo = source.match(/repo\s*:\s*["']([^"']+)["']/)?.[1];
|
|
675
|
-
const projectRepo = source.match(/project\s*:\s*\{[^}]*repo\s*:\s*["']([^"']+)["']/s)?.[1] ?? (owner && repo ? `${owner}/${repo}` : undefined);
|
|
676
|
-
const taskKind = source.match(/taskSource\s*:\s*\{[^}]*kind\s*:\s*["']([^"']+)["']/s)?.[1];
|
|
677
|
-
if (projectRepo || taskKind) {
|
|
678
|
-
return {
|
|
679
|
-
...projectRepo ? { project: { name: projectRepo, repo: projectRepo } } : {},
|
|
680
|
-
...taskKind ? { taskSource: { kind: taskKind, ...owner ? { owner } : {}, ...repo ? { repo } : {} } } : {}
|
|
681
|
-
};
|
|
682
|
-
}
|
|
683
|
-
} catch {
|
|
684
|
-
return null;
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
return null;
|
|
688
|
-
}
|
|
689
|
-
function projectStatusSlug(projectRoot, config) {
|
|
690
|
-
return readRepoConnection(projectRoot)?.project ?? repoSlugFromConfig(config);
|
|
691
|
-
}
|
|
692
|
-
function githubProjectsCheck(config) {
|
|
693
|
-
const github = config?.github;
|
|
694
|
-
const projects = github?.projects;
|
|
695
|
-
if (!projects?.enabled) {
|
|
696
|
-
return check("github-projects", "GitHub Projects status sync", "warn", "disabled or not configured", "Run `rig init --github-project <project>` or configure github.projects when Project status sync should be authoritative.");
|
|
697
|
-
}
|
|
698
|
-
if (projects.projectId && projects.statusFieldId) {
|
|
699
|
-
return check("github-projects", "GitHub Projects status sync", "pass", `project ${projects.projectId}`);
|
|
700
|
-
}
|
|
701
|
-
return check("github-projects", "GitHub Projects status sync", "fail", "enabled but projectId/statusFieldId is incomplete", "Configure github.projects.projectId and github.projects.statusFieldId, or disable github.projects.enabled.");
|
|
702
|
-
}
|
|
703
|
-
function permissionAllowsPr(payload) {
|
|
704
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
705
|
-
return null;
|
|
706
|
-
const record = payload;
|
|
707
|
-
if (record.canOpenPullRequest === true || record.pullRequests === true || record.push === true || record.maintain === true || record.admin === true)
|
|
708
|
-
return true;
|
|
709
|
-
if (record.canOpenPullRequest === false || record.pullRequests === false || record.push === false)
|
|
710
|
-
return false;
|
|
711
|
-
const permissions = record.permissions;
|
|
712
|
-
if (permissions && typeof permissions === "object" && !Array.isArray(permissions)) {
|
|
713
|
-
const p = permissions;
|
|
714
|
-
if (p.push === true || p.maintain === true || p.admin === true)
|
|
715
|
-
return true;
|
|
716
|
-
if (p.push === false && p.maintain !== true && p.admin !== true)
|
|
717
|
-
return false;
|
|
718
|
-
}
|
|
719
|
-
return null;
|
|
720
|
-
}
|
|
721
|
-
function labelsReady(payload) {
|
|
722
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
723
|
-
return null;
|
|
724
|
-
const record = payload;
|
|
725
|
-
if (record.ok === true || record.ready === true || record.labelsReady === true)
|
|
726
|
-
return true;
|
|
727
|
-
if (record.ok === false || record.ready === false || record.labelsReady === false)
|
|
728
|
-
return false;
|
|
729
|
-
return null;
|
|
730
|
-
}
|
|
731
|
-
function prMergeCheck(config) {
|
|
732
|
-
const pr = config?.pr;
|
|
733
|
-
const merge = config?.merge;
|
|
734
|
-
if (pr?.mode === "off" || merge?.mode === "off") {
|
|
735
|
-
return check("pr-merge", "PR/merge automation", "warn", "automatic PR or merge is disabled", "Set pr.mode and merge.mode to auto for autonomous YOLO runs.");
|
|
736
|
-
}
|
|
737
|
-
return check("pr-merge", "PR/merge automation", "pass", `pr=${pr?.mode ?? "auto"}, merge=${merge?.mode ?? "auto"}, method=${merge?.method ?? "repo-default"}`);
|
|
738
|
-
}
|
|
739
|
-
async function runRigDoctorChecks(options) {
|
|
740
|
-
const projectRoot = options.projectRoot;
|
|
741
|
-
const checks = [];
|
|
742
|
-
const which = options.which ?? ((binary) => Bun.which(binary));
|
|
743
|
-
const bunVersion = options.bunVersion ?? Bun.version;
|
|
744
|
-
const request = options.requestJson ?? ((pathname, init) => requestServerJson({ projectRoot }, pathname, init));
|
|
745
|
-
const loadConfig = options.loadConfig ?? loadRigConfigOrNull;
|
|
746
|
-
checks.push(check("bun", `bun >= ${MIN_SUPPORTED_BUN_VERSION}`, isSupportedBunVersion(bunVersion) ? "pass" : "fail", `found ${bunVersion}`, `Install Bun ${MIN_SUPPORTED_BUN_VERSION} or newer.`), check("git", "git", which("git") ? "pass" : "fail", which("git") ?? undefined, "Install git and ensure it is on PATH."), check("jq", "jq", which("jq") ? "pass" : "warn", which("jq") ?? undefined, "Install jq (for example `brew install jq`)."));
|
|
747
|
-
const loadedConfig = await loadConfig(projectRoot).catch(() => null);
|
|
748
|
-
const config = loadedConfig ?? loadFallbackConfig(projectRoot);
|
|
749
|
-
const hasConfigFile = ["rig.config.ts", "rig.config.mts", "rig.config.json"].some((name) => existsSync4(resolve5(projectRoot, name)));
|
|
750
|
-
checks.push(config ? check("config", "rig.config loadable", "pass") : check("config", "rig.config loadable", hasConfigFile ? "fail" : "fail", hasConfigFile ? "config file exists but failed to load" : "missing rig.config.ts/json", "Run `rig init` or fix the config error."));
|
|
751
|
-
const taskSourceKind = config?.taskSource?.kind;
|
|
752
|
-
checks.push(taskSourceKind ? check("task-source", "task source configured", "pass", taskSourceKind) : check("task-source", "task source configured", "fail", "missing taskSource", "Configure taskSource in rig.config.ts."));
|
|
753
|
-
const repo = readRepoConnection(projectRoot);
|
|
754
|
-
checks.push(repo ? check("project-link", "repo selected Rig server", repo.project ? "pass" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : ""}`, "Run `rig init --yes --repo owner/repo` to link this checkout to a GitHub repo slug.") : check("project-link", "repo selected Rig server", "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
|
|
755
|
-
const selected = (() => {
|
|
756
|
-
try {
|
|
757
|
-
return resolveSelectedConnection(projectRoot);
|
|
758
|
-
} catch {
|
|
759
|
-
return null;
|
|
760
|
-
}
|
|
761
|
-
})();
|
|
762
|
-
checks.push(selected ? check("connection", "selected server connection", "pass", selected.connection.kind === "remote" ? selected.connection.baseUrl : "local auto") : check("connection", "selected server", repo ? "fail" : "warn", repo ? "selected alias is missing" : "will auto-start local server", repo ? "Run `rig server list` and `rig server use <alias|local>`." : undefined));
|
|
763
|
-
let server = null;
|
|
764
|
-
try {
|
|
765
|
-
server = await (options.resolveServer ?? ensureServerForCli)(projectRoot);
|
|
766
|
-
checks.push(check("server", "Rig server reachable", "pass", `${server.connectionKind} ${server.baseUrl}`));
|
|
767
|
-
} catch (error) {
|
|
768
|
-
checks.push(check("server", "Rig server reachable", "fail", errorMessage(error), "Start the local Rig server or fix the selected remote connection."));
|
|
769
|
-
}
|
|
770
|
-
if (server || options.requestJson) {
|
|
771
|
-
try {
|
|
772
|
-
const status = await request("/api/server/status");
|
|
773
|
-
checks.push(check("server-status", "server project status", "pass", JSON.stringify(status).slice(0, 180)));
|
|
774
|
-
} catch (error) {
|
|
775
|
-
checks.push(check("server-status", "server project status", "fail", errorMessage(error), "Run `rig doctor` after the selected server is reachable."));
|
|
776
|
-
}
|
|
777
|
-
try {
|
|
778
|
-
const auth = await request("/api/github/auth/status");
|
|
779
|
-
checks.push(isAuthenticated(auth) ? check("github-auth", "GitHub auth", "pass") : check("github-auth", "GitHub auth", "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
|
|
780
|
-
} catch (error) {
|
|
781
|
-
checks.push(check("github-auth", "GitHub auth", "fail", errorMessage(error), "Authenticate GitHub through Rig and ensure the server exposes auth status."));
|
|
782
|
-
}
|
|
783
|
-
try {
|
|
784
|
-
const permissions = await request("/api/github/repo/permissions");
|
|
785
|
-
const allowed = permissionAllowsPr(permissions);
|
|
786
|
-
checks.push(allowed === true ? check("github-repo-permissions", "GitHub repo PR permissions", "pass", JSON.stringify(permissions).slice(0, 180)) : allowed === false ? check("github-repo-permissions", "GitHub repo PR permissions", "fail", JSON.stringify(permissions).slice(0, 180), "Grant the selected GitHub token permission to push branches, open PRs, and merge according to repo rules.") : check("github-repo-permissions", "GitHub repo PR permissions", "warn", JSON.stringify(permissions).slice(0, 180), "Confirm the selected token can push branches and open PRs."));
|
|
787
|
-
} catch (error) {
|
|
788
|
-
checks.push(check("github-repo-permissions", "GitHub repo PR permissions", "warn", errorMessage(error), "Ensure the server exposes repo permission checks and the token can open PRs."));
|
|
789
|
-
}
|
|
790
|
-
try {
|
|
791
|
-
const labels = await request("/api/workspace/task-labels");
|
|
792
|
-
const ready = labelsReady(labels);
|
|
793
|
-
checks.push(ready === false ? check("task-labels", "GitHub issue labels", "fail", JSON.stringify(labels).slice(0, 180), "Let Rig create required labels or create the configured lifecycle labels manually.") : check("task-labels", "GitHub issue labels", ready === true ? "pass" : "warn", JSON.stringify(labels).slice(0, 180), "Confirm required Rig lifecycle labels exist."));
|
|
794
|
-
} catch (error) {
|
|
795
|
-
checks.push(check("task-labels", "GitHub issue labels", "warn", errorMessage(error), "Run `rig init`/`rig doctor` after label setup is wired on the server."));
|
|
796
|
-
}
|
|
797
|
-
try {
|
|
798
|
-
const projection = await request("/api/workspace/task-projection");
|
|
799
|
-
checks.push(check("task-projection", "task projection", "pass", JSON.stringify(projection).slice(0, 180)));
|
|
800
|
-
} catch (error) {
|
|
801
|
-
checks.push(check("task-projection", "task projection", "warn", errorMessage(error), "Refresh task projection with `rig task list` or fix the task source."));
|
|
802
|
-
}
|
|
803
|
-
const slug = projectStatusSlug(projectRoot, config);
|
|
804
|
-
if (slug) {
|
|
805
|
-
try {
|
|
806
|
-
const project = await request(`/api/projects/${encodeURIComponent(slug)}`);
|
|
807
|
-
checks.push(check("remote-checkout", "server project checkout", "pass", JSON.stringify(project).slice(0, 180)));
|
|
808
|
-
} catch (error) {
|
|
809
|
-
checks.push(check("remote-checkout", "server project checkout", "warn", errorMessage(error), "Run `rig init --yes --repo owner/repo` to register/link the server project checkout."));
|
|
810
|
-
}
|
|
811
|
-
} else {
|
|
812
|
-
checks.push(check("remote-checkout", "server project checkout", "warn", "repo slug unknown", "Set project.repo or run `rig init --repo owner/repo`."));
|
|
813
|
-
}
|
|
814
|
-
}
|
|
815
|
-
if (taskSourceKind === "github-issues") {
|
|
816
|
-
checks.push(check("gh", "gh CLI fallback", which("gh") ? "pass" : "warn", which("gh") ?? undefined, "Install gh for local/dev GitHub fallback operations."));
|
|
817
|
-
}
|
|
818
|
-
checks.push(githubProjectsCheck(config));
|
|
819
|
-
checks.push(prMergeCheck(config));
|
|
820
|
-
const piChecks = await (options.piChecks ?? (() => buildPiSetupChecks()))().catch((error) => [{
|
|
821
|
-
ok: false,
|
|
822
|
-
label: "pi/pi-rig checks",
|
|
823
|
-
hint: errorMessage(error)
|
|
824
|
-
}]);
|
|
825
|
-
for (const pi of piChecks) {
|
|
826
|
-
checks.push(check(pi.label === "pi" ? "pi" : "pi-rig", pi.label, pi.ok ? "pass" : "warn", pi.detail, pi.hint ?? (pi.ok ? undefined : "Run `rig init --yes` to install/update Pi and enable pi-rig.")));
|
|
827
|
-
}
|
|
828
|
-
return checks;
|
|
829
|
-
}
|
|
830
|
-
function countDoctorFailures(checks) {
|
|
831
|
-
return checks.filter((entry) => entry.status === "fail").length;
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
// packages/cli/src/commands/init.ts
|
|
835
|
-
var RIG_CONFIG_PACKAGE_DIST_TAG = "latest";
|
|
836
|
-
var DEFAULT_REMOTE_RIG_URL = "https://where.rig-does.work";
|
|
837
|
-
var RIG_CONFIG_DEV_DEPENDENCIES = {
|
|
838
|
-
"@rig/core": `npm:@h-rig/core@${RIG_CONFIG_PACKAGE_DIST_TAG}`,
|
|
839
|
-
"@rig/standard-plugin": `npm:@h-rig/standard-plugin@${RIG_CONFIG_PACKAGE_DIST_TAG}`
|
|
840
|
-
};
|
|
841
|
-
function parseRepoSlugFromRemote(remoteUrl) {
|
|
842
|
-
const trimmed = remoteUrl.trim();
|
|
843
|
-
const gitHubMatch = trimmed.match(/github\.com[:/]([^/]+)\/([^/.]+)(?:\.git)?$/i);
|
|
844
|
-
return gitHubMatch ? `${gitHubMatch[1]}/${gitHubMatch[2]}` : null;
|
|
845
|
-
}
|
|
846
|
-
function detectOriginRepoSlug(projectRoot) {
|
|
847
|
-
const result = spawnSync("git", ["-C", projectRoot, "remote", "get-url", "origin"], { encoding: "utf8" });
|
|
848
|
-
if (result.status !== 0)
|
|
849
|
-
return null;
|
|
850
|
-
return parseRepoSlugFromRemote(result.stdout.trim());
|
|
851
|
-
}
|
|
852
|
-
function parseRepoSlug(value) {
|
|
853
|
-
const match = value.trim().match(/^([^/\s]+)\/([^/\s]+)$/);
|
|
854
|
-
if (!match)
|
|
855
|
-
throw new CliError2(`Invalid GitHub repo slug: ${value}. Expected owner/repo.`, 1);
|
|
856
|
-
return { owner: match[1], repo: match[2], slug: `${match[1]}/${match[2]}` };
|
|
857
|
-
}
|
|
858
|
-
function ensureRigPrivateDirs(projectRoot) {
|
|
859
|
-
const rigDir = resolve6(projectRoot, ".rig");
|
|
860
|
-
mkdirSync2(resolve6(rigDir, "state"), { recursive: true });
|
|
861
|
-
mkdirSync2(resolve6(rigDir, "logs"), { recursive: true });
|
|
862
|
-
mkdirSync2(resolve6(rigDir, "runs"), { recursive: true });
|
|
863
|
-
mkdirSync2(resolve6(rigDir, "tmp"), { recursive: true });
|
|
864
|
-
mkdirSync2(resolve6(projectRoot, "artifacts"), { recursive: true });
|
|
865
|
-
const taskConfigPath = resolve6(rigDir, "task-config.json");
|
|
866
|
-
if (!existsSync5(taskConfigPath))
|
|
867
|
-
writeFileSync2(taskConfigPath, `{}
|
|
868
|
-
`, "utf-8");
|
|
869
|
-
}
|
|
870
|
-
function ensureGitignoreEntries(projectRoot) {
|
|
871
|
-
const path = resolve6(projectRoot, ".gitignore");
|
|
872
|
-
const existing = existsSync5(path) ? readFileSync5(path, "utf8") : "";
|
|
873
|
-
const entries = [".rig/state/", ".rig/logs/", ".rig/runs/", ".rig/tmp/"];
|
|
874
|
-
const missing = entries.filter((entry) => !existing.split(/\r?\n/).includes(entry));
|
|
875
|
-
if (missing.length === 0)
|
|
876
|
-
return;
|
|
877
|
-
const prefix = existing.length > 0 && !existing.endsWith(`
|
|
878
|
-
`) ? `
|
|
879
|
-
` : "";
|
|
880
|
-
appendFileSync(path, `${prefix}${missing.join(`
|
|
881
|
-
`)}
|
|
882
|
-
`, "utf8");
|
|
883
|
-
}
|
|
884
|
-
function ensureRigConfigPackageDependencies(projectRoot) {
|
|
885
|
-
const path = resolve6(projectRoot, "package.json");
|
|
886
|
-
const existing = existsSync5(path) ? JSON.parse(readFileSync5(path, "utf8")) : {};
|
|
887
|
-
const devDependencies = existing.devDependencies && typeof existing.devDependencies === "object" && !Array.isArray(existing.devDependencies) ? { ...existing.devDependencies } : {};
|
|
888
|
-
for (const [name, spec] of Object.entries(RIG_CONFIG_DEV_DEPENDENCIES)) {
|
|
889
|
-
devDependencies[name] = spec;
|
|
890
|
-
}
|
|
891
|
-
const next = {
|
|
892
|
-
...existsSync5(path) ? existing : { name: "rig-project", private: true },
|
|
893
|
-
devDependencies
|
|
894
|
-
};
|
|
895
|
-
writeFileSync2(path, `${JSON.stringify(next, null, 2)}
|
|
896
|
-
`, "utf8");
|
|
897
|
-
}
|
|
898
|
-
function applyGitHubProjectConfig(source, options) {
|
|
899
|
-
if (!options.githubProject || options.githubProject === "off")
|
|
900
|
-
return source;
|
|
901
|
-
const projectId = JSON.stringify(options.githubProject);
|
|
902
|
-
const statusFieldId = JSON.stringify(options.githubProjectStatusField ?? "Status");
|
|
903
|
-
const statuses = options.githubProjectStatuses && Object.keys(options.githubProjectStatuses).length > 0 ? `
|
|
904
|
-
statuses: ${JSON.stringify(options.githubProjectStatuses, null, 8).replace(/\n/g, `
|
|
905
|
-
`)},` : "";
|
|
906
|
-
return source.replace(` projects: { enabled: false },`, [
|
|
907
|
-
` projects: {`,
|
|
908
|
-
` enabled: true,`,
|
|
909
|
-
` projectId: ${projectId},`,
|
|
910
|
-
` statusFieldId: ${statusFieldId},${statuses}`,
|
|
911
|
-
` },`
|
|
912
|
-
].join(`
|
|
913
|
-
`));
|
|
914
|
-
}
|
|
915
|
-
function checkoutForInit(projectRoot, serverKind, strategy) {
|
|
916
|
-
if (serverKind === "local")
|
|
917
|
-
return { kind: "local", path: projectRoot };
|
|
918
|
-
const selected = strategy ?? { kind: "managed-clone" };
|
|
919
|
-
switch (selected.kind) {
|
|
920
|
-
case "managed-clone":
|
|
921
|
-
return { kind: "managed-clone", path: projectRoot };
|
|
922
|
-
case "current-ref":
|
|
923
|
-
return { kind: "current-ref", path: projectRoot, ...selected.ref ? { ref: selected.ref } : {} };
|
|
924
|
-
case "uploaded-snapshot":
|
|
925
|
-
return { kind: "uploaded-snapshot", path: projectRoot, source: "local-working-tree" };
|
|
926
|
-
case "existing-path":
|
|
927
|
-
return { kind: "existing-path", path: selected.path };
|
|
928
|
-
}
|
|
929
|
-
}
|
|
930
|
-
function detectGhLogin() {
|
|
931
|
-
const result = spawnSync("gh", ["api", "user", "--jq", ".login"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] });
|
|
932
|
-
return result.status === 0 && result.stdout.trim() ? result.stdout.trim() : null;
|
|
933
|
-
}
|
|
934
|
-
function readGhAuthToken() {
|
|
935
|
-
const result = spawnSync("gh", ["auth", "token"], { encoding: "utf8" });
|
|
936
|
-
if (result.status !== 0 || !result.stdout.trim()) {
|
|
937
|
-
throw new CliError2(result.stderr.trim() || "Could not read GitHub token from `gh auth token`.", result.status || 1);
|
|
938
|
-
}
|
|
939
|
-
return result.stdout.trim();
|
|
940
|
-
}
|
|
941
|
-
function refreshGhProjectScopesAndReadToken() {
|
|
942
|
-
const result = spawnSync("gh", ["auth", "refresh", "--scopes", "read:project"], {
|
|
943
|
-
encoding: "utf8",
|
|
944
|
-
stdio: ["inherit", "pipe", "pipe"]
|
|
945
|
-
});
|
|
946
|
-
if (result.status !== 0)
|
|
947
|
-
return null;
|
|
948
|
-
try {
|
|
949
|
-
return readGhAuthToken();
|
|
950
|
-
} catch {
|
|
951
|
-
return null;
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
async function loadClackPrompts() {
|
|
955
|
-
return await import("@clack/prompts");
|
|
956
|
-
}
|
|
957
|
-
function clackTextOptions(options) {
|
|
958
|
-
return {
|
|
959
|
-
message: options.message,
|
|
960
|
-
...options.placeholder ? { placeholder: options.placeholder } : {},
|
|
961
|
-
...(options.initialValue ?? options.defaultValue)?.trim() ? { initialValue: (options.initialValue ?? options.defaultValue).trim() } : {}
|
|
962
|
-
};
|
|
963
|
-
}
|
|
964
|
-
async function promptRequiredText(prompts, options) {
|
|
965
|
-
const value = await prompts.text(clackTextOptions(options));
|
|
966
|
-
if (prompts.isCancel(value))
|
|
967
|
-
throw new CliError2("Init cancelled.", 1);
|
|
968
|
-
const text = String(value ?? "").trim();
|
|
969
|
-
if (!text)
|
|
970
|
-
throw new CliError2(`${options.message} is required.`, 1);
|
|
971
|
-
return text;
|
|
972
|
-
}
|
|
973
|
-
async function promptOptionalText(prompts, options) {
|
|
974
|
-
const value = await prompts.text(clackTextOptions(options));
|
|
975
|
-
if (prompts.isCancel(value))
|
|
976
|
-
throw new CliError2("Init cancelled.", 1);
|
|
977
|
-
return String(value ?? "").trim();
|
|
978
|
-
}
|
|
979
|
-
async function promptSelect(prompts, options) {
|
|
980
|
-
const value = await prompts.select(options);
|
|
981
|
-
if (prompts.isCancel(value))
|
|
982
|
-
throw new CliError2("Init cancelled.", 1);
|
|
983
|
-
return String(value);
|
|
984
|
-
}
|
|
985
|
-
function repoOwnerFromSlug(repoSlug) {
|
|
986
|
-
return repoSlug.trim().match(/^([^/]+)\/[^/]+$/)?.[1] ?? null;
|
|
987
|
-
}
|
|
988
|
-
function recordArray(value, key) {
|
|
989
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
990
|
-
return [];
|
|
991
|
-
const raw = value[key];
|
|
992
|
-
return Array.isArray(raw) ? raw.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
|
|
993
|
-
}
|
|
994
|
-
async function listGitHubProjectsForInit(context, owner, token) {
|
|
995
|
-
if (token?.trim()) {
|
|
996
|
-
try {
|
|
997
|
-
return { ok: true, projects: await listGitHubProjectsDirect({ owner, token: token.trim() }) };
|
|
998
|
-
} catch (directError) {
|
|
999
|
-
const serverPayload = await listGitHubProjectsViaServer(context, owner).catch(() => null);
|
|
1000
|
-
if (recordArray(serverPayload, "projects").length > 0)
|
|
1001
|
-
return serverPayload;
|
|
1002
|
-
return { ok: false, error: directError instanceof Error ? directError.message : String(directError), projects: [] };
|
|
1003
|
-
}
|
|
1004
|
-
}
|
|
1005
|
-
return listGitHubProjectsViaServer(context, owner);
|
|
1006
|
-
}
|
|
1007
|
-
async function getGitHubProjectStatusFieldForInit(context, projectId, token) {
|
|
1008
|
-
if (token?.trim()) {
|
|
1009
|
-
try {
|
|
1010
|
-
return { ok: true, field: await resolveProjectStatusFieldDirect({ projectId, token: token.trim() }) };
|
|
1011
|
-
} catch (directError) {
|
|
1012
|
-
const serverPayload = await getGitHubProjectStatusFieldViaServer(context, projectId).catch(() => null);
|
|
1013
|
-
if (serverPayload && typeof serverPayload === "object" && !Array.isArray(serverPayload) && "field" in serverPayload) {
|
|
1014
|
-
return serverPayload;
|
|
1015
|
-
}
|
|
1016
|
-
return { ok: false, error: directError instanceof Error ? directError.message : String(directError) };
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
return getGitHubProjectStatusFieldViaServer(context, projectId);
|
|
1020
|
-
}
|
|
1021
|
-
var PROJECT_STATUS_PROMPTS = {
|
|
1022
|
-
running: "Running/In progress",
|
|
1023
|
-
prOpen: "PR open/review",
|
|
1024
|
-
ciFixing: "CI/review fixing",
|
|
1025
|
-
merging: "Merging",
|
|
1026
|
-
done: "Done",
|
|
1027
|
-
needsAttention: "Needs attention"
|
|
1028
|
-
};
|
|
1029
|
-
var DEFAULT_PROJECT_STATUS_OPTIONS = {
|
|
1030
|
-
running: "In Progress",
|
|
1031
|
-
prOpen: "In Review",
|
|
1032
|
-
ciFixing: "In Review",
|
|
1033
|
-
merging: "Merging",
|
|
1034
|
-
done: "Done",
|
|
1035
|
-
needsAttention: "Needs Attention"
|
|
1036
|
-
};
|
|
1037
|
-
async function promptManualProjectStatusMapping(prompts) {
|
|
1038
|
-
const statuses = {};
|
|
1039
|
-
for (const [key, label] of Object.entries(PROJECT_STATUS_PROMPTS)) {
|
|
1040
|
-
const defaultLabel = DEFAULT_PROJECT_STATUS_OPTIONS[key] ?? label;
|
|
1041
|
-
const value = await promptOptionalText(prompts, {
|
|
1042
|
-
message: `Project status option id/name for ${label} (blank for ${defaultLabel})`,
|
|
1043
|
-
placeholder: defaultLabel
|
|
1044
|
-
});
|
|
1045
|
-
statuses[key] = value || defaultLabel;
|
|
1046
|
-
}
|
|
1047
|
-
return statuses;
|
|
1048
|
-
}
|
|
1049
|
-
function projectScopeError(value) {
|
|
1050
|
-
const text = typeof value === "string" ? value : JSON.stringify(value ?? "");
|
|
1051
|
-
return /INSUFFICIENT_SCOPES|read:project|required scopes/i.test(text);
|
|
1052
|
-
}
|
|
1053
|
-
function optionName(option) {
|
|
1054
|
-
return String(option.name ?? option.label ?? option.id ?? "").trim();
|
|
1055
|
-
}
|
|
1056
|
-
function autoProjectStatusValue(options, key, label) {
|
|
1057
|
-
const candidates = [DEFAULT_PROJECT_STATUS_OPTIONS[key], label].filter((value) => Boolean(value)).map((value) => value.trim().toLowerCase());
|
|
1058
|
-
const match = options.find((option) => candidates.includes(optionName(option).toLowerCase()));
|
|
1059
|
-
if (!match)
|
|
1060
|
-
return null;
|
|
1061
|
-
return String(match.id ?? match.name);
|
|
1062
|
-
}
|
|
1063
|
-
async function promptGitHubProjectConfig(context, prompts, repoSlug, githubToken, refreshProjectToken) {
|
|
1064
|
-
const projectChoice = await promptSelect(prompts, {
|
|
1065
|
-
message: "GitHub Projects status sync",
|
|
1066
|
-
initialValue: "select",
|
|
1067
|
-
options: [
|
|
1068
|
-
{ value: "select", label: "Select accessible ProjectV2" },
|
|
1069
|
-
{ value: "off", label: "Off" },
|
|
1070
|
-
{ value: "manual", label: "Enter ProjectV2 ids manually" }
|
|
1071
|
-
]
|
|
1072
|
-
});
|
|
1073
|
-
if (projectChoice === "off")
|
|
1074
|
-
return { githubProject: "off" };
|
|
1075
|
-
if (projectChoice === "manual") {
|
|
1076
|
-
return {
|
|
1077
|
-
githubProject: await promptRequiredText(prompts, { message: "GitHub ProjectV2 id", placeholder: "PVT_..." }),
|
|
1078
|
-
githubProjectStatusField: await promptRequiredText(prompts, { message: "Project Status field id", placeholder: "field_status" }),
|
|
1079
|
-
githubProjectStatuses: await promptManualProjectStatusMapping(prompts)
|
|
1080
|
-
};
|
|
1081
|
-
}
|
|
1082
|
-
const owner = repoOwnerFromSlug(repoSlug);
|
|
1083
|
-
if (!owner)
|
|
1084
|
-
throw new CliError2(`Cannot derive GitHub owner from repo slug ${repoSlug}.`, 1);
|
|
1085
|
-
let activeToken = githubToken?.trim() || null;
|
|
1086
|
-
let projectsPayload = await listGitHubProjectsForInit(context, owner, activeToken).catch((error) => ({ ok: false, error: error instanceof Error ? error.message : String(error), projects: [] }));
|
|
1087
|
-
let projects = recordArray(projectsPayload, "projects");
|
|
1088
|
-
if (projects.length === 0 && projectScopeError(projectsPayload.error) && refreshProjectToken) {
|
|
1089
|
-
prompts.outro?.("GitHub token is missing read:project; refreshing gh auth scopes and retrying Projects.");
|
|
1090
|
-
const refreshedToken = refreshProjectToken();
|
|
1091
|
-
if (refreshedToken) {
|
|
1092
|
-
activeToken = refreshedToken;
|
|
1093
|
-
projectsPayload = await listGitHubProjectsForInit(context, owner, activeToken).catch((error) => ({ ok: false, error: error instanceof Error ? error.message : String(error), projects: [] }));
|
|
1094
|
-
projects = recordArray(projectsPayload, "projects");
|
|
1095
|
-
}
|
|
1096
|
-
}
|
|
1097
|
-
if (projects.length === 0) {
|
|
1098
|
-
const error = typeof projectsPayload.error === "string" ? ` (${String(projectsPayload.error).replace(/\s+/g, " ").slice(0, 240)})` : "";
|
|
1099
|
-
prompts.outro?.(`No accessible GitHub Projects were returned${error}; continuing with GitHub Projects status sync off.`);
|
|
1100
|
-
return { githubProject: "off", ...activeToken ? { githubToken: activeToken } : {} };
|
|
1101
|
-
}
|
|
1102
|
-
const selectedProjectId = await promptSelect(prompts, {
|
|
1103
|
-
message: "GitHub ProjectV2 project",
|
|
1104
|
-
options: [
|
|
1105
|
-
...projects.map((project) => ({
|
|
1106
|
-
value: String(project.id),
|
|
1107
|
-
label: `${String(project.title ?? "Untitled project")} (#${String(project.number ?? "?")})`,
|
|
1108
|
-
hint: typeof project.url === "string" ? project.url : undefined
|
|
1109
|
-
})),
|
|
1110
|
-
{ value: "manual", label: "Enter ProjectV2 id manually" }
|
|
1111
|
-
]
|
|
1112
|
-
});
|
|
1113
|
-
const projectId = selectedProjectId === "manual" ? await promptRequiredText(prompts, { message: "GitHub ProjectV2 id", placeholder: "PVT_..." }) : selectedProjectId;
|
|
1114
|
-
const fieldPayload = await getGitHubProjectStatusFieldForInit(context, projectId, activeToken).catch((error) => ({ ok: false, error: error instanceof Error ? error.message : String(error) }));
|
|
1115
|
-
const fieldPayloadRecord = fieldPayload && typeof fieldPayload === "object" && !Array.isArray(fieldPayload) ? fieldPayload : {};
|
|
1116
|
-
const rawField = fieldPayloadRecord.field;
|
|
1117
|
-
const field = rawField && typeof rawField === "object" && !Array.isArray(rawField) ? rawField : null;
|
|
1118
|
-
const fieldId = typeof field?.id === "string" && field.id.trim() ? field.id : await promptRequiredText(prompts, { message: "Project Status field id", placeholder: "field_status" });
|
|
1119
|
-
const options = Array.isArray(field?.options) ? field.options.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
|
|
1120
|
-
if (options.length === 0) {
|
|
1121
|
-
return {
|
|
1122
|
-
githubProject: projectId,
|
|
1123
|
-
githubProjectStatusField: fieldId,
|
|
1124
|
-
githubProjectStatuses: await promptManualProjectStatusMapping(prompts),
|
|
1125
|
-
...activeToken ? { githubToken: activeToken } : {}
|
|
1126
|
-
};
|
|
1127
|
-
}
|
|
1128
|
-
const statuses = {};
|
|
1129
|
-
for (const [key, label] of Object.entries(PROJECT_STATUS_PROMPTS)) {
|
|
1130
|
-
const auto = autoProjectStatusValue(options, key, label);
|
|
1131
|
-
statuses[key] = auto ?? await promptSelect(prompts, {
|
|
1132
|
-
message: `Project status option for ${label}`,
|
|
1133
|
-
options: options.map((option) => ({ value: String(option.id ?? option.name), label: optionName(option) }))
|
|
1134
|
-
});
|
|
1135
|
-
}
|
|
1136
|
-
return {
|
|
1137
|
-
githubProject: projectId,
|
|
1138
|
-
githubProjectStatusField: fieldId,
|
|
1139
|
-
githubProjectStatuses: Object.keys(statuses).length > 0 ? statuses : undefined,
|
|
1140
|
-
...activeToken ? { githubToken: activeToken } : {}
|
|
1141
|
-
};
|
|
1142
|
-
}
|
|
1143
|
-
function sleep2(ms) {
|
|
1144
|
-
return new Promise((resolve7) => setTimeout(resolve7, ms));
|
|
1145
|
-
}
|
|
1146
|
-
function positiveIntFromEnv(name, fallback) {
|
|
1147
|
-
const value = Number.parseInt(process.env[name] ?? "", 10);
|
|
1148
|
-
return Number.isFinite(value) && value >= 0 ? value : fallback;
|
|
1149
|
-
}
|
|
1150
|
-
function apiSessionTokenFrom(payload) {
|
|
1151
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
1152
|
-
return null;
|
|
1153
|
-
const token = payload.apiSessionToken;
|
|
1154
|
-
return typeof token === "string" && token.trim() ? token.trim() : null;
|
|
1155
|
-
}
|
|
1156
|
-
function cleanPayloadString(value) {
|
|
1157
|
-
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
1158
|
-
}
|
|
1159
|
-
function remoteGitHubAuthMetadata(payload) {
|
|
1160
|
-
if (!payload)
|
|
1161
|
-
return {};
|
|
1162
|
-
const userNamespace = payload.userNamespace && typeof payload.userNamespace === "object" && !Array.isArray(payload.userNamespace) ? payload.userNamespace : null;
|
|
1163
|
-
return {
|
|
1164
|
-
...cleanPayloadString(payload.login) ? { login: cleanPayloadString(payload.login) } : {},
|
|
1165
|
-
...cleanPayloadString(payload.userId) ? { userId: cleanPayloadString(payload.userId) } : {},
|
|
1166
|
-
...cleanPayloadString(userNamespace?.key) ? { userNamespaceKey: cleanPayloadString(userNamespace?.key) } : {},
|
|
1167
|
-
...cleanPayloadString(userNamespace?.root) ? { userNamespaceRoot: cleanPayloadString(userNamespace?.root) } : {},
|
|
1168
|
-
...cleanPayloadString(userNamespace?.checkoutBaseDir) ? { checkoutBaseDir: cleanPayloadString(userNamespace?.checkoutBaseDir) } : {},
|
|
1169
|
-
...cleanPayloadString(userNamespace?.snapshotBaseDir) ? { snapshotBaseDir: cleanPayloadString(userNamespace?.snapshotBaseDir) } : {}
|
|
1170
|
-
};
|
|
1171
|
-
}
|
|
1172
|
-
function writeRemoteGitHubAuthState(projectRoot, input) {
|
|
1173
|
-
writeFileSync2(resolve6(projectRoot, ".rig", "state", "github-auth.json"), `${JSON.stringify({
|
|
1174
|
-
authenticated: true,
|
|
1175
|
-
source: input.source,
|
|
1176
|
-
storedOnServer: true,
|
|
1177
|
-
selectedRepo: input.selectedRepo,
|
|
1178
|
-
...remoteGitHubAuthMetadata(input.authPayload ?? null),
|
|
1179
|
-
...input.apiSessionToken ? { apiSessionToken: input.apiSessionToken } : {},
|
|
1180
|
-
updatedAt: new Date().toISOString()
|
|
1181
|
-
}, null, 2)}
|
|
1182
|
-
`, "utf8");
|
|
1183
|
-
}
|
|
1184
|
-
async function pollDeviceAuthUntilComplete(context, pollId, firstPayload) {
|
|
1185
|
-
if (typeof pollId !== "string" || !pollId.trim())
|
|
1186
|
-
return null;
|
|
1187
|
-
const intervalSeconds = typeof firstPayload.interval === "number" && Number.isFinite(firstPayload.interval) && firstPayload.interval > 0 ? firstPayload.interval : 5;
|
|
1188
|
-
const timeoutMs = positiveIntFromEnv("RIG_DEVICE_AUTH_POLL_TIMEOUT_MS", 300000);
|
|
1189
|
-
const intervalMs = positiveIntFromEnv("RIG_DEVICE_AUTH_POLL_INTERVAL_MS", Math.max(1000, intervalSeconds * 1000));
|
|
1190
|
-
const deadline = Date.now() + timeoutMs;
|
|
1191
|
-
let last = null;
|
|
1192
|
-
do {
|
|
1193
|
-
const payload = await requestServerJson(context, "/api/github/auth/device/poll", {
|
|
1194
|
-
method: "POST",
|
|
1195
|
-
headers: { "content-type": "application/json" },
|
|
1196
|
-
body: JSON.stringify({ pollId })
|
|
1197
|
-
}).catch(() => null);
|
|
1198
|
-
last = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : null;
|
|
1199
|
-
const status = typeof last?.status === "string" ? last.status : null;
|
|
1200
|
-
if (status === "signed-in" || status === "expired" || status === "cancelled" || status === "failed") {
|
|
1201
|
-
return last;
|
|
1202
|
-
}
|
|
1203
|
-
if (timeoutMs <= 0)
|
|
1204
|
-
return last;
|
|
1205
|
-
await sleep2(intervalMs);
|
|
1206
|
-
} while (Date.now() < deadline);
|
|
1207
|
-
return last;
|
|
1208
|
-
}
|
|
1209
|
-
async function runControlPlaneInit(context, options) {
|
|
1210
|
-
const projectRoot = context.projectRoot;
|
|
1211
|
-
const detectedSlug = options.repoSlug ?? detectOriginRepoSlug(projectRoot);
|
|
1212
|
-
if (!detectedSlug) {
|
|
1213
|
-
throw new CliError2("Could not detect GitHub repo slug from origin. Pass --repo owner/repo.", 1);
|
|
1214
|
-
}
|
|
1215
|
-
const repo = parseRepoSlug(detectedSlug);
|
|
1216
|
-
const serverKind = options.server ?? "local";
|
|
1217
|
-
const connectionAlias = options.connectionAlias ?? (serverKind === "local" ? "local" : "remote");
|
|
1218
|
-
if (serverKind === "remote") {
|
|
1219
|
-
if (!options.remoteUrl)
|
|
1220
|
-
throw new CliError2("Missing --remote-url for --server remote.", 1);
|
|
1221
|
-
upsertGlobalConnection(connectionAlias, { kind: "remote", baseUrl: options.remoteUrl });
|
|
1222
|
-
}
|
|
1223
|
-
writeRepoConnection(projectRoot, {
|
|
1224
|
-
selected: connectionAlias,
|
|
1225
|
-
project: repo.slug,
|
|
1226
|
-
linkedAt: new Date().toISOString()
|
|
1227
|
-
});
|
|
1228
|
-
ensureRigPrivateDirs(projectRoot);
|
|
1229
|
-
ensureGitignoreEntries(projectRoot);
|
|
1230
|
-
const configTsPath = resolve6(projectRoot, "rig.config.ts");
|
|
1231
|
-
const configJsonPath = resolve6(projectRoot, "rig.config.json");
|
|
1232
|
-
const configExists = existsSync5(configTsPath) || existsSync5(configJsonPath);
|
|
1233
|
-
if (!options.privateStateOnly) {
|
|
1234
|
-
if (configExists && !options.repair) {
|
|
1235
|
-
if (context.outputMode !== "json")
|
|
1236
|
-
console.log("rig.config already exists; leaving it unchanged. Pass --repair to rewrite it.");
|
|
1237
|
-
} else {
|
|
1238
|
-
const source = applyGitHubProjectConfig(buildRigInitConfigSource({
|
|
1239
|
-
projectName: repo.slug,
|
|
1240
|
-
projectRepo: repo.slug,
|
|
1241
|
-
taskSource: { kind: "github-issues", owner: repo.owner, repo: repo.repo },
|
|
1242
|
-
useStandardPlugin: true
|
|
1243
|
-
}), options);
|
|
1244
|
-
writeFileSync2(configTsPath, source, "utf-8");
|
|
1245
|
-
}
|
|
1246
|
-
ensureRigConfigPackageDependencies(projectRoot);
|
|
1247
|
-
}
|
|
1248
|
-
writeFileSync2(resolve6(projectRoot, ".rig", "state", "project-link.json"), `${JSON.stringify({ repoSlug: repo.slug, connection: connectionAlias, linkedAt: new Date().toISOString() }, null, 2)}
|
|
1249
|
-
`, "utf8");
|
|
1250
|
-
const checkout = checkoutForInit(projectRoot, serverKind, options.remoteCheckout);
|
|
1251
|
-
let uploadedSnapshot = null;
|
|
1252
|
-
if (serverKind === "remote" && options.remoteCheckout?.kind === "uploaded-snapshot") {
|
|
1253
|
-
const archive = await createSnapshotUploadArchive(projectRoot);
|
|
1254
|
-
uploadedSnapshot = await uploadSnapshotArchiveViaServer(context, { repoSlug: repo.slug, archive });
|
|
1255
|
-
const uploadedCheckout = uploadedSnapshot.checkout;
|
|
1256
|
-
if (uploadedCheckout && typeof uploadedCheckout === "object" && !Array.isArray(uploadedCheckout)) {
|
|
1257
|
-
Object.assign(checkout, uploadedCheckout);
|
|
1258
|
-
}
|
|
1259
|
-
}
|
|
1260
|
-
let githubAuth = null;
|
|
1261
|
-
let deviceAuth = null;
|
|
1262
|
-
const authMethod = options.githubAuthMethod ?? (options.githubToken ? "token" : "skip");
|
|
1263
|
-
const remoteGhTokenWarning = serverKind === "remote" && authMethod === "gh" ? `This sends a GitHub token from this machine to ${options.remoteUrl ?? "the remote Rig server"}.` : null;
|
|
1264
|
-
if (remoteGhTokenWarning && !options.yes) {
|
|
1265
|
-
throw new CliError2(`${remoteGhTokenWarning} Re-run with --yes to confirm this explicit token transfer.`, 1);
|
|
1266
|
-
}
|
|
1267
|
-
const token = authMethod === "gh" && !options.githubToken ? readGhAuthToken() : options.githubToken?.trim();
|
|
1268
|
-
if (token) {
|
|
1269
|
-
githubAuth = await postGitHubTokenViaServer(context, token, { selectedRepo: repo.slug });
|
|
1270
|
-
const apiSessionToken = apiSessionTokenFrom(githubAuth);
|
|
1271
|
-
setGitHubBearerTokenForCurrentProcess(apiSessionToken ?? token, projectRoot);
|
|
1272
|
-
if (serverKind === "remote") {
|
|
1273
|
-
writeRemoteGitHubAuthState(projectRoot, {
|
|
1274
|
-
source: authMethod === "gh" ? "gh" : "init-token",
|
|
1275
|
-
selectedRepo: repo.slug,
|
|
1276
|
-
apiSessionToken,
|
|
1277
|
-
authPayload: githubAuth
|
|
1278
|
-
});
|
|
1279
|
-
}
|
|
1280
|
-
} else if (authMethod === "device") {
|
|
1281
|
-
const payload = await requestServerJson(context, "/api/github/auth/device/start", {
|
|
1282
|
-
method: "POST",
|
|
1283
|
-
headers: { "content-type": "application/json" },
|
|
1284
|
-
body: JSON.stringify({ repoSlug: repo.slug })
|
|
1285
|
-
});
|
|
1286
|
-
deviceAuth = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
1287
|
-
if (context.outputMode !== "json") {
|
|
1288
|
-
const verificationUri = String(deviceAuth.verificationUri ?? deviceAuth.verification_uri ?? deviceAuth.verification_uri_complete ?? "the verification URL returned by the server");
|
|
1289
|
-
const userCode = String(deviceAuth.userCode ?? deviceAuth.user_code ?? "the returned user code");
|
|
1290
|
-
console.log(`GitHub device flow: open ${verificationUri} and enter ${userCode}. Waiting for authorization...`);
|
|
1291
|
-
}
|
|
1292
|
-
const completed = await pollDeviceAuthUntilComplete(context, deviceAuth.pollId, deviceAuth);
|
|
1293
|
-
if (completed) {
|
|
1294
|
-
const apiSessionToken = apiSessionTokenFrom(completed);
|
|
1295
|
-
if (apiSessionToken) {
|
|
1296
|
-
setGitHubBearerTokenForCurrentProcess(apiSessionToken, projectRoot);
|
|
1297
|
-
if (serverKind === "remote") {
|
|
1298
|
-
writeRemoteGitHubAuthState(projectRoot, { source: "device", selectedRepo: repo.slug, apiSessionToken, authPayload: completed });
|
|
1299
|
-
}
|
|
1300
|
-
}
|
|
1301
|
-
deviceAuth = { ...deviceAuth, poll: completed, completed: completed.status === "signed-in" };
|
|
1302
|
-
}
|
|
1303
|
-
}
|
|
1304
|
-
let remoteCheckoutPreparation = null;
|
|
1305
|
-
if (serverKind === "remote" && options.remoteCheckout?.kind !== "uploaded-snapshot") {
|
|
1306
|
-
remoteCheckoutPreparation = await prepareRemoteCheckoutViaServer(context, {
|
|
1307
|
-
repoSlug: repo.slug,
|
|
1308
|
-
checkout,
|
|
1309
|
-
repoUrl: `https://github.com/${repo.slug}.git`
|
|
1310
|
-
});
|
|
1311
|
-
const preparedCheckout = remoteCheckoutPreparation.checkout;
|
|
1312
|
-
if (preparedCheckout && typeof preparedCheckout === "object" && !Array.isArray(preparedCheckout)) {
|
|
1313
|
-
Object.assign(checkout, preparedCheckout);
|
|
1314
|
-
}
|
|
1315
|
-
}
|
|
1316
|
-
const checkoutPath = typeof checkout.path === "string" ? checkout.path : null;
|
|
1317
|
-
if (serverKind === "remote" && checkoutPath && token) {
|
|
1318
|
-
githubAuth = await postGitHubTokenViaServer(context, token, { selectedRepo: repo.slug, projectRoot: checkoutPath });
|
|
1319
|
-
const apiSessionToken = apiSessionTokenFrom(githubAuth);
|
|
1320
|
-
setGitHubBearerTokenForCurrentProcess(apiSessionToken ?? token, projectRoot);
|
|
1321
|
-
writeRemoteGitHubAuthState(projectRoot, { source: authMethod === "gh" ? "gh" : "init-token", selectedRepo: repo.slug, apiSessionToken, authPayload: githubAuth });
|
|
1322
|
-
}
|
|
1323
|
-
const registered = await registerProjectViaServer(context, {
|
|
1324
|
-
repoSlug: repo.slug,
|
|
1325
|
-
checkout
|
|
1326
|
-
});
|
|
1327
|
-
const serverRootSwitch = serverKind === "remote" && checkoutPath ? await switchServerProjectRootViaServer(context, checkoutPath) : null;
|
|
1328
|
-
const activeProjectRegistration = serverRootSwitch ? await registerProjectViaServer(context, { repoSlug: repo.slug, checkout }) : null;
|
|
1329
|
-
const labelSetup = await ensureTaskLabelsViaServer(context).catch((error) => ({
|
|
1330
|
-
ok: false,
|
|
1331
|
-
ready: false,
|
|
1332
|
-
labelsReady: false,
|
|
1333
|
-
error: error instanceof Error ? error.message : String(error)
|
|
1334
|
-
}));
|
|
1335
|
-
const pi = serverKind === "remote" ? await ensureRemotePiRigInstalled({ requestJson: (pathname, init) => requestServerJson(context, pathname, init) }).catch((error) => ({
|
|
1336
|
-
remote: true,
|
|
1337
|
-
pi: { ok: false, label: "pi", hint: error instanceof Error ? error.message : String(error) },
|
|
1338
|
-
piRig: { ok: false, label: "pi-rig global extension", hint: "Remote server did not complete pi-rig installation." },
|
|
1339
|
-
extensionPath: "remote:~/.pi/agent/extensions/pi-rig"
|
|
1340
|
-
})) : await ensurePiRigInstalled({ projectRoot, homeDir: process.env.RIG_PI_HOME_DIR }).catch((error) => ({
|
|
1341
|
-
pi: { ok: false, label: "pi", hint: error instanceof Error ? error.message : String(error) },
|
|
1342
|
-
piRig: { ok: false, label: "pi-rig global extension", hint: "Local pi-rig installation failed." },
|
|
1343
|
-
extensionPath: null,
|
|
1344
|
-
installedPath: null
|
|
1345
|
-
}));
|
|
1346
|
-
const doctor = await runRigDoctorChecks({ projectRoot }).then((checks) => ({
|
|
1347
|
-
ok: countDoctorFailures(checks) === 0,
|
|
1348
|
-
failures: countDoctorFailures(checks),
|
|
1349
|
-
checks
|
|
1350
|
-
}));
|
|
1351
|
-
const details = {
|
|
1352
|
-
repoSlug: repo.slug,
|
|
1353
|
-
server: serverKind,
|
|
1354
|
-
connection: connectionAlias,
|
|
1355
|
-
githubProject: options.githubProject ?? "off",
|
|
1356
|
-
checkout,
|
|
1357
|
-
remoteCheckoutPreparation,
|
|
1358
|
-
uploadedSnapshot,
|
|
1359
|
-
projectRegistration: registered,
|
|
1360
|
-
activeProjectRegistration,
|
|
1361
|
-
serverRootSwitch,
|
|
1362
|
-
githubAuth,
|
|
1363
|
-
deviceAuth,
|
|
1364
|
-
githubAuthWarning: remoteGhTokenWarning,
|
|
1365
|
-
labelSetup,
|
|
1366
|
-
pi,
|
|
1367
|
-
doctor
|
|
1368
|
-
};
|
|
1369
|
-
if (context.outputMode === "json")
|
|
1370
|
-
console.log(JSON.stringify(details, null, 2));
|
|
1371
|
-
else
|
|
1372
|
-
console.log(`Initialized Rig control-plane project ${repo.slug}. Next: rig doctor && rig task list`);
|
|
1373
|
-
return { ok: true, group: "init", command: "init", details };
|
|
1374
|
-
}
|
|
1375
|
-
function parseInitOptions(args) {
|
|
1376
|
-
let rest = [...args];
|
|
1377
|
-
const yes = takeFlag(rest, "--yes");
|
|
1378
|
-
rest = yes.rest;
|
|
1379
|
-
const repair = takeFlag(rest, "--repair");
|
|
1380
|
-
rest = repair.rest;
|
|
1381
|
-
const privateStateOnly = takeFlag(rest, "--private-state-only");
|
|
1382
|
-
rest = privateStateOnly.rest;
|
|
1383
|
-
const server = takeOption(rest, "--server");
|
|
1384
|
-
rest = server.rest;
|
|
1385
|
-
const remoteUrl = takeOption(rest, "--remote-url");
|
|
1386
|
-
rest = remoteUrl.rest;
|
|
1387
|
-
const connectionAlias = takeOption(rest, "--connection");
|
|
1388
|
-
rest = connectionAlias.rest;
|
|
1389
|
-
const repoSlug = takeOption(rest, "--repo");
|
|
1390
|
-
rest = repoSlug.rest;
|
|
1391
|
-
const githubToken = takeOption(rest, "--github-token");
|
|
1392
|
-
rest = githubToken.rest;
|
|
1393
|
-
const githubProject = takeOption(rest, "--github-project");
|
|
1394
|
-
rest = githubProject.rest;
|
|
1395
|
-
const githubProjectStatusField = takeOption(rest, "--github-project-status-field");
|
|
1396
|
-
rest = githubProjectStatusField.rest;
|
|
1397
|
-
const githubAuth = takeOption(rest, "--github-auth");
|
|
1398
|
-
rest = githubAuth.rest;
|
|
1399
|
-
const remoteCheckout = takeOption(rest, "--remote-checkout");
|
|
1400
|
-
rest = remoteCheckout.rest;
|
|
1401
|
-
const existingPath = takeOption(rest, "--existing-path");
|
|
1402
|
-
rest = existingPath.rest;
|
|
1403
|
-
const ref = takeOption(rest, "--ref");
|
|
1404
|
-
rest = ref.rest;
|
|
1405
|
-
const options = {
|
|
1406
|
-
yes: yes.value,
|
|
1407
|
-
repair: repair.value,
|
|
1408
|
-
privateStateOnly: privateStateOnly.value,
|
|
1409
|
-
server: server.value === "remote" ? "remote" : server.value === "local" ? "local" : undefined,
|
|
1410
|
-
remoteUrl: remoteUrl.value,
|
|
1411
|
-
connectionAlias: connectionAlias.value,
|
|
1412
|
-
repoSlug: repoSlug.value,
|
|
1413
|
-
githubToken: githubToken.value,
|
|
1414
|
-
githubAuthMethod: githubAuth.value,
|
|
1415
|
-
githubProject: githubProject.value,
|
|
1416
|
-
githubProjectStatusField: githubProjectStatusField.value
|
|
1417
|
-
};
|
|
1418
|
-
if (server.value && options.server === undefined) {
|
|
1419
|
-
throw new CliError2("--server must be local or remote.", 1);
|
|
1420
|
-
}
|
|
1421
|
-
if (githubAuth.value && !["gh", "token", "device", "skip"].includes(githubAuth.value)) {
|
|
1422
|
-
throw new CliError2("--github-auth must be gh, token, device, or skip.", 1);
|
|
1423
|
-
}
|
|
1424
|
-
if (remoteCheckout.value) {
|
|
1425
|
-
if (remoteCheckout.value === "managed-clone")
|
|
1426
|
-
options.remoteCheckout = { kind: "managed-clone" };
|
|
1427
|
-
else if (remoteCheckout.value === "current-ref")
|
|
1428
|
-
options.remoteCheckout = { kind: "current-ref", ref: ref.value };
|
|
1429
|
-
else if (remoteCheckout.value === "uploaded-snapshot")
|
|
1430
|
-
options.remoteCheckout = { kind: "uploaded-snapshot" };
|
|
1431
|
-
else if (remoteCheckout.value === "existing-path") {
|
|
1432
|
-
if (!existingPath.value)
|
|
1433
|
-
throw new CliError2("--remote-checkout existing-path requires --existing-path <path>.", 1);
|
|
1434
|
-
options.remoteCheckout = { kind: "existing-path", path: existingPath.value };
|
|
1435
|
-
} else {
|
|
1436
|
-
throw new CliError2("--remote-checkout must be managed-clone, current-ref, uploaded-snapshot, or existing-path.", 1);
|
|
1437
|
-
}
|
|
1438
|
-
}
|
|
1439
|
-
return { options, rest };
|
|
1440
|
-
}
|
|
1441
|
-
async function runInteractiveControlPlaneInit(context, prompts) {
|
|
1442
|
-
prompts.intro?.("Initialize a Rig control-plane project");
|
|
1443
|
-
const projectRoot = context.projectRoot;
|
|
1444
|
-
const existingConfig = existsSync5(resolve6(projectRoot, "rig.config.ts")) || existsSync5(resolve6(projectRoot, "rig.config.json"));
|
|
1445
|
-
let repair = false;
|
|
1446
|
-
let privateStateOnly = false;
|
|
1447
|
-
if (existingConfig) {
|
|
1448
|
-
const action = await promptSelect(prompts, {
|
|
1449
|
-
message: "rig.config already exists. What should rig init do?",
|
|
1450
|
-
options: [
|
|
1451
|
-
{ value: "repair", label: "Verify/repair generated config" },
|
|
1452
|
-
{ value: "reconfigure", label: "Reconfigure project and rewrite config" },
|
|
1453
|
-
{ value: "private-state-only", label: "Leave config unchanged; update private connection/auth state only" },
|
|
1454
|
-
{ value: "cancel", label: "Cancel" }
|
|
1455
|
-
]
|
|
1456
|
-
});
|
|
1457
|
-
if (action === "cancel") {
|
|
1458
|
-
prompts.cancel?.("Init cancelled.");
|
|
1459
|
-
return { ok: false, group: "init", command: "init", details: { cancelled: true } };
|
|
1460
|
-
}
|
|
1461
|
-
repair = action === "repair" || action === "reconfigure";
|
|
1462
|
-
privateStateOnly = action === "private-state-only";
|
|
1463
|
-
}
|
|
1464
|
-
const detectedRepo = detectOriginRepoSlug(projectRoot) ?? undefined;
|
|
1465
|
-
const repoSlug = await promptRequiredText(prompts, {
|
|
1466
|
-
message: "GitHub repo slug",
|
|
1467
|
-
placeholder: "owner/repo",
|
|
1468
|
-
defaultValue: detectedRepo
|
|
1469
|
-
});
|
|
1470
|
-
const serverChoice = await promptSelect(prompts, {
|
|
1471
|
-
message: "Rig server",
|
|
1472
|
-
initialValue: "remote",
|
|
1473
|
-
options: [
|
|
1474
|
-
{ value: "remote", label: "Remote server", hint: "connect to an HTTPS Rig server" },
|
|
1475
|
-
{ value: "local", label: "Local server", hint: "run on this machine" }
|
|
1476
|
-
]
|
|
1477
|
-
});
|
|
1478
|
-
const remoteUrl = serverChoice === "remote" ? await promptRequiredText(prompts, { message: "Remote Rig server URL", placeholder: DEFAULT_REMOTE_RIG_URL, initialValue: DEFAULT_REMOTE_RIG_URL }) : undefined;
|
|
1479
|
-
let remoteCheckout;
|
|
1480
|
-
if (serverChoice === "remote") {
|
|
1481
|
-
const checkout = await promptSelect(prompts, {
|
|
1482
|
-
message: "Remote checkout strategy",
|
|
1483
|
-
options: [
|
|
1484
|
-
{ value: "managed-clone", label: "Server-managed clone (recommended)" },
|
|
1485
|
-
{ value: "current-ref", label: "Clone current branch/ref" },
|
|
1486
|
-
{ value: "uploaded-snapshot", label: "Upload current working-tree snapshot" },
|
|
1487
|
-
{ value: "existing-path", label: "Use existing server path" }
|
|
1488
|
-
]
|
|
1489
|
-
});
|
|
1490
|
-
if (checkout === "existing-path") {
|
|
1491
|
-
remoteCheckout = { kind: "existing-path", path: await promptRequiredText(prompts, { message: "Existing server checkout path", placeholder: "/srv/rig/checkouts/repo" }) };
|
|
1492
|
-
} else if (checkout === "current-ref") {
|
|
1493
|
-
remoteCheckout = { kind: "current-ref", ref: await promptOptionalText(prompts, { message: "Branch/ref to clone (blank for current HEAD)", placeholder: "main" }) || undefined };
|
|
1494
|
-
} else if (checkout === "uploaded-snapshot") {
|
|
1495
|
-
remoteCheckout = { kind: "uploaded-snapshot" };
|
|
1496
|
-
} else {
|
|
1497
|
-
remoteCheckout = { kind: "managed-clone" };
|
|
1498
|
-
}
|
|
1499
|
-
}
|
|
1500
|
-
const detectedGhLogin = detectGhLogin();
|
|
1501
|
-
const authMethod = await promptSelect(prompts, {
|
|
1502
|
-
message: `GitHub auth method${detectedGhLogin ? ` (detected gh login: ${detectedGhLogin})` : ""}`,
|
|
1503
|
-
options: [
|
|
1504
|
-
{ value: "gh", label: "Import token from gh auth token", hint: serverChoice === "local" ? "recommended for local" : "sends this machine's token to the remote server" },
|
|
1505
|
-
{ value: "device", label: "Start server GitHub device flow", hint: serverChoice === "remote" ? "recommended for remote" : undefined },
|
|
1506
|
-
{ value: "token", label: "Paste token" },
|
|
1507
|
-
{ value: "skip", label: "Skip for now" }
|
|
1508
|
-
]
|
|
1509
|
-
});
|
|
1510
|
-
let remoteGhTokenConfirmed = false;
|
|
1511
|
-
if (serverChoice === "remote" && authMethod === "gh") {
|
|
1512
|
-
if (!prompts.confirm)
|
|
1513
|
-
throw new CliError2("Remote gh-token import requires explicit confirmation.", 1);
|
|
1514
|
-
const confirmed = await prompts.confirm({
|
|
1515
|
-
message: `This sends a GitHub token from this machine to ${remoteUrl}. Continue?`,
|
|
1516
|
-
initialValue: true
|
|
1517
|
-
});
|
|
1518
|
-
if (prompts.isCancel(confirmed) || confirmed !== true) {
|
|
1519
|
-
throw new CliError2("Remote gh-token import cancelled.", 1);
|
|
1520
|
-
}
|
|
1521
|
-
remoteGhTokenConfirmed = true;
|
|
1522
|
-
}
|
|
1523
|
-
const githubToken = authMethod === "token" ? await promptRequiredText(prompts, { message: "GitHub token", placeholder: "ghp_..." }) : authMethod === "gh" ? readGhAuthToken() : undefined;
|
|
1524
|
-
const projectConfig = await promptGitHubProjectConfig(context, prompts, repoSlug, githubToken, authMethod === "gh" ? refreshGhProjectScopesAndReadToken : undefined);
|
|
1525
|
-
const effectiveGithubToken = projectConfig.githubToken ?? githubToken;
|
|
1526
|
-
const result = await runControlPlaneInit(context, {
|
|
1527
|
-
server: serverChoice,
|
|
1528
|
-
remoteUrl,
|
|
1529
|
-
repoSlug,
|
|
1530
|
-
githubToken: effectiveGithubToken,
|
|
1531
|
-
githubAuthMethod: authMethod,
|
|
1532
|
-
githubProject: projectConfig.githubProject,
|
|
1533
|
-
githubProjectStatusField: projectConfig.githubProjectStatusField,
|
|
1534
|
-
githubProjectStatuses: projectConfig.githubProjectStatuses,
|
|
1535
|
-
remoteCheckout,
|
|
1536
|
-
repair,
|
|
1537
|
-
privateStateOnly,
|
|
1538
|
-
yes: remoteGhTokenConfirmed || undefined
|
|
1539
|
-
});
|
|
1540
|
-
const details = result.details && typeof result.details === "object" && !Array.isArray(result.details) ? result.details : {};
|
|
1541
|
-
const deviceAuth = details.deviceAuth && typeof details.deviceAuth === "object" && !Array.isArray(details.deviceAuth) ? details.deviceAuth : null;
|
|
1542
|
-
const deviceMessage = deviceAuth ? ` GitHub device flow: open ${String(deviceAuth.verificationUri ?? deviceAuth.verification_uri ?? deviceAuth.verification_uri_complete ?? "the verification URL returned by the server")} and enter ${String(deviceAuth.userCode ?? deviceAuth.user_code ?? "the returned user code")}.` : "";
|
|
1543
|
-
prompts.outro?.(`Rig project initialized.${deviceMessage} Next: rig doctor && rig task list`);
|
|
1544
|
-
return result;
|
|
1545
|
-
}
|
|
1546
|
-
async function executeInit(context, args) {
|
|
1547
|
-
const parsed = parseInitOptions(args);
|
|
1548
|
-
if (parsed.options.yes || parsed.options.server || parsed.options.repoSlug || parsed.options.githubToken || parsed.options.privateStateOnly || parsed.options.repair || parsed.options.githubAuthMethod || parsed.options.remoteCheckout) {
|
|
1549
|
-
if (parsed.rest.length > 0)
|
|
1550
|
-
throw new CliError2(`Unexpected arguments: ${parsed.rest.join(" ")}
|
|
1551
|
-
Usage: rig init [--server local|remote] [--remote-url <url>] [--repo owner/repo] [--github-auth gh|token|device|skip] [--github-token <token>] [--github-project off|<project-id>] [--remote-checkout managed-clone|current-ref|uploaded-snapshot|existing-path] [--yes]`, 1);
|
|
1552
|
-
return runControlPlaneInit(context, parsed.options);
|
|
1553
|
-
}
|
|
1554
|
-
if (parsed.rest.length > 0)
|
|
1555
|
-
throw new CliError2(`Unexpected arguments: ${parsed.rest.join(" ")}
|
|
1556
|
-
Usage: rig init`, 1);
|
|
1557
|
-
return runInteractiveControlPlaneInit(context, await loadClackPrompts());
|
|
1558
|
-
}
|
|
1559
|
-
export {
|
|
1560
|
-
runInteractiveControlPlaneInit,
|
|
1561
|
-
executeInit,
|
|
1562
|
-
buildRigInitConfigSource
|
|
1563
|
-
};
|