@open-qa/qa 0.0.0-stage → 0.1.0-alpha.4

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 (313) hide show
  1. package/LICENSE +204 -0
  2. package/NOTICE +7 -0
  3. package/THIRD_PARTY.md +12 -0
  4. package/THIRD_PARTY_NOTICES.md +11 -0
  5. package/drizzle/0000_qa_core.sql +158 -0
  6. package/drizzle/0001_run_health.sql +3 -0
  7. package/drizzle/0002_bounded_cleanup.sql +5 -0
  8. package/drizzle/0003_step_replay_cache.sql +9 -0
  9. package/drizzle/0004_credential_expiry.sql +1 -0
  10. package/drizzle/0005_server_api.sql +19 -0
  11. package/drizzle/0006_submission_created.sql +3 -0
  12. package/drizzle/0007_findings.sql +19 -0
  13. package/drizzle/0008_classification_labels.sql +14 -0
  14. package/drizzle/0009_job_queue.sql +20 -0
  15. package/drizzle/0010_result_notifications.sql +13 -0
  16. package/drizzle/0011_result_notification_retries.sql +5 -0
  17. package/drizzle/0012_result_notification_flows.sql +44 -0
  18. package/drizzle/0013_flow_quarantine.sql +35 -0
  19. package/drizzle/0014_run_budgets.sql +2 -0
  20. package/drizzle/0015_flow_lifecycle.sql +9 -0
  21. package/drizzle/0016_open_qa_classification.sql +28 -0
  22. package/drizzle/meta/0000_snapshot.json +1002 -0
  23. package/drizzle/meta/0001_snapshot.json +1021 -0
  24. package/drizzle/meta/0002_snapshot.json +1027 -0
  25. package/drizzle/meta/0003_snapshot.json +1081 -0
  26. package/drizzle/meta/0004_snapshot.json +1087 -0
  27. package/drizzle/meta/0005_snapshot.json +1210 -0
  28. package/drizzle/meta/0006_snapshot.json +1244 -0
  29. package/drizzle/meta/0007_snapshot.json +1353 -0
  30. package/drizzle/meta/0008_snapshot.json +1435 -0
  31. package/drizzle/meta/0009_snapshot.json +1587 -0
  32. package/drizzle/meta/0010_snapshot.json +1675 -0
  33. package/drizzle/meta/0011_snapshot.json +1692 -0
  34. package/drizzle/meta/0012_snapshot.json +1818 -0
  35. package/drizzle/meta/0013_snapshot.json +2016 -0
  36. package/drizzle/meta/0014_snapshot.json +2028 -0
  37. package/drizzle/meta/0015_snapshot.json +2064 -0
  38. package/drizzle/meta/0016_snapshot.json +2076 -0
  39. package/drizzle/meta/_journal.json +125 -0
  40. package/package.json +118 -4
  41. package/problem-matcher.json +32 -0
  42. package/src/adapters/db-lease-pool.d.ts +25 -0
  43. package/src/adapters/db-lease-pool.js +293 -0
  44. package/src/adapters/dir-artifact-store.d.ts +9 -0
  45. package/src/adapters/dir-artifact-store.js +64 -0
  46. package/src/adapters/e2b-agent.d.ts +7 -0
  47. package/src/adapters/e2b-agent.js +94 -0
  48. package/src/adapters/e2b-artifacts.d.ts +3 -0
  49. package/src/adapters/e2b-artifacts.js +66 -0
  50. package/src/adapters/e2b-bounded.d.ts +1 -0
  51. package/src/adapters/e2b-bounded.js +19 -0
  52. package/src/adapters/e2b-client.d.ts +33 -0
  53. package/src/adapters/e2b-client.js +114 -0
  54. package/src/adapters/e2b-executor.d.ts +26 -0
  55. package/src/adapters/e2b-executor.js +194 -0
  56. package/src/adapters/e2b-lifetime.d.ts +20 -0
  57. package/src/adapters/e2b-lifetime.js +73 -0
  58. package/src/adapters/e2b-prune.d.ts +13 -0
  59. package/src/adapters/e2b-prune.js +42 -0
  60. package/src/adapters/file-replay-cache.d.ts +14 -0
  61. package/src/adapters/file-replay-cache.js +120 -0
  62. package/src/adapters/file-run-store.d.ts +175 -0
  63. package/src/adapters/file-run-store.js +280 -0
  64. package/src/adapters/fixed-lease-pool.d.ts +10 -0
  65. package/src/adapters/fixed-lease-pool.js +237 -0
  66. package/src/adapters/gcs/artifact-store.d.ts +49 -0
  67. package/src/adapters/gcs/artifact-store.js +247 -0
  68. package/src/adapters/gcs/client.d.ts +22 -0
  69. package/src/adapters/gcs/client.js +106 -0
  70. package/src/adapters/gcs/download.d.ts +9 -0
  71. package/src/adapters/gcs/download.js +43 -0
  72. package/src/adapters/gcs/index.d.ts +8 -0
  73. package/src/adapters/gcs/index.js +23 -0
  74. package/src/adapters/gcs/periodic-flush.d.ts +5 -0
  75. package/src/adapters/gcs/periodic-flush.js +16 -0
  76. package/src/adapters/gcs/pg-catalog.d.ts +16 -0
  77. package/src/adapters/gcs/pg-catalog.js +149 -0
  78. package/src/adapters/gcs/replay-completeness.d.ts +1 -0
  79. package/src/adapters/gcs/replay-completeness.js +65 -0
  80. package/src/adapters/gcs/scan-upload.d.ts +10 -0
  81. package/src/adapters/gcs/scan-upload.js +26 -0
  82. package/src/adapters/index.d.ts +5 -0
  83. package/src/adapters/index.js +12 -0
  84. package/src/adapters/lease-transaction.d.ts +2 -0
  85. package/src/adapters/lease-transaction.js +61 -0
  86. package/src/adapters/local-credential-resolver.d.ts +5 -0
  87. package/src/adapters/local-credential-resolver.js +15 -0
  88. package/src/adapters/local-env.d.ts +1 -0
  89. package/src/adapters/local-env.js +37 -0
  90. package/src/adapters/local-files.d.ts +17 -0
  91. package/src/adapters/local-files.js +150 -0
  92. package/src/adapters/pg-classification-store.d.ts +58 -0
  93. package/src/adapters/pg-classification-store.js +112 -0
  94. package/src/adapters/pg-replay-cache.d.ts +16 -0
  95. package/src/adapters/pg-replay-cache.js +111 -0
  96. package/src/adapters/pg-run-store.d.ts +58 -0
  97. package/src/adapters/pg-run-store.js +399 -0
  98. package/src/adapters/resource-pools.d.ts +2 -0
  99. package/src/adapters/resource-pools.js +28 -0
  100. package/src/adapters/secret-manager-credential-resolver.d.ts +44 -0
  101. package/src/adapters/secret-manager-credential-resolver.js +102 -0
  102. package/src/artifact-scan.d.ts +21 -0
  103. package/src/artifact-scan.js +139 -0
  104. package/src/budget-confirmation.d.ts +23 -0
  105. package/src/budget-confirmation.js +43 -0
  106. package/src/cache-command.d.ts +7 -0
  107. package/src/cache-command.js +107 -0
  108. package/src/classification-command.d.ts +14 -0
  109. package/src/classification-command.js +72 -0
  110. package/src/classification-diff.d.ts +10 -0
  111. package/src/classification-diff.js +47 -0
  112. package/src/classification-model.d.ts +17 -0
  113. package/src/classification-model.js +51 -0
  114. package/src/classification-notifier.d.ts +21 -0
  115. package/src/classification-notifier.js +34 -0
  116. package/src/classify-runs.d.ts +31 -0
  117. package/src/classify-runs.js +138 -0
  118. package/src/cli-program.d.ts +9 -0
  119. package/src/cli-program.js +172 -0
  120. package/src/cli.d.ts +2 -0
  121. package/src/cli.js +12 -0
  122. package/src/commands.d.ts +7 -0
  123. package/src/commands.js +17 -0
  124. package/src/credential-references.d.ts +24 -0
  125. package/src/credential-references.js +33 -0
  126. package/src/db/commands.d.ts +1 -0
  127. package/src/db/commands.js +34 -0
  128. package/src/db/credentials.d.ts +16 -0
  129. package/src/db/credentials.js +73 -0
  130. package/src/db/database.d.ts +12 -0
  131. package/src/db/database.js +135 -0
  132. package/src/db/event-chunks.d.ts +405 -0
  133. package/src/db/event-chunks.js +74 -0
  134. package/src/db/fencing.d.ts +8 -0
  135. package/src/db/fencing.js +16 -0
  136. package/src/db/flow-status.d.ts +41 -0
  137. package/src/db/flow-status.js +208 -0
  138. package/src/db/index.d.ts +12 -0
  139. package/src/db/index.js +24 -0
  140. package/src/db/queries.d.ts +73 -0
  141. package/src/db/queries.js +122 -0
  142. package/src/db/resources.d.ts +14 -0
  143. package/src/db/resources.js +61 -0
  144. package/src/db/schema.d.ts +3532 -0
  145. package/src/db/schema.js +501 -0
  146. package/src/demo-command.d.ts +1 -0
  147. package/src/demo-command.js +50 -0
  148. package/src/doctor-command.d.ts +15 -0
  149. package/src/doctor-command.js +275 -0
  150. package/src/doctor-summary.d.ts +2 -0
  151. package/src/doctor-summary.js +31 -0
  152. package/src/draft-api.d.ts +460 -0
  153. package/src/draft-api.js +333 -0
  154. package/src/draft-command.d.ts +10 -0
  155. package/src/draft-command.js +73 -0
  156. package/src/draft-hooks.d.ts +3 -0
  157. package/src/draft-hooks.js +33 -0
  158. package/src/draft-pages.d.ts +11 -0
  159. package/src/draft-pages.js +82 -0
  160. package/src/engine.d.ts +105 -0
  161. package/src/engine.js +323 -0
  162. package/src/execution-snapshot.d.ts +21 -0
  163. package/src/execution-snapshot.js +141 -0
  164. package/src/flow-check.d.ts +9 -0
  165. package/src/flow-check.js +68 -0
  166. package/src/flow-lifecycle.d.ts +6 -0
  167. package/src/flow-lifecycle.js +61 -0
  168. package/src/flow-lint.d.ts +8 -0
  169. package/src/flow-lint.js +73 -0
  170. package/src/flow-loader.d.ts +219 -0
  171. package/src/flow-loader.js +236 -0
  172. package/src/flow-source.d.ts +2 -0
  173. package/src/flow-source.js +6 -0
  174. package/src/flows-api.d.ts +1 -0
  175. package/src/flows-api.js +12 -0
  176. package/src/heal-notification.d.ts +16 -0
  177. package/src/heal-notification.js +62 -0
  178. package/src/hooks/api.d.ts +29 -0
  179. package/src/hooks/api.js +15 -0
  180. package/src/hooks/consumer.d.ts +18 -0
  181. package/src/hooks/consumer.js +98 -0
  182. package/src/hooks/loader.d.ts +6 -0
  183. package/src/hooks/loader.js +28 -0
  184. package/src/hooks/registry.d.ts +22 -0
  185. package/src/hooks/registry.js +23 -0
  186. package/src/hooks/runner.d.ts +19 -0
  187. package/src/hooks/runner.js +279 -0
  188. package/src/hooks/session-cache.d.ts +16 -0
  189. package/src/hooks/session-cache.js +42 -0
  190. package/src/hooks/session-store.d.ts +20 -0
  191. package/src/hooks/session-store.js +95 -0
  192. package/src/hooks/worker.d.ts +1 -0
  193. package/src/hooks/worker.js +84 -0
  194. package/src/http-stage-client.d.ts +367 -0
  195. package/src/http-stage-client.js +190 -0
  196. package/src/independent-model.d.ts +22 -0
  197. package/src/independent-model.js +215 -0
  198. package/src/lifecycle-command.d.ts +15 -0
  199. package/src/lifecycle-command.js +190 -0
  200. package/src/local-command.d.ts +3 -0
  201. package/src/local-command.js +27 -0
  202. package/src/local-host-executor.d.ts +38 -0
  203. package/src/local-host-executor.js +196 -0
  204. package/src/open-command.d.ts +7 -0
  205. package/src/open-command.js +39 -0
  206. package/src/operations-api.d.ts +2 -0
  207. package/src/operations-api.js +6 -0
  208. package/src/personas.d.ts +2 -0
  209. package/src/personas.js +61 -0
  210. package/src/program-runner.d.ts +3 -0
  211. package/src/program-runner.js +263 -0
  212. package/src/program-sandbox.py +75 -0
  213. package/src/program-scratch.d.ts +2 -0
  214. package/src/program-scratch.js +48 -0
  215. package/src/program-worker.mjs +101 -0
  216. package/src/public-id.d.ts +2 -0
  217. package/src/public-id.js +5 -0
  218. package/src/public-report-url.d.ts +1 -0
  219. package/src/public-report-url.js +18 -0
  220. package/src/publication-check.d.ts +1 -0
  221. package/src/publication-check.js +31 -0
  222. package/src/quarantine-command.d.ts +9 -0
  223. package/src/quarantine-command.js +69 -0
  224. package/src/remote-command.d.ts +30 -0
  225. package/src/remote-command.js +156 -0
  226. package/src/replay-image.d.ts +1 -0
  227. package/src/replay-image.js +35 -0
  228. package/src/report/assets.d.ts +1 -0
  229. package/src/report/assets.js +5 -0
  230. package/src/report/browser.css +414 -0
  231. package/src/report/browser.d.ts +1 -0
  232. package/src/report/browser.js +219 -0
  233. package/src/report/data.d.ts +1 -0
  234. package/src/report/data.js +4 -0
  235. package/src/report/generate.d.ts +1 -0
  236. package/src/report/generate.js +54 -0
  237. package/src/report/load.d.ts +870 -0
  238. package/src/report/load.js +139 -0
  239. package/src/report/resource-table.d.ts +2 -0
  240. package/src/report/resource-table.js +4 -0
  241. package/src/report/status-icon.d.ts +2 -0
  242. package/src/report/status-icon.js +20 -0
  243. package/src/report/style.css +413 -0
  244. package/src/result-notifier.d.ts +121 -0
  245. package/src/result-notifier.js +230 -0
  246. package/src/result-transports.d.ts +12 -0
  247. package/src/result-transports.js +150 -0
  248. package/src/run-command.d.ts +32 -0
  249. package/src/run-command.js +493 -0
  250. package/src/run-setup-error.d.ts +11 -0
  251. package/src/run-setup-error.js +18 -0
  252. package/src/sandboxes-command.d.ts +9 -0
  253. package/src/sandboxes-command.js +29 -0
  254. package/src/screen-proxy.d.ts +5 -0
  255. package/src/screen-proxy.js +79 -0
  256. package/src/screen-url.d.ts +18 -0
  257. package/src/screen-url.js +54 -0
  258. package/src/server/app.d.ts +29 -0
  259. package/src/server/app.js +350 -0
  260. package/src/server/auth.d.ts +33 -0
  261. package/src/server/auth.js +113 -0
  262. package/src/server/credentials.d.ts +30 -0
  263. package/src/server/credentials.js +77 -0
  264. package/src/server/errors.d.ts +9 -0
  265. package/src/server/errors.js +26 -0
  266. package/src/server/index.d.ts +35 -0
  267. package/src/server/index.js +96 -0
  268. package/src/server/maintenance.d.ts +13 -0
  269. package/src/server/maintenance.js +54 -0
  270. package/src/server/repository.d.ts +534 -0
  271. package/src/server/repository.js +219 -0
  272. package/src/setup-command.d.ts +10 -0
  273. package/src/setup-command.js +52 -0
  274. package/src/stage-environment.d.ts +1 -0
  275. package/src/stage-environment.js +35 -0
  276. package/src/stage-supervisor.mjs +95 -0
  277. package/src/studio-command.d.ts +7 -0
  278. package/src/studio-command.js +47 -0
  279. package/src/studio-control.d.ts +5 -0
  280. package/src/studio-control.js +207 -0
  281. package/src/studio-review.d.ts +24 -0
  282. package/src/studio-review.js +64 -0
  283. package/src/studio-worker.d.ts +1 -0
  284. package/src/studio-worker.js +48 -0
  285. package/src/system-config.d.ts +7 -0
  286. package/src/system-config.js +70 -0
  287. package/src/terminal-reporter.d.ts +13 -0
  288. package/src/terminal-reporter.js +93 -0
  289. package/src/vendor/gmail.d.ts +45 -0
  290. package/src/vendor/gmail.js +193 -0
  291. package/src/watch-command.d.ts +16 -0
  292. package/src/watch-command.js +93 -0
  293. package/src/watch-state.d.ts +4 -0
  294. package/src/watch-state.js +53 -0
  295. package/src/worker/execution-error.d.ts +5 -0
  296. package/src/worker/execution-error.js +10 -0
  297. package/src/worker/execution.d.ts +24 -0
  298. package/src/worker/execution.js +190 -0
  299. package/src/worker/index.d.ts +8 -0
  300. package/src/worker/index.js +40 -0
  301. package/src/worker/prune.d.ts +3 -0
  302. package/src/worker/prune.js +22 -0
  303. package/src/worker/quarantine-notifications.d.ts +8 -0
  304. package/src/worker/quarantine-notifications.js +89 -0
  305. package/src/worker/queue.d.ts +65 -0
  306. package/src/worker/queue.js +438 -0
  307. package/src/worker/result-notifications.d.ts +28 -0
  308. package/src/worker/result-notifications.js +347 -0
  309. package/src/worker/store.d.ts +4 -0
  310. package/src/worker/store.js +46 -0
  311. package/src/worker/worker.d.ts +21 -0
  312. package/src/worker/worker.js +140 -0
  313. package/README.md +0 -3
@@ -0,0 +1,150 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, readdir, readFile, rename, rmdir, unlink } from "node:fs/promises";
4
+ import { hostname } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { setTimeout } from "node:timers/promises";
7
+ import { z } from "zod";
8
+ const lockOwnerSchema = z.object({
9
+ pid: z.number().int().positive(),
10
+ hostname: z.string(),
11
+ startedAt: z.number().finite().nonnegative(),
12
+ runId: z.string(),
13
+ resource: z.string().optional()
14
+ });
15
+ function hasCode(error, code) {
16
+ return error instanceof Error && "code" in error && error.code === code;
17
+ }
18
+ function runDirectory(qaRoot, runId) {
19
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(runId))
20
+ throw new Error("Invalid run ID: use 1-128 letters, digits, underscores or hyphens");
21
+ return join(resolve(qaRoot), "runs", runId);
22
+ }
23
+ function lockName(value) {
24
+ return createHash("sha256").update(value).digest("hex");
25
+ }
26
+ async function ensureDirectory(directory) {
27
+ try {
28
+ await mkdir(directory, { mode: 448 });
29
+ } catch (error) {
30
+ if (hasCode(error, "ENOENT")) {
31
+ await ensureDirectory(dirname(directory));
32
+ return ensureDirectory(directory);
33
+ }
34
+ if (!hasCode(error, "EEXIST")) throw error;
35
+ }
36
+ await assertDirectory(directory);
37
+ }
38
+ async function assertDirectory(directory) {
39
+ const stat = await lstat(directory);
40
+ if (stat.isSymbolicLink()) throw new Error("Local QA paths must not contain symbolic links");
41
+ if (!stat.isDirectory()) throw new Error("Expected a local QA directory");
42
+ }
43
+ async function assertRegularFile(file) {
44
+ const stat = await lstat(file);
45
+ if (stat.isSymbolicLink()) throw new Error("Local QA paths must not contain symbolic links");
46
+ if (!stat.isFile()) throw new Error("Expected a regular local QA file");
47
+ }
48
+ async function atomicWrite(file, data) {
49
+ const temporary = join(dirname(file), `.tmp-${randomUUID()}`);
50
+ const handle = await open(temporary, "wx", 384);
51
+ try {
52
+ await handle.writeFile(data);
53
+ await handle.sync();
54
+ await handle.close();
55
+ await rename(temporary, file);
56
+ } finally {
57
+ await handle.close();
58
+ await unlink(temporary).catch((error) => {
59
+ if (!hasCode(error, "ENOENT")) throw error;
60
+ });
61
+ }
62
+ }
63
+ async function acquireLock(directory, owner, context) {
64
+ await ensureDirectory(dirname(directory));
65
+ try {
66
+ await mkdir(directory, { mode: 448 });
67
+ } catch (error) {
68
+ if (hasCode(error, "EEXIST")) return false;
69
+ throw error;
70
+ }
71
+ try {
72
+ await atomicWrite(
73
+ join(directory, owner),
74
+ JSON.stringify({
75
+ pid: process.pid,
76
+ hostname: hostname(),
77
+ startedAt: Date.now(),
78
+ ...context
79
+ }) + "\n"
80
+ );
81
+ return true;
82
+ } catch (error) {
83
+ await rmdir(directory);
84
+ throw error;
85
+ }
86
+ }
87
+ async function lockConflict(directory) {
88
+ let holder = "owner unavailable (interrupted initialization or invalid metadata)";
89
+ try {
90
+ for (const entry of await readdir(directory)) {
91
+ if (!/^[a-f0-9-]{36}$/.test(entry)) continue;
92
+ const parsed = lockOwnerSchema.safeParse(
93
+ JSON.parse(await readFile(join(directory, entry), "utf8"))
94
+ );
95
+ if (parsed.success) {
96
+ const value = parsed.data;
97
+ holder = `run ${JSON.stringify(value.runId)}, pid ${value.pid}, host ${JSON.stringify(value.hostname)}, started at ${value.startedAt}`;
98
+ break;
99
+ }
100
+ }
101
+ } catch (error) {
102
+ if (!hasCode(error, "ENOENT") && !(error instanceof SyntaxError)) throw error;
103
+ }
104
+ return `Lock ${directory}; ${holder}. Verify the holder has stopped and remove only this lock directory before retrying`;
105
+ }
106
+ async function releaseLock(directory, owner) {
107
+ try {
108
+ await unlink(join(directory, owner));
109
+ } catch (error) {
110
+ if (hasCode(error, "ENOENT")) return;
111
+ throw error;
112
+ }
113
+ await rmdir(directory);
114
+ }
115
+ async function withRunLock(qaRoot, runId, operation) {
116
+ qaRoot = resolve(qaRoot);
117
+ runDirectory(qaRoot, runId);
118
+ await ensureDirectory(qaRoot);
119
+ await ensureDirectory(join(qaRoot, "locks"));
120
+ await ensureDirectory(join(qaRoot, "locks", "runs"));
121
+ const directory = join(qaRoot, "locks", "runs", lockName(runId));
122
+ const owner = randomUUID();
123
+ const deadline = Date.now() + 5e3;
124
+ while (!await acquireLock(directory, owner, { runId })) {
125
+ if (Date.now() >= deadline) throw new Error(`Run is locked. ${await lockConflict(directory)}`);
126
+ await setTimeout(10);
127
+ }
128
+ try {
129
+ return await operation();
130
+ } finally {
131
+ await releaseLock(directory, owner);
132
+ }
133
+ }
134
+ const noFollowRead = constants.O_RDONLY | constants.O_NOFOLLOW;
135
+ const noFollowWrite = constants.O_RDWR | constants.O_CREAT | constants.O_NOFOLLOW;
136
+ export {
137
+ acquireLock,
138
+ assertDirectory,
139
+ assertRegularFile,
140
+ atomicWrite,
141
+ ensureDirectory,
142
+ hasCode,
143
+ lockConflict,
144
+ lockName,
145
+ noFollowRead,
146
+ noFollowWrite,
147
+ releaseLock,
148
+ runDirectory,
149
+ withRunLock
150
+ };
@@ -0,0 +1,58 @@
1
+ import type { PoolClient } from "pg";
2
+ import type { ClassificationStore } from "@open-qa/qa-engine";
3
+ import { type Classification } from "@open-qa/qa-engine/protocol";
4
+ import { QaDatabase } from "../db/database.js";
5
+ export declare class PgClassificationStore implements ClassificationStore {
6
+ private readonly db;
7
+ private readonly project;
8
+ private readonly guard?;
9
+ constructor(db: QaDatabase, project: string, guard?: ((client: PoolClient) => Promise<unknown>) | undefined);
10
+ private read;
11
+ getClassification(id: string): Promise<{
12
+ classification: {
13
+ category: "env" | "agent" | "product-bug" | "test-case" | "flaky";
14
+ confidence: number;
15
+ reason: string;
16
+ source: "model" | "fallback" | "rule" | "human";
17
+ } | null;
18
+ labels: {
19
+ category: "env" | "agent" | "product-bug" | "test-case" | "flaky";
20
+ reason: string;
21
+ modifiedBy: string;
22
+ modifiedAt: number;
23
+ predicted: {
24
+ category: "env" | "agent" | "product-bug" | "test-case" | "flaky";
25
+ confidence: number;
26
+ reason: string;
27
+ source: "model" | "fallback" | "rule" | "human";
28
+ } | null;
29
+ }[];
30
+ } | undefined>;
31
+ private lock;
32
+ private write;
33
+ saveClassification(id: string, value: Classification): Promise<void>;
34
+ labelClassification(id: string, input: {
35
+ category: Classification["category"];
36
+ reason: string;
37
+ modifiedBy: string;
38
+ }): Promise<{
39
+ classification: {
40
+ category: "env" | "agent" | "product-bug" | "test-case" | "flaky";
41
+ confidence: number;
42
+ reason: string;
43
+ source: "model" | "fallback" | "rule" | "human";
44
+ };
45
+ labels: {
46
+ category: "env" | "agent" | "product-bug" | "test-case" | "flaky";
47
+ reason: string;
48
+ modifiedBy: string;
49
+ modifiedAt: number;
50
+ predicted: {
51
+ category: "env" | "agent" | "product-bug" | "test-case" | "flaky";
52
+ confidence: number;
53
+ reason: string;
54
+ source: "model" | "fallback" | "rule" | "human";
55
+ } | null;
56
+ }[];
57
+ }>;
58
+ }
@@ -0,0 +1,112 @@
1
+ import {
2
+ classificationSchema,
3
+ classificationLabelSchema
4
+ } from "@open-qa/qa-engine/protocol";
5
+ import { assertPostgresText, publicId } from "../db/database.js";
6
+ import { Conflict } from "../server/repository.js";
7
+ class PgClassificationStore {
8
+ constructor(db, project, guard) {
9
+ this.db = db;
10
+ this.project = project;
11
+ this.guard = guard;
12
+ publicId.parse(project);
13
+ }
14
+ db;
15
+ project;
16
+ guard;
17
+ async read(client, id) {
18
+ publicId.parse(id);
19
+ const { rows } = await client.query("SELECT classification,metadata FROM qa.runs WHERE project_id=$1 AND id=$2", [
20
+ this.project,
21
+ id
22
+ ]);
23
+ if (!rows[0]) return void 0;
24
+ const labels = await client.query(
25
+ 'SELECT category,reason,modified_by AS "modifiedBy",modified_at AS "modifiedAt",predicted FROM qa.classification_labels WHERE project_id=$1 AND run_id=$2 ORDER BY ordinal',
26
+ [this.project, id]
27
+ );
28
+ const category = rows[0].classification;
29
+ const metadata = rows[0].metadata?.failureClassification;
30
+ return {
31
+ classification: metadata ? classificationSchema.parse(metadata) : category ? classificationSchema.parse({
32
+ category,
33
+ confidence: 0,
34
+ source: "fallback",
35
+ reason: "Legacy classification"
36
+ }) : null,
37
+ labels: labels.rows.map((row) => classificationLabelSchema.parse(row))
38
+ };
39
+ }
40
+ getClassification(id) {
41
+ publicId.parse(id);
42
+ return this.db.transaction(async (client) => {
43
+ await client.query("SELECT id FROM qa.runs WHERE project_id=$1 AND id=$2 FOR SHARE", [
44
+ this.project,
45
+ id
46
+ ]);
47
+ return this.read(client, id);
48
+ });
49
+ }
50
+ async lock(client, id) {
51
+ publicId.parse(id);
52
+ const { rows } = await client.query(
53
+ "SELECT verdict FROM qa.runs WHERE project_id=$1 AND id=$2 FOR UPDATE",
54
+ [this.project, id]
55
+ );
56
+ if (!rows[0] || !["failed", "error"].includes(rows[0].verdict ?? ""))
57
+ throw new Conflict("Only failed/error runs can be classified");
58
+ }
59
+ async write(client, id, value) {
60
+ await client.query(
61
+ "UPDATE qa.runs SET classification=$3,metadata=jsonb_set(COALESCE(metadata,'{}'::jsonb),'{failureClassification}',$4::jsonb) WHERE project_id=$1 AND id=$2",
62
+ [this.project, id, value.category, JSON.stringify(value)]
63
+ );
64
+ }
65
+ async saveClassification(id, value) {
66
+ value = classificationSchema.parse(value);
67
+ assertPostgresText(value);
68
+ await this.db.transaction(async (client) => {
69
+ await this.guard?.(client);
70
+ await this.lock(client, id);
71
+ const record = await this.read(client, id);
72
+ if (record.labels.length) return;
73
+ await this.write(client, id, value);
74
+ });
75
+ }
76
+ async labelClassification(id, input) {
77
+ assertPostgresText(input);
78
+ return this.db.transaction(async (client) => {
79
+ await this.lock(client, id);
80
+ const record = await this.read(client, id);
81
+ const label = classificationLabelSchema.parse({
82
+ ...input,
83
+ modifiedAt: Date.now(),
84
+ predicted: record.classification?.source === "human" ? record.labels[0]?.predicted ?? null : record.classification
85
+ });
86
+ await client.query(
87
+ "INSERT INTO qa.classification_labels(project_id,run_id,ordinal,category,reason,modified_by,modified_at,predicted) VALUES($1,$2,$3,$4,$5,$6,$7,$8)",
88
+ [
89
+ this.project,
90
+ id,
91
+ record.labels.length + 1,
92
+ label.category,
93
+ label.reason,
94
+ label.modifiedBy,
95
+ label.modifiedAt,
96
+ label.predicted
97
+ ]
98
+ );
99
+ const classification = {
100
+ category: label.category,
101
+ reason: label.reason,
102
+ confidence: 1,
103
+ source: "human"
104
+ };
105
+ await this.write(client, id, classification);
106
+ return { classification, labels: [...record.labels, label] };
107
+ });
108
+ }
109
+ }
110
+ export {
111
+ PgClassificationStore
112
+ };
@@ -0,0 +1,16 @@
1
+ import { SecretRedactor, type CacheReview, type ReplayCache, type ReplayCacheDraft, type ReplayCacheEntry, type ReplayCacheKey } from "@open-qa/qa-engine";
2
+ import { type QaDatabase } from "../db/database.js";
3
+ export declare class PgReplayCache implements ReplayCache {
4
+ private readonly db;
5
+ private readonly redactor;
6
+ private readonly projectId;
7
+ constructor(db: QaDatabase, projectId: string, redactor?: SecretRedactor);
8
+ append(input: ReplayCacheDraft): Promise<ReplayCacheEntry>;
9
+ latest(key: ReplayCacheKey): Promise<ReplayCacheEntry | undefined>;
10
+ history(key: ReplayCacheKey): Promise<ReplayCacheEntry[]>;
11
+ pending(input?: ReplayCacheKey): Promise<ReplayCacheEntry[]>;
12
+ approve(id: string, review?: CacheReview): Promise<ReplayCacheEntry>;
13
+ reject(id: string, rejectedBy?: string): Promise<ReplayCacheEntry>;
14
+ private review;
15
+ private read;
16
+ }
@@ -0,0 +1,111 @@
1
+ import {
2
+ replayCacheKey,
3
+ parseReplayCacheId,
4
+ replayCacheKeySchema,
5
+ replayCacheDraftSchema,
6
+ replayCacheEntrySchema,
7
+ approveReplayCache,
8
+ rejectReplayCache,
9
+ SecretRedactor
10
+ } from "@open-qa/qa-engine";
11
+ import { assertPostgresText, publicId } from "../db/database.js";
12
+ class PgReplayCache {
13
+ constructor(db, projectId, redactor = new SecretRedactor()) {
14
+ this.db = db;
15
+ this.redactor = redactor;
16
+ this.projectId = publicId.parse(projectId);
17
+ }
18
+ db;
19
+ redactor;
20
+ projectId;
21
+ async append(input) {
22
+ const draft = replayCacheDraftSchema.parse(input);
23
+ assertPostgresText(draft);
24
+ const key = replayCacheKey(draft.key);
25
+ return this.db.transaction(async (client) => {
26
+ await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 1046))", [
27
+ JSON.stringify([this.projectId, key])
28
+ ]);
29
+ const result = await client.query(
30
+ "SELECT version,entry FROM qa.cache_entries WHERE project_id=$1 AND cache_key=$2 ORDER BY version DESC LIMIT 1",
31
+ [this.projectId, key]
32
+ );
33
+ if (result.rows[0]?.entry && replayCacheEntrySchema.parse(result.rows[0].entry).approval === "pending")
34
+ throw new Error("Cache review is pending");
35
+ if (draft.healing) {
36
+ const active = await client.query(
37
+ "SELECT version FROM qa.cache_entries WHERE project_id=$1 AND cache_key=$2 AND COALESCE(entry->>'approval','') NOT IN ('pending','rejected') ORDER BY version DESC LIMIT 1",
38
+ [this.projectId, key]
39
+ );
40
+ if (active.rows[0]?.version !== draft.healing.sourceVersion)
41
+ throw new Error("Healing source was superseded");
42
+ }
43
+ const entry = replayCacheEntrySchema.parse({
44
+ ...draft,
45
+ version: (result.rows[0]?.version ?? 0) + 1
46
+ });
47
+ await client.query(
48
+ "INSERT INTO qa.cache_entries (project_id,cache_key,version,entry) VALUES ($1,$2,$3,$4::jsonb)",
49
+ [this.projectId, key, entry.version, JSON.stringify(entry)]
50
+ );
51
+ return entry;
52
+ });
53
+ }
54
+ async latest(key) {
55
+ const entries = await this.read(key, true);
56
+ return entries[0];
57
+ }
58
+ async history(key) {
59
+ return this.read(key, false);
60
+ }
61
+ async pending(input) {
62
+ const key = input ? replayCacheKey(replayCacheKeySchema.parse(input)) : void 0;
63
+ const { rows } = await this.db.pool.query(
64
+ `SELECT entry FROM (SELECT DISTINCT ON (cache_key) entry FROM qa.cache_entries WHERE project_id=$1 ${key ? "AND cache_key=$2" : ""} ORDER BY cache_key,version DESC) latest WHERE entry->>'approval'='pending'`,
65
+ key ? [this.projectId, key] : [this.projectId]
66
+ );
67
+ return rows.map(({ entry }) => replayCacheEntrySchema.parse(entry));
68
+ }
69
+ async approve(id, review) {
70
+ return this.review(id, (entry) => approveReplayCache(entry, this.redactor, review));
71
+ }
72
+ async reject(id, rejectedBy = "local") {
73
+ return this.review(id, (entry) => rejectReplayCache(entry, rejectedBy));
74
+ }
75
+ async review(id, decide) {
76
+ const { digest, version } = parseReplayCacheId(id);
77
+ return this.db.transaction(async (client) => {
78
+ await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 1046))", [
79
+ JSON.stringify([this.projectId, digest])
80
+ ]);
81
+ const { rows } = await client.query(
82
+ "SELECT entry FROM qa.cache_entries WHERE project_id=$1 AND cache_key=$2 ORDER BY version DESC LIMIT 1",
83
+ [this.projectId, digest]
84
+ );
85
+ const entry = rows[0] ? replayCacheEntrySchema.parse(rows[0].entry) : void 0;
86
+ if (!entry || entry.version !== version || replayCacheKey(entry.key) !== digest)
87
+ throw new Error("Cache version was superseded or does not exist");
88
+ const approved = decide(entry);
89
+ await client.query(
90
+ "UPDATE qa.cache_entries SET entry=$4::jsonb WHERE project_id=$1 AND cache_key=$2 AND version=$3",
91
+ [this.projectId, digest, version, JSON.stringify(approved)]
92
+ );
93
+ return approved;
94
+ });
95
+ }
96
+ async read(input, latest) {
97
+ const key = replayCacheKey(replayCacheKeySchema.parse(input));
98
+ const { rows } = await this.db.pool.query(
99
+ `SELECT entry FROM qa.cache_entries WHERE project_id=$1 AND cache_key=$2 ${latest ? "AND COALESCE(entry->>'approval','') NOT IN ('pending','rejected')" : ""} ORDER BY version ${latest ? "DESC LIMIT 1" : "ASC"}`,
100
+ [this.projectId, key]
101
+ );
102
+ return rows.map(({ entry }) => {
103
+ const parsed = replayCacheEntrySchema.parse(entry);
104
+ if (replayCacheKey(parsed.key) !== key) throw new Error("Invalid replay cache key");
105
+ return parsed;
106
+ });
107
+ }
108
+ }
109
+ export {
110
+ PgReplayCache
111
+ };
@@ -0,0 +1,58 @@
1
+ import type { PoolClient } from "pg";
2
+ import { type CreateRun, type FinishRun, type RunStore } from "@open-qa/qa-engine";
3
+ import { type RunEvent } from "@open-qa/qa-engine/protocol";
4
+ import { QaDatabase } from "../db/database.js";
5
+ import { type LeaseFence } from "../db/fencing.js";
6
+ import { type EventObjects } from "../db/event-chunks.js";
7
+ import { PgQueries } from "../db/queries.js";
8
+ /** SQL owns the commit point; EventObjects owns immutable, checksum-verified NDJSON. */
9
+ export declare class PgRunStore implements RunStore {
10
+ private readonly db;
11
+ private readonly project;
12
+ private readonly objects;
13
+ private readonly fence?;
14
+ private readonly jobGuard?;
15
+ readonly queries: PgQueries;
16
+ constructor(db: QaDatabase, project: string, objects: EventObjects, fence?: LeaseFence | undefined, jobGuard?: ((client: PoolClient) => Promise<unknown>) | undefined);
17
+ createRun(input: CreateRun): Promise<void>;
18
+ getRun(id: string): Promise<import("../db/index.js").StoredRun | undefined>;
19
+ recentUsage(flow: string): Promise<{
20
+ inputTokens: number;
21
+ outputTokens: number;
22
+ actions: number;
23
+ minutes: number;
24
+ cacheReadTokens?: number | undefined;
25
+ cacheWriteTokens?: number | undefined;
26
+ costUsd?: number | undefined;
27
+ costUnknown?: true | undefined;
28
+ e2bMinutes?: number | undefined;
29
+ }[]>;
30
+ listRuns(limit?: number): Promise<import("../db/index.js").StoredRun[]>;
31
+ appendEvents(runId: string, events: readonly RunEvent[]): Promise<void>;
32
+ /** Persist batchId across retries. Different content under that ID is always rejected. */
33
+ appendChunk(runId: string, batchId: string, input: readonly RunEvent[]): Promise<void>;
34
+ finishRun(runId: string, input: FinishRun): Promise<void>;
35
+ readFindings(runId: string): Promise<{
36
+ eventSeqs: number[];
37
+ shots: string[];
38
+ actor: string;
39
+ step: string;
40
+ category: "scope" | "other";
41
+ severity: "low" | "medium" | "high";
42
+ description: string;
43
+ }[]>;
44
+ /** Attach all subsequent writes to this lease's owner/epoch; unfenced writers then fail. */
45
+ claimRun(runId: string, token: LeaseFence): Promise<PgRunStore>;
46
+ heartbeat(runId: string): Promise<void>;
47
+ readEvents(runId: string, afterSeq?: number, limit?: number): Promise<RunEvent[]>;
48
+ repairEventIndex(runId: string): Promise<void>;
49
+ cleanOrphans(graceMs: number): Promise<number>;
50
+ private lockRun;
51
+ private authorize;
52
+ private writable;
53
+ private checkCursor;
54
+ private existingChunk;
55
+ private readSegments;
56
+ private checkHistory;
57
+ private projectEvents;
58
+ }