@abubakarsiddiik/qa 0.0.0-stage → 0.1.1

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 (75) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +36 -2
  3. package/dist/checks.d.ts +18 -0
  4. package/dist/checks.d.ts.map +1 -0
  5. package/dist/checks.js +88 -0
  6. package/dist/checks.js.map +1 -0
  7. package/dist/config.d.ts +57 -0
  8. package/dist/config.d.ts.map +1 -0
  9. package/dist/config.js +143 -0
  10. package/dist/config.js.map +1 -0
  11. package/dist/errors.d.ts +8 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +12 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/fixtures.d.ts +19 -0
  16. package/dist/fixtures.d.ts.map +1 -0
  17. package/dist/fixtures.js +103 -0
  18. package/dist/fixtures.js.map +1 -0
  19. package/dist/generate.d.ts +46 -0
  20. package/dist/generate.d.ts.map +1 -0
  21. package/dist/generate.js +303 -0
  22. package/dist/generate.js.map +1 -0
  23. package/dist/git.d.ts +6 -0
  24. package/dist/git.d.ts.map +1 -0
  25. package/dist/git.js +32 -0
  26. package/dist/git.js.map +1 -0
  27. package/dist/harness.d.ts +23 -0
  28. package/dist/harness.d.ts.map +1 -0
  29. package/dist/harness.js +146 -0
  30. package/dist/harness.js.map +1 -0
  31. package/dist/index.d.ts +17 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +17 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/mcp-stdio.d.ts +2 -0
  36. package/dist/mcp-stdio.d.ts.map +1 -0
  37. package/dist/mcp-stdio.js +23 -0
  38. package/dist/mcp-stdio.js.map +1 -0
  39. package/dist/mcp.d.ts +13 -0
  40. package/dist/mcp.d.ts.map +1 -0
  41. package/dist/mcp.js +236 -0
  42. package/dist/mcp.js.map +1 -0
  43. package/dist/plan.d.ts +33 -0
  44. package/dist/plan.d.ts.map +1 -0
  45. package/dist/plan.js +80 -0
  46. package/dist/plan.js.map +1 -0
  47. package/dist/repair.d.ts +50 -0
  48. package/dist/repair.d.ts.map +1 -0
  49. package/dist/repair.js +176 -0
  50. package/dist/repair.js.map +1 -0
  51. package/dist/report.d.ts +10 -0
  52. package/dist/report.d.ts.map +1 -0
  53. package/dist/report.js +67 -0
  54. package/dist/report.js.map +1 -0
  55. package/dist/runner.d.ts +101 -0
  56. package/dist/runner.d.ts.map +1 -0
  57. package/dist/runner.js +568 -0
  58. package/dist/runner.js.map +1 -0
  59. package/dist/service.d.ts +131 -0
  60. package/dist/service.d.ts.map +1 -0
  61. package/dist/service.js +518 -0
  62. package/dist/service.js.map +1 -0
  63. package/dist/spec.d.ts +512 -0
  64. package/dist/spec.d.ts.map +1 -0
  65. package/dist/spec.js +325 -0
  66. package/dist/spec.js.map +1 -0
  67. package/dist/store.d.ts +148 -0
  68. package/dist/store.d.ts.map +1 -0
  69. package/dist/store.js +438 -0
  70. package/dist/store.js.map +1 -0
  71. package/dist/types.d.ts +9 -0
  72. package/dist/types.d.ts.map +1 -0
  73. package/dist/types.js +2 -0
  74. package/dist/types.js.map +1 -0
  75. package/package.json +49 -3
@@ -0,0 +1,131 @@
1
+ import { type SiteMap } from "@abubakarsiddiik/protocol";
2
+ import type { QaConfig } from "./config.js";
3
+ import { type GenerateOptions } from "./generate.js";
4
+ import { type Plan } from "./plan.js";
5
+ import { type RepairChange } from "./repair.js";
6
+ import { type CaseResult, type CreateSubstrate, type RunOutcome } from "./runner.js";
7
+ import { type QaCase } from "./spec.js";
8
+ import { type CaseFilter, type CaseRow, QaStore, type RunReport } from "./store.js";
9
+ export type Selection = {
10
+ suite?: string;
11
+ ids?: string[];
12
+ tags?: string[];
13
+ changed?: boolean;
14
+ includeQuarantined?: boolean;
15
+ max?: number;
16
+ };
17
+ export type ResolvedSelection = {
18
+ cases: QaCase[];
19
+ plan?: Plan;
20
+ trusted: string[];
21
+ unverified: string[];
22
+ };
23
+ export type RunOptions = {
24
+ repeat?: number;
25
+ allowUnverified?: boolean;
26
+ evidence?: "failures" | "all" | "none";
27
+ trigger?: string;
28
+ };
29
+ export type RunResult = {
30
+ run_id: string;
31
+ summary: RunOutcome["summary"];
32
+ results: CaseResult[];
33
+ };
34
+ export type VerifyReport = {
35
+ case_id: string;
36
+ verified: boolean;
37
+ runs: number;
38
+ results: CaseResult[];
39
+ reason?: string;
40
+ };
41
+ export type GenerateReport = {
42
+ case_id: string;
43
+ path: string;
44
+ spec: QaCase;
45
+ warnings: string[];
46
+ next: string[];
47
+ };
48
+ export type RepairReport = {
49
+ case_id: string;
50
+ repaired: boolean;
51
+ reason: string;
52
+ run_id?: string;
53
+ changes: RepairChange[];
54
+ confirmation?: {
55
+ run_id: string;
56
+ status: CaseResult["status"];
57
+ fail_code?: string;
58
+ fail_reason?: string;
59
+ };
60
+ next: string[];
61
+ };
62
+ export type QaServiceDeps = {
63
+ now?: () => Date;
64
+ /** Overrides substrate creation; tests inject a fake. */
65
+ createSubstrate?: CreateSubstrate;
66
+ };
67
+ /**
68
+ * The shared engine behind the CLI and the MCP server.
69
+ *
70
+ * It owns the spec/DB boundary: every read syncs first, every write updates
71
+ * the file and the index together.
72
+ */
73
+ export declare class QaService {
74
+ readonly config: QaConfig;
75
+ readonly store: QaStore;
76
+ private readonly fixtures;
77
+ private readonly now;
78
+ private readonly createSubstrate?;
79
+ constructor(config: QaConfig, deps?: QaServiceDeps);
80
+ close(): void;
81
+ sync(): ReturnType<QaStore["syncSpecs"]>;
82
+ list(filter?: CaseFilter): CaseRow[];
83
+ caseRead(id: string): {
84
+ spec: QaCase;
85
+ row: CaseRow;
86
+ path: string;
87
+ };
88
+ caseWrite(spec: QaCase): {
89
+ spec: QaCase;
90
+ row: CaseRow;
91
+ path: string;
92
+ };
93
+ /**
94
+ * Normalize an agent-authored spec or a recorded trace into a draft case and
95
+ * write it. The write path is `qa_case_write` semantics: always draft, one
96
+ * file per case, promoted only by verify.
97
+ */
98
+ generate(input: {
99
+ fromSpec?: unknown;
100
+ fromTracePath?: string;
101
+ }, options?: GenerateOptions): GenerateReport;
102
+ /**
103
+ * Attempt locator recovery for a case that failed on `not_found`,
104
+ * `stale_ref`, or `not_interactive`: replay to the failure, re-resolve the
105
+ * target on a fresh capture, rewrite the locator, write the case as draft,
106
+ * record a drift event, and run the repaired case once to confirm.
107
+ */
108
+ repair(input: {
109
+ caseId: string;
110
+ fromRun?: string;
111
+ }): Promise<RepairReport>;
112
+ select(selection?: Selection): ResolvedSelection;
113
+ run(selection?: Selection, options?: RunOptions): Promise<RunResult>;
114
+ verify(selection?: Selection, options?: {
115
+ repeat?: number;
116
+ }): Promise<VerifyReport[]>;
117
+ getRun(id: string): RunReport | undefined;
118
+ coverage(): Array<{
119
+ kind: string;
120
+ key: string;
121
+ covered_by: string[];
122
+ }>;
123
+ loadMap(site: string, requested?: number): SiteMap | undefined;
124
+ private redactResult;
125
+ /** The newest failed run of this case, or the one the caller named. */
126
+ private findFailure;
127
+ private suite;
128
+ private commit;
129
+ private branch;
130
+ }
131
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAIA,OAAO,EAAY,KAAK,OAAO,EAAE,MAAM,2BAA2B,CAAC;AAEnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAG5C,OAAO,EACL,KAAK,eAAe,EAIrB,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,KAAK,IAAI,EAAa,MAAM,WAAW,CAAC;AACjD,OAAO,EAAkD,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAChG,OAAO,EACL,KAAK,UAAU,EACf,KAAK,eAAe,EAEpB,KAAK,UAAU,EAGhB,MAAM,aAAa,CAAC;AACrB,OAAO,EAML,KAAK,MAAM,EAKZ,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,KAAK,UAAU,EAEf,KAAK,OAAO,EAC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:fs";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { parseMap } from "@abubakarsiddiik/protocol";
5
+ import { QaError } from "./errors.js";
6
+ import { loadFixtures, redactValues } from "./fixtures.js";
7
+ import { generateFromSpec, generateFromTrace, readTraceFile, } from "./generate.js";
8
+ import { gitChangedFiles } from "./git.js";
9
+ import { planCases } from "./plan.js";
10
+ import { applyRepair, findReplacement, REPAIRABLE_CODES } from "./repair.js";
11
+ import { defaultCreateSubstrate, replaySteps, runCases, } from "./runner.js";
12
+ import { caseContentSha, caseMatchesSuite, loadCases, loadSuites, readCaseFile, writeCaseFile, } from "./spec.js";
13
+ import { QaStore, } from "./store.js";
14
+ /**
15
+ * The shared engine behind the CLI and the MCP server.
16
+ *
17
+ * It owns the spec/DB boundary: every read syncs first, every write updates
18
+ * the file and the index together.
19
+ */
20
+ export class QaService {
21
+ config;
22
+ store;
23
+ fixtures;
24
+ now;
25
+ createSubstrate;
26
+ constructor(config, deps = {}) {
27
+ this.config = config;
28
+ this.store = new QaStore(config.database);
29
+ this.fixtures = loadFixtures(config.fixtures);
30
+ this.now = deps.now ?? (() => new Date());
31
+ this.createSubstrate = deps.createSubstrate;
32
+ this.sync();
33
+ }
34
+ close() {
35
+ this.store.close();
36
+ }
37
+ sync() {
38
+ return this.store.syncSpecs({
39
+ cases: loadCases(this.config.cases),
40
+ suites: loadSuites(this.config.suites),
41
+ });
42
+ }
43
+ list(filter = {}) {
44
+ this.sync();
45
+ return this.store.listCases(filter);
46
+ }
47
+ caseRead(id) {
48
+ this.sync();
49
+ const found = this.store.getCase(id);
50
+ if (found === undefined)
51
+ throw new QaError("not_found", `no case "${id}"`);
52
+ return { ...found, path: found.row.file_path };
53
+ }
54
+ caseWrite(spec) {
55
+ const path = join(this.config.cases, `${spec.id}.json`);
56
+ const written = writeCaseFile(path, spec, { status: "draft", now: this.now() });
57
+ const loaded = readCaseFile(path);
58
+ const row = this.store.putCase(loaded, { note: "qa_case_write", status: "draft" });
59
+ return { spec: written, row, path };
60
+ }
61
+ /**
62
+ * Normalize an agent-authored spec or a recorded trace into a draft case and
63
+ * write it. The write path is `qa_case_write` semantics: always draft, one
64
+ * file per case, promoted only by verify.
65
+ */
66
+ generate(input, options = {}) {
67
+ let generated;
68
+ if (input.fromTracePath !== undefined) {
69
+ const tracePath = isAbsolute(input.fromTracePath)
70
+ ? input.fromTracePath
71
+ : join(this.config.root, input.fromTracePath);
72
+ const trace = readTraceFile(tracePath);
73
+ generated = generateFromTrace(trace, {
74
+ ...options,
75
+ ...(options.redact === undefined ? { redact: this.config.redact } : {}),
76
+ });
77
+ }
78
+ else if (input.fromSpec !== undefined) {
79
+ generated = generateFromSpec(input.fromSpec, options);
80
+ }
81
+ else {
82
+ throw new QaError("invalid_request", "generate needs from_spec or from_trace");
83
+ }
84
+ this.sync();
85
+ if (this.store.getCase(generated.spec.id) !== undefined) {
86
+ throw new QaError("invalid_request", `case "${generated.spec.id}" already exists; pass a new id`, {
87
+ existing: generated.spec.id,
88
+ });
89
+ }
90
+ const written = this.caseWrite(generated.spec);
91
+ return {
92
+ case_id: written.spec.id,
93
+ path: written.path,
94
+ spec: written.spec,
95
+ warnings: generated.warnings,
96
+ next: [`qa verify ${written.spec.id}`, `read the case: ${written.path}`],
97
+ };
98
+ }
99
+ /**
100
+ * Attempt locator recovery for a case that failed on `not_found`,
101
+ * `stale_ref`, or `not_interactive`: replay to the failure, re-resolve the
102
+ * target on a fresh capture, rewrite the locator, write the case as draft,
103
+ * record a drift event, and run the repaired case once to confirm.
104
+ */
105
+ async repair(input) {
106
+ this.sync();
107
+ const found = this.store.getCase(input.caseId);
108
+ if (found === undefined)
109
+ throw new QaError("not_found", `no case "${input.caseId}"`);
110
+ const spec = found.spec;
111
+ const failure = this.findFailure(input.caseId, input.fromRun);
112
+ if (failure === undefined) {
113
+ return {
114
+ case_id: input.caseId,
115
+ repaired: false,
116
+ reason: "no failed run recorded for this case; run it first, then repair from its evidence",
117
+ changes: [],
118
+ next: [`qa run --case ${input.caseId}`],
119
+ };
120
+ }
121
+ const { runId, row } = failure;
122
+ if (!REPAIRABLE_CODES.has(row.fail_code ?? "")) {
123
+ return {
124
+ case_id: input.caseId,
125
+ repaired: false,
126
+ reason: `fail_code "${row.fail_code ?? "none"}" is not a locator failure (${[...REPAIRABLE_CODES].join(", ")})`,
127
+ run_id: runId,
128
+ changes: [],
129
+ next: [`qa result ${runId} --case ${input.caseId}`, "fix the app or the expectation"],
130
+ };
131
+ }
132
+ const target = failureTarget(spec, row);
133
+ if (target === undefined) {
134
+ return {
135
+ case_id: input.caseId,
136
+ repaired: false,
137
+ reason: "the failed step has no locator to recover",
138
+ run_id: runId,
139
+ changes: [],
140
+ next: [`qa result ${runId} --case ${input.caseId}`],
141
+ };
142
+ }
143
+ const create = this.createSubstrate ?? defaultCreateSubstrate;
144
+ let substrate;
145
+ try {
146
+ substrate = await create({
147
+ baseUrl: this.config.baseUrl,
148
+ headless: this.config.headless,
149
+ ...(this.config.chrome !== undefined ? { executablePath: this.config.chrome } : {}),
150
+ timeoutMs: this.config.timeoutMs,
151
+ });
152
+ try {
153
+ await replaySteps({
154
+ spec,
155
+ uptoStep: target.phase === "check" ? spec.steps.length : (row.fail_step ?? 0),
156
+ substrate,
157
+ baseUrl: this.config.baseUrl,
158
+ timeoutMs: this.config.timeoutMs,
159
+ fixtures: this.fixtures,
160
+ env: process.env,
161
+ redact: this.config.redact,
162
+ loadMap: (site, version) => this.loadMap(site, version),
163
+ });
164
+ }
165
+ catch (error) {
166
+ const reason = error instanceof QaError ? `${error.code}: ${error.message}` : String(error);
167
+ return {
168
+ case_id: input.caseId,
169
+ repaired: false,
170
+ reason: `the case no longer replays to the failure point (${reason}); repair by hand`,
171
+ run_id: runId,
172
+ changes: [],
173
+ next: [`qa result ${runId} --case ${input.caseId}`],
174
+ };
175
+ }
176
+ const view = await substrate.view();
177
+ const outcome = findReplacement(view.snapshot.nodes, target.locator);
178
+ if (outcome.status !== "replaced") {
179
+ return {
180
+ case_id: input.caseId,
181
+ repaired: false,
182
+ reason: outcome.reason,
183
+ run_id: runId,
184
+ changes: [],
185
+ next: outcome.status === "resolves"
186
+ ? [`qa run --case ${input.caseId}`, "the failure was transient, not drift"]
187
+ : [`qa result ${runId} --case ${input.caseId}`, "update the locator by hand"],
188
+ };
189
+ }
190
+ const repaired = applyRepair(spec, target.locator, outcome.locator);
191
+ this.caseWrite(repaired.spec);
192
+ this.store.recordDrift(input.caseId, "selector", { from: target.locator, to: outcome.locator, reason: outcome.reason }, runId);
193
+ const confirmation = await this.run({ ids: [input.caseId] }, { allowUnverified: true, trigger: "repair" });
194
+ const result = confirmation.results[0];
195
+ const confirmed = result?.status === "pass";
196
+ return {
197
+ case_id: input.caseId,
198
+ repaired: true,
199
+ reason: outcome.reason,
200
+ run_id: runId,
201
+ changes: repaired.changes,
202
+ confirmation: result === undefined
203
+ ? undefined
204
+ : {
205
+ run_id: confirmation.run_id,
206
+ status: result.status,
207
+ ...(result.fail_code !== undefined ? { fail_code: result.fail_code } : {}),
208
+ ...(result.fail_reason !== undefined ? { fail_reason: result.fail_reason } : {}),
209
+ },
210
+ next: confirmed
211
+ ? [`qa verify ${input.caseId}`]
212
+ : [
213
+ `qa result ${confirmation.run_id} --case ${input.caseId}`,
214
+ "the rewrite did not fix the run; repair again or by hand",
215
+ ],
216
+ };
217
+ }
218
+ finally {
219
+ await substrate?.close?.();
220
+ }
221
+ }
222
+ select(selection = {}) {
223
+ this.sync();
224
+ const all = loadCases(this.config.cases);
225
+ const rows = new Map(this.store.listCases().map((row) => [row.id, row]));
226
+ const excluded = new Set();
227
+ for (const row of rows.values()) {
228
+ if (row.status === "orphaned" || row.status === "disabled")
229
+ excluded.add(row.id);
230
+ if (row.status === "quarantined" && selection.includeQuarantined !== true) {
231
+ excluded.add(row.id);
232
+ }
233
+ }
234
+ let chosen = all.filter((item) => !excluded.has(item.spec.id));
235
+ let plan;
236
+ if (selection.changed === true) {
237
+ plan = planCases({
238
+ cases: [...rows.values()].map((row) => ({
239
+ id: row.id,
240
+ status: row.status,
241
+ tags: row.tags,
242
+ touches: row.touches,
243
+ })),
244
+ changedFiles: gitChangedFiles(this.config.root, this.config.baseRef),
245
+ max: selection.max ?? this.config.maxCases,
246
+ includeQuarantined: selection.includeQuarantined ?? false,
247
+ });
248
+ const selected = new Set(plan.selected);
249
+ chosen = chosen.filter((item) => selected.has(item.spec.id));
250
+ }
251
+ else if (selection.suite !== undefined) {
252
+ const suite = this.suite(selection.suite);
253
+ chosen = chosen.filter((item) => caseMatchesSuite(item.spec, suite));
254
+ }
255
+ else if (selection.ids !== undefined && selection.ids.length > 0) {
256
+ const ids = new Set(selection.ids);
257
+ chosen = chosen.filter((item) => ids.has(item.spec.id));
258
+ }
259
+ else if (selection.tags !== undefined && selection.tags.length > 0) {
260
+ const tags = new Set(selection.tags);
261
+ chosen = chosen.filter((item) => item.spec.tags.some((tag) => tags.has(tag)));
262
+ }
263
+ if (selection.max !== undefined)
264
+ chosen = chosen.slice(0, selection.max);
265
+ const trusted = chosen
266
+ .filter((item) => {
267
+ const row = rows.get(item.spec.id);
268
+ return row?.status === "verified" && row.verified_sha === caseContentSha(item.spec);
269
+ })
270
+ .map((item) => item.spec.id);
271
+ const trustedSet = new Set(trusted);
272
+ const unverified = chosen
273
+ .filter((item) => !trustedSet.has(item.spec.id))
274
+ .map((item) => item.spec.id);
275
+ return {
276
+ cases: chosen.map((item) => item.spec),
277
+ ...(plan !== undefined ? { plan } : {}),
278
+ trusted,
279
+ unverified,
280
+ };
281
+ }
282
+ async run(selection = {}, options = {}) {
283
+ const resolved = this.select(selection);
284
+ const run = this.store.startRun({
285
+ base_url: this.config.baseUrl,
286
+ trigger: options.trigger ?? "manual",
287
+ ...(this.commit() !== undefined ? { commit: this.commit() } : {}),
288
+ ...(this.branch() !== undefined ? { branch: this.branch() } : {}),
289
+ selection,
290
+ config: { repeat: options.repeat ?? this.config.repeat },
291
+ });
292
+ let outcome;
293
+ try {
294
+ outcome = await runCases({
295
+ baseUrl: this.config.baseUrl,
296
+ cases: resolved.cases,
297
+ repeat: options.repeat ?? this.config.repeat,
298
+ headless: this.config.headless,
299
+ ...(this.config.chrome !== undefined ? { executablePath: this.config.chrome } : {}),
300
+ ...(this.createSubstrate !== undefined ? { createSubstrate: this.createSubstrate } : {}),
301
+ timeoutMs: this.config.timeoutMs,
302
+ evidence: options.evidence ?? this.config.evidence,
303
+ evidenceRoot: this.config.runs,
304
+ runId: run.id,
305
+ allowUnverified: options.allowUnverified ?? this.config.allowUnverified,
306
+ trusted: resolved.trusted,
307
+ screenshot: this.config.screenshot,
308
+ fixtures: this.fixtures,
309
+ env: process.env,
310
+ redact: this.config.redact,
311
+ loadMap: (site, version) => this.loadMap(site, version),
312
+ });
313
+ }
314
+ catch (error) {
315
+ this.store.finishRun(run.id, "error");
316
+ throw error;
317
+ }
318
+ const redacted = outcome.results.map((result) => this.redactResult(result));
319
+ for (const result of redacted) {
320
+ this.store.recordCase(run.id, result);
321
+ if (result.status === "pass" || result.status === "fail") {
322
+ this.store.recordFlake(result.case_id, result.status === "pass");
323
+ }
324
+ if (result.evidence_dir !== undefined) {
325
+ this.store.addEvidence(run.id, result.case_id, "evidence", result.evidence_dir, 0, "");
326
+ }
327
+ }
328
+ const failed = outcome.summary.fail > 0 || outcome.summary.error > 0;
329
+ this.store.finishRun(run.id, failed ? "failed" : "passed");
330
+ return { run_id: run.id, summary: outcome.summary, results: redacted };
331
+ }
332
+ async verify(selection = {}, options = {}) {
333
+ const resolved = this.select(selection);
334
+ const repeat = options.repeat ?? this.config.verifyRepeat;
335
+ const reports = [];
336
+ for (const spec of resolved.cases) {
337
+ const results = [];
338
+ for (let attempt = 0; attempt < repeat; attempt += 1) {
339
+ const outcome = await runCases({
340
+ baseUrl: this.config.baseUrl,
341
+ cases: [spec],
342
+ repeat: 1,
343
+ headless: this.config.headless,
344
+ ...(this.config.chrome !== undefined ? { executablePath: this.config.chrome } : {}),
345
+ ...(this.createSubstrate !== undefined ? { createSubstrate: this.createSubstrate } : {}),
346
+ timeoutMs: this.config.timeoutMs,
347
+ evidence: "none",
348
+ allowUnverified: true,
349
+ trusted: [spec.id],
350
+ screenshot: false,
351
+ fixtures: this.fixtures,
352
+ env: process.env,
353
+ redact: this.config.redact,
354
+ loadMap: (site, version) => this.loadMap(site, version),
355
+ });
356
+ results.push(...outcome.results);
357
+ }
358
+ const failed = results.find((result) => result.status !== "pass");
359
+ const report = {
360
+ case_id: spec.id,
361
+ verified: failed === undefined,
362
+ runs: results.length,
363
+ results,
364
+ ...(failed !== undefined
365
+ ? { reason: `${failed.fail_code ?? failed.status}: ${failed.fail_reason ?? ""}` }
366
+ : {}),
367
+ };
368
+ if (report.verified) {
369
+ const path = join(this.config.cases, `${spec.id}.json`);
370
+ writeCaseFile(path, spec, {
371
+ status: "verified",
372
+ verifiedRuns: repeat,
373
+ now: this.now(),
374
+ });
375
+ const loaded = readCaseFile(path);
376
+ this.store.putCase(loaded, { note: "verified", status: "verified" });
377
+ }
378
+ else {
379
+ this.store.setStatus(spec.id, "broken");
380
+ }
381
+ reports.push(report);
382
+ }
383
+ return reports;
384
+ }
385
+ getRun(id) {
386
+ return this.store.getRun(id);
387
+ }
388
+ coverage() {
389
+ const cases = loadCases(this.config.cases);
390
+ const routes = new Map();
391
+ for (const item of cases) {
392
+ for (const route of item.spec.routes) {
393
+ routes.set(route, [...(routes.get(route) ?? []), item.spec.id]);
394
+ }
395
+ }
396
+ const entries = [...routes.entries()].map(([key, covered_by]) => ({
397
+ kind: "route",
398
+ key,
399
+ covered_by,
400
+ }));
401
+ this.store.putCoverage("current", entries);
402
+ return entries;
403
+ }
404
+ loadMap(site, requested) {
405
+ const dir = join(this.config.maps, site);
406
+ if (!existsSync(dir))
407
+ return undefined;
408
+ let version = requested;
409
+ if (version === undefined) {
410
+ const versions = readdirSync(dir)
411
+ .map((name) => /^v(\d+)\.json$/.exec(name))
412
+ .filter((match) => match !== null)
413
+ .map((match) => Number(match[1]))
414
+ .sort((a, b) => b - a);
415
+ version = versions[0];
416
+ }
417
+ if (version === undefined)
418
+ return undefined;
419
+ try {
420
+ return parseMap(readFileSync(join(dir, `v${version}.json`), "utf8"));
421
+ }
422
+ catch {
423
+ return undefined;
424
+ }
425
+ }
426
+ redactResult(result) {
427
+ const safe = redactValues({
428
+ ...result,
429
+ expected: cap(result.expected),
430
+ actual: cap(result.actual),
431
+ }, this.config.redact);
432
+ return safe;
433
+ }
434
+ /** The newest failed run of this case, or the one the caller named. */
435
+ findFailure(caseId, fromRun) {
436
+ if (fromRun !== undefined) {
437
+ const report = this.store.getRun(fromRun);
438
+ const row = report?.cases.find((item) => item.case_id === caseId);
439
+ if (report === undefined || row === undefined) {
440
+ throw new QaError("not_found", `run "${fromRun}" has no result for case "${caseId}"`);
441
+ }
442
+ return { runId: fromRun, row };
443
+ }
444
+ for (const run of this.store.listRuns(25)) {
445
+ const row = this.store
446
+ .getRun(run.id)
447
+ ?.cases.find((item) => item.case_id === caseId && (item.status === "fail" || item.status === "error"));
448
+ if (row !== undefined)
449
+ return { runId: run.id, row };
450
+ }
451
+ return undefined;
452
+ }
453
+ suite(name) {
454
+ const suite = loadSuites(this.config.suites).find((item) => item.spec.name === name);
455
+ if (suite === undefined)
456
+ throw new QaError("not_found", `no suite "${name}"`);
457
+ return suite.spec;
458
+ }
459
+ commit() {
460
+ return gitValue(this.config.root, ["rev-parse", "HEAD"]);
461
+ }
462
+ branch() {
463
+ return gitValue(this.config.root, ["rev-parse", "--abbrev-ref", "HEAD"]);
464
+ }
465
+ }
466
+ function cap(value, limit = 2000) {
467
+ if (value === undefined)
468
+ return undefined;
469
+ const text = JSON.stringify(value);
470
+ if (text === undefined || text.length <= limit)
471
+ return value;
472
+ return `${text.slice(0, limit)}…[truncated]`;
473
+ }
474
+ /**
475
+ * The locator a failed run broke on, read from the current spec.
476
+ *
477
+ * `fail_step` indexes `steps`; a check failure is recorded as
478
+ * `steps.length + check_index`. Setup steps index into `setup` with the same
479
+ * counter, so when both phases could own the index we prefer whichever
480
+ * actually holds a target.
481
+ */
482
+ function failureTarget(spec, row) {
483
+ const failStep = row.fail_step;
484
+ if (failStep === null || failStep < 0)
485
+ return undefined;
486
+ const step = spec.steps[failStep];
487
+ if (step !== undefined && "target" in step && step.target !== undefined) {
488
+ return { locator: step.target, phase: "step" };
489
+ }
490
+ const setupStep = spec.setup[failStep];
491
+ if (setupStep !== undefined && "target" in setupStep && setupStep.target !== undefined) {
492
+ return { locator: setupStep.target, phase: "setup" };
493
+ }
494
+ const check = spec.expect[failStep - spec.steps.length];
495
+ if (check === undefined)
496
+ return undefined;
497
+ if ("visible" in check)
498
+ return { locator: check.visible, phase: "check" };
499
+ if ("absent" in check)
500
+ return { locator: check.absent, phase: "check" };
501
+ if ("value" in check)
502
+ return { locator: check.value.target, phase: "check" };
503
+ return undefined;
504
+ }
505
+ function gitValue(root, args) {
506
+ try {
507
+ const value = execFileSync("git", args, {
508
+ cwd: root,
509
+ encoding: "utf8",
510
+ stdio: ["ignore", "pipe", "ignore"],
511
+ }).trim();
512
+ return value.length === 0 ? undefined : value;
513
+ }
514
+ catch {
515
+ return undefined;
516
+ }
517
+ }
518
+ //# sourceMappingURL=service.js.map