@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,10 +1,14 @@
1
+ import { classifierAuditUpdate } from "../attempt-audit.js";
1
2
  import { open, readdir } from "node:fs/promises";
2
3
  import { join, resolve } from "node:path";
3
4
  import { z } from "zod";
4
5
  import { artifactScanSchema } from "../artifact-scan.js";
5
6
  import {
6
7
  withExecutionObservation,
7
- readExecutionSnapshot
8
+ withExecutionBrowserViews,
9
+ ClassificationRegistryError,
10
+ readExecutionSnapshot,
11
+ loadClassificationRegistry
8
12
  } from "@open-qa/qa-engine";
9
13
  import {
10
14
  classificationRecordSchema,
@@ -15,7 +19,8 @@ import {
15
19
  millisecondsSchema,
16
20
  runEventSchema,
17
21
  verdictSchema,
18
- runUsageSchema
22
+ runUsageSchema,
23
+ withResultDetails
19
24
  } from "@open-qa/qa-engine/protocol";
20
25
  import {
21
26
  assertRegularFile,
@@ -28,6 +33,8 @@ import {
28
33
  runDirectory,
29
34
  withRunLock
30
35
  } from "./local-files.js";
36
+ import { assertNewRunMetadata } from "./run-metadata.js";
37
+ import { classificationCorrection, validateClassificationWrite } from "./classification-write.js";
31
38
  const runSchema = z.strictObject({
32
39
  classification: classificationSchema.nullable().default(null),
33
40
  classificationLabels: z.array(classificationLabelSchema).default([]),
@@ -53,13 +60,17 @@ const runSchema = z.strictObject({
53
60
  }).optional()
54
61
  });
55
62
  class FileRunStore {
56
- qaRoot;
57
- constructor(qaRoot = ".qa") {
63
+ constructor(qaRoot = ".qa", scope) {
64
+ this.scope = scope;
58
65
  this.qaRoot = resolve(qaRoot);
59
66
  }
67
+ scope;
68
+ qaRoot;
69
+ get classificationScope() {
70
+ return this.scope ??= loadClassificationRegistry().forProject("local");
71
+ }
60
72
  async createRun(run) {
61
- if (run.metadata?.executionSnapshot !== void 0 && readExecutionSnapshot(run.metadata.executionSnapshot).status !== "recorded")
62
- throw new Error("Invalid execution snapshot");
73
+ assertNewRunMetadata(run.metadata);
63
74
  const directory = runDirectory(this.qaRoot, run.id);
64
75
  await withRunLock(this.qaRoot, run.id, async () => {
65
76
  if (await this.getRun(run.id)) throw new Error(`Run already exists: ${run.id}`);
@@ -123,12 +134,50 @@ class FileRunStore {
123
134
  await withRunLock(this.qaRoot, runId, async () => {
124
135
  const stored = await this.requireRun(runId);
125
136
  if (stored.result) throw new Error(`Run is finished: ${runId}`);
126
- const { executionObservation, findings = [], ...outcome } = result;
137
+ const {
138
+ executionObservation,
139
+ browserViews,
140
+ findings = [],
141
+ outcome: resultOutcome,
142
+ evidence,
143
+ attemptAudit,
144
+ ...outcome
145
+ } = result;
127
146
  if (executionObservation)
128
147
  stored.run.metadata = withExecutionObservation(stored.run.metadata, executionObservation);
148
+ stored.run.metadata = withResultDetails(
149
+ withExecutionBrowserViews(stored.run.metadata, browserViews),
150
+ {
151
+ engineResult: {
152
+ verdict: outcome.verdict,
153
+ reason: outcome.reason ?? null,
154
+ finishedAt: outcome.finishedAt
155
+ },
156
+ ...resultOutcome && { outcome: resultOutcome },
157
+ ...evidence && { evidence }
158
+ }
159
+ );
160
+ if (attemptAudit) stored.run.metadata = { ...stored.run.metadata, attemptAudit };
129
161
  await this.save(runId, runSchema.parse({ ...stored, result: outcome, findings }));
130
162
  });
131
163
  }
164
+ async recordClassifierUsage(runId, samples) {
165
+ if (!samples.length) return;
166
+ await withRunLock(this.qaRoot, runId, async () => {
167
+ const stored = await this.requireRun(runId);
168
+ if (!stored.result) throw new Error("Classifier usage requires a finished attempt");
169
+ const updated = classifierAuditUpdate(stored.run.metadata, stored.result.usage, samples);
170
+ if (!updated) return;
171
+ await this.save(
172
+ runId,
173
+ runSchema.parse({
174
+ ...stored,
175
+ run: { ...stored.run, metadata: updated.metadata },
176
+ result: { ...stored.result, usage: updated.usage }
177
+ })
178
+ );
179
+ });
180
+ }
132
181
  async getRun(runId) {
133
182
  const directory = runDirectory(this.qaRoot, runId);
134
183
  try {
@@ -159,37 +208,56 @@ class FileRunStore {
159
208
  labels: stored.classificationLabels
160
209
  }) : void 0;
161
210
  }
211
+ assertClassificationProject(stored) {
212
+ const snapshot = readExecutionSnapshot(stored.run.metadata?.executionSnapshot);
213
+ const project = snapshot.status === "recorded" ? snapshot.snapshot.projectId : stored.classification?.taxonomy?.project;
214
+ if (project && project !== this.classificationScope.project)
215
+ throw new ClassificationRegistryError("Classification project does not match the run");
216
+ }
162
217
  async saveClassification(runId, value) {
218
+ const classification = validateClassificationWrite(this.classificationScope, value);
163
219
  await withRunLock(this.qaRoot, runId, async () => {
164
220
  const stored = await this.requireRun(runId);
221
+ this.assertClassificationProject(stored);
165
222
  if (!["failed", "error"].includes(stored.result?.verdict ?? ""))
166
223
  throw new Error("Only failed/error runs can be classified");
167
224
  if (stored.classificationLabels.length) return;
168
- stored.classification = classificationSchema.parse(value);
225
+ stored.classification = classification;
169
226
  await this.save(runId, stored);
170
227
  });
171
228
  }
172
229
  async labelClassification(runId, input) {
173
230
  return withRunLock(this.qaRoot, runId, async () => {
174
231
  const stored = await this.requireRun(runId);
232
+ this.assertClassificationProject(stored);
175
233
  if (!["failed", "error"].includes(stored.result?.verdict ?? ""))
176
234
  throw new Error("Only failed/error runs can be classified");
177
- const label = classificationLabelSchema.parse({
178
- ...input,
179
- modifiedAt: Date.now(),
180
- predicted: stored.classification?.source === "human" ? stored.classificationLabels[0]?.predicted ?? null : stored.classification
181
- });
235
+ const { label, classification } = classificationCorrection(
236
+ this.classificationScope,
237
+ input,
238
+ stored.classification?.source === "human" ? stored.classificationLabels[0]?.predicted ?? null : stored.classification
239
+ );
182
240
  stored.classificationLabels.push(label);
183
- stored.classification = {
184
- category: label.category,
185
- reason: label.reason,
186
- confidence: 1,
187
- source: "human"
188
- };
241
+ stored.classification = classification;
189
242
  await this.save(runId, stored);
190
243
  return { classification: stored.classification, labels: stored.classificationLabels };
191
244
  });
192
245
  }
246
+ async recordQuarantine(runId, quarantined, overdueSince) {
247
+ await withRunLock(this.qaRoot, runId, async () => {
248
+ const stored = await this.requireRun(runId);
249
+ if (!stored.result) throw new Error("Quarantine status requires a finished run");
250
+ const previous = stored.run.metadata?.flowQuarantined;
251
+ if (previous === quarantined) return;
252
+ if (previous !== void 0) throw new Error("Conflicting immutable quarantine status");
253
+ stored.run.metadata = {
254
+ ...stored.run.metadata,
255
+ flowQuarantined: quarantined,
256
+ ...overdueSince !== void 0 && { flowQuarantineOverdueSince: overdueSince }
257
+ };
258
+ await this.save(runId, stored);
259
+ });
260
+ }
193
261
  async recordArtifactScan(runId, scan) {
194
262
  await withRunLock(this.qaRoot, runId, async () => {
195
263
  const stored = await this.requireRun(runId);
@@ -0,0 +1,280 @@
1
+ import { type TrialAuditStore, type TrialGroup, type TrialReceipt } from "../trial-audit.js";
2
+ export declare function readAuditFile(path: string): Promise<unknown>;
3
+ export declare function appendAuditFile(path: string, value: unknown): Promise<void>;
4
+ export declare class FileTrialAudit implements TrialAuditStore {
5
+ private readonly projectId;
6
+ private readonly directory;
7
+ constructor(root: string, projectId: string);
8
+ create(input: TrialGroup): Promise<void>;
9
+ append(groupId: string, input: TrialReceipt): Promise<void>;
10
+ list(flow?: string): Promise<{
11
+ schemaVersion: 1;
12
+ groupId: string;
13
+ projectId: string;
14
+ batchId: string;
15
+ caseId: string;
16
+ flow: string;
17
+ caseRevision: string;
18
+ target: string;
19
+ targetRevision: string | null;
20
+ generation: number | null;
21
+ planned: number;
22
+ startedAt: number;
23
+ environment: Record<string, import("zod").JSONType>;
24
+ independent?: boolean | undefined;
25
+ quarantinePolicy?: {
26
+ expiresAfterHours: number;
27
+ evidenceMaxAgeHours: number;
28
+ minimumPassedTrials: number;
29
+ flakyStreak: number;
30
+ } | undefined;
31
+ }[]>;
32
+ get(groupId: string): Promise<{
33
+ group: {
34
+ schemaVersion: 1;
35
+ groupId: string;
36
+ projectId: string;
37
+ batchId: string;
38
+ caseId: string;
39
+ flow: string;
40
+ caseRevision: string;
41
+ target: string;
42
+ targetRevision: string | null;
43
+ generation: number | null;
44
+ planned: number;
45
+ startedAt: number;
46
+ environment: Record<string, import("zod").JSONType>;
47
+ independent?: boolean | undefined;
48
+ quarantinePolicy?: {
49
+ expiresAfterHours: number;
50
+ evidenceMaxAgeHours: number;
51
+ minimumPassedTrials: number;
52
+ flakyStreak: number;
53
+ } | undefined;
54
+ };
55
+ receipts: ({
56
+ kind: "attempt-started";
57
+ trace: {
58
+ schemaVersion: 1;
59
+ projectId: string;
60
+ caseId: string;
61
+ caseRevision: string | null;
62
+ executionId: string;
63
+ attemptId: string;
64
+ attempt: number;
65
+ started: boolean;
66
+ retryOf: string | null;
67
+ batchId: string | null;
68
+ trial: {
69
+ groupId: string;
70
+ index: number;
71
+ count: number;
72
+ } | null;
73
+ target: string | null;
74
+ targetRevision: string | null;
75
+ commit: string | null;
76
+ parameters: {
77
+ runtime: "claude-code" | "codex" | "scripted" | "pi" | null;
78
+ modelAccess: "env" | "login" | "personal" | "team" | null;
79
+ placement: "local-host" | "e2b" | null;
80
+ agentAt: "host" | "stage" | null;
81
+ headed: boolean | null;
82
+ level: "semantic" | "pixel" | "hybrid" | null;
83
+ device: string | null;
84
+ persona: string | null;
85
+ replay: "off" | "enabled" | null;
86
+ };
87
+ parameterFingerprint: string;
88
+ environmentFingerprint: string;
89
+ acceptance?: {
90
+ source: string;
91
+ revision: string;
92
+ criteria: {
93
+ id: string;
94
+ text: string;
95
+ source?: string | undefined;
96
+ }[];
97
+ flows: {
98
+ flow: string;
99
+ covers: string[];
100
+ }[];
101
+ } | undefined;
102
+ covers?: string[] | undefined;
103
+ traceability?: {
104
+ caseId?: string | undefined;
105
+ risk?: string | undefined;
106
+ owner?: string | undefined;
107
+ } | undefined;
108
+ context?: {
109
+ device?: string | undefined;
110
+ ci?: {
111
+ pipeline?: string | undefined;
112
+ task?: string | undefined;
113
+ runId?: string | undefined;
114
+ runUrl?: string | undefined;
115
+ } | undefined;
116
+ build?: {
117
+ id?: string | undefined;
118
+ url?: string | undefined;
119
+ } | undefined;
120
+ correlation?: {
121
+ traceId?: string | undefined;
122
+ spanId?: string | undefined;
123
+ requestId?: string | undefined;
124
+ } | undefined;
125
+ productPr?: {
126
+ url: string;
127
+ base?: string | undefined;
128
+ head?: string | undefined;
129
+ revision?: string | undefined;
130
+ } | undefined;
131
+ qa?: {
132
+ issue?: string | undefined;
133
+ pr?: string | undefined;
134
+ } | undefined;
135
+ defects?: {
136
+ url: string;
137
+ acceptance: string[];
138
+ }[] | undefined;
139
+ } | undefined;
140
+ outcome?: "skipped" | "blocked" | "not-run" | "expected-failure" | undefined;
141
+ engineResult?: {
142
+ verdict: "error" | "passed" | "failed" | "inconclusive" | "canceled";
143
+ reason: string | null;
144
+ finishedAt: number;
145
+ } | undefined;
146
+ evidence?: {
147
+ path: string;
148
+ actor: string | null;
149
+ view: string | null;
150
+ step: string | null;
151
+ eventSeq: number;
152
+ }[] | undefined;
153
+ };
154
+ } | {
155
+ kind: "attempt-finished";
156
+ attemptId: string;
157
+ at: number;
158
+ verdict: "error" | "passed" | "failed" | "inconclusive" | "canceled";
159
+ outcome?: "skipped" | "blocked" | "not-run" | "expected-failure" | undefined;
160
+ usage?: {
161
+ inputTokens: number;
162
+ outputTokens: number;
163
+ actions: number;
164
+ minutes: number;
165
+ cacheReadTokens?: number | undefined;
166
+ cacheWriteTokens?: number | undefined;
167
+ costUsd?: number | undefined;
168
+ costUnknown?: true | undefined;
169
+ e2bMinutes?: number | undefined;
170
+ } | undefined;
171
+ audit?: {
172
+ schemaVersion: 1;
173
+ usage: {
174
+ inputTokens: number;
175
+ outputTokens: number;
176
+ role: "heal" | "main" | "judge" | "reviewer" | "classifier";
177
+ billing: "subscription" | "metered" | null;
178
+ cacheReadTokens?: number | undefined;
179
+ cacheWriteTokens?: number | undefined;
180
+ costUsd?: number | undefined;
181
+ costUnknown?: true | undefined;
182
+ model?: {
183
+ provider: string | null;
184
+ model: string | null;
185
+ seed: number | "unknown" | "unsupported";
186
+ billingVersion: string | null;
187
+ deployment?: string | undefined;
188
+ promptVersion?: string | undefined;
189
+ promptHash?: string | undefined;
190
+ parameters?: Record<string, import("zod").JSONType> | undefined;
191
+ } | undefined;
192
+ billingMode?: "subscription" | "metered" | undefined;
193
+ costUnknownReason?: "subscription" | "unpriced" | "usage-unavailable" | "billing-unrecorded" | undefined;
194
+ actor?: string | undefined;
195
+ step?: string | undefined;
196
+ }[];
197
+ judges: {
198
+ eventSeq: number;
199
+ actor: string | null;
200
+ step: string | null;
201
+ verdict: "passed" | "failed" | "inconclusive";
202
+ confidence: number | null;
203
+ reason: string;
204
+ rubricVersion: string | null;
205
+ rubricHash: string | null;
206
+ outcome: {
207
+ eventSeq: number;
208
+ type: string;
209
+ passed: boolean;
210
+ }[];
211
+ reviewStatus: "recorded" | "pending" | "deterministic";
212
+ }[];
213
+ reviewer: {
214
+ eventSeq: number;
215
+ status: "completed" | "incomplete" | "skipped";
216
+ reason: string;
217
+ failureType: string | null;
218
+ rubricVersion: string | null;
219
+ rubricHash: string | null;
220
+ }[];
221
+ environment?: {
222
+ image: {
223
+ template: string | null;
224
+ digest: string | null;
225
+ };
226
+ runtime: string | null;
227
+ views: {
228
+ view: string;
229
+ browser: string | null;
230
+ viewport: {
231
+ width: number;
232
+ height: number;
233
+ } | null;
234
+ device: string | null;
235
+ }[];
236
+ } | undefined;
237
+ } | undefined;
238
+ observation?: Record<string, import("zod").JSONType> | undefined;
239
+ evidence?: {
240
+ path: string;
241
+ actor: string | null;
242
+ view: string | null;
243
+ step: string | null;
244
+ eventSeq: number;
245
+ }[] | undefined;
246
+ } | {
247
+ kind: "classifier-usage";
248
+ attemptId: string;
249
+ usage: {
250
+ inputTokens: number;
251
+ outputTokens: number;
252
+ cacheReadTokens?: number | undefined;
253
+ cacheWriteTokens?: number | undefined;
254
+ costUsd?: number | undefined;
255
+ costUnknown?: true | undefined;
256
+ model?: {
257
+ provider: string | null;
258
+ model: string | null;
259
+ seed: number | "unknown" | "unsupported";
260
+ billingVersion: string | null;
261
+ deployment?: string | undefined;
262
+ promptVersion?: string | undefined;
263
+ promptHash?: string | undefined;
264
+ parameters?: Record<string, import("zod").JSONType> | undefined;
265
+ } | undefined;
266
+ billingMode?: "subscription" | "metered" | undefined;
267
+ costUnknownReason?: "subscription" | "unpriced" | "usage-unavailable" | "billing-unrecorded" | undefined;
268
+ }[];
269
+ } | {
270
+ kind: "trial-finished";
271
+ index: number;
272
+ attemptId: string;
273
+ quarantined: boolean;
274
+ } | {
275
+ kind: "group-finished";
276
+ at: number;
277
+ })[];
278
+ } | undefined>;
279
+ private readGroup;
280
+ }
@@ -0,0 +1,105 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { link, readdir, readFile, unlink } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { publicId } from "../public-id.js";
6
+ import {
7
+ trialGroupSchema,
8
+ trialReceiptKey,
9
+ trialReceiptSchema
10
+ } from "../trial-audit.js";
11
+ import {
12
+ assertDirectory,
13
+ assertRegularFile,
14
+ atomicWrite,
15
+ ensureDirectory,
16
+ hasCode,
17
+ lockName
18
+ } from "./local-files.js";
19
+ async function readAuditFile(path) {
20
+ await assertRegularFile(path);
21
+ return JSON.parse(await readFile(path, "utf8"));
22
+ }
23
+ async function appendAuditFile(path, value) {
24
+ const temporary = `${path}.${randomUUID()}.pending`;
25
+ const encoded = JSON.stringify(value);
26
+ await atomicWrite(temporary, encoded + "\n");
27
+ try {
28
+ await link(temporary, path);
29
+ } catch (error) {
30
+ if (!hasCode(error, "EEXIST")) throw error;
31
+ if (!isDeepStrictEqual(await readAuditFile(path), JSON.parse(encoded)))
32
+ throw new Error("Conflicting immutable audit record", { cause: error });
33
+ } finally {
34
+ await unlink(temporary);
35
+ }
36
+ }
37
+ class FileTrialAudit {
38
+ constructor(root, projectId) {
39
+ this.projectId = projectId;
40
+ this.directory = resolve(root, "trial-history", publicId.parse(projectId));
41
+ }
42
+ projectId;
43
+ directory;
44
+ async create(input) {
45
+ const group = trialGroupSchema.parse(input);
46
+ if (group.projectId !== this.projectId) throw new Error("Trial project mismatch");
47
+ const directory = join(this.directory, lockName(group.groupId));
48
+ await ensureDirectory(this.directory);
49
+ await ensureDirectory(directory);
50
+ await appendAuditFile(join(directory, "group.json"), group);
51
+ }
52
+ async append(groupId, input) {
53
+ const receipt = trialReceiptSchema.parse(input);
54
+ const directory = join(this.directory, lockName(groupId));
55
+ const group = await this.readGroup(directory);
56
+ if (!group) throw new Error("Trial group not found");
57
+ const key = trialReceiptKey(group, receipt);
58
+ await appendAuditFile(join(directory, `receipt-${lockName(key)}.json`), receipt);
59
+ }
60
+ async list(flow) {
61
+ let entries;
62
+ try {
63
+ await assertDirectory(this.directory);
64
+ entries = await readdir(this.directory);
65
+ } catch (error) {
66
+ if (hasCode(error, "ENOENT")) return [];
67
+ throw error;
68
+ }
69
+ const groups = [];
70
+ for (const entry of entries) {
71
+ if (!/^[a-f0-9]{64}$/.test(entry)) continue;
72
+ const group = await this.readGroup(join(this.directory, entry));
73
+ if (group && (!flow || group.flow === flow)) groups.push(group);
74
+ }
75
+ return groups.sort((a, b) => b.startedAt - a.startedAt || a.groupId.localeCompare(b.groupId));
76
+ }
77
+ async get(groupId) {
78
+ const directory = join(this.directory, lockName(groupId));
79
+ const group = await this.readGroup(directory);
80
+ if (!group) return;
81
+ const receipts = [];
82
+ for (const entry of await readdir(directory)) {
83
+ if (!/^receipt-[a-f0-9]{64}\.json$/.test(entry)) continue;
84
+ receipts.push(trialReceiptSchema.parse(await readAuditFile(join(directory, entry))));
85
+ }
86
+ return { group, receipts };
87
+ }
88
+ async readGroup(directory) {
89
+ try {
90
+ await assertDirectory(directory);
91
+ const group = trialGroupSchema.parse(await readAuditFile(join(directory, "group.json")));
92
+ if (group.projectId !== this.projectId || join(this.directory, lockName(group.groupId)) !== directory)
93
+ throw new Error("Trial history identity mismatch");
94
+ return group;
95
+ } catch (error) {
96
+ if (hasCode(error, "ENOENT")) return void 0;
97
+ throw error;
98
+ }
99
+ }
100
+ }
101
+ export {
102
+ FileTrialAudit,
103
+ appendAuditFile,
104
+ readAuditFile
105
+ };