@ultimat3/cli 31.46.0 → 31.47.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 (100) hide show
  1. package/CLAUDE.md +1 -1
  2. package/README.md +1 -1
  3. package/package.json +29 -29
  4. package/src/affected.ts +3 -2
  5. package/src/app-config-load.ts +8 -5
  6. package/src/app-mcp.ts +2 -5
  7. package/src/app-runtime.ts +4 -4
  8. package/src/cmd-cache.ts +8 -4
  9. package/src/cmd-deploy-compose.ts +11 -12
  10. package/src/cmd-deploy-helm.ts +5 -8
  11. package/src/cmd-exercise-spec.ts +2 -2
  12. package/src/cmd-exercise.ts +7 -19
  13. package/src/cmd-new.ts +4 -3
  14. package/src/cmd-planned.ts +11 -76
  15. package/src/cmd-shot-matrix.ts +3 -2
  16. package/src/cmd-token.ts +11 -3
  17. package/src/codemods/ci-weekly-schedule.ts +61 -0
  18. package/src/codemods/index.ts +2 -0
  19. package/src/codemods/vendored-guards.ts +3 -5
  20. package/src/codemods/verify-floor-skips.ts +4 -6
  21. package/src/codemods/verify-floor-steps.ts +4 -3
  22. package/src/db-seed.ts +3 -2
  23. package/src/dispatch.ts +2 -11
  24. package/src/duplicate-packages.ts +4 -4
  25. package/src/exercise-findings.ts +4 -3
  26. package/src/exercise-floor.ts +1 -1
  27. package/src/exercise-seed.ts +34 -0
  28. package/src/fix-command.ts +2 -3
  29. package/src/flag-reads.ts +6 -3
  30. package/src/generate-files.ts +10 -6
  31. package/src/gitignore.ts +4 -3
  32. package/src/guards-built-in.ts +3 -6
  33. package/src/guards.ts +5 -8
  34. package/src/island-bundle.ts +3 -2
  35. package/src/island-sources.ts +4 -3
  36. package/src/island-states-load.ts +4 -3
  37. package/src/island-store.ts +3 -2
  38. package/src/json-merge.ts +8 -6
  39. package/src/lint-findings.ts +4 -7
  40. package/src/mcp-errors.ts +1 -1
  41. package/src/messages.ts +1 -0
  42. package/src/prerender-out.ts +4 -3
  43. package/src/publish-closure.ts +4 -6
  44. package/src/pwa-manifest-locales.ts +5 -8
  45. package/src/registry.ts +0 -7
  46. package/src/root-env.ts +3 -2
  47. package/src/runtime-admin.ts +2 -4
  48. package/src/runtime-keys.ts +5 -2
  49. package/src/static-report.ts +5 -8
  50. package/src/templates/github/ci-schedule.ts +86 -0
  51. package/src/templates/github/ci.yml.ts +6 -8
  52. package/src/templates/github/dependabot.yml.ts +6 -1
  53. package/src/templates/scaffold-docs.ts +1 -0
  54. package/src/templates/shapes/overlay.ts +4 -7
  55. package/src/upgrade-guards-baseline.ts +3 -5
  56. package/src/verify-merge-skips.ts +2 -4
  57. package/src/verify-merge.ts +13 -8
  58. package/src/verify-part-step.ts +5 -7
  59. package/src/worker-bundle.ts +4 -2
  60. package/wiki/Actions.md +69 -5
  61. package/wiki/Agents.md +13 -0
  62. package/wiki/Auth.md +4 -0
  63. package/wiki/Batching-And-Preloading.md +77 -3
  64. package/wiki/CLI-Reference.md +18 -5
  65. package/wiki/Caching-And-Invalidation.md +76 -23
  66. package/wiki/Client-Navigation.md +2 -0
  67. package/wiki/Configuration.md +17 -4
  68. package/wiki/Entities-And-Migrations.md +168 -6
  69. package/wiki/FAQ.md +1 -1
  70. package/wiki/Feature-Flags.md +3 -0
  71. package/wiki/Getting-Started.md +27 -1
  72. package/wiki/Jobs-And-Workflows.md +70 -13
  73. package/wiki/Known-Gaps.md +58 -49
  74. package/wiki/MCP-And-AI.md +43 -3
  75. package/wiki/Mail.md +6 -0
  76. package/wiki/Migrations-And-Backfills.md +13 -0
  77. package/wiki/Money.md +20 -1
  78. package/wiki/N-Plus-One-Detection.md +31 -1
  79. package/wiki/Notify.md +13 -2
  80. package/wiki/PWA-And-Offline.md +34 -4
  81. package/wiki/Policies-And-Authz.md +27 -5
  82. package/wiki/Queries-And-Live-Queries.md +41 -4
  83. package/wiki/Realtime.md +22 -0
  84. package/wiki/Resource-Management.md +6 -1
  85. package/wiki/Routes-And-Render-Modes.md +54 -6
  86. package/wiki/SEO.md +24 -2
  87. package/wiki/Scheduled-Tasks.md +29 -11
  88. package/wiki/Scraping.md +33 -2
  89. package/wiki/Static-Assets.md +1 -0
  90. package/wiki/Storage-And-Uploads.md +8 -1
  91. package/wiki/Testing.md +120 -13
  92. package/wiki/The-Eight-Primitives.md +125 -6
  93. package/wiki/Timezones-And-Dates.md +13 -5
  94. package/wiki/Troubleshooting.md +1 -1
  95. package/wiki/Tutorial-02-First-Feature.md +6 -0
  96. package/wiki/Tutorial-03-Auth-And-Admin.md +8 -0
  97. package/wiki/Tutorial-04-Jobs-And-Realtime.md +40 -2
  98. package/wiki/Tutorial-06-Growing-Up.md +1 -2
  99. package/wiki/UI-Components.md +14 -5
  100. package/wiki/Upgrading.md +41 -4
package/wiki/Testing.md CHANGED
@@ -89,7 +89,7 @@ Any test that can pass twice and fail the third time is worse than no test — i
89
89
  | Control | Behavior |
90
90
  |---|---|
91
91
  | **Seeds** | `seed(name)` builds a named, deterministic fixture graph via entity factories. Same input → identical rows, identical UUIDs |
92
- | **Frozen clock** | time starts at a fixed instant. `clock.advance('3d')` moves it, and it also drives `step.sleep` and cron in tests |
92
+ | **Frozen clock** | time starts at a fixed instant. `clock.advance('3d')` moves it and makes a `step.sleep` due. It fires no cron: a task test reads `task.entries(occurrenceMs)` |
93
93
  | **Seeded RNG** | `Math.random`, `crypto.randomUUID`, and Bun's RNG are seeded per test file from its path — reproducible, distinct across files |
94
94
  | **Sealed network** | a `fetch`, a `new WebSocket(…)`, a `Bun.connect(…)` or a `node:net` / `node:tls` / `node:http` / `node:https` / `node:http2` connection (all dial through `net.Socket#connect`, sealed there) to anywhere not explicitly mocked or allowed **fails the test** with `X_TEST_NETWORK_SEALED`, naming the URL and the fix — every dial shares one gate, so the allow-list (`allowHost('host:port')` for a socket) and `offline()` apply to all of them — `offline()` refuses a loopback dial too (`X_TEST_NETWORK_OFFLINE`). A `node:*` refusal is the socket's `error` event, as a failed real dial is. A `mockFetch` route answers `fetch` only: a `node:http` request to a mocked host is refused, never dialled. A `Bun.udpSocket` send (and `node:dgram`, which sends through it) asks the same gate per datagram, the connected peer included: a refusal throws from `send`/`sendMany` as Bun's own UDP failures do, a refused `connect` option rejects, and `dgram` hands it to the send callback — or emits `error` when there is none. A unix socket is never sealed |
95
95
  | **Sealed names** | Every resolution path asks the same gate — `lookup`, every `resolve*`, `reverse`, `lookupService` (by `node:dns`, `node:dns/promises` or `Bun.dns`, a named import bound before the seal included), both `Resolver` classes and `Bun.dns.prefetch`: a host a `mockFetch` route names answers an address query (`lookup`, `A`, `ANY`) with `MOCKED_HOST_ADDRESS` (`11.11.11.11`, public, so an SSRF screen such as `screenDial` passes it and the dial it pins still meets the mock by its `Host`) and any other record type (`MX`, `TXT`, …) with `X_TEST_NETWORK_SEALED` — a mock declares an endpoint, not a zone; this machine, an `allowHost` name and a `lookup` of an address literal resolve for real (a `reverse` of a public address is sealed: it is a query); offline refuses every name (`X_TEST_NETWORK_OFFLINE`); any other name is `X_TEST_NETWORK_SEALED` — its fix opens with `mockFetch(…)` for an address query and with `allowHost('<name>')` for a record or reverse query, which no mock answers. A RegExp route names a host it matches at the origin or spells in its source |
@@ -219,6 +219,10 @@ committed baseline, never on an absolute score — models drift, prompts should
219
219
  | the baseline was never recorded | `X_EVAL_BASELINE_MISSING` |
220
220
 
221
221
  ```ts
222
+ import { defineEval, exact, jsonSchemaValid, type Prompt } from '@ultimat3/ai';
223
+
224
+ declare const summarizePrompt: Prompt<{ ticket: string }>;
225
+
222
226
  export const summarizeEval = defineEval({
223
227
  name: 'summarize',
224
228
  prompt: summarizePrompt,
@@ -271,27 +275,61 @@ is the app's script — `transcriptOf(error)` hands over what happened.
271
275
 
272
276
  ```ts
273
277
  // contract test — generated as a scaffold with the action
274
- test('publishPost denies a non-owner', async ({ seed, actorFor }) => {
275
- const { post, stranger } = await seed('two-orgs');
276
- await expect(publishPost.as(actorFor(stranger), { postId: post.id }))
277
- .rejects.toBeUltimateError('X_FORBIDDEN');
278
+ import { type Action, t } from '@ultimat3/action';
279
+ import { testActor } from '@ultimat3/policy';
280
+ import { contractTest, expect } from '@ultimat3/testing';
281
+
282
+ const PostView = t.object({ id: t.uuid, orgId: t.uuid, title: t.string });
283
+ const PublishPostInput = t.object({ postId: t.uuid });
284
+ declare const publishPost: Action<typeof PublishPostInput, typeof PostView>;
285
+ declare const postId: string;
286
+
287
+ // Named here because this file does not boot the app; at boot `defineApi` stamps the same name.
288
+ const target = publishPost.named('publishPost');
289
+
290
+ // Holds the grant, wrong org: a denial here is the policy deciding, not the permission check.
291
+ const outsider = testActor('outsider', {
292
+ orgId: '00000000-0000-4000-8000-000000000009',
293
+ permissions: ['post:publish'],
294
+ }).actor;
295
+
296
+ contractTest('publishPost denies a foreign org', async () => {
297
+ const denied = await target.as(outsider, { postId }).catch((error: unknown) => error);
298
+ expect(denied).toBeUltimateError('X_FORBIDDEN');
278
299
  });
279
300
  ```
280
301
 
281
302
  ```ts
282
303
  // job test — the step guarantee, not the happy path
283
- test('onboardOrg retries only the failed step', async ({ seed, clock, mail }) => {
284
- const { org } = await seed('fresh-org');
304
+ import type { JobHandle } from '@ultimat3/jobs';
305
+ import type { AnyMailDefinition } from '@ultimat3/mail';
306
+ import { expect, jobTest } from '@ultimat3/testing';
307
+
308
+ declare const nudgeEmail: AnyMailDefinition;
309
+ declare const onboardOrg: JobHandle<{ orgId: string }>;
310
+ declare const orgId: string;
311
+
312
+ jobTest('a resumed run replays its steps, and a mail blip retries the mail job', async ({
313
+ clock,
314
+ mail,
315
+ runJobs,
316
+ }) => {
285
317
  mail.failOnce(nudgeEmail);
286
- await runJobs(onboardOrg, { orgId: org.id });
318
+ await runJobs(onboardOrg, { orgId });
287
319
  clock.advance('3d');
288
- const trace = await runJobs.drain();
289
- expect(trace.steps.provision.executions).toBe(1); // replayed from storage
290
- expect(trace.steps['nudge'].executions).toBe(2); // only this one retried
320
+ const resumed = await runJobs.drain();
321
+ expect(resumed.steps['provision']?.executions).toBe(1); // replayed from storage
322
+ expect(resumed.steps['nudge']?.executions).toBe(1);
323
+ expect(mail.outbox()).toHaveLength(1); // the nudge's send was refused
324
+
325
+ clock.advance('1h');
326
+ const retried = await runJobs.drain();
327
+ expect(mail.outbox()).toHaveLength(2); // the mail job's retry lands
328
+ expect(retried.steps['nudge']?.executions).toBe(1); // and the step never ran again
291
329
  });
292
330
  ```
293
331
 
294
- The `job` example is the one that matters: it asserts the durability guarantee, not that mail was sent. See [Jobs and workflows](Jobs-And-Workflows) and [Policies and authz](Policies-And-Authz).
332
+ The `job` example is the one that matters: finished steps replay, and a refused send costs one retry of the mail job, never a re-run of the step that enqueued it. See [Jobs and workflows](Jobs-And-Workflows) and [Policies and authz](Policies-And-Authz).
295
333
 
296
334
  ## The accessibility audit
297
335
 
@@ -373,6 +411,14 @@ Installed by the preload on `expect`.
373
411
  enumerate a sealed column ([Sealed columns](Entities-And-Migrations#sealed-columns)):
374
412
 
375
413
  ```ts
414
+ import { database, entity, text, uuid } from '@ultimat3/entity';
415
+ import { expect } from '@ultimat3/testing';
416
+
417
+ const connections = entity('connections', {
418
+ columns: { id: uuid().primaryKey(), label: text(), password: text().sealed() },
419
+ });
420
+ const db = database({ connections });
421
+
376
422
  const row = await db.connections.insert({ label: 'primary', password: 'hunter2' });
377
423
 
378
424
  expect(row).toEqual({ id: row.id, label: 'primary', password: 'hunter2' }); // fails, empty diff
@@ -438,6 +484,14 @@ The worked example: `examples/dummy/apps/web/app/settings/page.test.ts`. `As of
438
484
  ## Running a mutator's local half
439
485
 
440
486
  ```ts
487
+ import { type Mutator, t } from '@ultimat3/action';
488
+ import { expect, memoryLocalTx } from '@ultimat3/testing';
489
+
490
+ const RenameInput = t.object({ id: t.uuid, orgId: t.uuid, title: t.string });
491
+ declare const renamePost: Mutator<typeof RenameInput, typeof RenameInput>;
492
+ declare const id: string;
493
+ declare const orgId: string;
494
+
441
495
  const store = memoryLocalTx({ posts: { [id]: { id, title: 'before', pending: false } } });
442
496
  renamePost.local(store.tx, { id, orgId, title: 'after' });
443
497
  expect(store.rows('posts')).toEqual({ [id]: { id, title: 'after', pending: true } });
@@ -574,6 +628,11 @@ The last five are **declared, not built**. The framework does not bundle a brows
574
628
 
575
629
  ```ts
576
630
  // scripts/test-setup.ts
631
+ import { defineFixtures, type PageLike } from '@ultimat3/testing';
632
+
633
+ declare function openBrowserPage(): Promise<PageLike>;
634
+ declare function loadSeed(name: string): Promise<void>;
635
+
577
636
  defineFixtures({ page: () => openBrowserPage(), seed: () => loadSeed });
578
637
  ```
579
638
 
@@ -584,6 +643,15 @@ defineFixtures({ page: () => openBrowserPage(), seed: () => loadSeed });
584
643
  ## A job under `runJobs`
585
644
 
586
645
  ```ts
646
+ import { unitTest } from '@ultimat3/testing';
647
+ import { expect } from 'bun:test';
648
+ import { type JobHandle } from '@ultimat3/jobs';
649
+
650
+ declare const reindexPost: JobHandle<{ id: string; orgId: string }>;
651
+
652
+ declare const orgId: string;
653
+ declare const id: string;
654
+
587
655
  unitTest('a row deleted before the run is skipped, not failed', async ({ runJobs }) => {
588
656
  const trace = await runJobs(reindexPost, { id, orgId });
589
657
  expect(trace.executions.map((run) => run.outcome)).toEqual(['completed']);
@@ -656,6 +724,18 @@ mount (`beforeAll`, 60 s unless `timeoutMs` says otherwise) and the teardown; th
656
724
  once per file.
657
725
 
658
726
  ```ts
727
+ import { join } from 'node:path';
728
+ import {
729
+ describeIslandState,
730
+ expect,
731
+ type IslandStatesManifest,
732
+ type IslandStateSuiteOptions,
733
+ test,
734
+ } from '@ultimat3/testing';
735
+
736
+ declare const buildIslands: IslandStateSuiteOptions['build'];
737
+ declare const counterStates: IslandStatesManifest;
738
+
659
739
  const island = { build: buildIslands, root: join(import.meta.dir, '..', '..', '..') };
660
740
 
661
741
  describeIslandState(counterStates, 'idle', island, (mounted) => {
@@ -691,6 +771,13 @@ Symbol.for('ultimate.realtime'))`: that leaves the socket open. `As of 2026-11`.
691
771
  ## Testing an authenticator
692
772
 
693
773
  ```ts
774
+ import type { Authenticator } from '@ultimat3/http';
775
+ import { authRequest, expect, unitTest } from '@ultimat3/testing';
776
+
777
+ declare const authenticate: Authenticator; // what the app hands configureAuthenticator()
778
+ declare const member: { readonly id: string };
779
+ declare const token: string;
780
+
694
781
  unitTest('a session cookie resolves the member it was issued to', async () => {
695
782
  const actor = await authenticate(...(await authRequest({ cookies: { session: token } })));
696
783
  expect(actor?.id).toBe(member.id);
@@ -769,6 +856,10 @@ terminal and never the logger, so a test asserting on an `info` audit line passe
769
856
  `x dev` warns about a query loop; CI is where nobody is watching. Destructuring `statements` installs the same detector in **strict** mode for the length of one test:
770
857
 
771
858
  ```ts
859
+ import { expect, test } from '@ultimat3/testing';
860
+
861
+ declare function renderFeed(): Promise<void>;
862
+
772
863
  test('the feed reads its authors once', async ({ statements }) => {
773
864
  await renderFeed();
774
865
  // X_N_PLUS_ONE_QUERY: members.findById ran 5 times in one request — one read per row
@@ -791,6 +882,12 @@ The loop runs to its end and the verdict is raised when the fixture is disposed
791
882
  A deliberate loop is declared where it is written, never silenced at the test:
792
883
 
793
884
  ```ts
885
+ import { expectedQueryLoop } from '@ultimat3/db';
886
+
887
+ declare function searchEachField(term: string): Promise<void>;
888
+
889
+ declare const term: string;
890
+
794
891
  await expectedQueryLoop('one indexed lookup per searchable field', () => searchEachField(term));
795
892
  ```
796
893
 
@@ -969,6 +1066,13 @@ unitTest('a cursor round-trips any position', () => {
969
1066
  One contract, asserted against many subjects, with the subject passed as a **thunk** so a `beforeAll`-built value is read at test time rather than at declaration time.
970
1067
 
971
1068
  ```ts
1069
+ import { behavesLike, describe, expect, sharedExamples, test, testName } from '@ultimat3/testing';
1070
+
1071
+ interface Denier {
1072
+ denies(actor: 'anonymous'): boolean;
1073
+ }
1074
+ declare const publishPost: Denier;
1075
+
972
1076
  const anAuthenticatedAction = sharedExamples<Denier>('an authenticated action', (subject) => {
973
1077
  test('denies an anonymous actor', () => {
974
1078
  expect(subject().denies('anonymous')).toBe(true);
@@ -1060,6 +1164,7 @@ shape, same unreached code. `As of 2026-11`.
1060
1164
  | A step held by a cookie | `defineExercise({ finishSignIn: { request: { cookies: { pending: '<value>' } } } })` — the call's inbound request carries it, read by `useRequestCookie()` / `useRequestHeader()` in the handler; `headers: { … }` beside it. A function `request: async (actor) => ({ cookies: { sid: await mintSession(actor) } })` is awaited before each call, as that call's actor (A's and B's each mint their own). A cookie goes in `cookies`, never a `Cookie` header: that, a name outside the token set or a header `Headers` refuses is `X_EXERCISE_REQUEST_INVALID`. Read by `x exercise` and the contract step alike: `.contract({ exercise })` runs each generated run inside that request (`withRequestAs`, `@ultimat3/http`); with no `request` its call has none, so a handler reading a cookie there is `X_CONTRACT_DEFECT` on `X_NO_REQUEST` (`As of 2026-11-08`) |
1061
1165
  | Rows a generated value cannot satisfy | a cross-column `c.satisfies(…)` reads `X_SEED_GRAPH_UNSATISFIED`: `defineExercise({ … }, { factories: { bosses: defineFactory(bosses, { defaults: (i) => ({ … }) }) } })`, keyed by entity name, the graph's keys kept. A column that follows from a key or reference the graph picked: `derive: (row) => ({ scopeKey: … })` beside `build`/`reset`, reading `row.ownerOrgId`. A partial unique whose columns the factory builds is the database's to judge. An unknown name is `X_DECLARATION_UNKNOWN` |
1062
1166
  | Drift | a schema no draw satisfies is `unreached`, `X_CONTRACT_DRIFT`; its `override` binds each field the sampler names as a gap with what it needs (`digest: "<must match ^[0-9a-f]{64}$>"`), the contract step's `fix:` the same `input:` (`As of 2026-11-08`) |
1167
+ | Seed | one constant unless `--seed <n>` names another, so a tree gets one verdict; `--seed random` explores a fresh one, and the report's `seed` replays either (`As of 31.47.0`). Row ids follow the seed and the scale sweep's sized calls share one tenant, in order, so a call that archives a row changes what later calls find. A helper in `apps/web/exercise.ts` (an `input`, a factory) picks its rows by what they are, never by id order, and assumes no order between sized calls: one that does is reported `unproven`, at some seeds and not others |
1063
1168
  | Report | `.x/exercise.json` and `--json`: `{ seed, counts, records[] }`, each record `{ kind, name, outcome, code?, reason?, defect?, statements, effects, ms, override?, fix?, tenant?, crash? }` — `fix` where no override reaches it; `defect` on a 5xx: `{ cause, statement?, fields? }`, the error's own cause (a value the input held under a credential key or a `.sensitive()` field masked `[redacted]`), the SQL a database refusal names and the paths a validation failure names, all carried into the `X_CONTRACT_EXERCISE_UNREACHED` finding. The fields before `tenant` are A's call. The human table's `tenant` and `crash` columns are the verdicts, `-` where none ran |
1064
1169
  | Gate | the `exercise` step, after `job`, runs `x exercise --json` as a child and is red on its findings: `X_CONTRACT_EXERCISE_UNREACHED`, `X_TENANT_LEAK`, `X_TENANT_WRITE_CROSSED`, `X_JOB_CRASH_DIVERGED`, and — on a whole pass, not `x exercise <name>` — `X_ENTITY_TENANT_UNDECLARED`. `unreached` is never sampled or skipped: it is a finding whose `fix:` is the entry to paste |
1065
1170
 
@@ -1268,7 +1373,9 @@ What is red is `x.verify.json`'s call ([Configuration](Configuration#the-gates-f
1268
1373
  `x new` writes `{ "unprovenMax": 0, "statementsMax": 100 }`. An app scaffolded before 31.16.0 stays
1269
1374
  green with warnings until it opts in, and `x upgrade` writes the figures its hop measured — the
1270
1375
  busiest undeclared call, never under 100 — so the floor starts where the app is. A figure the run
1271
- beats is a warning naming the lower number: the floor only falls.
1376
+ beats is a warning naming the lower number: the floor only falls. A figure measured before 31.47.0
1377
+ came from a random seed, so the constant one can land above it: `x exercise --json` re-measures, and
1378
+ each `unproven` record names the helper to fix. Nothing raises a floor for you.
1272
1379
 
1273
1380
  ## Memory, width and isolation
1274
1381
 
@@ -77,7 +77,12 @@ A table + its domain type + invariants. The single source of the DB schema, the
77
77
  An authz rule, evaluated in every surface.
78
78
 
79
79
  ```ts
80
- policy: can('post:publish', ({ input, actor }) => ownsPost(actor, input.postId))
80
+ import { can } from '@ultimat3/policy';
81
+ import { type Actor } from '@ultimat3/core';
82
+
83
+ declare function ownsPost(actor: Actor | null, postId: string): boolean;
84
+
85
+ policy: can<{ postId: string }>('post:publish', ({ input, actor }) => ownsPost(actor, input.postId))
81
86
  ```
82
87
 
83
88
  | Aspect | Rule |
@@ -91,10 +96,36 @@ policy: can('post:publish', ({ input, actor }) => ownsPost(actor, input.postId))
91
96
  A mutation or command, server-authoritative. Declared once, projected six ways.
92
97
 
93
98
  ```ts
99
+ import { action, t } from '@ultimat3/action';
100
+ import { tag } from '@ultimat3/cache';
101
+ import type { Actor } from '@ultimat3/core';
102
+ import type { JobHandle } from '@ultimat3/jobs';
103
+ import { can } from '@ultimat3/policy';
104
+
105
+ declare module '@ultimat3/cache' {
106
+ interface CacheTagRegistry {
107
+ post: true;
108
+ feed: true;
109
+ }
110
+ }
111
+ declare module '@ultimat3/core' {
112
+ interface CtxServices {
113
+ readonly posts: {
114
+ publish(id: string): Promise<{ id: string; orgId: string; title: string }>;
115
+ like(id: string): Promise<{ likeCount: number; likedByMe: boolean }>;
116
+ body(id: string): Promise<string>;
117
+ };
118
+ }
119
+ }
120
+
121
+ declare const notifySubscribers: JobHandle<{ postId: string; orgId: string }>;
122
+ declare function ownsPost(actor: Actor | null, postId: string): boolean;
123
+ const PostView = t.object({ id: t.uuid, orgId: t.uuid, title: t.string });
124
+
94
125
  export const publishPost = action({
95
126
  input: t.object({ postId: t.uuid, notify: t.boolean.default(true) }),
96
127
  output: PostView,
97
- policy: can('post:publish', ({ input, actor }) => ownsPost(actor, input.postId)),
128
+ policy: can<{ postId: string }>('post:publish', ({ input, actor }) => ownsPost(actor, input.postId)),
98
129
  cache: { invalidates: [tag.post, tag.feed] },
99
130
  mcp: { expose: true, description: 'Publish a draft post' },
100
131
  async handle({ input, ctx }) {
@@ -116,7 +147,28 @@ export const publishPost = action({
116
147
  An action with an optimistic local twin. `local` runs client-side against the local store; `server` is authoritative. Same input, same name, both halves in one file.
117
148
 
118
149
  ```ts
150
+ import { mutator, t } from '@ultimat3/action';
151
+ import { can } from '@ultimat3/policy';
152
+
153
+ declare module '@ultimat3/core' {
154
+ interface CtxServices {
155
+ readonly posts: {
156
+ publish(id: string): Promise<{ id: string; orgId: string; title: string }>;
157
+ like(id: string): Promise<{ likeCount: number; likedByMe: boolean }>;
158
+ body(id: string): Promise<string>;
159
+ };
160
+ }
161
+ }
162
+ declare module '@ultimat3/action' {
163
+ interface LocalTables {
164
+ posts: { likedByMe: boolean; likeCount: number };
165
+ }
166
+ }
167
+
119
168
  export const likePost = mutator({
169
+ input: t.object({ postId: t.uuid }),
170
+ output: t.object({ likeCount: t.number, likedByMe: t.boolean }),
171
+ policy: can('post:like'),
120
172
  // REQUIRED (`X_MUTATOR_NOT_IDEMPOTENT`): a replay under the same Idempotency-Key answers the
121
173
  // first result instead of running `server` again.
122
174
  idempotent: true,
@@ -142,11 +194,27 @@ export const likePost = mutator({
142
194
  A read; optionally live (subscribable).
143
195
 
144
196
  ```ts
197
+ import { from, query } from '@ultimat3/query';
198
+ import { t } from '@ultimat3/action';
199
+ import { can } from '@ultimat3/policy';
200
+ import { database, entity, timestamp, uuid } from '@ultimat3/entity';
201
+
202
+ const posts = entity('posts', {
203
+ tenant: 'orgId',
204
+ columns: { id: uuid().primaryKey(), orgId: uuid(), createdAt: timestamp().defaultNow() },
205
+ });
206
+ const db = database({ posts });
207
+ type Post = typeof posts.$row;
208
+
145
209
  export const liveFeed = query({
146
210
  input: t.object({ orgId: t.uuid }),
147
211
  policy: can('feed:read'),
148
212
  live: true,
149
- sql: ({ orgId }) => db.posts.where({ orgId }).orderBy('createdAt').limit(50),
213
+ sql: ({ orgId }) =>
214
+ from<Post>('posts', () => db.posts.where({ orgId }).all())
215
+ .where({ orgId })
216
+ .orderBy('createdAt')
217
+ .limit(50),
150
218
  });
151
219
  ```
152
220
 
@@ -161,6 +229,23 @@ export const liveFeed = query({
161
229
  Durable background work, optionally multi-step. `idempotencyKey` is **required by the type**.
162
230
 
163
231
  ```ts
232
+ import { job } from '@ultimat3/jobs';
233
+ import { t } from '@ultimat3/action';
234
+ import { type AnyMailDefinition } from '@ultimat3/mail';
235
+
236
+ declare module '@ultimat3/core' {
237
+ interface CtxServices {
238
+ readonly orgs: {
239
+ provision(id: string): Promise<{ id: string; name: string }>;
240
+ byId(id: string): Promise<{ id: string; name: string }>;
241
+ };
242
+ readonly mail: { send(mail: unknown, to: unknown): Promise<void> };
243
+ }
244
+ }
245
+
246
+ declare const welcomeEmail: AnyMailDefinition;
247
+ declare const nudgeEmail: AnyMailDefinition;
248
+
164
249
  export const onboardOrg = job({
165
250
  input: t.object({ orgId: t.uuid }),
166
251
  tenant: ({ orgId }) => orgId, // the org this run acts as
@@ -187,15 +272,45 @@ export const onboardOrg = job({
187
272
  A URL + render mode + metadata + offline strategy.
188
273
 
189
274
  ```ts
275
+ import { tag } from '@ultimat3/cache';
276
+ import { defineRoute } from '@ultimat3/render';
277
+ import { ld } from '@ultimat3/seo';
278
+
279
+ declare module '@ultimat3/cache' {
280
+ interface CacheTagRegistry {
281
+ post: true;
282
+ feed: true;
283
+ }
284
+ }
285
+
286
+ interface Post {
287
+ readonly title: string;
288
+ readonly excerpt: string;
289
+ readonly cover: string;
290
+ readonly publishedAt: string;
291
+ readonly author: string;
292
+ }
293
+ declare function listPostSlugs(): Promise<readonly string[]>;
294
+ declare function loadPost(slug: string): Promise<Post>;
295
+
190
296
  export const config = defineRoute({
191
297
  render: 'isr', // static | isr | ssr | stream
192
298
  revalidate: { tags: [tag.post] },
193
- prerender: () => db.posts.slugs(),
299
+ prerender: () => listPostSlugs(),
194
300
  offline: 'precache', // precache | runtime | network-only
195
301
  hydrate: 'visible', // idle | visible | interaction | never
196
302
  budget: { js: '40kb' },
197
- meta: ({ post }) => ({ title: post.title, description: post.excerpt,
198
- og: { image: post.cover }, ld: ld.Article(post) }),
303
+ load: ({ params }) => loadPost(params['slug'] ?? ''),
304
+ meta: ({ data: post }) => ({
305
+ title: post.title,
306
+ description: post.excerpt,
307
+ og: { image: post.cover },
308
+ ld: [ld.Article({
309
+ headline: post.title,
310
+ datePublished: post.publishedAt,
311
+ author: { name: post.author },
312
+ })],
313
+ }),
199
314
  });
200
315
  ```
201
316
 
@@ -212,6 +327,10 @@ Render modes: `static` (built once), `isr` (static + background regen), `ssr` (p
212
327
  A scheduled trigger. Enqueues jobs; never does work itself.
213
328
 
214
329
  ```ts
330
+ import { type JobHandle, task } from '@ultimat3/jobs';
331
+
332
+ declare const sendDigest: JobHandle<Record<string, never>>;
333
+
215
334
  export const nightlyDigest = task({
216
335
  cron: '0 3 * * *',
217
336
  tz: 'UTC',
@@ -129,6 +129,10 @@ Parsed once into milliseconds. A bare number is a type error — the unit must b
129
129
 
130
130
  ```ts
131
131
  // task (cron)
132
+ import { type JobHandle, task } from '@ultimat3/jobs';
133
+
134
+ declare const sendDigest: JobHandle<Record<string, never>>;
135
+
132
136
  export const nightlyDigest = task({
133
137
  cron: '0 3 * * *',
134
138
  tz: 'UTC',
@@ -162,8 +166,8 @@ Cron is a civil-calendar schedule; sleeps are elapsed time. Mixing them is where
162
166
 
163
167
  | Control | Behavior |
164
168
  |---|---|
165
- | Frozen clock | time starts at a fixed instant, does not advance on its own |
166
- | `clock.advance('3d')` | moves it, and also drives `step.sleep` and cron dispatch |
169
+ | Frozen clock | time starts at `2026-01-01T00:00:00.000Z` (`DEFAULT_NOW`), does not advance on its own |
170
+ | `clock.advance('3d')` | moves it, and makes a `step.sleep` due. It fires no cron: a task test reads `task.entries(occurrenceMs)` ([Scheduled tasks](Scheduled-Tasks#testing)) |
167
171
  | Fixed zone | `UTC` unless a test declares otherwise |
168
172
  | Fixed locale | `en-US` unless a test declares otherwise |
169
173
  | tz-dependent bugs | fail deterministically — declare a zone in the test and the bug reproduces every run |
@@ -172,11 +176,15 @@ Cron is a civil-calendar schedule; sleeps are elapsed time. Mixing them is where
172
176
  Declare a zone when the behavior is the point:
173
177
 
174
178
  ```ts
175
- test('digest window respects the org zone', async ({ seed, clock }) => {
176
- const { org } = await seed('org-in-berlin');
179
+ import { expect, test } from '@ultimat3/testing';
180
+
181
+ declare const org: { readonly id: string };
182
+ declare function digestWindow(org: { readonly id: string }, zone: string): { readonly label: string };
183
+
184
+ test('digest window respects the org zone', async ({ clock }) => {
177
185
  clock.advance('1d');
178
186
  const window = digestWindow(org, 'Europe/Berlin');
179
- expect(window.label).toBe('Jul 27, 2026');
187
+ expect(window.label).toBe('Jan 2, 2026'); // the frozen clock starts at 2026-01-01T00:00Z
180
188
  });
181
189
  ```
182
190
 
@@ -130,7 +130,7 @@ Boundaries run on pre-push and inside `x verify`. They are build errors, never l
130
130
  |---|---|---|
131
131
  | `X_TEST_NETWORK_SEALED` | a test reached the network unmocked | the error names the URL. Mock it — sealed network is the design, not a bug |
132
132
  | A test passes alone, fails in the suite | shared state that should not exist — each worker gets its own cloned DB | check for a module-level singleton or a fixture written outside `seed()` |
133
- | Time-dependent failure | asserted on wall clock | use the frozen clock and `clock.advance('3d')` — it also drives `step.sleep` and cron |
133
+ | Time-dependent failure | asserted on wall clock | use the frozen clock and `clock.advance('3d')` — it also makes a `step.sleep` due; it fires no cron ([Scheduled tasks](Scheduled-Tasks#testing)) |
134
134
  | A test flakes | **fix it or delete it the same day** | there is no `retry: 3`. A test that passes twice and fails the third trains people to ignore red |
135
135
  | Snapshot/UUID churn between runs | not using `seed(name)` | seeds are deterministic: same input → identical rows, identical UUIDs |
136
136
  | Job test doesn't drain | queue not advanced | `await runJobs.drain()`; workers run deterministically in tests |
@@ -91,6 +91,8 @@ The slice enforces one call direction, and `x verify`'s `boundaries` step is wha
91
91
  ## The entity
92
92
 
93
93
  ```ts
94
+ import { entity, invariant, money, text, timestamp, uuid } from '@ultimat3/entity';
95
+
94
96
  export const todo = entity('todos', {
95
97
  // Naming the tenant column is what turns tenancy on: a read with no org predicate then fails
96
98
  // with X_TENANCY_UNSCOPED instead of leaking another org's rows.
@@ -117,6 +119,10 @@ Each invariant runs twice from one declaration — in the app on every write, an
117
119
  ## The policy decides once, everywhere
118
120
 
119
121
  ```ts
122
+ import { can } from '@ultimat3/policy';
123
+
124
+ type TodoScope = { readonly orgId: string };
125
+
120
126
  export const canTodoWrite = can<TodoScope>(
121
127
  'todo:write',
122
128
  ({ actor, input }) => actor !== null && actor.orgId === input.orgId,
@@ -124,6 +124,14 @@ The defaults: a 30-day absolute and a 7-day idle session, cookie `__Host-x_sessi
124
124
  Register, log in, resolve — the real flow, against Postgres, with `const auth = appAuth()` and `org` the seeded demo org (`DEMO_ORG_ID` from `apps/web/shared/demo-org.ts`):
125
125
 
126
126
  ```ts
127
+ import { type Auth, login, register } from '@ultimat3/auth';
128
+
129
+ declare const auth: Auth;
130
+ declare const org: string;
131
+ declare const email: string;
132
+ declare const password: string;
133
+ declare const ip: string;
134
+
127
135
  await register(auth, { email, password, orgId: org, roles: ['member'] });
128
136
  const { actor, token, cookie } = await login(auth, { email, password, ip });
129
137
  ```
@@ -11,6 +11,15 @@ Series: [1 — first app](Tutorial-01-First-App) · [2 — first feature](Tutori
11
11
  `x g resource` already wrote one. Its shape is the whole contract:
12
12
 
13
13
  ```ts
14
+ import { t } from '@ultimat3/action';
15
+ import { job } from '@ultimat3/jobs';
16
+
17
+ // The slice's `repo.ts`, as `x g resource` wrote it.
18
+ declare const repo: {
19
+ byId(id: string): Promise<{ readonly id: string } | null>;
20
+ list(limit: number): Promise<readonly { readonly id: string }[]>;
21
+ };
22
+
14
23
  export const reindexTodo = job({
15
24
  input: t.object({ id: t.uuid, orgId: t.uuid }),
16
25
  tenant: (input) => input.orgId, // the org the body reads as, from its own input
@@ -37,9 +46,17 @@ export const reindexTodo = job({
37
46
  The generated `reindex-todo.job.test.ts` pins the distant invariant rather than the happy path:
38
47
 
39
48
  ```ts
40
- const first = await reindexTodo.enqueue({ id });
49
+ import { expect } from 'bun:test';
50
+ import { type JobHandle } from '@ultimat3/jobs';
51
+
52
+ declare const reindexTodo: JobHandle<{ id: string; orgId: string }>;
53
+
54
+ declare const id: string;
55
+ declare const orgId: string;
56
+
57
+ const first = await reindexTodo.enqueue({ id, orgId });
41
58
  expect(first.deduped).toBe(false);
42
- const again = await reindexTodo.enqueue({ id });
59
+ const again = await reindexTodo.enqueue({ id, orgId });
43
60
  expect(again.deduped).toBe(true);
44
61
  ```
45
62
 
@@ -69,6 +86,10 @@ bunx x g task daily-digest --feature todo
69
86
  `--feature todo` puts the task in the existing slice; without it the generator opens a `daily-digest` slice of its own. Either way the task and its job are added to `apps/web/api/index.ts`, which is what names them.
70
87
 
71
88
  ```ts
89
+ import { type JobHandle, task } from '@ultimat3/jobs';
90
+
91
+ declare const dailyDigestJob: JobHandle<{ id: string; orgId: string }>;
92
+
72
93
  export const dailyDigest = task({
73
94
  cron: '0 3 * * *',
74
95
  tz: 'UTC',
@@ -151,6 +172,18 @@ export const todoListSorts = ['createdAt', 'title'] as const;
151
172
  ```
152
173
 
153
174
  ```ts
175
+ import { t } from '@ultimat3/action';
176
+ import { from, query, type QueryPolicy } from '@ultimat3/query';
177
+
178
+ type Todo = { readonly id: string; readonly orgId: string; readonly title: string; readonly createdAt: Date };
179
+
180
+ const todoListSorts = ['createdAt', 'title'] as const;
181
+ declare const canTodoRead: QueryPolicy;
182
+ // The slice's `repo.ts`, as `x g resource` wrote it.
183
+ declare const repo: {
184
+ list(limit: number, sort: string, dir: 'asc' | 'desc'): Promise<readonly Todo[]>;
185
+ };
186
+
154
187
  export const todoList = query({
155
188
  input: t.object({
156
189
  limit: t.number.default(50),
@@ -188,6 +221,11 @@ export const todoList = query({
188
221
  The generated `todo-list.live.test.ts` asserts on the **SQL text**, because that is the contract an agent reads to self-correct:
189
222
 
190
223
  ```ts
224
+ import { type AnyQuery, sourceFor } from '@ultimat3/query';
225
+ import { expect } from '@ultimat3/testing';
226
+
227
+ declare const target: AnyQuery;
228
+
191
229
  const source = await sourceFor(
192
230
  target,
193
231
  { limit: 50 },
@@ -139,8 +139,7 @@ Named rather than left to be discovered:
139
139
  | no Helm chart in a scaffolded app | 3 |
140
140
  | no OTLP **logs** signal, and a rejected export is dropped with a `warn` rather than retried — traces and metrics do export | 3–4 |
141
141
  | a custom-metrics adapter, which the chart's HPAs need and the framework never ships | 3–4 |
142
- | `x logs` planned — `X_NOT_IMPLEMENTED`, with `x dev` → the `/_x` timeline panel as its fix | any |
143
- | the Redis **job** driver throws `X_NOT_IMPLEMENTED` (no NATS job driver since 25.0.0) | any |
142
+ | `redisJobDriver()` has no `introspect`, `backfills` or `leases`, so `x jobs show`/`retry`/`cancel` and queue pauses answer for Postgres only (no NATS job driver since 25.0.0) | any |
144
143
  | realtime tier 3 (local-first, `persist: true`), the plugin API, multi-region replication | **not shipped**, `As of 2026-08` |
145
144
 
146
145
  Each sits behind an interface that ships today and fails loudly, rather than pretending to work. The full list, with a workaround per row: [Known gaps](Known-Gaps).
@@ -104,11 +104,20 @@ A `level` outside 1–6 throws `X_UI_INVALID_VALUE` rather than emitting an `<h7
104
104
  `Button` has no `href`. A link that looks like a button is `<Link appearance="button">`; a pager on a server-rendered list is `<Pagination hrefFor>`. Neither needs an island.
105
105
 
106
106
  ```tsx
107
- <Link appearance="button" variant="secondary" size="sm" href="/posts/new">{t('posts.new')}</Link>
108
-
109
- // `page` is a framework `Page` (a query's `.page()`): `nextCursor` is `string | null`, handed as is.
110
- const list = listUrl(props.url, { sorts: ['title', 'createdAt'] });
111
- <Pagination nextCursor={page.nextCursor} hrefFor={list.hrefFor} firstHref={list.firstHref} />
107
+ import type { Page } from '@ultimat3/core';
108
+ import { t } from '@ultimat3/i18n';
109
+ import { Link, listUrl, Pagination } from '@ultimat3/ui';
110
+
111
+ export function PostsFooter(props: { readonly url: URL; readonly page: Page<object> }) {
112
+ // `page` is a framework `Page` (a query's `.page()`): `nextCursor` is `string | null`, handed as is.
113
+ const list = listUrl(props.url, { sorts: ['title', 'createdAt'] });
114
+ return (
115
+ <>
116
+ <Link appearance="button" variant="secondary" size="sm" href="/posts/new">{t('posts.new')}</Link>
117
+ <Pagination nextCursor={props.page.nextCursor} hrefFor={list.hrefFor} firstHref={list.firstHref} />
118
+ </>
119
+ );
120
+ }
112
121
  ```
113
122
 
114
123
  `listUrl(url, { sorts, ns?, limit? })` reads a list's state out of its URL — `sort`, `cursor`, `limit`, `q`, never throwing: an unknown sort or a hostile limit is the default — and writes it back as hrefs: `hrefFor` (the cursor, everything else kept), `sortHrefFor` and `href(change)` (the change, the cursor dropped), `firstHref` (`undefined` on the first page). Param names are `sort`, `dir`, `after`, `limit`, `q`; `ns: 'runs'` prefixes them all (`runs.after`) for two lists on a page, and then any change but a cursor drops every cursor on the page, since a cursor is bound to its filter and sort (`X_CURSOR_INVALID`). The same object feeds a `DataTable`'s `hrefFor`, `sortHrefFor` and `firstHref`.