@codetelemetry/connect 0.1.5 → 0.2.0

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/dist/bin.js CHANGED
@@ -1,3 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import { run } from "./cli.js";
3
- process.exitCode = await run(process.argv.slice(2));
3
+ import { scrub } from "./keys.js";
4
+ try {
5
+ process.exitCode = await run(process.argv.slice(2));
6
+ }
7
+ catch (error) {
8
+ process.stderr.write(scrub(`CodeTelemetry: ${String(error.message)}\n`));
9
+ process.exitCode = 1;
10
+ }
@@ -0,0 +1,28 @@
1
+ import { type FetchLike } from "./otlp.ts";
2
+ export type BootstrapOptions = {
3
+ name: string;
4
+ repositoryPath?: string;
5
+ organizationName?: string;
6
+ organizationId?: string;
7
+ client?: "claude" | "codex";
8
+ configPath?: string;
9
+ features?: string;
10
+ checks?: Record<string, unknown>[];
11
+ publish?: boolean;
12
+ githubRepository?: string;
13
+ terraform?: boolean;
14
+ enrich?: boolean;
15
+ repositoryObservation?: boolean;
16
+ reauthorize?: boolean;
17
+ };
18
+ export declare function bootstrapWorkspace(options: BootstrapOptions, environment?: {
19
+ apiBase?: string;
20
+ fetchImpl?: FetchLike;
21
+ timeoutMs?: number;
22
+ }): Promise<{
23
+ nextAction?: string | undefined;
24
+ ok: boolean;
25
+ status: string;
26
+ workspace: string;
27
+ steps: Record<string, string>;
28
+ }>;
@@ -0,0 +1,585 @@
1
+ import { prepareGitHubWorkflow, verifyGitHubSetup } from "./bootstrapGitHub.js";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
+ import { bindWorkspace, bindingOf, codexWorkspaceProfilePath, writeCodexWorkspaceProfile, WORKSPACE_MCP_PACKAGE, contextPath, workspaceLock, loadWorkspace, readWorkspaceFile, saveWorkspace, workspaceHome, workspaceName, workspaceOrigin, writeWorkspaceFile, } from "./workspaces.js";
7
+ import { resolveEndpoints } from "./config.js";
8
+ import { verifyScope, confirmLanded } from "./connectivity.js";
9
+ import { pollOnce } from "./deviceClient.js";
10
+ import { CLIENTS } from "./clients.js";
11
+ import { sendTestEvent } from "./otlp.js";
12
+ import { scrub, keyHash } from "./keys.js";
13
+ import { writeGraderArtifact } from "./graderArtifact.js";
14
+ async function request(base, route, body, fetchImpl, deadline, key, scope) {
15
+ const remaining = deadline - Date.now();
16
+ if (remaining <= 0)
17
+ throw new Error("Bootstrap time limit reached; resume this workspace.");
18
+ const response = await fetchImpl(base + route, {
19
+ method: "POST",
20
+ redirect: "error",
21
+ signal: AbortSignal.timeout(Math.min(8_000, remaining)),
22
+ headers: {
23
+ "content-type": "application/json",
24
+ ...(key ? { authorization: `Bearer ${key}` } : {}),
25
+ ...(scope ? { "x-codetelemetry-workspace": JSON.stringify(scope) } : {}),
26
+ },
27
+ body: JSON.stringify(body),
28
+ });
29
+ const reader = response.body?.getReader();
30
+ let size = 0;
31
+ const chunks = [];
32
+ if (reader)
33
+ try {
34
+ while (true) {
35
+ const { done, value } = await reader.read();
36
+ if (done)
37
+ break;
38
+ size += value.length;
39
+ if (size > 65536)
40
+ throw new Error("Bootstrap response exceeds 64 KiB.");
41
+ chunks.push(value);
42
+ }
43
+ }
44
+ finally {
45
+ await reader.cancel();
46
+ }
47
+ let result;
48
+ try {
49
+ result = JSON.parse(Buffer.concat(chunks).toString("utf8"));
50
+ }
51
+ catch {
52
+ throw new Error("Invalid bootstrap response; resume after checking the service.");
53
+ }
54
+ if (!response.ok || result.ok === false)
55
+ throw new Error(`Bootstrap request failed (HTTP ${response.status}${typeof result.error === "string" && /^[a-z_]{1,64}$/.test(result.error) ? `, ${result.error}` : ""}); resume after resolving it.`);
56
+ return result;
57
+ }
58
+ function validatePlan(options) {
59
+ workspaceName(options.name);
60
+ const allowed = new Set([
61
+ "name",
62
+ "repositoryPath",
63
+ "organizationName",
64
+ "organizationId",
65
+ "client",
66
+ "configPath",
67
+ "features",
68
+ "checks",
69
+ "publish",
70
+ "githubRepository",
71
+ "terraform",
72
+ "enrich",
73
+ "repositoryObservation",
74
+ ]);
75
+ if (Object.keys(options).some((key) => !allowed.has(key)))
76
+ throw new Error("Unknown bootstrap option.");
77
+ for (const key of [
78
+ "publish",
79
+ "terraform",
80
+ "enrich",
81
+ "repositoryObservation",
82
+ ])
83
+ if (options[key] !== undefined && typeof options[key] !== "boolean")
84
+ throw new Error(`${key} must be a boolean.`);
85
+ if (options.organizationName !== undefined &&
86
+ (typeof options.organizationName !== "string" ||
87
+ !options.organizationName.trim() ||
88
+ options.organizationName.length > 60))
89
+ throw new Error("New organization name must contain 1–60 characters.");
90
+ if (options.organizationId !== undefined &&
91
+ !/^tm_[A-Za-z0-9_-]{1,128}$/.test(options.organizationId))
92
+ throw new Error("Invalid organization ID.");
93
+ if (options.organizationName && options.organizationId)
94
+ throw new Error("Choose an existing organization ID or a new organization name.");
95
+ if (options.client !== undefined &&
96
+ !["claude", "codex"].includes(options.client))
97
+ throw new Error("Bootstrap supports Claude Code and Codex.");
98
+ if (options.githubRepository !== undefined &&
99
+ !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(options.githubRepository))
100
+ throw new Error("GitHub repository must be owner/name.");
101
+ if (options.features !== undefined &&
102
+ (typeof options.features !== "string" ||
103
+ options.features.length > 4000 ||
104
+ !options.features.trim()))
105
+ throw new Error("Describe Grader features in 1–4000 characters.");
106
+ if (options.checks !== undefined &&
107
+ (!Array.isArray(options.checks) ||
108
+ options.checks.length > 30 ||
109
+ options.checks.some((c) => !c ||
110
+ typeof c !== "object" ||
111
+ Array.isArray(c) ||
112
+ typeof c.id !== "string")))
113
+ throw new Error("Select at most 30 Grader checks with IDs.");
114
+ if (options.checks?.length && !options.features)
115
+ throw new Error("Describe the requested Grader features.");
116
+ if ((options.publish || options.terraform) && !options.checks?.length)
117
+ throw new Error("Select the checks to publish.");
118
+ const encoded = JSON.stringify(options);
119
+ if (/gh[pousr]_[A-Za-z0-9]{20,}|npm_[A-Za-z0-9]{20,}|(?:AKIA|ASIA)[A-Z0-9]{16}|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|eyJ[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/.test(encoded))
120
+ throw new Error("Remove credentials from the bootstrap plan.");
121
+ if (encoded !== scrub(encoded))
122
+ throw new Error("Remove credentials from the bootstrap plan.");
123
+ const repositoryPath = fs.realpathSync(options.repositoryPath ?? process.cwd());
124
+ if (!fs.statSync(repositoryPath).isDirectory() ||
125
+ repositoryPath === os.homedir() ||
126
+ repositoryPath === path.parse(repositoryPath).root)
127
+ throw new Error("Choose a repository directory before authorizing setup.");
128
+ const client = options.client ?? "codex";
129
+ const configPath = options.configPath
130
+ ? path.resolve(options.configPath)
131
+ : client === "codex"
132
+ ? codexWorkspaceProfilePath(options.name)
133
+ : path.join(repositoryPath, ".claude", "settings.local.json");
134
+ const allowedConfig = client === "codex"
135
+ ? codexWorkspaceProfilePath(options.name)
136
+ : path.join(repositoryPath, ".claude", "settings.local.json");
137
+ if (configPath !== allowedConfig)
138
+ throw new Error("Bootstrap writes only this workspace's named Codex profile or repository-local Claude settings.");
139
+ return { ...options, repositoryPath, client, configPath };
140
+ }
141
+ export async function bootstrapWorkspace(options, environment = {}) {
142
+ if (options.reauthorize !== undefined &&
143
+ typeof options.reauthorize !== "boolean")
144
+ throw new Error("reauthorize must be a boolean.");
145
+ const reauthorize = options.reauthorize === true;
146
+ options = { ...options };
147
+ delete options.reauthorize;
148
+ const name = workspaceName(options.name), stateFile = path.join(workspaceHome(), `${name}.bootstrap.json`);
149
+ const savedOrigin = fs.existsSync(stateFile)
150
+ ? readWorkspaceFile(stateFile).apiBase
151
+ : fs.existsSync(contextPath(name))
152
+ ? loadWorkspace(name).apiBase
153
+ : undefined;
154
+ const apiBase = workspaceOrigin(environment.apiBase ??
155
+ process.env.CODETELEMETRY_API_BASE ??
156
+ savedOrigin ??
157
+ resolveEndpoints().apiBase);
158
+ const release = workspaceLock(name), deadline = Date.now() +
159
+ Math.min(50_000, Math.max(1, environment.timeoutMs ?? 45_000));
160
+ const fetchImpl = environment.fetchImpl ?? fetch;
161
+ try {
162
+ let state;
163
+ if (fs.existsSync(stateFile)) {
164
+ state = readWorkspaceFile(stateFile);
165
+ if (state.version !== 1 ||
166
+ !Number.isFinite(state.startedAt) ||
167
+ state.name !== name ||
168
+ state.plan?.name !== name ||
169
+ typeof state.operationId !== "string" ||
170
+ !/^[A-Za-z0-9_-]{16,128}$/.test(state.operationId) ||
171
+ state.apiBase !== apiBase ||
172
+ !state.plan ||
173
+ !state.steps)
174
+ throw new Error("Unsupported or mismatched bootstrap checkpoint.");
175
+ const validated = validatePlan(state.plan);
176
+ if (JSON.stringify(validated) !== JSON.stringify(state.plan))
177
+ throw new Error("Bootstrap repository or configuration path changed.");
178
+ for (const [key, value] of Object.entries(options))
179
+ if (key !== "name" &&
180
+ JSON.stringify(value) !== JSON.stringify(state.plan[key]))
181
+ throw new Error("Bootstrap plan changed; use another context name for a different setup.");
182
+ }
183
+ else {
184
+ if (options.organizationName && fs.existsSync(contextPath(name)))
185
+ throw new Error("This context already exists. Omit organizationName to configure it, or choose a new context name to create another organization.");
186
+ const plan = validatePlan(options);
187
+ state = {
188
+ version: 1,
189
+ name,
190
+ startedAt: Date.now(),
191
+ operationId: randomUUID(),
192
+ apiBase,
193
+ plan,
194
+ steps: {},
195
+ };
196
+ writeWorkspaceFile(stateFile, state);
197
+ }
198
+ const checkpoint = () => writeWorkspaceFile(stateFile, state);
199
+ const result = (status, nextAction, extra = {}) => ({
200
+ ok: status === "ready",
201
+ status,
202
+ workspace: name,
203
+ steps: state.steps,
204
+ ...(nextAction ? { nextAction } : {}),
205
+ ...extra,
206
+ });
207
+ let context = fs.existsSync(contextPath(name))
208
+ ? loadWorkspace(name)
209
+ : null;
210
+ if (context &&
211
+ (context.apiBase !== apiBase ||
212
+ (state.plan.organizationId &&
213
+ context.scope.teamId !== state.plan.organizationId)))
214
+ throw new Error("Bootstrap and saved context scopes disagree.");
215
+ if (reauthorize) {
216
+ state.reconnect = true;
217
+ delete state.pending;
218
+ checkpoint();
219
+ }
220
+ const priorContext = context;
221
+ if (state.reconnect)
222
+ context = null;
223
+ if (!context) {
224
+ if (!state.pending || state.pending.expiresAt <= Date.now()) {
225
+ const expected = priorContext?.scope ??
226
+ (state.plan.organizationId
227
+ ? { teamId: state.plan.organizationId }
228
+ : undefined);
229
+ if (!state.plan.organizationName && !expected)
230
+ throw new Error("Choose an organizationName or organizationId when bootstrapping a new context.");
231
+ const code = await request(apiBase, state.plan.organizationName && !priorContext
232
+ ? "/api/device/code/bootstrap-v1"
233
+ : "/api/device/code/scope-v1", state.plan.organizationName && !priorContext
234
+ ? {
235
+ organizationName: state.plan.organizationName,
236
+ operationId: state.operationId,
237
+ }
238
+ : { expected }, fetchImpl, deadline);
239
+ if (typeof code.device_code !== "string" ||
240
+ typeof code.user_code !== "string" ||
241
+ !Number.isFinite(code.expires_in) ||
242
+ code.expires_in <= 0 ||
243
+ code.expires_in > 900 ||
244
+ !Number.isFinite(code.interval) ||
245
+ code.interval < 1 ||
246
+ code.interval > 60)
247
+ throw new Error("Invalid bootstrap authorization response.");
248
+ const uri = new URL("/activate", apiBase);
249
+ uri.searchParams.set("code", code.user_code);
250
+ if (state.plan.organizationName && !priorContext) {
251
+ uri.searchParams.set("bootstrap", "1");
252
+ uri.searchParams.set("organizationName", state.plan.organizationName);
253
+ }
254
+ else {
255
+ uri.searchParams.set("scope", "v1");
256
+ const team = priorContext?.scope.teamId ?? state.plan.organizationId;
257
+ if (team)
258
+ uri.searchParams.set("teamId", team);
259
+ }
260
+ state.pending = {
261
+ deviceCode: code.device_code,
262
+ userCode: code.user_code,
263
+ uri: uri.href,
264
+ expiresAt: Date.now() + code.expires_in * 1000,
265
+ interval: code.interval,
266
+ nextPoll: Date.now() + code.interval * 1000,
267
+ };
268
+ checkpoint();
269
+ return result("authorization_required", "Approve the displayed account and organization in the browser, then resume bootstrap_workspace with this name.", { authorizationUrl: uri.href, userCode: code.user_code });
270
+ }
271
+ if (state.pending.nextPoll > Date.now())
272
+ return result("authorization_pending", "Resume after the authorization polling interval.", {
273
+ authorizationUrl: state.pending.uri,
274
+ retryAfterMs: state.pending.nextPoll - Date.now(),
275
+ });
276
+ state.pending.nextPoll = Date.now() + state.pending.interval * 1000;
277
+ checkpoint();
278
+ const authorized = await pollOnce(resolveEndpoints({ apiBase }), state.pending.deviceCode, fetchImpl, Math.min(8000, Math.max(1, deadline - Date.now())), { scopeFenced: !!state.plan.organizationId || !!priorContext });
279
+ if (authorized.status === "pending")
280
+ return result("authorization_pending", "Finish browser approval, then resume.", { authorizationUrl: state.pending.uri });
281
+ if (authorized.status === "error") {
282
+ delete state.pending;
283
+ checkpoint();
284
+ return result("authorization_expired", "Resume to start a new authorization for the same operation.");
285
+ }
286
+ if (!authorized.scope ||
287
+ (!priorContext && !authorized.scope.teamId) ||
288
+ (state.plan.organizationId &&
289
+ state.plan.organizationId !== authorized.scope.teamId))
290
+ throw new Error("Device approval did not attest the requested organization.");
291
+ context = {
292
+ version: 1,
293
+ name,
294
+ apiBase,
295
+ scope: authorized.scope,
296
+ ingestKey: authorized.apiKey,
297
+ ingestEndpoint: authorized.ingestEndpoint,
298
+ };
299
+ if (priorContext &&
300
+ (context.scope.tenantId !== priorContext.scope.tenantId ||
301
+ context.scope.teamId !== priorContext.scope.teamId ||
302
+ context.scope.billingAccountId !==
303
+ priorContext.scope.billingAccountId))
304
+ throw new Error("Reauthorization changed the workspace identity; the new credential was not kept.");
305
+ delete state.reconnect;
306
+ saveWorkspace(context);
307
+ delete state.pending;
308
+ state.steps.authentication = "verified";
309
+ checkpoint();
310
+ }
311
+ const endpoints = resolveEndpoints({
312
+ apiBase,
313
+ ingestEndpoint: context.ingestEndpoint,
314
+ });
315
+ const verified = await verifyScope({
316
+ key: context.ingestKey,
317
+ connectivityUrl: endpoints.connectivityUrl,
318
+ expected: context.scope,
319
+ fetchImpl,
320
+ timeoutMs: Math.min(8000, Math.max(1, deadline - Date.now())),
321
+ });
322
+ if (!["scope_verified", "budget_exhausted"].includes(verified.state) ||
323
+ !verified.scope ||
324
+ verified.scope.tenantId !== context.scope.tenantId ||
325
+ verified.scope.teamId !== context.scope.teamId ||
326
+ verified.scope.billingAccountId !== context.scope.billingAccountId)
327
+ return result("credential_unavailable", `Workspace verification returned ${verified.state}; reconnect this context before continuing.`);
328
+ state.steps.scope = "verified";
329
+ delete state.steps.funding;
330
+ delete state.steps.telemetry;
331
+ bindWorkspace(state.plan.repositoryPath, context);
332
+ state.steps.repository = "bound";
333
+ checkpoint();
334
+ if (verified.state === "budget_exhausted")
335
+ return result("funding_required", "Fund this organization's billing pool, then resume; the context and authorization are saved.", {
336
+ billingUrl: context.scope.teamId
337
+ ? `${apiBase}/app/teams/${context.scope.teamId}`
338
+ : `${apiBase}/app`,
339
+ scope: context.scope,
340
+ });
341
+ state.steps.funding = "available";
342
+ const ignoreFile = path.join(state.plan.repositoryPath, ".gitignore");
343
+ let ignored = "";
344
+ if (fs.existsSync(ignoreFile)) {
345
+ const st = fs.lstatSync(ignoreFile);
346
+ if (!st.isFile() || st.isSymbolicLink() || st.size > 65536)
347
+ throw new Error("Repository .gitignore must be a regular file within 64 KiB.");
348
+ ignored = fs.readFileSync(ignoreFile, "utf8");
349
+ }
350
+ const ignoreEntry = state.plan.client === "codex"
351
+ ? "/.codex/"
352
+ : "/.claude/settings.local.json";
353
+ if (!ignored.split(/\r?\n/).includes(ignoreEntry)) {
354
+ const fd = fs.openSync(ignoreFile, fs.constants.O_WRONLY |
355
+ fs.constants.O_CREAT |
356
+ fs.constants.O_APPEND |
357
+ fs.constants.O_NOFOLLOW, 0o644);
358
+ try {
359
+ fs.writeFileSync(fd, `${ignored.endsWith("\n") || !ignored ? "" : "\n"}# Local CodeTelemetry credentials\n${ignoreEntry}\n`);
360
+ }
361
+ finally {
362
+ fs.closeSync(fd);
363
+ }
364
+ }
365
+ const client = CLIENTS[state.plan.client];
366
+ if (state.plan.client === "codex" &&
367
+ path.resolve(state.plan.configPath) !==
368
+ codexWorkspaceProfilePath(name) &&
369
+ path
370
+ .resolve(state.plan.configPath)
371
+ .startsWith(state.plan.repositoryPath + path.sep))
372
+ throw new Error("Codex ignores project-local telemetry. Use the named user-level workspace profile.");
373
+ const written = state.plan.client === "codex" &&
374
+ path.resolve(state.plan.configPath) === codexWorkspaceProfilePath(name)
375
+ ? writeCodexWorkspaceProfile(context, {
376
+ enrich: state.plan.enrich,
377
+ repositoryObservation: state.plan.repositoryObservation,
378
+ })
379
+ : client.write({
380
+ key: context.ingestKey,
381
+ ingestEndpoint: context.ingestEndpoint,
382
+ configPath: state.plan.configPath,
383
+ enrich: state.plan.enrich === true,
384
+ repositoryObservation: state.plan.repositoryObservation === true,
385
+ });
386
+ context.clientConfig = {
387
+ client: state.plan.client,
388
+ path: written.path,
389
+ enrich: state.plan.enrich === true,
390
+ repositoryObservation: state.plan.repositoryObservation === true,
391
+ };
392
+ saveWorkspace(context);
393
+ if (state.plan.client === "claude") {
394
+ const file = path.join(state.plan.repositoryPath, ".mcp.json");
395
+ const existing = fs.existsSync(file)
396
+ ? readWorkspaceFile(file, false)
397
+ : {};
398
+ const servers = existing.mcpServers ?? {};
399
+ if (servers.codetelemetry &&
400
+ (servers.codetelemetry.command !== "npx" ||
401
+ !servers.codetelemetry.args?.some((a) => typeof a === "string" && a.includes("@codetelemetry/mcp"))))
402
+ throw new Error("Existing project MCP entry differs; review it before connecting this workspace.");
403
+ writeWorkspaceFile(file, {
404
+ ...existing,
405
+ mcpServers: {
406
+ ...servers,
407
+ codetelemetry: {
408
+ command: "npx",
409
+ args: [
410
+ "-y",
411
+ `--package=${WORKSPACE_MCP_PACKAGE}`,
412
+ "codetelemetry-mcp",
413
+ ],
414
+ env: {
415
+ CODETELEMETRY_WORKSPACE: name,
416
+ CODETELEMETRY_CONTEXT_HOME: workspaceHome(),
417
+ },
418
+ },
419
+ },
420
+ });
421
+ }
422
+ state.steps.clientConfig = written.path;
423
+ state.steps.clientLaunch =
424
+ state.plan.client === "codex"
425
+ ? `codetelemetry-connect run ${name} -- <codex arguments>`
426
+ : "Open Claude Code in the bound repository.";
427
+ checkpoint();
428
+ if (!state.probe ||
429
+ state.probe.key !== keyHash(context.ingestKey) ||
430
+ Date.now() - state.probe.at > 3_000_000) {
431
+ const sent = await sendTestEvent({
432
+ key: context.ingestKey,
433
+ ingestEndpoint: context.ingestEndpoint,
434
+ fetchImpl,
435
+ timeoutMs: Math.min(8000, Math.max(1, deadline - Date.now())),
436
+ });
437
+ if (!sent.ok)
438
+ return result("ingestion_failed", `The test event returned HTTP ${sent.httpStatus}; resolve ingestion and resume.`);
439
+ state.probe = {
440
+ id: sent.probeId,
441
+ key: keyHash(context.ingestKey),
442
+ at: Date.now(),
443
+ };
444
+ checkpoint();
445
+ }
446
+ const landed = await confirmLanded({
447
+ key: context.ingestKey,
448
+ connectivityUrl: endpoints.connectivityUrl,
449
+ probeId: state.probe.id,
450
+ expected: context.scope,
451
+ fetchImpl,
452
+ timeoutMs: Math.min(5000, Math.max(1, deadline - Date.now())),
453
+ });
454
+ if (!landed.landed)
455
+ return result("ingestion_pending", `Telemetry verification returned ${landed.state}; resume to check the same probe.`);
456
+ state.steps.telemetry = "verified";
457
+ checkpoint();
458
+ if (state.plan.checks?.length) {
459
+ const checks = [];
460
+ let config = {};
461
+ for (let page = 0, offset = 0; page < 6; page++) {
462
+ const read = await request(apiBase, "/api/agent/grader", { offset, limit: 10 }, fetchImpl, deadline, context.ingestKey, context.scope);
463
+ if (!read.config?.draft ||
464
+ !Array.isArray(read.config.draft.checks) ||
465
+ (config.revision && config.revision !== read.config.revision))
466
+ throw new Error("Grader changed during bootstrap; resume.");
467
+ config = read.config;
468
+ checks.push(...config.draft.checks);
469
+ if (config.nextOffset === undefined)
470
+ break;
471
+ if (config.nextOffset !== offset + config.draft.checks.length ||
472
+ config.nextOffset <= offset ||
473
+ page === 5)
474
+ throw new Error("Invalid Grader pagination.");
475
+ offset = config.nextOffset;
476
+ }
477
+ const equal = (a, b) => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
478
+ if (state.plan.checks.some((want) => !checks.some((have) => have.id === want.id && equal(have, want)))) {
479
+ const saved = await request(apiBase, "/api/agent/grader/configure", {
480
+ expectedRevision: config.revision,
481
+ features: state.plan.features,
482
+ upsertChecks: state.plan.checks,
483
+ }, fetchImpl, deadline, context.ingestKey, context.scope);
484
+ config = saved.config;
485
+ state.steps.grader = "draft_saved";
486
+ checkpoint();
487
+ }
488
+ else
489
+ state.steps.grader = "draft_verified";
490
+ if (state.plan.terraform) {
491
+ const artifactPath = path.join(state.plan.repositoryPath, "codetelemetry-grader.tf.json");
492
+ if (!fs.existsSync(artifactPath))
493
+ writeGraderArtifact({
494
+ repositoryPath: state.plan.repositoryPath,
495
+ format: "terraform",
496
+ features: state.plan.features,
497
+ checks: state.plan.checks,
498
+ });
499
+ else {
500
+ const artifact = readWorkspaceFile(artifactPath, false);
501
+ const raw = artifact?.resource?.codetelemetry_grader_config?.instructions
502
+ ?.checks_json;
503
+ if (typeof raw !== "string" ||
504
+ !equal(JSON.parse(raw.replaceAll("$${", "${").replaceAll("%%{", "%{")), state.plan.checks))
505
+ throw new Error("Existing Terraform artifact differs from the saved setup; review it before resuming.");
506
+ }
507
+ state.steps.terraform = "artifact_written; apply remains explicit";
508
+ }
509
+ if (state.plan.publish && config.publishedMatchesDraft === true) {
510
+ state.publishedRevision = config.revision;
511
+ state.steps.publication = `policy_${config.publishedVersion}`;
512
+ checkpoint();
513
+ }
514
+ else if (state.plan.publish &&
515
+ state.publishedRevision !== config.revision) {
516
+ const published = await request(apiBase, "/api/agent/grader/publish", { expectedRevision: config.revision }, fetchImpl, deadline, context.ingestKey, context.scope);
517
+ state.publishedRevision = published.config.revision;
518
+ state.steps.publication = `policy_${published.config.publishedVersion}`;
519
+ checkpoint();
520
+ }
521
+ }
522
+ if (state.plan.githubRepository) {
523
+ const gate = await request(apiBase, "/api/agent/github-gate/configure", { enabled: true, addRepositories: [state.plan.githubRepository] }, fetchImpl, deadline, context.ingestKey, context.scope);
524
+ state.steps.gate = "configured";
525
+ if (!gate.gate?.actions?.workflow)
526
+ return result("repository_action_required", "The service did not provide a workflow; check the gate deployment.");
527
+ const workflowPath = prepareGitHubWorkflow(state.plan.repositoryPath, gate.gate.actions.workflow);
528
+ checkpoint();
529
+ let verification;
530
+ try {
531
+ const current = await request(apiBase, "/api/agent/grader", { offset: 0, limit: 1 }, fetchImpl, deadline, context.ingestKey, context.scope);
532
+ if (!Number.isSafeInteger(current.config?.publishedVersion))
533
+ throw new Error("Current published policy is unavailable.");
534
+ verification = verifyGitHubSetup(gate.gate, state.plan.githubRepository, state.plan.repositoryPath, state.startedAt, deadline, current.config.publishedVersion);
535
+ }
536
+ catch (error) {
537
+ return result("repository_action_required", String(error.message), {
538
+ workflowPath,
539
+ requiredCheck: gate.gate.actions.requiredCheck,
540
+ rulesetJson: gate.gate.actions.rulesetJson,
541
+ });
542
+ }
543
+ if (!verification.verified)
544
+ return result("repository_action_required", verification.reason, {
545
+ workflowPath,
546
+ requiredCheck: gate.gate.actions.requiredCheck,
547
+ rulesetJson: gate.gate.actions.rulesetJson,
548
+ });
549
+ state.steps.gate = "verified";
550
+ checkpoint();
551
+ return result("ready", undefined, {
552
+ scope: context.scope,
553
+ verification: {
554
+ ingestion: true,
555
+ gate: verification.decision,
556
+ terraformApply: "not_run",
557
+ },
558
+ });
559
+ }
560
+ checkpoint();
561
+ return result("ready", undefined, {
562
+ scope: context.scope,
563
+ binding: bindingOf(context),
564
+ verification: {
565
+ ingestion: true,
566
+ grader: state.steps.grader ?? "not_requested",
567
+ publication: state.steps.publication ?? "not_requested",
568
+ terraformApply: "not_run",
569
+ pullRequestVerdict: "not_requested",
570
+ },
571
+ });
572
+ }
573
+ finally {
574
+ release();
575
+ }
576
+ }
577
+ function canonical(value) {
578
+ if (Array.isArray(value))
579
+ return value.map(canonical);
580
+ if (value && typeof value === "object")
581
+ return Object.fromEntries(Object.entries(value)
582
+ .sort(([a], [b]) => a.localeCompare(b))
583
+ .map(([k, v]) => [k, canonical(v)]));
584
+ return value;
585
+ }
@@ -0,0 +1,21 @@
1
+ export declare function decisionForHead(decisions: any[], repository: string, head: string, startedAt: number, policyVersion?: number): any;
2
+ export declare function prepareGitHubWorkflow(root: string, workflow: {
3
+ path: string;
4
+ content: string;
5
+ }): string;
6
+ export declare function verifyGitHubSetup(gate: any, repository: string, root: string, startedAt: number, deadline: number, policyVersion?: number): {
7
+ verified: boolean;
8
+ reason: string;
9
+ decision?: undefined;
10
+ } | {
11
+ verified: boolean;
12
+ decision: {
13
+ prUrl: any;
14
+ headSha: any;
15
+ verdict: any;
16
+ score: any;
17
+ threshold: any;
18
+ policyVersion: any;
19
+ };
20
+ reason?: undefined;
21
+ };