@ultimat3/cli 31.25.0 → 31.27.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 (123) hide show
  1. package/CLAUDE.md +44 -36
  2. package/README.md +5 -4
  3. package/package.json +29 -29
  4. package/src/app-mcp.ts +17 -3
  5. package/src/cmd-cache-spec.ts +5 -2
  6. package/src/cmd-db-recount.ts +7 -0
  7. package/src/cmd-db-spec.ts +2 -3
  8. package/src/cmd-db.ts +0 -2
  9. package/src/cmd-deploy-verify-sample.ts +93 -0
  10. package/src/cmd-deploy-verify.ts +2 -41
  11. package/src/cmd-dev-spec.ts +15 -1
  12. package/src/cmd-dev.ts +31 -4
  13. package/src/cmd-doctor.ts +4 -1
  14. package/src/cmd-exercise-spec.ts +7 -1
  15. package/src/cmd-exercise.ts +22 -10
  16. package/src/cmd-generate.ts +2 -0
  17. package/src/cmd-jobs-spec.ts +3 -6
  18. package/src/cmd-jobs.ts +1 -7
  19. package/src/cmd-logs-spec.ts +2 -1
  20. package/src/cmd-logs.ts +9 -28
  21. package/src/cmd-planned.ts +11 -45
  22. package/src/cmd-profile-frames.ts +99 -0
  23. package/src/cmd-profile-spec.ts +24 -0
  24. package/src/cmd-profile.ts +164 -0
  25. package/src/cmd-status-sample.ts +57 -0
  26. package/src/cmd-status-spec.ts +30 -0
  27. package/src/cmd-status.ts +108 -0
  28. package/src/cmd-token-spec.ts +5 -2
  29. package/src/cmd-token.ts +7 -3
  30. package/src/coverage-island.ts +121 -0
  31. package/src/coverage-lcov.ts +49 -5
  32. package/src/coverage-remap.ts +146 -0
  33. package/src/db-replay-engine-prepared.ts +66 -0
  34. package/src/db-replay-engine-template.ts +156 -0
  35. package/src/db-replay-engine.ts +4 -0
  36. package/src/db-replay-scratch-reap.ts +54 -0
  37. package/src/deploy-verify-flags.ts +9 -2
  38. package/src/deploy-verify-grade.ts +10 -3
  39. package/src/dev-boot.ts +14 -1
  40. package/src/dev-dashboard-guard.ts +57 -10
  41. package/src/dev-host.ts +46 -0
  42. package/src/dev-tls-cache.ts +103 -0
  43. package/src/dev-tls-der.ts +69 -0
  44. package/src/dev-tls.ts +120 -0
  45. package/src/dispatch.ts +6 -1
  46. package/src/doctor-browser.ts +60 -0
  47. package/src/error-codes-verify.ts +47 -0
  48. package/src/error-codes.ts +14 -23
  49. package/src/exercise-database.ts +40 -7
  50. package/src/exercise-push-device.ts +51 -0
  51. package/src/exercise-route-api.ts +74 -0
  52. package/src/exercise-routes.ts +14 -5
  53. package/src/exercise-services.ts +3 -1
  54. package/src/exercise-shard-flag.ts +47 -0
  55. package/src/fix-command.ts +2 -2
  56. package/src/generate-factories.ts +9 -11
  57. package/src/generate-feature-required.ts +9 -4
  58. package/src/generate-files.ts +20 -2
  59. package/src/generate-kinds.ts +5 -1
  60. package/src/guards.ts +21 -6
  61. package/src/island-bundle-options.ts +48 -0
  62. package/src/island-bundle.ts +18 -46
  63. package/src/island-link.ts +5 -0
  64. package/src/island-outputs.ts +5 -0
  65. package/src/mcp-errors-verify.ts +35 -0
  66. package/src/mcp-errors.ts +10 -19
  67. package/src/mcp-host-logs.ts +121 -0
  68. package/src/mcp-host.ts +12 -73
  69. package/src/messages-floor.ts +19 -0
  70. package/src/messages-status.ts +10 -0
  71. package/src/messages.ts +21 -0
  72. package/src/registry.ts +4 -0
  73. package/src/role-start-types.ts +7 -0
  74. package/src/role-start.ts +4 -0
  75. package/src/serve-boot.ts +7 -1
  76. package/src/serve-env-tls.ts +57 -0
  77. package/src/solid-loader.ts +27 -10
  78. package/src/templates/generate-export-rows.ts +136 -0
  79. package/src/templates/generate-import-rows.ts +186 -0
  80. package/src/templates/generate-rows-slice.ts +95 -0
  81. package/src/templates/github/ci.yml.ts +4 -0
  82. package/src/templates/scaffold-db-package.ts +3 -0
  83. package/src/templates/scaffold-docs.ts +8 -6
  84. package/src/templates/scaffold-repo.ts +2 -7
  85. package/src/templates/scaffold-site.ts +4 -1
  86. package/src/templates/scaffold-suites.ts +72 -0
  87. package/src/templates/scaffold-test-services.ts +35 -10
  88. package/src/templates/scaffold-verify-floor.ts +53 -31
  89. package/src/templates/shapes/api.ts +4 -0
  90. package/src/templates/slice-foundation.ts +3 -3
  91. package/src/unthrown-codes.ts +1 -1
  92. package/src/upgrade-gate.ts +6 -1
  93. package/src/upgrade-guards-baseline.ts +43 -0
  94. package/src/upgrade-guards.ts +37 -2
  95. package/src/upgrade-report.ts +3 -0
  96. package/src/verify-coverage-run.ts +42 -11
  97. package/src/verify-e2e.ts +115 -4
  98. package/src/verify-floor.ts +27 -0
  99. package/src/verify-guard-baseline.ts +109 -0
  100. package/src/verify-live.ts +72 -0
  101. package/src/verify-merge-skips.ts +51 -0
  102. package/src/verify-merge.ts +36 -2
  103. package/src/verify-run.ts +48 -7
  104. package/src/verify-services.ts +287 -0
  105. package/src/verify-skip-reason.ts +53 -0
  106. package/src/verify-strict.ts +108 -0
  107. package/src/verify-test-command.ts +129 -0
  108. package/src/verify-tests.ts +39 -126
  109. package/types/babel-modules.d.ts +2 -0
  110. package/wiki/Agents.md +2 -5
  111. package/wiki/CLI-Reference.md +142 -23
  112. package/wiki/Caching-And-Invalidation.md +1 -1
  113. package/wiki/Entities-And-Migrations.md +1 -1
  114. package/wiki/Interface-Rules.md +5 -0
  115. package/wiki/Jobs-And-Workflows.md +3 -3
  116. package/wiki/Known-Gaps.md +5 -1
  117. package/wiki/MCP-And-AI.md +103 -2
  118. package/wiki/Mail.md +52 -0
  119. package/wiki/PWA-And-Offline.md +1 -1
  120. package/wiki/Scraping.md +19 -4
  121. package/wiki/Troubleshooting.md +3 -3
  122. package/wiki/Tutorial-05-Deploy-Free.md +2 -2
  123. package/wiki/Upgrading.md +3 -0
@@ -23,14 +23,18 @@ import { decodeCoverage, mergeCoverage } from './coverage-lcov';
23
23
  import { msg } from './messages';
24
24
  import type { CommandResult, Finding, StepResult } from './output';
25
25
  import type { TestCounts } from './test-counts';
26
+ import { deferredBrowserFinding } from './verify-e2e';
26
27
  import type { VerifyFloor } from './verify-floor';
27
28
  import { floorRequires, skippedSuiteFinding } from './verify-floor';
29
+ import { foldSkipReasons, readPartSkipReasons } from './verify-merge-skips';
28
30
  import type { PartStep } from './verify-part-step';
29
31
  import { readPartStep } from './verify-part-step';
30
32
  import { verifySummary } from './verify-run';
31
33
  import { corpusHash } from './verify-shard';
32
34
  import { judgeSkips } from './verify-skip-ceiling';
35
+ import { ranNothingReason, skipLines } from './verify-skip-reason';
33
36
  import { GATE_COMMAND, VERIFY_STEP_NAMES } from './verify-step';
37
+ import { judgeUnrun, skipWhy } from './verify-strict';
34
38
 
35
39
  /**
36
40
  * A part handed to `x verify merge` that is not an `x verify --json` document. `command` is the
@@ -55,6 +59,8 @@ export interface VerifyPart {
55
59
  readonly steps: readonly PartStep[];
56
60
  /** step → what this part's slice of it covered and did not judge (`data.coverage.<step>.facts`). */
57
61
  readonly coverage?: Readonly<Record<string, CoverageMap>>;
62
+ /** step → why it ran no check in this part (`data.skipReasons`). */
63
+ readonly skipReasons?: Readonly<Record<string, string>>;
58
64
  }
59
65
 
60
66
  /** Findings a step earns from the parts TOGETHER, which no one part could raise. */
@@ -121,11 +127,13 @@ export function parsePart(file: string, text: string, command: string = GATE_COM
121
127
  }
122
128
  coverage.set(step, map);
123
129
  }
130
+ const skipReasons = readPartSkipReasons(data);
124
131
  return {
125
132
  file,
126
133
  durationMs: typeof data['durationMs'] === 'number' ? data['durationMs'] : 0,
127
134
  steps,
128
135
  ...(coverage.size === 0 ? {} : { coverage: Object.fromEntries(coverage) }),
136
+ ...(skipReasons === undefined ? {} : { skipReasons }),
129
137
  };
130
138
  }
131
139
 
@@ -257,6 +265,7 @@ function mergeStep(
257
265
  floor: VerifyFloor | undefined,
258
266
  kinds: Gaps,
259
267
  rider: MergeRiders[string] | undefined,
268
+ command: string,
260
269
  ): StepResult {
261
270
  const gap = kinds.present;
262
271
  if (entries.length === 0) {
@@ -323,6 +332,15 @@ function mergeStep(
323
332
  const nothingRan = sharded.length > 0 && tests !== undefined && tests.ran === 0;
324
333
  const required = floorRequires(floor, name);
325
334
  const floorGap = nothingRan && required ? [skippedSuiteFinding(name, tests.skipped)] : [];
335
+ // The browser the e2e shards deferred, on the same sum, ahead of the floor's re-run fix.
336
+ const browser =
337
+ name === 'e2e' && floorGap.length > 0
338
+ ? deferredBrowserFinding(steps.flatMap((step) => step.warnings ?? []))
339
+ : undefined;
340
+ // Strict, on the same sum: each shard deferred it, exactly as it deferred the floor.
341
+ const strict = nothingRan
342
+ ? judgeUnrun(floor, name, ranNothingReason(tests), required, command)
343
+ : [];
326
344
  // The ceiling on the SUM, always: a merge is the CI verdict, and one shard's skips say nothing.
327
345
  const skips =
328
346
  sharded.length > 0
@@ -332,7 +350,9 @@ function mergeStep(
332
350
  const findings = [
333
351
  ...steps.flatMap((step) => step.findings),
334
352
  ...gaps,
353
+ ...(browser === undefined ? [] : [browser]),
335
354
  ...floorGap,
355
+ ...strict,
336
356
  ...skips.findings,
337
357
  ...riding,
338
358
  ];
@@ -343,17 +363,25 @@ function mergeStep(
343
363
  ...(rider?.output === undefined ? [] : [rider.output]),
344
364
  ].join('\n');
345
365
  // Every part's advice, once each and in the order the parts reported it.
366
+ // A `skip` why over a split step the shards together ran: each slice deferred it to the sum.
367
+ const staleWhy =
368
+ sharded.length > 0 && tests !== undefined && tests.ran > 0 && skipWhy(floor, name) !== undefined
369
+ ? [msg('cli.verify.waiverStale', { step: name })]
370
+ : [];
346
371
  const warnings = [
347
- ...new Set([...steps.flatMap((step) => step.warnings ?? []), ...skips.warnings]),
372
+ ...new Set([...steps.flatMap((step) => step.warnings ?? []), ...skips.warnings, ...staleWhy]),
348
373
  ];
349
374
  const skipped =
350
- sharded.length > 0 ? nothingRan && !required : steps.every((step) => step.skipped);
375
+ sharded.length > 0
376
+ ? nothingRan && !required && strict.length === 0
377
+ : steps.every((step) => step.skipped);
351
378
  return {
352
379
  name,
353
380
  ok:
354
381
  steps.every((step) => step.ok) &&
355
382
  gaps.length === 0 &&
356
383
  floorGap.length === 0 &&
384
+ strict.length === 0 &&
357
385
  skips.findings.length === 0 &&
358
386
  riding.length === 0,
359
387
  // The slowest job: the parts ran side by side, and wall time is what a CI run waits on.
@@ -397,6 +425,7 @@ export function mergeParts(
397
425
  options.riders !== undefined && Object.hasOwn(options.riders, name)
398
426
  ? options.riders[name]
399
427
  : undefined,
428
+ options.command ?? GATE_COMMAND,
400
429
  ),
401
430
  );
402
431
  const failed = steps.filter((step) => !step.ok).map((step) => step.name);
@@ -404,17 +433,22 @@ export function mergeParts(
404
433
  const durationMs = Math.max(0, ...parts.map((part) => part.durationMs));
405
434
  const ok = failed.length === 0 && unknown.length === 0;
406
435
  const summary = verifySummary({ results: steps, failed, skipped, totalMs: durationMs });
436
+ const unrun = foldSkipReasons(steps, parts, floor);
437
+ const lines = skipLines(unrun.reasons, unrun.unwaived);
407
438
  return {
408
439
  ok,
409
440
  command: 'verify',
410
441
  summary: msg('cli.verify.merged', { parts: parts.length, summary }),
411
442
  steps,
443
+ ...(lines.length === 0 ? {} : { lines }),
412
444
  ...(unknown.length === 0 ? {} : { findings: unknown }),
413
445
  data: {
414
446
  failed,
415
447
  skipped,
416
448
  durationMs,
417
449
  merged: { parts: parts.map((part) => part.file) },
450
+ ...(Object.keys(unrun.reasons).length === 0 ? {} : { skipReasons: unrun.reasons }),
451
+ ...(unrun.unwaived.length === 0 ? {} : { unwaived: unrun.unwaived }),
418
452
  },
419
453
  exitCode: ok ? 0 : 1,
420
454
  };
package/src/verify-run.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  vanishedSuiteFinding,
18
18
  } from './verify-floor';
19
19
  import { inCi, judgeSkips } from './verify-skip-ceiling';
20
+ import { appliesReason, ranNothingReason, skipLines } from './verify-skip-reason';
20
21
  import { stalledOutput, stepTimeoutFinding } from './verify-stalled';
21
22
  import type {
22
23
  CoverageNumbers,
@@ -26,6 +27,7 @@ import type {
26
27
  VerifyStepName,
27
28
  } from './verify-step';
28
29
  import { GATE_COMMAND } from './verify-step';
30
+ import { judgeUnrun, skipWhy } from './verify-strict';
29
31
  import { resetTestDiscovery } from './verify-tests';
30
32
 
31
33
  /**
@@ -51,6 +53,8 @@ export async function runVerify(
51
53
  // Per step: the numbers a judged run measured, or — under `--shard`, which cannot judge — the
52
54
  // `facts` its slice covered, for `x verify merge` to fold.
53
55
  const coverage = new Map<string, JsonValue>();
56
+ // Per step that ran no check: why, in words — `data.skipReasons` and one human line each.
57
+ const unrun = new Map<string, string>();
54
58
  // One per run: a step's tag is `<step>@<run>`, so two gates on one machine never kill each
55
59
  // other's children.
56
60
  const runId = crypto.randomUUID().slice(0, 8);
@@ -63,6 +67,7 @@ export async function runVerify(
63
67
  }
64
68
  const ran = await runStep(step, stepCtx, floor, runId);
65
69
  byName.set(step.name, ran.result);
70
+ if (ran.unrun !== undefined) unrun.set(step.name, ran.unrun);
66
71
  if (ran.coverage !== undefined) {
67
72
  coverage.set(step.name, { facts: encodeCoverage(ran.coverage) });
68
73
  } else if (ran.measured !== undefined) {
@@ -129,6 +134,19 @@ export async function runVerify(
129
134
  // WALL time, not the sum of step times: with steps overlapping, the sum overstates what a run
130
135
  // costs, and the wall clock is the number a CI job waits on.
131
136
  const totalMs = Math.round(performance.now() - began);
137
+ // In declared order, like the table. Not strict: the skipped steps no `skip` why excuses are a
138
+ // WARNING, never red — an existing app meets this on `main` (X_BREAKING_ON_MAIN); `next` flips it.
139
+ const skipReasons = Object.fromEntries(
140
+ results.flatMap((step) => {
141
+ const reason = unrun.get(step.name);
142
+ return reason === undefined ? [] : [[step.name, reason] as const];
143
+ }),
144
+ );
145
+ const unwaived =
146
+ floor?.strict === true
147
+ ? []
148
+ : skippedSteps.filter((name) => unrun.has(name) && skipWhy(floor, name) === undefined);
149
+ const lines = skipLines(skipReasons, unwaived);
132
150
  const summary = verifySummary({
133
151
  results,
134
152
  failed: failedSteps,
@@ -143,12 +161,15 @@ export async function runVerify(
143
161
  // user-facing string outside `messages.ts` for a fact `--json` was already carrying twice.
144
162
  summary: only === undefined ? summary : msg('cli.verify.notAGateRun', { summary }),
145
163
  steps: results,
164
+ ...(lines.length === 0 ? {} : { lines }),
146
165
  // `skipped` is a list beside `failed` and not a count, because the two answer the same kind of
147
166
  // question — *which* steps, not how many — and a caller ratcheting on coverage needs the names.
148
167
  data: {
149
168
  failed: failedSteps,
150
169
  skipped: skippedSteps,
151
170
  durationMs: totalMs,
171
+ ...(unrun.size === 0 ? {} : { skipReasons }),
172
+ ...(unwaived.length === 0 ? {} : { unwaived }),
152
173
  // A BOOLEAN beside the banner, so a reader of `--json` never has to substring-match a
153
174
  // summary line to learn that this run checked one thing.
154
175
  // `only` is always the LIST, in declared order — one name is a list of one.
@@ -227,6 +248,8 @@ async function runStep(
227
248
  readonly result: StepResult;
228
249
  readonly coverage?: CoverageMap;
229
250
  readonly measured?: CoverageNumbers;
251
+ /** Why the step ran no check, when it ran none: a skip, a vanished suite, or strict red. */
252
+ readonly unrun?: string;
230
253
  }> {
231
254
  const command = ctx.command ?? GATE_COMMAND;
232
255
  // Inside the step's own failure, like a throwing `run`: an `applies` that threw escaped every
@@ -251,14 +274,19 @@ async function runStep(
251
274
  // about. Recorded as failed and NOT as skipped, so every reader of a step table sees it:
252
275
  // the summary, `data.failed`, and the reference-app gate's own red list.
253
276
  const required = floorRequires(floor, step.name);
277
+ const reason = appliesReason(step.name);
278
+ // Strict: a step no floor line requires and no `skip` why excuses is red the same way.
279
+ const strict = judgeUnrun(floor, step.name, reason, required, command);
280
+ const red = required || strict.length > 0;
254
281
  return {
255
282
  result: {
256
283
  name: step.name,
257
- ok: !required,
284
+ ok: !red,
258
285
  durationMs: 0,
259
- skipped: !required,
260
- findings: required ? [vanishedSuiteFinding(step.name, command)] : [],
286
+ skipped: !red,
287
+ findings: required ? [vanishedSuiteFinding(step.name, command)] : strict,
261
288
  },
289
+ unrun: reason,
262
290
  };
263
291
  }
264
292
  const started = performance.now();
@@ -296,23 +324,35 @@ async function runStep(
296
324
  // with no files at all — the run just had to finish before it could be seen. Appended to the
297
325
  // step's own findings so `data.failed`, the counts and every gate reading this table carry it.
298
326
  const vanished = nothingRan && required ? [skippedSuiteFinding(step.name, tests.skipped)] : [];
327
+ const unrun = nothingRan ? ranNothingReason(tests) : undefined;
328
+ const strict = unrun === undefined ? [] : judgeUnrun(floor, step.name, unrun, required, command);
329
+ // A `skip` why over a suite that RAN tests is stale: said on the step, never red. Only on counts
330
+ // a whole run holds — a shard's slice is `x verify merge`'s to judge on the sum, and a step that
331
+ // spawned nothing (`--changed`) proves nothing either way.
332
+ const staleWhy =
333
+ tests !== undefined &&
334
+ tests.ran > 0 &&
335
+ outcome.shard === undefined &&
336
+ skipWhy(floor, step.name) !== undefined
337
+ ? [msg('cli.verify.waiverStale', { step: step.name })]
338
+ : [];
299
339
  // A mostly skipped suite, judged where the verdict is: CI, and only a whole run (a shard's
300
340
  // share is judged by `x verify merge`, on the sum). A laptop without services stays a dev loop.
301
341
  const skips =
302
342
  outcome.shard === undefined && inCi(ctx.env ?? Bun.env)
303
343
  ? judgeSkips(step.name, tests, floor?.skipCeiling)
304
344
  : { findings: [], warnings: [] };
305
- const warnings = [...(outcome.warnings ?? []), ...skips.warnings];
345
+ const warnings = [...(outcome.warnings ?? []), ...skips.warnings, ...staleWhy];
306
346
  return {
307
347
  result: {
308
348
  name: step.name,
309
- ok: outcome.ok && vanished.length === 0 && skips.findings.length === 0,
349
+ ok: outcome.ok && vanished.length === 0 && strict.length === 0 && skips.findings.length === 0,
310
350
  durationMs: Math.round(performance.now() - started),
311
351
  // Without a floor to require it, a suite that ran nothing is a SKIP and not a pass (#434):
312
352
  // the `e2e` step printed `✓ e2e 46ms` over its one skipped test, which is the one thing a
313
353
  // step table may never do — a reader cannot tell a lane that ran from a lane that did not.
314
- skipped: nothingRan && !required,
315
- findings: [...outcome.findings, ...vanished, ...skips.findings],
354
+ skipped: nothingRan && !required && strict.length === 0,
355
+ findings: [...outcome.findings, ...vanished, ...strict, ...skips.findings],
316
356
  ...(outcome.output === undefined ? {} : { output: outcome.output }),
317
357
  ...(warnings.length === 0 ? {} : { warnings }),
318
358
  ...(outcome.workers === undefined ? {} : { workers: outcome.workers }),
@@ -325,6 +365,7 @@ async function runStep(
325
365
  },
326
366
  ...(outcome.coverage === undefined ? {} : { coverage: outcome.coverage }),
327
367
  ...(outcome.measured === undefined ? {} : { measured: outcome.measured }),
368
+ ...(unrun === undefined ? {} : { unrun }),
328
369
  };
329
370
  }
330
371
 
@@ -0,0 +1,287 @@
1
+ // The test database the `live` step needs, found or started: the env file `x new` writes names
2
+ // where the suites look (`docker/test-services.env`), and its compose file is what starts them.
3
+ // Split from `verify-live.ts`, which decides WHEN; this file owns how a server is found ours (it
4
+ // answers, and takes our login) and the one `docker compose` line that brings it up.
5
+
6
+ // why: Bun ships no synchronous existence check or path-join primitive.
7
+ import { existsSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { renderThrowable } from '@ultimat3/core';
10
+ import type { Runner } from './exec';
11
+ import { execOutput } from './exec';
12
+ import type { Finding } from './output';
13
+ import { TEST_COMPOSE_PATH, TEST_ENV_PATH } from './templates/scaffold-test-services';
14
+ import { parseDotenvValues } from './test-dotenv';
15
+
16
+ /** The URL every live suite reads first; the one this file probes. */
17
+ export const TEST_DATABASE_KEY = 'TEST_DATABASE_URL';
18
+
19
+ /** The command the scaffold's own docs name, verbatim: the fix is the line a human would run. */
20
+ export const SERVICES_UP: readonly string[] = [
21
+ 'docker',
22
+ 'compose',
23
+ '-f',
24
+ TEST_COMPOSE_PATH,
25
+ 'up',
26
+ '-d',
27
+ '--wait',
28
+ // Bounded: a healthcheck that never passes would hold the step until its own deadline killed
29
+ // it, with no word of why. Two minutes is well past a RAM-only stack's cold start.
30
+ '--wait-timeout',
31
+ '120',
32
+ ];
33
+ export const SERVICES_DOWN = `docker compose -f ${TEST_COMPOSE_PATH} down`;
34
+
35
+ /** Compose's own list of the stack's running services, one name a line: asked before and after `up`. */
36
+ export const SERVICES_RUNNING: readonly string[] = [
37
+ 'docker',
38
+ 'compose',
39
+ '-f',
40
+ TEST_COMPOSE_PATH,
41
+ 'ps',
42
+ '--services',
43
+ '--status',
44
+ 'running',
45
+ ];
46
+
47
+ /** Whether something accepts a TCP connection at a URL's host and port. Injected in tests. */
48
+ export type Probe = (url: string) => Promise<boolean>;
49
+
50
+ /** Postgres's own port, for a URL that names none. */
51
+ const DEFAULT_PORT = 5432;
52
+ const PROBE_TIMEOUT_MS = 1000;
53
+
54
+ /**
55
+ * A TCP connect and nothing more: no handshake, no credentials. "Nothing listens" is the only
56
+ * question here — a server that listens and refuses the login is the suite's to report, with the
57
+ * driver's own error, not this probe's to guess at.
58
+ */
59
+ export const tcpReachable: Probe = async (url) => {
60
+ let parsed: URL;
61
+ try {
62
+ parsed = new URL(url);
63
+ } catch {
64
+ return false;
65
+ }
66
+ const hostname = parsed.hostname.replace(/^\[|\]$/g, '');
67
+ const port = parsed.port === '' ? DEFAULT_PORT : Number(parsed.port);
68
+ const { promise, resolve } = Promise.withResolvers<boolean>();
69
+ const timer = setTimeout(() => resolve(false), PROBE_TIMEOUT_MS);
70
+ const settle = (reachable: boolean) => {
71
+ clearTimeout(timer);
72
+ resolve(reachable);
73
+ };
74
+ Bun.connect({
75
+ hostname,
76
+ port,
77
+ socket: {
78
+ open: (socket) => {
79
+ socket.end();
80
+ settle(true);
81
+ },
82
+ connectError: () => settle(false),
83
+ data: () => undefined,
84
+ },
85
+ }).catch(() => settle(false));
86
+ return promise;
87
+ };
88
+
89
+ /** Whether the declared credentials log in: `refused` only on the server's own no. */
90
+ export type LoginVerdict = 'ok' | 'refused' | 'unknown';
91
+ export type LoginProbe = (url: string) => Promise<LoginVerdict>;
92
+
93
+ /** SQLSTATEs that mean "a Postgres answered and this is not our login": auth, role, database. */
94
+ const NOT_OURS = new Set(['28P01', '28000', '3D000']);
95
+
96
+ const sqlStateOf = (error: unknown): string | undefined => {
97
+ if (typeof error !== 'object' || error === null) return undefined;
98
+ const { errno, code } = error as { readonly errno?: unknown; readonly code?: unknown };
99
+ if (typeof errno === 'string') return errno;
100
+ return typeof code === 'string' ? code : undefined;
101
+ };
102
+
103
+ /**
104
+ * One `select 1` with the env file's own credentials. A port that answers TCP may be ANOTHER app's
105
+ * test stack — two scaffolds once shared one port — and its refusal is the only way to tell.
106
+ * Anything but a refusal is `unknown`: the suite reports it with the driver's own error.
107
+ */
108
+ export const postgresLogin: LoginProbe = async (url) => {
109
+ let sql: Bun.SQL | undefined;
110
+ try {
111
+ sql = new Bun.SQL(url, { max: 1, connectionTimeout: 2, idleTimeout: 1 });
112
+ await sql`select 1`;
113
+ return 'ok';
114
+ } catch (error) {
115
+ const state = sqlStateOf(error);
116
+ return state !== undefined && NOT_OURS.has(state) ? 'refused' : 'unknown';
117
+ } finally {
118
+ await sql?.close().catch(() => undefined);
119
+ }
120
+ };
121
+
122
+ const portOf = (url: string): string => {
123
+ try {
124
+ const parsed = new URL(url);
125
+ return parsed.port === '' ? String(DEFAULT_PORT) : parsed.port;
126
+ } catch {
127
+ return String(DEFAULT_PORT);
128
+ }
129
+ };
130
+
131
+ const hostOf = (url: string): string => {
132
+ try {
133
+ return new URL(url).host;
134
+ } catch {
135
+ return url;
136
+ }
137
+ };
138
+
139
+ /** Something else holds the declared port: named, with the line that shows which container. */
140
+ const foreignFinding = (url: string): Finding => ({
141
+ code: 'X_TEST_SERVICES_UNAVAILABLE',
142
+ cause: `a Postgres answers at ${hostOf(url)} (${TEST_ENV_PATH}'s ${TEST_DATABASE_KEY}) and refuses this app's credentials — another app's test stack holds the port, so the live suites are not run against it`,
143
+ fix: `docker ps --filter publish=${portOf(url)} # stop that stack (docker compose -p <project> down), or give this app another port in ${TEST_COMPOSE_PATH} and ${TEST_ENV_PATH}`,
144
+ at: TEST_ENV_PATH,
145
+ });
146
+
147
+ /** What `ensureTestServices` found: the env to hand the suites, and what happened on the way. */
148
+ export type ServicesVerdict =
149
+ /** Nothing to do: the caller's own URL, or a repo with no test stack to start. */
150
+ | { readonly kind: 'ambient' }
151
+ /**
152
+ * Postgres was already ours: the env file's values for the keys the caller left unset — every one
153
+ * once `up` brought the rest, only those whose service answers when it could not.
154
+ */
155
+ | {
156
+ readonly kind: 'reachable';
157
+ readonly env: Readonly<Record<string, string>>;
158
+ /** What this run's `up` started — compose's answer, never inferred from Postgres. */
159
+ readonly startedServices: readonly string[];
160
+ }
161
+ /** This run started it, and left it running. */
162
+ | {
163
+ readonly kind: 'started';
164
+ readonly env: Readonly<Record<string, string>>;
165
+ readonly startedServices: readonly string[];
166
+ }
167
+ /** It could not be started: the suites run as they would have, and this says why. */
168
+ | { readonly kind: 'unavailable'; readonly finding: Finding };
169
+
170
+ export interface ServicesInput {
171
+ readonly root: string;
172
+ readonly runner: Runner;
173
+ readonly env: Readonly<Record<string, string | undefined>>;
174
+ readonly probe?: Probe;
175
+ readonly login?: LoginProbe;
176
+ }
177
+
178
+ /** The env file's values for every key the caller's own environment does not already set. */
179
+ const unsetFrom = (
180
+ file: ReadonlyMap<string, string>,
181
+ env: ServicesInput['env'],
182
+ ): Readonly<Record<string, string>> => {
183
+ const out = new Map<string, string>();
184
+ for (const [key, value] of file) if (env[key] === undefined) out.set(key, value);
185
+ return Object.fromEntries(out);
186
+ };
187
+
188
+ /**
189
+ * Found or started, never torn down: the stack is RAM-only and starts in seconds, so the next run
190
+ * reuses it and the warning names `SERVICES_DOWN`. A caller URL that is NOT the env file's is the
191
+ * caller's own server — never second-guessed, reachable or not.
192
+ */
193
+ export async function ensureTestServices(input: ServicesInput): Promise<ServicesVerdict> {
194
+ const compose = join(input.root, TEST_COMPOSE_PATH);
195
+ const envFile = join(input.root, TEST_ENV_PATH);
196
+ if (!existsSync(compose) || !existsSync(envFile)) return { kind: 'ambient' };
197
+ const file = parseDotenvValues(await Bun.file(envFile).text());
198
+ const declared = file.get(TEST_DATABASE_KEY);
199
+ const ambient = input.env[TEST_DATABASE_KEY];
200
+ if (declared === undefined) return { kind: 'ambient' };
201
+ if (ambient !== undefined && ambient !== declared) return { kind: 'ambient' };
202
+ const env = unsetFrom(file, input.env);
203
+ const probe = input.probe ?? tcpReachable;
204
+ const login = (): Promise<LoginVerdict | 'down'> =>
205
+ probe(declared).then((up) => (up ? (input.login ?? postgresLogin)(declared) : 'down'));
206
+ const before = await login();
207
+ if (before === 'refused') return { kind: 'unavailable', finding: foreignFinding(declared) };
208
+ // Always the idempotent `up`, even with Postgres answering: it may still be starting (`unknown`),
209
+ // and the env file names Redis, NATS and S3 too — a key handed on must have a service behind it.
210
+ const running = await runningServices(input);
211
+ const refused = await startStack(input);
212
+ if (refused === undefined) {
213
+ const now = (await runningServices(input)) ?? new Set<string>();
214
+ const startedServices = [...now].filter((name) => running?.has(name) !== true).sort();
215
+ return { kind: before === 'down' ? 'started' : 'reachable', env, startedServices };
216
+ }
217
+ // A failed `up` may be a concurrent run's container-name conflict: ask the database again.
218
+ const after = await login();
219
+ if (after === 'refused') return { kind: 'unavailable', finding: foreignFinding(declared) };
220
+ if (after !== 'ok') return { kind: 'unavailable', finding: refused };
221
+ return { kind: 'reachable', env: await answering(env, probe), startedServices: [] };
222
+ }
223
+
224
+ /**
225
+ * The stack's running services by compose's own answer, or `undefined` when it gave none — then
226
+ * every service running after `up` counts as this run's: a warning too many, never one too few.
227
+ */
228
+ async function runningServices(input: ServicesInput): Promise<ReadonlySet<string> | undefined> {
229
+ try {
230
+ const result = await input.runner(SERVICES_RUNNING, { cwd: input.root });
231
+ if (!result.ok) return undefined;
232
+ return new Set(
233
+ result.stdout
234
+ .split('\n')
235
+ .map((line) => line.trim())
236
+ .filter((line) => line !== ''),
237
+ );
238
+ } catch {
239
+ // No `docker` on PATH: `up` reports that, with its own coded refusal.
240
+ return undefined;
241
+ }
242
+ }
243
+
244
+ /**
245
+ * The keys whose service answers, when the stack could not be brought up whole: a suite whose URL
246
+ * is unset skips, one handed a dead URL fails to connect. A value that is no URL (a certificate
247
+ * path) names no service and is kept.
248
+ */
249
+ async function answering(
250
+ env: Readonly<Record<string, string>>,
251
+ probe: Probe,
252
+ ): Promise<Readonly<Record<string, string>>> {
253
+ const kept = await Promise.all(
254
+ Object.entries(env).map(async ([key, value]) =>
255
+ !isServiceUrl(value) || (await probe(value)) ? [key, value] : undefined,
256
+ ),
257
+ );
258
+ return Object.fromEntries(kept.filter((pair) => pair !== undefined));
259
+ }
260
+
261
+ const isServiceUrl = (value: string): boolean => {
262
+ try {
263
+ return new URL(value).hostname !== '';
264
+ } catch {
265
+ return false;
266
+ }
267
+ };
268
+
269
+ /** `undefined` when the stack came up; otherwise the finding naming why and the line to run. */
270
+ async function startStack(input: ServicesInput): Promise<Finding | undefined> {
271
+ let why: string;
272
+ try {
273
+ const result = await input.runner(SERVICES_UP, { cwd: input.root });
274
+ if (result.ok) return undefined;
275
+ why = `it exited ${String(result.code)}: ${execOutput(result).slice(-400)}`;
276
+ } catch (error) {
277
+ // No `docker` on PATH: `exec.ts` raises its own coded refusal, rendered here, never thrown —
278
+ // a missing container runtime costs the live suites their database, not the whole gate.
279
+ why = renderThrowable(error);
280
+ }
281
+ return {
282
+ code: 'X_TEST_SERVICES_UNAVAILABLE',
283
+ cause: `no test database answers at ${TEST_ENV_PATH}'s ${TEST_DATABASE_KEY}, and \`${SERVICES_UP.join(' ')}\` could not start one — ${why}`,
284
+ fix: `${SERVICES_UP.join(' ')} # needs Docker running; or export ${TEST_DATABASE_KEY} to a Postgres you run`,
285
+ at: TEST_COMPOSE_PATH,
286
+ };
287
+ }
@@ -0,0 +1,53 @@
1
+ // Why a step ran no check, in words, and the lines a run prints for each. `applies` answers only
2
+ // yes or no, so the reason a step said no is written here, beside the one test that holds every
3
+ // step with an `applies` to a reason of its own.
4
+
5
+ import { APP_CONFIG_FILE } from '@ultimat3/core';
6
+ import { MANIFEST_FILENAME } from '@ultimat3/manifest';
7
+ import { msg } from './messages';
8
+ import type { TestCounts } from './test-counts';
9
+ import type { VerifyStepName } from './verify-step';
10
+
11
+ /** Each `applies` in the step list, as the sentence it would say. A step absent here never skips. */
12
+ const APPLIES_REASONS: Partial<Record<VerifyStepName, () => string>> = {
13
+ 'package-shape': () => msg('cli.verify.skip.noPackages'),
14
+ contract: () => msg('cli.verify.skip.noTypedFiles', { type: 'contract' }),
15
+ live: () => msg('cli.verify.skip.noTypedFiles', { type: 'live' }),
16
+ job: () => msg('cli.verify.skip.noTypedFiles', { type: 'job' }),
17
+ e2e: () => msg('cli.verify.skip.noTypedFiles', { type: 'e2e' }),
18
+ eval: () => msg('cli.verify.skip.noEval'),
19
+ exercise: () => msg('cli.verify.skip.noApp', { file: APP_CONFIG_FILE }),
20
+ drift: () => msg('cli.verify.skip.noApp', { file: APP_CONFIG_FILE }),
21
+ 'contract-diff': () => msg('cli.verify.skip.noManifest', { file: MANIFEST_FILENAME }),
22
+ budgets: () => msg('cli.verify.skip.noApp', { file: APP_CONFIG_FILE }),
23
+ seo: () => msg('cli.verify.skip.noApp', { file: APP_CONFIG_FILE }),
24
+ i18n: () => msg('cli.verify.skip.noApp', { file: APP_CONFIG_FILE }),
25
+ policy: () => msg('cli.verify.skip.noApp', { file: APP_CONFIG_FILE }),
26
+ roadmap: () => msg('cli.verify.skip.noRoadmap', { file: 'docs/idea/14-roadmap.md' }),
27
+ };
28
+
29
+ /** The steps with a written `applies` reason — what the completeness test holds the list to. */
30
+ export const stepsWithAppliesReason = (): readonly string[] => Object.keys(APPLIES_REASONS);
31
+
32
+ /** Why a step whose `applies` said no has nothing to check here. */
33
+ export const appliesReason = (step: string): string =>
34
+ (APPLIES_REASONS as Record<string, (() => string) | undefined>)[step]?.() ??
35
+ msg('cli.verify.skip.nothing');
36
+
37
+ /** Why a suite that spawned ran nothing: the two shapes its counts can take. */
38
+ export const ranNothingReason = (tests: TestCounts): string =>
39
+ tests.skipped === 0
40
+ ? msg('cli.verify.ranNothing')
41
+ : msg('cli.verify.allSkipped', { skipped: tests.skipped });
42
+
43
+ /**
44
+ * What a run adds to the human lines for its zero-check steps: one `skipped:` line each, then —
45
+ * on a floor that is not strict — the one warning naming the steps no `skip` why excuses.
46
+ */
47
+ export const skipLines = (
48
+ reasons: Readonly<Record<string, string>>,
49
+ unwaived: readonly string[],
50
+ ): readonly string[] => [
51
+ ...Object.entries(reasons).map(([step, reason]) => msg('cli.verify.skip.line', { step, reason })),
52
+ ...(unwaived.length === 0 ? [] : [msg('cli.verify.unwaived', { names: unwaived.join(', ') })]),
53
+ ];