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,693 @@
1
+ // Canonical product store (Fundamentals #6 / observability-canonical-store.md),
2
+ // impure half: bun:sqlite file handle, transactional persistence, schema migrations,
3
+ // and exact round-trip deserialization.
4
+ //
5
+ // Invariant: The SQLite database is the canonical source of truth. JSON artifacts
6
+ // and reports are derived exports.
7
+
8
+ import { Database, type SQLQueryBindings } from "bun:sqlite";
9
+ import { mkdirSync } from "node:fs";
10
+ import path from "node:path";
11
+ import {
12
+ type DebugDedupedFinding,
13
+ type DebugRefutedFinding,
14
+ type Finding,
15
+ type FindingsDocument,
16
+ type HopTrail,
17
+ type HopTrailStep,
18
+ type IndexMode,
19
+ type RunSummary,
20
+ SCHEMA_VERSION,
21
+ type Telemetry,
22
+ validateFindingsDocument,
23
+ } from "#review/findings";
24
+ import {
25
+ type CanonicalFindingRow,
26
+ type CanonicalRunRow,
27
+ type DebugFindingRow,
28
+ type FindingTriageRow,
29
+ migrationsForProductStore,
30
+ type ProjectedCompleteRun,
31
+ } from "./preflight";
32
+
33
+ const BUSY_TIMEOUT_MS = 5000;
34
+
35
+ export function openProductStore(dbPath: string): Database {
36
+ mkdirSync(path.dirname(dbPath), { recursive: true });
37
+ const db = new Database(dbPath, { create: true });
38
+ db.exec("PRAGMA journal_mode = WAL;");
39
+ db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS};`);
40
+
41
+ const current = (
42
+ db.query("PRAGMA user_version;").get() as { user_version: number }
43
+ ).user_version;
44
+ const migration = migrationsForProductStore(current);
45
+
46
+ if (migration.statements.length > 0) {
47
+ db.exec("PRAGMA foreign_keys = OFF;");
48
+ db.transaction(() => {
49
+ for (const statement of migration.statements) {
50
+ db.exec(statement);
51
+ }
52
+ })();
53
+ db.exec(`PRAGMA user_version = ${migration.toVersion};`);
54
+ }
55
+
56
+ db.exec("PRAGMA foreign_keys = ON;");
57
+
58
+ return db;
59
+ }
60
+
61
+ // `generated_at` on conflict: a live re-run into the same run dir (an explicit
62
+ // --out) is a new run, so its timestamp moves with its cost and head. The
63
+ // historical backfill keeps the stored one only for the SAME run: it
64
+ // re-derives the time from artifacts and must not rewrite when that run
65
+ // happened. The live persist always stamps after the pipeline wrote its
66
+ // artifacts (store/preflight.ts), so for the run a row describes the artifact
67
+ // time is never later than the stored one. A different head, or a later
68
+ // artifact time, is a later run in the same run dir whose live persist was
69
+ // missed: it takes the artifact's own time along with its cost and head.
70
+ function runUpsertSql(keepGeneratedAt: boolean): string {
71
+ return RUN_UPSERT_SQL.replace(
72
+ "generated_at = runs.generated_at",
73
+ keepGeneratedAt
74
+ ? "generated_at = CASE WHEN excluded.head_sha = runs.head_sha " +
75
+ "AND excluded.generated_at <= runs.generated_at " +
76
+ "THEN runs.generated_at ELSE excluded.generated_at END"
77
+ : "generated_at = excluded.generated_at",
78
+ );
79
+ }
80
+
81
+ const RUN_UPSERT_SQL = `
82
+ INSERT INTO runs (
83
+ repo_id, run_dir, pr, checkout_path, head_sha, base_sha, diff_from_sha,
84
+ run_status, session_failed, model, iteration, parity_hunter_fired,
85
+ prompt_set_name, prompt_set_sha256, driver_sha, engine_name, engine_version,
86
+ engine_revision, findings_schema_version, summary_prose, summary_score,
87
+ summary_score_reason, generated_at, wall_ms, index_ms, index_mode,
88
+ index_disk_mb, sync_ms, tokens_in, tokens_out, tokens_total, cost_usd_est,
89
+ blocking, advisory, root_causes_json, greptile_found, diversity_plan_json
90
+ ) VALUES (
91
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
92
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
93
+ )
94
+ ON CONFLICT(repo_id, run_dir) DO UPDATE SET
95
+ repo_id = excluded.repo_id,
96
+ pr = excluded.pr,
97
+ checkout_path = excluded.checkout_path,
98
+ head_sha = excluded.head_sha,
99
+ base_sha = excluded.base_sha,
100
+ diff_from_sha = COALESCE(excluded.diff_from_sha, runs.diff_from_sha),
101
+ run_status = excluded.run_status,
102
+ session_failed = excluded.session_failed,
103
+ model = excluded.model,
104
+ iteration = excluded.iteration,
105
+ parity_hunter_fired = excluded.parity_hunter_fired,
106
+ prompt_set_name = excluded.prompt_set_name,
107
+ prompt_set_sha256 = excluded.prompt_set_sha256,
108
+ driver_sha = excluded.driver_sha,
109
+ engine_name = excluded.engine_name,
110
+ engine_version = excluded.engine_version,
111
+ engine_revision = excluded.engine_revision,
112
+ findings_schema_version = excluded.findings_schema_version,
113
+ summary_prose = excluded.summary_prose,
114
+ summary_score = excluded.summary_score,
115
+ summary_score_reason = excluded.summary_score_reason,
116
+ generated_at = runs.generated_at,
117
+ wall_ms = excluded.wall_ms,
118
+ index_ms = excluded.index_ms,
119
+ index_mode = excluded.index_mode,
120
+ index_disk_mb = excluded.index_disk_mb,
121
+ sync_ms = excluded.sync_ms,
122
+ tokens_in = excluded.tokens_in,
123
+ tokens_out = excluded.tokens_out,
124
+ tokens_total = excluded.tokens_total,
125
+ cost_usd_est = excluded.cost_usd_est,
126
+ blocking = excluded.blocking,
127
+ advisory = excluded.advisory,
128
+ root_causes_json = excluded.root_causes_json,
129
+ greptile_found = COALESCE(excluded.greptile_found, runs.greptile_found),
130
+ diversity_plan_json = excluded.diversity_plan_json
131
+ `;
132
+
133
+ function runParams(row: CanonicalRunRow): SQLQueryBindings[] {
134
+ return [
135
+ row.repo_id,
136
+ row.run_dir,
137
+ row.pr,
138
+ row.checkout_path,
139
+ row.head_sha,
140
+ row.base_sha,
141
+ row.diff_from_sha,
142
+ row.run_status,
143
+ row.session_failed,
144
+ row.model,
145
+ row.iteration,
146
+ row.parity_hunter_fired,
147
+ row.prompt_set_name,
148
+ row.prompt_set_sha256,
149
+ row.driver_sha,
150
+ row.engine_name,
151
+ row.engine_version,
152
+ row.engine_revision,
153
+ row.findings_schema_version,
154
+ row.summary_prose,
155
+ row.summary_score,
156
+ row.summary_score_reason,
157
+ row.generated_at,
158
+ row.wall_ms,
159
+ row.index_ms,
160
+ row.index_mode,
161
+ row.index_disk_mb,
162
+ row.sync_ms,
163
+ row.tokens_in,
164
+ row.tokens_out,
165
+ row.tokens_total,
166
+ row.cost_usd_est,
167
+ row.blocking,
168
+ row.advisory,
169
+ row.root_causes_json,
170
+ row.greptile_found,
171
+ row.diversity_plan_json,
172
+ ];
173
+ }
174
+
175
+ export function saveRunTransaction(
176
+ db: Database,
177
+ projected: ProjectedCompleteRun,
178
+ options: { keepGeneratedAt?: boolean } = {},
179
+ ): number {
180
+ let runId = 0;
181
+ db.transaction(() => {
182
+ db.query(runUpsertSql(options.keepGeneratedAt === true)).run(
183
+ ...runParams(projected.run),
184
+ );
185
+ const runRow = db
186
+ .query("SELECT id FROM runs WHERE repo_id = ? AND run_dir = ?")
187
+ .get(projected.run.repo_id, projected.run.run_dir) as { id: number };
188
+ runId = runRow.id;
189
+
190
+ // Delete existing child records for clean idempotent replacement
191
+ db.query("DELETE FROM findings WHERE run_id = ?").run(runId);
192
+ db.query("DELETE FROM debug_findings WHERE run_id = ?").run(runId);
193
+ db.query("DELETE FROM run_agents WHERE run_id = ?").run(runId);
194
+ db.query("DELETE FROM diversity_observations WHERE run_id = ?").run(runId);
195
+ db.query("DELETE FROM diversity_attempts WHERE run_id = ?").run(runId);
196
+
197
+ // Insert findings + proof refs + hop trails
198
+ const insertFinding = db.query(`
199
+ INSERT INTO findings (
200
+ run_id, finding_id, category, path, line, symbol, severity,
201
+ evidence_class, refuter_verdict, causal_disposition, claim, hunter,
202
+ tier, hops_used, dedupe_key, root_cause_id, finding_order
203
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
204
+ `);
205
+
206
+ const insertProofRef = db.query(`
207
+ INSERT INTO finding_proof_refs (
208
+ finding_id, ref_order, proof_ref
209
+ ) VALUES (?, ?, ?)
210
+ `);
211
+
212
+ const insertHopTrail = db.query(`
213
+ INSERT INTO finding_hop_trail (
214
+ finding_id, step_order, step_num, kind, query, reached, is_raw_string
215
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
216
+ `);
217
+
218
+ for (const item of projected.findings) {
219
+ insertFinding.run(
220
+ runId,
221
+ item.finding.finding_id,
222
+ item.finding.category,
223
+ item.finding.path,
224
+ item.finding.line,
225
+ item.finding.symbol,
226
+ item.finding.severity,
227
+ item.finding.evidence_class,
228
+ item.finding.refuter_verdict,
229
+ item.finding.causal_disposition,
230
+ item.finding.claim,
231
+ item.finding.hunter,
232
+ item.finding.tier,
233
+ item.finding.hops_used,
234
+ item.finding.dedupe_key,
235
+ item.finding.root_cause_id,
236
+ item.finding.finding_order,
237
+ );
238
+
239
+ const fRow = db
240
+ .query("SELECT id FROM findings WHERE run_id = ? AND finding_id = ?")
241
+ .get(runId, item.finding.finding_id) as { id: number };
242
+ const findingDbId = fRow.id;
243
+
244
+ item.proofRefs.forEach((ref, refIndex) => {
245
+ insertProofRef.run(findingDbId, refIndex, ref);
246
+ });
247
+
248
+ item.hopTrail.forEach((hop, hopIndex) => {
249
+ if (typeof hop === "string") {
250
+ insertHopTrail.run(
251
+ findingDbId,
252
+ hopIndex,
253
+ hopIndex + 1,
254
+ "trace",
255
+ hop,
256
+ null,
257
+ 1,
258
+ );
259
+ } else {
260
+ insertHopTrail.run(
261
+ findingDbId,
262
+ hopIndex,
263
+ hop.step ?? hopIndex + 1,
264
+ hop.kind ?? "trace",
265
+ hop.query ?? "",
266
+ hop.reached ?? null,
267
+ 0,
268
+ );
269
+ }
270
+ });
271
+ }
272
+
273
+ // Insert debug findings
274
+ if (projected.debugFindings.length > 0) {
275
+ const insertDebug = db.query(`
276
+ INSERT INTO debug_findings (
277
+ run_id, finding_id, kind, merged_into, category, path, line, symbol,
278
+ severity, evidence_class, refuter_verdict, causal_disposition, claim,
279
+ proof_refs_json, hunter, hops_used, hop_trail_json, dedupe_key,
280
+ root_cause_id, debug_order
281
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
282
+ `);
283
+ for (const d of projected.debugFindings) {
284
+ insertDebug.run(
285
+ runId,
286
+ d.finding_id,
287
+ d.kind,
288
+ d.merged_into,
289
+ d.category,
290
+ d.path,
291
+ d.line,
292
+ d.symbol,
293
+ d.severity,
294
+ d.evidence_class,
295
+ d.refuter_verdict,
296
+ d.causal_disposition,
297
+ d.claim,
298
+ d.proof_refs_json,
299
+ d.hunter,
300
+ d.hops_used,
301
+ d.hop_trail_json,
302
+ d.dedupe_key,
303
+ d.root_cause_id,
304
+ d.debug_order,
305
+ );
306
+ }
307
+ }
308
+
309
+ // Insert run agents
310
+ if (projected.agents.length > 0) {
311
+ const insertAgent = db.query(`
312
+ INSERT INTO run_agents (
313
+ run_id, agent_key, tokens_total, duration_ms, tokens_in, tokens_out,
314
+ cost_usd_est, attempts, status
315
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
316
+ `);
317
+ for (const a of projected.agents) {
318
+ insertAgent.run(
319
+ runId,
320
+ a.agent_key,
321
+ a.tokens_total,
322
+ a.duration_ms,
323
+ a.tokens_in,
324
+ a.tokens_out,
325
+ a.cost_usd_est,
326
+ a.attempts,
327
+ a.status,
328
+ );
329
+ }
330
+ }
331
+
332
+ if (projected.diversityAttempts.length > 0) {
333
+ const insertAttempt = db.query(`
334
+ INSERT INTO diversity_attempts (
335
+ run_id, attempt_id, leg_id, arm_id, specialty, replicate, attempt,
336
+ status, cash_cost_usd, notional_cost_usd
337
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
338
+ `);
339
+ for (const attempt of projected.diversityAttempts) {
340
+ insertAttempt.run(
341
+ runId,
342
+ attempt.attempt_id,
343
+ attempt.leg_id,
344
+ attempt.arm_id,
345
+ attempt.specialty,
346
+ attempt.replicate,
347
+ attempt.attempt,
348
+ attempt.status,
349
+ attempt.cash_cost_usd,
350
+ attempt.notional_cost_usd,
351
+ );
352
+ }
353
+ }
354
+
355
+ if (projected.diversityObservations.length > 0) {
356
+ const insertObservation = db.query(`
357
+ INSERT INTO diversity_observations (
358
+ run_id, observation_id, attempt_id, leg_id, arm_id, specialty,
359
+ observation_json
360
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
361
+ `);
362
+ for (const observation of projected.diversityObservations) {
363
+ insertObservation.run(
364
+ runId,
365
+ observation.observation_id,
366
+ observation.attempt_id,
367
+ observation.leg_id,
368
+ observation.arm_id,
369
+ observation.specialty,
370
+ observation.observation_json,
371
+ );
372
+ }
373
+ }
374
+ })();
375
+
376
+ return runId;
377
+ }
378
+
379
+ export function getRunById(
380
+ db: Database,
381
+ runId: number,
382
+ ): CanonicalRunRow | null {
383
+ const row = db.query("SELECT * FROM runs WHERE id = ?").get(runId);
384
+ return (row as CanonicalRunRow) ?? null;
385
+ }
386
+
387
+ export function getRunByDir(
388
+ db: Database,
389
+ repoId: string,
390
+ runDir: string,
391
+ ): CanonicalRunRow | null {
392
+ const row = db
393
+ .query("SELECT * FROM runs WHERE repo_id = ? AND run_dir = ?")
394
+ .get(repoId, runDir);
395
+ return (row as CanonicalRunRow) ?? null;
396
+ }
397
+
398
+ export function exportFindingsDocument(
399
+ db: Database,
400
+ runId: number,
401
+ ): FindingsDocument | null {
402
+ const run = getRunById(db, runId);
403
+ if (!run) return null;
404
+
405
+ // Retrieve findings
406
+ const findingRows = db
407
+ .query("SELECT * FROM findings WHERE run_id = ? ORDER BY finding_order ASC")
408
+ .all(runId) as (CanonicalFindingRow & { id: number })[];
409
+
410
+ const findings: Finding[] = [];
411
+ for (const f of findingRows) {
412
+ const proofRefRows = db
413
+ .query(
414
+ "SELECT proof_ref FROM finding_proof_refs WHERE finding_id = ? ORDER BY ref_order ASC",
415
+ )
416
+ .all(f.id) as { proof_ref: string }[];
417
+
418
+ const hopTrailRows = db
419
+ .query(
420
+ "SELECT step_num, kind, query, reached, is_raw_string FROM finding_hop_trail WHERE finding_id = ? ORDER BY step_order ASC",
421
+ )
422
+ .all(f.id) as {
423
+ step_num: number;
424
+ kind: string;
425
+ query: string;
426
+ reached: string | null;
427
+ is_raw_string: number;
428
+ }[];
429
+
430
+ const isRaw =
431
+ hopTrailRows.length > 0 && hopTrailRows[0]?.is_raw_string === 1;
432
+ const hop_trail: HopTrail = isRaw
433
+ ? hopTrailRows.map((h) => h.query)
434
+ : hopTrailRows.map((h) => ({
435
+ step: h.step_num,
436
+ kind: h.kind,
437
+ query: h.query,
438
+ reached: h.reached ?? "",
439
+ }));
440
+
441
+ findings.push({
442
+ id: f.finding_id,
443
+ category: f.category,
444
+ path: f.path,
445
+ line: f.line,
446
+ ...(f.symbol ? { symbol: f.symbol } : {}),
447
+ severity: f.severity,
448
+ evidence_class: f.evidence_class,
449
+ refuter_verdict: f.refuter_verdict,
450
+ causal_disposition: f.causal_disposition,
451
+ claim: f.claim,
452
+ proof_refs: proofRefRows.map((p) => p.proof_ref),
453
+ hunter: f.hunter,
454
+ tier: f.tier,
455
+ hops_used: f.hops_used,
456
+ hop_trail,
457
+ dedupe_key: f.dedupe_key,
458
+ ...(f.root_cause_id ? { root_cause_id: f.root_cause_id } : {}),
459
+ });
460
+ }
461
+
462
+ // Retrieve debug findings
463
+ const debugRows = db
464
+ .query(
465
+ "SELECT * FROM debug_findings WHERE run_id = ? ORDER BY debug_order ASC",
466
+ )
467
+ .all(runId) as DebugFindingRow[];
468
+
469
+ const refuted: DebugRefutedFinding[] = [];
470
+ const deduped: DebugDedupedFinding[] = [];
471
+
472
+ for (const d of debugRows) {
473
+ const proof_refs = JSON.parse(d.proof_refs_json) as string[];
474
+ const hop_trail = JSON.parse(d.hop_trail_json) as HopTrailStep[];
475
+
476
+ if (d.kind === "refuted") {
477
+ refuted.push({
478
+ id: d.finding_id,
479
+ category: d.category,
480
+ path: d.path,
481
+ line: d.line,
482
+ ...(d.symbol ? { symbol: d.symbol } : {}),
483
+ severity: d.severity,
484
+ evidence_class: d.evidence_class,
485
+ refuter_verdict: "refuted",
486
+ causal_disposition: d.causal_disposition,
487
+ claim: d.claim,
488
+ proof_refs,
489
+ hunter: d.hunter,
490
+ hops_used: d.hops_used,
491
+ hop_trail,
492
+ dedupe_key: d.dedupe_key,
493
+ ...(d.root_cause_id ? { root_cause_id: d.root_cause_id } : {}),
494
+ });
495
+ } else {
496
+ deduped.push({
497
+ id: d.finding_id,
498
+ category: d.category,
499
+ path: d.path,
500
+ line: d.line,
501
+ ...(d.symbol ? { symbol: d.symbol } : {}),
502
+ severity: d.severity,
503
+ evidence_class: d.evidence_class,
504
+ refuter_verdict: d.refuter_verdict,
505
+ causal_disposition: d.causal_disposition,
506
+ claim: d.claim,
507
+ proof_refs,
508
+ hunter: d.hunter,
509
+ hops_used: d.hops_used,
510
+ hop_trail,
511
+ dedupe_key: d.dedupe_key,
512
+ ...(d.root_cause_id ? { root_cause_id: d.root_cause_id } : {}),
513
+ merged_into: d.merged_into ?? "",
514
+ });
515
+ }
516
+ }
517
+
518
+ // Per agent usage for telemetry
519
+ const agentRows = db
520
+ .query(
521
+ "SELECT agent_key, tokens_total, duration_ms FROM run_agents WHERE run_id = ?",
522
+ )
523
+ .all(runId) as {
524
+ agent_key: string;
525
+ tokens_total: number;
526
+ duration_ms: number;
527
+ }[];
528
+
529
+ const per_agent: Record<
530
+ string,
531
+ { tokens_total: number; duration_ms: number }
532
+ > = {};
533
+ for (const a of agentRows) {
534
+ per_agent[a.agent_key] = {
535
+ tokens_total: a.tokens_total,
536
+ duration_ms: a.duration_ms,
537
+ };
538
+ }
539
+
540
+ const telemetry: Telemetry = {
541
+ index_ms: run.index_ms,
542
+ index_mode: (run.index_mode ?? "sync") as IndexMode,
543
+ ...(run.sync_ms !== null ? { sync_ms: run.sync_ms } : {}),
544
+ index_disk_mb: run.index_disk_mb ?? 0,
545
+ wall_ms: run.wall_ms,
546
+ tokens_in: run.tokens_in,
547
+ tokens_out: run.tokens_out,
548
+ tokens_total: run.tokens_total,
549
+ cost_usd_est: run.cost_usd_est,
550
+ ...(agentRows.length > 0 ? { per_agent } : {}),
551
+ };
552
+
553
+ let summary: RunSummary | undefined;
554
+ if (
555
+ run.summary_prose &&
556
+ run.summary_score !== null &&
557
+ run.summary_score_reason
558
+ ) {
559
+ summary = {
560
+ prose: run.summary_prose,
561
+ score: run.summary_score,
562
+ score_reason: run.summary_score_reason,
563
+ };
564
+ }
565
+
566
+ const doc: FindingsDocument = {
567
+ schema_version: run.findings_schema_version ?? SCHEMA_VERSION,
568
+ pr: run.pr === null ? 0 : run.pr,
569
+ base_sha: run.base_sha,
570
+ head_sha: run.head_sha,
571
+ model: run.model,
572
+ iteration: run.iteration,
573
+ ...(run.prompt_set_name && run.prompt_set_sha256
574
+ ? {
575
+ prompt_set: {
576
+ name: run.prompt_set_name,
577
+ sha256: run.prompt_set_sha256,
578
+ },
579
+ }
580
+ : {}),
581
+ ...(run.driver_sha ? { driver_sha: run.driver_sha } : {}),
582
+ ...(run.engine_name && run.engine_version
583
+ ? {
584
+ engine: {
585
+ name: run.engine_name,
586
+ version: run.engine_version,
587
+ ...(run.engine_revision ? { revision: run.engine_revision } : {}),
588
+ },
589
+ }
590
+ : {}),
591
+ parity_hunter_fired: Boolean(run.parity_hunter_fired),
592
+ run_status: run.run_status,
593
+ ...(run.session_failed !== null
594
+ ? { sessionFailed: run.session_failed === 1 }
595
+ : {}),
596
+ ...(summary ? { summary } : {}),
597
+ telemetry,
598
+ findings,
599
+ debug: {
600
+ refuted,
601
+ ...(deduped.length > 0 ? { deduped } : {}),
602
+ ...(run.root_causes_json
603
+ ? { root_causes: JSON.parse(run.root_causes_json) }
604
+ : {}),
605
+ ...(run.diversity_plan_json
606
+ ? { diversity: JSON.parse(run.diversity_plan_json) }
607
+ : {}),
608
+ },
609
+ };
610
+
611
+ return validateFindingsDocument(doc);
612
+ }
613
+
614
+ export type StoreQueryScope = { repoId: string } | { all: true };
615
+
616
+ export function queryRuns(
617
+ db: Database,
618
+ scope: StoreQueryScope,
619
+ ): CanonicalRunRow[] {
620
+ if ("all" in scope) {
621
+ return db
622
+ .query("SELECT * FROM runs ORDER BY generated_at DESC;")
623
+ .all() as CanonicalRunRow[];
624
+ }
625
+ return db
626
+ .query("SELECT * FROM runs WHERE repo_id = ? ORDER BY generated_at DESC;")
627
+ .all(scope.repoId) as CanonicalRunRow[];
628
+ }
629
+
630
+ export function recordFindingTriage(
631
+ db: Database,
632
+ triage: FindingTriageRow,
633
+ ): number {
634
+ const runTx = db.transaction(() => {
635
+ const existing = db
636
+ .query(
637
+ "SELECT id FROM finding_triage WHERE run_id = ? AND finding_id = ? AND ifnull(comment_id, 0) = ifnull(?, 0) LIMIT 1",
638
+ )
639
+ .get(triage.run_id, triage.finding_id, triage.comment_id ?? null) as {
640
+ id: number;
641
+ } | null;
642
+ if (existing) {
643
+ db.query(`
644
+ UPDATE finding_triage
645
+ SET tag = ?, verdict = ?, actor = ?, reasoning = ?, issue_number = ?, created_at = ?
646
+ WHERE id = ?
647
+ `).run(
648
+ triage.tag,
649
+ triage.verdict ?? null,
650
+ triage.actor,
651
+ triage.reasoning,
652
+ triage.issue_number ?? null,
653
+ triage.created_at,
654
+ existing.id,
655
+ );
656
+ return existing.id;
657
+ }
658
+
659
+ const insert = db.query(`
660
+ INSERT INTO finding_triage (
661
+ run_id, finding_id, comment_id, tag, verdict, actor, reasoning, issue_number, created_at
662
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
663
+ `);
664
+
665
+ insert.run(
666
+ triage.run_id,
667
+ triage.finding_id,
668
+ triage.comment_id ?? null,
669
+ triage.tag,
670
+ triage.verdict ?? null,
671
+ triage.actor,
672
+ triage.reasoning,
673
+ triage.issue_number ?? null,
674
+ triage.created_at,
675
+ );
676
+
677
+ const lastId = (
678
+ db.query("SELECT last_insert_rowid() as id").get() as { id: number }
679
+ ).id;
680
+ return lastId;
681
+ });
682
+
683
+ return runTx();
684
+ }
685
+
686
+ export function getFindingTriageByRunId(
687
+ db: Database,
688
+ runId: number,
689
+ ): FindingTriageRow[] {
690
+ return db
691
+ .query("SELECT * FROM finding_triage WHERE run_id = ? ORDER BY id ASC")
692
+ .all(runId) as FindingTriageRow[];
693
+ }