@ultimat3/cli 31.49.0 → 31.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CLAUDE.md +1 -1
  2. package/package.json +30 -30
  3. package/src/api-registration.ts +18 -1
  4. package/src/api-routes.ts +1 -0
  5. package/src/app-boundaries.ts +2 -0
  6. package/src/app-dev-imports.ts +77 -0
  7. package/src/app-load-import-chain.ts +112 -0
  8. package/src/app-load-unresolved.ts +173 -16
  9. package/src/app-load.ts +23 -7
  10. package/src/app-openapi.ts +7 -1
  11. package/src/budgets.ts +2 -1
  12. package/src/cmd-i18n.ts +33 -1
  13. package/src/codemods/engine-fs.ts +9 -2
  14. package/src/codemods/merge-drivers.ts +85 -4
  15. package/src/dev-only-imports.ts +59 -0
  16. package/src/error-codes-boundary.ts +2 -0
  17. package/src/evaluated-walk.ts +103 -0
  18. package/src/exercise-services.ts +13 -3
  19. package/src/framework-schema.ts +15 -5
  20. package/src/guard-sources.ts +1 -2
  21. package/src/index.ts +2 -0
  22. package/src/mcp-errors.ts +3 -1
  23. package/src/messages-upgrade.ts +4 -0
  24. package/src/module-imports.ts +26 -15
  25. package/src/page-navigation.ts +5 -2
  26. package/src/page-route.ts +75 -0
  27. package/src/pwa-artifacts.ts +1 -1
  28. package/src/retained-assets-boot.ts +1 -1
  29. package/src/runtime-assets-site.ts +2 -2
  30. package/src/runtime-assets.ts +1 -1
  31. package/src/runtime-render-document.ts +1 -2
  32. package/src/scan-ways.ts +145 -0
  33. package/src/site-asset-routes.ts +2 -2
  34. package/src/site-assets.ts +5 -158
  35. package/src/sw-precache-plan.ts +1 -1
  36. package/src/templates/guard-raw-motion.ts +96 -0
  37. package/src/templates/guard-released-forms.ts +4 -1
  38. package/src/templates/scaffold-repo.ts +1 -1
  39. package/src/test-only-shipped.ts +29 -2
  40. package/src/test-shards.ts +20 -8
  41. package/src/upgrade-coverage-ratchet.ts +95 -0
  42. package/src/upgrade-gate.ts +31 -11
  43. package/src/upgrade-report.ts +14 -0
  44. package/src/verify-checks.ts +7 -3
  45. package/src/verify-e2e.ts +21 -3
  46. package/src/workspace-checks.ts +4 -1
  47. package/wiki/Actions.md +64 -2
  48. package/wiki/Auth.md +6 -2
  49. package/wiki/CLI-Reference.md +8 -2
  50. package/wiki/Client-Navigation.md +34 -4
  51. package/wiki/Configuration.md +2 -1
  52. package/wiki/Entities-And-Migrations.md +12 -2
  53. package/wiki/Home.md +2 -2
  54. package/wiki/I18n.md +1 -1
  55. package/wiki/Interface-Rules.md +3 -1
  56. package/wiki/Known-Gaps.md +1 -1
  57. package/wiki/MCP-And-AI.md +41 -9
  58. package/wiki/Notify.md +4 -2
  59. package/wiki/Outbound-HTTP.md +53 -2
  60. package/wiki/Policies-And-Authz.md +1 -1
  61. package/wiki/Realtime.md +14 -6
  62. package/wiki/Routes-And-Render-Modes.md +1 -1
  63. package/wiki/Static-Assets.md +5 -3
  64. package/wiki/Testing.md +82 -3
  65. package/wiki/Theming.md +6 -3
  66. package/wiki/Troubleshooting.md +1 -1
  67. package/wiki/UI-Components.md +1 -0
  68. package/wiki/Upgrading.md +2 -0
@@ -15,6 +15,11 @@ export interface ShippedPackage {
15
15
  readonly dir: string;
16
16
  /** Package-relative (`src/index.ts`), and may be a glob (`src/icons/glyphs/*.ts`). */
17
17
  readonly entries: readonly string[];
18
+ /**
19
+ * The `files` negations, without their `!` (`src/link-login.ts`): a module one matches is not in
20
+ * the tarball, so it ships nothing whoever imports it.
21
+ */
22
+ readonly excluded?: readonly string[];
18
23
  }
19
24
 
20
25
  export interface TestOnlyModule {
@@ -29,7 +34,12 @@ export interface TestOnlyModule {
29
34
  * field: a module the manifest names is shipped on purpose, whichever field names it.
30
35
  */
31
36
  export function entryPatternsOf(manifest: unknown): readonly string[] {
32
- const text = JSON.stringify(manifest ?? null);
37
+ // A `files` negation names what the tarball leaves out, never an entry it ships.
38
+ const text = JSON.stringify(manifest ?? null, (key, value: unknown) =>
39
+ key === 'files' && Array.isArray(value)
40
+ ? value.filter((entry) => typeof entry !== 'string' || !entry.startsWith('!'))
41
+ : value,
42
+ );
33
43
  const found = [...text.matchAll(/(?:\.\/)?(src\/[\w./*-]+?\.tsx?)(?![\w.])/g)];
34
44
  return [...new Set(found.map((match) => match[1] ?? ''))].sort();
35
45
  }
@@ -135,18 +145,35 @@ export function testOnlyModules(
135
145
  pkg.entries.map((entry) => new Bun.Glob(`packages/${pkg.dir}/${entry}`)),
136
146
  ]),
137
147
  );
148
+ // A negation names a file or a directory (`!src/held/`): match the pattern and what is under it.
149
+ const excludedGlobs = new Map(
150
+ packages.map((pkg) => [
151
+ pkg.dir,
152
+ (pkg.excluded ?? []).flatMap((pattern) => {
153
+ const base = `packages/${pkg.dir}/${pattern.replace(/\/+$/, '')}`;
154
+ return [new Bun.Glob(base), new Bun.Glob(`${base}/**`)];
155
+ }),
156
+ ]),
157
+ );
158
+ const isExcluded = (path: string): boolean => {
159
+ const dir = /^packages\/([^/]+)\/src\//.exec(path)?.[1];
160
+ return (excludedGlobs.get(dir ?? '') ?? []).some((glob) => glob.match(path));
161
+ };
138
162
  const referrers = new Map<string, ReadonlySet<string>>();
139
163
  for (const path of sources.keys()) {
140
164
  const dir = /^packages\/([^/]+)\/src\//.exec(path)?.[1];
141
165
  const globs = dir === undefined ? undefined : entryGlobs.get(dir);
142
166
  if (globs === undefined || !path.endsWith('.ts') || isGenerated(path)) continue;
167
+ if (isExcluded(path)) continue;
143
168
  if (isTest(path) || isFixture(path) || globs.some((glob) => glob.match(path))) continue;
144
169
  const from = new Set([...(imports.get(path) ?? []), ...(named.get(baseName(path)) ?? [])]);
145
170
  from.delete(path);
146
171
  if (from.size > 0) referrers.set(path, from);
147
172
  }
148
173
  const testOnly = new Set(referrers.keys());
149
- const live = (path: string): boolean => !isTest(path) && !isFixture(path) && !testOnly.has(path);
174
+ // An excluded file is not in the tarball, so what only it imports ships for no one's sake.
175
+ const live = (path: string): boolean =>
176
+ !isTest(path) && !isFixture(path) && !isExcluded(path) && !testOnly.has(path);
150
177
  for (let changed = true; changed; ) {
151
178
  changed = false;
152
179
  for (const path of testOnly) {
@@ -64,6 +64,7 @@ import type { TestFile } from './test-select';
64
64
  import { loadTimings, SLOWEST_KEPT, slowestOf } from './test-timings';
65
65
  import { allSkippedFinding, failingFiles } from './test-verdict';
66
66
  import { BATCH_FILES_PER_WORKER, SHARED_BATCH_FILES_PER_WORKER } from './test-workers';
67
+ import { appE2eRun, drivesBrowser, type E2eRun, isAppRoot } from './verify-e2e';
67
68
  import type { TestType } from './verify-tests';
68
69
 
69
70
  /**
@@ -340,6 +341,15 @@ export async function runShards(options: RunShardsOptions): Promise<CommandResul
340
341
  isolatedRun(options) ? BATCH_FILES_PER_WORKER : SHARED_BATCH_FILES_PER_WORKER,
341
342
  )
342
343
  : [files];
344
+ // The e2e pass runs as the gate's `e2e` step does: in an app with a browser, under the e2e
345
+ // preload that spawns the app (`verify-e2e.ts`). Elsewhere its browser cases skip, as there.
346
+ const launch =
347
+ pass.type === 'e2e' && (await drivesBrowser(isAppRoot(options.root), options.env ?? Bun.env));
348
+ const passRun = (command: readonly string[]): E2eRun =>
349
+ launch
350
+ ? appE2eRun({ root: options.root, command, env: envOverrides })
351
+ : { command, env: envOverrides };
352
+ const passEnv = passRun([]).env;
343
353
  const result = await runBatches({
344
354
  runner: options.runner,
345
355
  batches,
@@ -347,16 +357,18 @@ export async function runShards(options: RunShardsOptions): Promise<CommandResul
347
357
  workers: pass.workers,
348
358
  ...(options.lease === undefined ? {} : { lease: options.lease }),
349
359
  argsFor: (batch, width) =>
350
- testArgs({
351
- files: batch,
352
- workers: width,
353
- ...(options.passthrough === undefined ? {} : { passthrough: options.passthrough }),
354
- ...(options.isolate === undefined ? {} : { isolate: options.isolate }),
355
- timings: join(options.root, TEST_TIMINGS_FILE),
356
- }),
360
+ passRun(
361
+ testArgs({
362
+ files: batch,
363
+ workers: width,
364
+ ...(options.passthrough === undefined ? {} : { passthrough: options.passthrough }),
365
+ ...(options.isolate === undefined ? {} : { isolate: options.isolate }),
366
+ timings: join(options.root, TEST_TIMINGS_FILE),
367
+ }),
368
+ ).command,
357
369
  options: {
358
370
  cwd: options.root,
359
- ...(Object.keys(envOverrides).length === 0 ? {} : { env: envOverrides }),
371
+ ...(Object.keys(passEnv).length === 0 ? {} : { env: passEnv }),
360
372
  },
361
373
  });
362
374
  batchCount += batches.length;
@@ -0,0 +1,95 @@
1
+ // A hop's coverage ratchet: a gate whose `unit` step says `X_COVERAGE_FLOOR_STALE` — the tree
2
+ // covers more than `x.verify.json` states, a codemod's test among the causes — gets the floor
3
+ // raised to what that run measured, never lowered, and `unit` judged again. Written into the
4
+ // hop's diff and reported, never silently.
5
+
6
+ // why: Bun exposes no path-join primitive; `x.verify.json` sits at the app root.
7
+ import { join } from 'node:path';
8
+ import { t } from '@ultimat3/schema';
9
+ import { COVERAGE_BAR, COVERAGE_FIELD, floorFor } from './coverage-floor';
10
+ import { msg } from './messages';
11
+ import { statedCoverage } from './upgrade-coverage';
12
+ import { documentIn } from './upgrade-document';
13
+ import type { HopGate } from './upgrade-gate';
14
+ import { VERIFY_FLOOR_FILE } from './verify-floor';
15
+
16
+ const STALE = 'X_COVERAGE_FLOOR_STALE';
17
+ const UNIT = 'unit';
18
+
19
+ interface Numbers {
20
+ readonly lines: number;
21
+ readonly funcs: number;
22
+ }
23
+
24
+ /** What the report carries: the floor before, the one written, and the run that measured it. */
25
+ export interface HopCoverageRatchet {
26
+ readonly file: string;
27
+ readonly measured: Numbers;
28
+ readonly from: Numbers;
29
+ readonly to: Numbers;
30
+ }
31
+
32
+ type Verify = HopGate['verify'];
33
+
34
+ const MEASURED = t.object({
35
+ data: t.object({ coverage: t.object({ unit: t.object({ lines: t.number, funcs: t.number }) }) }),
36
+ });
37
+
38
+ /** Whether the gate's `unit` step said its floor is stale. */
39
+ export const staleUnitFloor = (verify: Verify): boolean =>
40
+ verify.findings.some((finding) => finding.step === UNIT && finding.code === STALE);
41
+
42
+ /** The `unit` step's measurement off a verify document; undefined when it carries none. */
43
+ export function measuredUnit(stdout: string): Numbers | undefined {
44
+ const parsed = MEASURED.safeParse(documentIn(stdout));
45
+ if (parsed.issues !== undefined) return undefined;
46
+ const { lines, funcs } = (parsed.value as { data: { coverage: { unit: Numbers } } }).data.coverage
47
+ .unit;
48
+ return { lines, funcs };
49
+ }
50
+
51
+ /**
52
+ * Each number to the larger of the stated floor and the measured whole percent — the stale
53
+ * finding's own fix — so no floor ever falls. A floor that reaches the bar drops its `why`, as
54
+ * that fix says. Null when nothing rises, or the app states no floor to raise.
55
+ */
56
+ export async function raiseCoverageFloor(
57
+ root: string,
58
+ measured: Numbers,
59
+ ): Promise<HopCoverageRatchet | null> {
60
+ const stated = await statedCoverage(root);
61
+ if (stated === undefined) return null;
62
+ const from = { lines: stated.floor.lines, funcs: stated.floor.funcs };
63
+ const to = {
64
+ lines: Math.max(from.lines, floorFor(measured.lines)),
65
+ funcs: Math.max(from.funcs, floorFor(measured.funcs)),
66
+ };
67
+ if (to.lines === from.lines && to.funcs === from.funcs) return null;
68
+ const { why, ...raw } = stated.payload[COVERAGE_FIELD] as Record<string, unknown>;
69
+ const cleared = to.lines >= COVERAGE_BAR && to.funcs >= COVERAGE_BAR;
70
+ const coverage = cleared ? { ...raw, ...to } : { ...raw, ...to, why };
71
+ const next = { ...stated.payload, [COVERAGE_FIELD]: coverage };
72
+ await Bun.write(join(root, VERIFY_FLOOR_FILE), `${JSON.stringify(next, null, 2)}\n`);
73
+ return { file: VERIFY_FLOOR_FILE, measured: { ...measured }, from, to };
74
+ }
75
+
76
+ /**
77
+ * The gate's verdict with `unit` replaced by its re-run. Green only when `unit` was the one red
78
+ * step, its re-run passed, and no finding sits outside every step.
79
+ */
80
+ export function rejudgedVerify(verify: Verify, unit: Verify): Verify {
81
+ const others = verify.findings.filter((finding) => finding.step !== UNIT);
82
+ const failedOthers = verify.failed.filter((name) => name !== UNIT);
83
+ const ok =
84
+ unit.ok &&
85
+ failedOthers.length === 0 &&
86
+ verify.failed.includes(UNIT) &&
87
+ others.every((finding) => finding.step !== undefined);
88
+ return {
89
+ ...verify,
90
+ ok,
91
+ summary: msg('cli.upgrade.coverageRejudged', { summary: verify.summary, unit: unit.summary }),
92
+ failed: unit.ok ? failedOthers : verify.failed,
93
+ findings: [...others, ...unit.findings],
94
+ };
95
+ }
@@ -1,7 +1,7 @@
1
1
  // A hop's gate, run by the CLI the hop just installed: codemods, manifest, doctor, missing guards,
2
- // a Bun-floor hop's coverage, exercise, verify (`upgrade-gate-codemods.ts`, `upgrade-guards.ts`).
3
- // Never in this process: the installed CLI may be majors older, so each answer is read as a
4
- // foreign document (`local-cli.ts`), and one that will not parse is never green.
2
+ // a Bun-floor hop's coverage, exercise, verify, a stale coverage floor raised (`upgrade-gate-*`,
3
+ // `upgrade-guards.ts`, `upgrade-coverage-ratchet.ts`). Never in this process: the installed CLI may
4
+ // be majors older, so each answer is a foreign document (`local-cli.ts`); unparsed is never green.
5
5
 
6
6
  // why: Bun exposes no path-join primitive; the installed bin is assembled from the app root.
7
7
  import { join } from 'node:path';
@@ -13,6 +13,13 @@ import { exerciseReportStamp } from './exercise-floor-report';
13
13
  import { LOCAL_CLI_BIN } from './local-cli';
14
14
  import type { CoverageRebaseline, HopCoverage } from './upgrade-coverage';
15
15
  import { rebaselineCoverage, statedCoverage } from './upgrade-coverage';
16
+ import type { HopCoverageRatchet } from './upgrade-coverage-ratchet';
17
+ import {
18
+ measuredUnit,
19
+ raiseCoverageFloor,
20
+ rejudgedVerify,
21
+ staleUnitFloor,
22
+ } from './upgrade-coverage-ratchet';
16
23
  import { documentIn } from './upgrade-document';
17
24
  import type { HopExerciseFloor } from './upgrade-exercise-floor';
18
25
  import { ratchetExerciseFloor } from './upgrade-exercise-floor';
@@ -140,6 +147,11 @@ export interface HopGate {
140
147
  readonly exercise: HopExercise;
141
148
  /** The exercise figures the hop wrote into `x.verify.json` as its ratchet; null when none. */
142
149
  readonly exerciseFloor: HopExerciseFloor | null;
150
+ /**
151
+ * The coverage floor raised to what the gate's `unit` run measured, on its `X_COVERAGE_FLOOR_STALE`
152
+ * — `verify` is then the verdict with `unit` re-run. Absent when nothing was raised.
153
+ */
154
+ readonly coverageRaised?: HopCoverageRatchet;
143
155
  readonly verify: {
144
156
  readonly ok: boolean;
145
157
  readonly summary: string;
@@ -305,14 +317,21 @@ export async function runHopGate(input: {
305
317
  // The installed gate's own list first: the steps owed to CI are steps that CLI has. None owed
306
318
  // (every one of its steps named) is that CLI's full gate, run and reported as one.
307
319
  const notRun = only === undefined ? undefined : await installedNotRun(installed, only);
308
- const verify =
309
- only === undefined || notRun === undefined || notRun.length === 0
310
- ? readVerify(await installed(['verify', '--json']))
311
- : {
312
- ...readVerify(await installed(['verify', '--only', only.steps.join(','), '--json'])),
313
- only: only.steps,
314
- notRun,
315
- };
320
+ const full = only === undefined || notRun === undefined || notRun.length === 0;
321
+ const ran = await installed(
322
+ full ? ['verify', '--json'] : ['verify', '--only', only.steps.join(','), '--json'],
323
+ );
324
+ let verify: HopGate['verify'] = full
325
+ ? readVerify(ran)
326
+ : { ...readVerify(ran), only: only.steps, notRun };
327
+ let coverageRaised: HopCoverageRatchet | null = null;
328
+ const measured = staleUnitFloor(verify) ? measuredUnit(ran.stdout) : undefined;
329
+ if (measured !== undefined) coverageRaised = await raiseCoverageFloor(root, measured);
330
+ if (coverageRaised !== null) {
331
+ onStage('coverage');
332
+ const unit = readVerify(await installed(['verify', '--only', 'unit', '--json']));
333
+ verify = rejudgedVerify(verify, unit);
334
+ }
316
335
  return {
317
336
  codemods,
318
337
  superseded,
@@ -322,6 +341,7 @@ export async function runHopGate(input: {
322
341
  coverage,
323
342
  exercise,
324
343
  exerciseFloor,
344
+ ...(coverageRaised === null ? {} : { coverageRaised }),
325
345
  verify,
326
346
  };
327
347
  }
@@ -145,6 +145,19 @@ export const humanLines = (
145
145
  funcs: Math.floor(gate.coverage.measured.funcs * 10) / 10,
146
146
  }),
147
147
  ]),
148
+ ...(gate?.coverageRaised === undefined
149
+ ? []
150
+ : [
151
+ msg('cli.upgrade.coverageRaised', {
152
+ file: gate.coverageRaised.file,
153
+ fromLines: gate.coverageRaised.from.lines,
154
+ fromFuncs: gate.coverageRaised.from.funcs,
155
+ toLines: gate.coverageRaised.to.lines,
156
+ toFuncs: gate.coverageRaised.to.funcs,
157
+ lines: Math.floor(gate.coverageRaised.measured.lines * 10) / 10,
158
+ funcs: Math.floor(gate.coverageRaised.measured.funcs * 10) / 10,
159
+ }),
160
+ ]),
148
161
  ...(gate === undefined || gate.exerciseFloor === null
149
162
  ? []
150
163
  : [
@@ -220,6 +233,7 @@ export const report = (
220
233
  doctorWarnings: gate?.doctorWarnings ?? [],
221
234
  exercise: gate?.exercise ?? null,
222
235
  exerciseFloor: gate?.exerciseFloor ?? null,
236
+ coverageRaised: gate?.coverageRaised ?? null,
223
237
  verify: gate?.verify ?? null,
224
238
  scripts,
225
239
  then,
@@ -10,6 +10,7 @@ import type { MetaIssue } from '@ultimat3/seo';
10
10
  import { llmsDescriptionIssues, validateMeta } from '@ultimat3/seo';
11
11
  import { checkAgentsMd } from './app-agents-md';
12
12
  import { readAppSources } from './app-boundaries';
13
+ import { devImportWarnings } from './app-dev-imports';
13
14
  import { envExampleFindings } from './app-env';
14
15
  import { loadApp } from './app-load';
15
16
  import { appManifest } from './app-manifest';
@@ -125,18 +126,21 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
125
126
  // second time (`guard-sources.ts`).
126
127
  //
127
128
  // A report-only guard's findings ride as warnings, as the filesize band does: listed, never red.
129
+ // So does a development entry a role loads (`app-dev-imports.ts`).
128
130
  async run(ctx) {
129
131
  const sources = await readAppSources(ctx.root);
130
132
  const guards = await guardReport(ctx.root, sources);
133
+ const warnings = [
134
+ ...guards.warnings.map(guardWarningLine),
135
+ ...(await devImportWarnings(ctx.root)),
136
+ ];
131
137
  return {
132
138
  ...fromFindings([
133
139
  ...(await appBoundaryFindings(ctx.root, sources)),
134
140
  ...guards.findings,
135
141
  ...(await hostFindings(ctx, 'boundaries')),
136
142
  ]),
137
- ...(guards.warnings.length === 0
138
- ? {}
139
- : { warnings: guards.warnings.map(guardWarningLine) }),
143
+ ...(warnings.length === 0 ? {} : { warnings }),
140
144
  };
141
145
  },
142
146
  },
package/src/verify-e2e.ts CHANGED
@@ -7,7 +7,10 @@
7
7
  // `x.verify.json` requires `e2e` and ran nothing for want of a browser is red by `judgeE2eBrowser`,
8
8
  // with the command that installs one.
9
9
 
10
- import { ERROR_DOCS_URL } from '@ultimat3/core';
10
+ // why: Bun ships no synchronous existence check, and `isAppRoot` answers inside a sync predicate.
11
+ import { existsSync } from 'node:fs';
12
+ import { join } from 'node:path'; // why: Bun exposes no path-join primitive.
13
+ import { APP_CONFIG_FILE, ERROR_DOCS_URL } from '@ultimat3/core';
11
14
  import { CHROME_PATH_ENV, chromeCandidates, findChrome } from '@ultimat3/scraping/cdp';
12
15
  import { E2E_ROOT_ENV } from '@ultimat3/testing';
13
16
  import type { ExecResult } from './exec';
@@ -61,11 +64,26 @@ export async function withE2eApp(
61
64
  },
62
65
  run: (e2e: E2eRun) => Promise<ExecResult>,
63
66
  ): Promise<ExecResult> {
64
- const chrome = input.isApp ? await findChrome(input.hostEnv) : undefined;
65
- if (chrome === undefined) return run({ command: input.command, env: input.env });
67
+ if (!(await drivesBrowser(input.isApp, input.hostEnv))) {
68
+ return run({ command: input.command, env: input.env });
69
+ }
66
70
  return run(appE2eRun({ root: input.root, command: input.command, env: input.env }));
67
71
  }
68
72
 
73
+ /** Whether `root` is an app: its `app.config.ts` is what the e2e preload boots. */
74
+ export const isAppRoot = (root: string): boolean => existsSync(join(root, APP_CONFIG_FILE));
75
+
76
+ /**
77
+ * Whether an e2e run drives a browser: an app, on a machine with one. The ONE answer
78
+ * `x verify`'s `e2e` step and `x test`'s e2e pass launch on, so the two never disagree.
79
+ */
80
+ export async function drivesBrowser(
81
+ isApp: boolean,
82
+ hostEnv: Readonly<Record<string, string | undefined>>,
83
+ ): Promise<boolean> {
84
+ return isApp && (await findChrome(hostEnv)) !== undefined;
85
+ }
86
+
69
87
  /** The floored e2e step that ran nothing because this machine has no browser to drive. */
70
88
  export const E2E_BROWSER_MISSING = 'X_VERIFY_E2E_BROWSER_MISSING';
71
89
 
@@ -442,7 +442,10 @@ export async function checkPackageShape(
442
442
  }
443
443
  if (record.private !== true) {
444
444
  findings.push(...(await fixtureReach(root, dir, manifest)));
445
- shipped.push({ dir, entries: entryPatternsOf(manifest) });
445
+ const excluded = filesOf(manifest)
446
+ .filter((entry) => entry.startsWith('!'))
447
+ .map((entry) => entry.slice(1));
448
+ shipped.push({ dir, entries: entryPatternsOf(manifest), excluded });
446
449
  }
447
450
  facts.push({
448
451
  dir,
package/wiki/Actions.md CHANGED
@@ -57,7 +57,7 @@ Declared one per file in a feature's `actions/` (`actions/publish-post.ts`, what
57
57
  | `mcp.description` | `string` | no | the tool description an agent reads, and the OpenAPI `summary`. Contract text, so it stays outside `t()` — `openapi.json` must not depend on a locale. Write it for a stranger |
58
58
  | `mcp.visibleTo` | `readonly string[]` | no | roles that may see the projected tool; a caller whose role is not named gets ToolNotFound, never Forbidden — the policy still decides every call |
59
59
  | `rateLimit` | `{ limit: number \| (({ ctx }) => number \| Promise<number>); windowMs: number }` | no | `limit` may be resolved **per call** from `ctx` (the tenant's plan, read by the app), before any bucket is touched; a resolver answering `NaN`, `0`, `Infinity` or a non-number is `X_RATE_LIMIT_INVALID`, never allow-all. A per-call limit publishes as `rateLimit: null` + `rateLimitPerCall: { windowMs }` in `describe()` and `x-ultimate.rateLimit.limit: 'per-call'` in `openapi.json`. Spent **inside `invoke`**, so the HTTP route, the MCP tool, the in-app agent's tool call and `.job()` draw on ONE bucket — the third call to a `limit: 2` action is `X_RATE_LIMITED` whichever surface it came through; a direct in-process call spends nothing. Keyed actor → org → IP; counted in `@ultimat3/http`'s installed store — the `rateLimitStore` adapter port, filled by the boot on every role, `postgresRateLimitStore` unless `apps/<app>/runtime.ts` names one ([Adapters](Adapters#ratelimitstore)). Over HTTP the refusal is `429` + `Retry-After` and `RateLimit-*`, and the route is not also capped by the `default` bucket; the same `toBucket` conversion feeds `openapi.json`, so the published numbers are the enforced ones. `/mcp` additionally buckets by verb class (`MCP_RATE_LIMITS`, read 120/min, write 20/min per token) |
60
- | `meter` | `{ name, period: 'hour' \| 'day' \| 'month', limit, warnAt?, onWarn? }` | no | a durable per-period allowance — see [Usage meters](#usage-meters-meter). Drawn on **every** surface, `server` included, after the policy and before `handle`; spent, `X_METER_EXCEEDED` (429) |
60
+ | `meter` | `{ name, period: 'hour' \| 'day' \| 'month', limit, warnAt?, onWarn? }` | no | a durable per-period allowance — see [Usage meters](#usage-meters-meter); an amount measured after the work is [`drawMeter`](#programmatic-draws-drawmeter). Drawn on **every** surface, `server` included, after the policy and before `handle`; spent, `X_METER_EXCEEDED` (429) |
61
61
  | `idempotent` | `boolean` | no — **required `true` on a `mutator`** | marks the action safe to retry with an `Idempotency-Key` header — over MCP, the tool's optional `idempotencyKey` argument. Inside a transaction the Postgres store settles the record with the write's own `COMMIT`, so a rollback never leaves a `settled` record behind. A field core redacts by name (`apiKey`, `password`, `*Token`…) or a `Secret` is stored as `[redacted]`, and the replay of such an answer is `X_IDEMPOTENT_REPLAY_REDACTED` |
62
62
  | `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)) |
63
63
  | `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` |
@@ -129,6 +129,66 @@ export const callTool = action({
129
129
  | contract diff | breaking when a call pattern the old meter admitted is refused: a meter introduced, a lower limit, a longer period not covering the old one at full use (100/day → month needs ≥ 3,100), a rename (`meta.meter` is on the wire), a move to or from a per-call limit. A shorter period at the same limit admits MORE (100/day → 100/hour): additive, as are a higher limit and a removed meter. `warnAt` is internal. `As of 2026-11` |
130
130
  | tests | the app preload resets the meter store at every file boundary, as it does the rate-limit store: a test file never resets it itself |
131
131
 
132
+ ### Programmatic draws: `drawMeter`
133
+
134
+ Work measured after the fact — tokens a model spent, bytes exported, rows synced — is drawn with `drawMeter(ctx, { meter, period, amount, limit, key })` from `@ultimat3/action`, inside the handler that measured it. Same counters, same store, same caller as `meter:`. `As of 2026-11`.
135
+
136
+ ```ts
137
+ import { action, drawMeter, t } from '@ultimat3/action';
138
+ import { allow } from '@ultimat3/policy';
139
+
140
+ const PLAN_TOKENS = new Map([['org-free', 100_000]]);
141
+ const tokensFor = (orgId: string | undefined) => PLAN_TOKENS.get(orgId ?? '') ?? 0;
142
+ // The app's own model client, whatever it is: it answers the run's id, its text and its usage.
143
+ declare const model: {
144
+ complete(text: string): Promise<{ id: string; text: string; usage: { totalTokens: number } }>;
145
+ };
146
+
147
+ export const summarise = action({
148
+ input: t.object({ text: t.string }),
149
+ output: t.object({ summary: t.string, used: t.number.int() }),
150
+ policy: allow(),
151
+ // Admission, before the model runs: a caller with no token allowance — anonymous, or on a plan
152
+ // without one — is refused here, or every call would bill the provider and record nothing.
153
+ meter: {
154
+ name: 'summaries',
155
+ period: 'day',
156
+ limit: ({ ctx }) => (tokensFor(ctx.actor.orgId) > 0 ? 1_000 : 0),
157
+ },
158
+ handle: async ({ input, ctx }) => {
159
+ // The handler does the work, so it measures the usage: never a count or an id the caller sent,
160
+ // which would let any member spend the tenant's allowance without running anything.
161
+ // Accounting after the fact, NOT a spend cap: the model has run before the draw is judged, so a
162
+ // tenant past its tokens still costs one run per admitted call, refused here and unrecorded.
163
+ // Bound that with the admission meter's call count and the model's own max-tokens setting.
164
+ const run = await model.complete(input.text);
165
+ const drawn = await drawMeter(ctx, {
166
+ meter: 'tokens',
167
+ period: 'day',
168
+ amount: run.usage.totalTokens,
169
+ limit: ({ ctx }) => tokensFor(ctx.actor.orgId),
170
+ key: run.id, // the run's own id: a retry of this draw for the same run counts once
171
+ });
172
+ return { summary: run.text, used: drawn.used }; // also: limit, replayed, resetsAt
173
+ },
174
+ });
175
+ ```
176
+
177
+ | Use | When |
178
+ |---|---|
179
+ | `meter:` on the action | the unit is **the call**, known before the handler runs: refused before any work starts — also the admission gate in front of a costly handler, a limit of 0 for a caller with no allowance |
180
+ | `drawMeter` | the unit is an **amount known only after the work**, or one action draws several meters. It records and refuses what was spent; it cannot stop work already done, so it bounds spend only together with a pre-work gate (a `meter:`, a per-call cap on the work) |
181
+
182
+ | Rule | What happens |
183
+ |---|---|
184
+ | amount | a positive safe integer, added whole or not at all: an amount that would pass `limit` counts nothing and throws `X_METER_EXCEEDED` (429, the same `meta` and `Retry-After`). One larger than the whole limit fits no period: its refusal says so, names no `retryAfterSeconds` (no `Retry-After`) and is `retry: 'terminal'`, so a job dead-letters it instead of waiting out a reset. `limit` judges new charges: a remembered key replays even after its limit drops below its amount |
185
+ | key | required, 1–255 chars, no NUL or lone surrogate (Postgres `text` cannot hold either as written): the unit of work's own id, never one the caller made up. A second draw under it — a retry, a duplicate on another replica, a parallel one — adds nothing and answers `replayed: true`. Remembered for the period it counted in and the next, so a retry just after the reset still counts once; a lagging replica's draw counts in, and is remembered by, the counter's period. A refused draw leaves no key. Replicas share keys only through a shared store: `memoryMeterStore()` remembers per process, and either bound ends that early: `maxDrawKeys` (default 200,000 across every counter, the period before dropped first) or `maxKeys`, whose eviction of a counter takes its keys with it. A durable guarantee is the Postgres store's |
186
+ | counter | a `meter:` with the same name and period counts on the same counter; units are the app's to keep consistent |
187
+ | transaction | the draw is written outside the caller's transaction and stays counted if it rolls back — retry with the same `key` |
188
+ | store | the installed `MeterStore` with `amount` and `drawKey` on `MeterDraw`, declaring `keyedDraws: true` (one that does not is `X_METER_INVALID` before it is drawn on: a store written before keyed draws would count one call and never replay): memory in one process, `x_meter` + `x_meter_key` in Postgres (the counter row locked, then the key claimed under it). A store of your own passes `meterStoreConformance` |
189
+ | no warning | `warnAt`/`onWarn` are `meter:`'s; read `used` and `limit` off the answer |
190
+ | malformed | a bad name, period, amount, key or resolved limit is `X_METER_INVALID`, its fix naming the `drawMeter` call |
191
+
132
192
  ## Streaming: `stream:` and an async generator
133
193
 
134
194
  An action that answers in pieces declares `stream: <chunk schema>` and writes `handle` as `async *handle({ input, ctx })`: each `yield` is a chunk, the `return` is the output.
@@ -194,6 +254,7 @@ export const load = async (): Promise<{ readonly answer: ActionAnswer | null }>
194
254
  | `static` / `isr` pages read `null` | a shared document is rendered as nobody, with no inbound cookie |
195
255
  | outside a request (the `llms.txt` build runs `load` with none) reads `null`, never `X_NO_REQUEST` | no request, no answer |
196
256
  | translate on `code` and `issues[].rule` with `t()` | the flash carries no prose, so no locale |
257
+ | a field's text reaches its declared type | a form posts text; the route coerces it toward `input` as a query route coerces a query string — `ok=on` is `true` for `t.boolean`, `count=7` is `7`, one value fills a `t.array`, the last of a repeated scalar wins (a hidden `false` before its checkbox). A JSON body is never coerced. `As of 2026-11` |
197
258
  | 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 |
198
259
 
199
260
  **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`.
@@ -243,7 +304,8 @@ There is **one execution path**. HTTP, MCP, jobs, and direct server calls differ
243
304
  | Key | Effect |
244
305
  |---|---|
245
306
  | `http.pathStyle` | `'resource'` (default — every existing URL stays) or `'readable'`: `signIn` → `/api/sign-in`, `health` → `/api/health`. A browser states nothing: the server stamps a non-default style into every document (`<meta name="ultimate-path-style">`) and `rpc({ baseUrl: '' })`, `useMutation` and the outbox replay derive under it. A caller with no document — a script, another service — passes `rpc({ baseUrl, pathStyle: 'readable' })`; the wrong one is answered 404 `X_CONTRACT_DRIFT` naming the style served and the action's real path, never a bare `X_ROUTE_NOT_FOUND`. The module scan evaluates `apps/web/api/index.ts` first, so a module-level `derivePath(name)` anywhere else sees the declared style; one evaluated earlier (inside the index's own imports) is refused at the declaration, `X_ACTION_PATH_DERIVED_EARLY` — derive inside the function that uses it |
246
- | `http.mounts[]` | `{ prefix: '/v1', scopes, resolveToken, rateLimit?, openapi? }` — a second door onto a cut of the same routes. Only `Authorization: Bearer` authenticates there (a session cookie reaches nothing, so no CSRF proof is needed); a primitive outside the token's scopes answers **404** like MCP's unknown tool; no/invalid token **401** with `WWW-Authenticate: Bearer`; a per-token `rateLimit` answers `RateLimit-*` and **429** + `Retry-After`, and it **replaces** the `default` bucket on the mount's routes (no `rateLimit`, `default` stands; a route's own bucket and the tenant allowance still apply). A `Link: rel="successor-version"` names the mounted path, and is dropped when the successor is outside this token's cut. `scopes` is the map `defineAppMcp` takes; `resolveToken` the same resolver. `/api/create-case` → `/v1/create-case`, `/_x/query/case-list` → `GET /v1/case-list` |
307
+ | `http.mounts[]` | `{ prefix: '/v1', scopes, resolveToken, rateLimit?, openapi?, tenant? }` — a second door onto a cut of the same routes. Only `Authorization: Bearer` authenticates there (a session cookie reaches nothing, so no CSRF proof is needed); a primitive outside the token's scopes answers **404** like MCP's unknown tool; no/invalid token **401** with `WWW-Authenticate: Bearer`; a per-token `rateLimit` answers `RateLimit-*` and **429** + `Retry-After`, and it **replaces** the `default` bucket on the mount's routes (no `rateLimit`, `default` stands; a route's own bucket and the tenant allowance still apply). A `Link: rel="successor-version"` names the mounted path, and is dropped when the successor is outside this token's cut. `scopes` is the map `defineAppMcp` takes; `resolveToken` the same resolver. `/api/create-case` → `/v1/create-case`, `/_x/query/case-list` → `GET /v1/case-list` |
308
+ | `http.mounts[].tenant` | `{ arg, resolve, list }` — the shape `defineAppMcp({ tenant })` takes, with MCP's three outcomes. The token resolves to a person; every call to a mounted primitive names its tenant in the query string, `?org=org_a`, read after the per-token allowance (an exhausted token is **429** before its tenant is read) and before the pipeline's tenant-aware rate limit, the body and the policy, never from the body; `resolve({ person, value })`'s actor is the caller, so policy, the tenant allowance and a meter see one org per call. None named: **400** `X_BEARER_TENANT_REQUIRED`, fix `GET /v1/tenants`. One the person is not in: the **404** a primitive outside the token's scopes gets, byte for byte. `resolve` threw, or answered no actor: **500** `X_BEARER_TENANT_UNRESOLVED`. `GET <prefix>/tenants` answers `{ tenants }` from `list({ person })` to any valid token, and is the exception: no scope, no tenant; a listed value that `isTenantValue` (`@ultimat3/http`) refuses — not a string, empty, over 256 characters (code points), or holding a lone surrogate — is **500** `X_BEARER_TENANT_LIST_INVALID`. A successor link keeps the tenant the call named. The mount's document requires the parameter on every primitive operation (keeping a read's own schema for it) and adds the `tenants` path beside any operation already there. `As of 2026-11-23` |
247
309
  | `http.mounts[].openapi` | a file (`'openapi.v1.json'`) `x manifest` writes with only the cut, bearer-secured; `x verify` refuses it stale or missing. Each operation's `security` is `[{ bearer: ['<its scope>'] }]` — the one scope of `scopes` that names it (also `x-ultimate.scope`) — and `components.securitySchemes.bearer` lists every scope with the operations it unlocks, in its `description` and as `x-ultimate.scopes` (`{ scope: [names] }`). `As of 22.12`; before, every operation said `bearer: []` |
248
310
  | `openapi` | `{ title, version, description, servers, sessionCookie }` — any key makes `openapi.json` complete: `info`, `servers`, `securitySchemes` (`cookie`, plus `bearer` with a mount), `401` + `429` (with `Retry-After`) on every operation its route authenticates, `RateLimit-*` on rate-limited ones. Absent, the bytes are unchanged |
249
311
 
package/wiki/Auth.md CHANGED
@@ -214,6 +214,7 @@ const approved = await verifyPasskeyEvidence(evidence, { rpId: 'example.com', or
214
214
  | checked, every ceremony | `clientDataJSON` type, the origin against the declared list exactly (no cross-origin iframe), `rpIdHash`, **UP and UV** (user verification is required, never preferred), the signature with the STORED key's algorithm |
215
215
  | challenge | 32 random bytes, stored as its sha256 in `x_passkey_challenges` with a TTL, consumed by one `DELETE … RETURNING` — single-use across the fleet, never a process map. Unknown, spent and late are one code: `X_PASSKEY_CHALLENGE_EXPIRED` |
216
216
  | counter | a signature counter that did not move forward is a cloned authenticator (`X_PASSKEY_INVALID`); both zero is an authenticator that keeps none, allowed. Advanced compare-and-set |
217
+ | label | `renamePasskey(auth, { userId, id, label: 'Work laptop' })` names it — right after `register`, or later — `null` clearing it, `null` answered for an id `userId` does not hold (`As of 2026-11`). 1-64 characters after trimming, then no control character or lone surrogate, else `X_PASSKEY_LABEL_INVALID`. `PasskeyCredential.label` is absent for none. An adapter of your own without the optional `renamePasskey` member is `X_PASSKEY_RENAME_UNSUPPORTED` |
217
218
  | registration | `attestation: 'none'` — the statement is parsed, not trusted; a credential id already registered to anyone is `X_AUTH_WRITE_FAILED`; a challenge issued to one account never registers onto another |
218
219
  | sign-in | the session is `mfaSatisfied`: a user-verified passkey is possession plus the device's PIN or biometric |
219
220
  | step-up challenge | `SHA-256("ultimate.passkey.step-up.v1\0" ‖ nonce ‖ len ‖ digest ‖ userId)` — never supplied by a caller. A proof for other bytes, or none, is `X_PASSKEY_STEP_UP_REQUIRED` |
@@ -226,6 +227,7 @@ const approved = await verifyPasskeyEvidence(evidence, { rpId: 'example.com', or
226
227
  |---|---|
227
228
  | TOTP + recovery codes | `enrolTotp`, `saveTotpSecret`, `generateRecoveryCodes`. The secret is **sealed at rest** under the app's master key and a plaintext one is refused, never read (`X_MFA_SECRET_UNSEALED`; `x auth seal-mfa` seals rows from before); a recovery code is consumed in one statement, so it works once. A password proven with a factor outstanding is `X_MFA_REQUIRED`, whose `meta.challenge` is a sealed five-minute credential; `completeMfa(auth, challenge, code)` finishes the sign-in, meters the guess against the same lockout buckets a password guess spends, and refuses a spent code on every replica (`x_totp_steps`, installed by the boot) |
228
229
  | email verification, password reset, any other mailed credential | `defineVerificationPurpose({ name, template, ttlMs, identifier? })` → `{ issue, consume }` (`As of 2026-11`); `emailVerification` and `passwordReset` are its two built-in instances, and `issueVerification` / `consumeVerification` take any declared name. A token is consumed only when its hash matches, so a wrong guess cannot burn the victim's live link, and one purpose's token never consumes another's. A name declared twice or with no template is `X_VERIFICATION_PURPOSE_INVALID` at boot; an undeclared one at the call is `X_VERIFICATION_PURPOSE_UNKNOWN` (400). `VerificationPurpose` is `string`: a `switch` over it needs a default arm. The mail is sent through an injected `MailSender` ([Mail](Mail)) |
230
+ | sign-in by mailed link | `signInWithLink(auth, { purpose, identifier, token, signUp? })` (`As of 2026-11`): consumes a link issued under a purpose declared `signIn: true` (`defineVerificationPurpose`) and answers what `login()` answers. TOTP enrolled: `X_MFA_REQUIRED` with the sealed challenge and no session, finished by `completeMfa`. The link is spent first, so it is good for one attempt; a wrong token leaves it live. No account: refused, or created verified and passwordless when the call declares `signUp`. A disabled account, and one that never verified its address, are refused. Recovery requires an app-owned flow that proves the inbox, clears all credentials while disabled and atomically checks ownership before reopening, coordinated with every administrative disable. `updateUser` and `enableUser` do not supply that check. `'email-verify'`, `'password-reset'` and any declared purpose not marked `signIn: true` are not sign-in purposes (`X_CONFIG_INVALID`); an undeclared name is `X_VERIFICATION_PURPOSE_UNKNOWN` |
229
231
  | API keys — how an agent authenticates | `issueApiKey` → `ult_<env>_<id>_<secret>`, shown once; `verifyApiKey` + `apiKeyActor` give a `kind: 'agent'` actor whose scopes are the key's and never the owner's roles (`X_API_KEY_INVALID`). A key is its owner's credential: a missing or disabled owner refuses it on the next use, a wildcard scope (`*`, `<resource>:*`) is refused at issue, and an owned key keeps only the scopes its owner's grants cover — pass `grantsOf` to expand roles ([`packages/auth/README.md`](https://github.com/developerz-ai/ultimate/blob/main/packages/auth/README.md)); a key with no `userId` is unchanged. `apiKeyResolver(() => store)` is both as the `resolveToken` a bearer mount and `defineAppMcp()` take: `{ actor, scopes }` for a live key, one `null` for every wrong one, and a store fault left a throw. In a test the store is `memoryAuthAdapter()` |
230
232
  | service-to-service | `verifyWorkloadToken` reads a Kubernetes service-account token, a SPIFFE JWT-SVID or a cloud IMDS token (they are all one JWT); `actorFromService` gives a `kind: 'service'` actor. The returned `WorkloadToken` carries `raw`, the whole decoded payload, read only after every check held. mTLS is the mesh's job |
231
233
  | an external issuer's bearer (`As of 2026-11`) | `jwtBearerResolver({ keys, issuers, audience, requiredScope?, accept?, actorOf })` — `apiKeyResolver`'s twin for JWTs, the `resolveToken` a bearer mount and `defineAppMcp()` take. `keys` is a thunk read when a token arrives (no discovery at import); `accept(raw)` is the app's own claim check after the signature; `actorOf(token)` builds the actor. Every refusal — signature, issuer, audience, expiry, scope, `accept`, and a key set that cannot be read — is `null` plus one `auth.jwt_bearer.refused` log line naming the check, never a claim's value. The mount answers that `null` as `401 X_UNAUTHENTICATED` |
@@ -285,8 +287,9 @@ const resolveToken = oauthBearerResolver(oauth, { actor: (grant) => actorFor(gra
285
287
  | consent | the page calls `readRequest(url, { callerKey })` (`callerKey`: the request's address) → `{ client, scopes, resource, redirectUri }` or a refusal; a metadata-document client carries `client.host`, its `client_id`'s host, beside the `name` its own document chose — show the host, since the name is the client's to write (`As of 2026-11-19`); 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) |
286
288
  | device | the verification page calls `readDevice({ userCode, key })`, `approveDevice` / `denyDevice`; `key` is the caller's bucket — 10 misses lock it (`X_ACCOUNT_LOCKED`) |
287
289
  | `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 |
288
- | `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 |
289
- | `revoke({ subject, clientId? })` · `purge({ before })` | immediate; `purge` is the app's `task` to schedule, nothing here runs on a timer. `purge` also deletes a self-registered client (a `d_` id, minted by `/oauth/register`) created before the refresh idle window that no grant, code or device code names; its next call is `invalid_client` and an MCP client re-registers. A client from `registerClient` (`c_`), and any registered before `As of 2026-11-19`, is never reaped |
290
+ | `resolve(token)` | `{ grantId, subject, scopes, clientId, resource } \| null` — `grantId` is the grant the token was issued under — a user's consent, or a `client_credentials` client's own — the same across every refresh rotation (`As of 2026-11-24`). `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 |
291
+ | `grants({ subject, clientId? })` | the subject's live grants, oldest first: `{ grantId, clientId, scopes, resource, createdAt, refreshedAt }[]` — not revoked, and holding a stored token neither expired nor retired, so an abandoned consent or a grant whose tokens all passed their stored expiry is not listed. It needs an existing, unrevoked grant row and reads stored token expiry and retirement, not the current refresh policy: after a lifetime is shortened, or a client is denied refresh, its grant can stay listed while its row and an unexpired, unretired token remain — until that stored expiry, or sooner if `purge` removes the row. Each entry is a copy (`As of 2026-11-24`). A store without `liveGrants` (one of the app's own) is `X_AUTH_GRANTS_UNSUPPORTED` (`As of 2026-11-23`) |
292
+ | `revoke({ subject, clientId? })` · `revokeGrant({ subject, grantId, clientId? })` · `purge({ before })` | immediate; `revokeGrant` ends that one grant alone, refresh tokens included, and answers 0 for an id another subject (or another client than the one named) holds — the same answer as an unknown id (`As of 2026-11-23`); two racing calls on one grant count it once, through the store's optional `revokeLiveGrant(id, at)`, which answers `true` only for the write that ended it; the memory and Postgres stores implement it, and a store without it (an app's own) is counted on its read (`As of 2026-11-24`). `grants` and `revokeGrant` are optional in the `AuthorizationServer` type only, so an app's own implementation still compiles: call them as `server.grants?.(…)`; `authorizationServer()` always sets both; `purge` is the app's `task` to schedule, nothing here runs on a timer. `purge` also deletes a self-registered client (a `d_` id, minted by `/oauth/register`) created before the refresh idle window that no grant, code or device code names; its next call is `invalid_client` and an MCP client re-registers. A client from `registerClient` (`c_`), and any registered before `As of 2026-11-19`, is never reaped |
290
293
 
291
294
  | Rule | Held by |
292
295
  |---|---|
@@ -300,6 +303,7 @@ const resolveToken = oauthBearerResolver(oauth, { actor: (grant) => actorFor(gra
300
303
  | `registerClient` refuses an empty or whitespace-holding list value, before a secret is minted (`X_AUTH_CLIENT_INVALID`) | `authorization-server-register-client.test.ts` |
301
304
  | `resource` (RFC 8707) binds the grant; one not in `resources` is `invalid_target` | `authorization-server-request.test.ts`, `oauth-bearer-resolver.test.ts` |
302
305
  | tokens are opaque and stored hashed, never a JWT, so `revoke` holds on the next lookup | `token-endpoints.test.ts` |
306
+ | `revokeGrant({ subject, grantId })` ends one grant and leaves its sibling on the same client refreshing; a rotation keeps the id; another subject's id revokes nothing | `authorization-server-grants.test.ts`, `authorization-server-postgres.test.ts` |
303
307
  | 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` |
304
308
  | every metadata-document fetch is metered (`X_ACCOUNT_LOCKED` past 10 a minute): per `callerKey`'s network (`ipKey`: IPv4 whole, IPv6 per /64), or — when the consent page names none — on ONE shared bucket, so an unkeyed page is throttled as one caller | `authorization-server-clients.test.ts` |
305
309
  | `client_credentials`: confidential only, no refresh token, subject is the client | `grant-client-credentials.test.ts` |
@@ -799,7 +799,12 @@ declaration and say so in the output. **`x test live` and `x test e2e` obey the
799
799
  `As of 2026-08-27`** — they did not, so `x test live --workers 8` ran eight processes over the very
800
800
  files `x verify` ran one over. `--workers` is accepted there and clamps to 1. That clamp read the
801
801
  POSITIONAL, so the bare `x test --workers 8` still widened over the same files until 2026-09; the
802
- selection is now partitioned by each file's own type. The default width is
802
+ selection is now partitioned by each file's own type. `x test`'s e2e pass also LAUNCHES as the
803
+ gate's `e2e` step does, `As of 2026-11`: in an app root with a browser (`CHROME_PATH`, or one
804
+ `x doctor` finds) it runs under `@ultimat3/testing`'s e2e preload, which spawns the app, with the
805
+ device zone `America/Los_Angeles` — before, `x test e2e` never opened a browser and every
806
+ browser-backed case skipped. With no browser both skip those cases alike, and under
807
+ `E2E_BROWSER_REQUIRED=1` those cases refuse instead of skipping, in both. The default width is
803
808
  a memory budget, `As of 2026-11-07`: `max(2.75 GiB, 25% of RAM)` (`BUDGET_RULE`) at 1.25 GiB a worker
804
809
  (`WORKER_BYTES`, `GATE_BUDGET_FLOOR` and `GATE_BUDGET_SHARE` in
805
810
  `packages/cli/src/test-workers.ts`), at most one per core — the paragraph under `x verify` above.
@@ -872,7 +877,7 @@ $ x verify --json
872
877
  "summary":"1 of 21 steps failed — 3 skipped: e2e, contract-diff, roadmap","steps":[
873
878
  {"name":"budgets","ok":false,"durationMs":812,"skipped":false,"findings":[
874
879
  {"code":"X_BUDGET_EXCEEDED","cause":"/pricing ships 61.2kb of JS (minified, uncompressed) over a 40kb budget via site/pricing/page.tsx -> islands/post-form-04f75f18.js; charged: /islands/post-form-04f75f18.js 50123 B, inline scripts 855 B",
875
- "fix":"edit apps/web/site/pricing/page.tsx — set budget: { js: '62kb' } with // measured: 62682 B (x build --target static) — why: <the function it buys> directly above it; or x routes --json for the chain and move the heavy import behind hydrate: 'interaction'",
880
+ "fix":"edit apps/web/site/pricing/page.tsx — set budget: { js: '62kb' } with // measured: 62682 B (x build --target static) — why: <the function it buys> directly above it, then x manifest (x.manifest.json carries the budget); or x routes --json for the chain and move the heavy import behind hydrate: 'interaction'",
876
881
  "docs":"https://github.com/developerz-ai/ultimate/wiki/Error-Codes",
877
882
  "at":"apps/web/site/pricing/page.tsx",
878
883
  "meta":{"jsBytes":62682,"charged":[{"url":"/islands/post-form-04f75f18.js","bytes":50123}],"inlineJsBytes":855}}]}],
@@ -1840,6 +1845,7 @@ A dry run refuses exactly what the real run would, then stops before step 4 —
1840
1845
  | `guards.baselined` | `[{ name, findings }]`, absent when empty, `As of 2026-11-15`: a guard the tree breaks, kept anyway — its measured count merged into `x.verify.json` as `"guardBaseline": { "<name>": n }` (beside the app's keys; a baseline the app already wrote for it, or a floor that is not a JSON object, is never touched) and kept only when the installed CLI's `boundaries` then finds no more than before. Also in `installed[]`. `findings: null` stays withheld |
1841
1846
  | `coverage` | a hop that moved the Bun floor re-measures unit coverage (`x verify --only unit`); only when that measurement is `X_COVERAGE_BELOW_FLOOR` is the `x.verify.json` `coverage` floor moved to it, the number that fell alone, with a dated `why`: `{ file, measured, from, to, why }`. `null` when nothing moved |
1842
1847
  | `exerciseFloor` | `{ file, written }`: the `exercise` keys (`unprovenMax`, `statementsMax` ≥ 100) the hop's own `x exercise` measured, written into an `x.verify.json` that stated none, so the hop stays green and the floor only falls. A key the app already wrote is never touched; `null` when nothing was written |
1848
+ | `coverageRaised` | `As of 2026-11-20`: `{ file, measured, from, to }` when the gate's `unit` step said `X_COVERAGE_FLOOR_STALE` (the tree covers more than its floor, a codemod's new test among the causes): each `x.verify.json` `coverage` number is set to the larger of the stated floor and the whole percent that run measured, never lowered (a floor reaching 95 drops its `why`), then `x verify --only unit` re-runs and `verify` is the verdict with `unit` replaced by that run. `null` when nothing rose |
1843
1849
  | `manifest` | `{ ok, findings[] }`. A failure does not stop the gate |
1844
1850
  | `exercise` | `{ reported, ok, findings[] }` from the hop's own `x exercise --json`, listed (and printed) before the gate's findings; each `fix` pastes as written. `reported: false`: the hop's CLI answered no exercise document — unknown, never a finding |
1845
1851
  | `verify` | `{ ok, summary, failed[], findings[], only?, notRun? }`, each finding `{ step?, code, cause, fix, at? }`. `only[]` and `notRun[]` only under `--only`: the steps run, and the gate's steps this hop did not run |