lynkeus 0.2.0 → 0.4.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 (134) hide show
  1. package/lib/cases/ahead.d.ts +31 -0
  2. package/lib/cases/ahead.js +90 -0
  3. package/lib/cases/fixtures.d.ts +12 -0
  4. package/lib/cases/fixtures.js +32 -0
  5. package/lib/cases/flakes.d.ts +28 -0
  6. package/lib/cases/flakes.js +61 -0
  7. package/lib/cases/format.d.ts +5 -0
  8. package/lib/cases/format.js +30 -4
  9. package/lib/cases/portClaim.d.ts +10 -0
  10. package/lib/cases/portClaim.js +55 -0
  11. package/lib/cases/runfile.d.ts +24 -0
  12. package/lib/cases/runfile.js +108 -0
  13. package/lib/cases/runner.d.ts +82 -3
  14. package/lib/cases/runner.js +394 -40
  15. package/lib/cases/templates.d.ts +2 -2
  16. package/lib/cases/templates.js +14 -4
  17. package/lib/cases/traces.d.ts +58 -0
  18. package/lib/cases/traces.js +250 -0
  19. package/lib/cli.js +28 -7
  20. package/lib/commands/cases.js +411 -42
  21. package/lib/commands/check.d.ts +6 -0
  22. package/lib/commands/check.js +8 -3
  23. package/lib/commands/doctor.js +8 -2
  24. package/lib/commands/drive.js +32 -8
  25. package/lib/commands/headless.js +132 -8
  26. package/lib/commands/init.d.ts +29 -0
  27. package/lib/commands/init.js +295 -33
  28. package/lib/commands/report.d.ts +97 -0
  29. package/lib/commands/report.js +228 -0
  30. package/lib/config.d.ts +26 -1
  31. package/lib/config.js +30 -0
  32. package/lib/device/agentVersion.d.ts +7 -0
  33. package/lib/device/agentVersion.js +12 -0
  34. package/lib/device/devices.d.ts +5 -0
  35. package/lib/device/devices.js +27 -0
  36. package/lib/device/driver.js +2 -2
  37. package/lib/flow/runner.js +33 -1
  38. package/lib/flow/types.d.ts +2 -1
  39. package/lib/knowledge/contrast.d.ts +45 -0
  40. package/lib/knowledge/contrast.js +114 -0
  41. package/lib/knowledge/errors.js +1 -1
  42. package/lib/knowledge/lint.d.ts +2 -0
  43. package/lib/knowledge/lint.js +13 -3
  44. package/lib/mcp/server.js +31 -2
  45. package/lib/registry.d.ts +5 -0
  46. package/lib/targets.d.ts +10 -1
  47. package/lib/targets.js +16 -3
  48. package/package.json +10 -6
  49. package/src/cases/ahead.ts +111 -0
  50. package/src/cases/fixtures.ts +37 -0
  51. package/src/cases/flakes.ts +67 -0
  52. package/src/cases/format.ts +31 -6
  53. package/src/cases/portClaim.ts +52 -0
  54. package/src/cases/runfile.ts +119 -0
  55. package/src/cases/runner.ts +454 -46
  56. package/src/cases/templates.ts +14 -4
  57. package/src/cases/traces.ts +298 -0
  58. package/src/cli.ts +29 -7
  59. package/src/commands/cases.ts +428 -41
  60. package/src/commands/check.ts +11 -4
  61. package/src/commands/doctor.ts +9 -2
  62. package/src/commands/drive.ts +31 -8
  63. package/src/commands/headless.ts +143 -8
  64. package/src/commands/init.ts +338 -30
  65. package/src/commands/report.ts +272 -0
  66. package/src/config.ts +39 -2
  67. package/src/device/agentVersion.ts +15 -0
  68. package/src/device/devices.ts +28 -0
  69. package/src/device/driver.ts +2 -2
  70. package/src/flow/runner.ts +35 -1
  71. package/src/flow/types.ts +2 -2
  72. package/src/knowledge/contrast.ts +135 -0
  73. package/src/knowledge/errors.ts +1 -1
  74. package/src/knowledge/lint.ts +15 -4
  75. package/src/mcp/server.ts +31 -2
  76. package/src/registry.ts +2 -0
  77. package/src/targets.ts +17 -3
  78. package/lib/__tests__/args.test.d.ts +0 -1
  79. package/lib/__tests__/args.test.js +0 -69
  80. package/lib/__tests__/check.test.d.ts +0 -1
  81. package/lib/__tests__/check.test.js +0 -60
  82. package/lib/__tests__/init.test.d.ts +0 -1
  83. package/lib/__tests__/init.test.js +0 -42
  84. package/lib/__tests__/record.test.d.ts +0 -1
  85. package/lib/__tests__/record.test.js +0 -44
  86. package/lib/__tests__/snapshot.test.d.ts +0 -1
  87. package/lib/__tests__/snapshot.test.js +0 -47
  88. package/lib/__tests__/targets.test.d.ts +0 -1
  89. package/lib/__tests__/targets.test.js +0 -127
  90. package/lib/cases/__tests__/format.test.d.ts +0 -1
  91. package/lib/cases/__tests__/format.test.js +0 -61
  92. package/lib/cases/__tests__/runner.test.d.ts +0 -1
  93. package/lib/cases/__tests__/runner.test.js +0 -188
  94. package/lib/knowledge/__tests__/edges.test.d.ts +0 -1
  95. package/lib/knowledge/__tests__/edges.test.js +0 -25
  96. package/lib/knowledge/__tests__/events.test.d.ts +0 -1
  97. package/lib/knowledge/__tests__/events.test.js +0 -39
  98. package/lib/knowledge/__tests__/extract.test.d.ts +0 -1
  99. package/lib/knowledge/__tests__/extract.test.js +0 -69
  100. package/lib/knowledge/__tests__/frontier.test.d.ts +0 -1
  101. package/lib/knowledge/__tests__/frontier.test.js +0 -57
  102. package/lib/knowledge/__tests__/funnels.test.d.ts +0 -1
  103. package/lib/knowledge/__tests__/funnels.test.js +0 -40
  104. package/lib/knowledge/__tests__/lint.test.d.ts +0 -1
  105. package/lib/knowledge/__tests__/lint.test.js +0 -53
  106. package/lib/knowledge/__tests__/perf.test.d.ts +0 -1
  107. package/lib/knowledge/__tests__/perf.test.js +0 -34
  108. package/lib/knowledge/__tests__/plan.test.d.ts +0 -1
  109. package/lib/knowledge/__tests__/plan.test.js +0 -35
  110. package/lib/knowledge/__tests__/query.test.d.ts +0 -1
  111. package/lib/knowledge/__tests__/query.test.js +0 -55
  112. package/lib/knowledge/__tests__/screens.test.d.ts +0 -1
  113. package/lib/knowledge/__tests__/screens.test.js +0 -30
  114. package/lib/knowledge/__tests__/why.test.d.ts +0 -1
  115. package/lib/knowledge/__tests__/why.test.js +0 -28
  116. package/src/__tests__/args.test.ts +0 -82
  117. package/src/__tests__/check.test.ts +0 -71
  118. package/src/__tests__/init.test.ts +0 -52
  119. package/src/__tests__/record.test.ts +0 -49
  120. package/src/__tests__/snapshot.test.ts +0 -51
  121. package/src/__tests__/targets.test.ts +0 -132
  122. package/src/cases/__tests__/format.test.ts +0 -76
  123. package/src/cases/__tests__/runner.test.ts +0 -230
  124. package/src/knowledge/__tests__/edges.test.ts +0 -34
  125. package/src/knowledge/__tests__/events.test.ts +0 -45
  126. package/src/knowledge/__tests__/extract.test.ts +0 -88
  127. package/src/knowledge/__tests__/frontier.test.ts +0 -77
  128. package/src/knowledge/__tests__/funnels.test.ts +0 -58
  129. package/src/knowledge/__tests__/lint.test.ts +0 -66
  130. package/src/knowledge/__tests__/perf.test.ts +0 -41
  131. package/src/knowledge/__tests__/plan.test.ts +0 -52
  132. package/src/knowledge/__tests__/query.test.ts +0 -74
  133. package/src/knowledge/__tests__/screens.test.ts +0 -37
  134. package/src/knowledge/__tests__/why.test.ts +0 -40
@@ -1,14 +1,22 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import fs from 'node:fs';
3
+ import os from 'node:os';
3
4
  import path from 'node:path';
5
+ import { stripVTControlCharacters } from 'node:util';
4
6
  import { Fixtures } from '../cases/fixtures.js';
5
7
  import { readCases } from '../cases/format.js';
6
- import { runCase } from '../cases/runner.js';
8
+ import { missingFixtures, preparable, runCase } from '../cases/runner.js';
7
9
  import { CONFIG, EXAMPLE_CASE, FIXTURES, FORMAT } from '../cases/templates.js';
8
- import { configFile } from '../config.js';
10
+ import { claimPorts } from '../cases/portClaim.js';
11
+ import { configFile, portFromEnv } from '../config.js';
9
12
  import { readJson, writeJson } from '../files.js';
13
+ import { Ahead, InMemory } from '../cases/ahead.js';
14
+ import { Flakes } from '../cases/flakes.js';
15
+ import { RunFile } from '../cases/runfile.js';
10
16
  import { eventsFile } from '../knowledge/events.js';
11
17
  import { define } from '../registry.js';
18
+ import { describeChanges, pushRun, service } from './report.js';
19
+ import { TraceSink } from '../cases/traces.js';
12
20
  const startHost = async (root, err) => {
13
21
  // Its own process group: the host starts a test runner of its own, and stopping one without the other leaves an app dialing in.
14
22
  const host = spawn(process.execPath, [process.argv[1], 'headless', 'start'], {
@@ -19,6 +27,18 @@ const startHost = async (root, err) => {
19
27
  });
20
28
  let output = '';
21
29
  const tail = (n) => output.trim().split('\n').slice(-n).join(' · ');
30
+ // `headless start` ends a crash with what it usually means; without that, the error line jest printed.
31
+ const why = () => {
32
+ const plain = stripVTControlCharacters(output);
33
+ const explained = plain.split('lynkeus: what this looks like')[1];
34
+ if (explained)
35
+ return explained
36
+ .trim()
37
+ .split('\n')
38
+ .map((line) => line.trim())
39
+ .join(' · ');
40
+ return plain.match(/^\s*(\w*Error\b.*|Cannot find module.*)$/m)?.[1]?.trim() ?? tail(3);
41
+ };
22
42
  await new Promise((resolve, reject) => {
23
43
  const settle = (error) => {
24
44
  clearTimeout(timer);
@@ -32,12 +52,11 @@ const startHost = async (root, err) => {
32
52
  output = (output + chunk.toString()).slice(-4000);
33
53
  if (/waiting for a driver/.test(output))
34
54
  settle();
35
- else if (/Test suite failed/.test(output))
36
- settle(new Error(`the host failed to start: ${tail(5)}`));
37
55
  };
38
56
  host.stdout?.on('data', read);
39
57
  host.stderr?.on('data', read);
40
- host.once('exit', (code) => settle(new Error(`the host exited (${code}): ${tail(3)}`)));
58
+ // A suite that fails to load exits right after printing why, so its explanation is read in full here.
59
+ host.once('exit', (code) => settle(new Error(`${/Test suite failed/.test(output) ? 'the host failed to start' : `the host exited (${code})`}: ${why()}`)));
41
60
  });
42
61
  err('host: up');
43
62
  return host;
@@ -48,12 +67,32 @@ const stopGroup = (pid) => {
48
67
  }
49
68
  catch { }
50
69
  };
70
+ /**
71
+ * Stops a host and waits until it is gone. The next case's host dials the same port, and a host still on
72
+ * its way out dials it too: whichever reaches the driver first is the one the case talks to.
73
+ */
74
+ const stopHost = async (host) => {
75
+ if (!host.pid || host.exitCode !== null || host.signalCode !== null)
76
+ return;
77
+ const gone = new Promise((resolve) => host.once('exit', () => resolve()));
78
+ host.stdin?.end();
79
+ stopGroup(host.pid);
80
+ const late = setTimeout(() => {
81
+ try {
82
+ process.kill(-host.pid, 'SIGKILL');
83
+ }
84
+ catch { }
85
+ }, 2000);
86
+ await gone;
87
+ clearTimeout(late);
88
+ };
51
89
  const describe = (report) => {
52
- const counts = { passed: 0, failed: 0, skipped: 0 };
90
+ const counts = { passed: 0, failed: 0, skipped: 0, unsupported: 0 };
53
91
  for (const s of report.steps)
54
92
  counts[s.status] += 1;
93
+ const headline = { passed: '✅ PASSED', failed: '❌ FAILED', unsupported: '🚫 NOT ON THIS HOST' }[report.result];
55
94
  const lines = [
56
- `${report.result === 'passed' ? '✅ PASSED' : '❌ FAILED'} ✅ ${counts.passed}${counts.failed ? ` ❌ ${counts.failed}` : ''}${counts.skipped ? ` ⏭️ ${counts.skipped}` : ''} — ${(report.ms / 1000).toFixed(1)}s`,
95
+ `${headline} ✅ ${counts.passed}${counts.failed ? ` ❌ ${counts.failed}` : ''}${counts.unsupported ? ` 🚫 ${counts.unsupported}` : ''}${counts.skipped ? ` ⏭️ ${counts.skipped}` : ''} — ${(report.ms / 1000).toFixed(1)}s`,
57
96
  ];
58
97
  if (report.evidence?.screen)
59
98
  lines.push('— screen at the failure:', ...report.evidence.screen.split('\n').map((l) => ` ${l}`));
@@ -63,6 +102,90 @@ const describe = (report) => {
63
102
  lines.push('— why:', ...report.evidence.why.split('\n').map((l) => ` ${l}`));
64
103
  return lines.join('\n');
65
104
  };
105
+ /** The share of the machine's CPU that sat idle over the next 300 ms. */
106
+ const idleShare = async () => {
107
+ const total = () => os.cpus().reduce((sum, cpu) => {
108
+ const t = cpu.times;
109
+ return { idle: sum.idle + t.idle, all: sum.all + t.idle + t.user + t.sys + t.nice + t.irq };
110
+ }, { idle: 0, all: 0 });
111
+ const before = total();
112
+ await new Promise((r) => setTimeout(r, 300));
113
+ const after = total();
114
+ return after.all > before.all ? (after.idle - before.idle) / (after.all - before.all) : 1;
115
+ };
116
+ /** The case files named, or every case under the cases directory; a sentence when there are none. */
117
+ const caseFiles = (args, home, casesDir) => {
118
+ const dir = path.resolve(home, casesDir ?? 'cases');
119
+ const files = args.length
120
+ ? args.map((f) => path.resolve(f))
121
+ : fs.existsSync(dir)
122
+ ? fs
123
+ .readdirSync(dir)
124
+ .filter((f) => f.endsWith('.md') && !/^(README|FORMAT|CATALOG)\.md$/i.test(f) && !f.startsWith('.'))
125
+ .sort()
126
+ .map((f) => path.join(dir, f))
127
+ : [];
128
+ return files.length > 0 ? files : `no cases under ${path.relative(home, dir) || '.'}; \`lynkeus case init\` writes one`;
129
+ };
130
+ /**
131
+ * Runs the setups of `cases` ahead of them, in order, `jobs` at a time: never more than `limit` waiting
132
+ * to be taken, and only while the machine has `idle` of its CPU to spare. A case that started first is skipped.
133
+ */
134
+ const prepareAhead = async (cases, o) => {
135
+ let next = 0;
136
+ let made = 0;
137
+ let skipped = 0;
138
+ // Far enough ahead, or the machine busy: a setup made then only takes the CPU from the cases
139
+ // running now, and the suite gains nothing from having it early.
140
+ const room = async () => {
141
+ if (o.store.waiting() < o.limit)
142
+ return (await idleShare()) >= o.idle;
143
+ // A timer, not a bare check: the jobs that take the waiting setups may run in this same process,
144
+ // and a loop that never yields to the event loop would keep them from ever taking one.
145
+ await new Promise((r) => setTimeout(r, 100));
146
+ return false;
147
+ };
148
+ const worker = async () => {
149
+ const fixtures = o.open();
150
+ await fixtures.ahead();
151
+ try {
152
+ for (let c = cases[next++]; c; c = cases[next++]) {
153
+ while (!o.store.started(c) && !(await room()))
154
+ ;
155
+ if (o.store.started(c)) {
156
+ skipped++;
157
+ continue;
158
+ }
159
+ const done = c;
160
+ await runCase(done, { base: o.base, config: o.config, fixtures, setupOnly: { keep: (p) => o.store.keep(done, p) } });
161
+ made++;
162
+ }
163
+ }
164
+ finally {
165
+ fixtures.close();
166
+ }
167
+ };
168
+ await Promise.all(Array.from({ length: Math.max(1, o.jobs) }, worker));
169
+ return { made, skipped };
170
+ };
171
+ /** A host for one case, started by the project's own command: `{port}` is where it dials the driver. */
172
+ const spawnHost = (command, port, job, cwd) => spawn('/bin/sh', ['-c', command.replaceAll('{port}', String(port)).replaceAll('{job}', String(job))], {
173
+ cwd,
174
+ env: process.env,
175
+ // stdin stays open for the host's life: a host that serves until its stdin closes stops with the case.
176
+ stdio: ['pipe', 'ignore', 'ignore'],
177
+ detached: true,
178
+ });
179
+ /** A run that could not be uploaded still ran: the failure is said, not raised. */
180
+ const pushed = async (dir, to, project) => {
181
+ try {
182
+ const run = await pushRun(dir, { ...to, project });
183
+ return [`report: ${run.url}${run.refused.length ? ` (not kept on this plan: ${run.refused.join(', ')})` : ''}`, ...describeChanges(run.changes)].join('\n');
184
+ }
185
+ catch (error) {
186
+ return `the report was not uploaded: ${error.message}`;
187
+ }
188
+ };
66
189
  export const caseCommands = [
67
190
  define({
68
191
  name: 'case run',
@@ -73,34 +196,125 @@ export const caseCommands = [
73
196
  flags: {
74
197
  host: { type: 'boolean', help: 'start `headless start` for the run and stop it after' },
75
198
  once: { type: 'boolean', help: 'no second chance for a case that fails' },
199
+ continue: { type: 'boolean', help: "keep running a case's steps after one fails (a failed setup still stops it)" },
200
+ seen: { type: 'string', help: 'write <dir>/<case id>.json with the screens each passing case went through, for a coverage map', value: 'dir' },
76
201
  report: { type: 'string', help: 'append one JSON line per case', value: 'file' },
77
202
  events: { type: 'string', help: 'keep what the app told its analytics, per case, as <dir>/<case id>/events.jsonl', value: 'dir' },
203
+ out: { type: 'string', help: 'write the run as a directory a report can read: run.json and cases.jsonl, a line per attempt', value: 'dir' },
204
+ screenshots: { type: 'boolean', help: 'with --out: a frame of the screen after every step of the app' },
205
+ settle: {
206
+ type: 'number',
207
+ help: 'with --screenshots: how long the screen must stay still before a frame, in ms; 700 for frames two runs can be compared by',
208
+ default: 150,
209
+ value: 'ms',
210
+ },
211
+ video: { type: 'boolean', help: 'with --out: film each case, where the host films (the step says at what second it began)' },
212
+ traces: {
213
+ type: 'boolean',
214
+ help: 'listen for the backend’s OpenTelemetry traces (OTLP over HTTP) and keep, under each step, what the backend did for it; point the backend’s OTEL_EXPORTER_OTLP_ENDPOINT at http://localhost:<traces-port>',
215
+ },
216
+ 'traces-port': { type: 'number', help: 'where --traces listens', default: 4318, value: 'port' },
217
+ push: { type: 'boolean', help: 'with --out: upload the run to the reports service when it ends and print the report’s address' },
218
+ project: { type: 'string', help: 'with --push: the project the run is filed under (default: the app’s folder name)', value: 'name' },
219
+ 'video-fps': { type: 'number', help: 'frames per second of the film', default: 30, value: 'n' },
220
+ 'video-scale': { type: 'number', help: 'pixels per point of the film, where the host takes one (fastsim: 1 to 3, 2 unless told)', value: 'n' },
221
+ flakes: { type: 'string', help: 'the ledger of how each case did across runs (default .lynkeus/flakes.json)', value: 'file' },
222
+ prepared: { type: 'string', help: 'where `case prepare` leaves setups made ahead; a case found there skips its setup', value: 'dir' },
223
+ jobs: { type: 'number', help: 'cases at once, each on its own host (needs --ports)', value: 'n', default: 1 },
224
+ ports: { type: 'string', help: 'the driver port of each job, comma-separated: where its host dials in', value: 'list' },
225
+ 'host-command': {
226
+ type: 'string',
227
+ help: 'starts a fresh host for every case and stops it after; {port} is where the host dials, {job} the job',
228
+ value: 'command',
229
+ },
230
+ 'in-order': { type: 'boolean', help: 'with --jobs: take the cases in the order given, not the longest first' },
231
+ ahead: { type: 'number', help: 'make up to this many setups ahead of their cases while others run (0: none)', value: 'n', default: 0 },
232
+ idle: { type: 'number', help: 'with --ahead: start a setup only while this share of the CPU is idle', value: 'share', default: 0.25 },
78
233
  'dry-run': { type: 'boolean', help: 'parse and list the steps without running them' },
79
234
  },
80
235
  needs: 'nothing',
81
236
  session: false,
82
- mcp: false,
237
+ mcp: 'core',
238
+ mcpOmit: [
239
+ 'seen',
240
+ 'report',
241
+ 'events',
242
+ 'settle',
243
+ 'traces',
244
+ 'traces-port',
245
+ 'video-fps',
246
+ 'video-scale',
247
+ 'flakes',
248
+ 'prepared',
249
+ 'jobs',
250
+ 'ports',
251
+ 'host-command',
252
+ 'in-order',
253
+ 'ahead',
254
+ 'idle',
255
+ 'continue',
256
+ 'video',
257
+ 'project',
258
+ ],
259
+ mcpDetails: 'Runs case files (default: all in cases.dir) against the attached app, or with `host` in Node. A case that fails comes back with its screen and reason. `out` + `screenshots` + `push` uploads the run and prints its address.',
83
260
  run: async (ctx) => {
84
261
  const config = ctx.config.cases ?? {};
85
262
  const home = config.base ?? ctx.root;
86
- const dir = path.resolve(home, config.dir ?? 'cases');
87
- const files = ctx.args.length
88
- ? ctx.args.map((f) => path.resolve(f))
89
- : fs.existsSync(dir)
90
- ? fs
91
- .readdirSync(dir)
92
- .filter((f) => f.endsWith('.md') && !/^(README|FORMAT|CATALOG)\.md$/i.test(f) && !f.startsWith('.'))
93
- .sort()
94
- .map((f) => path.join(dir, f))
95
- : [];
96
- if (files.length === 0)
97
- return { text: `no cases under ${path.relative(ctx.root, dir) || '.'}; \`lynkeus case init\` writes one`, code: 1 };
263
+ const files = caseFiles(ctx.args, home, config.dir);
264
+ if (typeof files === 'string')
265
+ return { text: files, code: 1 };
98
266
  const cases = files.flatMap(readCases);
99
267
  const dry = !!ctx.flags['dry-run'];
100
- const events = typeof ctx.flags.events === 'string';
268
+ const seenDir = typeof ctx.flags.seen === 'string' && !dry ? path.resolve(ctx.flags.seen) : undefined;
269
+ const out = typeof ctx.flags.out === 'string' && !dry ? new RunFile(path.resolve(ctx.flags.out), ctx.root) : undefined;
270
+ if ((ctx.flags.screenshots || ctx.flags.video) && !out)
271
+ return { text: '--screenshots and --video keep what they take in the run directory: add --out <dir>', code: 2 };
272
+ // Checked before the run, so a missing key does not surface only after every case has run.
273
+ const reportsTo = ctx.flags.push && out ? service() : undefined;
274
+ if (ctx.flags.push && !out)
275
+ return { text: '--push uploads the run directory: add --out <dir>', code: 2 };
276
+ if (typeof reportsTo === 'string')
277
+ return { text: reportsTo, code: 2 };
278
+ const evidenceOf = (id, attempt) => out && (ctx.flags.screenshots || ctx.flags.video)
279
+ ? {
280
+ dir: out.evidenceDir(id, attempt),
281
+ screenshots: !!ctx.flags.screenshots,
282
+ settleMs: Number(ctx.flags.settle ?? 150),
283
+ ...(ctx.flags.video
284
+ ? { video: { fps: Number(ctx.flags['video-fps'] ?? 30), ...(ctx.flags['video-scale'] ? { scale: Number(ctx.flags['video-scale']) } : {}) } }
285
+ : {}),
286
+ }
287
+ : undefined;
288
+ const ledger = dry ? undefined : new Flakes(path.resolve(ctx.root, typeof ctx.flags.flakes === 'string' ? ctx.flags.flakes : '.lynkeus/flakes.json'));
289
+ // A run file files each event under its step, so it needs them collected.
290
+ const events = typeof ctx.flags.events === 'string' || out !== undefined;
291
+ const claimed = dry
292
+ ? undefined
293
+ : claimPorts(typeof ctx.flags.ports === 'string'
294
+ ? ctx.flags.ports
295
+ .split(',')
296
+ .map(Number)
297
+ .filter(Number.isInteger)
298
+ .slice(0, Math.max(1, Number(ctx.flags.jobs ?? 1)))
299
+ : [portFromEnv(ctx.config) ?? 8123]);
300
+ if (claimed && 'refused' in claimed)
301
+ return { text: claimed.refused, code: 1 };
101
302
  const host = ctx.flags.host && !dry ? await startHost(ctx.root, ctx.err) : undefined;
102
303
  const fixtures = config.fixtures && !dry ? new Fixtures(config.fixtures, home) : undefined;
304
+ const traces = ctx.flags.traces && !dry ? new TraceSink(Number(ctx.flags['traces-port'] ?? 4318)) : undefined;
305
+ if (traces) {
306
+ try {
307
+ await traces.start();
308
+ }
309
+ catch (error) {
310
+ fixtures?.close();
311
+ return { text: `--traces could not listen on port ${traces.port}: ${error.message}`, code: 2 };
312
+ }
313
+ ctx.err(`backend traces: listening on http://localhost:${traces.port} (the backend's OTEL_EXPORTER_OTLP_ENDPOINT)`);
314
+ }
103
315
  const stop = () => {
316
+ traces?.close();
317
+ claimed?.release();
104
318
  fixtures?.close();
105
319
  if (host?.pid)
106
320
  stopGroup(host.pid);
@@ -113,34 +327,189 @@ export const caseCommands = [
113
327
  process.once('SIGTERM', interrupted);
114
328
  const reports = [];
115
329
  try {
116
- for (const c of cases) {
117
- ctx.err(`▶ ${c.id}${c.title ? ` — ${c.title}` : ''}`);
118
- let report = await runCase(c, { base: ctx, config, fixtures, dry, events, log: ctx.err });
119
- ctx.err(describe(report));
120
- if (report.result === 'failed' && !ctx.flags.once && !dry) {
121
- ctx.err(` retrying ${c.id} once`);
122
- report = { ...(await runCase(c, { base: ctx, config, fixtures, events, log: ctx.err })), retried: true };
123
- ctx.err(describe(report));
330
+ // A case that names a fixture the server does not have fails halfway, after it has changed the backend. Better not to start.
331
+ const described = await fixtures?.describe();
332
+ if (described?.down)
333
+ return { text: `the fixtures server cannot serve: ${described.down}`, code: 1 };
334
+ if (described) {
335
+ const missing = cases.flatMap((c) => missingFixtures(c, config, described.commands).map((name) => `${c.id}: no fixture ${name}`));
336
+ if (missing.length > 0)
337
+ return { text: [...missing, `the fixtures command answers: ${described.commands.join(', ')}`].join('\n'), code: 1 };
338
+ }
339
+ const jobs = Math.max(1, Number(ctx.flags.jobs ?? 1));
340
+ const ports = typeof ctx.flags.ports === 'string' ? ctx.flags.ports.split(',').map(Number) : [];
341
+ const hostCommand = typeof ctx.flags['host-command'] === 'string' && !dry ? ctx.flags['host-command'] : undefined;
342
+ if ((jobs > 1 || hostCommand) && (ports.length < jobs || ports.some((p) => !Number.isInteger(p)) || !ctx.forPort))
343
+ return { text: `--jobs and --host-command need a driver port per job: --ports with ${jobs}`, code: 2 };
344
+ // Several jobs finish together only if the longest cases start first: one left for the end runs alone
345
+ // while the other jobs wait. A case the ledger has not timed goes first too, as it may be long.
346
+ if (jobs > 1 && ledger && !ctx.flags['in-order']) {
347
+ const took = (id) => ledger.lastMs(id) ?? Number.POSITIVE_INFINITY;
348
+ cases.sort((a, b) => took(b.id) - took(a.id));
349
+ }
350
+ const limit = Number(ctx.flags.ahead ?? 0);
351
+ const store = typeof ctx.flags.prepared === 'string' && !dry ? new Ahead(path.resolve(ctx.flags.prepared)) : limit > 0 && fixtures ? new InMemory() : undefined;
352
+ const declared = config.fixtures;
353
+ // The setups of the cases to come, made while these run, in the order the jobs will take them.
354
+ const preparing = limit > 0 && declared && store && !dry
355
+ ? prepareAhead(cases.filter((c) => preparable(c, config)), {
356
+ base: ctx,
357
+ config,
358
+ store,
359
+ open: () => new Fixtures(declared, home),
360
+ limit,
361
+ idle: Number(ctx.flags.idle ?? 0.25),
362
+ jobs: 1,
363
+ })
364
+ : undefined;
365
+ let next = 0;
366
+ const job = async (index) => {
367
+ // Each job keeps its own connection to the fixtures server, warm from one case to the next.
368
+ const own = index === 0 ? fixtures : declared && !dry ? new Fixtures(declared, home) : undefined;
369
+ const port = ports[index];
370
+ try {
371
+ for (let c = cases[next++]; c; c = cases[next++]) {
372
+ const lines = [];
373
+ // With several jobs a case's lines are held and printed together, not interleaved.
374
+ const log = jobs > 1 ? (line) => lines.push(line) : ctx.err;
375
+ log(`▶ ${c.id}${c.title ? ` — ${c.title}` : ''}`);
376
+ store?.start(c);
377
+ const attempt = async (n, prepared) => {
378
+ const host = hostCommand && port !== undefined ? spawnHost(hostCommand, port, index, ctx.root) : undefined;
379
+ const scoped = port !== undefined && ctx.forPort ? ctx.forPort(port) : { base: ctx, stop: async () => undefined };
380
+ const startedAt = new Date();
381
+ try {
382
+ // A host just started is still drawing its first screens; with the setup made ahead nothing
383
+ // else gives it that moment before the first press.
384
+ if (host)
385
+ await scoped.base
386
+ .device()
387
+ .then((d) => d.idle({ quietMs: 300, timeoutMs: 5000 }))
388
+ .catch(() => undefined);
389
+ const report = await runCase(c, {
390
+ base: scoped.base,
391
+ config,
392
+ fixtures: own,
393
+ dry,
394
+ events,
395
+ evidence: evidenceOf(c.id, n),
396
+ log,
397
+ prepared,
398
+ continue: !!ctx.flags.continue,
399
+ routes: seenDir ? (host ? 'fresh' : true) : false,
400
+ traces,
401
+ });
402
+ if (seenDir && report.result === 'passed' && report.routes?.length) {
403
+ fs.mkdirSync(seenDir, { recursive: true });
404
+ fs.writeFileSync(path.join(seenDir, `${c.id}.json`), `${JSON.stringify({ id: c.id, routes: report.routes }, null, 2)}\n`);
405
+ }
406
+ return { report, startedAt, hello: (await scoped.base.device().catch(() => undefined))?.server.hello ?? undefined };
407
+ }
408
+ finally {
409
+ if (host)
410
+ await stopHost(host);
411
+ await scoped.stop();
412
+ }
413
+ };
414
+ let { report, startedAt, hello, } = await attempt(1, store?.take(c));
415
+ seen ??= hello;
416
+ log(describe(report));
417
+ out?.add(c, { report, attempt: 1, startedAt });
418
+ if (report.result === 'failed' && !ctx.flags.once && !dry) {
419
+ log(` retrying ${c.id} once`);
420
+ const again = await attempt(2);
421
+ report = { ...again.report, retried: true };
422
+ startedAt = again.startedAt;
423
+ log(describe(report));
424
+ out?.add(c, { report, attempt: 2, startedAt });
425
+ }
426
+ if (jobs > 1)
427
+ ctx.err(lines.join('\n'));
428
+ ledger?.note(report);
429
+ if (typeof ctx.flags.events === 'string' && report.events) {
430
+ const dir = path.resolve(ctx.flags.events, c.id);
431
+ fs.mkdirSync(dir, { recursive: true });
432
+ fs.writeFileSync(eventsFile(dir), report.events.map((e) => `${JSON.stringify(e)}\n`).join(''));
433
+ }
434
+ reports.push(report);
435
+ if (ctx.flags.report)
436
+ fs.appendFileSync(path.resolve(ctx.flags.report), `${JSON.stringify(report)}\n`);
437
+ }
124
438
  }
125
- if (events && report.events) {
126
- const out = path.resolve(ctx.flags.events, c.id);
127
- fs.mkdirSync(out, { recursive: true });
128
- fs.writeFileSync(eventsFile(out), report.events.map((e) => `${JSON.stringify(e)}\n`).join(''));
439
+ finally {
440
+ if (own !== fixtures)
441
+ own?.close();
129
442
  }
130
- reports.push(report);
131
- if (ctx.flags.report)
132
- fs.appendFileSync(path.resolve(ctx.flags.report), `${JSON.stringify(report)}\n`);
133
- }
443
+ };
444
+ let seen;
445
+ await Promise.all(Array.from({ length: jobs }, (_, i) => job(i)));
446
+ await preparing;
447
+ if (out)
448
+ out.finish({ platform: seen?.platform, native: seen?.native });
134
449
  }
135
450
  finally {
136
451
  stop();
137
452
  }
138
- const passed = reports.filter((r) => r.result === 'passed').length;
453
+ const count = (result) => reports.filter((r) => r.result === result).length;
454
+ const unsupported = count('unsupported');
139
455
  const summary = [
140
- ...reports.map((r) => `${r.result === 'passed' ? '✅' : '❌'} ${r.id}${r.retried && r.result === 'passed' ? ' ⚠ passed on retry' : ''}`),
141
- `${passed}/${reports.length} passed`,
456
+ ...reports.map((r) => `${{ passed: '✅', failed: '❌', unsupported: '🚫' }[r.result]} ${r.id}${r.retried && r.result === 'passed' ? ' ⚠ passed on retry' : ''}` +
457
+ // In a session or over MCP the caller reads this answer and nothing else: a case that did not pass brings its steps.
458
+ (ctx.attached && r.result !== 'passed' ? `\n${describe(r)}` : '')),
459
+ `${count('passed')}/${reports.length} passed${unsupported ? `, ${unsupported} cannot run on this host` : ''}`,
460
+ ...(ledger ? ledger.flaky(reports.map((r) => r.id)) : []),
461
+ ...(reportsTo && out
462
+ ? [
463
+ await pushed(path.resolve(ctx.flags.out), reportsTo, typeof ctx.flags.project === 'string' ? ctx.flags.project : path.basename(ctx.root)),
464
+ ]
465
+ : []),
142
466
  ].join('\n');
143
- return { text: summary, json: reports, code: passed === reports.length ? 0 : 1 };
467
+ ledger?.save();
468
+ // A case this host cannot run is not a failure of the app; only a failed case fails the run.
469
+ return { text: summary, json: reports, code: count('failed') === 0 ? 0 : 1 };
470
+ },
471
+ }),
472
+ define({
473
+ name: 'case prepare',
474
+ group: 'runs',
475
+ summary: 'Run the setup of cases ahead of them, so each starts at its first step',
476
+ details: 'For a suite that starts `case run --prepared <dir>` once per case: start this first, with the same cases in the order they will run, and leave it running. It runs every setup made only of the project fixtures and leaves what each produced in <dir>; a case that starts before its setup is ready runs its own, and this skips it. It asks the fixtures server for a lower priority (`lynkeus.ahead`), so it takes what the running cases leave of the machine.',
477
+ positionals: [{ name: 'files', help: 'case files, in the order they will run (default: every .md under cases.dir)', rest: true }],
478
+ flags: {
479
+ prepared: { type: 'string', help: 'where to leave the setups (emptied first)', value: 'dir', default: '.lynkeus/prepared' },
480
+ jobs: { type: 'number', help: 'setups made at once', value: 'n', default: 1 },
481
+ ahead: { type: 'number', help: 'setups kept ready and not yet taken, at most', value: 'n', default: 4 },
482
+ idle: { type: 'number', help: 'start a setup only while at least this share of the CPU is idle (0 to 1)', value: 'share', default: 0.25 },
483
+ },
484
+ needs: 'nothing',
485
+ session: false,
486
+ mcp: false,
487
+ run: async (ctx) => {
488
+ const config = ctx.config.cases ?? {};
489
+ if (!config.fixtures)
490
+ return { text: 'the project declares no fixtures (cases.fixtures in lynkeus.config.json): nothing to prepare', code: 1 };
491
+ const declared = config.fixtures;
492
+ const home = config.base ?? ctx.root;
493
+ const files = caseFiles(ctx.args, home, config.dir);
494
+ if (typeof files === 'string')
495
+ return { text: files, code: 1 };
496
+ const cases = files.flatMap(readCases).filter((c) => preparable(c, config));
497
+ const probe = new Fixtures(declared, home);
498
+ const described = await probe.describe().finally(() => probe.close());
499
+ if (described?.down)
500
+ return { text: `the fixtures server cannot serve: ${described.down}`, code: 1 };
501
+ const store = new Ahead(path.resolve(ctx.root, String(ctx.flags.prepared ?? '.lynkeus/prepared')));
502
+ store.clear();
503
+ const { made, skipped } = await prepareAhead(cases, {
504
+ base: ctx,
505
+ config,
506
+ store,
507
+ open: () => new Fixtures(declared, home),
508
+ limit: Math.max(1, Number(ctx.flags.ahead ?? 4)),
509
+ idle: Number(ctx.flags.idle ?? 0.25),
510
+ jobs: Number(ctx.flags.jobs ?? 1),
511
+ });
512
+ return { text: `${made} setups made ahead, ${skipped} cases had started first`, json: { made, skipped } };
144
513
  },
145
514
  }),
146
515
  define({
@@ -150,7 +519,7 @@ export const caseCommands = [
150
519
  flags: { force: { type: 'boolean', help: 'overwrite what is there' } },
151
520
  needs: 'nothing',
152
521
  session: false,
153
- mcp: false,
522
+ mcp: 'core',
154
523
  run: async (ctx) => {
155
524
  const dir = path.resolve(ctx.root, ctx.config.cases?.dir ?? 'cases');
156
525
  fs.mkdirSync(dir, { recursive: true });
@@ -25,12 +25,18 @@ export declare const diffGraphs: (base: ScreenGraph, head: ScreenGraph) => Graph
25
25
  export type LintBaseline = Record<string, {
26
26
  rule: string;
27
27
  testId?: string;
28
+ subject?: string;
28
29
  message: string;
29
30
  }[]>;
30
31
  type LintedFinding = {
31
32
  finding: Finding;
32
33
  testId?: string;
33
34
  };
35
+ /**
36
+ * A finding is known by its rule and what it is about, not by what was measured: a target that went from
37
+ * 32 to 30 points is the finding the baseline already has. A baseline saved before findings named their
38
+ * subject has only the message to go by.
39
+ */
34
40
  export declare const newFindings: (baseline: LintBaseline, route: string, findings: LintedFinding[]) => LintedFinding[];
35
41
  export declare const describeGraphDiff: (d: GraphDiff) => string;
36
42
  export {};
@@ -44,10 +44,15 @@ export const diffGraphs = (base, head) => {
44
44
  selectorsRemoved: minus(bs, hs).map(selector),
45
45
  };
46
46
  };
47
- const key = (rule, testId, message) => `${rule}|${testId ?? ''}|${message}`;
47
+ const key = (rule, testId, what) => `${rule}|${testId ?? ''}|${what}`;
48
+ /**
49
+ * A finding is known by its rule and what it is about, not by what was measured: a target that went from
50
+ * 32 to 30 points is the finding the baseline already has. A baseline saved before findings named their
51
+ * subject has only the message to go by.
52
+ */
48
53
  export const newFindings = (baseline, route, findings) => {
49
- const seen = new Set((baseline[route] ?? []).map((b) => key(b.rule, b.testId, b.message)));
50
- return findings.filter((f) => !seen.has(key(f.finding.rule, f.testId, f.finding.message)));
54
+ const seen = new Set((baseline[route] ?? []).map((b) => key(b.rule, b.testId, b.subject ?? b.message)));
55
+ return findings.filter((f) => !seen.has(key(f.finding.rule, f.testId, f.finding.subject ?? f.finding.message)) && !seen.has(key(f.finding.rule, f.testId, f.finding.message)));
51
56
  };
52
57
  export const describeGraphDiff = (d) => {
53
58
  const lines = [];
@@ -73,6 +73,12 @@ const PATTERNS = [
73
73
  { re: /requireNativeComponent\s*(?:<[^>]*>)?\(\s*['"]([^'"]+)['"]/g, how: 'requireNativeComponent' },
74
74
  { re: /codegenNativeComponent\s*<[^>]*>\(\s*['"]([^'"]+)['"]/g, how: 'codegenNativeComponent' },
75
75
  ];
76
+ /**
77
+ * The text with its comments blanked, lines kept where they were: a mock or a native module named in a comment
78
+ * (the generated entry shows `jest.mock('some-native-package', …)` as an example) is neither. Only comments that
79
+ * own their line are taken, so a `//` inside a string (a URL) stays.
80
+ */
81
+ const withoutComments = (text) => text.replace(/\/\*[\s\S]*?\*\//g, (block) => block.replace(/[^\n]/g, ' ')).replace(/^[ \t]*\/\/.*$/gm, '');
76
82
  const scanNativeRefs = (root) => {
77
83
  const files = [];
78
84
  for (const d of SCAN_DIRS)
@@ -81,7 +87,7 @@ const scanNativeRefs = (root) => {
81
87
  for (const file of files) {
82
88
  let text;
83
89
  try {
84
- text = fs.readFileSync(file, 'utf8');
90
+ text = withoutComments(fs.readFileSync(file, 'utf8'));
85
91
  }
86
92
  catch {
87
93
  continue;
@@ -104,7 +110,7 @@ const entryMocks = (root, entry) => {
104
110
  const entryPath = path.join(root, entry);
105
111
  let text = '';
106
112
  try {
107
- text = fs.readFileSync(entryPath, 'utf8');
113
+ text = withoutComments(fs.readFileSync(entryPath, 'utf8'));
108
114
  }
109
115
  catch {
110
116
  return { specs, files };