@gate-forge/cli 0.7.0 → 0.8.0

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 (254) hide show
  1. package/README.md +511 -51
  2. package/dist/adapter-audit.d.ts +154 -0
  3. package/dist/adapter-audit.d.ts.map +1 -0
  4. package/dist/adapter-audit.js +531 -0
  5. package/dist/adapter-audit.js.map +1 -0
  6. package/dist/adapter-scaffold.d.ts +66 -0
  7. package/dist/adapter-scaffold.d.ts.map +1 -0
  8. package/dist/adapter-scaffold.js +353 -0
  9. package/dist/adapter-scaffold.js.map +1 -0
  10. package/dist/adopted-baseline.d.ts +10 -0
  11. package/dist/adopted-baseline.d.ts.map +1 -1
  12. package/dist/adopted-baseline.js +18 -1
  13. package/dist/adopted-baseline.js.map +1 -1
  14. package/dist/args.d.ts +15 -0
  15. package/dist/args.d.ts.map +1 -1
  16. package/dist/args.js +59 -2
  17. package/dist/args.js.map +1 -1
  18. package/dist/behavior-setup.d.ts +239 -0
  19. package/dist/behavior-setup.d.ts.map +1 -0
  20. package/dist/behavior-setup.js +738 -0
  21. package/dist/behavior-setup.js.map +1 -0
  22. package/dist/broker.d.ts.map +1 -1
  23. package/dist/broker.js +28 -2
  24. package/dist/broker.js.map +1 -1
  25. package/dist/cache-exclusions.d.ts +45 -0
  26. package/dist/cache-exclusions.d.ts.map +1 -0
  27. package/dist/cache-exclusions.js +205 -0
  28. package/dist/cache-exclusions.js.map +1 -0
  29. package/dist/candidate-tree.d.ts +86 -14
  30. package/dist/candidate-tree.d.ts.map +1 -1
  31. package/dist/candidate-tree.js +236 -62
  32. package/dist/candidate-tree.js.map +1 -1
  33. package/dist/ci-witnessed-template.d.ts +43 -0
  34. package/dist/ci-witnessed-template.d.ts.map +1 -0
  35. package/dist/ci-witnessed-template.js +283 -0
  36. package/dist/ci-witnessed-template.js.map +1 -0
  37. package/dist/cli.d.ts +1 -1
  38. package/dist/cli.d.ts.map +1 -1
  39. package/dist/cli.js +31 -4
  40. package/dist/cli.js.map +1 -1
  41. package/dist/commands/adapters.d.ts +15 -0
  42. package/dist/commands/adapters.d.ts.map +1 -0
  43. package/dist/commands/adapters.js +284 -0
  44. package/dist/commands/adapters.js.map +1 -0
  45. package/dist/commands/adopt.d.ts.map +1 -1
  46. package/dist/commands/adopt.js +9 -1
  47. package/dist/commands/adopt.js.map +1 -1
  48. package/dist/commands/baseline.d.ts.map +1 -1
  49. package/dist/commands/baseline.js +42 -1
  50. package/dist/commands/baseline.js.map +1 -1
  51. package/dist/commands/blocking.d.ts +81 -2
  52. package/dist/commands/blocking.d.ts.map +1 -1
  53. package/dist/commands/blocking.js +336 -53
  54. package/dist/commands/blocking.js.map +1 -1
  55. package/dist/commands/check.d.ts +36 -0
  56. package/dist/commands/check.d.ts.map +1 -1
  57. package/dist/commands/check.js +1008 -62
  58. package/dist/commands/check.js.map +1 -1
  59. package/dist/commands/classify.d.ts +2 -1
  60. package/dist/commands/classify.d.ts.map +1 -1
  61. package/dist/commands/classify.js +143 -5
  62. package/dist/commands/classify.js.map +1 -1
  63. package/dist/commands/enforce.d.ts +4 -4
  64. package/dist/commands/enforce.d.ts.map +1 -1
  65. package/dist/commands/enforce.js +41 -9
  66. package/dist/commands/enforce.js.map +1 -1
  67. package/dist/commands/enforcement.d.ts +13 -1
  68. package/dist/commands/enforcement.d.ts.map +1 -1
  69. package/dist/commands/enforcement.js +800 -30
  70. package/dist/commands/enforcement.js.map +1 -1
  71. package/dist/commands/history.d.ts +12 -0
  72. package/dist/commands/history.d.ts.map +1 -0
  73. package/dist/commands/history.js +45 -0
  74. package/dist/commands/history.js.map +1 -0
  75. package/dist/commands/init-presets.d.ts +148 -0
  76. package/dist/commands/init-presets.d.ts.map +1 -0
  77. package/dist/commands/init-presets.js +194 -0
  78. package/dist/commands/init-presets.js.map +1 -0
  79. package/dist/commands/init.d.ts +7 -12
  80. package/dist/commands/init.d.ts.map +1 -1
  81. package/dist/commands/init.js +610 -69
  82. package/dist/commands/init.js.map +1 -1
  83. package/dist/commands/keys.d.ts.map +1 -1
  84. package/dist/commands/keys.js +29 -13
  85. package/dist/commands/keys.js.map +1 -1
  86. package/dist/commands/next.d.ts.map +1 -1
  87. package/dist/commands/next.js +744 -15
  88. package/dist/commands/next.js.map +1 -1
  89. package/dist/commands/pre-commit.d.ts +25 -0
  90. package/dist/commands/pre-commit.d.ts.map +1 -1
  91. package/dist/commands/pre-commit.js +91 -6
  92. package/dist/commands/pre-commit.js.map +1 -1
  93. package/dist/commands/quarantine.d.ts +16 -0
  94. package/dist/commands/quarantine.d.ts.map +1 -0
  95. package/dist/commands/quarantine.js +213 -0
  96. package/dist/commands/quarantine.js.map +1 -0
  97. package/dist/commands/run.d.ts +39 -0
  98. package/dist/commands/run.d.ts.map +1 -0
  99. package/dist/commands/run.js +196 -0
  100. package/dist/commands/run.js.map +1 -0
  101. package/dist/commands/test-gates.d.ts +284 -2
  102. package/dist/commands/test-gates.d.ts.map +1 -1
  103. package/dist/commands/test-gates.js +3619 -186
  104. package/dist/commands/test-gates.js.map +1 -1
  105. package/dist/commands/tests.d.ts +1 -1
  106. package/dist/commands/tests.d.ts.map +1 -1
  107. package/dist/commands/tests.js +225 -22
  108. package/dist/commands/tests.js.map +1 -1
  109. package/dist/endpoint-compiler.d.ts.map +1 -1
  110. package/dist/endpoint-compiler.js +29 -8
  111. package/dist/endpoint-compiler.js.map +1 -1
  112. package/dist/engine-browser.d.ts +183 -0
  113. package/dist/engine-browser.d.ts.map +1 -0
  114. package/dist/engine-browser.js +381 -0
  115. package/dist/engine-browser.js.map +1 -0
  116. package/dist/engine-identity.d.ts +100 -0
  117. package/dist/engine-identity.d.ts.map +1 -0
  118. package/dist/engine-identity.js +182 -0
  119. package/dist/engine-identity.js.map +1 -0
  120. package/dist/evaluate.d.ts +89 -0
  121. package/dist/evaluate.d.ts.map +1 -1
  122. package/dist/evaluate.js +137 -16
  123. package/dist/evaluate.js.map +1 -1
  124. package/dist/execution.d.ts +253 -9
  125. package/dist/execution.d.ts.map +1 -1
  126. package/dist/execution.js +309 -12
  127. package/dist/execution.js.map +1 -1
  128. package/dist/git-hooks.d.ts +17 -0
  129. package/dist/git-hooks.d.ts.map +1 -1
  130. package/dist/git-hooks.js +119 -0
  131. package/dist/git-hooks.js.map +1 -1
  132. package/dist/git-objects.d.ts +60 -0
  133. package/dist/git-objects.d.ts.map +1 -0
  134. package/dist/git-objects.js +152 -0
  135. package/dist/git-objects.js.map +1 -0
  136. package/dist/history.d.ts +52 -0
  137. package/dist/history.d.ts.map +1 -0
  138. package/dist/history.js +116 -0
  139. package/dist/history.js.map +1 -0
  140. package/dist/host-load.d.ts +49 -0
  141. package/dist/host-load.d.ts.map +1 -0
  142. package/dist/host-load.js +78 -0
  143. package/dist/host-load.js.map +1 -0
  144. package/dist/input-snapshot.d.ts +63 -9
  145. package/dist/input-snapshot.d.ts.map +1 -1
  146. package/dist/input-snapshot.js +195 -17
  147. package/dist/input-snapshot.js.map +1 -1
  148. package/dist/io.d.ts +36 -0
  149. package/dist/io.d.ts.map +1 -1
  150. package/dist/io.js +21 -0
  151. package/dist/io.js.map +1 -1
  152. package/dist/mapping.d.ts +84 -1
  153. package/dist/mapping.d.ts.map +1 -1
  154. package/dist/mapping.js +276 -5
  155. package/dist/mapping.js.map +1 -1
  156. package/dist/native-freeze.d.ts +217 -0
  157. package/dist/native-freeze.d.ts.map +1 -0
  158. package/dist/native-freeze.js +332 -0
  159. package/dist/native-freeze.js.map +1 -0
  160. package/dist/pipeline.d.ts +52 -1
  161. package/dist/pipeline.d.ts.map +1 -1
  162. package/dist/pipeline.js +141 -3
  163. package/dist/pipeline.js.map +1 -1
  164. package/dist/playwright-browsers.d.ts +210 -0
  165. package/dist/playwright-browsers.d.ts.map +1 -0
  166. package/dist/playwright-browsers.js +364 -0
  167. package/dist/playwright-browsers.js.map +1 -0
  168. package/dist/plugins.d.ts +15 -5
  169. package/dist/plugins.d.ts.map +1 -1
  170. package/dist/plugins.js +59 -9
  171. package/dist/plugins.js.map +1 -1
  172. package/dist/progress.d.ts +148 -0
  173. package/dist/progress.d.ts.map +1 -0
  174. package/dist/progress.js +263 -0
  175. package/dist/progress.js.map +1 -0
  176. package/dist/providers.d.ts +26 -1
  177. package/dist/providers.d.ts.map +1 -1
  178. package/dist/providers.js +39 -0
  179. package/dist/providers.js.map +1 -1
  180. package/dist/receipts.d.ts +1 -0
  181. package/dist/receipts.d.ts.map +1 -1
  182. package/dist/receipts.js +35 -7
  183. package/dist/receipts.js.map +1 -1
  184. package/dist/repo-scan.d.ts +8 -1
  185. package/dist/repo-scan.d.ts.map +1 -1
  186. package/dist/repo-scan.js +221 -27
  187. package/dist/repo-scan.js.map +1 -1
  188. package/dist/reseal-chain.d.ts +184 -0
  189. package/dist/reseal-chain.d.ts.map +1 -0
  190. package/dist/reseal-chain.js +735 -0
  191. package/dist/reseal-chain.js.map +1 -0
  192. package/dist/reseal-evidence.d.ts +241 -0
  193. package/dist/reseal-evidence.d.ts.map +1 -0
  194. package/dist/reseal-evidence.js +319 -0
  195. package/dist/reseal-evidence.js.map +1 -0
  196. package/dist/reseal.d.ts +181 -0
  197. package/dist/reseal.d.ts.map +1 -0
  198. package/dist/reseal.js +1620 -0
  199. package/dist/reseal.js.map +1 -0
  200. package/dist/response-field-guidance.d.ts +82 -0
  201. package/dist/response-field-guidance.d.ts.map +1 -0
  202. package/dist/response-field-guidance.js +184 -0
  203. package/dist/response-field-guidance.js.map +1 -0
  204. package/dist/run-cache.d.ts +260 -0
  205. package/dist/run-cache.d.ts.map +1 -0
  206. package/dist/run-cache.js +771 -0
  207. package/dist/run-cache.js.map +1 -0
  208. package/dist/run-preflight.d.ts +77 -0
  209. package/dist/run-preflight.d.ts.map +1 -0
  210. package/dist/run-preflight.js +774 -0
  211. package/dist/run-preflight.js.map +1 -0
  212. package/dist/run-recipe.d.ts +107 -0
  213. package/dist/run-recipe.d.ts.map +1 -0
  214. package/dist/run-recipe.js +295 -0
  215. package/dist/run-recipe.js.map +1 -0
  216. package/dist/run-reliability.d.ts +126 -0
  217. package/dist/run-reliability.d.ts.map +1 -0
  218. package/dist/run-reliability.js +221 -0
  219. package/dist/run-reliability.js.map +1 -0
  220. package/dist/runtime.d.ts +15 -0
  221. package/dist/runtime.d.ts.map +1 -1
  222. package/dist/runtime.js +11 -1
  223. package/dist/runtime.js.map +1 -1
  224. package/dist/secret-guard.d.ts +36 -0
  225. package/dist/secret-guard.d.ts.map +1 -0
  226. package/dist/secret-guard.js +63 -0
  227. package/dist/secret-guard.js.map +1 -0
  228. package/dist/singleton-guidance.d.ts +73 -0
  229. package/dist/singleton-guidance.d.ts.map +1 -0
  230. package/dist/singleton-guidance.js +118 -0
  231. package/dist/singleton-guidance.js.map +1 -0
  232. package/dist/staged-candidate.d.ts +17 -0
  233. package/dist/staged-candidate.d.ts.map +1 -1
  234. package/dist/staged-candidate.js +50 -0
  235. package/dist/staged-candidate.js.map +1 -1
  236. package/dist/state-artifacts.d.ts +70 -0
  237. package/dist/state-artifacts.d.ts.map +1 -0
  238. package/dist/state-artifacts.js +215 -0
  239. package/dist/state-artifacts.js.map +1 -0
  240. package/dist/state.d.ts +170 -2
  241. package/dist/state.d.ts.map +1 -1
  242. package/dist/state.js +248 -8
  243. package/dist/state.js.map +1 -1
  244. package/dist/verifier-keys.d.ts +33 -2
  245. package/dist/verifier-keys.d.ts.map +1 -1
  246. package/dist/verifier-keys.js +95 -9
  247. package/dist/verifier-keys.js.map +1 -1
  248. package/guides/CONNECT-YOUR-PROJECT.md +367 -0
  249. package/guides/QUICKSTART.md +404 -0
  250. package/guides/RUNNER-NEUTRAL-EVIDENCE.md +199 -0
  251. package/guides/TEST-ENVIRONMENT.md +1226 -0
  252. package/guides/UPGRADE-0.6-to-0.7.md +65 -0
  253. package/guides/UPGRADE-0.7-to-0.8.md +114 -0
  254. package/package.json +12 -10
package/dist/reseal.js ADDED
@@ -0,0 +1,1620 @@
1
+ /**
2
+ * Test-only change classification (plan phases 1-2): Gateforge never
3
+ * takes the candidate's word for what changed. It computes the change
4
+ * set itself from the two SEALED candidate trees (the parent receipt's
5
+ * `candidateTreeId` and the tree this run froze), classifies every
6
+ * changed path from the runner's OWN test catalog plus the repository's
7
+ * own import graph, and fails closed on any doubt.
8
+ *
9
+ * Import statements are read from each file's SYNTAX, never from its
10
+ * text: a JS/TS blob is parsed with the TypeScript compiler API and a
11
+ * Python blob with its comment lines and triple-quoted text removed, so
12
+ * a sentence in a comment that happens to name an import call is prose
13
+ * and never a computed import. Bytes the parser cannot read refuse the
14
+ * re-seal rather than pass unexamined.
15
+ *
16
+ * Three classes exist, and only the first two may re-seal:
17
+ *
18
+ * - **test file** — a path the runner's own enumeration lists as
19
+ * containing tests (the catalog rows are the only definition of a
20
+ * test file: `playwright --list`, pytest collection, `vitest list`,
21
+ * Cypress spec scan — whatever the configured runner enumerated).
22
+ * - **test helper** — a file under a runner test root whose every
23
+ * importer Gateforge can resolve is itself test code. Its importers
24
+ * re-run, transitively.
25
+ * - **anything else** — app code, runner config, manifests/lockfiles,
26
+ * fixtures, generated files, docs: not eligible, full run as before.
27
+ *
28
+ * Uncertainty is never resolved in the candidate's favour: a dynamic or
29
+ * unresolvable import makes a helper claim impossible to prove, and a
30
+ * helper that cannot be proven is an ordinary non-test file.
31
+ */
32
+ import { spawnSync } from 'node:child_process';
33
+ import { readFileSync } from 'node:fs';
34
+ import { join, posix, relative, resolve } from 'node:path';
35
+ import picomatch from 'picomatch';
36
+ import ts from 'typescript';
37
+ import { parse as parseYaml } from 'yaml';
38
+ import { CONFIG_SEARCH_PRUNED_DIRS, PLAYWRIGHT_CONFIG_NAMES } from '@gate-forge/pack-playwright';
39
+ import { sanitizedAuthorityEnv } from './candidate-tree.js';
40
+ import { UsageError } from './errors.js';
41
+ /**
42
+ * Reads one committed tree's file list, so a path can be proven to be
43
+ * untracked in it. A changed path that EITHER commit tracks is source
44
+ * and never matches a runtime declaration, however the glob reads.
45
+ *
46
+ * Args:
47
+ * gitDir: the absolute git dir holding the tree object.
48
+ * env: the process environment (Git redirectors are stripped).
49
+ * treeId: the commit's tree (`<sha>^{tree}`).
50
+ *
51
+ * Returns:
52
+ * Set<string>: every repo-relative posix path the commit tracks;
53
+ * null when the list cannot be read (never a guess — the caller
54
+ * then disregards nothing).
55
+ */
56
+ function committedPaths(gitDir, env, treeId) {
57
+ const out = run(gitDir, env, ['ls-tree', '-r', '-z', '--name-only', treeId]);
58
+ if (out === null)
59
+ return null;
60
+ return new Set(out.split('\0').filter((path) => path.length > 0));
61
+ }
62
+ /**
63
+ * The git modes a candidate tree records. Only an ordinary blob is
64
+ * generated OUTPUT: a symlink (`120000`) and a submodule/gitlink
65
+ * (`160000`) are links, not bytes this run may have produced, and a
66
+ * missing entry is a path that is not in the sealed tree at all.
67
+ */
68
+ const REGULAR_FILE_MODE = { '100644': true, '100755': true };
69
+ /**
70
+ * Every path a sealed candidate tree records, with its git mode. The
71
+ * candidate tree carries the workspace's untracked bytes too — that is
72
+ * what makes it a candidate — so this listing is what tells a generated
73
+ * artifact apart from a link.
74
+ *
75
+ * Args:
76
+ * gitDir: the absolute git dir holding the tree object.
77
+ * env: the process environment (Git redirectors are stripped).
78
+ * treeId: the sealed candidate tree.
79
+ *
80
+ * Returns:
81
+ * Map<string, string>: repo-relative posix path → git mode; null when
82
+ * the listing cannot be read (never a partial answer).
83
+ */
84
+ function sealedTreeModes(gitDir, env, treeId) {
85
+ const out = run(gitDir, env, ['ls-tree', '-r', '-z', treeId]);
86
+ if (out === null)
87
+ return null;
88
+ const modes = new Map();
89
+ for (const record of out.split('\0')) {
90
+ if (record.length === 0)
91
+ continue;
92
+ const tab = record.indexOf('\t');
93
+ if (tab < 0)
94
+ return null;
95
+ const mode = record.slice(0, tab).split(/\s+/)[0];
96
+ if (mode === undefined)
97
+ return null;
98
+ modes.set(record.slice(tab + 1), mode);
99
+ }
100
+ return modes;
101
+ }
102
+ /**
103
+ * Why a changed path the SEALED runner config declares as a browser state
104
+ * is NOT generated output this run may have produced, or null when it is.
105
+ *
106
+ * A declaration is a READ statement first: it names where a project reads
107
+ * a session, never which bytes preparation owns. Only a path that is
108
+ * untracked in BOTH sealed commits, outside the run's input inventory, an
109
+ * ordinary file in the sealed tree and not a deletion is generated output,
110
+ * so a repository that COMMITS its fixture session keeps a perfectly valid
111
+ * read declaration whose bytes stay immutable.
112
+ *
113
+ * Args:
114
+ * entry: the changed path, with its tree-diff status.
115
+ * mode: the path's git mode in the sealed candidate tree.
116
+ * parentTracked: every path the parent's commit tracks.
117
+ * currentTracked: every path this run's commit tracks.
118
+ * inputFiles: the paths this run's input snapshot binds, or null when
119
+ * the caller has no inventory (never a guess).
120
+ *
121
+ * Returns:
122
+ * string | null: the plain refusal, or null when admissible.
123
+ */
124
+ function generatedStateRefusal(entry, mode, parentTracked, currentTracked, inputFiles) {
125
+ const named = `declared browser state changed: ${entry.path}`;
126
+ if (parentTracked.has(entry.path) || currentTracked.has(entry.path)) {
127
+ return (`${named} — it is tracked by git, so it is source: a use.storageState declaration is a READ path, ` +
128
+ 'never a write permission over tracked bytes');
129
+ }
130
+ if (inputFiles !== null && inputFiles.has(entry.path)) {
131
+ return `${named} — it is bound by this run's input snapshot, so preparation may not redefine what the run tested`;
132
+ }
133
+ if (entry.status === 'D') {
134
+ return `${named} — a removal is never preparation output, so it cannot be carried as a state change`;
135
+ }
136
+ if (mode === undefined || !Object.hasOwn(REGULAR_FILE_MODE, mode)) {
137
+ return `${named} — it is not an ordinary file inside the sealed candidate, so it is never generated output`;
138
+ }
139
+ return null;
140
+ }
141
+ /**
142
+ * Extensions whose import statements the graph resolves.
143
+ *
144
+ * A fixed string-keyed lookup, so it is a Record and membership is
145
+ * `Object.hasOwn` — never the `in` operator, which would answer `true`
146
+ * for an inherited prototype key. The keys are extensions, so nothing in
147
+ * the graph can name a prototype member; the own-property test is what
148
+ * keeps that guarantee independent of the key spelling.
149
+ */
150
+ const SOURCE_EXTENSIONS = {
151
+ '.ts': true,
152
+ '.tsx': true,
153
+ '.mts': true,
154
+ '.cts': true,
155
+ '.js': true,
156
+ '.jsx': true,
157
+ '.mjs': true,
158
+ '.cjs': true,
159
+ '.py': true,
160
+ };
161
+ /** Suffixes a relative specifier may carry, longest first. */
162
+ const RESOLVABLE_SUFFIXES = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.py'];
163
+ /**
164
+ * Runs one git plumbing command against the authority object store and
165
+ * returns its raw stdout bytes. Object sizes git reports are BYTE
166
+ * counts, so any caller that cuts output by those sizes must work on
167
+ * these bytes, never on a decoded string.
168
+ *
169
+ * Args:
170
+ * gitDir: the absolute git dir.
171
+ * env: the process environment (Git redirectors are stripped).
172
+ * args: the git arguments.
173
+ * input: optional stdin text.
174
+ *
175
+ * Returns:
176
+ * Buffer | null: stdout bytes, or null when git exits non-zero.
177
+ */
178
+ function runBytes(gitDir, env, args, input) {
179
+ const result = spawnSync('git', ['--git-dir', gitDir, '--no-replace-objects', ...args], {
180
+ env: sanitizedAuthorityEnv(env),
181
+ ...(input !== undefined ? { input } : {}),
182
+ maxBuffer: 256 * 1024 * 1024,
183
+ });
184
+ if (result.error !== undefined) {
185
+ throw new UsageError(`re-seal change classification: cannot run git: ${result.error.message}`);
186
+ }
187
+ if (result.status !== 0)
188
+ return null;
189
+ return result.stdout;
190
+ }
191
+ function run(gitDir, env, args, input) {
192
+ return runBytes(gitDir, env, args, input)?.toString('utf8') ?? null;
193
+ }
194
+ function extname(path) {
195
+ const base = path.slice(path.lastIndexOf('/') + 1);
196
+ const dot = base.lastIndexOf('.');
197
+ return dot <= 0 ? '' : base.slice(dot).toLowerCase();
198
+ }
199
+ /**
200
+ * Computes the changed path set between two sealed candidate trees in
201
+ * one object store (`git diff-tree -r --no-renames`, so a rename reads
202
+ * as a delete plus an add and can never smuggle content past the
203
+ * classification).
204
+ *
205
+ * Args:
206
+ * gitDir: the absolute git dir holding both tree objects.
207
+ * env: the process environment (Git redirectors are stripped).
208
+ * parentTreeId: the parent receipt's sealed candidate tree.
209
+ * currentTreeId: the candidate tree this run froze.
210
+ *
211
+ * Returns:
212
+ * ChangedPath[]: every changed path with its status, sorted by path;
213
+ * null when the diff cannot be computed (never a guess).
214
+ */
215
+ export function diffSealedTrees(gitDir, env, parentTreeId, currentTreeId) {
216
+ const out = run(gitDir, env, ['diff-tree', '-r', '--no-renames', '--no-commit-id', parentTreeId, currentTreeId]);
217
+ if (out === null)
218
+ return null;
219
+ const changed = [];
220
+ for (const line of out.split('\n')) {
221
+ if (line.trim().length === 0)
222
+ continue;
223
+ // `:100644 100644 <old> <new> M\t<path>` — the path is everything
224
+ // after the first tab and may contain spaces.
225
+ const tab = line.indexOf('\t');
226
+ if (tab < 0)
227
+ return null;
228
+ const meta = line.slice(0, tab).trim().split(/\s+/);
229
+ const status = meta[meta.length - 1] ?? '';
230
+ const path = line.slice(tab + 1);
231
+ if (status.length === 0 || path.length === 0)
232
+ return null;
233
+ changed.push({ path, status });
234
+ }
235
+ changed.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));
236
+ return changed;
237
+ }
238
+ /**
239
+ * Whether a re-seal parent is bound to its OWN commit: the commit the
240
+ * parent document says it sealed must exist in this repository's
241
+ * object store and be an ancestor of (or equal to) HEAD. A parent
242
+ * sealed on a sibling branch, or one whose commit this repository
243
+ * cannot read, proves nothing about the bytes this run froze.
244
+ *
245
+ * The commit is read from the parent DOCUMENT, never from a CI
246
+ * variable: a merge request's diff base is a different commit from the
247
+ * one the previous pipeline tested, and no CI sets that variable to
248
+ * the parent anyway.
249
+ *
250
+ * Args:
251
+ * gitDir: the absolute git dir of this repository.
252
+ * env: the process environment (Git redirectors are stripped).
253
+ * sha: the commit the parent document names, or null when it names
254
+ * none.
255
+ *
256
+ * Returns:
257
+ * 'ancestor' when the commit exists and HEAD descends from it,
258
+ * 'missing' when the parent names no commit or none this
259
+ * repository can read, and 'diverged' when the commit exists but
260
+ * HEAD does not descend from it.
261
+ */
262
+ export function parentCommitAcceptance(gitDir, env, sha) {
263
+ const commit = (sha ?? '').trim();
264
+ if (gitDir === null || !/^[0-9a-f]{40}$/.test(commit))
265
+ return 'missing';
266
+ if (runBytes(gitDir, env, ['cat-file', '-e', `${commit}^{commit}`]) === null)
267
+ return 'missing';
268
+ return runBytes(gitDir, env, ['merge-base', '--is-ancestor', commit, 'HEAD']) === null ? 'diverged' : 'ancestor';
269
+ }
270
+ /**
271
+ * Tests whether a parent receipt's sealed tree and the tree this run
272
+ * froze differ ONLY in paths the caller already evaluated itself.
273
+ *
274
+ * A sealed candidate tree carries the workspace's untracked and
275
+ * gitignored bytes, so a verified parent proves the outcomes for ITS
276
+ * bytes — never for whatever the workspace holds now. A path the
277
+ * caller never evaluated (a gitignored dependency, an untracked file)
278
+ * is therefore invisible to its decision, and reusing the parent's
279
+ * outcomes over it would carry a proof nobody produced. The re-seal
280
+ * path does not need this test because it classifies the whole
281
+ * difference itself (see `classifyResealChange`).
282
+ *
283
+ * Args:
284
+ * gitDir: the absolute git dir holding both tree objects.
285
+ * env: the process environment (Git redirectors are stripped).
286
+ * parentTreeId: the parent receipt's sealed candidate tree.
287
+ * currentTreeId: the candidate tree this run froze.
288
+ * evaluatedPaths: repo-relative posix paths the caller evaluated.
289
+ *
290
+ * Returns:
291
+ * boolean: true only when the trees differ exclusively in evaluated
292
+ * paths; false on any unevaluated path or an undiffable pair (fail
293
+ * closed — the caller then runs exactly as it did before).
294
+ */
295
+ export function carryDiffIsWithinScope(input) {
296
+ const changed = diffSealedTrees(input.gitDir, input.env, input.parentTreeId, input.currentTreeId);
297
+ if (changed === null)
298
+ return false;
299
+ const evaluated = new Set(input.evaluatedPaths);
300
+ return changed.every((entry) => evaluated.has(entry.path));
301
+ }
302
+ /** One regex per static Python import form. */
303
+ const PYTHON_IMPORT_PATTERNS = [
304
+ /^\s*import\s+([\w.]+)\s*(?:$|#)/gm,
305
+ /^\s*from\s+([\w.]+)\s+import\b/gm,
306
+ /^\s*from\s+(\.[\w.]*)\s+import\b/gm,
307
+ ];
308
+ /**
309
+ * One Python module-loading call form: the head that locates the call,
310
+ * and the same call with a single string-literal argument. A literal
311
+ * specifier is fixed at parse time, so the call is an ordinary import
312
+ * edge; anything else (a variable, a concatenation, a template with
313
+ * `${…}`) is computed and refuses the re-seal.
314
+ */
315
+ const PYTHON_MODULE_CALLS = [
316
+ {
317
+ head: /\bimportlib\s*\.\s*import_module\s*\(/g,
318
+ literal: /\bimportlib\s*\.\s*import_module\s*\(\s*(?:(['"])([^'"\n]*)\1|`([^`$\n]*)`)\s*\)/,
319
+ },
320
+ {
321
+ head: /\b__import__\s*\(/g,
322
+ literal: /\b__import__\s*\(\s*(?:(['"])([^'"\n]*)\1|`([^`$\n]*)`)\s*\)/,
323
+ },
324
+ ];
325
+ /**
326
+ * The parser mode a path's extension implies, so a `.tsx` file is read
327
+ * as TSX and a `.mjs` file as JS rather than being parsed as the wrong
328
+ * language and refused for bytes that are perfectly valid.
329
+ *
330
+ * Args:
331
+ * path: repository-relative POSIX path.
332
+ *
333
+ * Returns:
334
+ * ts.ScriptKind: the parser mode for that path.
335
+ */
336
+ function scriptKindFor(path) {
337
+ const extension = extname(path);
338
+ if (extension === '.tsx')
339
+ return ts.ScriptKind.TSX;
340
+ if (extension === '.jsx')
341
+ return ts.ScriptKind.JSX;
342
+ if (extension === '.js' || extension === '.mjs' || extension === '.cjs')
343
+ return ts.ScriptKind.JS;
344
+ return ts.ScriptKind.TS;
345
+ }
346
+ /**
347
+ * The Python source with comment lines and triple-quoted block text
348
+ * removed, so only real code is left to scan. A line whose first
349
+ * non-space character is `#` is a comment, and text between `'''` or
350
+ * `"""` delimiters is a string: neither is syntax, and neither can
351
+ * declare an import.
352
+ *
353
+ * Args:
354
+ * source: the blob's bytes.
355
+ *
356
+ * Returns:
357
+ * string: the code lines, rejoined.
358
+ */
359
+ function pythonCodeOnly(source) {
360
+ const kept = [];
361
+ let closer = null;
362
+ for (const line of source.split('\n')) {
363
+ if (closer !== null) {
364
+ if (line.includes(closer))
365
+ closer = null;
366
+ continue;
367
+ }
368
+ if (line.trimStart().startsWith('#'))
369
+ continue;
370
+ let code = line;
371
+ for (;;) {
372
+ // The earliest triple-quote on the line opens a string. A partner
373
+ // on the same line makes the whole string droppable; without one
374
+ // the string runs on, and the rest of the file is its text.
375
+ const [earliest] = ['"""', "'''"]
376
+ .map((quote) => ({ quote, at: code.indexOf(quote) }))
377
+ .filter((candidate) => candidate.at >= 0)
378
+ .sort((left, right) => left.at - right.at);
379
+ if (earliest === undefined)
380
+ break;
381
+ const end = code.indexOf(earliest.quote, earliest.at + 3);
382
+ if (end < 0) {
383
+ code = code.slice(0, earliest.at);
384
+ closer = earliest.quote;
385
+ break;
386
+ }
387
+ code = code.slice(0, earliest.at) + code.slice(end + 3);
388
+ }
389
+ kept.push(code);
390
+ }
391
+ return kept.join('\n');
392
+ }
393
+ /**
394
+ * The suffix every refusal line ends with. The re-seal path is
395
+ * attempted only under `--scope changed`, so the only thing a refusal
396
+ * ever changes is that this run takes the ordinary CHANGED-SCOPE path
397
+ * (three tests, `scope: changed` receipt) — never a full run.
398
+ */
399
+ export const RESEAL_REFUSAL_SUFFIX = '→ changed-scope run';
400
+ /** One plain reason line, ending in what this run actually does next. */
401
+ export function resealRefusal(reason) {
402
+ return `${reason} ${RESEAL_REFUSAL_SUFFIX}`;
403
+ }
404
+ /** The same reason without the suffix, for a recomputation verdict. */
405
+ export function resealRefusalVerdict(reason) {
406
+ return String(reason).replace(new RegExp(` ${RESEAL_REFUSAL_SUFFIX}$`), '');
407
+ }
408
+ /**
409
+ * The one plain line a run prints when a declared runtime file was
410
+ * dropped from the change set, so a user sees exactly which ignored
411
+ * bytes the decision ignored instead of having to infer it.
412
+ *
413
+ * Args:
414
+ * paths: the disregarded changed paths, sorted.
415
+ *
416
+ * Returns:
417
+ * string: the line body, without the `test-gates: ` prefix the
418
+ * caller writes (that prefix is the surface, not the message).
419
+ */
420
+ export function resealDisregardNotice(paths) {
421
+ return `re-seal disregards ${String(paths.length)} declared runtime file(s): ${paths.join(', ')}`;
422
+ }
423
+ /**
424
+ * Reads one JS/TS blob's import statements out of its syntax tree.
425
+ * Comments and string contents are not syntax, so a sentence that
426
+ * happens to name an import call can never be read as one. A specifier
427
+ * written as a string literal or a no-substitution template is fixed at
428
+ * parse time and is an ordinary edge; every other argument form — a
429
+ * variable, a concatenation, a template with `${…}` — computes the
430
+ * specifier and refuses. Bytes the parser cannot read refuse too,
431
+ * because an unread file cannot be shown to declare nothing computed.
432
+ *
433
+ * Args:
434
+ * path: repository-relative POSIX path (selects the parser mode).
435
+ * source: the blob's bytes.
436
+ *
437
+ * Returns:
438
+ * TrackedFile: the edges, the computed-import flag, the parse flag.
439
+ */
440
+ function parseScriptFile(path, source) {
441
+ // A byte-order mark is an encoding artifact, not source text. Node
442
+ // strips one before compiling, and the TypeScript parser cannot read
443
+ // a shebang that follows it, so leaving the mark in place would
444
+ // refuse a re-seal over bytes that run.
445
+ const text = source.charCodeAt(0) === 0xfeff ? source.slice(1) : source;
446
+ const sourceFile = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, scriptKindFor(path));
447
+ const parseDiagnostics = sourceFile
448
+ .parseDiagnostics;
449
+ if ((parseDiagnostics ?? []).length > 0) {
450
+ return { path, imports: [], dynamic: false, unparsable: true };
451
+ }
452
+ const imports = [];
453
+ let dynamic = false;
454
+ const record = (expression) => {
455
+ if (expression === undefined) {
456
+ dynamic = true;
457
+ return;
458
+ }
459
+ if (!ts.isStringLiteral(expression) && !ts.isNoSubstitutionTemplateLiteral(expression)) {
460
+ dynamic = true;
461
+ return;
462
+ }
463
+ imports.push({ specifier: expression.text });
464
+ };
465
+ const visit = (node) => {
466
+ if (ts.isImportDeclaration(node)) {
467
+ record(node.moduleSpecifier);
468
+ }
469
+ else if (ts.isExportDeclaration(node)) {
470
+ // `export { x };` re-exports a local binding and loads nothing;
471
+ // only `export … from 'y'` names a module.
472
+ if (node.moduleSpecifier !== undefined)
473
+ record(node.moduleSpecifier);
474
+ }
475
+ else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
476
+ record(node.moduleReference.expression);
477
+ }
478
+ else if (ts.isImportTypeNode(node)) {
479
+ // A type-position `import('x').T` loads nothing at run time, but
480
+ // it still couples this file to the target's shape, so it is an
481
+ // edge; only a computed one refuses.
482
+ if (!ts.isLiteralTypeNode(node.argument) || !ts.isStringLiteral(node.argument.literal))
483
+ dynamic = true;
484
+ else
485
+ imports.push({ specifier: node.argument.literal.text });
486
+ }
487
+ else if (ts.isCallExpression(node)) {
488
+ if (node.expression.kind === ts.SyntaxKind.ImportKeyword)
489
+ record(node.arguments[0]);
490
+ else if (ts.isIdentifier(node.expression) && node.expression.text === 'require')
491
+ record(node.arguments[0]);
492
+ }
493
+ ts.forEachChild(node, visit);
494
+ };
495
+ ts.forEachChild(sourceFile, visit);
496
+ return { path, imports, dynamic, unparsable: false };
497
+ }
498
+ /**
499
+ * Reads one Python blob's import statements out of its code lines.
500
+ *
501
+ * Args:
502
+ * path: repository-relative POSIX path.
503
+ * source: the blob's bytes.
504
+ *
505
+ * Returns:
506
+ * TrackedFile: the edges and the computed-import flag.
507
+ */
508
+ function parsePythonFile(path, source) {
509
+ const code = pythonCodeOnly(source);
510
+ const imports = [];
511
+ for (const pattern of PYTHON_IMPORT_PATTERNS) {
512
+ for (const match of code.matchAll(pattern)) {
513
+ if (match[1] !== undefined)
514
+ imports.push({ specifier: match[1] });
515
+ }
516
+ }
517
+ // A literal argument is a normal edge; the backtick alternative
518
+ // excludes `$`, so an interpolated template never matches it.
519
+ let dynamic = false;
520
+ for (const call of PYTHON_MODULE_CALLS) {
521
+ for (const match of code.matchAll(call.head)) {
522
+ const literal = call.literal.exec(code.slice(match.index));
523
+ const specifier = literal?.[2] ?? literal?.[3];
524
+ if (literal === null || specifier === undefined)
525
+ dynamic = true;
526
+ else
527
+ imports.push({ specifier });
528
+ }
529
+ }
530
+ return { path, imports, dynamic, unparsable: false };
531
+ }
532
+ /** Parses one file's import statements out of its bytes. */
533
+ function parseTrackedFile(path, source) {
534
+ return extname(path) === '.py' ? parsePythonFile(path, source) : parseScriptFile(path, source);
535
+ }
536
+ /**
537
+ * Splits a `git cat-file --batch` transcript into the requested blobs'
538
+ * texts, in request order. Records are read sequentially by the BYTE
539
+ * sizes git reports; decoding happens per blob, after the cut, so a
540
+ * multi-byte character can never shift a record boundary.
541
+ *
542
+ * Args:
543
+ * batch: the raw transcript bytes.
544
+ * shas: the object ids that were requested, in order.
545
+ *
546
+ * Returns:
547
+ * string[] | null: one decoded text per requested id, or null when
548
+ * any record is missing, is not a blob, or is truncated — an unread
549
+ * object is never read as "declares nothing".
550
+ */
551
+ function batchBlobs(batch, shas) {
552
+ const texts = [];
553
+ let offset = 0;
554
+ for (const sha of shas) {
555
+ const headerEnd = batch.indexOf(0x0a, offset);
556
+ if (headerEnd < 0)
557
+ return null;
558
+ const [id, type, sizeText] = batch.toString('utf8', offset, headerEnd).split(' ');
559
+ const size = Number.parseInt(sizeText ?? '', 10);
560
+ if (id !== sha || type !== 'blob' || !Number.isSafeInteger(size) || size < 0)
561
+ return null;
562
+ const bodyEnd = headerEnd + 1 + size;
563
+ if (bodyEnd >= batch.length || batch[bodyEnd] !== 0x0a)
564
+ return null;
565
+ texts.push(batch.toString('utf8', headerEnd + 1, bodyEnd));
566
+ offset = bodyEnd + 1;
567
+ }
568
+ return texts;
569
+ }
570
+ /**
571
+ * Lists the tracked source files of a sealed tree with the imports
572
+ * their bytes declare. Content comes from the object store, not the
573
+ * workspace, so the graph describes exactly the tree under judgement.
574
+ *
575
+ * Args:
576
+ * gitDir: the absolute git dir holding the tree object.
577
+ * env: the process environment (Git redirectors are stripped).
578
+ * treeId: the sealed candidate tree.
579
+ *
580
+ * Returns:
581
+ * TrackedFile[]: parsed source files sorted by path; null when the
582
+ * tree cannot be read (never a partial graph).
583
+ */
584
+ function trackedSources(gitDir, env, treeId) {
585
+ const listing = run(gitDir, env, ['ls-tree', '-r', '-z', treeId]);
586
+ if (listing === null)
587
+ return null;
588
+ const entries = [];
589
+ for (const record of listing.split('\0')) {
590
+ if (record.length === 0)
591
+ continue;
592
+ const tab = record.indexOf('\t');
593
+ if (tab < 0)
594
+ return null;
595
+ const meta = record.slice(0, tab).split(/\s+/);
596
+ const sha = meta[2] ?? '';
597
+ const path = record.slice(tab + 1);
598
+ if ((meta[1] ?? '') !== 'blob' || sha.length === 0)
599
+ continue;
600
+ if (!Object.hasOwn(SOURCE_EXTENSIONS, extname(path)))
601
+ continue;
602
+ entries.push({ path, sha });
603
+ }
604
+ if (entries.length === 0)
605
+ return [];
606
+ const shas = entries.map((entry) => entry.sha);
607
+ const batch = runBytes(gitDir, env, ['cat-file', '--batch'], `${shas.join('\n')}\n`);
608
+ const texts = batch === null ? null : batchBlobs(batch, shas);
609
+ if (texts === null)
610
+ return null;
611
+ return entries
612
+ .map((entry, index) => parseTrackedFile(entry.path, texts[index] ?? ''))
613
+ .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));
614
+ }
615
+ /** Reads the repository's tsconfig/jsconfig path aliases (fail closed). */
616
+ function pathAliases(cwd) {
617
+ for (const name of ['tsconfig.json', 'jsconfig.json']) {
618
+ let raw;
619
+ try {
620
+ raw = readFileSync(join(cwd, name), 'utf8');
621
+ }
622
+ catch {
623
+ continue;
624
+ }
625
+ let parsed;
626
+ try {
627
+ // tsconfig documents carry comments and trailing commas.
628
+ parsed = JSON.parse(raw
629
+ .replace(/\/\*[\s\S]*?\*\//g, '')
630
+ .replace(/(^|\s)\/\/.*$/gm, '$1')
631
+ .replace(/,\s*([}\]])/g, '$1'));
632
+ }
633
+ catch {
634
+ return [];
635
+ }
636
+ const options = parsed
637
+ ?.compilerOptions;
638
+ const aliases = [];
639
+ for (const [pattern, targets] of Object.entries(options?.paths ?? {})) {
640
+ const target = targets[0];
641
+ if (target === undefined)
642
+ continue;
643
+ aliases.push({
644
+ prefix: pattern.endsWith('/*') ? pattern.slice(0, -2) : pattern.replace(/\*$/, ''),
645
+ target: relative(cwd, resolve(cwd, options?.baseUrl ?? '.', target.replace(/\*$/, '')))
646
+ .split(/[\\/]/)
647
+ .join('/'),
648
+ });
649
+ }
650
+ return aliases;
651
+ }
652
+ return [];
653
+ }
654
+ function resolutionCandidates(fromFile, specifier, aliases) {
655
+ let base = null;
656
+ if (specifier.startsWith('.')) {
657
+ base = posix.normalize(posix.join(posix.dirname(fromFile), specifier));
658
+ }
659
+ else {
660
+ const alias = aliases.find((candidate) => specifier.startsWith(candidate.prefix));
661
+ if (alias !== undefined) {
662
+ base = posix.normalize(posix.join(alias.target, specifier.slice(alias.prefix.length).replace(/^\//, '')));
663
+ }
664
+ else if (/^[@a-zA-Z]/.test(specifier)) {
665
+ return [];
666
+ }
667
+ else {
668
+ return null;
669
+ }
670
+ }
671
+ return [
672
+ base,
673
+ // An ESM-style specifier names the emitted extension; the source may
674
+ // be its TypeScript twin (`./helper.js` resolves to `helper.ts`).
675
+ ...(base.match(/\.(js|mjs|cjs|jsx)$/) !== null
676
+ ? [base.replace(/\.(js|mjs|cjs|jsx)$/, '.ts'), base.replace(/\.(js|mjs|cjs|jsx)$/, '.tsx')]
677
+ : []),
678
+ ...RESOLVABLE_SUFFIXES.map((suffix) => `${base}${suffix}`),
679
+ ...RESOLVABLE_SUFFIXES.slice(0, 4).map((suffix) => `${base}/index${suffix}`),
680
+ ];
681
+ }
682
+ /** Each configured runner reads its own config, not another runner's root file. */
683
+ const RUNNER_CONFIG_NAMES = {
684
+ playwright: PLAYWRIGHT_CONFIG_NAMES,
685
+ vitest: ['vitest.config.ts', 'vitest.config.js'],
686
+ cypress: ['cypress.config.ts', 'cypress.config.js'],
687
+ pytest: [],
688
+ };
689
+ /**
690
+ * True for a test file the setup naming conventions claim: the
691
+ * extension-stripped basename ends in `setup` (`auth.setup.ts`,
692
+ * `global-setup.ts`, `e2e/setup.ts`) and is not itself a spec/test
693
+ * file, whose name says nothing about the stage it runs in.
694
+ */
695
+ function isSetupByConvention(path) {
696
+ const base = path.slice(path.lastIndexOf('/') + 1);
697
+ const dot = base.lastIndexOf('.');
698
+ const stem = (dot <= 0 ? base : base.slice(0, dot)).toLowerCase();
699
+ if (/(?:^|[.\-_])(?:spec|test)$/.test(stem))
700
+ return false;
701
+ return /(?:^|[.\-_])(?:global[-_])?setup$/.test(stem);
702
+ }
703
+ /** Splits a brace-delimited array/object literal into its top-level items. */
704
+ function splitTopLevel(text) {
705
+ const items = [];
706
+ let depth = 0;
707
+ let start = 0;
708
+ let quote = null;
709
+ for (let index = 0; index < text.length; index += 1) {
710
+ const char = text[index];
711
+ if (quote !== null) {
712
+ if (char === quote)
713
+ quote = null;
714
+ continue;
715
+ }
716
+ if (char === "'" || char === '"' || char === '`') {
717
+ quote = char;
718
+ continue;
719
+ }
720
+ if (char === '{' || char === '[')
721
+ depth += 1;
722
+ else if (char === '}' || char === ']') {
723
+ depth -= 1;
724
+ if (depth === 0) {
725
+ items.push(text.slice(start, index + 1).trim());
726
+ start = index + 1;
727
+ }
728
+ }
729
+ else if (char === ',' && depth === 0) {
730
+ // Between top-level items: the item was already closed and pushed.
731
+ start = index + 1;
732
+ }
733
+ }
734
+ const tail = text.slice(start).trim();
735
+ if (tail.length > 0)
736
+ items.push(tail);
737
+ return items;
738
+ }
739
+ /**
740
+ * The string values of already-split items, or null when any item is
741
+ * not a plain quoted literal (a computed value fails closed).
742
+ */
743
+ function stringLiterals(items) {
744
+ const values = [];
745
+ for (const item of items) {
746
+ const value = /^['"`]([^'"`]+)['"`]$/.exec(item)?.[1];
747
+ if (value === undefined)
748
+ return null;
749
+ values.push(value);
750
+ }
751
+ return values;
752
+ }
753
+ /** Reads selected config bytes only from the sealed tree, never the working copy. */
754
+ function runnerConfigText(gitDir, env, treeId) {
755
+ const root = run(gitDir, env, ['ls-tree', '-z', treeId]);
756
+ if (root === null)
757
+ return null;
758
+ const rootPaths = new Set();
759
+ const nested = [];
760
+ for (const entry of root.split('\0')) {
761
+ const tab = entry.indexOf('\t');
762
+ if (tab < 0)
763
+ continue;
764
+ const name = entry.slice(tab + 1);
765
+ rootPaths.add(name);
766
+ if (entry.startsWith('040000 tree ') && CONFIG_SEARCH_PRUNED_DIRS[name] !== true)
767
+ nested.push(name);
768
+ }
769
+ let runner = 'playwright';
770
+ if (rootPaths.has('.gateforge.yml')) {
771
+ const config = run(gitDir, env, ['cat-file', 'blob', `${treeId}:.gateforge.yml`]);
772
+ if (config === null)
773
+ return null;
774
+ try {
775
+ const document = parseYaml(config);
776
+ if (typeof document?.runner === 'string')
777
+ runner = document.runner;
778
+ }
779
+ catch {
780
+ return null;
781
+ }
782
+ }
783
+ if (!Object.hasOwn(RUNNER_CONFIG_NAMES, runner))
784
+ return null;
785
+ for (const name of RUNNER_CONFIG_NAMES[runner] ?? []) {
786
+ if (!rootPaths.has(name))
787
+ continue;
788
+ const text = run(gitDir, env, ['cat-file', 'blob', `${treeId}:${name}`]);
789
+ return text === null ? null : { text, directory: '.', name, runner };
790
+ }
791
+ if (runner !== 'playwright' || nested.length === 0)
792
+ return null;
793
+ nested.sort();
794
+ // One bounded listing of immediate children, not one Git process per candidate.
795
+ const children = run(gitDir, env, ['ls-tree', '--name-only', '-z', treeId, ...nested.map((name) => `${name}/`)]);
796
+ if (children === null)
797
+ return null;
798
+ const paths = new Set(children.split('\0'));
799
+ for (const directory of nested) {
800
+ for (const name of PLAYWRIGHT_CONFIG_NAMES) {
801
+ const path = `${directory}/${name}`;
802
+ if (!paths.has(path))
803
+ continue;
804
+ const text = run(gitDir, env, ['cat-file', 'blob', `${treeId}:${path}`]);
805
+ return text === null ? null : { text, directory, name, runner };
806
+ }
807
+ }
808
+ return null;
809
+ }
810
+ /**
811
+ * Resolves the setup/dependency stage from the runner config's own
812
+ * bytes: every project another project names in `dependencies` owns
813
+ * the test files its `testMatch` selects. A `dependencies` value that
814
+ * is not a literal list of project names leaves the stage unresolved,
815
+ * which fails the whole re-seal closed rather than guessing.
816
+ *
817
+ * Args:
818
+ * gitDir: the absolute git dir holding the tree object.
819
+ * env: the process environment (Git redirectors are stripped).
820
+ * treeId: the sealed candidate tree.
821
+ * testFiles: repository-relative paths the runner catalog enumerates.
822
+ *
823
+ * Returns:
824
+ * SetupStage: the setup test files, or `unresolved` when the config
825
+ * declares a dependency stage the bytes do not pin down.
826
+ */
827
+ function setupStage(gitDir, env, treeId, testFiles) {
828
+ const files = new Set(testFiles.filter((file) => isSetupByConvention(file)));
829
+ // Tracked apart from `files`: only these are re-executed by a run
830
+ // because a `dependencies` edge orders them (see dependencyFiles).
831
+ const dependencyFiles = new Set();
832
+ const source = runnerConfigText(gitDir, env, treeId);
833
+ const config = source?.text ?? null;
834
+ // No `dependencies` token anywhere means no dependency stage the
835
+ // config declares; a token we cannot resolve fails closed below.
836
+ if (config === null || !/\bdependencies\b/.test(config)) {
837
+ return { files: [...files], dependencyFiles: [], unresolved: false };
838
+ }
839
+ const projectsAt = config.indexOf('projects');
840
+ if (projectsAt < 0)
841
+ return { files: [...files], dependencyFiles: [], unresolved: true };
842
+ const arrayAt = config.indexOf('[', projectsAt);
843
+ if (arrayAt < 0)
844
+ return { files: [...files], dependencyFiles: [], unresolved: true };
845
+ let depth = 0;
846
+ let end = -1;
847
+ for (let index = arrayAt; index < config.length; index += 1) {
848
+ const char = config[index];
849
+ if (char === '[')
850
+ depth += 1;
851
+ else if (char === ']') {
852
+ depth -= 1;
853
+ if (depth === 0) {
854
+ end = index;
855
+ break;
856
+ }
857
+ }
858
+ }
859
+ if (end < 0)
860
+ return { files: [...files], dependencyFiles: [], unresolved: true };
861
+ const outerConfig = config.slice(0, projectsAt) + config.slice(end + 1);
862
+ const inheritedTestDir = /\btestDir\s*:\s*['"`]([^'"`]+)['"`]/.exec(outerConfig)?.[1];
863
+ if (/\btestDir\s*:/.test(outerConfig) && inheritedTestDir === undefined) {
864
+ return { files: [...files], dependencyFiles: [], unresolved: true };
865
+ }
866
+ const projectLiterals = splitTopLevel(config.slice(arrayAt + 1, end)).filter((literal) => literal.startsWith('{'));
867
+ if (projectLiterals.length === 0)
868
+ return { files: [...files], dependencyFiles: [], unresolved: true };
869
+ const byName = new Map();
870
+ let anyDependency = false;
871
+ for (const literal of projectLiterals) {
872
+ const name = /\bname\s*:\s*['"`]([^'"`]+)['"`]/.exec(literal)?.[1];
873
+ if (name === undefined)
874
+ return { files: [...files], dependencyFiles: [], unresolved: true };
875
+ byName.set(name, literal);
876
+ if (/\bdependencies\s*:/.test(literal))
877
+ anyDependency = true;
878
+ }
879
+ if (!anyDependency)
880
+ return { files: [...files], dependencyFiles: [], unresolved: false };
881
+ for (const literal of projectLiterals) {
882
+ const declared = /\bdependencies\s*:\s*\[([^\]]*)\]/.exec(literal);
883
+ if (declared === null || declared[1] === undefined) {
884
+ if (/\bdependencies\s*:/.test(literal)) {
885
+ return { files: [...files], dependencyFiles: [], unresolved: true };
886
+ }
887
+ continue;
888
+ }
889
+ const names = stringLiterals(splitTopLevel(declared[1]));
890
+ if (names === null)
891
+ return { files: [...files], dependencyFiles: [], unresolved: true };
892
+ for (const name of names) {
893
+ const project = byName.get(name);
894
+ if (project === undefined)
895
+ return { files: [...files], dependencyFiles: [], unresolved: true };
896
+ const testDir = /\btestDir\s*:\s*['"`]([^'"`]+)['"`]/.exec(project)?.[1];
897
+ if (project.includes('testDir') && testDir === undefined) {
898
+ return { files: [...files], dependencyFiles: [], unresolved: true };
899
+ }
900
+ const match = /\btestMatch\s*:\s*(['"`][^'"`]+['"`]|\[[^\]]*\])/.exec(project);
901
+ if (match === null || match[1] === undefined) {
902
+ return { files: [...files], dependencyFiles: [], unresolved: true };
903
+ }
904
+ const literal = match[1];
905
+ const patterns = literal.startsWith('[') ? stringLiterals(splitTopLevel(literal.slice(1, -1))) : stringLiterals([literal]);
906
+ if (patterns === null)
907
+ return { files: [...files], dependencyFiles: [], unresolved: true };
908
+ const testRoot = posix.normalize(posix.join(source?.directory ?? '.', testDir ?? inheritedTestDir ?? '.'));
909
+ const prefix = testRoot === '.' ? '' : `${testRoot}/`;
910
+ for (const pattern of patterns) {
911
+ const matches = picomatch(pattern, { dot: true, matchBase: !pattern.includes('/') });
912
+ for (const file of testFiles) {
913
+ if (!file.startsWith(prefix))
914
+ continue;
915
+ if (matches(file.slice(prefix.length))) {
916
+ files.add(file);
917
+ dependencyFiles.add(file);
918
+ }
919
+ }
920
+ }
921
+ }
922
+ }
923
+ return { files: [...files].sort(), dependencyFiles: [...dependencyFiles].sort(), unresolved: false };
924
+ }
925
+ /**
926
+ * The name of one object-literal member, or null when the key is
927
+ * computed and therefore names nothing this resolver can read.
928
+ */
929
+ function configPropertyName(member) {
930
+ const name = member.name;
931
+ // A member the syntax tree does not give a name for is a member this
932
+ // resolver cannot key on, exactly like a computed key: it reports
933
+ // nothing rather than guessing.
934
+ if (name === undefined)
935
+ return null;
936
+ if (ts.isIdentifier(name))
937
+ return name.text;
938
+ if (ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name))
939
+ return name.text;
940
+ return null;
941
+ }
942
+ /**
943
+ * One object literal's member by name, distinguishing three states that
944
+ * must never be collapsed: the key is ABSENT, the key is present with a
945
+ * readable initializer, or the key cannot be read at all.
946
+ *
947
+ * A spread only blocks a value when it comes AFTER the literal member,
948
+ * because a later spread can overwrite it. A spread BEFORE the literal
949
+ * member is overwritten BY it, which is what keeps the common
950
+ * `defineConfig({ …devices['Desktop Chrome'], projects: […] })` shape
951
+ * readable. An absent key is reported absent even beside a spread: a
952
+ * spread that really did supply it can only make this resolver
953
+ * UNDER-report a declaration, and an unreported declaration classifies as
954
+ * app code and is refused by name — never the other way round, which is
955
+ * the direction that would matter.
956
+ */
957
+ function configProperty(object, name) {
958
+ let found = null;
959
+ for (const member of object.properties) {
960
+ if (ts.isSpreadAssignment(member)) {
961
+ if (found !== null)
962
+ return { present: true, node: null };
963
+ continue;
964
+ }
965
+ const key = configPropertyName(member);
966
+ if (key === null) {
967
+ // A computed key could be this very property, in this very place.
968
+ if (found !== null)
969
+ return { present: true, node: null };
970
+ continue;
971
+ }
972
+ if (key !== name)
973
+ continue;
974
+ if (!ts.isPropertyAssignment(member))
975
+ return { present: true, node: null };
976
+ found = member.initializer;
977
+ }
978
+ return { present: found !== null, node: found };
979
+ }
980
+ /**
981
+ * A fixed string value, or null when the expression computes one. This is
982
+ * the narrowing the whole declaration resolver rests on, exactly as it is
983
+ * for the import graph above: a string literal or a no-substitution
984
+ * template is fixed at parse time, and everything else computes.
985
+ */
986
+ function sealedString(node) {
987
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
988
+ return node.text;
989
+ return null;
990
+ }
991
+ /**
992
+ * A fixed array of strings, or null when the expression is not one. An
993
+ * empty array IS a fixed value (`dependencies: []`), which is why callers
994
+ * read presence separately from emptiness.
995
+ */
996
+ function sealedStringArray(node) {
997
+ if (!ts.isArrayLiteralExpression(node))
998
+ return null;
999
+ const values = [];
1000
+ for (const element of node.elements) {
1001
+ if (ts.isSpreadElement(element))
1002
+ return null;
1003
+ const value = sealedString(element);
1004
+ if (value === null)
1005
+ return null;
1006
+ values.push(value);
1007
+ }
1008
+ return values;
1009
+ }
1010
+ /** A fixed string OR a fixed array of strings, or null when computed. */
1011
+ function sealedStringPatterns(node) {
1012
+ const single = sealedString(node);
1013
+ return single === null ? sealedStringArray(node) : [single];
1014
+ }
1015
+ /**
1016
+ * Whether a normalized repo-relative posix path stays inside the
1017
+ * repository: not absolute, not the parent, not under it.
1018
+ */
1019
+ function withinRepository(path) {
1020
+ return path.length > 0 && !path.startsWith('/') && path !== '..' && !path.startsWith('../');
1021
+ }
1022
+ /**
1023
+ * One `testMatch` pattern against a path relative to the project's own
1024
+ * `testDir`. A pattern with no `/` matches a basename, exactly as the
1025
+ * runner's own default matching does.
1026
+ */
1027
+ function matchesTestPattern(pattern, relativePath) {
1028
+ return picomatch(pattern, { dot: true, matchBase: !pattern.includes('/') })(relativePath);
1029
+ }
1030
+ /**
1031
+ * The configuration object a runner config module default-exports, or
1032
+ * null when the module exports anything else (a call this resolver
1033
+ * cannot fold, a re-export, or nothing at all).
1034
+ */
1035
+ function sealedConfigObject(sourceFile) {
1036
+ for (const statement of sourceFile.statements) {
1037
+ if (!ts.isExportAssignment(statement) || statement.isExportEquals)
1038
+ continue;
1039
+ let expression = statement.expression;
1040
+ // `defineConfig({ … })` is the one call the runner's own shape uses,
1041
+ // and it takes exactly the object literal this resolver reads.
1042
+ if (ts.isCallExpression(expression)) {
1043
+ if (expression.arguments.length !== 1)
1044
+ return null;
1045
+ const [only] = expression.arguments;
1046
+ if (only === undefined)
1047
+ return null;
1048
+ expression = only;
1049
+ }
1050
+ while (ts.isParenthesizedExpression(expression))
1051
+ expression = expression.expression;
1052
+ return ts.isObjectLiteralExpression(expression) ? expression : null;
1053
+ }
1054
+ return null;
1055
+ }
1056
+ /**
1057
+ * Resolves the sealed runner config's projects, honouring root/global
1058
+ * inheritance the way the runner honours it.
1059
+ *
1060
+ * Every field is reported as ABSENT, FIXED or UNRESOLVED and never
1061
+ * guessed. A declaration the bytes compute (a variable, a concatenation,
1062
+ * a template with `${…}`, a call) is a doubt: it refuses, because the
1063
+ * classifier's whole job is to know who reads a declared state file.
1064
+ */
1065
+ function sealedConfigProjects(text, name, directory) {
1066
+ const unresolvable = (problem) => ({ directory, projects: [], problem });
1067
+ const source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
1068
+ const sourceFile = ts.createSourceFile(name, source, ts.ScriptTarget.Latest, true, scriptKindFor(name));
1069
+ const parseDiagnostics = sourceFile
1070
+ .parseDiagnostics;
1071
+ if ((parseDiagnostics ?? []).length > 0) {
1072
+ return unresolvable(`the runner config '${name}' does not parse, so its declarations cannot be read`);
1073
+ }
1074
+ const config = sealedConfigObject(sourceFile);
1075
+ if (config === null) {
1076
+ return unresolvable(`the runner config '${name}' exports no configuration object literal`);
1077
+ }
1078
+ // The root/global values a project inherits unless it declares its own.
1079
+ const rootUse = configProperty(config, 'use');
1080
+ if (rootUse.present && (rootUse.node === null || !ts.isObjectLiteralExpression(rootUse.node))) {
1081
+ return unresolvable(`the runner config '${name}' computes its root 'use' block`);
1082
+ }
1083
+ let rootState = null;
1084
+ if (rootUse.node !== null && ts.isObjectLiteralExpression(rootUse.node)) {
1085
+ const state = configProperty(rootUse.node, 'storageState');
1086
+ if (state.present && state.node === null) {
1087
+ return unresolvable(`the runner config '${name}' computes its root 'use.storageState'`);
1088
+ }
1089
+ // An INLINE state (`{ cookies, origins }`) names no file at all, so
1090
+ // it nominates nothing; a computed value names an unknown file,
1091
+ // which is a doubt and refuses.
1092
+ if (state.node !== null && !ts.isObjectLiteralExpression(state.node)) {
1093
+ rootState = sealedString(state.node);
1094
+ if (rootState === null) {
1095
+ return unresolvable(`the runner config '${name}' computes its root 'use.storageState'`);
1096
+ }
1097
+ }
1098
+ }
1099
+ const rootTestDir = configProperty(config, 'testDir');
1100
+ if (rootTestDir.present && (rootTestDir.node === null || sealedString(rootTestDir.node) === null)) {
1101
+ return unresolvable(`the runner config '${name}' declares a root 'testDir' that is not a fixed path`);
1102
+ }
1103
+ const rootTestMatch = configProperty(config, 'testMatch');
1104
+ if (rootTestMatch.present && (rootTestMatch.node === null || sealedStringPatterns(rootTestMatch.node) === null)) {
1105
+ return unresolvable(`the runner config '${name}' declares a root 'testMatch' that is not a fixed pattern list`);
1106
+ }
1107
+ const projectsProperty = configProperty(config, 'projects');
1108
+ if (!projectsProperty.present)
1109
+ return { directory, projects: [], problem: null };
1110
+ if (projectsProperty.node === null || !ts.isArrayLiteralExpression(projectsProperty.node)) {
1111
+ return unresolvable(`the runner config '${name}' computes its 'projects' list`);
1112
+ }
1113
+ const projects = [];
1114
+ const seen = new Set();
1115
+ for (const element of projectsProperty.node.elements) {
1116
+ if (!ts.isObjectLiteralExpression(element)) {
1117
+ return unresolvable(`the runner config '${name}' computes one of its project declarations`);
1118
+ }
1119
+ const nameProperty = configProperty(element, 'name');
1120
+ const projectName = nameProperty.node === null ? null : sealedString(nameProperty.node);
1121
+ if (!nameProperty.present || projectName === null || projectName.length === 0) {
1122
+ return unresolvable(`a project in the runner config '${name}' has no fixed name`);
1123
+ }
1124
+ if (seen.has(projectName)) {
1125
+ return unresolvable(`the runner config '${name}' declares project '${projectName}' twice`);
1126
+ }
1127
+ seen.add(projectName);
1128
+ const testDirProperty = configProperty(element, 'testDir');
1129
+ if (testDirProperty.present && (testDirProperty.node === null || sealedString(testDirProperty.node) === null)) {
1130
+ return unresolvable(`project '${projectName}' in the runner config '${name}' declares a 'testDir' that is not a fixed path`);
1131
+ }
1132
+ const testMatchProperty = configProperty(element, 'testMatch');
1133
+ if (testMatchProperty.present && (testMatchProperty.node === null || sealedStringPatterns(testMatchProperty.node) === null)) {
1134
+ return unresolvable(`project '${projectName}' in the runner config '${name}' declares a 'testMatch' that is not a fixed pattern list`);
1135
+ }
1136
+ const dependenciesProperty = configProperty(element, 'dependencies');
1137
+ if (dependenciesProperty.present && (dependenciesProperty.node === null || sealedStringArray(dependenciesProperty.node) === null)) {
1138
+ return unresolvable(`project '${projectName}' in the runner config '${name}' declares 'dependencies' that are not a fixed name list`);
1139
+ }
1140
+ const useProperty = configProperty(element, 'use');
1141
+ if (useProperty.present && (useProperty.node === null || !ts.isObjectLiteralExpression(useProperty.node))) {
1142
+ return unresolvable(`project '${projectName}' in the runner config '${name}' declares a 'use' that is not an object literal`);
1143
+ }
1144
+ let state = null;
1145
+ if (useProperty.node !== null && ts.isObjectLiteralExpression(useProperty.node)) {
1146
+ const stateProperty = configProperty(useProperty.node, 'storageState');
1147
+ if (stateProperty.present && stateProperty.node === null) {
1148
+ return unresolvable(`project '${projectName}' in the runner config '${name}' computes its 'use.storageState'`);
1149
+ }
1150
+ if (stateProperty.node !== null && !ts.isObjectLiteralExpression(stateProperty.node)) {
1151
+ state = sealedString(stateProperty.node);
1152
+ if (state === null) {
1153
+ return unresolvable(`project '${projectName}' in the runner config '${name}' computes its 'use.storageState'`);
1154
+ }
1155
+ }
1156
+ }
1157
+ const ownTestDir = testDirProperty.node === null ? null : sealedString(testDirProperty.node);
1158
+ const ownTestMatch = testMatchProperty.node === null ? null : sealedStringPatterns(testMatchProperty.node);
1159
+ projects.push({
1160
+ name: projectName,
1161
+ testDir: ownTestDir ?? (rootTestDir.node === null ? null : sealedString(rootTestDir.node)),
1162
+ testMatch: ownTestMatch ?? (rootTestMatch.node === null ? null : sealedStringPatterns(rootTestMatch.node)),
1163
+ dependencies: dependenciesProperty.node === null ? null : sealedStringArray(dependenciesProperty.node),
1164
+ state: state ?? rootState,
1165
+ });
1166
+ }
1167
+ return { directory, projects, problem: null };
1168
+ }
1169
+ /**
1170
+ * The GENERATED STATE a runner's own configuration declares, and the test
1171
+ * files that CONSUME it — read from the SEALED config's own SYNTAX, never
1172
+ * from a candidate-supplied document, never from an unsigned diagnostic
1173
+ * and never from an environment variable.
1174
+ *
1175
+ * A `use.storageState` token anywhere in the file proves nothing: a
1176
+ * comment, nested metadata, a spread or a computed value can all carry
1177
+ * the same three words with no project reading a browser state at all. So
1178
+ * the declarations come from the parsed tree, with the same conventions
1179
+ * this file's import graph uses.
1180
+ *
1181
+ * The consumer set is the declaring project plus every project that
1182
+ * DEPENDS ON it, transitively — the DOWNSTREAM closure, walked over
1183
+ * reverse dependency edges. Walking the declaring project's own
1184
+ * `dependencies` instead reaches its UPSTREAM prerequisites, which
1185
+ * produce artifacts rather than consume them, and silently omits the very
1186
+ * bodies whose saved session the file carries.
1187
+ */
1188
+ function generatedStateConsumers(gitDir, env, treeId, testFiles) {
1189
+ const source = runnerConfigText(gitDir, env, treeId);
1190
+ // No runner config in this sealed tree means nothing declares a
1191
+ // generated state, which is a fact rather than a doubt.
1192
+ if (source === null)
1193
+ return { consumers: new Map(), problem: null };
1194
+ // Only the Playwright shape declares projects and a per-project state;
1195
+ // every other runner's config keeps its classification untouched.
1196
+ if (source.runner !== 'playwright')
1197
+ return { consumers: new Map(), problem: null };
1198
+ const declaration = sealedConfigProjects(source.text, source.name, source.directory);
1199
+ if (declaration.problem !== null)
1200
+ return { consumers: new Map(), problem: declaration.problem };
1201
+ const byName = new Map();
1202
+ for (const project of declaration.projects) {
1203
+ const testRoot = posix.normalize(posix.join(declaration.directory, project.testDir ?? '.'));
1204
+ if (!withinRepository(testRoot)) {
1205
+ return {
1206
+ consumers: new Map(),
1207
+ problem: `project '${project.name}' collects from outside the repository ('${testRoot}')`,
1208
+ };
1209
+ }
1210
+ const prefix = testRoot === '.' ? '' : `${testRoot}/`;
1211
+ const owned = testFiles.filter((file) => {
1212
+ if (!file.startsWith(prefix))
1213
+ return false;
1214
+ if (project.testMatch === null)
1215
+ return true;
1216
+ const relativePath = file.slice(prefix.length);
1217
+ return project.testMatch.some((pattern) => matchesTestPattern(pattern, relativePath));
1218
+ });
1219
+ byName.set(project.name, { declaration: project, files: [...new Set(owned)].sort() });
1220
+ }
1221
+ // Reverse edges: the projects each declared project is a prerequisite
1222
+ // of. A name that resolves to no declared project leaves the graph
1223
+ // incomplete, so it is a doubt rather than an empty edge.
1224
+ const dependents = new Map();
1225
+ for (const [name, entry] of byName) {
1226
+ for (const dependency of entry.declaration.dependencies ?? []) {
1227
+ if (!byName.has(dependency)) {
1228
+ return {
1229
+ consumers: new Map(),
1230
+ problem: `project '${name}' depends on '${dependency}', which the sealed runner config does not declare`,
1231
+ };
1232
+ }
1233
+ const list = dependents.get(dependency) ?? [];
1234
+ list.push(name);
1235
+ dependents.set(dependency, list);
1236
+ }
1237
+ }
1238
+ const consumers = new Map();
1239
+ for (const entry of byName.values()) {
1240
+ if (entry.declaration.state === null)
1241
+ continue;
1242
+ const declared = posix.normalize(posix.join(declaration.directory, entry.declaration.state));
1243
+ // A declaration that resolves outside the repository names no path
1244
+ // in either sealed tree, so it can never be a changed candidate.
1245
+ if (!withinRepository(declared))
1246
+ continue;
1247
+ const reached = new Set([entry.declaration.name]);
1248
+ const queue = [entry.declaration.name];
1249
+ while (queue.length > 0) {
1250
+ const current = queue.shift();
1251
+ for (const dependent of dependents.get(current) ?? []) {
1252
+ if (reached.has(dependent))
1253
+ continue;
1254
+ reached.add(dependent);
1255
+ queue.push(dependent);
1256
+ }
1257
+ }
1258
+ const files = new Set();
1259
+ for (const name of reached) {
1260
+ for (const file of byName.get(name)?.files ?? [])
1261
+ files.add(file);
1262
+ }
1263
+ const existing = consumers.get(declared) ?? [];
1264
+ for (const file of files)
1265
+ existing.push(file);
1266
+ consumers.set(declared, [...new Set(existing)].sort());
1267
+ }
1268
+ return { consumers, problem: null };
1269
+ }
1270
+ /** Every directory the catalog's test files live in or under. */
1271
+ function testRoots(testFiles) {
1272
+ return [...new Set(testFiles.map((file) => posix.dirname(file)))].filter((dir) => dir.length > 0).sort();
1273
+ }
1274
+ function underTestRoot(path, roots) {
1275
+ return roots.some((root) => path === root || path.startsWith(`${root}/`));
1276
+ }
1277
+ /**
1278
+ * Classifies one change set against the runner's own test catalog.
1279
+ *
1280
+ * Args:
1281
+ * gitDir: the absolute git dir holding both tree objects.
1282
+ * env: the process environment (Git redirectors are stripped).
1283
+ * cwd: the repository root (tsconfig alias resolution).
1284
+ * parentTreeId: the parent receipt's sealed candidate tree.
1285
+ * currentTreeId: the candidate tree this run froze.
1286
+ * testFiles: repository-relative paths the runner catalog enumerates.
1287
+ *
1288
+ * Returns:
1289
+ * ResealChangeClassification: the classes, the affected test files, and
1290
+ * — when the change is not test-only — the single plain reason line.
1291
+ */
1292
+ export function classifyResealChange(input) {
1293
+ const changed = diffSealedTrees(input.gitDir, input.env, input.parentTreeId, input.currentTreeId);
1294
+ const changedPaths = (changed ?? []).map((entry) => entry.path);
1295
+ // An undeclared repository gets no `disregardedPaths` key at all, so
1296
+ // the whole result object is the one it got before this feature.
1297
+ const declared = input.runtimeFileGlobs ?? [];
1298
+ const refuse = (reason, disregarded = []) => ({
1299
+ eligible: false,
1300
+ reason: resealRefusal(reason),
1301
+ changedPaths,
1302
+ testFiles: [],
1303
+ helperFiles: [],
1304
+ affectedTestFiles: [],
1305
+ ...(declared.length > 0 ? { disregardedPaths: disregarded } : {}),
1306
+ });
1307
+ if (changed === null) {
1308
+ return refuse(`the sealed trees could not be diffed (${input.parentTreeId} → ${input.currentTreeId})`);
1309
+ }
1310
+ // The GENERATED STATE the SEALED runner config declares (the standard
1311
+ // auth pattern's saved session above all), read from that config's own
1312
+ // syntax. A change in one of those paths is a change in the INPUTS of
1313
+ // the tests that consume it — never app code — so it is kept out of the
1314
+ // app/helper classification and instead demands exactly those consumers
1315
+ // re-execute. Deriving it here, from the sealed config bytes, is what
1316
+ // lets the sealing run and an independent consumer recompute the
1317
+ // identical affected set with no extra receipt field and no owner
1318
+ // declaration.
1319
+ //
1320
+ // A declaration the bytes COMPUTE is a refusal, not an empty list: a
1321
+ // guess about who reads a state file is precisely the guess that must
1322
+ // not be made, and an unreadable declaration that fell through to the
1323
+ // app-code branch would only hide that doubt behind a worse message.
1324
+ const stateGraph = generatedStateConsumers(input.gitDir, input.env, input.currentTreeId, input.testFiles);
1325
+ // The two sealed COMMIT trees say which paths are TRACKED source. One
1326
+ // reading serves both decisions that need exactly that fact: an owner
1327
+ // declaration may hide only an untracked path, and a declared browser
1328
+ // state counts as generated output only when it is untracked too.
1329
+ // Without both commit trees neither decision can be made, so both fail
1330
+ // closed — an unreadable listing refuses, and an absent one classifies
1331
+ // nothing as ignorable and nothing as generated.
1332
+ let trackedness = null;
1333
+ if (input.parentCommitTreeId !== undefined &&
1334
+ input.currentCommitTreeId !== undefined &&
1335
+ (declared.length > 0 || stateGraph.consumers.size > 0)) {
1336
+ const parent = committedPaths(input.gitDir, input.env, input.parentCommitTreeId);
1337
+ const current = committedPaths(input.gitDir, input.env, input.currentCommitTreeId);
1338
+ if (parent === null || current === null) {
1339
+ return refuse(`the files tracked by the two sealed commits could not be read ` +
1340
+ `(${input.parentCommitTreeId}, ${input.currentCommitTreeId})`);
1341
+ }
1342
+ trackedness = { parent, current };
1343
+ }
1344
+ const testFileSet = new Set(input.testFiles);
1345
+ // The owner may declare runtime state the run itself rewrites (a
1346
+ // witnessed login stage's storage state, a runner's own cache): the
1347
+ // bytes are gitignored workspace state, so EVERY sealed candidate
1348
+ // tree differs from the last one in them and no re-seal could ever
1349
+ // succeed without a declaration. It is an OWNER ASSERTION, so it is
1350
+ // deliberately narrow: a matching changed path is disregarded only
1351
+ // when it is absent from BOTH sealed commits, i.e. when it exists
1352
+ // solely as untracked/ignored workspace bytes, AND when the sealed
1353
+ // runner config does not itself speak for that path. A tracked path
1354
+ // never matches, whatever the glob reads. Without a declaration, or
1355
+ // without the two commit trees to check trackedness against, nothing
1356
+ // is disregarded (fail closed).
1357
+ //
1358
+ // PRECEDENCE: the sealed runner config outranks the owner assertion,
1359
+ // because a glob is a claim about bytes while a `use.storageState`
1360
+ // nomination is a claim about who READS them. A nominated target is
1361
+ // the input of the tests that consume it, so it must reach the
1362
+ // generated-state rules below — untracked, outside the input
1363
+ // inventory, an ordinary file, not a removal, every reader
1364
+ // re-executing — instead of being swallowed as ignorable runtime
1365
+ // bytes, which is exactly how a changed state would be carried as a
1366
+ // proven cache write. And when those declarations cannot be COMPUTED
1367
+ // no nomination can be named at all, so no raw non-test path may be
1368
+ // disregarded then either: the refusal below is the only place that
1369
+ // reports that doubt, and a glob must not hide it. Every other case
1370
+ // is unchanged, which is what an ordinary runtime cache relies on.
1371
+ let disregarded = [];
1372
+ if (declared.length > 0 && trackedness !== null) {
1373
+ const { parent, current } = trackedness;
1374
+ const matchers = declared.map((glob) => picomatch(glob, { dot: true }));
1375
+ disregarded = changed
1376
+ .filter((entry) => !stateGraph.consumers.has(entry.path) &&
1377
+ (stateGraph.problem === null || testFileSet.has(entry.path)) &&
1378
+ !parent.has(entry.path) &&
1379
+ !current.has(entry.path) &&
1380
+ matchers.some((matcher) => matcher(entry.path)))
1381
+ .map((entry) => entry.path);
1382
+ }
1383
+ const ignored = new Set(disregarded);
1384
+ const changes = changed.filter((entry) => !ignored.has(entry.path));
1385
+ const classifiedPaths = changes.map((entry) => entry.path);
1386
+ if (changes.length === 0) {
1387
+ return refuse('the sealed trees are identical, so there is nothing to classify', disregarded);
1388
+ }
1389
+ const roots = testRoots(input.testFiles);
1390
+ // A sealed config whose declarations the bytes COMPUTE cannot say who
1391
+ // reads a declared state file. That is a refusal the moment the change
1392
+ // set holds a non-test path, because such a path may be exactly the
1393
+ // generated state — never a silent empty dependency set that would let
1394
+ // it through as app code nobody looked at.
1395
+ if (stateGraph.problem !== null) {
1396
+ const undecomposed = classifiedPaths.find((path) => !testFileSet.has(path));
1397
+ if (undecomposed !== undefined) {
1398
+ return refuse(`${stateGraph.problem}, so '${undecomposed}' cannot be shown to be test code`);
1399
+ }
1400
+ }
1401
+ // A declared state path is generated OUTPUT only when it is untracked
1402
+ // in both sealed commits, outside the input inventory, an ordinary file
1403
+ // in the sealed candidate and not a deletion. Anything else keeps the
1404
+ // ordinary app-code classification — which refuses it by name — so a
1405
+ // TRACKED app/config/source file can never escape that refusal merely
1406
+ // by being named in the runner config.
1407
+ const stateChanged = [];
1408
+ const stateConsumers = new Map();
1409
+ const stateConsumerFiles = new Set();
1410
+ if (stateGraph.problem === null && trackedness !== null && stateGraph.consumers.size > 0) {
1411
+ const modes = sealedTreeModes(input.gitDir, input.env, input.currentTreeId);
1412
+ if (modes === null) {
1413
+ return refuse(`the sealed candidate tree's entry modes could not be read (${input.currentTreeId})`);
1414
+ }
1415
+ for (const entry of changes) {
1416
+ const consumers = stateGraph.consumers.get(entry.path);
1417
+ if (consumers === undefined)
1418
+ continue;
1419
+ const refusal = generatedStateRefusal(entry, modes.get(entry.path), trackedness.parent, trackedness.current, input.inputFiles ?? null);
1420
+ if (refusal !== null)
1421
+ return refuse(refusal);
1422
+ stateChanged.push(entry);
1423
+ stateConsumers.set(entry.path, consumers);
1424
+ for (const file of consumers)
1425
+ stateConsumerFiles.add(file);
1426
+ }
1427
+ }
1428
+ const statePaths = new Set(stateConsumers.keys());
1429
+ const codeChanges = changes.filter((entry) => !statePaths.has(entry.path));
1430
+ const testFiles = codeChanges.filter((entry) => testFileSet.has(entry.path)).map((entry) => entry.path);
1431
+ // A deleted path is classified by the SAME catalog: a deleted test
1432
+ // file simply leaves the expected set, while a deleted anything-else is
1433
+ // app code by definition and its importers break at run time.
1434
+ for (const entry of codeChanges) {
1435
+ if (entry.status === 'D' && !testFileSet.has(entry.path)) {
1436
+ return refuse(`app file deleted: ${entry.path}`);
1437
+ }
1438
+ }
1439
+ const candidates = codeChanges.filter((entry) => !testFileSet.has(entry.path)).map((entry) => entry.path);
1440
+ // A changed path outside every test root is app code whatever the
1441
+ // import graph says, so it refuses first and by its own name: the
1442
+ // reason a user needs is "you changed app code", not a doubt about
1443
+ // some unrelated file's imports.
1444
+ const appFile = candidates.find((path) => !underTestRoot(path, roots));
1445
+ if (appFile !== undefined)
1446
+ return refuse(`app file changed: ${appFile}`);
1447
+ // A setup/dependency test file changes every dependent test without an
1448
+ // import edge, so it can never be carried. A config whose dependency
1449
+ // project the bytes do not pin down makes every changed test file a
1450
+ // possible setup file.
1451
+ const stage = setupStage(input.gitDir, input.env, input.currentTreeId, input.testFiles);
1452
+ if (stage.unresolved) {
1453
+ const first = testFiles[0];
1454
+ if (first !== undefined) {
1455
+ return refuse(`setup test changed: ${first} (the runner config declares a dependency project whose tests cannot be resolved)`);
1456
+ }
1457
+ return refuse(`setup dependency tests cannot be resolved from the runner config for ${candidates[0]}`);
1458
+ }
1459
+ else {
1460
+ const setup = testFiles.find((file) => stage.files.includes(file));
1461
+ if (setup !== undefined) {
1462
+ return refuse(`setup test changed: ${setup}`);
1463
+ }
1464
+ }
1465
+ // The import graph is consulted for EVERY change set, not only for a
1466
+ // helper claim: a spec file can export a shared fixture or a
1467
+ // `test.extend`, so a changed test file affects its importers too.
1468
+ // Any doubt the graph cannot resolve refuses the whole re-seal.
1469
+ const allSources = trackedSources(input.gitDir, input.env, input.currentTreeId);
1470
+ if (allSources === null) {
1471
+ return refuse(`the sealed tree's import graph could not be read (${input.currentTreeId})`);
1472
+ }
1473
+ // Imports never cross the language boundary: a Python import (static
1474
+ // or computed) loads only Python modules, and a JS/TS import loads
1475
+ // only JS/TS/data files. So a file can reach a changed path only when
1476
+ // the change set holds a path of its own family (a changed non-Python
1477
+ // file of any extension counts as the script family, since a script
1478
+ // can import data files). Files of the other family can hide no edge
1479
+ // and are left out of the graph, doubts included.
1480
+ const pythonChanged = classifiedPaths.some((path) => extname(path) === '.py');
1481
+ const scriptChanged = classifiedPaths.some((path) => extname(path) !== '.py');
1482
+ const sources = allSources.filter((file) => (extname(file.path) === '.py' ? pythonChanged : scriptChanged));
1483
+ // A file whose bytes the parser rejects has NOT been shown to declare
1484
+ // nothing computed, so it refuses before the graph is read.
1485
+ const unparsableFile = sources.find((file) => file.unparsable);
1486
+ if (unparsableFile !== undefined) {
1487
+ return refuse(`unresolvable import: ${unparsableFile.path} does not parse as a script`);
1488
+ }
1489
+ const dynamicFile = sources.find((file) => file.dynamic);
1490
+ if (dynamicFile !== undefined) {
1491
+ return refuse(`unresolvable import: ${dynamicFile.path} loads a module through a computed specifier`);
1492
+ }
1493
+ const aliases = pathAliases(input.cwd);
1494
+ /** Every candidate path each import could name, or null when one cannot be read. */
1495
+ const resolveImports = (file) => {
1496
+ const resolved = [];
1497
+ for (const reference of file.imports) {
1498
+ const candidates = resolutionCandidates(file.path, reference.specifier, aliases);
1499
+ if (candidates === null)
1500
+ return null;
1501
+ resolved.push(candidates);
1502
+ }
1503
+ return resolved;
1504
+ };
1505
+ /**
1506
+ * Every file whose imports could name `target`. Keyed on ALL
1507
+ * resolution candidates, not only the tracked one, so a DELETED test
1508
+ * file still reaches the specs that imported it (its own path is no
1509
+ * longer in the tree, but the importer's specifier still names it).
1510
+ */
1511
+ const importersOf = new Map();
1512
+ const importsOf = new Map();
1513
+ for (const file of sources) {
1514
+ const resolved = resolveImports(file);
1515
+ if (resolved === null) {
1516
+ const unresolvable = file.imports.find((reference) => resolutionCandidates(file.path, reference.specifier, aliases) === null);
1517
+ return refuse(`unresolvable import: ${file.path} → ${unresolvable?.specifier ?? '?'}`);
1518
+ }
1519
+ importsOf.set(file.path, resolved);
1520
+ for (const candidates of resolved) {
1521
+ for (const target of candidates) {
1522
+ const importers = importersOf.get(target);
1523
+ if (importers === undefined)
1524
+ importersOf.set(target, [file.path]);
1525
+ else if (!importers.includes(file.path))
1526
+ importers.push(file.path);
1527
+ }
1528
+ }
1529
+ }
1530
+ // Directory membership alone does not make an application importer
1531
+ // test code. Each importer must also lead to a cataloged test.
1532
+ const testCode = new Set(testFileSet);
1533
+ const pendingTestCode = [...testFileSet];
1534
+ for (let index = 0; index < pendingTestCode.length; index += 1) {
1535
+ for (const candidates of importsOf.get(pendingTestCode[index]) ?? []) {
1536
+ for (const target of candidates) {
1537
+ if (!importsOf.has(target) || testCode.has(target))
1538
+ continue;
1539
+ testCode.add(target);
1540
+ pendingTestCode.push(target);
1541
+ }
1542
+ }
1543
+ }
1544
+ const helperFiles = [];
1545
+ const affected = new Set(testFiles);
1546
+ // A DEPENDENCY project's tests run BEFORE the dependents in every
1547
+ // supervised run (the `dependencies` edge the enumeration captured),
1548
+ // so a dependent change re-executes the whole stage. The affected set
1549
+ // must say so: the chain recomputation (reseal-chain) re-derives this
1550
+ // same set from the same two trees and refuses a fresh outcome
1551
+ // outside it, so omitting the stage makes the run re-execute a test
1552
+ // its own receipt then rejects as EVIDENCE_STALE. Only files a
1553
+ // declared `dependencies` project owns are added — a
1554
+ // convention-named setup file is never re-executed, so naming it
1555
+ // would demand an outcome that never arrives. An UNRESOLVED stage
1556
+ // adds nothing: the refusal above already failed this change set
1557
+ // closed, and a stage we cannot read must not be guessed at.
1558
+ if (!stage.unresolved) {
1559
+ for (const file of stage.dependencyFiles)
1560
+ affected.add(file);
1561
+ }
1562
+ // A changed declared-state path demands exactly its consumers: the test
1563
+ // files whose own project reads it, plus every project ordered after it
1564
+ // (its upstream prerequisites, which produce the state, are already in
1565
+ // the dependency stage above). The consumers SEED the importer closure
1566
+ // below rather than only joining its result: a consumer that other
1567
+ // specs reach through a shared fixture must drag those importers with
1568
+ // it, or the run would carry proof for specs whose browser state
1569
+ // changed underneath them. A changed state target with NO consumer this
1570
+ // run can name is a refusal, not a silent pass: the bytes that changed
1571
+ // would otherwise reach a body nobody re-ran.
1572
+ for (const entry of stateChanged) {
1573
+ const consumers = stateConsumers.get(entry.path) ?? [];
1574
+ if (consumers.length === 0) {
1575
+ return refuse(`generated state changed: ${entry.path} has no consumer this run can name from the sealed runner ` +
1576
+ 'config, so nothing proves which test reads it (fail closed)');
1577
+ }
1578
+ for (const file of consumers)
1579
+ affected.add(file);
1580
+ }
1581
+ for (const path of [...new Set([...testFiles, ...candidates, ...stateConsumerFiles])]) {
1582
+ const isTestFile = testFileSet.has(path);
1583
+ // Importers re-run transitively: a shared fixture declared in a
1584
+ // helper OR in another spec file reaches every spec that imports it
1585
+ // (a helper of a helper counts). A changed test file needs no
1586
+ // importer; a changed non-test file must be proven to be a helper.
1587
+ const seen = new Set();
1588
+ const queue = [path];
1589
+ while (queue.length > 0) {
1590
+ const current = queue.shift();
1591
+ for (const file of importersOf.get(current) ?? []) {
1592
+ if (seen.has(file))
1593
+ continue;
1594
+ seen.add(file);
1595
+ if (testFileSet.has(file))
1596
+ affected.add(file);
1597
+ else if (!underTestRoot(file, roots) || !testCode.has(file)) {
1598
+ return refuse(`app file changed: ${file} imports the changed ${isTestFile ? 'test file' : 'test helper'} ${path}`);
1599
+ }
1600
+ else
1601
+ queue.push(file);
1602
+ }
1603
+ }
1604
+ if (!isTestFile && seen.size === 0) {
1605
+ return refuse(`app file changed: ${path} is imported by no test file, so it is not a test helper`);
1606
+ }
1607
+ if (!isTestFile)
1608
+ helperFiles.push(path);
1609
+ }
1610
+ return {
1611
+ eligible: true,
1612
+ reason: null,
1613
+ changedPaths,
1614
+ testFiles,
1615
+ helperFiles: helperFiles.sort(),
1616
+ affectedTestFiles: [...affected].sort(),
1617
+ ...(declared.length > 0 ? { disregardedPaths: disregarded } : {}),
1618
+ };
1619
+ }
1620
+ //# sourceMappingURL=reseal.js.map