@ultimat3/cli 31.9.0 → 31.11.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cli",
3
- "version": "31.9.0",
3
+ "version": "31.11.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.9.0",
57
- "@ultimat3/admin": "31.9.0",
58
- "@ultimat3/ai": "31.9.0",
59
- "@ultimat3/auth": "31.9.0",
60
- "@ultimat3/cache": "31.9.0",
61
- "@ultimat3/core": "31.9.0",
62
- "@ultimat3/db": "31.9.0",
63
- "@ultimat3/entity": "31.9.0",
64
- "@ultimat3/flags": "31.9.0",
65
- "@ultimat3/http": "31.9.0",
66
- "@ultimat3/i18n": "31.9.0",
67
- "@ultimat3/jobs": "31.9.0",
68
- "@ultimat3/mail": "31.9.0",
69
- "@ultimat3/manifest": "31.9.0",
70
- "@ultimat3/mcp": "31.9.0",
71
- "@ultimat3/money": "31.9.0",
72
- "@ultimat3/notify": "31.9.0",
73
- "@ultimat3/policy": "31.9.0",
74
- "@ultimat3/pwa": "31.9.0",
75
- "@ultimat3/query": "31.9.0",
76
- "@ultimat3/realtime": "31.9.0",
77
- "@ultimat3/render": "31.9.0",
78
- "@ultimat3/schema": "31.9.0",
79
- "@ultimat3/scraping": "31.9.0",
80
- "@ultimat3/seo": "31.9.0",
81
- "@ultimat3/storage": "31.9.0",
82
- "@ultimat3/testing": "31.9.0",
83
- "@ultimat3/time": "31.9.0",
56
+ "@ultimat3/action": "31.11.0",
57
+ "@ultimat3/admin": "31.11.0",
58
+ "@ultimat3/ai": "31.11.0",
59
+ "@ultimat3/auth": "31.11.0",
60
+ "@ultimat3/cache": "31.11.0",
61
+ "@ultimat3/core": "31.11.0",
62
+ "@ultimat3/db": "31.11.0",
63
+ "@ultimat3/entity": "31.11.0",
64
+ "@ultimat3/flags": "31.11.0",
65
+ "@ultimat3/http": "31.11.0",
66
+ "@ultimat3/i18n": "31.11.0",
67
+ "@ultimat3/jobs": "31.11.0",
68
+ "@ultimat3/mail": "31.11.0",
69
+ "@ultimat3/manifest": "31.11.0",
70
+ "@ultimat3/mcp": "31.11.0",
71
+ "@ultimat3/money": "31.11.0",
72
+ "@ultimat3/notify": "31.11.0",
73
+ "@ultimat3/policy": "31.11.0",
74
+ "@ultimat3/pwa": "31.11.0",
75
+ "@ultimat3/query": "31.11.0",
76
+ "@ultimat3/realtime": "31.11.0",
77
+ "@ultimat3/render": "31.11.0",
78
+ "@ultimat3/schema": "31.11.0",
79
+ "@ultimat3/scraping": "31.11.0",
80
+ "@ultimat3/seo": "31.11.0",
81
+ "@ultimat3/storage": "31.11.0",
82
+ "@ultimat3/testing": "31.11.0",
83
+ "@ultimat3/time": "31.11.0",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
@@ -238,6 +238,7 @@ export const CLI_OWNED_ERROR_CODES = [
238
238
  'X_PARTITIONS_UNMAINTAINED',
239
239
  'X_TYPESCRIPT_VERSION',
240
240
  'X_SEED_FAILED',
241
+ 'X_NATIVE_FORM_UNANSWERED',
241
242
  ] as const;
242
243
 
243
244
  /**
@@ -462,6 +463,7 @@ export const CLI_ERROR_TITLES: Readonly<Record<CliListedErrorCode, string>> = {
462
463
  X_PARTITIONS_UNMAINTAINED: 'a partitioned entity with no partitions() job',
463
464
  X_TYPESCRIPT_VERSION: 'The app declares a TypeScript older than the one x new scaffolds',
464
465
  X_SEED_FAILED: 'a seed threw an uncoded error',
466
+ X_NATIVE_FORM_UNANSWERED: 'a page form posts to an action that declares no native answer',
465
467
  };
466
468
 
467
469
  // One unconditional call, so a second package claiming one of the CLI's codes throws
@@ -14,6 +14,7 @@ import {
14
14
  SQL_ERROR_GROUPS_TABLE,
15
15
  } from '@ultimat3/admin/schema';
16
16
  import {
17
+ AUTH_LOCKOUTS_STORAGE,
17
18
  AUTH_SERVER_TABLES,
18
19
  AUTH_TABLE_NAMES,
19
20
  AUTH_TABLES,
@@ -21,7 +22,7 @@ import {
21
22
  SQL_AUTH_SERVER_TABLES,
22
23
  SQL_TOTP_REPLAY_TABLE,
23
24
  } from '@ultimat3/auth/schema';
24
- import { FAILURES_TABLE, SQL_FAILURES_TABLE, type TableStorage, tableStorage } from '@ultimat3/db';
25
+ import { FAILURES_TABLE, SQL_FAILURES_TABLE, type TableStorage } from '@ultimat3/db';
25
26
  import { RATE_LIMIT_STORAGE, SQL_RATE_LIMIT_TABLE } from '@ultimat3/http';
26
27
  import { SQL_JOBS_TABLE } from '@ultimat3/jobs';
27
28
  import { MCP_CONFIRMATIONS_TABLE, SQL_MCP_CONFIRMATIONS_TABLE } from '@ultimat3/mcp/schema';
@@ -114,7 +115,7 @@ export const FRAMEWORK_SCHEMA: readonly FrameworkSchema[] = Object.freeze([
114
115
  ddl: Object.freeze([SQL_AUTH_LIMIT_TABLES]),
115
116
  // Stays LOGGED, stated so drift catches a hand `set unlogged`: a crash must never forget a
116
117
  // 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 })]),
118
+ storage: Object.freeze([AUTH_LOCKOUTS_STORAGE]),
118
119
  }),
119
120
  // Spent TOTP steps, so a code is single-use across the fleet rather than per replica.
120
121
  Object.freeze({
package/src/mcp-errors.ts CHANGED
@@ -380,6 +380,8 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
380
380
  X_TYPESCRIPT_VERSION:
381
381
  'x doctor --json # each X_TYPESCRIPT_VERSION finding names its manifest and the bun add that moves it',
382
382
  X_SEED_FAILED: 'bun --eval \'await (await import("./packages/db/seeds/dev.ts")).dev.run()\'',
383
+ X_NATIVE_FORM_UNANSWERED:
384
+ "native: { success: (output) => '/where-it-lands' } in the action's declaration, then x verify --only manifest",
383
385
  };
384
386
 
385
387
  const isCliCode = (code: string): code is CliErrorCode =>
@@ -0,0 +1,119 @@
1
+ // Which action a page's `<form method="post">` posts to, read from the page's SOURCE: a literal
2
+ // path, `derivePath(name).path`, `actionHttpPath(name, …).path`, or a same-file `const` holding one
3
+ // of those. Pure text in, targets out — `verify-native-form.ts` matches them to registered actions.
4
+
5
+ /** A form's target: an action named outright, or a URL path to match against the routes. */
6
+ export type FormTarget =
7
+ | { readonly kind: 'name'; readonly value: string }
8
+ | { readonly kind: 'path'; readonly value: string };
9
+
10
+ export interface PostForm {
11
+ readonly line: number;
12
+ readonly target: FormTarget;
13
+ }
14
+
15
+ /** How many `const` hops a value is followed through; a page that needs more is not read. */
16
+ const MAX_HOPS = 3;
17
+
18
+ const PATH_CALL = /^(?:derivePath|actionHttpPath)\(\s*([^,)]+?)\s*[,)]/;
19
+ const STRING = /^(['"])([^'"`]*)\1/;
20
+
21
+ /** The text up to the `>` that closes this tag, quotes and `{…}` skipped whole; `undefined` if open. */
22
+ function openingTag(source: string, from: number): string | undefined {
23
+ let depth = 0;
24
+ let quote: string | null = null;
25
+ for (let i = from; i < source.length; i++) {
26
+ const ch = source[i];
27
+ if (quote !== null) {
28
+ if (ch === quote) quote = null;
29
+ } else if (ch === '"' || ch === "'" || ch === '`') quote = ch;
30
+ else if (ch === '{') depth++;
31
+ else if (ch === '}') depth--;
32
+ else if (ch === '>' && depth === 0) return source.slice(from, i);
33
+ }
34
+ return undefined;
35
+ }
36
+
37
+ /** An attribute's raw value: a quoted string's text, or a `{…}` expression's, balanced. */
38
+ function attribute(tag: string, name: string): { quoted: boolean; text: string } | undefined {
39
+ const at = new RegExp(`\\s${name}\\s*=\\s*`).exec(tag);
40
+ if (at === null) return undefined;
41
+ const start = at.index + at[0].length;
42
+ const open = tag[start];
43
+ if (open === '"' || open === "'") {
44
+ const end = tag.indexOf(open, start + 1);
45
+ return end === -1 ? undefined : { quoted: true, text: tag.slice(start + 1, end) };
46
+ }
47
+ if (open !== '{') return undefined;
48
+ let depth = 0;
49
+ for (let i = start; i < tag.length; i++) {
50
+ if (tag[i] === '{') depth++;
51
+ else if (tag[i] === '}' && --depth === 0)
52
+ return { quoted: false, text: tag.slice(start + 1, i) };
53
+ }
54
+ return undefined;
55
+ }
56
+
57
+ /** `const NAME = <expr>;` in this file, or `undefined`. */
58
+ function constValue(source: string, name: string): string | undefined {
59
+ const match = new RegExp(`\\bconst\\s+${name}\\s*=\\s*([^;]+);`).exec(source);
60
+ return match?.[1]?.trim();
61
+ }
62
+
63
+ /** A string an expression evaluates to — a literal (`satisfies` ignored) or a const holding one. */
64
+ function stringOf(source: string, expression: string, hops: number): string | undefined {
65
+ const text = expression.trim();
66
+ const literal = STRING.exec(text);
67
+ if (literal !== null) return literal[2];
68
+ if (hops >= MAX_HOPS || !/^[A-Za-z_$][\w$]*$/.test(text)) return undefined;
69
+ const held = constValue(source, text);
70
+ return held === undefined ? undefined : stringOf(source, held, hops + 1);
71
+ }
72
+
73
+ /** What an `action={…}` expression names, followed through same-file consts. */
74
+ export function targetOf(source: string, expression: string, hops = 0): FormTarget | undefined {
75
+ const text = expression.trim();
76
+ const call = PATH_CALL.exec(text);
77
+ if (call !== null) {
78
+ const name = stringOf(source, call[1] ?? '', 0);
79
+ return name === undefined ? undefined : { kind: 'name', value: name };
80
+ }
81
+ const literal = STRING.exec(text);
82
+ if (literal !== null) {
83
+ const value = literal[2] ?? '';
84
+ return value.startsWith('/') ? { kind: 'path', value } : undefined;
85
+ }
86
+ if (hops >= MAX_HOPS || !/^[A-Za-z_$][\w$]*$/.test(text)) return undefined;
87
+ const held = constValue(source, text);
88
+ return held === undefined ? undefined : targetOf(source, held, hops + 1);
89
+ }
90
+
91
+ /** Every `<form method="post" action=…>` in a page whose target can be read. */
92
+ export function postForms(source: string): readonly PostForm[] {
93
+ const forms: PostForm[] = [];
94
+ for (const match of source.matchAll(/<form\b/g)) {
95
+ const tag = openingTag(source, match.index);
96
+ if (tag === undefined) continue;
97
+ const method = attribute(tag, 'method');
98
+ const verb = method?.quoted === true ? method.text : stringOf(source, method?.text ?? '', 0);
99
+ if (verb?.toLowerCase() !== 'post') continue;
100
+ const action = attribute(tag, 'action');
101
+ if (action === undefined) continue;
102
+ const target = action.quoted
103
+ ? action.text.startsWith('/')
104
+ ? ({ kind: 'path', value: action.text } as const)
105
+ : undefined
106
+ : targetOf(source, action.text);
107
+ if (target === undefined) continue;
108
+ forms.push({ line: source.slice(0, match.index).split('\n').length, target });
109
+ }
110
+ return forms;
111
+ }
112
+
113
+ /** Does a route path (`/orders/:id/refund`) answer this URL path? Query and fragment ignored. */
114
+ export function pathMatches(route: string, path: string): boolean {
115
+ const want = route.split('/');
116
+ const got = (path.split(/[?#]/)[0] ?? '').split('/');
117
+ if (want.length !== got.length) return false;
118
+ return want.every((segment, i) => segment.startsWith(':') || segment === got[i]);
119
+ }
@@ -56,6 +56,7 @@ import { nestedAppRootFindings } from './verify-drift-owner';
56
56
  import { exerciseStep } from './verify-exercise';
57
57
  import { floorProblemFindings, readVerifyFloor } from './verify-floor';
58
58
  import { mcpMountFindings } from './verify-mcp-mount';
59
+ import { nativeFormWarnings } from './verify-native-form';
59
60
  import { roleLoadFindings } from './verify-role-load';
60
61
  import type { VerifyStep } from './verify-step';
61
62
  import { fromExec, fromFindings, hostFindings } from './verify-step';
@@ -421,10 +422,14 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
421
422
  ...agents.warnings.map((warning) => `${AGENTS_MD_FILENAME}: ${warning}`),
422
423
  ...remote.warnings,
423
424
  ];
425
+ // A page's `<form method="post">` to an action with no `native`: a JSON dead end. Advice on
426
+ // `main` — refusing it would redden an app that passed yesterday (X_BREAKING_ON_MAIN).
427
+ const warnings = app ? await nativeFormWarnings(ctx.root) : [];
424
428
  return {
425
429
  ok: findings.length === 0,
426
430
  findings,
427
431
  ...(output.length === 0 ? {} : { output: output.join('\n') }),
432
+ ...(warnings.length === 0 ? {} : { warnings }),
428
433
  };
429
434
  },
430
435
  },
@@ -0,0 +1,94 @@
1
+ // The `manifest` step's native-form rider: a page's `<form method="post">` that posts to an action
2
+ // declaring no `native` leaves a reader with scripting off staring at JSON. On `main` it is a
3
+ // WARNING naming `X_NATIVE_FORM_UNANSWERED` (a red gate on an existing app is X_BREAKING_ON_MAIN);
4
+ // the refusal lands on `next`. The form's target is read by `native-form-scan.ts`.
5
+
6
+ // why: Bun exposes no path-join primitive; Bun.file takes one already joined.
7
+ import { join } from 'node:path';
8
+ import type { AnyAction } from '@ultimat3/action';
9
+ import { answersNatively, listActions } from '@ultimat3/action';
10
+ import { loadApp } from './app-load';
11
+ import type { AppLoader } from './app-permissions';
12
+ import type { PostForm } from './native-form-scan';
13
+ import { pathMatches, postForms } from './native-form-scan';
14
+ import type { Finding } from './output';
15
+
16
+ /** Every page an app serves: the directory is the URL, the file is always `page.tsx`. */
17
+ export const PAGE_GLOB = 'apps/*/{app,site}/**/page.tsx';
18
+
19
+ /** The registered action a form posts to, if any — by name, or by the route path it answers. */
20
+ function actionFor(form: PostForm, actions: readonly AnyAction[]): AnyAction | undefined {
21
+ if (form.target.kind === 'name') {
22
+ const { value } = form.target;
23
+ return actions.find((one) => one.name === value);
24
+ }
25
+ const { value } = form.target;
26
+ return actions.find((one) => pathMatches(one.describe().path, value));
27
+ }
28
+
29
+ /** An unanswered form: the action it posts to, and where. */
30
+ interface UnansweredForm {
31
+ readonly action: string;
32
+ readonly page: string;
33
+ readonly line: number;
34
+ }
35
+
36
+ export function nativeFormFinding(action: string, page: string, line: number): Finding {
37
+ return {
38
+ code: 'X_NATIVE_FORM_UNANSWERED',
39
+ cause: `${page}:${line} posts a <form method="post"> to action "${action}", which declares no native answer — a browser submitting it lands on JSON`,
40
+ fix: `native: { success: (output) => '/where-it-lands' } # in action "${action}"'s declaration, then x verify --only manifest`,
41
+ at: page,
42
+ };
43
+ }
44
+
45
+ /** Every unanswered form, after the app loaded — a short registry is the load's finding. */
46
+ async function unansweredForms(
47
+ root: string,
48
+ load: AppLoader,
49
+ actions: () => readonly AnyAction[],
50
+ ): Promise<readonly UnansweredForm[]> {
51
+ if ((await load(root)).findings.length > 0) return [];
52
+ const registered = actions();
53
+ const pages: string[] = [];
54
+ for await (const page of new Bun.Glob(PAGE_GLOB).scan({ cwd: root })) {
55
+ pages.push(page.replaceAll('\\', '/'));
56
+ }
57
+ const unanswered: UnansweredForm[] = [];
58
+ for (const page of pages.sort()) {
59
+ const source = await Bun.file(join(root, page)).text();
60
+ for (const form of postForms(source)) {
61
+ const target = actionFor(form, registered);
62
+ if (target !== undefined && !answersNatively(target)) {
63
+ unanswered.push({ action: target.name, page, line: form.line });
64
+ }
65
+ }
66
+ }
67
+ return unanswered;
68
+ }
69
+
70
+ /** The findings the refusal on `next` will report — the same facts the warnings print. */
71
+ export async function nativeFormFindings(
72
+ root: string,
73
+ load: AppLoader = loadApp,
74
+ actions: () => readonly AnyAction[] = listActions,
75
+ ): Promise<readonly Finding[]> {
76
+ return (await unansweredForms(root, load, actions)).map((form) =>
77
+ nativeFormFinding(form.action, form.page, form.line),
78
+ );
79
+ }
80
+
81
+ /**
82
+ * What the `manifest` step carries on `main`: one line per unanswered form — the code, the cause
83
+ * (which opens with `page:line`) and the fix — advice in `StepOutcome.warnings`, never a failed step.
84
+ */
85
+ export async function nativeFormWarnings(
86
+ root: string,
87
+ load: AppLoader = loadApp,
88
+ actions: () => readonly AnyAction[] = listActions,
89
+ ): Promise<readonly string[]> {
90
+ return (await unansweredForms(root, load, actions)).map((form) => {
91
+ const finding = nativeFormFinding(form.action, form.page, form.line);
92
+ return `${finding.code} ${finding.cause} — fix: ${finding.fix}`;
93
+ });
94
+ }
package/wiki/Actions.md CHANGED
@@ -36,6 +36,7 @@ Declared one per file in a feature's `actions/` (`actions/publish-post.ts`, what
36
36
  | `http.path` | `string` | no | pins the URL whatever the app's `pathStyle` derives — for a path a caller already holds (`'/api/uploads/signed'`) or a resource-shaped one (`'/orders/:id/refund'`). Lowercase static segments and `:param`s, never `/_x`; each `:param` a REQUIRED `t.string` key of `input:`, else `X_ACTION_HTTP_PATH_INVALID` at registration. The URL's value joins the body before the input is parsed, so the schema, the policy, `row` and the handler read one object; a body naming the key with another value is **400** `X_HTTP_PATH_INPUT_CONFLICT`, never overridden. Under a bearer mount the pin is served at the prefix (`/v1/orders/:id/refund`) — and still at its own path, with the cookie session, as every pin is; the policy decides both. `derivePath(name)` refuses a template; `actionHttpPath(name, { id })` fills it. A `deprecated.replacedBy` naming one is `X_ACTION_DEPRECATION_INVALID`. An inbound webhook is not this door: it is `webhookReceiver()` ([Jobs and workflows](Jobs-And-Workflows#inbound-webhooks)) |
37
37
  | `http.method` | `'POST'` · `'PUT'` · `'PATCH'` · `'DELETE'` | no — `'POST'` | the verb the pin answers; needs `http.path`. `X_ACTION_PATH_DUPLICATE` keys on method and path, so `PUT /orders/:id` and `DELETE /orders/:id` are two actions. `action.client()` sends it and fills the URL from the input (each value one encoded segment, the key left out of the body); `rpc()` by name cannot see a pin. In `openapi.json`: `{id}`, an `in: path` required parameter, the key gone from the request body, the operation under the declared verb. `x.manifest.json` writes `http: { path, method }` for a pin only; moving it is breaking. `As of 2026-11` |
38
38
  | `errors` | `readonly string[]` | no — `x g action` writes `errors: []` | the refusals a caller may branch on, each a registered 4xx code listed once (`X_ACTION_ERRORS_INVALID` otherwise, at `action()`). Declared, the list is CLOSED — see [Declared refusals](#declared-refusals-errors). Absent: today's open contract, bytes unchanged. `As of 2026-11` |
39
+ | `native` | `{ success: (output) => path; refusal?: (refusal) => path }` | no — expected on an action a `page.tsx` `<form method="post">` posts to: `X_NATIVE_FORM_UNANSWERED` is a warning on `main`, a refusal planned for `next` | the answer a browser's own form submission gets: `303` to a path, the outcome in a one-read flash. A fetch or MCP caller is answered exactly as before — see [Native forms](#native-forms-native). `As of 2026-11` |
39
40
  | `handle({ input, ctx })` | `(args) => Promise<Output>` | yes | the body. Parsed `input`, ambient `ctx`. Returns `output`-shaped data |
40
41
 
41
42
  **`.sensitive()` on an input field** — `cardPan: t.string.sensitive()` — means sent in, never
@@ -116,6 +117,59 @@ An action that answers in pieces declares `stream: <chunk schema>` and writes `h
116
117
 
117
118
  A chunk its schema refuses, or `stream:` beside a handle that is not a generator, is `X_ACTION_STREAM_INVALID`. The OpenAPI 200 lists `text/event-stream` beside `application/json` for a streaming action only. `agent()` streams this way.
118
119
 
120
+ ## Native forms: `native:`
121
+
122
+ A `<form method="post" action>` with scripting off gets a page back, never `{"ok":true}`. One declaration on the action; the action, its route and its JSON answer are unchanged.
123
+
124
+ ```ts
125
+ import { action, t } from '@ultimat3/action';
126
+ import { can } from '@ultimat3/policy';
127
+
128
+ export const createPost = action({
129
+ input: t.object({ title: t.string.min(3) }),
130
+ output: t.object({ id: t.string }),
131
+ policy: can('post:create'),
132
+ errors: [],
133
+ native: {
134
+ success: (post) => `/posts/${post.id}`,
135
+ refusal: () => '/posts/new', // omitted: back to the form's own page (a `Referer` on this host)
136
+ },
137
+ handle: async ({ input }) => ({ id: input.title }),
138
+ });
139
+ ```
140
+
141
+ | Caller | Answer |
142
+ |---|---|
143
+ | a browser form POST — `accept` names `text/html` and the body is `application/x-www-form-urlencoded` or `multipart/form-data` (the client router's submit included) | succeeded: `303` to `success(output)`; a `setRedirect()` inside `handle` still wins for that request (a sign-in's `next`). Refused with a 4xx other than `X_UNAUTHENTICATED` (a sign-in's own 401, a wrong password, included): `303` to `refusal(refusal)`, else the path and query of a `Referer` on this host (`http`/`https`, the request's own host and port). Either way a flash cookie carries the outcome |
144
+ | the same POST refused with `X_UNAUTHENTICATED`, a 5xx, or a refusal with no `refusal` and no `Referer` on this host | the ordinary error path: the sign-in redirect, the error page |
145
+ | `fetch` / the typed client / `rpc()` / MCP / `.job()` / a direct call | unchanged — JSON, the problem document, the output. `native` is read by the HTTP projection alone |
146
+
147
+ **The flash.** `x_action_answer`: `HttpOnly`, `SameSite=Lax`, `Max-Age=60`. It holds the action's name, the outcome and, for a refusal, its `code` and each field issue's `path`, `rule` and `params` — never a submitted value or an English message. Read it once, in the next page's `load`:
148
+
149
+ ```ts
150
+ import type { ActionAnswer, AnyAction } from '@ultimat3/action';
151
+ import { useActionAnswer } from '@ultimat3/action';
152
+
153
+ declare const createPost: AnyAction; // the action above
154
+
155
+ // `load:` of the form page's `defineRoute({ render: 'ssr', … })`
156
+ export const load = async (): Promise<{ readonly answer: ActionAnswer | null }> => ({
157
+ answer: useActionAnswer(createPost),
158
+ });
159
+ // answer: null | { action, outcome: 'success' } | { action, outcome: 'refusal', code, issues, truncated }
160
+ ```
161
+
162
+ | Rule | Why |
163
+ |---|---|
164
+ | read in `load`, never in a component | the read clears the cookie, and a header after the first flush is `X_STREAM_ALREADY_FLUSHED` |
165
+ | `useActionAnswer(createPost)` answers only that action's outcome — or by name, `useActionAnswer('createPost' satisfies keyof Api['actions'])`, from a page that may not import the action; `useActionAnswer()` any | two forms on one page |
166
+ | a cookie that is not one this package wrote reads as `null` | it arrives from the browser: parsed, bounded, never trusted |
167
+ | `static` / `isr` pages read `null` | a shared document is rendered as nobody, with no inbound cookie |
168
+ | translate on `code` and `issues[].rule` with `t()` | the flash carries no prose, so no locale |
169
+ | field values are not carried back | a password or a card number does not belong in a cookie; the form re-renders empty, or the page keeps a draft |
170
+
171
+ **Enforced.** The `manifest` step of `x verify` reads every `page.tsx` for a `<form method="post">` whose `action` names an action — a literal path, `derivePath(name).path`, `actionHttpPath(name, …).path`, or a `const` in the same file holding one — and reports one with no `native` as `X_NATIVE_FORM_UNANSWERED`, the page's `file:line` and the fix. On `main` it is a **warning** — listed under the step's `warnings` in `--json`, the step stays green — because refusing it would turn an app's gate red between two minors (`X_BREAKING_ON_MAIN`); the refusal is planned for `next`. A form inside a component other than the page is not read. `As of 2026-11`.
172
+
119
173
  ## The fluent surface
120
174
 
121
175
  Every projection this package owns is a method on the action — `publishPost.openapi()`, never `toOpenApiOperation(publishPost)`. The MCP tool is the exception by tier: `@ultimat3/mcp`'s one projection, `toolFrom(publishPost)` (`As of 25.0.0` there is no `.tool()`). Exactly four declared fields are lifted onto it as readable properties: `input`, `output`, `policy`, `mcp`. The rest of the declaration is structured metadata, reachable through `describe()` and nowhere else. An action has no `.def`.
package/wiki/Auth.md CHANGED
@@ -43,6 +43,7 @@ login on an app that declared no `handles` is `X_CONFIG_INVALID`. The deployed d
43
43
  | two expiries, independent | absolute and idle; activity never moves the absolute ceiling (`X_SESSION_EXPIRED` names which) |
44
44
  | not a write per request | `lastSeenAt` moves at most once per `idleSlideMs` (default `idleTtlMs / 20`); a changed IP or user agent is written at once |
45
45
  | revocation is immediate | the user row is re-read on every request, so a revoked role takes effect on the next one |
46
+ | one statement per request | `authenticate` reads the session and its user in one join on `postgresAuthAdapter` (was two; `As of 2026-11`, `authenticate-statements.test.ts`), through the adapter's optional `getSessionWithUser(id)` → `{ session, user \| null } \| null`. An adapter without it gets `getSession` then `findUserById`, the same answer; `authAdapterConformance` holds one that has it to exactly that answer. A slid idle window adds its one write |
46
47
  | the cookie | `__Host-x_session`, `HttpOnly`, `Secure`, `SameSite=Lax`, `Path=/`, `Max-Age` |
47
48
  | brute force | per-IP, per-account and per-org buckets (`X_ACCOUNT_LOCKED`); every login failure is one indistinguishable `X_UNAUTHENTICATED`. `rateLimit: { scope: 'shared' }` makes the count one for the fleet. The org bucket (`orgMaxAttempts`, default 100 per window) can be exhausted by someone who knows about 20 of an org's addresses, locking its password sign-in — kept by decision ([`SECURITY.md`](https://github.com/developerz-ai/ultimate/blob/main/SECURITY.md#known-gaps)) |
48
49
 
@@ -247,7 +248,7 @@ const resolveToken = oauthBearerResolver(oauth, { actor: (grant) => actorFor(gra
247
248
  | `routes` | `GET /.well-known/oauth-authorization-server` (RFC 8414), `POST /oauth/token`, `/oauth/revoke` (RFC 7009), `/oauth/introspect` (RFC 7662), plus `/oauth/register` (RFC 7591, `registration: 'dynamic'`) and `/oauth/device` (RFC 8628). Plain `Route`s for `runtime.routes`, public, no cookie authenticates them. Every answer is `no-store` RFC 6749 JSON |
248
249
  | consent | the page calls `readRequest(url)` → `{ client, scopes, resource, redirectUri }` or a refusal; an unknown client or unregistered redirect has `redirectTo: null` — render it, never redirect. Its action calls `approve({ subject, request, scopes? })` / `deny({ request })` for the redirect URL (`code`, `state`, `iss`). A forged request is `X_AUTH_CONSENT_INVALID` (422) |
249
250
  | device | the verification page calls `readDevice({ userCode, key })`, `approveDevice` / `denyDevice`; `key` is the caller's bucket — 10 misses lock it (`X_ACCOUNT_LOCKED`) |
250
- | `registerClient(...)` | a client the app creates itself — a partner's `client_credentials` client; the secret is shown once and stored hashed |
251
+ | `registerClient(...)` | a client the app creates itself — a partner's `client_credentials` client; the secret is shown once and stored hashed. A redirect URI, grant, scope or resource that is empty or holds whitespace is `X_AUTH_CLIENT_INVALID` (422, `meta.field`): the store keeps each list space-joined, so it would read back as a different list |
251
252
  | `resolve(token)` | `{ subject, scopes, clientId, resource } \| null`. `oauthBearerResolver(server, { actor, resource? })` is the `resolveToken` a bearer mount and `defineAppMcp` take; `actor` runs per call, so a removed member loses access at once |
252
253
  | `revoke({ subject, clientId? })` · `purge({ before })` | immediate; `purge` is the app's `task` to schedule, nothing here runs on a timer |
253
254
 
@@ -260,6 +261,7 @@ const resolveToken = oauthBearerResolver(oauth, { actor: (grant) => actorFor(gra
260
261
  | 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
262
  | a confidential client authenticates only with its registered `token_endpoint_auth_method`; the other is `invalid_client` | `authorization-server-clients.test.ts` |
262
263
  | a redirect URI containing whitespace is refused at registration | `authorization-server-clients.test.ts` |
264
+ | `registerClient` refuses an empty or whitespace-holding list value, before a secret is minted (`X_AUTH_CLIENT_INVALID`) | `authorization-server-register-client.test.ts` |
263
265
  | `resource` (RFC 8707) binds the grant; one not in `resources` is `invalid_target` | `authorization-server-request.test.ts`, `oauth-bearer-resolver.test.ts` |
264
266
  | tokens are opaque and stored hashed, never a JWT, so `revoke` holds on the next lookup | `token-endpoints.test.ts` |
265
267
  | 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` |
@@ -67,12 +67,67 @@ 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. 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)) |
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)). Key parts — `expression`, `orders`, `include`, `operatorClass` — under [Index key parts](#index-key-parts) |
71
+ | `version` | the optimistic-lock column, `As of 2026-11`: `update(id)` must carry it and fails `X_ENTITY_STALE` (409) when it moved. See [An optimistic lock](#an-optimistic-lock--version) |
71
72
  | `primaryKey` | composite keys only — a single key is `.primaryKey()` on the column |
72
73
  | `tags` | extra cache tags this entity participates in, beyond its own `entity:<name>` |
73
74
 
74
75
  Presence of a `deletedAt` column is what makes an entity soft-deletable — not a flag.
75
76
 
77
+ ### Index key parts
78
+
79
+ Four optional fields beside `on`, `As of 2026-11`. Each absent by default, so no existing index
80
+ name, schema hash or migration moves. A bad combination is `X_INVARIANT_VIOLATED` at `entity()`
81
+ (`declared-index-keys.ts`), never a server syntax error inside `ROLE=migrate`.
82
+
83
+ ```ts
84
+ import { entity, text, timestamp, uuid } from '@ultimat3/entity';
85
+
86
+ export const users = entity('users', {
87
+ columns: {
88
+ id: uuid().primaryKey(),
89
+ orgId: uuid().tenant(),
90
+ email: text(),
91
+ status: text(),
92
+ title: text(),
93
+ createdAt: timestamp().defaultNow(),
94
+ },
95
+ indexes: [
96
+ { on: ['email'], unique: true, expression: 'lower(email)' }, // unique(lower(email))
97
+ { on: ['orgId', 'createdAt'], orders: ['asc', 'desc'] },
98
+ { on: ['orgId', 'status'], include: ['title'] }, // an index-only scan reads title
99
+ { on: ['title'], using: 'gin', operatorClass: 'gin_trgm_ops' }, // what text `contains` needs
100
+ ],
101
+ });
102
+ ```
103
+
104
+ | Field | Rule |
105
+ |---|---|
106
+ | `expression` | the ONE key is this SQL, over **physical** column names; `on` names the columns it reads (the name and the covering rule read those). A unique expression index is no `upsertAll` conflict target (Postgres `42P10`), and no key for a concurrent `refreshView` (`X_JOB_REFRESH_VIEW_INVALID`) |
107
+ | `orders` | one direction per key, `null` writes none. btree only; never beside `order` |
108
+ | `include` | `INCLUDE` payload columns, the entity's own properties. btree only, never empty |
109
+ | `operatorClass` | `'gin_trgm_ops'` on every key; needs `using: 'gin'`. `x db gen` writes `create extension if not exists pg_trgm` in the migration that first builds one |
110
+
111
+ A column's own index (`.references()`, `.index()`, `.tenant()`) that the primary key, another
112
+ total btree index or a unique invariant already leads with is **still emitted**: dropping it would
113
+ make `x db gen` remove a live index in every existing app. It is listed on
114
+ `RegistryEntry.coveredIndexes` (`CoveredIndex`: `name`, `columns`, `coveredBy`), outside
115
+ `$describe()` so no schema hash moves. Nothing reads the list yet — a report and an opt-in drop are
116
+ planned.
117
+
118
+ ### Substring search is `contains` on a text column
119
+
120
+ `andWhere('title', 'contains', term)` on a `text()` or `char()` column is a case-insensitive
121
+ substring match, `As of 2026-11`: `"title" ilike $1`, the term bound with `%`, `_` and `\` escaped
122
+ — a `%` typed into a search box is a percent sign. On `jsonb` and `arrayOf()` it stays `@>`
123
+ containment (`text-contains.ts`). Memory answers the same (both sides lower-cased; Unicode
124
+ `toLowerCase`, so only locale-specific folds such as Turkish dotted I can differ).
125
+
126
+ Served only by a trigram index: `indexes: [{ on: ['title'], using: 'gin', operatorClass:
127
+ 'gin_trgm_ops' }]`. Nothing checks it at runtime; the `exercise` step's plan sweep reports a
128
+ sequential scan as `X_QUERY_UNINDEXED`, its fix that exact declaration (`trigramDeclaration(col)`,
129
+ exported). Ranked full-text search stays [`.search()`](#full-text-search--the-searchindex-port).
130
+
76
131
  ### Which invariants reach the database
77
132
 
78
133
  "Where expressible" is a rule, not a hedge. An invariant reports a `sql:` string or `sql: null`, and
@@ -251,15 +306,23 @@ export async function like(postId: string): Promise<void> {
251
306
  export async function nextInvoice(year: number): Promise<number> {
252
307
  return db.invoices.lockKey(`number:${String(year)}`, async (tx) => nextNumber(year, tx));
253
308
  }
309
+
310
+ // Both invoice series held for one renumbering, whichever order a caller names them in.
311
+ export async function renumber(a: number, b: number): Promise<void> {
312
+ await db.invoices.lockKeys([`number:${String(a)}`, `number:${String(b)}`], async (tx) => {
313
+ await nextNumber(a, tx);
314
+ await nextNumber(b, tx);
315
+ });
316
+ }
254
317
  ```
255
318
 
256
- | | `lock(id, (row, tx) => R, options?)` | `lockKey(key, (tx) => R, options?)` |
257
- |---|---|---|
258
- | Postgres | `select … for update`, the read path's own statement | `pg_advisory_xact_lock(hashtextextended('<table>:<tenant or ->:<key>', 0))` |
259
- | Scope | that row | one key, one table, one tenant: org A's key never blocks org B |
260
- | Absent, another tenant's, soft-deleted | `X_NOT_FOUND` | n/a |
261
- | No actor on a scoped entity | `X_TENANCY_UNSCOPED`, as a read | `X_TENANCY_UNSCOPED`, as a read |
262
- | Blank key | n/a | `X_INVARIANT` |
319
+ | | `lock(id, (row, tx) => R, options?)` | `lockKey(key, (tx) => R, options?)` | `lockKeys(keys, (tx) => R, options?)` |
320
+ |---|---|---|---|
321
+ | Postgres | `select … for update`, the read path's own statement | `pg_advisory_xact_lock(hashtextextended('<table>:<tenant or ->:<key>', 0))` | the same per key, every key in ONE statement, taken in sorted order — two callers naming overlapping keys in any order never deadlock |
322
+ | Scope | that row | one key, one table, one tenant: org A's key never blocks org B | each key as `lockKey`'s, deduplicated |
323
+ | Absent, another tenant's, soft-deleted | `X_NOT_FOUND` | n/a | n/a |
324
+ | No actor on a scoped entity | `X_TENANCY_UNSCOPED`, as a read | `X_TENANCY_UNSCOPED`, as a read | `X_TENANCY_UNSCOPED`, as a read |
325
+ | Blank key | n/a | `X_INVARIANT` | `X_INVARIANT`; so are an empty list and more than `MAX_LOCK_KEYS` (64) distinct keys — the fix is one coarser key |
263
326
 
264
327
  | Rule | Detail |
265
328
  |---|---|
@@ -267,9 +330,43 @@ export async function nextInvoice(year: number): Promise<number> {
267
330
  | Writes inside `fn` | with `{ tx }`, the rule on every write. Memory undoes only what names it |
268
331
  | Bound | no wait option. The role's `statement_timeout`. A deadlock is `X_DB_SERIALIZATION_FAILURE` |
269
332
  | Memory driver | a queue per key, reentrant within one async chain; a nested lock joins the outer one's transaction; `update(id)` and `delete(id)` wait for a row's holder, the filtered writes and `upsertAll` do not; a waiter past 5 s is `X_DB_STATEMENT_TIMEOUT`, Postgres' code, usually two locks taken in opposite order |
270
- | A hand-written `Repo` | both are optional on the contract; the handle answers `X_LOCK_UNSUPPORTED` |
333
+ | A hand-written `Repo` | all three are optional on the contract; the handle answers `X_LOCK_UNSUPPORTED`. Memory and `defineDriver` build `lockKeys` from their one-key lock, held in the same sorted order inside one transaction (`holdInOrder`, `lock-key.ts`) |
271
334
  | `crossTenant()` with no `orgId` | holds its own `<table>:-:<key>`, no org's. Name `orgId` to take that org's key |
272
335
 
336
+ ### An optimistic lock — `version`
337
+
338
+ A form open for minutes cannot hold a row lock. `entity({ version })` makes a write that read a
339
+ stale row fail instead of overwriting it, `As of 2026-11`:
340
+
341
+ ```ts
342
+ import { database, entity, integer, text, uuid } from '@ultimat3/entity';
343
+
344
+ const notes = entity('notes', {
345
+ columns: { id: uuid().primaryKey(), body: text(), lockVersion: integer().default(0) },
346
+ version: 'lockVersion',
347
+ });
348
+ const db = database({ notes });
349
+
350
+ // `lockVersion` is the one the editor read; it travels in the mutator's input.
351
+ export async function saveNote(id: string, body: string, lockVersion: number): Promise<void> {
352
+ await db.notes.update(id, { body, lockVersion });
353
+ }
354
+ ```
355
+
356
+ | Write | Rule |
357
+ |---|---|
358
+ | `update(id, patch)` | the patch must name the version (else `X_ENTITY_VERSION_INVALID`, 500). The statement is conditioned on it and increments it: `where "lock_version" = $n`, `set "lock_version" = "lock_version" + 1`. Moved since the read: `X_ENTITY_STALE` (409); absent: `X_NOT_FOUND` |
359
+ | `updateMany(rows)` | every row names its version; one stale row refuses the whole batch, nothing written |
360
+ | `updateWhere` · chain `updateAll` · `transition` · soft delete | increment it on every matched row and may not set it (`X_ENTITY_VERSION_INVALID`). Compare-and-set over a filter goes in the filter: `where({ id, lockVersion: 3 }).updateAll(patch)` |
361
+ | `upsertAll` | `onMatch: 'update'` — the default — is refused: it would overwrite rows it never read. `onMatch: 'nothing'` is allowed |
362
+ | `insert`, `insertAll`, `copyAll`, hard delete | untouched; an insert takes the column default |
363
+ | Declaration | the column is an `integer()`, not nullable, with a `.default(n)`, neither key nor tenant column — else `X_ENTITY_VERSION_INVALID` at `entity()` |
364
+
365
+ Memory, Postgres and `defineDriver` answer alike (`entity-conformance-version-lock.ts`); a
366
+ `defineDriver` store gets one compare-and-set write per row. No mutator option: the version is a
367
+ column of the row, so the input carries it and a stale submit answers 409 through any surface
368
+ (`packages/action/src/mutator-version.test.ts`).
369
+
273
370
  ## The repo
274
371
 
275
372
  A feature's `repo.ts` is the only module that touches the database, and every statement in it goes
@@ -444,6 +541,7 @@ a page later.
444
541
  | Shape | a `belongsTo` attaches the row or `null`; a `hasMany` attaches an array, empty when there are none. Always present, so "no author" and "nobody preloaded the author" cannot read the same |
445
542
  | Statements | one extra statement per named relation, resolved **concurrently** — two `preload()` calls are two statements in flight, never one after the other. Naming one relation twice is one statement |
446
543
  | Ceiling | `preload('<relation>', { max })` — the most related rows one relation may attach to one page; default 10,000 (`MAX_PRELOADED_ROWS`, the largest page a read may ask for). Past it the read is refused with `X_INVARIANT_VIOLATED`, never truncated |
544
+ | First n per parent | `preload('<relation>', { perParent: n, order?, direction? })`, a `hasMany` only (`As of 2026-11`): at most `n` related rows per parent — "the last 3 messages of each conversation" — in ONE `cross join lateral` statement per 500 parents, each reading `n` rows off an index, not one `limit(n)` read per parent. `order` is a column of the related entity, `direction` defaults to `desc`; unnamed, the related key descending. `perParent` on a `belongsTo`, an `order` without `perParent`, or `n` outside 1–10,000 is `X_INVARIANT_VIOLATED`. A repository without `latestBy` (hand-written, `defineDriver`) answers through paged `findMany` reads: the same rows, more statements |
447
545
  | Terminals | `page()`, `all()`, `one()` resolve every named relation. `count()`, `countBy()` and `plan()` do not — a count reads no row to attach one to |
448
546
  | Projection | attached after `select()`. `select()` is widened internally with the relation's own key, so a projection can drop neither the key the preload reads nor the relation it attaches — `plan().select` reports the widened list, the one that actually ran |
449
547
  | Tenancy | the page's own tenant predicate carries onto the related read only when **both** entities are scoped by a column of that same name — a value that scopes one entity is a guess on another, and a source scoped by `workspaceId` may carry an ordinary `orgId` predicate that is a filter and not its tenancy. Carrying nothing is not silence: the related read builds its own plan, so it is refused as `X_TENANCY_UNSCOPED` rather than answered with a guess |
@@ -457,11 +555,52 @@ stated rather than inferred from a loop. The other two members of the family ask
457
555
  `findById` batches a same-microtask fan-out for itself, and a `for … of` loop over a page is
458
556
  already two statements, above.
459
557
 
558
+ ## The newest row per group is `latestBy`
559
+
560
+ "The last message of each conversation" is one statement, not one `.orderBy().one()` per
561
+ conversation, `As of 2026-11`:
562
+
563
+ ```ts
564
+ import { database, entity, timestamp, uuid } from '@ultimat3/entity';
565
+
566
+ const messages = entity('messages', {
567
+ columns: {
568
+ id: uuid().primaryKey(),
569
+ orgId: uuid().tenant(),
570
+ conversationId: uuid(),
571
+ createdAt: timestamp().defaultNow(),
572
+ },
573
+ });
574
+ const db = database({ messages });
575
+
576
+ // select distinct on ("conversation_id") … order by "conversation_id", "created_at" desc, "id" desc
577
+ export const lastMessages = (orgId: string, ids: readonly string[]) =>
578
+ db.messages
579
+ .where({ orgId })
580
+ .andWhere('conversationId', 'in', ids)
581
+ .latestBy('conversationId', { order: 'createdAt' });
582
+ ```
583
+
584
+ | Property | Behavior |
585
+ |---|---|
586
+ | Rows | one per group the chain matches; a group with no row is absent. Ordered by the group, `null` last |
587
+ | Newest | `order` (required) in `direction` (default `desc`); ties go to the primary key in the same direction |
588
+ | Scope | the chain's filters, tenancy and soft-delete visibility, as `page()`. Sealed columns cannot be the group or the order |
589
+ | Bound | more than `MAX_LATEST_GROUPS` (1,000) groups is `X_INVARIANT_VIOLATED`, never truncated — the read asks for one group past the bound |
590
+ | Refused on the chain | `orderBy()`, `limit()`, `after()`: one row per group is the whole shape, and it has no cursor (`X_INVARIANT_VIOLATED`) |
591
+ | Cost | `DISTINCT ON` reads every row of the matched groups, then keeps one each. Bound the groups with `andWhere(group, 'in', …)`; for a few rows per parent over long histories, `preload(rel, { perParent })` reads `n` per key off an index |
592
+ | Drivers | Postgres and memory in one pass each (`pg-latest-by.ts`, `memory-latest-by.ts`). `Repo.latestBy` is optional: a hand-written repository or a `defineDriver` store is answered by paged `findMany` reads folded in process (`latestRows`, `latest-by.ts`) — correct, never one statement |
593
+
460
594
  ## Reading a whole table is a loop of pages
461
595
 
462
596
  A page is bounded on purpose, so reading everything is iteration — and the iteration is a terminal
463
597
  on the same chain, not something written around `page()`, `As of 2026-08`:
464
598
 
599
+ `.all()` is that one page too — 50 rows unless the chain says `.limit(n)`. When a next page existed
600
+ and the chain named no limit, a development or test process logs one warning, `entity.all.truncated`
601
+ (`ALL_TRUNCATED`), naming the entity and both ways out: `.inBatches(n)` for every row, `.limit(n)`
602
+ for one page meant. Staging and production say nothing; refusing is a break, and waits for a major.
603
+
465
604
  ```ts
466
605
  // One statement per batch, one page of rows in memory at a time.
467
606
  for await (const batch of db.posts.where({ orgId }).preload('author').inBatches(500)) {
@@ -539,6 +678,45 @@ a `number | undefined` — and the `undefined` is load-bearing.
539
678
  There is no `groupBy()` builder and no error code of its own: `countBy` is a terminal on the chain
540
679
  that already exists, over exactly the rows `count()` counts.
541
680
 
681
+ ### A filtered count and several measures, one statement
682
+
683
+ `countBy(column, { where })` counts only the rows that satisfy `where` in each group, and
684
+ `aggregate({ name: measure })` answers several measures at once, each with its own filter —
685
+ `count(*) filter (where …)`, `As of 2026-11`:
686
+
687
+ ```ts
688
+ import { database, entity, money, text, uuid } from '@ultimat3/entity';
689
+
690
+ const posts = entity('posts', {
691
+ columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), authorId: uuid(), status: text() },
692
+ });
693
+ const orders = entity('orders', {
694
+ columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), status: text(), total: money() },
695
+ });
696
+ const db = database({ posts, orders });
697
+
698
+ // Every author the chain matched, with 0 for one who has published nothing.
699
+ export const publishedPerAuthor = (orgId: string) =>
700
+ db.posts.where({ orgId }).countBy('authorId', { where: [['status', 'eq', 'published']] });
701
+
702
+ // { all: number, paid: number, revenue: MoneyValue | null } in one statement.
703
+ export const orderTile = (orgId: string) =>
704
+ db.orders.where({ orgId }).aggregate({
705
+ all: { fn: 'count' },
706
+ paid: { fn: 'count', where: [['status', 'eq', 'paid']] },
707
+ revenue: { fn: 'sum', column: 'total', where: [['status', 'eq', 'paid']] },
708
+ });
709
+ ```
710
+
711
+ | Property | Behavior |
712
+ |---|---|
713
+ | `where` | `andWhere`'s three arguments as a tuple, per filter; narrows that measure only, inside the rows the chain matched (filters, tenancy, soft delete) |
714
+ | `countBy` with `where` | a group the chain matched but no row satisfies is present with `0` — what tells it from `andWhere(…).countBy(col)`, where it is absent |
715
+ | Measures | `fn` is `'count'` (no `column`: `count(*)`; with one, its non-null values), `'sum'`, `'avg'`, `'min'`, `'max'`. At most `MAX_MEASURES` (32) |
716
+ | Answers | a `count` a number, `0` over no rows; the rest exactly what `sum()`/`avg()`/`min()`/`max()` answer — decimal text, money a `MoneyValue`, `null` over no rows. Never a float |
717
+ | Refused | before any row is read, `X_AGGREGATE_UNSUPPORTED`: an unknown function, an undeclared column or filter column, a kind with no aggregate, `avg` over money, no measures or more than 32. Two currencies under one money `sum`: `X_AGGREGATE_MIXED_CURRENCY` |
718
+ | Drivers | one statement on Postgres and memory. A `defineDriver` store composes both from the capabilities it already declares (`aggregate:countBy`, `aggregate:<fn>`): several store calls, the same answer. A hand-written `Repo` without `aggregates` answers `aggregate()` with `X_AGGREGATE_UNSUPPORTED` |
719
+
542
720
  ## A count per day is a series
543
721
 
544
722
  A chart is a count per bucket of time, in a person's zone. One statement, under every guard the
@@ -813,7 +991,39 @@ refuses it at the wire first, as a 400. `As of 2026-09-29`.
813
991
 
814
992
  Chain: `.primaryKey()` · `.nullable()` · `.unique()` · `.default(v)` · `.defaultNow()` ·
815
993
  `.onUpdateNow()` · `.references(() => other.id, { onDelete })` · `.tenant()` · `.column(name)` ·
816
- `.sealed()` on `text()` — [Sealed columns](#sealed-columns).
994
+ `.sealed()` on `text()` — [Sealed columns](#sealed-columns) · `.collate('C')` on `text()` — [below](#code-point-collation).
995
+
996
+ ### Code-point collation
997
+
998
+ `text().collate('C')` declares `collate "C"`, `As of 31.11.0`: the column orders and compares by
999
+ code point — the order the memory driver and a live window's matcher already keep. Without it
1000
+ Postgres orders by the database's collation (`en_US.utf8`: `apple` before `Banana`), which is why a
1001
+ live query ordered by such a column logs `query.live.order_collation`
1002
+ ([Queries](Queries-And-Live-Queries#live-true-requires-deterministic-bounded-sql)).
1003
+
1004
+ ```ts
1005
+ import { entity, text, uuid } from '@ultimat3/entity';
1006
+
1007
+ export const tags = entity('tags', {
1008
+ columns: {
1009
+ id: uuid().primaryKey(),
1010
+ name: text({ max: 40 }).collate('C'), // a live list may .orderBy('name')
1011
+ },
1012
+ });
1013
+ ```
1014
+
1015
+ | Rule | Where |
1016
+ |---|---|
1017
+ | `'C'` is the only collation a column may declare; another is `X_INVARIANT_VIOLATED` at `entity()` | `packages/entity/src/sealed-column.ts` (`declaredCollation`) |
1018
+ | only `text()` has `.collate()`; `enumerated()`, `url()`, `tz()`, `locale()` store text and do not | `TextColumn` in `packages/entity/src/types.ts` |
1019
+ | `x db gen` writes `collate "C"` after the type on `create table` and `add column`; declaring or dropping it on an existing column is one in-place `alter column … type text collate "C"` (or `"default"`), its reverse in `down`; a retype restates it, since Postgres resets a collation on a type change | `packages/db/src/generate-collation.test.ts` |
1020
+ | the snapshot records `collation` only when declared, so no existing snapshot moves | same |
1021
+ | drift does not read a live column's collation, as it reads no column type: a hand-set collation is not reported | `packages/db/README.md`, "A declared collation" |
1022
+
1023
+ Declaring it changes the visible order of every read of that column, not only the live one. On an
1024
+ existing table the `alter` is Postgres' `alter column … type`: an `ACCESS EXCLUSIVE` lock while every
1025
+ index on the column is rebuilt. `X_MIGRATION_LOCK_HEAVY` does not flag it — a large table wants a
1026
+ quiet window.
817
1027
 
818
1028
  **A date is not an instant.** `effective_on` is the date a rate applies, not a moment; stored as a
819
1029
  `timestamptz` it is a different date on either side of midnight for half the planet. `PlainDate`
@@ -1068,10 +1278,11 @@ export const likes = entity('likes', {
1068
1278
  ```
1069
1279
 
1070
1280
  - **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.
1071
- - **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 sets (`X_ENTITY_APPEND_ONLY`, SQLSTATE `23001`). Reading it is an ordinary, tenant-scoped, cursor-paged read: `database({ posts, postsHistory: posts.$history })`.
1281
+ - **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 })`.
1072
1282
  - **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.
1073
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.
1074
- - **A counter's write is the trigger's, not the repository's.** The WAL replicator reports it; the in-process `entity.row` event (what `x dev` on PGlite and the memory driver feed live queries from) does not, so a live view of the counter on those does not move until the parent row is written again. A counter a page shows live stays the mutator's job until that event reports trigger writes. As of 2026-11.
1284
+ - **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
+ - **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.
1075
1286
  - **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).
1076
1287
  - Drift names a missing or disabled lifecycle trigger: `X_LIFECYCLE_TRIGGER_MISSING`, its fix the statements that re-create it.
1077
1288
 
@@ -1162,7 +1373,10 @@ A store that is not Postgres — Mongo, Cassandra, a key-value store — is a `D
1162
1373
  An undeclared capability (`upsert`, `matches`, `aggregate:<kind>`, `transactions`) is
1163
1374
  `X_DRIVER_UNSUPPORTED` with `meta.capability`; a declared one with no method behind it is
1164
1375
  `X_DRIVER_CAPABILITY_MISSING` when the table opens. `lock` and `series` undeclared answer the
1165
- shipped `X_LOCK_UNSUPPORTED` / `X_ENTITY_SERIES_UNSUPPORTED`.
1376
+ shipped `X_LOCK_UNSUPPORTED` / `X_ENTITY_SERIES_UNSUPPORTED`. A child entity whose column declares
1377
+ `countedIn` is refused when `database()` builds its repository (`X_DRIVER_UNSUPPORTED`,
1378
+ `meta.capability: 'countedIn'`, `driver-counters.ts`): a custom store has no trigger and no
1379
+ repository hook, so the parent's count would never move. `As of 2026-11`.
1166
1380
 
1167
1381
  A searchable entity's version is strictly increasing per row, and a custom store advances it in
1168
1382
  its OWN write, atomically: `update(filter, patch, advance?)` writes `advance.property` per matched
@@ -514,6 +514,8 @@ export const exportMember = subjectExport({
514
514
  | children first, the subject last; one step per page of parent keys | a killed run resumes at the page it stopped on; every write is an equality on one key, so a replay changes nothing twice |
515
515
  | a loop of deleted tables needs one nullable key | it is cleared first; none is `X_SUBJECT_CYCLE` |
516
516
  | a table with no foreign key to the person is invisible | list it: `columns: { audit_copies: 'memberId' }`, then it needs a treatment too |
517
+ | a deleted or anonymized table's `<table>_history` is reached too (`As of 2026-11`) | the write records the person in one more before image, and `row_id` is no foreign key. `'delete'` removes every history row whose `before` or `after` image names the subject (`@>` on the parent's key column, tenant-scoped — so a row deleted, soft-deleted or inserted before the erase is reached too) in the parent's own step and transaction, after the write — the one delete the append-only guard lets through (`x.purge` on Postgres, `purgingHistory` in memory); `{ retain: '<why>' }` keeps and counts the same rows; `anonymize` is `X_SUBJECT_TREATMENT_INVALID`, undeclared `X_SUBJECT_TABLE_UNDECLARED`. |
518
+ | a deleted table's own delete purges the images Postgres writes into a child's history (`As of 2026-11`) | `on delete set null` or `cascade` rewrites a child row, and the child's trigger records the person's key in its before image. A child history declared `'delete'` loses those images in the parent's step and transaction (`orphansOf`, `packages/jobs/src/subject-plan.ts:341`; `packages/jobs/src/subject-erase-history.ts`). Limits: the memory driver applies no `onDelete` action, so a kept child keeps the erased key there; a child history declared `{ retain }` is counted only for writes to its own table — the images a set-null or cascade write records into it are neither purged nor counted |
517
519
  | framework data is a `targets:` entry | `authSubjectTarget` (`@ultimat3/auth`), `auditSubjectTarget` (`@ultimat3/action`, rewrites who acted, keeps the row), `storageSubjectTarget(disk, keysOf)` (`@ultimat3/storage`); `{ target, retain }` keeps one |
518
520
  | the export is one object per page per table plus `index.json` | each table's count, treatment and `retain` reason; sealed columns never leave |
519
521
  | one job per tenant | crossing tenants is the app's loop; queued job inputs and logs are out of reach (`x_jobs` ages out by `jobs-retention.ts`) |
@@ -599,7 +601,7 @@ export const refreshPostTotals = refreshView({
599
601
  | `refreshView()` | |
600
602
  |---|---|
601
603
  | Each run | `refresh materialized view [concurrently]` in one step; `tenant: 'none'` — the read path scopes the rows |
602
- | `concurrently` | readers keep the old rows meanwhile; needs a unique index on the view (`.unique()`) |
604
+ | `concurrently` | readers keep the old rows meanwhile; needs a unique index on the view (`.unique()`) over plain columns, with no `where` — a unique `expression` index is no key for it (`As of 2026-11`) |
603
605
  | Refused at declaration | a table, a plain view, `concurrently` with no unique index — `X_JOB_REFRESH_VIEW_INVALID` |
604
606
 
605
607
  ## Rebuilding a search index — `reindex()`
@@ -35,7 +35,7 @@ CHANGELOG.md` finds its bounds, and it changes on any commit.
35
35
  | A purge that a replica never hears is bounded by `ttl`, not by the next request | `As of 2026-10-10`. The purge reaches the other replicas through the invalidation broadcast. With the bus down, a replica with its own store answers its copy as a fresh hit until that copy's `ttl` (and tells an edge the ttl's remainder), then renders. `'purge'` therefore requires a `ttl` | choose the `ttl` as the longest a missed purge may last; or share one `runtime.isrStore` with a `tagFence`, where the delete is every replica's at once |
36
36
  | A bust purges by the **route's** tags | `As of 2026-10-10`. A stored `isr` page records no tags of its own, so `post:1` reaches every stored page of a route tagged `post` — one render too many per page, never one too few. Each bust reads the store's keys once; the route of each key is remembered, not re-matched [pin](https://github.com/developerz-ai/ultimate/blob/main/packages/render/src/render-isr-purge.test.ts#every%20stored%20key%20of%20the%20route%20goes%3A%20both%20locales%2C%20and%20every%20keyed%20query) | tag a route as narrowly as its data allows; a very large shared store pays one `paths()` per bust per replica |
37
37
  | A declared `isr` query parameter's **values** are unbounded | `As of 2026-10-10`. `query: ['page']` puts `page` in the key, and `?page=1` … `?page=999999` are each a key: the framework cannot know which values name a page. The store is bounded (least recently generated out first), so it thrashes rather than grows [pin](https://github.com/developerz-ai/ultimate/blob/main/packages/render/src/render-isr-query.test.ts#only%20a%20declared%20parameter%20is%20part%20of%20the%20key%2C%20and%20of%20the%20URL%20load%20is%20given) | answer `withStatus(404, …)` from `load` for a value that names nothing, and rate-limit the route at the ingress; put a small closed set in the path instead (`/blog/page/[n]` with `prerender()`) |
38
- | A `grantUpload` with a `target` is never sniffed | `As of 2026-11-02`. A presigned PUT signs `host` and the size, so on an s3 disk the uploader chooses the stored type and the bytes. `promoteAttachment` is what checks them (`X_STORAGE_TYPE_REJECTED`), and a grant with a `target` lands straight on the row's key with no promotion step. With an `uploadScanner` installed such a grant is refused outright (`X_STORAGE_TARGET_UNSCANNED`, `As of 31.0.0`), so the gap is only an app's with no scanner. Served, it is contained: `objectResponse` sandboxes a type a browser would run, and a false `image/png` is shown under `nosniff` [pin](https://github.com/developerz-ai/ultimate/blob/main/packages/storage/src/grant.test.ts#naming%20a%20target%20puts%20the%20key%20on%20the%20row%20instead%20of%20in%20pending) | grant with no `target` and call `promoteAttachment({ …, policy })`; for a targeted grant, read the head yourself with `validateStoredHead(…)` before writing the key to the row → [Storage and uploads](Storage-And-Uploads) |
38
+ | A `grantUpload` with a `target` is never sniffed | `As of 2026-11-02`. A presigned PUT signs `host` and the size, so on an s3 disk the uploader chooses the stored type and the bytes. `promoteAttachment` is what checks them (`X_STORAGE_TYPE_REJECTED`), and a grant with a `target` lands straight on the row's key with no promotion step. With an `uploadScanner` installed such a grant is refused outright (`X_STORAGE_TARGET_UNSCANNED`, `As of 31.0.0`), so the gap is only an app's with no scanner. Served, it is contained: `objectResponse` sandboxes a type a browser would run, and a false `image/png` is shown under `nosniff` [pin](https://github.com/developerz-ai/ultimate/blob/main/packages/storage/src/grant.test.ts#naming%20a%20target%20puts%20the%20key%20on%20the%20row%20instead%20of%20in%20pending) | declare the pair with `uploadFlow()` (`@ultimat3/action`, `As of 31.11.0`), which never grants a target and sniffs at `confirm`; or by hand, grant with no `target` and call `promoteAttachment({ …, policy })`. Keeping a targeted grant: read the head yourself with `validateStoredHead(…)` before writing the key to the row → [Storage and uploads](Storage-And-Uploads) |
39
39
  | A queued offline write is not bound to its principal **on the server** | `As of 2026-10`. The fence is in the page: a principal change abandons the running replay, refuses a write in flight (`X_OFFLINE_QUEUE_ABANDONED`) and wipes the queue. A second TAB whose replay is already past its store read when another tab changes the session cookie still sends its remaining entry under the new session — one entry, one in-flight pass, on a shared browser | sign out by full navigation (`signOutHeaders()` clears site data, and every boot wipes other principals' queues); do not share a browser profile between accounts with offline writes queued |
40
40
  | Presence leaves past the lease roster cap | the sweep leader ships at most 4,096 member ids on its lease (`PRESENCE_LEASE_ROSTER_LIMIT`). When the leader's node dies, members beyond that whose TTL expired before the successor's first leading pass are never announced as left. A successor cannot diff against the shared store: the expired members are already gone from it | nothing to do: each client's next beat is answered with the whole roster, so it heals within one beat (10 s by default) |
41
41
  | An **offline** scrape reads `/robots.txt` over the real network | every `fakeBrowser` / `fixtureBrowser` run takes the default `robots: 'obey'`, and the gate reads `https://<host>/robots.txt` with the platform `fetch` before the first navigation, so outside `bun test` one request still leaves the process. **The silent half is closed `As of 2026-10-04`**: an unreachable robots.txt (5xx, 429, network error, timeout) now refuses the origin with `X_SCRAPE_ROBOTS_DISALLOWED` (RFC 9309 §2.3.1.4 for 5xx, network error and timeout; refusing on `429` is Ultimate's stricter policy — the RFC calls a `4xx` unavailable), so under `bun test` the sealed network's refusal turns the run red instead of reading as allow-everything | declare the policy in the definition under test — `robots: { ignore: 'fixture host, no live origin' }` — which returns a gate that reads nothing at all. There is no boolean and no ambient off switch, by design — see [Scraping](Scraping#testing-offline) |
@@ -101,7 +101,6 @@ downstream app on Ultimate and of systems built without it; no row is a defect i
101
101
 
102
102
  | Gap | Evidence | Precedent |
103
103
  |---|---|---|
104
- | a native form's refusal answer — `setRedirect` covers success (`packages/http/src/redirect.ts`) | 234 wrapper calls in 142 files | Rails' form convention: 303 on success, 422 re-rendering the form with its errors; `flash` |
105
104
  | route-group defaults | 111 routes × ~25 repeated lines | layouts, `before_action`, controller inheritance |
106
105
  | a view-scoped lazy lookup for `t()` inside an island — the subset itself ships (`catalogSubset` / `subsetTranslator`, #710), named key by key | 94 label types, 3,092 lines of label files | lazy lookup `t('.title')` scoped to the view |
107
106
  | a server-first dialog, menu and combobox with a small enhancer | ~2,200 app-side lines; 13 catalog components at 0 imports | HTML first, a small controller second |
@@ -122,6 +121,7 @@ the release that fixed it. Upgrading is the fix, and the breaking entries are th
122
121
 
123
122
  | Gap | Fixed in | If you are pinned below that |
124
123
  |---|---|---|
124
+ | A browser's own `<form method="post">` to an action got JSON back on a refusal — `setRedirect` covered success only (deferred by plan 101: 234 wrapper calls in 142 files of one app) | **31.11.0** | `action({ native: { success, refusal? } })`: a `303` either way, the outcome in a one-read flash `useActionAnswer()` reads in `load`; a `page.tsx` form posting to an action without it is an `X_NATIVE_FORM_UNANSWERED` warning ([Actions](Actions#native-forms-native)). Below it: `if ((useRequestHeader('accept') ?? '').includes('text/html')) setRedirect(next)` in `handle` (both from `@ultimat3/http`) answers success; a refusal still answers the error page |
125
125
  | `bun run error-render` could not see a `catch (error)` binding | **8.0.0** | The gate matched a **parameter** annotated `unknown`/`any`; a `catch (error)` binding is `unknown` by inference and carries no annotation, which is how `String(error)` echoing a caller's request body into a 422 `cause:` stayed green in `packages/http/src/request.ts` through 3.0.0. `error-render` now joins `catchRenderFindings` ([`scripts/catch-render.ts`](https://github.com/developerz-ai/ultimate/blob/main/scripts/catch-render.ts)), which reads the catch binding and a `.catch((error: unknown) => …)` callback; its header lists what it still cannot see (a helper in a third file, a field laundered by another package). Below it: review every `catch` by hand — a caught value reaches a `cause:`/`fix:` only through `renderThrowable(error)` from `@ultimat3/core` |
126
126
  | The manifest did not record an admin action's `readonly` or `matching`, a scope's `count`, or a resource's permission noun | **25.0.0** | [B29](https://github.com/developerz-ai/ultimate/blob/main/docs/plans/2026/10/04/101-squeaky-clean-sweep/10-carried-backlog.md), #691. `AdminActionFact` records `readonly` and `matching` and `x manifest diff` reports the gate moving between `admin:write` and `admin:read` ([`packages/manifest/src/diff-admin.ts`](https://github.com/developerz-ai/ultimate/blob/main/packages/manifest/src/diff-admin.ts)); a scope's `count` is diffed; the permission noun reaches the diff through each admin route's `permissions` (`<noun>:read`). Below it: read them from the declaration in `apps/admin/app/admin/admin.ts` |
127
127
  | The two-platform deploy proof (milestone 11) was undemonstrated | **22.1.0** | Not a defect in what shipped: the build targets, compose files and chart all shipped, the proof did not. `.github/workflows/ci.yml`'s `deploy-proof` job (`docker/deploy-proof/run.sh`) installs a scaffolded app into kind with `x deploy --method helm` and upgrades it under mixed GET/POST load, failing on one non-2xx ([roadmap](https://github.com/developerz-ai/ultimate/blob/main/docs/idea/14-roadmap.md)). Nothing to work around below it |
@@ -1,6 +1,6 @@
1
1
  # Policies and authz
2
2
 
3
- One authz system. Authentication is Better Auth, wrapped ([Configuration](Configuration)); **authorization is ours**, because it must be identical in HTTP, WebSocket, jobs, and MCP.
3
+ One authz system. Authentication is `@ultimat3/auth` ([Auth](Auth)); **authorization is this page**, because it must be identical in HTTP, WebSocket, jobs, and MCP.
4
4
 
5
5
  ```ts
6
6
  policy: can('post:publish', ({ input, actor }) => ownsPost(actor, input.postId))
@@ -116,6 +116,60 @@ The matrix runs **outside a request**: no input, no row. A rule that reads eithe
116
116
 
117
117
  `x policy list` also names the permissions **no** action or query enforces. A grant nothing checks is a grant that does nothing, and it is invisible from any single declaration.
118
118
 
119
+ ## Scope — a policy's database filter
120
+
121
+ `scoped(policy, scope)` attaches `scope(actor) → where` to a policy, `As of 2026-11`: the
122
+ conjunction a read hands the database, so the visible rows arrive as one index-served page rather
123
+ than a JS filter over an over-fetch that leaves a viewer a short page. The policy decides exactly as
124
+ before; the JS rule stays the authority.
125
+
126
+ ```ts
127
+ import type { Actor, Policy } from '@ultimat3/policy';
128
+ import { policyScope, scoped } from '@ultimat3/policy';
129
+
130
+ interface Post {
131
+ readonly orgId: string;
132
+ readonly audience: 'public' | 'members';
133
+ }
134
+ declare const postRule: Policy<unknown, Post>;
135
+ declare const actor: Actor | null;
136
+
137
+ export const seePost = scoped(postRule, (who) =>
138
+ who === null
139
+ ? [{ column: 'audience', op: 'eq', value: 'public' }]
140
+ : [{ column: 'orgId', op: 'eq', value: who.orgId }],
141
+ );
142
+ policyScope(seePost, actor); // the frozen conditions, or undefined for an unscoped policy
143
+ ```
144
+
145
+ | `policyScope(policy, actor)` answers | Means |
146
+ |---|---|
147
+ | `undefined` | no scope declared: nothing is handed down |
148
+ | `[]` | every row (an admin): the empty conjunction |
149
+ | `[{ column, op, value? }, …]` | every condition must hold — AND only, there is no `or`. `column` is typed by the policy's row; `op` is one of `eq` `neq` `in` `gt` `gte` `lt` `lte` `is-null` `is-not-null`; `value` is always bound |
150
+
151
+ - **The scope belongs to the clause it is declared on.** `and`/`or`/`not` over a scoped policy
152
+ carry none: the conjunction of children's scopes is not the scope of `or`. Scope the outermost
153
+ policy.
154
+ - **Tenant scoping is not scope.** Tenancy stays the entity layer's (the tenant predicate every
155
+ repository applies, [below](#tenancy)); a scope narrows what one actor sees inside a tenant and
156
+ never replaces it.
157
+ - **A query read composes it**, `As of 31.11.0`: a `query({ policy: seePost, sql })` whose `sql`
158
+ returns `from()` gets each condition as a filter before the page is cut, and still runs the rule
159
+ on every row — [Queries: a scoped policy narrows the read](Queries-And-Live-Queries#a-scoped-policy-narrows-the-read).
160
+ Another `SqlSource` is `X_QUERY_SCOPE_UNCOMPOSABLE`. An action, or a repository read outside a
161
+ query, composes nothing: there `policyScope` is the read an app composes itself, e.g.
162
+ `db.posts.where({ orgId })` plus each condition as `andWhere`.
163
+ - **AND-only, by decision** (2026-11, `packages/policy/src/scope.ts`). A scope lands as query
164
+ filters, so it reaches the live matcher's shape, every provider's `RowWindow.filters` and the
165
+ entity chain, each a conjunction; an `or` group would widen all of them at once. A rule whose
166
+ visibility is a disjunction (a friend OR the author OR public, minus a block set) stays unscoped
167
+ and keeps the JS rule over what it reads.
168
+ - **Planned, not shipped:** a finding for a scope that admits other rows than its rule on the
169
+ exercise seed (`X_POLICY_SCOPE_MISMATCH`, not registered yet). Until then, a scope wider than its
170
+ rule costs rows the rule then drops — a short page again — and a narrower one hides rows the rule
171
+ would admit, silently.
172
+
119
173
  ## Tenancy
120
174
 
121
175
  Authz and tenancy are separate checks, both mandatory.
@@ -256,6 +256,22 @@ the `DownloadFile` and `await runRecording.url(input, { ctx })` the path.
256
256
 
257
257
  **A patched row lands where `order by` returns it** (`As of 2026-10`). The matcher, `from()`'s in-memory execution and the cursor fallback compare two values by the column's DECLARED kind, through `@ultimat3/entity`'s own comparator — `@ultimat3/query` has none. A `bigint()` or `decimal()` column orders by its digits (its row value is decimal text: `'9'` before `'10'`), a `uuid()` is a value whatever its case, a `timestamp()` is an instant. The kinds resolve from the entity declared on the table `from(name, …)` names; a relation no entity declares has none, and its digits compare as text — as a `text` column's do. A custom `SqlSource` calling `compareRows`, `matchesFilter` or `isAfterKey` passes `kindsOf(shape.entity)`; `compareValues` is gone.
258
258
 
259
+ **A text order is warned until it is code-point order**, `As of 31.11.0`. The matcher orders a
260
+ text value by code point; Postgres orders it by the column's collation, and on an
261
+ `en_US.utf8` cluster that is `apple` before `Banana`. A patched row then lands where the next read
262
+ does not put it, and a full window evicts the wrong row. So a live query ordered by a declared text
263
+ column — `text()`, or `enumerated()`, `url()`, `tz()`, `locale()`, which store text — not declared `.collate('C')` logs `query.live.order_collation` (`X_LIVE_ORDER_COLLATION`) at
264
+ subscribe — in development and test, once per query, never thrown; staging and production are
265
+ silent (`packages/query/src/live-collation.ts`). A refusal at subscribe is planned for `next`.
266
+
267
+ | Fix | Cost |
268
+ |---|---|
269
+ | `name: text().collate('C')` on a `text()` column, then `x db gen "<table> name collate C"` | an in-place `alter column … collate "C"`; every read of that column orders by code point, not only the live one ([Code-point collation](Entities-And-Migrations#code-point-collation)) |
270
+ | order the live read by a non-text key: `.orderBy('createdAt', 'desc').orderBy('id')` | none; the text column can still be filtered on. The only fix for `enumerated()`, `url()`, `tz()`, `locale()`: they have no `.collate()` |
271
+
272
+ Not warned: a relation no entity declares (it has no kinds), and a text primary key reached only as
273
+ the automatic `id` tiebreak.
274
+
259
275
  A page is served `order by <declared keys>, "id" asc`, and so is a live window — `As of 2026-08`,
260
276
  the initial window, the matcher's patch positions and the keyset re-read a reconnect resumes with
261
277
  are one ordering. A row tied on every declared key lands where its id puts it, not after the tie
@@ -300,6 +316,26 @@ Policy is not a subscribe-time gate that then trusts the stream.
300
316
 
301
317
  One authz system. A live query cannot become a second door into your data — that is the failure mode that killed the `allow`/`deny` generation of frameworks ([The eight primitives](The-Eight-Primitives)).
302
318
 
319
+
320
+ ## A scoped policy narrows the read
321
+
322
+ A policy built with `scoped(rule, (actor) => conditions)` ([Policies](Policies-And-Authz#scope--a-policys-database-filter))
323
+ hands its conditions to every read it guards, `As of 31.11.0` (`packages/query/src/scope-compose.ts`).
324
+ Without it the rule filters after the page is cut, so a viewer whose hidden rows precede their
325
+ visible ones gets a short page.
326
+
327
+ | What happens | Where |
328
+ |---|---|
329
+ | each condition becomes a `.compare()` filter on the `from()` builder `sql` returned, before the page is cut | the SQL text, the live shape and the provider's `RowWindow.filters`, exactly as a `.where()` would |
330
+ | the rule still runs on every row returned; a row it refuses is dropped, never served | a scope wider than its rule costs rows, never leaks them (`read-scope.test.ts`) |
331
+ | the read's cache key is the actor's, whatever `cache.scope` says | the rows are that actor's |
332
+ | a `sql` that returns a hand-written `SqlSource`, not `from()` | `X_QUERY_SCOPE_UNCOMPOSABLE` (500) on the call — never served unscoped |
333
+ | a build with `sourceFor(…, { unenforced })`, and the shared live window a sync node reads per org | no scope: there is no admitted actor to scope by. Each subscriber's rows are still filtered by the rule, as above |
334
+
335
+ Conditions are a conjunction only — no `or` group, by decision (`packages/policy/src/scope.ts`): the
336
+ builder's filters, the live matcher's shape, `RowWindow.filters` and the entity chain are all
337
+ conjunctive. A rule whose visibility is a disjunction stays unscoped and keeps the per-row filter.
338
+
303
339
  ## NULL
304
340
 
305
341
  `As of 2026-08`, one rule for the generated SQL, the in-memory source behind `from()` and the live
@@ -364,6 +400,7 @@ Fifty *counts* collapse neither way — one `count()` per row is fifty different
364
400
  | Not recorded | `explainQuery()`, `describeSql()`, the shared live window: built `unenforced`, no caller to attribute |
365
401
  | No sink installed | `X_QUERY_AUDIT_SINK_MISSING`, before the input parse |
366
402
  | The sink refuses | a denied/failed record: logged (`audit.sink.failed`), the caller gets the original error. An allowed record: the rows are withheld, `X_QUERY_AUDIT_SINK_FAILED` — a read commits nothing, so retry |
403
+ | Group commit | opt-in, `As of 31.11.0`: `postgresAuditSink({ executor, groupCommit: true })` (`@ultimat3/action`) queues each record up to 5 ms or 256 records (`{ maxRecords, maxDelayMs }` to change either) and writes the batch as one `x_audit` insert. Each call waits on its own batch, so the rule above holds per call: a failed batch is `X_QUERY_AUDIT_SINK_FAILED` (an action's, `X_AUDIT_SINK_FAILED`) on every allowed call it carried. Flushed on drain, before the pool closes. Any sink with a `writeMany(records)`: `batchedAuditSink(sink, opts)` from `@ultimat3/action/adapter` |
367
404
 
368
405
  ## Every cached query carries a tag
369
406
 
@@ -119,6 +119,15 @@ They go straight to the disk, in three calls — and **the client never names th
119
119
  | 2. browser | `uploadFile({ file, grant, onProgress })` | a PUT with real progress; `storage/upload-client.ts` is the one XHR seam in the browser |
120
120
  | 3. server, at `PUT /_storage/:disk/*key` | mounted by the framework in `x dev` and `runRole`, around `acceptSignedUpload`. Answers `201 { key }` | refuses a bad or expired signature, a key outside the actor's org, more bytes or another type than was granted, or magic bytes that contradict the type |
121
121
 
122
+ **The two server halves are one declaration: `uploadFlow()`** from `@ultimat3/action`, `As of
123
+ 31.11.0`. It returns `{ request, confirm }`, two actions — hop 1 as `request`, and `confirm` as
124
+ `promoteAttachment` onto the row, the stored object measured against `maxBytes`, sniffed against
125
+ `accept` (`X_STORAGE_TYPE_REJECTED`, left pending) and scanned when an `uploadScanner` is installed.
126
+ `request` never grants onto the row's key, so the targeted-grant gap below does not apply to it. A
127
+ doubled `confirm` answers the attached object; `attached` (write the key to the row there) runs
128
+ once. Hop 2 is unchanged — `grant` is `request`'s typed-client method: `uploadFile({ file, grant: client.requestPostCover })`. Declaration and
129
+ rules: [`@ultimat3/action` README, `uploadFlow()`](https://github.com/developerz-ai/ultimate/blob/main/packages/action/README.md#uploadflow--an-upload-as-one-declaration).
130
+
122
131
  **The mounted `PUT`** (`As of 2026-09-24`, #523) requires a signed-in actor, like the `GET`. It
123
132
  needs no permission: the grant is the authorization, and the action that minted it ran its own
124
133
  policy. The route checks the signature and the expiry, and it checks that the key is inside the
@@ -341,7 +350,7 @@ does not pass. Bytes past the window are not sniffed on any path through promoti
341
350
  | over 4,096 bytes of leading whitespace (`MAX_LEADING_WHITESPACE`), on every path | no real file opens that way, and past the window nothing is seen |
342
351
  | a disk whose `maxGetBytes` is under the window | its own `X_STORAGE_TOO_LARGE`: the ceiling bounds the range |
343
352
 
344
- A grant with a `target` has no promotion step: [Known gaps](Known-Gaps). With an `uploadScanner` installed it is refused outright, by `grantUpload` and `grantMultipart` alike (`X_STORAGE_TARGET_UNSCANNED`, 500): grant with no `target` and promote.
353
+ A grant with a `target` has no promotion step: [Known gaps](Known-Gaps). With an `uploadScanner` installed it is refused outright, by `grantUpload` and `grantMultipart` alike (`X_STORAGE_TARGET_UNSCANNED`, 500): grant with no `target` and promote — `uploadFlow()` (above) is that pair, declared once.
345
354
 
346
355
  ## Scanning uploads — the `uploadScanner` port
347
356
 
package/wiki/Upgrading.md CHANGED
@@ -224,13 +224,26 @@ A setter still on a package's `.` barrel is `X_ADAPTER_PORT_INCOMPLETE` on the `
224
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
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
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 |
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. Through 31.9.x an entity's `indexes:` cannot declare `include` or an operator class; from **31.10.0** it can (`include`, `operatorClass`, [Index key parts](Entities-And-Migrations#index-key-parts)) |
228
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
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. An app that commits the framework schema dump (`packages/db/schema/framework/`) sees `X_SCHEMA_DUMP_DRIFT` on `x_rate_limit` until it regenerates it | `x db gen` once, commit the regenerated `04_tables/x_rate_limit.sql` (now `create unlogged table … with (fillfactor=70)`); no migration |
230
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 |
231
231
  | a read whose page weighs more than `MAX_PAGE_BYTES` (64 MiB) before decoding is `X_ENTITY_PAGE_TOO_LARGE`, a 500 (**31.9.0**), on Postgres, memory and `defineDriver` alike — a test storing big rows in memory meets it too. Before, the page was decoded whole. `inBatches()` halves its batch instead of refusing, down to one row | paste the `fix:` onto that read: `.select({ … })` without the heaviest column it names, and the `.limit(n)` that fits — or `.inBatches(n)` to visit every row. A single row over 64 MiB on its own stays refused: move that value to storage |
232
232
  | `updateMany`, `copyAll` and the `{ returning: false }` forms (**31.9.0**) reach a hand-written `Repo` — a `Driver.repo()` not built with `defineDriver` — through fallbacks, as optional members: `updateMany` is one `updateWhere` per row (n statements, no duplicate-id or same-columns refusal, atomic only inside `withTransaction`), `copyAll` and a count form are `insertAll(…)` / `upsertAll(…)` counted. A `defineDriver` store needs nothing | nothing. For one statement, implement `updateMany`, `insertAllCount`, `upsertAllCount` and `copyAll` on the repository (`Repo` in `@ultimat3/entity`) |
233
233
  | `deletePlan` / `updatePlan` from `@ultimat3/entity/adapter` are the shipped names of `writeWherePlan` / `updateWherePlan` (**31.9.0**): the same arguments and refusals, plus an optional `options.where` for a chain's predicates | nothing |
234
+ | `X_SUBJECT_TABLE_UNDECLARED` for `<table>_history` (**31.10.0**, security): a `defineSubject()` that deletes or anonymizes an entity declared with `history: true` now reaches its history table, because that write records the person in one more before image. The run refuses before touching a row, and `x verify`'s `exercise` step reports it. Before, an erased person's data survived in `before`/`after` images | add the history table to `tables`: `posts_history: 'delete'` (every row whose `before` or `after` image names the subject, a row deleted before the erase included, removed in the parent's own transaction) or `posts_history: { retain: '<why>' }`. Images of people erased before the upgrade stay until removed by hand, per table: `begin; select set_config('x.purge', '<t>_history', true); delete from "<t>_history" where row_id = any(array['<id>', …]); commit;` — the ids from the images themselves, e.g. `select distinct row_id from "<t>_history" where before->>'<author_column>' = '<subject id>'` |
235
+ | `andWhere(col, 'contains', term)` on a `text()`/`char()` column is a case-insensitive substring match (**31.10.0**). Before, Postgres refused the statement (`text @> text[]`) and the memory driver compared for equality, so a test passed that production failed | where equality was meant, `andWhere(col, 'eq', term)`. Where search was meant, keep it and declare `indexes: [{ on: ['<col>'], using: 'gin', operatorClass: 'gin_trgm_ops' }]`, then `x db gen "trigram <col>"` — without it the plan sweep reports `X_QUERY_UNINDEXED` |
236
+ | `database()` over a `defineDriver` store throws `X_DRIVER_UNSUPPORTED` (`meta.capability: 'countedIn'`) for an entity whose column declares `countedIn` (**31.10.0**). Before, the parent's count silently never moved | serve that entity with `postgresDriver()` or `memoryDriver()`, or drop `countedIn` from the column and read `db.<child>.countBy('<key>')` instead |
237
+ | `registerClient()` throws `X_AUTH_CLIENT_INVALID` (422, `meta.field`) for a redirect URI, grant type, scope or resource that is empty or contains whitespace (**31.10.0**). Before, it was stored and read back as a different list | split the value into one element per item: `registerClient({ name, scopes: ['read', 'write'] })`, never `['read write']`. Rows already stored: `select client_id, redirect_uris, scopes from x_oauth_clients` and re-register any whose list is wrong |
238
+ | a `development` or `test` process logs `entity.all.truncated` (`ALL_TRUNCATED`) when `.all()` dropped a next page and its chain named no `.limit(n)` (**31.10.0**). The rows answered are unchanged: one page | `.inBatches(n)` where every row was meant; `.limit(n)` where one page was |
239
+ | a `countedIn` child write publishes an `entity.row` `update` for the parent row on memory and Postgres, PGlite in `x dev` included (**31.10.0**), so a live view of the count moves by itself | nothing. A mutator that recounted only to move a live view (`countBy` then `update`) can drop the recount |
240
+ | `AuthAdapter` gains the optional `getSessionWithUser(id)` (**31.10.0**); `postgresAuthAdapter` and `memoryAuthAdapter` implement it, taking `authenticate` from two statements to one | nothing. A hand-written adapter may add it — `{ session, user \| null }` or `null`, what `getSession` then `findUserById` answer — and run `authAdapterConformance` on it |
241
+ | an entity that adds `version: '<column>'` (**31.10.0**, opt-in) refuses `update(id)` without the version, setting it in `updateWhere`, and `upsertAll` with the default `onMatch: 'update'` — a seed's `upsertAll` included (`X_ENTITY_VERSION_INVALID`) | carry the version read: `update(id, { …patch, lockVersion: row.lockVersion })`; a seed uses `upsertAll(rows, { onConflict, onMatch: 'nothing' })` |
242
+ | a read whose policy is `scoped()` (`@ultimat3/policy`, **31.10.0**) has the scope composed into its `from()` source before the page is cut (**31.11.0**): a page that came back short because the rule dropped rows after the cut now comes back full, so a page's rows and its `nextCursor` can differ from 31.10.x. The rule still runs on every row. Such a read is cached per actor, whatever its `cache.scope`. A scoped policy on a read whose `sql` returns a hand-written `SqlSource` is `X_QUERY_SCOPE_UNCOMPOSABLE` (500) on every call | nothing for a `from()` read. Under `X_QUERY_SCOPE_UNCOMPOSABLE`: return `from(entity, (window) => repo.window(window))` from `sql`, or keep the hand-written source and declare the policy without `scoped()` |
243
+ | a `development` or `test` process logs `query.live.order_collation` (`X_LIVE_ORDER_COLLATION`) once per live query ordered by a declared text column (`text()`, `enumerated()`, `url()`, `tz()`, `locale()`) not `.collate('C')` (**31.11.0**). Nothing is refused and nothing else changes; staging and production stay silent. A refusal at subscribe is planned for `next` | for a `text()` column, declare it `text().collate('C')` and run `x db gen "<table> <column> collate C"` (an in-place `alter column … collate "C"`; the column's visible order becomes code-point order everywhere it is read), or order the live read by a non-text key: `.orderBy('createdAt', 'desc').orderBy('id')` — the only fix for `enumerated()`/`url()`/`tz()`/`locale()`, which have no `.collate()` |
244
+ | `x verify`'s `manifest` step lists `X_NATIVE_FORM_UNANSWERED` under `warnings` for each `page.tsx` `<form method="post">` posting to an action with no `native` (**31.11.0**). The step stays green; a refusal is planned for `next` | add `native: { success: (output) => '/where-it-lands' }` to that action's declaration, then `x verify --only manifest` |
245
+ | an action that declares `native` answers a refusal with a 4xx other than `X_UNAUTHENTICATED` to a browser form POST as a `303` (**31.11.0**). `X_UNAUTHENTICATED` keeps the sign-in redirect, so a protected form posted signed-out lands on sign-in as before; a sign-in action's own 401 (a wrong password) is a refusal and lands back on its form with its code. Without `native` nothing changes | nothing. A sign-in page that showed its failure some other way reads `useActionAnswer('<action>')` in its route's `load`: `outcome: 'refusal'` and the `code` the sign-in threw. Any 401 a sign-in throws must use its own code, never `X_UNAUTHENTICATED`, or it takes the sign-in redirect |
246
+ | an action that answers a browser form by sniffing `accept` itself (**31.11.0**, optional) | delete the hand-written `if (accept includes 'text/html') setRedirect(next)` from `handle` and declare `native: { success: (output) => output.next }` on the action. A `setRedirect()` still in `handle` keeps winning on success, so a sign-in's per-request `next` can stay where it is |
234
247
 
235
248
  ## 29.x → 30.0.0, entry by entry
236
249