@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
package/src/engine.js ADDED
@@ -0,0 +1,323 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { join } from "node:path";
3
+ import {
4
+ runFlow,
5
+ selectAgentPlacement,
6
+ SecretRedactor,
7
+ ModelJudge,
8
+ ModelReviewer,
9
+ credentialSecrets
10
+ } from "@open-qa/qa-engine";
11
+ import { ClaudeCodeRuntime, CodexRuntime, PiRuntime } from "@open-qa/qa-agents";
12
+ import { FileReplayCache, FileRunStore, FixedLeasePool, LocalCredentialResolver } from "./adapters/index.js";
13
+ import { ClassifyingRuns, lastPassedDiff } from "./classify-runs.js";
14
+ import { ModelClassifier } from "./classification-model.js";
15
+ import { IndependentModelCaller } from "./independent-model.js";
16
+ import { loadReplayImage } from "./replay-image.js";
17
+ import { runDirectory } from "./adapters/local-files.js";
18
+ import { HookRegistry } from "./hooks/registry.js";
19
+ import { readConsumerManifest } from "./hooks/consumer.js";
20
+ import { FileHookRunner } from "./hooks/runner.js";
21
+ import { HttpStageClient } from "./http-stage-client.js";
22
+ import { LocalHostExecutor } from "./local-host-executor.js";
23
+ import { E2bExecutor } from "./adapters/e2b-executor.js";
24
+ import { createQaE2bClient, e2bConfig } from "./adapters/e2b-client.js";
25
+ import { systemSecretValues } from "./system-config.js";
26
+ class FlowStatusWriteError extends Error {
27
+ constructor(result) {
28
+ super(
29
+ "Raw execution completed; quarantine metadata was not saved. Check QA PostgreSQL connectivity and applied migrations"
30
+ );
31
+ this.result = result;
32
+ }
33
+ result;
34
+ }
35
+ const PUBLIC_ENV_KEYS = /* @__PURE__ */ new Set([
36
+ "QA_TARGET_ENV",
37
+ "QA_WEB_URL",
38
+ "QA_AGENT_SERVER_URL",
39
+ "QA_LITELLM_BASE_URL",
40
+ "QA_GMAIL_ADDRESS",
41
+ "QA_DISCORD_GUILD_ID",
42
+ "QA_DISCORD_CHANNEL_ID",
43
+ "QA_ENV_FILE"
44
+ ]);
45
+ const PUBLIC_INDEXED_ENV_KEY = /^QA_TELEGRAM_(?:BOT_\d+_USERNAME|GROUP_\d+_CHAT_ID)$/;
46
+ const PRIVATE_ENV_KEY = /(?:TOKEN|PASSWORD|SECRET|API_KEY)$/;
47
+ function privateEnvSecrets(env, publicEnv = []) {
48
+ const publicKeys = /* @__PURE__ */ new Set([...PUBLIC_ENV_KEYS, ...publicEnv]);
49
+ return Object.entries(env).filter(([key]) => !publicKeys.has(key) && !PUBLIC_INDEXED_ENV_KEY.test(key)).flatMap(([key, value]) => {
50
+ if (key === "QA_RESOURCES" || key === "QA_RESOURCE_POOLS") {
51
+ try {
52
+ const resources = JSON.parse(value ?? "{}");
53
+ if (!resources || typeof resources !== "object") return [];
54
+ return Object.values(resources).flatMap(
55
+ (resource) => key === "QA_RESOURCE_POOLS" && resource && typeof resource === "object" ? Object.values(resource).flatMap((item) => credentialSecrets(item)) : credentialSecrets(resource)
56
+ );
57
+ } catch {
58
+ return value ? [value] : [];
59
+ }
60
+ }
61
+ return value && value.length >= (PRIVATE_ENV_KEY.test(key) ? 1 : 8) ? [value] : [];
62
+ });
63
+ }
64
+ function createEngine(options) {
65
+ const modelAccess = options.modelAccess ?? (options.origin === "server" ? "env" : "login");
66
+ const agentAt = selectAgentPlacement({
67
+ stage: options.placement ?? "local-host",
68
+ origin: options.origin ?? "cli",
69
+ requested: options.agentAt,
70
+ modelAccess
71
+ });
72
+ if (modelAccess === "env" && [
73
+ options.runtime?.id ?? options.runtimeId,
74
+ options.healRuntime?.id ?? options.heal?.runtime
75
+ ].includes("codex"))
76
+ throw new Error("Codex supports host subscription login only");
77
+ let activeHandle;
78
+ if (options.runId && options.retries !== 0)
79
+ throw new Error("A supplied run ID requires queue-managed retries");
80
+ const allowConsumerHooks = options.allowConsumerHooks ?? options.origin !== "server";
81
+ const publicEnv = options.consumerPublicEnv ?? (allowConsumerHooks ? readConsumerManifest(options.root)?.publicEnv ?? [] : []);
82
+ const redactor = options.redactor ?? new SecretRedactor();
83
+ const stageSecrets = [
84
+ ...options.stage?.redactions ?? [],
85
+ ...systemSecretValues(options.stage?.systems),
86
+ ...Object.values(options.stage?.email ?? {}),
87
+ options.stage?.discord?.botToken ?? "",
88
+ options.stage?.page?.access?.clientId ?? "",
89
+ options.stage?.page?.access?.clientSecret ?? ""
90
+ ].filter(Boolean);
91
+ redactor.add([
92
+ ...privateEnvSecrets(options.env ?? {}, publicEnv),
93
+ options.subscriptionToken ?? "",
94
+ ...stageSecrets
95
+ ]);
96
+ const runtime = options.runtime ?? (options.runtimeId === "codex" ? new CodexRuntime() : new ClaudeCodeRuntime());
97
+ const credentials = options.credentials ?? new LocalCredentialResolver();
98
+ const observation = {
99
+ runtime: null,
100
+ modelAccess: null,
101
+ credentialSource: null,
102
+ placement: null,
103
+ capabilities: null
104
+ };
105
+ const stageOptions = { ...options.stage, redactions: stageSecrets };
106
+ const e2b = options.placement === "e2b" && !options.executor ? new E2bExecutor({
107
+ ...requiredE2bOptions(options),
108
+ client: options.e2bClient ?? createQaE2bClient(e2bConfig(process.env).apiKey),
109
+ stage: stageOptions
110
+ }) : void 0;
111
+ const executor = options.executor ?? e2b ?? new LocalHostExecutor(stageOptions);
112
+ const wrapRuntime = (runtime2, observe = true) => ({
113
+ id: runtime2.id,
114
+ async start(start, signal) {
115
+ const access = await credentials.resolve({
116
+ runtime: runtime2.id,
117
+ actor: start.actor,
118
+ access: runtime2.id === "pi" ? options.healCredentials ?? options.modelCredentials : modelAccess === "env" ? options.modelCredentials : runtime2.id !== "codex" && options.subscriptionToken ? { mode: "env", env: { CLAUDE_CODE_OAUTH_TOKEN: options.subscriptionToken } } : { mode: "inherit-login" }
119
+ });
120
+ if (access.mode === "env") {
121
+ redactor.add(Object.values(access.env));
122
+ }
123
+ const selectedRuntime = agentAt === "stage" ? activeHandle && (options.stageRuntime?.(activeHandle, runtime2) ?? e2b?.agentRuntime(activeHandle, runtime2.id)) : runtime2;
124
+ if (!selectedRuntime) throw new Error("Stage agent transport unavailable");
125
+ const session = await selectedRuntime.start({ ...start, access }, signal);
126
+ if (observe) {
127
+ observation.runtime = runtime2.id === "claude-code" || runtime2.id === "codex" || runtime2.id === "scripted" ? runtime2.id : null;
128
+ observation.modelAccess = modelAccess;
129
+ observation.credentialSource = modelAccess === "env" ? "model-env" : access.mode === "env" ? "subscription-token" : "local-login";
130
+ }
131
+ return session;
132
+ }
133
+ });
134
+ const store = options.runStore ?? new FileRunStore(options.root);
135
+ const history = options.runHistory ?? (store.listRuns ? { listRuns: store.listRuns.bind(store) } : void 0);
136
+ const classifications = options.classifications ?? (store instanceof FileRunStore ? store : void 0);
137
+ const pendingNotifications = [];
138
+ const classifying = classifications ? new ClassifyingRuns({
139
+ store,
140
+ classifications,
141
+ redactor,
142
+ classifier: options.classifier ?? new ModelClassifier(
143
+ new IndependentModelCaller({
144
+ credentials,
145
+ runtime,
146
+ redactor,
147
+ purpose: "classifier",
148
+ model: options.classifierConfig?.model,
149
+ subscriptionToken: options.subscriptionToken,
150
+ localAccess: modelAccess === "env" ? options.modelCredentials : void 0,
151
+ requireTeam: options.origin === "server"
152
+ }),
153
+ { ...options.classifierConfig, redactor }
154
+ ),
155
+ diff: async (flow) => {
156
+ let reason = "Run store has no classification history reader; inject runHistory";
157
+ const gitDiff = history ? await lastPassedDiff({
158
+ root: options.root,
159
+ runs: history,
160
+ flow,
161
+ target: options.target.url,
162
+ revision: options.target.revision,
163
+ sourceFiles: options.classifierConfig?.sourceFiles,
164
+ redactor,
165
+ onUnavailable: (value) => {
166
+ reason = value;
167
+ }
168
+ }) : null;
169
+ return { gitDiff, reason };
170
+ },
171
+ targetRevision: options.targetRevision,
172
+ onClassified: async (runId, classification, verdict, errorReason) => {
173
+ await options.onClassified?.(runId, classification, verdict);
174
+ pendingNotifications.push({
175
+ runId,
176
+ verdict,
177
+ classification,
178
+ ...errorReason && { errorReason },
179
+ ...options.classificationOwners
180
+ });
181
+ }
182
+ }) : void 0;
183
+ const healRuntime = options.healRuntime ?? (options.heal?.runtime ? options.heal.runtime === "codex" ? new CodexRuntime() : options.heal.runtime === "pi" ? new PiRuntime() : new ClaudeCodeRuntime() : runtime);
184
+ const deps = {
185
+ billing: options.billing ?? (modelAccess === "env" ? "metered" : "subscription"),
186
+ healBilling: healRuntime.id === "pi" ? "metered" : void 0,
187
+ executor: {
188
+ async provision(spec, signal) {
189
+ const handle = await executor.provision(spec, signal);
190
+ activeHandle = handle;
191
+ try {
192
+ await options.onStage?.(spec.runId, handle);
193
+ } catch (error) {
194
+ await handle.asyncDispose();
195
+ throw error;
196
+ }
197
+ redactor.add([
198
+ handle.conductorToken,
199
+ ...Object.values(handle.actorTokens),
200
+ handle.screenAccess?.token ?? ""
201
+ ]);
202
+ observation.placement = handle.placement;
203
+ return handle;
204
+ }
205
+ },
206
+ runtime: wrapRuntime(runtime),
207
+ healRuntime: wrapRuntime(healRuntime, false),
208
+ healModel: options.heal?.model,
209
+ healModelAccess: healRuntime.id === "pi" ? "env" : modelAccess,
210
+ principalId: options.principalId,
211
+ store: classifying?.store ?? store,
212
+ onCleanup: options.onCleanup,
213
+ judge: options.judge ?? new ModelJudge(
214
+ new IndependentModelCaller({
215
+ credentials,
216
+ runtime,
217
+ redactor,
218
+ model: options.judgeConfig?.model,
219
+ subscriptionToken: options.subscriptionToken,
220
+ localAccess: modelAccess === "env" ? options.modelCredentials : void 0,
221
+ requireTeam: options.origin === "server"
222
+ }),
223
+ { ...options.judgeConfig, redactor }
224
+ ),
225
+ judgeTimeoutMs: (options.judgeConfig?.timeoutMs ?? 6e4) + 5e3,
226
+ judgeScreenshots: options.judgeConfig?.screenshots !== false,
227
+ reviewer: options.reviewer ?? new ModelReviewer(
228
+ new IndependentModelCaller({
229
+ credentials,
230
+ runtime,
231
+ redactor,
232
+ purpose: "reviewer",
233
+ model: options.reviewerConfig?.model,
234
+ subscriptionToken: options.subscriptionToken,
235
+ localAccess: modelAccess === "env" ? options.modelCredentials : void 0,
236
+ requireTeam: options.origin === "server"
237
+ }),
238
+ { ...options.reviewerConfig, redactor }
239
+ ),
240
+ reviewerTimeoutMs: (options.reviewerConfig?.timeoutMs ?? 6e4) + 5e3,
241
+ reviewerScreenshots: options.reviewerConfig?.screenshots !== false,
242
+ replay: options.replay,
243
+ replayImage: (runId, crop) => loadReplayImage(options.root, runId, crop),
244
+ replayCache: options.replayCache ?? new FileReplayCache(options.root, redactor),
245
+ leases: options.leases ?? new FixedLeasePool(options.root),
246
+ hooks: options.hooks ?? new FileHookRunner({
247
+ root: options.root,
248
+ registry: allowConsumerHooks ? void 0 : new HookRegistry(),
249
+ hostEnv: options.env
250
+ }),
251
+ connectStage: (handle) => options.connectStage?.(handle) ?? e2b?.connectStage(handle) ?? new HttpStageClient(handle),
252
+ placement: options.placement ?? "local-host",
253
+ clock: { now: Date.now },
254
+ ids: {
255
+ next: (prefix) => prefix === "run" && options.runId ? options.runId : `${prefix}_${randomUUID()}`
256
+ },
257
+ target: options.target,
258
+ brief: options.brief,
259
+ artifacts: (id) => ({ type: "directory", path: join(runDirectory(options.root, id), "stage") }),
260
+ retries: options.retries,
261
+ level: options.level,
262
+ secrets: [
263
+ ...privateEnvSecrets(options.env ?? {}, publicEnv),
264
+ options.subscriptionToken,
265
+ ...systemSecretValues(options.stage?.systems)
266
+ ].filter((value) => !!value),
267
+ redactor,
268
+ stageSecrets
269
+ };
270
+ return {
271
+ observation,
272
+ run: async (plan, signal) => {
273
+ const result = await runFlow(plan, deps, signal);
274
+ await classifying?.finish(plan.key, result, signal);
275
+ const records = await Promise.all(
276
+ result.runs.map((run) => classifications?.getClassification(run.runId))
277
+ );
278
+ const category = records.find((record) => record?.classification?.category === "flaky")?.classification?.category ?? records.findLast((record) => record?.classification)?.classification?.category ?? null;
279
+ let state;
280
+ try {
281
+ state = await options.flowStatus?.record({
282
+ flow: plan.key,
283
+ executionId: result.runId,
284
+ verdict: result.verdict,
285
+ category,
286
+ owner: options.classificationOwners?.flowOwner,
287
+ ...options.flowRevision && { revision: options.flowRevision }
288
+ });
289
+ } catch {
290
+ throw new FlowStatusWriteError({ ...result, category });
291
+ }
292
+ if (!state?.quarantined)
293
+ for (const run of pendingNotifications.splice(0)) {
294
+ try {
295
+ await options.notifier?.notify({
296
+ batchId: options.batchId ?? result.runId,
297
+ runs: [run]
298
+ });
299
+ } catch {
300
+ console.warn("QA classification notification failed");
301
+ }
302
+ }
303
+ pendingNotifications.length = 0;
304
+ return {
305
+ ...result,
306
+ category,
307
+ quarantined: state?.quarantined ?? false,
308
+ lifecycle: state?.status
309
+ };
310
+ }
311
+ };
312
+ }
313
+ function requiredE2bOptions(options) {
314
+ if (!options.e2b)
315
+ throw new Error("QA E2B execution requires project, batch, template and budget configuration");
316
+ return options.e2b;
317
+ }
318
+ export {
319
+ FlowStatusWriteError,
320
+ PUBLIC_ENV_KEYS,
321
+ createEngine,
322
+ privateEnvSecrets
323
+ };
@@ -0,0 +1,21 @@
1
+ import { type ExecutionPlan, type ExecutionSnapshot, type QaConfig } from "@open-qa/qa-engine";
2
+ import type { LoadedFlow } from "./flow-loader.js";
3
+ export declare function sourceVersions(root: string): Promise<ExecutionSnapshot["versions"]>;
4
+ export declare function captureExecutionSnapshot(input: {
5
+ config: QaConfig;
6
+ definitions: LoadedFlow["definitions"];
7
+ plan: ExecutionPlan;
8
+ targetName: string;
9
+ runtime: "claude-code" | "codex";
10
+ retries: 0 | 1;
11
+ placement?: "local-host" | "e2b";
12
+ agentAt?: "host" | "stage";
13
+ modelAccess?: "login" | "env";
14
+ headed?: boolean;
15
+ level?: string;
16
+ versions: ExecutionSnapshot["versions"];
17
+ env: NodeJS.ProcessEnv;
18
+ publicEnv?: readonly string[];
19
+ subscriptionToken?: string;
20
+ systemSecrets?: readonly string[];
21
+ }): ExecutionSnapshot;
@@ -0,0 +1,141 @@
1
+ import { isProtectedTarget } from "@open-qa/qa-engine";
2
+ import { execFile } from "node:child_process";
3
+ import { readFile } from "node:fs/promises";
4
+ import { promisify } from "node:util";
5
+ import {
6
+ SecretRedactor,
7
+ executionSnapshotSchema
8
+ } from "@open-qa/qa-engine";
9
+ import { privateEnvSecrets } from "./engine.js";
10
+ const execute = promisify(execFile);
11
+ async function packageVersion(url) {
12
+ try {
13
+ const metadata = JSON.parse(await readFile(url, "utf8"));
14
+ return typeof metadata?.version === "string" && metadata.version ? metadata.version : "unknown";
15
+ } catch {
16
+ return "unknown";
17
+ }
18
+ }
19
+ async function sourceVersions(root) {
20
+ const versions = await Promise.all([
21
+ packageVersion(new URL("../package.json", import.meta.url)),
22
+ packageVersion(new URL(import.meta.resolve("@open-qa/qa-engine/package.json")))
23
+ ]);
24
+ let commit = null;
25
+ let dirty = null;
26
+ try {
27
+ const revision = await execute("git", ["rev-parse", "HEAD"], { cwd: root, timeout: 3e3 });
28
+ const status = await execute("git", ["status", "--porcelain", "--untracked-files=normal"], {
29
+ cwd: root,
30
+ timeout: 3e3
31
+ });
32
+ commit = /^[a-f0-9]{40,64}$/.test(revision.stdout.trim()) ? revision.stdout.trim() : null;
33
+ dirty = !!status.stdout.trim();
34
+ } catch {
35
+ }
36
+ return {
37
+ cli: versions[0],
38
+ engine: versions[1],
39
+ node: process.versions.node,
40
+ commit,
41
+ dirty
42
+ };
43
+ }
44
+ function captureExecutionSnapshot(input) {
45
+ const { config, plan, targetName } = input;
46
+ const target = config.targets[targetName];
47
+ let zone;
48
+ if (config.timeZone) zone = { value: config.timeZone, source: "config" };
49
+ else {
50
+ const value = Intl.DateTimeFormat().resolvedOptions().timeZone;
51
+ zone = value ? { value, source: "machine" } : { value: "UTC", source: "fallback" };
52
+ }
53
+ const snapshot = executionSnapshotSchema.parse({
54
+ schemaVersion: 6,
55
+ capturedAt: Date.now(),
56
+ projectId: config.projectId,
57
+ timeZone: zone,
58
+ definitions: input.definitions,
59
+ target: {
60
+ ...target.revision && { revision: target.revision },
61
+ name: targetName,
62
+ origin: new URL(target.url).origin,
63
+ allow: target.allow,
64
+ access: target.access ?? "none",
65
+ prodSafeOnly: isProtectedTarget(targetName, target)
66
+ },
67
+ effective: {
68
+ prod: plan.prod,
69
+ tier: plan.tier ?? null,
70
+ budget: plan.budget ?? null,
71
+ record: plan.record,
72
+ retries: input.retries,
73
+ headed: !!input.headed,
74
+ level: input.level ?? null
75
+ },
76
+ declared: {
77
+ heal: {
78
+ runtime: config.heal?.runtime ?? input.runtime,
79
+ model: config.heal?.model ?? null,
80
+ modelAccess: config.heal?.runtime === "pi" ? "env" : input.modelAccess ?? "login"
81
+ },
82
+ runtime: input.runtime,
83
+ modelAccess: input.modelAccess ?? "login",
84
+ agentAt: input.agentAt ?? "host",
85
+ placement: input.placement ?? "local-host",
86
+ capabilities: {
87
+ surfaces: [...new Set(Object.values(plan.views).map((view) => view.surface))],
88
+ recording: ["rrweb"],
89
+ levels: ["semantic", "pixel", "hybrid"]
90
+ }
91
+ },
92
+ observed: {
93
+ runtime: null,
94
+ modelAccess: null,
95
+ credentialSource: null,
96
+ placement: null,
97
+ capabilities: null
98
+ },
99
+ versions: input.versions,
100
+ environment: {
101
+ subscriptionToken: input.runtime === "claude-code" ? input.subscriptionToken ? "set" : "missing" : "unknown",
102
+ cloudflareAccess: target.access === "cloudflare" ? input.env.QA_CF_ACCESS_CLIENT_ID && input.env.QA_CF_ACCESS_CLIENT_SECRET ? "set" : "missing" : "unknown"
103
+ }
104
+ });
105
+ const redactor = new SecretRedactor();
106
+ redactor.add(
107
+ [
108
+ ...privateEnvSecrets(input.env, input.publicEnv),
109
+ input.subscriptionToken,
110
+ ...input.systemSecrets ?? []
111
+ ].filter((value) => !!value)
112
+ );
113
+ if (redactor.text(snapshot.projectId) !== snapshot.projectId || redactor.text(snapshot.timeZone.value) !== snapshot.timeZone.value)
114
+ throw new Error(
115
+ "Execution snapshot contains sensitive configuration in public identity fields"
116
+ );
117
+ if ((snapshot.schemaVersion === 5 || snapshot.schemaVersion === 6) && snapshot.declared.heal.model)
118
+ snapshot.declared.heal.model = redactor.text(snapshot.declared.heal.model);
119
+ const revision = (value) => value ? { ...value, source: redactor.text(value.source) } : null;
120
+ return {
121
+ ...snapshot,
122
+ definitions: {
123
+ flow: {
124
+ ...snapshot.definitions.flow,
125
+ source: redactor.text(snapshot.definitions.flow.source)
126
+ },
127
+ suite: revision(snapshot.definitions.suite),
128
+ config: revision(snapshot.definitions.config)
129
+ },
130
+ target: {
131
+ ...snapshot.target,
132
+ name: redactor.text(snapshot.target.name),
133
+ origin: snapshot.target.origin && redactor.text(snapshot.target.origin) === snapshot.target.origin ? snapshot.target.origin : null,
134
+ allow: snapshot.target.allow.map((host) => redactor.text(host))
135
+ }
136
+ };
137
+ }
138
+ export {
139
+ captureExecutionSnapshot,
140
+ sourceVersions
141
+ };
@@ -0,0 +1,9 @@
1
+ export declare function checkFlows(path: string, options: {
2
+ root?: string;
3
+ lint: boolean;
4
+ strict?: boolean;
5
+ }): Promise<{
6
+ summary: string;
7
+ diagnostics: string[];
8
+ failed: boolean;
9
+ }>;
@@ -0,0 +1,68 @@
1
+ import { stat } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { compile, CompileError } from "@open-qa/qa-engine";
4
+ import { findQaRoot, loadFlowDocument, loadFlowDocuments } from "./flow-loader.js";
5
+ import { validateDraftHooks } from "./draft-hooks.js";
6
+ import { lintFlow } from "./flow-lint.js";
7
+ async function checkFlows(path, options) {
8
+ const target = resolve(path);
9
+ const schemaDiagnostics = /* @__PURE__ */ new Set();
10
+ function schemaError(error) {
11
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") throw error;
12
+ const message = error instanceof Error ? error.message : String(error);
13
+ for (const line of message.split("\n"))
14
+ schemaDiagnostics.add(line.replace(/^(.+:\d+:\d+) /, "$1 schema "));
15
+ }
16
+ let documents;
17
+ let root;
18
+ try {
19
+ const targetStat = await stat(target);
20
+ root = options.root ? resolve(options.root) : findQaRoot(target);
21
+ documents = targetStat.isDirectory() ? await loadFlowDocuments(root, target, schemaError) : [await loadFlowDocument(target, root)];
22
+ } catch (error) {
23
+ const message = error instanceof Error ? error.message : String(error);
24
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") throw error;
25
+ throw new Error(message.replace(/^(.+:\d+:\d+) /gm, "$1 schema "), { cause: error });
26
+ }
27
+ const diagnostics = [...schemaDiagnostics];
28
+ let errors = diagnostics.length;
29
+ let warnings = 0;
30
+ for (const document of documents) {
31
+ try {
32
+ compile(document.flow);
33
+ } catch (error) {
34
+ if (!(error instanceof CompileError)) throw error;
35
+ diagnostics.push(...error.issues.map((issue) => document.diagnostic(issue, "compile")));
36
+ errors += error.issues.length;
37
+ continue;
38
+ }
39
+ try {
40
+ await validateDraftHooks(root, document.flow);
41
+ } catch (error) {
42
+ diagnostics.push(
43
+ document.diagnostic(
44
+ {
45
+ path: ["setup"],
46
+ message: error instanceof Error ? error.message : "Invalid hook registry"
47
+ },
48
+ "hooks"
49
+ )
50
+ );
51
+ errors++;
52
+ continue;
53
+ }
54
+ if (options.lint) {
55
+ const issues = lintFlow(document.flow, document.programSource);
56
+ diagnostics.push(...issues.map((issue) => document.diagnostic(issue, issue.rule)));
57
+ warnings += issues.length;
58
+ }
59
+ }
60
+ return {
61
+ summary: errors ? `validation failed with ${errors} errors` : options.lint ? `linted ${documents.length} flows, ${warnings} warnings` : `validated ${documents.length} flows`,
62
+ diagnostics,
63
+ failed: errors > 0 || !!options.strict && warnings > 0
64
+ };
65
+ }
66
+ export {
67
+ checkFlows
68
+ };
@@ -0,0 +1,6 @@
1
+ import { type FlowLifecycleStore, type FlowTrigger } from "@open-qa/qa-engine";
2
+ import type { LoadedFlow } from "./flow-loader.js";
3
+ export declare const NO_LIFECYCLE_NOTICE = "Flow lifecycle not applied: QA_DATABASE_URL is not set. Using file rules: flows under drafts/ or with status: draft are skipped in directory runs.";
4
+ export declare function fileDraft({ flow, definitions }: Pick<LoadedFlow, "flow" | "definitions">): boolean;
5
+ /** Directory runs are suite triggers; naming one flow file is a manual trigger. */
6
+ export declare function selectByLifecycle<T extends Pick<LoadedFlow, "flow" | "definitions">>(flows: readonly T[], trigger: FlowTrigger, store: FlowLifecycleStore | undefined, output: (line: string) => void): Promise<T[]>;
@@ -0,0 +1,61 @@
1
+ import {
2
+ isDraftPath,
3
+ lifecycleOf,
4
+ runsOn
5
+ } from "@open-qa/qa-engine";
6
+ const NO_LIFECYCLE_NOTICE = "Flow lifecycle not applied: QA_DATABASE_URL is not set. Using file rules: flows under drafts/ or with status: draft are skipped in directory runs.";
7
+ function fileDraft({ flow, definitions }) {
8
+ return flow.status === "draft" || isDraftPath(definitions.flow.source);
9
+ }
10
+ async function selectByLifecycle(flows, trigger, store, output) {
11
+ if (!store) {
12
+ if (trigger === "manual") return [...flows];
13
+ if (!process.env.QA_DATABASE_URL) output(NO_LIFECYCLE_NOTICE);
14
+ return flows.filter((flow) => !fileDraft(flow));
15
+ }
16
+ let states;
17
+ try {
18
+ states = await store.states(flows.map(({ flow }) => flow.key));
19
+ } catch {
20
+ throw new Error(
21
+ "Cannot read flow lifecycle states; check QA_DATABASE_URL and applied migrations"
22
+ );
23
+ }
24
+ const status = (item) => lifecycleOf(states.get(item.flow.key), item.definitions.flow.sha256);
25
+ const selected = flows.filter((item) => runsOn(status(item), trigger));
26
+ const skipped = flows.filter((item) => !selected.includes(item));
27
+ if (trigger === "manual") {
28
+ if (skipped[0])
29
+ throw new Error(
30
+ `Flow ${skipped[0].flow.key} is retired and no longer runs. A new key starts a new draft.`
31
+ );
32
+ for (const item of selected) {
33
+ const current = status(item);
34
+ if (current === "draft" || current === "review")
35
+ output(
36
+ `${item.flow.key} \xB7 ${current} \xB7 this manual run becomes its first run; review the replay, then run pnpm qa accept ${item.flow.key}`
37
+ );
38
+ }
39
+ return selected;
40
+ }
41
+ if (skipped.length) {
42
+ const counts = /* @__PURE__ */ new Map();
43
+ for (const item of skipped) counts.set(status(item), (counts.get(status(item)) ?? 0) + 1);
44
+ output(
45
+ `Skipped ${skipped.length} flow(s) by lifecycle: ${[...counts].map(([name, count]) => `${count} ${name}`).join(", ")}. Run one flow file to give a draft its first run.`
46
+ );
47
+ }
48
+ const unrecorded = skipped.filter(
49
+ (item) => !states.has(item.flow.key) && !fileDraft(item)
50
+ ).length;
51
+ if (!selected.length && unrecorded)
52
+ throw new Error(
53
+ `No active flows match the selection. ${unrecorded} flow(s) outside drafts/ have no lifecycle record; adopt existing flows once with pnpm qa accept --baseline <directory>.`
54
+ );
55
+ return selected;
56
+ }
57
+ export {
58
+ NO_LIFECYCLE_NOTICE,
59
+ fileDraft,
60
+ selectByLifecycle
61
+ };
@@ -0,0 +1,8 @@
1
+ import type { FlowSpec } from "@open-qa/qa-engine";
2
+ import type { FieldPath } from "./flow-source.js";
3
+ export interface LintWarning {
4
+ path: FieldPath;
5
+ rule: string;
6
+ message: string;
7
+ }
8
+ export declare function lintFlow(flow: FlowSpec, programSource?: string | undefined): LintWarning[];