@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
@@ -0,0 +1,207 @@
1
+ import { fork } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { mkdtemp, link, open, realpath, rm, unlink, writeFile } from "node:fs/promises";
5
+ import { createServer } from "node:http";
6
+ import { tmpdir } from "node:os";
7
+ import { join, resolve } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { z } from "zod";
10
+ import { setupReasons } from "./run-setup-error.js";
11
+ import { reviewFlow, StudioError } from "./studio-review.js";
12
+ const runId = z.string().regex(/^run_[\da-f-]{36}$/);
13
+ const command = z.discriminatedUnion("action", [
14
+ z.strictObject({
15
+ action: z.literal("review"),
16
+ project: z.string(),
17
+ flowId: z.string().regex(/^[a-f0-9]{64}$/),
18
+ source: z.string().max(1024),
19
+ target: z.string().min(1).max(128)
20
+ }),
21
+ z.strictObject({
22
+ action: z.literal("start"),
23
+ ticket: z.uuid(),
24
+ key: z.uuid(),
25
+ accepted: z.boolean()
26
+ }),
27
+ z.strictObject({ action: z.enum(["stop", "status"]), runId })
28
+ ]);
29
+ async function lockOwner(lock) {
30
+ const handle = await open(lock, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
31
+ try {
32
+ const bytes = Buffer.alloc(64);
33
+ if (!(await handle.stat()).isFile()) return;
34
+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
35
+ const active = runId.safeParse(bytes.toString("utf8", 0, bytesRead));
36
+ return active.success ? active.data : void 0;
37
+ } finally {
38
+ await handle.close();
39
+ }
40
+ }
41
+ async function acquireStudioLock(root, id) {
42
+ const lock = join(root, ".studio-run.lock"), staging = lock + "." + randomUUID();
43
+ await writeFile(staging, id, { mode: 384, flag: "wx" });
44
+ try {
45
+ try {
46
+ await link(staging, lock);
47
+ } catch (error) {
48
+ if (error.code !== "EEXIST") throw error;
49
+ throw new StudioError(
50
+ `Another run holds the project lock at ${lock}. Check its worker and resource leases before manually clearing a stale lock.`,
51
+ 409,
52
+ await lockOwner(lock)
53
+ );
54
+ }
55
+ } finally {
56
+ await unlink(staging);
57
+ }
58
+ return async () => {
59
+ try {
60
+ if (await lockOwner(lock) === id) await unlink(lock);
61
+ } catch (error) {
62
+ if (error.code !== "ENOENT") throw error;
63
+ }
64
+ };
65
+ }
66
+ async function listenStudio(directory) {
67
+ const root = await realpath(directory), temp = await mkdtemp(join(tmpdir(), "open-qa-"));
68
+ const path = join(temp, "control.sock"), tickets = /* @__PURE__ */ new Map();
69
+ const runs = /* @__PURE__ */ new Map();
70
+ let active;
71
+ let closing = false;
72
+ async function start(t, accepted) {
73
+ const r = t.request;
74
+ const current = await reviewFlow(root, r.project, r.source, r.flowId, r.target);
75
+ if (JSON.stringify(current) !== JSON.stringify(t.review))
76
+ throw new StudioError("Configuration changed; review again.");
77
+ if (current.prompt && !accepted)
78
+ throw new StudioError("Confirm this cost estimate to continue.", 400);
79
+ const id = "run_" + randomUUID();
80
+ const release = await acquireStudioLock(root, id);
81
+ try {
82
+ if (closing) throw new StudioError("Launcher is closing.");
83
+ const worker = fork(fileURLToPath(new URL("./studio-worker.js", import.meta.url)), [], {
84
+ execArgv: ["--import", import.meta.resolve("tsx")],
85
+ stdio: ["ignore", "ignore", "ignore", "ipc"]
86
+ });
87
+ const result = { runId: id, state: "starting" };
88
+ if (runs.size >= 128) runs.delete(runs.keys().next().value);
89
+ runs.set(id, result);
90
+ let timer;
91
+ const stop = () => {
92
+ if (result.state === "stopping") return;
93
+ result.state = "stopping";
94
+ if (worker.connected) worker.send("stop", () => {
95
+ });
96
+ timer = setTimeout(() => worker.kill("SIGKILL"), 15e3);
97
+ };
98
+ let saved = false;
99
+ worker.on("message", (m) => {
100
+ if (typeof m === "string" && Object.hasOwn(setupReasons, m))
101
+ result.reason = setupReasons[m];
102
+ if (m === "saved") saved = true;
103
+ if (m === "running" && result.state === "starting") result.state = "running";
104
+ });
105
+ const done = new Promise((resolveDone) => {
106
+ worker.once("error", () => {
107
+ result.state = "failed";
108
+ result.reason = "Studio could not launch the local worker. Restart Studio and try again.";
109
+ });
110
+ worker.once("close", async (_code, signal) => {
111
+ clearTimeout(timer);
112
+ result.state = signal ? "interrupted" : saved ? "finished" : "failed";
113
+ if (!signal)
114
+ await release().catch(() => {
115
+ result.state = "interrupted";
116
+ });
117
+ if (active?.runId === id) active = void 0;
118
+ resolveDone();
119
+ });
120
+ });
121
+ active = { runId: id, stop, done };
122
+ worker.send(
123
+ { root, path: resolve(root, r.source), runId: id, review: current, accepted },
124
+ (error) => {
125
+ if (error) stop();
126
+ }
127
+ );
128
+ return result;
129
+ } catch (error) {
130
+ await release();
131
+ throw error;
132
+ }
133
+ }
134
+ const server = createServer(async (req, res) => {
135
+ const reply = (status, value) => {
136
+ res.writeHead(status, { "Content-Type": "application/json" });
137
+ res.end(JSON.stringify(value));
138
+ };
139
+ try {
140
+ if (closing || req.method !== "POST" || req.url !== "/")
141
+ throw new StudioError("Unavailable.", 403);
142
+ const chunks = [];
143
+ let size = 0;
144
+ for await (const chunk of req) {
145
+ size += chunk.length;
146
+ if (size > 4096) throw new StudioError("Request too large.", 413);
147
+ chunks.push(chunk);
148
+ }
149
+ const parsed = command.safeParse(JSON.parse(Buffer.concat(chunks).toString()));
150
+ if (!parsed.success) throw new StudioError("Invalid request.", 400);
151
+ const input = parsed.data;
152
+ if (input.action === "review") {
153
+ const review = await reviewFlow(
154
+ root,
155
+ input.project,
156
+ input.source,
157
+ input.flowId,
158
+ input.target
159
+ );
160
+ for (const [k, t] of tickets) if (t.expires <= Date.now()) tickets.delete(k);
161
+ if (tickets.size >= 128)
162
+ throw new StudioError("Too many recent reviews. Try again later.", 429);
163
+ const ticket = randomUUID();
164
+ tickets.set(ticket, { request: input, review, expires: Date.now() + 10 * 6e4 });
165
+ return reply(200, { ticket, ...review });
166
+ }
167
+ if (input.action === "start") {
168
+ const t = tickets.get(input.ticket);
169
+ if (!t || t.expires <= Date.now()) throw new StudioError("Review expired; review again.");
170
+ if (t.start && t.start.key !== input.key)
171
+ throw new StudioError("This review has already been used.");
172
+ t.start ??= { key: input.key, result: start(t, input.accepted) };
173
+ return reply(200, await t.start.result);
174
+ }
175
+ const result = runs.get(input.runId);
176
+ if (!result) throw new StudioError("This launcher does not own the run.", 404);
177
+ if (input.action === "stop" && active?.runId === input.runId) active.stop();
178
+ reply(200, result);
179
+ } catch (error) {
180
+ if (error instanceof StudioError)
181
+ reply(error.status, { error: error.message, runId: error.runId });
182
+ else
183
+ reply(400, {
184
+ error: "Unable to read or start this flow. Review the project configuration."
185
+ });
186
+ }
187
+ });
188
+ server.requestTimeout = 1e4;
189
+ await new Promise((res, rej) => {
190
+ server.once("error", rej);
191
+ server.listen(path, res);
192
+ });
193
+ return {
194
+ path,
195
+ async close() {
196
+ closing = true;
197
+ const closed = new Promise((res) => server.close(() => res()));
198
+ active?.stop();
199
+ await Promise.all([closed, active?.done]);
200
+ await rm(temp, { force: true, recursive: true });
201
+ }
202
+ };
203
+ }
204
+ export {
205
+ acquireStudioLock,
206
+ listenStudio
207
+ };
@@ -0,0 +1,24 @@
1
+ import { loadConfig, type LoadedFlow } from "./flow-loader.js";
2
+ export declare class StudioError extends Error {
3
+ status: number;
4
+ runId?: string;
5
+ constructor(message: string, status?: number, runId?: string);
6
+ }
7
+ export declare function studioRevision(config: Awaited<ReturnType<typeof loadConfig>>, doc: LoadedFlow): string;
8
+ export declare function reviewFlow(root: string, project: string, source: string, id: string, name: string): Promise<{
9
+ revision: string;
10
+ estimate: string[];
11
+ prompt: string;
12
+ flow: string;
13
+ target: string;
14
+ url: string;
15
+ budget: {
16
+ actions?: number | undefined;
17
+ minutes?: number | undefined;
18
+ usd?: number | undefined;
19
+ } | null;
20
+ recording: "rrweb"[];
21
+ policy: "never" | "safe";
22
+ runtime: string;
23
+ }>;
24
+ export type Review = Awaited<ReturnType<typeof reviewFlow>>;
@@ -0,0 +1,64 @@
1
+ import { createHash } from "node:crypto";
2
+ import { resolve } from "node:path";
3
+ import { compile, isProtectedTarget, targetAllowsUrl } from "@open-qa/qa-engine";
4
+ import { loadConfig, loadFlowDocument } from "./flow-loader.js";
5
+ import { confirmRunEstimate } from "./budget-confirmation.js";
6
+ import { FileRunStore } from "./adapters/file-run-store.js";
7
+ class StudioError extends Error {
8
+ status;
9
+ runId;
10
+ constructor(message, status = 409, runId) {
11
+ super(message);
12
+ this.status = status;
13
+ this.runId = runId;
14
+ }
15
+ }
16
+ function studioRevision(config, doc) {
17
+ return createHash("sha256").update(JSON.stringify([config, doc.definitions])).digest("hex");
18
+ }
19
+ async function reviewFlow(root, project, source, id, name) {
20
+ const config = await loadConfig(root);
21
+ const target = config.targets && Object.hasOwn(config.targets, name) && config.targets[name];
22
+ if (!target || config.projectId !== project || !targetAllowsUrl(target, target.url))
23
+ throw new StudioError("This test environment is unavailable.", 400);
24
+ if (isProtectedTarget(name, target))
25
+ throw new StudioError("Protected environments require the CLI.", 403);
26
+ const doc = await loadFlowDocument(resolve(root, source), root);
27
+ if (createHash("sha256").update(doc.flow.key).digest("hex") !== id)
28
+ throw new StudioError("Configuration changed; review again.");
29
+ const plan = compile(doc.flow, void 0, { providers: doc.providers });
30
+ const estimate = [];
31
+ let prompt = "";
32
+ const store = new FileRunStore(root);
33
+ await confirmRunEstimate({
34
+ flows: [plan.key],
35
+ recentUsage: store.recentUsage.bind(store),
36
+ thresholds: config.confirmAbove,
37
+ subscription: true,
38
+ attempts: 1,
39
+ interactive: true,
40
+ output: (line) => estimate.push(line),
41
+ confirm: async (message) => {
42
+ prompt = message;
43
+ return true;
44
+ }
45
+ });
46
+ const url = new URL(target.url);
47
+ return {
48
+ revision: studioRevision(config, doc),
49
+ estimate,
50
+ prompt,
51
+ flow: plan.key,
52
+ target: name,
53
+ url: url.origin + url.pathname,
54
+ budget: plan.budget ?? null,
55
+ recording: plan.record,
56
+ policy: plan.prod,
57
+ runtime: "Claude Code with subscription login on the local host (one attempt)"
58
+ };
59
+ }
60
+ export {
61
+ StudioError,
62
+ reviewFlow,
63
+ studioRevision
64
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,48 @@
1
+ import { RunSetupError } from "./run-setup-error.js";
2
+ import { runCommand } from "./run-command.js";
3
+ import { studioRevision } from "./studio-review.js";
4
+ const controller = new AbortController();
5
+ const cancel = () => controller.abort(new Error("Studio canceled this run"));
6
+ process.once("disconnect", cancel);
7
+ process.once("message", async (start) => {
8
+ process.on("message", (message) => {
9
+ if (message === "stop") cancel();
10
+ });
11
+ let estimate = "";
12
+ let created = false;
13
+ try {
14
+ process.exitCode = await runCommand(
15
+ start.path,
16
+ { root: start.root, target: start.review.target, retries: 0 },
17
+ {
18
+ signal: controller.signal,
19
+ interactive: true,
20
+ output: (line) => {
21
+ if (line.startsWith("Estimate ")) estimate = line;
22
+ },
23
+ confirm: async (message) => {
24
+ if (!start.accepted || message !== start.review.prompt || estimate !== start.review.estimate[0])
25
+ throw new RunSetupError("review-changed", "Review changed");
26
+ return true;
27
+ },
28
+ studio: {
29
+ runId: start.runId,
30
+ verify: (config, doc) => {
31
+ if (studioRevision(config, doc) !== start.review.revision)
32
+ throw new RunSetupError("review-changed", "Review changed");
33
+ },
34
+ created: () => {
35
+ created = true;
36
+ process.send?.("running");
37
+ },
38
+ saved: () => process.send?.("saved")
39
+ }
40
+ }
41
+ );
42
+ } catch (error) {
43
+ if (!created) process.send?.(error instanceof RunSetupError ? error.code : "configuration");
44
+ process.exitCode = 2;
45
+ } finally {
46
+ if (process.connected) process.disconnect();
47
+ }
48
+ });
@@ -1,7 +1,7 @@
1
- import type { ExecutionPlan, QaConfig } from "@open-qa/qa-engine";
1
+ import { ProviderRegistry, type ExecutionPlan, type QaConfig } from "@open-qa/qa-engine";
2
2
  import { type SystemConfig } from "@open-qa/qa-engine/protocol";
3
3
  type Settings = NonNullable<QaConfig["targets"]>[string]["systems"];
4
4
  export declare function systemSecretValues(systems?: SystemConfig): string[];
5
5
  export declare function resolveSystems(target: SystemConfig["target"], settings: Settings, env: NodeJS.ProcessEnv, plan?: ExecutionPlan): SystemConfig | undefined;
6
- export declare function actorPermissions(plan: ExecutionPlan): Record<string, string[]>;
6
+ export declare function actorPermissions(plan: ExecutionPlan, providers?: ProviderRegistry<unknown>): Record<string, string[]>;
7
7
  export {};
@@ -1,10 +1,10 @@
1
+ import { ProviderRegistry } from "@open-qa/qa-engine";
1
2
  import {
2
3
  discordToolNames,
3
4
  emailToolNames,
4
5
  pageToolNames,
5
6
  telegramToolNames,
6
- systemConfigSchema,
7
- systemToolNames
7
+ systemConfigSchema
8
8
  } from "@open-qa/qa-engine/protocol";
9
9
  function systemSecretValues(systems) {
10
10
  return [
@@ -49,7 +49,7 @@ function resolveSystems(target, settings, env, plan) {
49
49
  );
50
50
  }
51
51
  }
52
- function actorPermissions(plan) {
52
+ function actorPermissions(plan, providers = new ProviderRegistry()) {
53
53
  return Object.fromEntries(
54
54
  plan.lanes.map((lane) => [
55
55
  lane.actor,
@@ -58,7 +58,8 @@ function actorPermissions(plan) {
58
58
  ...lane.views.some((view) => plan.views[view]?.surface === "telegram") ? telegramToolNames : [],
59
59
  ...lane.views.some((view) => plan.views[view].surface === "discord") ? discordToolNames : [],
60
60
  ...lane.views.some((view) => plan.views[view].surface === "email") ? emailToolNames : [],
61
- ...(lane.spec.tools ?? []).map((tool) => systemToolNames[tool])
61
+ ...(lane.spec.tools ?? []).flatMap((tool) => providers.commandsFor("tool", tool)),
62
+ ...lane.views.flatMap((view) => providers.commandsFor("surface", plan.views[view].surface))
62
63
  ]
63
64
  ])
64
65
  );