@ultimat3/cli 31.3.0 → 31.4.1

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 (33) hide show
  1. package/package.json +29 -29
  2. package/src/cmd-doctor.ts +12 -316
  3. package/src/doctor-database.ts +121 -0
  4. package/src/doctor-port.ts +88 -0
  5. package/src/doctor-probe.ts +148 -0
  6. package/src/framework-schema.ts +4 -2
  7. package/src/guard-sources.ts +32 -11
  8. package/src/templates/guard-bare-error.ts +1 -1
  9. package/src/templates/guard-error-declared.ts +51 -5
  10. package/src/templates/guard-image-dimensions.ts +3 -2
  11. package/src/templates/guard-local-binding.ts +74 -0
  12. package/src/templates/guard-native-confirm.ts +16 -1
  13. package/src/templates/guard-raw-fetch.ts +11 -3
  14. package/src/templates/guard-raw-interval.ts +8 -1
  15. package/src/templates/guard-raw-motion.ts +20 -4
  16. package/src/templates/guard-semantic-interactive.ts +20 -2
  17. package/src/templates/guard-undeclared-custom-property.ts +34 -10
  18. package/src/templates/guard-undefined-style-class.ts +34 -7
  19. package/src/templates/guard-untranslated-string.ts +5 -4
  20. package/src/templates/guard-unzoned-date.ts +14 -1
  21. package/src/templates/scaffold-auth.ts +7 -10
  22. package/src/templates/scaffold-claude-agents.ts +1 -1
  23. package/src/templates/scaffold-claude-commands.ts +1 -1
  24. package/src/templates/scaffold-docs.ts +1 -1
  25. package/src/templates/scaffold-domain-package.ts +1 -1
  26. package/src/templates/slice-foundation.ts +1 -1
  27. package/wiki/Actions.md +3 -2
  28. package/wiki/Agents.md +1 -1
  29. package/wiki/Building-Your-Own-Base.md +1 -1
  30. package/wiki/Interface-Rules.md +3 -3
  31. package/wiki/MCP-And-AI.md +1 -1
  32. package/wiki/Stability.md +6 -5
  33. package/wiki/Upgrading.md +11 -10
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cli",
3
- "version": "31.3.0",
3
+ "version": "31.4.1",
4
4
  "description": "The `x` binary: new, dev, build, verify, generate, db, mcp, doctor, deploy",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -53,34 +53,34 @@
53
53
  },
54
54
  "dependencies": {
55
55
  "@babel/core": "^8.0.9",
56
- "@ultimat3/action": "31.3.0",
57
- "@ultimat3/admin": "31.3.0",
58
- "@ultimat3/ai": "31.3.0",
59
- "@ultimat3/auth": "31.3.0",
60
- "@ultimat3/cache": "31.3.0",
61
- "@ultimat3/core": "31.3.0",
62
- "@ultimat3/db": "31.3.0",
63
- "@ultimat3/entity": "31.3.0",
64
- "@ultimat3/flags": "31.3.0",
65
- "@ultimat3/http": "31.3.0",
66
- "@ultimat3/i18n": "31.3.0",
67
- "@ultimat3/jobs": "31.3.0",
68
- "@ultimat3/mail": "31.3.0",
69
- "@ultimat3/manifest": "31.3.0",
70
- "@ultimat3/mcp": "31.3.0",
71
- "@ultimat3/money": "31.3.0",
72
- "@ultimat3/notify": "31.3.0",
73
- "@ultimat3/policy": "31.3.0",
74
- "@ultimat3/pwa": "31.3.0",
75
- "@ultimat3/query": "31.3.0",
76
- "@ultimat3/realtime": "31.3.0",
77
- "@ultimat3/render": "31.3.0",
78
- "@ultimat3/schema": "31.3.0",
79
- "@ultimat3/scraping": "31.3.0",
80
- "@ultimat3/seo": "31.3.0",
81
- "@ultimat3/storage": "31.3.0",
82
- "@ultimat3/testing": "31.3.0",
83
- "@ultimat3/time": "31.3.0",
56
+ "@ultimat3/action": "31.4.1",
57
+ "@ultimat3/admin": "31.4.1",
58
+ "@ultimat3/ai": "31.4.1",
59
+ "@ultimat3/auth": "31.4.1",
60
+ "@ultimat3/cache": "31.4.1",
61
+ "@ultimat3/core": "31.4.1",
62
+ "@ultimat3/db": "31.4.1",
63
+ "@ultimat3/entity": "31.4.1",
64
+ "@ultimat3/flags": "31.4.1",
65
+ "@ultimat3/http": "31.4.1",
66
+ "@ultimat3/i18n": "31.4.1",
67
+ "@ultimat3/jobs": "31.4.1",
68
+ "@ultimat3/mail": "31.4.1",
69
+ "@ultimat3/manifest": "31.4.1",
70
+ "@ultimat3/mcp": "31.4.1",
71
+ "@ultimat3/money": "31.4.1",
72
+ "@ultimat3/notify": "31.4.1",
73
+ "@ultimat3/policy": "31.4.1",
74
+ "@ultimat3/pwa": "31.4.1",
75
+ "@ultimat3/query": "31.4.1",
76
+ "@ultimat3/realtime": "31.4.1",
77
+ "@ultimat3/render": "31.4.1",
78
+ "@ultimat3/schema": "31.4.1",
79
+ "@ultimat3/scraping": "31.4.1",
80
+ "@ultimat3/seo": "31.4.1",
81
+ "@ultimat3/storage": "31.4.1",
82
+ "@ultimat3/testing": "31.4.1",
83
+ "@ultimat3/time": "31.4.1",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
package/src/cmd-doctor.ts CHANGED
@@ -2,203 +2,40 @@
2
2
  // carries the command that fixes it; a diagnostic that only describes a problem has handed the
3
3
  // work back to the reader.
4
4
 
5
- import { existsSync } from 'node:fs';
6
- import { dirname, join, resolve, sep } from 'node:path';
7
5
  import { ENV_EXAMPLE_PATH, ERROR_DOCS_URL } from '@ultimat3/core';
8
- import { checkDb, PGLITE_FIX, PGLITE_MISSING, PGLITE_PACKAGE, postgresClient } from '@ultimat3/db';
9
- import { loadApp } from './app-load';
10
- import { IMPORT_UNRESOLVED } from './app-load-unresolved';
11
- import { findAppRoot, REQUIRED_BUN, versionAtLeast } from './app-root';
6
+ import { REQUIRED_BUN, versionAtLeast } from './app-root';
12
7
  import { doctorSpec } from './cmd-doctor-spec';
13
8
  import type { CliCommand, CommandContext } from './command';
14
- import { checkMigrationSnapshots } from './db-snapshot';
15
9
  import { appUrlFindings } from './doctor-app-url';
16
- import { type AuthStorageFact, authStorageFindings, authStorageProbe } from './doctor-auth';
10
+ import { authStorageFindings } from './doctor-auth';
17
11
  import { chartAlertsProbe, withChartAlertsListing } from './doctor-chart-alerts';
18
12
  import { coverageExcludesProbe, withCoverageExcludes } from './doctor-coverage';
13
+ import { embeddedDatabaseFinding } from './doctor-database';
19
14
  import { shippedGuardsProbe, withGuardListing } from './doctor-guards';
20
- import type { OfflineFallbackFact } from './doctor-offline';
21
- import { offlineFallbackFinding, offlineFallbackProbe } from './doctor-offline';
22
- import type { PoolerFact } from './doctor-pooler';
23
- import { NO_POOLER_FACT, poolerFindings, poolerProbe, withPoolerReport } from './doctor-pooler';
15
+ import { offlineFallbackFinding } from './doctor-offline';
16
+ import { NO_POOLER_FACT, poolerFindings, withPoolerReport } from './doctor-pooler';
17
+ import { doctorPort, portFindings } from './doctor-port';
18
+ import type { DoctorProbe } from './doctor-probe';
19
+ import { probeFor } from './doctor-probe';
24
20
  import { rollingSinceProbe, withRollingReminder } from './doctor-rolling';
25
- import { rowSecurityProbe } from './doctor-row-security';
26
- import type { SealedKeysFact } from './doctor-sealed';
27
- import { sealedKeyFindings, sealedKeysProbe } from './doctor-sealed';
28
- import { typescriptFindings, typescriptProbe } from './doctor-typescript';
29
- import { PORT_RANGE, portPairAfter, readIntFlag } from './flag-number';
30
- import { machineSecretFindings } from './framework-env';
21
+ import { sealedKeyFindings } from './doctor-sealed';
22
+ import { typescriptFindings } from './doctor-typescript';
31
23
  import { ICON_SOURCE } from './icon-assets';
32
24
  import { msg } from './messages';
33
25
  import type { CommandResult, Finding } from './output';
34
- import { findingFrom } from './output';
35
- import type { ParsedArgs } from './parse';
36
- import { portFree } from './port-probe';
37
- import { syncPortFor } from './role-sync';
38
- import { checkMigrationDrift } from './schema-drift';
39
- import { portFromEnv } from './serve-env';
40
26
  import { quoteArg } from './shell-quote';
41
- import type { TypescriptLag } from './typescript-floor';
42
27
 
43
- /**
44
- * The injection seam `runDoctor` reads instead of the environment. Not a semver surface —
45
- * `wiki/Upgrading.md` covers `X_*` codes, the eight primitive shapes, the `x` CLI surface, the
46
- * tier table and `app.config.ts` fields, and not this — so a new fact the probe must report is a
47
- * REQUIRED field: an optional one lets an implementation skip the check and still typecheck.
48
- */
49
- export interface DoctorProbe {
50
- readonly bunVersion: string;
51
- /** App root, or undefined when the command runs outside an app. */
52
- readonly root: string | undefined;
53
- readonly port: number;
54
- /** `APP_URL` as this environment declares it; `undefined` when unset. */
55
- readonly appUrl: string | undefined;
56
- /**
57
- * The framework's own secrets this machine lacks — `framework-env.ts`'s
58
- * `machineSecretFindings`, gated by `namedDeployed`: only an environment NAMED staging or
59
- * production (an unnamed developer shell owes nothing; `x env check` is the fail-closed answer).
60
- * The list's own `needed`/`unsafe` decide; doctor reports.
61
- */
62
- readonly frameworkFindings: readonly Finding[];
63
- exists(relativePath: string): boolean;
64
- portFree(port: number): Promise<boolean>;
65
- /**
66
- * Is the configured database reachable, and what refused? `null` is "reachable, or there is
67
- * nothing external to reach" — an unset `DATABASE_URL` is embedded PGlite, which `x dev` owns
68
- * and which a probe would take the single-writer lock on.
69
- *
70
- * Until this existed `x doctor` answered "no findings — environment is shippable" against
71
- * `DATABASE_URL=postgres://nope:nope@localhost:5432/nope`, while `x db migrate` on the same env
72
- * correctly answered `X_DB_UNAVAILABLE` (#F5).
73
- */
74
- database(): Promise<Finding | null>;
75
- /**
76
- * Is the EMBEDDED database usable, and is it the one this environment would open? A FACT and not
77
- * a finding, the split `offlineFallback` makes below: reaching a module resolver is IO, and what
78
- * an unresolvable optional peer MEANS is a pure rule with a pure test.
79
- *
80
- * `database()` answers `null` the moment `DATABASE_URL` is unset — which is exactly a bare VM,
81
- * the configuration `x dev` invents a database FOR — so until this existed `x doctor` was silent
82
- * about the only database a fresh box has. `bin/setup` found out instead, at `x db migrate`.
83
- */
84
- embeddedDatabase(): Promise<EmbeddedDatabase>;
85
- drift(): Promise<readonly Finding[]>;
86
- /**
87
- * The other half of the migrations directory: a newest migration with no `.snapshot.json`, which
88
- * is what `x db gen` refuses on. Separate from `drift()` because they are separate questions with
89
- * separate remedies — one is "generate a migration", the other is "this migration is incomplete".
90
- */
91
- snapshots(): Promise<readonly Finding[]>;
92
- /**
93
- * What the app declared as its offline fallback, and which routes it really serves. A FACT and
94
- * not a finding, because deciding is `offlineFallbackFinding`'s and this seam's whole job is
95
- * reaching the disk — the same split `drift()` makes one question over.
96
- */
97
- offlineFallback(): Promise<OfflineFallbackFact>;
98
- /**
99
- * The app's `.sealed()` columns and the master keys this environment declares. A FACT, for the
100
- * reason `offlineFallback` is one: loading the app and opening the secrets file is IO, and what
101
- * a retired key beside a sealed column means is `sealedKeyFindings`' pure rule.
102
- */
103
- sealedKeys(): Promise<SealedKeysFact>;
104
- /**
105
- * What an upgrade left in the auth tables for an operator to finish: unsealed second-factor
106
- * secrets, and tables no release reads. Asked of an external database only.
107
- */
108
- authStorage(): Promise<AuthStorageFact>;
109
- /** The statement bound the session really reads, and what a pooler refused (`doctor-pooler.ts`). */
110
- pooler(): Promise<PoolerFact>;
111
- /** Each manifest whose `typescript` range lags the scaffold's (`doctor-typescript.ts`). */
112
- typescript(): Promise<readonly TypescriptLag[]>;
113
- /** With `database.rowSecurity` on, whether the serving role is exempt (`doctor-row-security.ts`). */
114
- rowSecurity?(): Promise<readonly Finding[]>;
115
- }
116
-
117
- /** What `x doctor` reads about the embedded database, without opening it. */
118
- export interface EmbeddedDatabase {
119
- /**
120
- * True while `DATABASE_URL` is unset or blank — the condition that makes PGlite the app's
121
- * database (`resolveServices`), and the same reading `probeDatabase` returns `null` on.
122
- */
123
- readonly selected: boolean;
124
- /** Does `@electric-sql/pglite` resolve from the app root? */
125
- readonly resolved: boolean;
126
- }
28
+ // `src/index.ts` publishes the seam from here; its declaration lives in `doctor-probe.ts`.
29
+ export type { DoctorProbe } from './doctor-probe';
127
30
 
128
31
  const finding = (code: string, cause: string, fix: string, at?: string): Finding =>
129
32
  at === undefined
130
33
  ? { code, cause, fix, docs: ERROR_DOCS_URL }
131
34
  : { code, cause, fix, docs: ERROR_DOCS_URL, at };
132
35
 
133
- /**
134
- * The rule, pure. Red only where the embedded database is the one that would be opened: an app
135
- * pointed at a real Postgres never loads PGlite, and a finding about an absent optional peer there
136
- * is noise the reader learns to skim.
137
- *
138
- * `@ultimat3/db`'s own refusal, not a CLI twin of it — same `X_DB_UNAVAILABLE`, same sentence,
139
- * same runnable fix. The package already says this the moment a query arrives; `x doctor` is what
140
- * says it before `bin/setup` gets that far.
141
- */
142
- export const embeddedDatabaseFinding = (fact: EmbeddedDatabase): Finding | undefined =>
143
- fact.selected && !fact.resolved
144
- ? finding(
145
- 'X_DB_UNAVAILABLE',
146
- `${PGLITE_MISSING} — and DATABASE_URL is unset or blank, so the embedded one is the database this app would open`,
147
- PGLITE_FIX,
148
- )
149
- : undefined;
150
-
151
36
  /** The file `x doctor` reports missing, and the one the reader creates. */
152
37
  export const ENV_DEVELOPMENT = '.env.development';
153
38
 
154
- /**
155
- * Both ports `x dev` binds, each labelled with the role that wants it. `x dev --port 3999` printed
156
- * `web listening on 3999`, then died on 4000 as `X_CLI_UNEXPECTED` with a caught `Error` rendered
157
- * into its cause — and `x doctor --port 3999` answered "no findings", because it probed the web
158
- * port and only the web port (#F5). The neighbouring port is not an implementation detail an
159
- * operator can ignore: `docker-compose.prod.yml` publishes `3001:3001` from it and `docker/helm`
160
- * derives `PORT = .port - 1` from it, so it is part of the contract `x dev` runs by.
161
- *
162
- * The suggested port moves BOTH: `x dev --port N` occupies N and N+1, so a free N beside a taken
163
- * N+1 is still not a runnable command. It did not move both until 2026-09 — the line was
164
- * `neighbouringPort(probe.port)`, which for the sync finding IS the port the finding is about, and
165
- * a docblock claiming otherwise is how it survived. `portPairAfter` is the one reader of that rule
166
- * and `role-sync.ts`'s own refusal shares it.
167
- *
168
- * The sync port is `syncPortFor`, never `neighbouringPort` again: that helper answers 65534 for a
169
- * web port of 65535 — BELOW the web port, and a port `x dev` never binds — where the boot refuses
170
- * the run outright with `X_PORT_INVALID`. A probe that reports on a socket the command would never
171
- * open is answering a question nobody asked, so the boot's own rule decides, and its refusal is
172
- * reported instead of a probe. Alone, and ahead of the web port: there is no runnable `x dev` at
173
- * this port whatever the other one answers, and a second finding about it is noise over the cause.
174
- */
175
- async function portFindings(probe: DoctorProbe): Promise<readonly Finding[]> {
176
- let syncPort: number;
177
- try {
178
- syncPort = syncPortFor(probe.port);
179
- } catch (error) {
180
- // The boot's own error, carried whole — `findingFrom` reads its code, cause and fix off the
181
- // value rather than rendering it, which is what `scripts/catch-render.ts` requires.
182
- return [findingFrom(error)];
183
- }
184
- const wanted = [
185
- { port: probe.port, role: 'web' },
186
- { port: syncPort, role: 'sync' },
187
- ] as const;
188
- const findings: Finding[] = [];
189
- for (const entry of wanted) {
190
- if (await probe.portFree(entry.port)) continue;
191
- findings.push(
192
- finding(
193
- 'X_PORT_IN_USE',
194
- `port ${entry.port} is already listening, and \`x dev --port ${probe.port}\` binds it for the ${entry.role} role`,
195
- `x dev --port ${quoteArg(String(portPairAfter(probe.port)))}`,
196
- ),
197
- );
198
- }
199
- return findings;
200
- }
201
-
202
39
  /**
203
40
  * Ordered cheapest-first so the first failure is usually the root cause: a wrong Bun explains
204
41
  * every other symptom, and running outside an app explains the rest.
@@ -297,147 +134,6 @@ export async function runDoctor(probe: DoctorProbe): Promise<readonly Finding[]>
297
134
  return findings;
298
135
  }
299
136
 
300
- /**
301
- * The port to TEST, and the one place `x doctor` reads it: `devPortFor`'s order — `--port`, then
302
- * `PORT` (`portFromEnv`, the one reader of it), then 3000 — so the probe answers about the port
303
- * `x dev` will bind. It probed 3000 under `PORT=4000` while dev bound 4000 and 4001. `PORT_RANGE.min`
304
- * is 0 because `x dev --port 0` means "let the kernel pick"; here 0 means nothing, and
305
- * `Bun.serve({ port: 0 })` always succeeds — so the port check could not fail.
306
- */
307
- export const doctorPort = (
308
- args: ParsedArgs,
309
- env: Readonly<Record<string, string | undefined>>,
310
- ): number =>
311
- readIntFlag(args, {
312
- name: 'port',
313
- command: 'doctor',
314
- ...PORT_RANGE,
315
- min: 1,
316
- example: 'x doctor --port 3000',
317
- }) ?? portFromEnv(env);
318
-
319
- /**
320
- * `DATABASE_URL` as BOTH halves of the database question read it: unset and blank are one case.
321
- * One seam, because the two halves are complementary — a second reading of the same variable is
322
- * how a configuration ends up reported by neither probe, or by both.
323
- */
324
- const externalUrl = (raw: string | undefined): string | undefined =>
325
- raw === undefined || raw.trim() === '' ? undefined : raw;
326
-
327
- /**
328
- * Is the optional peer INSTALLED for this app — a `node_modules` walk up from the app root.
329
- *
330
- * Never an IMPORT: loading PGlite boots 26 MB of WASM and takes the single-writer lock the next
331
- * command needs, and a diagnostic must not be the reason `x dev` cannot open the database it just
332
- * reported on.
333
- *
334
- * Never `Bun.resolveSync` either, which was this check's first draft. It falls back to Bun's
335
- * machine-global install cache: measured 2026-09-11 against a freshly scaffolded app with no
336
- * `node_modules` anywhere above it, `Bun.resolveSync('@electric-sql/pglite', <app>)` answered
337
- * `~/.bun/install/cache/@electric-sql/pglite@0.5.8@@@1/dist/index.js` — a version the app does not
338
- * depend on, in a directory `bun install` never wrote for it. A box that had downloaded the package
339
- * ONCE, for anything, would have read as ready on every app after it, which is the exact opposite
340
- * of the question. The walk asks what `bun add` answers, and nothing else.
341
- *
342
- * Up from the root and not at it, because an app checked out inside a larger workspace is installed
343
- * by the hoisting one: `examples/dummy` in this repository has no `node_modules` of its own.
344
- */
345
- const installedAbove = (dir: string, specifier: string): boolean => {
346
- let current = resolve(dir);
347
- // Bounded by the path itself — one segment per step — rather than by `for (;;)` and the promise
348
- // that `dirname('/')` is `/`. The loop still stops on that, one step earlier.
349
- for (let remaining = current.split(sep).length; remaining > 0; remaining -= 1) {
350
- if (existsSync(join(current, 'node_modules', specifier, 'package.json'))) return true;
351
- const parent = dirname(current);
352
- if (parent === current) return false;
353
- current = parent;
354
- }
355
- return false;
356
- };
357
-
358
- /**
359
- * A real `select 1` through the app's own driver, not a TCP connect: a running Postgres with the
360
- * wrong credentials or a database that does not exist accepts the socket and refuses the session,
361
- * which is the case an operator most needs told about before a deploy.
362
- *
363
- * The pool is CLOSED on every path — this command exits, and a held pool is a connection slot the
364
- * next `x db migrate` cannot have.
365
- */
366
- async function probeDatabase(
367
- url: string | undefined,
368
- env: Readonly<Record<string, string | undefined>>,
369
- ): Promise<Finding | null> {
370
- if (externalUrl(url) === undefined) return null;
371
- let client: ReturnType<typeof postgresClient>;
372
- try {
373
- client = postgresClient({ url, env, applicationName: 'x-doctor' });
374
- } catch (error) {
375
- return findingFrom(error);
376
- }
377
- try {
378
- const report = await checkDb(client);
379
- if (report.ok) return null;
380
- // `DbHealthReport.error` is `checkDb`'s own rendering of what refused, never this file's — the
381
- // caught value is `checkDb`'s to read, and it is the one function that already reads it safely.
382
- return finding(
383
- 'X_DB_UNAVAILABLE',
384
- `DATABASE_URL does not answer \`select 1\`: ${report.error ?? 'no reason reported'}`,
385
- // `dbUnavailable`'s own two branches, verbatim: a second wording for one condition is two
386
- // answers to "what do I do", and this one is reached first, before any command opens a pool.
387
- 'set DATABASE_URL to a reachable Postgres url, or run `x dev` to use the embedded PGlite',
388
- );
389
- } finally {
390
- await client.close();
391
- }
392
- }
393
-
394
- export function probeFor(
395
- cwd: string,
396
- bunVersion: string,
397
- port: number,
398
- // The environment `doctorPort` read `PORT` from, so `APP_URL` is judged against the same one.
399
- env: Readonly<Record<string, string | undefined>> = process.env,
400
- ): DoctorProbe {
401
- const root = findAppRoot(cwd)?.dir;
402
- return {
403
- bunVersion,
404
- root,
405
- port,
406
- appUrl: env['APP_URL'],
407
- frameworkFindings: machineSecretFindings(env),
408
- exists: (relativePath) => (root === undefined ? false : existsSync(join(root, relativePath))),
409
- portFree,
410
- database: () => probeDatabase(process.env['DATABASE_URL'], env),
411
- // `root ?? cwd` because the walk needs a directory that exists; outside an app `runDoctor`
412
- // returns on `X_NOT_IN_APP` before this is ever asked, so the value only has to be honest.
413
- embeddedDatabase: async () => ({
414
- selected: externalUrl(process.env['DATABASE_URL']) === undefined,
415
- resolved: installedAbove(root ?? cwd, PGLITE_PACKAGE),
416
- }),
417
- drift: async () => (root === undefined ? [] : checkMigrationDrift(root)),
418
- // The import half too: `X_CLI_UNEXPECTED` used to send a reader here and find this silent.
419
- snapshots: async () =>
420
- root === undefined
421
- ? []
422
- : [...(await unresolvedImportFindings(root)), ...(await checkMigrationSnapshots(root))],
423
- // `routes: undefined` outside an app is "not judged", which is what the caller already is:
424
- // `runDoctor` returns on `X_NOT_IN_APP` before this can be asked.
425
- offlineFallback: async () =>
426
- root === undefined ? { fallback: null, routes: undefined } : offlineFallbackProbe(root),
427
- sealedKeys: async () =>
428
- root === undefined ? { columns: undefined, keys: undefined } : sealedKeysProbe(root),
429
- authStorage: () => authStorageProbe(process.env['DATABASE_URL'], env),
430
- pooler: () => poolerProbe(process.env['DATABASE_URL'], env),
431
- typescript: async () => (root === undefined ? [] : typescriptProbe(root)),
432
- rowSecurity: async () =>
433
- root === undefined ? [] : rowSecurityProbe(root, process.env['DATABASE_URL'], env),
434
- };
435
- }
436
-
437
- /** What a load reports, narrowed to the one failure a doctor can name a repair for. */
438
- const unresolvedImportFindings = async (root: string): Promise<readonly Finding[]> =>
439
- (await loadApp(root)).findings.filter((finding) => finding.code === IMPORT_UNRESOLVED);
440
-
441
137
  export const doctorCommand: CliCommand = {
442
138
  spec: doctorSpec,
443
139
  async run(ctx: CommandContext): Promise<CommandResult> {
@@ -0,0 +1,121 @@
1
+ // `x doctor`'s database checks: the external Postgres answers `select 1`, and the embedded PGlite
2
+ // the app would open where there is none is installed. Facts read here, decided by pure rules.
3
+
4
+ // why: Bun has no synchronous file-exists or path-walking API; the peer is found on disk, never loaded.
5
+ import { existsSync } from 'node:fs';
6
+ import { dirname, join, resolve, sep } from 'node:path';
7
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
8
+ import { checkDb, PGLITE_FIX, PGLITE_MISSING, postgresClient } from '@ultimat3/db';
9
+ import type { Finding } from './output';
10
+ import { findingFrom } from './output';
11
+
12
+ /** What `x doctor` reads about the embedded database, without opening it. */
13
+ export interface EmbeddedDatabase {
14
+ /**
15
+ * True while `DATABASE_URL` is unset or blank — the condition that makes PGlite the app's
16
+ * database (`resolveServices`), and the same reading `probeDatabase` returns `null` on.
17
+ */
18
+ readonly selected: boolean;
19
+ /** Does `@electric-sql/pglite` resolve from the app root? */
20
+ readonly resolved: boolean;
21
+ }
22
+
23
+ const finding = (code: string, cause: string, fix: string): Finding => ({
24
+ code,
25
+ cause,
26
+ fix,
27
+ docs: ERROR_DOCS_URL,
28
+ });
29
+
30
+ /**
31
+ * The rule, pure. Red only where the embedded database is the one that would be opened: an app
32
+ * pointed at a real Postgres never loads PGlite, and a finding about an absent optional peer there
33
+ * is noise the reader learns to skim.
34
+ *
35
+ * `@ultimat3/db`'s own refusal, not a CLI twin of it — same `X_DB_UNAVAILABLE`, same sentence,
36
+ * same runnable fix. The package already says this the moment a query arrives; `x doctor` is what
37
+ * says it before `bin/setup` gets that far.
38
+ */
39
+ export const embeddedDatabaseFinding = (fact: EmbeddedDatabase): Finding | undefined =>
40
+ fact.selected && !fact.resolved
41
+ ? finding(
42
+ 'X_DB_UNAVAILABLE',
43
+ `${PGLITE_MISSING} — and DATABASE_URL is unset or blank, so the embedded one is the database this app would open`,
44
+ PGLITE_FIX,
45
+ )
46
+ : undefined;
47
+
48
+ /**
49
+ * `DATABASE_URL` as BOTH halves of the database question read it: unset and blank are one case.
50
+ * One seam, because the two halves are complementary — a second reading of the same variable is
51
+ * how a configuration ends up reported by neither probe, or by both.
52
+ */
53
+ export const externalUrl = (raw: string | undefined): string | undefined =>
54
+ raw === undefined || raw.trim() === '' ? undefined : raw;
55
+
56
+ /**
57
+ * Is the optional peer INSTALLED for this app — a `node_modules` walk up from the app root.
58
+ *
59
+ * Never an IMPORT: loading PGlite boots 26 MB of WASM and takes the single-writer lock the next
60
+ * command needs, and a diagnostic must not be the reason `x dev` cannot open the database it just
61
+ * reported on.
62
+ *
63
+ * Never `Bun.resolveSync` either, which was this check's first draft. It falls back to Bun's
64
+ * machine-global install cache: measured 2026-09-11 against a freshly scaffolded app with no
65
+ * `node_modules` anywhere above it, `Bun.resolveSync('@electric-sql/pglite', <app>)` answered
66
+ * `~/.bun/install/cache/@electric-sql/pglite@0.5.8@@@1/dist/index.js` — a version the app does not
67
+ * depend on, in a directory `bun install` never wrote for it. A box that had downloaded the package
68
+ * ONCE, for anything, would have read as ready on every app after it, which is the exact opposite
69
+ * of the question. The walk asks what `bun add` answers, and nothing else.
70
+ *
71
+ * Up from the root and not at it, because an app checked out inside a larger workspace is installed
72
+ * by the hoisting one: `examples/dummy` in this repository has no `node_modules` of its own.
73
+ */
74
+ export const installedAbove = (dir: string, specifier: string): boolean => {
75
+ let current = resolve(dir);
76
+ // Bounded by the path itself — one segment per step — rather than by `for (;;)` and the promise
77
+ // that `dirname('/')` is `/`. The loop still stops on that, one step earlier.
78
+ for (let remaining = current.split(sep).length; remaining > 0; remaining -= 1) {
79
+ if (existsSync(join(current, 'node_modules', specifier, 'package.json'))) return true;
80
+ const parent = dirname(current);
81
+ if (parent === current) return false;
82
+ current = parent;
83
+ }
84
+ return false;
85
+ };
86
+
87
+ /**
88
+ * A real `select 1` through the app's own driver, not a TCP connect: a running Postgres with the
89
+ * wrong credentials or a database that does not exist accepts the socket and refuses the session,
90
+ * which is the case an operator most needs told about before a deploy.
91
+ *
92
+ * The pool is CLOSED on every path — this command exits, and a held pool is a connection slot the
93
+ * next `x db migrate` cannot have.
94
+ */
95
+ export async function probeDatabase(
96
+ url: string | undefined,
97
+ env: Readonly<Record<string, string | undefined>>,
98
+ ): Promise<Finding | null> {
99
+ if (externalUrl(url) === undefined) return null;
100
+ let client: ReturnType<typeof postgresClient>;
101
+ try {
102
+ client = postgresClient({ url, env, applicationName: 'x-doctor' });
103
+ } catch (error) {
104
+ return findingFrom(error);
105
+ }
106
+ try {
107
+ const report = await checkDb(client);
108
+ if (report.ok) return null;
109
+ // `DbHealthReport.error` is `checkDb`'s own rendering of what refused, never this file's — the
110
+ // caught value is `checkDb`'s to read, and it is the one function that already reads it safely.
111
+ return finding(
112
+ 'X_DB_UNAVAILABLE',
113
+ `DATABASE_URL does not answer \`select 1\`: ${report.error ?? 'no reason reported'}`,
114
+ // `dbUnavailable`'s own two branches, verbatim: a second wording for one condition is two
115
+ // answers to "what do I do", and this one is reached first, before any command opens a pool.
116
+ 'set DATABASE_URL to a reachable Postgres url, or run `x dev` to use the embedded PGlite',
117
+ );
118
+ } finally {
119
+ await client.close();
120
+ }
121
+ }
@@ -0,0 +1,88 @@
1
+ // `x doctor`'s port checks: both ports `x dev` binds, probed by role, and the one reading of which
2
+ // port that is (`--port`, then `PORT`, then 3000).
3
+
4
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
5
+ import type { DoctorProbe } from './doctor-probe';
6
+ import { PORT_RANGE, portPairAfter, readIntFlag } from './flag-number';
7
+ import type { Finding } from './output';
8
+ import { findingFrom } from './output';
9
+ import type { ParsedArgs } from './parse';
10
+ import { syncPortFor } from './role-sync';
11
+ import { portFromEnv } from './serve-env';
12
+ import { quoteArg } from './shell-quote';
13
+
14
+ const finding = (code: string, cause: string, fix: string): Finding => ({
15
+ code,
16
+ cause,
17
+ fix,
18
+ docs: ERROR_DOCS_URL,
19
+ });
20
+
21
+ /**
22
+ * Both ports `x dev` binds, each labelled with the role that wants it. `x dev --port 3999` printed
23
+ * `web listening on 3999`, then died on 4000 as `X_CLI_UNEXPECTED` with a caught `Error` rendered
24
+ * into its cause — and `x doctor --port 3999` answered "no findings", because it probed the web
25
+ * port and only the web port (#F5). The neighbouring port is not an implementation detail an
26
+ * operator can ignore: `docker-compose.prod.yml` publishes `3001:3001` from it and `docker/helm`
27
+ * derives `PORT = .port - 1` from it, so it is part of the contract `x dev` runs by.
28
+ *
29
+ * The suggested port moves BOTH: `x dev --port N` occupies N and N+1, so a free N beside a taken
30
+ * N+1 is still not a runnable command. It did not move both until 2026-09 — the line was
31
+ * `neighbouringPort(probe.port)`, which for the sync finding IS the port the finding is about, and
32
+ * a docblock claiming otherwise is how it survived. `portPairAfter` is the one reader of that rule
33
+ * and `role-sync.ts`'s own refusal shares it.
34
+ *
35
+ * The sync port is `syncPortFor`, never `neighbouringPort` again: that helper answers 65534 for a
36
+ * web port of 65535 — BELOW the web port, and a port `x dev` never binds — where the boot refuses
37
+ * the run outright with `X_PORT_INVALID`. A probe that reports on a socket the command would never
38
+ * open is answering a question nobody asked, so the boot's own rule decides, and its refusal is
39
+ * reported instead of a probe. Alone, and ahead of the web port: there is no runnable `x dev` at
40
+ * this port whatever the other one answers, and a second finding about it is noise over the cause.
41
+ */
42
+ export async function portFindings(
43
+ probe: Pick<DoctorProbe, 'port' | 'portFree'>,
44
+ ): Promise<readonly Finding[]> {
45
+ let syncPort: number;
46
+ try {
47
+ syncPort = syncPortFor(probe.port);
48
+ } catch (error) {
49
+ // The boot's own error, carried whole — `findingFrom` reads its code, cause and fix off the
50
+ // value rather than rendering it, which is what `scripts/catch-render.ts` requires.
51
+ return [findingFrom(error)];
52
+ }
53
+ const wanted = [
54
+ { port: probe.port, role: 'web' },
55
+ { port: syncPort, role: 'sync' },
56
+ ] as const;
57
+ const findings: Finding[] = [];
58
+ for (const entry of wanted) {
59
+ if (await probe.portFree(entry.port)) continue;
60
+ findings.push(
61
+ finding(
62
+ 'X_PORT_IN_USE',
63
+ `port ${entry.port} is already listening, and \`x dev --port ${probe.port}\` binds it for the ${entry.role} role`,
64
+ `x dev --port ${quoteArg(String(portPairAfter(probe.port)))}`,
65
+ ),
66
+ );
67
+ }
68
+ return findings;
69
+ }
70
+
71
+ /**
72
+ * The port to TEST, and the one place `x doctor` reads it: `devPortFor`'s order — `--port`, then
73
+ * `PORT` (`portFromEnv`, the one reader of it), then 3000 — so the probe answers about the port
74
+ * `x dev` will bind. It probed 3000 under `PORT=4000` while dev bound 4000 and 4001. `PORT_RANGE.min`
75
+ * is 0 because `x dev --port 0` means "let the kernel pick"; here 0 means nothing, and
76
+ * `Bun.serve({ port: 0 })` always succeeds — so the port check could not fail.
77
+ */
78
+ export const doctorPort = (
79
+ args: ParsedArgs,
80
+ env: Readonly<Record<string, string | undefined>>,
81
+ ): number =>
82
+ readIntFlag(args, {
83
+ name: 'port',
84
+ command: 'doctor',
85
+ ...PORT_RANGE,
86
+ min: 1,
87
+ example: 'x doctor --port 3000',
88
+ }) ?? portFromEnv(env);