crysk 0.0.0-stage → 0.3.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 (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +610 -2
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +82 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,469 @@
1
+ // §8 (docs/multi-runtime-model-diversity-design.md lines 426-463): usage
2
+ // normalization and inclusion semantics. Pure by design — no transport, no
3
+ // harness, no I/O; zero consumers yet (PR1a). Transports (PR2) will call the
4
+ // builders below to turn a provider's raw usage shape into the disjoint §8
5
+ // leaves; the harness will accumulate across attempts with
6
+ // `sumNormalizedUsage` and project the legacy flat shape at the
7
+ // `runPipeline` return boundary with `projectLegacyUsage`.
8
+
9
+ import type { SessionUsage } from "../usage";
10
+
11
+ export type UsageCompleteness = "complete" | "partial" | "unavailable";
12
+ // #182 follow-up: "free" is a USAGE-layer precision, not a capability mode.
13
+ // A free-declared route bills nothing, but a model free at probe time can flip
14
+ // to metered before/during the attempt — and the transport observes
15
+ // provider-reported cost per message (opencode-sdk.ts cashCostUsd,
16
+ // costSource "provider"). Stamping "subscription" would let
17
+ // `settlementFromUsage`'s free-nonzero rule (spend-limiter.ts) never fire and
18
+ // settle a flipped attempt's priced cost as a truthful zero. Capability
19
+ // `BillingMode` ("subscription"|"metered") stays binary on purpose: the exact
20
+ // binding still reports a free route as subscription/not_applicable, and the
21
+ // spend ledger is composed for it by credential kind (production-runtime.ts).
22
+ export type UsageBillingMode = "subscription" | "metered" | "free" | "unknown";
23
+ export type UsageCostSource =
24
+ | "provider"
25
+ | "versioned_rate_table"
26
+ | "subscription"
27
+ | "unknown";
28
+
29
+ // 2026-09-02, #177. THE one place that says "this environment carries a
30
+ // per-token credential". Two callers need it and they must not each carry
31
+ // their own copy: `deriveCiBillingMode` (ci/gates.ts) turns it into a CI spend
32
+ // ceiling, and the Claude CLI transport turns it into the `billingMode`
33
+ // STAMPED ON EVERY USAGE RECORD it emits. This is the same anti-drift shape
34
+ // `credentialKindBillsMetered` (runner-authority.ts) already applies to the
35
+ // credential KIND, and for the same measured reason: #177 IS the drift. The CI
36
+ // gate already called an API-key route metered while the transport filed that
37
+ // user's real spend as `notionalCostUsd`, which renders as "at list price, not
38
+ // charged" — and since budget enforcement is cash-only (§8), that user's spend
39
+ // ceiling read $0 and stopped existing.
40
+ //
41
+ // A boolean, not a mode, matching its sibling: the two callers narrow it into
42
+ // two DIFFERENT enums (`CiBillingMode`, `UsageBillingMode`), and returning a
43
+ // mode here would invite one of them to overwrite the other's semantics
44
+ // instead of asking the question this answers.
45
+ //
46
+ // WHICH variables, and why these two: `ENV_PASSTHROUGH` (harness.ts) projects
47
+ // ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN into the child side by side as
48
+ // one credential class — a per-token key and a per-token bearer token.
49
+ // CLAUDE_CODE_OAUTH_TOKEN is deliberately absent: that IS the subscription.
50
+ // 2026-09-02: "projects into the child" holds only where no credential
51
+ // projection is active. When one IS, `buildChildEnv` strips both keys
52
+ // (PROJECTION_OWNED_KEYS, harness.ts) because the projection owns the
53
+ // credential, so this predicate reads subscription on that path — which is
54
+ // the truth there, and was not before the strip.
55
+ // When an OAuth token and a key are both present this repo does not know which
56
+ // one the Claude CLI bills (ci/gates.ts states that gap at length), and does
57
+ // not need to — presence of a key answers metered, because guessing
58
+ // subscription wrongly reports real money as not charged.
59
+ //
60
+ // Trimming is load-bearing, and it is worth being exact about WHAT it buys,
61
+ // because the sentence it replaces overstated it and #177 is a finding about
62
+ // comments claiming more than their code. action.yml:111 binds
63
+ // ANTHROPIC_API_KEY UNCONDITIONALLY and GitHub renders an unset input as the
64
+ // empty string, so every subscription-route CI run carries
65
+ // `ANTHROPIC_API_KEY=""` — but `""` is already falsy, so that case is safe
66
+ // with or without the trim. What the trim actually catches is a
67
+ // WHITESPACE-ONLY value (a secret whose content is a space, a YAML block
68
+ // scalar that kept its newline), which is truthy and would otherwise read as
69
+ // a live key and impose a ceiling — or, here, book a subscription run's quota
70
+ // spend as cash. Mutation-checked: dropping the trim flips exactly the
71
+ // whitespace arms, never the empty-string ones.
72
+ //
73
+ // ---------------------------------------------------------------------------
74
+ // ADMISSION WIRING, #161. This predicate now has a SECOND caller:
75
+ // `credentialKindForRoute` (runner-authority.ts) — the single place that
76
+ // decides which credential a claude-code route runs on, and therefore its
77
+ // projection, its broker, and its rate-limit bucket. Until #161 this block
78
+ // banned exactly that wiring outright; read both halves below before adding
79
+ // a THIRD caller, because the ban is lifted for exactly one function, not
80
+ // for the question in general.
81
+ //
82
+ // Until #197 the reason was safety: deriving either side from env turned a
83
+ // metered claude-code route into `pricingApplicability: "required"` with no
84
+ // pricing source to answer, so the route was refused admission outright
85
+ // (`pricing_table_missing`, blocking) and API-key users stopped being able to
86
+ // run at all. #197 flipped the claude-code transport's `pricingReady` to
87
+ // `true`, so that refusal can no longer happen and the fail-closed argument
88
+ // is spent.
89
+ //
90
+ // What remained was ownership, and #161 settles it by NAMING the owner
91
+ // instead of banning the wiring outright: `credentialKindForRoute` is the
92
+ // one admission-side reader of this predicate, and `envBillsMetered` is the
93
+ // one shared implementation both it and the Claude CLI transport's
94
+ // `claudeCliCostBasis` call — never two copies of the same trim rule
95
+ // answering "does this environment carry a per-token credential?"
96
+ // differently for the same attempt.
97
+ //
98
+ // The two calls read DIFFERENT env values on purpose, and on a SUCCESSFUL
99
+ // projection that is not a fork: `claudeCliCostBasis` reads the child's
100
+ // ACTUAL, POST-projection-strip env (`request.isolation.env`) — a successful
101
+ // projection strips the key-bearing vars (`PROJECTION_OWNED_KEYS`,
102
+ // harness.ts), so this is a truthful read of what the process the money was
103
+ // spent by actually saw. `credentialKindForRoute` runs BEFORE any child
104
+ // exists, so it cannot read that env — it reads the raw, pre-strip one plus
105
+ // whether a broker WILL ATTEMPT to strip it (`hasBroker`), and
106
+ // `!hasBroker && envBillsMetered(rawEnv)` equals `envBillsMetered(postStripEnv)`
107
+ // on that path: a successful strip removes the key whenever a broker is
108
+ // attached, and the post-strip env equals the raw env exactly when none is.
109
+ // Same predicate, same answer, two different envs because one runs before
110
+ // the strip and one runs after it.
111
+ //
112
+ // KNOWN EXCEPTION — #279 (fixed 2026-09-24, option 2). A broker's projection
113
+ // can DEGRADE (`missing_subscription_record`, credential-broker.ts +
114
+ // harness.ts ~756-778) instead of stripping anything: the child then runs
115
+ // UNSTRIPPED, so `hasBroker: true` no longer implies "the child's env has no
116
+ // key" — admission still says subscription (this function's answer is
117
+ // deliberately left unchanged; it cannot see a runtime degrade), and
118
+ // `claudeCliCostBasis` (reading the real, unstripped child env) correctly
119
+ // files it metered. That disagreement between admission and filing is
120
+ // permanent by design — but the spend it describes is no longer
121
+ // unaccounted for: `StepExecutionHarness.run` (harness.ts) recognizes its
122
+ // own degraded projection and applies THIS SAME `envBillsMetered` predicate
123
+ // to the SAME child env to open a spend-ledger reservation for that one
124
+ // attempt, settling or fencing it exactly like a metered route. Pre-existing:
125
+ // this exact admission/filing mismatch already existed for every degraded
126
+ // projection before #161, which named the ownership rule but did not add or
127
+ // remove this exception; #279's fix lives in the harness, not here.
128
+ //
129
+ // Everything downstream of the KIND (the projection, the bucket, and
130
+ // `FrozenRuntimeBinding.capabilities()`'s `effectiveBillingMode` via
131
+ // `credentialKindBillsMetered`) inherits the answer from that one call and
132
+ // never re-reads env itself — so admission and usage filing agree by
133
+ // construction on a successful projection, #279 aside.
134
+ //
135
+ // The ban stands for everyone ELSE. `CLAUDE_CAPABILITY_STATICS.billingMode`
136
+ // (model/provider-capabilities.ts) stays a static "subscription" on purpose —
137
+ // it is the BACKEND-WIDE report, produced before any route (and therefore any
138
+ // credential) resolves, so it has no per-route env to read honestly; the
139
+ // per-route truth lives on the exact binding instead. A THIRD caller
140
+ // deriving straight from env, instead of going through
141
+ // `credentialKindForRoute`, is exactly the fork this predicate exists to
142
+ // prevent — route it through the kind instead.
143
+ // ---------------------------------------------------------------------------
144
+ export function envBillsMetered(
145
+ env: Readonly<Record<string, string | undefined>>,
146
+ ): boolean {
147
+ return METERED_CREDENTIAL_ENV.some((name) => Boolean(env[name]?.trim()));
148
+ }
149
+
150
+ // The per-token credential variables, in the order the CLI prefers them. The one list
151
+ // envBillsMetered reads and the failure-credential naming of the Claude transport reads,
152
+ // so a variable that bills as metered is also a variable a failure can name.
153
+ export const METERED_CREDENTIAL_ENV = [
154
+ "ANTHROPIC_API_KEY",
155
+ "ANTHROPIC_AUTH_TOKEN",
156
+ ] as const;
157
+
158
+ // §8 lines 429-450, verbatim field names (camelCase — the legacy flat shape
159
+ // keeps its own snake_case names; `projectLegacyUsage` below is the ONLY
160
+ // bridge between the two, per the "coexistence, not rename" design decision).
161
+ export interface NormalizedTokens {
162
+ readonly inputUncached?: number;
163
+ readonly inputCacheRead?: number;
164
+ readonly inputCacheWrite?: number;
165
+ readonly inputOther?: number;
166
+ readonly outputVisible?: number;
167
+ readonly outputReasoning?: number;
168
+ readonly outputOther?: number;
169
+ readonly inputKnown?: number;
170
+ readonly outputKnown?: number;
171
+ readonly totalKnown?: number;
172
+ readonly providerReportedTotal?: number;
173
+ }
174
+
175
+ export interface NormalizedUsage {
176
+ readonly wallMs: number;
177
+ readonly tokens: NormalizedTokens;
178
+ readonly completeness: UsageCompleteness;
179
+ readonly billingMode: UsageBillingMode;
180
+ readonly cashCostUsd?: number;
181
+ readonly notionalCostUsd?: number;
182
+ readonly costSource: UsageCostSource;
183
+ readonly redactedRaw?: unknown;
184
+ }
185
+
186
+ interface UsageCostInput {
187
+ readonly billingMode: UsageBillingMode;
188
+ readonly costSource: UsageCostSource;
189
+ readonly cashCostUsd?: number;
190
+ readonly notionalCostUsd?: number;
191
+ }
192
+
193
+ function sumOrZero(...values: ReadonlyArray<number | undefined>): number {
194
+ return values.reduce<number>((total, v) => total + (v ?? 0), 0);
195
+ }
196
+
197
+ function sumIfAnyDefined(
198
+ ...values: ReadonlyArray<number | undefined>
199
+ ): number | undefined {
200
+ return values.every((v) => v === undefined)
201
+ ? undefined
202
+ : sumOrZero(...values);
203
+ }
204
+
205
+ function attemptTotalKnown(tokens: NormalizedTokens): number | undefined {
206
+ return tokens.totalKnown ?? tokens.providerReportedTotal;
207
+ }
208
+
209
+ // 2026-09-02: "did this attempt produce output tokens?", answered from the
210
+ // LEAVES and not from `outputKnown` alone. `outputKnown` is a rollup some
211
+ // builders populate (`normalizeInclusiveUsage`, the OpenCode transport) and
212
+ // others do not, so a reader that consulted it alone would let a transport
213
+ // filling only `outputVisible` slip past — deciding an accounting question by
214
+ // which fields a transport happens to set rather than by whether tokens were
215
+ // produced. The §8 output leaves are disjoint by contract, so summing them is
216
+ // not double counting. One consumer today: `settlementFromUsage`'s
217
+ // metered-zero rule (spend-limiter.ts).
218
+ export function outputTokensKnown(
219
+ tokens: NormalizedTokens,
220
+ ): number | undefined {
221
+ return (
222
+ tokens.outputKnown ??
223
+ sumIfAnyDefined(
224
+ tokens.outputVisible,
225
+ tokens.outputReasoning,
226
+ tokens.outputOther,
227
+ )
228
+ );
229
+ }
230
+
231
+ // §8 line 455: "If a provider total includes detailed cache/reasoning
232
+ // values, split the total into leaves and store only the non-negative
233
+ // residual in inputOther/outputOther; never add the detail to the inclusive
234
+ // total." OpenAI's `prompt_tokens`/`completion_tokens` are this shape — the
235
+ // detail fields are a SUBSET of the total, never additional to it.
236
+ export interface InclusiveUsageInput extends UsageCostInput {
237
+ readonly wallMs: number;
238
+ readonly inputTotal: number;
239
+ readonly inputCacheRead?: number;
240
+ readonly inputCacheWrite?: number;
241
+ readonly outputTotal: number;
242
+ readonly outputReasoning?: number;
243
+ }
244
+
245
+ export function normalizeInclusiveUsage(
246
+ input: InclusiveUsageInput,
247
+ ): NormalizedUsage {
248
+ const inputOther = Math.max(
249
+ 0,
250
+ input.inputTotal - sumOrZero(input.inputCacheRead, input.inputCacheWrite),
251
+ );
252
+ const outputOther = Math.max(
253
+ 0,
254
+ input.outputTotal - sumOrZero(input.outputReasoning),
255
+ );
256
+ return {
257
+ wallMs: input.wallMs,
258
+ tokens: {
259
+ inputCacheRead: input.inputCacheRead,
260
+ inputCacheWrite: input.inputCacheWrite,
261
+ inputOther,
262
+ outputReasoning: input.outputReasoning,
263
+ outputOther,
264
+ inputKnown: input.inputTotal,
265
+ outputKnown: input.outputTotal,
266
+ totalKnown: input.inputTotal + input.outputTotal,
267
+ providerReportedTotal: input.inputTotal + input.outputTotal,
268
+ },
269
+ completeness: "complete",
270
+ billingMode: input.billingMode,
271
+ costSource: input.costSource,
272
+ cashCostUsd: input.cashCostUsd,
273
+ notionalCostUsd: input.notionalCostUsd,
274
+ };
275
+ }
276
+
277
+ // §8 line 457: "If inclusion cannot be proven, keep providerReportedTotal,
278
+ // mark partial, and do not invent a split." No leaf field is populated here
279
+ // — inventing one would resurrect the exact "$0 on parse failure" collapse
280
+ // this slice exists to kill, just with a fabricated split instead of a
281
+ // fabricated zero.
282
+ export interface PartialUsageInput extends UsageCostInput {
283
+ readonly wallMs: number;
284
+ readonly providerReportedTotal: number;
285
+ }
286
+
287
+ export function normalizePartialUsage(
288
+ input: PartialUsageInput,
289
+ ): NormalizedUsage {
290
+ return {
291
+ wallMs: input.wallMs,
292
+ tokens: { providerReportedTotal: input.providerReportedTotal },
293
+ completeness: "partial",
294
+ billingMode: input.billingMode,
295
+ costSource: input.costSource,
296
+ cashCostUsd: input.cashCostUsd,
297
+ notionalCostUsd: input.notionalCostUsd,
298
+ };
299
+ }
300
+
301
+ // spec: "Parse Failure Yields Unavailable Completeness, Never Zero Cost" —
302
+ // used when nothing about an attempt's usage can be trusted (corrupted
303
+ // stdout, a dropped final usage chunk, a safety-blocked response with no
304
+ // usage block at all). No leaf, cost, or total field is ever populated as a
305
+ // fabricated zero; billingMode/costSource fall back to "unknown" rather
306
+ // than guessing which one applied.
307
+ export interface UnavailableUsageInput {
308
+ readonly wallMs: number;
309
+ readonly billingMode?: UsageBillingMode;
310
+ }
311
+
312
+ export function normalizeUnavailableUsage(
313
+ input: UnavailableUsageInput,
314
+ ): NormalizedUsage {
315
+ return {
316
+ wallMs: input.wallMs,
317
+ tokens: {},
318
+ completeness: "unavailable",
319
+ billingMode: input.billingMode ?? "unknown",
320
+ costSource: "unknown",
321
+ };
322
+ }
323
+
324
+ const COMPLETENESS_RANK: Record<UsageCompleteness, number> = {
325
+ complete: 0,
326
+ partial: 1,
327
+ unavailable: 2,
328
+ };
329
+
330
+ function worseCompleteness(
331
+ a: UsageCompleteness,
332
+ b: UsageCompleteness,
333
+ ): UsageCompleteness {
334
+ return COMPLETENESS_RANK[a] >= COMPLETENESS_RANK[b] ? a : b;
335
+ }
336
+
337
+ // Accumulates two attempts' usage within one step. A failed attempt's tokens
338
+ // still cost money (ported rationale from `sumUsage` in `src/usage.ts`), so
339
+ // this sums, never replaces. Cash and notional accumulate independently
340
+ // (spec: "Cash And Notional Cost Stay Separate") — neither is ever read to
341
+ // derive the other. billingMode/costSource fall back to "unknown" on
342
+ // disagreement between attempts rather than guessing which one is right.
343
+ export function sumNormalizedUsage(
344
+ a: NormalizedUsage,
345
+ b: NormalizedUsage,
346
+ ): NormalizedUsage {
347
+ return {
348
+ wallMs: a.wallMs + b.wallMs,
349
+ tokens: {
350
+ inputUncached: sumIfAnyDefined(
351
+ a.tokens.inputUncached,
352
+ b.tokens.inputUncached,
353
+ ),
354
+ inputCacheRead: sumIfAnyDefined(
355
+ a.tokens.inputCacheRead,
356
+ b.tokens.inputCacheRead,
357
+ ),
358
+ inputCacheWrite: sumIfAnyDefined(
359
+ a.tokens.inputCacheWrite,
360
+ b.tokens.inputCacheWrite,
361
+ ),
362
+ inputOther: sumIfAnyDefined(a.tokens.inputOther, b.tokens.inputOther),
363
+ outputVisible: sumIfAnyDefined(
364
+ a.tokens.outputVisible,
365
+ b.tokens.outputVisible,
366
+ ),
367
+ outputReasoning: sumIfAnyDefined(
368
+ a.tokens.outputReasoning,
369
+ b.tokens.outputReasoning,
370
+ ),
371
+ outputOther: sumIfAnyDefined(a.tokens.outputOther, b.tokens.outputOther),
372
+ inputKnown: sumIfAnyDefined(a.tokens.inputKnown, b.tokens.inputKnown),
373
+ outputKnown: sumIfAnyDefined(a.tokens.outputKnown, b.tokens.outputKnown),
374
+ totalKnown: sumIfAnyDefined(
375
+ attemptTotalKnown(a.tokens),
376
+ attemptTotalKnown(b.tokens),
377
+ ),
378
+ providerReportedTotal: sumIfAnyDefined(
379
+ a.tokens.providerReportedTotal,
380
+ b.tokens.providerReportedTotal,
381
+ ),
382
+ },
383
+ completeness: worseCompleteness(a.completeness, b.completeness),
384
+ billingMode: a.billingMode === b.billingMode ? a.billingMode : "unknown",
385
+ costSource: a.costSource === b.costSource ? a.costSource : "unknown",
386
+ cashCostUsd: sumIfAnyDefined(a.cashCostUsd, b.cashCostUsd),
387
+ notionalCostUsd: sumIfAnyDefined(a.notionalCostUsd, b.notionalCostUsd),
388
+ };
389
+ }
390
+
391
+ // §4.1 line 195: "The first usage event fixes the attempt's aggregation
392
+ // mode. snapshot replaces the current provider snapshot; delta adds disjoint
393
+ // increments. A later mode change is protocol_mismatch." This reducer is the
394
+ // pure state machine PR2's transports will fold provider usage events
395
+ // through — a mode change throws rather than silently mixing.
396
+ export type UsageUpdateMode = "snapshot" | "delta";
397
+
398
+ export class UsageModeMismatchError extends Error {
399
+ readonly attemptMode: UsageUpdateMode;
400
+ readonly incomingMode: UsageUpdateMode;
401
+
402
+ constructor(attemptMode: UsageUpdateMode, incomingMode: UsageUpdateMode) {
403
+ super(
404
+ `usage event mode mismatch: attempt started as "${attemptMode}", received "${incomingMode}"`,
405
+ );
406
+ this.name = "UsageModeMismatchError";
407
+ this.attemptMode = attemptMode;
408
+ this.incomingMode = incomingMode;
409
+ }
410
+ }
411
+
412
+ export interface UsageModeState {
413
+ readonly mode: UsageUpdateMode;
414
+ readonly tokens: Partial<NormalizedTokens>;
415
+ }
416
+
417
+ export function applyUsageUpdate(
418
+ state: UsageModeState | undefined,
419
+ mode: UsageUpdateMode,
420
+ update: Partial<NormalizedTokens>,
421
+ ): UsageModeState {
422
+ if (state !== undefined && state.mode !== mode) {
423
+ throw new UsageModeMismatchError(state.mode, mode);
424
+ }
425
+ if (mode === "snapshot") {
426
+ return { mode, tokens: { ...update } };
427
+ }
428
+ const merged: Record<string, number> = { ...(state?.tokens ?? {}) };
429
+ for (const [key, value] of Object.entries(update)) {
430
+ if (typeof value === "number") {
431
+ merged[key] = (merged[key] ?? 0) + value;
432
+ }
433
+ }
434
+ return { mode, tokens: merged as Partial<NormalizedTokens> };
435
+ }
436
+
437
+ // spec: "Legacy Usage Projection At The Published Boundary" — the ONLY place
438
+ // NormalizedUsage becomes the legacy flat shape. Field names are copied
439
+ // verbatim from `SessionUsage` (src/usage.ts) because
440
+ // `../deep-review/runner/telemetry.ts` reads them by name off `runPipeline`'s
441
+ // returned `usage` object; a rename there would zero the bench ledger
442
+ // silently. When the input/output split is unknown (partial usage), the
443
+ // total is preserved but the split is honestly reported as 0 rather than
444
+ // invented.
445
+ export function projectLegacyUsage(usage: NormalizedUsage): SessionUsage {
446
+ const t = usage.tokens;
447
+ const tokens_in =
448
+ t.inputKnown ??
449
+ sumIfAnyDefined(
450
+ t.inputUncached,
451
+ t.inputCacheRead,
452
+ t.inputCacheWrite,
453
+ t.inputOther,
454
+ ) ??
455
+ 0;
456
+ const tokens_out =
457
+ t.outputKnown ??
458
+ sumIfAnyDefined(t.outputVisible, t.outputReasoning, t.outputOther) ??
459
+ 0;
460
+ const tokens_total =
461
+ t.totalKnown ?? t.providerReportedTotal ?? tokens_in + tokens_out;
462
+ return {
463
+ wall_ms: usage.wallMs,
464
+ tokens_in,
465
+ tokens_out,
466
+ tokens_total,
467
+ cost_usd_est: usage.cashCostUsd ?? 0,
468
+ };
469
+ }