@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,5 @@
1
1
  ---
2
- name: qa-reviewer
2
+ name: vc-qa-reviewer
3
3
  description: "QA test reviewer: checks a diff against the framework rules, the repository's style, the stand (nothing left behind) and the definition of done. Dispatched fresh with the diff, the contract path and, after a heal, the healer line; reports, never fixes"
4
4
  model: opus
5
5
  color: yellow
@@ -14,8 +14,8 @@ only the diff, the contract and what the repository holds. You never fix, edit,
14
14
  tracker, wiki or code host; you report.
15
15
 
16
16
  Your shell is read-only, enforced by a hook. It runs `git diff|log|show|status`,
17
- `npx --no playwright test --list --reporter=json|list|null` (with `--config=<suiteDir>` when the facts name a suite
18
- directory other than the root) and `node .claude/checks/<module>.mts` only. A refused command is final: do not look
17
+ `<playwright> --list --reporter=json|list|null` (`playwright` of the project facts: the suite's launcher
18
+ and config) and `node .claude/checks/<module>.mts` only. A refused command is final: do not look
19
19
  for a way around it.
20
20
 
21
21
  Whether a test checks the behaviour its case claims, and fails when that behaviour breaks, is the judge's call,
@@ -23,7 +23,7 @@ not yours. Do not re-judge it; report an assertion-free test only when you see o
23
23
 
24
24
  ## Before Anything
25
25
 
26
- 1. Read the skill `framework-rules`, then `project-facts`. Run `node .claude/checks/project-facts.mts`; when it
26
+ 1. Read the skill `vc-framework-rules`, then `vc-project-facts`. Run `node .claude/checks/project-facts.mts`; when it
27
27
  fails, stop and report its line. Never fall back to values from another repository or from memory.
28
28
  2. Run `node .claude/checks/contract.mts check --approved --implemented <contract>`. When it does not print `ok`,
29
29
  report its lines as Critical and stop. When the brief says there is no contract (a branch review), a missing
@@ -37,20 +37,23 @@ not yours. Do not re-judge it; report an assertion-free test only when you see o
37
37
 
38
38
  | Task | Skill |
39
39
  |---|---|
40
- | Review spec files and the building blocks under them | `/review-test-code` |
41
- | Review a pull request, from the diff and metadata the dispatcher gives you | `/review-pr` |
40
+ | Review spec files and the building blocks under them | `/vc-review-test-code` |
41
+ | Review a pull request, from the diff and metadata the dispatcher gives you | `/vc-review-pr` |
42
42
 
43
43
  ## Framework Rules
44
44
 
45
- Check the diff against every rule of `framework-rules`. The skill is the source, not memory.
45
+ Check the diff against every rule of `vc-framework-rules`. The skill is the source, not memory.
46
46
  Report each break with file and line. Typical Critical findings: data created outside `arrange`, or data the code
47
47
  under test creates with no `...Later` removal registered right after the act; fixed waits (`waitForTimeout`,
48
- sleeps, `networkidle`); credentials, store ids or URLs as literals; a `test.fixme`, `test.skip`, retry or workaround
49
- that hides a platform defect, or a `test.fail` that is not a known-issue mark (`framework-rules`, Platform Defects); a skip with no reason; a changed expected value or assertion that moves
48
+ sleeps, `networkidle`); credentials or URLs as literals, or a store id as a literal anywhere but one module-level constant; a `test.fixme`, `test.skip`, retry or workaround
49
+ that hides a platform defect, or a `test.fail` that is not a known-issue mark (`vc-framework-rules`, Platform Defects); a skip with no reason; a changed expected value or assertion that moves
50
50
  toward the build; shared state changed outside the isolated project's directory; a layer import the layer
51
51
  configuration forbids. Typical Warnings: duplicated building blocks, conditionals or casts in a spec, raw selectors
52
52
  in a spec, fallbacks that hide missing data, a deletion proven only by search.
53
53
 
54
+ A break of a framework rule that the contract itself writes as an `assumed:` line (the person was never asked, or did not
55
+ answer) is not Critical: the verdict is NEEDS_DISCUSSION, naming the rule and the line.
56
+
54
57
  Scope: anything in the diff that is not a contract case row or a `## Building blocks` entry, and not covered by an
55
58
  approved amendment, is Critical. Exception: a brief line `healer: <baseline> <new>` (two tree ids) means a heal
56
59
  passed the guard; only the hunks of `git diff <baseline> <new>` under `facts.healerPaths` are spared this rule.
@@ -72,14 +75,16 @@ A shared stand is not ours alone. For every test the diff adds or changes:
72
75
  test creates is registered for removal with a `...Later` method right after the act, never after an assertion
73
76
  or after a step that can fail. A removal registered later, or missing, is Critical.
74
77
  - Every entity the test or the code under test creates is removed, or the test says why in a `leaves data`
75
- annotation.
78
+ annotation. Your shell cannot query the stand: report "nothing left behind" as `not checked`, naming the removal
79
+ code you read instead, never as clean. A client suite with no `arrange` layer removes in a `finally`
80
+ (`vc-framework-rules`).
76
81
  - Only data the stand profile marks `owned` is changed, where the profile provides data modes. Until it does:
77
82
  nothing platform-wide (settings, index, restart, a dataset user's own state) is changed outside the isolated
78
83
  project, and everything created is removed.
79
84
 
80
85
  ## Definition of Done
81
86
 
82
- Do not take the author's word for the run. Follow `review-test-code` "Definition of Done" for each Playwright
87
+ Do not take the author's word for the run. Follow `vc-review-test-code` "Definition of Done" for each Playwright
83
88
  project in the contract's case rows.
84
89
 
85
90
  APPROVE only when reconciliation exits 0 for every project, or lists only failures of tests whose cases are under
@@ -111,6 +116,8 @@ Output format, exactly (this one, not the skill's):
111
116
 
112
117
  ## Example from this repository
113
118
 
119
+ The framework's own suite, as an example and not a rule; another repository's values come from its facts and files.
120
+
114
121
  - Style source: `CLAUDE.md` and `docs/contributing/conventions.md` (no code comments, `function` declarations,
115
122
  "frontend" not "storefront"); `npm run check` sorts imports.
116
123
  - Layer rules: `.biome/layers.json`; specs import Playwright only through `@fixtures`.
@@ -1,3 +1,4 @@
1
+ import { execFileSync } from "node:child_process";
1
2
  import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
2
3
  import { basename, join } from "node:path";
3
4
  import { parseEnv } from "node:util";
@@ -11,6 +12,8 @@ const UNSAFE_VALUE = /['\r\n]/;
11
12
 
12
13
  type Vars = Readonly<Record<string, string | undefined>>;
13
14
 
15
+ type Run = (command: string, args: string[]) => unknown;
16
+
14
17
  /**
15
18
  * The variables of the run, as the tests see them: the suite's `.env` (`<suiteDir>/.env` of the project facts), and
16
19
  * one set in the shell wins over the same one there.
@@ -54,6 +57,42 @@ export function browserSecrets(names: readonly string[], vars: Vars): Record<str
54
57
  );
55
58
  }
56
59
 
60
+ function runQuietly(command: string, args: string[]): unknown {
61
+ return execFileSync(command, args, { stdio: "ignore", windowsHide: true });
62
+ }
63
+
64
+ /**
65
+ * Restricts the secrets file to the current user and says what it did. Mode 0600 does that on POSIX; Windows ignores
66
+ * the mode, so there the file's access list is replaced with `icacls`: inheritance removed, full control for the
67
+ * current user only.
68
+ *
69
+ * @returns `"mode 0600"`, `"icacls"`, or a warning (starting `"warning:"`) when the file may be readable by other
70
+ * accounts of the computer, because `icacls` is not available or failed.
71
+ */
72
+ export function restrictToOwner(
73
+ filePath: string,
74
+ platform: NodeJS.Platform = process.platform,
75
+ vars: Vars = process.env,
76
+ run: Run = runQuietly,
77
+ ): string {
78
+ chmodSync(filePath, OWNER_ONLY);
79
+ if (platform !== "win32") {
80
+ return "mode 0600";
81
+ }
82
+ const user = vars["USERNAME"];
83
+ if (user === undefined || user === "") {
84
+ return "warning: on Windows the file mode is ignored and USERNAME is not set, so the file could not be restricted: remove other accounts' access to it yourself";
85
+ }
86
+ const domain = vars["USERDOMAIN"];
87
+ const account = domain === undefined || domain === "" ? user : `${domain}\\${user}`;
88
+ try {
89
+ run("icacls", [filePath, "/inheritance:r", "/grant:r", `${account}:F`]);
90
+ return "icacls";
91
+ } catch {
92
+ return "warning: on Windows the file mode is ignored and icacls failed, so other accounts of this computer may be able to read the file: remove their access to it yourself";
93
+ }
94
+ }
95
+
57
96
  /** The secrets file's text: one `NAME='value'` line each. */
58
97
  export function secretsFileText(secrets: Readonly<Record<string, string>>): string {
59
98
  return Object.entries(secrets)
@@ -96,10 +135,14 @@ if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
96
135
  const secrets = browserSecrets(names, runVariables(projectDir));
97
136
  const filePath = join(projectDir, BROWSER_SECRETS_PATH);
98
137
  writeFileSync(filePath, secretsFileText(secrets), { mode: OWNER_ONLY });
99
- chmodSync(filePath, OWNER_ONLY);
138
+ const restricted = restrictToOwner(filePath);
139
+ const warning = restricted.startsWith("warning:");
100
140
  process.stdout.write(
101
- `browser-secrets: wrote ${BROWSER_SECRETS_PATH} with ${names.length === 0 ? "no variable (no passwordFor)" : names.join(", ")}; restart the browser server to use it\n`,
141
+ `browser-secrets: wrote ${BROWSER_SECRETS_PATH} with ${names.length === 0 ? "no variable (no passwordFor)" : names.join(", ")}${warning ? "" : ` (owner only, by ${restricted})`}; restart the browser server to use it\n`,
102
142
  );
143
+ if (warning) {
144
+ process.stderr.write(`browser-secrets: ${restricted}\n`);
145
+ }
103
146
  } catch (error) {
104
147
  process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
105
148
  process.exitCode = 1;
@@ -1,8 +1,11 @@
1
- import { readFileSync } from "node:fs";
2
- import { basename } from "node:path";
1
+ import { spawnSync } from "node:child_process";
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { basename, join } from "node:path";
3
4
 
4
- import { readProjectFacts } from "./project-facts.mts";
5
+ import { PLAYWRIGHT_CLI, playwrightConfigArgs, readProjectFacts, suitePackageDir } from "./project-facts.mts";
5
6
  import { CREDENTIAL_SHAPE } from "./readonly-shell.mts";
7
+ import { walkRoot } from "./reconcile-run.mts";
8
+ import { contractSeries, sameSpec } from "./run-record.mts";
6
9
 
7
10
  const CLI_FILE_NAME = "contract.mts";
8
11
  const APPROVED_FLAG = "--approved";
@@ -14,15 +17,28 @@ const REQUIRED_SECTIONS = [
14
17
  "Source",
15
18
  "Scope",
16
19
  "Out of scope",
20
+ "Existing coverage",
17
21
  "Cases",
18
22
  "Stand needs",
19
23
  "Building blocks",
20
24
  "Platform defects",
21
25
  "Verification",
22
26
  ] as const;
23
- const CASE_COLUMNS = ["Case", "Technique", "Project", "Data role", "Oracle"] as const;
27
+ const CASE_COLUMNS = ["Case", "Technique", "Project", "Data role", "Critical flow", "Parameters", "Oracle"] as const;
24
28
  const AMENDMENTS_HEADING = /^amendment/i;
25
29
  const NO_ROLE = "none";
30
+ const NOT_CRITICAL = "no";
31
+ const COMMENT = /<!--[\s\S]*?-->/g;
32
+ const LOCAL_STATE = /\.qa\/(?:reports|kb)\/[^\s`'"()<>,;]*/g;
33
+ const PATH_END_PUNCTUATION = /[.:!?\]]+$/;
34
+ const FILE_NAME = /[^/]\.[A-Za-z0-9]+$/;
35
+ const GLOB = /[*?]/;
36
+ const STATED_DATE = /\((\d{4}-\d{2}-\d{2})\)/;
37
+ const AMENDMENT_FIELDS = ["Cases", "Changes"] as const;
38
+ const DROPS_LINE = /^Drops:\s*(.+)$/im;
39
+ const TITLE_SEPARATOR = " › ";
40
+ const LIST_BUFFER = 256 * 1024 * 1024;
41
+ const MAX_REASON = 300;
26
42
  const APPROVAL_LINE = /^Approved:\s*([^,\s][^,]*),\s*\d{4}-\d{2}-\d{2}(?:\s+\(relayed: "[^\n]+"\))?\s*$/;
27
43
  const APPROVAL = new RegExp(APPROVAL_LINE.source, "m");
28
44
  const APPROVAL_SECTION = "Approval";
@@ -63,10 +79,50 @@ function hasText(lines: string[]): boolean {
63
79
  return lines.some((line) => line.trim() !== "");
64
80
  }
65
81
 
66
- function checkSource(lines: string[]): string[] {
82
+ /**
83
+ * The files a line names under `.qa/reports/` or `.qa/kb/`. A path ends at whitespace, a backtick, a quote or a
84
+ * bracket, and the sentence's closing punctuation is not part of it. A directory (`.qa/reports/`), a name with no
85
+ * extension and a pattern (`coverage-*.md`) name no file, as in "none exists under `.qa/reports/`".
86
+ */
87
+ function localStateFiles(line: string): string[] {
88
+ return [...line.matchAll(LOCAL_STATE)]
89
+ .map((match) => match[0].replace(PATH_END_PUNCTUATION, ""))
90
+ .filter((path) => FILE_NAME.test(path) && !GLOB.test(path));
91
+ }
92
+
93
+ /**
94
+ * A line of `## Source` that names a report or a knowledge snapshot (`.qa/reports/…`, `.qa/kb/…`) must carry the date
95
+ * the planner read it, `(<yyyy-mm-dd>)`, and the file must not have changed after that date (`modifiedOn`, when given).
96
+ */
97
+ function checkLocalState(lines: string[], modifiedOn: ((path: string) => string | undefined) | undefined): string[] {
98
+ const problems: string[] = [];
99
+ for (const line of lines) {
100
+ const date = STATED_DATE.exec(line)?.[1];
101
+ for (const path of localStateFiles(line)) {
102
+ const changed = date === undefined ? undefined : modifiedOn?.(path);
103
+ if (date === undefined) {
104
+ problems.push(
105
+ problem(`## Source names ${path} with no date: write (<yyyy-mm-dd>) after it, the day it was read`),
106
+ );
107
+ } else if (changed !== undefined && changed > date) {
108
+ problems.push(
109
+ problem(
110
+ `## Source: ${path} changed on ${changed}, after the ${date} the contract states: read it again and update the date`,
111
+ ),
112
+ );
113
+ }
114
+ }
115
+ }
116
+ return problems;
117
+ }
118
+
119
+ function checkSource(lines: string[], modifiedOn: ((path: string) => string | undefined) | undefined): string[] {
67
120
  const first = lines.find((line) => line.trim() !== "")?.trim() ?? "";
68
121
  const accepted = SOURCE_KINDS.some((kind) => new RegExp(`^${kind}:\\s*\\S`).test(first));
69
- return accepted ? [] : [problem("## Source must start with ticket:, doc:, area: or gap:")];
122
+ return [
123
+ ...(accepted ? [] : [problem("## Source must start with ticket:, doc:, area: or gap:")]),
124
+ ...checkLocalState(lines, modifiedOn),
125
+ ];
70
126
  }
71
127
 
72
128
  /** Splits the Oracle cell on `separator` outside double quotes, so a quoted observed value may hold `;`. */
@@ -115,7 +171,16 @@ function isObservedOnly(oracle: string): boolean {
115
171
  return sources.length > 0 && sources.every((source) => source === "observed");
116
172
  }
117
173
 
118
- function checkCases(lines: string[], roles: string[] | undefined): { problems: string[]; rows: CaseRow[] } {
174
+ /** The text without `<!-- -->` comments, which hold the template's instructions and its commented-out sections. */
175
+ function withoutComments(markdown: string): string {
176
+ return markdown.replace(COMMENT, "");
177
+ }
178
+
179
+ function checkCases(
180
+ lines: string[],
181
+ roles: string[] | undefined,
182
+ critical: string[] | undefined,
183
+ ): { problems: string[]; rows: CaseRow[] } {
119
184
  const problems: string[] = [];
120
185
  const rows: CaseRow[] = [];
121
186
  const tableLines = lines.filter((line) => line.trim().startsWith("|"));
@@ -163,6 +228,14 @@ function checkCases(lines: string[], roles: string[] | undefined): { problems: s
163
228
  problems.push(problem(`${label} data role "${role}" is not in the facts roles`));
164
229
  }
165
230
  }
231
+ const flow = cell(cells, "Critical flow");
232
+ for (const item of flow.split(",").map((value) => value.trim())) {
233
+ if (critical !== undefined && item !== "" && item !== NOT_CRITICAL && !critical.includes(item)) {
234
+ problems.push(
235
+ problem(`${label} critical flow "${item}" is not in the facts critical list (or ${NOT_CRITICAL})`),
236
+ );
237
+ }
238
+ }
166
239
  rows.push({ name, dataRole, oracle });
167
240
  }
168
241
  return { problems, rows };
@@ -179,7 +252,8 @@ function recordedLine(report: string, caseId: string, value: string): string | u
179
252
  return recorded.map((line) => line.trim()).find((line) => line.startsWith(`- ${caseId}: ${value} (`));
180
253
  }
181
254
 
182
- function namesCase(text: string, caseId: string): boolean {
255
+ /** True when `text` (a test title) names `caseId` as a whole word: `C-1` is not named by `C-10`. */
256
+ export function namesCase(text: string, caseId: string): boolean {
183
257
  return new RegExp(`(^|[^\\w-])${caseId.replace(REGEX_SPECIALS, "\\$&")}([^\\w-]|$)`).test(text);
184
258
  }
185
259
 
@@ -337,6 +411,16 @@ function approvedAmendmentText(sections: Section[]): string {
337
411
  .join("\n");
338
412
  }
339
413
 
414
+ /** The case ids an approved amendment drops (`Drops: C-04, C-05`): they need no test. */
415
+ function droppedCases(sections: Section[]): string[] {
416
+ return sections
417
+ .filter(({ heading }) => AMENDMENTS_HEADING.test(heading))
418
+ .flatMap(({ lines }) => amendmentEntries(lines).entries)
419
+ .filter((entry) => APPROVAL.test(entry.body.join("\n")))
420
+ .flatMap((entry) => (DROPS_LINE.exec(entry.body.join("\n"))?.[1] ?? "").split(/[\s,]+/))
421
+ .filter((id) => id !== "");
422
+ }
423
+
340
424
  function checkAmendments(heading: string, lines: string[]): string[] {
341
425
  const { entries, outside } = amendmentEntries(lines);
342
426
  const problems: string[] = [];
@@ -344,32 +428,79 @@ function checkAmendments(heading: string, lines: string[]): string[] {
344
428
  problems.push(problem(`## ${heading} has text outside a ### entry`));
345
429
  }
346
430
  for (const entry of entries) {
347
- if (!APPROVAL.test(entry.body.join("\n"))) {
431
+ const body = entry.body.join("\n");
432
+ if (!APPROVAL.test(body)) {
348
433
  problems.push(problem(`## ${heading} entry "${entry.title}" has no Approved: <who>, <date> line`));
349
434
  }
435
+ for (const field of AMENDMENT_FIELDS) {
436
+ if (!new RegExp(`^${field}:\\s*\\S`, "m").test(body)) {
437
+ problems.push(problem(`## ${heading} entry "${entry.title}" has no ${field}: line naming what it changes`));
438
+ }
439
+ }
350
440
  }
351
441
  return problems;
352
442
  }
353
443
 
444
+ /** A test the suite lists: its spec file, relative to the config's root directory, and its own title. */
445
+ export type ListedTest = { file: string; title: string };
446
+
447
+ /**
448
+ * Every case id of the contract, but one an approved amendment drops, appears in the title of a listed test of a spec
449
+ * file the contract's `## Verification` runs. Case ids (`C-01`) repeat from one contract to the next, so a test of
450
+ * another contract's spec never counts.
451
+ */
452
+ function checkTestsExist(rows: CaseRow[], tests: readonly ListedTest[], markdown: string, dropped: string[]): string[] {
453
+ const specs = contractSeries(markdown).flatMap((series) => series.specs);
454
+ if (specs.length === 0) {
455
+ return [
456
+ problem(
457
+ "## Verification names no spec file: write the command that runs the new specs, so --implemented can find this contract's tests",
458
+ ),
459
+ ];
460
+ }
461
+ const titles = tests.filter((test) => specs.some((spec) => sameSpec(spec, test.file))).map((test) => test.title);
462
+ return rows
463
+ .map((row) => row.name.split(/\s+/)[0] ?? "")
464
+ .filter((caseId) => caseId !== "" && !dropped.includes(caseId))
465
+ .filter((caseId) => !titles.some((title) => namesCase(title, caseId)))
466
+ .map((caseId) =>
467
+ problem(
468
+ `case ${caseId} has no test: no title of the tests in the spec files of ## Verification names it (the case id comes first in the title)`,
469
+ ),
470
+ );
471
+ }
472
+
473
+ /** What the contract is checked against besides its own text; every part is optional and the CLI fills them from disk. */
474
+ export type ContractChecks = {
475
+ /** Every data role in the cases table must be one of these (or `none`). */
476
+ roles?: string[];
477
+ /** Every critical flow in the cases table must be one of these (or `no`): the facts' `critical`. */
478
+ critical?: string[];
479
+ /** The text of a report an `observed:` oracle names, or `undefined` when it does not exist: the report must hold the value. */
480
+ readReport?: (path: string) => string | undefined;
481
+ /** The day (`yyyy-mm-dd`) a local file last changed, or `undefined` when it does not exist: for the dates in `## Source`. */
482
+ modifiedOn?: (path: string) => string | undefined;
483
+ /** The contract must also carry its `## Approval` line (`check --approved`). */
484
+ requireApproval?: boolean;
485
+ /**
486
+ * No `observed: at first run` part may be left and, when `listedTests` is given, every case id appears in the title of
487
+ * one of them in a spec file of `## Verification` (`check --implemented`).
488
+ */
489
+ requireImplemented?: boolean;
490
+ /** The tests the suite lists (`--list`): spec file and own title, without describe titles. */
491
+ listedTests?: ListedTest[];
492
+ };
493
+
354
494
  /**
355
- * Checks the shape of a contract. Only the shape: it does not judge whether the cases are good.
495
+ * Checks the shape of a contract. Only the shape: it does not judge whether the cases are good. `<!-- -->` comments are
496
+ * ignored.
356
497
  *
357
- * @param roles when given, every data role in the cases table must be one of them (or `none`).
358
- * @param readReport returns the text of a report an `observed:` oracle names, or `undefined` when it does not exist;
359
- * when given, the report must hold the oracle's value for the case. The CLI reads from disk; omitted, only the shape
360
- * is checked.
361
- * @param requireApproval when true, the contract must also carry its `## Approval` line (`check --approved`).
362
- * @param requireImplemented when true, no `observed: at first run` part may be left (`check --implemented`).
498
+ * @param checks what to check besides the text, see {@link ContractChecks}; omitted, only the shape is checked.
363
499
  * @returns one line per problem, empty when the contract is valid.
364
500
  */
365
- export function checkContract(
366
- markdown: string,
367
- roles?: string[],
368
- readReport?: (path: string) => string | undefined,
369
- requireApproval = false,
370
- requireImplemented = false,
371
- ): string[] {
372
- const parsed = parseSections(markdown);
501
+ export function checkContract(markdown: string, checks: ContractChecks = {}): string[] {
502
+ const { roles, critical, readReport, modifiedOn, requireApproval = false, requireImplemented = false } = checks;
503
+ const parsed = parseSections(withoutComments(markdown));
373
504
  const sections = new Map<string, string[]>();
374
505
  const problems: string[] = [];
375
506
  for (const { heading, lines } of parsed) {
@@ -391,10 +522,11 @@ export function checkContract(
391
522
  }
392
523
  const source = sections.get("Source");
393
524
  if (source !== undefined && hasText(source)) {
394
- problems.push(...checkSource(source));
525
+ problems.push(...checkSource(source, modifiedOn));
395
526
  }
396
527
  const cases = sections.get("Cases");
397
- const checked = cases !== undefined && hasText(cases) ? checkCases(cases, roles) : { problems: [], rows: [] };
528
+ const checked =
529
+ cases !== undefined && hasText(cases) ? checkCases(cases, roles, critical) : { problems: [], rows: [] };
398
530
  problems.push(
399
531
  ...checked.problems,
400
532
  ...checkObservedValues(checked.rows, {
@@ -404,6 +536,9 @@ export function checkContract(
404
536
  implemented: requireImplemented,
405
537
  }),
406
538
  ...checkObservedOnly(sections.get("Observed only"), checked.rows),
539
+ ...(requireImplemented && checks.listedTests !== undefined
540
+ ? checkTestsExist(checked.rows, checks.listedTests, markdown, droppedCases(parsed))
541
+ : []),
407
542
  );
408
543
  const approval = sections.get(APPROVAL_SECTION);
409
544
  if (approval !== undefined) {
@@ -419,6 +554,48 @@ export function checkContract(
419
554
  return problems;
420
555
  }
421
556
 
557
+ /** What another check reads from a contract besides its shape. */
558
+ export type ContractReferences = {
559
+ /** The id of every row of `## Cases`, the first word of its Case cell. */
560
+ caseIds: string[];
561
+ /** The case ids an approved amendment drops (`Drops:`). */
562
+ dropped: string[];
563
+ /** The `.qa/reports/explore-<slug>[-observed].md` reports its `observed:` oracles name. */
564
+ observedReports: string[];
565
+ /** The files under `.qa/reports/` and `.qa/kb/` its `## Source` names. */
566
+ sourceFiles: string[];
567
+ /** Whether it has an `## Approval` section. */
568
+ approved: boolean;
569
+ };
570
+
571
+ /**
572
+ * Reads the case ids, the dropped cases, the reports and the approval of a contract, without checking its shape.
573
+ * `<!-- -->` comments are ignored.
574
+ *
575
+ * @returns what the contract names; a missing section gives an empty list.
576
+ */
577
+ function sectionLines(parsed: Section[], heading: string): string[] {
578
+ return parsed.find((section) => section.heading === heading)?.lines ?? [];
579
+ }
580
+
581
+ export function contractReferences(markdown: string): ContractReferences {
582
+ const parsed = parseSections(withoutComments(markdown));
583
+ const cases = sectionLines(parsed, "Cases");
584
+ const rows = hasText(cases) ? checkCases(cases, undefined, undefined).rows : [];
585
+ const observedReports = rows
586
+ .flatMap((row) => sourceParts(row.oracle))
587
+ .filter((part) => part.text.startsWith(OBSERVED))
588
+ .map((part) => RECORDED.exec(part.text.slice(OBSERVED.length).trim())?.[2]?.trim() ?? "")
589
+ .filter((path) => REPORT_PATH.test(path));
590
+ return {
591
+ caseIds: rows.map((row) => row.name.split(/\s+/)[0] ?? "").filter((caseId) => caseId !== ""),
592
+ dropped: droppedCases(parsed),
593
+ observedReports: [...new Set(observedReports)],
594
+ sourceFiles: [...new Set(sectionLines(parsed, "Source").flatMap(localStateFiles))],
595
+ approved: parsed.some((section) => section.heading === APPROVAL_SECTION),
596
+ };
597
+ }
598
+
422
599
  function readReportFile(path: string): string | undefined {
423
600
  try {
424
601
  return readFileSync(path, "utf8");
@@ -427,6 +604,50 @@ function readReportFile(path: string): string | undefined {
427
604
  }
428
605
  }
429
606
 
607
+ function twoDigits(value: number): string {
608
+ return String(value).padStart(2, "0");
609
+ }
610
+
611
+ function modifiedOnDay(path: string): string | undefined {
612
+ try {
613
+ const time = statSync(path).mtime;
614
+ return `${time.getFullYear()}-${twoDigits(time.getMonth() + 1)}-${twoDigits(time.getDate())}`;
615
+ } catch {
616
+ return undefined;
617
+ }
618
+ }
619
+
620
+ /**
621
+ * Every test the suite lists (`playwright test --list --reporter=json` with the suite's config, Playwright from the
622
+ * suite's own `node_modules` when it is its own npm project): its spec file and its own title, without describe titles.
623
+ *
624
+ * @throws Error when the list cannot be made or is not Playwright JSON.
625
+ */
626
+ function listedTests(suiteDir: string): ListedTest[] {
627
+ const cli = join(process.cwd(), suitePackageDir(process.cwd(), suiteDir), ...PLAYWRIGHT_CLI);
628
+ const { PLAYWRIGHT_JSON_OUTPUT_FILE: _output, ...environment } = process.env;
629
+ const listed = spawnSync(
630
+ process.execPath,
631
+ [cli, "test", ...playwrightConfigArgs(suiteDir), "--list", "--reporter=json"],
632
+ { cwd: process.cwd(), env: environment, encoding: "utf8", maxBuffer: LIST_BUFFER, windowsHide: true },
633
+ );
634
+ if (listed.status !== 0) {
635
+ const reason = ((listed.stderr || listed.stdout).trim().split("\n")[0] ?? "").trim().slice(0, MAX_REASON);
636
+ throw new Error(`contract: --implemented could not list the tests: ${reason}`);
637
+ }
638
+ const tests: ListedTest[] = [];
639
+ try {
640
+ walkRoot(JSON.parse(listed.stdout), "list", (test) => {
641
+ const parts = test.split(TITLE_SEPARATOR);
642
+ tests.push({ file: parts[0] ?? "", title: parts.at(-1) ?? "" });
643
+ });
644
+ } catch (error) {
645
+ const reason = error instanceof Error ? error.message : String(error);
646
+ throw new Error(`contract: --implemented could not read the list of tests: ${reason}`);
647
+ }
648
+ return tests;
649
+ }
650
+
430
651
  if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
431
652
  try {
432
653
  const [command, ...rest] = process.argv.slice(2);
@@ -449,13 +670,17 @@ if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
449
670
  } catch {
450
671
  throw new Error(`contract: ${file} cannot be read`);
451
672
  }
452
- const problems = checkContract(
453
- text,
454
- Object.keys(readProjectFacts().roles),
455
- readReportFile,
456
- flags.includes(APPROVED_FLAG),
457
- flags.includes(IMPLEMENTED_FLAG),
458
- );
673
+ const facts = readProjectFacts();
674
+ const implemented = flags.includes(IMPLEMENTED_FLAG);
675
+ const problems = checkContract(text, {
676
+ roles: Object.keys(facts.roles),
677
+ critical: facts.critical,
678
+ readReport: readReportFile,
679
+ modifiedOn: modifiedOnDay,
680
+ requireApproval: flags.includes(APPROVED_FLAG),
681
+ requireImplemented: implemented,
682
+ ...(implemented ? { listedTests: listedTests(facts.suiteDir) } : {}),
683
+ });
459
684
  if (problems.length > 0) {
460
685
  process.stderr.write(`${problems.join("\n")}\n`);
461
686
  process.exitCode = 1;