crysk 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +26 -17
  2. package/config/models/anthropic.json +1 -1
  3. package/dist/SKILL-k4k0zn1w.md +143 -0
  4. package/dist/SKILL-vhb4c3vv.md +553 -0
  5. package/dist/SKILL-xpf6kmdw.md +74 -0
  6. package/dist/ci-admission-0ken6ehx.md +128 -0
  7. package/dist/cli.js +3056 -1623
  8. package/dist/index.js +1744 -938
  9. package/dist/opencode-ci-ac5zksdn.md +106 -0
  10. package/dist/workflow-4pkyck01.yml +160 -0
  11. package/package.json +1 -1
  12. package/prompts/default/PROVENANCE.md +1 -0
  13. package/skills/crysk/SKILL.md +16 -16
  14. package/skills/crysk-ci-setup/SKILL.md +41 -38
  15. package/skills/crysk-ci-setup/assets/workflow.yml +31 -22
  16. package/skills/crysk-ci-setup/references/ci-admission.md +1 -1
  17. package/skills/crysk-ci-setup/references/opencode-ci.md +53 -88
  18. package/skills/crysk-loop/SKILL.md +1 -1
  19. package/src/asset-manifest.ts +0 -4
  20. package/src/assets.ts +1 -1
  21. package/src/ci/admission-ledger.ts +4 -0
  22. package/src/ci/classify-error.ts +21 -24
  23. package/src/ci/cli-record.ts +53 -1
  24. package/src/ci/crysk-secrets.ts +409 -0
  25. package/src/ci/force-comment.ts +14 -1
  26. package/src/ci/gates.ts +86 -57
  27. package/src/ci/outcome.ts +421 -330
  28. package/src/ci/platform-config.ts +2 -2
  29. package/src/ci/platform-estimate.ts +111 -0
  30. package/src/ci/platform-report.ts +274 -41
  31. package/src/ci/platform-trace.ts +581 -0
  32. package/src/ci/platform.ts +58 -12
  33. package/src/ci/publish.ts +19 -6
  34. package/src/ci/reporter.ts +14 -4
  35. package/src/ci/review-levels.ts +8 -7
  36. package/src/ci/run.ts +88 -0
  37. package/src/ci/setup.ts +485 -118
  38. package/src/ci/trace-bundle.ts +1486 -0
  39. package/src/ci/trace-transcripts.ts +480 -0
  40. package/src/ci/trigger.ts +176 -33
  41. package/src/cli.ts +11 -3
  42. package/src/commands/ci-setup-questions.ts +3 -3
  43. package/src/commands/ci-setup.ts +152 -6
  44. package/src/commands/config.ts +3 -0
  45. package/src/commands/doctor.ts +15 -6
  46. package/src/config/config.ts +16 -3
  47. package/src/diversity/clustering.ts +0 -1
  48. package/src/diversity/identity.ts +4 -5
  49. package/src/diversity/pipeline-integration.ts +1 -9
  50. package/src/doctor.ts +3 -3
  51. package/src/execution/attempt-evidence.ts +10 -5
  52. package/src/execution/claude-session-trace.ts +480 -0
  53. package/src/execution/contracts.ts +21 -4
  54. package/src/execution/harness.ts +105 -8
  55. package/src/execution/model-fallback.ts +239 -0
  56. package/src/execution/usage-normalized.ts +6 -4
  57. package/src/home-preflight.ts +1 -1
  58. package/src/index.ts +1 -1
  59. package/src/model/catalog.ts +13 -37
  60. package/src/model/free-discovery.ts +117 -8
  61. package/src/model/model-name.ts +404 -0
  62. package/src/model/provider-capabilities.ts +22 -7
  63. package/src/model/routing.ts +346 -467
  64. package/src/pr/admission.ts +18 -0
  65. package/src/pr/ci-admission-gate.ts +2 -0
  66. package/src/pr/discovery.ts +18 -0
  67. package/src/pr/plan.ts +55 -5
  68. package/src/pr/preflight.ts +1 -1
  69. package/src/pr/publish-outcome.ts +1 -1
  70. package/src/pr/review-pr.ts +26 -1
  71. package/src/pr/target.ts +63 -11
  72. package/src/production-runtime.ts +760 -331
  73. package/src/review/pipeline.ts +277 -101
  74. package/src/review/preflight.ts +201 -294
  75. package/src/review/report.ts +30 -26
  76. package/src/review/review.ts +20 -3
  77. package/src/review/route-preflight.ts +79 -11
  78. package/src/review/run.ts +44 -6
  79. package/src/review/scout.ts +1 -1
  80. package/src/review/spec.ts +3 -3
  81. package/src/review/step-runner.ts +70 -1
  82. package/src/runner-authority.ts +127 -9
  83. package/src/security/binding-policy.ts +1 -2
  84. package/src/security/claude-credential.ts +355 -0
  85. package/src/security/credential-broker.ts +56 -40
  86. package/src/security/evidence-redaction.ts +179 -4
  87. package/src/security/opencode-secret-manifest.ts +114 -0
  88. package/src/security/redact.ts +45 -0
  89. package/src/system-tools.ts +48 -21
  90. package/src/transport-registry.ts +12 -2
  91. package/src/transports/claude-code-cli.ts +21 -2
  92. package/src/transports/opencode-sdk.ts +11 -9
  93. package/src/transports/opencode-server.ts +7 -10
  94. package/src/ui/config-edit.ts +9 -20
  95. package/src/ui/config.ts +32 -27
  96. package/src/ui/plan.ts +84 -50
  97. package/src/updater.ts +10 -7
  98. package/prompts/default/deep-review-lifecycle.md +0 -362
@@ -0,0 +1,581 @@
1
+ // The action's trace step: send the platform the review's full trace, so every
2
+ // run on a platform-managed repository can be studied afterwards, the failed
3
+ // ones above all (odd/tasks/review-traces.md in the platform repository).
4
+ //
5
+ // It runs only in platform mode (action.yml gates the step on
6
+ // `workflow_dispatch`, a non-empty `dispatch-id` and a run token being present),
7
+ // under always(), after the report step and the cancelled-run refresh. A
8
+ // standalone run never reaches it, so it sends nothing anywhere.
9
+ //
10
+ // WHAT IT SENDS: the crysk.trace.v1 bundle src/ci/trace-bundle.ts builds from
11
+ // the run directory, gzip-compressed, to POST /runs/trace with the run token.
12
+ // Content (prompts, outputs, tool arguments and results, transcripts) goes only
13
+ // when the same exchange as the token said `trace_content` (CRYSK_TRACE_CONTENT
14
+ // is exactly `true`); otherwise metadata only.
15
+ //
16
+ // WHICH RUN DIRECTORY: the run step's `run_dir` output, else the run-dir record
17
+ // the CLI wrote into the outcome directory (src/ci/cli-record.ts recordRunDir).
18
+ // That output is empty when every hunter failed, on a fatal error and on a
19
+ // cancelled job, the runs a trace is most for. With neither, the trace is the
20
+ // run's root alone, built from cli.json.
21
+ //
22
+ // WHICH CODE: the one the publish step renders (decidePublication), from the
23
+ // same records, so the trace and the pull request name the same CRYSK-* code.
24
+ //
25
+ // WHY it never fails the job: tracing is best effort (S10). A 503 is retried
26
+ // once (the platform answers it when its storage failed and released the
27
+ // claim); any other failure is a `::warning::` and the step exits 0.
28
+ //
29
+ // BUILTINS ONLY: under always() this step can run when `bun install` never did.
30
+ // test/ci/platform-trace.test.ts walks the import closure.
31
+
32
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
33
+ import path from "node:path";
34
+ import {
35
+ CLI_RECORD_FILE,
36
+ type CliRecord,
37
+ parseCliRecord,
38
+ parseSetupRecord,
39
+ parseTriggerRecord,
40
+ RUN_DIR_FILE,
41
+ } from "./outcome";
42
+ import { PLATFORM_API_URL } from "./platform";
43
+ import { decidePublication } from "./publish";
44
+ import {
45
+ type AttemptStart,
46
+ encodeTrace,
47
+ type TraceAttemptInput,
48
+ type TraceOutcome,
49
+ type TraceRunInput,
50
+ type TraceStepInput,
51
+ } from "./trace-bundle";
52
+ import {
53
+ type Conversation,
54
+ openCodeConversation,
55
+ scanClaudeSessionFile,
56
+ withoutContent,
57
+ } from "./trace-transcripts";
58
+
59
+ // A 25 MB body over a slow link, but never the job's tail held for long.
60
+ const REQUEST_TIMEOUT_MS = 120_000;
61
+ const RETRY_DELAY_MS = 2_000;
62
+ // The CLI's session copy stops at 64 MiB (claude-session-trace.ts); a prompt or
63
+ // an output file past this is not read.
64
+ const MAX_TRANSCRIPT_BYTES = 65 * 1024 * 1024;
65
+ const MAX_FILE_BYTES = 8 * 1024 * 1024;
66
+ const SHA = /^[0-9a-f]{40}$/;
67
+ const OUTCOMES = new Set<string>([
68
+ "reviewed",
69
+ "hunters-failed",
70
+ "skipped",
71
+ "yielded",
72
+ "error",
73
+ ]);
74
+
75
+ function readText(file: string, max: number): string | undefined {
76
+ try {
77
+ if (statSync(file).size > max) return undefined;
78
+ return readFileSync(file, "utf8");
79
+ } catch {
80
+ return undefined;
81
+ }
82
+ }
83
+
84
+ function readJson(file: string): unknown {
85
+ const text = readText(file, MAX_FILE_BYTES);
86
+ if (text === undefined) return undefined;
87
+ try {
88
+ return JSON.parse(text) as unknown;
89
+ } catch {
90
+ return undefined;
91
+ }
92
+ }
93
+
94
+ function isDirectory(dir: string): boolean {
95
+ try {
96
+ return statSync(dir).isDirectory();
97
+ } catch {
98
+ return false;
99
+ }
100
+ }
101
+
102
+ function mtimeMs(file: string): number | undefined {
103
+ try {
104
+ return statSync(file).mtimeMs;
105
+ } catch {
106
+ return undefined;
107
+ }
108
+ }
109
+
110
+ function isRecord(value: unknown): value is Record<string, unknown> {
111
+ return typeof value === "object" && value !== null && !Array.isArray(value);
112
+ }
113
+
114
+ // The run step's output, else the CLI's record of it. The record is read only
115
+ // when it names this pull request's run directory (`pr-<n>-...`): the trigger
116
+ // clears it at job start, and this keeps a leftover from ever standing in.
117
+ export function locateRunDir(
118
+ env: Readonly<Record<string, string | undefined>>,
119
+ ): string | undefined {
120
+ const output = env.CRYSK_RUN_DIR ?? "";
121
+ if (output !== "" && isDirectory(output)) return output;
122
+ const outcomeDir = env.CRYSK_OUTCOME_DIR ?? "";
123
+ if (outcomeDir === "") return undefined;
124
+ const recorded = readText(path.join(outcomeDir, RUN_DIR_FILE), 4096)
125
+ ?.split("\n")[0]
126
+ ?.trim();
127
+ if (recorded === undefined || !path.isAbsolute(recorded)) return undefined;
128
+ const pr = env.TRIGGER_PR ?? "";
129
+ if (pr === "" || !path.basename(recorded).startsWith(`pr-${pr}-`)) {
130
+ return undefined;
131
+ }
132
+ return isDirectory(recorded) ? recorded : undefined;
133
+ }
134
+
135
+ const EVIDENCE = /^evidence\.(.+)\.attempt(\d+)\.json$/;
136
+ const CAPTURE = /^evidence\.(.+)\.attempt(\d+)\.capture\.json$/;
137
+ const TRANSCRIPT = /^trace\.(.+)\.attempt(\d+)\.jsonl$/;
138
+ const REQUEST = /^evidence\.(.+)\.attempt(\d+)\.request\.json$/;
139
+
140
+ // Every step the run directory holds files for: pipeline.json's steps, and any
141
+ // step whose evidence or transcript exists without a pipeline row (a run that
142
+ // stopped before it wrote pipeline.json).
143
+ //
144
+ // Without `content` no content is kept. The prompts and outputs are not read.
145
+ // Each Claude session (up to 65 MiB) is scanned line by line for its tool
146
+ // calls' names and times, its finish reason and its response model, never held
147
+ // whole (scanClaudeSessionFile); each OpenCode capture, which its writer caps
148
+ // at 4 MiB (src/transports/opencode-evidence.ts), is parsed whole, reduced the
149
+ // same way and dropped. So a metadata trace has the content trace's spans.
150
+ export function readRunSteps(
151
+ runDir: string,
152
+ pipeline: unknown,
153
+ content: boolean,
154
+ ): TraceStepInput[] {
155
+ const stepsDir = path.join(runDir, "steps");
156
+ let names: string[] = [];
157
+ try {
158
+ names = readdirSync(stepsDir);
159
+ } catch {
160
+ names = [];
161
+ }
162
+ const steps = new Map<string, Map<number, TraceAttemptInput>>();
163
+ const attemptOf = (step: string, n: number): TraceAttemptInput => {
164
+ const attempts = steps.get(step) ?? new Map<number, TraceAttemptInput>();
165
+ steps.set(step, attempts);
166
+ const found = attempts.get(n) ?? { attempt: n };
167
+ attempts.set(n, found);
168
+ return found;
169
+ };
170
+ for (const name of names.sort()) {
171
+ const file = path.join(stepsDir, name);
172
+ const capture = CAPTURE.exec(name);
173
+ if (capture?.[1] !== undefined) {
174
+ if (!content) {
175
+ // A session, when there is one, says more (parseAttempt reads it
176
+ // first); names sort captures before sessions.
177
+ const found = captureMetadata(file);
178
+ if (found !== undefined) {
179
+ const attempt = attemptOf(capture[1], Number(capture[2]));
180
+ attempt.transcriptMetadata ??= found;
181
+ }
182
+ continue;
183
+ }
184
+ const text = readText(file, MAX_TRANSCRIPT_BYTES);
185
+ if (text !== undefined) {
186
+ attemptOf(capture[1], Number(capture[2])).openCodeCapture = text;
187
+ }
188
+ continue;
189
+ }
190
+ // #511: the plan an attempt freezes at spawn, the one file a hunter still
191
+ // running at a cancel has written.
192
+ const request = REQUEST.exec(name);
193
+ if (request?.[1] !== undefined) {
194
+ const started = attemptStart(file);
195
+ if (started !== undefined) {
196
+ attemptOf(request[1], Number(request[2])).started = started;
197
+ }
198
+ continue;
199
+ }
200
+ const evidence = EVIDENCE.exec(name);
201
+ if (evidence?.[1] !== undefined) {
202
+ const parsed = readJson(file);
203
+ if (parsed !== undefined) {
204
+ attemptOf(evidence[1], Number(evidence[2])).evidence = parsed;
205
+ }
206
+ continue;
207
+ }
208
+ const transcript = TRANSCRIPT.exec(name);
209
+ if (transcript?.[1] !== undefined && !content) {
210
+ const found = scanClaudeSessionFile(file);
211
+ if (found !== undefined) {
212
+ attemptOf(transcript[1], Number(transcript[2])).transcriptMetadata =
213
+ found;
214
+ }
215
+ } else if (transcript?.[1] !== undefined) {
216
+ const text = readText(file, MAX_TRANSCRIPT_BYTES);
217
+ if (text !== undefined) {
218
+ attemptOf(transcript[1], Number(transcript[2])).sessionJsonl = text;
219
+ }
220
+ }
221
+ }
222
+ const metas =
223
+ isRecord(pipeline) && Array.isArray(pipeline.steps)
224
+ ? pipeline.steps.filter(isRecord)
225
+ : [];
226
+ const allNames = [
227
+ ...new Set([
228
+ ...metas.map((meta) => String(meta.name)),
229
+ ...[...steps.keys()].sort(),
230
+ ]),
231
+ ];
232
+ return allNames.map((name) => {
233
+ const attempts = [...(steps.get(name)?.values() ?? [])];
234
+ if (!content) return { name, attempts };
235
+ const meta = metas.find((item) => item.name === name);
236
+ // pipeline.json names absolute paths of the runner that wrote them; the
237
+ // files sit in steps/ under the same basename.
238
+ const inSteps = (value: unknown, fallback: string) =>
239
+ path.join(
240
+ stepsDir,
241
+ typeof value === "string" && value !== ""
242
+ ? path.basename(value)
243
+ : fallback,
244
+ );
245
+ const systemPrompt = readText(
246
+ inSteps(meta?.systemPromptPath, `${name}.system.md`),
247
+ MAX_FILE_BYTES,
248
+ );
249
+ const promptBody = readText(
250
+ path.join(stepsDir, `${name}.body.md`),
251
+ MAX_FILE_BYTES,
252
+ );
253
+ const output =
254
+ typeof meta?.outPath === "string"
255
+ ? readText(inSteps(meta.outPath, ""), MAX_FILE_BYTES)
256
+ : undefined;
257
+ return {
258
+ name,
259
+ ...(systemPrompt === undefined ? {} : { systemPrompt }),
260
+ ...(promptBody === undefined ? {} : { promptBody }),
261
+ ...(output === undefined ? {} : { output }),
262
+ attempts,
263
+ };
264
+ });
265
+ }
266
+
267
+ // What a frozen request plan says of its attempt: its route's model and
268
+ // provider, and the file's time as the spawn's.
269
+ function attemptStart(file: string): AttemptStart | undefined {
270
+ const plan = readJson(file);
271
+ if (!isRecord(plan)) return undefined;
272
+ const route = isRecord(plan.route) ? plan.route : {};
273
+ const started: AttemptStart = {};
274
+ const atMs = mtimeMs(file);
275
+ if (atMs !== undefined) started.atMs = atMs;
276
+ if (typeof route.modelSnapshot === "string" && route.modelSnapshot !== "") {
277
+ started.model = route.modelSnapshot;
278
+ }
279
+ if (typeof route.provider === "string" && route.provider !== "") {
280
+ started.provider = route.provider;
281
+ }
282
+ return started;
283
+ }
284
+
285
+ // An OpenCode capture's metadata: its conversation without content. The text
286
+ // and the parsed capture are dropped on return.
287
+ function captureMetadata(file: string): Conversation | undefined {
288
+ const parsed = readJson(file);
289
+ return parsed === undefined
290
+ ? undefined
291
+ : withoutContent(openCodeConversation(parsed));
292
+ }
293
+
294
+ interface OutcomeFacts {
295
+ outcome: TraceOutcome;
296
+ code: string | null;
297
+ cli?: CliRecord;
298
+ startedAtMs?: number;
299
+ }
300
+
301
+ // A cancelled job: job.status says so, or the cancelled-run refresh ran (it
302
+ // runs only on a cancel). The second signal is there because the job context's
303
+ // value inside a composite action is not documented.
304
+ function wasCancelled(
305
+ env: Readonly<Record<string, string | undefined>>,
306
+ ): boolean {
307
+ const refresh = env.CRYSK_CANCEL_REFRESH ?? "";
308
+ return (
309
+ env.CRYSK_JOB_STATUS === "cancelled" ||
310
+ (refresh !== "" && refresh !== "skipped")
311
+ );
312
+ }
313
+
314
+ // The outcome from cli.json (a killed CLI that left `reviewing`, or none, is an
315
+ // error), and the code the publisher renders from the same records.
316
+ export function readOutcome(
317
+ env: Readonly<Record<string, string | undefined>>,
318
+ ): OutcomeFacts {
319
+ const dir = env.CRYSK_OUTCOME_DIR ?? "";
320
+ const triggerFile = path.join(dir, "trigger.json");
321
+ const startedFile = path.join(dir, "cli-started");
322
+ const startedAtMs =
323
+ dir === "" ? undefined : (mtimeMs(startedFile) ?? mtimeMs(triggerFile));
324
+ const timing = startedAtMs === undefined ? {} : { startedAtMs };
325
+ // A cancel after the CLI wrote a terminal outcome (the job was cancelled
326
+ // during the steps after the review) keeps that outcome: the review ran.
327
+ if (wasCancelled(env)) {
328
+ const cli =
329
+ dir === ""
330
+ ? undefined
331
+ : parseCliRecord(
332
+ readText(path.join(dir, CLI_RECORD_FILE), MAX_FILE_BYTES) ?? "",
333
+ );
334
+ if (cli === undefined || !OUTCOMES.has(cli.outcome)) {
335
+ return {
336
+ outcome: "error",
337
+ code: "CRYSK-CANCELLED",
338
+ ...(cli === undefined ? {} : { cli }),
339
+ ...timing,
340
+ };
341
+ }
342
+ }
343
+ if (dir === "") return { outcome: "error", code: null };
344
+ const record = parseTriggerRecord(
345
+ readText(triggerFile, MAX_FILE_BYTES) ?? "",
346
+ );
347
+ const cliStarted = existsSync(startedFile);
348
+ const cli = cliStarted
349
+ ? parseCliRecord(
350
+ readText(path.join(dir, CLI_RECORD_FILE), MAX_FILE_BYTES) ?? "",
351
+ )
352
+ : undefined;
353
+ const setupText = readText(path.join(dir, "setup.json"), MAX_FILE_BYTES);
354
+ const setup =
355
+ setupText === undefined ? undefined : parseSetupRecord(setupText);
356
+ const outcome: TraceOutcome =
357
+ cli !== undefined && OUTCOMES.has(cli.outcome)
358
+ ? (cli.outcome as TraceOutcome)
359
+ : "error";
360
+ let code: string | null = null;
361
+ if (outcome === "error" || outcome === "hunters-failed") {
362
+ const plan = decidePublication({
363
+ record,
364
+ cliStarted,
365
+ ...(cli === undefined ? {} : { cliRecord: cli }),
366
+ ...(setup === undefined ? {} : { setup }),
367
+ });
368
+ code =
369
+ plan.kind === "remote" || plan.kind === "local"
370
+ ? plan.rendered.code
371
+ : null;
372
+ }
373
+ return { outcome, code, ...(cli === undefined ? {} : { cli }), ...timing };
374
+ }
375
+
376
+ // The engine that wrote the run's records, else the action's own package.json
377
+ // (CRYSK_ACTION_PATH, the step's github.action_path): a refusal before the review
378
+ // wrote anything still names its engine. Never derived from import.meta, which
379
+ // only src/assets.ts may do.
380
+ function engineVersion(
381
+ env: Readonly<Record<string, string | undefined>>,
382
+ ...docs: unknown[]
383
+ ): string | undefined {
384
+ for (const doc of docs) {
385
+ if (isRecord(doc) && isRecord(doc.engine)) {
386
+ const version = doc.engine.version;
387
+ if (typeof version === "string" && version !== "") return version;
388
+ }
389
+ }
390
+ const actionPath = env.CRYSK_ACTION_PATH ?? "";
391
+ if (actionPath === "") return undefined;
392
+ const pkg = readJson(path.join(actionPath, "package.json"));
393
+ return isRecord(pkg) && typeof pkg.version === "string" && pkg.version !== ""
394
+ ? pkg.version
395
+ : undefined;
396
+ }
397
+
398
+ export function readTraceRun(
399
+ env: Readonly<Record<string, string | undefined>>,
400
+ now: number,
401
+ content: boolean,
402
+ ): TraceRunInput {
403
+ const facts = readOutcome(env);
404
+ const runDir = locateRunDir(env);
405
+ const pipeline =
406
+ runDir === undefined
407
+ ? undefined
408
+ : readJson(path.join(runDir, "pipeline.json"));
409
+ const findings =
410
+ runDir === undefined
411
+ ? undefined
412
+ : readJson(path.join(runDir, "findings.json"));
413
+ const pr = Number(env.TRIGGER_PR ?? "");
414
+ const head = [
415
+ facts.cli?.head_sha,
416
+ isRecord(findings) ? findings.head_sha : undefined,
417
+ env.TRIGGER_HEAD_SHA,
418
+ ].find((sha): sha is string => typeof sha === "string" && SHA.test(sha));
419
+ const version = engineVersion(env, findings, pipeline);
420
+ return {
421
+ outcome: facts.outcome,
422
+ code: facts.code,
423
+ ...(facts.cli === undefined ? {} : { cli: facts.cli }),
424
+ ...(pipeline === undefined ? {} : { pipeline }),
425
+ ...(findings === undefined ? {} : { findings }),
426
+ steps: runDir === undefined ? [] : readRunSteps(runDir, pipeline, content),
427
+ ...(Number.isInteger(pr) && pr > 0 ? { prNumber: pr } : {}),
428
+ ...(head === undefined ? {} : { headSha: head }),
429
+ ...(version === undefined ? {} : { engineVersion: version }),
430
+ startedAtMs: Math.min(facts.startedAtMs ?? now, now),
431
+ endedAtMs: now,
432
+ };
433
+ }
434
+
435
+ export type SendTraceResult =
436
+ | { ok: true; recorded: boolean }
437
+ // `message` names the HTTP status and the API's own `message`. It never
438
+ // carries the token.
439
+ | { ok: false; message: string };
440
+
441
+ export interface SendTraceDeps {
442
+ fetch: typeof fetch;
443
+ baseUrl: string;
444
+ runToken: string;
445
+ sleep: (ms: number) => Promise<void>;
446
+ }
447
+
448
+ async function apiMessage(response: Response): Promise<string | undefined> {
449
+ try {
450
+ const parsed = (await response.json()) as { message?: unknown };
451
+ return typeof parsed.message === "string" && parsed.message !== ""
452
+ ? parsed.message
453
+ : undefined;
454
+ } catch {
455
+ return undefined;
456
+ }
457
+ }
458
+
459
+ export async function sendTrace(
460
+ deps: SendTraceDeps,
461
+ body: Uint8Array,
462
+ ): Promise<SendTraceResult> {
463
+ for (let attempt = 1; ; attempt++) {
464
+ try {
465
+ const response = await deps.fetch(`${deps.baseUrl}/runs/trace`, {
466
+ method: "POST",
467
+ headers: {
468
+ Authorization: `Bearer ${deps.runToken}`,
469
+ "Content-Type": "application/json",
470
+ "Content-Encoding": "gzip",
471
+ },
472
+ // A copy over a plain ArrayBuffer, the body type fetch accepts.
473
+ body: new Uint8Array(body),
474
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
475
+ });
476
+ if (response.status === 503 && attempt === 1) {
477
+ await response.body?.cancel().catch(() => undefined);
478
+ await deps.sleep(RETRY_DELAY_MS);
479
+ continue;
480
+ }
481
+ if (!response.ok) {
482
+ const message = await apiMessage(response);
483
+ return {
484
+ ok: false,
485
+ message: `HTTP ${response.status}${message === undefined ? "" : ` — ${message}`}`,
486
+ };
487
+ }
488
+ const reply: unknown = await response.json().catch(() => ({}));
489
+ return {
490
+ ok: true,
491
+ recorded: !(isRecord(reply) && reply.recorded === false),
492
+ };
493
+ } catch (error) {
494
+ const detail = error instanceof Error ? error.message : String(error);
495
+ return {
496
+ ok: false,
497
+ message: `the request could not complete: ${detail.split(deps.runToken).join("***")}`,
498
+ };
499
+ }
500
+ }
501
+ }
502
+
503
+ function escapeCommandData(text: string): string {
504
+ return text.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
505
+ }
506
+
507
+ export interface TraceStepDeps {
508
+ fetch: typeof fetch;
509
+ env: Readonly<Record<string, string | undefined>>;
510
+ baseUrl: string;
511
+ stdout: (text: string) => void;
512
+ now?: () => number;
513
+ sleep?: (ms: number) => Promise<void>;
514
+ }
515
+
516
+ // The step's shell. ALWAYS 0: see the header.
517
+ export async function runTraceStep(deps: TraceStepDeps): Promise<number> {
518
+ const runToken = deps.env.CRYSK_RUN_TOKEN ?? "";
519
+ const warn = (message: string): void =>
520
+ deps.stdout(
521
+ `::warning title=crysk::${escapeCommandData(`Crysk trace not uploaded: ${message}`)}\n`,
522
+ );
523
+ try {
524
+ if (runToken === "") {
525
+ warn("no run token reached this step.");
526
+ return 0;
527
+ }
528
+ const content = deps.env.CRYSK_TRACE_CONTENT === "true";
529
+ const run = readTraceRun(deps.env, (deps.now ?? Date.now)(), content);
530
+ const encoded = encodeTrace(run, content);
531
+ if (!encoded.ok) {
532
+ warn(
533
+ `the trace is too large even without its content (${encoded.jsonBytes} bytes of JSON).`,
534
+ );
535
+ return 0;
536
+ }
537
+ const result = await sendTrace(
538
+ {
539
+ fetch: deps.fetch,
540
+ baseUrl: deps.baseUrl,
541
+ runToken,
542
+ sleep:
543
+ deps.sleep ??
544
+ ((ms) => {
545
+ const { promise, resolve } = Promise.withResolvers<void>();
546
+ setTimeout(resolve, ms);
547
+ return promise;
548
+ }),
549
+ },
550
+ encoded.body,
551
+ );
552
+ if (!result.ok) {
553
+ warn(result.message);
554
+ return 0;
555
+ }
556
+ const dropped = [
557
+ encoded.droppedTranscripts > 0
558
+ ? `${encoded.droppedTranscripts} transcripts`
559
+ : "",
560
+ encoded.droppedContent ? "the content" : "",
561
+ ].filter((part) => part !== "");
562
+ deps.stdout(
563
+ `Crysk trace ${result.recorded ? "recorded" : "sent (not recorded again)"}: ${Math.ceil(encoded.body.byteLength / 1024)} KB gzip${dropped.length > 0 ? `, without ${dropped.join(" and ")} to fit the size cap` : ""}.\n`,
564
+ );
565
+ } catch (error) {
566
+ const detail = error instanceof Error ? error.message : String(error);
567
+ warn(`the trace could not be built: ${detail.split(runToken).join("***")}`);
568
+ }
569
+ return 0;
570
+ }
571
+
572
+ if (import.meta.main) {
573
+ process.exit(
574
+ await runTraceStep({
575
+ fetch,
576
+ env: process.env,
577
+ baseUrl: PLATFORM_API_URL,
578
+ stdout: (text) => process.stdout.write(text),
579
+ }),
580
+ );
581
+ }