@ultimat3/cli 31.23.0 → 31.24.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.
@@ -3,7 +3,13 @@
3
3
  // binds, so before `/readyz` can say ready — and hand back the reader the asset routes miss into.
4
4
 
5
5
  import type { AppConfig, AssetsRetainConfig } from '@ultimat3/core';
6
- import { ConfigInvalidError, logger, renderFixLiteral, UltimateError } from '@ultimat3/core';
6
+ import {
7
+ bootWarning,
8
+ ConfigInvalidError,
9
+ logger,
10
+ renderFixLiteral,
11
+ UltimateError,
12
+ } from '@ultimat3/core';
7
13
  import type { Storage } from '@ultimat3/storage';
8
14
  import type { IslandBundle } from './island-bundle';
9
15
  import type { BuildAsset, PublishReport, RetainLog } from './retained-assets';
@@ -11,7 +17,7 @@ import { publishBuildAssets } from './retained-assets';
11
17
  import { retainedPrefix } from './retained-assets-layout';
12
18
  import type { RetainedAssets } from './retained-assets-read';
13
19
  import { retainedAssets } from './retained-assets-read';
14
- import { warnOncePerBuild } from './retained-assets-warned';
20
+ import { retainedBuildOnce } from './runtime-boot-warnings';
15
21
  import { siteAssetTable } from './site-assets';
16
22
  import type { StyleBundle } from './style-bundle';
17
23
  import type { FrameworkScript } from './worker-bundle';
@@ -83,11 +89,9 @@ const LOCAL_ENVIRONMENTS: ReadonlySet<string> = new Set(['development', 'test'])
83
89
 
84
90
  /** This file is the web role's boot alone (`serve-web.ts`): the role half of the warned key. */
85
91
  const WEB_ROLE = 'web';
86
-
87
92
  /**
88
- * Once per build id for the web role, not per boot: the marker sits on the app's default disk,
89
- * the one place every pod of a deploy may share (`warnOncePerBuild`). With no `app.config.ts`
90
- * there is no app name to scope it by, so that boot says it every time.
93
+ * Once per build id for the web role, not per boot (`retainedBuildOnce`). With no `app.config.ts`
94
+ * there is no app name to scope the marker by, so that boot says it every time.
91
95
  */
92
96
  async function warnUndeclared(input: RetainBootInput): Promise<void> {
93
97
  if (LOCAL_ENVIRONMENTS.has(input.environment) || buildAssetsOf(input).length === 0) return;
@@ -95,17 +99,26 @@ async function warnUndeclared(input: RetainBootInput): Promise<void> {
95
99
  environment: input.environment,
96
100
  disks: input.storage.diskNames,
97
101
  });
98
- const warn = (): void =>
99
- (input.log ?? logger).warn(warning.format(), { code: warning.code, ...warning.meta });
100
- if (input.config === undefined) return warn();
101
- await warnOncePerBuild(
102
+ await bootWarning(
103
+ {
104
+ code: warning.code,
105
+ roles: [WEB_ROLE],
106
+ once: input.config === undefined ? undefined : 'build',
107
+ message: warning.format(),
108
+ fields: warning.meta,
109
+ },
102
110
  {
103
- disk: () => input.storage.disk(),
104
- prefix: retainedPrefix(input.config.name, input.environment),
105
- role: WEB_ROLE,
106
- buildId: input.buildId,
111
+ roles: [WEB_ROLE],
112
+ log: input.log ?? logger,
113
+ buildOnce:
114
+ input.config === undefined
115
+ ? undefined
116
+ : retainedBuildOnce({
117
+ storage: input.storage,
118
+ prefix: retainedPrefix(input.config.name, input.environment),
119
+ buildId: input.buildId,
120
+ }),
107
121
  },
108
- warn,
109
122
  );
110
123
  }
111
124
 
package/src/role-start.ts CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  registeredJobs,
30
30
  } from '@ultimat3/jobs';
31
31
  import type { SyncWs } from '@ultimat3/realtime/server';
32
+ import { loadAppConfig } from './app-config-load';
32
33
  import { errorPageHook } from './error-pages';
33
34
  import { BadFlagError, RuntimeDriverSplitError } from './errors';
34
35
  import {
@@ -44,6 +45,7 @@ import type { RunningRoles, StartRolesOptions } from './role-start-types';
44
45
  import { DEV_ROLES } from './role-start-types';
45
46
  import { prepareSync, type RunningSync, syncReadsChanges } from './role-sync';
46
47
  import { startWorkerWake } from './role-wake';
48
+ import { installRoleBootWarnings } from './runtime-boot-warnings';
47
49
  import { devHooks } from './runtime-hooks';
48
50
  import { workerOptionsFor } from './runtime-jobs';
49
51
  import { reportUnservedQueues } from './runtime-jobs-unserved';
@@ -287,6 +289,17 @@ export async function startRoles(options: StartRolesOptions): Promise<RunningRol
287
289
  // call and another's HTTP call spend one bucket in one table.
288
290
  // A frame of its own over what `startServices` adopted, popped by its own undo — so stopping
289
291
  // these roles takes back exactly this install, whatever else stacked over or under it.
292
+ // Once, before any role serves: which roles core's `bootWarning` concerns, and its per-build
293
+ // marker store (`runtime-boot-warnings.ts`). Released by the stop, like every frame here.
294
+ const config = options.root === undefined ? undefined : await loadAppConfig(options.root);
295
+ const releaseWarnings = installRoleBootWarnings({
296
+ roles: selected,
297
+ config,
298
+ storage: options.runtime.storage,
299
+ env: options.env,
300
+ buildId: options.buildId,
301
+ });
302
+ started.push(async () => releaseWarnings());
290
303
  const limits = rateLimitStoreFor(options);
291
304
  const restoreLimits = limits === undefined ? () => undefined : installRateLimitStore(limits);
292
305
  started.push(async () => restoreLimits());
@@ -0,0 +1,65 @@
1
+ // The boot's half of core's `bootWarning`: the roles this process runs and the per-build memory —
2
+ // a zero-byte marker on the disk every pod of a deploy shares (`retained-assets-warned.ts`) —
3
+ // installed once by `startRoles`. The marker and storage modules load on the first `once: 'build'`
4
+ // claim, so a role that never says one evaluates neither.
5
+
6
+ import type { AppConfig, BuildOnceStore, Role } from '@ultimat3/core';
7
+ import { resolveEnvironment } from '@ultimat3/core';
8
+ import { installBootWarnings } from '@ultimat3/core/adapter';
9
+ import type { Storage } from '@ultimat3/storage';
10
+ import { retainedPrefix } from './retained-assets-layout';
11
+
12
+ /** The code whose marker predates the store: it keeps `<prefix>/warned/<role>/`. */
13
+ const RETAIN_UNDECLARED = 'X_ASSET_RETAIN_UNDECLARED';
14
+
15
+ /**
16
+ * Core's `once: 'build'` memory over `warnOncePerBuild`. The retain warning keeps the marker it
17
+ * always had, `<prefix>/warned/<role>/`; any other code is `<role>~<code>`, its own directory, so
18
+ * neither silences nor prunes the other. The app's own disks win over the host's, as every
19
+ * framework route reads them (`servedStorage`).
20
+ */
21
+ export function retainedBuildOnce(input: {
22
+ readonly storage: Storage;
23
+ readonly prefix: string;
24
+ readonly buildId: string;
25
+ }): BuildOnceStore {
26
+ return async (claim, say) => {
27
+ const [{ warnOncePerBuild }, { servedStorage }] = await Promise.all([
28
+ import('./retained-assets-warned'),
29
+ import('./runtime-storage'),
30
+ ]);
31
+ const storage = servedStorage(input.storage);
32
+ await warnOncePerBuild(
33
+ {
34
+ disk: () => storage.disk(),
35
+ prefix: input.prefix,
36
+ role: claim.code === RETAIN_UNDECLARED ? claim.role : `${claim.role}~${claim.code}`,
37
+ buildId: input.buildId,
38
+ },
39
+ say,
40
+ );
41
+ };
42
+ }
43
+
44
+ export interface RoleBootWarningsInput {
45
+ readonly roles: readonly Role[];
46
+ /** `undefined` with no `app.config.ts`: no app name to scope a marker by, so no build store. */
47
+ readonly config: Pick<AppConfig, 'name'> | undefined;
48
+ readonly storage: Storage;
49
+ readonly env: Readonly<Record<string, string | undefined>>;
50
+ readonly buildId: string;
51
+ }
52
+
53
+ /** Installs the booting roles and, with an app config, the build store. Returns the release. */
54
+ export function installRoleBootWarnings(input: RoleBootWarningsInput): () => void {
55
+ if (input.config === undefined) return installBootWarnings({ roles: input.roles });
56
+ const environment = resolveEnvironment({ env: input.env, fallback: 'production' });
57
+ return installBootWarnings({
58
+ roles: input.roles,
59
+ buildOnce: retainedBuildOnce({
60
+ storage: input.storage,
61
+ prefix: retainedPrefix(input.config.name, environment),
62
+ buildId: input.buildId,
63
+ }),
64
+ });
65
+ }
@@ -29,6 +29,7 @@ import type { AppConfig, CacheTierName } from '@ultimat3/core';
29
29
  import {
30
30
  backoffDelay,
31
31
  defineConfig,
32
+ failureStreak,
32
33
  finiteCount,
33
34
  isOutageMilestone,
34
35
  logger,
@@ -290,15 +291,23 @@ export function startCacheTiers(options: CacheTiersOptions): () => Promise<void>
290
291
  // delete too; this is the sender's half, and does not depend on hearing its own publish.)
291
292
  await purgeEdgeAgain(batch);
292
293
  };
294
+ // A flapping bus refuses the settle of every reconnect: one line per cause, one when it lands.
295
+ const settleFailures = failureStreak({
296
+ event: 'cache.broadcast.deferred-failed',
297
+ recoveredEvent: 'cache.broadcast.deferred-recovered',
298
+ level: 'warn',
299
+ });
293
300
  // ONE settle at a time. It is asked for by every reconnect and after every accepted publish,
294
301
  // and two that overlapped both published the same batch (and the same flush-all). A call that
295
302
  // arrives mid-run asks for one more pass instead, which finds whatever the run did not carry.
303
+ // The outcome is reported HERE, once per run: a joiner that reported it too counted one refused
304
+ // settle once per reconnect that joined it. Never rejects — what is unpublished stays owed.
296
305
  let settling: Promise<void> | undefined;
297
306
  let again = false;
298
- const settle = (): Promise<void> => {
307
+ const settleQuietly = (): void => {
299
308
  if (settling !== undefined) {
300
309
  again = true;
301
- return settling;
310
+ return;
302
311
  }
303
312
  settling = (async (): Promise<void> => {
304
313
  try {
@@ -306,17 +315,14 @@ export function startCacheTiers(options: CacheTiersOptions): () => Promise<void>
306
315
  again = false;
307
316
  await settleOnce();
308
317
  } while (again);
318
+ settleFailures.passed();
319
+ } catch (error) {
320
+ settleFailures.failed(error);
309
321
  } finally {
310
322
  again = false;
311
323
  settling = undefined;
312
324
  }
313
325
  })();
314
- return settling;
315
- };
316
- const settleQuietly = (): void => {
317
- void settle().catch((error: unknown) => {
318
- logger.warn('cache.broadcast.deferred-failed', { error: broadcastErrorText(error) });
319
- });
320
326
  };
321
327
 
322
328
  registerInvalidationBroadcast(async (wireTags) => {
@@ -22,7 +22,7 @@ import {
22
22
  snapshotOf,
23
23
  unrenderedOf,
24
24
  } from '@ultimat3/db';
25
- import { describeEntities } from '@ultimat3/entity';
25
+ import { registeredEntities } from '@ultimat3/entity';
26
26
  import { loadApp } from './app-load';
27
27
  import { checkSourceDrift, DB_PACKAGE } from './drift';
28
28
  import {
@@ -32,6 +32,7 @@ import {
32
32
  } from './drift-replica-identity';
33
33
  import { MIGRATIONS_DIR, readMigrations } from './migrations';
34
34
  import type { Finding } from './output';
35
+ import { settledDescriptions } from './redundant-indexes';
35
36
  import { appRowSecurity, type RowSecurityWanted, rowSecurityFindings } from './row-security-wanted';
36
37
  import { diffDeclaredSchema, type SchemaDifference } from './schema-diff';
37
38
 
@@ -53,7 +54,9 @@ export type DeclaredEntities = (
53
54
  export const appEntities: DeclaredEntities = async (root) => {
54
55
  const app = await loadApp(root);
55
56
  if (app.findings.length > 0) return undefined;
56
- return describeEntities();
57
+ // What `x db gen` diffed (`settledDescriptions`): a covered index `--drop-redundant` dropped is
58
+ // still described by its entity, and reading the raw registry would report it as unmigrated.
59
+ return settledDescriptions(registeredEntities(), await readMigrations(root), false);
57
60
  };
58
61
 
59
62
  /**
@@ -1,8 +1,9 @@
1
- // The roles each boot warning concerns, in one table, and the step that runs the post-load ones for
2
- // the booting role alone. Production logged the same warnings in all five roles on every boot — a
3
- // warning a role cannot act on is noise that buries the one it can.
1
+ // The roles each FRAMEWORK boot warning concerns, in one table, and the step that runs the
2
+ // post-load ones for the booting role alone. The role rule is core's `bootWarning`'s
3
+ // (`bootRolesConcerned`) — one answer for these and for an app's own role-scoped boot line.
4
4
 
5
5
  import type { Role } from '@ultimat3/core';
6
+ import { bootRolesConcerned } from '@ultimat3/core';
6
7
 
7
8
  /** Every warning a container boot can say. A new one does not compile until it names its roles. */
8
9
  export type BootWarning =
@@ -32,13 +33,13 @@ export const BOOT_WARNINGS: ReadonlyMap<BootWarning, readonly Role[]> = new Map(
32
33
  Object.entries(DECLARED) as [BootWarning, readonly Role[]][],
33
34
  );
34
35
 
35
- /** Whether `warning` is one `role` can act on. An unknown warning concerns nobody. */
36
- export const bootWarningConcerns = (warning: BootWarning, role: Role): boolean =>
37
- BOOT_WARNINGS.get(warning)?.includes(role) ?? false;
38
-
39
36
  /** Whether any of `roles` — `x dev` runs several in one process — can act on `warning`. */
40
37
  export const bootWarningConcernsAny = (warning: BootWarning, roles: readonly Role[]): boolean =>
41
- roles.some((role) => bootWarningConcerns(warning, role));
38
+ bootRolesConcerned(BOOT_WARNINGS.get(warning) ?? [], roles);
39
+
40
+ /** Whether `warning` is one `role` can act on. An unknown warning concerns nobody. */
41
+ export const bootWarningConcerns = (warning: BootWarning, role: Role): boolean =>
42
+ bootWarningConcernsAny(warning, [role]);
42
43
 
43
44
  /** The post-load probes: each logs its own line and answers whether it had anything to say. */
44
45
  export interface BootWarningProbes {
package/src/serve.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  // `dev: true`. The only production-shaped decisions live here: which role, which port, and which
5
5
  // interface — every one by default, because a container is reached through a port mapping.
6
6
 
7
- import { assertNoDevSecretsOutsideLocal, logger } from '@ultimat3/core';
7
+ import { assertNoDevSecretsOutsideLocal, frameworkVersion, logger } from '@ultimat3/core';
8
8
  import { assertNoSchemaDrift, checkDrift, migrate } from '@ultimat3/db';
9
9
  import { loadAppRuntime } from './app-runtime';
10
10
  import { acceptCreatedTables } from './db-accept-created';
@@ -218,6 +218,9 @@ export async function runRole(input: ServeOptions): Promise<StartedApp> {
218
218
  // `nats(connecting)` on a role that only publishes is a served pod with the bus down;
219
219
  // `ultimate bus` is logged with `nats(up)` when the dial lands.
220
220
  bus: app.bus,
221
+ // `buildId` is the app's; this is which framework release booted it — the same fact the
222
+ // monitor's `framework_version` tag and `target_info`'s label carry.
223
+ frameworkVersion: frameworkVersion(),
221
224
  });
222
225
  await hold();
223
226
  return app;
@@ -113,12 +113,43 @@ const literalCodeIn = (text: string, open: number): boolean => {
113
113
  return false;
114
114
  };
115
115
 
116
- const finding = (file: SourceFile, line: number, what: string): Finding => ({
117
- code: CODE,
118
- cause: \`\${file.path}:\${line} \${what} — the title, the HTTP status and the class are then declared apart, and a code with no status answers 500 and hides its cause\`,
119
- fix: \`rewrite it in \${file.path} as defineError({ code, title, status, cause, fix }) from @ultimat3/core/page (offSocket: true for a code no response carries), then: x verify\`,
120
- at: file.path,
121
- });
116
+ /** The first literal code in a span: the one a finding's fix declares. */
117
+ const CODE_LITERAL = /\\b(?:code|'code'|"code")\\s*:\\s*['"\`](X(?:_[A-Z0-9]+)+)['"\`]/;
118
+ const CLASS_NAME = /\\bclass\\s+([A-Za-z_$][\\w$]*)\\s*$/;
119
+ /** Where the next declaration starts, so a span never reads the following class's code. */
120
+ const NEXT_DECLARATION = /\\b(?:class|new)\\s/g;
121
+
122
+ const codeIn = (text: string, from: number): string | undefined => {
123
+ NEXT_DECLARATION.lastIndex = from + 1;
124
+ const next = NEXT_DECLARATION.exec(text);
125
+ return CODE_LITERAL.exec(text.slice(from, next === null ? text.length : next.index))?.[1];
126
+ };
127
+
128
+ /** The code's own words, the binding a class-less finding's fix declares: X_POST_GONE → PostGone. */
129
+ const bindingOf = (code: string): string =>
130
+ code
131
+ .slice(2)
132
+ .split('_')
133
+ .map((word) => word.charAt(0) + word.slice(1).toLowerCase())
134
+ .join('');
135
+
136
+ /** What a finding can name of the class it replaces; a placeholder for whatever it cannot read. */
137
+ interface Declared {
138
+ readonly name?: string | undefined;
139
+ readonly code?: string | undefined;
140
+ }
141
+
142
+ const finding = (file: SourceFile, line: number, what: string, declared: Declared): Finding => {
143
+ const name =
144
+ declared.name ?? (declared.code === undefined ? '<ErrorName>' : bindingOf(declared.code));
145
+ const code = \`'\${declared.code ?? 'X_<CODE>'}'\`;
146
+ return {
147
+ code: CODE,
148
+ cause: \`\${file.path}:\${line} \${what} — the title, the HTTP status and the class are then declared apart, and a code with no status answers 500 and hides its cause\`,
149
+ fix: \`rewrite it in \${file.path} as one call per class, from @ultimat3/core/page: export const \${name} = defineError({ code: \${code}, title, status, cause, fix, problemMeta: ['<meta key>'] }) — it replaces the class and its registerErrorStatus / registerProblemMeta rows (offSocket: true instead of status for a code no response carries; publicCause: true for a 5xx whose cause a caller may read; drop problemMeta when its meta stays operator-only), then: x verify\`,
150
+ at: file.path,
151
+ };
152
+ };
122
153
 
123
154
  const barrelFinding = (file: SourceFile, line: number): Finding => ({
124
155
  code: CODE,
@@ -150,24 +181,30 @@ export function undeclaredErrors(files: readonly SourceFile[]): readonly Finding
150
181
  for (const file of files) {
151
182
  const text = blank(file.source);
152
183
  const names = nameSource(classNames(text));
153
- const push = (index: number, what: string): void => {
184
+ const push = (index: number, what: string, declared: Declared): void => {
154
185
  const line = lineOf(text, index);
155
- found.push({ path: file.path, line, finding: finding(file, line, what) });
186
+ found.push({ path: file.path, line, finding: finding(file, line, what, declared) });
156
187
  };
157
188
  for (const line of barrelDefineErrorLines(text)) {
158
189
  found.push({ path: file.path, line, finding: barrelFinding(file, line) });
159
190
  }
160
191
  for (const match of text.matchAll(new RegExp(\`\\\\bextends\\\\s+(?:\${names})\\\\b\`, 'g'))) {
161
- push(match.index, 'subclasses UltimateError by hand');
192
+ const name = CLASS_NAME.exec(text.slice(0, match.index))?.[1];
193
+ push(match.index, 'subclasses UltimateError by hand', {
194
+ name,
195
+ code: codeIn(text, match.index),
196
+ });
162
197
  }
163
198
  for (const match of text.matchAll(new RegExp(\`\\\\bnew\\\\s+(?:\${names})\\\\s*\\\\(\\\\s*\`, 'g'))) {
164
199
  const at = match.index + match[0].length;
165
200
  // Anything but an object literal hides its code from this read: a value built elsewhere,
166
201
  // Object.assign over a literal. A re-raise is written as a literal, with code: err.code.
167
202
  if (text[at] !== '{')
168
- push(match.index, 'builds new UltimateError from a value this guard cannot read');
203
+ push(match.index, 'builds new UltimateError from a value this guard cannot read', {});
169
204
  else if (literalCodeIn(text, at))
170
- push(match.index, 'builds new UltimateError with a literal code');
205
+ push(match.index, 'builds new UltimateError with a literal code', {
206
+ code: codeIn(text, at),
207
+ });
171
208
  }
172
209
  }
173
210
  return found
@@ -1,17 +1,22 @@
1
- // The `repo-unbounded` guard `x new` ships, REPORT ONLY: a handle chain in a `repo.ts` ending in
2
- // `.all()` with no `.limit(n)` answers the handle's default page and drops the cursor to the rest —
3
- // neither every row nor a page the caller chose. Pairs with entity's `entity.all.truncated` event.
1
+ // The `repo-unbounded` guard `x new` ships: a handle chain in a `repo.ts` ending in `.all()` with no
2
+ // `.limit(n)` answers the handle's default page and drops the cursor to the rest — neither every
3
+ // row nor a page the caller chose. Pairs with entity's `X_ENTITY_ALL_TRUNCATED` warning. A new app
4
+ // gets it FAILING the gate; `'warning'` renders the report-only form apps scaffolded earlier hold.
4
5
 
5
6
  import { guardCode } from './guard';
6
7
  import { repoUnboundedTest } from './guard-repo-unbounded-test';
7
8
  import type { GeneratedFile } from './naming';
8
9
 
10
+ /** How the emitted guard reports: failing `boundaries`, or listing on it (`severity: 'warning'`). */
11
+ export type RepoUnboundedSeverity = 'error' | 'warning';
12
+
9
13
  /** Derived from the guard's name, never a literal: an `X_*` literal here is a FRAMEWORK code. */
10
14
  const NAME = 'repo-unbounded';
11
15
  const CODE = guardCode(NAME);
12
16
 
13
- const source =
14
- (): string => `// repo-unbounded: a repo.ts read says how many rows it wants, never a bare \`.all()\`.
17
+ const source = (
18
+ severity: RepoUnboundedSeverity,
19
+ ): string => `// repo-unbounded: a repo.ts read says how many rows it wants, never a bare \`.all()\`.
15
20
  // \`x verify\` discovers every file in \`guards/\` and runs its \`guard\` inside the \`boundaries\`
16
21
  // step — nothing registers this file, so nothing can forget to. Delete it to drop the rule.
17
22
  //
@@ -20,8 +25,11 @@ const source =
20
25
  // only from a missing row. Read: a \`db.<table>…all()\` or \`tx.<table>…all()\` chain with no
21
26
  // \`.limit(\`, \`.page(\`, \`.keyset(\` or \`.one(\` in it, in \`{apps,packages}/**/repo{,-*}.ts\`, never a
22
27
  // test. Admitted: a \`// why:\` on the chain's first line or the line above it, naming the bound.
23
- // REPORT ONLY (\`severity: 'warning'\`): its findings list on \`boundaries\`, never fail it.
24
-
28
+ ${
29
+ severity === 'warning'
30
+ ? "// REPORT ONLY (`severity: 'warning'`): its findings list on `boundaries`, never fail it.\n"
31
+ : ''
32
+ }
25
33
  import type { Finding, Guard } from '@ultimat3/cli';
26
34
 
27
35
  /** The app owns the codes its own conventions raise — this one is named for the guard. */
@@ -179,9 +187,11 @@ export function unboundedReads(files: readonly RepoFile[]): readonly Finding[] {
179
187
 
180
188
  export const guard: Guard = {
181
189
  summary: 'a repo.ts read says how many rows it wants: no .all() without a .limit(n)',
182
- // REPORT ONLY: findings are warnings on the \`boundaries\` step. Delete this line to enforce it.
183
- severity: 'warning',
184
- async check(_root, sources) {
190
+ ${
191
+ severity === 'warning'
192
+ ? " // REPORT ONLY: findings are warnings on the `boundaries` step. Delete this line to enforce it.\n severity: 'warning',\n"
193
+ : ''
194
+ } async check(_root, sources) {
185
195
  // The run's ONE read of these files: \`repo-raw-sql\` asks for the same glob, so they share it.
186
196
  const repos = await sources.files('{apps,packages}/**/repo{,-*}.ts');
187
197
  const read = repos.filter((file) => !file.path.endsWith('.test.ts'));
@@ -190,8 +200,14 @@ export const guard: Guard = {
190
200
  };
191
201
  `;
192
202
 
193
- /** `guards/repo-unbounded.ts` and its test. No index, no registry — the directory registers it. */
194
- export const repoUnboundedGuardFiles = (): readonly GeneratedFile[] => [
195
- { path: `guards/${NAME}.ts`, contents: source() },
203
+ /**
204
+ * `guards/repo-unbounded.ts` and its test. No index, no registry — the directory registers it.
205
+ * `'error'` is what `x new` and `x g guard` write; `'warning'` is the form shipped before, which an
206
+ * existing app keeps until it deletes the severity line itself.
207
+ */
208
+ export const repoUnboundedGuardFiles = (
209
+ severity: RepoUnboundedSeverity = 'error',
210
+ ): readonly GeneratedFile[] => [
211
+ { path: `guards/${NAME}.ts`, contents: source(severity) },
196
212
  { path: `guards/${NAME}.test.ts`, contents: repoUnboundedTest(CODE) },
197
213
  ];
@@ -25,8 +25,9 @@
25
25
  // about the TAB: an island polls with `visibleInterval()`, which a hidden tab and a lost session stop.
26
26
  // One is about the QUESTION: a destructive act asks through `ConfirmDialog`, never `confirm(`.
27
27
  // One is about the POOL: a database call per row runs through `mapBounded`, never all at once.
28
- // Two more are about the REPO, REPORT ONLY (`severity: 'warning'`) until the apps are clean of
29
- // them: an `await` per turn of a loop, and a `.all()` that says no bound.
28
+ // Two more are about the REPO: an `await` per turn of a loop, REPORT ONLY (`severity: 'warning'`)
29
+ // until the apps are clean of it, and a `.all()` that says no bound — failing the gate in an app
30
+ // scaffolded from 31.23 on, while an older app keeps the report-only copy it was given.
30
31
 
31
32
  import { animatedLayoutPropertyGuardFiles } from './guard-animated-layout-property';
32
33
  import { bareErrorGuardFiles } from './guard-bare-error';
@@ -80,7 +81,7 @@ const SHIPPED: readonly (readonly [string, () => readonly GeneratedFile[]])[] =
80
81
  ['raw-z-index', rawZIndexGuardFiles],
81
82
  ['repo-await-in-loop', repoAwaitInLoopGuardFiles],
82
83
  ['repo-raw-sql', repoRawSqlGuardFiles],
83
- ['repo-unbounded', repoUnboundedGuardFiles],
84
+ ['repo-unbounded', () => repoUnboundedGuardFiles('error')],
84
85
  ['semantic-interactive', semanticInteractiveGuardFiles],
85
86
  ['unbounded-fanout', unboundedFanoutGuardFiles],
86
87
  ['undeclared-custom-property', undeclaredCustomPropertyGuardFiles],
@@ -111,6 +112,28 @@ export const shippedGuardSource = (name: string): string | undefined => {
111
112
  return typeof contents === 'string' ? contents : undefined;
112
113
  };
113
114
 
115
+ /**
116
+ * A shipped guard's earlier form that still counts as current for an app holding it: the template
117
+ * moved for NEW apps only. `repo-unbounded` became failing in 31.23; an app scaffolded before keeps
118
+ * its report-only copy, and `x doctor` must not call that copy stale.
119
+ */
120
+ const ALSO_CURRENT: Readonly<Record<string, () => readonly GeneratedFile[]>> = {
121
+ 'repo-unbounded': () => repoUnboundedGuardFiles('warning'),
122
+ };
123
+
124
+ /**
125
+ * Every rule-file text that reads as current for a shipped guard — the template first, then any
126
+ * earlier form an existing app is allowed to keep. Empty when the name was never shipped.
127
+ */
128
+ export const shippedGuardSources = (name: string): readonly string[] => {
129
+ const current = shippedGuardSource(name);
130
+ if (current === undefined) return [];
131
+ const earlier = (Object.hasOwn(ALSO_CURRENT, name) ? ALSO_CURRENT[name] : undefined)?.().find(
132
+ (file) => file.path === `guards/${name}.ts`,
133
+ );
134
+ return typeof earlier?.contents === 'string' ? [current, earlier.contents] : [current];
135
+ };
136
+
114
137
  /**
115
138
  * Every guard `x new` ships, each with its test. One module per guard, because an app deletes a
116
139
  * rule it does not want by deleting one file — and a guard the app then writes for itself is
@@ -479,7 +479,7 @@ x db gen "add publish_at" | migrate | reset | studio
479
479
  | `backfill --pending` | every backfill the app **declared**, minus the ones that completed | the alarm: a sweep merged and never enqueued had no ledger row and was invisible everywhere. **Non-zero exit** when anything is unswept, so a cron reads the code and not the table |
480
480
  | `backfill <name>` / `backfill --all` | gate one sweep (or every pending one) and enqueue it | **dry run by default** — `--write` is never implied. `--write` enqueues; the workers perform the pass, because the queue is a job's execution surface. `--all` isolates per name and continues past a failure, exiting non-zero naming each |
481
481
  | `diagnostics` | what the database is doing now: `blockers` (each waiting `pid` and the `blockedBy` pid holding it, at `data.blockers.rows[]`), `activity`, `slowQueries`, `unusedIndexes`, `invalidIndexes`, `notValidConstraints`, `deadTuples` | **facts, never a verdict: exit 0** whatever they say. The one failure is a connection that never opens, `X_DB_UNAVAILABLE`. Every section is one catalog read in its own `BEGIN READ ONLY` with a 2 s `statement_timeout`, capped at `--limit` rows (default 20, at most 1000). A section that fails is `{ available: false, code, reason, fix }` in place and the other six still answer; `slowQueries` is unavailable until an operator installs `pg_stat_statements` (never on the embedded database). No user table is read; session SQL is printed with every literal as `?`; a credential in a reason is masked. **Whoever runs it sees the redacted SQL of every session on the app's database role** (every role, when it holds `pg_read_all_stats`): statement shape and identifiers, never values. `unusedIndexes` skips unique and primary indexes and carries `statsAgeSeconds` and `replica`. Opens the database without applying the framework tables; an embedded one `x dev` holds is refused (`X_DEV_ALREADY_RUNNING`). `--json`: `data.<section>`. Arbitrary read-only SQL is `db.query` over [`x mcp serve`](MCP-And-AI) |
482
- | `recount <entity>.<column>` | compare a `countedIn` counter with the true count of its child rows | **dry run by default**: lists the drifted rows (at most 50, the count whole) and exits non-zero with `X_LIFECYCLE_TRIGGER_MISSING` when any drifted. `--write` sets them in one cross-tenant transaction and exits 0. An unknown `<entity>.<column>` is `X_CLI_BAD_FLAG`. `--json`: `data` = `{ target, write, drifted, rows }` |
482
+ | `recount <entity>.<column>` | compare a `countedIn` counter with the true count of its child rows | **dry run by default**: lists the drifted rows (at most 50, the count whole) and exits non-zero with `X_LIFECYCLE_TRIGGER_MISSING` when any drifted. The parent is walked in windows of 1,000 keys, in key order, each window one cross-tenant transaction (`As of 31.23`). `--write` repairs each window's drift inside its transaction and exits 0. An unknown `<entity>.<column>` is `X_CLI_BAD_FLAG`. `--json`: `data` = `{ target, write, drifted, batches, rows }` |
483
483
 
484
484
  A bare `x db backfill` is `X_CLI_BAD_FLAG` naming a shape that works: the four answer four different questions, and defaulting to one of them is the ambiguity axiom 1 refuses.
485
485
 
@@ -524,6 +524,7 @@ Two more facts about the set, both `As of 2026-08`:
524
524
  |---|---|---|---|
525
525
  | `--name` | string | — | migration or branch name, or the backfill to filter the ledger by. Under `backfill --list` it is the **only** spelling of that filter: a positional there is a pass target in every other shape and is refused with `X_CLI_BAD_FLAG` rather than silently dropped |
526
526
  | `--allow-destructive` | boolean | `false` | let `gen` emit a DROP whose `down` cannot restore the rows. `X_MIGRATION_IRREVERSIBLE`'s own `fix:` line names it |
527
+ | `--drop-redundant` | boolean | `false` | `gen`: leave out of the diff each implicit index (a column's own, from `.references()` or `.index()`) that another index, the primary key or a unique invariant already leads with, so the migration drops it `concurrently` in a non-transactional step you review. Never a default; once dropped, a plain `x db gen` does not rebuild it. A table with no migration yet keeps every index. `x doctor` lists what it would drop (`data.redundantIndexes`), `As of 2026-11-14` |
527
528
  | `--list` | boolean | `false` | `backfill`: print the ledger |
528
529
  | `--pending` | boolean | `false` | `backfill`: declared minus completed, judged in this `ULTIMATE_ENV`. Non-zero exit when anything is unswept |
529
530
  | `--all` | boolean | `false` | `backfill`: every pending sweep, isolated per name |
@@ -1256,6 +1257,8 @@ Four warnings about how the app is held, `As of 31.16.0` (a fifth, `X_SHIPPED_GU
1256
1257
  | `X_ENV_NAME_RESERVED` | a name the app declares in `envSchema` or seals in `secrets.enc.json` is one `FRAMEWORK_ENV` (`@ultimat3/core`) lists as a `switch` or `internal` name — setting it for the app also switches that package's behaviour. Deploy-contract names (`DATABASE_URL`, `PORT`) and host names are not collisions | rename it `APP_<name>` (or delete it where the value is meant for the framework); then `x env example` |
1257
1258
  | `X_SHIPPED_GUARD_MISSING` (`As of 31.22`) | a guard `x new` ships is not in the app's `guards/`, so the gate does not hold the app to that rule — one per guard | `x g guard <name> && x verify --only boundaries --json` |
1258
1259
 
1260
+ **Redundant indexes**, the same way (`As of 2026-11-14`): each implicit index the entities describe that another index, the primary key or a unique invariant already leads with, still in the newest migration's snapshot, is one line — `<table>.<index> (<columns>) — <covering index>` — under a header naming `x db gen "drop redundant indexes" --drop-redundant`; `--json`: `data.redundantIndexes[]` = `{ table, name, columns, coveredBy }`, `[]` when none, absent when the app would not load or has no snapshot. A listing, never a finding: every write pays for each twice, and dropping it is a migration the app opts into.
1261
+
1259
1262
  **The chart's monitoring templates**, the same way (`As of 2026-11`): an app with a `docker/helm/Chart.yaml` and no `templates/servicemonitor.yaml` or `templates/alert-rules.yaml` gets one line per missing file, then `x g chart-alerts`, which writes only those (`--json`: `data.chartAlerts`, `{ missing[], add }`). The dashboard is its own row: no `dashboards/ultimate-app.json` or `templates/dashboard-configmap.yaml` lists them, then `x g chart-dashboard` (`data.chartDashboard`, the same shape). A chart that dropped them on purpose keeps a green verdict; an app with no chart is listed nothing.
1260
1263
 
1261
1264
  The embedded half is the bare-VM case: the external-database probe answers nothing the moment `DATABASE_URL` is unset, and that silence *is* the configuration a fresh box has. So `x doctor` also asks whether `@electric-sql/pglite` resolves from the app root — a resolve, never an import, because loading it boots the WASM build and takes the single-writer lock the next command needs. Red only where both hold: `DATABASE_URL` unset **and** the peer unresolvable, reported as `X_DB_UNAVAILABLE` with `@ultimat3/db`'s own sentence and its own runnable fix ([Bare VM](Bare-VM)). The snapshot half is `As of 2026-08` and separate from drift on purpose: they are two questions with two remedies, and `x db gen`'s own `X_MIGRATION_SNAPSHOT_MISSING` was a condition this diagnostic could not see at all, so `x doctor --json` — the `fix:` of the `X_CLI_UNEXPECTED` an author reaches it through — ran clean over a broken app.
@@ -65,6 +65,7 @@ The entity name is the first argument. Everything else is the init object:
65
65
  | `table` | the physical table, when it is not the entity's own name. For a schema this framework did not generate — see [Adopting an existing database](#adopting-an-existing-database) |
66
66
  | `tenant` | the tenant column. Omitted, it is inferred from `.tenant()` or a column named `orgId` — silence never means unscoped |
67
67
  | `shared` | `'<why its rows belong to no tenant>'` — for an entity with no tenant column whose references reach one that has a tenant (a price list every org's subscriptions point at). Without it the `exercise` step reports `X_ENTITY_TENANT_UNDECLARED`; blank is refused at `entity()` with the same code, and beside a tenant column it is `X_INVARIANT_VIOLATED`. See [Policies and authz](Policies-And-Authz#the-static-tenant-check) |
68
+ | `global` | `'<why every tenant reads the same rows>'` — for an entity with no tenant column that references none (a plan catalog), `As of 2026-11-14`. A query reading only global entities is the tenant proof's `global` verdict, not `unproven`; projected on `$describe().global`. Blank is `X_ENTITY_TENANT_UNDECLARED`; beside a tenant column, or beside `shared`, `X_INVARIANT_VIOLATED`. See [Policies and authz](Policies-And-Authz#the-dynamic-tenant-proof) |
68
69
  | `scan` | `'<why it stays small>'` — a bounded table (`'a closed catalog of 8 rows'`) the `exercise` step's plan sweep may see read whole. Without it a sequential scan of it is `X_QUERY_UNINDEXED`; blank is `X_INVARIANT_VIOLATED`. See [Testing](Testing#the-plan-and-scale-sweeps) |
69
70
  | `invariants` | `(c) => [invariant(name, expr), …]` — named predicates enforced on write, projected to a CHECK or UNIQUE constraint where expressible. `c` is typed from `columns`, so a typo is a compile error |
70
71
  | `indexes` | composite and partial indexes; a single unique or indexed column declares it on the column instead. On a table that already exists `x db gen` builds it with `create index concurrently` by default (`As of 2026-11`), in a migration of its own, outside a transaction; `concurrently: false` is the plain build, marked `-- lock-heavy: true` ([Indexes built concurrently](Migrations-And-Backfills#indexes-built-concurrently--expand--contract)). Key parts — `expression`, `orders`, `include`, `operatorClass` — under [Index key parts](#index-key-parts) |
@@ -456,7 +457,8 @@ export async function feed(orgId: string, after: string | null) {
456
457
  | The plan | `order by` stays on the bare columns: an index on `(created_at desc, id desc)` answers it as an Index Only Scan. `date_trunc('milliseconds', …)` measured 100 ms against 0.2 ms on 300,000 rows |
457
458
  | Kinds | `timestamptz`, `uuid`, `text`, `integer`, `bigint` |
458
459
  | Directions | all one way: a row comparison. Mixed: the or-chain |
459
- | A null key | `X_KEYSET_NULL_KEY` on any row of the page: a row comparison has no null order. `coalesce` the key, or order by a not-null column |
460
+ | A nullable key | `As of 2026-11-14`: declare it — `{ column: raw('p.published_at'), kind: 'timestamptz', direction: 'desc', nullable: true }`. NULL's place is written into `order by` (`nulls: 'first' \| 'last'`; default `asc nulls last`, `desc nulls first`, the entity driver's), the cursor carries present/absent, and the seek is the or-chain. The last key stays not null |
461
+ | A null key | on a key not declared `nullable`, `X_KEYSET_NULL_KEY` on any row of the page: a row comparison has no null order. A nullable last key is the same code, at `keyset()` |
460
462
  | A cursor from another read | `X_CURSOR_INVALID`. The scope is yours plus the keys: the same scope under another sort is refused too |
461
463
  | Memory | none: raw SQL has no memory path. Test it on the migrated database |
462
464
 
@@ -1258,6 +1260,7 @@ Three declarations on the entity, each compiled to a trigger or a purge target,
1258
1260
  | `retain: { after: '90d', on: 'createdAt' }` | a `PurgeTarget` per entity — batched, cross-tenant `delete … where created_at < now - after` | no window (`X_ENTITY_RETAIN_INVALID`), `on` not an indexed `timestamp()` (`X_ENTITY_RETAIN_UNINDEXED`), beside `appendOnly`, or on a table the catalog holds partitioned (drift, `X_ENTITY_RETAIN_INVALID`: detach partitions in a `task`) |
1259
1261
  | `history: true` · `history: { retain: { after: '365d' }, ignore: ['likeCount', 'updatedAt'] }` | `<table>_history (id, <tenant>, row_id, op, at, actor_id, request_id, before, after)` — a registered entity (`posts.$history`), written by the `ultimate_history` trigger, guarded by `ultimate_history_guard` | a composite primary key, `appendOnly` (`X_INVARIANT_VIOLATED`) |
1260
1262
  | `references(() => posts.id, { countedIn: () => posts.likeCount })` | a trigger on the child moving `posts.like_count` by one in the write's own transaction | the column is no `integer()`, or the key points at no single primary key (`X_ENTITY_COUNTS_INVALID`) |
1263
+ | `countedIn: { to: () => posts.upCount, where: (): Expr => whereColumns(likes).kind.eq('up') }` | the same trigger, counting only the child rows the predicate holds over — compiled once into its condition, its `update of` list and the recount | the predicate has no SQL (a function in `matches`/`satisfies`), or names no column of the child (`X_ENTITY_COUNTS_INVALID`) |
1261
1264
 
1262
1265
  ```ts
1263
1266
  import { entity, integer, timestamp, uuid } from '@ultimat3/entity';
@@ -1280,7 +1283,8 @@ export const likes = entity('likes', {
1280
1283
  - **Retention is a promise `x verify` checks.** A `retain` no `purge()` covers is `X_ENTITY_RETAIN_UNSWEPT` in the `manifest` step. `purge({ entities: 'declared' })` covers every one, history tables included, and needs no line per entity.
1281
1284
  - **History is recorded by trigger**, so `updateWhere`, a cascade and raw SQL are recorded too. An update that changes nothing records nothing; a change to a counted column, or to columns `history: { ignore }` names, alone records nothing — on both drivers (`history-ignore.test.ts`). `ignore` takes the entity's own columns, typed; another name is `X_INVARIANT_VIOLATED`. Declaring it changes the trigger's arguments, so `x db gen` writes the migration that reinstalls it. `.sealed()` columns stay ciphertext in the images. `actor_id`/`request_id` are what the WRITE'S transaction set (`x.actor`, `x.request`): the repository sets them before its first write to a history entity inside a transaction; an autocommit write records `null`, never a guess. Update of a history row is refused always; delete only under `x.purge` naming that table, which the retention sweep and a subject erase set (`X_ENTITY_APPEND_ONLY`, SQLSTATE `23001`). Reading it is an ordinary, tenant-scoped, cursor-paged read: `database({ posts, postsHistory: posts.$history })`.
1282
1285
  - **One row's history is `history(db.postsHistory, id)`**: every version, oldest first, each numbered `version` from 1 — ordered by chaining each `before` onto the previous `after` across every version, `at` only breaking ties: `at` is the transaction's START, so a transaction that began first and committed last carries the earlier `at` and the later image. `history(table, id, { limit: n })` reads the `n` versions with the latest `at` (ties at the edge kept), numbered as the whole history numbers them — chosen by transaction start, so a transaction that began before that window and committed inside it can fall outside. The read is the history table's, so another tenant's row reads back `[]`; the policy is the query or action that calls it. `version` counts what is retained: after a `retain` sweep, 1 is the oldest kept. As of 31.3.
1283
- - **A counter locks its parent row.** A hot parent serializes its writers; where that matters, `countBy` plus a cache is the alternative. A soft-deleted child is not counted. A new counter's migration recounts once, so an existing table starts true; `x db recount posts.likeCount` reports drift and `--write` repairs it.
1286
+ - **A counter locks its parent row.** A hot parent serializes its writers; where that matters, `countBy` plus a cache is the alternative. A soft-deleted child is not counted. A new counter's migration recounts once, so an existing table starts true; `x db recount posts.likeCount` reports drift and `--write` repairs it, in key-range batches.
1287
+ - **A counter's `where` is the invariant language over the CHILD**, built from `whereColumns(<child>)` — a thunk, like `to`, so it is typed by the child's own columns. Annotate it `(): Expr =>` (`import type { Expr } from '@ultimat3/entity'`): the child names itself inside its own declaration, and without the return type TypeScript reports the cycle (TS7022). A NULL operand is not counted, as a SQL `where` decides it; memory decides it the same way (`counter-where.test.ts`). Changing the predicate reinstalls the trigger and recounts in the same migration. The bare `countedIn: () => col` form is unchanged. As of 31.23.
1284
1288
  - **A counter's write is reported as the parent's change.** The WAL replicator sees the trigger's write; the in-process `entity.row` event (what `x dev` on PGlite and the memory driver feed live queries from) reports it too: after a child write, while `entity.row` has a subscriber, the parents whose count moved are read back in the write's transaction and each is an `update` at COMMIT, `before` the row with the count moved back. A filtered write (`deleteWhere`, `updateWhere`, a chain's `deleteAll`/`updateAll`) pinned to one parent by its key reports that row with `before: null`; one spanning parents is `entity.bulk` for the parent table. With no subscriber, nothing is read. So a live count needs no recount in the mutator (`counter-observed.test.ts`). As of 2026-11.
1285
1289
  - **An erase reaches history.** A parent `subjectErase()` deletes or anonymizes writes the person into a before image, so its `<table>_history` needs a line in `defineSubject({ tables })`: `'delete'` removes every image of those rows in the parent's own transaction — under `x.purge` on Postgres, under `purgingHistory(table, work)` in memory, the one delete each lets through — `{ retain: '<why>' }` keeps them, `anonymize` is refused. An undeclared one is `X_SUBJECT_TABLE_UNDECLARED`, an `anonymize` `X_SUBJECT_TREATMENT_INVALID`; images written before an upgrade are reached only by the next erase of that subject ([Jobs and workflows](Jobs-And-Workflows#one-persons-data--subjectexport-and-subjecterase)). As of 2026-11.
1286
1290
  - **Memory answers as Postgres does**: the memory driver records history and moves counters in its repository (`counter.test.ts`, `history.test.ts` are the parity tables).
@@ -537,7 +537,7 @@ Position in the plan is **necessary and not sufficient**: `docker compose up -d`
537
537
 
538
538
  ### `x db recount` — a counter, repaired
539
539
 
540
- `x db recount <entity>.<column>` compares a `countedIn` counter with the count of child rows and lists the drifted rows; `--write` sets them in one cross-tenant transaction. A counter drifts only while its trigger was missing (`X_LIFECYCLE_TRIGGER_MISSING`). As of 2026-11 the repair is one statement, not a paced `backfill()` pass.
540
+ `x db recount <entity>.<column>` compares a `countedIn` counter with the count of child rows — under its `where`, when it declares one — and lists the drifted rows; `--write` sets them. A counter drifts only while its trigger was missing (`X_LIFECYCLE_TRIGGER_MISSING`). The parent is walked in key-range windows of 1,000 rows, one cross-tenant transaction each, so a big table never holds one long lock; the dry run reads the same windows and writes nothing. Batched in the command itself, not through `backfill()`: that factory declares a job for a worker, and a recount names its counter at run time. As of 31.23.
541
541
 
542
542
  ### `x g backfill` — the generator
543
543