@ultimat3/cli 31.14.0 → 31.16.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 (69) hide show
  1. package/CLAUDE.md +1 -1
  2. package/README.md +3 -2
  3. package/package.json +29 -29
  4. package/src/budgets-requests.ts +37 -0
  5. package/src/budgets.ts +20 -1
  6. package/src/cmd-doctor.ts +47 -37
  7. package/src/cmd-exercise.ts +14 -1
  8. package/src/cmd-upgrade.ts +19 -2
  9. package/src/coverage-floor.ts +2 -2
  10. package/src/dev-boot.ts +2 -2
  11. package/src/dev-route-table.ts +5 -9
  12. package/src/doctor-env-reserved.ts +111 -0
  13. package/src/doctor-floor.ts +62 -0
  14. package/src/doctor-pins.ts +101 -0
  15. package/src/doctor-probe.ts +21 -1
  16. package/src/doctor-row-security.ts +119 -4
  17. package/src/doctor-warnings.ts +55 -0
  18. package/src/document-options.ts +0 -7
  19. package/src/error-codes-doctor.ts +24 -0
  20. package/src/error-codes.ts +5 -0
  21. package/src/exercise-floor-report.ts +138 -0
  22. package/src/exercise-floor-verdict.ts +98 -0
  23. package/src/exercise-floor.ts +158 -0
  24. package/src/island-bundle.ts +52 -12
  25. package/src/island-disposer.ts +1 -1
  26. package/src/island-group-cache.ts +4 -0
  27. package/src/island-link-check.ts +73 -0
  28. package/src/island-vendor.ts +183 -0
  29. package/src/mcp-errors.ts +11 -1
  30. package/src/messages-upgrade.ts +13 -0
  31. package/src/messages.ts +3 -0
  32. package/src/prerender.ts +7 -7
  33. package/src/route-islands-preload.ts +54 -11
  34. package/src/runtime-admin.ts +2 -4
  35. package/src/runtime-render-document.ts +34 -13
  36. package/src/runtime-render.ts +58 -30
  37. package/src/serve-web.ts +8 -11
  38. package/src/static-images.ts +25 -4
  39. package/src/static-precompress.ts +57 -0
  40. package/src/style-bundle.ts +28 -6
  41. package/src/templates/guard-island-mount-clears.ts +151 -0
  42. package/src/templates/island.ts +8 -7
  43. package/src/templates/resource-form-island.ts +12 -9
  44. package/src/templates/scaffold-docs.ts +1 -0
  45. package/src/templates/scaffold-guards.ts +4 -1
  46. package/src/templates/scaffold-shell.ts +12 -9
  47. package/src/templates/scaffold-verify-floor.ts +4 -0
  48. package/src/test-dotenv.ts +15 -2
  49. package/src/theme-brand.ts +18 -20
  50. package/src/upgrade-coverage.ts +109 -0
  51. package/src/upgrade-document.ts +18 -0
  52. package/src/upgrade-exercise-floor.ts +53 -0
  53. package/src/upgrade-gate.ts +68 -25
  54. package/src/upgrade-guards.ts +159 -0
  55. package/src/upgrade-report.ts +29 -1
  56. package/src/verify-checks.ts +3 -1
  57. package/src/verify-floor.ts +13 -0
  58. package/wiki/CLI-Reference.md +26 -3
  59. package/wiki/Client-Data.md +52 -0
  60. package/wiki/Configuration.md +17 -0
  61. package/wiki/MCP-And-AI.md +42 -1
  62. package/wiki/Notify.md +6 -0
  63. package/wiki/PWA-And-Offline.md +11 -0
  64. package/wiki/Realtime.md +4 -3
  65. package/wiki/SEO.md +1 -1
  66. package/wiki/Static-Assets.md +30 -3
  67. package/wiki/Testing.md +64 -2
  68. package/wiki/Theming.md +6 -6
  69. package/wiki/Upgrading.md +11 -0
@@ -0,0 +1,101 @@
1
+ // `x doctor`'s pin check: an `@ultimat3/*` dependency written as a range (`^31.0.0`, `latest`) in
2
+ // any of the app's manifests. The framework moves in lockstep and `x new` pins exactly; a range is a
3
+ // silent upgrade on the next install, and two of them drift into the mixed set `x upgrade` refuses.
4
+
5
+ // why: Bun exposes no path-join primitive; Bun.file takes one already joined.
6
+ import { join } from 'node:path';
7
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
8
+ import { t } from '@ultimat3/schema';
9
+ import type { Finding } from './output';
10
+ import { readManifests, readPins } from './upgrade-pins';
11
+ import { pinVersion, type UpgradePin } from './upgrade-plan';
12
+
13
+ export const PIN_RANGE = 'X_FRAMEWORK_PIN_RANGE';
14
+
15
+ /** What an installed package's manifest must say to name the version `bun install` resolved. */
16
+ const INSTALLED = t.object({ version: t.string });
17
+
18
+ /** An exact release, or a prerelease of one: what `x new` and `x upgrade` write. */
19
+ const EXACT = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
20
+
21
+ /** `workspace:*`, `file:` and `link:` name a directory, never a version: nothing to move. */
22
+ const LOCAL = /^(?:workspace|file|link):/;
23
+
24
+ /** `npm:@ultimat3/core@^31.0.0` → its alias prefix and the spec it pins, the part after the last @. */
25
+ const aliasOf = (spec: string): { readonly prefix: string; readonly version: string } => {
26
+ const trimmed = spec.trim();
27
+ if (!trimmed.startsWith('npm:')) return { prefix: '', version: trimmed };
28
+ const at = trimmed.lastIndexOf('@');
29
+ return at <= 'npm:'.length
30
+ ? { prefix: trimmed, version: '' }
31
+ : { prefix: trimmed.slice(0, at + 1), version: trimmed.slice(at + 1) };
32
+ };
33
+
34
+ /**
35
+ * Everything but an exact version or a local link moves on the next install: `^`/`~`, `*`, `x`,
36
+ * a dist-tag (`latest`), a comparator pair (`>=31 <32`), a hyphen range — and an `npm:` alias is
37
+ * judged on the spec it carries.
38
+ */
39
+ const isRange = (spec: string): boolean =>
40
+ !LOCAL.test(spec.trim()) && !EXACT.test(aliasOf(spec).version);
41
+
42
+ /** The value the fix writes: the installed version, else the range's floor, alias kept. */
43
+ const exactFor = (pin: UpgradePin, installed: ReadonlyMap<string, string>): string => {
44
+ const { prefix, version } = aliasOf(pin.spec);
45
+ const exact = installed.get(pin.name) ?? pinVersion(version);
46
+ return exact === undefined
47
+ ? `<the exact version: npm view ${pin.name} version>`
48
+ : `${prefix}${exact}`;
49
+ };
50
+
51
+ export interface PinFact {
52
+ readonly pins: readonly UpgradePin[];
53
+ /** The version `bun install` resolved, per package name — what the exact pin should say. */
54
+ readonly installed: ReadonlyMap<string, string>;
55
+ /** The 1-based line of each pin, keyed `file` then `name`, where the probe read the text. */
56
+ readonly lines?: ReadonlyMap<string, ReadonlyMap<string, number>>;
57
+ }
58
+
59
+ /** The rule, pure: one finding per manifest, naming every ranged pin in it and its exact value. */
60
+ export function pinRangeFindings(fact: PinFact): readonly Finding[] {
61
+ const byFile = new Map<string, UpgradePin[]>();
62
+ for (const pin of fact.pins.filter((one) => isRange(one.spec))) {
63
+ byFile.set(pin.file, [...(byFile.get(pin.file) ?? []), pin]);
64
+ }
65
+ return [...byFile].map(([file, pins]) => {
66
+ const exact = pins.map((pin) => `"${pin.name}": "${exactFor(pin, fact.installed)}"`);
67
+ const line = fact.lines?.get(file)?.get(pins[0]?.name ?? '') ?? 1;
68
+ return {
69
+ code: PIN_RANGE,
70
+ cause: `${file} pins ${pins.map((pin) => `${pin.name} ${pin.spec}`).join(', ')} as a range; the framework releases in lockstep, so the next install may move one package without the rest`,
71
+ fix: `edit ${file}:${line} — write ${exact.join(', ')}; then: bun install && x doctor --json`,
72
+ docs: ERROR_DOCS_URL,
73
+ at: file,
74
+ };
75
+ });
76
+ }
77
+
78
+ /** The I/O half. A manifest that will not parse is `x upgrade`'s refusal; here it is nothing. */
79
+ export async function pinProbe(root: string): Promise<PinFact> {
80
+ const manifests = await readManifests(root).catch(() => []);
81
+ const pins = readPins(manifests);
82
+ const lines = new Map<string, Map<string, number>>();
83
+ for (const { file, text } of manifests) {
84
+ const byName = new Map<string, number>();
85
+ text.split('\n').forEach((row, index) => {
86
+ const name = /"(@ultimat3\/[a-z0-9-]+)"\s*:/.exec(row)?.[1];
87
+ if (name !== undefined && !byName.has(name)) byName.set(name, index + 1);
88
+ });
89
+ lines.set(file, byName);
90
+ }
91
+ const installed = new Map<string, string>();
92
+ for (const name of new Set(pins.map((pin) => pin.name))) {
93
+ const manifest: unknown = await Bun.file(join(root, 'node_modules', name, 'package.json'))
94
+ .json()
95
+ .catch(() => undefined);
96
+ const parsed = INSTALLED.safeParse(manifest);
97
+ if (parsed.issues === undefined)
98
+ installed.set(name, (parsed.value as { version: string }).version);
99
+ }
100
+ return { pins, installed, lines };
101
+ }
@@ -12,11 +12,17 @@ import { checkMigrationSnapshots } from './db-snapshot';
12
12
  import { type AuthStorageFact, authStorageProbe } from './doctor-auth';
13
13
  import type { EmbeddedDatabase } from './doctor-database';
14
14
  import { externalUrl, installedAbove, probeDatabase } from './doctor-database';
15
+ import type { AppEnvNamesFact } from './doctor-env-reserved';
16
+ import { appEnvNamesProbe, NO_APP_ENV_NAMES } from './doctor-env-reserved';
17
+ import { unflooredStepsProbe } from './doctor-floor';
15
18
  import type { OfflineFallbackFact } from './doctor-offline';
16
19
  import { offlineFallbackProbe } from './doctor-offline';
20
+ import type { PinFact } from './doctor-pins';
21
+ import { pinProbe } from './doctor-pins';
17
22
  import type { PoolerFact } from './doctor-pooler';
18
23
  import { poolerProbe } from './doctor-pooler';
19
- import { rowSecurityProbe } from './doctor-row-security';
24
+ import type { RowSecurityOffFact } from './doctor-row-security';
25
+ import { rowSecurityOffProbe, rowSecurityProbe } from './doctor-row-security';
20
26
  import type { SealedKeysFact } from './doctor-sealed';
21
27
  import { sealedKeysProbe } from './doctor-sealed';
22
28
  import { typescriptProbe } from './doctor-typescript';
@@ -25,6 +31,7 @@ import type { Finding } from './output';
25
31
  import { portFree } from './port-probe';
26
32
  import { checkMigrationDrift } from './schema-drift';
27
33
  import type { TypescriptLag } from './typescript-floor';
34
+ import type { VerifyStepName } from './verify-step';
28
35
 
29
36
  /**
30
37
  * The injection seam `runDoctor` reads instead of the environment. Not a semver surface —
@@ -98,6 +105,14 @@ export interface DoctorProbe {
98
105
  typescript(): Promise<readonly TypescriptLag[]>;
99
106
  /** With `database.rowSecurity` on, whether the serving role is exempt (`doctor-row-security.ts`). */
100
107
  rowSecurity?(): Promise<readonly Finding[]>;
108
+ /** With it off, the raw `sql` statements that name a tenant table (`doctor-row-security.ts`). */
109
+ rowSecurityOff(): Promise<RowSecurityOffFact>;
110
+ /** The app's own env names, declared and sealed (`doctor-env-reserved.ts`). */
111
+ envNames(): Promise<AppEnvNamesFact>;
112
+ /** Every `@ultimat3/*` pin and the version installed for it (`doctor-pins.ts`). */
113
+ pins(): Promise<PinFact>;
114
+ /** The gate steps that apply here and `x.verify.json` does not floor (`doctor-floor.ts`). */
115
+ unflooredSteps(): Promise<readonly VerifyStepName[]>;
101
116
  }
102
117
 
103
118
  export function probeFor(
@@ -140,6 +155,11 @@ export function probeFor(
140
155
  typescript: async () => (root === undefined ? [] : typescriptProbe(root)),
141
156
  rowSecurity: async () =>
142
157
  root === undefined ? [] : rowSecurityProbe(root, process.env['DATABASE_URL'], env),
158
+ rowSecurityOff: async () =>
159
+ root === undefined ? { declared: false, touches: [] } : rowSecurityOffProbe(root),
160
+ envNames: async () => (root === undefined ? NO_APP_ENV_NAMES : appEnvNamesProbe(root, env)),
161
+ pins: async () => (root === undefined ? { pins: [], installed: new Map() } : pinProbe(root)),
162
+ unflooredSteps: async () => (root === undefined ? [] : unflooredStepsProbe(root)),
143
163
  };
144
164
  }
145
165
 
@@ -1,14 +1,28 @@
1
- // Single responsibility: `x doctor`'s row-security question, asked without booting — with
2
- // `database.rowSecurity` on, is the role `DATABASE_URL` connects as one Postgres applies policies
3
- // to. The boot refuses the same role (`X_DB_ROW_SECURITY_BYPASSED`); this says so before a deploy.
1
+ // Single responsibility: `x doctor`'s row-security questions, asked without booting — with
2
+ // `database.rowSecurity` on, is the serving role one Postgres applies policies to (the boot's own
3
+ // `X_DB_ROW_SECURITY_BYPASSED`); with it off, does raw `sql` reach a tenant table the policy would guard.
4
4
 
5
- import { resolveRole } from '@ultimat3/core';
5
+ // why: Bun exposes no path-join primitive; Bun.file takes one already joined.
6
+ import { join } from 'node:path';
7
+ import {
8
+ APP_CONFIG_FILE,
9
+ ERROR_DOCS_URL,
10
+ endOfLiteral,
11
+ maskLiterals,
12
+ resolveRole,
13
+ stripComments,
14
+ } from '@ultimat3/core';
6
15
  import { assertRowSecurityBinds, DbError, postgresClient } from '@ultimat3/db';
16
+ import { describeTenancy } from '@ultimat3/entity';
17
+ import { statementTables } from '@ultimat3/testing';
7
18
  import { loadAppConfig } from './app-config-load';
19
+ import { loadApp } from './app-load';
8
20
  import type { Finding } from './output';
9
21
  import { findingFrom } from './output';
10
22
  import { rowSecurityDeclared } from './row-security-boot';
11
23
 
24
+ import { eachSourceFile } from './source-files';
25
+
12
26
  /**
13
27
  * External databases only: an embedded one serves as `x_app` by construction (`serveAsAppRole`).
14
28
  * An unreachable server is `database()`'s finding to make, so only the exemption is reported here.
@@ -38,3 +52,104 @@ export async function rowSecurityProbe(
38
52
  await client.close();
39
53
  }
40
54
  }
55
+
56
+ export const ROW_SECURITY_OFF = 'X_DB_ROW_SECURITY_OFF';
57
+
58
+ /** One raw `sql\`…\`` statement in the app's source naming a tenant table. */
59
+ export interface RawTenantSql {
60
+ readonly at: string;
61
+ readonly table: string;
62
+ }
63
+
64
+ /** The other question: with `database.rowSecurity` OFF, does raw SQL reach a tenant table? */
65
+ export interface RowSecurityOffFact {
66
+ readonly declared: boolean;
67
+ readonly touches: readonly RawTenantSql[];
68
+ }
69
+
70
+ /**
71
+ * The repository scopes every entity read by its tenant column; a raw `sql\`…\`` statement is
72
+ * outside that scope, and only the database's own policy (`database.rowSecurity`) holds there. Off
73
+ * with no raw tenant SQL is a decision with nothing riding on it, and is not reported.
74
+ */
75
+ export function rowSecurityOffFindings(fact: RowSecurityOffFact): readonly Finding[] {
76
+ if (fact.declared || fact.touches.length === 0) return [];
77
+ const tables = [...new Set(fact.touches.map((touch) => touch.table))].sort();
78
+ const sites = fact.touches.slice(0, 5).map((touch) => `${touch.at} (${touch.table})`);
79
+ return [
80
+ {
81
+ code: ROW_SECURITY_OFF,
82
+ cause: `database.rowSecurity is off and ${fact.touches.length} raw sql statement(s) name tenant table(s) ${tables.join(', ')} — ${sites.join(', ')}: the repository's tenant scope does not reach a raw statement, so one missing tenant predicate reads every tenant's rows`,
83
+ fix: `database: { rowSecurity: true } # in defineConfig, ${APP_CONFIG_FILE}; then: x db gen "row security" --json && x db migrate --json && x doctor --json`,
84
+ docs: ERROR_DOCS_URL,
85
+ at: APP_CONFIG_FILE,
86
+ },
87
+ ];
88
+ }
89
+
90
+ /**
91
+ * A tagged `sql` template — `@ultimat3/db`'s, Bun's own `Bun.sql`, or a handle's `tx.sql` — found
92
+ * in the masked text so a quoted or commented one is not one; `mysql\`` is a longer name, not it.
93
+ */
94
+ const SQL_TAG = /(?<![\w$])sql\s*`/g;
95
+ /** `raw('…')` (a statement) and `identifier('…')` (a table name): SQL built outside a template. */
96
+ const SQL_CALL = /(?<![\w$.])(raw|identifier)\s*\(\s*/g;
97
+
98
+ /** The rule's scan, pure: each raw `sql` template or call in `source` naming one of `tables`. */
99
+ export function rawTenantSql(
100
+ path: string,
101
+ source: string,
102
+ tables: ReadonlySet<string>,
103
+ ): readonly RawTenantSql[] {
104
+ if (tables.size === 0 || !/sql|raw|identifier/.test(source)) return [];
105
+ const masked = maskLiterals(source);
106
+ const text = stripComments(source);
107
+ const found: RawTenantSql[] = [];
108
+ const report = (index: number, named: readonly string[]) => {
109
+ const line = text.slice(0, index).split('\n').length;
110
+ for (const table of new Set(named)) {
111
+ if (tables.has(table)) found.push({ at: `${path}:${line}`, table });
112
+ }
113
+ };
114
+ // `scope` is masked text or a template's own body, `offset` where it starts in `text`.
115
+ const calls = (scope: string, offset: number) => {
116
+ for (const call of scope.matchAll(SQL_CALL)) {
117
+ const open = offset + call.index + call[0].length;
118
+ const quote = text[open];
119
+ if (quote !== "'" && quote !== '"' && quote !== '`') continue;
120
+ const literal = text.slice(open + 1, endOfLiteral(text, open) - 1);
121
+ const named = call[1] === 'raw' ? statementTables(literal) : [literal.toLowerCase()];
122
+ report(offset + call.index, named);
123
+ }
124
+ };
125
+ for (const tag of masked.matchAll(SQL_TAG)) {
126
+ const open = tag.index + tag[0].length - 1;
127
+ const body = text.slice(open + 1, endOfLiteral(text, open) - 1);
128
+ report(tag.index, statementTables(body));
129
+ // Masking blanks a template's `${…}` too: `${identifier('posts')}` is read off the body.
130
+ calls(body, open + 1);
131
+ }
132
+ calls(masked, 0);
133
+ return found;
134
+ }
135
+
136
+ /** Migrations and seeds are SQL by design; tests are fixtures. */
137
+ const NOT_JUDGED = /(?:^|\/)(?:migrations|seeds?)\/|\.test\.tsx?$|\.d\.ts$/;
138
+
139
+ /**
140
+ * The I/O half: the flag, and the app's raw tenant SQL. An app that will not load declares no
141
+ * tenant table here — `snapshots()` already reports why it will not load.
142
+ */
143
+ export async function rowSecurityOffProbe(root: string): Promise<RowSecurityOffFact> {
144
+ const declared = rowSecurityDeclared(await loadAppConfig(root).catch(() => undefined));
145
+ if (declared) return { declared, touches: [] };
146
+ const loaded = await loadApp(root);
147
+ if (loaded.findings.length > 0) return { declared, touches: [] };
148
+ const tables = new Set(describeTenancy().map((tenant) => tenant.table.toLowerCase()));
149
+ const touches: RawTenantSql[] = [];
150
+ for await (const path of eachSourceFile(root)) {
151
+ if (NOT_JUDGED.test(path)) continue;
152
+ touches.push(...rawTenantSql(path, await Bun.file(join(root, path)).text(), tables));
153
+ }
154
+ return { declared, touches };
155
+ }
@@ -0,0 +1,55 @@
1
+ // `x doctor`'s warnings: the 31.16.0 checks on how an app is held, reported BESIDE the verdict and
2
+ // never in it. On `main` an app that upgrades with no change keeps a green doctor
3
+ // (`X_BREAKING_ON_MAIN`); on `next` these move into `runDoctor`'s findings and the verdict.
4
+
5
+ import { reservedEnvFindings } from './doctor-env-reserved';
6
+ import { unflooredStepFindings } from './doctor-floor';
7
+ import { pinRangeFindings } from './doctor-pins';
8
+ import type { DoctorProbe } from './doctor-probe';
9
+ import { rowSecurityOffFindings } from './doctor-row-security';
10
+ import { msg } from './messages';
11
+ import type { CommandResult, Finding, JsonValue } from './output';
12
+
13
+ /** The probes that only warn on `main`. Asked inside an app only; outside one there is no app. */
14
+ export async function doctorWarnings(probe: DoctorProbe): Promise<readonly Finding[]> {
15
+ if (probe.root === undefined) return [];
16
+ return [
17
+ // A ranged pin moves one package on the next install.
18
+ ...pinRangeFindings(await probe.pins()),
19
+ // An app's own name the framework reads too (`FRAMEWORK_ENV`).
20
+ ...reservedEnvFindings(await probe.envNames()),
21
+ // Static, so asked whatever the database answered: raw tenant SQL with the policy off.
22
+ ...rowSecurityOffFindings(await probe.rowSecurityOff()),
23
+ // A floor gap is the gate's blind spot, never a reason anything else is red.
24
+ ...unflooredStepFindings(await probe.unflooredSteps()),
25
+ ];
26
+ }
27
+
28
+ const asJson = (warning: Finding): JsonValue => ({
29
+ code: warning.code,
30
+ cause: warning.cause,
31
+ fix: warning.fix,
32
+ ...(warning.docs === undefined ? {} : { docs: warning.docs }),
33
+ ...(warning.at === undefined ? {} : { at: warning.at }),
34
+ });
35
+
36
+ /**
37
+ * The warnings, on a result `x doctor` already decided: `data.warnings[]` (`{ code, cause, fix,
38
+ * docs, at }`) for a machine, a line each for a person. `ok`, the summary and findings stay.
39
+ */
40
+ export function withDoctorWarnings(
41
+ result: CommandResult,
42
+ warnings: readonly Finding[],
43
+ ): CommandResult {
44
+ if (warnings.length === 0) return result;
45
+ const data = typeof result.data === 'object' && result.data !== null ? result.data : {};
46
+ return {
47
+ ...result,
48
+ data: { ...(data as Record<string, JsonValue>), warnings: warnings.map(asJson) },
49
+ lines: [
50
+ ...(result.lines ?? []),
51
+ msg('cli.doctor.warnings', { count: warnings.length }),
52
+ ...warnings.map(({ code, cause, fix }) => msg('cli.doctor.warning', { code, cause, fix })),
53
+ ],
54
+ };
55
+ }
@@ -50,13 +50,6 @@ export interface DocumentOptions {
50
50
  * decided by `app.config.ts`, which the boot read and the renderer cannot.
51
51
  */
52
52
  readonly themeHead?: string;
53
- /**
54
- * The app's brand `<style>` from `theme-brand.ts`, or absent for an app with no
55
- * `apps/web/shared/theme.ts`. Rendered AFTER the surface stylesheet `<link>`, never in the head
56
- * block `themeHead` rides: the brand answers `theme.scss` at equal specificity, so only a later
57
- * position in the cascade lets it win.
58
- */
59
- readonly brandHead?: string;
60
53
  /**
61
54
  * The page's sync target — `pageSync(…).head` — rendered as render's `clientSyncTags` on every
62
55
  * document this process serves. Principal-free, so a shareable document carries it too; absent
@@ -0,0 +1,24 @@
1
+ // The X_* codes of how an app is HELD — `x doctor`'s floor, pin, env-name and row-security checks
2
+ // and the `exercise` floor in `x.verify.json` — split out of `error-codes.ts` at its 500-line
3
+ // ceiling, as `error-codes-shot.ts` was. `error-codes.ts` folds these into the CLI's one owned union
4
+ // and registers them in its one call; nothing else imports this file.
5
+
6
+ /** Codes `x doctor` and the `exercise` floor declare and own. */
7
+ export const CLI_DOCTOR_ERROR_CODES = [
8
+ 'X_EXERCISE_UNPROVEN_ABOVE_FLOOR',
9
+ 'X_ENV_NAME_RESERVED',
10
+ 'X_FRAMEWORK_PIN_RANGE',
11
+ 'X_VERIFY_STEP_UNFLOORED',
12
+ 'X_DB_ROW_SECURITY_OFF',
13
+ ] as const;
14
+
15
+ export type CliDoctorErrorCode = (typeof CLI_DOCTOR_ERROR_CODES)[number];
16
+
17
+ export const CLI_DOCTOR_ERROR_TITLES: Readonly<Record<CliDoctorErrorCode, string>> = {
18
+ X_EXERCISE_UNPROVEN_ABOVE_FLOOR:
19
+ 'The exercise pass left more primitives unproven than x.verify.json allows',
20
+ X_ENV_NAME_RESERVED: 'An app variable is named on a name the framework reads',
21
+ X_FRAMEWORK_PIN_RANGE: 'An @ultimat3/* dependency is pinned as a range',
22
+ X_VERIFY_STEP_UNFLOORED: 'A gate step applies to this app but x.verify.json does not floor it',
23
+ X_DB_ROW_SECURITY_OFF: 'Raw sql reaches tenant tables while database.rowSecurity is off',
24
+ };
@@ -5,6 +5,8 @@
5
5
  import { registerErrorCodes } from '@ultimat3/core';
6
6
  import type { CliBoundaryErrorCode } from './error-codes-boundary';
7
7
  import { CLI_BOUNDARY_ERROR_CODES, CLI_BOUNDARY_ERROR_TITLES } from './error-codes-boundary';
8
+ import type { CliDoctorErrorCode } from './error-codes-doctor';
9
+ import { CLI_DOCTOR_ERROR_CODES, CLI_DOCTOR_ERROR_TITLES } from './error-codes-doctor';
8
10
  import type { CliPackageErrorCode } from './error-codes-package';
9
11
  import { CLI_PACKAGE_ERROR_CODES, CLI_PACKAGE_ERROR_TITLES } from './error-codes-package';
10
12
  import type { CliShotErrorCode } from './error-codes-shot';
@@ -276,6 +278,7 @@ export const CLI_BORROWED_ERROR_CODES = [
276
278
  export const CLI_ERROR_CODES = [
277
279
  ...CLI_OWNED_ERROR_CODES,
278
280
  ...CLI_BOUNDARY_ERROR_CODES,
281
+ ...CLI_DOCTOR_ERROR_CODES,
279
282
  ...CLI_PACKAGE_ERROR_CODES,
280
283
  ...CLI_SHOT_ERROR_CODES,
281
284
  ...CLI_TOOLING_ERROR_CODES,
@@ -287,6 +290,7 @@ type CliListedErrorCode = (typeof CLI_OWNED_ERROR_CODES)[number];
287
290
  export type CliOwnedErrorCode =
288
291
  | CliListedErrorCode
289
292
  | CliBoundaryErrorCode
293
+ | CliDoctorErrorCode
290
294
  | CliPackageErrorCode
291
295
  | CliShotErrorCode
292
296
  | CliToolingErrorCode;
@@ -475,6 +479,7 @@ registerErrorCodes(
475
479
  Object.entries({
476
480
  ...CLI_ERROR_TITLES,
477
481
  ...CLI_BOUNDARY_ERROR_TITLES,
482
+ ...CLI_DOCTOR_ERROR_TITLES,
478
483
  ...CLI_PACKAGE_ERROR_TITLES,
479
484
  ...CLI_SHOT_ERROR_TITLES,
480
485
  ...CLI_TOOLING_ERROR_TITLES,
@@ -0,0 +1,138 @@
1
+ // The `exercise` floor applied where the verdict is: the gate step reads the `.x/exercise.json` its
2
+ // child just wrote and judges it (`exercise-floor-verdict.ts`), and `x upgrade` reads the same file
3
+ // for the figures an upgraded app's ratchet starts at. A report the run did not rewrite is never
4
+ // judged — a child that died before writing would otherwise be judged by the last pass's numbers.
5
+
6
+ // why: Bun ships no path joiner.
7
+ import { join } from 'node:path';
8
+ import { t } from '@ultimat3/schema';
9
+ import { EXERCISE_REPORT_FILE } from './exercise-findings';
10
+ import type { ExerciseFloor } from './exercise-floor';
11
+ import { EXERCISE_FIELD, unprovenTally } from './exercise-floor';
12
+ import type { FloorRecord } from './exercise-floor-verdict';
13
+ import { exerciseFloorVerdict, FLOOR_CODES, measuredStatementsMax } from './exercise-floor-verdict';
14
+ import { readVerifyFloor } from './verify-floor';
15
+ import type { VerifyStep } from './verify-step';
16
+
17
+ const PROOF = t.optional(
18
+ t.object({
19
+ verdict: t.string,
20
+ reason: t.optional(t.string),
21
+ seed: t.optional(t.object({ entity: t.string, table: t.string, cause: t.string })),
22
+ }),
23
+ );
24
+ const CEILING = t.optional(
25
+ t.object({
26
+ verdict: t.string,
27
+ statements: t.number,
28
+ max: t.number,
29
+ why: t.optional(t.string),
30
+ declared: t.optional(t.boolean),
31
+ top: t.optional(t.array(t.object({ fingerprint: t.string, count: t.number }))),
32
+ }),
33
+ );
34
+ const REPORT = t.object({
35
+ records: t.array(
36
+ t.object({
37
+ kind: t.string,
38
+ name: t.string,
39
+ outcome: t.string,
40
+ tenant: PROOF,
41
+ crash: PROOF,
42
+ scale: PROOF,
43
+ statementCeiling: CEILING,
44
+ }),
45
+ ),
46
+ });
47
+
48
+ const reportFile = (root: string): Bun.BunFile => Bun.file(join(root, EXERCISE_REPORT_FILE));
49
+
50
+ /** The report's modification stamp, or `undefined` with no report: what "rewritten" is judged by. */
51
+ export const exerciseReportStamp = async (root: string): Promise<number | undefined> => {
52
+ const file = reportFile(root);
53
+ return (await file.exists()) ? file.lastModified : undefined;
54
+ };
55
+
56
+ /** The report's records, when the file exists and parses. */
57
+ export async function readExerciseRecords(
58
+ root: string,
59
+ ): Promise<readonly FloorRecord[] | undefined> {
60
+ const file = reportFile(root);
61
+ if (!(await file.exists())) return undefined;
62
+ const parsed = REPORT.safeParse(await file.json().catch(() => undefined));
63
+ // The schema checked every field the verdict reads; verdict strings are compared, never trusted.
64
+ return parsed.issues === undefined ? (parsed.value.records as readonly FloorRecord[]) : undefined;
65
+ }
66
+
67
+ /**
68
+ * `step` (the `exercise` gate step), then the floor's verdict on the report it wrote. The child
69
+ * judged the same report with the same function; its copies of the floor's codes are dropped so
70
+ * each is said once, and a child red only on them is green here when the verdict is.
71
+ */
72
+ export function withUnprovenFloor(step: VerifyStep): VerifyStep {
73
+ return {
74
+ ...step,
75
+ async run(ctx) {
76
+ // The file's own stamp before and after, never the clock: a test's frozen `Date.now` and the
77
+ // filesystem's real one are two clocks, and a report this run did not rewrite is not judged.
78
+ const before = await exerciseReportStamp(ctx.root);
79
+ const outcome = await step.run(ctx);
80
+ const after = await exerciseReportStamp(ctx.root);
81
+ if (after === undefined || after === before) return outcome;
82
+ const records = await readExerciseRecords(ctx.root);
83
+ if (records === undefined) return outcome;
84
+ const verdict = exerciseFloorVerdict(records, (await readVerifyFloor(ctx.root))?.exercise);
85
+ const own = outcome.findings.filter((finding) => !FLOOR_CODES.has(finding.code));
86
+ const onlyFloor = !outcome.ok && outcome.findings.length > 0 && own.length === 0;
87
+ const warnings = [...(outcome.warnings ?? []), ...verdict.warnings];
88
+ return {
89
+ ...outcome,
90
+ ok: (outcome.ok || onlyFloor) && verdict.findings.length === 0,
91
+ findings: [...own, ...verdict.findings],
92
+ ...(warnings.length === 0 ? {} : { warnings }),
93
+ };
94
+ },
95
+ };
96
+ }
97
+
98
+ /** The figures `x upgrade` writes as the app's ratchet: the last pass's, or `undefined` with none. */
99
+ export async function measuredExerciseFloor(
100
+ root: string,
101
+ ): Promise<Required<ExerciseFloor> | undefined> {
102
+ const records = await readExerciseRecords(root);
103
+ return records === undefined
104
+ ? undefined
105
+ : { unprovenMax: unprovenTally(records).figure, statementsMax: measuredStatementsMax(records) };
106
+ }
107
+
108
+ /**
109
+ * `x.verify.json`'s text with each `exercise` figure given, every other key untouched. A figure
110
+ * already at or under the one given is kept: the ratchet only falls. Text that is not a JSON
111
+ * object is returned as it was — the `manifest` step already reports that file's problems.
112
+ */
113
+ export function withExerciseFloor(text: string, figures: ExerciseFloor): string {
114
+ let payload: unknown;
115
+ try {
116
+ payload = JSON.parse(text);
117
+ } catch {
118
+ return text;
119
+ }
120
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return text;
121
+ const record = payload as Record<string, unknown>;
122
+ const current = record[EXERCISE_FIELD];
123
+ const section =
124
+ typeof current === 'object' && current !== null && !Array.isArray(current)
125
+ ? (current as Record<string, unknown>)
126
+ : {};
127
+ const next: Record<string, unknown> = { ...section };
128
+ let changed = false;
129
+ for (const [key, figure] of Object.entries(figures)) {
130
+ if (typeof figure !== 'number') continue;
131
+ const held = section[key];
132
+ if (typeof held === 'number' && held <= figure) continue;
133
+ next[key] = figure;
134
+ changed = true;
135
+ }
136
+ if (!changed) return text;
137
+ return `${JSON.stringify({ ...record, [EXERCISE_FIELD]: next }, null, 2)}\n`;
138
+ }
@@ -0,0 +1,98 @@
1
+ // The whole `exercise` floor verdict, one function for `x exercise` and the gate step alike: the
2
+ // unproven ratio (`exercise-floor.ts`), the sized-seed failures that explain it, and the statement
3
+ // ceiling. Each is red only where `x.verify.json`'s `exercise` key opted in; otherwise a warning,
4
+ // so an app that has not opted in stays green on `main` (X_BREAKING_ON_MAIN).
5
+
6
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
7
+ import type { ExerciseRecord } from '@ultimat3/testing';
8
+ import { STATEMENTS_MAX, scaleSeedFindings, statementCeilingFindings } from '@ultimat3/testing';
9
+ import type { ExerciseFloor } from './exercise-floor';
10
+ import { judgeUnproven } from './exercise-floor';
11
+ import type { Finding } from './output';
12
+
13
+ /** What the verdict reads of a record: who it is and its three proofs. */
14
+ export type FloorRecord = Pick<
15
+ ExerciseRecord,
16
+ 'kind' | 'name' | 'outcome' | 'tenant' | 'crash' | 'scale' | 'statementCeiling'
17
+ >;
18
+
19
+ /** The codes this verdict owns: the gate drops the child's copies and states its own. */
20
+ export const FLOOR_CODES: ReadonlySet<string> = new Set([
21
+ 'X_EXERCISE_UNPROVEN_ABOVE_FLOOR',
22
+ 'X_EXERCISE_SEED_FAILED',
23
+ 'X_STATEMENTS_OVER_BUDGET',
24
+ ]);
25
+
26
+ export interface FloorVerdict {
27
+ readonly findings: readonly Finding[];
28
+ readonly warnings: readonly string[];
29
+ }
30
+
31
+ /** A finding a floor did not opt into, as the one warning line a gate prints for it. */
32
+ const asWarning = (finding: Omit<Finding, 'docs'>): string =>
33
+ `${finding.code} ${finding.cause} — fix: ${finding.fix}`;
34
+
35
+ /**
36
+ * A within proof the entry declared: `declared`, or — in a report written before it carried that —
37
+ * a max other than the default. `statements: { max: 100, why }` is the default figure, declared.
38
+ */
39
+ const declaredWithin = (proof: { readonly max: number; readonly declared?: true }): boolean =>
40
+ proof.declared === true || proof.max !== STATEMENTS_MAX;
41
+
42
+ /**
43
+ * `statementsMax` replaces the default ceiling for every primitive whose entry declared none; an
44
+ * entry's own `statements: { max, why }` stands. The pass judged against `STATEMENTS_MAX`, so the
45
+ * floor re-judges from the counts it recorded.
46
+ */
47
+ const rejudged = (records: readonly FloorRecord[], max: number): readonly FloorRecord[] =>
48
+ records.map((record) => {
49
+ const proof = record.statementCeiling;
50
+ if (proof === undefined || (proof.verdict === 'over' && proof.why !== undefined)) return record;
51
+ if (proof.verdict === 'within' && declaredWithin(proof)) return record;
52
+ // The excluded `expectedQueryLoop` count rides along: the judged count alone reads as a typo.
53
+ const { statements } = proof;
54
+ const expected = proof.expected === undefined ? {} : { expected: proof.expected };
55
+ if (statements <= max) {
56
+ return { ...record, statementCeiling: { verdict: 'within', statements, max, ...expected } };
57
+ }
58
+ const top = proof.verdict === 'over' ? proof.top : [];
59
+ return {
60
+ ...record,
61
+ statementCeiling: { verdict: 'over', statements, max, ...expected, top },
62
+ };
63
+ });
64
+
65
+ /** The figure `x upgrade` writes: the busiest undeclared call, never under the default. */
66
+ export function measuredStatementsMax(records: readonly FloorRecord[]): number {
67
+ return records.reduce((top, record) => {
68
+ const proof = record.statementCeiling;
69
+ if (proof === undefined) return top;
70
+ const declared = proof.verdict === 'over' ? proof.why !== undefined : declaredWithin(proof);
71
+ return declared ? top : Math.max(top, proof.statements);
72
+ }, STATEMENTS_MAX);
73
+ }
74
+
75
+ export function exerciseFloorVerdict(
76
+ records: readonly FloorRecord[],
77
+ floor: ExerciseFloor | undefined,
78
+ ): FloorVerdict {
79
+ const unproven = judgeUnproven(records, floor);
80
+ const seeds = scaleSeedFindings(records);
81
+ // A seed failure is the reason behind an unproven ratio: red exactly when that ratio is.
82
+ const seedRed = unproven.findings.length > 0;
83
+ const max = floor?.statementsMax;
84
+ const statements = statementCeilingFindings(max === undefined ? records : rejudged(records, max));
85
+ const docs = (finding: Omit<Finding, 'docs'>): Finding => ({ ...finding, docs: ERROR_DOCS_URL });
86
+ return {
87
+ findings: [
88
+ ...unproven.findings,
89
+ ...(seedRed ? seeds.map(docs) : []),
90
+ ...(max === undefined ? [] : statements.map(docs)),
91
+ ],
92
+ warnings: [
93
+ ...unproven.warnings,
94
+ ...(seedRed ? [] : seeds.map(asWarning)),
95
+ ...(max === undefined ? statements.map(asWarning) : []),
96
+ ],
97
+ };
98
+ }