crysk 0.7.0 → 0.8.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.
Files changed (133) hide show
  1. package/README.md +27 -23
  2. package/dist/SKILL-1q3658n0.md +74 -0
  3. package/dist/SKILL-25j4q9b8.md +143 -0
  4. package/dist/SKILL-4747bhne.md +143 -0
  5. package/dist/SKILL-4jc3sv23.md +74 -0
  6. package/dist/SKILL-c0492rch.md +540 -0
  7. package/dist/SKILL-d1nzkhhr.md +74 -0
  8. package/dist/SKILL-f8p7kvx0.md +143 -0
  9. package/dist/SKILL-gxd45g38.md +553 -0
  10. package/dist/SKILL-rec41991.md +66 -0
  11. package/dist/SKILL-zze8zj5g.md +536 -0
  12. package/dist/cli.js +24658 -24654
  13. package/dist/index.js +492 -463
  14. package/dist/opencode-ci-qrcv7a99.md +106 -0
  15. package/dist/opencode-ci-rdpcc7xc.md +106 -0
  16. package/dist/opencode-ci-yt0k74t0.md +106 -0
  17. package/dist/workflow-andv2dvm.yml +158 -0
  18. package/package.json +1 -1
  19. package/prompts/default/PROVENANCE.md +1 -0
  20. package/skills/crysk/SKILL.md +6 -6
  21. package/skills/crysk-ci-setup/SKILL.md +32 -33
  22. package/skills/crysk-ci-setup/assets/workflow.yml +5 -10
  23. package/skills/crysk-ci-setup/references/ci-admission.md +5 -5
  24. package/skills/crysk-ci-setup/references/opencode-ci.md +6 -6
  25. package/skills/crysk-loop/SKILL.md +37 -54
  26. package/skills/crysk-pr/SKILL.md +1 -1
  27. package/src/asset-manifest.ts +0 -6
  28. package/src/assets.ts +1 -4
  29. package/src/brand.ts +20 -30
  30. package/src/ci/gates.ts +155 -201
  31. package/src/ci/outcome.ts +4 -31
  32. package/src/ci/platform-limits.ts +135 -0
  33. package/src/ci/platform-report.ts +212 -126
  34. package/src/ci/platform.ts +28 -26
  35. package/src/ci/reporter.ts +25 -26
  36. package/src/ci/review-admission.ts +1 -2
  37. package/src/ci/review-levels.ts +12 -53
  38. package/src/ci/setup.ts +96 -66
  39. package/src/ci/trace-bundle.ts +11 -27
  40. package/src/ci/trace-transcripts.ts +4 -6
  41. package/src/ci/trigger.ts +3 -5
  42. package/src/cli.ts +6 -5
  43. package/src/commands/ci-setup-questions.ts +2 -55
  44. package/src/commands/ci-setup.ts +2 -26
  45. package/src/commands/triage.ts +131 -38
  46. package/src/commands/usage.ts +0 -1
  47. package/src/compare/compare.ts +3 -3
  48. package/src/compare/floor-test.ts +30 -201
  49. package/src/config/config.ts +6 -30
  50. package/src/diversity/accounting.ts +0 -26
  51. package/src/diversity/benchmark.ts +1 -17
  52. package/src/diversity/identity.ts +0 -14
  53. package/src/diversity/pipeline-integration.ts +0 -29
  54. package/src/doctor.ts +3 -6
  55. package/src/execution/claude-session-trace.ts +7 -2
  56. package/src/execution/contracts.ts +15 -9
  57. package/src/execution/harness.ts +165 -187
  58. package/src/execution/spend-limiter.ts +39 -131
  59. package/src/execution/usage-facts.ts +397 -0
  60. package/src/execution/usage-normalized.ts +33 -86
  61. package/src/harness/materiality-judge.ts +0 -5
  62. package/src/harness/pipeline-plan.ts +0 -3
  63. package/src/harness/replay-rows.ts +0 -5
  64. package/src/harness/route-runner.ts +2 -2
  65. package/src/harness/single-step.ts +3 -9
  66. package/src/index.ts +1 -1
  67. package/src/mcp/preflight.ts +2 -2
  68. package/src/model/catalog.ts +1 -3
  69. package/src/model/free-discovery.ts +11 -78
  70. package/src/model/model-name.ts +14 -4
  71. package/src/model/profiles/claude.ts +1 -2
  72. package/src/model/profiles/openai.ts +1 -2
  73. package/src/model/profiles.ts +1 -2
  74. package/src/model/provider-capabilities.ts +16 -55
  75. package/src/model/routing.ts +39 -36
  76. package/src/pr/admission.ts +6 -6
  77. package/src/pr/answered-findings.ts +8 -4
  78. package/src/pr/ci-publish.ts +0 -2
  79. package/src/pr/discovery.ts +4 -25
  80. package/src/pr/plan.ts +40 -121
  81. package/src/pr/pr-status.ts +14 -2
  82. package/src/pr/preflight.ts +15 -12
  83. package/src/pr/publish-outcome.ts +1 -19
  84. package/src/pr/review-pr.ts +10 -47
  85. package/src/pr/target.ts +76 -82
  86. package/src/production-runtime.ts +52 -114
  87. package/src/progress.ts +0 -54
  88. package/src/rereview/prepare.ts +4 -1
  89. package/src/rereview/state.ts +1 -1
  90. package/src/review/boundary.ts +4 -8
  91. package/src/review/drafts.ts +3 -3
  92. package/src/review/findings-conformance.ts +1 -1
  93. package/src/review/findings.ts +0 -4
  94. package/src/review/pipeline.ts +57 -395
  95. package/src/review/preflight.ts +162 -201
  96. package/src/review/prompt-set.ts +0 -2
  97. package/src/review/report.ts +2 -162
  98. package/src/review/review.ts +16 -65
  99. package/src/review/route-preflight.ts +3 -35
  100. package/src/review/run.ts +37 -73
  101. package/src/review/size-gate.ts +3 -3
  102. package/src/review/spec.ts +6 -11
  103. package/src/review/step-runner.ts +4 -4
  104. package/src/runner-authority.ts +10 -9
  105. package/src/security/credential-broker.ts +5 -6
  106. package/src/server/preflight.ts +0 -1
  107. package/src/server/server.ts +17 -6
  108. package/src/store/activity.ts +1 -2
  109. package/src/store/backfill-preflight.ts +0 -3
  110. package/src/store/backfill.ts +0 -1
  111. package/src/store/metrics-preflight.ts +4 -14
  112. package/src/store/metrics.ts +5 -5
  113. package/src/store/preflight.ts +0 -13
  114. package/src/store/store.ts +11 -12
  115. package/src/transport-registry.ts +6 -30
  116. package/src/transports/claude-code-cli.ts +149 -215
  117. package/src/transports/opencode-client.ts +4 -24
  118. package/src/transports/opencode-sdk.ts +17 -112
  119. package/src/triage/plain-reply.ts +37 -0
  120. package/src/ui/activity.ts +1 -6
  121. package/src/ui/config-edit.ts +14 -67
  122. package/src/ui/config.ts +3 -8
  123. package/src/ui/plan.ts +11 -198
  124. package/src/ui/progress.ts +3 -49
  125. package/src/ui/result.ts +18 -77
  126. package/src/ui/review-menu.ts +3 -12
  127. package/src/ui/select.ts +9 -79
  128. package/src/updater.ts +1 -1
  129. package/src/usage.ts +1 -7
  130. package/prompts/default/deep-review-parity.md +0 -152
  131. package/prompts/scout.md +0 -140
  132. package/src/ci/platform-estimate.ts +0 -111
  133. package/src/review/scout.ts +0 -323
@@ -1,5 +1,5 @@
1
1
  // The action's report step: tell the Crysk platform how a run ended, so every
2
- // run is recorded (#157) with its cost attributed (#139), then hand it the
2
+ // run is recorded (#157) with its usage attributed (#139), then hand it the
3
3
  // run's findings so the dashboard can show them.
4
4
  //
5
5
  // It runs only in platform mode (action.yml gates the step on
@@ -7,7 +7,7 @@
7
7
  // after the publish step. Standalone use never reaches it.
8
8
  //
9
9
  // WHY THE REPORT IS METADATA ONLY: the body carries counts, token totals,
10
- // costs, model names and shas. It never carries a finding, a claim, a summary,
10
+ // model names and shas. It never carries a finding, a claim, a summary,
11
11
  // a hop trail or any other text that can quote the customer's code. The
12
12
  // builder below COPIES the numeric fields it names out of the run directory
13
13
  // instead of forwarding a document, so a field added to findings.json tomorrow
@@ -81,11 +81,8 @@ interface ReportTokens {
81
81
  output?: number;
82
82
  }
83
83
 
84
- // Added beside the legacy fields, never replacing them: `cost_usd` stays the cash cost (0 on a
85
- // subscription), and `list_cost_usd` is what the same tokens cost at list price whatever paid for them.
86
84
  interface ReportUsageSplit {
87
85
  tokens?: ReportTokens;
88
- list_cost_usd?: number;
89
86
  }
90
87
 
91
88
  export interface RunReportAgent extends ReportUsageSplit {
@@ -93,7 +90,6 @@ export interface RunReportAgent extends ReportUsageSplit {
93
90
  model?: string;
94
91
  tokens_in: number;
95
92
  tokens_out: number;
96
- cost_usd: number;
97
93
  duration_ms?: number;
98
94
  attempts?: number;
99
95
  status?: string;
@@ -120,16 +116,31 @@ export interface RunReportBody {
120
116
  usage: ReportUsageSplit & {
121
117
  tokens_in: number;
122
118
  tokens_out: number;
123
- cost_usd: number;
124
- cost_is_floor?: boolean;
125
119
  wall_ms?: number;
126
120
  index_ms?: number;
127
121
  sync_ms?: number;
128
- billing?: "subscription" | "metered";
129
122
  };
130
123
  agents: RunReportAgent[];
131
124
  // Which findings stay open, under ids that last across runs. Absent when the run recorded none.
132
125
  finding_states?: FindingStateRecord;
126
+ // What the run measured per model request: the platform prices the run from it, so the body
127
+ // carries no dollar figure anywhere.
128
+ usage_facts: ReportUsageFacts;
129
+ }
130
+
131
+ export type ReportCredential = "api" | "subscription" | "free";
132
+
133
+ // odd/tasks/platform-owned-cost-contract.md section 3. Indexes point into `steps` and `routes`.
134
+ export interface ReportUsageFacts {
135
+ v: 1;
136
+ steps: { key: string; role: string; agent?: string }[];
137
+ routes: { provider: string; model: string; credential: ReportCredential }[];
138
+ // [step, attempt, route, uncached, cacheRead, cacheWrite, cacheWrite1h, output, reasoning]
139
+ requests: number[][];
140
+ // [step, route, uncached, cacheRead, cacheWrite, cacheWrite1h, output, reasoning]
141
+ remainders?: number[][];
142
+ // [step, attempt, reason]
143
+ gaps?: [number, number, string][];
133
144
  }
134
145
 
135
146
  // What the builder knows about the run directory. Either part is absent when
@@ -177,8 +188,10 @@ export function buildRunReport(
177
188
  pr_number: input.prNumber,
178
189
  head_sha: headSha,
179
190
  counts: { blocking: 0, advisory: 0 },
180
- usage: { tokens_in: 0, tokens_out: 0, cost_usd: 0 },
191
+ usage: { tokens_in: 0, tokens_out: 0 },
181
192
  agents: [],
193
+ // A run that wrote no findings can still have spent tokens before it died.
194
+ usage_facts: buildUsageFacts(input.run.pipeline, new Map()),
182
195
  };
183
196
  }
184
197
 
@@ -189,6 +202,14 @@ export function buildRunReport(
189
202
  if (finding.tier === "blocking") blocking += 1;
190
203
  else if (finding.tier === "advisory") advisory += 1;
191
204
  }
205
+ const steps = pipelineSteps(input.run.pipeline);
206
+ const rows = agentRows(doc);
207
+ // Owners are decided over every row, the capped ones too, so a step of a row
208
+ // past the cap is dropped with it instead of landing on another row.
209
+ const owned = stepsByOwner(
210
+ steps,
211
+ rows.map(([key]) => key),
212
+ );
192
213
 
193
214
  return {
194
215
  outcome: input.outcome === "" ? "error" : input.outcome,
@@ -212,10 +233,6 @@ export function buildRunReport(
212
233
  usage: {
213
234
  tokens_in: count(telemetry.tokens_in),
214
235
  tokens_out: count(telemetry.tokens_out),
215
- cost_usd: cost(telemetry.cost_usd_est),
216
- ...(telemetry.cost_usd_est_is_floor === true
217
- ? { cost_is_floor: true }
218
- : {}),
219
236
  wall_ms: count(telemetry.wall_ms),
220
237
  // Zero means no index was built, so there is no time to report.
221
238
  ...(count(telemetry.index_ms) > 0
@@ -226,8 +243,12 @@ export function buildRunReport(
226
243
  : { sync_ms: count(telemetry.sync_ms) }),
227
244
  ...runUsageSplit(input.run.pipeline),
228
245
  },
229
- agents: buildAgents(doc, input.run.pipeline),
246
+ agents: buildAgents(rows, steps, owned),
230
247
  ...findingStates(input.run.findingStates),
248
+ usage_facts: buildUsageFacts(
249
+ input.run.pipeline,
250
+ ownerOfStep(owned, rows.slice(0, MAX_AGENTS)),
251
+ ),
231
252
  };
232
253
  }
233
254
 
@@ -332,36 +353,29 @@ function count(value: unknown): number {
332
353
  : 0;
333
354
  }
334
355
 
335
- function cost(value: unknown): number {
336
- return typeof value === "number" && Number.isFinite(value) && value > 0
337
- ? value
338
- : 0;
339
- }
340
-
341
356
  // `telemetry.per_agent` is declared with the lab-shared minimum (tokens_total +
342
357
  // duration_ms) but this engine writes the richer PerAgentUsage, so each field
343
358
  // is read through a runtime check, as review/report.ts does. `detail` is never
344
359
  // copied: it is the provider's own words and can echo prompt text.
345
- function buildAgents(
346
- doc: FindingsDocument,
347
- pipeline: unknown,
348
- ): RunReportAgent[] {
349
- const steps = pipelineSteps(pipeline);
360
+ type AgentRow = [string, Record<string, unknown>];
361
+
362
+ // validateFindingsDocument only checks that `telemetry` is an object, so a
363
+ // row that is not one is skipped instead of read.
364
+ function agentRows(doc: FindingsDocument): AgentRow[] {
350
365
  const perAgent = doc.telemetry.per_agent ?? {};
351
- // validateFindingsDocument only checks that `telemetry` is an object, so a
352
- // row that is not one is skipped instead of read.
353
- const rows = Object.entries(perAgent as Record<string, unknown>).filter(
354
- (entry): entry is [string, Record<string, unknown>] =>
366
+ return Object.entries(perAgent as Record<string, unknown>).filter(
367
+ (entry): entry is AgentRow =>
355
368
  typeof entry[1] === "object" &&
356
369
  entry[1] !== null &&
357
370
  !Array.isArray(entry[1]),
358
371
  );
359
- // Owners are decided over every row, the capped ones too, so a step of a row
360
- // past the cap is dropped with it instead of landing on another row.
361
- const owned = stepsByOwner(
362
- steps,
363
- rows.map(([key]) => key),
364
- );
372
+ }
373
+
374
+ function buildAgents(
375
+ rows: ReadonlyArray<AgentRow>,
376
+ steps: ReadonlyArray<PipelineStep>,
377
+ owned: ReadonlyMap<string, PipelineStep[]>,
378
+ ): RunReportAgent[] {
365
379
  return rows.slice(0, MAX_AGENTS).map(([key, row]) => {
366
380
  const model = modelOf(steps, key);
367
381
  return {
@@ -369,7 +383,6 @@ function buildAgents(
369
383
  ...(model === undefined ? {} : { model }),
370
384
  tokens_in: count(row.tokens_in),
371
385
  tokens_out: count(row.tokens_out),
372
- cost_usd: cost(row.cost_usd_est),
373
386
  duration_ms: count(row.duration_ms),
374
387
  ...(typeof row.attempts === "number" && row.attempts > 0
375
388
  ? { attempts: count(row.attempts) }
@@ -380,14 +393,14 @@ function buildAgents(
380
393
  });
381
394
  }
382
395
 
383
- // pipeline.json's `steps[]` rows are `{ name, model, usage_v2, model_attempts, ... }`.
384
- // Only what this file reads is kept, and `usage_v2` stays unread until the
385
- // split below checks each of its fields.
396
+ // pipeline.json's `steps[]` rows are `{ name, model, usage_v2, usage_facts, ... }`.
397
+ // Only what this file reads is kept, and `usage_v2` and `usage_facts` stay
398
+ // unread until the code that sends them checks each of their fields.
386
399
  interface PipelineStep {
387
400
  name: string;
388
401
  model?: string;
389
402
  usage?: unknown;
390
- modelUsages?: unknown[];
403
+ usageFacts?: unknown;
391
404
  }
392
405
 
393
406
  function pipelineSteps(pipeline: unknown): PipelineStep[] {
@@ -397,7 +410,7 @@ function pipelineSteps(pipeline: unknown): PipelineStep[] {
397
410
  const rows: PipelineStep[] = [];
398
411
  for (const step of steps) {
399
412
  if (typeof step !== "object" || step === null) continue;
400
- const { name, model, usage_v2, model_attempts } = step as Record<
413
+ const { name, model, usage_v2, usage_facts } = step as Record<
401
414
  string,
402
415
  unknown
403
416
  >;
@@ -406,13 +419,7 @@ function pipelineSteps(pipeline: unknown): PipelineStep[] {
406
419
  name,
407
420
  ...(typeof model === "string" && model !== "" ? { model } : {}),
408
421
  usage: usage_v2,
409
- ...(Array.isArray(model_attempts)
410
- ? {
411
- modelUsages: model_attempts.map(
412
- (entry) => (entry as { usage_v2?: unknown } | null)?.usage_v2,
413
- ),
414
- }
415
- : {}),
422
+ ...(usage_facts === undefined ? {} : { usageFacts: usage_facts }),
416
423
  });
417
424
  }
418
425
  return rows;
@@ -527,85 +534,14 @@ function tokenSplit(usage: UsageRecord | undefined): ReportTokens {
527
534
  );
528
535
  }
529
536
 
530
- // The list price of what one usage record consumed. The Claude CLI files the
531
- // CLI's list total in exactly one field (transports/claude-code-cli.ts,
532
- // `costFor`): `notionalCostUsd` on a subscription, which charges nothing, and
533
- // `cashCostUsd` on a per-token key, where list price is the charge. Any other
534
- // billing (free, or unknown because attempts disagreed) names no field that
535
- // holds a list price, so it has none rather than a guessed one.
536
- function listCost(usage: UsageRecord | undefined): number | undefined {
537
- switch (usage?.billingMode) {
538
- case "subscription":
539
- return amount(usage.notionalCostUsd);
540
- case "metered":
541
- return amount(usage.cashCostUsd);
542
- default:
543
- return undefined;
544
- }
545
- }
546
-
547
- // A step whose models billed differently reads `unknown` once summed, so its
548
- // list cost is each model's own (`model_attempts[].usage_v2`, kept for exactly
549
- // this). Unknown when any model that reported usage cannot be priced.
550
- function stepListCost(step: PipelineStep): number | undefined {
551
- const usage = usageRecord(step.usage);
552
- const own = listCost(usage);
553
- if (own !== undefined || step.modelUsages === undefined) return own;
554
- return sumAll(
555
- step.modelUsages.map(usageRecord).filter((entry) => entry !== undefined),
556
- listCost,
557
- );
558
- }
559
-
560
- // A sum only when every record that reported usage has a value: one unpriced
561
- // part would make the total look smaller than what was spent.
562
- function sumAll<T>(
563
- items: readonly T[],
564
- value: (item: T) => number | undefined,
565
- ): number | undefined {
566
- if (items.length === 0) return undefined;
567
- let total = 0;
568
- for (const item of items) {
569
- const part = value(item);
570
- if (part === undefined) return undefined;
571
- total += part;
572
- }
573
- return total;
574
- }
575
-
576
- function splitFields(
577
- tokens: ReportTokens,
578
- listUsd: number | undefined,
579
- ): ReportUsageSplit {
580
- return {
581
- ...(Object.keys(tokens).length === 0 ? {} : { tokens }),
582
- ...(listUsd === undefined ? {} : { list_cost_usd: listUsd }),
583
- };
537
+ function splitFields(tokens: ReportTokens): ReportUsageSplit {
538
+ return Object.keys(tokens).length === 0 ? {} : { tokens };
584
539
  }
585
540
 
586
- // The run's tokens and billing come from its own `usage_v2`. Its list cost is the
587
- // sum of every step's, by the rule an agent row uses: the rolled-up notional total
588
- // counts only the steps that filed one while the tokens count them all, so a step
589
- // with no list price drops the run's list cost rather than leaving it short. A
590
- // pipeline with no per-step usage falls back to the run's own figure.
591
- function runUsageSplit(
592
- pipeline: unknown,
593
- ): ReportUsageSplit & { billing?: "subscription" | "metered" } {
541
+ // The run's token split comes from its own `usage_v2`.
542
+ function runUsageSplit(pipeline: unknown): ReportUsageSplit {
594
543
  const usage = usageRecord(usageRecord(pipeline)?.usage_v2);
595
- if (usage === undefined) return {};
596
- const billing = usage.billingMode;
597
- // Every step that filed usage, a malformed record included: one that cannot be
598
- // read cannot be priced, so it drops the sum rather than shrinking it.
599
- const priced = pipelineSteps(pipeline).filter(
600
- (step) => step.usage !== undefined,
601
- );
602
- return {
603
- ...splitFields(
604
- tokenSplit(usage),
605
- priced.length > 0 ? sumAll(priced, stepListCost) : listCost(usage),
606
- ),
607
- ...(billing === "subscription" || billing === "metered" ? { billing } : {}),
608
- };
544
+ return usage === undefined ? {} : splitFields(tokenSplit(usage));
609
545
  }
610
546
 
611
547
  // A row's split is the sum of the steps it owns, refuter fan-out included.
@@ -626,7 +562,157 @@ function agentUsageSplit(steps: ReadonlyArray<PipelineStep>): ReportUsageSplit {
626
562
  return total === undefined ? [] : [[key, total]];
627
563
  }),
628
564
  );
629
- return splitFields(tokens, sumAll(usages, stepListCost));
565
+ return splitFields(tokens);
566
+ }
567
+
568
+ // Which `per_agent` row owns each step, among the rows the report sends, so a
569
+ // usage step names the `run_agents` row it belongs to by the same rule the
570
+ // rows' own usage follows (stepsByOwner), never a second one.
571
+ function ownerOfStep(
572
+ owned: ReadonlyMap<string, PipelineStep[]>,
573
+ sent: ReadonlyArray<AgentRow>,
574
+ ): Map<string, string> {
575
+ const owners = new Map<string, string>();
576
+ for (const [key] of sent) {
577
+ for (const step of owned.get(key) ?? []) owners.set(step.name, key);
578
+ }
579
+ return owners;
580
+ }
581
+
582
+ // The route plan's role for a step, else the step name's first word. Also the
583
+ // trace step's role (src/ci/trace-bundle.ts), so both name a step alike.
584
+ export function stepRole(pipeline: unknown, name: string): string {
585
+ const plan = usageRecord(usageRecord(pipeline)?.route_plan);
586
+ const planned = Array.isArray(plan?.steps)
587
+ ? plan.steps
588
+ .map(usageRecord)
589
+ .find((step) => step !== undefined && step.stepKey === name)
590
+ : undefined;
591
+ const role = planned?.role;
592
+ if (typeof role === "string" && role !== "") return role;
593
+ return name.split(/[-.]/)[0] ?? name;
594
+ }
595
+
596
+ const CREDENTIALS = new Set<string>(["api", "subscription", "free"]);
597
+ const GAP_REASONS = new Set<string>([
598
+ "no_session",
599
+ "line_omitted",
600
+ "truncated",
601
+ "no_readback",
602
+ "no_summary",
603
+ ]);
604
+ // The platform's own bound on a label (apps/api/src/runs/usage-facts.ts).
605
+ const MAX_LABEL = 200;
606
+
607
+ function label(value: unknown): value is string {
608
+ return (
609
+ typeof value === "string" &&
610
+ value.length > 0 &&
611
+ value.length <= MAX_LABEL &&
612
+ !value.includes("\u0000")
613
+ );
614
+ }
615
+
616
+ function tokenCount(value: unknown): value is number {
617
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
618
+ }
619
+
620
+ // One [provider, model, ...six counts] entry of a pipeline.json attempt, as the
621
+ // harness wrote it (src/execution/usage-facts.ts), or undefined when it is not one.
622
+ function factEntry(
623
+ value: unknown,
624
+ ): { provider: string; model: string; counts: number[] } | undefined {
625
+ if (!Array.isArray(value) || value.length !== 8) return undefined;
626
+ const [provider, model, ...counts] = value as unknown[];
627
+ return label(provider) && label(model) && counts.every(tokenCount)
628
+ ? { provider, model, counts: counts as number[] }
629
+ : undefined;
630
+ }
631
+
632
+ // The platform's `usage_facts` (odd/tasks/platform-owned-cost-contract.md,
633
+ // section 3) from each step's `usage_facts` in pipeline.json. This only copies:
634
+ // the harness read every number at the attempt's settlement. Identifiers and
635
+ // counts only, so it is safe in metadata-only mode too. An entry that does not
636
+ // check is left out on its own; the platform counts nothing for it.
637
+ function buildUsageFacts(
638
+ pipeline: unknown,
639
+ owners: ReadonlyMap<string, string>,
640
+ ): ReportUsageFacts {
641
+ const facts: ReportUsageFacts = {
642
+ v: 1,
643
+ steps: [],
644
+ routes: [],
645
+ requests: [],
646
+ };
647
+ const remainders = new Map<string, number[]>();
648
+ const gaps: [number, number, string][] = [];
649
+ const routeIndex = new Map<string, number>();
650
+ const routeOf = (
651
+ provider: string,
652
+ model: string,
653
+ credential: ReportCredential,
654
+ ): number => {
655
+ const key = JSON.stringify([provider, model, credential]);
656
+ let index = routeIndex.get(key);
657
+ if (index === undefined) {
658
+ index = facts.routes.push({ provider, model, credential }) - 1;
659
+ routeIndex.set(key, index);
660
+ }
661
+ return index;
662
+ };
663
+ for (const step of pipelineSteps(pipeline)) {
664
+ if (!Array.isArray(step.usageFacts) || !label(step.name)) continue;
665
+ const attempts = step.usageFacts
666
+ .map(usageRecord)
667
+ .filter(
668
+ (a): a is UsageRecord =>
669
+ a !== undefined &&
670
+ tokenCount(a.attempt) &&
671
+ a.attempt >= 1 &&
672
+ typeof a.credential === "string" &&
673
+ CREDENTIALS.has(a.credential),
674
+ );
675
+ if (attempts.length === 0) continue;
676
+ const owner = owners.get(step.name);
677
+ const index =
678
+ facts.steps.push({
679
+ key: step.name,
680
+ role: stepRole(pipeline, step.name),
681
+ ...(owner === undefined ? {} : { agent: owner }),
682
+ }) - 1;
683
+ for (const a of attempts) {
684
+ const attempt = a.attempt as number;
685
+ const credential = a.credential as ReportCredential;
686
+ for (const value of Array.isArray(a.requests) ? a.requests : []) {
687
+ const request = factEntry(value);
688
+ if (request === undefined) continue;
689
+ const route = routeOf(request.provider, request.model, credential);
690
+ facts.requests.push([index, attempt, route, ...request.counts]);
691
+ }
692
+ // The platform keys a remainder by step and route, so the step's attempts are summed.
693
+ for (const value of Array.isArray(a.remainders) ? a.remainders : []) {
694
+ const remainder = factEntry(value);
695
+ if (remainder === undefined) continue;
696
+ const route = routeOf(remainder.provider, remainder.model, credential);
697
+ const key = `${index}:${route}`;
698
+ const sum = remainders.get(key) ?? [index, route, 0, 0, 0, 0, 0, 0];
699
+ remainder.counts.forEach((n, i) => {
700
+ sum[i + 2] = (sum[i + 2] ?? 0) + n;
701
+ });
702
+ remainders.set(key, sum);
703
+ }
704
+ for (const reason of Array.isArray(a.gaps) ? a.gaps : []) {
705
+ if (typeof reason === "string" && GAP_REASONS.has(reason)) {
706
+ gaps.push([index, attempt, reason]);
707
+ }
708
+ }
709
+ }
710
+ }
711
+ return {
712
+ ...facts,
713
+ ...(remainders.size === 0 ? {} : { remainders: [...remainders.values()] }),
714
+ ...(gaps.length === 0 ? {} : { gaps }),
715
+ };
630
716
  }
631
717
 
632
718
  // Reads findings.json and pipeline.json from a run directory. A missing or
@@ -39,11 +39,11 @@ import {
39
39
  } from "../model/profiles";
40
40
  // A sibling with no imports of its own, so the builtins-only rule still holds.
41
41
  import {
42
- PLATFORM_ESTIMATE_CAPABILITY,
43
- type PlatformEstimate,
44
- parsePlatformEstimate,
45
- serializePlatformEstimate,
46
- } from "./platform-estimate";
42
+ PLATFORM_LIMITS_CAPABILITY,
43
+ type PlatformLimits,
44
+ parsePlatformLimits,
45
+ serializePlatformLimits,
46
+ } from "./platform-limits";
47
47
 
48
48
  export const PLATFORM_API_URL = "https://api.crysk.dev";
49
49
 
@@ -52,11 +52,17 @@ export const PLATFORM_API_URL = "https://api.crysk.dev";
52
52
  // profile only to a run that names this capability.
53
53
  export const PLATFORM_PROFILE_CAPABILITY = "profile";
54
54
 
55
+ // platform-owned-cost T7 (L55): this engine applies the platform's limits. Only
56
+ // a run that names the capability gets `limits` in the token response: the
57
+ // per-review limit, what is left of the month's, and the platform's estimate.
58
+ // There is no capability for the usage facts any more: the report always
59
+ // carries them (src/ci/platform-report.ts).
60
+
55
61
  // What this engine reads from the `/runs/token` response, as the platform's
56
62
  // comma-separated `X-Crysk-Capabilities` list.
57
63
  export const PLATFORM_CAPABILITIES = [
58
- PLATFORM_ESTIMATE_CAPABILITY,
59
64
  PLATFORM_PROFILE_CAPABILITY,
65
+ PLATFORM_LIMITS_CAPABILITY,
60
66
  ].join(",");
61
67
 
62
68
  // The audience the platform verifies. An OIDC token minted for any other
@@ -174,8 +180,8 @@ export type PlatformTokenResult =
174
180
  // `full` or `metadata_only`; the connect step reads absence as metadata_only.
175
181
  // `traceContent` is present, and true, only when the platform sent exactly
176
182
  // `true`; the connect step reads absence as false.
177
- // `estimate` is present only for the first connect step (refresh steps do not
178
- // ask for one) and only when the platform sent a usable range.
183
+ // `limits` is present only for the first connect step (refresh steps do not
184
+ // ask for it) and only when the platform sent at least one usable number.
179
185
  | {
180
186
  ok: true;
181
187
  githubToken: string;
@@ -184,7 +190,7 @@ export type PlatformTokenResult =
184
190
  dataMode?: PlatformDataMode;
185
191
  traceContent?: true;
186
192
  config?: PlatformConfig;
187
- estimate?: PlatformEstimate;
193
+ limits?: PlatformLimits;
188
194
  command?: PlatformCommandAnswer;
189
195
  }
190
196
  // `message` names the HTTP status and the API's own `message` when there was
@@ -307,9 +313,9 @@ export async function exchangePlatformToken(
307
313
  headers: {
308
314
  Authorization: `Bearer ${oidc}`,
309
315
  "X-Crysk-Dispatch-Id": dispatchId,
310
- // Only the first connect step asks: its estimate is the one the budget
311
- // gate reads, the platform records each estimate it sends, and only
312
- // that step reads the config a profile arrives in.
316
+ // Only the first connect step asks: its limits are the ones the run
317
+ // step's gate reads, and only that step reads the config a profile
318
+ // arrives in.
313
319
  ...(deps.ignoreConfig === true
314
320
  ? {}
315
321
  : { "X-Crysk-Capabilities": PLATFORM_CAPABILITIES }),
@@ -330,7 +336,7 @@ export async function exchangePlatformToken(
330
336
  data_mode?: unknown;
331
337
  trace_content?: unknown;
332
338
  config?: unknown;
333
- estimate?: unknown;
339
+ limits?: unknown;
334
340
  command?: unknown;
335
341
  };
336
342
  const {
@@ -365,13 +371,11 @@ export async function exchangePlatformToken(
365
371
  [...secrets, githubToken, runToken],
366
372
  );
367
373
  }
368
- // An estimate is advice: one that does not parse is dropped and the
369
- // engine's own band decides, never a failed exchange.
374
+ // Limits are advice: ones that do not parse are dropped and the review
375
+ // runs, never a failed exchange.
370
376
  const command = parsePlatformCommand(body.command);
371
- const estimate =
372
- deps.ignoreConfig === true
373
- ? undefined
374
- : parsePlatformEstimate(body.estimate);
377
+ const limits =
378
+ deps.ignoreConfig === true ? undefined : parsePlatformLimits(body.limits);
375
379
  return {
376
380
  ok: true,
377
381
  githubToken,
@@ -387,7 +391,7 @@ export async function exchangePlatformToken(
387
391
  // an absent or malformed value sends metadata only.
388
392
  ...(body.trace_content === true ? { traceContent: true as const } : {}),
389
393
  ...(config.config === undefined ? {} : { config: config.config }),
390
- ...(estimate === undefined ? {} : { estimate }),
394
+ ...(limits === undefined ? {} : { limits }),
391
395
  ...(command === undefined ? {} : { command }),
392
396
  };
393
397
  } catch (error) {
@@ -504,12 +508,10 @@ export async function runPlatformConnect(
504
508
  }
505
509
  }
506
510
  }
507
- // Not a secret: two validated numbers and a basis. The run step's budget
508
- // gate reads it as CRYSK_PLATFORM_ESTIMATE in place of the engine's band.
509
- if (result.estimate !== undefined) {
510
- deps.appendOutput(
511
- `estimate=${serializePlatformEstimate(result.estimate)}\n`,
512
- );
511
+ // Not a secret: validated numbers (the limits, and the estimate split per
512
+ // role). The run step's limits gate reads it as CRYSK_PLATFORM_LIMITS.
513
+ if (result.limits !== undefined) {
514
+ deps.appendOutput(`limits=${serializePlatformLimits(result.limits)}\n`);
513
515
  }
514
516
  // Present only when there is configuration to apply: the setup step and the
515
517
  // run step are gated on it, so a standalone run (no platform step, no