@ultimat3/cli 31.24.0 → 31.26.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.
@@ -71,9 +71,10 @@ x-image: &image
71
71
  # The image's own HEALTHCHECK fetches \`/readyz\` on $PORT, and only \`web\` and \`sync\` open an HTTP
72
72
  # socket — every other role gets the scrape listener and nothing else. A service that inherits that
73
73
  # probe is fetching a port it never binds: it reports \`unhealthy\` for its whole life and anything
74
- # gated on it never starts. Probes follow the role here, exactly as they do in \`docker/helm\`.
74
+ # gated on it never starts. Probes follow the role here, exactly as they do in \`docker/helm\`:
75
+ # \`/healthz\`, the one path on the scrape listener that reads the loops' heartbeats.
75
76
  x-metrics-probe: &metrics-probe
76
- test: ['CMD', 'bun', '--eval', "fetch('http://127.0.0.1:'+(process.env.METRICS_PORT||9090)+'/metrics').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))"]
77
+ test: ['CMD', 'bun', '--eval', "fetch('http://127.0.0.1:'+(process.env.METRICS_PORT||9090)+'/healthz').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))"]
77
78
  interval: 10s
78
79
  timeout: 3s
79
80
  start_period: 30s
@@ -167,7 +167,7 @@ nobody bound. Derived here rather than stated twice in values.yaml, where the tw
167
167
  periodSeconds: 5
168
168
  {{- end }}
169
169
  livenessProbe:
170
- httpGet: { path: /metrics, port: metrics }
170
+ httpGet: { path: /healthz, port: metrics }
171
171
  periodSeconds: 15
172
172
  failureThreshold: 4
173
173
  {{- /*
@@ -98,6 +98,7 @@ const rootPackage = (app: NameSet, version: string): string => `{
98
98
  "@ultimat3/http": "^${version}",
99
99
  "@ultimat3/i18n": "^${version}",
100
100
  "@ultimat3/jobs": "^${version}",
101
+ "@ultimat3/mail": "^${version}",
101
102
  "@ultimat3/mcp": "^${version}",
102
103
  "@ultimat3/money": "^${version}",
103
104
  "@ultimat3/policy": "^${version}",
package/wiki/Agents.md CHANGED
@@ -414,11 +414,8 @@ export const kbAgent = agent({
414
414
  | `openAiProvider()` | any other `baseUrl` | any | none | nowhere |
415
415
 
416
416
  **Your own endpoint is a row on its provider**, read before the table, first match by model prefix
417
- (`As of 2026-11`): `openAiProvider({ …, promptCache: { rules: [{ model: 'anthropic/', marks: 'parts', session: 'x-session-id' }] } })`
418
- for a company gateway fronting a marking family; `anthropicProvider({ …, promptCache: { rules: [{ model: '', marks: 'none', session: 'none' }] } })`
419
- for a proxy that rejects `cache_control`. The budget's estimate follows the row. A mark or session
420
- carrier the wire cannot speak — `parts` or a session on the Messages wire, `blocks` on
421
- chat-completions — is `X_AI_REQUEST_INVALID` when the provider is built.
417
+ (`As of 2026-11`): the rule shapes, the order and the refusal are in
418
+ [MCP and AI](MCP-And-AI#prompt-caching-on-your-own-endpoint). The budget's estimate follows the row.
422
419
 
423
420
  | Rule | Detail |
424
421
  |---|---|
package/wiki/Auth.md CHANGED
@@ -218,6 +218,30 @@ const approved = await verifyPasskeyEvidence(evidence, { rpId: 'example.com', or
218
218
  | 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 |
219
219
  | 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` |
220
220
 
221
+ ## Member invites
222
+
223
+ `As of 2026-11-14`. `defineMemberInvite({ name?, template, ttlMs })` declares the flow once, at
224
+ module scope, over a verification purpose (default name `member-invite`) and the user's one
225
+ `orgId`. It ships the structural half; who may invite, seat limits and the roles an invite offers
226
+ are the app's `policy` and the app's wrapper action.
227
+
228
+ | Call | What the framework guarantees |
229
+ |---|---|
230
+ | `flow.invite(auth, mail, { orgId, email, locale, link?, data? })` | a single-use token, hashed at rest, living `ttlMs`, keyed on the **pair** (tenant, normalised address) and mailed to the address. Re-inviting the pair is the resend: it supersedes the earlier link, so one live link per pair. A blank `orgId` is `X_FORBIDDEN` before anything is written. `link` must carry `orgId`: accept needs it |
231
+ | `flow.accept(auth, { orgId, token, userId, roles?, session? })` | the token is consumed under (that tenant, **the signed-in account's own address**), so a link aimed at another tenant or forwarded to another account finds no row and stays live for its invitee. Success sets `orgId`, replaces `roles` with what the wrapper passed (default none), clears direct `permissions`, stamps `emailVerifiedAt` (the link proved the inbox), and rotates `session` through `updatePrivileges` — set the returned `cookie`. An unknown or disabled account gets the bad-link refusal word for word, under the flow's own purpose name |
232
+ | `flow.revoke(auth, { orgId, email, reason })` | logs `auth.revocation` first and kills the pending link. It removes a membership **only one this invite flow granted** — the address joined this tenant by redeeming an invite (`orgId`, `roles`, `permissions` cleared, every session ended). A founder, a seeded admin, a member who was already in the org when they redeemed a link, or a member of another tenant is never touched: who else may be removed is the app's. A revoke racing an accept wins — the accept that loses is refused and leaves nobody joined |
233
+
234
+ | Refusal | Code |
235
+ |---|---|
236
+ | expired, already used, superseded, revoked, another tenant's, another account's, unknown or disabled account | `X_UNAUTHENTICATED` — one code and one cause for all of them, as every mailed credential: telling them apart tells a caller which address has a live invite |
237
+ | the account is a member of another tenant | `X_FORBIDDEN`, checked before the consume so the link survives a move. Membership is one tenant per account (`x_users.org_id`); moving is the app's own `updatePrivileges` call |
238
+
239
+ The flow is functions, not actions: `@ultimat3/auth` is tier 2 and cannot import
240
+ `@ultimat3/action`. Wrap each call in the app's own `action()` with the app's policy — the shape
241
+ `x g sign-in` writes for `login()`; `x g invite` writes those three actions, their policy and the two pages
242
+ ([CLI reference](CLI-Reference#x-g)). Proof: `bun test ./packages/auth/src/member-invite.test.ts`,
243
+ including a seeded property test that an invite for tenant X never yields membership in Y.
244
+
221
245
  ## Authorization server
222
246
 
223
247
  `As of 2026-11`. `authorizationServer({ issuer, store, consentPath, lifetimes, scopes, registration?, grants?, resources? })`
@@ -178,6 +178,26 @@ A **starter** (a whole app shape, not a factory) is not a package: it is a repos
178
178
  copies, and its README says so. Once one exists, a community list is a wiki page added by pull
179
179
  request.
180
180
 
181
+ ## Recipe: a PIN for a shared device
182
+
183
+ Decided 2026-11-14 (plan 101, owner decision OD6): a PIN or device-operator sign-in is **a recipe,
184
+ not a framework method**. One adopter needed it, in two files, and every rule it needs already
185
+ ships. A shared device (a till, a kiosk, a shop-floor tablet) signs in once as a device account;
186
+ an operator then proves who they are with a short PIN, and that browser's session becomes theirs.
187
+
188
+ | Piece | Where it lives | What it calls |
189
+ |---|---|---|
190
+ | the device account | an `x_users` row with the app's own `device` role, signed in by the normal sign-in | `login()` |
191
+ | the operator's PIN | the app's own entity (`operators`: `userId`, `pinHash`), never `x_users.password_hash` — a PIN is weaker than the password policy allows (`X_PASSWORD_WEAK`) | `hashPassword(pin)` on enrolment |
192
+ | the lockout | **before** the KDF, keyed per operator and per device: a 4-digit PIN is 10 000 guesses, so the budget is the whole defence | `appAuth().limiter.reserve('pin:<operatorId>:<deviceId>')` — `X_ACCOUNT_LOCKED` refuses; `recordSuccess` on a match |
193
+ | the check | constant cost whether or not the operator exists | `verifyPassword({ hash: row?.pinHash ?? null, password: pin })` |
194
+ | the switch | a session for the operator, capped at the device session's ceiling, set as that browser's cookie; signing the operator out lands on the device sign-in again | `createSession(appAuth().sessions, { userId: operator.userId, absoluteExpiresAt: device.absoluteExpiresAt })`, then `sessionCookie(issued.token, appAuth().sessions.policy)` on the response |
195
+ | who may switch | the app's policy on its own `switchOperator` action: the caller holds the `device` role | `can('operator:switch', …)` |
196
+
197
+ The action is the app's (`apps/web/app/operators/actions/switch-operator.ts`), so it projects like
198
+ any other — route, typed client, MCP tool, contract test. Nothing in the framework learns that a PIN
199
+ exists, which is the point: the next app's PIN rules (length, rotation, which devices) are its own.
200
+
181
201
  ## The honest limit
182
202
 
183
203
  **The registry cannot tell that an entity came from your factory, and that erasure is the feature.**
@@ -321,6 +321,7 @@ x g island <name> [--at <dir>] # a client component on an otherwise
321
321
  x g admin:page <name> --permission <perm> [--at <dir>] # a custom admin screen, guarded by construction
322
322
  x g guard <name> # a convention this app enforces, as a build error
323
323
  x g sign-in --password | --oidc <provider> # the app's one sign-in: pages, actions, boot guard
324
+ x g invite # the member invite: three actions and two pages over defineMemberInvite
324
325
  x g chart-alerts [--print] # the chart's ServiceMonitor + alert rules, backfilled
325
326
  x g chart-dashboard [--print] # the chart's Grafana dashboard + its ConfigMap, backfilled
326
327
  x g app <name> # one more app workspace: apps/<name>/
@@ -338,6 +339,8 @@ x g package <name> # one more shared package: packages/
338
339
 
339
340
  The boot guard is generated, app-owned: `apps/web/runtime.ts` calls `assertSignInConfigured(process.env)` before the boot binds a port, and outside `development`/`test` a `web` or `sync` role with a sign-in key unset refuses to start — `X_AUTH_SIGN_IN_UNCONFIGURED`, fix `export <KEY>="<value>"` in the role's deployed environment, then restart it (`x env example` lists the keys). The keys: `ULTIMATE_SECRETS_KEY` for `--password` (it seals the second-factor challenge); the provider's three plus `SESSION_SECRET` and `APP_URL` for `--oidc`. A second `x g sign-in` is `X_GENERATE_CONFLICT` and writes nothing. `--password` keeps the development viewer: it ships no sign-up page, so the first user is `register(appAuth(), { email, password, orgId, roles })`. An app that already has an `apps/web/runtime.ts` is that conflict too — merge the two `runtime` objects by hand.
340
341
 
342
+ **`x g invite`** (`As of 2026-11-14`) is the member invite, as the app's own actions over `@ultimat3/auth`'s `defineMemberInvite` ([Auth](Auth#member-invites)) — the shape `x g sign-in` writes for `login()`. No `<name>` (an app has one), and any `x g` flag but `--force`, `--dry-run` and `--locales` is `X_CLI_BAD_FLAG`, fix `x g invite`. Under `apps/web/app/auth/`: `invite.ts` (the flow, its `defineMail` and the link to `/auth/invites/accept?orgId=…&token=…`, built on `APP_URL` — never the request's `Host`, which the caller writes; unset, `inviteMember` is `X_ENV_MISSING`, fix `export APP_URL=…`), `policy.ts` (`member:invite`, the actor's own org), `inviteMember` and `revokeInvite` behind it (revoke removes only an address that joined through an invite; owner protection is the app's rule in `policy.ts`), `acceptInvite` (public by declaration; refuses an anonymous caller, rotates the session), `invites/page.tsx` and `invites/accept/page.tsx` (native forms, 0 kB), a test beside each. Also edits: `apps/web/shared/roles.ts` (`member:invite` to `admin`), `apps/web/api/index.ts` (the three actions), `apps/web/exercise.ts` (each action `off`, with its reason — the pass holds no mailed token), the root `package.json` of an app scaffolded before `x new` declared `@ultimat3/mail` (at the range `@ultimat3/auth` has; run `bun install`), the catalogs. Who may invite, seat limits and the roles a joiner gets are those files', to edit. A second run is `X_GENERATE_CONFLICT`, and so is an API index already binding `inviteMember`. Proof: `bun test ./packages/cli/src/generate-invite.contract.test.ts` — a fresh scaffold, the run, `tsc`, Biome and the generated tests.
343
+
341
344
  **`x g chart-alerts`** (`As of 2026-11`) writes the two monitoring templates `x new`'s chart carries into an app chart that predates them — `docker/helm/templates/servicemonitor.yaml` and `alert-rules.yaml`, named after `Chart.yaml`'s `name` — and appends the `serviceMonitor:` / `alerts:` blocks `values.yaml` lacks. Only what is missing: a template already there is kept (`--force` rewrites both), and a values key already there — `enabled: false` included — is never touched; both templates read a missing block as `auto`, rendering only where the cluster serves the Prometheus operator's kinds. A second run writes nothing. No `<name>`, and any other `x g` flag but `--force`/`--dry-run` is `X_CLI_BAD_FLAG`. **`--print`** writes nothing and needs no chart: the same rules as plain Prometheus rule groups, defaults in place, for a loader outside Kubernetes (`--json`: `data.rules`, the YAML text). No `docker/helm/Chart.yaml` is `X_CHART_MISSING`, fix `x g chart-alerts --print --json`. `x doctor` lists the missing templates. The rules: [Observability](Observability).
342
345
 
343
346
  **`x g chart-dashboard`** (`As of 2026-11`) is the same backfill for the chart's Grafana dashboard: `docker/helm/dashboards/ultimate-app.json` (one column of panels over the series the framework declares — requests, latency by route, statements, pool, jobs, realtime, the process) and `templates/dashboard-configmap.yaml`, which ships it as a ConfigMap a Grafana sidecar provisions by label — plus the `dashboard:` block `values.yaml` lacks, `enabled: false` (`x new`'s chart writes the same three). The same rules as `chart-alerts`: only what is missing, `--force` rewrites, no `<name>`, `X_CHART_MISSING` with no chart. **`--print`** writes nothing and needs no chart: the dashboard JSON, to import into a Grafana outside Kubernetes (`--json`: `data.dashboard`).
package/wiki/FAQ.md CHANGED
@@ -27,7 +27,7 @@ What it does **not** claim:
27
27
 
28
28
  | Not claimed | Detail |
29
29
  |---|---|
30
- | A multi-node realtime result | the 50k forced-restart benchmark **is** measured and committed, but on **one** `sync` node over `InProcessTransport` — it never crossed NATS. Fanout across nodes, throughput, and per-node socket capacity are all still targets, not results ([Realtime](Realtime)) |
30
+ | A multi-node realtime **rate** | correctness across nodes is proven over a real NATS bus (`multi-node.live.test.ts`, `As of 2026-11-14`): a publish on one node delivered by another in order, a page resuming on a survivor from its cursor with nothing lost or twice, a restarted node's snapshot, a missed-bus gap re-served at once ([Realtime](Realtime#across-nodes-over-a-real-bus)). The 50k forced-restart benchmark is still **one** `sync` node over `InProcessTransport`; fanout throughput and per-node socket capacity across nodes are unmeasured targets, not results |
31
31
  | A rolling restart on **Compose** | Compose is the single-node rung: one published port has one binder, so a restart there is a restart. The invisible-restart proof is Kubernetes only ([Deployment](Deployment)) |
32
32
  | Not shipped, `As of 2026-09-23` | the plugin API, multi-region replication, and the Redis **job** driver — all behind the interfaces that ship today (there is no NATS job driver since 25.0.0). The Redis driver throws `X_NOT_IMPLEMENTED` with a runnable `fix:` line rather than pretending to work |
33
33
 
@@ -119,7 +119,7 @@ Yes. `realtime: { enabled: false }` in `app.config.ts` is the opt-out (its defau
119
119
 
120
120
  ### What happens if the sync engine doesn't work out?
121
121
 
122
- It is roughly **70% of total effort** and the single largest risk. Tiers 1–2 shipped in milestone 6 and are under semver; tier 3 local-first shipped in 21.0.0, opt-in per entity (`entity(name, { persist: true })`). The reconnect benchmark that gated topology — 50k sockets, a forced `sync` restart, recovery time and DB load — **is measured at 1.1.0**: all 50,000 reconnected, 49,981 received a channel patch inside the window, p50 54.0s / p90 105.5s, 156,851 connect attempts shed before any query path ([Realtime](Realtime)). That is **reachability** — first patch on the reconnected socket — not consistency; the delivery half is a separate 10,000-client run, **1,666,882 patches received, 0 observed sequence gaps** — a lower bound, since a hole is only visible between two frames one connection received ([Realtime](Realtime)) — and `As of 2026-08` the only run that counts lost patches at all. Both were run on **one** node, so multi-node fanout is still unproven. If the incremental matcher turns out to be the bottleneck, wrapping an existing protocol (Zero's) is an accepted fallback.
122
+ It is roughly **70% of total effort** and the single largest risk. Tiers 1–2 shipped in milestone 6 and are under semver; tier 3 local-first shipped in 21.0.0, opt-in per entity (`entity(name, { persist: true })`). The reconnect benchmark that gated topology — 50k sockets, a forced `sync` restart, recovery time and DB load — **is measured at 1.1.0**: all 50,000 reconnected, 49,981 received a channel patch inside the window, p50 54.0s / p90 105.5s, 156,851 connect attempts shed before any query path ([Realtime](Realtime)). That is **reachability** — first patch on the reconnected socket — not consistency; the delivery half is a separate 10,000-client run, **1,666,882 patches received, 0 observed sequence gaps** — a lower bound, since a hole is only visible between two frames one connection received ([Realtime](Realtime)) — and `As of 2026-08` the only run that counts lost patches at all. Both were run on **one** node. Correctness across nodes — delivery, ordering, cursor resume on a survivor, gap repair — is proven separately over a real NATS bus ([Realtime](Realtime#across-nodes-over-a-real-bus)); multi-node fanout throughput and socket capacity are still unmeasured. If the incremental matcher turns out to be the bottleneck, wrapping an existing protocol (Zero's) is an accepted fallback.
123
123
 
124
124
  ### Why ship realtime last if it's the differentiator?
125
125
 
package/wiki/Home.md CHANGED
@@ -17,7 +17,7 @@ No Docker and no service: embedded Postgres, in-process NATS, local storage, a s
17
17
  | an agent writes most of your code: one way per task, `--json` everywhere, every error a code, a cause and a `fix:` command | you need Node.js or Deno: Bun only |
18
18
  | you want authz written once: one `policy` guards HTTP, live queries, jobs, MCP and admin | your database is not Postgres, or your UI is not SolidJS |
19
19
  | you want jobs, realtime, auth, mail, storage, i18n, SEO, admin and MCP decided and gated | you deploy to Vercel functions, Lambda or Workers: containers only |
20
- | the app may grow: the same code from one PaaS process to Kubernetes | you want a plugin API (an app wraps a primitive instead), or multi-node realtime proven today ([Known gaps](Known-Gaps)) |
20
+ | the app may grow: the same code from one PaaS process to Kubernetes | you want a plugin API (an app wraps a primitive instead), or realtime throughput and socket capacity measured across nodes today — delivery, ordering and resume across nodes are proven, the rates are not ([Realtime](Realtime#across-nodes-over-a-real-bus)) |
21
21
 
22
22
  ## Is it for a project this size
23
23
 
@@ -150,6 +150,9 @@ can see.
150
150
  | An icon with no `label` is decorative and hidden | `Icon` emits `aria-hidden="true"` unless given one |
151
151
  | A live region exists before the message does | `AppShell` renders both `liveRegionAttrs` regions into the server response |
152
152
  | One announcement path per message: `announce()` for a state change with no surface, a toast for a notification | **judgement** — two paths make a screen reader read it twice |
153
+ | A listbox, option, menuitem or treeitem is named, and by its OWN name: a tree branch never by its loading text, an option never by its description (`aria-describedby`), an open listbox by the field's own `<label>`s | `components/a11y-roles.test.ts`; Chrome's accessibility tree in `ui-a11y-roles.e2e.test.ts` |
154
+ | Nothing a Tab lands on is a nameless box: a `Table`'s scroll stop is a region named with its caption | `components/a11y-roles.test.ts` (every component that sets a `tabindex`) |
155
+ | Tab or Escape from an open `Menu` closes it, focus back on the trigger (the APG menu button) | `components/a11y-roles.test.ts`, `ui-a11y-roles.e2e.test.ts` |
153
156
  | Text meets 4.5:1 and the focus ring 3:1, in **both** themes | `packages/ui/src/tokens/contrast.test.ts`, `x verify`'s `unit` step. Shipped pairings only |
154
157
 
155
158
  **No ARIA is better than bad ARIA** — the WAI-ARIA Authoring Practices Guide's own line, and the
@@ -237,6 +240,8 @@ them: [Testing](Testing#seeing-what-you-built).
237
240
  | A drag is Pointer Events with capture from a handle; never HTML5 drag events | `drag/pointer-drag.ts` is the one gesture; `ui-drag.e2e.test.ts` (keyboard, pointer, rtl) |
238
241
  | A drop is a request: `onMove` once, the row held until it settles, a rejection restores and is announced | `sort-controller.test.ts`, `drag-interaction.test.ts` |
239
242
  | Reordering works by keyboard alone and with scripting off | Space/arrows/Esc in `drag-interaction.test.ts`; the per-row `<form>` in `posts/board/page.test.ts` |
243
+ | Only the handle and a separator refuse the browser's pan, so a phone page still scrolls from a card's body | a REAL finger (`E2eTab.touchDrag`) in `ui-drag-touch.e2e.test.ts`: the handle moves a card across columns, the separator resizes, a body drag scrolls and is cancelled with no lift |
244
+ | A drag survives its row moving lists under the pointer | `pointer-drag.ts` takes back a capture the move released; `pointer-drag-bind.test.ts`, and the finger drag above |
240
245
  | A business rule on a drop is `canDrop`, never a fork | **judgement** — the one seam the components take |
241
246
  | Text a model or member wrote renders as a tree, never HTML; only http/https/mailto/relative links | `viewers-no-html.test.ts`, `markdown-parse.test.ts`, no alert under CSP in `ui-viewers.e2e.test.ts` |
242
247
  | A remote image in a body is a link to its alt unless `resolveImage` reserves its box | `viewers.test.ts` |
@@ -38,7 +38,7 @@ Every projection is a method on the job — `onboardOrg.enqueue({ orgId })`, nev
38
38
  | `.parse(raw)` | the payload check | a raw queue payload against the declared `input` |
39
39
  | `.idempotencyKeyFor(input)` | the dedupe key | whatever the declared `idempotencyKey` returned. An empty string throws `X_INVARIANT` at the call — an empty key makes every enqueue look like a duplicate of every other |
40
40
  | `.concurrencyKeyFor(input)` | the concurrency key | `concurrency.key(input)` for a keyed cap, `undefined` otherwise. An empty or non-string key, or one over 200 characters, throws `X_JOB_DECLARATION_INVALID` — the enqueue asks it first, so the refusal reaches the caller |
41
- | `.describe()` | the manifest row | `name`, `input` (JSON Schema), `queue`, `retry: { attempts, backoff }`, `steps`, `idempotent`, `concurrency: { limit, keyed, whenBusy } \| null`. Never a key: both keys are computed from an input, so they are app data |
41
+ | `.describe()` | the manifest row | `name`, `input` (JSON Schema), `queue`, `retry: { attempts, backoff }`, `steps`, `idempotent`, `concurrency: { limit, keyed, whenBusy } \| null`, `onSettled`, `limiter: { name, rate, concurrency } \| null`. Never a key: both keys are computed from an input, so they are app data |
42
42
  | `.kind` `.name` `.queue` `.retry` `.concurrency` `.whenBusy` `.timeoutMs` `.stepTimeoutMs` `.eventPollMs` `.input` | the declaration, lifted | readable, and already **resolved**: `kind` is `'job'`, `queue` is `'default'` when undeclared, `retry` carries the framework defaults merged underneath, `concurrency` is the cap as a number whichever way it was declared (`whenBusy` is set exactly when it is per key), and `timeout` / `stepTimeout` / `eventPoll` are normalized to ms. `stepTimeout` is a ceiling on **one** `step.run`, distinct from `timeout`'s ceiling on the whole job; `eventPoll` is how often `step.waitForEvent` looks. Both were implemented and unreachable until 2.0.0 — a non-positive value is refused at declaration, because `<= 0` reads as "no ceiling" |
43
43
 
44
44
  **One enqueue implementation.** `<job>.enqueue`, `<job>.as` and a [task](Scheduled-Tasks)'s own `enqueue()` all resolve the same ambient facade; the only other calls into a driver's `enqueue` are the outbox relay and the scheduler's occurrence dispatch. So "does this join the transaction?" has one answer for every enqueue an app writes, and there is no second path to forget about.
@@ -211,7 +211,7 @@ export async function onDocSaved(docId: string, revision: number): Promise<void>
211
211
  |---|---|
212
212
  | `onConflict: 'replace'` | debounce. A row of this job under the same key still `ready` or `delayed` takes this `input` and `runAt`, in one statement (`SQL_ENQUEUE_REPLACE`). A `running` or `suspended` holder is untouched — the enqueue is the plain dedupe. Answered `{ deduped: true }` with the holder's ids either way. The holder takes this request's `expiresAt` too — or none, when this request names none. Fenced by request order: a replace no newer than the input a row of the key already holds, live or finished, moves nothing and starts no run — an outbox row the relay publishes again after a crash never puts old input back |
213
213
  | `onConflict: 'dedupe'` | the default: the first payload wins |
214
- | `expiresAt` | epoch ms past which the work is worthless. A claim that finds the row still waiting after it settles it `failed`, `lastError` `JOB_EXPIRED` (`'expired'`), never running the body; `onSettled` hears `dropped`, **at most once** (the claim records no debt). Only a row never claimed expires: a started run — a retry waiting out its backoff included — never is. `x jobs retry` clears the expiry. Lazy: no index, no sweep — an expired row stays `ready`/`delayed` until a claim reaches it |
214
+ | `expiresAt` | epoch ms past which the work is worthless. A claim that finds the row still waiting after it settles it `failed`, `lastError` `JOB_EXPIRED` (`'expired'`), never running the body; `onSettled` hears `dropped`, at least once (the claim records the debt in the same write). Only a row never claimed expires: a started run — a retry waiting out its backoff included — never is. `x jobs retry` clears the expiry. Lazy: no index, no sweep — an expired row stays `ready`/`delayed` until a claim reaches it |
215
215
  | inside a transaction | both are staged with the row (`x_outbox.on_conflict`, `x_outbox.expires_at`); the relay publishes such a row alone through `driver.enqueue`, in staged order, while plain rows around it keep batching |
216
216
 
217
217
  ## Concurrency, rate limits, queues, retry
@@ -235,12 +235,14 @@ export const syncCrm = job({
235
235
  | `concurrency: 4` | max simultaneous runs of **this job**, fleet-wide | one `x_job_leases` row per **held slot**, keyed `(lease_key, slot)` — the primary key is what serialises two workers reaching for the same slot. A driver with no `LeaseStore` refuses the job at worker start (`X_JOB_CONCURRENCY_UNENFORCEABLE`) rather than capping per process |
236
236
  | `concurrency: { key, limit }` | max simultaneous runs **sharing one key** — "one run per account" | the same lease rows, one set per `key(input)`. `key` answers a non-empty string of at most 200 characters; `limit` is a whole number, 1 or more |
237
237
  | `concurrency.whenBusy` | what a claim over the cap does. `'wait'` (default): the run stays queued, no attempt burned. `'fail'`: the run settles **`failed`** with `X_JOB_KEY_BUSY`, its body never runs, nothing retries it, and it is not a dead letter | the worker, at claim. A plain number always waits |
238
- | rate limits | starts per window, per tenant | `concurrencyLimiter({ ratePerTenant })` on the worker — **per process**, never a `job()` field. There is no `rateLimit:` on a job, `As of 2026-11`. A start is a body that ran: a claim handed back over `job.concurrency`, or refused by its key, spends none |
239
- | a **fleet** budget — "600 sends a minute to the mail vendor" | one bucket every worker spends | `@ultimat3/http`'s limiter over the store the boot installs on every role, as the body's FIRST lines, ahead of the first `step.run`: `const vendor = rateLimiter({ config, store: installedRateLimitStore() }); assertRateLimitScope(config, vendor); await vendor.assert(key, bucket)`, with `config = resolveRateLimitConfig({ scope: 'shared', buckets: { vendor: toBucket('<job>', { limit, windowMs }) }, defaultBucket: 'vendor' })` at module scope. `assertRateLimitScope` refuses one process' memory under `'shared'` (`X_RATE_LIMIT_NOT_SHARED`) — N workers would each spend the whole budget. A refusal is `X_RATE_LIMITED`: the run is deferred to its `Retry-After` with the attempt **uncounted**, so a backlog waits for the vendor and is never dead-lettered for waiting. First, because a refusal after a step replays nothing that ran. Pinned by `rate-recipe.job.test.ts`; Postly's `deliverDigest` is the worked use |
238
+ | `limiter: vendorApi` | a **named fleet budget** several jobs share — "the payment provider takes 10 calls a second and 4 at once, whichever job makes them". Declare `export const vendorApi = limiter('vendor-api', { rate: { limit: 10, windowMs: 1_000 }, concurrency: 4 })` ONCE at module scope and import it into every `job({ limiter })`. `rate` is at most `limit` starts in any `windowMs` (sliding, no burst past it); `concurrency` is runs holding it at once. Either or both. `As of 2026-11-14` | the installed driver's `JobDriver.leases` — `x_job_leases` rows keyed `limiter:<name>:rate` (one per start, TTL the window) and `:concurrency` (one per held slot, renewed, released at the end) — gated around the BODY, ahead of the first `step.run`. A run over it throws `X_RATE_LIMITED`, deferred to when the oldest start lapses (1 s for a full concurrency cap) with the attempt **uncounted**. A start is an entry before any step completed or suspended: a resume after `step.sleep`/`waitForEvent`, or a retry past a completed step, spends no rate; a retry after a failed first step spends again. The slot's TTL and renewal are the worker's (visibility timeout, heartbeat, `schedule`). Whole numbers ≥ 1, `rate.limit` and `concurrency` ≤ 1,000, one set of numbers per name: `X_JOB_DECLARATION_INVALID`. No lease store: `X_JOB_CONCURRENCY_UNENFORCEABLE` at worker start. `.describe().limiter` is `{ name, rate, concurrency }`. Pinned by `limiter.live.test.ts` (two replicas, one Postgres) |
239
+ | per-process rate | starts per window, per tenant, in ONE worker | `concurrencyLimiter({ ratePerTenant })` on the worker — **per process**, multiplied by the replica count; a fleet budget is `limiter` above. A start is a body that ran: a claim handed back over `job.concurrency`, or refused by its key, spends none |
240
+ | a budget keyed by **request data** (per customer, per API key) | one bucket per key every worker spends | `@ultimat3/http`'s limiter over the store the boot installs on every role, as the body's FIRST lines, ahead of the first `step.run`: `const vendor = rateLimiter({ config, store: installedRateLimitStore() }); assertRateLimitScope(config, vendor); await vendor.assert(key, bucket)`, with `config = resolveRateLimitConfig({ scope: 'shared', buckets: { vendor: toBucket('<job>', { limit, windowMs }) }, defaultBucket: 'vendor' })` at module scope. `assertRateLimitScope` refuses one process' memory under `'shared'` (`X_RATE_LIMIT_NOT_SHARED`). A refusal is `X_RATE_LIMITED`, deferred uncounted like `limiter`'s. Pinned by `rate-recipe.job.test.ts` |
240
241
  | `maxInFlight` | max simultaneous runs in **one worker process**, across every queue it serves — Sidekiq's `concurrency`. `jobs.maxInFlight` in `app.config.ts`, or `jobWorker({ maxInFlight })`; unset, no process cap | read before every claim, so a worker at the cap claims nothing; each run that ends frees one claim at once. The per-queue `jobs.concurrency` slots still bound each queue under it. A pass splits its room over the queues (`ceil(room / queues left)`), hands what an empty queue leaves to the next, and starts after the last queue served — no queue starves. `worker.stats().maxInFlight`, gauges `job_worker_in_flight` / `job_worker_capacity`. `0`, fractional, `NaN`, `Infinity`: `X_INVARIANT` / `X_CONFIG_INVALID` |
241
242
  | `maxPending` | back-pressure: an enqueue onto a queue already holding that many `ready` + `delayed` rows is `X_JOB_BACKLOG_FULL`, a 429 (`JobBacklogFullError`); an `enqueueMany` that would cross it is refused whole, nothing written. Omitted, no ceiling. `As of 2026-11-12` | one capped count before the write (`JobDriver.backlog`, `SQL_BACKLOG`), on the direct and the staged path, plus the rows the caller's own transaction already staged for the queue (a key staged twice counts once). An enqueue that adds no row — a dedupe, or a replace onto the key's live holder (`JobDriver.holds`, asked only once full) — is never refused. Soft, not a quota: concurrent producers can overshoot by their number, and committed rows the relay has not yet published are counted by nobody. A driver with no `backlog` refuses a job declaring it at enqueue (`X_INVARIANT`) |
242
243
  | `queue` | named pool; the `worker` role runs one pool per config (`WORKER_QUEUES=default,integrations`) | worker pool sizing, see [Deployment](Deployment) |
243
244
  | priority | **a separate queue**, never a field: `queue: 'urgent'` on the job, and workers whose `WORKER_QUEUES` lists it (with its own `jobs.concurrency` slots, or a pool of its own). Inside one queue the claim takes the earliest `runAt` first, and nothing reorders it. `As of 2026-11`: no `priority` column — it would widen the claim index of the hottest table for an order a second queue already gives, and isolates better (a flood of low-priority work cannot hold the slots) | the claim, per queue |
245
+ | batches — a job that fans out and **awaits its children** | **durable steps, never a field**: `const ids = await step.run('fan-out', () => child.enqueueMany(inputs).then((r) => r.map((one) => one.id)))`, then one `step.waitForEvent(\`child:${id}\`, 'child.done', { schema, match: id })` per persisted id; the child's `onSettled` calls `publishEvent('child.done', { … }, { correlationKey: settled.jobId })`. The names come from a step's stored output, so they are stable across replays. No `batch()` primitive: the parent is a job, every child is a job, and the wait is a step (`As of 2026-11-14`) | `x jobs show <parent>` lists one wait per child |
244
246
  | `retry.attempts` / `backoff` | `'exponential' \| 'linear' \| 'fixed'` | driver scheduler |
245
247
  | `retry.jitter` | core's `JitterMode`: `'equal'` by default — half fixed, half rolled — so a job that has already failed twice is never handed a near-zero wait; `'none'` and `'full'` on request. A boolean was the v30 shape ([Upgrading](Upgrading) entry 60) | driver scheduler |
246
248
  | a **`terminal`** thrown code | stops on the attempt that failed, before `attempts` is reached — the same code run again is the same answer, and the attempts left are a queue slot, a provider bill, or three more wrong passwords at a site that locks the account after three. `lastError` records `— not retried: this code is classified terminal`, so an early stop is never silent | the code's `retry` classification, `registerErrorRetry({ X_YOUR_CODE: 'terminal' })`. An **unclassified** code is unaffected |
@@ -375,7 +377,7 @@ Every operator capability is a member of `JobIntrospection` (`driver.introspect`
375
377
  | who is working | `workers()` — id, host, started, queues, slots, in-flight job ids, last heartbeat | a row expires `max(60 s, visibility timeout)` after its last renewal, renewed every third of that (20 s); a killed worker leaves by expiry, so it stays listed up to 60 s. As of 2026-11-12 |
376
378
  | history | `counters({ job, sinceMs })`, `counterTotals(sinceMs)` — `done`, `retried`, `failed`, `dead`, `durationMs` | `COUNTER_TIERS`: 1-minute buckets for 24 h, 5-minute for 7 d, 1-hour for 30 d. On Postgres a process batches its settles' counts and writes them every 10 s and on `close()`: a read from the same process flushes first, one from another process can lag up to 10 s, and a crash loses at most 10 s of counts — never a job row's state |
377
379
  | progress | `run({ progress })` → `progress(done, total, note?)`, on the row and in `x jobs show` | one write a second per run at most, and always the last before the run settles |
378
- | how a run ended | `job({ onSettled })` — `completed` (with what `run` returned), `dead-lettered`, `dropped` or `refused`; after the row is settled, under the job's tenant, three tries of its own, on a live `ctx.signal` under `onSettledTimeout` (30 s by default): its `fetch` and its writes land | at least once across a crash (`redriven: true` on the re-drive), but at most once for a completion whose body returned a value and for a row the claim settles (a final-attempt burial, an expiry); a hook that keeps failing is `X_JOB_ON_SETTLED_FAILED`, logged and reported, and the row is untouched. A cancel is not a settlement: whoever cancels is the observer |
380
+ | how a run ended | `job({ onSettled })` — `completed` (with what `run` returned), `dead-lettered`, `dropped` or `refused`; after the row is settled, under the job's tenant, three tries of its own, on a live `ctx.signal` under `onSettledTimeout` (30 s by default): its `fetch` and its writes land | at least once across a crash (`redriven: true` on the re-drive), but at most once for a completion whose body returned a value; a hook that keeps failing is `X_JOB_ON_SETTLED_FAILED`, logged and reported, and the row is untouched. A cancel is not a settlement: whoever cancels is the observer |
379
381
 
380
382
  ```ts
381
383
  export const syncAccount = job({
@@ -408,7 +410,7 @@ export const syncAccount = job({
408
410
  | `dead-lettered` / `dropped` | failed for good; `dropped` is a job declaring `retry.deadLetter: false`. Carries `error` (the row's `lastError`), `code` (its `X_*` code, when it has one) and `input` — `undefined` when the stored payload no longer parses |
409
411
  | `refused` | `whenBusy: 'fail'` over a busy key. The body never ran; `code` is `X_JOB_KEY_BUSY` |
410
412
  | never called for | a retry, a suspension, a drain, a row cancelled or removed by a caller, a settle that did not land |
411
- | delivery | **at least once** per ending a worker settles: a worker killed between the settle and the hook leaves a debt (`x_jobs.settle_owed`) the scheduler leader re-drives past `onSettledTimeout` × 3, with `redriven: true, reason: 'lost'` — write the hook to be repeated. **Except**, at most once: a completion whose body returned a value, as a result is never stored (planned for `next`); and a row the claim settles itself — a final-attempt lease lapse buried `dead`, an expired row — as the claim records no debt. What must be recorded for certain is written by the body, inside a `step.run` |
413
+ | delivery | **at least once** per ending a worker settles: a worker killed between the settle and the hook leaves a debt (`x_jobs.settle_owed`) the scheduler leader re-drives past `onSettledTimeout` × 3, with `redriven: true, reason: 'lost'` — write the hook to be repeated. A row the claim settles itself — a final-attempt lease lapse buried `dead`, an expired row — owes it too, recorded by the claim. **Except**, at most once: a completion whose body returned a value, as a result is never stored (planned for `next`). What must be recorded for certain is written by the body, inside a `step.run` |
412
414
  | failure | three tries back to back, all inside one `onSettledTimeout` (30 s by default), which aborts `ctx.signal` with `X_JOB_TIMEOUT` and gives the worker its slot back; then `X_JOB_ON_SETTLED_FAILED`. The job's outcome never changes |
413
415
 
414
416
  | Fact | Detail |
@@ -50,7 +50,7 @@ CHANGELOG.md` finds its bounds, and it changes on any commit.
50
50
  | A pod evaluates the framework from **source**, one module at a time — ~28 Mi of resident memory per pod that a bundle would not hold | `As of 2026-10-01`, measured on the framework serve graph alone: 1,071 modules from source settle at **80.4 Mi**; the same graph as one `bun build --target=bun` file is 5 modules and settles at **51.8 Mi** — ~34 kB of RSS per source module, the runtime's cost and not the code's. It is the largest saving left after the per-role load and the prebuilt store (a web pod of the demo app settles at 97–102 Mi, a worker at 80–85 Mi). **Not a patch**: a registry is a module instance, so the framework bundled apart from the app is two `@ultimat3/jobs`, two `@ultimat3/entity` — the app registers into one and the boot reads the other. The unit has to be the app **and** the framework as one graph, per role, built inside the image build from a generated entry that imports what `scanAppModules` would, with the `.tsx`/`.scss` loaders as build plugins. Containers only either way (axiom 7). Design note: [`docs/architecture/13-topology-runtime.md`](https://github.com/developerz-ai/ultimate/blob/main/docs/architecture/13-topology-runtime.md#not-built-one-bundle-per-role) pin: none — a resident-memory measurement of a running pod, not a behaviour a unit test can assert | nothing to do in an app. Size a pod's memory request from `process_resident_memory_bytes` on `/metrics`, not from a guess |
51
51
  | Every role evaluates all of `@ultimat3/jobs` — 96 modules (`As of 2026-10-02`, by file) — whatever it runs | `As of 2026-10-01`, read off the serve graph by the names each role's code uses: a `web` pod needs 43 of them (enqueue, the outbox relay, the purge task), a `scheduler` 46, a `worker` 62. The rest ride the barrel: `worker.ts` and its eighteen dependencies in a web pod, the `backfill()` / `exportJob()` / `webhook()` factories (17 modules, 123 kB of source) in an app that declares none, and the memory driver (3 modules) outside a test. ~1.6 Mi per web pod at the measured 34 kB a module. Closing it means subpath entries (`@ultimat3/jobs/worker`, one per factory) and every importer rewritten — a breaking move for a saving the per-role bundle above makes moot, so it waits on that decision. The operator surface is **not** in this list: `JobIntrospection` is a member of the driver, and the worker announces itself and counts settles through it pin: none — a module count read off a role's serve graph, measured rather than asserted | nothing to do in an app |
52
52
  | A job's `runAt` is stamped from the enqueuer's clock | `As of 2026-10`. An enqueuer running ahead of the database delays its own "immediate" jobs; up to 1 s ahead still wakes a worker, beyond that the job starts on the poll. A delayed job enqueued by another process starts within the idle ceiling after its `runAt` — 5 s with a proven wake, 2 s without; only a retry or a sleep the worker itself handed back gets a due-time timer | NTP on every pod; for a deadline tighter than the ceiling, enqueue at the moment the work is due rather than with `runAt` |
53
- | `onSettled` for a completion that **returned a value**, or a row the claim settles, runs at most once across a crash | `As of 2026-11-12`. Every ending a worker settles is at least once: the settle records the debt in its own write (`x_jobs.settle_owed`) and the scheduler leader re-drives a dead worker's with `redriven: true, reason: 'lost'` — failures, dead letters, refusals, and completions whose body returned `undefined`. A row the CLAIM settles is at most once too: a final-attempt lease lapse buried `dead` and an expired row are told by the claiming worker, and the claim records no debt (`packages/jobs/src/claim-exhausted.ts`). A body's return value is never stored (`x_jobs` has no result column), so a re-drive could only hand `result: undefined` to a hook typed for a value; on a minor that would break every `onSettled` reading `result`. Storing the result, and so at-least-once for every completion, is planned for `next` [pin](https://github.com/developerz-ai/ultimate/blob/main/packages/jobs/src/settle-redrive.test.ts#a%20completion%20that%20returned%20a%20value%20owes%20nothing%3A%20told%20once%2C%20at%20most%20once) | write what must be recorded for certain inside the body, in a `step.run`; or have the body return nothing and read what it wrote from there |
53
+ | `onSettled` for a completion that **returned a value** runs at most once across a crash | `As of 2026-11-14`. Every other ending is at least once: the write that settles the row records the debt (`x_jobs.settle_owed`) and the scheduler leader re-drives a dead worker's with `redriven: true, reason: 'lost'` — failures, dead letters, refusals, completions whose body returned `undefined`, and the rows the CLAIM settles (a final-attempt lease lapse buried `dead`, an expired row: `ClaimOptions.settleOwed`, `packages/jobs/src/claim-exhausted.ts`). A body's return value is never stored (`x_jobs` has no result column), so a re-drive could only hand `result: undefined` to a hook typed for a value; on a minor that would break every `onSettled` reading `result`. Storing the result, and so at-least-once for every completion, is planned for `next` [pin](https://github.com/developerz-ai/ultimate/blob/main/packages/jobs/src/settle-redrive.test.ts#a%20completion%20that%20returned%20a%20value%20owes%20nothing%3A%20told%20once%2C%20at%20most%20once) | write what must be recorded for certain inside the body, in a `step.run`; or have the body return nothing and read what it wrote from there |
54
54
  | A `step.run` output past 256 KiB is stored with a warning, not refused | `As of 2026-11-12`. Undeclared, `STEP_OUTPUT_MAX_BYTES` logs `jobs.step.output-too-large` (`X_STEP_OUTPUT_TOO_LARGE`) once per job and step and stores the output, because refusing by default would fail shipped jobs on a minor; every attempt still loads it. Refusal by default is planned for `next` [pin](https://github.com/developerz-ai/ultimate/blob/main/packages/jobs/src/steps-output.test.ts#the%20default%20256%20KiB%20warns%20once%20per%20job%20and%20step%2C%20with%20the%20code%2C%20and%20still%20stores) | declare `job({ stepOutputMax: 262_144 })` to be refused now, and persist the payload, returning its key from the step |
55
55
  | The CDP driver cannot PIN a name, and a page's WebSocket is not screened at all | `As of 2026-11`. Measured on Chrome 150 with `localBrowser()`: interception (page-level and the browser-level `Fetch` that now covers popups) never pauses a WebSocket handshake, so `new WebSocket('ws://off-list/…')` from a scraped page connects. Since 31.0.0 a host a wildcard admitted is resolved before the browser leg releases it, and an inward or unresolvable answer is refused (`packages/scraping/src/browser-dial.ts`). But the browser then resolves again for itself, so a name that answers public to the screen and private to Chrome (DNS rebinding) is reached — the HTTP leg and the robots read resolve and pin (`packages/scraping/src/pinned-host.ts`), the browser cannot be pinned through this port — [pin](https://github.com/developerz-ai/ultimate/blob/main/packages/scraping/src/cdp-arm-dial.test.ts#a%20screened%20name%20is%20continued%20by%20request%20id%20only%2C%20never%20pinned%20to%20the%20approved%20address) | list exact hosts rather than `'*'` on a scrape that runs where private addresses are reachable, and dial a scrape through an `egress` proxy outside that network |
56
56
  | `ScrapeReport.usage.bytesIn` counts the HTTP leg only | `As of 2026-10`. The CDP port subscribes to requests, not to their sizes, so the browser leg's bytes are not in the figure (`packages/scraping/src/usage.ts`) | treat `bytesIn` as a lower bound; a provider's own byte count, returned through the resolver's `cost`, is the billable one |
@@ -79,7 +79,6 @@ Each of these is a defect somebody has already argued about, and the reasoning i
79
79
 
80
80
  | Open | Where it stands |
81
81
  |---|---|
82
- | Multi-node realtime | the forced-restart benchmarks **are** measured, on one `sync` node over `InProcessTransport` — neither run crossed NATS and neither subscribes to a live query, so no cursor, snapshot or gap-repair path is under test. Fanout, throughput and per-node socket capacity across nodes remain targets → [Realtime](Realtime) |
83
82
  | `x db studio` | planned. `X_DB_STUDIO_FAILED` is reserved and not thrown; the command exits `X_NOT_IMPLEMENTED` pointing at `x dev` → the `/_x` db panel. Keeping a `bunx drizzle-kit studio` shell-out would have meant a second schema engine for one subcommand |
84
83
  | `api/**/route.ts` | not a file kind — owner decision 1 ([#648](https://github.com/developerz-ai/ultimate/issues/648)), `As of 2026-10`. `api/` holds the action and query projections `defineApi()` collects; a route file there is refused at registration (`X_ROUTE_FILE_INVALID`), and 26.0.0 deleted `ROUTE_FILENAME`'s `api` row ([#709](https://github.com/developerz-ai/ultimate/issues/709)). A wire format an action cannot speak — a webhook receiver, an OAuth endpoint — is a plain HTTP route in the `routes` runtime override ([Configuration](Configuration)) |
85
84
  | Deferred, `As of 2026-10-07` | the plugin API and multi-region replication. The Redis **job** driver shipped (`redisJobDriver()`, #710) without the operator surface, backfill bookkeeping or fleet-wide `concurrency` — those answer on Postgres only; the NATS job driver stub that threw `X_NOT_IMPLEMENTED` was deleted in 25.0.0. |
@@ -639,7 +639,8 @@ export const summarize = llm({
639
639
  | Caching | semantic cache from [Caching and invalidation](Caching-And-Invalidation) |
640
640
  | Provider prompt caching | the provider keeps a request's stable prefix; on by default for `agent()`, off for `llm()` → [Agents](Agents#provider-prompt-caching) |
641
641
  | Tracing | one OTel span per call with model, tokens, cache hit, prompt version |
642
- | Fallback | ordered provider list per model; the provider that answered is on the span as `gen_ai.provider.name`, never silent. A refusal names a more capable model for the declaration to adopt — models are never swapped at runtime |
642
+ | Fallback | ordered provider list per model; the provider that answered is on the span as `gen_ai.provider.name`, never silent. Across models only through a declared `fallbackModels` chain → [Model fallback](#model-fallback-fallbackmodels). A refusal names a more capable model for the declaration to adopt — never an automatic swap |
643
+ | Provider parameters | `providerOptions: { openai: { top_p: 0.9 } }` — one bag per wire, keys screened → [Provider parameters](#provider-parameters-provideroptions) |
643
644
  | Money | `Money = { minor, currency }` — never a float → [Money](Money) |
644
645
 
645
646
  **A stream is the same action over a different transport, with one difference that is forced rather than chosen: there is no repair turn.** The non-streaming call retries once on a parse failure; a stream cannot, because the tokens are already on the reader's screen and a second answer is two answers to one question. So a stream yields **unvalidated** text increments plus one final `done` carrying the value that did satisfy `output`, and a schema disagreement is `X_LLM_STREAM_INVALID` naming the non-streaming call as the fix. A structured schema wants the non-streaming call.
@@ -664,6 +665,106 @@ and usage records are `JsonView`; a model's proposed edit against the original i
664
665
 
665
666
  Long or multi-call chains are `job`s with steps, so a model call that fails on step 4 retries step 4 only. See [Jobs and workflows](Jobs-And-Workflows).
666
667
 
668
+ ### Model fallback: `fallbackModels`
669
+
670
+ **A second model is asked only when the first fails with a declared class, and only because the
671
+ declaration named it** — on `llm()`, on `agent()` (every turn walks the chain; a run's own
672
+ `model()` pick is left out of it), or on a raw `GenerateRequest`. `As of 2026-11`.
673
+
674
+ ```ts
675
+ import { definePrompt, llm, t } from '@ultimat3/ai';
676
+ import { allow } from '@ultimat3/policy';
677
+
678
+ const digestPrompt = definePrompt<{ postId: string }>({
679
+ id: 'digest',
680
+ version: '1.0.0',
681
+ template: 'Summarise post {{postId}} in one sentence.',
682
+ });
683
+
684
+ export const digest = llm({
685
+ model: 'claude-sonnet-5-5',
686
+ fallbackModels: ['gpt-5.6-terra'], // tried in order; each one registerModel-ed
687
+ providerOptions: { openai: { top_p: 0.9 } }, // read only by a chat-completions provider
688
+ input: t.object({ postId: t.uuid }),
689
+ output: t.object({ summary: t.string }),
690
+ prompt: digestPrompt,
691
+ vars: ({ input }) => ({ postId: input.postId }),
692
+ policy: allow(),
693
+ });
694
+ ```
695
+
696
+ | Falls over (`MODEL_FALLBACK_ON`) | Read from |
697
+ |---|---|
698
+ | `rate_limited` | 429 |
699
+ | `overloaded` | 529 |
700
+ | `timeout` | 408, 504, `ETIMEDOUT` |
701
+ | `unavailable` | any other 5xx, a refused or dropped socket, every provider's breaker open |
702
+
703
+ Never on a 4xx, a refusal, a truncation, a budget refusal, an abort, or a model no provider lists:
704
+ each fails the same way on every model. The verdict is reached after the gateway's provider retries
705
+ for that model ran out, and only when **every** failure had a class.
706
+
707
+ | Rule | Detail |
708
+ |---|---|
709
+ | billed per attempt | each model reserves its own estimate and settles on its own; the run meter (`meteredRun`, `meta.billed`) counts a failed model as an `unsettled` attempt, never as free — also when the chain's last model fails outside the class and that error is thrown as it stands |
710
+ | priced per model | a fallback's answer is billed at its own model's rate, never folded into the primary's; `onCall` / `onTurn` name the model that answered |
711
+ | one trace | the caller's span is the one parent; each model is an `ai.model.attempt` child with `gen_ai.request.model`, `ultimate.llm.fallback.index` and, on failure, `ultimate.llm.fallback.reason`. A call with no chain opens none |
712
+ | visible | `GenerateResult.fallbacks` lists each failed model, its class and cause |
713
+ | streams | fall over only before the first chunk reaches the reader; after it, the failure is thrown as it stands |
714
+ | the chain | screened before any request: an unregistered id is `X_AI_MODEL_UNKNOWN`, a repeated one `X_AI_REQUEST_INVALID` |
715
+ | all fail | one `X_AI_PROVIDER_UNAVAILABLE` naming every model, `a → b` |
716
+ | `retry.timeBudgetMs` | one clock for the whole chain, checked before every call after the first — the next provider, the next model; a call that ran out of time does not fall over |
717
+
718
+ ### Provider parameters: `providerOptions`
719
+
720
+ **A wire parameter the framework does not model passes through one typed bag per wire, screened
721
+ key by key before any request.** The keys are the wire's own names. `As of 2026-11`.
722
+
723
+ | Wire | Keys (`PROVIDER_OPTION_KEYS`) |
724
+ |---|---|
725
+ | `anthropic` | `metadata` (`{ user_id }`), `service_tier` (`'auto'`, `'standard_only'`) |
726
+ | `openai` | `frequency_penalty`, `presence_penalty` (-2 to 2), `top_p` (0 to 1), `user`, `parallel_tool_calls`, `service_tier` (`'auto'`, `'default'`, `'flex'`, `'priority'`) |
727
+
728
+ An unknown wire, an unknown key, a wrong type or an out-of-range number is `X_AI_REQUEST_INVALID`:
729
+ at declaration on `llm()` and `agent()`, in the gateway for a raw `generate`/`stream`, and in each body builder for
730
+ a direct provider call. Each provider sends its own wire's bag only, so one request may carry both
731
+ when its `fallbackModels` cross formats. The bag is part of the response cache key. A key the
732
+ framework sets itself (`temperature`, `seed`, `max_tokens`, `tools`, …) is not in the table.
733
+
734
+ ## Prompt caching on your own endpoint
735
+
736
+ **An endpoint the built-in table does not name gets no cache mark until its provider declares
737
+ one.** A self-hosted or company gateway speaking the OpenAI format says how it is told on its own
738
+ provider, never in a process-wide registry: the provider already is the wire and the host. `As of
739
+ 2026-11`.
740
+
741
+ ```ts
742
+ import { openAiProvider } from '@ultimat3/ai';
743
+
744
+ export const internalProvider = openAiProvider({
745
+ baseUrl: 'https://llm.internal.example/v1',
746
+ models: ['family/large'],
747
+ promptCache: { rules: [{ model: 'family/', marks: 'parts', session: 'x-session-id' }] },
748
+ });
749
+ ```
750
+
751
+ | Step | What decides the marks for one request |
752
+ |---|---|
753
+ | 1. the provider's rows | `promptCache.rules`, first match by model-id prefix (`''` is every model) |
754
+ | 2. the built-in table | `PROMPT_CACHE_RULES`: any Anthropic Messages endpoint, `openrouter.ai`, `api.openai.com` → [Agents](Agents#provider-prompt-caching) |
755
+ | 3. nothing | no mark and no session field: a field a self-hosted server has never heard of can be a 400 |
756
+
757
+ | Row field | `openAiProvider()` | `anthropicProvider()` |
758
+ |---|---|---|
759
+ | `marks` | `'parts'` (stable system part + the tail message's last part) or `'none'` | `'blocks'` or `'none'` |
760
+ | `session` | `'x-session-id'` header, `'prompt_cache_key'` body field, or `'none'` | `'none'` only |
761
+
762
+ A row the wire cannot speak — `blocks` on chat-completions, `parts` or a session on the Messages
763
+ wire, a row that is not `{ model, marks, session }` — is `X_AI_REQUEST_INVALID` when the provider
764
+ is built, never a 400 on every hinted call. The rows only say *how*; *whether* a call asks is still
765
+ `promptCache` on the declaration (`agent()` `'auto'`, `llm()` `'off'`), and the budget reserves the
766
+ cache-write rate exactly where a mark is sent.
767
+
667
768
  ## Agents, hives and agent jobs → [Agents](Agents)
668
769
 
669
770
  `llm()` is one model call. A **tool-using loop** is `agent()`, and it is the same kind of thing — an action factory, not a ninth primitive. Everything the loop needs is a factory over a primitive already in the vocabulary:
package/wiki/Mail.md CHANGED
@@ -107,6 +107,58 @@ an hour later is not refused by the signature window. Declaring it is its regist
107
107
  mounts its route. `api/` holds no route file.
108
108
  `SES_CONFIGURATION_SET` names the SES configuration set sent on every message (`ConfigurationSetName`) — the set whose event destination publishes to that SNS topic.
109
109
 
110
+ ## Inbound mail: `@ultimat3/mail/inbound`
111
+
112
+ `As of 2026-11-15`. Rule: received email is `inboundMail()`, a factory over
113
+ [`webhookReceiver()`](Jobs-And-Workflows#inbound-webhooks) — never a ninth primitive, never a route
114
+ file. Declared in `defineApi({ jobs })`, the boot mounts its `POST path`.
115
+
116
+ ```ts
117
+ import { inboundMail, resendInbound } from '@ultimat3/mail/inbound';
118
+
119
+ export const supportInbox = inboundMail({
120
+ name: 'support.inbound',
121
+ path: '/hooks/mail/inbound',
122
+ // A thunk, built on the first delivery: every role imports this, only the web role receives.
123
+ provider: () =>
124
+ resendInbound({
125
+ secret: Bun.env['RESEND_INBOUND_SECRET'] ?? '',
126
+ apiKey: Bun.env['RESEND_API_KEY'] ?? '',
127
+ }),
128
+ tenant: 'none',
129
+ handle: async ({ message }) => ({ subject: message.subject }),
130
+ });
131
+ ```
132
+
133
+ | Step | Where | What |
134
+ |---|---|---|
135
+ | verify | the door | the provider's signature over the exact bytes — before any parse. SNS via `sesEventReceiver`'s verifier, Svix via `resendEventReceiver`'s. A forgery is `X_MAIL_EVENT_UNVERIFIED` (401) and queues nothing |
136
+ | queue | the door | the verified envelope (`recipients`, and SES's `content` or Resend's email id), `.sensitive()` |
137
+ | fetch | the job | SES: the row's `content`. Resend: `GET /emails/receiving/:id` with the API key, then the signed `raw.download_url` without it |
138
+ | parse | the job | in-tree, bounded MIME: multipart trees, base64 / quoted-printable, RFC 2047 words, RFC 2231 filenames, address groups |
139
+ | store | the job | each attachment through storage's `validateUpload` (size, allowlist, sniff) and `put`, at a key derived from the message id |
140
+ | handle | the job | your function, with one `InboundMessage`, at least once per `eventId` |
141
+
142
+ | Bound | Default | Refusal |
143
+ |---|---|---|
144
+ | `limits.maxBytes` | 10 MiB | `X_MAIL_INBOUND_TOO_LARGE` (`meta.limit`) — refused whole, never truncated |
145
+ | `limits.maxParts` · `maxDepth` | 100 · 8 | the same |
146
+ | `limits.maxAttachments` · `maxHeaderBytes` | 20 · 64 KiB | the same |
147
+ | unreadable MIME | — | `X_MAIL_INBOUND_MALFORMED` (`meta.problem`), terminal |
148
+
149
+ **Sender-controlled, unsanitised:** `html`, every `filename`, every `contentId`, `subject`, the
150
+ address names. Never render `html` on the app's origin (a sandboxed frame, or text); never use a
151
+ `filename` as a path. `recipients` comes from the provider's signed payload, never a header: SES's
152
+ is the SMTP envelope; Resend's is its `to`, not documented as the envelope — route only on your
153
+ own receiving domain. An SES virus verdict of `FAIL` stores no attachment (`refusal: 'verdict'`)
154
+ unless `attachments: { keepOnVirusFail: true }`.
155
+
156
+ An attachment the upload policy refuses (HTML, SVG, a type the sniff contradicts) arrives
157
+ `stored: false` with storage's code — or `X_MAIL_INBOUND_MALFORMED` when its transfer encoding does
158
+ not decode; the message is still delivered (only an undecodable text or HTML BODY refuses it). `attachments: { disk, policy,
159
+ prefix }` overrides each part; `attachments: false` stores nothing. SES's spam/virus/SPF/DKIM/DMARC
160
+ verdicts ride on `message.verdicts` — what to do about a `FAIL` is the app's decision.
161
+
110
162
  ## Previews
111
163
 
112
164
  `As of 2026-11-06`. `defineMail({ preview })` declares the data a template is checked by: a value,
package/wiki/Realtime.md CHANGED
@@ -599,7 +599,23 @@ arrived meanwhile after it. A dropped `events` frame is ephemeral by design and
599
599
  already repairs the same drop, as it has since 2026-08: the subscriber is marked desynced, and the
600
600
  next change re-snapshots it.
601
601
 
602
- What it is **not**: a multi-node result — neither run crossed NATS, so this is **per-node recovery**, not fanout. Not a throughput figure either: no requests/sec, no message rate, no sustained-load number. Per-node socket capacity in the tables above this section is still a target derived from Bun's native WebSocket implementation, not a benchmark result. Long-running Bun processes are also less battle-proven than Node's; sustained-socket memory profiling is explicit roadmap work.
602
+ What it is **not**: a multi-node result — neither run crossed NATS, so this is **per-node recovery**, not fanout; the cross-node claims are the next section's, proven by a test and not by this benchmark. Not a throughput figure either: no requests/sec, no message rate, no sustained-load number. Per-node socket capacity in the tables above this section is still a target derived from Bun's native WebSocket implementation, not a benchmark result. Long-running Bun processes are also less battle-proven than Node's; sustained-socket memory profiling is explicit roadmap work.
603
+
604
+ ## Across nodes, over a real bus
605
+
606
+ `As of 2026-11-14`, proven by `bun test ./packages/realtime/src/multi-node.live.test.ts` (needs `TEST_NATS_URL`): two `sync` nodes, each on its own NATS connection and its own port, the replicator on a third, pages on real websockets through `LiveClient`. Loss and duplication are read off the frames each page received, never off its state.
607
+
608
+ | Claim | What the suite does |
609
+ |---|---|
610
+ | An event published on one node reaches a member on another, in publish order | 50 `publishEvent` calls through node A's hub, the member seated on node B: all 50, in order |
611
+ | A replicated change reaches every node's pages, each in lsn order | 40 commits, a page on each node: one snapshot each, then 40 patches, none at or below the position already held |
612
+ | A page whose node dies resumes on a survivor **from its cursor** — no loss, no duplicate | node A's sockets ended with no `reconnect` frame and its bus dropped mid-stream; the page redials node B once, and B replays its retained window: still one snapshot in total, each of the 60 commits exactly once |
613
+ | A node restarted empty serves the returning page one snapshot, and the stream goes on from it | the page's cursor names a window the new node never held: one snapshot holding what was written while it was down, then patches above it |
614
+ | A node that misses changes on the bus detects it and re-serves its pages **with no later write** | only that node's bus is cut (a relay); 20 commits go past it, then nothing. On reconnect (`live.bus_reconnected`) every window is re-read at once and its pages re-snapshotted |
615
+
616
+ The last row was a defect the suite found: a bus reconnect or a replicator resync marked every window and repaired it only on the next change the node heard, so a quiet query showed its pre-outage rows until a write or the idle sweep (`idleTimeoutMs / 4`, 30 s by default). Both now repair at once (`sync-bus-handlers.ts`, `sync-bus-repair.test.ts`). A gap seen on a message needed no change: that message's delivery reaches every stale window.
617
+
618
+ Delivery is at most once on the bus and exactly once to the page: a lost bus message is a gap the node detects (`SeqGapDetector`, or the reconnect itself) and answers with a snapshot, and a patch at or below the cursor is refused by the window's lsn guard. The "kill" is in-process — listener stopped with its sockets, node stopped, bus closed, no drain — which is what a `SIGKILL` leaves the page and the bus to find. **Still targets, not results:** cross-node fanout throughput and per-node socket capacity; nothing here measures a rate.
603
619
 
604
620
  ## `sync` drain
605
621
 
@@ -135,7 +135,7 @@ Fixed **1**. Cron dispatch only.
135
135
  | Renewal | `acquire()` **is** the renewal, sent every `ttlMs / 3` (20s) — tick 1s, lease TTL `DEFAULT_LEADER_TTL_MS` = 60s. A node that stops renewing loses the lease by expiry, with nothing to clean up: a killed leader's standby takes over up to ~80s later (the 60s lease, then its next ask), a drained one's within 20s (the drain deletes the row; the standby's next ask takes it). As of 2026-11-12 |
136
136
  | Second instance | a warm standby, not a duplicate. It calls `acquire()` every `renewEveryMs` (20s), the cadence the leader renews on, not every round; while another node holds an unexpired row it acquires nothing and dispatches nothing, and its first ask after that row expires takes the row and makes it the leader |
137
137
  | Leadership lost | logged once as `jobs.scheduler.leadership-lost`; the node keeps polling and takes over on its first ask (every 20s) after the holder's lease expires. **The process does not exit**, and neither does a `replicator` container that loses its lock: it stands by unready and re-asks. Only `x dev --role replicator` refuses (`X_REPLICATOR_SLOT_HELD`) |
138
- | `/readyz` on the standby | there is none. `ROLE=scheduler` binds the metrics port only (`/metrics`, `METRICS_PORT`, default 9090) and no HTTP server, so liveness is that endpoint — the probe [`docs/ops/01-kubernetes.md`](https://github.com/developerz-ai/ultimate/blob/main/docs/ops/01-kubernetes.md) declares. Nothing routes request traffic to a scheduler in the first place |
138
+ | `/readyz` on the standby | on the metrics port only: `ROLE=scheduler` binds `METRICS_PORT` (default 9090) and no HTTP server. Liveness is `/healthz` there, 503 once the dispatch loop stops turning — the probe [`docs/ops/01-kubernetes.md`](https://github.com/developerz-ai/ultimate/blob/main/docs/ops/01-kubernetes.md) declares. Nothing routes request traffic to a scheduler in the first place |
139
139
  | Missed tick (leader down, node paused, clock jump) | **fires late rather than being skipped** |
140
140
  | Double fire during handover | absorbed by the enqueued job's `idempotencyKey` — the second enqueue returns the existing handle, no new row |
141
141
  | Drain on SIGTERM | registered at the `accept` phase: stop dispatching, wait out the dispatch round in flight, then delete the lease row — the standby promotes on its next round rather than waiting out the TTL, and never onto an occurrence this node is still enqueueing for |