crysk 0.0.0 → 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 +609 -3
  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 +81 -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,350 @@
1
+ // Durable CI admission attempt ledger (WU-02): pure reserve/settle/idempotency.
2
+ // Persistence is GitHub Check Runs (pr/pr.ts); PR comments stay presentation-only.
3
+
4
+ import { createHash } from "node:crypto";
5
+ import { ADMISSION_CHECK_RUN_NAME } from "../brand";
6
+
7
+ export const ADMISSION_LEDGER_SCHEMA_VERSION = 1;
8
+ // Written under the new name; the ledger's readers (pr/pr.ts) also accept the
9
+ // legacy name, see brand.ts.
10
+ export { ADMISSION_CHECK_RUN_NAME };
11
+
12
+ // `"yielded"`: this run stood down because another pr-hero review already
13
+ // held a pending commit status on the same head (musive #1935: a local hook
14
+ // review was running when CI started). It is terminal, never re-settled, and
15
+ // spends no attempt. Older engines read it through parseAdmissionRecord's
16
+ // open string status as neither budget-counting nor active, which is the
17
+ // same answer, so no schema bump is needed.
18
+ export type AdmissionAttemptStatus =
19
+ | "reserved"
20
+ | "provider-started"
21
+ | "completed"
22
+ | "skipped"
23
+ | "failed"
24
+ | "cancelled"
25
+ | "yielded"
26
+ // #326: a size or budget gate skip. Terminal, and it spends nothing (see
27
+ // TERMINAL_BUDGET_STATUSES). An older engine reads it as an unknown string
28
+ // status, which is neither budget-counting nor active: the same answer as
29
+ // `"yielded"` above, so no schema bump either.
30
+ | "gate-skipped"
31
+ | "unknown";
32
+
33
+ export interface AdmissionRecord {
34
+ schemaVersion: 1;
35
+ prNumber: number;
36
+ headSha: string;
37
+ policyHash: string;
38
+ reservationId: string;
39
+ attemptNumber: number;
40
+ status: AdmissionAttemptStatus;
41
+ decisionReason: string;
42
+ priorScore: number | null;
43
+ blockingCount: number | null;
44
+ advisoryCount: number | null;
45
+ workflowRunId: string | null;
46
+ createdAt: string;
47
+ settledAt: string | null;
48
+ // WHY a flag and not decisionReason: settleAdmissionAttempt overwrites
49
+ // decisionReason at every settle, so a forced run's reason is gone by the
50
+ // time a count reads the row. Absent on an automatic row, so every row
51
+ // written before this field existed reads as automatic.
52
+ forced?: true;
53
+ // WHY a per-POST nonce: a reserve POST whose gh call timed out may have
54
+ // created a run GitHub accepted. The nonce is minted once per upsert call and
55
+ // written into that run's record, so a lookup can name exactly the run this
56
+ // call created. Absent on every row written before this field existed, and
57
+ // such a row never matches a lookup.
58
+ postNonce?: string;
59
+ }
60
+
61
+ // #164, Juanma 2026-09-01: a cancelled run posted nothing, so it must not
62
+ // spend one of the PR's review attempts. `"cancelled"` stays a real status
63
+ // (the signal handler settles to it) and stays OUT of this set. Putting it
64
+ // back would make the settlement a no-op on the budget half of the issue.
65
+ // `"provider-started"` stays in: a record still armed that way is a run that
66
+ // never settled, and counting it is what makes an abandoned reservation
67
+ // visible until the handler writes `"cancelled"`.
68
+ // `"yielded"` stays out for the same reason as `"cancelled"`: the run spent
69
+ // nothing and reviewed nothing. The review that DID run on this head is
70
+ // counted where it records itself (its own ledger row in CI, or the summary
71
+ // comment's state block for a local review). Counting the yield as well
72
+ // would charge the PR twice for one review and exhaust the budget early.
73
+ // #326: a SIZE or BUDGET gate skip stands down the same way, so it settles as
74
+ // `"gate-skipped"`, and that stays out too. It used to settle as `"skipped"`,
75
+ // which is in this set (admission skips keep it on purpose), so every gate
76
+ // skip spent an attempt. The workflow-heads leg then counted that head a second
77
+ // time, and a PR with one review run reported "2/2 attempts" (#326).
78
+ // A forced row (`forced: true`, a `/crysk review` or `/crysk recheck`
79
+ // comment) is excluded whatever its status: the budget bounds AUTOMATIC reviews,
80
+ // and a writer's explicit comment is a deliberate spend outside it. The filter
81
+ // is in countTerminalAttempts, not in this set, because a forced `completed`
82
+ // row is still a real completed review.
83
+ const TERMINAL_BUDGET_STATUSES: ReadonlySet<AdmissionAttemptStatus> = new Set([
84
+ "completed",
85
+ "failed",
86
+ "provider-started",
87
+ "skipped",
88
+ ]);
89
+
90
+ // #326, workflow-run leg: a head leaves the attempt count only when EVERY
91
+ // ledger row on it is in this allowlist, because each listed status is written
92
+ // BEFORE any provider spend, so it proves the run spent nothing:
93
+ // - `"gate-skipped"`: settleCiGateSkip (pr/admission.ts:152) runs from the size
94
+ // gate (pr/review-pr.ts:312) and the budget gate (pr/plan.ts:153, reached from
95
+ // pr/review-pr.ts:401). Both come before the `"provider-started"` settle at
96
+ // pr/review-pr.ts:516.
97
+ // - `"gate-skipped"` also comes from recordCiConfigErrorSkip (pr/ci-admission-gate.ts),
98
+ // called from the pre-reservation catch in pr/review-pr.ts when gotchas or the
99
+ // prompt set is misconfigured. It runs before any reservation or provider call.
100
+ // - `"yielded"`: written only by yieldToInFlightReview (pr/ci-admission-gate.ts:380),
101
+ // whose sole caller is pr/review-pr.ts:359, again before the `"provider-started"`
102
+ // settle at pr/review-pr.ts:516.
103
+ // `"cancelled"` is excluded on purpose, because it can be written AFTER spend:
104
+ // settleHeldAdmissionLedgerOnSignal (pr/admission.ts:123) writes it over a
105
+ // `"provider-started"` row when cli.ts:287 or cli.ts:299 handles a SIGTERM or
106
+ // SIGINT, and by then hunters may already have run. A job killed by
107
+ // `timeout-minutes` concludes `failure`, so its head stays counted. The
108
+ // ledger-row count still ignores `"cancelled"` (see TERMINAL_BUDGET_STATUSES,
109
+ // #164). That decision stands. This list does not widen it.
110
+ // `"reserved"` is deliberately absent. The `"provider-started"` settle runs
111
+ // before runPipeline and is best-effort (tryPersistCiAdmissionLedger swallows a
112
+ // write error), so a run killed after that write failed still sits at
113
+ // `"reserved"` although it may have spent provider tokens. The run list counted
114
+ // that head before #326 and must keep counting it. Any unknown status also stays
115
+ // out, so the rule fails closed.
116
+ export const PROVABLY_UNSPENT_STATUSES: ReadonlySet<AdmissionAttemptStatus> =
117
+ new Set(["gate-skipped", "yielded"]);
118
+
119
+ const ACTIVE_RESERVATION_STATUSES: ReadonlySet<AdmissionAttemptStatus> =
120
+ new Set(["reserved", "provider-started"]);
121
+
122
+ export function admissionRecordFingerprint(
123
+ prNumber: number,
124
+ headSha: string,
125
+ policyHash: string,
126
+ ): string {
127
+ const canonical = `${prNumber}:${headSha}:${policyHash}`;
128
+ return createHash("sha256").update(canonical).digest("hex").slice(0, 16);
129
+ }
130
+
131
+ export function parseAdmissionRecord(text: string): AdmissionRecord | null {
132
+ const trimmed = text.trim();
133
+ if (trimmed.length === 0) return null;
134
+ try {
135
+ const parsed = JSON.parse(trimmed) as Partial<AdmissionRecord>;
136
+ if (
137
+ parsed.schemaVersion !== ADMISSION_LEDGER_SCHEMA_VERSION ||
138
+ typeof parsed.prNumber !== "number" ||
139
+ typeof parsed.headSha !== "string" ||
140
+ typeof parsed.policyHash !== "string" ||
141
+ typeof parsed.reservationId !== "string" ||
142
+ typeof parsed.attemptNumber !== "number" ||
143
+ typeof parsed.status !== "string" ||
144
+ typeof parsed.decisionReason !== "string" ||
145
+ typeof parsed.createdAt !== "string"
146
+ ) {
147
+ return null;
148
+ }
149
+ return {
150
+ schemaVersion: 1,
151
+ prNumber: parsed.prNumber,
152
+ headSha: parsed.headSha,
153
+ policyHash: parsed.policyHash,
154
+ reservationId: parsed.reservationId,
155
+ attemptNumber: parsed.attemptNumber,
156
+ status: parsed.status as AdmissionAttemptStatus,
157
+ decisionReason: parsed.decisionReason,
158
+ priorScore:
159
+ parsed.priorScore === null || typeof parsed.priorScore === "number"
160
+ ? (parsed.priorScore ?? null)
161
+ : null,
162
+ blockingCount:
163
+ parsed.blockingCount === null ||
164
+ typeof parsed.blockingCount === "number"
165
+ ? (parsed.blockingCount ?? null)
166
+ : null,
167
+ advisoryCount:
168
+ parsed.advisoryCount === null ||
169
+ typeof parsed.advisoryCount === "number"
170
+ ? (parsed.advisoryCount ?? null)
171
+ : null,
172
+ workflowRunId:
173
+ parsed.workflowRunId === null ||
174
+ typeof parsed.workflowRunId === "string"
175
+ ? (parsed.workflowRunId ?? null)
176
+ : null,
177
+ createdAt: parsed.createdAt,
178
+ settledAt:
179
+ parsed.settledAt === null || typeof parsed.settledAt === "string"
180
+ ? (parsed.settledAt ?? null)
181
+ : null,
182
+ ...(parsed.forced === true ? { forced: true as const } : {}),
183
+ ...(typeof parsed.postNonce === "string"
184
+ ? { postNonce: parsed.postNonce }
185
+ : {}),
186
+ };
187
+ } catch {
188
+ return null;
189
+ }
190
+ }
191
+
192
+ export function serializeAdmissionRecord(record: AdmissionRecord): string {
193
+ return JSON.stringify(record);
194
+ }
195
+
196
+ export function countTerminalAttempts(
197
+ records: readonly AdmissionRecord[],
198
+ ): number {
199
+ return records.filter(
200
+ (record) =>
201
+ record.forced !== true && TERMINAL_BUDGET_STATUSES.has(record.status),
202
+ ).length;
203
+ }
204
+
205
+ function recordsForFingerprint(
206
+ records: readonly AdmissionRecord[],
207
+ prNumber: number,
208
+ headSha: string,
209
+ policyHash: string,
210
+ ): AdmissionRecord[] {
211
+ const reservationId = admissionRecordFingerprint(
212
+ prNumber,
213
+ headSha,
214
+ policyHash,
215
+ );
216
+ return records.filter(
217
+ (record) =>
218
+ record.prNumber === prNumber &&
219
+ record.headSha === headSha &&
220
+ record.policyHash === policyHash &&
221
+ record.reservationId === reservationId,
222
+ );
223
+ }
224
+
225
+ function nextAttemptNumber(records: readonly AdmissionRecord[]): number {
226
+ let max = 0;
227
+ for (const record of records) {
228
+ if (record.attemptNumber > max) max = record.attemptNumber;
229
+ }
230
+ return max + 1;
231
+ }
232
+
233
+ export function isReservationStale(
234
+ record: AdmissionRecord,
235
+ ttlSeconds: number,
236
+ now: Date = new Date(),
237
+ ): boolean {
238
+ if (record.status !== "reserved") return false;
239
+ const createdMs = Date.parse(record.createdAt);
240
+ if (Number.isNaN(createdMs)) return true;
241
+ const ageSeconds = (now.getTime() - createdMs) / 1000;
242
+ return ageSeconds > ttlSeconds;
243
+ }
244
+
245
+ export function selectActiveReservation(
246
+ records: readonly AdmissionRecord[],
247
+ headSha: string,
248
+ policyHash: string,
249
+ ttlSeconds: number,
250
+ now?: Date,
251
+ ): AdmissionRecord | null {
252
+ const matches = records
253
+ .filter(
254
+ (record) =>
255
+ record.headSha === headSha &&
256
+ record.policyHash === policyHash &&
257
+ ACTIVE_RESERVATION_STATUSES.has(record.status),
258
+ )
259
+ .sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
260
+ for (const record of matches) {
261
+ if (
262
+ record.status === "reserved" &&
263
+ isReservationStale(record, ttlSeconds, now)
264
+ ) {
265
+ continue;
266
+ }
267
+ return record;
268
+ }
269
+ return null;
270
+ }
271
+
272
+ export function reserveAdmissionAttempt(input: {
273
+ existing: readonly AdmissionRecord[];
274
+ prNumber: number;
275
+ headSha: string;
276
+ policyHash: string;
277
+ workflowRunId?: string | null;
278
+ now?: Date;
279
+ decisionReason?: string;
280
+ priorScore?: number | null;
281
+ blockingCount?: number | null;
282
+ advisoryCount?: number | null;
283
+ reservationTtlSeconds: number;
284
+ forced?: boolean;
285
+ }): { record: AdmissionRecord; created: boolean } {
286
+ const now = input.now ?? new Date();
287
+ const active = selectActiveReservation(
288
+ input.existing,
289
+ input.headSha,
290
+ input.policyHash,
291
+ input.reservationTtlSeconds,
292
+ now,
293
+ );
294
+ // WHY an active row is reused only when its kind matches the caller's: a
295
+ // forced caller may take over an active AUTOMATIC row, and the run settles it
296
+ // as automatic (a forced run that races an in-flight automatic run is counted
297
+ // as that automatic run; accepted, the active row belongs to a run already
298
+ // in progress). An AUTOMATIC caller never takes over a FORCED row: that row
299
+ // would carry `forced: true` through every settle, and countTerminalAttempts
300
+ // would then drop the automatic run's own spend. So the automatic caller
301
+ // creates its own row beside it instead.
302
+ if (active !== null && !(input.forced !== true && active.forced === true)) {
303
+ return { record: active, created: false };
304
+ }
305
+
306
+ const scoped = recordsForFingerprint(
307
+ input.existing,
308
+ input.prNumber,
309
+ input.headSha,
310
+ input.policyHash,
311
+ );
312
+ const reservationId = admissionRecordFingerprint(
313
+ input.prNumber,
314
+ input.headSha,
315
+ input.policyHash,
316
+ );
317
+ const record: AdmissionRecord = {
318
+ schemaVersion: 1,
319
+ prNumber: input.prNumber,
320
+ headSha: input.headSha,
321
+ policyHash: input.policyHash,
322
+ reservationId,
323
+ attemptNumber: nextAttemptNumber(scoped),
324
+ status: "reserved",
325
+ decisionReason: input.decisionReason ?? "",
326
+ priorScore: input.priorScore ?? null,
327
+ blockingCount: input.blockingCount ?? null,
328
+ advisoryCount: input.advisoryCount ?? null,
329
+ workflowRunId: input.workflowRunId ?? null,
330
+ createdAt: now.toISOString(),
331
+ settledAt: null,
332
+ ...(input.forced === true ? { forced: true as const } : {}),
333
+ };
334
+ return { record, created: true };
335
+ }
336
+
337
+ export function settleAdmissionAttempt(
338
+ record: AdmissionRecord,
339
+ status: AdmissionAttemptStatus,
340
+ decisionReason: string,
341
+ settledAt?: Date,
342
+ ): AdmissionRecord {
343
+ const at = settledAt ?? new Date();
344
+ return {
345
+ ...record,
346
+ status,
347
+ decisionReason,
348
+ settledAt: at.toISOString(),
349
+ };
350
+ }
@@ -0,0 +1,73 @@
1
+ // The CLI's error classifier for cli.json (odd/tasks/agent-first-ci.md, T2c). It maps
2
+ // a thrown error to a class by instanceof, or by the class the throw site named on
3
+ // the error (T2d-1: CliError.cls, or a record class beside a plain error), which wins.
4
+ // A message is never parsed, so a wording change cannot move an error to another owner.
5
+ //
6
+ // Each mapping is justified by the throw site and by the catalog text of its code
7
+ // (src/ci/outcome.ts ERROR_CATALOG):
8
+ // - UnmappedRouteError (src/model/routing.ts) -> route/unmapped: "No route mapping
9
+ // found" and "supplies no modelSnapshot"; PRH-ROUTE-UNRESOLVABLE's unmapped text
10
+ // asks for a modelSnapshot in CRYSK_ROUTING.
11
+ // - AmbiguousMappingError (src/model/routing.ts) -> route/ambiguous: "found N
12
+ // duplicate mappings"; its text asks to remove the duplicate.
13
+ // - UnauthorizedRouteError (src/model/routing.ts) -> route/spend-disabled: every
14
+ // throw says "Spend is disabled"; its text asks to enable spend.
15
+ // - OpenCodeVersionAdmissionError (src/transport-registry.ts) with reason "version"
16
+ // -> capability/version_unsupported: the pinned version-pair checks
17
+ // (admitOpenCodeVersionPair, loadOpenCodeSdk); PRH-RUNTIME-UNAVAILABLE calls the
18
+ // action-installed runtime a pr-hero defect, which the pinned version is.
19
+ // - The same class with reason "identity" -> unknown: the observed identity is missing
20
+ // in production, or the declared versions contradict it (transport-registry.ts). That
21
+ // is not a version mismatch, and nothing here can name its owner, so the record does
22
+ // not guess one.
23
+ // - OpenCodeSdkUnavailableError (src/transports/opencode-admission.ts) -> capability/
24
+ // sdk_unavailable: "is not installed"; the same code, the local text says reconcile.
25
+ //
26
+ // Not mapped, on purpose: ModelRoutingError (its own throws name no route fault),
27
+ // RouteAdmissionError and OpenCodeProductionGatedError (a readiness gate, which no
28
+ // capability issue names), CliError and everything else.
29
+ //
30
+ // This module imports runtime classes from the repo, unlike outcome.ts and
31
+ // trigger.ts: it is imported only by the CLI, after the install, never by a step
32
+ // that runs before it.
33
+
34
+ import { CliError, CliUsageError, recordClassOf } from "../errors";
35
+ import {
36
+ AmbiguousMappingError,
37
+ UnauthorizedRouteError,
38
+ UnmappedRouteError,
39
+ } from "../model/routing";
40
+ import { OpenCodeVersionAdmissionError } from "../transport-registry";
41
+ import { OpenCodeSdkUnavailableError } from "../transports/opencode-admission";
42
+ import type { CliErrorClass } from "./outcome";
43
+
44
+ export function classifyCliError(error: unknown): CliErrorClass {
45
+ // The class the throw site named wins over the instanceof mapping below. WHY: the
46
+ // parser or the step that threw knows its failure, and no class of its type can.
47
+ const named = recordClassOf(error);
48
+ if (named !== undefined) return named;
49
+ if (
50
+ (error instanceof CliError || error instanceof CliUsageError) &&
51
+ error.cls !== undefined
52
+ ) {
53
+ return error.cls;
54
+ }
55
+ if (error instanceof UnmappedRouteError) {
56
+ return { kind: "route", reason: "unmapped" };
57
+ }
58
+ if (error instanceof AmbiguousMappingError) {
59
+ return { kind: "route", reason: "ambiguous" };
60
+ }
61
+ if (error instanceof UnauthorizedRouteError) {
62
+ return { kind: "route", reason: "spend-disabled" };
63
+ }
64
+ if (error instanceof OpenCodeVersionAdmissionError) {
65
+ return error.reason === "identity"
66
+ ? { kind: "unknown" }
67
+ : { kind: "capability", issue: "version_unsupported" };
68
+ }
69
+ if (error instanceof OpenCodeSdkUnavailableError) {
70
+ return { kind: "capability", issue: "sdk_unavailable" };
71
+ }
72
+ return { kind: "unknown" };
73
+ }