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,413 @@
1
+ import { Database } from "bun:sqlite";
2
+ import {
3
+ existsSync,
4
+ mkdirSync,
5
+ readdirSync,
6
+ readFileSync,
7
+ unlinkSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+ import { countLaunchedToday, localIsoTimestamp } from "#watch/preflight";
13
+ import { resolveHomeDir } from "../brand-paths";
14
+ import { prheroLayout } from "../home-preflight";
15
+
16
+ export interface ActiveRunRecord {
17
+ pid: number;
18
+ repo: string;
19
+ pr?: number;
20
+ runDir: string;
21
+ startedAt: string;
22
+ }
23
+
24
+ export function activeRunsDir(home: string): string {
25
+ return path.join(resolveHomeDir(home), "active_runs");
26
+ }
27
+
28
+ export function activeRunFilePath(home: string, pid: number): string {
29
+ return path.join(activeRunsDir(home), `${pid}.json`);
30
+ }
31
+
32
+ export function isPidAlive(
33
+ pid: number,
34
+ killFn: (pid: number, signal: number) => void = (p, s) => process.kill(p, s),
35
+ ): boolean {
36
+ try {
37
+ killFn(pid, 0);
38
+ return true;
39
+ } catch (err) {
40
+ return (err as { code?: string })?.code === "EPERM";
41
+ }
42
+ }
43
+
44
+ export interface RegisterActiveRunOptions {
45
+ home?: string;
46
+ writeFile?: (path: string, content: string) => void;
47
+ mkdir?: (path: string, opts?: { recursive?: boolean }) => void;
48
+ }
49
+
50
+ export async function registerActiveRun(
51
+ record: ActiveRunRecord,
52
+ options: RegisterActiveRunOptions = {},
53
+ ): Promise<void> {
54
+ const home = options.home ?? os.homedir();
55
+ const dir = activeRunsDir(home);
56
+ const targetPath = activeRunFilePath(home, record.pid);
57
+
58
+ const mkdir =
59
+ options.mkdir ??
60
+ ((p, o) => {
61
+ if (!options.writeFile) mkdirSync(p, o);
62
+ });
63
+ const writeFile =
64
+ options.writeFile ?? ((p, c) => writeFileSync(p, c, "utf-8"));
65
+
66
+ mkdir(dir, { recursive: true });
67
+ writeFile(targetPath, `${JSON.stringify(record, null, 2)}\n`);
68
+ }
69
+
70
+ export interface UnregisterActiveRunOptions {
71
+ home?: string;
72
+ unlink?: (path: string) => void;
73
+ exists?: (path: string) => boolean;
74
+ }
75
+
76
+ export async function unregisterActiveRun(
77
+ pid: number,
78
+ options: UnregisterActiveRunOptions = {},
79
+ ): Promise<void> {
80
+ const home = options.home ?? os.homedir();
81
+ const targetPath = activeRunFilePath(home, pid);
82
+ const exists = options.exists ?? existsSync;
83
+ const unlink = options.unlink ?? unlinkSync;
84
+
85
+ if (exists(targetPath)) {
86
+ try {
87
+ unlink(targetPath);
88
+ } catch {
89
+ // Ignore
90
+ }
91
+ }
92
+ }
93
+
94
+ export interface ListActiveRunsOptions {
95
+ home?: string;
96
+ readdir?: (dir: string) => string[];
97
+ readFile?: (path: string) => string | undefined;
98
+ exists?: (path: string) => boolean;
99
+ isAlive?: (pid: number) => boolean;
100
+ unlink?: (path: string) => void;
101
+ }
102
+
103
+ export async function listActiveRuns(
104
+ options: ListActiveRunsOptions = {},
105
+ ): Promise<ActiveRunRecord[]> {
106
+ const home = options.home ?? os.homedir();
107
+ const dir = activeRunsDir(home);
108
+ const exists = options.exists ?? existsSync;
109
+ const readdir = options.readdir ?? readdirSync;
110
+ const readFile =
111
+ options.readFile ??
112
+ ((p: string) => {
113
+ try {
114
+ return readFileSync(p, "utf-8");
115
+ } catch {
116
+ return undefined;
117
+ }
118
+ });
119
+ const isAlive = options.isAlive ?? isPidAlive;
120
+ const unlink = options.unlink ?? unlinkSync;
121
+
122
+ if (!exists(dir)) return [];
123
+
124
+ let entries: string[] = [];
125
+ try {
126
+ entries = readdir(dir);
127
+ } catch {
128
+ return [];
129
+ }
130
+
131
+ const activeRuns: ActiveRunRecord[] = [];
132
+
133
+ for (const entry of entries) {
134
+ if (!entry.endsWith(".json")) continue;
135
+ const fullPath = path.join(dir, entry);
136
+ const raw = readFile(fullPath);
137
+ if (!raw) continue;
138
+
139
+ try {
140
+ const parsed = JSON.parse(raw) as ActiveRunRecord;
141
+ if (!parsed.pid) continue;
142
+
143
+ if (!isAlive(parsed.pid)) {
144
+ // Stale entry: dead PID -> prune
145
+ try {
146
+ unlink(fullPath);
147
+ } catch {
148
+ // Ignore
149
+ }
150
+ continue;
151
+ }
152
+
153
+ activeRuns.push(parsed);
154
+ } catch {
155
+ // Malformed JSON -> prune
156
+ try {
157
+ unlink(fullPath);
158
+ } catch {
159
+ // Ignore
160
+ }
161
+ }
162
+ }
163
+
164
+ activeRuns.sort((a, b) => Date.parse(a.startedAt) - Date.parse(b.startedAt));
165
+ return activeRuns;
166
+ }
167
+
168
+ export async function checkProcessIdentity(
169
+ pid: number,
170
+ execFn?: (cmd: string[]) => Promise<string>,
171
+ ): Promise<boolean> {
172
+ const exec =
173
+ execFn ??
174
+ (async (cmd: string[]) => {
175
+ const proc = Bun.spawn(cmd, { stdout: "pipe", stderr: "pipe" });
176
+ await proc.exited;
177
+ return await new Response(proc.stdout).text();
178
+ });
179
+
180
+ try {
181
+ const cmdline = await exec(["ps", "-o", "command=", "-p", `${pid}`]);
182
+ const trimmed = cmdline.trim();
183
+ if (!trimmed) return false;
184
+ return (
185
+ trimmed.includes("crysk") ||
186
+ trimmed.includes("pr-hero") ||
187
+ trimmed.includes("src/cli.ts") ||
188
+ (trimmed.includes("bun") && trimmed.includes("review")) ||
189
+ (trimmed.includes("node") && trimmed.includes("review"))
190
+ );
191
+ } catch {
192
+ return false;
193
+ }
194
+ }
195
+
196
+ export type KillResult =
197
+ | { status: "not_found"; message: string }
198
+ | { status: "identity_mismatch"; message: string }
199
+ | {
200
+ status: "terminated";
201
+ pid: number;
202
+ signal: "SIGTERM" | "SIGKILL";
203
+ escalated: boolean;
204
+ warning?: string;
205
+ };
206
+
207
+ export interface KillActiveRunOptions {
208
+ home?: string;
209
+ isAlive?: (pid: number) => boolean;
210
+ checkIdentity?: (pid: number) => Promise<boolean>;
211
+ sendSignal?: (pid: number, signal: string | number) => void;
212
+ sleep?: (ms: number) => Promise<void>;
213
+ timeoutMs?: number;
214
+ unregister?: (pid: number) => Promise<void>;
215
+ }
216
+
217
+ export async function killActiveRun(
218
+ pid: number,
219
+ options: KillActiveRunOptions = {},
220
+ ): Promise<KillResult> {
221
+ const home = options.home ?? os.homedir();
222
+ const isAlive = options.isAlive ?? isPidAlive;
223
+ const checkIdentity = options.checkIdentity ?? checkProcessIdentity;
224
+ const sendSignal =
225
+ options.sendSignal ??
226
+ ((p: number, s: string | number) => {
227
+ process.kill(p, s);
228
+ });
229
+ const sleep =
230
+ options.sleep ??
231
+ ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
232
+ const timeoutMs = options.timeoutMs ?? 10000;
233
+ const unregister =
234
+ options.unregister ?? ((p: number) => unregisterActiveRun(p, { home }));
235
+
236
+ // 1. Check if process is alive
237
+ if (!isAlive(pid)) {
238
+ await unregister(pid);
239
+ return {
240
+ status: "not_found",
241
+ message: `No active run with PID ${pid} (process is not running).`,
242
+ };
243
+ }
244
+
245
+ // 2. Check identity
246
+ const isTargetIdentity = await checkIdentity(pid);
247
+ if (!isTargetIdentity) {
248
+ await unregister(pid);
249
+ return {
250
+ status: "identity_mismatch",
251
+ message: `PID ${pid} is running another command (PID reuse). Pruned stale entry without signalling.`,
252
+ };
253
+ }
254
+
255
+ // 3. Send SIGTERM
256
+ try {
257
+ sendSignal(pid, "SIGTERM");
258
+ } catch {
259
+ await unregister(pid);
260
+ return {
261
+ status: "not_found",
262
+ message: `Process ${pid} exited before signal could be delivered.`,
263
+ };
264
+ }
265
+
266
+ // 4. Bounded wait up to timeoutMs
267
+ const startMs = Date.now();
268
+ while (Date.now() - startMs < timeoutMs) {
269
+ if (!isAlive(pid)) {
270
+ await unregister(pid);
271
+ return {
272
+ status: "terminated",
273
+ pid,
274
+ signal: "SIGTERM",
275
+ escalated: false,
276
+ };
277
+ }
278
+ await sleep(100);
279
+ }
280
+
281
+ // 5. Escalate to SIGKILL if still alive
282
+ try {
283
+ sendSignal(pid, "SIGKILL");
284
+ } catch {
285
+ // Process exited during escalation
286
+ }
287
+ await sleep(100);
288
+ await unregister(pid);
289
+
290
+ return {
291
+ status: "terminated",
292
+ pid,
293
+ signal: "SIGKILL",
294
+ escalated: true,
295
+ warning:
296
+ "Process did not exit after SIGTERM. Escalated to SIGKILL. Agent subprocesses may have survived; check with 'ps aux | grep claude'.",
297
+ };
298
+ }
299
+
300
+ export interface GetWatcherSpendOptions {
301
+ home?: string;
302
+ countLaunchedToday?: () => Promise<number>;
303
+ readConfig?: () => Promise<{ daily_cap?: number; dailyCap?: number }>;
304
+ }
305
+
306
+ export async function getWatcherSpend(
307
+ options: GetWatcherSpendOptions = {},
308
+ ): Promise<{ launchedToday: number; dailyCap: number }> {
309
+ const home = options.home ?? os.homedir();
310
+ const layout = prheroLayout(home);
311
+
312
+ let launchedToday = 0;
313
+ if (options.countLaunchedToday) {
314
+ launchedToday = await options.countLaunchedToday();
315
+ } else if (existsSync(layout.logPath)) {
316
+ try {
317
+ const raw = readFileSync(layout.logPath, "utf-8");
318
+ const todayIso = localIsoTimestamp(new Date()).slice(0, 10);
319
+ launchedToday = countLaunchedToday(raw, todayIso);
320
+ } catch {
321
+ launchedToday = 0;
322
+ }
323
+ }
324
+
325
+ let dailyCap = 8;
326
+ if (options.readConfig) {
327
+ const cfg = await options.readConfig();
328
+ if (cfg?.daily_cap !== undefined) dailyCap = cfg.daily_cap;
329
+ else if (cfg?.dailyCap !== undefined) dailyCap = cfg.dailyCap;
330
+ } else if (existsSync(layout.watchConfigPath)) {
331
+ try {
332
+ const raw = readFileSync(layout.watchConfigPath, "utf-8");
333
+ const cfg = JSON.parse(raw);
334
+ if (cfg?.daily_cap !== undefined) dailyCap = cfg.daily_cap;
335
+ else if (cfg?.dailyCap !== undefined) dailyCap = cfg.dailyCap;
336
+ } catch {
337
+ dailyCap = 8;
338
+ }
339
+ }
340
+
341
+ return { launchedToday, dailyCap };
342
+ }
343
+
344
+ export interface RunHistoryItem {
345
+ id: string;
346
+ run_status: string;
347
+ blocking: number;
348
+ advisory: number;
349
+ wall_ms: number;
350
+ cost_usd_est: number;
351
+ generated_at: string;
352
+ pr?: number;
353
+ repo_id?: string;
354
+ }
355
+
356
+ export interface QueryRecentRunsOptions {
357
+ home?: string;
358
+ dbPath?: string;
359
+ limit?: number;
360
+ dbQuery?: (limit: number) => Promise<RunHistoryItem[]>;
361
+ }
362
+
363
+ export async function queryRecentRuns(
364
+ options: QueryRecentRunsOptions = {},
365
+ ): Promise<RunHistoryItem[]> {
366
+ const limit = options.limit ?? 10;
367
+
368
+ if (options.dbQuery) {
369
+ return await options.dbQuery(limit);
370
+ }
371
+
372
+ const home = options.home ?? os.homedir();
373
+ const layout = prheroLayout(home);
374
+ const dbPath = options.dbPath ?? layout.prheroDbPath;
375
+
376
+ if (!existsSync(dbPath)) {
377
+ return [];
378
+ }
379
+
380
+ let db: Database | undefined;
381
+ try {
382
+ db = new Database(dbPath, { readonly: true });
383
+ // Check if runs table exists
384
+ const tableExists = db
385
+ .query(
386
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='runs'",
387
+ )
388
+ .get() as { name?: string } | null;
389
+ if (!tableExists) {
390
+ db.close();
391
+ return [];
392
+ }
393
+
394
+ const rows = db
395
+ .query(
396
+ `SELECT id, run_status, blocking, advisory, wall_ms, cost_usd_est, generated_at, pr, repo_id
397
+ FROM runs
398
+ ORDER BY generated_at DESC
399
+ LIMIT ?`,
400
+ )
401
+ .all(limit) as RunHistoryItem[];
402
+
403
+ db.close();
404
+ return rows;
405
+ } catch {
406
+ try {
407
+ db?.close();
408
+ } catch {
409
+ // Ignore
410
+ }
411
+ return [];
412
+ }
413
+ }
@@ -0,0 +1,49 @@
1
+ // Canonical product store (Fundamentals #6 / observability-canonical-store.md),
2
+ // backfill pure half: path matchers, stats accumulators, and report renderers.
3
+ //
4
+ // Pure and testable offline: no filesystem, no database handles.
5
+
6
+ export interface BackfillStats {
7
+ discovered: number;
8
+ ingested: number;
9
+ skipped: number;
10
+ errors: number;
11
+ total_tokens: number;
12
+ total_cost_usd: number;
13
+ }
14
+
15
+ export function createEmptyBackfillStats(): BackfillStats {
16
+ return {
17
+ discovered: 0,
18
+ ingested: 0,
19
+ skipped: 0,
20
+ errors: 0,
21
+ total_tokens: 0,
22
+ total_cost_usd: 0,
23
+ };
24
+ }
25
+
26
+ export function parseRepoIdFromRelPath(relPath: string): string | null {
27
+ // e.g. "github.com/owner/repo/runs/pr-42-abc-1/findings.json"
28
+ // or "github.com/owner/repo/runs/local-abc-1/findings.json"
29
+ const parts = relPath.split("/");
30
+ const runsIndex = parts.indexOf("runs");
31
+ if (runsIndex > 0) {
32
+ return parts.slice(0, runsIndex).join("/");
33
+ }
34
+ return null;
35
+ }
36
+
37
+ export function renderBackfillReport(stats: BackfillStats): string {
38
+ const lines = [
39
+ "Canonical Product Store Backfill Report",
40
+ "=======================================",
41
+ `Discovered runs: ${stats.discovered}`,
42
+ `Ingested runs: ${stats.ingested}`,
43
+ `Skipped runs: ${stats.skipped}`,
44
+ `Errors: ${stats.errors}`,
45
+ `Total tokens: ${stats.total_tokens.toLocaleString()}`,
46
+ `Total cost USD: $${stats.total_cost_usd.toFixed(2)}`,
47
+ ];
48
+ return lines.join("\n");
49
+ }
@@ -0,0 +1,141 @@
1
+ // Canonical product store (Fundamentals #6 / observability-canonical-store.md),
2
+ // historical backfill & metrics.db migration module.
3
+ //
4
+ // Ingests historical findings.json runs across ~/.prhero/repos into
5
+ // ~/.prhero/prhero.db idempotently. comparison.json is no longer read: PR mode
6
+ // stopped writing it, and the store keeps whatever diff_from_sha and
7
+ // greptile_found it already holds (a re-save never overwrites them with NULL).
8
+
9
+ import { copyFileSync, existsSync } from "node:fs";
10
+ import { stat } from "node:fs/promises";
11
+ import path from "node:path";
12
+ import {
13
+ type FindingsDocument,
14
+ validateFindingsDocument,
15
+ } from "#review/findings";
16
+ import { prheroLayout } from "../home-preflight";
17
+ import {
18
+ type BackfillStats,
19
+ createEmptyBackfillStats,
20
+ parseRepoIdFromRelPath,
21
+ } from "./backfill-preflight";
22
+ import { projectCompleteRun } from "./preflight";
23
+ import { openProductStore, saveRunTransaction } from "./store";
24
+
25
+ export interface BackfillOptions {
26
+ home: string;
27
+ reposDir?: string;
28
+ dbPath?: string;
29
+ log?: (msg: string) => void;
30
+ }
31
+
32
+ export async function backfillHistoricalRuns(
33
+ options: BackfillOptions,
34
+ ): Promise<BackfillStats> {
35
+ const layout = prheroLayout(options.home);
36
+ const reposDir = options.reposDir ?? layout.reposDir;
37
+ const dbPath = options.dbPath ?? layout.prheroDbPath;
38
+ const stats = createEmptyBackfillStats();
39
+
40
+ if (!existsSync(reposDir)) {
41
+ return stats;
42
+ }
43
+
44
+ const db = openProductStore(dbPath);
45
+ try {
46
+ const glob = new Bun.Glob("**/findings.json");
47
+ for await (const rel of glob.scan({ cwd: reposDir })) {
48
+ stats.discovered++;
49
+ const findingsPath = path.join(reposDir, rel);
50
+ const runDir = path.dirname(findingsPath);
51
+ const runDirName = path.basename(runDir);
52
+
53
+ try {
54
+ const text = await Bun.file(findingsPath).text();
55
+ const json = JSON.parse(text);
56
+ let doc: FindingsDocument;
57
+ try {
58
+ doc = validateFindingsDocument(json);
59
+ } catch (err) {
60
+ stats.errors++;
61
+ options.log?.(
62
+ `warning: invalid findings.json in ${runDir}: ${(err as Error).message}`,
63
+ );
64
+ continue;
65
+ }
66
+
67
+ // Try reading pipeline.json for provenance / repo_id / when the run happened
68
+ let repoId = parseRepoIdFromRelPath(rel);
69
+ let pipelineGeneratedAt: string | null = null;
70
+ const pipelinePath = path.join(runDir, "pipeline.json");
71
+ if (existsSync(pipelinePath)) {
72
+ try {
73
+ const pipeJson = JSON.parse(await Bun.file(pipelinePath).text());
74
+ if (pipeJson.repo_id && typeof pipeJson.repo_id === "string") {
75
+ repoId = pipeJson.repo_id;
76
+ }
77
+ if (typeof pipeJson.generated_at === "string") {
78
+ pipelineGeneratedAt = pipeJson.generated_at;
79
+ }
80
+ } catch {}
81
+ }
82
+
83
+ if (!repoId) {
84
+ stats.skipped++;
85
+ options.log?.(
86
+ `warning: could not determine repo_id for ${runDir}; skipped`,
87
+ );
88
+ continue;
89
+ }
90
+
91
+ const { mtime } = await stat(findingsPath);
92
+ const generatedAt = pipelineGeneratedAt ?? mtime.toISOString();
93
+
94
+ const projected = projectCompleteRun({
95
+ doc,
96
+ perAgent: {},
97
+ repoId,
98
+ runDir: runDirName,
99
+ checkoutPath: null,
100
+ generatedAt,
101
+ });
102
+
103
+ saveRunTransaction(db, projected, { keepGeneratedAt: true });
104
+ stats.ingested++;
105
+ stats.total_tokens += doc.telemetry.tokens_total;
106
+ stats.total_cost_usd += doc.telemetry.cost_usd_est;
107
+ } catch (err) {
108
+ stats.errors++;
109
+ options.log?.(
110
+ `error: failed to backfill ${runDir}: ${(err as Error).message}`,
111
+ );
112
+ }
113
+ }
114
+ } finally {
115
+ db.close();
116
+ }
117
+
118
+ return stats;
119
+ }
120
+
121
+ export interface MigrationResult {
122
+ migrated: boolean;
123
+ backupPath?: string;
124
+ }
125
+
126
+ export function migrateMetricsDb(home: string): MigrationResult {
127
+ const layout = prheroLayout(home);
128
+ if (!existsSync(layout.metricsDbPath)) {
129
+ return { migrated: false };
130
+ }
131
+
132
+ const backupPath = `${layout.metricsDbPath}.bak`;
133
+ if (!existsSync(backupPath)) {
134
+ copyFileSync(layout.metricsDbPath, backupPath);
135
+ }
136
+
137
+ return {
138
+ migrated: true,
139
+ backupPath,
140
+ };
141
+ }