@open-qa/qa 0.1.0-alpha.4 → 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 (109) 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 +53 -7
  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/draft-api.d.ts +25 -421
  53. package/src/draft-api.js +10 -3
  54. package/src/engine.d.ts +47 -4
  55. package/src/engine.js +97 -8
  56. package/src/execution-snapshot.d.ts +1 -1
  57. package/src/execution-snapshot.js +22 -17
  58. package/src/export-command.d.ts +6 -0
  59. package/src/export-command.js +106 -0
  60. package/src/flow-check.js +1 -1
  61. package/src/flow-loader.d.ts +72 -6
  62. package/src/flow-loader.js +76 -12
  63. package/src/http-stage-client.d.ts +98 -1
  64. package/src/independent-model.js +53 -6
  65. package/src/judge-review-store.d.ts +13 -0
  66. package/src/judge-review-store.js +58 -0
  67. package/src/local-host-executor.d.ts +3 -1
  68. package/src/local-host-executor.js +2 -0
  69. package/src/quarantine-command.d.ts +5 -1
  70. package/src/quarantine-command.js +56 -13
  71. package/src/remote-command.js +2 -0
  72. package/src/report/browser.js +37 -37
  73. package/src/report/ctrf.d.ts +983 -0
  74. package/src/report/ctrf.js +306 -0
  75. package/src/report/generate.d.ts +1 -1
  76. package/src/report/generate.js +29 -6
  77. package/src/report/load.d.ts +738 -42
  78. package/src/report/load.js +78 -6
  79. package/src/result-notifier.js +1 -1
  80. package/src/result-trace.d.ts +62 -0
  81. package/src/result-trace.js +81 -0
  82. package/src/run-command.d.ts +2 -0
  83. package/src/run-command.js +285 -62
  84. package/src/run-setup-error.d.ts +1 -1
  85. package/src/run-setup-error.js +2 -2
  86. package/src/server/app.js +5 -4
  87. package/src/server/index.d.ts +2 -0
  88. package/src/server/index.js +11 -2
  89. package/src/server/repository.d.ts +166 -29
  90. package/src/server/repository.js +14 -2
  91. package/src/studio-review.js +1 -1
  92. package/src/system-config.d.ts +2 -2
  93. package/src/system-config.js +5 -4
  94. package/src/trial-audit.d.ts +630 -0
  95. package/src/trial-audit.js +272 -0
  96. package/src/visual-baseline.d.ts +4 -0
  97. package/src/visual-baseline.js +42 -0
  98. package/src/webhook-notification.d.ts +15 -0
  99. package/src/webhook-notification.js +61 -0
  100. package/src/worker/execution.d.ts +2 -1
  101. package/src/worker/execution.js +122 -3
  102. package/src/worker/index.d.ts +4 -0
  103. package/src/worker/index.js +10 -1
  104. package/src/worker/quarantine-notifications.js +2 -2
  105. package/src/worker/queue.d.ts +6 -2
  106. package/src/worker/queue.js +80 -19
  107. package/src/worker/result-notifications.d.ts +10 -2
  108. package/src/worker/result-notifications.js +120 -23
  109. package/src/worker/store.js +6 -3
@@ -2,11 +2,14 @@ import { createHash } from "node:crypto";
2
2
  import { lstat, readFile, readdir } from "node:fs/promises";
3
3
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
4
4
  import {
5
- flowSchema,
5
+ createFlowSchema,
6
+ flowAcceptance,
7
+ loadProviderRegistry,
6
8
  resolveFlowDefaults,
7
9
  qaConfigSchema,
8
10
  suiteSchema
9
11
  } from "@open-qa/qa-engine";
12
+ import { coversSchema } from "@open-qa/qa-engine/protocol";
10
13
  import { DEFAULT_PROGRAM_MINUTES, runProgram } from "./program-runner.js";
11
14
  import {
12
15
  parseTypeScriptSource,
@@ -24,12 +27,17 @@ async function rejectSymlinks(root, file) {
24
27
  throw new Error(`${file}:1:1 $: symlinks are not supported`);
25
28
  }
26
29
  }
27
- async function readSource(file, root) {
30
+ async function readSourceContent(file, root) {
28
31
  await rejectSymlinks(root, file);
29
- const content = await readFile(file, "utf8");
30
- const source = file.endsWith(".flow.ts") ? parseTypeScriptSource(file, content) : parseYamlSource(file, content);
32
+ return readFile(file, "utf8");
33
+ }
34
+ function parseSource(file, content) {
35
+ return file.endsWith(".flow.ts") ? parseTypeScriptSource(file, content) : parseYamlSource(file, content);
36
+ }
37
+ async function readSource(file, root) {
38
+ const content = await readSourceContent(file, root);
31
39
  return {
32
- ...source,
40
+ ...parseSource(file, content),
33
41
  content,
34
42
  revision: {
35
43
  source: relative(root, file),
@@ -77,14 +85,18 @@ function findQaRoot(file) {
77
85
  async function loadFlow(file, qaRoot = findQaRoot(file)) {
78
86
  return (await loadFlowDocument(file, qaRoot)).flow;
79
87
  }
80
- async function loadFlowDocument(file, qaRoot = findQaRoot(file)) {
88
+ async function loadFlowDocument(file, qaRoot = findQaRoot(file), registry) {
89
+ return loadDocument(file, qaRoot, registry, /* @__PURE__ */ new Map());
90
+ }
91
+ async function loadDocument(file, qaRoot, registry, inventories) {
81
92
  file = resolve(file);
82
93
  qaRoot = resolve(qaRoot);
83
94
  if (!inside(qaRoot, file)) throw new Error(`${file}:1:1 $: flow must be inside ${qaRoot}`);
84
95
  if (!/\.flow\.(yaml|ts)$/.test(file))
85
96
  throw new Error(`${file}:1:1 $: only *.flow.yaml and *.flow.ts are supported`);
86
97
  const configSource = await optionalSource(join(qaRoot, "config.yaml"), qaRoot);
87
- const config = configSource ? validate(qaConfigSchema, configSource) : {};
98
+ const providers = registry ?? await loadProviderRegistry();
99
+ const config = configSource ? validateConfig(configSource, providers) : {};
88
100
  let suiteSource;
89
101
  for (let directory = dirname(file); inside(qaRoot, directory); directory = dirname(directory)) {
90
102
  suiteSource = await optionalSource(join(directory, "_suite.yaml"), qaRoot);
@@ -92,7 +104,9 @@ async function loadFlowDocument(file, qaRoot = findQaRoot(file)) {
92
104
  }
93
105
  const suite = suiteSource ? validate(suiteSchema, suiteSource) : {};
94
106
  const flowSource = await readSource(file, qaRoot);
95
- const result = flowSchema.safeParse(resolveFlowDefaults(flowSource.value, config, suite));
107
+ const result = createFlowSchema(providers, suite.acceptance ?? []).safeParse(
108
+ resolveFlowDefaults(flowSource.value, config, suite)
109
+ );
96
110
  function diagnostic(issue, rule) {
97
111
  const path = issue.path.filter((key) => typeof key !== "symbol");
98
112
  const lookup = issue.keys?.length ? [...path, issue.keys[0]] : path;
@@ -117,6 +131,15 @@ async function loadFlowDocument(file, qaRoot = findQaRoot(file)) {
117
131
  if (!result.success)
118
132
  throw new Error(result.error.issues.map((issue) => diagnostic(issue)).join("\n"));
119
133
  const flow = result.data;
134
+ if (suiteSource && suite.acceptance) {
135
+ const { source, sha256 } = suiteSource.revision;
136
+ let flows = inventories.get(source);
137
+ if (!flows) {
138
+ flows = await coveringFlows(qaRoot, dirname(join(qaRoot, source)));
139
+ inventories.set(source, flows);
140
+ }
141
+ flow[flowAcceptance] = { source, revision: sha256, criteria: suite.acceptance, flows };
142
+ }
120
143
  if (flow.run) {
121
144
  flow.budget = { ...flow.budget, minutes: flow.budget?.minutes ?? DEFAULT_PROGRAM_MINUTES };
122
145
  const timeoutMs = flow.budget.minutes * 6e4;
@@ -124,6 +147,7 @@ async function loadFlowDocument(file, qaRoot = findQaRoot(file)) {
124
147
  }
125
148
  return {
126
149
  flow,
150
+ providers,
127
151
  ...flow.run ? { programSource: flowSource.content } : {},
128
152
  diagnostic,
129
153
  definitions: {
@@ -136,7 +160,7 @@ async function loadFlowDocument(file, qaRoot = findQaRoot(file)) {
136
160
  async function loadFlows(qaRoot, directory = qaRoot) {
137
161
  return (await loadFlowDocuments(qaRoot, directory)).map((document) => document.flow);
138
162
  }
139
- async function loadFlowDocuments(qaRoot, directory = qaRoot, onError) {
163
+ async function loadFlowDocuments(qaRoot, directory = qaRoot, onError, registry) {
140
164
  qaRoot = resolve(qaRoot);
141
165
  directory = resolve(directory);
142
166
  if (!inside(qaRoot, directory))
@@ -160,20 +184,37 @@ async function loadFlowDocuments(qaRoot, directory = qaRoot, onError) {
160
184
  const selected = readable.filter((file) => inside(directory, file));
161
185
  if (!selected.length && !files.some((file) => inside(directory, file)))
162
186
  throw new Error(`${directory}:1:1 $: no flows found (*.flow.yaml or *.flow.ts)`);
187
+ const providers = registry ?? await loadProviderRegistry();
163
188
  const flows = [];
189
+ const inventories = /* @__PURE__ */ new Map();
164
190
  for (const file of selected) {
165
191
  try {
166
- flows.push(await loadFlowDocument(file, qaRoot));
192
+ flows.push(await loadDocument(file, qaRoot, providers, inventories));
167
193
  } catch (error) {
168
194
  report(error);
169
195
  }
170
196
  }
171
197
  return flows;
172
198
  }
173
- async function loadConfig(qaRoot) {
199
+ function validateConfig(source, providers) {
200
+ const config = validate(qaConfigSchema, source);
201
+ for (const [name, target] of Object.entries(config.targets ?? {})) {
202
+ if (!target.access) continue;
203
+ try {
204
+ providers.resolve("access", target.access, name);
205
+ } catch (error) {
206
+ throw sourceError(source, {
207
+ path: ["targets", name, "access"],
208
+ message: error.message
209
+ });
210
+ }
211
+ }
212
+ return config;
213
+ }
214
+ async function loadConfig(qaRoot, providers) {
174
215
  qaRoot = resolve(qaRoot);
175
216
  const source = await optionalSource(join(qaRoot, "config.yaml"), qaRoot);
176
- return source ? validate(qaConfigSchema, source) : {};
217
+ return source ? validateConfig(source, providers ?? await loadProviderRegistry()) : {};
177
218
  }
178
219
  async function discoverFlowSources(qaRoot) {
179
220
  const files = [];
@@ -192,6 +233,29 @@ async function discoverFlowSources(qaRoot) {
192
233
  await walk(qaRoot);
193
234
  return { files: files.sort(), suites: suites.sort() };
194
235
  }
236
+ async function coveringFlows(qaRoot, directory) {
237
+ const { files, suites } = await discoverFlowSources(directory);
238
+ const nested = new Set(suites.map(dirname).filter((path) => path !== directory));
239
+ const flows = [];
240
+ for (const file of files) {
241
+ let current = dirname(file);
242
+ while (current !== directory && !nested.has(current)) current = dirname(current);
243
+ if (current !== directory) continue;
244
+ const content = await readSourceContent(file, qaRoot);
245
+ let value;
246
+ try {
247
+ value = parseSource(file, content).value;
248
+ } catch {
249
+ continue;
250
+ }
251
+ if (!value || typeof value !== "object" || !("key" in value) || typeof value.key !== "string")
252
+ continue;
253
+ const covers = coversSchema.safeParse("covers" in value ? value.covers : []);
254
+ if (covers.success && covers.data.length)
255
+ flows.push({ flow: value.key, covers: [...new Set(covers.data)] });
256
+ }
257
+ return flows;
258
+ }
195
259
  async function readFlowKeys(qaRoot, files, report = (error) => {
196
260
  throw error;
197
261
  }) {
@@ -220,15 +220,39 @@ export declare class HttpStageClient implements StageClient {
220
220
  type: "page";
221
221
  url: string;
222
222
  storageState?: Record<string, import("zod").JSONType> | undefined;
223
+ device?: {
224
+ browser?: "chromium" | undefined;
225
+ preset?: "desktop" | "mobile" | undefined;
226
+ viewport?: {
227
+ width: number;
228
+ height: number;
229
+ } | undefined;
230
+ userAgent?: string | undefined;
231
+ hasTouch?: boolean | undefined;
232
+ isMobile?: boolean | undefined;
233
+ locale?: string | undefined;
234
+ colorScheme?: "light" | "dark" | undefined;
235
+ deviceScaleFactor?: number | undefined;
236
+ } | undefined;
237
+ popup?: {
238
+ allowedOrigins: string[];
239
+ callbackOrigin?: string | undefined;
240
+ } | undefined;
223
241
  viewport?: {
224
242
  width: number;
225
243
  height: number;
226
244
  } | undefined;
245
+ } | {
246
+ actor: string;
247
+ view: string;
248
+ type: "provider";
249
+ surface: string;
250
+ url: string;
227
251
  } | {
228
252
  actor: string;
229
253
  view: string;
230
254
  type: "rendered";
231
- template: "chat" | "telegram" | "email";
255
+ template: "telegram" | "email" | "chat";
232
256
  email?: {
233
257
  address: string;
234
258
  } | undefined;
@@ -253,6 +277,23 @@ export declare class HttpStageClient implements StageClient {
253
277
  width: number;
254
278
  height: number;
255
279
  } | undefined;
280
+ browser?: string | undefined;
281
+ device?: string | undefined;
282
+ browserSettings?: {
283
+ viewport: {
284
+ width: number;
285
+ height: number;
286
+ };
287
+ version: string;
288
+ browser: "chromium";
289
+ preset: "desktop" | "mobile";
290
+ userAgent: string;
291
+ hasTouch: boolean;
292
+ isMobile: boolean;
293
+ locale: string;
294
+ colorScheme: "light" | "dark";
295
+ deviceScaleFactor: number;
296
+ } | undefined;
256
297
  }>;
257
298
  renderView: (request: {
258
299
  view: string;
@@ -313,6 +354,62 @@ export declare class HttpStageClient implements StageClient {
313
354
  };
314
355
  view?: string | undefined;
315
356
  step?: string | undefined;
357
+ visual?: {
358
+ key: {
359
+ caseId: string;
360
+ caseRevision: string;
361
+ check: string;
362
+ environment: string;
363
+ device: {
364
+ viewport: {
365
+ width: number;
366
+ height: number;
367
+ };
368
+ version: string;
369
+ browser: "chromium";
370
+ preset: "desktop" | "mobile";
371
+ userAgent: string;
372
+ hasTouch: boolean;
373
+ isMobile: boolean;
374
+ locale: string;
375
+ colorScheme: "light" | "dark";
376
+ deviceScaleFactor: number;
377
+ };
378
+ };
379
+ attemptId: string;
380
+ baseline?: {
381
+ manifest: {
382
+ schemaVersion: 1;
383
+ key: {
384
+ caseId: string;
385
+ caseRevision: string;
386
+ check: string;
387
+ environment: string;
388
+ device: {
389
+ viewport: {
390
+ width: number;
391
+ height: number;
392
+ };
393
+ version: string;
394
+ browser: "chromium";
395
+ preset: "desktop" | "mobile";
396
+ userAgent: string;
397
+ hasTouch: boolean;
398
+ isMobile: boolean;
399
+ locale: string;
400
+ colorScheme: "light" | "dark";
401
+ deviceScaleFactor: number;
402
+ };
403
+ };
404
+ version: number;
405
+ sha256: string;
406
+ updatedBy: string;
407
+ reason: string;
408
+ sourceAttempt: string;
409
+ };
410
+ png: string;
411
+ } | undefined;
412
+ } | undefined;
316
413
  }, signal?: AbortSignal) => Promise<{
317
414
  passed: boolean;
318
415
  evidence: Record<string, import("zod").JSONType>;
@@ -118,27 +118,53 @@ class IndependentModelCaller {
118
118
  }
119
119
  const body = await readBounded(response);
120
120
  const parsed = parseUniqueJson(body);
121
- const reported = z.object({
121
+ const responseFields = z.object({
122
+ model: z.string().max(200).optional(),
123
+ provider: z.string().max(200).optional(),
122
124
  usage: z.object({
123
125
  prompt_tokens: z.number().int().nonnegative(),
124
126
  completion_tokens: z.number().int().nonnegative(),
125
127
  prompt_tokens_details: z.object({ cached_tokens: z.number().int().nonnegative().optional() }).optional(),
126
128
  cost: z.number().finite().nonnegative().optional()
127
129
  }).optional()
128
- }).parse(parsed).usage;
130
+ }).parse(parsed);
131
+ const reported = responseFields.usage;
132
+ const headerCost = response.headers.get("x-litellm-response-cost");
133
+ const cost = headerCost === null ? reported?.cost : headerCost.trim() ? Number(headerCost) : void 0;
134
+ const known = cost !== void 0 && Number.isFinite(cost) && cost >= 0;
135
+ const deployment = response.headers.get("x-litellm-model-id");
136
+ const provider = responseFields.provider ?? response.headers.get("x-litellm-model-provider");
137
+ const model = {
138
+ provider: provider ? this.options.redactor.text(provider).slice(0, 200) : null,
139
+ model: responseFields.model ? this.options.redactor.text(responseFields.model).slice(0, 200) : null,
140
+ ...deployment && { deployment: this.options.redactor.text(deployment).slice(0, 200) },
141
+ // The gateway does not report the effective route's seed or seed capability.
142
+ seed: "unknown",
143
+ parameters: { gateway: "litellm", requestedModel: this.options.model, imageFallback },
144
+ billingVersion: known ? headerCost === null ? "litellm-usage-cost-v1" : "litellm-response-cost-v1" : null
145
+ };
129
146
  if (reported) {
130
- const headerCost = response.headers.get("x-litellm-response-cost");
131
- const cost = headerCost === null ? reported.cost : Number(headerCost);
132
147
  request.onUsage?.(
133
148
  usageSchema.parse({
149
+ billingMode: "metered",
134
150
  inputTokens: reported.prompt_tokens,
135
151
  outputTokens: reported.completion_tokens,
136
152
  ...reported.prompt_tokens_details?.cached_tokens !== void 0 && {
137
153
  cacheReadTokens: reported.prompt_tokens_details.cached_tokens
138
154
  },
139
- ...cost !== void 0 && Number.isFinite(cost) && cost >= 0 && { costUsd: cost }
155
+ ...known ? { costUsd: cost } : { costUnknown: true, costUnknownReason: "unpriced" },
156
+ model
140
157
  })
141
158
  );
159
+ } else {
160
+ request.onUsage?.({
161
+ inputTokens: 0,
162
+ outputTokens: 0,
163
+ billingMode: "metered",
164
+ ...known ? { costUsd: cost } : { costUnknown: true },
165
+ costUnknownReason: "usage-unavailable",
166
+ model
167
+ });
142
168
  }
143
169
  signal?.throwIfAborted();
144
170
  const result = completionSchema.parse(parsed);
@@ -165,6 +191,8 @@ ${JSON.stringify(request.responseSchema)}`,
165
191
  },
166
192
  signal
167
193
  );
194
+ let measured = false;
195
+ const billingMode = this.options.localAccess?.mode === "env" ? "metered" : "subscription";
168
196
  try {
169
197
  let text = "";
170
198
  let finished = false;
@@ -174,8 +202,18 @@ ${JSON.stringify(request.responseSchema)}`,
174
202
  imageFallback ? void 0 : request.images
175
203
  )) {
176
204
  if (event.kind === "usage") {
205
+ measured = true;
177
206
  const { kind: _kind, ...usage } = event;
178
- request.onUsage?.(usage);
207
+ request.onUsage?.({
208
+ ...usage,
209
+ billingMode,
210
+ model: usage.model ?? session.model ?? {
211
+ provider: null,
212
+ model: null,
213
+ seed: "unknown",
214
+ billingVersion: null
215
+ }
216
+ });
179
217
  }
180
218
  signal?.throwIfAborted();
181
219
  if (finished || event.kind === "tool_call")
@@ -201,6 +239,15 @@ ${JSON.stringify(request.responseSchema)}`,
201
239
  if (!(error instanceof UnsupportedImages)) throw error;
202
240
  signal?.throwIfAborted();
203
241
  } finally {
242
+ if (!measured)
243
+ request.onUsage?.({
244
+ inputTokens: 0,
245
+ outputTokens: 0,
246
+ billingMode,
247
+ costUnknown: true,
248
+ costUnknownReason: "usage-unavailable",
249
+ model: session.model
250
+ });
204
251
  await session.close();
205
252
  }
206
253
  }
@@ -0,0 +1,13 @@
1
+ import { type JudgeReview } from "./attempt-audit.js";
2
+ import { type QaDatabase } from "./db/database.js";
3
+ export declare function recordJudgeReview(root: string, db: QaDatabase | undefined, project: string, attempt: string, decision: JudgeReview): Promise<void>;
4
+ export declare function readJudgeReviews(root: string, db: QaDatabase | undefined, project: string, attempt: string): Promise<{
5
+ schemaVersion: 1;
6
+ eventSeq: number;
7
+ actor: string;
8
+ at: number;
9
+ reason: string;
10
+ verdict: "passed" | "failed" | "inconclusive";
11
+ dbUser?: string | undefined;
12
+ host?: string | undefined;
13
+ }[]>;
@@ -0,0 +1,58 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readdir } from "node:fs/promises";
3
+ import { hostname } from "node:os";
4
+ import { join } from "node:path";
5
+ import { appendAuditFile, readAuditFile } from "./adapters/file-trial-audit.js";
6
+ import { assertDirectory, ensureDirectory, hasCode } from "./adapters/local-files.js";
7
+ import { judgeReviewSchema } from "./attempt-audit.js";
8
+ import { assertPostgresText, postgresAuditContext } from "./db/database.js";
9
+ import { publicId } from "./public-id.js";
10
+ function reviewDirectory(root, project, attempt) {
11
+ return join(root, "judge-reviews", publicId.parse(project), publicId.parse(attempt));
12
+ }
13
+ async function recordJudgeReview(root, db, project, attempt, decision) {
14
+ const review = judgeReviewSchema.parse(decision);
15
+ const key = `judge:${randomUUID()}`;
16
+ if (db) {
17
+ await db.transaction(async (client) => {
18
+ const receipt = { ...review, ...await postgresAuditContext(client) };
19
+ assertPostgresText(receipt);
20
+ await client.query(
21
+ "INSERT INTO qa.audit_decisions(project_id,subject,key,document) VALUES($1,$2,$3,$4)",
22
+ [publicId.parse(project), `attempt:${publicId.parse(attempt)}`, key, receipt]
23
+ );
24
+ });
25
+ } else {
26
+ const directory = reviewDirectory(root, project, attempt);
27
+ await ensureDirectory(directory);
28
+ await appendAuditFile(join(directory, key.replace(":", "-") + ".json"), {
29
+ ...review,
30
+ host: hostname()
31
+ });
32
+ }
33
+ }
34
+ async function readJudgeReviews(root, db, project, attempt) {
35
+ if (db) {
36
+ const { rows } = await db.pool.query(
37
+ "SELECT document FROM qa.audit_decisions WHERE project_id=$1 AND subject=$2 AND key LIKE 'judge:%' ORDER BY (document->>'at')::double precision,key",
38
+ [publicId.parse(project), `attempt:${publicId.parse(attempt)}`]
39
+ );
40
+ return rows.map(({ document }) => judgeReviewSchema.parse(document));
41
+ }
42
+ const directory = reviewDirectory(root, project, attempt);
43
+ try {
44
+ await assertDirectory(directory);
45
+ const files = (await readdir(directory)).filter((file) => /^judge-[a-f0-9-]{36}\.json$/.test(file)).sort();
46
+ const reviews = await Promise.all(
47
+ files.map(async (file) => judgeReviewSchema.parse(await readAuditFile(join(directory, file))))
48
+ );
49
+ return reviews.sort((a, b) => a.at - b.at);
50
+ } catch (error) {
51
+ if (hasCode(error, "ENOENT")) return [];
52
+ throw error;
53
+ }
54
+ }
55
+ export {
56
+ readJudgeReviews,
57
+ recordJudgeReview
58
+ };
@@ -1,6 +1,7 @@
1
1
  import type { GmailCredentials } from "./vendor/gmail.js";
2
2
  import type { Executor, ProvisionSpec, StageHandle } from "@open-qa/qa-engine";
3
- import type { SystemConfig } from "@open-qa/qa-engine/protocol";
3
+ import type { z } from "zod";
4
+ import type { accessHeadersSchema, SystemConfig } from "@open-qa/qa-engine/protocol";
4
5
  export interface LocalHostExecutorOptions {
5
6
  redactions?: readonly string[];
6
7
  systems?: SystemConfig;
@@ -19,6 +20,7 @@ export interface LocalHostExecutorOptions {
19
20
  clientId: string;
20
21
  clientSecret: string;
21
22
  };
23
+ accessHeaders?: z.infer<typeof accessHeadersSchema>;
22
24
  permissions: Record<string, string[]>;
23
25
  };
24
26
  startupTimeoutMs?: number;
@@ -49,9 +49,11 @@ class LocalHostExecutor {
49
49
  cwd: directory,
50
50
  env: {
51
51
  ...stageEnvironment(),
52
+ OPEN_QA_PROVIDER_MODULES: process.env.OPEN_QA_STAGE_PROVIDER_MODULES ?? process.env.OPEN_QA_PROVIDER_MODULES,
52
53
  QA_STAGE_CONFIG: JSON.stringify({
53
54
  host: "127.0.0.1",
54
55
  port: 0,
56
+ providers: spec.providers,
55
57
  dir: directory,
56
58
  conductorToken,
57
59
  actorTokens,
@@ -1,8 +1,12 @@
1
- import type { FlowStatusStore, RepeatResult } from "@open-qa/qa-engine";
1
+ import { type FlowStatusStore, type RepeatResult } from "@open-qa/qa-engine";
2
2
  export declare function printRepeat(result: RepeatResult | null, output: (line: string) => void): void;
3
3
  export declare function quarantineCommand(action: "list" | "release", flow: string | undefined, options?: {
4
4
  project?: string;
5
5
  root?: string;
6
+ generation?: string;
7
+ reason?: string;
8
+ group?: string;
9
+ flow?: string;
6
10
  }, adapters?: {
7
11
  store?: FlowStatusStore;
8
12
  output?: (line: string) => void;
@@ -1,10 +1,17 @@
1
1
  import { resolve } from "node:path";
2
+ import { userInfo } from "node:os";
3
+ import {
4
+ quarantinePolicySchema,
5
+ SecretRedactor
6
+ } from "@open-qa/qa-engine";
2
7
  import { QaDatabase, publicId } from "./db/database.js";
3
8
  import { PgFlowStatus } from "./db/flow-status.js";
4
- import { loadConfig } from "./flow-loader.js";
9
+ import { loadConfig, loadFlowDocuments } from "./flow-loader.js";
10
+ import { resultCaseId } from "./result-trace.js";
11
+ import { PgTrialAudit } from "./db/trial-audit.js";
5
12
  function printRepeat(result, output) {
6
13
  if (!result) {
7
- output("No saved repeat result. Run --repeat before releasing this flow.");
14
+ output("No saved repeat result. Run --repeat to check whether the flow can be released.");
8
15
  return;
9
16
  }
10
17
  const canceled = result.runs.filter((run) => run.verdict === "canceled").length;
@@ -21,8 +28,10 @@ async function quarantineCommand(action, flow, options = {}, adapters = {}) {
21
28
  let database;
22
29
  try {
23
30
  let store = adapters.store;
31
+ const root = resolve(options.root ?? ".qa");
32
+ const config = !store ? await loadConfig(root) : void 0;
33
+ const project = options.project ?? process.env.QA_PROJECT_ID ?? config?.projectId;
24
34
  if (!store) {
25
- const project = options.project ?? process.env.QA_PROJECT_ID ?? (await loadConfig(resolve(options.root ?? ".qa"))).projectId;
26
35
  if (!publicId.safeParse(project).success)
27
36
  throw new Error("Quarantine requires a valid QA project ID");
28
37
  if (!process.env.QA_DATABASE_URL) throw new Error("Quarantine requires QA_DATABASE_URL");
@@ -30,28 +39,62 @@ async function quarantineCommand(action, flow, options = {}, adapters = {}) {
30
39
  store = new PgFlowStatus(database, project);
31
40
  }
32
41
  if (action === "list") {
42
+ if (options.flow !== void 0) {
43
+ if (!(store instanceof PgFlowStatus)) {
44
+ output("Quarantine audit history requires PostgreSQL");
45
+ return 1;
46
+ }
47
+ const [row2] = await store.list([options.flow]);
48
+ if (row2?.quarantineDeadline?.overdue)
49
+ output(
50
+ JSON.stringify({
51
+ action: "quarantine-status",
52
+ flow: row2.flow,
53
+ generation: row2.generation,
54
+ ...row2.quarantineDeadline
55
+ })
56
+ );
57
+ for (const decision2 of await store.quarantineHistory(options.flow))
58
+ output(JSON.stringify(decision2));
59
+ return 0;
60
+ }
33
61
  const rows = await store.list();
34
62
  if (!rows.length) output("No quarantined flows");
35
63
  for (const row2 of rows) {
36
64
  output(
37
- `${row2.flow} \xB7 quarantined \xB7 flaky streak ${row2.flakyStreak} \xB7 owner ${row2.owner ?? "unassigned"}`
65
+ `${row2.flow} \xB7 quarantined${row2.quarantineDeadline?.overdue ? " \xB7 overdue" : ""} \xB7 generation ${row2.generation ?? "unknown"} \xB7 flaky streak ${row2.flakyStreak} \xB7 owner ${row2.owner ?? "unassigned"}`
38
66
  );
39
67
  printRepeat(row2.latestRepeat, output);
68
+ if (store instanceof PgFlowStatus)
69
+ for (const decision2 of await store.quarantineHistory(row2.flow))
70
+ output(JSON.stringify(decision2));
40
71
  }
41
72
  return 0;
42
73
  }
43
74
  if (!flow) throw new Error("quarantine release requires a flow");
44
- const current = await store.get(flow);
45
- if (current?.status === "active") {
46
- output(`${current.flow} \xB7 already active \xB7 flaky streak unchanged (${current.flakyStreak})`);
47
- printRepeat(current.latestRepeat, output);
48
- return 0;
49
- }
50
- const row = await store.release(flow);
51
- if (!row) {
52
- output("Flow has no recorded quarantine state");
75
+ if (!store.release) throw new Error("Quarantine release is unavailable");
76
+ const groupId = options.group ?? "";
77
+ const history = database && groupId && await new PgTrialAudit(database, project).get(groupId);
78
+ const targets = config?.targets;
79
+ const target = history && targets && Object.hasOwn(targets, history.group.target) ? targets[history.group.target] : void 0;
80
+ const document = config && (await loadFlowDocuments(root, root, () => {
81
+ })).find((item) => item.flow.key === flow);
82
+ const generation = Number(options.generation?.trim() || NaN);
83
+ const decision = await store.release(flow, {
84
+ generation: Number.isSafeInteger(generation) && generation >= 0 ? generation : -1,
85
+ groupId,
86
+ actor: userInfo().username,
87
+ reason: new SecretRedactor().text(options.reason ?? ""),
88
+ policy: config?.quarantine ?? quarantinePolicySchema.parse({}),
89
+ caseId: document && project && target ? resultCaseId(project, document.flow.traceability?.caseId ?? flow) : void 0,
90
+ revision: document?.definitions.flow.sha256,
91
+ targetRevision: target?.revision ?? null
92
+ });
93
+ if (!decision.ok) {
94
+ output(`Quarantine release denied \xB7 ${decision.reason}`);
53
95
  return 1;
54
96
  }
97
+ const row = decision.status;
55
98
  output(`${row.flow} \xB7 active \xB7 flaky streak reset`);
56
99
  printRepeat(row.latestRepeat, output);
57
100
  return 0;
@@ -11,6 +11,7 @@ import {
11
11
  credentialDtoSchema,
12
12
  submitBatchSchema
13
13
  } from "@open-qa/qa-engine/protocol";
14
+ import { readRunContext } from "./result-trace.js";
14
15
  class QaRemoteError extends Error {
15
16
  constructor(status) {
16
17
  super(`QA server rejected request (${status})`);
@@ -80,6 +81,7 @@ async function remoteRunCommand(flow, options, deps = {}) {
80
81
  throw new Error("Remote model access must be personal or team");
81
82
  const request = submitBatchSchema.parse({
82
83
  flows: [flow],
84
+ runContext: await readRunContext(options.runContext),
83
85
  target: options.target ?? "local",
84
86
  runtime: options.runtime ?? "claude-code",
85
87
  modelAccess: options.modelAccess === "team" ? "team" : "personal",