@ultimat3/cli 31.6.1 → 31.8.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.
package/CLAUDE.md CHANGED
@@ -54,7 +54,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
54
54
  | `load-findings.ts` | a module-load failure is reported once, by `manifest`; while red, each step that loads the app is wrapped in `blockedByLoad`: `skipped: load failed (see manifest)`. Under `--only` without `manifest` it carries the findings itself |
55
55
  | `verify-contract-diff.ts` | `contract-diff`: baseline is `x.manifest.json` at HEAD; in CI, at the merge base with `origin/$GITHUB_BASE_REF`, or that ref itself when a shallow checkout reaches no merge base; HEAD plus a fetch notice when the ref is not fetched; outside git, the file on disk with a notice |
56
56
  | `verify-factories.ts` | `unit` lints `<app>/packages/db/factories.ts` (`X_TEST_FACTORY_INVALID`) |
57
- | `verify-seeds.ts` | `unit` runs the seeds on one memory driver; a refused row keeps the entity's code and fix, an uncoded throw is `X_SEED_FAILED` |
57
+ | `verify-seeds.ts` / `verify-seeds-probe.ts` | `unit` runs the seeds in a child on ONE scratch database — `x exercise`'s (`withExerciseDatabase`): framework schema + migrations, installed as `db()`, so `register()` and entity rows agree; a refused row keeps the entity's code and fix, an uncoded throw is `X_SEED_FAILED` |
58
58
  | `boundary-findings.ts` / `app-boundaries.ts` / `boundary-cuts.ts` / `package-boundaries.ts` | surface + layer rules, `X_BOUNDARY_PACKAGE_TO_APP`; a `fix:` is the concrete cut † |
59
59
  | `app-boundaries.ts` (workspaces) | `@<scope>/<app>/<rest>` resolves onto `apps/<app>/<rest>` when that is an app source, so the surface rules hold across app workspaces |
60
60
  | `app-transport.ts` / `browser-transport.ts` / `transport-calls.ts` / `transport-values.ts` / `binding-names.ts` / `import-closure.ts` / `server-barrels.ts` / `browser-import-chain.ts` / `browser-barrel-cut.ts` | `boundaries`, built in: one browser transport; a server barrel below an island is cut at its first hop unless the browser entry exports every name taken (`meta.chain`; `x fix boundary` lists it, rule `browser-server-barrel`); never a `guards/` file † |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cli",
3
- "version": "31.6.1",
3
+ "version": "31.8.0",
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.6.1",
57
- "@ultimat3/admin": "31.6.1",
58
- "@ultimat3/ai": "31.6.1",
59
- "@ultimat3/auth": "31.6.1",
60
- "@ultimat3/cache": "31.6.1",
61
- "@ultimat3/core": "31.6.1",
62
- "@ultimat3/db": "31.6.1",
63
- "@ultimat3/entity": "31.6.1",
64
- "@ultimat3/flags": "31.6.1",
65
- "@ultimat3/http": "31.6.1",
66
- "@ultimat3/i18n": "31.6.1",
67
- "@ultimat3/jobs": "31.6.1",
68
- "@ultimat3/mail": "31.6.1",
69
- "@ultimat3/manifest": "31.6.1",
70
- "@ultimat3/mcp": "31.6.1",
71
- "@ultimat3/money": "31.6.1",
72
- "@ultimat3/notify": "31.6.1",
73
- "@ultimat3/policy": "31.6.1",
74
- "@ultimat3/pwa": "31.6.1",
75
- "@ultimat3/query": "31.6.1",
76
- "@ultimat3/realtime": "31.6.1",
77
- "@ultimat3/render": "31.6.1",
78
- "@ultimat3/schema": "31.6.1",
79
- "@ultimat3/scraping": "31.6.1",
80
- "@ultimat3/seo": "31.6.1",
81
- "@ultimat3/storage": "31.6.1",
82
- "@ultimat3/testing": "31.6.1",
83
- "@ultimat3/time": "31.6.1",
56
+ "@ultimat3/action": "31.8.0",
57
+ "@ultimat3/admin": "31.8.0",
58
+ "@ultimat3/ai": "31.8.0",
59
+ "@ultimat3/auth": "31.8.0",
60
+ "@ultimat3/cache": "31.8.0",
61
+ "@ultimat3/core": "31.8.0",
62
+ "@ultimat3/db": "31.8.0",
63
+ "@ultimat3/entity": "31.8.0",
64
+ "@ultimat3/flags": "31.8.0",
65
+ "@ultimat3/http": "31.8.0",
66
+ "@ultimat3/i18n": "31.8.0",
67
+ "@ultimat3/jobs": "31.8.0",
68
+ "@ultimat3/mail": "31.8.0",
69
+ "@ultimat3/manifest": "31.8.0",
70
+ "@ultimat3/mcp": "31.8.0",
71
+ "@ultimat3/money": "31.8.0",
72
+ "@ultimat3/notify": "31.8.0",
73
+ "@ultimat3/policy": "31.8.0",
74
+ "@ultimat3/pwa": "31.8.0",
75
+ "@ultimat3/query": "31.8.0",
76
+ "@ultimat3/realtime": "31.8.0",
77
+ "@ultimat3/render": "31.8.0",
78
+ "@ultimat3/schema": "31.8.0",
79
+ "@ultimat3/scraping": "31.8.0",
80
+ "@ultimat3/seo": "31.8.0",
81
+ "@ultimat3/storage": "31.8.0",
82
+ "@ultimat3/testing": "31.8.0",
83
+ "@ultimat3/time": "31.8.0",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
package/src/cmd-dev.ts CHANGED
@@ -56,7 +56,7 @@ export const devCommand: CliCommand = {
56
56
  // refuses every later one with a pid that is no longer running.
57
57
  // Before the boot, so its own lines are in it: `logs.tail` reads this file, and a dev server
58
58
  // that never wrote it answered every agent with X_NOT_IMPLEMENTED.
59
- const untee = teeDevLog(services.stateDir, { json: ctx.args.json });
59
+ const untee = teeDevLog(services.stateDir);
60
60
  const restart = childRestart(root, ctx.env);
61
61
  const server = await startDev({
62
62
  root,
@@ -2,6 +2,7 @@
2
2
  // (`docker/Dockerfile`, through `scripts/compile-x.ts`) and the boot e2e that proves it. One
3
3
  // `Bun.build`, because the CLI's `bun build --compile` takes no plugin and this graph needs one.
4
4
 
5
+ import { rasterWorkerBundle } from '@ultimat3/core';
5
6
  import { serverTsxBuildPlugin } from '@ultimat3/render/server';
6
7
  import { COMPILE_EXTERNALS } from './compile-externals';
7
8
  import { ExecutableCompileFailedError } from './errors';
@@ -23,13 +24,35 @@ export interface CompileExecutableOptions {
23
24
  * nobody defines. `serverTsxBuildPlugin` compiles them to the server factory, as the runtime
24
25
  * loader does for the same files off disk.
25
26
  */
27
+ /**
28
+ * What the graph is built from: the entry, plus core's raster Worker — this graph BUNDLES core, and
29
+ * Bun neither finds a `new Worker(…)` target on its own nor resolves one off disk inside the
30
+ * executable. Without it `transformImageBytes` runs inline and the web role (`ROLE` unset) refuses
31
+ * every static OG card as `X_IMAGE_RASTER_BUDGET`. The caller's defines win no key of the worker's.
32
+ */
33
+ export function executableGraph(options: CompileExecutableOptions): {
34
+ readonly entrypoints: readonly string[];
35
+ readonly root: string;
36
+ readonly define: Readonly<Record<string, string>>;
37
+ } {
38
+ const raster = rasterWorkerBundle([options.entry]);
39
+ return {
40
+ entrypoints: [options.entry, raster.entrypoint],
41
+ // Stated, not inferred: the worker's define is a path relative to exactly this directory.
42
+ root: raster.root,
43
+ define: { ...options.define, ...raster.define },
44
+ };
45
+ }
46
+
26
47
  export async function compileExecutable(options: CompileExecutableOptions): Promise<void> {
48
+ const graph = executableGraph(options);
27
49
  const built = await Bun.build({
28
- entrypoints: [options.entry],
50
+ entrypoints: [...graph.entrypoints],
51
+ root: graph.root,
29
52
  compile: { outfile: options.outfile },
30
53
  minify: options.minify ?? false,
31
54
  sourcemap: options.sourcemap === true ? 'linked' : 'none',
32
- define: { ...options.define },
55
+ define: { ...graph.define },
33
56
  external: [...COMPILE_EXTERNALS],
34
57
  plugins: [serverTsxBuildPlugin],
35
58
  throw: false,
@@ -1,11 +1,13 @@
1
- // `x db migrate`'s second look at the database it just migrated: does it hold a trigger, function,
2
- // view, type or sequence that replaying the migrations does not create? `runMigrations` compares
3
- // tables against the snapshot and closes its connection; a snapshot records only what entities
4
- // declare, so everything else is asked here, against the catalog the schema dump was rendered from.
1
+ // `x db migrate`'s second look at the database it just migrated: a trigger, function, view, type or
2
+ // sequence replaying the migrations does not create, and a framework table's storage parameters
3
+ // moved by hand. A snapshot records only what entities declare, so both are asked here, against the
4
+ // catalog the schema dump was rendered from; `runMigrations` has closed its connection by then.
5
5
 
6
- import type { DriftDifference } from '@ultimat3/db';
6
+ import type { DbClient, DriftDifference, TableStorageDifference } from '@ultimat3/db';
7
+ import { readTableStorageDrift } from '@ultimat3/db';
7
8
  import type { CatalogDescription } from '@ultimat3/db/schema-dump';
8
9
  import { introspectCatalog, unexpectedObjects } from '@ultimat3/db/schema-dump';
10
+ import { frameworkTableStorage } from './framework-schema';
9
11
  import { resolveServices } from './runtime-bindings';
10
12
  import { startQueue } from './runtime-queue';
11
13
 
@@ -23,8 +25,36 @@ export async function liveObjectDrift(
23
25
  ): Promise<readonly DriftDifference[]> {
24
26
  const queue = await startQueue(resolveServices(root, env), undefined, env);
25
27
  try {
26
- return unexpectedObjects(await introspectCatalog({ client: queue.db }), expected);
28
+ const [catalog, storage] = await Promise.all([
29
+ introspectCatalog({ client: queue.db }),
30
+ frameworkStorageDrift(queue.db),
31
+ ]);
32
+ return [...unexpectedObjects(catalog, expected), ...storage];
27
33
  } finally {
28
34
  await queue.stop();
29
35
  }
30
36
  }
37
+
38
+ /** One storage difference as drift: a missing table is `missing-table`, anything else its own kind. */
39
+ export function storageDifference(difference: TableStorageDifference): DriftDifference {
40
+ const { table, parameter, declared, live, fix } = difference;
41
+ return {
42
+ kind: parameter === 'table' ? 'missing-table' : 'changed-table-storage',
43
+ table,
44
+ column: null,
45
+ cause:
46
+ parameter === 'table'
47
+ ? `framework table "${table}" is absent; the framework schema apply creates it`
48
+ : `framework table "${table}" has ${parameter} ${live}; its tableStorage() declares ${declared}`,
49
+ fix,
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Every `tableStorage()` a `FRAMEWORK_SCHEMA` row declares, against `pg_class` in one read. A hand
55
+ * `alter table x_rate_limit set logged` is reported here with the `alter` that undoes it; the next
56
+ * framework apply would also converge it, but only on the next build.
57
+ */
58
+ export async function frameworkStorageDrift(client: DbClient): Promise<readonly DriftDifference[]> {
59
+ return (await readTableStorageDrift(client, frameworkTableStorage())).map(storageDifference);
60
+ }
package/src/dev-boot.ts CHANGED
@@ -7,7 +7,7 @@ import { devShellStyle } from '@ultimat3/admin/dev';
7
7
  import type { Role } from '@ultimat3/core';
8
8
  import { subscribe, subscribeSemconvMetrics } from '@ultimat3/core';
9
9
  import type { OverlayNotice, RequestContext } from '@ultimat3/http';
10
- import { asCtx } from '@ultimat3/http';
10
+ import { asCtx, subscribeRequestTimings } from '@ultimat3/http';
11
11
  import { loadSignInPath } from './app-auth';
12
12
  import { loadAppConfig } from './app-config-load';
13
13
  import type { StalePin } from './app-reload-graph';
@@ -168,6 +168,9 @@ async function bootDev(
168
168
  // The semconv histograms (`db_client_operation_duration_seconds`, …) on `x dev`'s `/metrics` too,
169
169
  // so a dashboard built against dev reads the series production exports.
170
170
  const unsubscribeMetrics = subscribeSemconvMetrics();
171
+ // What `Server-Timing`'s breakdown (dev only) and `http.request.slow` read per request — the same
172
+ // subscriber `startOtlpExport` installs on a production boot.
173
+ const unsubscribeTimings = subscribeRequestTimings();
171
174
  // The `/_x` cache panel's history: the cache keeps no log of its own, the panel subscribes one.
172
175
  const invalidations = createInvalidationLog();
173
176
  const unsubscribeInvalidations = subscribe('cache.invalidate', (event) =>
@@ -176,6 +179,7 @@ async function bootDev(
176
179
  acquired.push(() => {
177
180
  unsubscribeInvalidations();
178
181
  invalidations.reset();
182
+ unsubscribeTimings();
179
183
  unsubscribeMetrics();
180
184
  unsubscribeStatements();
181
185
  statements.reset();
package/src/dev-log.ts CHANGED
@@ -15,9 +15,7 @@ import {
15
15
  } from 'node:fs';
16
16
  // why: Bun exposes no path-join primitive.
17
17
  import { join } from 'node:path';
18
- import type { LogLevel } from '@ultimat3/core';
19
- import { installLogSink } from '@ultimat3/core';
20
- import { writeErrorLine, writeLine } from './write-line';
18
+ import { teeLogLines } from '@ultimat3/core';
21
19
 
22
20
  export const DEV_LOG_FILENAME = 'dev.log';
23
21
  /** The size at which `dev.log` becomes `dev.log.1` and starts over. */
@@ -62,29 +60,14 @@ export function openDevLog(stateDir: string, maxBytes: number = DEV_LOG_MAX_BYTE
62
60
  };
63
61
  }
64
62
 
65
- /** Where a terminal line goes: the CLI's own synchronous fd writers, by default. */
66
- export type TerminalWrite = (line: string, stream: 'stdout' | 'stderr') => void;
67
-
68
- const toTerminal: TerminalWrite = (line, stream) =>
69
- stream === 'stderr' ? writeErrorLine(line) : writeLine(line);
70
-
71
- const ERROR_LEVELS: ReadonlySet<LogLevel> = new Set(['error', 'fatal']);
72
-
73
63
  /**
74
- * Tee the process logger into `dev.log` until the returned release runs. The terminal keeps the
75
- * lanes core's own writer uses: `--json` (`dispatch.ts`'s `setLogStream('stderr')`) and every
76
- * `error`/`fatal` line on stderr, the rest on stdout — stdout under `--json` is the document.
64
+ * Tee the process logger into `dev.log` until the returned release runs. A TEE, never a redirect:
65
+ * the terminal keeps every line on core's own lanes (`--json` and `error`/`fatal` on stderr), and
66
+ * which lane a level takes stays core's rule alone — this file only adds the copy on disk.
77
67
  */
78
- export function teeDevLog(
79
- stateDir: string,
80
- options: { readonly json: boolean; readonly write?: TerminalWrite },
81
- ): () => void {
68
+ export function teeDevLog(stateDir: string): () => void {
82
69
  const log = openDevLog(stateDir);
83
- const terminal = options.write ?? toTerminal;
84
- const release = installLogSink((line, level) => {
85
- log.write(line);
86
- terminal(line, options.json || ERROR_LEVELS.has(level) ? 'stderr' : 'stdout');
87
- });
70
+ const release = teeLogLines((line) => log.write(line));
88
71
  let released = false;
89
72
  return () => {
90
73
  if (released) return;
@@ -21,8 +21,8 @@ import {
21
21
  SQL_AUTH_SERVER_TABLES,
22
22
  SQL_TOTP_REPLAY_TABLE,
23
23
  } from '@ultimat3/auth/schema';
24
- import { FAILURES_TABLE, SQL_FAILURES_TABLE } from '@ultimat3/db';
25
- import { SQL_RATE_LIMIT_TABLE } from '@ultimat3/http';
24
+ import { FAILURES_TABLE, SQL_FAILURES_TABLE, type TableStorage, tableStorage } from '@ultimat3/db';
25
+ import { RATE_LIMIT_STORAGE, SQL_RATE_LIMIT_TABLE } from '@ultimat3/http';
26
26
  import { SQL_JOBS_TABLE } from '@ultimat3/jobs';
27
27
  import { MCP_CONFIRMATIONS_TABLE, SQL_MCP_CONFIRMATIONS_TABLE } from '@ultimat3/mcp/schema';
28
28
  import {
@@ -46,6 +46,11 @@ export interface FrameworkSchema {
46
46
  readonly tables: readonly string[];
47
47
  /** One or more statements each; `;` separates. */
48
48
  readonly ddl: readonly string[];
49
+ /**
50
+ * The storage parameters its DDL renders (`tableStorage()`, `@ultimat3/db`) — the same values,
51
+ * so the drift `x db migrate` reports (`frameworkStorageDrift`) judges what the apply wrote.
52
+ */
53
+ readonly storage?: readonly TableStorage[];
49
54
  }
50
55
 
51
56
  /**
@@ -101,11 +106,15 @@ export const FRAMEWORK_SCHEMA: readonly FrameworkSchema[] = Object.freeze([
101
106
  pkg: '@ultimat3/http',
102
107
  tables: Object.freeze(['x_rate_limit']),
103
108
  ddl: Object.freeze([SQL_RATE_LIMIT_TABLE]),
109
+ storage: Object.freeze([RATE_LIMIT_STORAGE]),
104
110
  }),
105
111
  Object.freeze({
106
112
  pkg: '@ultimat3/auth',
107
113
  tables: Object.freeze(['x_auth_lockouts']),
108
114
  ddl: Object.freeze([SQL_AUTH_LIMIT_TABLES]),
115
+ // Stays LOGGED, stated so drift catches a hand `set unlogged`: a crash must never forget a
116
+ // lockout (`x_rate_limit` may, a refilled bucket is a brief free burst, never a bypass).
117
+ storage: Object.freeze([tableStorage('x_auth_lockouts', { unlogged: false })]),
109
118
  }),
110
119
  // Spent TOTP steps, so a code is single-use across the fleet rather than per replica.
111
120
  Object.freeze({
@@ -229,6 +238,10 @@ export const FRAMEWORK_SCHEMA: readonly FrameworkSchema[] = Object.freeze([
229
238
  }),
230
239
  ]);
231
240
 
241
+ /** Every storage declaration, flattened — what framework drift compares to `pg_class`. */
242
+ export const frameworkTableStorage = (): readonly TableStorage[] =>
243
+ FRAMEWORK_SCHEMA.flatMap((entry) => [...(entry.storage ?? [])]);
244
+
232
245
  /** Every relation this boot creates, flattened. */
233
246
  export const frameworkTableNames = (): readonly string[] =>
234
247
  FRAMEWORK_SCHEMA.flatMap((entry) => [...entry.tables]);
@@ -0,0 +1,25 @@
1
+ // The lock-heavy rail at the gate: a migration newer than the rail that would hold a live table
2
+ // still for a full scan must take the two-step form or say the lock is deliberate. Files, not the
3
+ // database, so it fires in CI. `@ultimat3/db` owns the classifier, the marker and the bound.
4
+
5
+ import { lockHeavyJudged, lockHeavyStatements, migrationLockHeavy } from '@ultimat3/db';
6
+ import { MIGRATIONS_DIR, readMigrations } from './migrations';
7
+ import { type Finding, findingFrom } from './output';
8
+
9
+ /**
10
+ * One finding per migration, as `checkDestructiveMigrations`, counting the rest in `cause`. Never a
11
+ * file-wide pass: a `-- lock-heavy: true` line admits only the statement directly under it, and
12
+ * `lockHeavyStatements` already leaves that one out. Only ids past `LOCK_HEAVY_SINCE` are judged,
13
+ * since an applied migration cannot gain a marker.
14
+ */
15
+ export async function checkLockHeavyMigrations(root: string): Promise<readonly Finding[]> {
16
+ const findings: Finding[] = [];
17
+ for (const migration of await readMigrations(root)) {
18
+ if (!lockHeavyJudged(migration.id)) continue;
19
+ const [first, ...rest] = lockHeavyStatements(migration.up);
20
+ if (first === undefined) continue;
21
+ const file = `${MIGRATIONS_DIR}/${migration.id}.sql`;
22
+ findings.push({ ...findingFrom(migrationLockHeavy(file, first, rest.length)), at: file });
23
+ }
24
+ return findings;
25
+ }
@@ -1,10 +1,14 @@
1
- // OTLP export, switched on by the variable the shipped Helm chart already sets. Until this file
2
- // `OTEL_EXPORTER_OTLP_ENDPOINT` was in `docker/helm/values.yaml` and **no code read it**: a
1
+ // OTLP export, switched on by `OTEL_EXPORTER_OTLP_ENDPOINT` — the variable the shipped Helm chart
2
+ // already sets — plus the bus subscribers every production boot records with or without a
3
+ // collector: the semconv histograms, the slow-statement line and the per-request timings.
4
+ //
5
+ // Until this file the variable was in `docker/helm/values.yaml` and **no code read it**: a
3
6
  // deployment configured a collector, the collector received nothing, and the only signal that
4
7
  // anything was wrong was an empty dashboard.
5
8
 
6
9
  import type { OtlpSignal, ShutdownReason } from '@ultimat3/core';
7
10
  import {
11
+ isProduction,
8
12
  logger,
9
13
  onShutdown,
10
14
  otlpEndpointLabel,
@@ -17,6 +21,8 @@ import {
17
21
  systemClock,
18
22
  tryOtlpEndpoint,
19
23
  } from '@ultimat3/core';
24
+ import { SLOW_STATEMENT_THRESHOLD_MS, slowStatementLog } from '@ultimat3/db';
25
+ import { subscribeRequestTimings } from '@ultimat3/http';
20
26
  import type { Env } from './runtime-bindings';
21
27
 
22
28
  /**
@@ -68,7 +74,37 @@ export function startOtlpExport(env: Env = process.env): () => void {
68
74
  // them to a scrape-only deployment exactly as OTLP pushes them to a collector. Pushed first, so
69
75
  // the reversed release below drops them last — the drain's own statements are still counted.
70
76
  releases.push(subscribeSemconvMetrics());
77
+ // One grep-able warn line per slow statement shape, with the request id. Production only: a
78
+ // test suite's deliberately slow statements are not an operator's incident. Released with the
79
+ // rest, so a second boot in this process never logs each statement twice.
80
+ const production = isProduction({ env });
81
+ releases.push(slowStatementLog({ thresholdMs: production ? SLOW_STATEMENT_THRESHOLD_MS : 0 }));
82
+ // Every environment: the statements, renders and cache lookups each request caused, which
83
+ // `http.request.slow` carries (its own threshold, `http.slowRequestMs`, decides whether it is
84
+ // written). Without it the line holds the gate and handler split and no statement count.
85
+ releases.push(subscribeRequestTimings());
71
86
 
87
+ // An exporter refused at construction (`X_OTLP_PROTOCOL_UNSUPPORTED`) fails the boot, and the
88
+ // subscribers above go with it: the caller never got a release to call, so a refused boot that
89
+ // left them behind counted every later statement twice in this process.
90
+ try {
91
+ installExporters(env, releases, flushes);
92
+ } catch (error) {
93
+ for (const release of releases.reverse()) release();
94
+ throw error;
95
+ }
96
+
97
+ return () => {
98
+ for (const release of releases.reverse()) release();
99
+ };
100
+ }
101
+
102
+ /** One exporter per signal whose endpoint is set, each pushed with its release and its flush. */
103
+ function installExporters(
104
+ env: Env,
105
+ releases: (() => void)[],
106
+ flushes: (() => Promise<void>)[],
107
+ ): void {
72
108
  // The boot's OWN env, not `process.env`, and the resolved endpoint is then passed to the
73
109
  // exporter explicitly: `runRole({ env })` is a real seam — a test and an in-process host both
74
110
  // pass an env that is not the process's — and an exporter that re-read `process.env` would
@@ -112,10 +148,6 @@ export function startOtlpExport(env: Env = process.env): () => void {
112
148
  if (flushes.length > 0) {
113
149
  releases.push(onShutdown('otlp', (reason) => flushWithin(flushes, reason), { phase: 'close' }));
114
150
  }
115
-
116
- return () => {
117
- for (const release of releases.reverse()) release();
118
- };
119
151
  }
120
152
 
121
153
  /**
@@ -99,14 +99,14 @@ export function staticMemoKey(
99
99
 
100
100
  /**
101
101
  * The document, or a bodiless 304 when `If-None-Match` names its ETag. The 304 repeats the
102
- * validators and the cache posture (RFC 9110 §15.4.5) and drops `content-type`: it has no content.
103
- * Only a 200 revalidates — a 404 rendered under `static` is sent whole.
102
+ * validators and the cache posture (RFC 9110 §15.4.5), and keeps `content-type`: the `compress`
103
+ * stage reads it to give the 304 the validator form it gave the 200 (`@ultimat3/http`'s
104
+ * `etag-form.ts`). Only a 200 revalidates — a 404 rendered under `static` is sent whole.
104
105
  */
105
106
  export function staticResponse(request: UltimateRequest, result: StaticResult): Response {
106
107
  const etag = result.headers['etag'];
107
108
  if (result.status === 200 && etag !== undefined) {
108
- const { 'content-type': _dropped, ...headers } = result.headers;
109
- const fresh = notModified(request, etag, headers);
109
+ const fresh = notModified(request, etag, result.headers);
110
110
  if (fresh !== undefined) return fresh;
111
111
  }
112
112
  return html(result.body, { status: result.status, headers: result.headers });
@@ -39,6 +39,7 @@ import {
39
39
  } from './manifest-staleness';
40
40
  import { mcpLockFindings } from './mcp-lock-findings';
41
41
  import { msg } from './messages';
42
+ import { checkLockHeavyMigrations } from './migration-lock-check';
42
43
  import type { Finding } from './output';
43
44
  import { retainUnsweptFindings } from './retain-sweep';
44
45
  import { checkMigrationDrift } from './schema-drift';
@@ -215,6 +216,9 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
215
216
  schema: async () => [
216
217
  ...(await checkMigrationDrift(ctx.root)),
217
218
  ...(await checkDestructiveMigrations(ctx.root)),
219
+ // Beside it, the same shape: a statement that stops a live table's writes for a full scan
220
+ // must take the two-step form or say so. Judged only past `LOCK_HEAVY_SINCE`.
221
+ ...(await checkLockHeavyMigrations(ctx.root)),
218
222
  // The third rail, and the one the other two cannot see: a hand-written statement is
219
223
  // recorded by no snapshot and hashed by no source, so both halves above are green over SQL
220
224
  // a squash silently drops. Same directory, same reader, no database — this step's own
@@ -0,0 +1,87 @@
1
+ // The child `verify-seeds.ts` spawns: `bun verify-seeds-probe.ts <app root> <files as JSON>`, from
2
+ // the app's root. Every seed, in file order, on ONE scratch database — `x exercise`'s, with the
3
+ // framework schema and the app's migrations applied and installed as the ambient `db()` — so a
4
+ // seed's entity rows and what its `register()` writes land in the same place. Prints the failures.
5
+
6
+ // why: Bun exposes no path-join primitive.
7
+ import { join } from 'node:path';
8
+ import { renderThrowable, stringField } from '@ultimat3/core';
9
+ import { withTransaction } from '@ultimat3/db';
10
+ import { isSeed, postgresDriver } from '@ultimat3/entity';
11
+ import { parse, t } from '@ultimat3/schema';
12
+ import { withExerciseDatabase, withExerciseProcess } from './exercise-database';
13
+ import type { SeedFailure, SeedStage } from './verify-seeds';
14
+ import { SEEDS_PROBE_MARKER } from './verify-seeds';
15
+ import { writeLine } from './write-line';
16
+
17
+ type Env = Readonly<Record<string, string | undefined>>;
18
+
19
+ const failure = (
20
+ stage: SeedStage,
21
+ where: { file: string; export: string; seed: string },
22
+ error: unknown,
23
+ ): SeedFailure => ({
24
+ stage,
25
+ ...where,
26
+ code: stringField(error, 'code') ?? null,
27
+ cause: stringField(error, 'cause') ?? null,
28
+ fix: stringField(error, 'fix') ?? null,
29
+ message: stringField(error, 'message') ?? renderThrowable(error),
30
+ });
31
+
32
+ /**
33
+ * One transaction PER SEED, as `x db seed` runs them (`db-seed.ts`): a seed that throws takes only
34
+ * its own rows with it, and a later seed still reads what an earlier one committed. `db()` inside
35
+ * the transaction IS the transaction, so `register()` joins it without knowing.
36
+ */
37
+ async function runEach(root: string, files: readonly string[]): Promise<readonly SeedFailure[]> {
38
+ const driver = postgresDriver();
39
+ const failures: SeedFailure[] = [];
40
+ for (const file of files) {
41
+ let mod: Record<string, unknown>;
42
+ try {
43
+ mod = await import(join(root, file));
44
+ } catch (error) {
45
+ failures.push(failure('import', { file, export: '*', seed: '*' }, error));
46
+ continue;
47
+ }
48
+ for (const [name, value] of Object.entries(mod)) {
49
+ if (!isSeed(value)) continue;
50
+ try {
51
+ await withTransaction(() => value.run({ driver }));
52
+ } catch (error) {
53
+ failures.push(failure('run', { file, export: name, seed: value.name }, error));
54
+ }
55
+ }
56
+ }
57
+ return failures;
58
+ }
59
+
60
+ /**
61
+ * The seed run's failures for the app at `root` — one database for the whole run, discarded after.
62
+ * A database that would not open (a migration that fails, an extension PGlite cannot link and no
63
+ * `TEST_DATABASE_URL`) is one failure at stage `database`, carrying that refusal's own code and fix.
64
+ */
65
+ export async function probeSeeds(
66
+ root: string,
67
+ files: readonly string[],
68
+ env: Env,
69
+ ): Promise<readonly SeedFailure[]> {
70
+ try {
71
+ return await withExerciseProcess(root, env, () =>
72
+ withExerciseDatabase(root, env, () => runEach(root, files)),
73
+ );
74
+ } catch (error) {
75
+ return [failure('database', { file: files[0] ?? '*', export: '*', seed: '*' }, error)];
76
+ }
77
+ }
78
+
79
+ if (import.meta.main) {
80
+ const root = process.argv[2] ?? process.cwd();
81
+ const files = parse(t.array(t.string), JSON.parse(process.argv[3] ?? '[]'));
82
+ const failures = await probeSeeds(root, files, { ...process.env });
83
+ writeLine(`${SEEDS_PROBE_MARKER}${JSON.stringify(failures)}`);
84
+ // PGlite and the services `withExerciseDatabase` installed are released; anything a seed left
85
+ // open (a timer, a socket) must not hold the gate's step until its deadline.
86
+ process.exit(0);
87
+ }
@@ -1,13 +1,16 @@
1
1
  // The seed run on the `unit` step: every seed the app declares (`SEED_GLOBS`) runs once, in file
2
- // order, on one in-memory driver. A row its entity refuses — `{ minor: 19.99 }` typechecks — is
3
- // reported with the entity's OWN code and fix, here, instead of 13 s later inside the e2e step's
4
- // X_E2E_APP_FAILED. No seed file is no seeds: nothing is spawned.
2
+ // order, on one migrated scratch database. A row its entity refuses — `{ minor: 19.99 }`
3
+ // typechecks — is reported with the entity's OWN code and fix, here, instead of 13 s later inside
4
+ // the e2e step's X_E2E_APP_FAILED. No seed file is no seeds: nothing is spawned.
5
5
 
6
+ // why: Bun exposes no path-join primitive.
7
+ import { join } from 'node:path';
6
8
  import { ERROR_DOCS_URL, UltimateError } from '@ultimat3/core';
7
9
  import type { Infer } from '@ultimat3/schema';
8
10
  import { parse, t } from '@ultimat3/schema';
9
11
  import { SEED_GLOBS } from './db-seed';
10
12
  import type { Runner } from './exec';
13
+ import { MIGRATIONS_DIR } from './migrations';
11
14
  import type { Finding } from './output';
12
15
  import { findingFrom } from './output';
13
16
  import { hasPathSegment } from './path-segments';
@@ -15,8 +18,13 @@ import { posixRelative } from './posix-path';
15
18
  import { quoteArg } from './shell-quote';
16
19
  import { isTest, sortedPosix } from './source-files';
17
20
 
21
+ /** Where a failure happened: the seed run's database, a seed module's import, or a seed's run. */
22
+ const SEED_STAGES = ['database', 'import', 'run'] as const;
23
+ export type SeedStage = (typeof SEED_STAGES)[number];
24
+
18
25
  const reportSchema = t.array(
19
26
  t.object({
27
+ stage: t.enum(SEED_STAGES),
20
28
  file: t.string,
21
29
  /** The export that declared the seed; `*` when the module would not import. */
22
30
  export: t.string,
@@ -27,7 +35,7 @@ const reportSchema = t.array(
27
35
  message: t.string,
28
36
  }),
29
37
  );
30
- type SeedFailure = Infer<typeof reportSchema>[number];
38
+ export type SeedFailure = Infer<typeof reportSchema>[number];
31
39
 
32
40
  /** The seed files `x db seed` would import, app-root-relative and sorted: the run's order. */
33
41
  async function seedFiles(root: string): Promise<readonly string[]> {
@@ -42,35 +50,21 @@ async function seedFiles(root: string): Promise<readonly string[]> {
42
50
  return sortedPosix([...files]);
43
51
  }
44
52
 
53
+ /** The line the probe prints its answer on; everything else it writes is a seed's own output. */
54
+ export const SEEDS_PROBE_MARKER = 'x-seeds-probe:';
55
+
45
56
  /**
46
- * Run in a CHILD, from the app's root, for `verify-factories.ts`'s reason: the seeds, `isSeed` and
47
- * `memoryDriver` must be the app's own `@ultimat3/entity`, and the app's entities must not register
48
- * into this process. One driver for the whole run, so a later seed reads what an earlier one wrote,
49
- * as `x db seed` does. The last stdout line is the report: the failures only.
57
+ * Run in a CHILD, from the app's root (`verify-seeds-probe.ts`): the app's entities must not
58
+ * register into this process, and the scratch database the probe installs as `db()` must not be
59
+ * this process's either. One database for the whole run, so a later seed reads what an earlier one
60
+ * wrote, as `x db seed` does.
50
61
  */
51
- const script = (files: readonly string[]): string => `const files = ${JSON.stringify(files)};
52
- const { isSeed, memoryDriver } = await import('@ultimat3/entity');
53
- const driver = memoryDriver();
54
- const str = (value, key) => { try { const v = value?.[key]; return typeof v === 'string' ? v : null; } catch { return null; } };
55
- const failure = (file, name, seed, error) => ({ file, export: name, seed,
56
- code: str(error, 'code'), cause: str(error, 'cause'), fix: str(error, 'fix'),
57
- message: str(error, 'message') ?? (() => { try { return String(error); } catch { return 'a value that will not render'; } })() });
58
- const failures = [];
59
- for (const file of files) {
60
- let mod;
61
- try { mod = await import(\`\${process.cwd()}/\${file}\`); }
62
- catch (error) { failures.push(failure(file, '*', '*', error)); continue; }
63
- for (const [name, value] of Object.entries(mod)) {
64
- if (!isSeed(value)) continue;
65
- try { await value.run({ driver }); } catch (error) { failures.push(failure(file, name, value.name, error)); }
66
- }
67
- }
68
- console.log(JSON.stringify(failures));`;
62
+ const PROBE = join(import.meta.dir, 'verify-seeds-probe.ts');
69
63
 
70
64
  /**
71
65
  * A seed threw something with no code of its own (a `TypeError` in its body, a module that would
72
- * not import). The fix is the one line that reproduces it with a full stack, on the same in-memory
73
- * driver the unit step used — the seed's own file, its own export.
66
+ * not import, a scratch database that would not open). The fix is the one line that reproduces it with a full stack — the seed's own file,
67
+ * its own export.
74
68
  */
75
69
  export class SeedFailedError extends UltimateError {
76
70
  constructor(input: { failure: SeedFailure; where: string }) {
@@ -81,8 +75,9 @@ export class SeedFailedError extends UltimateError {
81
75
  : `await (await import('./${failure.file}'))[${JSON.stringify(failure.export)}].run()`;
82
76
  super({
83
77
  code: 'X_SEED_FAILED',
84
- cause: `${input.where} threw an uncoded value on the in-memory driver: ${failure.message}`,
85
- fix: `bun --eval ${quoteArg(call)}`,
78
+ cause: `${input.where} threw an uncoded value: ${failure.message}`,
79
+ // The database is `x exercise`'s own, opened the same way: that command reproduces it.
80
+ fix: failure.stage === 'database' ? 'x exercise --json' : `bun --eval ${quoteArg(call)}`,
86
81
  });
87
82
  }
88
83
  }
@@ -94,13 +89,15 @@ export class SeedFailedError extends UltimateError {
94
89
  */
95
90
  export const seedFinding = (failure: SeedFailure): Finding => {
96
91
  const where =
97
- failure.export === '*'
98
- ? `${failure.file} did not import`
99
- : `seed "${failure.seed}" (${failure.file})`;
92
+ failure.stage === 'database'
93
+ ? `the seed run's scratch database (the framework schema, then ${MIGRATIONS_DIR}) did not open`
94
+ : failure.stage === 'import'
95
+ ? `${failure.file} did not import`
96
+ : `seed "${failure.seed}" (${failure.file}) on the seed run's scratch database`;
100
97
  if (failure.code?.startsWith('X_') === true && failure.cause !== null && failure.fix !== null) {
101
98
  return {
102
99
  code: failure.code,
103
- cause: `${where} on the in-memory driver: ${failure.cause}`,
100
+ cause: `${where}: ${failure.cause}`,
104
101
  fix: failure.fix,
105
102
  docs: ERROR_DOCS_URL,
106
103
  at: failure.file,
@@ -109,15 +106,27 @@ export const seedFinding = (failure: SeedFailure): Finding => {
109
106
  return { ...findingFrom(new SeedFailedError({ failure, where })), at: failure.file };
110
107
  };
111
108
 
112
- /** The child's last stdout line, parsed — or one finding saying the run printed no report. */
109
+ /** The probe's marker line, parsed — or one finding saying the run printed no report. */
113
110
  function readReport(stdout: string, stderr: string, first: string): readonly SeedFailure[] {
114
- const last = stdout.trim().split('\n').at(-1) ?? '';
111
+ const line = stdout
112
+ .split('\n')
113
+ .reverse()
114
+ .find((one) => one.startsWith(SEEDS_PROBE_MARKER));
115
115
  try {
116
- return parse(reportSchema, JSON.parse(last));
116
+ return parse(reportSchema, JSON.parse(line?.slice(SEEDS_PROBE_MARKER.length) ?? ''));
117
117
  } catch {
118
118
  const reason = stderr.trim().split('\n').slice(-3).join(' ') || 'no report was printed';
119
119
  return [
120
- { file: first, export: '*', seed: '*', code: null, cause: null, fix: null, message: reason },
120
+ {
121
+ stage: 'import',
122
+ file: first,
123
+ export: '*',
124
+ seed: '*',
125
+ code: null,
126
+ cause: null,
127
+ fix: null,
128
+ message: reason,
129
+ },
121
130
  ];
122
131
  }
123
132
  }
@@ -127,6 +136,6 @@ export async function seedFindings(root: string, runner: Runner): Promise<readon
127
136
  const files = await seedFiles(root);
128
137
  const first = files[0];
129
138
  if (first === undefined) return [];
130
- const result = await runner(['bun', '--eval', script(files)], { cwd: root });
139
+ const result = await runner(['bun', PROBE, root, JSON.stringify(files)], { cwd: root });
131
140
  return readReport(result.stdout, result.stderr, first).map(seedFinding);
132
141
  }
package/wiki/Auth.md CHANGED
@@ -257,6 +257,9 @@ const resolveToken = oauthBearerResolver(oauth, { actor: (grant) => actorFor(gra
257
257
  | S256 only; an absent method is `plain` and refused | same |
258
258
  | a code lives 2 minutes, is stored hashed, is single use; a replay revokes what it minted | `authorization-server.test.ts`, `authServerStoreConformance` from `@ultimat3/testing/conformance` (racing redemptions, run on memory and on Postgres by `auth-server-store-conformance-postgres.live.test.ts`) |
259
259
  | refresh rotates; a retired one's replay revokes the grant; idle past `refreshIdleDays` is dead | `authorization-server.test.ts` |
260
+ | refresh tokens only for a client whose `grantTypes` list `refresh_token`; otherwise none is issued and refreshing is `unauthorized_client` (device grant too) | `authorization-server.test.ts`, `authorization-server-postgres.test.ts` |
261
+ | a confidential client authenticates only with its registered `token_endpoint_auth_method`; the other is `invalid_client` | `authorization-server-clients.test.ts` |
262
+ | a redirect URI containing whitespace is refused at registration | `authorization-server-clients.test.ts` |
260
263
  | `resource` (RFC 8707) binds the grant; one not in `resources` is `invalid_target` | `authorization-server-request.test.ts`, `oauth-bearer-resolver.test.ts` |
261
264
  | tokens are opaque and stored hashed, never a JWT, so `revoke` holds on the next lookup | `token-endpoints.test.ts` |
262
265
  | an `https://` `client_id` is a metadata document, fetched through `outbound({ dial: 'public' })`, 5 KiB, cached 5 minutes, public clients only | `authorization-server-clients.test.ts` |
@@ -428,7 +428,7 @@ table per mode: [`docs/ops/04-datastores.md`](https://github.com/developerz-ai/u
428
428
 
429
429
  ## Compression
430
430
 
431
- The container gzips a public text answer of 1 KiB to 256 KiB with a declared length. Nothing to configure, and nothing to add in front.
431
+ The container codes a public text answer of 1 KiB to 256 KiB with a declared length: zstd when the client offers it, gzip otherwise, by RFC 9110 weights (`As of 2026-11`). Nothing to configure, and nothing to add in front.
432
432
 
433
433
  | Situation | What happens |
434
434
  |---|---|
@@ -437,9 +437,24 @@ The container gzips a public text answer of 1 KiB to 256 KiB with a declared len
437
437
  | a handler streaming public text it must not buffer | sets `cache-control: no-transform`, or declares no `content-length` |
438
438
  | a `stream()` body | never read: it declares no length |
439
439
  | an action's `text/event-stream` answer (`stream:`, `llm()`, `agent()`) | never coded or buffered: the type is off the list, it is `no-store`, and it sends `x-accel-buffering: no` for an nginx in front |
440
+ | a public answer with a strong ETag | coded once per process and kept (bounded LRU: 512 entries, 16 MiB), not re-coded on every hit. Its ETag is `W/"…"` whenever a coding is offered, and the 304 carries the same form |
441
+ | `Accept-Encoding: br` alone | identity. Bun's only native brotli is `CompressionStream('brotli')` at quality 11 — 854 ms per 256 KiB against zstd's 2.9 ms (Bun 1.4.4) — so brotli is build-time work: precompressed hashed assets are **planned**, not shipped |
440
442
 
441
443
  Rule and figures: [`docs/architecture/16-build-pipeline.md`](https://github.com/developerz-ai/ultimate/blob/main/docs/architecture/16-build-pipeline.md#what-is-compressed).
442
444
 
445
+ ## The rate-limit table is unlogged
446
+
447
+ `x_rate_limit`, the shared rate-limit store, is an `unlogged` table at `fillfactor = 70` (`As of 2026-11`): a take writes no WAL. The boot applies it to an existing table with `alter table x_rate_limit set unlogged` — a rewrite under ACCESS EXCLUSIVE of a small table, bounded by the migrate `lock_timeout`.
448
+
449
+ | Event | The buckets |
450
+ |---|---|
451
+ | a clean restart or upgrade | kept |
452
+ | a Postgres crash | truncated: every bucket answers full, so each key gets one free burst. Never a lockout |
453
+ | a failover to a promoted standby | the same: an unlogged table is not replicated |
454
+ | `x_auth_lockouts` | not this table: it stays logged, because a lockout forgotten by a crash is the attack it exists to stop |
455
+
456
+ `x db migrate` reports a hand change to its persistence or fillfactor as `changed-table-storage`, with the `alter` that undoes it.
457
+
443
458
  ## Static deploys independently
444
459
 
445
460
  ```
@@ -67,7 +67,7 @@ The entity name is the first argument. Everything else is the init object:
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
68
  | `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
69
  | `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
- | `indexes` | composite and partial indexes; a single unique or indexed column declares it on the column instead. `concurrently: true` on an entry builds it with `create index concurrently` in a migration of its own, outside a transaction — for a big, hot table ([Indexes built concurrently](Migrations-And-Backfills#indexes-built-concurrently--expand--contract)) |
70
+ | `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)) |
71
71
  | `primaryKey` | composite keys only — a single key is `.primaryKey()` on the column |
72
72
  | `tags` | extra cache tags this entity participates in, beyond its own `entity:<name>` |
73
73
 
@@ -9,7 +9,7 @@ One engine per concern. A **migration** changes the shape of a table — schema,
9
9
  | Change | Write |
10
10
  |---|---|
11
11
  | Add, rename, retype, drop a column or table; add an index or constraint | a **migration** — `x db gen "<name>"` |
12
- | Add an index to a big, hot table, or drop one from it | a **migration** too — `indexes: [{ on, concurrently: true }]` for the build; every drop is concurrent already. [Indexes built concurrently](#indexes-built-concurrently--expand--contract) |
12
+ | Add an index to a big, hot table, or drop one from it | a **migration** too — `indexes: [{ on }]`: on an existing table the build is concurrent by default, and every drop is concurrent already. [Indexes built concurrently](#indexes-built-concurrently--expand--contract) |
13
13
  | Rewrite, normalize, re-derive or backfill values in rows that already exist | a **backfill** — `backfill({ … })` |
14
14
  | Add a nullable column, then populate every existing row before making it required | both: the migration adds the column, the backfill sweeps the rows, a second migration adds the `not null` once the sweep is done (expand → migrate → contract) |
15
15
 
@@ -98,7 +98,7 @@ fixed point of Biome 2.5.5 at `lineWidth: 100`, and `x new`'s `biome.json` exclu
98
98
 
99
99
  ## Indexes built concurrently — expand → contract
100
100
 
101
- `As of 2026-10-31`. `create index` holds SHARE on the table for the whole build, so every write
101
+ `As of 2026-11`: the default on a table that already exists. `create index` holds SHARE on the table for the whole build, so every write
102
102
  waits; `drop index` takes ACCESS EXCLUSIVE, so every read waits too. On a big, hot table either one
103
103
  stalls the app or trips the migration's 3 s `lock_timeout` mid-deploy. The concurrent forms block
104
104
  neither, and Postgres refuses them inside a transaction — so they ship in a migration of their own.
@@ -108,7 +108,7 @@ import { entity, text, uuid } from '@ultimat3/entity';
108
108
 
109
109
  export const runs = entity('runs', {
110
110
  columns: { id: uuid().primaryKey(), status: text({ max: 20 }), bank: text({ max: 40 }) },
111
- indexes: [{ on: ['status'], concurrently: true }],
111
+ indexes: [{ on: ['status'] }],
112
112
  });
113
113
  ```
114
114
 
@@ -126,17 +126,20 @@ drop index concurrently if exists "runs_status_idx";
126
126
 
127
127
  | | |
128
128
  |---|---|
129
- | Build | `concurrently: true` on an `indexes:` entry. On a table the same migration creates it changes nothing — the table is empty and invisible until COMMIT, so it is built in that transaction |
129
+ | Build | every `indexes:` entry on a table that already exists, unless it says `concurrently: false` — the plain build, which `x db gen` marks `-- lock-heavy: true`. A partitioned parent is built plainly and marked too (Postgres refuses `concurrently` there, `0A000`). On a table the same migration creates nothing changes — the table is empty and invisible until COMMIT, so it is built in that transaction |
130
130
  | Drop | **every** removed index, concurrently built or not: delete it from `indexes`, `x db gen`. A total unique btree (a shape a UNIQUE constraint may back) is first unhooked with `alter table … drop constraint if exists` in the same step, right before its concurrent drop — `drop index concurrently` on a constraint's index is `2BP01`. That ALTER takes ACCESS EXCLUSIVE, so the runner gives it a short transaction of its own under the 3 s `lock_timeout` |
131
- | Files | no concurrent work (no `concurrently: true` build on a live table, no removed index) → ONE transactional migration, exactly as before. Concurrent work and nothing else → ONE `-- transaction: false` migration. Concurrent work beside other changes → TWO: `<id>.sql` (the transaction: new columns, tables, constraints, plain indexes) then `<id>_concurrently.sql` (the concurrent builds, then every drop). Each has its own snapshot and hash, and `--json` names the second as `followUp` |
131
+ | Files | no concurrent work (no new index on a live table, or only `concurrently: false` ones; no removed index) → ONE transactional migration, exactly as before. Concurrent work and nothing else → ONE `-- transaction: false` migration. Concurrent work beside other changes → TWO: `<id>.sql` (the transaction: new columns, tables, constraints, plain indexes) then `<id>_concurrently.sql` (the concurrent builds, then every drop). Each has its own snapshot and hash, and `--json` names the second as `followUp` |
132
132
  | Order | expand, then contract: inside the step every build runs before any drop or constraint unhook, across tables — a renamed key's replacement exists before the old key goes, so for a moment both exist and never neither |
133
133
  | Failure | an interrupted build leaves an INVALID index under the name. The next `x db migrate` finds it (`pg_index.indisvalid`), drops it concurrently, and builds it again; no row was written, so nothing is skipped |
134
- | Never recorded | `concurrently` is how an index is built, not what it is — not in the name, not in the snapshot. Adding or removing it on an existing index generates nothing |
134
+ | Never recorded | `concurrently` is how an index is built, not what it is — not in the name, not in the snapshot. Changing it on an existing index generates nothing |
135
135
  | Not destructive | an index holds no rows, so the destructive rail leaves a concurrent drop alone — and still requires `-- destructive: true` for a column or table drop beside it |
136
136
 
137
137
  A hand-written migration with `create index concurrently`, `drop index concurrently` or
138
138
  `reindex … concurrently` and no `-- transaction: false` line is refused before `BEGIN`:
139
- `X_MIGRATION_CONCURRENT_IN_TRANSACTION`.
139
+ `X_MIGRATION_CONCURRENT_IN_TRANSACTION`. One newer than `20261113000000` that runs `create index`
140
+ without `concurrently` on a table it did not create, or `set not null` with no validated
141
+ `check (… is not null)` before it, is refused by `x verify`'s drift step: `X_MIGRATION_LOCK_HEAVY`.
142
+ A deliberate one carries `-- lock-heavy: true`.
140
143
 
141
144
  ## Partitioned tables
142
145
 
@@ -140,8 +140,9 @@ policy allows them; `audio/x-m4a` and `video/x-m4v` are read as `audio/mp4` and
140
140
  required: a grant with no whole byte count of at least 1 is `X_STORAGE_UPLOAD_SIZE_UNDECLARED`, and
141
141
  `uploadFile` sends the file's own. An s3 disk signs it as the exact `Content-Length`, so the provider
142
142
  answers any other length, a chunked body included, with 403 `SignatureDoesNotMatch` and stores
143
- nothing. The local disks sign it as the ceiling `acceptSignedUpload` counts against, so a shorter body
144
- passes there and not on s3. `grant.maxBytes` is that declared size. A bare
143
+ nothing. For a single upload the local disks sign it as the ceiling `acceptSignedUpload` counts
144
+ against, so a shorter body passes there and not on s3; a part is held exact on every disk (below).
145
+ `grant.maxBytes` is that declared size. A bare
145
146
  `disk.signedUrl(key, { method: 'PUT' })` on s3 still binds nothing; with a `maxBytes` and no
146
147
  `contentLength` it is refused rather than ignored. Proven on the test stack's gateway. A provider
147
148
  that skips SigV4's signed-header check is the one thing that would unbind it, so
@@ -162,7 +163,7 @@ every one held to the actor's org:
162
163
  | Call | Answers |
163
164
  |---|---|
164
165
  | `grantMultipart({ disk, orgId, request, policy, partBytes? })` | `{ key, uploadId, partBytes, maxParts, contentType, size, expiresAt }`: `grantUpload`'s refusals, then a session. `partBytes` is what 10,000 parts need for `size`, never under 5 MiB |
165
- | `signPart({ disk, orgId, key, uploadId, partNumber, size, policy })` | a PUT URL whose length is signed. s3: S3's own `UploadPart`, presigned by core's signer. Local: `/_storage/<disk>/<key>?x-upload=…&x-part=…`, both inside the HMAC. A part no object under `policy.maxBytes` holds — past `max((partNumber − 1) × 5 MiB + size, partNumber × size)` — is `X_STORAGE_TOO_LARGE` |
166
+ | `signPart({ disk, orgId, key, uploadId, partNumber, size, policy })` | a PUT URL whose length is signed. s3: S3's own `UploadPart`, presigned by core's signer. Local and memory: `/_storage/<disk>/<key>?x-upload=…&x-part=…&x-len=…`, all three inside the HMAC (`v3-part`, `As of 2026-11`); a part of any other length is `X_STORAGE_URL_INVALID`, as s3 refuses it. A part no object under `policy.maxBytes` holds — past `max((partNumber − 1) × 5 MiB + size, partNumber × size)` — is `X_STORAGE_TOO_LARGE` |
166
167
  | `listParts({ disk, orgId, key, uploadId })` | `{ partNumber, etag, size }[]`, the resume |
167
168
  | `completeUpload({ disk, orgId, key, uploadId, parts, policy })` | the object. Each named part must have landed, ascending, every one but the last at least 5 MiB (`X_STORAGE_PARTS_INVALID`); the etags are the disk's own, so no bucket CORS has to expose `ETag`. A total past `policy.maxBytes` aborts and is `X_STORAGE_TOO_LARGE` |
168
169
  | `abortUpload({ disk, orgId, key, uploadId })` | nothing left: no session, no part |
package/wiki/Upgrading.md CHANGED
@@ -209,9 +209,25 @@ A setter still on a package's `.` barrel is `X_ADAPTER_PORT_INCOMPLETE` on the `
209
209
  | `rateLimit.buckets` in `app.config.ts` merges over the shipped buckets key by key (**31.5.0**). Before, any `buckets` you declared replaced the whole table, so `auth`, `mutation` and `assets` were gone and routes naming them used `default` | nothing. A bucket you declared still wins under its own name; delete any copy of a shipped bucket you kept only so it would not disappear |
210
210
  | a `from(entity, fn)` provider's function receives a `RowWindow` (**31.5.0**), `{ after, limit, order, filters }`, the page the read is after | nothing: a function that ignores the argument behaves as before. Optional: a repository that reads its own top N reads `after` and `limit` instead, so later pages are not empty or short |
211
211
  | `x verify`'s `contract-diff` step is red, `X_MANIFEST_BREAKING`, on a breaking change that `x manifest` or `x g` had already written into `x.manifest.json`: from **31.6.0** the baseline is the manifest as committed (at `HEAD`, or at the merge base with `origin/$GITHUB_BASE_REF` in a GitHub pull request), never the working-tree file | bump the major version, or restore the removed surface. Regenerating the manifest no longer clears it |
212
- | `x verify`'s `unit` step runs the app's seeds on the memory driver (**31.6.0**): a seed row the entity refuses — float money, a value its schema rejects — turns `unit` red under the entity's own code, and a seed that throws with no code is `X_SEED_FAILED` | fix the seed row the finding names, as its `fix:` says. Then `x verify --only unit` |
212
+ | `x verify`'s `unit` step runs the app's seeds (**31.6.0**; on a migrated scratch database from **31.8.0**): a seed row the entity refuses — float money, a value its schema rejects — turns `unit` red under the entity's own code, and a seed that throws with no code is `X_SEED_FAILED` | fix the seed row the finding names, as its `fix:` says. Then `x verify --only unit` |
213
213
  | `x verify`'s `errors` step reports `X_ERROR_FIX_INVALID` on an app's own error whose `fix:` defers the edit (a whitespace-delimited `# after <verb>ing …` or `# once <…>ed`), only says re-run, or runs `x g … --force` (**31.6.0**) | rewrite that `fix:` as the edit itself (`edit <path>.<ext>:<line> — <instruction>`) or a command that works on its own, with no `--force` |
214
214
  | every island and `/_x/assets` URL changes once (**31.6.1**): each is now named by a hash of its final bytes, never its sources (#1075) | nothing to do; a CDN in front needs no purge, since new names never collide with old ones |
215
+ | Sentry grouping (**31.7.0**): the default fingerprint is `[code]` (`X_INTERNAL`: `[code, '<fn> <path>']`; `X_CLIENT_ERROR`: `[code, '<pattern>#<island>']`), and `exception.values[0].stacktrace.frames` carries the stack | nothing: each existing issue reopens once under its code's group, and issues split by operation merge. An alert rule keyed on the old hash moves to the `code` tag (source is a tag, operation is the transaction). `extra.stack` stays through 31.x. Custom grouping: `sentryErrorReporter({ fingerprint })` |
216
+ | `x verify`'s `unit` step runs the app's seeds on a migrated scratch database (**31.8.0**): `x exercise`'s embedded PGlite with the framework schema and the app's migrations (a server from `TEST_DATABASE_URL` when a migration needs an extension PGlite cannot link), so a seed that calls `register()` or `db()` passes. A seed that writes an entity with no migration behind it is now `X_DB_SCHEMA_STALE`, as `x db seed` already said | nothing for an app with migrations. Otherwise `x db gen initial`, then `x verify --only unit` |
217
+ | `pollEvery` / `visibleInterval` back off on failure by default (**31.7.0**): `maxMs` is 8 × `ms` | nothing, unless a poll must keep hitting a failing endpoint at full rate: pass `{ maxMs: <ms> }` equal to `ms` |
218
+ | `requestMemo(ctx)` from `@ultimat3/query` returns `MemoFlights`, not a `Map` (**31.7.0**) | a caller that wrote into it: use `memoFlights(ctx, name)` from `@ultimat3/cache`, or `memoPerRequest(fn, key)` for a plain function |
219
+ | `buildSitemap` / `sitemapUrls` option `now: Date` is deprecated (**31.7.0**) | pass `clock: frozenClock(now)` instead |
220
+ | a compiled web role cropping or compositing a raster above `RASTER_SYNC_PIXELS` where no Worker can start answers `X_IMAGE_RASTER_BUDGET` (503) (**31.7.0**) | move the transform into a `warmVariants` job |
221
+ | the authorization server stops issuing and honouring refresh tokens for a client registered with explicit `grantTypes` that leave out `refresh_token`, e.g. `['authorization_code']` (**31.7.0**): its existing refresh tokens answer `unauthorized_client` | add `'refresh_token'` to that client's `grantTypes` if it should keep them |
222
+ | a confidential client sending its secret by the method it did not register answers `invalid_client` (**31.7.0**) | switch the client to its registered method, or `update x_oauth_clients set auth_method = '<method>' where client_id = '<id>'` |
223
+ | a sealed column no longer enters a history image (**31.7.0**, security): `x verify` reports `X_DB_DRIFT` in every app with `history: true` until it migrates, since the shared `ultimate_record_history` body changed. Rows already written still hold sealed ciphertext | `x db gen "history leaves sealed columns out"`, then `x db migrate`. Then, per history table whose parent has sealed columns: `begin; alter table "<t>_history" disable trigger "ultimate_history_guard"; update "<t>_history" set "before" = "before" - array['<col>', ...], "after" = "after" - array['<col>', ...]; alter table "<t>_history" enable trigger "ultimate_history_guard"; commit;`. If history left the database (exports, admin), treat lookup ciphertext as leaked and rotate the seal key |
224
+ | `.search()` through a non-Postgres search index answers `X_INVARIANT_VIOLATED` when a term matches 10,000 or more rows (**31.7.0**); before, it silently counted and paged only the first 10,000 | narrow the term, or `installSearchIndex(postgresSearchIndex())` |
225
+ | a multipart part URL on a local or memory disk signs its exact length (**31.8.0**: `x-len`, `v3-part`): one minted before the upgrade is refused, and a part shorter than signed is `X_STORAGE_URL_INVALID`, as on s3 | nothing: `uploadFile` re-requests the part URL (each expires in 15 min anyway). A client of its own calls `signPart` again with the part's exact `size` |
226
+ | `x db gen` builds an index on an existing table `concurrently` by default (**31.8.0**), in a `-- transaction: false` follow-up file; `x verify` refuses an unmarked lock-heavy migration newer than `20261113000000` (`X_MIGRATION_LOCK_HEAVY`) | generated migrations: nothing. A hand-written `create index` on an existing table: `create index concurrently` in a file whose first line is `-- transaction: false`, or `-- lock-heavy: true` for a deliberate plain build. A hand-written `set not null`: a `check (… is not null) not valid` constraint, validated in the next migration, first |
227
+ | drift can newly report `changed-index` (**31.8.0**) for a live index of a declared name that a hand edit gave `INCLUDE` columns or a non-default operator class: drift now compares both | rebuild it as declared — `drop index concurrently` then `create index concurrently` in a `-- transaction: false` migration — or give the hand-built index a name of its own: a live index no snapshot names is never drift. An entity's `indexes:` cannot declare `include` or an operator class yet |
228
+ | an anonymous, compressible, public answer carries `W/"…"` whenever the request offers a coding (**31.8.0**), even when too small to be coded; the 304 carries the same form | nothing. A client comparing that ETag strongly switches to weak comparison |
229
+ | the boot runs `alter table x_rate_limit set unlogged` (**31.8.0**): a rewrite under ACCESS EXCLUSIVE of a tiny table, bounded by the migrate `lock_timeout`. After a Postgres crash, or on a promoted standby, every bucket comes back full — one free burst per key, never a lockout; a clean restart keeps the buckets. `x_auth_lockouts` stays logged | nothing |
230
+ | a routine 401/403/429 refusal logs `debug` after the first `info` line per route per minute (**31.8.0**) | an alert keyed on those `info` lines moves to the `http_refusals_total{code}` counter |
215
231
 
216
232
  ## 29.x → 30.0.0, entry by entry
217
233