@open-qa/qa 0.1.0-alpha.3 → 0.1.0-alpha.5

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 (118) hide show
  1. package/THIRD_PARTY.md +5 -0
  2. package/drizzle/0017_provider_notifications.sql +13 -0
  3. package/drizzle/0018_classification_registry.sql +39 -0
  4. package/drizzle/0019_trial_audit.sql +44 -0
  5. package/drizzle/meta/0017_snapshot.json +2092 -0
  6. package/drizzle/meta/0018_snapshot.json +2102 -0
  7. package/drizzle/meta/0019_snapshot.json +2451 -0
  8. package/drizzle/meta/_journal.json +21 -0
  9. package/package.json +12 -7
  10. package/src/access-binding.d.ts +8 -0
  11. package/src/access-binding.js +26 -0
  12. package/src/adapters/classification-write.d.ts +87 -0
  13. package/src/adapters/classification-write.js +64 -0
  14. package/src/adapters/e2b-executor.js +4 -0
  15. package/src/adapters/file-run-store.d.ts +186 -41
  16. package/src/adapters/file-run-store.js +87 -19
  17. package/src/adapters/file-trial-audit.d.ts +280 -0
  18. package/src/adapters/file-trial-audit.js +105 -0
  19. package/src/adapters/pg-classification-store.d.ts +98 -20
  20. package/src/adapters/pg-classification-store.js +84 -44
  21. package/src/adapters/pg-run-store.d.ts +1 -0
  22. package/src/adapters/pg-run-store.js +70 -9
  23. package/src/adapters/run-metadata.d.ts +2 -0
  24. package/src/adapters/run-metadata.js +10 -0
  25. package/src/adapters/secret-manager-credential-resolver.d.ts +1 -1
  26. package/src/attempt-audit.d.ts +363 -0
  27. package/src/attempt-audit.js +253 -0
  28. package/src/audit-command.d.ts +13 -0
  29. package/src/audit-command.js +77 -0
  30. package/src/classification-command.d.ts +14 -9
  31. package/src/classification-command.js +119 -26
  32. package/src/classification-model.d.ts +10 -3
  33. package/src/classification-model.js +40 -24
  34. package/src/classification-notifier.d.ts +4 -3
  35. package/src/classification-notifier.js +26 -6
  36. package/src/classify-runs.d.ts +2 -1
  37. package/src/classify-runs.js +39 -3
  38. package/src/cli-program.js +54 -8
  39. package/src/commands.d.ts +1 -0
  40. package/src/commands.js +2 -0
  41. package/src/db/database.d.ts +7 -0
  42. package/src/db/database.js +15 -0
  43. package/src/db/event-chunks.d.ts +38 -29
  44. package/src/db/flow-status.d.ts +7 -3
  45. package/src/db/flow-status.js +240 -16
  46. package/src/db/queries.d.ts +24 -1
  47. package/src/db/queries.js +22 -0
  48. package/src/db/schema.d.ts +333 -4
  49. package/src/db/schema.js +83 -11
  50. package/src/db/trial-audit.d.ts +526 -0
  51. package/src/db/trial-audit.js +84 -0
  52. package/src/doctor-command.js +2 -1
  53. package/src/draft-api.d.ts +25 -421
  54. package/src/draft-api.js +10 -3
  55. package/src/engine.d.ts +47 -4
  56. package/src/engine.js +97 -8
  57. package/src/execution-snapshot.d.ts +1 -1
  58. package/src/execution-snapshot.js +24 -18
  59. package/src/export-command.d.ts +6 -0
  60. package/src/export-command.js +106 -0
  61. package/src/flow-check.js +1 -1
  62. package/src/flow-loader.d.ts +72 -6
  63. package/src/flow-loader.js +76 -12
  64. package/src/http-stage-client.d.ts +98 -1
  65. package/src/independent-model.js +53 -6
  66. package/src/judge-review-store.d.ts +13 -0
  67. package/src/judge-review-store.js +58 -0
  68. package/src/local-host-executor.d.ts +3 -1
  69. package/src/local-host-executor.js +2 -0
  70. package/src/quarantine-command.d.ts +5 -1
  71. package/src/quarantine-command.js +56 -13
  72. package/src/remote-command.js +2 -0
  73. package/src/report/browser.css +1 -1
  74. package/src/report/browser.js +41 -41
  75. package/src/report/ctrf.d.ts +983 -0
  76. package/src/report/ctrf.js +306 -0
  77. package/src/report/generate.d.ts +1 -1
  78. package/src/report/generate.js +29 -6
  79. package/src/report/load.d.ts +738 -42
  80. package/src/report/load.js +78 -6
  81. package/src/result-notifier.js +1 -1
  82. package/src/result-trace.d.ts +62 -0
  83. package/src/result-trace.js +81 -0
  84. package/src/run-command.d.ts +9 -0
  85. package/src/run-command.js +300 -63
  86. package/src/run-setup-error.d.ts +11 -0
  87. package/src/run-setup-error.js +18 -0
  88. package/src/server/app.js +5 -4
  89. package/src/server/index.d.ts +2 -0
  90. package/src/server/index.js +11 -2
  91. package/src/server/repository.d.ts +166 -29
  92. package/src/server/repository.js +14 -2
  93. package/src/studio-command.d.ts +1 -0
  94. package/src/studio-command.js +11 -0
  95. package/src/studio-control.d.ts +5 -0
  96. package/src/studio-control.js +207 -0
  97. package/src/studio-review.d.ts +24 -0
  98. package/src/studio-review.js +64 -0
  99. package/src/studio-worker.d.ts +1 -0
  100. package/src/studio-worker.js +48 -0
  101. package/src/system-config.d.ts +2 -2
  102. package/src/system-config.js +5 -4
  103. package/src/trial-audit.d.ts +630 -0
  104. package/src/trial-audit.js +272 -0
  105. package/src/visual-baseline.d.ts +4 -0
  106. package/src/visual-baseline.js +42 -0
  107. package/src/webhook-notification.d.ts +15 -0
  108. package/src/webhook-notification.js +61 -0
  109. package/src/worker/execution.d.ts +2 -1
  110. package/src/worker/execution.js +122 -3
  111. package/src/worker/index.d.ts +4 -0
  112. package/src/worker/index.js +10 -1
  113. package/src/worker/quarantine-notifications.js +2 -2
  114. package/src/worker/queue.d.ts +6 -2
  115. package/src/worker/queue.js +80 -19
  116. package/src/worker/result-notifications.d.ts +10 -2
  117. package/src/worker/result-notifications.js +120 -23
  118. package/src/worker/store.js +6 -3
@@ -1,3 +1,6 @@
1
+ import { resolveAccessBinding } from "./access-binding.js";
2
+ import { RunSetupError } from "./run-setup-error.js";
3
+ import { isProtectedTarget } from "@open-qa/qa-engine";
1
4
  import { confirmRunEstimate } from "./budget-confirmation.js";
2
5
  import { writeWatchState, removeWatchState } from "./watch-state.js";
3
6
  import { e2bConfig } from "./adapters/e2b-client.js";
@@ -9,7 +12,11 @@ import { readFile, stat } from "node:fs/promises";
9
12
  import { join, resolve } from "node:path";
10
13
  import {
11
14
  compile,
15
+ CompileError,
16
+ loadProviderRegistry,
17
+ loadClassificationRegistry,
12
18
  sumRunUsage,
19
+ quarantinePolicySchema,
13
20
  SecretRedactor,
14
21
  selectAgentPlacement,
15
22
  targetAllowsUrl
@@ -22,17 +29,25 @@ import { hasCode, runDirectory } from "./adapters/local-files.js";
22
29
  import { readLocalEnv } from "./adapters/local-env.js";
23
30
  import { generateReport } from "./report/generate.js";
24
31
  import { captureExecutionSnapshot, sourceVersions } from "./execution-snapshot.js";
32
+ import { buildResultTrace, readRunContext, resultCaseId } from "./result-trace.js";
25
33
  import { readConsumerManifest } from "./hooks/consumer.js";
26
34
  import { TerminalReporter } from "./terminal-reporter.js";
27
35
  import { scanRunArtifacts } from "./artifact-scan.js";
28
- import { QaDatabase } from "./db/database.js";
36
+ import { QaDatabase, postgresNow } from "./db/database.js";
29
37
  import { PgFlowStatus } from "./db/flow-status.js";
30
38
  import { printRepeat } from "./quarantine-command.js";
31
39
  import { selectByLifecycle } from "./flow-lifecycle.js";
40
+ import { FileTrialAudit } from "./adapters/file-trial-audit.js";
41
+ import { PgTrialAudit } from "./db/trial-audit.js";
42
+ import { printTrial, summarizeTrial } from "./trial-audit.js";
43
+ import { attemptAuditSchema } from "./attempt-audit.js";
32
44
  async function runCommand(path, options, adapters = {}) {
45
+ const runContext = await readRunContext(options.runContext);
33
46
  const repeat = options.repeat ?? 1;
34
47
  if (!Number.isInteger(repeat) || repeat < 1 || repeat > 100)
35
48
  throw new Error("--repeat must be an integer between 1 and 100");
49
+ if (options.dependentTrials && options.repeat === void 0)
50
+ throw new Error("--dependent-trials requires --repeat");
36
51
  if (options.executor && options.executor !== "local-host" && options.executor !== "e2b")
37
52
  throw new Error("--executor must be local-host or e2b");
38
53
  const placement = options.executor === "e2b" ? "e2b" : "local-host";
@@ -73,7 +88,8 @@ async function runCommand(path, options, adapters = {}) {
73
88
  if (options.replay !== void 0 && options.replay !== "off")
74
89
  throw new Error("--replay only accepts off");
75
90
  const root = options.root ? resolve(options.root) : findQaRoot(path);
76
- const config = await loadConfig(root);
91
+ const providers = await loadProviderRegistry();
92
+ const config = await loadConfig(root, providers);
77
93
  if (!config.projectId)
78
94
  throw new Error(
79
95
  "Missing projectId in config.yaml; configure a persistent opaque projectId once and commit it with the project"
@@ -87,7 +103,12 @@ async function runCommand(path, options, adapters = {}) {
87
103
  if (!targetAllowsUrl(target, target.url))
88
104
  throw new Error(`Target ${targetName} URL is outside its allow list`);
89
105
  const trigger = (await stat(path)).isDirectory() ? "suite" : "manual";
90
- let flows = trigger === "suite" ? await loadFlowDocuments(root, path) : [await loadFlowDocument(path, root)];
106
+ let flows = trigger === "suite" ? await loadFlowDocuments(root, path, void 0, providers) : [await loadFlowDocument(path, root, providers)];
107
+ if (adapters.studio) {
108
+ if (trigger !== "manual" || isProtectedTarget(targetName, target) || flows.length !== 1)
109
+ throw new Error("Target unavailable in Studio");
110
+ adapters.studio.verify(config, flows[0]);
111
+ }
91
112
  if (options.tag) flows = flows.filter(({ flow }) => flow.tags?.includes(options.tag));
92
113
  if (!flows.length) throw new Error("No flows match the selection");
93
114
  const loaded = flows;
@@ -99,38 +120,55 @@ async function runCommand(path, options, adapters = {}) {
99
120
  if (!flows.length) throw new Error("No flows match the selection");
100
121
  if (options.repeat !== void 0 && flows.length !== 1)
101
122
  throw new Error("--repeat requires exactly one selected flow");
102
- const plans = flows.map(
103
- ({ flow }) => compile({
104
- ...flow,
105
- ...cloud ? { budget: { ...flow.budget, minutes: flow.budget?.minutes ?? 15 } } : {},
106
- actors: Object.fromEntries(
107
- Object.entries(flow.actors).map(([name, actor]) => [
108
- name,
109
- {
110
- ...actor,
111
- ...actor.kind !== "system" ? { persona: options.persona ?? actor.persona ?? "default" } : {}
123
+ const plans = flows.map((document) => {
124
+ const { flow } = document;
125
+ try {
126
+ return compile(
127
+ {
128
+ ...flow,
129
+ ...cloud ? { budget: { ...flow.budget, minutes: flow.budget?.minutes ?? 15 } } : {},
130
+ actors: Object.fromEntries(
131
+ Object.entries(flow.actors).map(([name, actor]) => [
132
+ name,
133
+ {
134
+ ...actor,
135
+ ...actor.kind !== "system" ? { persona: options.persona ?? actor.persona ?? "default" } : {}
136
+ }
137
+ ])
138
+ )
139
+ },
140
+ void 0,
141
+ {
142
+ providers,
143
+ target: {
144
+ name: targetName,
145
+ access: target.access,
146
+ protected: isProtectedTarget(targetName, target),
147
+ placement
112
148
  }
113
- ])
114
- )
115
- })
116
- );
149
+ }
150
+ );
151
+ } catch (error) {
152
+ if (!(error instanceof CompileError)) throw error;
153
+ const message = error.issues.map((issue) => document.diagnostic(issue, "compile")).join("\n");
154
+ if (error.issues.some(
155
+ (issue) => issue.message.startsWith("Unsupported ") && issue.path[0] === "views"
156
+ ))
157
+ throw new RunSetupError("unsupported-surface", message, { cause: error });
158
+ throw new Error(message, { cause: error });
159
+ }
160
+ });
117
161
  const personas = await loadPersonas(
118
162
  root,
119
163
  plans.flatMap(
120
164
  (plan) => plan.lanes.filter((lane) => lane.kind === "user").map((lane) => lane.spec.persona)
121
165
  )
122
166
  );
123
- for (const plan of plans) {
124
- if ((targetName === "prod" || target.prodSafeOnly) && plan.prod !== "safe")
167
+ for (const plan of plans)
168
+ if (isProtectedTarget(targetName, target) && plan.prod !== "safe")
125
169
  throw new Error(`Flow ${plan.key} must declare prod: safe for target ${targetName}`);
126
- for (const view of Object.values(plan.views)) {
127
- if (!["web", "telegram", "discord", "email"].includes(view.surface))
128
- throw new Error(`Unsupported local view surface: ${view.surface}`);
129
- if (view.surface === "telegram" && (targetName === "prod" || target.prodSafeOnly))
130
- throw new Error("Telegram requires a non-production target");
131
- }
132
- }
133
- const store = adapters.runStore ?? new FileRunStore(root);
170
+ const classificationScope = adapters.classificationScope ?? (adapters.runStore instanceof FileRunStore ? adapters.runStore.classificationScope : loadClassificationRegistry().forProject(config.projectId));
171
+ const store = adapters.runStore ?? new FileRunStore(root, classificationScope);
134
172
  await confirmRunEstimate({
135
173
  ...adapters,
136
174
  flows: plans.map((plan) => plan.key),
@@ -141,24 +179,38 @@ async function runCommand(path, options, adapters = {}) {
141
179
  attempts: (retries + 1) * repeat
142
180
  });
143
181
  const env = await optionalEnv(root);
144
- const stageTarget = targetName === "prod" || target.prodSafeOnly ? "prod" : targetName === "local" ? "dev" : "staging";
182
+ const stageTarget = isProtectedTarget(targetName, target) ? "prod" : targetName === "local" ? "dev" : "staging";
145
183
  const systems = new Map(
146
184
  plans.map((plan) => [plan, resolveSystems(stageTarget, target.systems, env, plan)])
147
185
  );
148
186
  let access;
149
187
  if (target.access === "cloudflare") {
150
188
  if (!env.QA_CF_ACCESS_CLIENT_ID || !env.QA_CF_ACCESS_CLIENT_SECRET)
151
- throw new Error(
189
+ throw new RunSetupError(
190
+ "access-credentials",
152
191
  `Cloudflare Access requires QA_CF_ACCESS_CLIENT_ID and QA_CF_ACCESS_CLIENT_SECRET in ${join(root, ".env.local")}`
153
192
  );
154
193
  if (new URL(target.url).protocol !== "https:")
155
- throw new Error("Cloudflare Access requires an HTTPS target");
194
+ throw new RunSetupError("access-https", "Cloudflare Access requires an HTTPS target");
156
195
  access = {
157
196
  origin: new URL(target.url).origin,
158
197
  clientId: env.QA_CF_ACCESS_CLIENT_ID,
159
198
  clientSecret: env.QA_CF_ACCESS_CLIENT_SECRET
160
199
  };
161
200
  }
201
+ const accessBinding = target.access && target.access !== "cloudflare" ? resolveAccessBinding(providers, target.access, targetName, target.url, {
202
+ ...process.env,
203
+ ...env
204
+ }) : void 0;
205
+ for (const [plan, config2] of systems) {
206
+ for (const capability of plan.providers ?? []) {
207
+ if (capability.kind === "tool" && ["db", "logs", "github"].includes(capability.id) && capability.provider === "open-qa" && !config2?.[capability.id])
208
+ throw new RunSetupError(
209
+ "configuration",
210
+ `Tool ${capability.id} requires target.systems configuration`
211
+ );
212
+ }
213
+ }
162
214
  const output = adapters.output ?? console.log;
163
215
  const subscriptionToken = modelAccess === "login" && runtimeId === "claude-code" ? process.env.CLAUDE_CODE_OAUTH_TOKEN : void 0;
164
216
  if (subscriptionToken) output("Using CLAUDE_CODE_OAUTH_TOKEN for subscription login");
@@ -190,11 +242,19 @@ async function runCommand(path, options, adapters = {}) {
190
242
  try {
191
243
  database = !adapters.flowStatus && process.env.QA_DATABASE_URL ? new QaDatabase(process.env.QA_DATABASE_URL) : void 0;
192
244
  const flowStatus = adapters.flowStatus ?? (database ? new PgFlowStatus(database, config.projectId) : void 0);
193
- for (const plan of plans.flatMap((plan2) => Array.from({ length: repeat }, () => plan2))) {
194
- if (signal.aborted) {
195
- code = Math.max(code, 1);
196
- break;
197
- }
245
+ const audit = options.repeat === void 0 ? void 0 : database ? new PgTrialAudit(database, config.projectId) : new FileTrialAudit(root, config.projectId);
246
+ const localAudit = database && localStore && audit ? new FileTrialAudit(root, config.projectId) : void 0;
247
+ const trialTime = (localTime = Date.now()) => database ? postgresNow(database.pool) : localTime;
248
+ const appendTrialReceipt = async (groupId, receipt) => {
249
+ await audit.append(groupId, receipt);
250
+ await localAudit?.append(groupId, receipt);
251
+ };
252
+ let group;
253
+ let quarantinedAtGroupStart = false;
254
+ const trials = plans.flatMap(
255
+ (plan) => Array.from({ length: repeat }, (_, index) => ({ plan, index: index + 1 }))
256
+ );
257
+ for (const { plan, index } of trials) {
198
258
  const reporter = new TerminalReporter(plan, output);
199
259
  const redactor = new SecretRedactor();
200
260
  const blocked = /* @__PURE__ */ new Set();
@@ -216,12 +276,98 @@ async function runCommand(path, options, adapters = {}) {
216
276
  env,
217
277
  publicEnv: readConsumerManifest(root)?.publicEnv,
218
278
  subscriptionToken,
219
- systemSecrets: systemSecretValues(systems.get(plan))
279
+ systemSecrets: [
280
+ ...systemSecretValues(systems.get(plan)),
281
+ ...accessBinding?.secrets ?? []
282
+ ]
220
283
  });
284
+ const caseId = resultCaseId(snapshot.projectId, plan.traceability?.caseId ?? plan.key);
285
+ if (audit && !group) {
286
+ const state = await flowStatus?.get(plan.key);
287
+ quarantinedAtGroupStart = state?.status === "quarantined";
288
+ const { expiresAfterHours, evidenceMaxAgeHours, minimumPassedTrials, flakyStreak } = config.quarantine ?? quarantinePolicySchema.parse({});
289
+ group = redactor.json({
290
+ schemaVersion: 1,
291
+ groupId: `trial:${batchId}:${caseId}`,
292
+ projectId: config.projectId,
293
+ batchId,
294
+ caseId,
295
+ flow: plan.key,
296
+ caseRevision: snapshot.definitions.flow.sha256,
297
+ target: targetName,
298
+ targetRevision: "revision" in snapshot.target ? snapshot.target.revision ?? null : null,
299
+ generation: state?.generation ?? null,
300
+ planned: repeat,
301
+ startedAt: await trialTime(repeatResult.startedAt),
302
+ environment: snapshot,
303
+ ...options.dependentTrials && { independent: false },
304
+ quarantinePolicy: {
305
+ expiresAfterHours,
306
+ evidenceMaxAgeHours,
307
+ minimumPassedTrials,
308
+ flakyStreak
309
+ }
310
+ });
311
+ await audit.create(group);
312
+ await localAudit?.create(group);
313
+ output(`Trial group ${group.groupId}`);
314
+ }
315
+ if (signal.aborted && !adapters.studio) {
316
+ code = Math.max(code, 1);
317
+ break;
318
+ }
319
+ const recordTrial = async (completed) => {
320
+ if (group)
321
+ await appendTrialReceipt(group.groupId, {
322
+ kind: "trial-finished",
323
+ index,
324
+ attemptId: completed.runId,
325
+ quarantined: completed.quarantined ?? false
326
+ });
327
+ };
328
+ const finished = [];
221
329
  const runStore = {
222
330
  ...store.listRuns && { listRuns: store.listRuns.bind(store) },
331
+ async recordClassifierUsage(id, samples) {
332
+ await store.recordClassifierUsage?.(id, samples);
333
+ if (group && samples.length)
334
+ await appendTrialReceipt(group.groupId, {
335
+ kind: "classifier-usage",
336
+ attemptId: id,
337
+ usage: [...samples]
338
+ });
339
+ },
223
340
  createRun: async (run) => {
224
341
  Object.assign(engine.observation, snapshot.observed);
342
+ const resultTrace = buildResultTrace({
343
+ projectId: snapshot.projectId,
344
+ flow: plan.key,
345
+ plan,
346
+ context: runContext,
347
+ attemptId: run.id,
348
+ retryOf: typeof run.metadata?.retryOf === "string" ? run.metadata.retryOf : void 0,
349
+ batchId,
350
+ trial: options.repeat === void 0 ? null : { groupId: `trial:${batchId}:${caseId}`, index, count: repeat },
351
+ caseRevision: snapshot.definitions.flow.sha256,
352
+ target: snapshot.target.name,
353
+ targetRevision: "revision" in snapshot.target ? snapshot.target.revision : null,
354
+ commit: snapshot.versions.commit,
355
+ parameters: {
356
+ ...context,
357
+ placement,
358
+ headed: snapshot.effective.headed,
359
+ level: snapshot.effective.level,
360
+ persona: options.persona,
361
+ replay: options.repeat !== void 0 || options.replay === "off" ? "off" : "enabled"
362
+ },
363
+ environment: {
364
+ ...snapshot.versions,
365
+ origin: snapshot.target.origin,
366
+ suite: snapshot.definitions.suite?.sha256,
367
+ config: snapshot.definitions.config?.sha256,
368
+ zone: snapshot.timeZone.value
369
+ }
370
+ });
225
371
  await store.createRun(
226
372
  redactor.json({
227
373
  ...run,
@@ -230,10 +376,17 @@ async function runCommand(path, options, adapters = {}) {
230
376
  batchId,
231
377
  target: targetName,
232
378
  ...context,
233
- executionSnapshot: { ...snapshot, capturedAt: run.startedAt }
379
+ executionSnapshot: { ...snapshot, capturedAt: run.startedAt },
380
+ resultTrace
234
381
  }
235
382
  })
236
383
  );
384
+ if (group)
385
+ await appendTrialReceipt(group.groupId, {
386
+ kind: "attempt-started",
387
+ trace: redactor.json(resultTrace)
388
+ });
389
+ adapters.studio?.created();
237
390
  output(` ${plan.key} \xB7 ${run.id}`);
238
391
  },
239
392
  appendEvents: async (id, events) => {
@@ -255,29 +408,24 @@ async function runCommand(path, options, adapters = {}) {
255
408
  finishRun: async (id, result2) => {
256
409
  if (localStore) await removeWatchState(root, id);
257
410
  await store.finishRun(id, { ...result2, executionObservation: { ...engine.observation } });
258
- if (localStore) {
259
- try {
260
- reports.set(id, await generateReport(root, id));
261
- } catch {
262
- output(
263
- ` Report not generated for ${id}; run result saved. Use open-qa open ${id} to inspect the run directory.`
264
- );
265
- }
266
- const scan = await scanRunArtifacts(root, id, redactor);
267
- await store.recordArtifactScan(id, scan);
268
- scans.set(id, scan);
269
- if (scan.status !== "passed") {
270
- blocked.add(id);
271
- reports.delete(id);
272
- code = 2;
273
- output(
274
- ` secret-leak \xB7 ${id} \xB7 artifact sharing blocked; inspect artifactScan in run.json locally`
275
- );
276
- }
277
- }
411
+ if (group)
412
+ await appendTrialReceipt(group.groupId, {
413
+ kind: "attempt-finished",
414
+ attemptId: id,
415
+ at: await trialTime(result2.finishedAt),
416
+ verdict: result2.verdict,
417
+ ...result2.attemptAudit && { audit: attemptAuditSchema.parse(result2.attemptAudit) },
418
+ observation: { ...engine.observation },
419
+ ...result2.evidence && { evidence: result2.evidence },
420
+ ...result2.outcome && { outcome: result2.outcome },
421
+ ...result2.usage && { usage: result2.usage }
422
+ });
423
+ adapters.studio?.saved();
424
+ if (localStore) finished.push(id);
278
425
  }
279
426
  };
280
427
  const engine = createEngine({
428
+ runId: adapters.studio?.runId,
281
429
  batchId,
282
430
  heal: config.heal,
283
431
  replay: options.repeat !== void 0 ? "off" : options.replay,
@@ -287,7 +435,12 @@ async function runCommand(path, options, adapters = {}) {
287
435
  classifications: adapters.classifications ?? (localStore ? store : void 0),
288
436
  targetRevision: adapters.targetRevision ?? (target.revision ? async () => target.revision : void 0),
289
437
  flowRevision: flows[plans.indexOf(plan)].definitions.flow.sha256,
438
+ visualBaseline: { caseId, environment: targetName },
439
+ quarantine: config.quarantine,
440
+ quarantineCaseId: caseId,
441
+ quarantineTarget: targetName,
290
442
  ...adapters,
443
+ classificationScope,
291
444
  flowStatus,
292
445
  onStage: async (id, handle) => {
293
446
  await adapters.onStage?.(id, handle);
@@ -327,6 +480,7 @@ async function runCommand(path, options, adapters = {}) {
327
480
  stage: {
328
481
  ...Object.values(plan.views).some((view) => view.surface === "email") ? { email: requiredEmail(env) } : {},
329
482
  systems: systems.get(plan),
483
+ redactions: accessBinding?.secrets,
330
484
  headed: options.headed,
331
485
  ...Object.values(plan.views).some((view) => view.surface === "discord") ? { discord: { botToken: requiredDiscordToken(env) } } : {},
332
486
  page: {
@@ -335,13 +489,68 @@ async function runCommand(path, options, adapters = {}) {
335
489
  allowedHosts: target.allow,
336
490
  targetOrigin: new URL(target.url).origin,
337
491
  access,
338
- permissions: actorPermissions(plan)
492
+ accessHeaders: accessBinding?.accessHeaders,
493
+ permissions: actorPermissions(plan, providers)
339
494
  }
340
495
  }
341
496
  });
497
+ const finalizeArtifacts = async () => {
498
+ if (!localStore) return;
499
+ for (const id of finished) {
500
+ try {
501
+ reports.set(id, await generateReport(root, id, config.projectId));
502
+ } catch {
503
+ output(
504
+ ` Report not generated for ${id}; run result saved. Use open-qa open ${id} to inspect the run directory.`
505
+ );
506
+ }
507
+ let diagnostic;
508
+ try {
509
+ const scan = await scanRunArtifacts(root, id, redactor);
510
+ await store.recordArtifactScan(id, scan);
511
+ scans.set(id, scan);
512
+ if (scan.status === "passed") continue;
513
+ diagnostic = "inspect artifactScan in run.json locally";
514
+ } catch {
515
+ diagnostic = "could not complete and record the artifact scan";
516
+ }
517
+ blocked.add(id);
518
+ reports.delete(id);
519
+ code = 2;
520
+ output(` secret-leak \xB7 ${id} \xB7 artifact sharing blocked; ${diagnostic}`);
521
+ }
522
+ };
342
523
  let result;
343
524
  try {
344
- result = await engine.run(plan, signal);
525
+ result = await engine.run(plan, signal).then(
526
+ async (completed) => {
527
+ await recordTrial(completed);
528
+ if (group && index === group.planned) {
529
+ await appendTrialReceipt(group.groupId, {
530
+ kind: "group-finished",
531
+ at: await trialTime()
532
+ });
533
+ }
534
+ if (localStore && flowStatus) {
535
+ const [state] = completed.quarantined && flowStatus instanceof PgFlowStatus ? await flowStatus.list([plan.key]) : [];
536
+ const deadline = state?.quarantineDeadline;
537
+ await store.recordQuarantine(
538
+ completed.runId,
539
+ completed.quarantined,
540
+ deadline?.overdue ? deadline.expiresAt : void 0
541
+ );
542
+ }
543
+ await finalizeArtifacts();
544
+ return completed;
545
+ },
546
+ async (error) => {
547
+ try {
548
+ await finalizeArtifacts();
549
+ } catch {
550
+ }
551
+ throw error;
552
+ }
553
+ );
345
554
  } catch (error) {
346
555
  if (!(error instanceof FlowStatusWriteError)) throw error;
347
556
  const completed = error.result;
@@ -354,7 +563,8 @@ async function runCommand(path, options, adapters = {}) {
354
563
  repeatResult.runs.push({
355
564
  runId: completed.runId,
356
565
  verdict: completed.verdict,
357
- category: completed.category
566
+ category: completed.category,
567
+ ...completed.taxonomy && { taxonomy: completed.taxonomy }
358
568
  });
359
569
  repeatResult.finishedAt = Date.now();
360
570
  try {
@@ -371,7 +581,8 @@ async function runCommand(path, options, adapters = {}) {
371
581
  repeatResult.runs.push({
372
582
  runId: result.runId,
373
583
  verdict: result.verdict,
374
- category: result.category
584
+ category: result.category,
585
+ ...result.taxonomy && { taxonomy: result.taxonomy }
375
586
  });
376
587
  if (!result.quarantined && localStore && notificationChannel)
377
588
  for (const [id, notifications] of healEvents) {
@@ -396,7 +607,9 @@ async function runCommand(path, options, adapters = {}) {
396
607
  for (const run of result.runs) {
397
608
  const classification = (await store.getClassification(run.runId))?.classification;
398
609
  if (classification)
399
- output(` ${run.runId} \xB7 ${classification.category} \xB7 ${classification.reason}`);
610
+ output(
611
+ ` ${run.runId} \xB7 ${classification.category ?? "needs review"} \xB7 ${classification.reason}`
612
+ );
400
613
  }
401
614
  if (signal.aborted || result.verdict === "canceled") code = Math.max(code, 1);
402
615
  else if (!result.quarantined)
@@ -409,11 +622,35 @@ async function runCommand(path, options, adapters = {}) {
409
622
  }
410
623
  if (options.repeat !== void 0) {
411
624
  repeatResult.finishedAt = Date.now();
625
+ if (group) {
626
+ let history = await audit.get(group.groupId);
627
+ if (history && !history.receipts.some(({ kind }) => kind === "group-finished")) {
628
+ await appendTrialReceipt(group.groupId, {
629
+ kind: "group-finished",
630
+ at: await trialTime(repeatResult.finishedAt)
631
+ });
632
+ history = await audit.get(group.groupId);
633
+ }
634
+ if (history) printTrial(summarizeTrial(history), output);
635
+ if (database && flowStatus instanceof PgFlowStatus && quarantinedAtGroupStart) {
636
+ const decision = await flowStatus.autoRelease(group.flow, {
637
+ groupId: group.groupId,
638
+ generation: group.generation ?? -1,
639
+ caseId: group.caseId,
640
+ revision: group.caseRevision,
641
+ targetRevision: group.targetRevision,
642
+ policy: config.quarantine ?? quarantinePolicySchema.parse({})
643
+ });
644
+ output(
645
+ decision.ok ? ` ${group.flow} \xB7 quarantine released automatically` : ` ${group.flow} \xB7 automatic quarantine release denied \xB7 ${decision.reason}`
646
+ );
647
+ }
648
+ }
412
649
  await flowStatus?.saveRepeat(plans[0].key, repeatResult);
413
650
  printRepeat(repeatResult, output);
414
651
  if (!flowStatus)
415
652
  output(
416
- "Repeat result was not saved to QA PostgreSQL; configure QA_DATABASE_URL to show it during release"
653
+ "Repeat result was not saved to QA PostgreSQL; configure QA_DATABASE_URL to check for automatic quarantine release"
417
654
  );
418
655
  }
419
656
  output(`Batch usage: ${JSON.stringify(sumRunUsage(usage))}`);
@@ -0,0 +1,11 @@
1
+ export declare const setupReasons: {
2
+ readonly "unsupported-surface": "This flow uses an unsupported local view surface. Choose web, Telegram, Discord or email.";
3
+ readonly "access-credentials": "Configure the Cloudflare Access client ID and client secret in the project’s .env.local file.";
4
+ readonly "access-https": "Configure an HTTPS URL for this Cloudflare Access environment.";
5
+ readonly "review-changed": "The configuration or estimate changed. Review the flow again before starting.";
6
+ readonly configuration: "Check the flow, environment and systems configuration. Run open-qa doctor for details.";
7
+ };
8
+ export declare class RunSetupError extends Error {
9
+ readonly code: keyof typeof setupReasons;
10
+ constructor(code: keyof typeof setupReasons, detail: string, options?: ErrorOptions);
11
+ }
@@ -0,0 +1,18 @@
1
+ const setupReasons = {
2
+ "unsupported-surface": "This flow uses an unsupported local view surface. Choose web, Telegram, Discord or email.",
3
+ "access-credentials": "Configure the Cloudflare Access client ID and client secret in the project\u2019s .env.local file.",
4
+ "access-https": "Configure an HTTPS URL for this Cloudflare Access environment.",
5
+ "review-changed": "The configuration or estimate changed. Review the flow again before starting.",
6
+ configuration: "Check the flow, environment and systems configuration. Run open-qa doctor for details."
7
+ };
8
+ class RunSetupError extends Error {
9
+ constructor(code, detail, options) {
10
+ super(detail, options);
11
+ this.code = code;
12
+ }
13
+ code;
14
+ }
15
+ export {
16
+ RunSetupError,
17
+ setupReasons
18
+ };
package/src/server/app.js CHANGED
@@ -6,7 +6,8 @@ import { z } from "zod";
6
6
  import {
7
7
  replayCacheId,
8
8
  parseReplayCacheId,
9
- SecretRedactor
9
+ SecretRedactor,
10
+ ClassificationRegistryError
10
11
  } from "@open-qa/qa-engine";
11
12
  import {
12
13
  classificationPatchSchema,
@@ -67,13 +68,13 @@ function createQaServer(options) {
67
68
  })
68
69
  );
69
70
  app.onError((error, c) => {
71
+ const invalid = error instanceof z.ZodError || error instanceof SyntaxError || error instanceof InvalidRequest || error instanceof ClassificationRegistryError;
70
72
  logFailure(
71
- error instanceof ServerFailure ? error.category : error instanceof z.ZodError || error instanceof SyntaxError || error instanceof InvalidRequest ? "invalid-request" : error instanceof Conflict ? "conflict" : "repository",
73
+ error instanceof ServerFailure ? error.category : invalid ? "invalid-request" : error instanceof Conflict ? "conflict" : "repository",
72
74
  c.req.routePath,
73
75
  c.get("project")
74
76
  );
75
- if (error instanceof z.ZodError || error instanceof SyntaxError || error instanceof InvalidRequest)
76
- return c.json({ error: "Invalid request" }, 400);
77
+ if (invalid) return c.json({ error: "Invalid request" }, 400);
77
78
  if (error instanceof Conflict) return c.json({ error: "Conflicting request" }, 409);
78
79
  return c.json({ error: "QA service unavailable" }, 503);
79
80
  });
@@ -1,4 +1,5 @@
1
1
  import type { ScreenAccess } from "../screen-url.js";
2
+ import { type ClassificationRegistry } from "@open-qa/qa-engine";
2
3
  import { QaDatabase } from "../db/database.js";
3
4
  import type { EventObjects } from "../db/event-chunks.js";
4
5
  import { type AuthPolicy } from "./auth.js";
@@ -14,6 +15,7 @@ export declare function startQaServer(options: {
14
15
  auth: AuthPolicy;
15
16
  objects: EventObjects;
16
17
  secrets: CredentialSecrets;
18
+ classificationRegistry?: ClassificationRegistry;
17
19
  projects: Readonly<Record<string, {
18
20
  secretProject: string;
19
21
  }>>;
@@ -1,5 +1,8 @@
1
1
  import { serve } from "@hono/node-server";
2
- import { SecretRedactor } from "@open-qa/qa-engine";
2
+ import {
3
+ loadClassificationRegistry,
4
+ SecretRedactor
5
+ } from "@open-qa/qa-engine";
3
6
  import { PgClassificationStore } from "../adapters/pg-classification-store.js";
4
7
  import { PgReplayCache } from "../adapters/pg-replay-cache.js";
5
8
  import { DbLeasePool } from "../adapters/db-lease-pool.js";
@@ -34,10 +37,16 @@ function startQaServer(options) {
34
37
  new PgReplayCache(options.db, project, redactor)
35
38
  ])
36
39
  );
40
+ const registry = options.classificationRegistry ?? loadClassificationRegistry();
37
41
  const classifications = new Map(
38
42
  Object.keys(options.projects).map((project) => [
39
43
  project,
40
- new PgClassificationStore(options.db, project)
44
+ new PgClassificationStore(
45
+ options.db,
46
+ project,
47
+ void 0,
48
+ registry.findProject(project) ?? null
49
+ )
41
50
  ])
42
51
  );
43
52
  const credentials = new Map(