@ultimat3/cli 31.19.0 → 31.21.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.19.0",
3
+ "version": "31.21.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.19.0",
57
- "@ultimat3/admin": "31.19.0",
58
- "@ultimat3/ai": "31.19.0",
59
- "@ultimat3/auth": "31.19.0",
60
- "@ultimat3/cache": "31.19.0",
61
- "@ultimat3/core": "31.19.0",
62
- "@ultimat3/db": "31.19.0",
63
- "@ultimat3/entity": "31.19.0",
64
- "@ultimat3/flags": "31.19.0",
65
- "@ultimat3/http": "31.19.0",
66
- "@ultimat3/i18n": "31.19.0",
67
- "@ultimat3/jobs": "31.19.0",
68
- "@ultimat3/mail": "31.19.0",
69
- "@ultimat3/manifest": "31.19.0",
70
- "@ultimat3/mcp": "31.19.0",
71
- "@ultimat3/money": "31.19.0",
72
- "@ultimat3/notify": "31.19.0",
73
- "@ultimat3/policy": "31.19.0",
74
- "@ultimat3/pwa": "31.19.0",
75
- "@ultimat3/query": "31.19.0",
76
- "@ultimat3/realtime": "31.19.0",
77
- "@ultimat3/render": "31.19.0",
78
- "@ultimat3/schema": "31.19.0",
79
- "@ultimat3/scraping": "31.19.0",
80
- "@ultimat3/seo": "31.19.0",
81
- "@ultimat3/storage": "31.19.0",
82
- "@ultimat3/testing": "31.19.0",
83
- "@ultimat3/time": "31.19.0",
56
+ "@ultimat3/action": "31.21.0",
57
+ "@ultimat3/admin": "31.21.0",
58
+ "@ultimat3/ai": "31.21.0",
59
+ "@ultimat3/auth": "31.21.0",
60
+ "@ultimat3/cache": "31.21.0",
61
+ "@ultimat3/core": "31.21.0",
62
+ "@ultimat3/db": "31.21.0",
63
+ "@ultimat3/entity": "31.21.0",
64
+ "@ultimat3/flags": "31.21.0",
65
+ "@ultimat3/http": "31.21.0",
66
+ "@ultimat3/i18n": "31.21.0",
67
+ "@ultimat3/jobs": "31.21.0",
68
+ "@ultimat3/mail": "31.21.0",
69
+ "@ultimat3/manifest": "31.21.0",
70
+ "@ultimat3/mcp": "31.21.0",
71
+ "@ultimat3/money": "31.21.0",
72
+ "@ultimat3/notify": "31.21.0",
73
+ "@ultimat3/policy": "31.21.0",
74
+ "@ultimat3/pwa": "31.21.0",
75
+ "@ultimat3/query": "31.21.0",
76
+ "@ultimat3/realtime": "31.21.0",
77
+ "@ultimat3/render": "31.21.0",
78
+ "@ultimat3/schema": "31.21.0",
79
+ "@ultimat3/scraping": "31.21.0",
80
+ "@ultimat3/seo": "31.21.0",
81
+ "@ultimat3/storage": "31.21.0",
82
+ "@ultimat3/testing": "31.21.0",
83
+ "@ultimat3/time": "31.21.0",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
@@ -1,6 +1,7 @@
1
1
  // Single responsibility: whether the `drift` step has a SQL schema to judge. Migrations, drift and
2
2
  // `x db` describe Postgres only; an app whose rows live in a `defineDriver` store owns its schema,
3
- // and the step skips it with the reason printed rather than demanding `x db gen "initial"`.
3
+ // and the step skips it with the reason printed rather than demanding `x db gen "initial"`. Also
4
+ // where the step's advice turns into a verdict: warnings on `main`, findings on `next`.
4
5
 
5
6
  import type { DriverStoreKind } from '@ultimat3/entity/adapter';
6
7
  import { driverStores } from '@ultimat3/entity/adapter';
@@ -33,11 +34,28 @@ export const nonSqlDriftSkip = (
33
34
  return msg('cli.verify.driftNonSql', { stores: custom.join(', ') });
34
35
  };
35
36
 
37
+ /**
38
+ * The `next` switch. `false` on `main`: an index nothing declares (`X_DB_INDEX_UNDECLARED`) rides
39
+ * in `warnings`, since refusing it reddens an app that passed yesterday (X_BREAKING_ON_MAIN).
40
+ * `next` sets it `true`, and the same facts are the step's findings.
41
+ */
42
+ export const REFUSE_UNDECLARED_INDEX = false;
43
+
44
+ /** One fact, in both shapes: the findings `next` refuses on, the lines `main` prints. */
45
+ export interface DriftAdvice {
46
+ readonly findings: () => Promise<readonly Finding[]>;
47
+ readonly warnings: () => Promise<readonly string[]>;
48
+ }
49
+
36
50
  export interface DriftRails {
37
51
  /** The migration and schema rails — the ones a store owning its own schema has nothing for. */
38
52
  readonly schema: () => Promise<readonly Finding[]>;
39
53
  /** The generated client against its stamp: a fact about the app's API, whatever stores rows. */
40
54
  readonly client: () => Promise<readonly Finding[]>;
55
+ /** A schema rail's advice: skipped with the schema rails, a verdict only under `refuseAdvice`. */
56
+ readonly advice?: DriftAdvice;
57
+ /** Defaults to `REFUSE_UNDECLARED_INDEX`; a test states the other branch. */
58
+ readonly refuseAdvice?: boolean;
41
59
  readonly stores?: Stores;
42
60
  }
43
61
 
@@ -47,9 +65,17 @@ export interface DriftRails {
47
65
  */
48
66
  export const driftOutcome = async (root: string, rails: DriftRails): Promise<StepOutcome> => {
49
67
  const skipped = nonSqlDriftSkip(root, rails.stores);
68
+ const advice = skipped === undefined ? rails.advice : undefined;
69
+ const refuse = rails.refuseAdvice ?? REFUSE_UNDECLARED_INDEX;
50
70
  const findings = [
51
71
  ...(skipped === undefined ? await rails.schema() : []),
72
+ ...(advice !== undefined && refuse ? await advice.findings() : []),
52
73
  ...(await rails.client()),
53
74
  ];
54
- return { ...fromFindings(findings), ...(skipped === undefined ? {} : { output: skipped }) };
75
+ const warnings = advice !== undefined && !refuse ? await advice.warnings() : [];
76
+ return {
77
+ ...fromFindings(findings),
78
+ ...(skipped === undefined ? {} : { output: skipped }),
79
+ ...(warnings.length === 0 ? {} : { warnings }),
80
+ };
55
81
  };
@@ -1,15 +1,16 @@
1
- // The X_* codes of how an app is HELD — `x doctor`'s floor, pin, env-name and row-security checks
2
- // and the `exercise` floor in `x.verify.json` — split out of `error-codes.ts` at its 500-line
1
+ // The X_* codes of how an app is HELD — `x doctor`'s floor, pin, env-name and row-security checks,
2
+ // the `exercise` floor in `x.verify.json` and the `drift` step's undeclared index — split out of `error-codes.ts` at its 500-line
3
3
  // ceiling, as `error-codes-shot.ts` was. `error-codes.ts` folds these into the CLI's one owned union
4
4
  // and registers them in its one call; nothing else imports this file.
5
5
 
6
- /** Codes `x doctor` and the `exercise` floor declare and own. */
6
+ /** Codes `x doctor`, the `exercise` floor and the `drift` step's index advice declare and own. */
7
7
  export const CLI_DOCTOR_ERROR_CODES = [
8
8
  'X_EXERCISE_UNPROVEN_ABOVE_FLOOR',
9
9
  'X_ENV_NAME_RESERVED',
10
10
  'X_FRAMEWORK_PIN_RANGE',
11
11
  'X_VERIFY_STEP_UNFLOORED',
12
12
  'X_DB_ROW_SECURITY_OFF',
13
+ 'X_DB_INDEX_UNDECLARED',
13
14
  ] as const;
14
15
 
15
16
  export type CliDoctorErrorCode = (typeof CLI_DOCTOR_ERROR_CODES)[number];
@@ -21,4 +22,5 @@ export const CLI_DOCTOR_ERROR_TITLES: Readonly<Record<CliDoctorErrorCode, string
21
22
  X_FRAMEWORK_PIN_RANGE: 'An @ultimat3/* dependency is pinned as a range',
22
23
  X_VERIFY_STEP_UNFLOORED: 'A gate step applies to this app but x.verify.json does not floor it',
23
24
  X_DB_ROW_SECURITY_OFF: 'Raw sql reaches tenant tables while database.rowSecurity is off',
25
+ X_DB_INDEX_UNDECLARED: 'Schema dump holds an index nothing declares',
24
26
  };
package/src/mcp-errors.ts CHANGED
@@ -398,6 +398,8 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
398
398
  'x db migrate --json # the fresh database has no tables yet; then x db seed --json if the app declares a seed. The moved directory (meta.aside) is kept: delete it once its rows are not needed',
399
399
  X_EXPLAIN_PRODUCTION_DATABASE:
400
400
  'env -u DATABASE_URL x queries list --json # then the same prefix on x explain <query> --json: it plans on the embedded dev database; for a copy of production data, point DATABASE_URL at a staging restore with ULTIMATE_ENV=staging',
401
+ X_DB_INDEX_UNDECLARED:
402
+ 'x verify --only drift --json # each X_DB_INDEX_UNDECLARED warning names the index: its DROP INDEX CONCURRENTLY IF EXISTS "<name>"; goes in a new hand-written migration (-- transaction: false), or declare it in the entity\'s indexes: [...] and x db gen "<change>"',
401
403
  };
402
404
 
403
405
  const isCliCode = (code: string): code is CliErrorCode =>
package/src/mcp-host.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  ROLES,
16
16
  renderFixShellArg,
17
17
  renderThrowable,
18
+ retryMemo,
18
19
  UltimateError,
19
20
  } from '@ultimat3/core';
20
21
  import type { DbClient } from '@ultimat3/db';
@@ -51,7 +52,6 @@ import { explainErrorCode } from './mcp-errors';
51
52
  import { type ShellRunInput, shellRunner, shellTests, shellVerify } from './mcp-host-shell';
52
53
  import { type UiCapabilities, uiCapabilities } from './mcp-ui';
53
54
  import { readMigrations } from './migrations';
54
- import { retryMemo } from './retry-memo';
55
55
  import { plainAppRoutes, routeRows } from './route-table';
56
56
  import type { DevServices, Env } from './runtime-bindings';
57
57
  import { resolveServices } from './runtime-bindings';
package/src/mcp-ui.ts CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
  // why: Bun exposes no path-join primitive, and the picture's directory is a path an agent opens.
12
12
  import { join } from 'node:path';
13
- import { finiteCount, UltimateError } from '@ultimat3/core';
13
+ import { finiteCount, retryMemo, UltimateError } from '@ultimat3/core';
14
14
  import type {
15
15
  UiDiffInput,
16
16
  UiDiffResult,
@@ -33,7 +33,6 @@ import { islandVerdictJson } from './island-verdict';
33
33
  import { diffShots } from './mcp-ui-diff';
34
34
  import { inspectRoute } from './mcp-ui-inspect';
35
35
  import { interactRoute } from './mcp-ui-interact';
36
- import { retryMemo } from './retry-memo';
37
36
  import type { Env } from './runtime-bindings';
38
37
  import { shotBrowserChoice } from './shot-browser';
39
38
  import { devServerFor, type ShotServer } from './shot-server';
@@ -1,7 +1,7 @@
1
- // The `drift` step's fourth rail: is the committed schema dump what the migrations produce, does
2
- // it hold what their snapshots record, and does a database loaded from it come back the same? The other three rails read files and open
3
- // nothing; this one replays the migrations on a scratch embedded database, because "what the
4
- // migrations produce" is a fact only a database can state — and so is what a view outputs.
1
+ // The `drift` step's fourth rail: is the committed dump what the migrations produce, does it hold
2
+ // what their snapshots record, and does it load back the same? Only a scratch database can state
3
+ // what migrations produce and what a view outputs. Beside it, with none: an index the dump holds
4
+ // and nothing declares (`X_DB_INDEX_UNDECLARED`), a warning on `main`.
5
5
 
6
6
  // why: Bun has no directory probe — `Bun.file().exists()` answers about a file.
7
7
  import { existsSync } from 'node:fs';
@@ -146,3 +146,77 @@ export async function checkSchemaDump(
146
146
  ...(entities === undefined ? [] : viewColumnFindings(entities, replayed.catalog)),
147
147
  ];
148
148
  }
149
+
150
+ /** One `CREATE [UNIQUE] INDEX name ON [ONLY] schema.table` of `pg_get_indexdef`, quoted only when it must be. */
151
+ const DUMP_INDEX =
152
+ /^CREATE (?:UNIQUE )?INDEX (?:"((?:[^"]|"")+)"|(\S+)) ON (?:ONLY )?(?:"(?:[^"]|"")+"|[^\s."]+)\.(?:"((?:[^"]|"")+)"|(\S+)) /gm;
153
+
154
+ const unquoted = (quoted: string | undefined, bare: string | undefined): string =>
155
+ quoted === undefined ? (bare ?? '') : quoted.replaceAll('""', '"');
156
+
157
+ interface DumpedIndex {
158
+ readonly name: string;
159
+ readonly table: string;
160
+ readonly path: string;
161
+ }
162
+
163
+ /** The app's own: `framework/` holds the tables the framework's migrations own, which it declares. */
164
+ const dumpedIndexes = (committed: readonly SchemaDumpFile[]): readonly DumpedIndex[] =>
165
+ committed
166
+ .filter((file) => file.path.startsWith('05_indexes/'))
167
+ .flatMap((file) =>
168
+ [...file.content.matchAll(DUMP_INDEX)].map((match) => ({
169
+ name: unquoted(match[1], match[2]),
170
+ table: unquoted(match[3], match[4]),
171
+ path: file.path,
172
+ })),
173
+ );
174
+
175
+ const undeclaredIndex = (index: DumpedIndex): Finding => ({
176
+ code: 'X_DB_INDEX_UNDECLARED',
177
+ cause: `the schema dump holds index "${index.name}" on table "${index.table}", which neither the newest migration snapshot nor any entity declares: every write maintains an index nothing asked for`,
178
+ fix: `DROP INDEX CONCURRENTLY IF EXISTS "${index.name}"; # a hand-written migration of its own under ${MIGRATIONS_DIR} with -- transaction: false. Meant to keep it: declare it in the "${index.table}" entity's indexes: [...], then x db gen "<change>"`,
179
+ docs: ERROR_DOCS_URL,
180
+ at: `${SCHEMA_DUMP_DIR}/${index.path}`,
181
+ });
182
+
183
+ /**
184
+ * The dump's own indexes against the newest snapshot and the entities. The replay cannot see this
185
+ * one either: a generated migration that records an index as renamed without dropping the old name
186
+ * replays into a dump holding both, and every snapshot since agrees with the entities. A registry
187
+ * that did not load answers nothing, since "declared by neither" is then not a fact; the entities
188
+ * are only asked for once the snapshot leaves an index unexplained.
189
+ */
190
+ export async function undeclaredIndexFindings(
191
+ root: string,
192
+ declared: DeclaredEntities = appEntities,
193
+ ): Promise<readonly Finding[]> {
194
+ if (!existsSync(join(root, DB_PACKAGE)) || !hasSchemaDump(root)) return [];
195
+ const migrations = await readMigrations(root);
196
+ const snapshot = migrations.findLast((migration) => migration.snapshot !== undefined)?.snapshot;
197
+ const recorded = new Set(
198
+ (snapshot?.tables ?? []).flatMap((table) => table.indexes.map((one) => one.name)),
199
+ );
200
+ const unexplained = dumpedIndexes(await readSchemaDump(root)).filter(
201
+ (index) => !recorded.has(index.name),
202
+ );
203
+ if (unexplained.length === 0) return [];
204
+ const entities = await declared(root);
205
+ if (entities === undefined) return [];
206
+ const named = new Set(entities.flatMap((entity) => entity.indexes.map((one) => one.name)));
207
+ return unexplained.filter((index) => !named.has(index.name)).map(undeclaredIndex);
208
+ }
209
+
210
+ /**
211
+ * What the `drift` step carries on `main`: advice in `StepOutcome.warnings`, never a failed step —
212
+ * a red gate on an app that passed yesterday is X_BREAKING_ON_MAIN. The refusal lands on `next`,
213
+ * where the step reports `undeclaredIndexFindings` as findings.
214
+ */
215
+ export async function undeclaredIndexWarnings(
216
+ root: string,
217
+ declared: DeclaredEntities = appEntities,
218
+ ): Promise<readonly string[]> {
219
+ return (await undeclaredIndexFindings(root, declared)).map(
220
+ (finding) => `${finding.code} ${finding.at}: ${finding.cause} — fix: ${finding.fix}`,
221
+ );
222
+ }
@@ -138,7 +138,7 @@ const authenticatorModule =
138
138
  // otherwise read as development too. \`x dev\` declares \`ULTIMATE_ENV=development\` for exactly this
139
139
  // reason, and \`bun test\` sets \`NODE_ENV=test\`, where a fixture mints its own actor.
140
140
  import { type Auth, authenticate } from '@ultimat3/auth';
141
- import { type Actor, logger, tryResolveEnvironment } from '@ultimat3/core';
141
+ import { type Actor, isSessionRefusal, logger, tryResolveEnvironment } from '@ultimat3/core';
142
142
  import { configureAuthenticator } from '@ultimat3/http';
143
143
  import { appAuth } from './auth';
144
144
  import {
@@ -161,18 +161,27 @@ export interface SessionAuthenticatorOptions {
161
161
  }
162
162
 
163
163
  /**
164
- * A session cookie is that session's user, or a refusal — never a fallback to anyone else:
165
- * \`X_SESSION_EXPIRED\` for a session past its absolute or idle expiry, \`X_UNAUTHENTICATED\` for
166
- * one that is unknown, revoked or forged, or whose user is disabled. No cookie is the development
167
- * viewer or nobody.
164
+ * A session cookie is that session's user, or nobody — never a fallback to anyone else. A session
165
+ * past its expiry, or one unknown, revoked or forged, or whose user is disabled, is a refusal
166
+ * \`authenticate()\` THROWS (\`isSessionRefusal\`: \`X_SESSION_EXPIRED\`, \`X_UNAUTHENTICATED\`), and it
167
+ * is answered \`null\`: a stale cookie is an anonymous visitor, so sign-in still opens and a live
168
+ * socket it opened is closed. Anything else it throws — a session store that is down — is not an
169
+ * answer about this visitor and propagates. No cookie is the development viewer or nobody.
168
170
  */
169
171
  export const sessionAuthenticator =
170
172
  (options: SessionAuthenticatorOptions) =>
171
173
  async (request: SessionRequest): Promise<Actor | null> => {
172
174
  const auth = options.auth();
173
175
  const token = request.cookie(auth.sessions.policy.cookieName);
174
- if (token !== null && token.length > 0) return await authenticate(auth, token);
175
- return options.development ? devAuthenticate(request) : null;
176
+ if (token === null || token.length === 0) {
177
+ return options.development ? devAuthenticate(request) : null;
178
+ }
179
+ try {
180
+ return await authenticate(auth, token);
181
+ } catch (error) {
182
+ if (isSessionRefusal(error)) return null;
183
+ throw error;
184
+ }
176
185
  };
177
186
 
178
187
  /**
@@ -283,7 +292,7 @@ unitTest('an undeclared role is answered as ANONYMOUS, and the log names what it
283
292
  const authenticatorTest =
284
293
  (): string => `// The real path and its one fallback: a session cookie is its user in every environment, a bad
285
294
  // one is refused rather than replaced, and only development answers a request with no session.
286
- import { defineAuth, login, memoryAuthAdapter, register } from '@ultimat3/auth';
295
+ import { defineAuth, login, logout, memoryAuthAdapter, register } from '@ultimat3/auth';
287
296
  import { configuredAuthenticator, resetAuthenticator } from '@ultimat3/http';
288
297
  import { expect, unitTest } from '@ultimat3/testing';
289
298
  import { DEMO_ORG_ID } from '../../shared/demo-org';
@@ -326,12 +335,27 @@ unitTest('a session cookie is the user it was issued to, in every environment',
326
335
  }
327
336
  });
328
337
 
329
- unitTest('a cookie naming no live session is refused, never answered as the viewer', async () => {
338
+ unitTest('a cookie naming no live session is nobody, never answered as the viewer', async () => {
330
339
  const auth = memoryAuth();
331
340
  const request = requestWith({ [auth().sessions.policy.cookieName]: 'forged.token' });
332
- await expect(sessionAuthenticator({ auth, development: true })(request)).rejects.toMatchObject({
333
- code: 'X_UNAUTHENTICATED',
341
+ // \`null\`, not a throw: thrown, a stale cookie was a 401 on the sign-in page itself.
342
+ expect(await sessionAuthenticator({ auth, development: true })(request)).toBeNull();
343
+ });
344
+
345
+ unitTest('a signed-out cookie is nobody, so its socket is closed on re-check', async () => {
346
+ const auth = memoryAuth();
347
+ await register(auth(), {
348
+ email: 'ada@example.com',
349
+ password: PASSWORD,
350
+ orgId: DEMO_ORG_ID,
351
+ roles: ['member'],
334
352
  });
353
+ const { token } = await login(auth(), { email: 'ada@example.com', password: PASSWORD });
354
+ await logout(auth(), token);
355
+ const request = requestWith({ [auth().sessions.policy.cookieName]: token });
356
+ for (const development of [true, false]) {
357
+ expect(await sessionAuthenticator({ auth, development })(request)).toBeNull();
358
+ }
335
359
  });
336
360
 
337
361
  unitTest('no session: the development viewer under x dev, anonymous anywhere else', async () => {
@@ -12,7 +12,7 @@ const authenticatorSource =
12
12
  // live subscribers, MCP tools) reads the actor this returns. With no session the request is
13
13
  // anonymous, everywhere: a developer signs in through \`/auth/sign-in\` like everyone else.
14
14
  import { type Auth, authenticate } from '@ultimat3/auth';
15
- import type { Actor } from '@ultimat3/core';
15
+ import { type Actor, isSessionRefusal } from '@ultimat3/core';
16
16
  import { configureAuthenticator } from '@ultimat3/http';
17
17
  import { appAuth } from './auth';
18
18
 
@@ -22,15 +22,24 @@ export interface SessionRequest {
22
22
  }
23
23
 
24
24
  /**
25
- * A session cookie is that session's user, or a refusal — never a fallback to anyone else:
26
- * \`X_SESSION_EXPIRED\` past its expiry, \`X_UNAUTHENTICATED\` for one unknown, revoked or forged.
25
+ * A session cookie is that session's user, or nobody — never a fallback to anyone else. A session
26
+ * past its expiry, or one unknown, revoked or forged, is a refusal \`authenticate()\` THROWS
27
+ * (\`isSessionRefusal\`: \`X_SESSION_EXPIRED\`, \`X_UNAUTHENTICATED\`), answered \`null\`: a stale
28
+ * cookie is an anonymous visitor, so sign-in still opens and a live socket it opened is closed.
29
+ * Anything else it throws — a session store that is down — propagates.
27
30
  */
28
31
  export const sessionAuthenticator =
29
32
  (auth: () => Auth) =>
30
33
  async (request: SessionRequest): Promise<Actor | null> => {
31
34
  const resolved = auth();
32
35
  const token = request.cookie(resolved.sessions.policy.cookieName);
33
- return token !== null && token.length > 0 ? await authenticate(resolved, token) : null;
36
+ if (token === null || token.length === 0) return null;
37
+ try {
38
+ return await authenticate(resolved, token);
39
+ } catch (error) {
40
+ if (isSessionRefusal(error)) return null;
41
+ throw error;
42
+ }
34
43
  };
35
44
 
36
45
  /** Installs the session authenticator. */
@@ -44,8 +53,9 @@ installAuthenticator();
44
53
  `;
45
54
 
46
55
  const authenticatorTest =
47
- (): string => `// A session cookie is the user it was issued to; a bad one is refused; none is nobody.
48
- import { defineAuth, login, memoryAuthAdapter, register } from '@ultimat3/auth';
56
+ (): string => `// A session cookie is the user it was issued to; a bad, expired or signed-out one is nobody, and
57
+ // so is none.
58
+ import { defineAuth, login, logout, memoryAuthAdapter, register } from '@ultimat3/auth';
49
59
  import { configuredAuthenticator, resetAuthenticator } from '@ultimat3/http';
50
60
  import { expect, unitTest } from '@ultimat3/testing';
51
61
  import { DEMO_ORG_ID } from '../../shared/demo-org';
@@ -78,15 +88,28 @@ unitTest('a session cookie is the user it was issued to', async () => {
78
88
  expect(actor?.roles).toEqual(['member']);
79
89
  });
80
90
 
81
- unitTest('a forged cookie is refused, and no cookie is anonymous', async () => {
91
+ unitTest('a forged cookie is nobody, and no cookie is anonymous', async () => {
82
92
  const auth = memoryAuth();
83
93
  const forged = requestWith({ [auth().sessions.policy.cookieName]: 'forged.token' });
84
- await expect(sessionAuthenticator(auth)(forged)).rejects.toMatchObject({
85
- code: 'X_UNAUTHENTICATED',
86
- });
94
+ // \`null\`, not a throw: thrown, a stale cookie was a 401 on the sign-in page itself.
95
+ expect(await sessionAuthenticator(auth)(forged)).toBeNull();
87
96
  expect(await sessionAuthenticator(auth)(requestWith({}))).toBeNull();
88
97
  });
89
98
 
99
+ unitTest('a signed-out cookie is nobody, so its socket is closed on re-check', async () => {
100
+ const auth = memoryAuth();
101
+ await register(auth(), {
102
+ email: 'ada@example.com',
103
+ password: PASSWORD,
104
+ orgId: DEMO_ORG_ID,
105
+ roles: ['member'],
106
+ });
107
+ const { token } = await login(auth(), { email: 'ada@example.com', password: PASSWORD });
108
+ await logout(auth(), token);
109
+ const cookie = requestWith({ [auth().sessions.policy.cookieName]: token });
110
+ expect(await sessionAuthenticator(auth)(cookie)).toBeNull();
111
+ });
112
+
90
113
  unitTest('it installs', () => {
91
114
  try {
92
115
  installAuthenticator(memoryAuth());
@@ -44,7 +44,11 @@ import { checkLockHeavyMigrations } from './migration-lock-check';
44
44
  import type { Finding } from './output';
45
45
  import { retainUnsweptFindings } from './retain-sweep';
46
46
  import { checkMigrationDrift } from './schema-drift';
47
- import { checkSchemaDump } from './schema-dump-drift';
47
+ import {
48
+ checkSchemaDump,
49
+ undeclaredIndexFindings,
50
+ undeclaredIndexWarnings,
51
+ } from './schema-dump-drift';
48
52
  import { cardRouteFindings } from './seo-cards';
49
53
  import { scanSiteMeta } from './seo-meta';
50
54
  import { quoteArg } from './shell-quote';
@@ -238,6 +242,13 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
238
242
  // registry, migrations and image (`X_APP_ROOT_NESTED`, `verify-drift-owner.ts`).
239
243
  ...(await nestedAppRootFindings(ctx.root)),
240
244
  ],
245
+ // Beside the schema rails, advice and not a verdict on `main`: an index the dump holds that
246
+ // no snapshot or entity declares (`X_DB_INDEX_UNDECLARED`). `REFUSE_UNDECLARED_INDEX`
247
+ // in `drift-store.ts` is the `next` switch that makes it a finding.
248
+ advice: {
249
+ findings: () => undeclaredIndexFindings(ctx.root),
250
+ warnings: () => undeclaredIndexWarnings(ctx.root),
251
+ },
241
252
  // The seventh: a generated client (`x client`) against its own stamp — a source document that
242
253
  // moved (`X_CLIENT_STALE`) or a body edited by hand (`X_CLIENT_EDITED`). No database.
243
254
  client: () => checkClientDrift(ctx.root),
package/wiki/Testing.md CHANGED
@@ -1484,7 +1484,7 @@ Full list: [Error codes](Error-Codes).
1484
1484
  - Never assert on wall-clock time. Advance the frozen clock.
1485
1485
  - Never let a test reach the network unmocked — it fails by design.
1486
1486
  - A flaky test is deleted or fixed the day it flakes. There is no `retry: 3`.
1487
- - Hunting an order flake: `x test unit --filter <file> -- --rerun-each=30 --randomize` — the `--` hands the rest to `bun test`.
1487
+ - Hunting an order flake: `x test unit --filter <file> -- --rerun-each=30 --randomize` — the `--` hands the rest to `bun test`. A rerun forgets the `entity()` and `job()` calls the file's module body made on its last load, so they declare again. `As of 2026-11`, an `action()`, a mail template or an OAuth provider declared at module scope still fails its second load with `X_*_DUPLICATE`. Declare those inside the test, or put the file in its own run.
1488
1488
  - Every framework package ships at least 2 tests that would catch a real regression. No `expect(true).toBe(true)`.
1489
1489
  - Tests live next to their source as `<file>.test.ts`.
1490
1490
  - A denial test per policy branch, not one happy-path test per action.
package/wiki/Upgrading.md CHANGED
@@ -282,6 +282,7 @@ A setter still on a package's `.` barrel is `X_ADAPTER_PORT_INCOMPLETE` on the `
282
282
  | the chart has six new alert rules (**31.18.0**): `UltimateErrorBudgetFastBurn` / `UltimateErrorBudgetSlowBurn` against `alerts.objective` (default 99.9), plus `UltimateJobFailures`, `UltimatePoolSaturated`, `UltimateEventLoopLag` and `UltimateMemoryNearLimit`. It also has an opt-in Grafana dashboard (`dashboard.enabled: false`). Every process on a memory-limited container now emits `process_memory_limit_bytes` | nothing; an older app chart keeps its rules. To adopt the new rules: `x g chart-alerts --force`. To add the dashboard: `x g chart-dashboard`, then set `dashboard.enabled: true` where a Grafana sidecar runs. `x doctor` lists the dashboard files while the chart lacks them. To disable one rule: `alerts: { rules: { UltimateEventLoopLag: { enabled: false } } }` |
283
283
  | the reference app's and the demo's `docker/Dockerfile` (`examples/dummy`, `dummy/social-media-clone`) now match `x new`'s template (**31.19.0**): a `manifests` stage copies every workspace `package.json` and nothing else, the `deps` stage installs from it and `bun.lock`, the runtime stage is built `FROM deps`, and it runs as `USER 1000:1000` where it said `USER bun` | nothing for an app `x new` wrote: its Dockerfile already had this shape. An app that copied either tracked file: copy a fresh scaffold's (`x new <scratch> && cp <scratch>/docker/Dockerfile docker/`). `1000` is the base image's `bun` user, so a volume owned by `bun` still opens |
284
284
  | the framework repo's `manifest` step prints `warning: X_PUBLIC_API_BREAK_UNDECLARED …` for an exported symbol whose declaration changed or that is gone with no `BREAKING —` entry naming it, and `X_PUBLIC_API_UNSCANNED` when the lock cannot be read (**31.19.0**). Report-only in 31.x: the step stays green, and only `bun run scripts/public-api.ts --strict` is red | nothing for an app. In this repo: revert the change, or land it on `next` with a `- **BREAKING —** (#N) <name> …` line under [Unreleased]; an addition is recorded with `bun run scripts/public-api.ts --write --json` |
285
+ | `x verify`'s `drift` step prints `X_DB_INDEX_UNDECLARED` as a **warning line** (**31.21.0**) for each index in the committed schema dump (`packages/db/schema/05_indexes/`) that neither the newest migration snapshot nor any entity's `indexes:` declares — typically the old name a rename migration never dropped, which every write still maintains. The step stays green; it is red on the next major, `next` | before the next major: `x verify --only drift --json`, then for each warning either drop it — a hand-written migration of its own in `packages/db/migrations/`, first line `-- transaction: false`, then the warning's `DROP INDEX CONCURRENTLY IF EXISTS "<name>";` — or keep it by declaring it in that entity's `indexes: [...]` and running `x db gen "<change>"` |
285
286
 
286
287
  ## 29.x → 30.0.0, entry by entry
287
288
 
package/src/retry-memo.ts DELETED
@@ -1,37 +0,0 @@
1
- // One in-flight attempt, shared — and a FAILED one not kept. `started ??= boot()` caches the
2
- // rejection with the value, so a Postgres that refused a connection once answered every later
3
- // call in the session with that same error and no retry was possible short of restarting the host.
4
-
5
- /**
6
- * A lazily made attempt that may be made again.
7
- *
8
- * `started()` is the half `??=` has no spelling for: it answers the attempt already in flight or
9
- * already made, and `undefined` when nobody has asked yet — so a `close()` can stop what was
10
- * booted without BOOTING one in order to stop it.
11
- */
12
- export interface RetryMemo<T> {
13
- get(): Promise<T>;
14
- started(): Promise<T> | undefined;
15
- }
16
-
17
- /**
18
- * `start` runs at most once per SUCCESS. `@ultimat3/db`'s `pgliteClient` states the rule this
19
- * generalises — "a failed boot must not be cached" — and the clearing handler is attached at
20
- * creation for the reason that matters: it therefore runs ahead of every caller's own `await`
21
- * continuation, so by the time anyone sees the rejection the slot is already empty and the next
22
- * call really does start a new attempt. Cleared inside the caller's `catch` instead, there is a
23
- * window in which a second call is handed the dead promise.
24
- */
25
- export function retryMemo<T>(start: () => Promise<T>): RetryMemo<T> {
26
- let attempt: Promise<T> | undefined;
27
- return {
28
- get(): Promise<T> {
29
- attempt ??= start().catch((error: unknown) => {
30
- attempt = undefined;
31
- throw error;
32
- });
33
- return attempt;
34
- },
35
- started: (): Promise<T> | undefined => attempt,
36
- };
37
- }