@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
@@ -0,0 +1,584 @@
1
+ import type { ContractReferences } from "./contract.mts";
2
+
3
+ import { execFileSync } from "node:child_process";
4
+ import { lstatSync, readdirSync, readFileSync, realpathSync, rmSync } from "node:fs";
5
+ import { basename, isAbsolute, join, relative, resolve } from "node:path";
6
+
7
+ import { contractReferences, namesCase } from "./contract.mts";
8
+ import { ROOT_SUITE_DIR, readProjectFacts } from "./project-facts.mts";
9
+ import { EXPLORER_WRITE_DIR, HEALER_RUN_DIR, JUDGE_WRITE_DIR, PROBE_DIR, PROBE_FILE } from "./readonly-shell.mts";
10
+ import { contractSeries, sameSpec } from "./run-record.mts";
11
+
12
+ const CLI_FILE_NAME = "prune.mts";
13
+ const QA_DIR = ".qa";
14
+ const CONTRACTS_DIR = `${QA_DIR}/contracts`;
15
+ const FETCH_FLAG = "--fetch";
16
+ const YES_FLAG = "--yes";
17
+ const STALE_FLAG = "--include-stale";
18
+ const DAYS_PREFIX = "--days=";
19
+ const FLAGS = [FETCH_FLAG, YES_FLAG, STALE_FLAG];
20
+ const DEFAULT_DAYS = 30;
21
+ const KEPT_COVERAGE_REPORTS = 3;
22
+ const DAY_MS = 24 * 60 * 60 * 1000;
23
+ const REMOTE = "origin";
24
+ const FALLBACK_BRANCHES = ["main", "dev"];
25
+ const GIT_BUFFER = 256 * 1024 * 1024;
26
+ const GIT_TIMEOUT_MS = 120_000;
27
+ const CONTRACT_FILE = /^([A-Za-z0-9][A-Za-z0-9_.-]*)\.md$/;
28
+ const SPEC_FILE = /\.(?:spec|test)\.[cm]?[jt]sx?$/;
29
+ const TEST_TITLE = /\btest(?:\.(?:only|skip|fixme|fail|slow))?\s*\(\s*(["'`])((?:\\.|(?!\1)[^\\])*)\1/g;
30
+ const EXPLORE_REPORT = /^explore-([a-z0-9]+(?:-[a-z0-9]+)*?)(-observed)?\.md$/;
31
+ const OBSERVED_REPORT = /-observed\.md$/;
32
+ const COVERAGE_REPORT = /^coverage-(\d{4}-\d{2}-\d{2})(?:-([a-z0-9]+(?:-[a-z0-9]+)*))?\.md$/;
33
+ const GAPS_SUFFIX = /-gaps\.md$/;
34
+ const HEAL_REPORT = /^heal-[a-z0-9]+(?:-[a-z0-9]+)*\.md$/;
35
+ const HEAL_RUN = /^heal-[a-z0-9]+(?:-[a-z0-9]+)*$/;
36
+ const LOCAL_ENV = /\.local\.env$/;
37
+ const BRANCH_BOUNDARY = "[^a-z0-9]";
38
+ const REGEX_SPECIALS = /[.*+?^${}()|[\]\\]/g;
39
+ const USAGE = `prune: usage is node .claude/checks/${CLI_FILE_NAME} [${FETCH_FLAG}] [${YES_FLAG} [${STALE_FLAG}]] [${DAYS_PREFIX}<n>, ${DEFAULT_DAYS} by default], run from the repository root`;
40
+
41
+ /** A path under `.qa/` to remove, relative to the repository root with `/`, and why, in one line. */
42
+ export type Removal = { path: string; reason: string };
43
+
44
+ /**
45
+ * What a prune would do: `automatic` is removed with `--yes`, `ask` only with `--yes --include-stale`, `held` names
46
+ * the done contracts that are kept and why, and `notes` say what could not be decided (`not reached: <why>`).
47
+ */
48
+ export type PrunePlan = { notes: string[]; automatic: Removal[]; held: Removal[]; ask: Removal[] };
49
+
50
+ /** Runs git in the repository with the given arguments and standard input; undefined when it fails. */
51
+ export type Git = (args: readonly string[], input?: string) => Buffer | undefined;
52
+
53
+ /** What the plan is made with: the suite directory, the age limit of the ask class, the time now, and whether to fetch. */
54
+ export type PruneOptions = { suiteDir: string; days: number; now: number; fetch: boolean };
55
+
56
+ type Contract = { name: string; path: string; markdown: string; references: ContractReferences; modified: number };
57
+
58
+ type Branches = { ref: string; unmerged: string[] };
59
+
60
+ function gitText(git: Git, args: readonly string[]): string | undefined {
61
+ return git(args)?.toString("utf8");
62
+ }
63
+
64
+ function exists(path: string): boolean {
65
+ try {
66
+ lstatSync(path);
67
+ return true;
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ function entriesOf(path: string): string[] {
74
+ try {
75
+ return readdirSync(path);
76
+ } catch {
77
+ return [];
78
+ }
79
+ }
80
+
81
+ function isFile(path: string): boolean {
82
+ try {
83
+ return lstatSync(path).isFile();
84
+ } catch {
85
+ return false;
86
+ }
87
+ }
88
+
89
+ function isDirectory(path: string): boolean {
90
+ try {
91
+ return lstatSync(path).isDirectory();
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+
97
+ /** The newest change time under `path`, the path itself included; links are not followed. */
98
+ function newestChange(path: string): number {
99
+ const stat = lstatSync(path);
100
+ if (!stat.isDirectory()) {
101
+ return stat.mtimeMs;
102
+ }
103
+ return Math.max(stat.mtimeMs, ...entriesOf(path).map((entry) => newestChange(join(path, entry))));
104
+ }
105
+
106
+ function ageInDays(root: string, path: string, now: number): number {
107
+ return Math.floor((now - newestChange(join(root, path))) / DAY_MS);
108
+ }
109
+
110
+ /** The default branch of `origin` as a remote ref (`origin/HEAD`, else `origin/main`, else `origin/dev`), or why not. */
111
+ function defaultBranch(git: Git): string | { notReached: string } {
112
+ const head = gitText(git, ["symbolic-ref", "--quiet", "--short", `refs/remotes/${REMOTE}/HEAD`])?.trim();
113
+ const candidates = [
114
+ ...(head === undefined || head === "" ? [] : [head]),
115
+ ...FALLBACK_BRANCHES.map((name) => `${REMOTE}/${name}`),
116
+ ];
117
+ const ref = candidates.find(
118
+ (candidate) =>
119
+ gitText(git, ["rev-parse", "--verify", "--quiet", `refs/remotes/${candidate}^{commit}`]) !== undefined,
120
+ );
121
+ return (
122
+ ref ?? {
123
+ notReached: `no ${REMOTE}/HEAD, ${FALLBACK_BRANCHES.map((name) => `${REMOTE}/${name}`).join(" or ")} ref (run with ${FETCH_FLAG})`,
124
+ }
125
+ );
126
+ }
127
+
128
+ /** The local branches not merged into `ref`. */
129
+ function unmergedBranches(git: Git, ref: string): string[] | undefined {
130
+ const all = gitText(git, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]);
131
+ const merged = gitText(git, ["for-each-ref", "--format=%(refname:short)", `--merged=${ref}`, "refs/heads"]);
132
+ if (all === undefined || merged === undefined) {
133
+ return undefined;
134
+ }
135
+ const mergedNames = merged.split("\n").map((name) => name.trim());
136
+ return all
137
+ .split("\n")
138
+ .map((name) => name.trim())
139
+ .filter((name) => name !== "" && !mergedNames.includes(name));
140
+ }
141
+
142
+ function parseBatch(output: Buffer, files: readonly string[]): Map<string, string> {
143
+ const contents = new Map<string, string>();
144
+ let offset = 0;
145
+ for (const file of files) {
146
+ const end = output.indexOf("\n", offset);
147
+ if (end < 0) {
148
+ break;
149
+ }
150
+ const header = output.subarray(offset, end).toString("utf8").split(" ");
151
+ offset = end + 1;
152
+ if (header[1] !== "blob") {
153
+ continue;
154
+ }
155
+ const size = Number(header[2]);
156
+ contents.set(file, output.subarray(offset, offset + size).toString("utf8"));
157
+ offset += size + 1;
158
+ }
159
+ return contents;
160
+ }
161
+
162
+ /**
163
+ * The test titles of every spec file of the suite directory at `ref`, by repository path, read from git objects: no
164
+ * checkout, no Playwright. A title is the first argument of `test(…)` (or `test.only`, `skip`, `fixme`, `fail`, `slow`)
165
+ * when it is a string literal.
166
+ */
167
+ function titlesAt(git: Git, ref: string, suiteDir: string): Map<string, string[]> | undefined {
168
+ const listing = gitText(git, ["ls-tree", "-r", "-z", "--full-name", "--name-only", ref, "--", suiteDir]);
169
+ if (listing === undefined) {
170
+ return undefined;
171
+ }
172
+ const files = listing.split("\0").filter((file) => SPEC_FILE.test(file) && !file.includes("\n"));
173
+ if (files.length === 0) {
174
+ return new Map();
175
+ }
176
+ const output = git(["cat-file", "--batch"], files.map((file) => `${ref}:${file}\n`).join(""));
177
+ if (output === undefined) {
178
+ return undefined;
179
+ }
180
+ const titles = new Map<string, string[]>();
181
+ for (const [file, source] of parseBatch(output, files)) {
182
+ titles.set(
183
+ file,
184
+ [...source.matchAll(TEST_TITLE)].map((match) => match[2] ?? ""),
185
+ );
186
+ }
187
+ return titles;
188
+ }
189
+
190
+ function readContracts(root: string): Contract[] {
191
+ return entriesOf(join(root, CONTRACTS_DIR)).flatMap((entry) => {
192
+ const name = CONTRACT_FILE.exec(entry)?.[1];
193
+ const path = `${CONTRACTS_DIR}/${entry}`;
194
+ if (name === undefined || !isFile(join(root, path))) {
195
+ return [];
196
+ }
197
+ const markdown = readFileSync(join(root, path), "utf8");
198
+ return [
199
+ { name, path, markdown, references: contractReferences(markdown), modified: newestChange(join(root, path)) },
200
+ ];
201
+ });
202
+ }
203
+
204
+ /**
205
+ * The spec files at the default branch that hold a test of the contract, when every live case has one; else none. Only
206
+ * the spec files its `## Verification` runs count: case ids (`C-01`) repeat from one contract to the next, so a title
207
+ * of another contract's spec never makes this one done, and a contract whose Verification names no spec file is never
208
+ * done.
209
+ */
210
+ function doneSpecs(contract: Contract, titles: Map<string, string[]>, suiteDir: string): string[] | undefined {
211
+ const { caseIds, dropped } = contract.references;
212
+ const live = caseIds.filter((caseId) => !dropped.includes(caseId));
213
+ const own = verificationSpecs(contract, suiteDir);
214
+ const specs = [...titles].filter(
215
+ ([file, names]) =>
216
+ own.some((spec) => sameSpec(spec, file)) &&
217
+ names.some((title) => live.some((caseId) => namesCase(title, caseId))),
218
+ );
219
+ const covered = live.every((caseId) => specs.some(([, names]) => names.some((title) => namesCase(title, caseId))));
220
+ return live.length > 0 && covered ? specs.map(([file]) => file) : undefined;
221
+ }
222
+
223
+ function verificationSpecs(contract: Contract, suiteDir: string): string[] {
224
+ return contractSeries(contract.markdown)
225
+ .flatMap((series) => series.specs)
226
+ .map((spec) => (suiteDir === ROOT_SUITE_DIR || spec.startsWith(`${suiteDir}/`) ? spec : `${suiteDir}/${spec}`));
227
+ }
228
+
229
+ function namesBranch(branch: string, name: string): boolean {
230
+ const pattern = `(^|${BRANCH_BOUNDARY})${name.toLowerCase().replace(REGEX_SPECIALS, "\\$&")}(${BRANCH_BOUNDARY}|$)`;
231
+ return new RegExp(pattern).test(branch.toLowerCase());
232
+ }
233
+
234
+ /** Why a done contract is kept: its spec files changed and not pushed, or an unmerged local branch carries its name. */
235
+ function holdReason(git: Git, contract: Contract, files: readonly string[], branches: Branches): string | undefined {
236
+ const status = gitText(git, ["status", "--porcelain", "-z", "--untracked-files=all", "--", ...files]);
237
+ if (status === undefined) {
238
+ return "git status of its spec files failed";
239
+ }
240
+ const changed = status.split("\0").find((entry) => entry.length > 3);
241
+ if (changed !== undefined) {
242
+ return `uncommitted changes in ${changed.slice(3)}`;
243
+ }
244
+ const upstream = gitText(git, ["rev-parse", "--verify", "--quiet", "@{upstream}"]);
245
+ const base = upstream === undefined ? branches.ref : "@{upstream}";
246
+ const unpushed = gitText(git, ["log", "--format=%h", `${base}..HEAD`, "--", ...files]);
247
+ if (unpushed === undefined) {
248
+ return "git log of its spec files failed";
249
+ }
250
+ if (unpushed.trim() !== "") {
251
+ return `unpushed commits change its spec files (${unpushed.trim().split("\n").length})`;
252
+ }
253
+ const branch = branches.unmerged.find((name) => namesBranch(name, contract.name));
254
+ return branch === undefined ? undefined : `local branch ${branch} is not merged into ${branches.ref}`;
255
+ }
256
+
257
+ function existing(root: string, paths: readonly string[]): string[] {
258
+ return paths.filter((path) => exists(join(root, path)));
259
+ }
260
+
261
+ function contractFiles(root: string, contract: Contract): string[] {
262
+ return existing(root, [contract.path, `${HEALER_RUN_DIR}/${contract.name}`, `${JUDGE_WRITE_DIR}/${contract.name}`]);
263
+ }
264
+
265
+ function reasonOf(path: string, contract: Contract, done: string): string {
266
+ if (path === contract.path) {
267
+ return done;
268
+ }
269
+ return path.startsWith(HEALER_RUN_DIR) ? `run record of ${contract.path}` : `judge verdict of ${contract.path}`;
270
+ }
271
+
272
+ /** The reports the contracts that stay cite, in their oracles or their `## Source`: never removed. */
273
+ function citedBy(contracts: readonly Contract[], done: ReadonlySet<string>): Set<string> {
274
+ return new Set(
275
+ contracts
276
+ .filter((contract) => !done.has(contract.path))
277
+ .flatMap((contract) => [...contract.references.observedReports, ...contract.references.sourceFiles]),
278
+ );
279
+ }
280
+
281
+ type AutomaticResult = { notes: string[]; automatic: Removal[]; held: Removal[]; done: Set<string> };
282
+
283
+ function automaticClass(root: string, git: Git, contracts: Contract[], options: PruneOptions): AutomaticResult {
284
+ const notes: string[] = [];
285
+ const hasRemote = gitText(git, ["remote", "get-url", REMOTE]) !== undefined;
286
+ if (hasRemote && options.fetch && git(["fetch", "--quiet", "--no-tags", REMOTE]) === undefined) {
287
+ notes.push(`git fetch ${REMOTE} failed: the existing remote refs are read`);
288
+ }
289
+ const ref = hasRemote ? defaultBranch(git) : { notReached: `no remote ${REMOTE}` };
290
+ if (typeof ref !== "string") {
291
+ return { notes: [...notes, `not reached: ${ref.notReached}`], automatic: [], held: [], done: new Set() };
292
+ }
293
+ const titles = titlesAt(git, ref, options.suiteDir);
294
+ const unmerged = unmergedBranches(git, ref);
295
+ if (titles === undefined || unmerged === undefined) {
296
+ return {
297
+ notes: [...notes, `not reached: the spec files or branches at ${ref} could not be read`],
298
+ automatic: [],
299
+ held: [],
300
+ done: new Set(),
301
+ };
302
+ }
303
+ const automatic: Removal[] = [];
304
+ const held: Removal[] = [];
305
+ const done = new Set<string>();
306
+ for (const contract of contracts) {
307
+ const specs = doneSpecs(contract, titles, options.suiteDir);
308
+ if (specs === undefined) {
309
+ continue;
310
+ }
311
+ const files = [...new Set([...specs, ...verificationSpecs(contract, options.suiteDir)])];
312
+ const hold = holdReason(git, contract, files, { ref, unmerged });
313
+ const where = `every case is in a test title of its Verification's spec files on ${ref}`;
314
+ if (hold !== undefined) {
315
+ held.push({ path: contract.path, reason: `${where}, but ${hold}` });
316
+ continue;
317
+ }
318
+ done.add(contract.path);
319
+ automatic.push(...contractFiles(root, contract).map((path) => ({ path, reason: reasonOf(path, contract, where) })));
320
+ }
321
+ const cited = citedBy(contracts, done);
322
+ for (const contract of contracts.filter((item) => done.has(item.path))) {
323
+ const reports = contract.references.observedReports.filter(
324
+ (path) => OBSERVED_REPORT.test(path) && !cited.has(path) && !automatic.some((removal) => removal.path === path),
325
+ );
326
+ automatic.push(...existing(root, reports).map((path) => ({ path, reason: `observed values of ${contract.path}` })));
327
+ }
328
+ return { notes, automatic, held, done };
329
+ }
330
+
331
+ function reportsIn(root: string): string[] {
332
+ return entriesOf(join(root, EXPLORER_WRITE_DIR)).filter((entry) => isFile(join(root, EXPLORER_WRITE_DIR, entry)));
333
+ }
334
+
335
+ function staleContracts(root: string, contracts: Contract[], skipped: Set<string>, options: PruneOptions): Removal[] {
336
+ return contracts
337
+ .filter((contract) => !skipped.has(contract.path) && !contract.references.approved)
338
+ .filter((contract) => options.now - contract.modified > options.days * DAY_MS)
339
+ .flatMap((contract) => {
340
+ const why = `no ## Approval, unchanged for ${ageInDays(root, contract.path, options.now)} days`;
341
+ return contractFiles(root, contract).map((path) => ({ path, reason: reasonOf(path, contract, why) }));
342
+ });
343
+ }
344
+
345
+ function oldCoverageReports(reports: readonly string[]): Removal[] {
346
+ const bySlug = new Map<string, { date: string; file: string }[]>();
347
+ for (const file of reports) {
348
+ const match = COVERAGE_REPORT.exec(file.replace(GAPS_SUFFIX, ".md"));
349
+ if (match?.[1] !== undefined) {
350
+ const slug = match[2] ?? "";
351
+ bySlug.set(slug, [...(bySlug.get(slug) ?? []), { date: match[1], file }]);
352
+ }
353
+ }
354
+ return [...bySlug].flatMap(([slug, files]) => {
355
+ const kept = [...new Set(files.map(({ date }) => date))].sort().reverse().slice(0, KEPT_COVERAGE_REPORTS);
356
+ return files
357
+ .filter(({ date }) => !kept.includes(date))
358
+ .map(({ date, file }) => ({
359
+ path: `${EXPLORER_WRITE_DIR}/${file}`,
360
+ reason: `coverage of ${slug === "" ? "the whole stand" : slug} from ${date}; the ${KEPT_COVERAGE_REPORTS} newest are kept`,
361
+ }));
362
+ });
363
+ }
364
+
365
+ /**
366
+ * The `-observed` reports older than the explorer report of their area (`explore-<slug>-observed.md` older than
367
+ * `explore-<slug>.md`): the area was explored again after the values were recorded. The area report itself is never
368
+ * planned here: observing writes its `-observed` report after the area report, so the newer one says nothing about it.
369
+ */
370
+ function olderExplorerReports(root: string, reports: readonly string[]): Removal[] {
371
+ const areaReports = new Map<string, string>();
372
+ const observed: { file: string; area: string }[] = [];
373
+ for (const file of reports) {
374
+ const match = EXPLORE_REPORT.exec(file);
375
+ if (match?.[1] !== undefined) {
376
+ if (match[2] === undefined) {
377
+ areaReports.set(match[1], file);
378
+ } else {
379
+ observed.push({ file, area: match[1] });
380
+ }
381
+ }
382
+ }
383
+ return observed.flatMap(({ file, area }) => {
384
+ const areaReport = areaReports.get(area);
385
+ return areaReport !== undefined &&
386
+ newestChange(join(root, EXPLORER_WRITE_DIR, file)) < newestChange(join(root, EXPLORER_WRITE_DIR, areaReport))
387
+ ? [
388
+ {
389
+ path: `${EXPLORER_WRITE_DIR}/${file}`,
390
+ reason: `older than ${EXPLORER_WRITE_DIR}/${areaReport}, the report of the same area`,
391
+ },
392
+ ]
393
+ : [];
394
+ });
395
+ }
396
+
397
+ function oldHealerFiles(root: string, reports: readonly string[], options: PruneOptions): Removal[] {
398
+ const runs = entriesOf(join(root, HEALER_RUN_DIR))
399
+ .filter((entry) => HEAL_RUN.test(entry) && isDirectory(join(root, HEALER_RUN_DIR, entry)))
400
+ .map((entry) => `${HEALER_RUN_DIR}/${entry}`);
401
+ const files = [
402
+ ...reports.filter((file) => HEAL_REPORT.test(file)).map((file) => `${EXPLORER_WRITE_DIR}/${file}`),
403
+ ...runs,
404
+ ];
405
+ return files
406
+ .map((path) => ({ path, days: ageInDays(root, path, options.now) }))
407
+ .filter(({ days }) => days > options.days)
408
+ .map(({ path, days }) => ({
409
+ path,
410
+ reason: `healer ${path.startsWith(HEALER_RUN_DIR) ? "runs" : "report"}, unchanged for ${days} days`,
411
+ }));
412
+ }
413
+
414
+ function probeFiles(root: string): Removal[] {
415
+ return entriesOf(join(root, PROBE_DIR))
416
+ .map((entry) => `${PROBE_DIR}/${entry}`)
417
+ .filter((path) => PROBE_FILE.test(path) && isFile(join(root, path)))
418
+ .map((path) => ({ path, reason: "probe file" }));
419
+ }
420
+
421
+ /**
422
+ * Plans the cleanup of the agents' local files under `.qa/`. A contract is done when every case id of its `## Cases`
423
+ * that no approved amendment drops is in a test title of a spec file its `## Verification` runs, on the default branch
424
+ * of `origin`; a done contract goes with its run record, its judge verdict and the `-observed` reports its oracles
425
+ * cite, unless its spec files have uncommitted or unpushed changes or an unmerged local branch carries its name. The
426
+ * ask class: contracts with no approval unchanged for `days`, coverage reports beyond the newest few per slug,
427
+ * `-observed` reports older than the explorer report of their area, healer reports and runs unchanged for `days`, and
428
+ * probe files. A report a kept contract cites is never planned.
429
+ *
430
+ * @param git runs git in `root`; see {@link Git}.
431
+ * @returns the plan; nothing is removed.
432
+ */
433
+ export function planPrune(root: string, options: PruneOptions, git: Git): PrunePlan {
434
+ const contracts = readContracts(root);
435
+ const { notes, automatic, held, done } = automaticClass(root, git, contracts, options);
436
+ const planned = new Set(automatic.map((removal) => removal.path));
437
+ const reports = reportsIn(root).filter((file) => !planned.has(`${EXPLORER_WRITE_DIR}/${file}`));
438
+ const skipped = new Set([...done, ...held.map((removal) => removal.path)]);
439
+ const cited = citedBy(contracts, done);
440
+ const ask = [
441
+ ...staleContracts(root, contracts, skipped, options),
442
+ ...oldCoverageReports(reports),
443
+ ...olderExplorerReports(root, reports),
444
+ ...oldHealerFiles(root, reports, options),
445
+ ...probeFiles(root),
446
+ ].filter((removal) => !cited.has(removal.path) && !planned.has(removal.path));
447
+ return { notes, automatic, held, ask };
448
+ }
449
+
450
+ function isInside(parent: string, child: string): boolean {
451
+ const path = relative(parent, child);
452
+ return path !== "" && !path.startsWith("..") && !isAbsolute(path);
453
+ }
454
+
455
+ /**
456
+ * Why `path` must not be removed: outside `.qa/` (also through a link), the knowledge directory or inside it, or a
457
+ * `.local.env` file; undefined when it may be.
458
+ */
459
+ export function refusal(root: string, path: string, knowledgeDir: string): string | undefined {
460
+ const qa = resolve(root, QA_DIR);
461
+ const target = resolve(root, path);
462
+ if (!isInside(qa, target) || path.split(/[\\/]/).includes("..")) {
463
+ return "not under .qa/";
464
+ }
465
+ const knowledge = resolve(root, knowledgeDir);
466
+ if (target === knowledge || isInside(knowledge, target)) {
467
+ return `inside the knowledge directory ${knowledgeDir}`;
468
+ }
469
+ if (LOCAL_ENV.test(basename(target))) {
470
+ return "a .local.env file";
471
+ }
472
+ try {
473
+ const realQa = realpathSync(qa);
474
+ if (
475
+ realQa !== resolve(realpathSync(root), QA_DIR) ||
476
+ !isInside(realQa, join(realpathSync(resolve(target, "..")), basename(target)))
477
+ ) {
478
+ return "reached through a link that leaves .qa/";
479
+ }
480
+ } catch {
481
+ return "its directory cannot be resolved";
482
+ }
483
+ return undefined;
484
+ }
485
+
486
+ function formatLine(verb: string, removal: Removal): string {
487
+ return `${verb} ${removal.path}: ${removal.reason}`;
488
+ }
489
+
490
+ /**
491
+ * Removes the planned paths and returns one line per path: `removed`, or `not removed` with why.
492
+ *
493
+ * @param knowledgeDir the facts' knowledge directory, never removed.
494
+ */
495
+ export function applyPrune(root: string, removals: readonly Removal[], knowledgeDir: string): string[] {
496
+ return removals.map((removal) => {
497
+ const refused = refusal(root, removal.path, knowledgeDir);
498
+ if (refused !== undefined) {
499
+ return `not removed ${removal.path}: ${refused}`;
500
+ }
501
+ try {
502
+ rmSync(join(root, removal.path), { recursive: true, force: true });
503
+ return formatLine("removed", removal);
504
+ } catch (error) {
505
+ return `not removed ${removal.path}: ${error instanceof Error && "code" in error ? String(error.code) : "failed"}`;
506
+ }
507
+ });
508
+ }
509
+
510
+ function runGit(root: string): Git {
511
+ return (args, input) => {
512
+ try {
513
+ return execFileSync("git", ["-c", "core.fsmonitor=false", "-c", "core.quotepath=off", ...args], {
514
+ cwd: root,
515
+ input,
516
+ maxBuffer: GIT_BUFFER,
517
+ timeout: GIT_TIMEOUT_MS,
518
+ windowsHide: true,
519
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", GIT_NO_LAZY_FETCH: "1" },
520
+ stdio: [input === undefined ? "ignore" : "pipe", "pipe", "ignore"],
521
+ });
522
+ } catch {
523
+ return undefined;
524
+ }
525
+ };
526
+ }
527
+
528
+ function parseDays(flags: readonly string[]): number {
529
+ const given = flags.filter((flag) => flag.startsWith(DAYS_PREFIX));
530
+ if (given.length === 0) {
531
+ return DEFAULT_DAYS;
532
+ }
533
+ const days = Number(given[0]?.slice(DAYS_PREFIX.length));
534
+ if (given.length > 1 || !Number.isInteger(days) || days < 1) {
535
+ throw new Error(USAGE);
536
+ }
537
+ return days;
538
+ }
539
+
540
+ if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
541
+ try {
542
+ const flags = process.argv.slice(2);
543
+ const known = flags.every((flag) => FLAGS.includes(flag) || flag.startsWith(DAYS_PREFIX));
544
+ if (!known || new Set(flags).size !== flags.length || (flags.includes(STALE_FLAG) && !flags.includes(YES_FLAG))) {
545
+ throw new Error(USAGE);
546
+ }
547
+ const days = parseDays(flags);
548
+ const root = process.cwd();
549
+ let facts: ReturnType<typeof readProjectFacts>;
550
+ try {
551
+ facts = readProjectFacts();
552
+ } catch (error) {
553
+ throw new Error(`prune: not reached: ${error instanceof Error ? error.message : String(error)}`);
554
+ }
555
+ const yes = flags.includes(YES_FLAG);
556
+ const stale = yes && flags.includes(STALE_FLAG);
557
+ const plan = planPrune(
558
+ root,
559
+ { suiteDir: facts.suiteDir, days, now: Date.now(), fetch: flags.includes(FETCH_FLAG) },
560
+ runGit(root),
561
+ );
562
+ const lines = [
563
+ ...plan.notes.map((note) => `prune: ${note}`),
564
+ ...(yes
565
+ ? applyPrune(root, plan.automatic, facts.knowledgeDir)
566
+ : plan.automatic.map((removal) => formatLine("would remove", removal))),
567
+ ...plan.held.map((removal) => formatLine("kept", removal)),
568
+ ...(stale
569
+ ? applyPrune(root, plan.ask, facts.knowledgeDir)
570
+ : plan.ask.map((removal) => formatLine("ask", removal))),
571
+ ];
572
+ const removed = lines.filter((line) => line.startsWith("removed ")).length;
573
+ const summary = yes
574
+ ? `prune: removed ${removed}, ${stale ? 0 : plan.ask.length} to ask (${YES_FLAG} ${STALE_FLAG}), ${plan.held.length} done but kept`
575
+ : `prune: ${plan.automatic.length} to remove (${YES_FLAG}), ${plan.ask.length} to ask (${YES_FLAG} ${STALE_FLAG}), ${plan.held.length} done but kept`;
576
+ process.stdout.write(`${[...lines, summary].join("\n")}\n`);
577
+ if (lines.some((line) => line.startsWith("not removed "))) {
578
+ process.exitCode = 1;
579
+ }
580
+ } catch (error) {
581
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
582
+ process.exitCode = 1;
583
+ }
584
+ }
@@ -17,7 +17,8 @@ export type Gap = {
17
17
  factors?: Partial<Record<keyof Weights, number>>;
18
18
  };
19
19
 
20
- export type RankedGap = Gap & { score: number };
20
+ /** A gap with its score. `tied` is true when another gap has the same enabled-on-stand, critical and score values, so the order between them is only the name fallback. */
21
+ export type RankedGap = Gap & { score: number; tied: boolean };
21
22
 
22
23
  const CLI_FILE_NAME = "rank-gaps.mts";
23
24
  const STDIN = 0;
@@ -56,21 +57,38 @@ function compareText(left: string, right: string): number {
56
57
  return left < right ? -1 : 1;
57
58
  }
58
59
 
59
- function compareRanked(left: RankedGap, right: RankedGap): number {
60
+ type Scored = Gap & { score: number };
61
+
62
+ function comparePriority(left: Scored, right: Scored): number {
60
63
  if (left.enabledOnStand !== right.enabledOnStand) {
61
64
  return left.enabledOnStand ? -1 : 1;
62
65
  }
63
66
  if (left.critical !== right.critical) {
64
67
  return left.critical ? -1 : 1;
65
68
  }
69
+ return right.score - left.score;
70
+ }
71
+
72
+ function compareRanked(left: Scored, right: Scored): number {
66
73
  return (
67
- right.score - left.score ||
74
+ comparePriority(left, right) ||
68
75
  compareText(left.name, right.name) ||
69
76
  compareText(left.area, right.area) ||
70
77
  compareText(left.surface, right.surface)
71
78
  );
72
79
  }
73
80
 
81
+ function markTied(sorted: readonly Scored[]): RankedGap[] {
82
+ return sorted.map((gap, index) => {
83
+ const before = sorted[index - 1];
84
+ const after = sorted[index + 1];
85
+ const tied =
86
+ (before !== undefined && comparePriority(before, gap) === 0) ||
87
+ (after !== undefined && comparePriority(gap, after) === 0);
88
+ return { ...gap, tied };
89
+ });
90
+ }
91
+
74
92
  /**
75
93
  * Ranks the coverage gaps, highest priority first. A gap's score is the weighted sum of its factors, each from 0 to
76
94
  * 1: `risk` (raised by 1 when the gap is a critical flow and by 0.5 when a UI test has no API test under it),
@@ -78,12 +96,13 @@ function compareRanked(left: RankedGap, right: RankedGap): number {
78
96
  * comes first; scores are rounded to nine decimals so equal scores tie. The order is strict: gaps enabled on the stand
79
97
  * before gaps that are not (a module or flag that is off), then critical flows before the others, then by score, highest
80
98
  * first, then by name, then area, then surface. A critical gap therefore outranks a non-critical one whatever the
81
- * scores and weights.
99
+ * scores and weights. A gap whose enabled-on-stand, critical and score values equal a neighbour's is marked `tied`:
100
+ * nothing but the name decides which of them comes first, so the order among tied gaps is not a priority.
82
101
  *
83
102
  * @throws Error when a factor is not a number from 0 to 1.
84
103
  */
85
104
  export function rankGaps(gaps: readonly Gap[], weights: Weights): RankedGap[] {
86
- return gaps.map((gap) => ({ ...gap, score: scoreOf(gap, weights) })).sort(compareRanked);
105
+ return markTied(gaps.map((gap) => ({ ...gap, score: scoreOf(gap, weights) })).sort(compareRanked));
87
106
  }
88
107
 
89
108
  /** Marks a gap critical when its name or its area is one of the project's critical flows (case-insensitive). */