@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,208 @@
1
+ import { z } from "zod";
2
+ import {
3
+ acceptance,
4
+ canRetire,
5
+ isFirstRun,
6
+ nextFlowStatus
7
+ } from "@open-qa/qa-engine";
8
+ import { verdictSchema, failureCategorySchema } from "@open-qa/qa-engine/protocol";
9
+ import { publicId, assertPostgresText } from "./database.js";
10
+ const flowKey = z.string().min(1).max(500).refine(
11
+ (value) => [...value].every((char) => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
12
+ );
13
+ const projectRow = (row) => ({
14
+ flow: row.flow,
15
+ status: row.status,
16
+ flakyStreak: row.flaky_streak,
17
+ owner: row.owner,
18
+ latestRepeat: row.latest_repeat,
19
+ firstRun: row.first_run_id && row.first_run_at ? {
20
+ runId: row.first_run_id,
21
+ revision: row.first_run_revision,
22
+ at: row.first_run_at.getTime()
23
+ } : null,
24
+ acceptedAt: row.accepted_at?.getTime() ?? null,
25
+ acceptedBy: row.accepted_by,
26
+ retiredAt: row.retired_at?.getTime() ?? null
27
+ });
28
+ const revisionSchema = z.string().regex(/^[a-f0-9]{64}$/);
29
+ const actorSchema = z.string().min(1).max(200);
30
+ const repeatSchema = z.object({
31
+ startedAt: z.number().finite().nonnegative(),
32
+ finishedAt: z.number().finite().nonnegative(),
33
+ target: z.string().min(1).max(2048),
34
+ requested: z.number().int().min(1).max(100),
35
+ runs: z.array(
36
+ z.object({
37
+ runId: publicId,
38
+ verdict: verdictSchema,
39
+ category: failureCategorySchema.nullable()
40
+ })
41
+ ).max(100)
42
+ }).refine((value) => value.finishedAt >= value.startedAt && value.runs.length <= value.requested);
43
+ class PgFlowStatus {
44
+ constructor(db, projectId) {
45
+ this.db = db;
46
+ this.projectId = projectId;
47
+ publicId.parse(projectId);
48
+ }
49
+ db;
50
+ projectId;
51
+ async get(flow) {
52
+ flowKey.parse(flow);
53
+ const { rows } = await this.db.pool.query(
54
+ "SELECT * FROM qa.flow_statuses WHERE project_id=$1 AND flow=$2",
55
+ [this.projectId, flow]
56
+ );
57
+ return rows[0] ? projectRow(rows[0]) : void 0;
58
+ }
59
+ async list() {
60
+ const { rows } = await this.db.pool.query(
61
+ "SELECT * FROM qa.flow_statuses WHERE project_id=$1 AND status='quarantined' ORDER BY flow",
62
+ [this.projectId]
63
+ );
64
+ return rows.map(projectRow);
65
+ }
66
+ record(input) {
67
+ return this.db.transaction((client) => this.recordInTransaction(client, input));
68
+ }
69
+ async recordInTransaction(client, input) {
70
+ flowKey.parse(input.flow);
71
+ publicId.parse(input.executionId);
72
+ verdictSchema.parse(input.verdict);
73
+ failureCategorySchema.nullable().parse(input.category);
74
+ if (input.owner !== void 0) z.string().min(1).max(200).parse(input.owner);
75
+ if (input.revision !== void 0) revisionSchema.parse(input.revision);
76
+ assertPostgresText(input);
77
+ const key = [this.projectId, input.flow];
78
+ await client.query(
79
+ "INSERT INTO qa.flow_statuses(project_id,flow,status) VALUES($1,$2,'draft') ON CONFLICT DO NOTHING",
80
+ key
81
+ );
82
+ const locked = await client.query(
83
+ "SELECT * FROM qa.flow_statuses WHERE project_id=$1 AND flow=$2 FOR UPDATE",
84
+ key
85
+ );
86
+ const previous = await client.query(
87
+ "SELECT quarantined,flow FROM qa.flow_results WHERE project_id=$1 AND execution_id=$2",
88
+ [this.projectId, input.executionId]
89
+ );
90
+ if (previous.rows[0]) {
91
+ if (previous.rows[0].flow !== input.flow)
92
+ throw new Error("Execution already belongs to another flow");
93
+ return { quarantined: !!previous.rows[0].quarantined, status: locked.rows[0].status };
94
+ }
95
+ const row = locked.rows[0];
96
+ const next = nextFlowStatus(projectRow(row), input.verdict, input.category, input.revision);
97
+ const entered = row.status === "active" && next.status === "quarantined";
98
+ const generation = row.generation + (entered ? 1 : 0);
99
+ const owner = input.owner ?? row.owner;
100
+ await client.query(
101
+ "UPDATE qa.flow_statuses SET status=$3,flaky_streak=$4,generation=$5,owner=$6 WHERE project_id=$1 AND flow=$2",
102
+ [...key, next.status, next.flakyStreak, generation, owner]
103
+ );
104
+ if (next.status === "review" && isFirstRun(input.verdict, input.revision))
105
+ await client.query(
106
+ "UPDATE qa.flow_statuses SET first_run_id=$3,first_run_revision=$4,first_run_at=clock_timestamp() WHERE project_id=$1 AND flow=$2",
107
+ [...key, input.executionId, input.revision ?? null]
108
+ );
109
+ await client.query(
110
+ "INSERT INTO qa.flow_results(project_id,execution_id,flow,quarantined) VALUES($1,$2,$3,$4)",
111
+ [this.projectId, input.executionId, input.flow, next.status === "quarantined" ? 1 : 0]
112
+ );
113
+ if (entered)
114
+ await client.query(
115
+ "INSERT INTO qa.quarantine_notifications(project_id,flow,generation,run_id,owner) VALUES($1,$2,$3,$4,$5)",
116
+ [...key, generation, input.executionId, owner]
117
+ );
118
+ return { quarantined: next.status === "quarantined", status: next.status };
119
+ }
120
+ async saveRepeat(flow, result) {
121
+ flowKey.parse(flow);
122
+ repeatSchema.parse(result);
123
+ assertPostgresText(result);
124
+ await this.db.pool.query(
125
+ `INSERT INTO qa.flow_statuses(project_id,flow,status,latest_repeat) VALUES($1,$2,'draft',$3::jsonb)
126
+ ON CONFLICT(project_id,flow) DO UPDATE SET latest_repeat=EXCLUDED.latest_repeat
127
+ WHERE COALESCE((qa.flow_statuses.latest_repeat->>'startedAt')::double precision,-1) <= $4`,
128
+ [this.projectId, flow, JSON.stringify(result), result.startedAt]
129
+ );
130
+ }
131
+ async release(flow) {
132
+ flowKey.parse(flow);
133
+ const { rows } = await this.db.pool.query(
134
+ "UPDATE qa.flow_statuses SET status='active',flaky_streak=0 WHERE project_id=$1 AND flow=$2 AND status='quarantined' RETURNING *",
135
+ [this.projectId, flow]
136
+ );
137
+ return rows[0] ? projectRow(rows[0]) : void 0;
138
+ }
139
+ async states(flows) {
140
+ for (const flow of flows) flowKey.parse(flow);
141
+ const { rows } = await this.db.pool.query(
142
+ "SELECT * FROM qa.flow_statuses WHERE project_id=$1 AND flow=ANY($2::text[])",
143
+ [this.projectId, [...flows]]
144
+ );
145
+ return new Map(rows.map((row) => [row.flow, projectRow(row)]));
146
+ }
147
+ accept(flow, input) {
148
+ flowKey.parse(flow);
149
+ revisionSchema.parse(input.revision);
150
+ actorSchema.parse(input.by);
151
+ assertPostgresText(input);
152
+ return this.db.transaction(async (client) => {
153
+ const key = [this.projectId, flow];
154
+ const { rows } = await client.query(
155
+ "SELECT * FROM qa.flow_statuses WHERE project_id=$1 AND flow=$2 FOR UPDATE",
156
+ key
157
+ );
158
+ const decision = acceptance(rows[0] && projectRow(rows[0]), input.revision);
159
+ if (!decision.ok) {
160
+ if (decision.reason === "changed")
161
+ await client.query(
162
+ "UPDATE qa.flow_statuses SET status='draft' WHERE project_id=$1 AND flow=$2",
163
+ key
164
+ );
165
+ return decision;
166
+ }
167
+ const updated = await client.query(
168
+ "UPDATE qa.flow_statuses SET status='active',flaky_streak=0,accepted_at=clock_timestamp(),accepted_by=$3 WHERE project_id=$1 AND flow=$2 RETURNING *",
169
+ [...key, input.by]
170
+ );
171
+ return { ok: true, status: projectRow(updated.rows[0]) };
172
+ });
173
+ }
174
+ retire(flow) {
175
+ flowKey.parse(flow);
176
+ return this.db.transaction(async (client) => {
177
+ const key = [this.projectId, flow];
178
+ const { rows } = await client.query(
179
+ "SELECT * FROM qa.flow_statuses WHERE project_id=$1 AND flow=$2 FOR UPDATE",
180
+ key
181
+ );
182
+ const status = rows[0]?.status ?? "draft";
183
+ if (!canRetire(status)) return { ok: false, reason: status };
184
+ const updated = await client.query(
185
+ "UPDATE qa.flow_statuses SET status='retired',retired_at=clock_timestamp() WHERE project_id=$1 AND flow=$2 RETURNING *",
186
+ key
187
+ );
188
+ return { ok: true, status: projectRow(updated.rows[0]) };
189
+ });
190
+ }
191
+ async baseline(flows, by) {
192
+ for (const flow of flows) flowKey.parse(flow);
193
+ actorSchema.parse(by);
194
+ assertPostgresText({ flows, by });
195
+ const { rows } = await this.db.pool.query(
196
+ `INSERT INTO qa.flow_statuses(project_id,flow,status,accepted_at,accepted_by)
197
+ SELECT $1,flow,'active',clock_timestamp(),$3 FROM unnest($2::text[]) AS flow
198
+ ON CONFLICT(project_id,flow) DO UPDATE
199
+ SET status='active',accepted_at=EXCLUDED.accepted_at,accepted_by=EXCLUDED.accepted_by
200
+ WHERE qa.flow_statuses.status='draft' RETURNING flow`,
201
+ [this.projectId, [...new Set(flows)], by]
202
+ );
203
+ return rows.map((row) => row.flow).sort();
204
+ }
205
+ }
206
+ export {
207
+ PgFlowStatus
208
+ };
@@ -0,0 +1,12 @@
1
+ export { QaDatabase, migrateQa, type QaDatabaseOptions } from "./database.js";
2
+ export { PgRunStore } from "../adapters/pg-run-store.js";
3
+ export { DbLeasePool, type DbLease, type ResourceResolver } from "../adapters/db-lease-pool.js";
4
+ export { PgQueries, type RunQueries, type ResourceQueries, type RunFilter, type StoredRun, } from "./queries.js";
5
+ export { importResources, parseResourceManifest, type ResourceReference } from "./resources.js";
6
+ export type { EventObjects } from "./event-chunks.js";
7
+ export type { LeaseFence } from "./fencing.js";
8
+ export { PgCredentialStore } from "./credentials.js";
9
+ export type { CredentialReference, CredentialReferences, CloudRuntime, } from "../credential-references.js";
10
+ export { PgReplayCache } from "../adapters/pg-replay-cache.js";
11
+ export { PgClassificationStore } from "../adapters/pg-classification-store.js";
12
+ export { PgFlowStatus } from "./flow-status.js";
@@ -0,0 +1,24 @@
1
+ import { QaDatabase, migrateQa } from "./database.js";
2
+ import { PgRunStore } from "../adapters/pg-run-store.js";
3
+ import { DbLeasePool } from "../adapters/db-lease-pool.js";
4
+ import {
5
+ PgQueries
6
+ } from "./queries.js";
7
+ import { importResources, parseResourceManifest } from "./resources.js";
8
+ import { PgCredentialStore } from "./credentials.js";
9
+ import { PgReplayCache } from "../adapters/pg-replay-cache.js";
10
+ import { PgClassificationStore } from "../adapters/pg-classification-store.js";
11
+ import { PgFlowStatus } from "./flow-status.js";
12
+ export {
13
+ DbLeasePool,
14
+ PgClassificationStore,
15
+ PgCredentialStore,
16
+ PgFlowStatus,
17
+ PgQueries,
18
+ PgReplayCache,
19
+ PgRunStore,
20
+ QaDatabase,
21
+ importResources,
22
+ migrateQa,
23
+ parseResourceManifest
24
+ };
@@ -0,0 +1,73 @@
1
+ import { type BatchUsage, type RunUsage, type FinishRun, type CreateRun } from "@open-qa/qa-engine";
2
+ import type { Verdict } from "@open-qa/qa-engine/protocol";
3
+ import { QaDatabase } from "./database.js";
4
+ import type { ResourceReference } from "./resources.js";
5
+ export interface StoredRun {
6
+ run: CreateRun;
7
+ eventIndex: {
8
+ bytes: number;
9
+ count: number;
10
+ lastSeq: number;
11
+ lastT: number;
12
+ };
13
+ result?: Pick<FinishRun, "verdict" | "finishedAt" | "reason" | "usage" | "errorReason"> & {
14
+ costStatus: "recorded" | "unavailable";
15
+ };
16
+ }
17
+ export interface RunFilter {
18
+ limit?: number;
19
+ flow?: string;
20
+ verdict?: Verdict;
21
+ before?: {
22
+ startedAt: number;
23
+ id: string;
24
+ };
25
+ }
26
+ export interface RunQueries {
27
+ getRun(id: string): Promise<StoredRun | undefined>;
28
+ listRuns(filter?: RunFilter): Promise<StoredRun[]>;
29
+ }
30
+ export interface ResourceQueries {
31
+ listResources(): Promise<Pick<ResourceReference, "id" | "kind">[]>;
32
+ }
33
+ export interface RunRow {
34
+ cost_usd: number;
35
+ usage?: RunUsage | null;
36
+ error_reason?: "budget" | null;
37
+ id: string;
38
+ flow: string;
39
+ started_at: number;
40
+ metadata: CreateRun["metadata"] | null;
41
+ event_count: number;
42
+ event_bytes: string;
43
+ last_seq: string;
44
+ last_t: number;
45
+ verdict: Verdict | null;
46
+ finished_at: number | null;
47
+ reason: string | null;
48
+ writer_lease_id: string | null;
49
+ }
50
+ export declare function toStoredRun(row: RunRow): StoredRun;
51
+ export declare class PgQueries implements RunQueries, ResourceQueries {
52
+ private readonly db;
53
+ private readonly project;
54
+ constructor(db: QaDatabase, project: string);
55
+ getRun(id: string): Promise<StoredRun | undefined>;
56
+ listRuns(filter?: RunFilter): Promise<StoredRun[]>;
57
+ recentUsage(flow: string): Promise<RunUsage[]>;
58
+ batchUsage(batchId: string): Promise<BatchUsage>;
59
+ listResources(): Promise<Pick<{
60
+ id: string;
61
+ kind: string;
62
+ canonicalId: string;
63
+ secretRef: string;
64
+ }, "kind" | "id">[]>;
65
+ listSteps(runId: string): Promise<{
66
+ actor: string;
67
+ step: string;
68
+ seq: number;
69
+ status: string;
70
+ startedAt: number;
71
+ finishedAt: number | null;
72
+ }[]>;
73
+ }
@@ -0,0 +1,122 @@
1
+ import {
2
+ publicRunUsage,
3
+ batchUsageSchema,
4
+ runUsageSchema
5
+ } from "@open-qa/qa-engine";
6
+ import { publicId } from "./database.js";
7
+ function toStoredRun(row) {
8
+ return {
9
+ run: {
10
+ id: row.id,
11
+ flow: row.flow,
12
+ startedAt: row.started_at,
13
+ ...row.metadata ? { metadata: row.metadata } : {}
14
+ },
15
+ eventIndex: {
16
+ bytes: Number(row.event_bytes),
17
+ count: row.event_count,
18
+ lastSeq: Number(row.last_seq),
19
+ lastT: row.last_t
20
+ },
21
+ ...row.verdict ? {
22
+ result: {
23
+ verdict: row.verdict,
24
+ // A default zero is unknown without usage; legacy nonzero totals are recorded costs.
25
+ costStatus: !row.usage?.costUnknown && (row.usage?.costUsd !== void 0 || row.cost_usd !== 0) ? "recorded" : "unavailable",
26
+ ...row.usage && { usage: runUsageSchema.parse(row.usage) },
27
+ ...row.error_reason && { errorReason: row.error_reason },
28
+ finishedAt: row.finished_at,
29
+ ...row.reason !== null ? { reason: row.reason } : {}
30
+ }
31
+ } : {}
32
+ };
33
+ }
34
+ class PgQueries {
35
+ constructor(db, project) {
36
+ this.db = db;
37
+ this.project = project;
38
+ publicId.parse(project);
39
+ }
40
+ db;
41
+ project;
42
+ async getRun(id) {
43
+ publicId.parse(id);
44
+ const { rows } = await this.db.pool.query(
45
+ "SELECT * FROM qa.runs WHERE project_id=$1 AND id=$2",
46
+ [this.project, id]
47
+ );
48
+ return rows[0] ? toStoredRun(rows[0]) : void 0;
49
+ }
50
+ async listRuns(filter = {}) {
51
+ const limit = filter.limit ?? 20;
52
+ if (!Number.isInteger(limit) || limit < 0 || limit > 1e3)
53
+ throw new Error("Run limit must be an integer between 0 and 1000");
54
+ const { rows } = await this.db.pool.query(
55
+ `SELECT * FROM qa.runs WHERE project_id=$1 AND ($2::text IS NULL OR flow=$2)
56
+ AND ($3::text IS NULL OR verdict=$3) AND ($4::double precision IS NULL OR started_at<$4 OR (started_at=$4 AND id COLLATE "C">$5 COLLATE "C"))
57
+ ORDER BY started_at DESC,id COLLATE "C" ASC LIMIT $6`,
58
+ [
59
+ this.project,
60
+ filter.flow,
61
+ filter.verdict,
62
+ filter.before?.startedAt,
63
+ filter.before?.id,
64
+ limit
65
+ ]
66
+ );
67
+ return rows.map(toStoredRun);
68
+ }
69
+ async recentUsage(flow) {
70
+ const { rows } = await this.db.pool.query(
71
+ `SELECT usage FROM qa.runs WHERE project_id=$1 AND flow=$2 AND verdict IS NOT NULL AND usage IS NOT NULL AND error_reason IS DISTINCT FROM 'budget'
72
+ ORDER BY started_at DESC,id COLLATE "C" ASC LIMIT 5`,
73
+ [this.project, flow]
74
+ );
75
+ return rows.map((row) => publicRunUsage(runUsageSchema.parse(row.usage)));
76
+ }
77
+ async batchUsage(batchId) {
78
+ publicId.parse(batchId);
79
+ const { rows } = await this.db.pool.query(
80
+ `SELECT jsonb_strip_nulls(jsonb_build_object(
81
+ 'inputTokens',COALESCE(sum((usage->>'inputTokens')::numeric),0),
82
+ 'outputTokens',COALESCE(sum((usage->>'outputTokens')::numeric),0),
83
+ 'cacheReadTokens',sum((usage->>'cacheReadTokens')::numeric),
84
+ 'cacheWriteTokens',sum((usage->>'cacheWriteTokens')::numeric),
85
+ 'costUsd',sum(cost_usd) FILTER (WHERE usage ? 'costUsd' OR cost_usd<>0),
86
+ 'costUnknown',CASE WHEN bool_or(usage->>'costUnknown'='true') THEN true END,
87
+ 'costUnavailableRuns',count(*) FILTER (WHERE usage->>'costUnknown'='true' OR (NOT COALESCE(usage ? 'costUsd',false) AND cost_usd=0)),
88
+ 'actions',COALESCE(sum((usage->>'actions')::numeric),0),
89
+ 'minutes',COALESCE(sum((usage->>'minutes')::double precision),0),
90
+ 'e2bMinutes',sum((usage->>'e2bMinutes')::double precision))) AS usage
91
+ FROM qa.runs WHERE project_id=$1 AND batch_id=$2`,
92
+ [this.project, batchId]
93
+ );
94
+ return publicRunUsage(batchUsageSchema.parse(rows[0].usage));
95
+ }
96
+ async listResources() {
97
+ const { rows } = await this.db.pool.query(
98
+ "SELECT id,kind FROM qa.lease_resources WHERE project_id=$1 ORDER BY kind,id",
99
+ [this.project]
100
+ );
101
+ return rows;
102
+ }
103
+ async listSteps(runId) {
104
+ publicId.parse(runId);
105
+ const { rows } = await this.db.pool.query(
106
+ `SELECT actor,step,seq,status,started_at,finished_at FROM qa.step_runs WHERE project_id=$1 AND run_id=$2 ORDER BY seq`,
107
+ [this.project, runId]
108
+ );
109
+ return rows.map((r) => ({
110
+ actor: r.actor,
111
+ step: r.step,
112
+ seq: Number(r.seq),
113
+ status: r.status,
114
+ startedAt: r.started_at,
115
+ finishedAt: r.finished_at
116
+ }));
117
+ }
118
+ }
119
+ export {
120
+ PgQueries,
121
+ toStoredRun
122
+ };
@@ -0,0 +1,14 @@
1
+ import { z } from "zod";
2
+ import type { PoolClient } from "pg";
3
+ import { QaDatabase } from "./database.js";
4
+ declare const resourceSchema: z.ZodObject<{
5
+ id: z.ZodString;
6
+ kind: z.ZodString;
7
+ canonicalId: z.ZodString;
8
+ secretRef: z.ZodString;
9
+ }, z.core.$strict>;
10
+ export type ResourceReference = z.infer<typeof resourceSchema>;
11
+ export declare function parseResourceManifest(value: unknown): ResourceReference[];
12
+ export declare function lockResources(client: PoolClient, project: string): Promise<boolean>;
13
+ export declare function importResources(db: QaDatabase, project: string, input: unknown): Promise<number>;
14
+ export {};
@@ -0,0 +1,61 @@
1
+ import { z } from "zod";
2
+ import { publicId } from "./database.js";
3
+ const resourceSchema = z.strictObject({
4
+ id: publicId,
5
+ kind: publicId,
6
+ canonicalId: publicId,
7
+ secretRef: z.string().regex(/^projects\/[a-zA-Z0-9_-]+\/secrets\/[a-zA-Z0-9_-]+\/versions\/(latest|[0-9]+)$/)
8
+ });
9
+ function parseResourceManifest(value) {
10
+ const parsed = z.array(resourceSchema).max(1e4).safeParse(value);
11
+ if (!parsed.success || new Set(parsed.data.map((r) => r.id)).size !== parsed.data.length)
12
+ throw new Error(
13
+ "Invalid resource manifest; expected distinct IDs, kinds, canonical IDs and Secret Manager references only"
14
+ );
15
+ return parsed.data;
16
+ }
17
+ async function lockResources(client, project) {
18
+ const result = await client.query(
19
+ "SELECT pg_try_advisory_xact_lock(1037, hashtext($1)) AS locked",
20
+ [project]
21
+ );
22
+ return result.rows[0].locked;
23
+ }
24
+ async function importResources(db, project, input) {
25
+ publicId.parse(project);
26
+ const resources = parseResourceManifest(input);
27
+ await db.transaction(async (client) => {
28
+ if (!await lockResources(client, project))
29
+ throw new Error("QA resource inventory is busy; retry import");
30
+ for (const r of resources) {
31
+ const claims = await client.query(
32
+ `SELECT 1 FROM qa.lease_claims WHERE project_id=$1 AND identity = ANY($2::text[])`,
33
+ [project, [`name:${r.id}`, `canonical:${r.canonicalId}`]]
34
+ );
35
+ const existing = await client.query(
36
+ `SELECT id,kind,canonical_id AS "canonicalId",secret_ref AS "secretRef" FROM qa.lease_resources WHERE project_id=$1 AND id=$2`,
37
+ [project, r.id]
38
+ );
39
+ const old = existing.rows[0];
40
+ if (old) {
41
+ if (old.canonicalId !== r.canonicalId)
42
+ throw new Error(
43
+ "Resource canonical identity is immutable; add a new ID after manual recovery"
44
+ );
45
+ if (old.kind === r.kind && old.secretRef === r.secretRef) continue;
46
+ }
47
+ if (claims.rowCount) throw new Error("Cannot change a leased or quarantined resource");
48
+ await client.query(
49
+ `INSERT INTO qa.lease_resources(project_id,id,kind,canonical_id,secret_ref) VALUES($1,$2,$3,$4,$5)
50
+ ON CONFLICT(project_id,id) DO UPDATE SET kind=excluded.kind,secret_ref=excluded.secret_ref`,
51
+ [project, r.id, r.kind, r.canonicalId, r.secretRef]
52
+ );
53
+ }
54
+ });
55
+ return resources.length;
56
+ }
57
+ export {
58
+ importResources,
59
+ lockResources,
60
+ parseResourceManifest
61
+ };