@codyswann/lisa 4.97.4 → 4.98.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 (92) hide show
  1. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  2. package/dist/core/upstream-evidence-manifest.d.ts.map +1 -1
  3. package/dist/core/upstream-evidence-manifest.js +42 -75
  4. package/dist/core/upstream-evidence-manifest.js.map +1 -1
  5. package/package.json +5 -4
  6. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  7. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  8. package/plugins/lisa/rules/reference/derived-branch-plan.md +1 -1
  9. package/plugins/lisa-agy/plugin.json +1 -1
  10. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  11. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  12. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  13. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  14. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  15. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  16. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  17. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  18. package/plugins/lisa-copilot/rules/reference/derived-branch-plan.md +1 -1
  19. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  20. package/plugins/lisa-cursor/rules/derived-branch-plan-reference.mdc +1 -1
  21. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  22. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  23. package/plugins/lisa-devin/rules/reference/derived-branch-plan.md +1 -1
  24. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  25. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  26. package/plugins/lisa-expo-agy/plugin.json +1 -1
  27. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  28. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  29. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  30. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  31. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  32. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  33. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  34. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  35. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  36. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  37. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  38. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  39. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  40. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  41. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  42. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  43. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  44. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  45. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  46. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  47. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  48. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  49. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  50. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  51. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  52. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  53. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  54. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  55. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  56. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  57. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  58. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  59. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  60. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  61. package/plugins/lisa-rails-agy/plugin.json +1 -1
  62. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  63. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  64. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  65. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  66. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  67. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  68. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  69. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  70. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  71. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  72. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  73. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  74. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  75. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  76. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  77. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  78. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  79. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  80. package/plugins/src/base/rules/reference/derived-branch-plan.md +1 -1
  81. package/scripts/check-phrase-manifest-parity.mjs +83 -0
  82. package/scripts/classify-phrase-tests.mjs +54 -0
  83. package/scripts/fix-namespace-test-assertions.mjs +3 -19
  84. package/scripts/generate-phrase-manifest.mjs +98 -0
  85. package/scripts/lib/phrase-tests/ast.mjs +147 -0
  86. package/scripts/lib/phrase-tests/classify.mjs +293 -0
  87. package/scripts/lib/phrase-tests/fold.mjs +55 -0
  88. package/scripts/lib/phrase-tests/manifest.mjs +183 -0
  89. package/scripts/lib/phrase-tests/parity.mjs +74 -0
  90. package/scripts/lib/phrase-tests/record.mjs +568 -0
  91. package/scripts/lib/phrase-tests/repo.mjs +99 -0
  92. package/scripts/lib/phrase-tests/runner.mjs +256 -0
@@ -0,0 +1,568 @@
1
+ /**
2
+ * Translate a phrase-only test file into manifest entries by running it
3
+ * (CodySwannGT/lisa#4609).
4
+ *
5
+ * Phrase tests compute what they read and what they assert at runtime —
6
+ * `describe.each` tables, path joins, helper calls — so the values cannot be
7
+ * read off the source. Instead the file is transpiled with the TypeScript
8
+ * compiler API and executed under a stub runner (see `runner.mjs`) in which
9
+ * every file read is recorded and `expect` records instead of asserting.
10
+ *
11
+ * One runtime phrase assertion translates to `{ file, polarity, kind, value }`
12
+ * only when its subject is EXACTLY (===) the full text of a file the test
13
+ * read. A subject that is a section, a slice or a normalised copy of a file
14
+ * has no faithful manifest form, so one such assertion makes the WHOLE test
15
+ * file untranslatable: it is kept unchanged and listed with the reason.
16
+ *
17
+ * Two different files can hold identical text (generated plugin copies are
18
+ * byte-for-byte copies of their source). When a subject matches more than one
19
+ * file read, the file is run a second time with every file's text made unique
20
+ * by an appended marker; the second run attributes each assertion exactly, and
21
+ * is accepted only when it makes the same assertions in the same order.
22
+ * @module scripts/lib/phrase-tests/record
23
+ */
24
+ import fs from "node:fs";
25
+ import fsPromises from "node:fs/promises";
26
+ import path from "node:path";
27
+ import { fileURLToPath, pathToFileURL } from "node:url";
28
+ import { callbackify } from "node:util";
29
+ import vm from "node:vm";
30
+
31
+ import ts from "typescript";
32
+
33
+ import { isExpectCall, isIncludesCall } from "./ast.mjs";
34
+ import { resolveTestImport } from "./classify.mjs";
35
+ import { SOURCE_SEPARATOR } from "./manifest.mjs";
36
+ import { createRunner } from "./runner.mjs";
37
+
38
+ /** Tag on the value `__phraseIncludes` hands to `expect`. */
39
+ const INCLUDES_TAG = Symbol("phrase-includes");
40
+
41
+ /** Parameters every transpiled module body is compiled with. */
42
+ const MODULE_PARAMETERS = Object.freeze([
43
+ "require",
44
+ "module",
45
+ "exports",
46
+ "__filename",
47
+ "__dirname",
48
+ "__phraseImportMeta",
49
+ "__phraseIncludes",
50
+ ]);
51
+
52
+ /**
53
+ * @typedef {object} Entry
54
+ * @property {string} file - Repository-relative path of the file read.
55
+ * @property {"required" | "forbidden"} polarity - Must the phrase be present?
56
+ * @property {"string" | "pattern"} kind - Substring or regular expression.
57
+ * @property {string | { source: string, flags: string }} value - The phrase.
58
+ * @property {string} source - Where it came from: `<test file> › <test title path>`.
59
+ */
60
+
61
+ /**
62
+ * @typedef {object} Recording
63
+ * @property {string} file - The test file.
64
+ * @property {number} raw - Runtime phrase assertions executed.
65
+ * @property {Entry[]} entries - Translated assertions, in execution order.
66
+ * @property {string[]} reasons - Why the file is untranslatable; empty when
67
+ * every assertion translated and the file ran cleanly.
68
+ */
69
+
70
+ /**
71
+ * Source transformer: `import.meta` becomes an injected identifier (a
72
+ * CommonJS body cannot contain it), and `expect(x.includes(y))` becomes
73
+ * `expect(__phraseIncludes(x, y))` so the recorder still sees the subject.
74
+ * @param {ts.TransformationContext} context - Compiler context.
75
+ * @returns {(sourceFile: ts.SourceFile) => ts.SourceFile} The transform.
76
+ */
77
+ function phraseTransformer(context) {
78
+ const { factory } = context;
79
+ /** @type {(node: ts.Node) => ts.Node} */
80
+ const visit = node => {
81
+ if (
82
+ ts.isMetaProperty(node) &&
83
+ node.keywordToken === ts.SyntaxKind.ImportKeyword
84
+ ) {
85
+ return factory.createIdentifier("__phraseImportMeta");
86
+ }
87
+ if (isExpectCall(node) && isIncludesCall(node.arguments[0])) {
88
+ const call = /** @type {ts.CallExpression} */ (node);
89
+ const includes = /** @type {ts.CallExpression} */ (call.arguments[0]);
90
+ const owner = /** @type {ts.PropertyAccessExpression} */ (
91
+ includes.expression
92
+ );
93
+ const tagged = factory.createCallExpression(
94
+ factory.createIdentifier("__phraseIncludes"),
95
+ undefined,
96
+ [
97
+ /** @type {ts.Expression} */ (ts.visitNode(owner.expression, visit)),
98
+ /** @type {ts.Expression} */ (
99
+ ts.visitNode(includes.arguments[0], visit)
100
+ ),
101
+ ]
102
+ );
103
+ return factory.updateCallExpression(
104
+ call,
105
+ call.expression,
106
+ call.typeArguments,
107
+ [
108
+ tagged,
109
+ ...call.arguments
110
+ .slice(1)
111
+ .map(
112
+ arg => /** @type {ts.Expression} */ (ts.visitNode(arg, visit))
113
+ ),
114
+ ]
115
+ );
116
+ }
117
+ return ts.visitEachChild(node, visit, context);
118
+ };
119
+ return sourceFile =>
120
+ /** @type {ts.SourceFile} */ (ts.visitNode(sourceFile, visit));
121
+ }
122
+
123
+ /**
124
+ * Transpile TypeScript to a CommonJS module body.
125
+ * @param {string} fileName - For diagnostics.
126
+ * @param {string} text - TypeScript source.
127
+ * @returns {string} JavaScript.
128
+ */
129
+ function transpile(fileName, text) {
130
+ return ts.transpileModule(text, {
131
+ fileName,
132
+ compilerOptions: {
133
+ module: ts.ModuleKind.CommonJS,
134
+ target: ts.ScriptTarget.ES2022,
135
+ esModuleInterop: true,
136
+ },
137
+ transformers: { before: [phraseTransformer] },
138
+ }).outputText;
139
+ }
140
+
141
+ /**
142
+ * @typedef {{ text: string, polarity: "required" | "forbidden", kind: "string" | "pattern", value: string | RegExp }} Shaped
143
+ * @typedef {{ reason: string }} Unshaped
144
+ * @typedef {(Shaped | Unshaped) & { test: string | undefined, holds: boolean }} Recorded
145
+ */
146
+
147
+ /**
148
+ * One run's mutable state.
149
+ * @typedef {object} RunState
150
+ * @property {string} root - Absolute repository root.
151
+ * @property {boolean} perturb - Whether reads are served with unique markers.
152
+ * @property {{ file: string, served: string }[]} reads - Every read, in order.
153
+ * @property {Map<string, number>} markers - Path to its marker index.
154
+ * @property {Recorded[]} assertions - Recorded assertions.
155
+ * @property {string | undefined} test - Title of the running test.
156
+ */
157
+
158
+ /**
159
+ * Serve one file read: record it and, when perturbing, make its text unique.
160
+ * @param {RunState} state - The run.
161
+ * @param {unknown} target - The path argument the test passed.
162
+ * @param {string | Buffer} data - What the real read returned.
163
+ * @returns {string | Buffer} What the test receives.
164
+ */
165
+ function serve(state, target, data) {
166
+ const absolute = path.resolve(
167
+ state.root,
168
+ target instanceof URL ? fileURLToPath(target) : String(target)
169
+ );
170
+ const file = path.relative(state.root, absolute).split(path.sep).join("/");
171
+ if (typeof data !== "string") {
172
+ state.reads.push({ file, served: data.toString("utf8") });
173
+ return data;
174
+ }
175
+ if (!state.markers.has(file)) state.markers.set(file, state.markers.size);
176
+ const served = state.perturb
177
+ ? `${data}\n\u0000phrase-recorder:${state.markers.get(file)}`
178
+ : data;
179
+ state.reads.push({ file, served });
180
+ return served;
181
+ }
182
+
183
+ /**
184
+ * Resolve a read target against the repository root rather than the cwd.
185
+ * @param {RunState} state - The run.
186
+ * @param {unknown} target - Path argument.
187
+ * @returns {unknown} The resolved path (non-strings pass through).
188
+ */
189
+ function resolveTarget(state, target) {
190
+ return typeof target === "string" ? path.resolve(state.root, target) : target;
191
+ }
192
+
193
+ /**
194
+ * File-system modules whose read calls are recorded.
195
+ * @param {RunState} state - The run.
196
+ * @returns {Record<string, object>} Module id to stub.
197
+ */
198
+ function fileSystemModules(state) {
199
+ /** @type {(target: unknown, options?: unknown) => string | Buffer} */
200
+ const readFileSync = (target, options) =>
201
+ serve(
202
+ state,
203
+ target,
204
+ fs.readFileSync(
205
+ /** @type {fs.PathOrFileDescriptor} */ (resolveTarget(state, target)),
206
+ /** @type {BufferEncoding} */ (options)
207
+ )
208
+ );
209
+ /** @type {(target: unknown, options: unknown) => Promise<string | Buffer>} */
210
+ const readFilePromise = async (target, options) =>
211
+ serve(
212
+ state,
213
+ target,
214
+ await fsPromises.readFile(
215
+ /** @type {fs.PathLike} */ (resolveTarget(state, target)),
216
+ /** @type {BufferEncoding} */ (options)
217
+ )
218
+ );
219
+ const readFileCallback = callbackify(readFilePromise);
220
+ /** @type {(target: unknown, ...rest: unknown[]) => unknown} */
221
+ const readFile = (target, ...rest) => {
222
+ const callback = rest.at(-1);
223
+ if (typeof callback !== "function") return readFilePromise(target, rest[0]);
224
+ const options = rest.length > 1 ? rest[0] : undefined;
225
+ return readFileCallback(
226
+ target,
227
+ options,
228
+ /** @type {(error: NodeJS.ErrnoException | null, data: string | Buffer) => void} */ (
229
+ callback
230
+ )
231
+ );
232
+ };
233
+ // Only the read members exist: a phrase-only file never needs more, and a
234
+ // write reached through some path the classifier missed must fail loudly
235
+ // rather than touch the repository.
236
+ const promises = { readFile: readFilePromise };
237
+ const nodeFs = { readFileSync, readFile, promises };
238
+ return {
239
+ "node:fs": nodeFs,
240
+ fs: nodeFs,
241
+ "node:fs/promises": promises,
242
+ "fs/promises": promises,
243
+ "fs-extra": nodeFs,
244
+ };
245
+ }
246
+
247
+ /**
248
+ * The value handed to `expect` for `expect(x.includes(y))`.
249
+ * @param {unknown} subject - `x`.
250
+ * @param {unknown} needle - `y`.
251
+ * @returns {object} A tagged record of both.
252
+ */
253
+ function phraseIncludes(subject, needle) {
254
+ return { [INCLUDES_TAG]: true, subject, needle };
255
+ }
256
+
257
+ /**
258
+ * Normalise one matcher call into (text, polarity, kind, value), or a reason.
259
+ * @param {string} matcher - Matcher name.
260
+ * @param {unknown} subject - `expect` argument.
261
+ * @param {unknown} expected - Matcher argument.
262
+ * @param {boolean} negated - Whether `.not` was used.
263
+ * @returns {{ text: string, polarity: "required" | "forbidden", kind: "string" | "pattern", value: string | RegExp } | { reason: string }} The shape.
264
+ */
265
+ function shape(matcher, subject, expected, negated) {
266
+ const tagged =
267
+ subject !== null && typeof subject === "object" && INCLUDES_TAG in subject;
268
+ if (matcher === "toBe") {
269
+ if (!tagged || typeof expected !== "boolean")
270
+ return { reason: "toBe on something other than <text>.includes(...)" };
271
+ const { subject: text, needle } =
272
+ /** @type {{ subject: unknown, needle: unknown }} */ (
273
+ /** @type {unknown} */ (subject)
274
+ );
275
+ if (typeof text !== "string" || typeof needle !== "string")
276
+ return { reason: "includes(...) on a non-string" };
277
+ const present = expected !== negated;
278
+ return {
279
+ text,
280
+ polarity: present ? "required" : "forbidden",
281
+ kind: "string",
282
+ value: needle,
283
+ };
284
+ }
285
+ if (tagged) return { reason: `${matcher} on <text>.includes(...)` };
286
+ if (typeof subject !== "string")
287
+ return { reason: `${matcher} on a non-string subject` };
288
+ const polarity = negated ? "forbidden" : "required";
289
+ if (typeof expected === "string")
290
+ return { text: subject, polarity, kind: "string", value: expected };
291
+ if (matcher === "toMatch" && expected instanceof RegExp)
292
+ return { text: subject, polarity, kind: "pattern", value: expected };
293
+ return { reason: `${matcher} with a non-string, non-RegExp argument` };
294
+ }
295
+
296
+ /**
297
+ * Whether the phrase is present, with vitest's semantics (`toMatch` with a
298
+ * string is a substring test; with a RegExp it is `String#match`).
299
+ * @param {string} text - Subject text.
300
+ * @param {"string" | "pattern"} kind - Phrase kind.
301
+ * @param {string | RegExp} value - Phrase.
302
+ * @returns {boolean} True when present.
303
+ */
304
+ function present(text, kind, value) {
305
+ return kind === "string"
306
+ ? text.includes(/** @type {string} */ (value))
307
+ : text.match(/** @type {RegExp} */ (value)) !== null;
308
+ }
309
+
310
+ /**
311
+ * A recording `expect`: each matcher records, then throws like vitest when
312
+ * the assertion does not hold, so control flow matches a real run.
313
+ * @param {RunState} state - The run.
314
+ * @returns {(subject: unknown) => object} The `expect` function.
315
+ */
316
+ function recordingExpect(state) {
317
+ /**
318
+ * The matchers for one subject.
319
+ * @param {unknown} subject - The `expect` argument.
320
+ * @param {boolean} negated - Whether these are the `.not` matchers.
321
+ * @returns {Record<string, (expected: unknown) => void>} Matchers.
322
+ */
323
+ const matchers = (subject, negated) => {
324
+ /** @type {(matcher: string) => (expected: unknown) => void} */
325
+ const call = matcher => expected => {
326
+ const result = shape(matcher, subject, expected, negated);
327
+ const holds =
328
+ "reason" in result
329
+ ? true
330
+ : present(result.text, result.kind, result.value) ===
331
+ (result.polarity === "required");
332
+ state.assertions.push({ ...result, test: state.test, holds });
333
+ if (!holds) {
334
+ throw new Error(
335
+ `phrase assertion fails on the current tree: ${"value" in result ? String(result.value) : ""}`
336
+ );
337
+ }
338
+ };
339
+ return {
340
+ toContain: call("toContain"),
341
+ toMatch: call("toMatch"),
342
+ toBe: call("toBe"),
343
+ };
344
+ };
345
+ return subject => ({
346
+ ...matchers(subject, false),
347
+ not: matchers(subject, true),
348
+ });
349
+ }
350
+
351
+ /**
352
+ * Load one module of the test's graph: a package stub, or a transpiled
353
+ * test/helper file executed with this run's `require`.
354
+ * @param {string} file - Repository-relative path.
355
+ * @param {object} context - Run context.
356
+ * @param {RunState} context.state - The run.
357
+ * @param {(file: string) => string | undefined} context.readSource - Reads sources.
358
+ * @param {Record<string, object>} context.packages - Package id to stub.
359
+ * @param {Map<string, object>} context.cache - Loaded modules.
360
+ * @returns {object} The module's exports.
361
+ */
362
+ function loadModule(file, context) {
363
+ const cached = context.cache.get(file);
364
+ if (cached) return cached;
365
+ const text = context.readSource(file);
366
+ if (text === undefined) throw new Error(`cannot read ${file}`);
367
+ const absolute = path.join(context.state.root, file);
368
+ const module = { exports: {} };
369
+ context.cache.set(file, module.exports);
370
+ /** @type {(specifier: string) => object} */
371
+ const require = specifier => {
372
+ if (!specifier.startsWith(".")) {
373
+ const stub = context.packages[specifier];
374
+ if (stub === undefined) throw new Error(`unexpected import ${specifier}`);
375
+ return stub;
376
+ }
377
+ const helper = resolveTestImport(
378
+ file,
379
+ specifier,
380
+ candidate => context.readSource(candidate) !== undefined
381
+ );
382
+ if (helper === undefined) throw new Error(`unexpected import ${specifier}`);
383
+ return loadModule(helper, context);
384
+ };
385
+ // The module runs in an inner arrow so a file that declares its own
386
+ // `const __dirname` shadows the injected one instead of colliding with it
387
+ // (vitest provides both names, like CommonJS).
388
+ const body = vm.compileFunction(
389
+ ["return (() => {", transpile(file, text), "})();"].join("\n"),
390
+ [...MODULE_PARAMETERS],
391
+ { filename: absolute }
392
+ );
393
+ body(
394
+ require,
395
+ module,
396
+ module.exports,
397
+ absolute,
398
+ path.dirname(absolute),
399
+ {
400
+ url: pathToFileURL(absolute).href,
401
+ filename: absolute,
402
+ dirname: path.dirname(absolute),
403
+ },
404
+ phraseIncludes
405
+ );
406
+ context.cache.set(file, module.exports);
407
+ return module.exports;
408
+ }
409
+
410
+ /**
411
+ * Execute a test file once under the recording runner.
412
+ * @param {string} testFile - Repository-relative test path.
413
+ * @param {{ root: string, readSource: (file: string) => string | undefined }} options - Where and how to read.
414
+ * @param {boolean} perturb - Serve every file's text with a unique marker.
415
+ * @returns {Promise<{ state: RunState, errors: string[] }>} The run.
416
+ */
417
+ async function runOnce(testFile, { root, readSource }, perturb) {
418
+ /** @type {RunState} */
419
+ const state = {
420
+ root,
421
+ perturb,
422
+ reads: [],
423
+ markers: new Map(),
424
+ assertions: [],
425
+ test: undefined,
426
+ };
427
+ const runner = createRunner({ onTest: name => (state.test = name) });
428
+ const vitest = { ...runner.api, expect: recordingExpect(state) };
429
+ const packages = {
430
+ ...fileSystemModules(state),
431
+ vitest,
432
+ "node:path": path,
433
+ path,
434
+ "node:url": { fileURLToPath, pathToFileURL, URL },
435
+ url: { fileURLToPath, pathToFileURL, URL },
436
+ };
437
+ try {
438
+ loadModule(testFile, { state, readSource, packages, cache: new Map() });
439
+ } catch (error) {
440
+ return { state, errors: [`loading: ${errorText(error)}`] };
441
+ }
442
+ return { state, errors: await runner.run() };
443
+ }
444
+
445
+ /**
446
+ * An error's message.
447
+ * @param {unknown} error - Anything thrown.
448
+ * @returns {string} Its message.
449
+ */
450
+ function errorText(error) {
451
+ return error instanceof Error ? error.message : String(error);
452
+ }
453
+
454
+ /**
455
+ * The files whose served text is exactly `text`.
456
+ * @param {RunState} state - The run.
457
+ * @param {string} text - An assertion subject.
458
+ * @returns {string[]} Distinct repository-relative paths.
459
+ */
460
+ function filesServing(state, text) {
461
+ return [
462
+ ...new Set(
463
+ state.reads.filter(read => read.served === text).map(read => read.file)
464
+ ),
465
+ ];
466
+ }
467
+
468
+ /**
469
+ * The comparable identity of an assertion, ignoring which file it hit.
470
+ * @param {Recorded | undefined} assertion - A recorded assertion.
471
+ * @returns {string} A key.
472
+ */
473
+ function signature(assertion) {
474
+ if (assertion === undefined) return "";
475
+ if ("reason" in assertion)
476
+ return JSON.stringify([assertion.test, assertion.reason]);
477
+ return JSON.stringify([
478
+ assertion.test,
479
+ assertion.polarity,
480
+ assertion.kind,
481
+ String(assertion.value),
482
+ ]);
483
+ }
484
+
485
+ /**
486
+ * Convert a phrase value to its manifest form.
487
+ * @param {string | RegExp} value - String or RegExp.
488
+ * @returns {string | { source: string, flags: string }} JSON-safe value.
489
+ */
490
+ function manifestValue(value) {
491
+ return value instanceof RegExp
492
+ ? { source: value.source, flags: value.flags }
493
+ : value;
494
+ }
495
+
496
+ /**
497
+ * Record one phrase-only test file.
498
+ * @param {string} testFile - Repository-relative path of the test.
499
+ * @param {{ root: string, readSource: (file: string) => string | undefined }} options -
500
+ * `root` is the repository whose text files the test reads; `readSource`
501
+ * returns the source of the test file and its helpers (the working tree, or
502
+ * a base commit via `git show` for the parity check).
503
+ * @returns {Promise<Recording>} The translation, or why there is none.
504
+ */
505
+ export async function recordTestFile(testFile, options) {
506
+ const first = await runOnce(testFile, options, false);
507
+ const reasons = [...first.errors];
508
+ const attributions = first.state.assertions.map(assertion =>
509
+ "reason" in assertion ? [] : filesServing(first.state, assertion.text)
510
+ );
511
+ if (attributions.some(files => files.length > 1)) {
512
+ const second = await runOnce(testFile, options, true);
513
+ const same =
514
+ second.state.assertions.length === first.state.assertions.length &&
515
+ second.state.assertions.every(
516
+ (assertion, index) =>
517
+ signature(assertion) === signature(first.state.assertions[index])
518
+ );
519
+ if (same) {
520
+ second.state.assertions.forEach((assertion, index) => {
521
+ if (!("reason" in assertion))
522
+ attributions[index] = filesServing(second.state, assertion.text);
523
+ });
524
+ } else {
525
+ reasons.push(
526
+ "identical text read from several files, and a run with the files made distinct behaved differently"
527
+ );
528
+ }
529
+ }
530
+ /** @type {Entry[]} */
531
+ const entries = [];
532
+ first.state.assertions.forEach((assertion, index) => {
533
+ const where = assertion.test ?? "(outside any test)";
534
+ if ("reason" in assertion) {
535
+ reasons.push(`${where}: ${assertion.reason}`);
536
+ return;
537
+ }
538
+ const files = attributions[index] ?? [];
539
+ const [file] = files;
540
+ if (file === undefined) {
541
+ reasons.push(`${where}: subject is not the full text of a file it read`);
542
+ return;
543
+ }
544
+ if (files.length > 1 || file.startsWith("..")) {
545
+ reasons.push(
546
+ `${where}: cannot attribute the subject to one repository file`
547
+ );
548
+ return;
549
+ }
550
+ if (!assertion.holds)
551
+ reasons.push(`${where}: assertion fails on the current tree`);
552
+ entries.push({
553
+ file,
554
+ polarity: assertion.polarity,
555
+ kind: assertion.kind,
556
+ value: manifestValue(assertion.value),
557
+ source: `${testFile}${SOURCE_SEPARATOR}${where}`,
558
+ });
559
+ });
560
+ if (first.state.assertions.length === 0)
561
+ reasons.push("no runtime phrase assertions");
562
+ return {
563
+ file: testFile,
564
+ raw: first.state.assertions.length,
565
+ entries,
566
+ reasons: [...new Set(reasons)],
567
+ };
568
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Repository access for the phrase-test tooling (CodySwannGT/lisa#4609):
3
+ * which test files exist, and how to read a source either from the working
4
+ * tree or from a commit, so the parity check can classify and run files that
5
+ * the working tree no longer has.
6
+ * @module scripts/lib/phrase-tests/repo
7
+ */
8
+ import { execFileSync } from "node:child_process";
9
+ import { existsSync, readFileSync } from "node:fs";
10
+ import path from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+
13
+ /** Absolute repository root (this file lives in scripts/lib/phrase-tests). */
14
+ export const REPO_ROOT = path.resolve(
15
+ path.dirname(fileURLToPath(import.meta.url)),
16
+ "../../.."
17
+ );
18
+
19
+ /** Test files the classifier considers. */
20
+ const TEST_PATHSPEC = "tests/**/*.test.ts";
21
+
22
+ /**
23
+ * Run git in the repository and return stdout.
24
+ * @param {string} root - Repository root.
25
+ * @param {string[]} args - git arguments.
26
+ * @returns {string} Output.
27
+ */
28
+ function git(root, args) {
29
+ return execFileSync("git", args, {
30
+ cwd: root,
31
+ encoding: "utf8",
32
+ maxBuffer: 256 * 1024 * 1024,
33
+ });
34
+ }
35
+
36
+ /**
37
+ * Every test file on disk in the working tree, tracked or not (but not
38
+ * ignored), so files restored from an older commit are seen too.
39
+ * @param {string} root - Repository root.
40
+ * @returns {string[]} Sorted repository-relative paths.
41
+ */
42
+ export function workingTreeTestFiles(root) {
43
+ return git(root, [
44
+ "ls-files",
45
+ "--cached",
46
+ "--others",
47
+ "--exclude-standard",
48
+ "--",
49
+ TEST_PATHSPEC,
50
+ ])
51
+ .split("\n")
52
+ .filter(file => file !== "" && existsSync(path.join(root, file)))
53
+ .sort();
54
+ }
55
+
56
+ /**
57
+ * Every test file at a commit.
58
+ * @param {string} root - Repository root.
59
+ * @param {string} ref - Commit-ish.
60
+ * @returns {string[]} Sorted repository-relative paths.
61
+ */
62
+ export function testFilesAt(root, ref) {
63
+ return git(root, ["ls-tree", "-r", "--name-only", ref, "--", "tests"])
64
+ .split("\n")
65
+ .filter(file => file.startsWith("tests/") && file.endsWith(".test.ts"))
66
+ .sort();
67
+ }
68
+
69
+ /**
70
+ * A reader over the working tree.
71
+ * @param {string} root - Repository root.
72
+ * @returns {(file: string) => string | undefined} Reads a repo-relative file.
73
+ */
74
+ export function workingTreeReader(root) {
75
+ return file => {
76
+ const absolute = path.join(root, file);
77
+ return existsSync(absolute) ? readFileSync(absolute, "utf8") : undefined;
78
+ };
79
+ }
80
+
81
+ /**
82
+ * A reader over one commit, via `git show <ref>:<path>`, memoised.
83
+ * @param {string} root - Repository root.
84
+ * @param {string} ref - Commit-ish.
85
+ * @returns {(file: string) => string | undefined} Reads a repo-relative file.
86
+ */
87
+ export function commitReader(root, ref) {
88
+ const tracked = new Set(
89
+ git(root, ["ls-tree", "-r", "--name-only", ref, "--", "tests"]).split("\n")
90
+ );
91
+ /** @type {Map<string, string>} */
92
+ const cache = new Map();
93
+ return file => {
94
+ if (!tracked.has(file)) return undefined;
95
+ if (!cache.has(file))
96
+ cache.set(file, git(root, ["show", `${ref}:${file}`]));
97
+ return cache.get(file);
98
+ };
99
+ }