@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,270 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { basename } from "node:path";
3
+
4
+ export type RunFailure = {
5
+ test: string;
6
+ project: string;
7
+ why:
8
+ | "failed"
9
+ | "flaky"
10
+ | "missing from the report"
11
+ | "skipped without a reason"
12
+ | "expected failure without a reason";
13
+ };
14
+
15
+ export type RunVerdict = {
16
+ expected: number;
17
+ passed: number;
18
+ explainedSkips: number;
19
+ failures: RunFailure[];
20
+ };
21
+
22
+ type Annotation = { type: string; description: string };
23
+
24
+ type Outcome = { status: string; expectedStatus: string; annotations: Annotation[] };
25
+
26
+ type Listed = { test: string; project: string };
27
+
28
+ const CLI_FILE_NAME = "reconcile-run.mts";
29
+ const TITLE_SEPARATOR = " › ";
30
+ const SKIP_ANNOTATIONS = ["skip", "fixme"];
31
+ const FAIL_ANNOTATIONS = ["fail"];
32
+
33
+ /**
34
+ * An input that is not what the tool reads. `what` is the message without the tool's name, so another module that
35
+ * reads the same files can say it under its own name.
36
+ */
37
+ export class InputError extends Error {
38
+ readonly what: string;
39
+
40
+ constructor(what: string) {
41
+ super(`reconcile: ${what}`);
42
+ this.what = what;
43
+ }
44
+ }
45
+
46
+ function notPlaywrightJson(label: string): never {
47
+ throw new InputError(`the ${label} is not Playwright JSON`);
48
+ }
49
+
50
+ export function isRecord(value: unknown): value is Record<string, unknown> {
51
+ return typeof value === "object" && value !== null && !Array.isArray(value);
52
+ }
53
+
54
+ export function listOf(value: unknown, label: string): unknown[] {
55
+ if (value === undefined) {
56
+ return [];
57
+ }
58
+ return Array.isArray(value) ? value : notPlaywrightJson(label);
59
+ }
60
+
61
+ export function textOf(value: unknown, label: string): string {
62
+ return typeof value === "string" ? value : notPlaywrightJson(label);
63
+ }
64
+
65
+ function annotationsOf(value: unknown, label: string): Annotation[] {
66
+ return listOf(value, label).map((item) => {
67
+ if (!isRecord(item)) {
68
+ return notPlaywrightJson(label);
69
+ }
70
+ const description = item["description"];
71
+ return { type: textOf(item["type"], label), description: typeof description === "string" ? description : "" };
72
+ });
73
+ }
74
+
75
+ function walk(
76
+ suite: unknown,
77
+ titles: readonly string[],
78
+ file: string,
79
+ label: string,
80
+ visit: (test: string, entry: Record<string, unknown>) => void,
81
+ ): void {
82
+ if (!isRecord(suite)) {
83
+ notPlaywrightJson(label);
84
+ }
85
+ for (const spec of listOf(suite["specs"], label)) {
86
+ if (!isRecord(spec)) {
87
+ notPlaywrightJson(label);
88
+ }
89
+ const test = [file, ...titles, textOf(spec["title"], label)].join(TITLE_SEPARATOR);
90
+ const entries = spec["tests"];
91
+ if (!Array.isArray(entries)) {
92
+ notPlaywrightJson(label);
93
+ }
94
+ for (const entry of entries) {
95
+ if (!isRecord(entry)) {
96
+ notPlaywrightJson(label);
97
+ }
98
+ visit(test, entry);
99
+ }
100
+ }
101
+ for (const child of listOf(suite["suites"], label)) {
102
+ if (!isRecord(child)) {
103
+ notPlaywrightJson(label);
104
+ }
105
+ walk(child, [...titles, textOf(child["title"], label)], file, label, visit);
106
+ }
107
+ }
108
+
109
+ function describeError(error: unknown): string {
110
+ const message = isRecord(error) ? error["message"] : undefined;
111
+ const text = typeof message === "string" ? message : JSON.stringify(error);
112
+ return (text.trim().split("\n")[0] ?? "").trim();
113
+ }
114
+
115
+ /**
116
+ * Walks every test entry of a Playwright JSON report or list in file order, naming it `<file> › <describe titles> ›
117
+ * <test title>`: the one name every module that reads these files uses for a test.
118
+ *
119
+ * @throws InputError when the input is not Playwright JSON, has no suites or has `errors`.
120
+ */
121
+ export function walkRoot(
122
+ root: unknown,
123
+ label: string,
124
+ visit: (test: string, entry: Record<string, unknown>) => void,
125
+ ): void {
126
+ if (!isRecord(root) || !Array.isArray(root["suites"])) {
127
+ throw new InputError(`the ${label} has no suites`);
128
+ }
129
+ const errors = listOf(root["errors"], label);
130
+ if (errors.length > 0) {
131
+ throw new InputError(`the ${label} has errors: ${errors.map(describeError).join("; ")}`);
132
+ }
133
+ for (const fileSuite of root["suites"]) {
134
+ if (!isRecord(fileSuite)) {
135
+ notPlaywrightJson(label);
136
+ }
137
+ const file = textOf(fileSuite["file"] ?? fileSuite["title"], label);
138
+ walk(fileSuite, [], file, label, visit);
139
+ }
140
+ }
141
+
142
+ function listedTests(listed: unknown): Listed[] {
143
+ const tests: Listed[] = [];
144
+ walkRoot(listed, "list", (test, entry) => {
145
+ tests.push({ test, project: textOf(entry["projectName"], "list") });
146
+ });
147
+ return tests;
148
+ }
149
+
150
+ function key(test: string, project: string): string {
151
+ return `${project}\u0000${test}`;
152
+ }
153
+
154
+ function reportedOutcomes(report: unknown): Map<string, Outcome[]> {
155
+ const outcomes = new Map<string, Outcome[]>();
156
+ walkRoot(report, "report", (test, entry) => {
157
+ const id = key(test, textOf(entry["projectName"], "report"));
158
+ outcomes.set(id, [
159
+ ...(outcomes.get(id) ?? []),
160
+ {
161
+ status: textOf(entry["status"], "report"),
162
+ expectedStatus: textOf(entry["expectedStatus"], "report"),
163
+ annotations: annotationsOf(entry["annotations"], "report"),
164
+ },
165
+ ]);
166
+ });
167
+ return outcomes;
168
+ }
169
+
170
+ function isExplained(annotations: readonly Annotation[], types: readonly string[]): boolean {
171
+ return annotations.some(({ type, description }) => types.includes(type) && description.trim() !== "");
172
+ }
173
+
174
+ type Judgement = { kind: "passed" } | { kind: "explained" } | { kind: "failure"; why: RunFailure["why"] };
175
+
176
+ function judge(outcome: Outcome): Judgement {
177
+ if (outcome.status === "expected") {
178
+ return outcome.expectedStatus === "failed" && !isExplained(outcome.annotations, FAIL_ANNOTATIONS)
179
+ ? { kind: "failure", why: "expected failure without a reason" }
180
+ : { kind: "passed" };
181
+ }
182
+ if (outcome.status === "flaky") {
183
+ return { kind: "failure", why: "flaky" };
184
+ }
185
+ if (outcome.status !== "skipped") {
186
+ return { kind: "failure", why: "failed" };
187
+ }
188
+ if (outcome.expectedStatus !== "skipped") {
189
+ return { kind: "failure", why: "missing from the report" };
190
+ }
191
+ return isExplained(outcome.annotations, SKIP_ANNOTATIONS)
192
+ ? { kind: "explained" }
193
+ : { kind: "failure", why: "skipped without a reason" };
194
+ }
195
+
196
+ /**
197
+ * Decides from Playwright's own records whether a run is done: every listed test (`--list --reporter=json`) is in the
198
+ * report (JSON reporter) of the same project, none failed or was flaky, and every skip has a reason. A skip is
199
+ * explained by a `skip` or `fixme` annotation with a description, an expected failure by a `fail` annotation with a
200
+ * description; a test the runner never started (skipped though it expected to run) counts as missing. A test listed
201
+ * more than once (`--repeat-each`) is reconciled entry by entry and a missing entry fails; a failing report entry
202
+ * beyond the listed count still fails, a passing one is ignored. Tests in the report that were not listed are ignored.
203
+ *
204
+ * @throws Error when an input is not Playwright JSON, has `errors`, or the list holds no tests.
205
+ */
206
+ export function reconcileRun(listed: unknown, report: unknown): RunVerdict {
207
+ const tests = listedTests(listed);
208
+ const outcomes = reportedOutcomes(report);
209
+ if (tests.length === 0) {
210
+ throw new Error("reconcile: the list contains no tests");
211
+ }
212
+ const verdict: RunVerdict = { expected: tests.length, passed: 0, explainedSkips: 0, failures: [] };
213
+ const listedCount = new Map<string, Listed & { count: number }>();
214
+ for (const { test, project } of tests) {
215
+ const id = key(test, project);
216
+ listedCount.set(id, { test, project, count: (listedCount.get(id)?.count ?? 0) + 1 });
217
+ }
218
+ for (const [id, { test, project, count }] of listedCount) {
219
+ const reported = outcomes.get(id) ?? [];
220
+ const judged: Judgement[] = reported.map(judge);
221
+ for (let missing = reported.length; missing < count; missing += 1) {
222
+ judged.push({ kind: "failure", why: "missing from the report" });
223
+ }
224
+ for (const judgement of judged) {
225
+ if (judgement.kind === "failure") {
226
+ verdict.failures.push({ test, project, why: judgement.why });
227
+ }
228
+ }
229
+ const room = Math.max(0, count - judged.filter(({ kind }) => kind === "failure").length);
230
+ for (const { kind } of judged.filter(({ kind }) => kind !== "failure").slice(0, room)) {
231
+ if (kind === "passed") {
232
+ verdict.passed += 1;
233
+ } else {
234
+ verdict.explainedSkips += 1;
235
+ }
236
+ }
237
+ }
238
+ return verdict;
239
+ }
240
+
241
+ export function readJson(file: string): unknown {
242
+ let text: string;
243
+ try {
244
+ text = readFileSync(file, "utf8");
245
+ } catch {
246
+ throw new InputError(`${file} cannot be read`);
247
+ }
248
+ try {
249
+ return JSON.parse(text);
250
+ } catch {
251
+ throw new InputError(`${file} is not valid JSON`);
252
+ }
253
+ }
254
+
255
+ if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
256
+ try {
257
+ const [listFile, reportFile] = process.argv.slice(2);
258
+ if (listFile === undefined || reportFile === undefined) {
259
+ throw new Error("reconcile: usage is node .claude/checks/reconcile-run.mts <list.json> <report.json>");
260
+ }
261
+ const verdict = reconcileRun(readJson(listFile), readJson(reportFile));
262
+ process.stdout.write(`${JSON.stringify(verdict, null, 2)}\n`);
263
+ if (verdict.failures.length > 0) {
264
+ process.exitCode = 1;
265
+ }
266
+ } catch (error) {
267
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
268
+ process.exitCode = 1;
269
+ }
270
+ }
@@ -0,0 +1,351 @@
1
+ import type { ProjectFacts } from "./project-facts.mts";
2
+
3
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
4
+ import { basename, join, relative } from "node:path";
5
+
6
+ import { ROLE_PURPOSES, readProjectFacts } from "./project-facts.mts";
7
+
8
+ export type PromptFinding = { file: string; line: number; finding: string };
9
+
10
+ export const PROMPT_DIRS = [".claude/agents", ".claude/skills", ".claude/commands", ".claude/hooks"] as const;
11
+ export const SETTINGS_PATH = ".claude/settings.json";
12
+ export const MODULES_DIR = ".claude/checks";
13
+ export const OURS_ONLY_PATH = ".claude/checks/ours-only.json";
14
+ export const CLIENT_TERMS_PATH = ".qa/client-terms.local.txt";
15
+ export const MAX_AGENT_CHARS = 8000;
16
+ export const EXAMPLE_HEADING = "Example from this repository";
17
+ export const HIDES_FILE = "example section hides the file";
18
+ export const ALLOWED_HOSTS = ["localhost", "127.0.0.1", "::1", "example.com", "api.github.com"] as const;
19
+
20
+ const CLI_FILE_NAME = "scan-prompts.mts";
21
+ const SKILLS_DIR = ".claude/skills";
22
+ const AGENTS_DIR = ".claude/agents/";
23
+ const HEADING = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
24
+ const FENCE_OPEN = /^\s*(`{3,}|~{3,})/;
25
+ const FENCE_CLOSE = /^\s*(`{3,}|~{3,})\s*$/;
26
+ const URL_HOST = /\b[a-z][a-z0-9+.-]*:\/\/(?:[^/@\s]*@)?(\[[0-9a-f:.]+\]|[^\s/:?#)"'`>\]<\\]+)/gi;
27
+ const BARE_HOST = /\b[a-z0-9-]+(?:\.[a-z0-9-]+)+(?![a-z0-9-]|\.[a-z0-9-]|\()/gi;
28
+ const TOP_LEVEL_DOMAINS = [
29
+ "com",
30
+ "net",
31
+ "org",
32
+ "io",
33
+ "dev",
34
+ "app",
35
+ "cloud",
36
+ "biz",
37
+ "info",
38
+ "co",
39
+ "us",
40
+ "eu",
41
+ "br",
42
+ "pl",
43
+ "nl",
44
+ "de",
45
+ "uk",
46
+ ];
47
+ const IPV4 = /\b\d{1,3}(?:\.\d{1,3}){3}\b/g;
48
+ const MARKDOWN_EXTENSION = /\.md$/i;
49
+ const EXTENSION = /\.[^./]+$/;
50
+ const TRAILING_PUNCTUATION = /[.,;:)]+$/;
51
+ const BRACKETS = /^\[|\]$/g;
52
+ const MIN_EXAMPLE_LEVEL = 2;
53
+ const MAX_EXAMPLE_LEVEL = 3;
54
+ const MAX_EXAMPLE_SHARE = 0.5;
55
+ const NUL = "\0";
56
+ const REGEX_SPECIALS = /[.*+?^${}()|[\]\\]/g;
57
+ const SEPARATORS = /[\s_-]+/;
58
+ const LETTERS_AND_SEPARATORS = /^[\p{L}\s_-]+$/u;
59
+ const CAMEL_CASE_BREAK = /(?=[A-Z])/;
60
+ const PURPOSE_WORDS = new Set(
61
+ ROLE_PURPOSES.flatMap((purpose) => [purpose, ...purpose.split(CAMEL_CASE_BREAK)].map((word) => word.toLowerCase())),
62
+ );
63
+
64
+ type Word = { term: string; pattern: RegExp };
65
+ type Rules = { accounts: string[]; domains: string[]; terms: string[]; words: Word[] };
66
+ type Heading = { index: number; level: number; text: string };
67
+ type ExampleSection = { start: number; end: number; level: number };
68
+
69
+ function isAllowedHost(host: string): boolean {
70
+ const name = host.toLowerCase().replace(BRACKETS, "");
71
+ return ALLOWED_HOSTS.some((allowed) => name === allowed) || name.endsWith(".example.com");
72
+ }
73
+
74
+ function isPlaceholder(host: string): boolean {
75
+ return host.startsWith("$") || host.includes("{");
76
+ }
77
+
78
+ function hostFindings(text: string): string[] {
79
+ const found: string[] = [];
80
+ const consider = (raw: string): void => {
81
+ const host = raw.replace(TRAILING_PUNCTUATION, "");
82
+ if (host !== "" && !isPlaceholder(host) && !isAllowedHost(host)) {
83
+ found.push(`host "${host.toLowerCase()}"`);
84
+ }
85
+ };
86
+ for (const match of text.matchAll(URL_HOST)) {
87
+ consider(match[1] ?? "");
88
+ }
89
+ for (const match of text.matchAll(BARE_HOST)) {
90
+ if (TOP_LEVEL_DOMAINS.includes((match[0].split(".").pop() ?? "").toLowerCase())) {
91
+ consider(match[0]);
92
+ }
93
+ }
94
+ for (const match of text.matchAll(IPV4)) {
95
+ consider(match[0]);
96
+ }
97
+ return found;
98
+ }
99
+
100
+ function listFiles(directory: string): string[] {
101
+ if (!existsSync(directory)) {
102
+ return [];
103
+ }
104
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
105
+ const path = join(directory, entry.name);
106
+ return entry.isDirectory() ? listFiles(path) : [path];
107
+ });
108
+ }
109
+
110
+ function readOursOnly(root: string): string[] {
111
+ const path = join(root, OURS_ONLY_PATH);
112
+ if (!existsSync(path)) {
113
+ return [];
114
+ }
115
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
116
+ if (!Array.isArray(parsed) || parsed.some((item) => typeof item !== "string")) {
117
+ throw new Error(`${OURS_ONLY_PATH} is not a list of names`);
118
+ }
119
+ return parsed.filter((item): item is string => typeof item === "string");
120
+ }
121
+
122
+ function normaliseTerms(terms: string[]): string[] {
123
+ return terms.map((term) => term.trim().toLowerCase()).filter((term) => term !== "" && !term.startsWith("#"));
124
+ }
125
+
126
+ function readClientTerms(root: string): string[] {
127
+ const path = join(root, CLIENT_TERMS_PATH);
128
+ return existsSync(path) ? normaliseTerms(readFileSync(path, "utf8").split(/\r?\n/)) : [];
129
+ }
130
+
131
+ function isOursOnly(path: string, oursOnly: string[]): boolean {
132
+ return oursOnly.some((name) => {
133
+ if (path.startsWith(`${SKILLS_DIR}/${name}/`)) {
134
+ return true;
135
+ }
136
+ return PROMPT_DIRS.filter((dir) => dir !== SKILLS_DIR).some(
137
+ (dir) => path.startsWith(`${dir}/`) && path.slice(dir.length + 1).replace(EXTENSION, "") === name,
138
+ );
139
+ });
140
+ }
141
+
142
+ function domainsOf(accounts: string[]): string[] {
143
+ return accounts.flatMap((account) => {
144
+ const at = account.lastIndexOf("@");
145
+ return at < 0 ? [] : [account.slice(at + 1)];
146
+ });
147
+ }
148
+
149
+ /**
150
+ * The role and permission names to look for. A name that is a purpose or a word of one (`admin`, `customer`, `other`)
151
+ * is matched only in its exact spelling, in quotes (see {@link quotedPattern}), and only when that spelling is not all
152
+ * lower case; an all-lower-case one is not checked (a known limit), since it is the shipped files' own vocabulary.
153
+ */
154
+ function wordsOf(facts: ProjectFacts): Word[] {
155
+ const names = [
156
+ ...Object.keys(facts.roles),
157
+ ...Object.values(facts.roleFor),
158
+ ...Object.values(facts.rolePermissions ?? {}).flat(),
159
+ ...Object.values(facts.passwordFor ?? {}),
160
+ ]
161
+ .map((name) => name.trim())
162
+ .filter((name) => name !== "" && !name.startsWith("#"));
163
+ const words = new Map<string, Word>();
164
+ for (const name of names) {
165
+ const term = name.toLowerCase();
166
+ if (!PURPOSE_WORDS.has(term)) {
167
+ words.set(term, { term, pattern: wordPattern(term) });
168
+ } else if (name !== term) {
169
+ words.set(name, { term: name, pattern: quotedPattern(name) });
170
+ }
171
+ }
172
+ return [...words.values()];
173
+ }
174
+
175
+ /** The term with its separators (any run of spaces, `_` or `-`) matching any such run, and the rest escaped. */
176
+ function termBody(term: string): string {
177
+ return term
178
+ .split(SEPARATORS)
179
+ .filter((part) => part !== "")
180
+ .map((part) => part.replace(REGEX_SPECIALS, "\\$&"))
181
+ .join("[\\s_-]+");
182
+ }
183
+
184
+ /**
185
+ * Matches `term` as a whole word in any letter case: a space, `_` or `-` in it matches any run of spaces, `_` or `-`,
186
+ * and a term of letters and those separators also matches with a trailing `s`. A `-` counts as part of a word at
187
+ * the edges, so "pre-sales rep" is not "sales rep". A term split over two lines is not found.
188
+ */
189
+ function wordPattern(term: string): RegExp {
190
+ const plural = LETTERS_AND_SEPARATORS.test(term) ? "s?" : "";
191
+ return new RegExp(`(?<![\\p{L}\\p{N}_-])${termBody(term)}${plural}(?![\\p{L}\\p{N}_-])`, "iu");
192
+ }
193
+
194
+ /**
195
+ * Matches a role named like a purpose or a word of one only where it is written as a name, in its exact spelling:
196
+ * alone inside quotes or backticks, spelled as the `roles` key is. Prose such as "a customer signs in",
197
+ * another spelling and the `roleFor.<purpose>` tokens are left alone. It applies to the `.claude/checks/` modules
198
+ * too: their own purpose names are lower case, so only a role's exact, capitalised spelling is found there.
199
+ */
200
+ function quotedPattern(name: string): RegExp {
201
+ return new RegExp(`(?<!roleFor\\[)(["'\`])${name.replace(REGEX_SPECIALS, "\\$&")}\\1`, "u");
202
+ }
203
+
204
+ function scanLine(text: string, rules: Rules): string[] {
205
+ const lower = text.toLowerCase();
206
+ const found = [
207
+ ...rules.accounts.filter((account) => lower.includes(account)).map((account) => `role account "${account}"`),
208
+ ...rules.domains.filter((domain) => lower.includes(domain)).map((domain) => `role domain "${domain}"`),
209
+ ...rules.terms.filter((term) => lower.includes(term)).map((term) => `client term "${term}"`),
210
+ ...rules.words.filter(({ pattern }) => pattern.test(text)).map(({ term }) => `project term "${term}"`),
211
+ ...hostFindings(text),
212
+ ];
213
+ return [...new Set(found)];
214
+ }
215
+
216
+ function headingsOf(lines: string[]): Heading[] {
217
+ const headings: Heading[] = [];
218
+ let fence = "";
219
+ lines.forEach((text, index) => {
220
+ if (fence !== "") {
221
+ const closing = FENCE_CLOSE.exec(text)?.[1] ?? "";
222
+ if (closing.startsWith(fence.charAt(0)) && closing.length >= fence.length) {
223
+ fence = "";
224
+ }
225
+ return;
226
+ }
227
+ const opening = FENCE_OPEN.exec(text)?.[1];
228
+ if (opening !== undefined) {
229
+ fence = opening;
230
+ return;
231
+ }
232
+ const heading = HEADING.exec(text);
233
+ if (heading !== null) {
234
+ headings.push({ index, level: (heading[1] ?? "").length, text: heading[2] ?? "" });
235
+ }
236
+ });
237
+ return headings;
238
+ }
239
+
240
+ function exampleSections(lines: string[], headings: Heading[]): ExampleSection[] {
241
+ const sections: ExampleSection[] = [];
242
+ let coveredUntil = -1;
243
+ headings.forEach((heading, position) => {
244
+ if (heading.text !== EXAMPLE_HEADING || heading.index <= coveredUntil) {
245
+ return;
246
+ }
247
+ const next = headings.slice(position + 1).find((other) => other.level <= heading.level);
248
+ const end = next === undefined ? lines.length : next.index;
249
+ coveredUntil = end - 1;
250
+ sections.push({ start: heading.index, end, level: heading.level });
251
+ });
252
+ return sections;
253
+ }
254
+
255
+ function isMisplaced(section: ExampleSection, firstHeadingIndex: number): boolean {
256
+ return section.level < MIN_EXAMPLE_LEVEL || section.level > MAX_EXAMPLE_LEVEL || section.start === firstHeadingIndex;
257
+ }
258
+
259
+ function nonEmptyLines(lines: string[], from: number, to: number): number {
260
+ return lines.slice(from, to).filter((line) => line.trim() !== "").length;
261
+ }
262
+
263
+ function hiddenSections(lines: string[], sections: ExampleSection[], firstHeading: number): ExampleSection[] {
264
+ const placed = sections.filter((section) => !isMisplaced(section, firstHeading));
265
+ const covered = placed.reduce((sum, section) => sum + nonEmptyLines(lines, section.start, section.end), 0);
266
+ const tooMuch = covered > nonEmptyLines(lines, 0, lines.length) * MAX_EXAMPLE_SHARE;
267
+ return sections.filter((section) => isMisplaced(section, firstHeading) || tooMuch);
268
+ }
269
+
270
+ function scanFile(file: string, content: string, rules: Rules): PromptFinding[] {
271
+ const findings: PromptFinding[] = [];
272
+ const lines = content.replaceAll("\r\n", "\n").split("\n");
273
+ const headings = headingsOf(lines);
274
+ const ignored = new Set<number>();
275
+ const sections = exampleSections(lines, headings);
276
+ const refused = new Set(hiddenSections(lines, sections, headings[0]?.index ?? -1));
277
+ for (const section of sections) {
278
+ if (refused.has(section)) {
279
+ findings.push({ file, line: section.start + 1, finding: HIDES_FILE });
280
+ continue;
281
+ }
282
+ for (let index = section.start; index < section.end; index += 1) {
283
+ ignored.add(index);
284
+ }
285
+ }
286
+ lines.forEach((text, index) => {
287
+ if (!ignored.has(index)) {
288
+ for (const finding of scanLine(text, rules)) {
289
+ findings.push({ file, line: index + 1, finding });
290
+ }
291
+ }
292
+ });
293
+ const length = lines.join("\n").length;
294
+ if (file.startsWith(AGENTS_DIR) && MARKDOWN_EXTENSION.test(file) && length > MAX_AGENT_CHARS) {
295
+ findings.push({ file, line: 1, finding: `agent file has ${length} characters, at most ${MAX_AGENT_CHARS}` });
296
+ }
297
+ return findings;
298
+ }
299
+
300
+ function shippedFiles(root: string): string[] {
301
+ const moduleDir = join(root, MODULES_DIR);
302
+ const modules = listFiles(moduleDir).filter(
303
+ (path) => relative(moduleDir, path).split(/[\\/]/).length === 1 && path.endsWith(".mts"),
304
+ );
305
+ const settings = existsSync(join(root, SETTINGS_PATH)) ? [join(root, SETTINGS_PATH)] : [];
306
+ return [...PROMPT_DIRS.flatMap((dir) => listFiles(join(root, dir))), ...settings, ...modules];
307
+ }
308
+
309
+ /**
310
+ * Scans the shipped agents, skills, commands, hooks, settings and `.claude/checks/*.mts` modules for client facts: role
311
+ * accounts and their email domains, any host (URL with any scheme, bare hostname or IPv4 address) outside
312
+ * {@link ALLOWED_HOSTS}, terms from `.qa/client-terms.local.txt` and `extraTerms`, the facts' role names (`roles` keys,
313
+ * `roleFor` values) and `rolePermissions` permission names as whole words in any letter case (see {@link wordPattern};
314
+ * a term split over two lines is a known gap), a role named like a purpose only in its exact spelling in quotes or
315
+ * backticks, when that spelling is not all lower case (see {@link quotedPattern}), and agent
316
+ * files over
317
+ * {@link MAX_AGENT_CHARS} characters. Names in `.claude/checks/ours-only.json` are skipped by exact path; a section under
318
+ * a level 2 or 3 heading "Example from this repository" is skipped unless it is the file's first heading or
319
+ * holds more than half of its non-empty lines, which is itself a finding.
320
+ */
321
+ export function scanPrompts(root: string, facts: ProjectFacts, extraTerms: string[] = []): PromptFinding[] {
322
+ const oursOnly = readOursOnly(root);
323
+ const accounts = Object.values(facts.roles).map((account) => account.toLowerCase());
324
+ const rules: Rules = {
325
+ accounts,
326
+ domains: domainsOf(accounts),
327
+ terms: [...readClientTerms(root), ...normaliseTerms(extraTerms)],
328
+ words: wordsOf(facts),
329
+ };
330
+ return shippedFiles(root)
331
+ .map((path) => relative(root, path).replaceAll("\\", "/"))
332
+ .filter((path) => !isOursOnly(path, oursOnly))
333
+ .sort()
334
+ .flatMap((path) => {
335
+ const content = readFileSync(join(root, path), "utf8");
336
+ return content.includes(NUL) ? [] : scanFile(path, content, rules);
337
+ });
338
+ }
339
+
340
+ if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
341
+ try {
342
+ const findings = scanPrompts(process.cwd(), readProjectFacts());
343
+ for (const { file, line, finding } of findings) {
344
+ process.stdout.write(`${file}:${line} ${finding}\n`);
345
+ }
346
+ process.exitCode = findings.length === 0 ? 0 : 1;
347
+ } catch (error) {
348
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
349
+ process.exitCode = 1;
350
+ }
351
+ }
@@ -0,0 +1,45 @@
1
+ import { basename } from "node:path";
2
+
3
+ import { runVariables, signInStatus } from "./browser-secrets.mts";
4
+
5
+ const CLI_FILE_NAME = "stand.mts";
6
+ const ORIGINS = [
7
+ ["frontend", "FRONTEND_BASE_URL"],
8
+ ["backend", "BACKEND_BASE_URL"],
9
+ ] as const;
10
+
11
+ export type StandOrigins = Record<(typeof ORIGINS)[number][0], string>;
12
+
13
+ /**
14
+ * The origins of the stand the tests run against, from `FRONTEND_BASE_URL` and `BACKEND_BASE_URL` in the run's
15
+ * variables (`runVariables`: the shell over the suite's `.env`). Only the origin of each is returned (scheme, host and
16
+ * port), never a path, a query or user info, so the read-only agents learn where the stand is without reading `.env`.
17
+ * This is the one exception to "never print `.env`": the origins and nothing else.
18
+ *
19
+ * @throws Error naming the variable that is unset or not an http or https address.
20
+ */
21
+ export function standOrigins(vars: Readonly<Record<string, string | undefined>>): StandOrigins {
22
+ const origins: Partial<StandOrigins> = {};
23
+ for (const [name, variable] of ORIGINS) {
24
+ const value = vars[variable] ?? "";
25
+ const url = URL.parse(value);
26
+ if (url === null || (url.protocol !== "http:" && url.protocol !== "https:")) {
27
+ throw new Error(`stand: ${variable} is ${value === "" ? "not set" : "not an http or https address"}`);
28
+ }
29
+ origins[name] = url.origin;
30
+ }
31
+ return origins as StandOrigins;
32
+ }
33
+
34
+ if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
35
+ try {
36
+ const projectDir = process.cwd();
37
+ const origins = standOrigins(runVariables(projectDir));
38
+ process.stdout.write(
39
+ `frontend: ${origins.frontend}\nbackend: ${origins.backend}\nsign-in: ${signInStatus(projectDir)}\n`,
40
+ );
41
+ } catch (error) {
42
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
43
+ process.exitCode = 1;
44
+ }
45
+ }