@virtocommerce/test-automation-framework 0.1.0-alpha.1 → 0.2.0-alpha.20261127111327

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 (135) hide show
  1. package/.claude/agents/vc-qa-automation-expert.md +122 -0
  2. package/.claude/agents/{qa-coverage.md → vc-qa-coverage.md} +10 -7
  3. package/.claude/agents/{qa-explorer.md → vc-qa-explorer.md} +20 -15
  4. package/.claude/agents/{qa-healer.md → vc-qa-healer.md} +15 -13
  5. package/.claude/agents/{qa-judge.md → vc-qa-judge.md} +35 -35
  6. package/.claude/agents/{qa-planner.md → vc-qa-planner.md} +29 -16
  7. package/.claude/agents/{qa-reviewer.md → vc-qa-reviewer.md} +18 -11
  8. package/.claude/checks/browser-secrets.mts +45 -2
  9. package/.claude/checks/contract.mts +258 -33
  10. package/.claude/checks/facts-consistency.mts +335 -0
  11. package/.claude/checks/introspect.mts +157 -0
  12. package/.claude/checks/judge-verdict.mts +44 -3
  13. package/.claude/checks/probe.mts +91 -0
  14. package/.claude/checks/project-facts.mts +85 -6
  15. package/.claude/checks/prove-fails.mts +254 -59
  16. package/.claude/checks/prune.mts +584 -0
  17. package/.claude/checks/rank-gaps.mts +24 -5
  18. package/.claude/checks/readonly-shell.mts +137 -58
  19. package/.claude/checks/reconcile-run.mts +64 -7
  20. package/.claude/checks/run-record.mts +338 -0
  21. package/.claude/checks/stand-request.mts +76 -0
  22. package/.claude/checks/test-shape.mts +78 -14
  23. package/.claude/commands/vc-qa-coverage.md +20 -0
  24. package/.claude/commands/{qa-explore.md → vc-qa-explore.md} +4 -4
  25. package/.claude/commands/{qa-heal.md → vc-qa-heal.md} +6 -6
  26. package/.claude/commands/{qa-implement.md → vc-qa-implement.md} +7 -7
  27. package/.claude/commands/vc-qa-plan.md +64 -0
  28. package/.claude/commands/{qa-review.md → vc-qa-review.md} +12 -12
  29. package/.claude/commands/{qa.md → vc-qa.md} +31 -22
  30. package/.claude/hooks/readonly-shell.mts +1 -1
  31. package/.claude/skills/{coverage-analysis → vc-coverage-analysis}/SKILL.md +24 -15
  32. package/.claude/skills/{create-graphql-layer → vc-create-graphql-layer}/SKILL.md +5 -3
  33. package/.claude/skills/{create-ui-layer → vc-create-ui-layer}/SKILL.md +5 -3
  34. package/.claude/skills/vc-explore-api/SKILL.md +93 -0
  35. package/.claude/skills/{explore-frontend → vc-explore-frontend}/SKILL.md +15 -9
  36. package/.claude/skills/{framework-rules → vc-framework-rules}/SKILL.md +34 -11
  37. package/.claude/skills/{heal-tests → vc-heal-tests}/SKILL.md +21 -21
  38. package/.claude/skills/{heal-tests → vc-heal-tests}/guard-recipe.md +3 -3
  39. package/.claude/skills/{judge-criteria → vc-judge-criteria}/SKILL.md +5 -3
  40. package/.claude/skills/{judge-criteria → vc-judge-criteria}/expert.md +10 -5
  41. package/.claude/skills/{plan-implementation → vc-plan-implementation}/SKILL.md +23 -11
  42. package/.claude/skills/vc-plan-implementation/contract-template.md +86 -0
  43. package/.claude/skills/{plan-test-strategy → vc-plan-test-strategy}/SKILL.md +24 -14
  44. package/.claude/skills/{project-facts → vc-project-facts}/SKILL.md +58 -23
  45. package/.claude/skills/{read-change → vc-read-change}/SKILL.md +4 -4
  46. package/.claude/skills/{read-ticket → vc-read-ticket}/SKILL.md +3 -3
  47. package/.claude/skills/{review-pr → vc-review-pr}/SKILL.md +4 -4
  48. package/.claude/skills/{review-test-code → vc-review-test-code}/SKILL.md +29 -15
  49. package/.claude/skills/{write-e2e-test → vc-write-e2e-test}/SKILL.md +11 -7
  50. package/.claude/skills/{write-graphql-test → vc-write-graphql-test}/SKILL.md +11 -7
  51. package/.claude/skills/{write-rest-api-test → vc-write-rest-api-test}/SKILL.md +16 -11
  52. package/.claude/skills/{write-security-test → vc-write-security-test}/SKILL.md +15 -11
  53. package/CHANGELOG.md +121 -0
  54. package/README.md +17 -0
  55. package/bin/vc-qa-agents.mjs +595 -0
  56. package/dist/auth/browser-sessions.d.ts +88 -0
  57. package/dist/auth/browser-sessions.js +126 -0
  58. package/dist/auth/browser-sessions.js.map +1 -0
  59. package/dist/auth/index.d.ts +5 -5
  60. package/dist/auth/index.js +2 -2
  61. package/dist/auth/index.js.map +1 -1
  62. package/dist/auth/sign-in-strategies.d.ts +67 -0
  63. package/dist/auth/sign-in-strategies.js +121 -0
  64. package/dist/auth/sign-in-strategies.js.map +1 -0
  65. package/dist/auth/token-client.d.ts +9 -1
  66. package/dist/auth/token-client.js +9 -4
  67. package/dist/auth/token-client.js.map +1 -1
  68. package/dist/core/default-reporters.d.ts +9 -6
  69. package/dist/core/default-reporters.js +16 -16
  70. package/dist/core/default-reporters.js.map +1 -1
  71. package/dist/core/index.d.ts +2 -0
  72. package/dist/core/index.js +1 -0
  73. package/dist/core/index.js.map +1 -1
  74. package/dist/core/secret-masking-reporter.d.ts +48 -0
  75. package/dist/core/secret-masking-reporter.js +78 -0
  76. package/dist/core/secret-masking-reporter.js.map +1 -0
  77. package/dist/fixtures/default-fixtures.d.ts +12 -9
  78. package/dist/fixtures/default-fixtures.js +12 -8
  79. package/dist/fixtures/default-fixtures.js.map +1 -1
  80. package/docs/README.md +3 -3
  81. package/docs/concepts/auth.md +68 -16
  82. package/docs/concepts/config.md +14 -6
  83. package/docs/concepts/dataset.md +5 -4
  84. package/docs/concepts/environment.md +17 -12
  85. package/docs/concepts/fixtures.md +23 -16
  86. package/docs/concepts/modules.md +2 -1
  87. package/docs/contributing/architecture.md +22 -15
  88. package/docs/contributing/documentation.md +10 -21
  89. package/docs/contributing/releasing.md +35 -21
  90. package/docs/examples/sign-in-strategies.ts +22 -0
  91. package/docs/getting-started.md +62 -1
  92. package/docs/guides/generating-types.md +5 -4
  93. package/docs/guides/qa-agents.md +193 -35
  94. package/package.json +4 -4
  95. package/templates/suite/.mcp.json +16 -0
  96. package/templates/suite/.qa/project.json +70 -0
  97. package/templates/suite/CLAUDE.template.md +62 -0
  98. package/templates/suite/allurerc.mjs +13 -0
  99. package/templates/suite/arrange/context.ts +15 -0
  100. package/templates/suite/arrange/index.ts +69 -0
  101. package/templates/suite/arrange/security.ts +78 -0
  102. package/templates/suite/biome.template.json +12 -0
  103. package/templates/suite/builders/security.ts +46 -0
  104. package/templates/suite/codegen.ts +27 -0
  105. package/templates/suite/env.example +10 -0
  106. package/templates/suite/env.ts +25 -0
  107. package/templates/suite/fixtures/index.ts +96 -0
  108. package/templates/suite/gitignore +13 -0
  109. package/templates/suite/pages/README.md +10 -0
  110. package/templates/suite/playwright.config.ts +48 -0
  111. package/templates/suite/scripts/generate-rest-types.ts +16 -0
  112. package/templates/suite/support/require-fields.ts +53 -0
  113. package/templates/suite/support/shopper.ts +51 -0
  114. package/templates/suite/support/store.ts +33 -0
  115. package/templates/suite/support/unique-id.ts +11 -0
  116. package/templates/suite/support/users.ts +6 -0
  117. package/templates/suite/tests/restapi/security/sign-in.spec.ts +23 -0
  118. package/templates/suite/tsconfig.json +33 -0
  119. package/.claude/agents/qa-automation-expert.md +0 -119
  120. package/.claude/commands/qa-coverage.md +0 -13
  121. package/.claude/commands/qa-plan.md +0 -55
  122. package/.claude/skills/explore-api/SKILL.md +0 -74
  123. package/.claude/skills/plan-implementation/contract-template.md +0 -72
  124. package/bin/install-qa-agents.mjs +0 -94
  125. package/dist/auth/frontend-browser-sessions.d.ts +0 -71
  126. package/dist/auth/frontend-browser-sessions.js +0 -130
  127. package/dist/auth/frontend-browser-sessions.js.map +0 -1
  128. package/dist/auth/platform-browser-sessions.d.ts +0 -47
  129. package/dist/auth/platform-browser-sessions.js +0 -92
  130. package/dist/auth/platform-browser-sessions.js.map +0 -1
  131. /package/.claude/skills/{judge-criteria → vc-judge-criteria}/coverage.md +0 -0
  132. /package/.claude/skills/{judge-criteria → vc-judge-criteria}/explorer.md +0 -0
  133. /package/.claude/skills/{judge-criteria → vc-judge-criteria}/healer.md +0 -0
  134. /package/.claude/skills/{judge-criteria → vc-judge-criteria}/planner.md +0 -0
  135. /package/.claude/skills/{read-ticket → vc-read-ticket}/providers.md +0 -0
@@ -1,5 +1,11 @@
1
- import { readFileSync } from "node:fs";
1
+ import type { BabelParser } from "./facts-consistency.mts";
2
+
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { createRequire } from "node:module";
2
5
  import { basename, join } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+
8
+ import { crossCheck, placeholderProblems, readSuiteWorld } from "./facts-consistency.mts";
3
9
 
4
10
  export type Route = "command" | "cli" | "api" | "mcp" | "paste";
5
11
 
@@ -11,11 +17,11 @@ export type ProjectFacts = {
11
17
  suiteDir: string;
12
18
  tracker: { kind: string; keyPattern: string; acceptanceCriteriaField?: string; routes: Route[] };
13
19
  docSources: { name: string; route: Route; where: string }[];
14
- commands: { typecheck: string; lint: string; seed?: string; test: Record<string, string> };
20
+ commands: { typecheck: string; lint?: string; seed?: string; test: Record<string, string> };
15
21
  critical: string[];
16
22
  knowledgeDir: string;
17
23
  roles: Record<string, string>;
18
- roleFor: { admin: string; customer: string; otherCustomer?: string };
24
+ roleFor: { admin?: string; customer: string; otherCustomer?: string };
19
25
  rolePermissions?: Record<string, string[]>;
20
26
  passwordFor?: Record<string, string>;
21
27
  coverageWeights: { risk: number; callFrequency: number; runFrequency: number; stability: number; cost: number };
@@ -43,6 +49,9 @@ const MIN_SLOWDOWN_RATIO = 1;
43
49
  export const PROJECT_FACTS_PATH = ".qa/project.json";
44
50
  export const ROOT_SUITE_DIR = ".";
45
51
  export const ENV_FILE = ".env";
52
+ export const PACKAGE_FILE = "package.json";
53
+ export const NODE_MODULES = "node_modules";
54
+ export const PLAYWRIGHT_CLI = [NODE_MODULES, "@playwright", "test", "cli.js"];
46
55
  const DEFAULT_AUTONOMY_KEY = "*";
47
56
  const CLI_FILE_NAME = "project-facts.mts";
48
57
  const HEALER_PATH = /^[A-Za-z0-9_-]+(\/[A-Za-z0-9_.-]+)*\/?$/;
@@ -196,10 +205,11 @@ function parseDocSources(value: unknown): ProjectFacts["docSources"] {
196
205
 
197
206
  function parseCommands(value: unknown): ProjectFacts["commands"] {
198
207
  const commands = asRecord(value, "commands");
208
+ const lint = commands["lint"];
199
209
  const seed = commands["seed"];
200
210
  return {
201
211
  typecheck: asString(present(commands, "typecheck", "commands.typecheck"), "commands.typecheck"),
202
- lint: asString(present(commands, "lint", "commands.lint"), "commands.lint"),
212
+ ...(lint === undefined ? {} : { lint: asString(lint, "commands.lint") }),
203
213
  ...(seed === undefined ? {} : { seed: asString(seed, "commands.seed") }),
204
214
  test: asStringMap(present(commands, "test", "commands.test"), "commands.test"),
205
215
  };
@@ -225,7 +235,8 @@ function parseRoleFor(value: unknown, roles: Record<string, string>): ProjectFac
225
235
  }
226
236
  const role = (purpose: RolePurpose): string =>
227
237
  asRoleName(present(roleFor, purpose, `roleFor.${purpose}`), `roleFor.${purpose}`, roles);
228
- const parsed = { admin: role("admin"), customer: role("customer") };
238
+ const admin = roleFor["admin"] === undefined ? {} : { admin: role("admin") };
239
+ const parsed = { ...admin, customer: role("customer") };
229
240
  if (roleFor["otherCustomer"] === undefined) {
230
241
  return parsed;
231
242
  }
@@ -419,6 +430,60 @@ export function playwrightConfigArgs(suiteDir: string): string[] {
419
430
  return suiteDir === ROOT_SUITE_DIR ? [] : [`--config=${suiteDir}`];
420
431
  }
421
432
 
433
+ /**
434
+ * Whether the suite is its own npm project: a suite directory other than the root with its own `package.json`. Its
435
+ * dependencies, Playwright among them, are then in `<suiteDir>/node_modules`, and the root may have none.
436
+ */
437
+ export function isOwnNpmProject(projectDir: string, suiteDir: string): boolean {
438
+ return suiteDir !== ROOT_SUITE_DIR && existsSync(join(projectDir, suiteDir, PACKAGE_FILE));
439
+ }
440
+
441
+ /** The directory, relative to the repository root, whose `node_modules` holds the suite's dependencies. */
442
+ export function suitePackageDir(projectDir: string, suiteDir: string): string {
443
+ return isOwnNpmProject(projectDir, suiteDir) ? suiteDir : ROOT_SUITE_DIR;
444
+ }
445
+
446
+ /**
447
+ * The words that start a tool the suite installs, from the repository root and never fetching a package: `npx --no`
448
+ * for the root's `node_modules`, `npm exec --prefix <packageDir> --no --` for a suite that is its own npm project. The
449
+ * command still runs in the root, so `--config` and spec paths stay repository-relative.
450
+ */
451
+ export function toolLauncher(packageDir: string): string[] {
452
+ return packageDir === ROOT_SUITE_DIR ? ["npx", "--no"] : ["npm", "exec", "--prefix", packageDir, "--no", "--"];
453
+ }
454
+
455
+ /** The command that starts Playwright Test on the suite from the repository root: the launcher, then the config. */
456
+ export function playwrightCommand(projectDir: string, suiteDir: string): string[] {
457
+ const launcher = toolLauncher(suitePackageDir(projectDir, suiteDir));
458
+ return [...launcher, "playwright", "test", ...playwrightConfigArgs(suiteDir)];
459
+ }
460
+
461
+ /**
462
+ * Imports a package the suite installs, such as `@babel/parser`: as the checks resolve it (the root's
463
+ * `node_modules`), else, for a suite that is its own npm project, from `<suiteDir>/node_modules`.
464
+ *
465
+ * @throws the error of the first import when neither has the package or the facts cannot be read.
466
+ */
467
+ export async function importSuiteDependency<T>(specifier: string, projectDir: string = process.cwd()): Promise<T> {
468
+ try {
469
+ return (await import(specifier)) as T;
470
+ } catch (error) {
471
+ let resolved: string;
472
+ try {
473
+ const { suiteDir } = readProjectFactsIn(projectDir);
474
+ resolved = isOwnNpmProject(projectDir, suiteDir)
475
+ ? createRequire(join(projectDir, suiteDir, PACKAGE_FILE)).resolve(specifier)
476
+ : "";
477
+ } catch {
478
+ resolved = "";
479
+ }
480
+ if (resolved === "") {
481
+ throw error;
482
+ }
483
+ return (await import(pathToFileURL(resolved).href)) as T;
484
+ }
485
+ }
486
+
422
487
  /** The suite's `.env` file, relative to the repository root: `<suiteDir>/.env`, or `.env` for a suite at the root. */
423
488
  export function suiteEnvPath(suiteDir: string): string {
424
489
  return suiteDir === ROOT_SUITE_DIR ? ENV_FILE : `${suiteDir}/${ENV_FILE}`;
@@ -483,7 +548,21 @@ export function readProjectFactsIn(projectDir: string): ProjectFacts {
483
548
 
484
549
  if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
485
550
  try {
486
- process.stdout.write(`${JSON.stringify(readProjectFacts(), null, 2)}\n`);
551
+ const facts = readProjectFacts();
552
+ const world = await readSuiteWorld(process.cwd(), facts.suiteDir, {
553
+ packageDir: suitePackageDir(process.cwd(), facts.suiteDir),
554
+ loadParser: (): Promise<BabelParser> => importSuiteDependency("@babel/parser"),
555
+ });
556
+ const { problems, notes } = crossCheck(facts, world);
557
+ for (const note of notes) {
558
+ process.stderr.write(`project-facts: ${note}\n`);
559
+ }
560
+ const refused = [...placeholderProblems(facts), ...problems];
561
+ if (refused.length > 0) {
562
+ throw new Error(refused.map((problem) => `project.json: ${problem}`).join("\n"));
563
+ }
564
+ const playwright = playwrightCommand(process.cwd(), facts.suiteDir).join(" ");
565
+ process.stdout.write(`${JSON.stringify({ ...facts, playwright }, null, 2)}\n`);
487
566
  } catch (error) {
488
567
  process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
489
568
  process.exitCode = 1;
@@ -16,9 +16,15 @@ import {
16
16
  import { tmpdir } from "node:os";
17
17
  import { basename, dirname, isAbsolute, join, posix, relative, resolve } from "node:path";
18
18
 
19
- import { parse } from "@babel/parser";
20
-
21
- import { playwrightConfigArgs, ROOT_SUITE_DIR, readProjectFactsIn } from "./project-facts.mts";
19
+ import {
20
+ importSuiteDependency,
21
+ NODE_MODULES,
22
+ PLAYWRIGHT_CLI,
23
+ playwrightConfigArgs,
24
+ ROOT_SUITE_DIR,
25
+ readProjectFactsIn,
26
+ suitePackageDir,
27
+ } from "./project-facts.mts";
22
28
 
23
29
  export type ProveFailsResult = { failed: boolean; output: string; mutated: string };
24
30
 
@@ -32,7 +38,6 @@ type Edit = { start: number; end: number; text: string };
32
38
 
33
39
  const CLI_FILE_NAME = "prove-fails.mts";
34
40
  const TEMP_PREFIX = "prove-fails-";
35
- const PLAYWRIGHT_CLI = ["node_modules", "@playwright", "test", "cli.js"];
36
41
  const RUN_TIMEOUT_MS = 300_000;
37
42
  const MAX_BUFFER = 64 * 1024 * 1024;
38
43
  const MAX_OUTPUT = 3000;
@@ -57,6 +62,28 @@ const MATCHERS = [
57
62
  "toHaveURL",
58
63
  "toHaveTitle",
59
64
  ];
65
+ const NUMERIC_MATCHERS = ["toHaveLength", "toHaveCount"];
66
+
67
+ const { parse } = await importSuiteDependency<typeof import("@babel/parser")>("@babel/parser");
68
+ const TEXT_MATCHERS = [
69
+ "toMatch",
70
+ "toContain",
71
+ "toHaveText",
72
+ "toContainText",
73
+ "toHaveValue",
74
+ "toHaveURL",
75
+ "toHaveTitle",
76
+ ];
77
+ const CONTAINER_MATCHERS = ["toEqual", "toStrictEqual", "toMatchObject"];
78
+ const UNORDERED = "arrayContaining";
79
+ const CONTAINING = [UNORDERED, "objectContaining"];
80
+ const OPPOSITES: Readonly<Record<string, string>> = {
81
+ toBeTruthy: "toBeFalsy",
82
+ toBeFalsy: "toBeTruthy",
83
+ toBeNull: "toBeUndefined",
84
+ toBeUndefined: "toBeDefined",
85
+ toBeDefined: "toBeUndefined",
86
+ };
60
87
  const MATCHER_CHAIN = ["resolves", "rejects"];
61
88
  const NEGATION = "not";
62
89
  const LINE_BREAK = new RegExp(`\\r\\n|[\\n\\r${String.fromCharCode(0x2028)}${String.fromCharCode(0x2029)}]`);
@@ -223,21 +250,26 @@ function argumentsOf(call: AstNode): unknown[] {
223
250
  return Array.isArray(call["arguments"]) ? call["arguments"] : [];
224
251
  }
225
252
 
226
- function matcherOf(node: AstNode): { negated: boolean } | undefined {
253
+ type MatcherCall = { name: string; property: AstNode; not: AstNode | undefined };
254
+
255
+ /** The matcher of an `expect(...)` chain: its name, its property node and the member `expect(...).not` when negated. */
256
+ function matcherOf(node: AstNode): MatcherCall | undefined {
227
257
  if (node.type !== "CallExpression") {
228
258
  return undefined;
229
259
  }
230
260
  const callee = node["callee"];
231
- if (!isMember(callee) || !MATCHERS.includes(nameOf(callee["property"]) ?? "")) {
261
+ const property = isMember(callee) ? callee["property"] : undefined;
262
+ const name = nameOf(property);
263
+ if (!isMember(callee) || !isNode(property) || name === undefined) {
232
264
  return undefined;
233
265
  }
234
- let negated = false;
266
+ let not: AstNode | undefined;
235
267
  let current: unknown = callee["object"];
236
268
  while (isMember(current) && [NEGATION, ...MATCHER_CHAIN].includes(nameOf(current["property"]) ?? "")) {
237
- negated = negated || nameOf(current["property"]) === NEGATION;
269
+ not = nameOf(current["property"]) === NEGATION && not === undefined ? current : not;
238
270
  current = current["object"];
239
271
  }
240
- return isExpectCall(current) ? { negated } : undefined;
272
+ return isExpectCall(current) ? { name, property, not } : undefined;
241
273
  }
242
274
 
243
275
  function jsonString(text: string): string {
@@ -254,6 +286,9 @@ function plainTemplateText(argument: AstNode): string | undefined {
254
286
 
255
287
  function mutationOf(argument: AstNode): string | undefined {
256
288
  const value = argument["value"];
289
+ if (argument.type === "BooleanLiteral" && typeof value === "boolean") {
290
+ return value ? "false" : "true";
291
+ }
257
292
  if (argument.type === "NumericLiteral" && typeof value === "number") {
258
293
  return Number.isFinite(value) && value + 1 !== value ? String(value + 1) : undefined;
259
294
  }
@@ -283,6 +318,30 @@ function isTestCall(callee: unknown): boolean {
283
318
  );
284
319
  }
285
320
 
321
+ function stepTitle(call: AstNode): string {
322
+ const [title] = argumentsOf(call);
323
+ if (isNode(title) && title.type === "StringLiteral" && typeof title["value"] === "string") {
324
+ return title["value"];
325
+ }
326
+ return isNode(title) && title.type === "TemplateLiteral" ? (plainTemplateText(title) ?? "") : "";
327
+ }
328
+
329
+ /** Whether the edit lies inside a `test.step("arrange: …")`, the innermost `test.step` around it. */
330
+ function insideArrangeStep(program: AstNode, edit: Edit): boolean {
331
+ const steps = collect(
332
+ program,
333
+ (node) =>
334
+ node.type === "CallExpression" &&
335
+ isMember(node["callee"]) &&
336
+ nameOf(node["callee"]["object"]) === "test" &&
337
+ nameOf(node["callee"]["property"]) === "step" &&
338
+ node.start <= edit.start &&
339
+ edit.end <= node.end,
340
+ );
341
+ const innermost = steps.sort((left, right) => left.end - left.start - (right.end - right.start))[0];
342
+ return innermost !== undefined && stepTitle(innermost).trim().startsWith("arrange:");
343
+ }
344
+
286
345
  function checkInsideTest(program: AstNode, testLine: number, line: number, edit: Edit): void {
287
346
  const calls = collect(
288
347
  program,
@@ -319,50 +378,172 @@ function assertionOn(program: AstNode, line: number): AstNode | undefined {
319
378
  return onLine[0];
320
379
  }
321
380
 
322
- function editOf(call: AstNode, line: number): Edit | undefined {
323
- const args = argumentsOf(call);
324
- const [argument] = args;
325
- if (args.length !== 1 || !isNode(argument) || lineOf(argument) !== line || matcherOf(call) === undefined) {
381
+ function isLiteral(node: unknown): boolean {
382
+ return isNode(node) && mutationOf(node) !== undefined;
383
+ }
384
+
385
+ /** A name or a chain of members (`a.b.c`, `a["k"]`), with no call: reading it has no side effect. */
386
+ function isReference(node: unknown): boolean {
387
+ const inner = unwrapped(node);
388
+ if (nameOf(inner) !== undefined) {
389
+ return true;
390
+ }
391
+ if (!isNode(inner) || !MEMBERS.includes(inner.type) || !isReference(inner["object"])) {
392
+ return false;
393
+ }
394
+ const key = inner["property"];
395
+ return inner["computed"] !== true || isLiteral(key) || isReference(key);
396
+ }
397
+
398
+ function isContaining(node: unknown): node is AstNode {
399
+ const callee = isNode(node) && CALLS.includes(node.type) ? node["callee"] : undefined;
400
+ return (
401
+ isMember(callee) && nameOf(callee["object"]) === "expect" && CONTAINING.includes(nameOf(callee["property"]) ?? "")
402
+ );
403
+ }
404
+
405
+ /**
406
+ * The first literal (depth first) of an object, array or `expect.arrayContaining`/`objectContaining` expected value,
407
+ * and whether it lies inside an `arrayContaining`, whose elements match in any order.
408
+ */
409
+ function firstLiteral(node: unknown, unordered = false): { literal: AstNode; unordered: boolean } | undefined {
410
+ if (!isNode(node)) {
326
411
  return undefined;
327
412
  }
413
+ if (mutationOf(node) !== undefined) {
414
+ return { literal: node, unordered };
415
+ }
416
+ let inner: unknown[] = [];
417
+ let innerUnordered = unordered;
418
+ if (node.type === "ObjectExpression" && Array.isArray(node["properties"])) {
419
+ inner = node["properties"].map((property) => (isNode(property) ? property["value"] : undefined));
420
+ } else if (node.type === "ArrayExpression" && Array.isArray(node["elements"])) {
421
+ inner = node["elements"];
422
+ } else if (isContaining(node)) {
423
+ inner = argumentsOf(node);
424
+ innerUnordered = unordered || nameOf(isNode(node["callee"]) ? node["callee"]["property"] : undefined) === UNORDERED;
425
+ }
426
+ return inner.map((child) => firstLiteral(child, innerUnordered)).find((found) => found !== undefined);
427
+ }
428
+
429
+ /**
430
+ * The mutation of a literal inside an `arrayContaining`: a text no element of the actual array can equal. A number or
431
+ * boolean changed as usual could equal another element (`[1, 2]` to `[2, 2]`), and the assertion would still pass.
432
+ */
433
+ function unorderedMutation(literal: AstNode): string | undefined {
434
+ const value = literal["value"];
435
+ return (literal.type === "NumericLiteral" || literal.type === "BooleanLiteral") && value !== undefined
436
+ ? jsonString(`${String(value)}${MUTATION_SUFFIX}`)
437
+ : mutationOf(literal);
438
+ }
439
+
440
+ function replacement(node: AstNode, text: string): Edit {
441
+ return { start: node.start, end: node.end, text };
442
+ }
443
+
444
+ /** The text a reference argument is replaced by: a value of another type than it, chosen by what the matcher takes. */
445
+ function referenceMutation(name: string, source: string): string {
446
+ if (NUMERIC_MATCHERS.includes(name)) {
447
+ return `(${source}) + 1`;
448
+ }
449
+ return TEXT_MATCHERS.includes(name) ? ["`${", source, "}", MUTATION_SUFFIX, "`"].join("") : `[${source}]`;
450
+ }
451
+
452
+ function argumentEdit(matcher: MatcherCall, argument: AstNode, source: string): Edit | undefined {
328
453
  const text = mutationOf(argument);
329
- return text === undefined ? undefined : { start: argument.start, end: argument.end, text };
454
+ if (MATCHERS.includes(matcher.name) && text !== undefined) {
455
+ return replacement(argument, text);
456
+ }
457
+ if (MATCHERS.includes(matcher.name) && isReference(argument)) {
458
+ return replacement(argument, referenceMutation(matcher.name, source.slice(argument.start, argument.end)));
459
+ }
460
+ if (CONTAINER_MATCHERS.includes(matcher.name) && !isReference(argument)) {
461
+ const found = firstLiteral(argument);
462
+ if (found === undefined) {
463
+ return undefined;
464
+ }
465
+ const changed = found.unordered ? unorderedMutation(found.literal) : mutationOf(found.literal);
466
+ return changed === undefined ? undefined : replacement(found.literal, changed);
467
+ }
468
+ return undefined;
469
+ }
470
+
471
+ /**
472
+ * The one edit that makes an assertion fail: removes the `.not` of a negated one; renames a matcher without an
473
+ * argument to its opposite (`toBeTruthy` to `toBeFalsy`); changes the literal, the reference or the first literal of an
474
+ * object, array or `arrayContaining`/`objectContaining` that is the one expected value of a matcher.
475
+ */
476
+ function editOf(call: AstNode, line: number, source: string): Edit | undefined {
477
+ const matcher = matcherOf(call);
478
+ if (matcher === undefined) {
479
+ return undefined;
480
+ }
481
+ if (matcher.not !== undefined) {
482
+ const object = matcher.not["object"];
483
+ const property = matcher.not["property"];
484
+ return isNode(object) && isNode(property) ? { start: object.end, end: property.end, text: "" } : undefined;
485
+ }
486
+ const args = argumentsOf(call);
487
+ const opposite = OPPOSITES[matcher.name];
488
+ if (args.length === 0) {
489
+ return opposite === undefined
490
+ ? undefined
491
+ : { start: matcher.property.start, end: matcher.property.end, text: opposite };
492
+ }
493
+ const [argument] = args;
494
+ return args.length === 1 && isNode(argument) && lineOf(argument) === line
495
+ ? argumentEdit(matcher, argument, source)
496
+ : undefined;
330
497
  }
331
498
 
332
499
  /**
333
- * Makes the mutation `proveFails` runs, and nothing else: it changes exactly one literal, the expected value of an
334
- * `expect(...).<matcher>(<literal>)` on `line`, where the matcher is one of the single-expected-value matchers
335
- * (`toBe`, `toEqual`, `toHaveText`, ...), is called with exactly one argument, and is not under `.not`. The line must
336
- * hold that assertion and no other: every `expect` chain that starts on the line or has an argument there counts,
337
- * whatever its matcher, so an assertion that cannot be proved is never credited by its neighbour. A bound
338
- * (`toBeGreaterThan`, `toBeLessThan`, ...) is not changed, because one more rarely breaks it. A number becomes its
339
- * value plus one, a string or plain template becomes itself with `__mutated__` appended. The source is parsed, so a
340
- * literal in a comment, a regular expression or a template with substitutions is never a candidate, and no text of
341
- * the caller enters the result. A name, a key, a file name or a second argument (`toHaveAttribute("href", ...)`,
342
- * `toHaveScreenshot("a.png")`, `toBeCloseTo(1, 2)`) is never changed. With `testLine` the changed literal must also
343
- * lie, by position, inside the function of the one `test(...)` or `test.only(...)` that starts there.
500
+ * Makes the mutation `proveFails` runs, and nothing else: it changes exactly one thing in the one assertion on `line`,
501
+ * so the test must fail if the assertion works:
502
+ *
503
+ * - `expect(...).not.<matcher>(...)`: the `.not` is removed (this proves the line is evaluated, not that the value it
504
+ * excludes is the broken behaviour);
505
+ * - a matcher without an argument (`toBeTruthy`, `toBeFalsy`, `toBeNull`, `toBeUndefined`, `toBeDefined`) becomes its
506
+ * opposite;
507
+ * - a matcher with one expected value (`toBe`, `toEqual`, `toHaveText`, ...): a number becomes its value plus one, a
508
+ * string or plain template itself with `__mutated__` appended, a boolean its opposite, a name or member chain
509
+ * (`expected`, `data.cart.id`) a value of another type (plus one, the text with `__mutated__`, or in an array);
510
+ * - `toEqual`, `toStrictEqual` and `toMatchObject` with an object, an array, or `expect.arrayContaining` or
511
+ * `objectContaining`: the first literal inside it is changed as above, except inside an `arrayContaining`, where it
512
+ * becomes the text of its value with `__mutated__` appended, so it cannot equal another element.
344
513
  *
345
- * @returns the mutated source and the mutated line.
346
- * @throws Error when the source cannot be parsed, the line holds no such assertion, more than one assertion, only a
347
- * `.not` one, or the literal is outside the test, or more than one test starts on `testLine`.
514
+ * The line must hold that assertion and no other: every `expect` chain that starts on the line or has an argument there
515
+ * counts, whatever its matcher, so an assertion that cannot be proved is never credited by its neighbour. A bound
516
+ * (`toBeGreaterThan`, `toBeLessThan`, ...) is not changed unless negated, because one more rarely breaks it. An
517
+ * assertion inside a `test.step("arrange: …")` is refused: it guards the test's data, not the behaviour. The source is
518
+ * parsed, so a literal in a comment, a regular expression or a template with substitutions is never a candidate, and no
519
+ * text of the caller enters the result. A name, a key, a file name or a second argument (`toHaveAttribute("href", ...)`,
520
+ * `toHaveScreenshot("a.png")`, `toBeCloseTo(1, 2)`) is never changed. With `testLine` the change must also lie, by
521
+ * position, inside the function of the one `test(...)` or `test.only(...)` that starts there.
522
+ *
523
+ * @returns the mutated source and the line that was changed, as mutated.
524
+ * @throws Error when the source cannot be parsed, the line holds no assertion it can change, more than one assertion,
525
+ * the assertion is in an `arrange:` step or outside the test, or more than one test starts on `testLine`.
348
526
  */
349
527
  export function mutateAssertion(source: string, line: number, testLine?: number): { source: string; mutated: string } {
350
528
  const program = parseSource(source);
351
529
  const call = assertionOn(program, line);
352
- const edit = call === undefined ? undefined : editOf(call, line);
353
- if (call !== undefined && edit !== undefined && matcherOf(call)?.negated) {
354
- throw problem(`line ${line} has only a negated assertion: a .not assertion cannot be proved this way`);
355
- }
530
+ const edit = call === undefined ? undefined : editOf(call, line, source);
356
531
  if (edit === undefined) {
357
532
  throw problem(
358
- `line ${line} has no assertion it can change: it needs one expect(...).<matcher>(<one string or number literal>) with a matcher from ${MATCHERS.join(", ")}`,
533
+ `line ${line} has no assertion it can change: it needs one expect(...) chain with .not, with a matcher of ${Object.keys(OPPOSITES).join(", ")} and no argument, or with a matcher from ${[...new Set([...MATCHERS, ...CONTAINER_MATCHERS])].join(", ")} and one argument: a literal, a name or member chain, or an object, array, arrayContaining or objectContaining that holds a literal`,
359
534
  );
360
535
  }
361
536
  if (testLine !== undefined) {
362
537
  checkInsideTest(program, testLine, line, edit);
363
538
  }
539
+ if (insideArrangeStep(program, edit)) {
540
+ throw problem(
541
+ `line ${line} is an assertion inside an "arrange:" step: it guards the test's data, not the behaviour the case checks, so a proof on it proves nothing; prove the assertion of an "assert:" or "act and assert:" step`,
542
+ );
543
+ }
364
544
  const mutated = `${source.slice(0, edit.start)}${edit.text}${source.slice(edit.end)}`;
365
- return { source: mutated, mutated: mutated.split(LINE_BREAK)[line - 1] ?? "" };
545
+ const editLine = source.slice(0, edit.start).split(LINE_BREAK).length;
546
+ return { source: mutated, mutated: mutated.split(LINE_BREAK)[editLine - 1] ?? "" };
366
547
  }
367
548
 
368
549
  async function checkedSpec(spec: string, root: string): Promise<string> {
@@ -438,10 +619,17 @@ function copyEnvFiles(root: string, worktree: string, suiteDir: string): void {
438
619
  }
439
620
  }
440
621
 
441
- function linkDependencies(root: string, worktree: string): void {
442
- const modules = join(root, "node_modules");
443
- if (existsSync(modules)) {
444
- symlinkSync(modules, join(worktree, "node_modules"), "junction");
622
+ /** The directories whose `node_modules` a worktree links: the root, and the suite's own npm project when it is one. */
623
+ function dependencyDirs(packageDir: string): string[] {
624
+ return packageDir === ROOT_SUITE_DIR ? [ROOT_SUITE_DIR] : [ROOT_SUITE_DIR, packageDir];
625
+ }
626
+
627
+ function linkDependencies(root: string, worktree: string, packageDir: string): void {
628
+ for (const dir of dependencyDirs(packageDir)) {
629
+ const modules = join(root, dir, NODE_MODULES);
630
+ if (existsSync(modules)) {
631
+ symlinkSync(modules, join(worktree, dir, NODE_MODULES), "junction");
632
+ }
445
633
  }
446
634
  }
447
635
 
@@ -453,23 +641,25 @@ function isLinkAt(path: string): boolean {
453
641
  }
454
642
  }
455
643
 
456
- function unlinkDependencies(worktree: string): boolean {
457
- const link = join(worktree, "node_modules");
458
- if (isLinkAt(link)) {
644
+ function unlinkDependencies(worktree: string, packageDir: string): boolean {
645
+ const links = dependencyDirs(packageDir).map((dir) => join(worktree, dir, NODE_MODULES));
646
+ for (const link of links.filter(isLinkAt)) {
459
647
  quietly(() => {
460
648
  unlinkSync(link);
461
649
  });
462
650
  }
463
- return !isLinkAt(link);
651
+ return !links.some(isLinkAt);
464
652
  }
465
653
 
466
654
  /**
467
- * Removes a throw-away worktree: the link to `node_modules` first (the target stays), then the worktree itself.
468
- * Every step is separate and none throws, so a cleanup problem never hides the result or error of the run. When the
655
+ * Removes a throw-away worktree: the links to `node_modules` first (the targets stay), then the worktree itself.
656
+ * Every step is separate and none throws, so a cleanup problem never hides the result or error of the run. When a
469
657
  * link cannot be removed nothing else is deleted.
658
+ *
659
+ * @param packageDir the suite's npm project directory (`suitePackageDir`), whose `node_modules` is linked too.
470
660
  */
471
- export async function removeWorktree(root: string, worktree: string): Promise<void> {
472
- if (!unlinkDependencies(worktree)) {
661
+ export async function removeWorktree(root: string, worktree: string, packageDir = ROOT_SUITE_DIR): Promise<void> {
662
+ if (!unlinkDependencies(worktree, packageDir)) {
473
663
  return;
474
664
  }
475
665
  const removed = await run("git", ["worktree", "remove", "--force", worktree], root);
@@ -548,16 +738,19 @@ export function childEnv(base: NodeJS.ProcessEnv, reportFile: string): NodeJS.Pr
548
738
  return { ...kept, PLAYWRIGHT_JSON_OUTPUT_FILE: reportFile };
549
739
  }
550
740
 
741
+ /**
742
+ * Runs Playwright Test in the worktree with `command`, the CLI and its first arguments (`<cli.js> test --config=…`).
743
+ */
551
744
  async function playwright(
552
745
  worktree: string,
553
- config: readonly string[],
746
+ command: readonly string[],
554
747
  args: readonly string[],
555
748
  reportFile: string,
556
749
  ): Promise<{ report: unknown; stderr: string }> {
557
750
  rmSync(reportFile, { force: true });
558
751
  const result = await run(
559
752
  process.execPath,
560
- [join(worktree, ...PLAYWRIGHT_CLI), "test", ...config, ...args, "--reporter=json"],
753
+ [...command, ...args, "--reporter=json"],
561
754
  worktree,
562
755
  childEnv(process.env, reportFile),
563
756
  );
@@ -654,7 +847,7 @@ function outcomeOf(report: unknown, target: TestRef): Outcome {
654
847
 
655
848
  async function runOnce(
656
849
  worktree: string,
657
- config: readonly string[],
850
+ command: readonly string[],
658
851
  spec: string,
659
852
  target: TestRef,
660
853
  reportFile: string,
@@ -666,7 +859,7 @@ async function runOnce(
666
859
  `--grep=${escapeRegExp(target.title)}$`,
667
860
  `${spec}:${target.line}`,
668
861
  ];
669
- const { report } = await playwright(worktree, config, args, reportFile);
862
+ const { report } = await playwright(worktree, command, args, reportFile);
670
863
  const outcome = outcomeOf(report, target);
671
864
  refuseExpectedFailure(target.title, outcome.expectedStatus);
672
865
  if (outcome.status === "expected") {
@@ -683,9 +876,10 @@ async function runOnce(
683
876
  * Proves that one test fails when a value it checks is changed. The script makes the change itself
684
877
  * ({@link mutateAssertion}): nothing the caller writes reaches the copy. It works on a throw-away git worktree in the
685
878
  * system temporary directory, outside the repository (the working tree is never touched): the worktree gets the
686
- * repository's `HEAD`, the working tree's uncommitted changes and the spec as it is on disk, a link to `node_modules`
687
- * and the `.env*` files of the suite directory (`suiteDir` of the project facts). Playwright runs with the suite's
688
- * config (`playwrightConfigArgs`). The test is run once as it is, with no retries, and must pass; then the literal on
879
+ * repository's `HEAD`, the working tree's uncommitted changes and the spec as it is on disk, links to `node_modules`
880
+ * (the root's, and the suite's own when it is its own npm project) and the `.env*` files of the suite directory
881
+ * (`suiteDir` of the project facts). Playwright, from the suite's own `node_modules` when it has one, runs with the
882
+ * suite's config (`playwrightConfigArgs`). The test is run once as it is, with no retries, and must pass; then the literal on
689
883
  * `line` is changed and the same test run again.
690
884
  *
691
885
  * `failed` is true only when the test passed before the change and failed after it. A flaky or skipped result, and a
@@ -708,36 +902,37 @@ export async function proveFails(
708
902
  checkedLine(line);
709
903
  const root = resolve((await git(["rev-parse", "--show-toplevel"], process.cwd())).trim());
710
904
  const { suiteDir } = readProjectFactsIn(root);
711
- const config = playwrightConfigArgs(suiteDir);
905
+ const packageDir = suitePackageDir(root, suiteDir);
712
906
  const specPath = await checkedSpec(spec, root);
713
907
  const suiteSpec = suitePathOf(specPath, suiteDir);
714
908
  const source = readFileSync(join(root, specPath), "utf8");
715
909
  mutateAssertion(source, line);
716
910
  const worktree = mkdtempSync(join(tmpdir(), TEMP_PREFIX));
911
+ const command = [join(worktree, packageDir, ...PLAYWRIGHT_CLI), "test", ...playwrightConfigArgs(suiteDir)];
717
912
  try {
718
913
  await git(["worktree", "add", "--detach", worktree, "HEAD"], root);
719
914
  await overlayWorkingTree(root, worktree, specPath);
720
915
  copyEnvFiles(root, worktree, suiteDir);
721
- linkDependencies(root, worktree);
916
+ linkDependencies(root, worktree, packageDir);
722
917
  const reportFile = join(worktree, ".prove-fails-report.json");
723
918
  const listed = await playwright(
724
919
  worktree,
725
- config,
920
+ command,
726
921
  ["--list", "--no-deps", ...(project === undefined ? [] : [`--project=${project}`]), specPath],
727
922
  reportFile,
728
923
  );
729
924
  const target = resolveTest(listed.report, specPath, suiteSpec, title, project);
730
925
  refuseExpectedFailure(target.title, target.expectedStatus);
731
926
  const change = mutateAssertion(source, line, target.line);
732
- const before = await runOnce(worktree, config, specPath, target, reportFile);
927
+ const before = await runOnce(worktree, command, specPath, target, reportFile);
733
928
  if (before.failed) {
734
929
  throw problem(`the test "${target.title}" fails before the change: ${firstLine(before.output)}`);
735
930
  }
736
931
  writeFileSync(join(worktree, specPath), change.source);
737
- const after = await runOnce(worktree, config, specPath, target, reportFile);
932
+ const after = await runOnce(worktree, command, specPath, target, reportFile);
738
933
  return { ...after, mutated: change.mutated };
739
934
  } finally {
740
- await removeWorktree(root, worktree);
935
+ await removeWorktree(root, worktree, packageDir);
741
936
  }
742
937
  }
743
938