@ultimat3/cli 31.13.0 → 31.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cli",
3
- "version": "31.13.0",
3
+ "version": "31.14.0",
4
4
  "description": "The `x` binary: new, dev, build, verify, generate, db, mcp, doctor, deploy",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -53,34 +53,34 @@
53
53
  },
54
54
  "dependencies": {
55
55
  "@babel/core": "^8.0.9",
56
- "@ultimat3/action": "31.13.0",
57
- "@ultimat3/admin": "31.13.0",
58
- "@ultimat3/ai": "31.13.0",
59
- "@ultimat3/auth": "31.13.0",
60
- "@ultimat3/cache": "31.13.0",
61
- "@ultimat3/core": "31.13.0",
62
- "@ultimat3/db": "31.13.0",
63
- "@ultimat3/entity": "31.13.0",
64
- "@ultimat3/flags": "31.13.0",
65
- "@ultimat3/http": "31.13.0",
66
- "@ultimat3/i18n": "31.13.0",
67
- "@ultimat3/jobs": "31.13.0",
68
- "@ultimat3/mail": "31.13.0",
69
- "@ultimat3/manifest": "31.13.0",
70
- "@ultimat3/mcp": "31.13.0",
71
- "@ultimat3/money": "31.13.0",
72
- "@ultimat3/notify": "31.13.0",
73
- "@ultimat3/policy": "31.13.0",
74
- "@ultimat3/pwa": "31.13.0",
75
- "@ultimat3/query": "31.13.0",
76
- "@ultimat3/realtime": "31.13.0",
77
- "@ultimat3/render": "31.13.0",
78
- "@ultimat3/schema": "31.13.0",
79
- "@ultimat3/scraping": "31.13.0",
80
- "@ultimat3/seo": "31.13.0",
81
- "@ultimat3/storage": "31.13.0",
82
- "@ultimat3/testing": "31.13.0",
83
- "@ultimat3/time": "31.13.0",
56
+ "@ultimat3/action": "31.14.0",
57
+ "@ultimat3/admin": "31.14.0",
58
+ "@ultimat3/ai": "31.14.0",
59
+ "@ultimat3/auth": "31.14.0",
60
+ "@ultimat3/cache": "31.14.0",
61
+ "@ultimat3/core": "31.14.0",
62
+ "@ultimat3/db": "31.14.0",
63
+ "@ultimat3/entity": "31.14.0",
64
+ "@ultimat3/flags": "31.14.0",
65
+ "@ultimat3/http": "31.14.0",
66
+ "@ultimat3/i18n": "31.14.0",
67
+ "@ultimat3/jobs": "31.14.0",
68
+ "@ultimat3/mail": "31.14.0",
69
+ "@ultimat3/manifest": "31.14.0",
70
+ "@ultimat3/mcp": "31.14.0",
71
+ "@ultimat3/money": "31.14.0",
72
+ "@ultimat3/notify": "31.14.0",
73
+ "@ultimat3/policy": "31.14.0",
74
+ "@ultimat3/pwa": "31.14.0",
75
+ "@ultimat3/query": "31.14.0",
76
+ "@ultimat3/realtime": "31.14.0",
77
+ "@ultimat3/render": "31.14.0",
78
+ "@ultimat3/schema": "31.14.0",
79
+ "@ultimat3/scraping": "31.14.0",
80
+ "@ultimat3/seo": "31.14.0",
81
+ "@ultimat3/storage": "31.14.0",
82
+ "@ultimat3/testing": "31.14.0",
83
+ "@ultimat3/time": "31.14.0",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
@@ -1,6 +1,6 @@
1
1
  // Realtime installed for the author, on exactly the islands that use it: an island whose own import
2
2
  // graph reaches `@ultimat3/realtime` is built from a virtual entry that first awaits the page
3
- // runtime (`island-runtime.ts`), then calls `installRealtime({ signal: createSignal })` with THIS
3
+ // runtime (`island-runtime.ts`), then calls `installRealtime({ signal, cleanup })` with THIS
4
4
  // bundle's solid-js, then re-exports the island whole. Every other island pays nothing. An island
5
5
  // that reads the record store or the outbox also waits for the page's restore before it mounts
6
6
  // (#506); one that only follows the socket does not (`island-realtime-state.ts`).
@@ -90,13 +90,19 @@ const entrySource = (file: string, follows: boolean): string =>
90
90
  * on a document rendered for a principal; anywhere else the island loads the runtime chunk, by a
91
91
  * path relative to its own URL, so it resolves under `/islands/` and beside it in `mountIsland`.
92
92
  * The chunk's URL is in this source, so a new runtime is a new URL for every island loading it.
93
+ *
94
+ * `cleanup` is Solid's `onCleanup`, so every hook a component holds is released with it — the
95
+ * island author writes no `onCleanup(() => h.release())`. A hook held outside a component (module
96
+ * scope, an event handler) has no owner, so Solid registers nothing and it stays the caller's: an
97
+ * island is built against solid's production build (`island-solid-dedupe.ts`), which is silent
98
+ * there.
93
99
  */
94
100
  const installSource = (runtimeUrl: string): string =>
95
101
  `import { installRealtime } from '${REALTIME}';\n` +
96
102
  `import { awaitPageRuntime } from '${WAIT}';\n` +
97
- `import { createSignal } from 'solid-js';\n` +
103
+ `import { createSignal, onCleanup } from 'solid-js';\n` +
98
104
  `await awaitPageRuntime({ boot: '${PAGE_BOOT_BASE_PATH}/', load: () => import('./${basename(runtimeUrl)}') });\n` +
99
- `installRealtime({ signal: createSignal });\n`;
105
+ `installRealtime({ signal: createSignal, cleanup: onCleanup });\n`;
100
106
 
101
107
  /**
102
108
  * The first-paint hold (#506), for an island that reads the record store or the outbox: `mount`
@@ -4,7 +4,12 @@
4
4
  // declaring `partitionBy` with no `partitions()` job registered (`X_PARTITIONS_UNMAINTAINED`).
5
5
 
6
6
  import { ERROR_DOCS_URL } from '@ultimat3/core';
7
- import { partitionedEntities, registeredJobs, registeredTasks } from '@ultimat3/jobs';
7
+ import {
8
+ isPartitionsJob,
9
+ partitionedEntities,
10
+ registeredJobs,
11
+ registeredTasks,
12
+ } from '@ultimat3/jobs';
8
13
  import { loadApp } from './app-load';
9
14
  import type { AppLoader } from './app-permissions';
10
15
  import type { Finding } from './output';
@@ -48,23 +53,14 @@ export async function unregisteredJobFindings(
48
53
  ];
49
54
  }
50
55
 
51
- /** What a registered job has to look like for this rule: a name, and maybe a `.schedule` task. */
52
- interface JobShape {
53
- readonly name: string;
54
- readonly schedule?: { readonly name: string };
55
- }
56
-
57
56
  /**
58
- * Recognised by SHAPE, so a renamed `partitions({ name })` counts: the handle carries the
59
- * `.schedule` task the factory minted, named `<job>.schedule`. Nothing else does — `consumer()`
60
- * carries `.supervisor`.
57
+ * Pure: the partitioned tables and the registered jobs in, one finding when none maintains them.
58
+ * A maintainer is recognised by IDENTITY (`isPartitionsJob`), so a renamed `partitions({ name })`
59
+ * counts and a `cronJob()` — the same `<job>.schedule` shape — does not.
61
60
  */
62
- const isPartitionsJob = (job: JobShape): boolean => job.schedule?.name === `${job.name}.schedule`;
63
-
64
- /** Pure: the partitioned tables and the registered jobs in, one finding when none maintains them. */
65
61
  export function unmaintainedPartitionFindings(
66
62
  tables: readonly string[],
67
- jobs: readonly JobShape[],
63
+ jobs: readonly unknown[],
68
64
  ): readonly Finding[] {
69
65
  if (tables.length === 0 || jobs.some(isPartitionsJob)) return [];
70
66
  return [
@@ -18,7 +18,8 @@ const source =
18
18
  //
19
19
  // Why: a raw interval keeps asking from a background tab, and from a tab past its session it asks
20
20
  // for a 401 forever. \`visibleInterval(run, ms)\` from \`@ultimat3/core/page\` makes no call while the
21
- // tab is hidden, one when it is shown, and stops at the first lost session. Read: a bare,
21
+ // tab is hidden, one when it is shown, and stops at the first lost session; a query's re-read is
22
+ // \`useQuery(ref, input, { poll: pollEvery(ms) })\`, the same timer, built. Read: a bare,
22
23
  // \`window.\`, \`self.\` or \`globalThis.\` \`setInterval(\` in a \`*.island.tsx\`. Admitted: a \`// why:\` on
23
24
  // the call's line or the line above it — an animation tick is not a read. Not read: a bare
24
25
  // \`setInterval(\` in a file that binds its own (declared, imported, a parameter, destructured).
@@ -64,7 +65,7 @@ export function rawIntervals(files: readonly SourceFile[]): readonly Finding[] {
64
65
  findings.push({
65
66
  code: CODE,
66
67
  cause: \`\${at} polls with setInterval, which keeps asking from a hidden tab and asks for a 401 forever once the session is gone\`,
67
- fix: \`import { visibleInterval } from '@ultimat3/core/page' and call visibleInterval(run, ms) at \${at}, disposing it on cleanup — or add a // why: comment on that line naming why this interval is not a read — then: x verify\`,
68
+ fix: \`re-read a query with useQuery(ref, input, { poll: pollEvery(ms) }) (pollEvery is exported by @ultimat3/realtime) at \${at}; any other read: import { visibleInterval } from '@ultimat3/core/page' and call visibleInterval(run, ms) there, disposing it on cleanup — or add a // why: comment on that line naming why this interval is not a read — then: x verify\`,
68
69
  at,
69
70
  });
70
71
  }
@@ -45,7 +45,7 @@ queries, jobs, MCP tools, published operations and tests it touches, each with p
45
45
  | Data | routes call actions and queries; only \`repo.ts\` touches the database | \`X_BOUNDARY_ROUTE_TO_DB\` |
46
46
  | Repos | a \`repo.ts\` reads through the typed handle, never a \`sql\` literal the handle can express | \`guards/repo-raw-sql.ts\` |
47
47
  | Vendors | a server \`fetch(\` carries a \`signal\` in its own options — better, it is \`outbound()\` from \`@ultimat3/core/outbound\`: a deadline, the caller's signal, safe-only retry | \`guards/raw-fetch.ts\` |
48
- | Polling | an island re-reads on a timer with \`visibleInterval(run, ms)\` from \`@ultimat3/core/page\` — no call while the tab is hidden, none after a lost session — never a bare \`setInterval(\`; a \`// why:\` on the line admits a tick that is not a read | \`guards/raw-interval.ts\` |
48
+ | Polling | an island re-reads a query on a timer with \`useQuery(ref, input, { poll: pollEvery(ms) })\` (\`@ultimat3/realtime\`), anything else with \`visibleInterval(run, ms)\` from \`@ultimat3/core/page\` — no call while the tab is hidden, none after a lost session — never a bare \`setInterval(\`; a \`// why:\` on the line admits a tick that is not a read | \`guards/raw-interval.ts\` |
49
49
  | Confirmation | a destructive act asks through \`ConfirmDialog\` from \`@ultimat3/ui\` — Cancel focused, a native post, stays open on a refusal — never \`confirm(\`; a \`// why:\` on the line admits a call that is not that question | \`guards/native-confirm.ts\` |
50
50
  | Errors | never \`throw new Error\` — declare each code once, \`defineError({ code, title, status, cause, fix })\` from \`@ultimat3/core/page\`, and throw its class; never a handwritten \`UltimateError\` subclass | \`guards/bare-error.ts\`, \`guards/error-declared.ts\` |
51
51
  | Money | \`{ minor, currency }\`, never a float — \`money()\` on the column | the type: \`price: 19.99\` is TS2322, \`number\` is not \`MoneyInput\` |
@@ -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
 
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 })`,
@@ -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,7 +136,7 @@ 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
@@ -176,7 +177,8 @@ name its entity (`{ name, entity: 'post' }`) so its rows are store records too.
176
177
 
177
178
  **Two limits, `As of 2026-09-22`.** `x build` sees realtime only in the island's **own** graph. An
178
179
  island that reaches it through a package, rather than importing it, calls
179
- `installRealtime({ signal: createSignal })` in `mount` itself, or throws `X_REALTIME_UNINSTALLED`.
180
+ `installRealtime({ signal: createSignal, cleanup: onCleanup })` in `mount` itself, or throws
181
+ `X_REALTIME_UNINSTALLED`; without `cleanup`, every hook's `release()` stays the island's to call.
180
182
  And `live` and `entity` on the ref are stated by hand, not derived from the query declaration. Both
181
183
  are in the plan-101 DX ledger.
182
184
 
@@ -620,6 +622,24 @@ So the drain is **server-directed**:
620
622
 
621
623
  Full drain sequence per role: [Deployment](Deployment).
622
624
 
625
+ ## What a rollout costs
626
+
627
+ A deploy restarts both realtime roles; what each restart costs a subscriber, `As of 31.14.0`:
628
+
629
+ | Restart | Cost |
630
+ |---|---|
631
+ | 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 |
632
+ | 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 |
633
+ | 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 |
634
+ | a lost tail, a new or recreated slot, a resync | one re-read per window, as a crash |
635
+ | 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 |
636
+
637
+ 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.
638
+
639
+ ## Out of scope: a duplex byte stream
640
+
641
+ 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.
642
+
623
643
  ## Wire protocol version
624
644
 
625
645
  `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 +734,8 @@ the listener's websocket paths are fixed when it binds. A container scans once,
714
734
  | `X_LIVE_QUERY_UNKNOWN` | a `subscribe` frame named a live query this node does not have | `x queries list --json` |
715
735
  | `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
736
  | `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 } })` |
737
+ | `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` |
738
+ | `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
739
  | `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
740
  | `X_MUTATOR_CLOCK_MISSING` | `conflict: 'last-write-wins'` with no number `updatedAt` on the entity | add the clock, or declare `conflict: 'server-wins'` |
721
741
  | `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` |
@@ -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
 
package/wiki/Upgrading.md CHANGED
@@ -251,6 +251,14 @@ A setter still on a package's `.` barrel is `X_ADAPTER_PORT_INCOMPLETE` on the `
251
251
  | an on-time `jobs.scheduler.dispatched` logs at `debug` (**31.13.0**); a catch-up fire and `jobs.scheduler.already-fired` stay `info` | an alert or dashboard keyed on `jobs.scheduler.dispatched` at `info` keys on `catchUp: true` for missed fires, or sets `LOG_LEVEL=debug` on the `scheduler` role to keep every line |
252
252
  | with a proven wake, an idle worker rests up to 60 s between claims (**31.13.0**; was ≤ 5 s). An enqueue due within 60 s now notifies (was within 1 s), so a delayed job another process queues still starts at its `runAt`; a worker that stops holding a retry or `step.sleep` due soon announces it (`JobDriver.wake`). Only a driver with `wake` rests — Redis keeps the 5 s poll | nothing for the shipped drivers. A custom `JobDriver` whose enqueues reach every worker adds `wake(queue?)` to let its workers rest; without it they keep the 2–5 s poll |
253
253
  | a custom `JobDriver` or `OutboxStore` proved with `behavesLike(jobDriverConformance, …)` / `behavesLike(outboxStoreConformance, …)` (`@ultimat3/testing/conformance`) meets new checks (**31.13.0**): an empty claim calls `ClaimOptions.onEmpty(dueInMs)` (`null`, a delayed row, a held lease), a claimed row carries `steps`, and an empty outbox `claim(limit, { onEmpty })` reports a held row's lease | implement them — `memoryJobDriver` and `memoryOutboxStore` are the shapes to copy — or keep the driver unproved: each is optional on the interface, and a driver without them keeps the 2–5 s poll and the per-attempt step list |
254
+ | the first boot on **31.14.0** adds `x_jobs.expires_at`, `x_jobs.settle_owed` (`boolean not null default false`) with the partial index `x_jobs_settle_owed_idx`, `x_jobs.debounced_id` (`uuid`) with the partial index `x_jobs_debounced_idx`, and `x_outbox.on_conflict` / `x_outbox.expires_at`, inside the locked framework-schema apply — additive, no row rewritten. An app that commits the framework schema dump (`packages/db/schema/framework/`) sees `X_SCHEMA_DUMP_DRIFT` on `x_jobs` and `x_outbox` until it regenerates it | `x db gen` once and commit the regenerated `04_tables/x_jobs.sql`, `04_tables/x_outbox.sql` and `05_indexes/x_jobs.sql`; no migration |
255
+ | `onSettled` can now run more than once for one ending (**31.14.0**): a failure, a dead letter, a `whenBusy: 'fail'` refusal or a completion whose body returned `undefined`, when the worker died between the settle and the hook's return — re-driven by the scheduler leader with `settled.redriven === true`, `reason: 'lost'`. A completion that returned a value, a final-attempt lease lapse the claim buried and an expired row are still told at most once | write the hook to be repeated: an upsert or a guarded update, a notification keyed by `settled.input` and the outcome. Branch on `settled.redriven` where a repeat must be told apart |
256
+ | `jobs.step.output-too-large` (`X_STEP_OUTPUT_TOO_LARGE`) at `warn`, once per job and step, for a `step.run` output past 256 KiB of JSON (**31.14.0**). Stored as before; refused by default from the next major | `step.run(name, async () => { await storage.put(key, bytes); return key; })` — persist the payload and return its key; or declare `job({ stepOutputMax: <bytes> })`, which refuses past it now (terminal) |
257
+ | `x verify` reports `X_PARTITIONS_UNMAINTAINED` in an app with an entity declaring `partitionBy` and no `partitions()` job, where a job carrying a `<name>.schedule` task — a `cronJob()`, or one built by hand that way — used to satisfy it (**31.14.0**: a maintainer is recognised by identity, `isPartitionsJob`) | export `partitions()` (`@ultimat3/jobs`) from a module listed under `jobs` in `apps/web/api/index.ts` and its `.schedule` under `tasks`, then `x verify --only manifest --json` — the error's own `fix:` |
258
+ | a custom `JobDriver` or `OutboxStore` proved with `behavesLike(jobDriverConformance, …)` / `behavesLike(outboxStoreConformance, …)` meets new checks (**31.14.0**): `onConflict: 'replace'` (fenced by request order, a repeat after the holder ran included) and `expiresAt` on `enqueue`, `backlog(queue, cap)`, `holds(name, key, tenantId?)`, the `settleDebt` debt, a requeue that clears expiry and debt, and a staged row keeping `onConflict` / `expiresAt` | implement them — `memoryJobDriver` (`driver-memory-enqueue.ts`, `driver-memory-settle.ts`) and `memoryOutboxStore` are the shapes to copy — or keep the driver unproved: `backlog` and `settleDebt` are optional, and without them a job declaring `maxPending` is `X_INVARIANT` at enqueue and `onSettled` stays at most once |
259
+ | a realtime hook created inside a component is released when that component is disposed (**31.14.0**): `x build`'s island bootstrap calls `installRealtime({ signal: createSignal, cleanup: onCleanup })`, and every `use*` hook registers its own `release()` through it. Before, it lived until the island called `release()` — or, forgotten, until the page unloaded, holding a socket subscription and a cap slot. A handle the island kept using after its component went (stored in a module variable or a parent's state) now reads nothing new | create a long-lived handle outside any component — at module scope or in `mount`, before `render()`: no owner, nothing registered, its `release()` is yours. A hand-built island (one that calls `installRealtime` itself) adds `cleanup: onCleanup` from its own `solid-js`; without it every `release()` stays the island's. An `onCleanup(() => h.release())` already written is harmless: a release runs once. Optional: delete it |
260
+ | `x doctor` lists `raw-interval` as differing from the shipped template after the **31.14.0** hop: its `fix:` now names `useQuery(ref, input, { poll: pollEvery(ms) })` for a query's timed re-read, before `visibleInterval(run, ms)`. The rule is the same; nothing new is reported | `x g guard raw-interval --force` — it rewrites `guards/raw-interval.ts` **and** its `.test.ts`, so review the diff and keep any rule you edited on purpose. Then `x verify` |
261
+ | a replicator restart chains (**31.14.0**): the change envelope is version 2 — a run's first envelope carries `from`, and a clean stop publishes a handover on `x.change.-handover` — so a deploy of the `replicator` role after a clean stop re-snapshots no live window. A crash still costs one re-read per window. During a roll, an old node reading a new replicator, or a new node reading an old one, reads the restart as a gap, exactly as before | roll the `sync` role before the `replicator` role. Either order is safe; only nodes already on 31.14.0 chain the replicator's own restart. A custom `ChangeFeed` (`@ultimat3/realtime/server`) chains only once it implements the optional `position()` and `onResume` |
254
262
 
255
263
  ## 29.x → 30.0.0, entry by entry
256
264