@ultimat3/cli 31.13.1 → 31.15.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 (49) hide show
  1. package/CLAUDE.md +1 -1
  2. package/README.md +2 -1
  3. package/package.json +29 -29
  4. package/src/budgets-requests.ts +37 -0
  5. package/src/budgets.ts +20 -1
  6. package/src/dev-boot.ts +2 -2
  7. package/src/dev-route-table.ts +5 -9
  8. package/src/document-options.ts +0 -7
  9. package/src/island-bundle.ts +52 -12
  10. package/src/island-disposer.ts +1 -1
  11. package/src/island-group-cache.ts +4 -0
  12. package/src/island-link-check.ts +73 -0
  13. package/src/island-realtime.ts +9 -3
  14. package/src/island-vendor.ts +183 -0
  15. package/src/job-registration.ts +10 -14
  16. package/src/mcp-errors.ts +1 -1
  17. package/src/prerender.ts +7 -7
  18. package/src/route-islands-preload.ts +54 -11
  19. package/src/runtime-admin.ts +2 -4
  20. package/src/runtime-render-document.ts +34 -13
  21. package/src/runtime-render.ts +58 -30
  22. package/src/serve-web.ts +8 -11
  23. package/src/static-images.ts +25 -4
  24. package/src/static-precompress.ts +57 -0
  25. package/src/style-bundle.ts +28 -6
  26. package/src/templates/guard-island-mount-clears.ts +151 -0
  27. package/src/templates/guard-raw-interval.ts +3 -2
  28. package/src/templates/island.ts +8 -7
  29. package/src/templates/resource-form-island.ts +12 -9
  30. package/src/templates/scaffold-docs.ts +2 -1
  31. package/src/templates/scaffold-guards.ts +4 -1
  32. package/src/templates/scaffold-shell.ts +12 -9
  33. package/src/theme-brand.ts +18 -20
  34. package/wiki/Client-Data.md +54 -2
  35. package/wiki/Configuration.md +1 -0
  36. package/wiki/Home.md +3 -3
  37. package/wiki/Jobs-And-Workflows.md +48 -6
  38. package/wiki/Known-Gaps.md +4 -3
  39. package/wiki/MCP-And-AI.md +42 -1
  40. package/wiki/Notify.md +6 -0
  41. package/wiki/PWA-And-Offline.md +11 -0
  42. package/wiki/Queries-And-Live-Queries.md +1 -1
  43. package/wiki/Realtime.md +28 -7
  44. package/wiki/SEO.md +1 -1
  45. package/wiki/Scheduled-Tasks.md +36 -0
  46. package/wiki/Scraping.md +3 -1
  47. package/wiki/Static-Assets.md +30 -3
  48. package/wiki/Theming.md +6 -6
  49. package/wiki/Upgrading.md +16 -0
@@ -20,7 +20,7 @@ answered before that wait on the page handle until it is. The design is
20
20
  | call a query from an island | `queryClient<Api['queries']>({ baseUrl: '' })` | shipped; now goes through the one transport |
21
21
  | ignore an answer for a principal that signed out | `if (isSuperseded(error)) return;` | shipped in 21.0.0 |
22
22
  | any other failure | `isUltimateError(error)`, then switch on `error.code` | shipped |
23
- | install realtime in an island | nothing: `x build` does it for every island whose own graph imports `@ultimat3/realtime`. An island that reaches realtime only through a package calls `installRealtime({ signal: createSignal })` in `mount` | shipped in 21.0.0 |
23
+ | install realtime in an island | nothing: `x build` does it for every island whose own graph imports `@ultimat3/realtime`. An island that reaches realtime only through a package calls `installRealtime({ signal: createSignal, cleanup: onCleanup })` in `mount` — `cleanup` releases each hook with its component (31.14.0) | shipped in 21.0.0 |
24
24
  | show one record in a component | `useRecord('post', id)`: record type, then record key, from `@ultimat3/realtime` | shipped in 21.0.0 |
25
25
  | show a list | `useQuery({ name: 'postList', entity: 'post' }, input)`, or `{ name, live: true }` for a live query | shipped in 21.0.0 |
26
26
  | read once, no socket | `useQuery({ name: 'postList', entity: 'post' }, input)` with no `live` — one HTTP GET through the query client, rows into the same store. Nothing opens a socket (`packages/realtime/src/use-query.ts`): a list that needs no push needs no timer either — never poll | shipped in 21.0.0 |
@@ -169,7 +169,7 @@ export async function rename(postId: string, title: string): Promise<void> {
169
169
  | `X_CLIENT_RECORD_ENVELOPE_INVALID` | a response carried `x-ultimate-records: 1` and a body of the wrong shape | build the body with `encodeRecordEnvelope()` from `@ultimat3/core` in the handler that set the header, or stop setting the header |
170
170
  | `X_RECORD_KEY_MISSING` | a returned row lacks a primary-key column | `x entities show <entity> --json` lists the key. Return the whole row |
171
171
  | `X_MUTATOR_CLOCK_MISSING` | a mutator declares `conflict: 'last-write-wins'` and its entity has no number `updatedAt`, or its output has no entity row | add `updatedAt` (a number, epoch ms, written by the server) to the entity, or declare `conflict: 'server-wins'` |
172
- | `X_REALTIME_UNINSTALLED` | a realtime hook ran in an island that never called `installRealtime()` | `x build`. If the island reaches realtime only through a package, call `installRealtime({ signal: createSignal })` in its `mount` |
172
+ | `X_REALTIME_UNINSTALLED` | a realtime hook ran in an island that never called `installRealtime()` | `x build`. If the island reaches realtime only through a package, call `installRealtime({ signal: createSignal, cleanup: onCleanup })` in its `mount` |
173
173
  | `X_RECORD_REJECTED` | a row reached the store with no key, or not as an object | `x entities show <entity> --json` lists the key. Return whole rows |
174
174
  | `X_CONTRACT_DRIFT` | the client bundle and the server are on different builds | reload the page to pick up the new client bundle |
175
175
 
@@ -198,3 +198,55 @@ Layering: the last config layer that states `sharedChunks` wins; absent everywhe
198
198
  (`mergeIslands`). A value that is not a boolean is refused at boot (`X_CONFIG_INVALID`). `As of
199
199
  2026-11`.
200
200
 
201
+ ## One Solid for every island
202
+
203
+ **Off by default, by measurement.** Each island build inlines the part of Solid it uses, ~14 kB
204
+ tree-shaken. `islands: { vendorSolid: true }` in `app.config.ts` builds Solid ONCE instead, as
205
+ `/islands/vendor-solid.<hash>.js` (`solid-js`, `solid-js/web`, `solid-js/store`, whole: 48,083 B,
206
+ 17,388 B gzip), and every island imports it. Named by its bytes, like every island output
207
+ (`packages/cli/src/island-vendor.ts`). Measured `As of 2026-11-12`, Bun 1.4.4, solid-js 1.9.17.
208
+
209
+ | Turn it on when | Leave it off when |
210
+ |---|---|
211
+ | a route renders four or more Solid islands that are built apart (not one route group) | a route renders one to three Solid islands — every Solid route of the three tracked apps grew 33,572–38,769 B with it on |
212
+ | `x build --target static`, then `x verify --only budgets`, shows the routes shrinking | any route's `budget.js` grows past its budget |
213
+
214
+ The vendor counts once per route in `budget.js`, is precached and preloaded like any shared chunk,
215
+ and adds one request. An island that imports no Solid loads no vendor. An `islands.vendorSolid`
216
+ that is not a boolean is `X_CONFIG_INVALID`.
217
+
218
+ ## Island mounts that never leave a blank box
219
+
220
+ **An island's `mount` draws through `mountOver`** (`@ultimat3/render/client`): it clears the
221
+ server's markup for the live render — Solid's `render` APPENDS — and puts that markup back when
222
+ the render throws, then rethrows. The hydration runtime still marks the root `data-x-failed`, and
223
+ `clientErrors` still reports it once. A visitor sees the server's HTML, never an empty box. 167 B
224
+ in a chunk; framework-neutral (the caller hands in the draw).
225
+
226
+ ```tsx
227
+ import { mountOver } from '@ultimat3/render/client';
228
+ import { render } from 'solid-js/web';
229
+
230
+ function Counter(props: { start: number }) {
231
+ return <p>{props.start}</p>;
232
+ }
233
+
234
+ export function mount(el: HTMLElement, props: { start: number }): () => void {
235
+ return mountOver(el, (root) => render(() => <Counter {...props} />, root));
236
+ }
237
+ ```
238
+
239
+ `x g island`, `x new` and the resource form island write it. An app scaffolded earlier adopts
240
+ through the `island-mount-clears` guard, which `x new` ships and an older app installs:
241
+
242
+ | Step | Command |
243
+ |---|---|
244
+ | install the guard | `x g guard island-mount-clears` |
245
+ | find each island that empties its wrapper outside `mountOver` | `x verify --only boundaries` — one finding per clear, at its line |
246
+ | fix each | delete `el.textContent = ''` and end `mount` with `return mountOver(el, (root) => render(() => <Island {...props} />, root))` |
247
+
248
+ The guard reads `.textContent = ''`, `.innerHTML = ''` and `.replaceChildren()` on `mount`'s own
249
+ first parameter in a `*.island.tsx` that calls no `mountOver(`. A clear of an element INSIDE the
250
+ wrapper — a handler emptying an output region — is the island's own business and is not read.
251
+ `As of 31.15.0`.
252
+
@@ -374,6 +374,7 @@ islands: { sharedChunks: true },
374
374
  | field | type | default | notes |
375
375
  |---|---|---|---|
376
376
  | `islands.sharedChunks` | `boolean` | `false` | **read** by `x dev`, the container and `x build`: `true` builds every island in one split bundle, so a module two islands import is one `/islands/chunk-<hash>.js` a page fetches once and a browser caches across pages; each route's `budget.js` counts it once. `false` (the default) groups by route: islands rendered on exactly the same set of routes are one split build sharing their modules, every other island is built alone, self-contained ([Client data](Client-Data#shared-island-chunks)). `true` is one group holding every island: tree shaking across one split build keeps what ANY importer uses, so a small island importing a helper from a module other islands use heavily pays for all of it (`examples/dummy`'s update banner 712 → 16,288 B). Turn it on only when cross-page caching of shared code is worth that, then weigh the routes with `x verify`. A non-boolean → `X_CONFIG_INVALID` |
377
+ | `islands.vendorSolid` | `boolean` | `false` | **read** by `x dev`, the container and `x build`: `true` builds Solid once as `/islands/vendor-solid.<hash>.js` (`solid-js`, `/web`, `/store`, whole) and every island imports it instead of inlining its own tree-shaken copy. Pays only on a route rendering four or more Solid islands built apart: the vendor is 48,083 B (17,388 B gzip) where an island inlines ~14 kB, measured `As of 2026-11-12` (Bun 1.4.4, solid-js 1.9.17) — every Solid route of the three tracked apps grew 33,572–38,769 B with it on ([Client data](Client-Data#one-solid-for-every-island)). A non-boolean → `X_CONFIG_INVALID` |
377
378
 
378
379
  ## `clientErrors`
379
380
 
package/wiki/Home.md CHANGED
@@ -107,7 +107,7 @@ Follow in order. Each page states what it was executed against in its own first
107
107
  | [I18n](I18n) | flat catalogs, loud misses, locale routing, `hreflang` |
108
108
  | [Theming](Theming) | 24 semantic colour roles as RGB channels, every token scale, breakpoint and layout mixins, `defineTheme()`, what contrast is gated |
109
109
  | [Interface rules](Interface-Rules) | how a screen must behave, and which of the app's `guards/` refuses each rule |
110
- | [UI components](UI-Components) | the four page composites, and the generated UI component catalog |
110
+ | [UI components](UI-Components) | the four page composites, and the generated catalog of 99 source-derived UI components |
111
111
  | [Timezones and dates](Timezones-And-Dates) | store UTC, format with an explicit IANA zone, frozen clocks in tests |
112
112
  | [Money](Money) | `Money = { minor, currency }`, never a float |
113
113
  | [Outbound HTTP](Outbound-HTTP) | `outbound()`: one vendor call with a whole-call deadline, the caller's signal, safe-only retry, idle and byte bounds, `dial: 'public'` pinning, and `breaker()` |
@@ -155,7 +155,7 @@ Follow in order. Each page states what it was executed against in its own first
155
155
  | [`docs/architecture/`](https://github.com/developerz-ai/ultimate/tree/main/docs/architecture) | **how** — the internals |
156
156
  | [`docs/ops/`](https://github.com/developerz-ai/ultimate/tree/main/docs/ops) | running an app for real: the PaaS → Compose → Kubernetes ladder, secrets, observability, datastore sizing, disaster recovery, runbooks. **Recommendations only** — the framework depends on none of it |
157
157
  | [`docs/idea/16-app-targets.md`](https://github.com/developerz-ai/ultimate/blob/main/docs/idea/16-app-targets.md) | three targets, one backend, two view layers — **design only, not shipped behaviour** |
158
- | [`docs/idea/17-scale-ladder.md`](https://github.com/developerz-ai/ultimate/blob/main/docs/idea/17-scale-ladder.md) | why the app code is identical at rung 0 and rung 4 — **shipped, not design only**: 24 of its 26 seam rows are marked shipped, rungs 0–2 are real, and the places the invariant breaks today are named |
159
- | [`packages/ui/CATALOG.md`](https://github.com/developerz-ai/ultimate/blob/main/packages/ui/CATALOG.md) | the full component catalog with every prop, generated from source and drift-tested |
158
+ | [`docs/idea/17-scale-ladder.md`](https://github.com/developerz-ai/ultimate/blob/main/docs/idea/17-scale-ladder.md) | why the app code is identical at rung 0 and rung 4 — **shipped, not design only**: all 26 seam rows are marked shipped, rungs 0–2 are real, and the places the invariant breaks today are named |
159
+ | [`packages/ui/CATALOG.md`](https://github.com/developerz-ai/ultimate/blob/main/packages/ui/CATALOG.md) | the full catalog of 99 source-derived UI components with every prop, generated from source and drift-tested |
160
160
  | [`framework.manifest.json`](https://github.com/developerz-ai/ultimate/blob/main/framework.manifest.json) | every package, tier, and `X_*` code with its owner — generated |
161
161
  | [llms.txt](https://github.com/developerz-ai/ultimate/blob/main/llms.txt) | the machine-readable repo map for agents |
@@ -76,7 +76,7 @@ External brokers are not exempted: the outbox table stays the transactional reco
76
76
 
77
77
  | API | Semantics |
78
78
  |---|---|
79
- | `step.run(name, fn)` | executes `fn` once ever. Result persisted under `(jobId, name)`. On replay, returns the stored result without calling `fn`. **It answers what it stored, on the first run too**, and its type says so (`StepOutput<T>`, the JSON form): a `Date` is a string, so a body writes `new Date(value)` at the read; a miss stored from `undefined` is `null`, so compare `=== null`; a `bigint` or a cycle is `X_STEP_OUTPUT_UNSERIALIZABLE`, terminal. Return a cursor or a small plain view, not a page of rows. `fn` receives an `AbortSignal` — this step's ceiling and the run's cancellation, whichever fires first |
79
+ | `step.run(name, fn)` | executes `fn` once ever. Result persisted under `(jobId, name)`. On replay, returns the stored result without calling `fn`. **It answers what it stored, on the first run too**, and its type says so (`StepOutput<T>`, the JSON form): a `Date` is a string, so a body writes `new Date(value)` at the read; a miss stored from `undefined` is `null`, so compare `=== null`; a `bigint` or a cycle is `X_STEP_OUTPUT_UNSERIALIZABLE`, terminal. Return a cursor or a small plain view, not a page of rows: past a declared `job({ stepOutputMax })` bytes of JSON it is `X_STEP_OUTPUT_TOO_LARGE`, terminal; undeclared, past 256 KiB (`STEP_OUTPUT_MAX_BYTES`) it is stored and logged once per job and step under that code, refused by default from the next major — every attempt loads every output of its run, so persist the payload and return its key, as `exportRows()` and `backfill()` do. `fn` receives an `AbortSignal` — this step's ceiling and the run's cancellation, whichever fires first |
80
80
  | `step.run(name, fn, { compensate })` | `compensate(output, { signal })` undoes the step if the run fails **for good** — never on a retry, a cancel, a drain or a suspension. Needs `job({ compensates: true })`, else `X_JOB_DECLARATION_INVALID`. See [Compensation](#compensation) |
81
81
  | `step.run(name, fn, { once: true })` | at most once, ever: `started` is persisted **before** `fn`; a replay finding it (or `failed`) without `completed` stops with terminal `X_STEP_OUTCOME_UNKNOWN` and never calls `fn`. `x jobs resolve-step <id> <step> --ran --output '<json>'` or `--not-ran`, then `x jobs retry <id>` |
82
82
  | `step.sleep(duration)` | persists a wake time, releases the worker, and the job resumes in a fresh process. No held connection, no timer in memory. `'3d'` is safe |
@@ -89,6 +89,7 @@ External brokers are not exempted: the outbox table stays the transactional reco
89
89
  | Names unique within one `run` | `X_STEP_DUPLICATE` at `x verify` |
90
90
  | Names stable across deploys | renaming a step invalidates its stored result — it re-runs |
91
91
  | Step results must be serializable | persisted through the driver's `steps` store (`StepStore.put`) |
92
+ | Step results are small | ≤ a declared `stepOutputMax` bytes of JSON, else `X_STEP_OUTPUT_TOO_LARGE` before anything is stored; undeclared, > 256 KiB is logged under that code and stored (refused by default from the next major) |
92
93
  | No step inside a loop with a computed name | non-deterministic names break replay; enumerate them |
93
94
  | Non-idempotent external call inside a step | wrap with the provider's idempotency header, keyed off `${jobId}:${stepName}` — or, with no key to send, `{ once: true }` |
94
95
  | `unwinding` and `compensate:*` are the framework's | `X_JOB_DECLARATION_INVALID` on `run`, `sleep` and `waitForEvent`, for every job |
@@ -171,13 +172,48 @@ Omitting it is a **compile error**, not a lint warning. At-least-once is the onl
171
172
  | Duplicate enqueue with a live key | second enqueue returns the existing job handle, no new row |
172
173
  | Key uniqueness window | while a row holding the key is **live** (`ready`, `delayed`, `running`, `suspended`) — scoped by job name and tenant (`x_jobs_name_tenant_idempotency_live_idx`, `LIVE_STATES` in every driver). Once that row is terminal (`done`, `failed`, `dead`, `cancelled`) the same key enqueues a new job at once; there is no per-queue retention policy and no post-terminal window. The terminal row itself is kept for `jobs.doneRetentionMs` (14 days) or `jobs.deadRetentionMs` (90 days), then the hourly `x.purge` deletes it ([Configuration](Configuration#jobs)) |
173
174
  | Key must be | deterministic from `input` only. No timestamps, no random, no `ctx` |
174
- | Same key, different payload | deduped: `{ deduped: true, id }` of the live row, the **first payload wins**, nothing thrown. `X_IDEMPOTENCY_CONFLICT` is an action's `Idempotency-Key` refusal ([Actions](Actions)), never the queue's |
175
+ | Same key, different payload | deduped: `{ deduped: true, id }` of the live row, the **first payload wins**, nothing thrown — unless the enqueue asks `onConflict: 'replace'` ([Debounce and expiry](#debounce-and-expiry)). `X_IDEMPOTENCY_CONFLICT` is an action's `Idempotency-Key` refusal ([Actions](Actions)), never the queue's |
175
176
  | Same key, still in flight | deduped too: a `running` row holds its key. A re-arm from outside (a `task` on a cron) is a no-op while the run is live and a fresh run once it settled |
176
177
  | Same key, from the job's own body | deduped onto the **running row itself**: a job re-enqueueing itself on its way out arms nothing, and no later run exists. Re-arm from outside the run instead |
177
178
  | Missing key | `X_IDEMPOTENCY_REQUIRED` at build time |
178
179
 
179
180
  **Durable business state lives in your tables, never only in the queue payload.** A payload is a pointer, not a record. If the queue is drained, replaced, or migrated to another driver, the business must still be reconstructible from Postgres alone. So `{ orgId }`, not `{ org: {...30 fields} }`.
180
181
 
182
+ ### Debounce and expiry
183
+
184
+ Two `enqueue` options, `As of 2026-11-12`. Neither is an `enqueueMany` option (the type omits both; a driver batch refuses them, `assertEnqueueMany`).
185
+
186
+ ```ts
187
+ import { job, t } from '@ultimat3/jobs';
188
+
189
+ export const reindexDoc = job({
190
+ name: 'reindexDoc',
191
+ input: t.object({ docId: t.string, revision: t.number }),
192
+ tenant: 'none',
193
+ idempotencyKey: ({ docId }) => `reindex:${docId}`,
194
+ retry: { attempts: 3 },
195
+ async run({ input }) {
196
+ return input.revision;
197
+ },
198
+ });
199
+
200
+ export async function onDocSaved(docId: string, revision: number): Promise<void> {
201
+ const now = Date.now();
202
+ await reindexDoc.enqueue(
203
+ { docId, revision },
204
+ // Every save within 5 s folds into one run with the latest revision; none past an hour.
205
+ { onConflict: 'replace', runAt: now + 5_000, expiresAt: now + 3_600_000 },
206
+ );
207
+ }
208
+ ```
209
+
210
+ | Option | Rule |
211
+ |---|---|
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
+ | `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 |
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
+
181
217
  ## Concurrency, rate limits, queues, retry
182
218
 
183
219
  Declared per job, held across the fleet.
@@ -202,7 +238,9 @@ export const syncCrm = job({
202
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 |
203
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 |
204
240
  | `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
+ | `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`) |
205
242
  | `queue` | named pool; the `worker` role runs one pool per config (`WORKER_QUEUES=default,integrations`) | worker pool sizing, see [Deployment](Deployment) |
243
+ | 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 |
206
244
  | `retry.attempts` / `backoff` | `'exponential' \| 'linear' \| 'fixed'` | driver scheduler |
207
245
  | `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 |
208
246
  | 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 |
@@ -336,7 +374,7 @@ Every operator capability is a member of `JobIntrospection` (`driver.introspect`
336
374
  | 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 |
337
375
  | 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 |
338
376
  | 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 |
339
- | 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 most once across a crash; 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 |
377
+ | 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 |
340
378
 
341
379
  ```ts
342
380
  export const syncAccount = job({
@@ -369,7 +407,7 @@ export const syncAccount = job({
369
407
  | `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 |
370
408
  | `refused` | `whenBusy: 'fail'` over a busy key. The body never ran; `code` is `X_JOB_KEY_BUSY` |
371
409
  | never called for | a retry, a suspension, a drain, a row cancelled or removed by a caller, a settle that did not land |
372
- | delivery | **at most once** per ending — a worker killed between the settle and the hook never runs it. What must be recorded for certain is written by the body, inside a `step.run` |
410
+ | 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` |
373
411
  | 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 |
374
412
 
375
413
  | Fact | Detail |
@@ -841,6 +879,8 @@ Every command supports `--json`. See [CLI reference](CLI-Reference).
841
879
 
842
880
  **A lease that lapses is reported, never swallowed.** A worker renews the visibility window every `heartbeatIntervalMs` (default a third of the window) for as long as a job runs. One failed renewal is `jobs.heartbeat.failed` at `warn` — the window still has room for the next. A whole window with none landing is `jobs.lease.lost` at `error` plus one point on `job_leases_lost_total{queue}`: the queue is now free to hand that job to another worker while this one is still running it, which is at-least-once becoming exactly-twice. Alert on any non-zero rate. The window is measured from the last renewal that **landed**, on the worker's own clock, so a `heartbeat` that hangs is caught the same as one that rejects.
843
881
 
882
+ **A body renews its own lease when the timer cannot.** `run({ lease })` hands the attempt's lease: `await lease.renew()` renews now and answers whether the attempt still holds the row (`false` once it is lost or the attempt's settle is sent) — call it between the chunks of a section longer than the visibility timeout, where the heartbeat timer cannot fire — `lease.lost()` answers whether it was lost, and `lease.signal` aborts when it is or when the attempt settles. It is this attempt's, and ends with it: a lock that must outlive one job is [`withLock()`](#a-lock--withlock). `As of 2026-11-12`.
883
+
844
884
  ## Errors
845
885
 
846
886
  | Code | Cause | Fix |
@@ -850,6 +890,8 @@ Every command supports `--json`. See [CLI reference](CLI-Reference).
850
890
  | `X_JOB_MAX_ATTEMPTS` | the job exhausted its retries and was dead-lettered | `x jobs show <id> --json`, then `x jobs retry <id>` — only a dead, cancelled, failed or done job can be requeued (`X_JOB_NOT_REQUEUEABLE` otherwise) |
851
891
  | `X_JOB_DECLARATION_INVALID` | a `job()` declaration lacks fields every job declares — the cause names each | add the fields the fix lists |
852
892
  | `X_IDEMPOTENCY_CONFLICT` | same key, different payload, or still in flight | fresh key for a different payload; otherwise retry after the first settles |
893
+ | `X_JOB_BACKLOG_FULL` | an enqueue past the job's declared `maxPending` — its queue already holds that many rows waiting to run. A 429 | `x jobs list --queue <queue> --json` for the depth; retry after a backoff, add workers for the queue, or raise `maxPending` |
894
+ | `X_STEP_OUTPUT_TOO_LARGE` | a `step.run` output past the job's declared `stepOutputMax` bytes of JSON — terminal, nothing stored. Undeclared, past 256 KiB it is logged under this code and stored | persist the payload and return its key from the step; or raise `job({ stepOutputMax })` |
853
895
  | `X_DRAINING` | the worker holding the job received SIGTERM — it is the reason on `ctx.signal`, and a body that unwinds on it is `interrupted` with the attempt uncounted | none — the job goes straight back to the queue and another worker claims it. Pass `ctx.signal` to outbound calls and `throwIfAborted(ctx)` between steps, so the body unwinds inside the drain budget instead of being killed at it |
854
896
  | `X_FORBIDDEN` | the job's actor fails the originating action's policy | grant the permission, or enqueue as a system actor |
855
897
  | `X_NOT_IMPLEMENTED` | introspection or the operator surface reached a driver with no `introspect` — a hand-rolled one | drop the `jobs:` field from `apps/<app>/runtime.ts` so the boot installs `postgresJobDriver()`, or `installJobDriver(memoryJobDriver())` from `@ultimat3/jobs/adapter` in a test. There is no config line to edit: `jobs.driver` was deleted in 5.0.0 because it never had a reader |
@@ -880,9 +922,9 @@ What a crash does to a job is asked by `crashProof(job, input)` — killed at ev
880
922
  ## Rules
881
923
 
882
924
  - Never assume a job runs once. Assume at-least-once. A `backfill()`'s `handle` is the same rule one level down: it runs *before* its checkpoint lands, so an attempt cancelled between the two hands that page to the next one — write through `upsertAll`, `updateWhere` or a statement whose second run changes nothing.
883
- - At-least-once has two JS-shaped edges. A body that ignores `ctx.signal` keeps running past a lost fleet slot, so `concurrency` is exceeded until it returns. A synchronous step that blocks the event loop longer than the 30 s visibility timeout starves the heartbeat: the lease lapses and another worker runs the job again. Await I/O, honour `signal`, and split CPU work into steps.
925
+ - At-least-once has two JS-shaped edges. A body that ignores `ctx.signal` keeps running past a lost fleet slot, so `concurrency` is exceeded until it returns. A synchronous step that blocks the event loop longer than the 30 s visibility timeout starves the heartbeat: the lease lapses and another worker runs the job again. Await I/O, honour `signal`, split CPU work into steps, and `await lease.renew()` between chunks.
884
926
  - Never put durable business state only in the payload.
885
927
  - Never do slow work inline in an action — enqueue a job.
886
928
  - A job never renders, redirects, or reads headers. Actor and tenant come from `ctx`.
887
929
  - One `step.run` per externally-visible side effect. A step that does two things cannot be retried.
888
- - Cron never contains a handler body — that is a [scheduled task](Scheduled-Tasks) enqueuing a job.
930
+ - Cron never contains a handler body — that is a [scheduled task](Scheduled-Tasks) enqueuing a job. A job only its own cron fires is one `cronJob()` declaration: the job, with the task as its `.schedule` ([Scheduled tasks](Scheduled-Tasks#a-job-on-its-own-cron--cronjob)).
@@ -50,7 +50,8 @@ 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` runs at most once across a crash | `As of 2026-10`, by decision of the first cut: the hook runs after the settle, inline, by the worker whose settle landed. A worker killed between the settle and the hook does not run it, and nothing re-drives it | record what must be recorded for certain inside the body, in a `step.run`, and use `onSettled` for what may be lost |
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 |
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 |
54
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 |
55
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 |
56
57
  | An org-scoped operator's runs list reads `x_jobs` with no index on `tenant_id` | `As of 2026-10`. The jobs dashboard keeps an actor with an `orgId` to its own org's runs through `JobFilter.tenantId`, and `x_jobs.tenant_id` is a plain column: the only index naming it is the idempotency one, led by `name` (`packages/jobs/src/driver-pg-ddl.ts`). A platform operator's list is unaffected [pin](https://github.com/developerz-ai/ultimate/blob/main/packages/jobs/src/driver-pg-sql.test.ts#no%20x_jobs%20index%20leads%20with%20tenant_id%3A%20an%20org-scoped%20runs%20list%20scans) | on a large queue, add `create index on x_jobs (tenant_id, created_at desc, id desc)` in an app migration, or operate the dashboard as a platform operator (an actor with no `orgId`) |
@@ -105,8 +106,8 @@ downstream app on Ultimate and of systems built without it; no row is a defect i
105
106
  | a view-scoped lazy lookup for `t()` inside an island — the subset itself ships (`catalogSubset` / `subsetTranslator`, #710), named key by key | 94 label types, 3,092 lines of label files | lazy lookup `t('.title')` scoped to the view |
106
107
  | a server-first dialog, menu and combobox with a small enhancer | ~2,200 app-side lines; 13 catalog components at 0 imports | HTML first, a small controller second |
107
108
  | `QueryRef` derived from the declaration | [Queries and live queries](Queries-And-Live-Queries) "Not derived" row | — |
108
- | a `task` that runs without a companion job; a boot hook | 35 task/job pairs, 2 boot stand-ins | recurring tasks that name a command; initializers |
109
- | batches with completion callbacks, debounce, priority, job expiry, argument encryption | each present in a surveyed job system; none asked for by the proving case | batches and limiters in established job systems; queue priorities |
109
+ | a boot hook — the task half closed: `cronJob()` declares a job and its task once ([Scheduled tasks](Scheduled-Tasks#a-job-on-its-own-cron--cronjob)) | 2 boot stand-ins | initializers |
110
+ | batches with completion callbacks, argument encryption — debounce and job expiry closed (`enqueue({ onConflict: 'replace', expiresAt })`, [Jobs](Jobs-And-Workflows#debounce-and-expiry)); priority is decided out: a separate queue ([Jobs](Jobs-And-Workflows#concurrency-rate-limits-queues-retry)) | each present in a surveyed job system; none asked for by the proving case | batches and limiters in established job systems; queue priorities |
110
111
  | proxy inventory, captcha, OTP relay | product features of a scraping service — the app's, by [axiom 8](https://github.com/developerz-ai/ultimate/blob/main/docs/idea/19-mechanism-not-convention.md) | — |
111
112
 
112
113
  The test-kit row of that plan's table shipped in 23.0.0 work (`renderView`, `runJobs({ actor })`,
@@ -66,6 +66,19 @@ None of them is exposed in `ROLE=web`. `db.query` accepts one statement, whose l
66
66
 
67
67
  **`bunx @ultimat3/cli`, never `bunx x`, in a client config.** A client may spawn the command outside the installed app, and there `bunx x` fetches an unrelated npm package named `x`. Inside an app's shell, `bunx x` resolves the app's own CLI. `scaffold-mcp-json.test.ts` pins the spelling, and CI's `scaffold-smoke` spawns the file's own command and asks it `initialize` and `tools/list` on every push.
68
68
 
69
+ ### The stdio wire
70
+
71
+ `x mcp serve --transport stdio` speaks newline-delimited JSON-RPC (`packages/mcp/src/transport-stdio.ts`).
72
+ `As of 31.15.0`:
73
+
74
+ | Rule | Detail |
75
+ |---|---|
76
+ | no call blocks another | each request is dispatched without waiting for the one before; answers are written one at a time, never interleaved |
77
+ | at most 16 at once | `STDIO_MAX_IN_FLIGHT`; past it a request waits in a queue of 64 (`STDIO_MAX_QUEUED`), and only a full queue stops the reader |
78
+ | `ping` is always answered | it never queues, so a busy server still says it is alive |
79
+ | `notifications/cancelled` aborts the named call | heard at the cap too: the tool's `ctx.signal` (a hand-written tool: `handle`'s optional third argument) aborts, a queued request never runs, and a cancelled request gets no answer |
80
+ | one message ≤ `lineLimitBytes` | 1 MiB by default, counted in BYTES before decoding; an over-long line is one `-32600` `X_MCP_BODY_TOO_LARGE` frame |
81
+
69
82
  ### Rate limits on the HTTP transport
70
83
 
71
84
  **Enforced `As of 2026-08-24`.** `mcpHttpRoute` meters itself, per caller, per class, per minute. It has to: all MCP traffic is one `POST /mcp`, so the HTTP pipeline's own buckets — which key on the route — cannot tell an `initialize` handshake from a migration.
@@ -74,7 +87,7 @@ None of them is exposed in `ROLE=web`. `db.query` accepts one statement, whose l
74
87
  |---|---|---|
75
88
  | `read` | 120 / minute | every method that is not `tools/call`, plus any tool that does not declare `destructive: true` |
76
89
  | `write` | 20 / minute | a `tools/call` naming a `destructive: true` tool, and **any call this server cannot resolve** — fail-closed, so a probing client never gets the cheap bucket |
77
- | `unauthenticated` | 20 / minute, per **address** | a missing token, or one `resolveToken` answers `null`. Past it the address is refused `429` **before** `resolveToken` runs — a valid guess included, so the answer says nothing about the token (`As of 2026-10`). Keyed on `handle(request, { address })` — the host's resolved client address; a host that passes none is not metered here |
90
+ | `unauthenticated` | 20 / minute, per **address** — an IPv6 /64 is one address (`addressNetwork`, `As of 31.15.0`) | a missing token, or one `resolveToken` answers `null`. Past it the address is refused `429` **before** `resolveToken` runs — a valid guess included, so the answer says nothing about the token (`As of 2026-10`). Keyed on `handle(request, { address })` — the host's resolved client address; a host that passes none is not metered here |
78
91
 
79
92
  | Rule | Detail |
80
93
  |---|---|
@@ -130,6 +143,14 @@ That line is the entire integration. From the existing declaration:
130
143
 
131
144
  The projected tool's `run` **is** `invoke` — the same entry point the HTTP route calls (`packages/mcp/src/projectable.ts`). Policy runs inside it, so there is nothing to keep in sync. The projection itself adds **no** MCP scope: a second gate hard-coded into the projection would sit in front of the only gate that matters, and the two would eventually disagree. `defineAppMcp`'s `scopes:` map may still attach one from outside — a property of the connection's token, never invented by the projection.
132
145
 
146
+ **An exposed LIST query answers one bounded page.** Its tool reads through the query's own
147
+ `.page()`: at most 500 rows (`MAX_WIRE_PAGE_SIZE`) and 256 KiB of JSON (`QUERY_LIMITS.maxBytes`),
148
+ `db.query`'s own ceilings. An answer that fits is the bare rows, as before. One cut short says so —
149
+ `truncated` (`'rows'` or `'bytes'`) and a `nextCursor` — and the agent asks for the next page by
150
+ passing that cursor back as the tool's optional `_after` argument, published in its `inputSchema`
151
+ (`packages/mcp/src/query-page.ts`). `As of 31.15.0`: a read with no `.limit()` dumped every row into
152
+ the model's context.
153
+
133
154
  No MCP-specific permission table, no service account with broad rights. Exposure is opt-in; silence exposes nothing.
134
155
 
135
156
  The user's own agents can therefore operate the user's product — refund an order, re-run an import, publish a post — with the exact permissions that user has in the UI. See [Admin dashboard](Admin-Dashboard) and [Actions](Actions).
@@ -531,6 +552,13 @@ Remote MCP tools as this app's actions — the app's `policy`, rate limit, confi
531
552
  3. On the callback, `exchange(handshake, { code, state })` answers `{ accessToken, refreshToken, expiresIn }`. `refresh(handshake, refreshToken)` answers the same shape.
532
553
  4. Store the tokens per connection. Return the access token from `mcpTools({ auth })`, which is read on every call, so a rotated token is never cached.
533
554
 
555
+ `begin` refuses, as `X_MCP_REMOTE_REFUSED`, metadata it cannot trust: a document that is not a URL,
556
+ resource metadata naming another resource (RFC 9728 §3.3), authorization-server metadata answering
557
+ for another issuer (RFC 8414 §3.3), no PKCE S256, and an `authorization_endpoint` or `token_endpoint`
558
+ that is not `https:` — `http:` only on a loopback host (`localhost`, `127.0.0.1`, `[::1]`, RFC 8252).
559
+ `authorizeUrl` is handed to a person as a link, so a `javascript:` endpoint would run in the app's
560
+ origin. `As of 31.15.0`.
561
+
534
562
  `clientId` is the HTTPS URL at which this app serves `metadata()` (a client ID metadata document), or an id the authorization server issued when the app was registered by hand. A `401` mid-session is `X_MCP_REMOTE_AUTH_REQUIRED`: run the handshake again.
535
563
 
536
564
  **Proved on itself.** `examples/dummy/packages/mcp/src/remote-self.contract.test.ts` points `mcpTools()` at the reference app's own MCP route. It locks the live list, calls `seatReport`, and meets three refusals: the remote policy's `X_FORBIDDEN` as a result, a stolen token as `X_MCP_REMOTE_AUTH_REQUIRED`, and a schema moved since the lock as `X_MCP_REMOTE_TOOL_CHANGED`.
@@ -612,6 +640,18 @@ export const summarize = llm({
612
640
 
613
641
  **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.
614
642
 
643
+ **A call that stops early still costs what the provider billed.** Every budget — `tokensPerRun`,
644
+ `costPerRun`, the actor and org ceilings — is charged on these paths (`packages/ai/src/gateway.ts`,
645
+ `stream-bill.ts`). `As of 31.15.0`:
646
+
647
+ | The call | Recorded |
648
+ |---|---|
649
+ | reaches `done` | the provider's own counts |
650
+ | a stream abandoned, cut or aborted after its first provider byte | the running usage the wire reported: the prompt from `message_start` (OpenAI-format: estimated) plus the output streamed so far |
651
+ | aborted after its request left the process, before any answer (`generate` or `stream`) | the prompt's estimate (`estimateInputTokens`): the provider has read it |
652
+ | aborted before the request was sent, or refused by the provider (a 4xx) | nothing: the reservation is released |
653
+ | a `done` whose ledger record throws | never booked a second time from the running bill |
654
+
615
655
  **Showing what a model wrote is `Markdown` from `@ultimat3/ui`**, never `innerHTML`: the text is
616
656
  parsed to a tree and rendered as elements, so a `<script>` or a `javascript:` link in an answer is
617
657
  text, and a streaming answer re-parses per token while finished blocks keep their nodes. Tool calls
@@ -673,6 +713,7 @@ pgvector in the same Postgres. No second datastore.
673
713
  | Index | HNSW: `postgresVectorStore({ name, dimension }).ddl()` prints the table and both indexes, pasted into a migration by the app |
674
714
  | Hybrid search | one `query` primitive fusing pgvector cosine + Postgres FTS with Reciprocal Rank Fusion; weights are config |
675
715
  | Filtering | tenant + policy filters applied **in SQL**, so vector search cannot leak across tenants; a store with no tenant bound, read inside a request acting for an org, is `X_VECTOR_UNSCOPED` — a backfill opts in with `scope: UNSCOPED` |
716
+ | HNSW recall | a search returns `k` hits for a small tenant on a large shared table: on pgvector ≥ 0.8 it runs with `hnsw.iterative_scan = relaxed_order`, before that with `hnsw.ef_search` raised to `max(40, k × 10)`, capped at 1,000 — the setting scoped to a read-only transaction the search opens (2–3 round trips), or to the caller's own, put back after (`pg-vector-recall.ts`). Without it pgvector took the 40 nearest rows and filtered afterwards, so a tenant holding a small share of the table got fewer than `k`, often none. `As of 31.15.0` |
676
717
  | Re-embed | `indexDocument` again: every chunk is embedded on each call, so a job decides when text changed |
677
718
 
678
719
  ## Evals as a test type
package/wiki/Notify.md CHANGED
@@ -61,6 +61,12 @@ message disappears is your decision ([Configuration](Configuration)).
61
61
  recipient)` taken before each send — a chunk that failed part-way re-sends nobody it reached.
62
62
  10k recipients on two channels is 40 preference reads and 40 delivery steps. A digest's append
63
63
  and drain stay one step per recipient; its send is one step per chunk.
64
+ - Inside a chunk, deliveries run 16 at a time (`NOTIFY_DELIVERY_WIDTH`), each with its own ledger
65
+ claim. One failing recipient never stops its neighbours: they go out and settle `sent`, then the
66
+ step fails (a retryable failure first) and the retry re-sends the failed one alone. A drain (the
67
+ run's signal aborting) claims nobody new and waits for every send already claimed to settle
68
+ before the step answers, so no row is left `sending` behind an exiting process. Measured
69
+ `As of 2026-11-12`: 100 recipients on a 50 ms channel, 5.1 s → 0.36 s.
64
70
  - Two attempts at once: one sends. The other raises `X_NOTIFY_DELIVERY_HELD` and retries past the
65
71
  holder's `reclaimAfterMs` (5 minutes by default), so a crashed attempt's recipient is still sent to
66
72
  and a late `settle` moves nothing.
@@ -64,6 +64,17 @@ export const config = defineRoute({
64
64
  | Fonts, icons, and `priority` images they reference | asset graph |
65
65
  | The offline fallback route | required (see below) |
66
66
 
67
+ **The worker answers a precached asset from the precache**, ahead of every route rule
68
+ (`packages/pwa/src/precached-asset-source.ts`): a content-addressed URL (an island chunk, a
69
+ `/styles/<hash>.css`) from the cache, the network only on a miss; any other precached asset from the
70
+ network, the precache answering offline. Before `31.15.0` nothing read them: an offline document
71
+ rendered unstyled beside its own stylesheet, and a precached chunk was downloaded twice.
72
+
73
+ **Each build's pages cache keeps at most 50 documents** (`PAGES_CACHE_MAX`), the oldest WRITTEN out
74
+ first — a page visited again is written again and outlives pages visited once since. One write at a
75
+ time, so a trim never deletes the page a refresh just stored. Unbounded, `x-pages-<id>` grew until
76
+ the next deploy or the browser's quota, and a quota eviction takes the origin's whole storage.
77
+
67
78
  Excluded always: `api/` responses and every personal route (a policy, a `stream`, a `no-store`/`private` cache) — even with `offline: 'precache'`, `As of 22.3.3`.
68
79
 
69
80
  Total precache size is a **warning, not a budget, `As of 2026-08`**: `buildPrecacheManifest` puts `DEFAULT_PRECACHE_WARN_BYTES` overruns on `PrecacheManifest.warnings`, and **nothing reads that field** — no `x verify` step loads a precache manifest, because nothing builds one. Designed as a budget; not one today.
@@ -90,7 +90,7 @@ const feed = useQuery<FeedRow>({ name: 'liveFeed', live: true }, { orgId });
90
90
  | Lists hold ids | the rows come from the page's `RecordStore`, so a record updated through any path re-renders every list holding it |
91
91
  | Input | read **once**, at call time. A changed input is a new `useQuery` |
92
92
  | `poll` | `pollEvery(ms, { maxMs? })` from `@ultimat3/realtime`; non-live only, refused by type on a live ref: `refetch` every `ms` through `visibleInterval` from `@ultimat3/core/page`, which only an island importing `pollEvery` carries — hidden tab skipped with one make-up read on show, stopped by a lost session and by `release()`. A non-finite value is `finiteOption`'s refusal |
93
- | Lifetime | the caller owns `release()` (Solid: `onCleanup`) |
93
+ | Lifetime | released with the component that called it (**31.14.0**: `x build`'s island bootstrap installs Solid's `onCleanup` as `installRealtime({ cleanup })`); `release()` lets go sooner, and is the caller's for a hook held outside a component. A release runs once however many of them fire |
94
94
  | Not derived, `As of 2026-09-22` | `live` and `entity` are stated on the ref by hand, and nothing checks them against the query declaration. A ref saying `live: true` for a non-live query subscribes to nothing |
95
95
  | Types | the row type is the caller's annotation (`useQuery<FeedRow>`), not inferred from the query. That is the price of never importing the query value |
96
96
  | A server render | answers `pending` with no subscription |
package/wiki/Realtime.md CHANGED
@@ -111,6 +111,7 @@ Opt-in per entity, and shipped in 21.0.0 (`CHANGELOG.md`). The 20.x shape (`stor
111
111
  | boot | the rows are restored **before** the socket connects, as provisional records; the first server row for a key wins outright |
112
112
  | an answer that did not carry every row the overlay wrote | the overlay stays for those rows until a server row for them arrives, capped at 10 s (`DEFAULT_AWAIT_SERVER_MS`), after which server truth stands |
113
113
  | a write with no response | only `X_CLIENT_TRANSPORT_FAILED` with `meta.failure: 'network'`: `useMutation` queues it in the page's one outbox under its idempotency key, keeps its overlay on screen, and resolves `undefined`. `'status'` rejects and drops the overlay; `'body'` (a 2xx that was not JSON, which may have landed) rejects and keeps the overlay until the next server row |
114
+ | two online calls of one mutator | sent in call order (**31.14.0**): one lane per mutator **name**, page-wide, so the next POST starts when the previous one settled — answered, queued or refused. Each overlay still paints at once; only the network leg waits. Before, a like then an unlike were POSTed together and could commit in either order. Different mutators never wait on each other. A write made while the browser is known offline never joins the lane: it reaches the outbox at once, so a POST hanging on a half-open socket cannot hold it off the disk. An online write that waited `LANE_WAIT_MS` (10 s) behind the previous one goes to the outbox under its key, and the writes after it queue behind it |
114
115
  | replay | in order, over HTTP, each write with its original idempotency key: whenever the page socket (re)connects, on `online`, and on the service worker's `OUTBOX_DRAIN_MESSAGE` ([PWA and offline](PWA-And-Offline)). A retryable failure stops the pass; a refusal is final and rolls back its overlay. **At least once**: an entry leaves the disk when its ack is written, so a 2xx that reached a document already being replaced is sent again by the next one, under the same key — answered from the action's idempotency store (a `mutator()` is `idempotent: true` or it does not declare), never applied twice. A `409 X_IDEMPOTENCY_CONFLICT` for a first attempt still running stays queued and is asked again |
115
116
  | a write queued offline | flushes the persisted records it touched first, so a reload inside the 250 ms persist debounce keeps the row the write changed. No replay runs while `navigator.onLine` is `false` (`page-outbox.ts`) |
116
117
  | a principal change | **within one page** (`rescope()`): the previous principal's rows and queue are wiped, and writes still queued are lost, deliberately. A replay on the wire at that moment is abandoned before its next write: nothing queued by one principal is sent under the next one's session. A write being queued at that moment is refused — `mutate` rejects with `X_OFFLINE_QUEUE_ABANDONED` and its optimistic twin is taken back. **A sign-out that navigates** to a new document (the reference app's idiom: the `endSession` action at `POST /api/sessions/end`, posted by a native form) clears the browser first: its response carries `signOutHeaders()` from `@ultimat3/auth`, whose `Clear-Site-Data: "cache", "storage"` drops IndexedDB, local storage, the service worker and its cache, in a secure context. The next boot is the second line: it wipes every stored scope except the current principal's before restoring anything (`packages/realtime/src/boot.ts`, `wipeOthers`). An unscoped page wipes nothing |
@@ -135,21 +136,22 @@ adapter, its sync URL and its `LiveClient`: the page's one socket is the framewo
135
136
  | 1. the dependency | root `package.json` | `bun add @ultimat3/realtime`. `x new` installs `@ultimat3/query` and **not** `@ultimat3/realtime` |
136
137
  | 2. the query | `app/<feature>/live.ts` | `query({ …, live: true, subscribes: ['posts'] })`, bounded and ordered; `x g query <name> --feature <slice> --live` writes it |
137
138
  | 3. the ref | the island | `{ name: 'liveFeed', live: true }`, the query's registered **name**, never the query value: importing that drags its whole read path into the island. `live` is stated beside the name, not derived (see below) |
138
- | 4. the install | nothing to write | `x build` builds every island whose own import graph reaches `@ultimat3/realtime` from an entry that calls `installRealtime({ signal: createSignal })` first, for about 100 B. An island not reaching realtime pays nothing. The sync target is read from the document's `<meta name="ultimate-sync">` ([Configuration](Configuration), `SYNC_URL`) |
139
+ | 4. the install | nothing to write | `x build` builds every island whose own import graph reaches `@ultimat3/realtime` from an entry that calls `installRealtime({ signal: createSignal, cleanup: onCleanup })` first, for about 100 B — `cleanup` releases every hook with the component that called it (31.14.0), so an island writes no `onCleanup(() => h.release())`. An island not reaching realtime pays nothing. The sync target is read from the document's `<meta name="ultimate-sync">` ([Configuration](Configuration), `SYNC_URL`) |
139
140
  | 5. the hook | the component | `useQuery(ref, input)` returns an `AsyncState` accessor. **In an island, never a page body**: a page component never runs in a browser, so the hook answers `pending` there forever |
140
141
 
141
142
  ```tsx
142
143
  // app/feed/feed.island.tsx — the only module of /feed a browser downloads
143
144
  import { useConnection, useQuery } from '@ultimat3/realtime';
145
+ import { mountOver } from '@ultimat3/render/client';
144
146
  import { For, Match, Switch } from 'solid-js';
145
147
  import { render } from 'solid-js/web';
146
148
 
147
149
  type FeedRow = { id: string; title: string };
148
150
  const LIVE_FEED = { name: 'liveFeed', live: true } as const;
149
151
 
150
- export function mount(el: HTMLElement, props: { orgId: string }) {
151
- el.textContent = ''; // Solid's render APPENDS; the server's loading shell goes first
152
- render(() => <Feed orgId={props.orgId} />, el);
152
+ // mountOver clears the server's loading shell (Solid's render APPENDS) and puts it back on a throw.
153
+ export function mount(el: HTMLElement, props: { orgId: string }): () => void {
154
+ return mountOver(el, (root) => render(() => <Feed orgId={props.orgId} />, root));
153
155
  }
154
156
 
155
157
  function Feed(props: { orgId: string }) {
@@ -176,7 +178,8 @@ name its entity (`{ name, entity: 'post' }`) so its rows are store records too.
176
178
 
177
179
  **Two limits, `As of 2026-09-22`.** `x build` sees realtime only in the island's **own** graph. An
178
180
  island that reaches it through a package, rather than importing it, calls
179
- `installRealtime({ signal: createSignal })` in `mount` itself, or throws `X_REALTIME_UNINSTALLED`.
181
+ `installRealtime({ signal: createSignal, cleanup: onCleanup })` in `mount` itself, or throws
182
+ `X_REALTIME_UNINSTALLED`; without `cleanup`, every hook's `release()` stays the island's to call.
180
183
  And `live` and `entity` on the ref are stated by hand, not derived from the query declaration. Both
181
184
  are in the plan-101 DX ledger.
182
185
 
@@ -620,6 +623,24 @@ So the drain is **server-directed**:
620
623
 
621
624
  Full drain sequence per role: [Deployment](Deployment).
622
625
 
626
+ ## What a rollout costs
627
+
628
+ A deploy restarts both realtime roles; what each restart costs a subscriber, `As of 31.14.0`:
629
+
630
+ | Restart | Cost |
631
+ |---|---|
632
+ | a `sync` node | its sockets reconnect, spread over `drainSpreadMs` ([`sync` drain](#sync-drain)); each live query resumes from its cursor — the change buffer when the cursor is inside it, one bounded snapshot when not |
633
+ | the `replicator`, after a clean stop — `stop()`, SIGTERM, a deploy | **free**: no window re-read, no snapshot frame. The stopping run publishes a handover on `x.change.-handover` (its last `seq`, and how far its slot was confirmed), and the next run's first envelope says where it resumed (`from`, envelope v2); a node that read up to there takes it as a continuation. Held by `replicator.live.test.ts` against Postgres: stop + start, and a second process after a clean stop, both 0 invalidations |
634
+ | the `replicator`, after a crash (killed, OOM, lost lock) | **one re-read per live window** on every node: with no handover, the new run resumes at the slot's confirmed position, above what any node read, and the node cannot tell a lost tail from none. Each window is re-snapshotted on its next change. A run that comes back after ANOTHER process confirmed the slot past it (it lost its lock, the successor was killed) costs the same one: Postgres starts it at the slot's position, and it says so rather than claiming its own older lsn. Held by `replicator.live.test.ts`: lock lost → takeover → kill → return, 1 invalidation |
635
+ | a lost tail, a new or recreated slot, a resync | one re-read per window, as a crash |
636
+ | a mixed fleet mid-roll (one side before 31.14.0) | one re-read per window: an older node drops the handover and ignores `from`, an older replicator sends neither. Roll `sync` nodes first, so the replicator's own roll lands on nodes that chain |
637
+
638
+ The stop itself is quiet in the database log too: the stream reads the walsender's goodbye (CopyDone, CommandComplete, ReadyForQuery, at most 1 s) before `Terminate`, where it used to close unread and leave `Connection reset by peer` behind on every deploy.
639
+
640
+ ## Out of scope: a duplex byte stream
641
+
642
+ No channel kind carries an ordered, two-way byte stream to a browser — a terminal, a file transfer, a media relay. Decided, not pending ([plan 101 OD4](https://github.com/developerz-ai/ultimate/blob/main/docs/plans/2026/11/11/101-full-stack-efficiency-sweeps/90-owner-decisions.md)): one app asked, and the transport is business-shaped. A channel is at-most-once events and presence; a live query is rows. An app that needs one builds it on an action — a long-poll read of what arrived since a cursor, a write per input — and keeps the page socket for rows and events. Not planned; a second app asking reopens it.
643
+
623
644
  ## Wire protocol version
624
645
 
625
646
  `PROTOCOL_VERSION` is **3** `As of 2026-09-22` (21.0.0; it was 2 from 2026-08-24) ([`packages/realtime/src/sync-protocol.ts`](https://github.com/developerz-ai/ultimate/blob/main/packages/realtime/src/sync-protocol.ts)). A mismatch is `X_PROTOCOL_VERSION` on the frame, with one instruction, rather than a per-field decode error nobody can act on.
@@ -714,8 +735,8 @@ the listener's websocket paths are fixed when it binds. A container scans once,
714
735
  | `X_LIVE_QUERY_UNKNOWN` | a `subscribe` frame named a live query this node does not have | `x queries list --json` |
715
736
  | `X_CURSOR_STALE` | resume cursor cannot be honoured and no snapshot path was supplied | `pass 'snapshot' to resumeFrom() so the fallback path can re-snapshot instead of failing` |
716
737
  | `X_REBASE_CONFLICT` | a `custom(merge)` returned something other than a row with a string `id` | `set conflict: 'server-wins' on the mutator, or return a row from custom(merge)` |
717
- | `X_REALTIME_UNINSTALLED` | a hook ran in a browser island whose bundle never called `installRealtime()` | `x build`, which installs it on every island whose own graph imports realtime. An island that reaches realtime only through a package calls `installRealtime({ signal: createSignal })` in `mount` |
718
- | `X_SYNC_UNCONFIGURED` | a live hook needed the page socket, and neither `installRealtime({ sync })` nor `<meta name="ultimate-sync">` named a target. The meta is not rendered at all when `app.config.ts` says `realtime: { enabled: false }`: no node is started, so there is nothing to dial (22.2.2) | serve the page through `x dev` or the container, which render the meta, or pass `installRealtime({ signal, sync: { url, buildId } })` |
738
+ | `X_REALTIME_UNINSTALLED` | a hook ran in a browser island whose bundle never called `installRealtime()` | `x build`, which installs it on every island whose own graph imports realtime. An island that reaches realtime only through a package calls `installRealtime({ signal: createSignal, cleanup: onCleanup })` in `mount` |
739
+ | `X_SYNC_UNCONFIGURED` | a live hook needed the page socket, and neither `installRealtime({ sync })` nor `<meta name="ultimate-sync">` named a target. The meta is not rendered at all when `app.config.ts` says `realtime: { enabled: false }`: no node is started, so there is nothing to dial (22.2.2) | serve the page through `x dev` or the container, which render the meta, or pass `installRealtime({ signal, cleanup, sync: { url, buildId } })` |
719
740
  | `X_RECORD_REJECTED` | a row reached the record store with no key, or not as an object | `x entities show <entity> --json`, then return whole rows |
720
741
  | `X_MUTATOR_CLOCK_MISSING` | `conflict: 'last-write-wins'` with no number `updatedAt` on the entity | add the clock, or declare `conflict: 'server-wins'` |
721
742
  | `X_TRANSPORT_UNAVAILABLE` | the fanout bus is down. At boot only for `sync` and the replicator, after a bounded wait; on `web`, `worker` and `scheduler` it is what a publish rejects with while the bus is away ([what each role needs](#what-each-role-needs-from-the-bus)); on a socket it is the one refusal a client treats as transient ([a bus outage, seen from an open page](#a-bus-outage-seen-from-an-open-page)) | `x doctor — then check NATS_URL points at a reachable nats-server` |
package/wiki/SEO.md CHANGED
@@ -140,7 +140,7 @@ card page, `page.screenshot()`, `disk.put()`, then `og: { image }` with the stor
140
140
  | `buildFeed()` | RSS 2.0, Atom and JSON Feed from one item list. The channel's `author`, `copyright` and `icon` reach Atom as `<author>`, `<rights>` and `<icon>`; an item's `author` is `<author>` in Atom and, in RSS, `<author>` with an email or `<dc:creator>` without one; an item's `image` is an Atom enclosure link and an RSS `<media:content>`. An item date must be ISO-8601 with an offset or `Z`; one that is not is treated as absent (and an offsetless one is logged as `seo.feed.date_offsetless`), never read through the server's zone |
141
141
  | `builtinImageDriver({ read })` | resize and blur placeholder over core's pipeline — decodes `png`, `jpeg`, `webp`, `gif`; encodes `png`, `jpeg`, `webp`. `avif` needs a CDN driver (`X_IMAGE_UNSUPPORTED`), so `responsiveImage()` offers `webp` only unless given `formats`, and no width past 8192 (`MAX_IMAGE_WIDTH`). `As of 2026-10` |
142
142
  | `parseImageQuery()` | the one reader of the `?w=&f=&q=` a responsive image URL carries (`X_IMAGE_QUERY_INVALID`) |
143
- | `setStaticExport()` | the static build's seam: while it renders, `responsiveImage()` names `/_img/<source hash>-<width>.<ext>` files and `og.capture` names `/_og/<path>.png`. Unset in a served process — [Static assets](Static-Assets#responsive-images-in-a-static-export) |
143
+ | `setStaticExport()` | the static build's seam: while it renders, `responsiveImage()` names `/_img/<variant hash>-<width>.<ext>` files (source bytes, width, format and encoder) and `og.capture` names `/_og/<path>.png`. Unset in a served process — [Static assets](Static-Assets#responsive-images-in-a-static-export) |
144
144
 
145
145
  Every `X_SEO_*` and image code is in [Error codes](Error-Codes).
146
146
 
@@ -40,6 +40,42 @@ export const rotateApiKeys = task({
40
40
  });
41
41
  ```
42
42
 
43
+ ## A job on its own cron — `cronJob()`
44
+
45
+ A job that one task fires, and nothing else enqueues, is ONE declaration: `cronJob()` returns the job handle, and its `.schedule` is the task. A factory over `job()` and `task()`, not a ninth primitive (`PRIMITIVE_FACTORIES`). `As of 2026-11`.
46
+
47
+ ```ts
48
+ import { cronJob, t } from '@ultimat3/jobs';
49
+
50
+ export const sendDigest = cronJob({
51
+ name: 'sendDigest',
52
+ cron: '0 3 * * *',
53
+ tz: 'UTC',
54
+ input: t.object({ runDate: t.string }),
55
+ // The occurrence's instant, never the wall clock — the rule `enqueue` follows above.
56
+ payload: (occurrenceMs) => ({ runDate: new Date(occurrenceMs).toISOString().slice(0, 10) }),
57
+ idempotencyKey: ({ runDate }) => `digest:${runDate}`,
58
+ tenant: 'none',
59
+ retry: { attempts: 3 },
60
+ async run({ input }) {
61
+ return input.runDate;
62
+ },
63
+ });
64
+
65
+ // The task, `sendDigest.schedule`: `.enqueue()`, `.describe()`, `.entries()` like any other.
66
+ export const digestTask = sendDigest.schedule;
67
+ ```
68
+
69
+ | Field | Rule |
70
+ |---|---|
71
+ | `name` | **required**, unlike `job()`: the task is `<name>.schedule`, and the scheduler keys a task's last fire and occurrence lock by name |
72
+ | `cron`, `tz`, `catchUp`, `maxCatchUp` | the task's, with the task's rules: `tz` required and IANA |
73
+ | `input` + `payload` | together or not at all. `payload(occurrenceMs)` builds one occurrence's input. Without `input` the job takes none and each occurrence enqueues `{}` |
74
+ | `idempotencyKey` | optional: default `() => name` — one live run at a time, and a manual `.schedule.enqueue()` during one is that run. A tick's key is occurrence-scoped on top, as for every task |
75
+ | everything else | `job()`'s fields, unchanged: `tenant`, `retry`, `queue`, `timeout`, `concurrency`, `run`, … |
76
+
77
+ Hand the job's module to `defineApi({ jobs })`; the task registers with it — it needs no `tasks` entry. A task that fires several jobs, or a job other code also enqueues, stays a `task()` beside its jobs.
78
+
43
79
  ## The fluent surface
44
80
 
45
81
  Every projection is a method on the task — `nightlyDigest.enqueue()`, never `runTask(nightlyDigest)` — and every declared field is lifted onto it. A task has no `.def`.
package/wiki/Scraping.md CHANGED
@@ -386,7 +386,9 @@ No quota, plan or ledger reads these numbers. What a number is worth is the app'
386
386
  | `dead-lettered` / `dropped` | `error`, `code`, and `usage`: what the last attempt used. A failed run has no report and was billed all the same |
387
387
  | `refused` | `code: 'X_JOB_KEY_BUSY'`; `usage` is `undefined` — the body never ran |
388
388
 
389
- After the row is settled, under the job's tenant, **at most once** across a crash; a hook that
389
+ After the row is settled, under the job's tenant. A `completed` run carries its report, a value, so
390
+ it is told **at most once** across a crash; any other ending is **at least once** — re-driven with
391
+ `redriven: true` and `usage: undefined` when its worker died first. A hook that
390
392
  throws is `X_JOB_ON_SETTLED_FAILED` and changes nothing. `run({ progress })` is the job's own
391
393
  `progress(done, total, note?)`, passed through.
392
394