crysk 0.0.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +611 -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/SKILL-y8rv8msh.md +134 -0
  10. package/dist/SKILL-ygka1bs0.md +515 -0
  11. package/dist/adjudicator-dtg2axnh.md +86 -0
  12. package/dist/admission-config.example-a9vqmmad.json +9 -0
  13. package/dist/ci-admission-camfbx2b.md +122 -0
  14. package/dist/ci-admission-qk9r9taq.md +124 -0
  15. package/dist/cli.js +42501 -0
  16. package/dist/consolidate-ac0mnfyj.md +24 -0
  17. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  18. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  19. package/dist/deep-review-parity-0ec904db.md +120 -0
  20. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  21. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  22. package/dist/index.js +20190 -0
  23. package/dist/opencode-ci-7b0be64p.md +141 -0
  24. package/dist/review-refuter-j4e9gezy.md +71 -0
  25. package/dist/scout-yvp153q7.md +140 -0
  26. package/dist/summarizer-zca44nxa.md +18 -0
  27. package/dist/workflow-w1g9szna.yml +151 -0
  28. package/package.json +81 -4
  29. package/prompts/consolidate.md +24 -0
  30. package/prompts/default/PROVENANCE.md +18 -0
  31. package/prompts/default/deep-review-lifecycle.md +362 -0
  32. package/prompts/default/deep-review-logic.md +156 -0
  33. package/prompts/default/deep-review-parity.md +120 -0
  34. package/prompts/default/deep-review-reliability.md +125 -0
  35. package/prompts/default/deep-review-resilience.md +118 -0
  36. package/prompts/default/review-refuter.md +71 -0
  37. package/prompts/scout.md +140 -0
  38. package/prompts/summarizer.md +18 -0
  39. package/skills/crysk/SKILL.md +74 -0
  40. package/skills/crysk-ci-setup/SKILL.md +134 -0
  41. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  42. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  43. package/skills/crysk-ci-setup/references/ci-admission.md +124 -0
  44. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  45. package/skills/crysk-loop/SKILL.md +515 -0
  46. package/skills/crysk-loop/adjudicator.md +86 -0
  47. package/skills/crysk-pr/SKILL.md +66 -0
  48. package/src/agent-env.ts +1084 -0
  49. package/src/asset-manifest.ts +83 -0
  50. package/src/assets.d.ts +6 -0
  51. package/src/assets.ts +183 -0
  52. package/src/brand-paths.ts +155 -0
  53. package/src/brand.ts +255 -0
  54. package/src/ci/admission-ledger.ts +350 -0
  55. package/src/ci/classify-error.ts +73 -0
  56. package/src/ci/cli-record.ts +271 -0
  57. package/src/ci/force-comment.ts +39 -0
  58. package/src/ci/gates.ts +945 -0
  59. package/src/ci/outcome.ts +2181 -0
  60. package/src/ci/override.ts +187 -0
  61. package/src/ci/publish.ts +1639 -0
  62. package/src/ci/reporter.ts +626 -0
  63. package/src/ci/review-admission.ts +910 -0
  64. package/src/ci/review-levels.ts +310 -0
  65. package/src/ci/review-policy.ts +18 -0
  66. package/src/ci/review-risk.ts +184 -0
  67. package/src/ci/setup.ts +844 -0
  68. package/src/ci/trigger.ts +1353 -0
  69. package/src/cli.ts +348 -0
  70. package/src/commands/activity.ts +67 -0
  71. package/src/commands/ci-setup-questions.ts +397 -0
  72. package/src/commands/ci-setup.ts +381 -0
  73. package/src/commands/config.ts +99 -0
  74. package/src/commands/doctor.ts +108 -0
  75. package/src/commands/init.ts +139 -0
  76. package/src/commands/mcp.ts +10 -0
  77. package/src/commands/menu.ts +129 -0
  78. package/src/commands/post.ts +302 -0
  79. package/src/commands/skills.ts +83 -0
  80. package/src/commands/status.ts +173 -0
  81. package/src/commands/triage.ts +342 -0
  82. package/src/commands/uninstall.ts +37 -0
  83. package/src/commands/upgrade.ts +214 -0
  84. package/src/commands/usage.ts +98 -0
  85. package/src/compare/compare.ts +28 -0
  86. package/src/compare/floor-test.ts +471 -0
  87. package/src/compare/martian-adapter.ts +80 -0
  88. package/src/config/config.ts +267 -0
  89. package/src/corpus/corpus.ts +1094 -0
  90. package/src/corpus/preflight.ts +1789 -0
  91. package/src/diversity/accounting.ts +90 -0
  92. package/src/diversity/adjudication.ts +145 -0
  93. package/src/diversity/admission.ts +60 -0
  94. package/src/diversity/benchmark.ts +195 -0
  95. package/src/diversity/clustering.ts +285 -0
  96. package/src/diversity/errors.ts +7 -0
  97. package/src/diversity/identity.ts +285 -0
  98. package/src/diversity/index.ts +11 -0
  99. package/src/diversity/pipeline-integration.ts +448 -0
  100. package/src/diversity/projection.ts +57 -0
  101. package/src/diversity/self-contained.ts +68 -0
  102. package/src/diversity/target-validation.ts +179 -0
  103. package/src/doctor-migration.ts +209 -0
  104. package/src/doctor.ts +723 -0
  105. package/src/errors.ts +83 -0
  106. package/src/execution/admission.ts +75 -0
  107. package/src/execution/atomic-write.ts +35 -0
  108. package/src/execution/attempt-evidence.ts +415 -0
  109. package/src/execution/bucket-id.ts +136 -0
  110. package/src/execution/concurrency-limiter.ts +175 -0
  111. package/src/execution/contracts.ts +443 -0
  112. package/src/execution/failure-classification.ts +42 -0
  113. package/src/execution/failure-policy.ts +240 -0
  114. package/src/execution/harness.ts +2548 -0
  115. package/src/execution/settlement.ts +348 -0
  116. package/src/execution/spawned-process.ts +66 -0
  117. package/src/execution/spend-limiter.ts +424 -0
  118. package/src/execution/step-artifacts.ts +55 -0
  119. package/src/execution/usage-normalized.ts +469 -0
  120. package/src/git/git.ts +396 -0
  121. package/src/git/identity.ts +64 -0
  122. package/src/git/refs.ts +140 -0
  123. package/src/home-preflight.ts +443 -0
  124. package/src/home.ts +243 -0
  125. package/src/ignore-file.ts +336 -0
  126. package/src/ignore-read.ts +118 -0
  127. package/src/index.ts +34 -0
  128. package/src/legacy-launchd.ts +29 -0
  129. package/src/mcp/mcp.ts +150 -0
  130. package/src/mcp/preflight.ts +407 -0
  131. package/src/menu-context.ts +192 -0
  132. package/src/model/catalog.ts +251 -0
  133. package/src/model/exec-snapshots.ts +390 -0
  134. package/src/model/free-discovery.ts +302 -0
  135. package/src/model/provider-capabilities.ts +814 -0
  136. package/src/model/routing.ts +600 -0
  137. package/src/pr/admission.ts +984 -0
  138. package/src/pr/answered-findings.ts +169 -0
  139. package/src/pr/ci-admission-gate.ts +743 -0
  140. package/src/pr/ci-publish.ts +76 -0
  141. package/src/pr/discovery.ts +432 -0
  142. package/src/pr/inline.ts +507 -0
  143. package/src/pr/plan.ts +366 -0
  144. package/src/pr/posting.ts +115 -0
  145. package/src/pr/pr-status.ts +845 -0
  146. package/src/pr/pr.ts +3642 -0
  147. package/src/pr/preflight.ts +1031 -0
  148. package/src/pr/publish-outcome.ts +361 -0
  149. package/src/pr/range.ts +119 -0
  150. package/src/pr/reverts-preflight.ts +606 -0
  151. package/src/pr/reverts.ts +377 -0
  152. package/src/pr/review-pr.ts +927 -0
  153. package/src/pr/status.ts +154 -0
  154. package/src/pr/target.ts +388 -0
  155. package/src/pr/teardown.ts +437 -0
  156. package/src/pr/worktree-setup.ts +60 -0
  157. package/src/production-runtime.ts +1877 -0
  158. package/src/progress.ts +487 -0
  159. package/src/rereview/adjudicate.ts +89 -0
  160. package/src/rereview/classify.ts +362 -0
  161. package/src/rereview/identity.ts +211 -0
  162. package/src/rereview/plan.ts +308 -0
  163. package/src/rereview/prepare.ts +1025 -0
  164. package/src/rereview/state.ts +767 -0
  165. package/src/rereview/verify.ts +241 -0
  166. package/src/review/boundary.ts +105 -0
  167. package/src/review/consolidate.ts +246 -0
  168. package/src/review/dedupe.ts +368 -0
  169. package/src/review/drafts.ts +448 -0
  170. package/src/review/findings-conformance.ts +120 -0
  171. package/src/review/findings.ts +714 -0
  172. package/src/review/pipeline.ts +3977 -0
  173. package/src/review/preflight.ts +3575 -0
  174. package/src/review/prompt-set.ts +177 -0
  175. package/src/review/proof-refs.ts +187 -0
  176. package/src/review/report.ts +1821 -0
  177. package/src/review/review.ts +490 -0
  178. package/src/review/root-cause.ts +120 -0
  179. package/src/review/route-preflight.ts +289 -0
  180. package/src/review/run.ts +601 -0
  181. package/src/review/scout.ts +323 -0
  182. package/src/review/size-gate.ts +595 -0
  183. package/src/review/spec.ts +235 -0
  184. package/src/review/step-runner.ts +233 -0
  185. package/src/runner-authority.ts +596 -0
  186. package/src/security/binding-policy.ts +115 -0
  187. package/src/security/credential-broker.ts +773 -0
  188. package/src/security/evidence-redaction.ts +62 -0
  189. package/src/security/execution-authority.ts +27 -0
  190. package/src/security/redact.ts +71 -0
  191. package/src/security/workspace-read-broker.ts +466 -0
  192. package/src/server/client.ts +190 -0
  193. package/src/server/preflight.ts +217 -0
  194. package/src/server/server.ts +327 -0
  195. package/src/signal-handler.ts +50 -0
  196. package/src/store/activity.ts +413 -0
  197. package/src/store/backfill-preflight.ts +49 -0
  198. package/src/store/backfill.ts +141 -0
  199. package/src/store/gc-preflight.ts +206 -0
  200. package/src/store/gc.ts +424 -0
  201. package/src/store/metrics-preflight.ts +229 -0
  202. package/src/store/metrics.ts +236 -0
  203. package/src/store/preflight.ts +748 -0
  204. package/src/store/store.ts +693 -0
  205. package/src/system-tools.ts +355 -0
  206. package/src/transport-registry.ts +1124 -0
  207. package/src/transports/claude-code-cli.ts +1348 -0
  208. package/src/transports/opencode-admission.ts +515 -0
  209. package/src/transports/opencode-client.ts +3328 -0
  210. package/src/transports/opencode-evidence.ts +557 -0
  211. package/src/transports/opencode-mcp.ts +248 -0
  212. package/src/transports/opencode-sdk.ts +2294 -0
  213. package/src/transports/opencode-server.ts +535 -0
  214. package/src/triage/adjudication.ts +113 -0
  215. package/src/triage/reply.ts +125 -0
  216. package/src/triage/triage.ts +255 -0
  217. package/src/ui/activity.ts +173 -0
  218. package/src/ui/config-edit.ts +816 -0
  219. package/src/ui/config.ts +462 -0
  220. package/src/ui/menu.ts +1325 -0
  221. package/src/ui/plan.ts +1039 -0
  222. package/src/ui/primitives.ts +300 -0
  223. package/src/ui/progress.ts +298 -0
  224. package/src/ui/result.ts +552 -0
  225. package/src/ui/review-menu.ts +312 -0
  226. package/src/ui/select.ts +528 -0
  227. package/src/ui/tree.ts +178 -0
  228. package/src/uninstaller.ts +479 -0
  229. package/src/updater.ts +836 -0
  230. package/src/usage.ts +77 -0
  231. package/src/watch/preflight.ts +1389 -0
  232. package/src/watch/watch.ts +1235 -0
  233. package/src/wizard.ts +877 -0
@@ -0,0 +1,714 @@
1
+ // Findings JSON schema v1.0.0 (design D2, reconciliation R1/R2).
2
+ // Ported verbatim from deep-review/runner/findings.ts — the lab and the engine
3
+ // must agree on these bytes' semantics or benchmark artifacts stop validating.
4
+ // Owned by the driver: hunter steps emit unvalidated drafts; this module
5
+ // validates the assembled output and merges in the driver-owned run envelope
6
+ // (schema_version, telemetry) before anything is written to a run dir.
7
+
8
+ import type { RootCauseSummary } from "./root-cause";
9
+
10
+ export const SCHEMA_VERSION = "1.0.0";
11
+ export const SCHEMA_VERSION_V1_1 = "1.1.0";
12
+
13
+ export interface EngineIdentity {
14
+ name: string;
15
+ version: string;
16
+ revision?: string;
17
+ }
18
+
19
+ export type EvidenceClass = "deterministic" | "inferential" | "insufficient";
20
+ export type CausalDisposition =
21
+ | "introduced"
22
+ | "behavior-activated"
23
+ | "worsened"
24
+ | "pre-existing"
25
+ | "base-only"
26
+ | "unknown";
27
+ export type Severity = "BLOCKER" | "CRITICAL" | "WARNING" | "SUGGESTION";
28
+ // Canonical "not sent to refuter" value per reconciliation R1 (spec's `n/a` maps to this).
29
+ // `downgraded-latent` (ROADMAP A2) is the "real, but unreachable today"
30
+ // verdict: the claim survives scrutiny as a genuine defect, yet nothing can
31
+ // execute it at this commit — a bug in newly-added code no caller wires up
32
+ // yet. It is deliberately NOT `refuted`, because refuting deletes the finding
33
+ // from findings[] and the G6 lesson was that a real defect must never be
34
+ // deleted for being latent. It lands advisory instead: recorded, visible, and
35
+ // unable to reach blocking tier. Additive widening; validators only reject
36
+ // out-of-set values, so historical artifacts keep validating.
37
+ export type RefuterVerdict =
38
+ | "corroborated"
39
+ | "refuted"
40
+ | "inconclusive"
41
+ | "downgraded-latent"
42
+ | "not_submitted";
43
+ export type Tier = "blocking" | "advisory";
44
+ export type Hunter = "reliability" | "resilience" | "parity" | "lifecycle";
45
+ export type RunStatus = "complete" | "partial";
46
+ export type IndexMode = "fresh" | "sync";
47
+
48
+ export interface HopTrailStep {
49
+ step: number;
50
+ kind: string;
51
+ query: string;
52
+ reached: string;
53
+ }
54
+
55
+ export type HopTrail = HopTrailStep[] | string[];
56
+
57
+ export interface Finding {
58
+ id: string;
59
+ // hunting-map.md taxonomy: 1-14 on any document, plus 15 = "local logic
60
+ // error" (wrong operator/condition/comparison/unit/normalization/variable
61
+ // within the changed lines) on v1.1 documents only (odd/tasks/logic-hunter.md
62
+ // T1). The v1.0 legacy validator (validateFinding) stays closed at 1-14;
63
+ // the v1.1 validator (validateFindingV11) accepts the full 1-15 range.
64
+ category: number;
65
+ path: string;
66
+ line: number;
67
+ symbol?: string;
68
+ severity: Severity;
69
+ evidence_class: EvidenceClass;
70
+ refuter_verdict: RefuterVerdict;
71
+ causal_disposition: CausalDisposition;
72
+ claim: string;
73
+ proof_refs: string[];
74
+ hunter: string;
75
+ tier: Tier;
76
+ hops_used: number;
77
+ hop_trail: HopTrail;
78
+ dedupe_key: string;
79
+ // Which derived root-cause cluster this finding belongs to (RC001, …).
80
+ // ADDITIVE and OPTIONAL: both validators are pure allowlists that reject
81
+ // only bad values of known keys, never unknown keys, so a document carrying
82
+ // this field still validates against the unchanged 1.0.0 schema on the lab
83
+ // side and a document without it still validates here. No version bump.
84
+ root_cause_id?: string;
85
+ }
86
+
87
+ // Refuted findings are excluded from `findings[]` (scorer contract unchanged)
88
+ // but stay visible here in benchmark mode only, per reconciliation R2.
89
+ export type DebugRefutedFinding = Omit<Finding, "tier"> & {
90
+ refuter_verdict: "refuted";
91
+ };
92
+
93
+ // Step 5 merge losers. Without these, a benchmark miss cannot be attributed:
94
+ // "no hunter saw it" and "a hunter saw it and dedupe collapsed it into a
95
+ // weaker sibling claim" look identical in `findings[]`.
96
+ export type DebugDedupedFinding = Omit<Finding, "tier"> & {
97
+ merged_into: string;
98
+ };
99
+
100
+ export interface Telemetry {
101
+ index_ms: number;
102
+ index_mode: IndexMode;
103
+ sync_ms?: number;
104
+ index_disk_mb: number;
105
+ wall_ms: number;
106
+ tokens_in: number;
107
+ tokens_out: number;
108
+ tokens_total: number;
109
+ cost_usd_est: number;
110
+ // True when at least one spend reservation ended unresolved_remote — the
111
+ // reported cost is a floor of known spend, not a closed total.
112
+ cost_usd_est_is_floor?: boolean;
113
+ // Engine v2 populates this per step (it runs one session per agent). The
114
+ // original best-effort caveat (reconciliation R3) still applies to v1
115
+ // documents: absence must never fail validation.
116
+ per_agent?: Record<string, { tokens_total: number; duration_ms: number }>;
117
+ }
118
+
119
+ // Which prompt bytes produced this score. Optional because runs 1-3 predate
120
+ // repo-side prompt sets; every run from honest iteration 2 on must carry it,
121
+ // otherwise an A/B delta cannot be attributed to a prompt at all.
122
+ export interface PromptSet {
123
+ name: string; // directory basename, e.g. "arm-a"
124
+ sha256: string; // fingerprint over the concatenated agent files
125
+ }
126
+
127
+ export interface RunSummary {
128
+ prose: string;
129
+ score: number;
130
+ score_reason: string;
131
+ }
132
+
133
+ export interface FindingsDocument {
134
+ schema_version: string;
135
+ pr: number;
136
+ base_sha: string;
137
+ head_sha: string;
138
+ model: string;
139
+ iteration: number;
140
+ prompt_set?: PromptSet;
141
+ // Fingerprint of the driver sources that produced this run. Iteration 2 was
142
+ // smeared by a mid-flight driver edit that left no trace in the artifacts.
143
+ driver_sha?: string;
144
+ // Which engine produced this run. Absent on v1 (monolithic orchestrator)
145
+ // documents; v2 (pr-hero) documents always carry it — without this field,
146
+ // v1 and v2 rows in the metrics ledger are indistinguishable (same
147
+ // prompt_set sha on both sides of the engine swap). Required on v1.1.0.
148
+ engine?: EngineIdentity;
149
+ parity_hunter_fired: boolean;
150
+ run_status: RunStatus;
151
+ // Juanma's decision (verify-report-pr3, #3305), over the verifier's cheaper
152
+ // "make `post` as permissive as `--pr --post`" suggestion: `run_status:
153
+ // "partial"` with zero findings covers at least THREE distinct situations
154
+ // — every hunter failed (the true sessionFailed case, review/pipeline.ts:771),
155
+ // no hunter ran at all because gotchas were unusable — missing, empty, or
156
+ // still the untouched scaffold (pipeline's step-2 fail-loud,
157
+ // sessionFailed: false), or one hunter died while the others found
158
+ // nothing. `run_status` alone cannot tell these apart, so a permissive
159
+ // `post` verb would publish a clean bill for a review that never ran.
160
+ // ADDITIVE and OPTIONAL, same precedent as `root_cause_id` above: both
161
+ // validators are allowlists that never reject unknown keys, so schema
162
+ // stays 1.0.0 (project rule 5 — lab compatibility is sacred) and an
163
+ // existing artifact without this field still validates. Absent MUST mean
164
+ // "unknown", never "false" — see `runPostCommand`'s guard in
165
+ // src/commands/post.ts for the back-compat fallback this enables.
166
+ sessionFailed?: boolean;
167
+ summary?: RunSummary;
168
+ telemetry: Telemetry;
169
+ findings: Finding[];
170
+ debug: {
171
+ refuted: DebugRefutedFinding[];
172
+ deduped?: DebugDedupedFinding[];
173
+ // The whole derived partition, kept next to the findings it describes.
174
+ // Also additive/optional: a run that never computed it validates the same.
175
+ root_causes?: RootCauseSummary;
176
+ diversity?: DiversityDebugArtifacts;
177
+ };
178
+ }
179
+
180
+ export interface DiversityDebugArtifacts {
181
+ readonly planFingerprint?: string;
182
+ readonly attempts?: readonly Record<string, unknown>[];
183
+ readonly observations?: readonly Record<string, unknown>[];
184
+ }
185
+
186
+ // Draft the engine assembles before the driver merges in the run envelope.
187
+ export interface SkillOutput {
188
+ findings: Finding[];
189
+ debug: {
190
+ refuted: DebugRefutedFinding[];
191
+ deduped?: DebugDedupedFinding[];
192
+ root_causes?: RootCauseSummary;
193
+ diversity?: DiversityDebugArtifacts | Record<string, unknown>;
194
+ };
195
+ parity_hunter_fired: boolean;
196
+ run_status: RunStatus;
197
+ summary?: RunSummary;
198
+ }
199
+
200
+ const SEVERITIES: Severity[] = ["BLOCKER", "CRITICAL", "WARNING", "SUGGESTION"];
201
+ const EVIDENCE_CLASSES: EvidenceClass[] = [
202
+ "deterministic",
203
+ "inferential",
204
+ "insufficient",
205
+ ];
206
+ const REFUTER_VERDICTS: RefuterVerdict[] = [
207
+ "corroborated",
208
+ "refuted",
209
+ "inconclusive",
210
+ "downgraded-latent",
211
+ "not_submitted",
212
+ ];
213
+ const CAUSAL_DISPOSITIONS: CausalDisposition[] = [
214
+ "introduced",
215
+ "behavior-activated",
216
+ "worsened",
217
+ "pre-existing",
218
+ "base-only",
219
+ "unknown",
220
+ ];
221
+ const TIERS: Tier[] = ["blocking", "advisory"];
222
+ const HUNTERS: Hunter[] = ["reliability", "resilience", "parity", "lifecycle"];
223
+ const SPECIALTY_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
224
+ const SUPPORTED_SCHEMA_VERSIONS = [
225
+ SCHEMA_VERSION,
226
+ SCHEMA_VERSION_V1_1,
227
+ ] as const;
228
+
229
+ export class FindingsValidationError extends Error {}
230
+
231
+ function isControlFree(value: string): boolean {
232
+ for (let i = 0; i < value.length; i++) {
233
+ const code = value.charCodeAt(i);
234
+ if (code < 32 || code === 127) return false;
235
+ }
236
+ return true;
237
+ }
238
+
239
+ function isValidSpecialtySlug(value: string): boolean {
240
+ return (
241
+ value.length >= 1 && value.length <= 64 && SPECIALTY_SLUG_RE.test(value)
242
+ );
243
+ }
244
+
245
+ function validateEngineString(value: unknown, label: string): string {
246
+ must(typeof value === "string", `${label} required`);
247
+ const raw = value as string;
248
+ const trimmed = raw.trim();
249
+ must(trimmed === raw, `${label} must be trimmed`);
250
+ must(
251
+ trimmed.length >= 1 && trimmed.length <= 128,
252
+ `${label} must be 1-128 characters`,
253
+ );
254
+ must(isControlFree(trimmed), `${label} must not contain control characters`);
255
+ return trimmed;
256
+ }
257
+
258
+ function validateEngineIdentity(
259
+ candidate: unknown,
260
+ options: { required: boolean },
261
+ ): EngineIdentity | undefined {
262
+ if (candidate === undefined) {
263
+ must(!options.required, "engine required");
264
+ return undefined;
265
+ }
266
+ must(
267
+ typeof candidate === "object" && candidate !== null,
268
+ "engine must be an object",
269
+ );
270
+ const engine = candidate as Record<string, unknown>;
271
+ const name = validateEngineString(engine.name, "engine.name");
272
+ const version = validateEngineString(engine.version, "engine.version");
273
+ const revision =
274
+ engine.revision === undefined
275
+ ? undefined
276
+ : validateEngineString(engine.revision, "engine.revision");
277
+ return {
278
+ name,
279
+ version,
280
+ ...(revision === undefined ? {} : { revision }),
281
+ };
282
+ }
283
+
284
+ function must(condition: boolean, message: string): void {
285
+ if (!condition) throw new FindingsValidationError(message);
286
+ }
287
+
288
+ // The artifact-side twin of review/drafts.ts's normalizeOptionalString — same rule,
289
+ // stated in full there. `null` on an optional string is REPAIRED to absent,
290
+ // a present-but-wrong-typed value is rejected.
291
+ //
292
+ // Repaired rather than rejected because this validator does double duty. It is
293
+ // the write gate (writeFindings, below), but it is ALSO the read-back gate for
294
+ // an artifact already on disk: `pr-hero post --from <run-dir>` and
295
+ // `pr-hero triage reply --from <run-dir>` (src/commands/post.ts and
296
+ // src/commands/triage.ts) both re-validate a findings.json written by an
297
+ // earlier engine. Rejecting here would permanently
298
+ // strand every artifact the PR #50 defect already wrote — including the $3.77
299
+ // run whose post it ate — and turn "the post crashed" into "the post can never
300
+ // happen". Repair keeps that recovery path open and still guarantees the
301
+ // invariant on write, since writeFindings stringifies what this returns.
302
+ //
303
+ // Mutates in place: validateFindingsDocument discards this function's return
304
+ // value, exactly as validateHunterDraft does with the draft twin.
305
+ function normalizeOptionalString(
306
+ f: Record<string, unknown>,
307
+ key: string,
308
+ label: string,
309
+ ): void {
310
+ if (f[key] === null) {
311
+ delete f[key];
312
+ return;
313
+ }
314
+ must(
315
+ f[key] === undefined || typeof f[key] === "string",
316
+ `${label} must be a string when present`,
317
+ );
318
+ }
319
+
320
+ export function validateFinding(candidate: unknown, index: number): Finding {
321
+ must(
322
+ typeof candidate === "object" && candidate !== null,
323
+ `findings[${index}] must be an object`,
324
+ );
325
+ const f = candidate as Record<string, unknown>;
326
+ must(
327
+ typeof f.id === "string" && f.id.length > 0,
328
+ `findings[${index}].id required`,
329
+ );
330
+ must(
331
+ typeof f.category === "number" && f.category >= 1 && f.category <= 14,
332
+ `findings[${index}].category must be 1-14`,
333
+ );
334
+ must(
335
+ typeof f.path === "string" && f.path.length > 0,
336
+ `findings[${index}].path required`,
337
+ );
338
+ must(typeof f.line === "number", `findings[${index}].line must be a number`);
339
+ must(
340
+ SEVERITIES.includes(f.severity as Severity),
341
+ `findings[${index}].severity invalid`,
342
+ );
343
+ must(
344
+ EVIDENCE_CLASSES.includes(f.evidence_class as EvidenceClass),
345
+ `findings[${index}].evidence_class invalid`,
346
+ );
347
+ must(
348
+ REFUTER_VERDICTS.includes(f.refuter_verdict as RefuterVerdict),
349
+ `findings[${index}].refuter_verdict invalid`,
350
+ );
351
+ must(
352
+ CAUSAL_DISPOSITIONS.includes(f.causal_disposition as CausalDisposition),
353
+ `findings[${index}].causal_disposition invalid`,
354
+ );
355
+ must(
356
+ typeof f.claim === "string" && f.claim.length > 0,
357
+ `findings[${index}].claim required`,
358
+ );
359
+ must(
360
+ Array.isArray(f.proof_refs),
361
+ `findings[${index}].proof_refs must be an array`,
362
+ );
363
+ must(
364
+ HUNTERS.includes(f.hunter as Hunter),
365
+ `findings[${index}].hunter invalid`,
366
+ );
367
+ must(TIERS.includes(f.tier as Tier), `findings[${index}].tier invalid`);
368
+ must(
369
+ typeof f.hops_used === "number",
370
+ `findings[${index}].hops_used must be a number`,
371
+ );
372
+ must(
373
+ Array.isArray(f.hop_trail),
374
+ `findings[${index}].hop_trail must be an array`,
375
+ );
376
+ must(
377
+ typeof f.dedupe_key === "string" && f.dedupe_key.length > 0,
378
+ `findings[${index}].dedupe_key required`,
379
+ );
380
+ must(
381
+ (f.proof_refs as unknown[]).every((ref) => typeof ref === "string"),
382
+ `findings[${index}].proof_refs must contain only strings`,
383
+ );
384
+ normalizeOptionalString(f, "symbol", `findings[${index}].symbol`);
385
+ normalizeOptionalString(
386
+ f,
387
+ "root_cause_id",
388
+ `findings[${index}].root_cause_id`,
389
+ );
390
+ return f as unknown as Finding;
391
+ }
392
+
393
+ function validateFindingV11(candidate: unknown, index: number): Finding {
394
+ must(
395
+ typeof candidate === "object" && candidate !== null,
396
+ `findings[${index}] must be an object`,
397
+ );
398
+ const f = candidate as Record<string, unknown>;
399
+ must(
400
+ typeof f.id === "string" && f.id.length > 0,
401
+ `findings[${index}].id required`,
402
+ );
403
+ must(
404
+ typeof f.category === "number" && f.category >= 1 && f.category <= 15,
405
+ `findings[${index}].category must be 1-15`,
406
+ );
407
+ must(
408
+ typeof f.path === "string" && f.path.length > 0,
409
+ `findings[${index}].path required`,
410
+ );
411
+ must(typeof f.line === "number", `findings[${index}].line must be a number`);
412
+ must(
413
+ SEVERITIES.includes(f.severity as Severity),
414
+ `findings[${index}].severity invalid`,
415
+ );
416
+ must(
417
+ EVIDENCE_CLASSES.includes(f.evidence_class as EvidenceClass),
418
+ `findings[${index}].evidence_class invalid`,
419
+ );
420
+ must(
421
+ REFUTER_VERDICTS.includes(f.refuter_verdict as RefuterVerdict),
422
+ `findings[${index}].refuter_verdict invalid`,
423
+ );
424
+ must(
425
+ CAUSAL_DISPOSITIONS.includes(f.causal_disposition as CausalDisposition),
426
+ `findings[${index}].causal_disposition invalid`,
427
+ );
428
+ must(
429
+ typeof f.claim === "string" && f.claim.length > 0,
430
+ `findings[${index}].claim required`,
431
+ );
432
+ must(
433
+ Array.isArray(f.proof_refs),
434
+ `findings[${index}].proof_refs must be an array`,
435
+ );
436
+ must(
437
+ typeof f.hunter === "string" && isValidSpecialtySlug(f.hunter),
438
+ `findings[${index}].hunter invalid`,
439
+ );
440
+ must(TIERS.includes(f.tier as Tier), `findings[${index}].tier invalid`);
441
+ must(
442
+ typeof f.hops_used === "number",
443
+ `findings[${index}].hops_used must be a number`,
444
+ );
445
+ must(
446
+ Array.isArray(f.hop_trail),
447
+ `findings[${index}].hop_trail must be an array`,
448
+ );
449
+ must(
450
+ typeof f.dedupe_key === "string" && f.dedupe_key.length > 0,
451
+ `findings[${index}].dedupe_key required`,
452
+ );
453
+ must(
454
+ (f.proof_refs as unknown[]).every((ref) => typeof ref === "string"),
455
+ `findings[${index}].proof_refs must contain only strings`,
456
+ );
457
+ normalizeOptionalString(f, "symbol", `findings[${index}].symbol`);
458
+ normalizeOptionalString(
459
+ f,
460
+ "root_cause_id",
461
+ `findings[${index}].root_cause_id`,
462
+ );
463
+ return f as unknown as Finding;
464
+ }
465
+
466
+ function validateDocumentSummary(d: Record<string, unknown>): void {
467
+ if (d.summary === undefined) return;
468
+ must(
469
+ typeof d.summary === "object" && d.summary !== null,
470
+ "summary must be an object when present",
471
+ );
472
+ const summary = d.summary as Record<string, unknown>;
473
+ must(
474
+ typeof summary.prose === "string" && summary.prose.length > 0,
475
+ "summary.prose required",
476
+ );
477
+ must(
478
+ typeof summary.prose === "string" && summary.prose.length <= 1200,
479
+ "summary.prose must be at most 1200 characters",
480
+ );
481
+ must(
482
+ typeof summary.score === "number" &&
483
+ Number.isInteger(summary.score) &&
484
+ summary.score >= 1 &&
485
+ summary.score <= 5,
486
+ "summary.score must be an integer 1-5",
487
+ );
488
+ must(
489
+ typeof summary.score_reason === "string" && summary.score_reason.length > 0,
490
+ "summary.score_reason required",
491
+ );
492
+ must(
493
+ typeof summary.score_reason === "string" &&
494
+ summary.score_reason.length <= 400,
495
+ "summary.score_reason must be at most 400 characters",
496
+ );
497
+ const prose = summary.prose as string;
498
+ const scoreReason = summary.score_reason as string;
499
+ must(
500
+ !prose.includes("<!--") &&
501
+ !prose.includes("-->") &&
502
+ !scoreReason.includes("<!--") &&
503
+ !scoreReason.includes("-->"),
504
+ "summary strings must not contain HTML comment markers",
505
+ );
506
+ }
507
+
508
+ function validateDocumentEnvelope(d: Record<string, unknown>): void {
509
+ must(typeof d.pr === "number", "pr must be a number");
510
+ must(
511
+ typeof d.base_sha === "string" && d.base_sha.length > 0,
512
+ "base_sha required",
513
+ );
514
+ must(
515
+ typeof d.head_sha === "string" && d.head_sha.length > 0,
516
+ "head_sha required",
517
+ );
518
+ must(typeof d.model === "string" && d.model.length > 0, "model required");
519
+ must(typeof d.iteration === "number", "iteration must be a number");
520
+ must(
521
+ typeof d.parity_hunter_fired === "boolean",
522
+ "parity_hunter_fired must be a boolean",
523
+ );
524
+ must(
525
+ d.run_status === "complete" || d.run_status === "partial",
526
+ "run_status must be complete|partial",
527
+ );
528
+ must(
529
+ d.sessionFailed === undefined || typeof d.sessionFailed === "boolean",
530
+ "sessionFailed must be a boolean when present",
531
+ );
532
+ validateDocumentSummary(d);
533
+ must(
534
+ typeof d.telemetry === "object" && d.telemetry !== null,
535
+ "telemetry required",
536
+ );
537
+ must(Array.isArray(d.findings), "findings must be an array");
538
+ const debug = d.debug as Record<string, unknown> | undefined;
539
+ must(
540
+ !!debug && Array.isArray(debug.refuted),
541
+ "debug.refuted must be an array",
542
+ );
543
+ }
544
+
545
+ function validateFindingsDocumentV10(
546
+ d: Record<string, unknown>,
547
+ ): FindingsDocument {
548
+ (d.findings as unknown[]).forEach((f, i) => {
549
+ validateFinding(f, i);
550
+ });
551
+ return d as unknown as FindingsDocument;
552
+ }
553
+
554
+ function validateFindingsDocumentV11(
555
+ d: Record<string, unknown>,
556
+ ): FindingsDocument {
557
+ validateEngineIdentity(d.engine, { required: true });
558
+ (d.findings as unknown[]).forEach((f, i) => {
559
+ validateFindingV11(f, i);
560
+ });
561
+ return d as unknown as FindingsDocument;
562
+ }
563
+
564
+ export function validateFindingsDocument(candidate: unknown): FindingsDocument {
565
+ must(
566
+ typeof candidate === "object" && candidate !== null,
567
+ "findings document must be an object",
568
+ );
569
+ const d = candidate as Record<string, unknown>;
570
+ const version = d.schema_version;
571
+ must(
572
+ SUPPORTED_SCHEMA_VERSIONS.includes(
573
+ version as (typeof SUPPORTED_SCHEMA_VERSIONS)[number],
574
+ ),
575
+ `schema_version must be ${SCHEMA_VERSION} or ${SCHEMA_VERSION_V1_1}`,
576
+ );
577
+ validateDocumentEnvelope(d);
578
+ if (version === SCHEMA_VERSION) {
579
+ return validateFindingsDocumentV10(d);
580
+ }
581
+ return validateFindingsDocumentV11(d);
582
+ }
583
+
584
+ // Full tier-assignment rule (spec BR "Full Tier-Assignment Rule"): only
585
+ // corroborated-or-deterministic BLOCKER/CRITICAL findings may block; a
586
+ // deterministic one is demoted to advisory when the refuter returns the
587
+ // positive `downgraded-latent` verdict, and also when an EXPECTED refuter
588
+ // check was cut short before the finding was ever submitted (see the
589
+ // `refuterCutShort` option below).
590
+ export function deriveTier(
591
+ finding: Pick<Finding, "severity" | "evidence_class" | "refuter_verdict">,
592
+ options: {
593
+ // Whether a refuter check this finding was ENTITLED TO never got to
594
+ // submit its verdict. NOT a synonym for "the run was truncated": the
595
+ // caller must have already established BOTH halves of that entitlement —
596
+ // a refuter was configured for this run AND the run ended early (pipeline
597
+ // ceiling / `run_status: "partial"`) rather than completing its legs.
598
+ // Those two are orthogonal, and the name says the conjunction so no future
599
+ // caller can satisfy it with truncation alone (src/review/pipeline.ts `finish()`
600
+ // is where the conjunction is computed, and says why).
601
+ // Defaults to FALSE on purpose: a caller that knows nothing about the
602
+ // refuter's fate must never be able to demote by accident, so the fallback
603
+ // is exactly today's behaviour.
604
+ refuterCutShort?: boolean;
605
+ } = {},
606
+ ): Tier {
607
+ const isBlockerClass =
608
+ finding.severity === "BLOCKER" || finding.severity === "CRITICAL";
609
+ if (!isBlockerClass) return "advisory";
610
+ if (finding.evidence_class === "insufficient") return "advisory";
611
+ // Ordered BEFORE the deterministic short-circuit on purpose. A verdict that
612
+ // could not outrank `deterministic` would be inert exactly where it is
613
+ // needed: the 2026-07-29 AudioTrimmer runs put 26 of 26 blocking findings in
614
+ // that class, so the gate had nothing to act on. Only a POSITIVE downgrade
615
+ // gets this power — `inconclusive` still blocks, mirroring the rule that
616
+ // `refuted` requires positive disproof. Silence is not a demotion.
617
+ if (finding.refuter_verdict === "downgraded-latent") return "advisory";
618
+ // The blocking tier does not change the job's exit code: ciExitCode stays 0
619
+ // on findings, and "blocking findings exit 0 in CI — reviewer, not a merge
620
+ // gate" (test/ci/review.test.ts) pins that. What it does change is the pr-hero commit status, and only in
621
+ // gate mode (the CI default, S4): there that status, which is the required
622
+ // check, goes red on blocking findings. In advisory mode the tier buys only
623
+ // the report's loudest register: the red badge, the "Blocking" section, and
624
+ // the headline count a human reads first. Either way the tier claims that an
625
+ // adversary looked and failed to knock the claim down, so the obligation is
626
+ // honesty about what was checked, and a gate may act on it.
627
+ //
628
+ // The demotion below
629
+ // fires on a THREE-part condition, and every part is load-bearing:
630
+ // 1. a refuter was CONFIGURED for this run, so an adversarial check was
631
+ // genuinely owed to this finding;
632
+ // 2. the run was truncated, so that leg was refused admission
633
+ // (src/review/pipeline.ts §5.3) and never spawned; and
634
+ // 3. the verdict is `not_submitted`, the fallback `finish()` stamps on a
635
+ // survivor no verdict ever arrived for.
636
+ // Parts 1 and 2 arrive pre-conjoined as `refuterCutShort` — deriveTier never
637
+ // sees truncation on its own, deliberately, because the two are ORTHOGONAL
638
+ // and collapsing them is the whole bug this gate was rewritten to close.
639
+ // Demote for that triple and NOTHING else, because each neighbouring case
640
+ // means something different:
641
+ // - `corroborated` on a cut-short run WAS adversarially checked before
642
+ // time ran out. Truncation is no reason to discard work that happened.
643
+ // - `inconclusive` means the refuter RAN and returned no positive
644
+ // downgrade — the standing rule above, paid for by AudioTrimmer.
645
+ // - `not_submitted` with NO refuter configured is the supported
646
+ // zero-refuter setup (src/review/spec.ts allows at most one refuter, so zero is
647
+ // configured absence, not failure). There `not_submitted` is the designed
648
+ // steady state, blocking is intended, and it stays intended no matter how
649
+ // the run ended — a hunter-bound or verify-bound ceiling on such a spec
650
+ // cut nothing short, because nothing was ever going to submit. Demoting
651
+ // it would empty blocking tier for every such user and undo the
652
+ // AudioTrimmer fix, which is exactly why part 1 exists.
653
+ // - `not_submitted` on a COMPLETE run with a refuter configured cannot
654
+ // occur — the leg either ran or was refused admission by truncation.
655
+ // An `inferential` finding needs no branch here: unrefuted, it is already
656
+ // advisory two lines down.
657
+ // Recording WHY the check is missing IN the artifact needs a new
658
+ // `refuter_verdict` value, and that is a coordinated schema v1.1 bump with
659
+ // the sibling lab (ROADMAP C2) — deliberately not this fix.
660
+ if (
661
+ options.refuterCutShort === true &&
662
+ finding.refuter_verdict === "not_submitted"
663
+ )
664
+ return "advisory";
665
+ if (finding.evidence_class === "deterministic") return "blocking";
666
+ return finding.refuter_verdict === "corroborated" ? "blocking" : "advisory";
667
+ }
668
+
669
+ export function mergeRunEnvelope(params: {
670
+ skillOutput: SkillOutput;
671
+ pr: number;
672
+ base_sha: string;
673
+ head_sha: string;
674
+ model: string;
675
+ iteration: number;
676
+ prompt_set?: PromptSet;
677
+ driver_sha?: string;
678
+ engine: EngineIdentity;
679
+ sessionFailed: boolean;
680
+ telemetry: Telemetry;
681
+ }): FindingsDocument {
682
+ const run_status: RunStatus =
683
+ params.sessionFailed || params.skillOutput.run_status === "partial"
684
+ ? "partial"
685
+ : "complete";
686
+ return {
687
+ schema_version: SCHEMA_VERSION_V1_1,
688
+ pr: params.pr,
689
+ base_sha: params.base_sha,
690
+ head_sha: params.head_sha,
691
+ model: params.model,
692
+ iteration: params.iteration,
693
+ ...(params.prompt_set ? { prompt_set: params.prompt_set } : {}),
694
+ ...(params.driver_sha ? { driver_sha: params.driver_sha } : {}),
695
+ engine: params.engine,
696
+ parity_hunter_fired: params.skillOutput.parity_hunter_fired,
697
+ run_status,
698
+ sessionFailed: params.sessionFailed,
699
+ ...(params.skillOutput.summary === undefined
700
+ ? {}
701
+ : { summary: params.skillOutput.summary }),
702
+ telemetry: params.telemetry,
703
+ findings: params.skillOutput.findings,
704
+ debug: params.skillOutput.debug,
705
+ };
706
+ }
707
+
708
+ export async function writeFindings(
709
+ outPath: string,
710
+ doc: FindingsDocument,
711
+ ): Promise<void> {
712
+ const validated = validateFindingsDocument(doc);
713
+ await Bun.write(outPath, `${JSON.stringify(validated, null, 2)}\n`);
714
+ }