@virtocommerce/test-automation-framework 0.0.0-stage → 0.1.0-alpha.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 (233) hide show
  1. package/.biome/formatter.json +11 -0
  2. package/.biome/imports.json +52 -0
  3. package/.biome/preset.json +4 -0
  4. package/.biome/rules.json +45 -0
  5. package/.claude/agents/qa-automation-expert.md +119 -0
  6. package/.claude/agents/qa-coverage.md +96 -0
  7. package/.claude/agents/qa-explorer.md +112 -0
  8. package/.claude/agents/qa-healer.md +88 -0
  9. package/.claude/agents/qa-judge.md +102 -0
  10. package/.claude/agents/qa-planner.md +104 -0
  11. package/.claude/agents/qa-reviewer.md +121 -0
  12. package/.claude/checks/browser-secrets.mts +107 -0
  13. package/.claude/checks/contract.mts +469 -0
  14. package/.claude/checks/expectation-guard.mts +665 -0
  15. package/.claude/checks/explore-extractors.mts +4 -0
  16. package/.claude/checks/judge-verdict.mts +165 -0
  17. package/.claude/checks/project-facts.mts +491 -0
  18. package/.claude/checks/prove-fails.mts +770 -0
  19. package/.claude/checks/rank-gaps.mts +177 -0
  20. package/.claude/checks/readonly-shell.mts +740 -0
  21. package/.claude/checks/reconcile-run.mts +270 -0
  22. package/.claude/checks/scan-prompts.mts +351 -0
  23. package/.claude/checks/stand.mts +45 -0
  24. package/.claude/checks/test-duration.mts +134 -0
  25. package/.claude/checks/test-shape.mts +224 -0
  26. package/.claude/checks/ticket-card.mts +195 -0
  27. package/.claude/commands/qa-coverage.md +13 -0
  28. package/.claude/commands/qa-explore.md +17 -0
  29. package/.claude/commands/qa-heal.md +44 -0
  30. package/.claude/commands/qa-implement.md +60 -0
  31. package/.claude/commands/qa-plan.md +55 -0
  32. package/.claude/commands/qa-review.md +90 -0
  33. package/.claude/commands/qa.md +156 -0
  34. package/.claude/hooks/readonly-shell.mts +65 -0
  35. package/.claude/settings.json +15 -0
  36. package/.claude/skills/coverage-analysis/SKILL.md +107 -0
  37. package/.claude/skills/create-graphql-layer/SKILL.md +159 -0
  38. package/.claude/skills/create-ui-layer/SKILL.md +189 -0
  39. package/.claude/skills/explore-api/SKILL.md +74 -0
  40. package/.claude/skills/explore-frontend/SKILL.md +85 -0
  41. package/.claude/skills/framework-rules/SKILL.md +189 -0
  42. package/.claude/skills/heal-tests/SKILL.md +197 -0
  43. package/.claude/skills/heal-tests/guard-recipe.md +53 -0
  44. package/.claude/skills/judge-criteria/SKILL.md +40 -0
  45. package/.claude/skills/judge-criteria/coverage.md +9 -0
  46. package/.claude/skills/judge-criteria/expert.md +23 -0
  47. package/.claude/skills/judge-criteria/explorer.md +9 -0
  48. package/.claude/skills/judge-criteria/healer.md +13 -0
  49. package/.claude/skills/judge-criteria/planner.md +12 -0
  50. package/.claude/skills/plan-implementation/SKILL.md +82 -0
  51. package/.claude/skills/plan-implementation/contract-template.md +72 -0
  52. package/.claude/skills/plan-test-strategy/SKILL.md +100 -0
  53. package/.claude/skills/project-facts/SKILL.md +130 -0
  54. package/.claude/skills/read-change/SKILL.md +64 -0
  55. package/.claude/skills/read-ticket/SKILL.md +63 -0
  56. package/.claude/skills/read-ticket/providers.md +58 -0
  57. package/.claude/skills/review-pr/SKILL.md +152 -0
  58. package/.claude/skills/review-test-code/SKILL.md +208 -0
  59. package/.claude/skills/write-e2e-test/SKILL.md +175 -0
  60. package/.claude/skills/write-graphql-test/SKILL.md +158 -0
  61. package/.claude/skills/write-rest-api-test/SKILL.md +182 -0
  62. package/.claude/skills/write-security-test/SKILL.md +253 -0
  63. package/.qa/project.example.json +71 -0
  64. package/CHANGELOG.md +1 -0
  65. package/LICENSE +12 -0
  66. package/README.md +53 -2
  67. package/bin/install-qa-agents.mjs +94 -0
  68. package/dist/auth/credentials.d.ts +10 -0
  69. package/dist/auth/credentials.js +2 -0
  70. package/dist/auth/credentials.js.map +1 -0
  71. package/dist/auth/frontend-browser-sessions.d.ts +71 -0
  72. package/dist/auth/frontend-browser-sessions.js +130 -0
  73. package/dist/auth/frontend-browser-sessions.js.map +1 -0
  74. package/dist/auth/index.d.ts +9 -0
  75. package/dist/auth/index.js +5 -0
  76. package/dist/auth/index.js.map +1 -0
  77. package/dist/auth/platform-browser-sessions.d.ts +47 -0
  78. package/dist/auth/platform-browser-sessions.js +92 -0
  79. package/dist/auth/platform-browser-sessions.js.map +1 -0
  80. package/dist/auth/sign-in-lock.d.ts +14 -0
  81. package/dist/auth/sign-in-lock.js +70 -0
  82. package/dist/auth/sign-in-lock.js.map +1 -0
  83. package/dist/auth/storage-state.d.ts +3 -0
  84. package/dist/auth/storage-state.js +2 -0
  85. package/dist/auth/storage-state.js.map +1 -0
  86. package/dist/auth/token-client.d.ts +82 -0
  87. package/dist/auth/token-client.js +111 -0
  88. package/dist/auth/token-client.js.map +1 -0
  89. package/dist/auth/token-manager.d.ts +67 -0
  90. package/dist/auth/token-manager.js +138 -0
  91. package/dist/auth/token-manager.js.map +1 -0
  92. package/dist/core/default-reporters.d.ts +31 -0
  93. package/dist/core/default-reporters.js +36 -0
  94. package/dist/core/default-reporters.js.map +1 -0
  95. package/dist/core/default-use.d.ts +28 -0
  96. package/dist/core/default-use.js +25 -0
  97. package/dist/core/default-use.js.map +1 -0
  98. package/dist/core/env.d.ts +24 -0
  99. package/dist/core/env.js +33 -0
  100. package/dist/core/env.js.map +1 -0
  101. package/dist/core/error-message.d.ts +10 -0
  102. package/dist/core/error-message.js +13 -0
  103. package/dist/core/error-message.js.map +1 -0
  104. package/dist/core/index.d.ts +16 -0
  105. package/dist/core/index.js +11 -0
  106. package/dist/core/index.js.map +1 -0
  107. package/dist/core/is-ci.d.ts +14 -0
  108. package/dist/core/is-ci.js +18 -0
  109. package/dist/core/is-ci.js.map +1 -0
  110. package/dist/core/parse-env.d.ts +13 -0
  111. package/dist/core/parse-env.js +21 -0
  112. package/dist/core/parse-env.js.map +1 -0
  113. package/dist/core/projects.d.ts +24 -0
  114. package/dist/core/projects.js +33 -0
  115. package/dist/core/projects.js.map +1 -0
  116. package/dist/core/run-options.d.ts +31 -0
  117. package/dist/core/run-options.js +43 -0
  118. package/dist/core/run-options.js.map +1 -0
  119. package/dist/core/secret.d.ts +105 -0
  120. package/dist/core/secret.js +167 -0
  121. package/dist/core/secret.js.map +1 -0
  122. package/dist/core/string-schemas.d.ts +39 -0
  123. package/dist/core/string-schemas.js +56 -0
  124. package/dist/core/string-schemas.js.map +1 -0
  125. package/dist/core/url-path.d.ts +7 -0
  126. package/dist/core/url-path.js +2 -0
  127. package/dist/core/url-path.js.map +1 -0
  128. package/dist/dataset/collection.d.ts +44 -0
  129. package/dist/dataset/collection.js +76 -0
  130. package/dist/dataset/collection.js.map +1 -0
  131. package/dist/dataset/index.d.ts +11 -0
  132. package/dist/dataset/index.js +6 -0
  133. package/dist/dataset/index.js.map +1 -0
  134. package/dist/dataset/load-dataset.d.ts +39 -0
  135. package/dist/dataset/load-dataset.js +62 -0
  136. package/dist/dataset/load-dataset.js.map +1 -0
  137. package/dist/dataset/manifest.d.ts +77 -0
  138. package/dist/dataset/manifest.js +10 -0
  139. package/dist/dataset/manifest.js.map +1 -0
  140. package/dist/dataset/placeholders.d.ts +66 -0
  141. package/dist/dataset/placeholders.js +87 -0
  142. package/dist/dataset/placeholders.js.map +1 -0
  143. package/dist/dataset/seed-collection.d.ts +53 -0
  144. package/dist/dataset/seed-collection.js +115 -0
  145. package/dist/dataset/seed-collection.js.map +1 -0
  146. package/dist/dataset/seed-dataset.d.ts +70 -0
  147. package/dist/dataset/seed-dataset.js +138 -0
  148. package/dist/dataset/seed-dataset.js.map +1 -0
  149. package/dist/dataset/seed-events.d.ts +81 -0
  150. package/dist/dataset/seed-events.js +2 -0
  151. package/dist/dataset/seed-events.js.map +1 -0
  152. package/dist/dataset/seed-requests.d.ts +102 -0
  153. package/dist/dataset/seed-requests.js +160 -0
  154. package/dist/dataset/seed-requests.js.map +1 -0
  155. package/dist/dataset/seed-scope.d.ts +39 -0
  156. package/dist/dataset/seed-scope.js +67 -0
  157. package/dist/dataset/seed-scope.js.map +1 -0
  158. package/dist/fixtures/default-fixtures.d.ts +93 -0
  159. package/dist/fixtures/default-fixtures.js +105 -0
  160. package/dist/fixtures/default-fixtures.js.map +1 -0
  161. package/dist/fixtures/index.d.ts +2 -0
  162. package/dist/fixtures/index.js +2 -0
  163. package/dist/fixtures/index.js.map +1 -0
  164. package/dist/graphql/graphql-client.d.ts +78 -0
  165. package/dist/graphql/graphql-client.js +83 -0
  166. package/dist/graphql/graphql-client.js.map +1 -0
  167. package/dist/graphql/graphql-codegen.d.ts +56 -0
  168. package/dist/graphql/graphql-codegen.js +42 -0
  169. package/dist/graphql/graphql-codegen.js.map +1 -0
  170. package/dist/graphql/graphql-error.d.ts +54 -0
  171. package/dist/graphql/graphql-error.js +74 -0
  172. package/dist/graphql/graphql-error.js.map +1 -0
  173. package/dist/graphql/index.d.ts +6 -0
  174. package/dist/graphql/index.js +4 -0
  175. package/dist/graphql/index.js.map +1 -0
  176. package/dist/http/authentication.d.ts +16 -0
  177. package/dist/http/authentication.js +2 -0
  178. package/dist/http/authentication.js.map +1 -0
  179. package/dist/http/http-client.d.ts +110 -0
  180. package/dist/http/http-client.js +237 -0
  181. package/dist/http/http-client.js.map +1 -0
  182. package/dist/http/http-error.d.ts +26 -0
  183. package/dist/http/http-error.js +34 -0
  184. package/dist/http/http-error.js.map +1 -0
  185. package/dist/http/http-method.d.ts +2 -0
  186. package/dist/http/http-method.js +2 -0
  187. package/dist/http/http-method.js.map +1 -0
  188. package/dist/http/http-response.d.ts +137 -0
  189. package/dist/http/http-response.js +166 -0
  190. package/dist/http/http-response.js.map +1 -0
  191. package/dist/http/index.d.ts +7 -0
  192. package/dist/http/index.js +4 -0
  193. package/dist/http/index.js.map +1 -0
  194. package/dist/http/request-options.d.ts +62 -0
  195. package/dist/http/request-options.js +2 -0
  196. package/dist/http/request-options.js.map +1 -0
  197. package/dist/modules/index.d.ts +2 -0
  198. package/dist/modules/index.js +2 -0
  199. package/dist/modules/index.js.map +1 -0
  200. package/dist/modules/installed-modules.d.ts +86 -0
  201. package/dist/modules/installed-modules.js +135 -0
  202. package/dist/modules/installed-modules.js.map +1 -0
  203. package/docs/README.md +43 -0
  204. package/docs/concepts/areas.md +38 -0
  205. package/docs/concepts/auth.md +92 -0
  206. package/docs/concepts/config.md +102 -0
  207. package/docs/concepts/dataset.md +183 -0
  208. package/docs/concepts/environment.md +54 -0
  209. package/docs/concepts/fixtures.md +109 -0
  210. package/docs/concepts/graphql.md +76 -0
  211. package/docs/concepts/http.md +88 -0
  212. package/docs/concepts/modules.md +63 -0
  213. package/docs/concepts/secrets.md +50 -0
  214. package/docs/contributing/architecture.md +67 -0
  215. package/docs/contributing/conventions.md +39 -0
  216. package/docs/contributing/documentation.md +37 -0
  217. package/docs/contributing/releasing.md +76 -0
  218. package/docs/examples/auth.ts +20 -0
  219. package/docs/examples/config.ts +36 -0
  220. package/docs/examples/dataset.ts +70 -0
  221. package/docs/examples/environment.ts +8 -0
  222. package/docs/examples/fixtures.ts +41 -0
  223. package/docs/examples/getting-started.ts +22 -0
  224. package/docs/examples/graphql-codegen.ts +9 -0
  225. package/docs/examples/graphql.ts +32 -0
  226. package/docs/examples/http.ts +18 -0
  227. package/docs/examples/modules.ts +19 -0
  228. package/docs/examples/secrets.ts +11 -0
  229. package/docs/examples/tsconfig.json +10 -0
  230. package/docs/getting-started.md +106 -0
  231. package/docs/guides/generating-types.md +75 -0
  232. package/docs/guides/qa-agents.md +66 -0
  233. package/package.json +156 -4
@@ -0,0 +1,134 @@
1
+ import type { ProjectFacts } from "./project-facts.mts";
2
+ import type { QualityFinding } from "./test-shape.mts";
3
+
4
+ import { basename } from "node:path";
5
+
6
+ import { readProjectFacts } from "./project-facts.mts";
7
+ import { InputError, isRecord, listOf, readJson, walkRoot } from "./reconcile-run.mts";
8
+
9
+ const CLI_FILE_NAME = "test-duration.mts";
10
+ const PASSED = "passed";
11
+ const EVEN = 2;
12
+
13
+ function finalPassedDuration(entry: Record<string, unknown>, label: string): number | undefined {
14
+ const last = listOf(entry["results"], label).at(-1);
15
+ if (last === undefined) {
16
+ return undefined;
17
+ }
18
+ if (!isRecord(last) || typeof last["duration"] !== "number") {
19
+ throw new InputError(`the ${label} is not Playwright JSON`);
20
+ }
21
+ return last["status"] === PASSED ? last["duration"] : undefined;
22
+ }
23
+
24
+ function translated<T>(action: () => T): T {
25
+ try {
26
+ return action();
27
+ } catch (error) {
28
+ throw error instanceof InputError ? new Error(`test-duration: ${error.what}`) : error;
29
+ }
30
+ }
31
+
32
+ function median(values: readonly number[]): number {
33
+ const sorted = [...values].sort((a, b) => a - b);
34
+ const middle = Math.floor(sorted.length / EVEN);
35
+ const high = sorted[middle] ?? 0;
36
+ return sorted.length % EVEN === 1 ? high : Math.round(((sorted[middle - 1] ?? high) + high) / EVEN);
37
+ }
38
+
39
+ function medianDurations(
40
+ report: unknown,
41
+ project: string,
42
+ label: string,
43
+ mustHoldProject: boolean,
44
+ ): Map<string, number> {
45
+ const durations = new Map<string, number[]>();
46
+ let ofProject = 0;
47
+ walkRoot(report, label, (test, entry) => {
48
+ if (entry["projectName"] !== project) {
49
+ return;
50
+ }
51
+ ofProject += 1;
52
+ const duration = finalPassedDuration(entry, label);
53
+ if (duration !== undefined) {
54
+ durations.set(test, [...(durations.get(test) ?? []), duration]);
55
+ }
56
+ });
57
+ if (mustHoldProject && ofProject === 0) {
58
+ throw new InputError(`the ${label} holds no test of project ${project}`);
59
+ }
60
+ return new Map([...durations].map(([test, values]) => [test, median(values)]));
61
+ }
62
+
63
+ /**
64
+ * Judges the duration of every test that passed in a Playwright JSON report (the reporter output `reconcile-run`
65
+ * reads) for one project. A test run several times (`--repeat-each`) is judged by the MEDIAN of its passing runs, each
66
+ * run counted by its last attempt: one slow call on a shared stand must not fail a test that is usually fast, while
67
+ * a test that is slow in most runs still does. A test is reported when its median is above the project's
68
+ * `durationBudgetMs` (a project without a budget is not judged on it), and, when a previous report is given, when it
69
+ * is more than `slowdownRatio` times its median in that report. A test whose previous median is under
70
+ * `slowdownMinMs` is not compared: a few milliseconds of jitter is not a slowdown. A test that failed, was skipped or
71
+ * is absent from the previous report is not judged: that is `reconcile-run`'s business and a first run has nothing to
72
+ * compare with. Tests are named as `reconcile-run` names them.
73
+ *
74
+ * @throws Error when an input is not Playwright JSON or the report holds no test of the project.
75
+ */
76
+ export function checkDurations(
77
+ report: unknown,
78
+ project: string,
79
+ quality: ProjectFacts["quality"],
80
+ previous?: unknown,
81
+ ): QualityFinding[] {
82
+ const current = translated(() => medianDurations(report, project, "report", true));
83
+ const before =
84
+ previous === undefined
85
+ ? new Map<string, number>()
86
+ : translated(() => medianDurations(previous, project, "previous", false));
87
+ const budget = quality.durationBudgetMs[project];
88
+ const findings: QualityFinding[] = [];
89
+ for (const [test, duration] of current) {
90
+ if (budget !== undefined && duration > budget) {
91
+ findings.push({ test, finding: `median ${duration} ms is above the ${budget} ms budget of project ${project}` });
92
+ }
93
+ const earlier = before.get(test);
94
+ if (
95
+ earlier !== undefined &&
96
+ earlier > 0 &&
97
+ earlier >= quality.slowdownMinMs &&
98
+ duration > earlier * quality.slowdownRatio
99
+ ) {
100
+ const times = (duration / earlier).toFixed(1);
101
+ findings.push({
102
+ test,
103
+ finding: `median ${duration} ms is ${times} times the previous ${earlier} ms, above the ${quality.slowdownRatio} times that quality.slowdownRatio allows`,
104
+ });
105
+ }
106
+ }
107
+ return findings;
108
+ }
109
+
110
+ if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
111
+ try {
112
+ const [reportFile, project, previousFile, ...extra] = process.argv.slice(2);
113
+ if (reportFile === undefined || project === undefined || extra.length > 0) {
114
+ throw new Error(
115
+ "test-duration: usage is node .claude/checks/test-duration.mts <report.json> <project> [<previous.json>]",
116
+ );
117
+ }
118
+ const findings = checkDurations(
119
+ translated(() => readJson(reportFile)),
120
+ project,
121
+ readProjectFacts().quality,
122
+ previousFile === undefined ? undefined : translated(() => readJson(previousFile)),
123
+ );
124
+ process.stdout.write(
125
+ findings.length === 0 ? "ok\n" : `${findings.map((f) => `${f.test}: ${f.finding}`).join("\n")}\n`,
126
+ );
127
+ if (findings.length > 0) {
128
+ process.exitCode = 1;
129
+ }
130
+ } catch (error) {
131
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
132
+ process.exitCode = 1;
133
+ }
134
+ }
@@ -0,0 +1,224 @@
1
+ import type { ProjectFacts } from "./project-facts.mts";
2
+
3
+ import { readFileSync } from "node:fs";
4
+ import { basename } from "node:path";
5
+
6
+ import { parse } from "@babel/parser";
7
+
8
+ import { readProjectFacts } from "./project-facts.mts";
9
+
10
+ export type QualityFinding = { test: string; finding: string };
11
+
12
+ type Limits = ProjectFacts["quality"];
13
+
14
+ type AstNode = Record<string, unknown> & { type: string; start: number; end: number };
15
+
16
+ type Shape = { steps: number; expects: number; conditionals: number; nesting: number };
17
+
18
+ const CLI_FILE_NAME = "test-shape.mts";
19
+ const TEST_NAME = "test";
20
+ const TEST_VARIANTS = ["only", "skip", "fixme", "fail"];
21
+ const STEP_NAME = "step";
22
+ const EXPECT_NAME = "expect";
23
+ const EXPECT_VARIANTS = ["soft", "poll"];
24
+ const TEST_FUNCTIONS = ["ArrowFunctionExpression", "FunctionExpression"];
25
+ const CALLS = ["CallExpression", "OptionalCallExpression"];
26
+ const MEMBERS = ["MemberExpression", "OptionalMemberExpression"];
27
+ const CONDITIONALS = [
28
+ "IfStatement",
29
+ "ConditionalExpression",
30
+ "SwitchStatement",
31
+ "WhileStatement",
32
+ "DoWhileStatement",
33
+ "ForStatement",
34
+ ];
35
+ const MIN_TEST_ARGUMENTS = 2;
36
+ const MAX_TITLE = 80;
37
+ const SKIPPED_KEYS = new Set(["loc", "extra", "leadingComments", "trailingComments", "innerComments", "comments"]);
38
+
39
+ function isRecord(value: unknown): value is Record<string, unknown> {
40
+ return typeof value === "object" && value !== null && !Array.isArray(value);
41
+ }
42
+
43
+ function isNode(value: unknown): value is AstNode {
44
+ return (
45
+ isRecord(value) &&
46
+ typeof value["type"] === "string" &&
47
+ typeof value["start"] === "number" &&
48
+ typeof value["end"] === "number"
49
+ );
50
+ }
51
+
52
+ function childrenOf(node: AstNode): AstNode[] {
53
+ const children: AstNode[] = [];
54
+ for (const [key, value] of Object.entries(node)) {
55
+ if (!SKIPPED_KEYS.has(key)) {
56
+ children.push(...(Array.isArray(value) ? value : [value]).filter(isNode));
57
+ }
58
+ }
59
+ return children;
60
+ }
61
+
62
+ function lineOf(node: AstNode, which: "start" | "end"): number {
63
+ const loc = node["loc"];
64
+ const position = isRecord(loc) ? loc[which] : undefined;
65
+ const line = isRecord(position) ? position["line"] : undefined;
66
+ return typeof line === "number" ? line : 0;
67
+ }
68
+
69
+ function nameOf(node: unknown): string | undefined {
70
+ return isNode(node) && node.type === "Identifier" && typeof node["name"] === "string" ? node["name"] : undefined;
71
+ }
72
+
73
+ function isMember(node: unknown): node is AstNode {
74
+ return isNode(node) && MEMBERS.includes(node.type) && node["computed"] !== true;
75
+ }
76
+
77
+ function isCall(node: AstNode): boolean {
78
+ return CALLS.includes(node.type);
79
+ }
80
+
81
+ function argumentsOf(call: AstNode): unknown[] {
82
+ const args = call["arguments"];
83
+ return Array.isArray(args) ? args : [];
84
+ }
85
+
86
+ function isMemberOf(callee: unknown, object: string, properties: readonly string[]): boolean {
87
+ return (
88
+ isMember(callee) && nameOf(callee["object"]) === object && properties.includes(nameOf(callee["property"]) ?? "")
89
+ );
90
+ }
91
+
92
+ function isTestCall(call: AstNode): boolean {
93
+ const callee = call["callee"];
94
+ const args = argumentsOf(call);
95
+ const last = args.at(-1);
96
+ return (
97
+ isCall(call) &&
98
+ (nameOf(callee) === TEST_NAME || isMemberOf(callee, TEST_NAME, TEST_VARIANTS)) &&
99
+ args.length >= MIN_TEST_ARGUMENTS &&
100
+ isNode(last) &&
101
+ TEST_FUNCTIONS.includes(last.type)
102
+ );
103
+ }
104
+
105
+ function isStepCall(node: AstNode): boolean {
106
+ return isCall(node) && isMemberOf(node["callee"], TEST_NAME, [STEP_NAME]);
107
+ }
108
+
109
+ function isExpectCall(node: AstNode): boolean {
110
+ const callee = node["callee"];
111
+ return isCall(node) && (nameOf(callee) === EXPECT_NAME || isMemberOf(callee, EXPECT_NAME, EXPECT_VARIANTS));
112
+ }
113
+
114
+ function measure(body: AstNode): Shape {
115
+ const shape: Shape = { steps: 0, expects: 0, conditionals: 0, nesting: 0 };
116
+ const visit = (node: AstNode, depth: number): void => {
117
+ const here = node.type === "BlockStatement" && node !== body ? depth + 1 : depth;
118
+ shape.nesting = Math.max(shape.nesting, here);
119
+ shape.steps += isStepCall(node) ? 1 : 0;
120
+ shape.expects += isExpectCall(node) ? 1 : 0;
121
+ shape.conditionals += CONDITIONALS.includes(node.type) ? 1 : 0;
122
+ for (const child of childrenOf(node)) {
123
+ visit(child, here);
124
+ }
125
+ };
126
+ visit(body, 0);
127
+ return shape;
128
+ }
129
+
130
+ function titleOf(call: AstNode, source: string): string {
131
+ const [title] = argumentsOf(call);
132
+ if (isNode(title) && title.type === "StringLiteral" && typeof title["value"] === "string") {
133
+ return title["value"].slice(0, MAX_TITLE);
134
+ }
135
+ return isNode(title) ? source.slice(title.start, title.end).replace(/\s+/g, " ").slice(0, MAX_TITLE) : "";
136
+ }
137
+
138
+ function collectTests(node: AstNode, found: AstNode[] = []): AstNode[] {
139
+ if (isTestCall(node)) {
140
+ found.push(node);
141
+ return found;
142
+ }
143
+ for (const child of childrenOf(node)) {
144
+ collectTests(child, found);
145
+ }
146
+ return found;
147
+ }
148
+
149
+ function parseSource(source: string, file: string): AstNode {
150
+ try {
151
+ const parsed: unknown = parse(source, { sourceType: "module", plugins: ["typescript"] });
152
+ if (isRecord(parsed) && isNode(parsed["program"])) {
153
+ return parsed["program"];
154
+ }
155
+ } catch (error) {
156
+ const reason = error instanceof Error ? (error.message.split("\n")[0] ?? "") : "";
157
+ throw new Error(`test-shape: ${file} cannot be parsed: ${reason}`);
158
+ }
159
+ throw new Error(`test-shape: ${file} cannot be parsed`);
160
+ }
161
+
162
+ function overLimit(count: number, limit: number, what: string, setting: string): string[] {
163
+ return count > limit ? [`${count} ${what}, more than the ${limit} that ${setting} allows`] : [];
164
+ }
165
+
166
+ /**
167
+ * Measures every `test(...)` (also `test.only`, `test.skip`, `test.fixme`, `test.fail` with a title and a function) in
168
+ * a spec's source against the project's `quality` limits, one finding per limit broken. The measure is static: a
169
+ * test counts once however often a table-driven loop runs it, and a `for ... of` or `for ... in` loop is not a
170
+ * conditional. Steps are `test.step` calls, expects are `expect`, `expect.soft` and `expect.poll` calls, nesting is
171
+ * the depth of blocks inside the test function (its own body not counted), conditionals are `if`, `?:`, `switch`,
172
+ * `while`, `do ... while` and `for (;;)`.
173
+ *
174
+ * @throws Error when the source cannot be parsed.
175
+ */
176
+ export function checkTestShape(source: string, file: string, limits: Limits): QualityFinding[] {
177
+ const findings: QualityFinding[] = [];
178
+ for (const call of collectTests(parseSource(source, file))) {
179
+ const fn = argumentsOf(call).at(-1);
180
+ if (!isNode(fn) || !isNode(fn["body"])) {
181
+ continue;
182
+ }
183
+ const test = `${file}:${lineOf(call, "start")} ${titleOf(call, source)}`;
184
+ const shape = measure(fn["body"]);
185
+ const lines = lineOf(call, "end") - lineOf(call, "start") + 1;
186
+ const reasons = [
187
+ ...overLimit(shape.steps, limits.maxSteps, "test.step calls", "quality.maxSteps"),
188
+ ...overLimit(lines, limits.maxLines, "lines", "quality.maxLines"),
189
+ ...overLimit(shape.expects, limits.maxExpects, "expect calls", "quality.maxExpects"),
190
+ ...overLimit(shape.nesting, limits.maxNesting, "levels of nesting", "quality.maxNesting"),
191
+ ...overLimit(shape.conditionals, limits.maxConditionals, "conditionals", "quality.maxConditionals"),
192
+ ];
193
+ findings.push(...reasons.map((finding) => ({ test, finding })));
194
+ }
195
+ return findings;
196
+ }
197
+
198
+ function readSpec(file: string): string {
199
+ try {
200
+ return readFileSync(file, "utf8");
201
+ } catch {
202
+ throw new Error(`test-shape: ${file} cannot be read`);
203
+ }
204
+ }
205
+
206
+ if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
207
+ try {
208
+ const files = process.argv.slice(2);
209
+ if (files.length === 0) {
210
+ throw new Error("test-shape: usage is node .claude/checks/test-shape.mts <spec>…");
211
+ }
212
+ const { quality } = readProjectFacts();
213
+ const findings = files.flatMap((file) => checkTestShape(readSpec(file), file, quality));
214
+ process.stdout.write(
215
+ findings.length === 0 ? "ok\n" : `${findings.map((f) => `${f.test}: ${f.finding}`).join("\n")}\n`,
216
+ );
217
+ if (findings.length > 0) {
218
+ process.exitCode = 1;
219
+ }
220
+ } catch (error) {
221
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
222
+ process.exitCode = 1;
223
+ }
224
+ }
@@ -0,0 +1,195 @@
1
+ import type { ProjectFacts, Route } from "./project-facts.mts";
2
+
3
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { basename, join } from "node:path";
5
+
6
+ import { readProjectFacts } from "./project-facts.mts";
7
+
8
+ export type TicketCard = {
9
+ key: string;
10
+ title: string;
11
+ type: string;
12
+ status: string;
13
+ description: string;
14
+ acceptanceCriteria: string[] | "none found";
15
+ links: { key: string; relation: string }[];
16
+ url: string;
17
+ route: Route;
18
+ capturedAt: string;
19
+ };
20
+
21
+ export const NO_ACCEPTANCE_CRITERIA = "none found";
22
+
23
+ const CLI_FILE_NAME = "ticket-card.mts";
24
+ const SAFE_FILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
25
+
26
+ function fail(path: string, problem: string): never {
27
+ throw new Error(`ticket card: ${path} ${problem}`);
28
+ }
29
+
30
+ function isRecord(value: unknown): value is Record<string, unknown> {
31
+ return typeof value === "object" && value !== null && !Array.isArray(value);
32
+ }
33
+
34
+ function asRecord(value: unknown, path: string): Record<string, unknown> {
35
+ if (!isRecord(value)) {
36
+ fail(path, "is not an object");
37
+ }
38
+ return value;
39
+ }
40
+
41
+ function present(source: Record<string, unknown>, key: string, path: string): unknown {
42
+ const value = source[key];
43
+ if (value === undefined) {
44
+ fail(path, "is missing");
45
+ }
46
+ return value;
47
+ }
48
+
49
+ function asString(value: unknown, path: string): string {
50
+ if (typeof value !== "string" || value === "") {
51
+ fail(path, "is not a non-empty string");
52
+ }
53
+ return value;
54
+ }
55
+
56
+ function asText(value: unknown, path: string): string {
57
+ if (typeof value !== "string") {
58
+ fail(path, "is not a string");
59
+ }
60
+ return value;
61
+ }
62
+
63
+ function checkSafeKey(key: string): void {
64
+ if (!SAFE_FILE_NAME.test(key) || key.includes("..")) {
65
+ fail("key", "is not a safe file name");
66
+ }
67
+ }
68
+
69
+ function parseKey(value: unknown, facts: ProjectFacts): string {
70
+ const key = asString(value, "key");
71
+ if (!new RegExp(facts.tracker.keyPattern).test(key)) {
72
+ fail("key", "does not match tracker.keyPattern");
73
+ }
74
+ checkSafeKey(key);
75
+ return key;
76
+ }
77
+
78
+ function parseAcceptanceCriteria(value: unknown): TicketCard["acceptanceCriteria"] {
79
+ if (value === NO_ACCEPTANCE_CRITERIA) {
80
+ return NO_ACCEPTANCE_CRITERIA;
81
+ }
82
+ if (!Array.isArray(value)) {
83
+ return fail("acceptanceCriteria", `is not a list or "${NO_ACCEPTANCE_CRITERIA}"`);
84
+ }
85
+ if (value.length === 0) {
86
+ return fail("acceptanceCriteria", `is empty, use "${NO_ACCEPTANCE_CRITERIA}"`);
87
+ }
88
+ return value.map((item, index) => asString(item, `acceptanceCriteria[${index}]`));
89
+ }
90
+
91
+ function parseLinks(value: unknown): TicketCard["links"] {
92
+ if (!Array.isArray(value)) {
93
+ return fail("links", "is not a list");
94
+ }
95
+ return value.map((item, index) => {
96
+ const path = `links[${index}]`;
97
+ const link = asRecord(item, path);
98
+ return {
99
+ key: asString(present(link, "key", `${path}.key`), `${path}.key`),
100
+ relation: asString(present(link, "relation", `${path}.relation`), `${path}.relation`),
101
+ };
102
+ });
103
+ }
104
+
105
+ function parseRoute(value: unknown, facts: ProjectFacts): Route {
106
+ switch (value) {
107
+ case "command":
108
+ case "cli":
109
+ case "api":
110
+ case "mcp":
111
+ case "paste":
112
+ if (!facts.tracker.routes.includes(value)) {
113
+ return fail("route", "is not allowed by tracker.routes");
114
+ }
115
+ return value;
116
+ default:
117
+ return fail("route", "is not a route");
118
+ }
119
+ }
120
+
121
+ function parseCapturedAt(value: unknown): string {
122
+ const text = asString(value, "capturedAt");
123
+ if (Number.isNaN(Date.parse(text)) || !/^\d{4}-\d{2}-\d{2}T/.test(text)) {
124
+ fail("capturedAt", "is not an ISO date");
125
+ }
126
+ return text;
127
+ }
128
+
129
+ /**
130
+ * Validates a ticket card against the project facts. A card is complete or it is rejected: there is no
131
+ * partial card.
132
+ *
133
+ * @throws Error `"ticket card: <path> <problem>"` naming the first missing or invalid field.
134
+ */
135
+ export function parseTicketCard(json: unknown, facts: ProjectFacts): TicketCard {
136
+ const root = asRecord(json, "card");
137
+ return {
138
+ key: parseKey(present(root, "key", "key"), facts),
139
+ title: asString(present(root, "title", "title"), "title"),
140
+ type: asString(present(root, "type", "type"), "type"),
141
+ status: asString(present(root, "status", "status"), "status"),
142
+ description: asText(present(root, "description", "description"), "description"),
143
+ acceptanceCriteria: parseAcceptanceCriteria(present(root, "acceptanceCriteria", "acceptanceCriteria")),
144
+ links: parseLinks(present(root, "links", "links")),
145
+ url: asString(present(root, "url", "url"), "url"),
146
+ route: parseRoute(present(root, "route", "route"), facts),
147
+ capturedAt: parseCapturedAt(present(root, "capturedAt", "capturedAt")),
148
+ };
149
+ }
150
+
151
+ /**
152
+ * Writes a validated card to `<dir>/tickets/<key>.json`, creating the directory. Overwrites an earlier card of
153
+ * the same ticket.
154
+ *
155
+ * @returns the path written.
156
+ * @throws Error `"ticket card: key is not a safe file name"` before anything is written.
157
+ */
158
+ export function writeTicketCard(card: TicketCard, dir: string): string {
159
+ checkSafeKey(card.key);
160
+ const directory = join(dir, "tickets");
161
+ mkdirSync(directory, { recursive: true });
162
+ const path = join(directory, `${card.key}.json`);
163
+ writeFileSync(path, `${JSON.stringify(card, null, 2)}\n`, "utf8");
164
+ return path;
165
+ }
166
+
167
+ function checkFile(file: string): TicketCard {
168
+ let text: string;
169
+ try {
170
+ text = readFileSync(file, "utf8");
171
+ } catch {
172
+ return fail(file, "cannot be read");
173
+ }
174
+ let json: unknown;
175
+ try {
176
+ json = JSON.parse(text);
177
+ } catch {
178
+ return fail(file, "is not valid JSON");
179
+ }
180
+ return parseTicketCard(json, readProjectFacts());
181
+ }
182
+
183
+ if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
184
+ try {
185
+ const [command, file] = process.argv.slice(2);
186
+ if (command !== "check" || file === undefined) {
187
+ throw new Error("ticket card: usage is node .claude/checks/ticket-card.mts check <file>");
188
+ }
189
+ const card = checkFile(file);
190
+ process.stdout.write(`ok ${card.key}\n`);
191
+ } catch (error) {
192
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
193
+ process.exitCode = 1;
194
+ }
195
+ }
@@ -0,0 +1,13 @@
1
+ # QA Coverage
2
+
3
+ Spawn the `qa-coverage` agent once to list what the stand offers, what the tests cover, and rank the gaps. It is
4
+ read-only and writes only a local report under `.qa/reports/`.
5
+
6
+ `$ARGUMENTS` optionally limits the scope to a module, a page or an API area. No arguments: the whole stand.
7
+
8
+ Dispatch the agent fresh with the scope and nothing else. Show the report path, the ranked gaps with their ids, and
9
+ the metrics. Do not plan anything; end with:
10
+ ```
11
+ Report: .qa/reports/<file>
12
+ Next: /qa-plan <gap id> to plan tests for a gap.
13
+ ```
@@ -0,0 +1,17 @@
1
+ # QA Explore
2
+
3
+ Spawn the `qa-explorer` agent once to map an area of the frontend or the API on the stand and write a report. It
4
+ writes no test code.
5
+
6
+ `$ARGUMENTS` is the area: a page, a module or an API area ("the cart page", "the orders API"). No arguments: ask
7
+ for one.
8
+
9
+ Dispatch the agent fresh with the area in the person's own words and nothing else. It reads `framework-rules` and
10
+ `project-facts`, explores read-only, and writes its report under `.qa/reports/`.
11
+
12
+ Show the report path and its findings: pages and selectors, missing test ids, operations, page-object proposals.
13
+ Do not start planning; end with:
14
+ ```
15
+ Report: .qa/reports/<file>
16
+ Next: /qa-plan "<area>" to plan tests for it, or /qa-coverage to see what is already tested.
17
+ ```
@@ -0,0 +1,44 @@
1
+ # QA Heal
2
+
3
+ Spawn the `qa-healer` agent once to run failing or flaky specs, classify each failure, and fix the test-side
4
+ defects in the healer paths of the project facts (page objects and data, never a spec). It never changes an expected
5
+ value or an assertion to match the build.
6
+
7
+ `$ARGUMENTS` is a spec file, a test title, or a run record path (`.qa/runs/<contract-name>/`). No arguments: ask for
8
+ one.
9
+
10
+ 1. Record a baseline and a fingerprint first: `node .claude/checks/expectation-guard.mts --snapshot` prints a git
11
+ tree id of the working tree, untracked files included; `node .claude/checks/expectation-guard.mts
12
+ --repo-fingerprint` prints one sha of `.git/config`, `.git/info/`, `.git/hooks/`, the directory `core.hooksPath`
13
+ names and `.qa/project.json` (it only reads; it is yours, the healer may not run it). When `--repo-fingerprint`
14
+ exits non-zero or prints anything but 64 lowercase hexadecimal characters (a configuration file under a healer
15
+ path, for one), show the person "fingerprint could not be computed:" followed by its stderr line, and do not
16
+ dispatch the healer. Then store the guard recipe as the baseline holds it:
17
+ `GIT_NO_LAZY_FETCH=1 git --no-replace-objects -c core.fsmonitor=false cat-file blob <baseline tree id>:.claude/skills/heal-tests/guard-recipe.md`
18
+ prints it; keep that text, and when it prints nothing, do not dispatch the healer. Dispatch the agent fresh with
19
+ the target and that baseline id, nothing else. It re-runs, classifies (test defect, product defect, stand data,
20
+ flaky), fixes page objects, data and waits, and stops after three rounds.
21
+ 2. Run the recipe you stored in step 1 word for word: its shell block with the baseline id and the fingerprint of
22
+ step 1, and what each outcome means. Never read `.claude/skills/heal-tests/guard-recipe.md` from the working tree
23
+ after the heal: the healer runs test code, which can rewrite any file, the recipe included. A guard that is not
24
+ clean ends here: show it to the person and offer no review.
25
+ 3. Present what it fixed, what it classified as a product defect (the test stays failing; a person files the
26
+ ticket and adds its link as an `issue` annotation, never a patch), and what it escalated. A stand that was not
27
+ reachable is "not done".
28
+
29
+ The heal belongs to a run record when the target is a run record `.qa/runs/<contract-name>/` and
30
+ `.qa/contracts/<contract-name>.md` exists. For a spec file or a test title, look before step 1: count the run records
31
+ whose `list.<project>.json` names the spec (or, for a title, a spec that holds it). Exactly one, and
32
+ `.qa/contracts/<contract-name>.md` exists: the heal belongs to it. Otherwise (zero, several, or no contract file): say
33
+ so; the review runs without a contract.
34
+
35
+ When the heal belongs to a run record, do what `/qa` does after a heal: the recipe's "After a Clean Guard", word for
36
+ word, with that record and contract.
37
+
38
+ When code changed and the guard is clean, end with the review command, its `healer:` line filled in from the guard
39
+ recipe (the baseline id, then the `healed tree`). Put the contract path first only when that re-run reconciled with
40
+ exit 0 on every project; otherwise leave it out, since `/qa-review` would reconcile a record that is not the healed one:
41
+ ```
42
+ Heal complete. Run /qa-review <contract path or nothing> healer: <baseline tree id> <new tree id> to review the changes.
43
+ ```
44
+ Without a clean guard, name no `healer:` line and offer no review.