@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
@@ -19,9 +19,11 @@
19
19
 
20
20
  // why: Bun ships no recursive delete and no path-join primitive; the lcov parts live under `.x/`.
21
21
  import { rm } from 'node:fs/promises';
22
- // why: Bun ships no path-join primitive.
23
- import { dirname, join } from 'node:path';
24
- import { ISOLATED_ENV } from '@ultimat3/testing';
22
+ // why: Bun ships no path API; `posix.basename` names the module an island chunk was imported by.
23
+ import { dirname, join, posix } from 'node:path';
24
+ import { ISLAND_COVERAGE_ENV, ISOLATED_ENV } from '@ultimat3/testing';
25
+ import type { ChunkPart } from './coverage-island';
26
+ import { ISLAND_MAPS_DIR, readChunkMaps, withIslandChunks } from './coverage-island';
25
27
  import type { CoverageMap } from './coverage-lcov';
26
28
  import { fileCoverageOf, mergeCoverage, parseLcov } from './coverage-lcov';
27
29
  import type { ExecResult, Runner } from './exec';
@@ -170,15 +172,30 @@ export async function runCovered(options: CoveredRunOptions): Promise<CoveredRun
170
172
  options.pace,
171
173
  options.timings !== undefined,
172
174
  ),
173
- { cwd: options.root, env: { ...overrides, ULTIMATE_TEST_WORKER: String(slot) } },
175
+ {
176
+ cwd: options.root,
177
+ env: {
178
+ ...overrides,
179
+ ULTIMATE_TEST_WORKER: String(slot),
180
+ // Where `mountIsland` records each chunk's source map, so the chunk's lines can be
181
+ // credited to the island source rather than to a temp file the cut below drops.
182
+ [ISLAND_COVERAGE_ENV]: join(base, String(index), ISLAND_MAPS_DIR),
183
+ },
184
+ },
174
185
  );
175
186
  }
176
187
  };
177
- let maps: CoverageMap[];
188
+ let parts: SlicePart[];
189
+ let coverage: CoverageMap;
178
190
  let measured: Record<string, number> = {};
179
191
  try {
180
192
  await Promise.all(Array.from({ length: width }, (_, slot) => worker(slot)));
181
- maps = await Promise.all(slices.map((_, index) => readPart(join(base, String(index)))));
193
+ parts = await Promise.all(slices.map((_, index) => readPart(join(base, String(index)))));
194
+ coverage = await withIslandChunks(
195
+ options.root,
196
+ mergeCoverage(parts.map((part) => part.own)),
197
+ parts,
198
+ );
182
199
  if (options.timings !== undefined) {
183
200
  const reports = await Promise.all(
184
201
  slices.map((_, index) => readReport(join(base, String(index)))),
@@ -224,7 +241,7 @@ export async function runCovered(options: CoveredRunOptions): Promise<CoveredRun
224
241
  tests: countsOf(results),
225
242
  ...(first === undefined ? {} : { output }),
226
243
  ...(Object.keys(measured).length === 0 ? {} : { slowest: slowestOf(measured, options.files) }),
227
- coverage: mergeCoverage(maps),
244
+ coverage,
228
245
  };
229
246
  }
230
247
 
@@ -234,17 +251,31 @@ const readReport = (dir: string): Promise<string> =>
234
251
  .text()
235
252
  .catch(() => '');
236
253
 
254
+ /** One slice's lcov: its own tree's records, and what the island chunks need to be credited. */
255
+ interface SlicePart extends ChunkPart {
256
+ readonly own: CoverageMap;
257
+ }
258
+
237
259
  /**
238
260
  * One slice's lcov as a map, kept to the app's own tree: a slice loads a thousand framework files
239
261
  * for every hundred of the app's, and none of those is what the floor measures. No file is no
240
262
  * coverage — the slice died before writing it, and its exit code already says so.
263
+ *
264
+ * The chunk records ride beside it: `mountIsland` imports an island chunk from a temp file, so
265
+ * its record names no app path, and its lines are credited back to the sources its recorded map
266
+ * names once every slice is folded (`coverage-island.ts`).
241
267
  */
242
- async function readPart(dir: string): Promise<CoverageMap> {
268
+ async function readPart(dir: string): Promise<SlicePart> {
243
269
  const file = Bun.file(join(dir, 'lcov.info'));
244
- if (!(await file.exists())) return {};
245
- return Object.fromEntries(
246
- parseLcov(await file.text())
270
+ if (!(await file.exists())) return { own: {}, records: [], maps: new Map() };
271
+ const records = parseLcov(await file.text());
272
+ const own = Object.fromEntries(
273
+ records
247
274
  .filter((record) => /^(?:apps|packages)\//.test(record.file))
248
275
  .map((record) => [record.file, fileCoverageOf(record)]),
249
276
  );
277
+ const maps = await readChunkMaps(dir);
278
+ // Only the chunks are kept past this slice: every slice's whole record list is the corpus again.
279
+ const chunks = records.filter((record) => maps.has(posix.basename(record.file)));
280
+ return { own, records: chunks, maps };
250
281
  }
package/src/verify-e2e.ts CHANGED
@@ -2,11 +2,16 @@
2
2
  // runs the suite with the e2e preload and names the app root, and the PRELOAD spawns the app — so
3
3
  // the app lives in the test process, where `deploy.newBuild()` can restart it. No browser, or not an
4
4
  // app: the suite runs as before and its browser-backed cases skip — or refuse under
5
- // `E2E_BROWSER_REQUIRED=1`.
5
+ // `E2E_BROWSER_REQUIRED=1`. An app whose `x.verify.json` requires `e2e` and ran nothing for want of
6
+ // a browser is red by `judgeE2eBrowser`, with the command that installs one.
6
7
 
7
- import { findChrome } from '@ultimat3/scraping/cdp';
8
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
9
+ import { CHROME_PATH_ENV, chromeCandidates, findChrome } from '@ultimat3/scraping/cdp';
8
10
  import { E2E_ROOT_ENV } from '@ultimat3/testing';
9
11
  import type { ExecResult } from './exec';
12
+ import type { Finding } from './output';
13
+ import { floorRequires, readVerifyFloor, VERIFY_FLOOR_FILE } from './verify-floor';
14
+ import type { StepOutcome } from './verify-step';
10
15
 
11
16
  /**
12
17
  * The preload `bun test` is handed, beside the app's own from `bunfig.toml` — `@ultimat3/testing`'s,
@@ -45,10 +50,116 @@ export async function withE2eApp(
45
50
  readonly isApp: boolean;
46
51
  readonly command: readonly string[];
47
52
  readonly env: Readonly<Record<string, string | undefined>>;
53
+ /**
54
+ * The step's whole environment (`ctx.env ?? Bun.env`), where `CHROME_PATH` is read — the same
55
+ * one `judgeE2eBrowser` reads, so the launch and the verdict never disagree about the browser.
56
+ * `env` above is only the overrides the child is handed.
57
+ */
58
+ readonly hostEnv: Readonly<Record<string, string | undefined>>;
48
59
  },
49
60
  run: (e2e: E2eRun) => Promise<ExecResult>,
50
61
  ): Promise<ExecResult> {
51
- const chrome = input.isApp ? await findChrome(Bun.env) : undefined;
62
+ const chrome = input.isApp ? await findChrome(input.hostEnv) : undefined;
52
63
  if (chrome === undefined) return run({ command: input.command, env: input.env });
53
- return run(appE2eRun(input));
64
+ return run(appE2eRun({ root: input.root, command: input.command, env: input.env }));
65
+ }
66
+
67
+ /** The floored e2e step that ran nothing because this machine has no browser to drive. */
68
+ export const E2E_BROWSER_MISSING = 'X_VERIFY_E2E_BROWSER_MISSING';
69
+
70
+ const LINUX_CHROME_DEB =
71
+ 'https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb';
72
+ const LINUX_CHROME_INSTALL = `curl -fsSLo /tmp/google-chrome.deb ${LINUX_CHROME_DEB} && sudo apt-get install -y /tmp/google-chrome.deb`;
73
+
74
+ type Env = Readonly<Record<string, string | undefined>>;
75
+
76
+ /**
77
+ * The one command that puts a browser `findChrome` probes on this platform: Google's own `.deb`
78
+ * lands at `/usr/bin/google-chrome` — never Ubuntu's `chromium`, a snap wrapper that cannot start
79
+ * outside a snap cgroup (`cdp-launch-probe.ts`) — and Homebrew's cask and winget's package at the
80
+ * paths `cdp-launch-candidates.ts` lists. Any other platform gets Linux's.
81
+ */
82
+ export function browserInstallCommand(platform: string): string {
83
+ if (platform === 'darwin') return 'brew install --cask google-chrome';
84
+ if (platform === 'win32') return 'winget install --id Google.Chrome -e';
85
+ return LINUX_CHROME_INSTALL;
86
+ }
87
+
88
+ /** Where this platform was searched: the operator's `CHROME_PATH` when set, else every candidate. */
89
+ export const browserSearched = (env: Env, platform: string): readonly string[] => {
90
+ const declared = env[CHROME_PATH_ENV];
91
+ return declared !== undefined && declared !== ''
92
+ ? [`${CHROME_PATH_ENV}=${declared}`]
93
+ : chromeCandidates(platform, env);
94
+ };
95
+
96
+ /**
97
+ * Install first, because it is the command that clears the finding on a bare machine; naming a
98
+ * binary that is already there is the alternative, behind the `#`, as is proving it took.
99
+ */
100
+ export const e2eBrowserMissingFinding = (env: Env, platform: string): Finding => ({
101
+ code: E2E_BROWSER_MISSING,
102
+ cause: `${VERIFY_FLOOR_FILE} requires the e2e step and no Chrome or Chromium was found (searched ${browserSearched(env, platform).join(', ')}), so every browser-backed e2e test skipped`,
103
+ fix: `${browserInstallCommand(platform)} # or export ${CHROME_PATH_ENV}=<any Chrome, Chromium or Edge binary>; then x doctor --json names the browser it found`,
104
+ docs: ERROR_DOCS_URL,
105
+ at: VERIFY_FLOOR_FILE,
106
+ });
107
+
108
+ /** Between a deferred finding's cause and its fix, in the one line a shard's warning carries. */
109
+ const FIX_SEPARATOR = ' — fix: ';
110
+
111
+ /**
112
+ * The finding a `--shard` slice defers, as the warning line its part carries to `x verify merge`:
113
+ * `code: cause — fix: fix`, the same line a person reads under the step.
114
+ */
115
+ export const e2eBrowserWarning = (finding: Finding): string =>
116
+ `${finding.code}: ${finding.cause}${FIX_SEPARATOR}${finding.fix}`;
117
+
118
+ /**
119
+ * The deferred finding back out of a part's warnings — the shard's machine is the one that looked
120
+ * for a browser, never the merging one. `undefined` when no shard deferred it.
121
+ */
122
+ export function deferredBrowserFinding(warnings: readonly string[]): Finding | undefined {
123
+ const head = `${E2E_BROWSER_MISSING}: `;
124
+ const line = warnings.find((warning) => warning.startsWith(head));
125
+ const at = line?.indexOf(FIX_SEPARATOR) ?? -1;
126
+ if (line === undefined || at < 0) return undefined;
127
+ return {
128
+ code: E2E_BROWSER_MISSING,
129
+ cause: line.slice(head.length, at),
130
+ fix: line.slice(at + FIX_SEPARATOR.length),
131
+ docs: ERROR_DOCS_URL,
132
+ at: VERIFY_FLOOR_FILE,
133
+ };
134
+ }
135
+
136
+ /**
137
+ * The e2e step's outcome, judged for the one case the floor alone words wrong: an APP that
138
+ * requires `e2e`, whose suite ran nothing, on a machine with no browser. `X_VERIFY_SUITE_VANISHED`
139
+ * still follows (`verify-run.ts` reads the same counts) but its fix reruns the suite, which skips
140
+ * again; this finding goes first because its fix is the one that changes the answer. Asked after
141
+ * the run, never before: a floored suite whose tests need no browser keeps passing.
142
+ *
143
+ * `sharded`: a `--shard` slice that ran nothing may sit beside one that ran, so it stays green and
144
+ * carries the finding as a warning; `x verify merge` judges it on the summed counts, as it judges
145
+ * the floor (`verify-run.ts` defers `X_VERIFY_SUITE_VANISHED` for a shard the same way).
146
+ */
147
+ export async function judgeE2eBrowser(input: {
148
+ readonly root: string;
149
+ readonly isApp: boolean;
150
+ readonly outcome: StepOutcome;
151
+ readonly env: Env;
152
+ readonly platform?: string;
153
+ readonly sharded?: boolean;
154
+ }): Promise<StepOutcome> {
155
+ const { outcome } = input;
156
+ if (!input.isApp || outcome.tests === undefined || outcome.tests.ran > 0) return outcome;
157
+ if (!floorRequires(await readVerifyFloor(input.root), 'e2e')) return outcome;
158
+ const platform = input.platform ?? process.platform;
159
+ if ((await findChrome(input.env, platform)) !== undefined) return outcome;
160
+ const finding = e2eBrowserMissingFinding(input.env, platform);
161
+ if (input.sharded === true) {
162
+ return { ...outcome, warnings: [...(outcome.warnings ?? []), e2eBrowserWarning(finding)] };
163
+ }
164
+ return { ...outcome, ok: false, findings: [finding, ...outcome.findings] };
54
165
  }
@@ -16,9 +16,13 @@ import { EXERCISE_FIELD, readExerciseFloor } from './exercise-floor';
16
16
  import type { Finding } from './output';
17
17
  import type { StepTimeouts } from './verify-deadline';
18
18
  import { readStepTimeouts, STEP_TIMEOUT_FIELD } from './verify-deadline';
19
+ import type { GuardBaseline } from './verify-guard-baseline';
20
+ import { GUARD_BASELINE_FIELD, readGuardBaseline } from './verify-guard-baseline';
19
21
  import type { SkipCeiling } from './verify-skip-ceiling';
20
22
  import { readSkipCeiling, SKIP_CEILING_FIELD } from './verify-skip-ceiling';
21
23
  import { GATE_COMMAND, VERIFY_STEP_NAMES } from './verify-step';
24
+ import type { SkipReasons } from './verify-strict';
25
+ import { readStrict, SKIP_FIELD, STRICT_FIELD } from './verify-strict';
22
26
 
23
27
  /** Hand-written and committed, beside the generated `x.manifest.json` the same gate reads. */
24
28
  export const VERIFY_FLOOR_FILE = 'x.verify.json';
@@ -82,6 +86,15 @@ export interface VerifyFloor {
82
86
  * naming the figure to write, never red: an app that has not opted in stays green on `main`.
83
87
  */
84
88
  readonly exercise?: ExerciseFloor;
89
+ /**
90
+ * Every one of the 21 steps must run a check or carry a `skip` why (`verify-strict.ts`): red is
91
+ * `X_VERIFY_STRICT_UNRUN`. Absent or `false` is a warning naming the steps that ran none.
92
+ */
93
+ readonly strict?: boolean;
94
+ /** Step → the written reason it runs no check in this repository (`verify-strict.ts`). */
95
+ readonly skip?: SkipReasons;
96
+ /** Guard → the findings it may still report as notices (`verify-guard-baseline.ts`). */
97
+ readonly guardBaseline?: GuardBaseline;
85
98
  /** Why part of the file is not a floor. The `manifest` step reports these; nothing swallows them. */
86
99
  readonly problems: readonly string[];
87
100
  }
@@ -202,6 +215,8 @@ export function parseVerifyFloor(
202
215
  const rolling = readRollingSince(record);
203
216
  const skips = readSkipCeiling(record, declared);
204
217
  const exercise = readExerciseFloor(record);
218
+ const strict = readStrict(record, declared);
219
+ const guards = readGuardBaseline(record);
205
220
  const rest = {
206
221
  ...(budget.budget === undefined ? {} : { agentsMdMaxBytes: budget.budget }),
207
222
  ...(typecheckBin.bin === undefined ? {} : { typecheckBin: typecheckBin.bin }),
@@ -211,7 +226,11 @@ export function parseVerifyFloor(
211
226
  ...(rolling.since === undefined ? {} : { rollingSince: rolling.since }),
212
227
  ...(skips.ceiling === undefined ? {} : { skipCeiling: skips.ceiling }),
213
228
  ...(exercise.floor === undefined ? {} : { exercise: exercise.floor }),
229
+ ...(strict.strict === undefined ? {} : { strict: strict.strict }),
230
+ ...(strict.skip === undefined ? {} : { skip: strict.skip }),
231
+ ...(guards.baseline === undefined ? {} : { guardBaseline: guards.baseline }),
214
232
  };
233
+ const later = [...strict.problems, ...guards.problems];
215
234
  const steps = record?.['steps'];
216
235
  if (!Array.isArray(steps)) {
217
236
  return {
@@ -227,6 +246,7 @@ export function parseVerifyFloor(
227
246
  ...rolling.problems,
228
247
  ...skips.problems,
229
248
  ...exercise.problems,
249
+ ...later,
230
250
  ],
231
251
  };
232
252
  }
@@ -248,6 +268,7 @@ export function parseVerifyFloor(
248
268
  ...rolling.problems,
249
269
  ...skips.problems,
250
270
  ...exercise.problems,
271
+ ...later,
251
272
  ],
252
273
  };
253
274
  }
@@ -329,6 +350,12 @@ export const floorProblemFindings = (floor: VerifyFloor | undefined): readonly F
329
350
  * problem this file can report that is not about `steps` at all.
330
351
  */
331
352
  const fixFor = (problem: string): string => {
353
+ if (problem.includes(`"${STRICT_FIELD}"`))
354
+ return `x verify --json # then set "${STRICT_FIELD}" in ${VERIFY_FLOOR_FILE} to true or false`;
355
+ if (problem.startsWith(`"${SKIP_FIELD}"`))
356
+ return `x verify --json # then write "${SKIP_FIELD}" in ${VERIFY_FLOOR_FILE} as { "e2e": "<why>" } — a step it runs and "steps" does not list, a written reason`;
357
+ if (problem.includes(`"${GUARD_BASELINE_FIELD}"`))
358
+ return `x verify --only boundaries --json # then write "${GUARD_BASELINE_FIELD}" in ${VERIFY_FLOOR_FILE} as { "<guard>": 3 } — a file in guards/, a whole number of findings`;
332
359
  if (problem.includes(`"${BUDGET_FIELD}"`))
333
360
  return `x verify --json # then set "${BUDGET_FIELD}" in ${VERIFY_FLOOR_FILE} to a positive whole number of bytes, or drop the key for the ${AGENTS_MD_MAX_BYTES}B default`;
334
361
  if (problem.includes(`"${TYPECHECK_BIN_FIELD}"`))
@@ -0,0 +1,109 @@
1
+ // `guardBaseline` in `x.verify.json`: how many findings one guard may still report while the tree
2
+ // is brought under it. Up to the count they are notices; above it red. The count only falls: one
3
+ // above what the tree has is red too, naming the lower number, so slack is never banked.
4
+
5
+ import { ERROR_DOCS_URL, renderFixShellArg } from '@ultimat3/core';
6
+ import type { Finding } from './output';
7
+
8
+ /** The floor's per-guard baseline key. Named once: the problem quotes it and the fix repairs it. */
9
+ export const GUARD_BASELINE_FIELD = 'guardBaseline';
10
+
11
+ /** Over the baseline. A string here until the coordinator registers it in `error-codes.ts`. */
12
+ export const GUARD_OVER_BASELINE_CODE = 'X_GUARD_OVER_BASELINE';
13
+
14
+ /** Under the baseline. A string here until the coordinator registers it in `error-codes.ts`. */
15
+ export const GUARD_BASELINE_STALE_CODE = 'X_GUARD_BASELINE_STALE';
16
+
17
+ /** Guard name (its file in `guards/`, no extension) → the findings it may still report. */
18
+ export type GuardBaseline = Readonly<Record<string, number>>;
19
+
20
+ /** A guard's file stem: what `x g guard <name>` writes as `guards/<name>.ts`. */
21
+ const GUARD_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
22
+
23
+ /** `{ "<guard>": n }`, a file stem and a whole number at or above zero each, or the problems. */
24
+ export function readGuardBaseline(payload: Record<string, unknown> | undefined): {
25
+ baseline?: GuardBaseline;
26
+ problems: readonly string[];
27
+ } {
28
+ const raw = payload?.[GUARD_BASELINE_FIELD];
29
+ if (raw === undefined) return { problems: [] };
30
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
31
+ return { problems: [`"${GUARD_BASELINE_FIELD}" is not an object of { "<guard>": findings }`] };
32
+ }
33
+ const problems: string[] = [];
34
+ const baseline = new Map<string, number>();
35
+ for (const [name, n] of Object.entries(raw)) {
36
+ if (!GUARD_NAME.test(name)) {
37
+ problems.push(
38
+ `"${GUARD_BASELINE_FIELD}" names ${JSON.stringify(name)}, not a guard file name`,
39
+ );
40
+ } else if (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0) {
41
+ problems.push(
42
+ `"${GUARD_BASELINE_FIELD}" gives ${name} ${JSON.stringify(n)}, which is not a whole number of findings`,
43
+ );
44
+ } else baseline.set(name, n);
45
+ }
46
+ return { ...(baseline.size === 0 ? {} : { baseline: Object.fromEntries(baseline) }), problems };
47
+ }
48
+
49
+ /** `guards/no-eval.ts` → `no-eval`: the key a baseline is written under. */
50
+ export const guardNameOf = (path: string): string =>
51
+ (path.split('/').pop() ?? path).replace(/\.tsx?$/, '');
52
+
53
+ const allowedFor = (baseline: GuardBaseline | undefined, name: string): number | undefined =>
54
+ baseline !== undefined && Object.hasOwn(baseline, name) ? baseline[name] : undefined;
55
+
56
+ const stale = (path: string, name: string, count: number, allowed: number): Finding => ({
57
+ code: GUARD_BASELINE_STALE_CODE,
58
+ cause: `${path} reports ${String(count)} finding(s) and x.verify.json "${GUARD_BASELINE_FIELD}" still allows ${String(allowed)}: the baseline only falls`,
59
+ fix:
60
+ count === 0
61
+ ? `x verify --only boundaries --json # then drop "${name}" from "${GUARD_BASELINE_FIELD}" in x.verify.json`
62
+ : `x verify --only boundaries --json # then lower your baseline to ${String(count)}: "${GUARD_BASELINE_FIELD}": { "${name}": ${String(count)} } in x.verify.json`,
63
+ docs: ERROR_DOCS_URL,
64
+ at: 'x.verify.json',
65
+ });
66
+
67
+ const over = (path: string, count: number, allowed: number): Finding => ({
68
+ code: GUARD_OVER_BASELINE_CODE,
69
+ cause: `${path} reports ${String(count)} finding(s) and x.verify.json "${GUARD_BASELINE_FIELD}" allows ${String(allowed)}`,
70
+ fix: `x verify --only boundaries --json # fix what ${renderFixShellArg(path, '<guard>')} lists until at most ${String(allowed)} remain — the baseline never rises`,
71
+ docs: ERROR_DOCS_URL,
72
+ at: path,
73
+ });
74
+
75
+ /**
76
+ * One gating guard's findings against its baseline. No entry: every finding fails, as before.
77
+ * At or under: they ride as notices, and under is the stale finding naming the number to write.
78
+ * Over: they fail, with the finding that says by how much.
79
+ */
80
+ export function judgeGuardBaseline(
81
+ path: string,
82
+ held: readonly Finding[],
83
+ baseline: GuardBaseline | undefined,
84
+ ): { readonly findings: readonly Finding[]; readonly notices: readonly Finding[] } {
85
+ const name = guardNameOf(path);
86
+ const allowed = allowedFor(baseline, name);
87
+ if (allowed === undefined) return { findings: held, notices: [] };
88
+ if (held.length > allowed) {
89
+ return { findings: [...held, over(path, held.length, allowed)], notices: [] };
90
+ }
91
+ return {
92
+ findings: held.length < allowed ? [stale(path, name, held.length, allowed)] : [],
93
+ notices: held,
94
+ };
95
+ }
96
+
97
+ /**
98
+ * A baseline naming a guard this app no longer has holds slack for nothing: stale, at zero.
99
+ * Judged over the run's own guard list, so a deleted guard cannot leave its count behind.
100
+ */
101
+ export const orphanedBaselineFindings = (
102
+ paths: readonly string[],
103
+ baseline: GuardBaseline | undefined,
104
+ ): readonly Finding[] => {
105
+ const present = new Set(paths.map(guardNameOf));
106
+ return Object.entries(baseline ?? {})
107
+ .filter(([name]) => !present.has(name))
108
+ .map(([name, allowed]) => stale(`guards/${name}.ts`, name, 0, allowed));
109
+ };
@@ -0,0 +1,72 @@
1
+ // The `live` step's one precondition: a test database. When the floor requires the step (or
2
+ // `--only` asks for it) and nothing answers, the gate starts the stack `x new` wrote
3
+ // (`verify-services.ts`) and hands its env to the suites — so "no database" is one command the
4
+ // gate runs itself, not a runner each app writes.
5
+
6
+ import type { Runner } from './exec';
7
+ import { msg } from './messages';
8
+ import { floorRequires, readVerifyFloor } from './verify-floor';
9
+ import type { LoginProbe, Probe } from './verify-services';
10
+ import { ensureTestServices, SERVICES_DOWN, SERVICES_UP } from './verify-services';
11
+ import type { StepOutcome, VerifyContext, VerifyStep } from './verify-step';
12
+
13
+ /** Whether this run asked for `live` by name or the committed floor holds it to running. */
14
+ async function liveRequired(ctx: VerifyContext): Promise<boolean> {
15
+ const only = ctx.only === undefined ? [] : typeof ctx.only === 'string' ? [ctx.only] : ctx.only;
16
+ if (only.includes('live')) return true;
17
+ return floorRequires(await readVerifyFloor(ctx.root), 'live');
18
+ }
19
+
20
+ /** `ctx` whose every child sees `env` beneath its own overrides — an explicit unset still wins. */
21
+ function withEnv(ctx: VerifyContext, env: Readonly<Record<string, string>>): VerifyContext {
22
+ const runner: Runner = (command, options) =>
23
+ ctx.runner(command, { ...options, env: { ...env, ...options.env } });
24
+ return { ...ctx, runner, env: { ...(ctx.env ?? Bun.env), ...env } };
25
+ }
26
+
27
+ const withWarning = (outcome: StepOutcome, warning: string): StepOutcome => ({
28
+ ...outcome,
29
+ warnings: [...(outcome.warnings ?? []), warning],
30
+ });
31
+
32
+ /**
33
+ * `step` with its database found or started first. A stack that cannot be started is a WARNING on
34
+ * this major, carrying `X_TEST_SERVICES_UNAVAILABLE` and the line to run: the suites skip exactly
35
+ * as they did before, and a floor whose every live test skipped is still `X_VERIFY_SUITE_VANISHED`.
36
+ * Never torn down: the next run reuses it, and the warning says how to stop it.
37
+ */
38
+ export function withTestServices(step: VerifyStep, probe?: Probe, login?: LoginProbe): VerifyStep {
39
+ return {
40
+ ...step,
41
+ async run(ctx) {
42
+ if (!(await liveRequired(ctx))) return step.run(ctx);
43
+ const verdict = await ensureTestServices({
44
+ root: ctx.root,
45
+ runner: ctx.runner,
46
+ env: ctx.env ?? Bun.env,
47
+ ...(probe === undefined ? {} : { probe }),
48
+ ...(login === undefined ? {} : { login }),
49
+ });
50
+ if (verdict.kind === 'ambient') return step.run(ctx);
51
+ if (verdict.kind === 'unavailable') {
52
+ const { code, cause, fix } = verdict.finding;
53
+ return withWarning(
54
+ await step.run(ctx),
55
+ msg('cli.verify.services.unavailable', { code, cause, fix }),
56
+ );
57
+ }
58
+ const outcome = await step.run(withEnv(ctx, verdict.env));
59
+ // Whatever this run's `up` started, by compose's answer — a reachable Postgres beside a
60
+ // freshly started Redis still leaves containers running; a stack already up says nothing.
61
+ if (verdict.startedServices.length === 0) return outcome;
62
+ return withWarning(
63
+ outcome,
64
+ msg('cli.verify.services.started', {
65
+ services: verdict.startedServices.join(', '),
66
+ command: SERVICES_UP.join(' '),
67
+ stop: SERVICES_DOWN,
68
+ }),
69
+ );
70
+ },
71
+ };
72
+ }
@@ -0,0 +1,51 @@
1
+ // `x verify merge`'s zero-check steps: each part's own `data.skipReasons`, read back and folded
2
+ // with the reason the summed shard counts give, and the same not-strict warning a whole run
3
+ // prints. Split from `verify-merge.ts`, which folds the verdict; this folds the reasons.
4
+
5
+ import type { StepResult } from './output';
6
+ import type { VerifyFloor } from './verify-floor';
7
+ import { ranNothingReason } from './verify-skip-reason';
8
+ import { skipWhy } from './verify-strict';
9
+
10
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
11
+ typeof value === 'object' && value !== null && !Array.isArray(value);
12
+
13
+ /** A part document's `data.skipReasons`, string values only; absent when it carries none. */
14
+ export const readPartSkipReasons = (
15
+ data: Record<string, unknown>,
16
+ ): Readonly<Record<string, string>> | undefined => {
17
+ const raw = data['skipReasons'];
18
+ if (!isRecord(raw)) return undefined;
19
+ const reasons = Object.entries(raw).filter(
20
+ (entry): entry is [string, string] => typeof entry[1] === 'string',
21
+ );
22
+ return reasons.length === 0 ? undefined : Object.fromEntries(reasons);
23
+ };
24
+
25
+ /**
26
+ * Per merged step, in declared order: the reason a part gave, else — a split step whose shards
27
+ * together ran nothing — the reason the sum gives. Then the steps no `skip` why excuses, on a
28
+ * floor that is not strict.
29
+ */
30
+ export function foldSkipReasons(
31
+ steps: readonly StepResult[],
32
+ parts: readonly { readonly skipReasons?: Readonly<Record<string, string>> }[],
33
+ floor: VerifyFloor | undefined,
34
+ ): { readonly reasons: Readonly<Record<string, string>>; readonly unwaived: readonly string[] } {
35
+ const reasons = new Map<string, string>();
36
+ for (const step of steps) {
37
+ const given = parts.find((part) => part.skipReasons?.[step.name] !== undefined);
38
+ const reason =
39
+ given?.skipReasons?.[step.name] ??
40
+ (step.tests !== undefined && step.tests.ran === 0 ? ranNothingReason(step.tests) : undefined);
41
+ if (reason !== undefined) reasons.set(step.name, reason);
42
+ }
43
+ const unwaived =
44
+ floor?.strict === true
45
+ ? []
46
+ : steps
47
+ .filter((step) => step.skipped === true && reasons.has(step.name))
48
+ .filter((step) => skipWhy(floor, step.name) === undefined)
49
+ .map((step) => step.name);
50
+ return { reasons: Object.fromEntries(reasons), unwaived };
51
+ }