@ultimat3/cli 31.15.0 → 31.17.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 (86) hide show
  1. package/README.md +7 -1
  2. package/package.json +29 -29
  3. package/src/cache-graph.ts +67 -0
  4. package/src/cmd-cache-spec.ts +25 -0
  5. package/src/cmd-cache.ts +187 -0
  6. package/src/cmd-config-spec.ts +23 -0
  7. package/src/cmd-config.ts +61 -0
  8. package/src/cmd-doctor.ts +47 -37
  9. package/src/cmd-exercise.ts +42 -5
  10. package/src/cmd-explain-spec.ts +24 -0
  11. package/src/cmd-explain.ts +201 -0
  12. package/src/cmd-logs-spec.ts +34 -0
  13. package/src/cmd-logs.ts +80 -0
  14. package/src/cmd-planned.ts +15 -29
  15. package/src/cmd-token-spec.ts +54 -0
  16. package/src/cmd-token.ts +173 -0
  17. package/src/cmd-upgrade.ts +19 -2
  18. package/src/cmd-verify-spec.ts +13 -3
  19. package/src/cmd-verify.ts +2 -0
  20. package/src/config-redact.ts +39 -0
  21. package/src/coverage-floor.ts +2 -2
  22. package/src/dev-boot-data-dir.ts +69 -0
  23. package/src/dev-boot.ts +26 -13
  24. package/src/doctor-env-reserved.ts +111 -0
  25. package/src/doctor-floor.ts +62 -0
  26. package/src/doctor-pins.ts +101 -0
  27. package/src/doctor-probe.ts +21 -1
  28. package/src/doctor-row-security.ts +119 -4
  29. package/src/doctor-warnings.ts +55 -0
  30. package/src/error-codes-doctor.ts +24 -0
  31. package/src/error-codes-tooling.ts +6 -4
  32. package/src/error-codes.ts +7 -0
  33. package/src/errors.ts +8 -2
  34. package/src/exercise-entry-edit.ts +5 -1
  35. package/src/exercise-floor-report.ts +138 -0
  36. package/src/exercise-floor-verdict.ts +98 -0
  37. package/src/exercise-floor.ts +158 -0
  38. package/src/exercise-routes.ts +59 -0
  39. package/src/explain-capture.ts +38 -0
  40. package/src/generate-exercise.ts +2 -2
  41. package/src/generate-factories.ts +133 -0
  42. package/src/generate-files.ts +11 -0
  43. package/src/generate-kinds.ts +13 -0
  44. package/src/mcp-db-target.ts +4 -3
  45. package/src/mcp-errors.ts +14 -0
  46. package/src/messages-gate.ts +2 -0
  47. package/src/messages-ops.ts +32 -0
  48. package/src/messages-upgrade.ts +14 -0
  49. package/src/messages.ts +5 -0
  50. package/src/otlp-export.ts +16 -2
  51. package/src/registry.ts +10 -0
  52. package/src/role-start.ts +11 -5
  53. package/src/runtime-services.ts +35 -19
  54. package/src/serve-boot-phases.ts +30 -0
  55. package/src/serve-boot-warnings.ts +62 -0
  56. package/src/serve-boot.ts +30 -11
  57. package/src/templates/generate-cron-job.ts +90 -0
  58. package/src/templates/generate-purge.ts +93 -0
  59. package/src/templates/generate-webhook-receiver.ts +274 -0
  60. package/src/templates/github/ci.yml.ts +101 -36
  61. package/src/templates/guard-repo-raw-sql-test.ts +174 -0
  62. package/src/templates/guard-repo-raw-sql.ts +115 -145
  63. package/src/templates/guard-unbounded-fanout.ts +170 -0
  64. package/src/templates/scaffold-claude-commands.ts +3 -2
  65. package/src/templates/scaffold-docs.ts +3 -2
  66. package/src/templates/scaffold-guards.ts +3 -0
  67. package/src/templates/scaffold-verify-floor.ts +4 -0
  68. package/src/test-dotenv.ts +15 -2
  69. package/src/upgrade-coverage.ts +109 -0
  70. package/src/upgrade-document.ts +18 -0
  71. package/src/upgrade-exercise-floor.ts +53 -0
  72. package/src/upgrade-gate.ts +84 -29
  73. package/src/upgrade-guards.ts +159 -0
  74. package/src/upgrade-report.ts +33 -1
  75. package/src/verify-checks.ts +3 -1
  76. package/src/verify-floor.ts +13 -0
  77. package/src/verify-plan.ts +127 -0
  78. package/wiki/CI-Parallel-Gate.md +38 -1
  79. package/wiki/CLI-Reference.md +115 -14
  80. package/wiki/Caching-And-Invalidation.md +10 -10
  81. package/wiki/Configuration.md +20 -2
  82. package/wiki/Known-Gaps.md +1 -1
  83. package/wiki/MCP-And-AI.md +1 -1
  84. package/wiki/Testing.md +96 -2
  85. package/wiki/Troubleshooting.md +3 -2
  86. package/wiki/Upgrading.md +9 -0
@@ -0,0 +1,32 @@
1
+ // The `x token`, `x config`, `x logs`, `x cache` and `x explain` rows of the CLI catalog
2
+ // (`messages.ts` composes them): what each operator command found or did. Data only.
3
+
4
+ export const OPS_MESSAGES = {
5
+ 'cli.token.created': 'issued {prefix} with {count} scope(s) — the token is printed once, below',
6
+ 'cli.token.plaintext': ' {token}',
7
+ 'cli.token.once': ' shown once: only its hash is stored, and no command prints it again',
8
+ 'cli.token.listed': '{count} token(s) owned by {owner}',
9
+ 'cli.token.row': ' {prefix} {scopes} {state}',
10
+ 'cli.token.revoked': 'revoked {at}',
11
+ 'cli.token.noExpiry': 'no expiry',
12
+ 'cli.token.expires': 'expires {at}',
13
+ 'cli.token.revokedOne': 'revoked {id} — the next request that presents it is refused',
14
+ 'cli.token.notLive': 'no live token has the id {id} — nothing to revoke',
15
+ 'cli.config.show': '{name}: {count} config section(s), defaults merged, from {path}',
16
+ 'cli.config.section': '{section}, defaults merged, from {path}',
17
+ 'cli.logs.tail': '{count} line(s) from the end of {path}',
18
+ 'cli.cache.graph': '{tags} tag(s); {stale} read and never invalidated by an action',
19
+ 'cli.cache.graphRow': ' {tag}: written by {writers} · read by {readers}',
20
+ 'cli.cache.busted': 'busted {tags} tag(s) here and on every replica listening on {bus}',
21
+ 'cli.cache.bustedLocal':
22
+ 'busted {tags} tag(s) in this process only: the bus is in-process, so no running server heard it — set NATS_URL or REDIS_URL, or bust from /_x',
23
+ 'cli.cache.tierRow': ' {tier}: {keys} key(s) dropped',
24
+ 'cli.explain.served': '{query}: {planned} statement(s) planned, each served by a declared index',
25
+ 'cli.explain.red': '{query}: {count} read(s) no declared index serves',
26
+ 'cli.explain.unplannable':
27
+ '{query}: the dev database could not plan it — x db migrate first if its tables are missing',
28
+ 'cli.explain.none':
29
+ '{query}: sent no statement — its rows come from memory or a provider that reads no table',
30
+ 'cli.explain.exempt': ' may scan: {reason}',
31
+ 'cli.explain.refused': ' not planned: {reason}',
32
+ } as const;
@@ -31,6 +31,20 @@ export const UPGRADE_MESSAGES = {
31
31
  'cli.upgrade.done': '{from} -> {to}: the gate is green',
32
32
  'cli.upgrade.dryRun': '{from} -> {to}: nothing written, no gate run',
33
33
  'cli.upgrade.guard': 'guard, yours to take or leave: {fix}',
34
+ 'cli.upgrade.doctorWarning': 'doctor warning: {code}, red on the next major — fix: {fix}',
35
+ 'cli.upgrade.guardInstalled':
36
+ 'guard installed: guards/{name}.ts, from this release (delete the file to drop the rule)',
37
+ 'cli.upgrade.guardWithheld':
38
+ 'guard not installed, the tree breaks it in {count} place(s) — yours to take: {fix}',
39
+ 'cli.upgrade.guardUnmeasured':
40
+ 'guard not installed, its findings could not be counted — yours to take: {fix}',
41
+ 'cli.upgrade.coverage':
42
+ 'coverage floor: {file} {fromLines} / {fromFuncs} -> {toLines} / {toFuncs}, measured {lines}% / {funcs}% after the Bun floor moved — review the why',
43
+ 'cli.upgrade.exerciseFloor':
44
+ 'exercise floor: {file} "exercise" {figures}, measured by this hop\'s x exercise — it may only fall',
45
+ 'cli.upgrade.coverage.unpinned': 'no engines.bun',
46
+ 'cli.upgrade.coverage.why':
47
+ 'Rebaselined {date} by x upgrade to {release}: Bun {bunFrom} -> {bunTo}, with no test or source changed, measured {lines}% of lines and {funcs}% of functions, so the floor moves from {fromLines} / {fromFuncs} to {toLines} / {toFuncs}.',
34
48
  'cli.upgrade.read': 'read: {title} — {url}',
35
49
  'cli.upgrade.red': '{from} -> {to}: not done, the gate says: {summary}',
36
50
  'cli.upgrade.stillRunning': 'x upgrade: still in {stage} ({elapsed})',
package/src/messages.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  import { CLIENT_MESSAGES } from './messages-client';
7
7
  import { DB_MESSAGES } from './messages-db';
8
8
  import { GATE_MESSAGES } from './messages-gate';
9
+ import { OPS_MESSAGES } from './messages-ops';
9
10
  import { REPRO_MESSAGES } from './messages-repro';
10
11
  import { SHOT_MESSAGES } from './messages-shot';
11
12
  import { UPGRADE_MESSAGES } from './messages-upgrade';
@@ -104,6 +105,9 @@ const CATALOG = {
104
105
  // `x doctor`'s reminder: the rolling rail is off until this key is set (`doctor-rolling.ts`).
105
106
  'cli.doctor.rollingSince':
106
107
  'the rolling-deploy rail is off: set "rollingSince": "{newest}" in x.verify.json to judge every migration after your newest',
108
+ // `x doctor`'s warnings: beside the verdict on `main`, red on `next` (`doctor-warnings.ts`).
109
+ 'cli.doctor.warnings': '{count} warning(s) — not in the verdict until the next major:',
110
+ 'cli.doctor.warning': ' {code}: {cause} — fix: {fix}',
107
111
  'cli.docs.code': '{code} is an error code — x errors explain answers it',
108
112
  'cli.docs.exports': 'exports: {list}',
109
113
  'cli.docs.installed': 'installed: {list}',
@@ -279,6 +283,7 @@ const CATALOG = {
279
283
  ...SHOT_MESSAGES,
280
284
  ...UPGRADE_MESSAGES,
281
285
  ...GATE_MESSAGES,
286
+ ...OPS_MESSAGES,
282
287
  } as const;
283
288
 
284
289
  export type MessageKey = keyof typeof CATALOG;
@@ -8,6 +8,7 @@
8
8
 
9
9
  import type { OtlpSignal, ShutdownReason } from '@ultimat3/core';
10
10
  import {
11
+ finiteCount,
11
12
  isProduction,
12
13
  logger,
13
14
  onShutdown,
@@ -65,7 +66,15 @@ export const METRIC_EXPORT_INTERVAL_MS = 60_000;
65
66
  * and its timer stops, rather than being dropped and leaked. Metrics are the same shape since
66
67
  * 31.0.0: a `metric.export` subscription, released by its unsubscribe.
67
68
  */
68
- export function startOtlpExport(env: Env = process.env): () => void {
69
+ export interface OtlpExportOptions {
70
+ /** `database.slowStatementMs` from `app.config.ts`: replaces the 500 ms default, `0` is off. */
71
+ readonly slowStatementMs?: number | undefined;
72
+ }
73
+
74
+ export function startOtlpExport(
75
+ env: Env = process.env,
76
+ options: OtlpExportOptions = {},
77
+ ): () => void {
69
78
  const releases: (() => void)[] = [];
70
79
  const flushes: (() => Promise<void>)[] = [];
71
80
 
@@ -78,7 +87,12 @@ export function startOtlpExport(env: Env = process.env): () => void {
78
87
  // test suite's deliberately slow statements are not an operator's incident. Released with the
79
88
  // rest, so a second boot in this process never logs each statement twice.
80
89
  const production = isProduction({ env });
81
- releases.push(slowStatementLog({ thresholdMs: production ? SLOW_STATEMENT_THRESHOLD_MS : 0 }));
90
+ const threshold = finiteCount(
91
+ 'startOtlpExport',
92
+ 'slowStatementMs',
93
+ options.slowStatementMs ?? SLOW_STATEMENT_THRESHOLD_MS,
94
+ );
95
+ releases.push(slowStatementLog({ thresholdMs: production ? threshold : 0 }));
82
96
  // Every environment: the statements, renders and cache lookups each request caused, which
83
97
  // `http.request.slow` carries (its own threshold, `http.slowRequestMs`, decides whether it is
84
98
  // written). Without it the line holds the gate and handler split and no statement count.
package/src/registry.ts CHANGED
@@ -9,9 +9,11 @@
9
9
  import { affectedSpec } from './cmd-affected-spec';
10
10
  import { authSpec } from './cmd-auth-spec';
11
11
  import { buildSpec } from './cmd-build-spec';
12
+ import { cacheSpec } from './cmd-cache-spec';
12
13
  import { ciSpec } from './cmd-ci-spec';
13
14
  import { cleanSpec } from './cmd-clean-spec';
14
15
  import { clientSpec } from './cmd-client-spec';
16
+ import { configSpec } from './cmd-config-spec';
15
17
  import { dbSpec } from './cmd-db-spec';
16
18
  import { deploySpec } from './cmd-deploy-spec';
17
19
  import { devSpec } from './cmd-dev-spec';
@@ -21,6 +23,7 @@ import { drillSpec } from './cmd-drill-spec';
21
23
  import { envSpec } from './cmd-env-spec';
22
24
  import { errorsSpec } from './cmd-errors-spec';
23
25
  import { exerciseSpec } from './cmd-exercise-spec';
26
+ import { explainSpec } from './cmd-explain-spec';
24
27
  import { fixSpec } from './cmd-fix-spec';
25
28
  import { generateSpec } from './cmd-generate-spec';
26
29
  import { graphSpec } from './cmd-graph-spec';
@@ -31,6 +34,7 @@ import { createHelpCommand, createVersionCommand } from './cmd-help';
31
34
  import { i18nSpec } from './cmd-i18n-spec';
32
35
  import { impactSpec } from './cmd-impact-spec';
33
36
  import { jobsSpec } from './cmd-jobs-spec';
37
+ import { logsSpec } from './cmd-logs-spec';
34
38
  import { mailSpec } from './cmd-mail-spec';
35
39
  import { manifestSpec } from './cmd-manifest-spec';
36
40
  import { mcpSpec } from './cmd-mcp-spec';
@@ -46,6 +50,7 @@ import { shotSpec } from './cmd-shot-spec';
46
50
  import { stopSpec } from './cmd-stop-spec';
47
51
  import { tasksSpec } from './cmd-tasks-spec';
48
52
  import { testSpec } from './cmd-test-spec';
53
+ import { tokenSpec } from './cmd-token-spec';
49
54
  import { upgradeSpec } from './cmd-upgrade-spec';
50
55
  import { vapidSpec } from './cmd-vapid-spec';
51
56
  import { verifySpec } from './cmd-verify-spec';
@@ -125,6 +130,11 @@ export const LAZY_COMMANDS: readonly LazyCommand[] = [
125
130
  lazy(clientSpec, async () => (await import('./cmd-client')).clientCommand),
126
131
  lazy(graphSpec, async () => (await import('./cmd-graph')).graphCommand),
127
132
  lazy(impactSpec, async () => (await import('./cmd-impact')).impactCommand),
133
+ lazy(tokenSpec, async () => (await import('./cmd-token')).tokenCommand),
134
+ lazy(configSpec, async () => (await import('./cmd-config')).configCommand),
135
+ lazy(logsSpec, async () => (await import('./cmd-logs')).logsCommand),
136
+ lazy(cacheSpec, async () => (await import('./cmd-cache')).cacheCommand),
137
+ lazy(explainSpec, async () => (await import('./cmd-explain')).explainCommand),
128
138
  ];
129
139
 
130
140
  /**
package/src/role-start.ts CHANGED
@@ -50,6 +50,7 @@ import { reportUnservedQueues } from './runtime-jobs-unserved';
50
50
  import { startLiveFeed } from './runtime-live-feed';
51
51
  import { type RunningServices, releaseOrThrow } from './runtime-services';
52
52
  import { inlineScriptSources } from './script-csp';
53
+ import { bootWarningConcernsAny } from './serve-boot-warnings';
53
54
  import { inlineStyleSources } from './style-csp';
54
55
  import { syncConnectSources } from './sync-url';
55
56
  import { trustedHopsFromEnv } from './trusted-hops';
@@ -157,10 +158,7 @@ function warnIfProcessScoped(store: RateLimitStore): void {
157
158
  * runtime, which is `httpServer`'s per-process memory store and `scope: 'process'` below.
158
159
  */
159
160
  function rateLimitStoreFor(options: StartRolesOptions): RateLimitStore | undefined {
160
- const supplied = options.overrides?.rateLimitStore;
161
- if (supplied === undefined) return options.runtime.rateLimitStore;
162
- warnIfProcessScoped(supplied);
163
- return supplied;
161
+ return options.overrides?.rateLimitStore ?? options.runtime.rateLimitStore;
164
162
  }
165
163
 
166
164
  /**
@@ -174,7 +172,6 @@ function startWeb(
174
172
  devices: readonly DeviceMount[],
175
173
  mount?: WebSocketMount<SyncWs>,
176
174
  ): ServerHandle {
177
- warnIfUnauthenticatable(options.routes);
178
175
  const binding = options.http ?? DEV_BINDING;
179
176
  const hops = trustedHopsFromEnv(options.env);
180
177
  const store = rateLimitStoreFor(options);
@@ -270,6 +267,15 @@ export async function startRoles(options: StartRolesOptions): Promise<RunningRol
270
267
  (options.http ?? DEV_BINDING).dev,
271
268
  );
272
269
  assertOneJobDriver(options.runtime);
270
+ // Once per process, and only where a role in it can act on the line (`serve-boot-warnings.ts`):
271
+ // `rateLimitStoreFor` is asked twice in a web boot, and a scheduler spends no limit at all.
272
+ if (bootWarningConcernsAny('auth-unconfigured', selected)) {
273
+ warnIfUnauthenticatable(options.routes);
274
+ }
275
+ const supplied = options.overrides?.rateLimitStore;
276
+ if (supplied !== undefined && bootWarningConcernsAny('rate-limit-process-scoped', selected)) {
277
+ warnIfProcessScoped(supplied);
278
+ }
273
279
  // Roles bind sockets in order, so a role that fails to start has to release the ones before it.
274
280
  // Without this a failed `sync` leaves the web server bound and unreachable by any caller.
275
281
  const started: (() => Promise<void>)[] = [];
@@ -6,7 +6,9 @@
6
6
  import { postgresAuthLimiter, postgresTotpReplayGuard } from '@ultimat3/auth';
7
7
  import type { PurgeDriver } from '@ultimat3/cache';
8
8
  import { isNoopPurgeDriver, selectPurgeDriver } from '@ultimat3/cache';
9
+ import type { Clock } from '@ultimat3/core';
9
10
  import {
11
+ finiteCount,
10
12
  type RealtimeConfig,
11
13
  type Role,
12
14
  registerReadinessCheck,
@@ -158,35 +160,48 @@ export function cdnLabel(runtime: RunningServices): string {
158
160
  }
159
161
 
160
162
  /**
161
- * A readiness check over a dependency that can only be asked asynchronously.
162
- *
163
- * `ReadinessCheck` is synchronous and that is the mechanism, not a limitation: a probe that awaits
164
- * a network call takes as long as the dependency does, so a slow database makes `/readyz` miss its
165
- * `timeoutSeconds`, the kubelet reads that as unready, and capacity is pulled from an already
166
- * struggling system — the outage the probe existed to prevent, caused by the probe.
167
- *
168
- * So the read answers the PREVIOUS probe and schedules the next, which is the standard cached
169
- * health shape: staleness is one poll period, and the poll period is the operator's own
170
- * `periodSeconds`. Deliberately not a `setInterval`: a timer would probe a process nobody is
171
- * asking about, and in `x dev` every probe is a statement — one span, one trace id — so a
172
- * one-per-second heartbeat would evict every real request from `/_x/timeline` inside a minute.
163
+ * The fewest milliseconds between two pings. Production saw `select $1` as the most-called
164
+ * statement — 38,195 in 26 h — because every read once the last ping settled started another. One
165
+ * second is below any kubelet `periodSeconds`, so the answer a probe reads is never staler than
166
+ * the probe period it already accepted.
167
+ */
168
+ export const READINESS_PROBE_MIN_MS = 1_000;
169
+
170
+ /**
171
+ * `ReadinessCheck` is synchronous and that is the mechanism: a probe that awaits a network call
172
+ * takes as long as the dependency does, so a slow database makes `/readyz` miss its
173
+ * `timeoutSeconds`, and capacity is pulled from an already struggling system. Deliberately not a
174
+ * `setInterval`: a timer probes a process nobody is asking about, and in `x dev` every probe is a
175
+ * statement on `/_x/timeline`.
173
176
  *
174
- * It starts `true` because it is already proven: `startQueue` pinged this pool before this line
175
- * ran, and a boot that could not would have thrown instead of reaching here.
177
+ * It starts `true`, with the interval already running, because it is proven: `startQueue` pinged
178
+ * this pool before this line ran, and a boot that could not would have thrown instead.
176
179
  */
177
- function probedReadinessCheck(name: string, probe: () => Promise<unknown>): () => void {
180
+ export function probedReadinessCheck(
181
+ name: string,
182
+ probe: () => Promise<unknown>,
183
+ options: { readonly clock?: Clock; readonly minIntervalMs?: number } = {},
184
+ ): () => void {
185
+ const clock = options.clock ?? systemClock;
186
+ const minIntervalMs = finiteCount(
187
+ 'probedReadinessCheck',
188
+ 'minIntervalMs',
189
+ options.minIntervalMs ?? READINESS_PROBE_MIN_MS,
190
+ );
178
191
  let live = true;
179
192
  let inFlight = false;
193
+ let startedAt = clock.monotonic();
180
194
  const refresh = (): void => {
181
- if (inFlight) return;
195
+ if (inFlight || clock.monotonic() - startedAt < minIntervalMs) return;
182
196
  inFlight = true;
197
+ startedAt = clock.monotonic();
183
198
  void probe()
184
199
  .then(
185
200
  () => {
186
201
  live = true;
187
202
  },
188
- // Every rejection, including the coded `X_DB_UNAVAILABLE` a closed pool answers with. A
189
- // check that threw would be reported as failing anyway; catching it here keeps the reason
203
+ // Every rejection, including the coded `X_DB_UNAVAILABLE` a closed pool answers with: a
204
+ // check that threw is reported as failing anyway, and catching it here keeps the reason
190
205
  // out of the endpoint's own path, where nothing could report it.
191
206
  () => {
192
207
  live = false;
@@ -380,7 +395,8 @@ export async function startServices(
380
395
  // `packages/http/src/server.ts` calls that BEFORE `Bun.serve`, while `role-start.ts` calls it
381
396
  // before `sync`, `worker` and `scheduler` start. The chart's `readinessProbe` and the container
382
397
  // healthcheck both route on it, so a replica whose pool was gone kept taking traffic.
383
- started.push(probedReadinessCheck('database', () => db.ping()));
398
+ // At most one ping per `READINESS_PROBE_MIN_MS` on this boot's clock, however many pollers ask.
399
+ started.push(probedReadinessCheck('database', () => db.ping(), { clock }));
384
400
  // Dialled here rather than at selection: the socket is a resource the unwind below has to
385
401
  // release. AWAITED only by a process that cannot work without the bus — a `sync` node, a
386
402
  // replicator — where an unreachable one must fail the boot, not the first change nobody
@@ -0,0 +1,30 @@
1
+ // The container boot's timeline: one `boot.phase {role, name, ms}` line as each phase ends. A boot
2
+ // spent seconds between two unrelated log lines — a worker importing every page for an unstamped
3
+ // build id — and nothing said which step it was (plan 101, 14 U12).
4
+
5
+ import type { Clock, Role } from '@ultimat3/core';
6
+ import { logger, systemClock } from '@ultimat3/core';
7
+
8
+ /** The phases a serving boot runs, in order. A name not here is not a phase. */
9
+ export type BootPhase = 'services' | 'app-load' | 'app-checks' | 'build-id' | 'web' | 'roles';
10
+
11
+ export interface BootTimeline {
12
+ /** Ends `name`: logs its milliseconds since the previous phase ended, or since the start. */
13
+ phase(name: BootPhase): void;
14
+ /** Whole milliseconds since the timeline started. */
15
+ totalMs(): number;
16
+ }
17
+
18
+ /** Starts the clock. The process's own clock by default; a test hands a frozen one. */
19
+ export function bootTimeline(role: Role, clock: Clock = systemClock): BootTimeline {
20
+ const started = clock.monotonic();
21
+ let last = started;
22
+ return {
23
+ phase(name) {
24
+ const now = clock.monotonic();
25
+ logger.info('boot.phase', { role, name, ms: Math.round(now - last) });
26
+ last = now;
27
+ },
28
+ totalMs: () => Math.round(clock.monotonic() - started),
29
+ };
30
+ }
@@ -0,0 +1,62 @@
1
+ // The roles each boot warning concerns, in one table, and the step that runs the post-load ones for
2
+ // the booting role alone. Production logged the same warnings in all five roles on every boot — a
3
+ // warning a role cannot act on is noise that buries the one it can.
4
+
5
+ import type { Role } from '@ultimat3/core';
6
+
7
+ /** Every warning a container boot can say. A new one does not compile until it names its roles. */
8
+ export type BootWarning =
9
+ | 'idempotency-process-scoped'
10
+ | 'mfa-secret-unsealed'
11
+ | 'build-id-unstamped'
12
+ | 'auth-unconfigured'
13
+ | 'rate-limit-process-scoped';
14
+
15
+ const DECLARED: Readonly<Record<BootWarning, readonly Role[]>> = {
16
+ // An `Idempotency-Key` arrives on an HTTP request or an MCP call, both the web role's: a job
17
+ // invokes its action on the `job` surface with no key, and `sync` relays frames, not writes.
18
+ 'idempotency-process-scoped': ['web'],
19
+ // The second factor is asked for where a user signs in.
20
+ 'mfa-secret-unsealed': ['web'],
21
+ // Only a background load leaves pages out, so only it pays to import them for the build id.
22
+ 'build-id-unstamped': ['worker', 'scheduler'],
23
+ // Guarded routes are served by the web role alone; every other role is handed none.
24
+ 'auth-unconfigured': ['web'],
25
+ // A declared `rateLimit:` is spent wherever a primitive runs: HTTP and MCP on web, `.job()` on a
26
+ // worker, a live query's reads on sync. The scheduler only enqueues; the replicator invokes none.
27
+ 'rate-limit-process-scoped': ['web', 'worker', 'sync'],
28
+ };
29
+
30
+ /** A `Map`, so a lookup is an own-key read — never a member of `Object.prototype`. */
31
+ export const BOOT_WARNINGS: ReadonlyMap<BootWarning, readonly Role[]> = new Map(
32
+ Object.entries(DECLARED) as [BootWarning, readonly Role[]][],
33
+ );
34
+
35
+ /** Whether `warning` is one `role` can act on. An unknown warning concerns nobody. */
36
+ export const bootWarningConcerns = (warning: BootWarning, role: Role): boolean =>
37
+ BOOT_WARNINGS.get(warning)?.includes(role) ?? false;
38
+
39
+ /** Whether any of `roles` — `x dev` runs several in one process — can act on `warning`. */
40
+ export const bootWarningConcernsAny = (warning: BootWarning, roles: readonly Role[]): boolean =>
41
+ roles.some((role) => bootWarningConcerns(warning, role));
42
+
43
+ /** The post-load probes: each logs its own line and answers whether it had anything to say. */
44
+ export interface BootWarningProbes {
45
+ readonly idempotency: () => boolean;
46
+ readonly mfa: () => Promise<number>;
47
+ }
48
+
49
+ /** Runs the probes `role` is concerned by, in table order; answers the warnings actually said. */
50
+ export async function warnAtBoot(
51
+ role: Role,
52
+ probes: BootWarningProbes,
53
+ ): Promise<readonly BootWarning[]> {
54
+ const said: BootWarning[] = [];
55
+ if (bootWarningConcerns('idempotency-process-scoped', role) && probes.idempotency()) {
56
+ said.push('idempotency-process-scoped');
57
+ }
58
+ if (bootWarningConcerns('mfa-secret-unsealed', role) && (await probes.mfa()) > 0) {
59
+ said.push('mfa-secret-unsealed');
60
+ }
61
+ return said;
62
+ }
package/src/serve-boot.ts CHANGED
@@ -12,7 +12,7 @@ import { armFailureCapture } from './failure-capture-boot';
12
12
  import type { MetricsEndpoint } from './metrics-endpoint';
13
13
  import { startOtlpExport } from './otlp-export';
14
14
  import type { Finding } from './output';
15
- import { loadAppForRole, roleLoadFor } from './role-load';
15
+ import { loadAppForRole } from './role-load';
16
16
  import { startRoles } from './role-start';
17
17
  import { armRowSecurity, rowSecurityDeclared } from './row-security-boot';
18
18
  import { resolveServices } from './runtime-bindings';
@@ -22,6 +22,9 @@ import { warnUnsealedMfaSecrets } from './runtime-mfa-warning';
22
22
  import { replicaOverrides } from './runtime-replica';
23
23
  import type { RunningServices } from './runtime-services';
24
24
  import { releaseOrThrow, startServices } from './runtime-services';
25
+ import type { BootTimeline } from './serve-boot-phases';
26
+ import { bootTimeline } from './serve-boot-phases';
27
+ import { bootWarningConcerns, warnAtBoot } from './serve-boot-warnings';
25
28
  import { loadDrainConfig, loadHealthConfig } from './serve-drain';
26
29
  import { configureReporting, containerBinding, metricsPortFor, portFromEnv } from './serve-env';
27
30
  import { adoptPrebuiltStyles, reportBootBuilds, watchBootBuilds } from './serve-prebuilt';
@@ -37,7 +40,7 @@ import type { ServedApp, ServeOptions } from './serve-types';
37
40
  async function buildIdFor(options: ServeOptions, role: Role): Promise<string> {
38
41
  const stamped = options.env['BUILD_ID'];
39
42
  if (stamped !== undefined && stamped.length > 0) return stamped;
40
- if (roleLoadFor(role) === 'background') {
43
+ if (bootWarningConcerns('build-id-unstamped', role)) {
41
44
  logger.warn('ultimate build id unstamped', {
42
45
  role,
43
46
  cause:
@@ -89,6 +92,8 @@ export async function bootServing(boot: {
89
92
  readonly metrics: MetricsEndpoint;
90
93
  }): Promise<ServedApp> {
91
94
  const { options } = boot;
95
+ // One `boot.phase` line as each step ends, so a slow boot names its slow step (U12).
96
+ const timeline = bootTimeline(boot.role, options.runtime?.clock);
92
97
  const services = resolveServices(options.root, options.env);
93
98
  // A serving role on a real database runs no DDL: `ROLE=migrate` applied this build's framework
94
99
  // tables first, and this boot only verifies the stamp it left (`framework-schema-apply.ts`).
@@ -97,7 +102,8 @@ export async function bootServing(boot: {
97
102
  // The role decides whether this boot waits for the bus: only `sync` and the replicator do.
98
103
  const runtime = await startServices(services, options.env, options.runtime, schema, [boot.role]);
99
104
  boot.acquired.push(() => runtime.stop());
100
- return bootRoles({ ...boot, runtime });
105
+ timeline.phase('services');
106
+ return bootRoles({ ...boot, runtime, timeline });
101
107
  }
102
108
 
103
109
  /**
@@ -131,8 +137,9 @@ async function bootRoles(boot: {
131
137
  readonly acquired: (() => void | Promise<void>)[];
132
138
  /** The scrape listener `serveApp` opened before any of this work; `startRoles` adopts it. */
133
139
  readonly metrics: MetricsEndpoint;
140
+ readonly timeline: BootTimeline;
134
141
  }): Promise<ServedApp> {
135
- const { options, role, runtime, acquired, metrics } = boot;
142
+ const { options, role, runtime, acquired, metrics, timeline } = boot;
136
143
  // Before the app's modules, because importing one may register a `close` hook, and that phase
137
144
  // runs last-registered first: the flush has to be the hook registered earliest, or a teardown's
138
145
  // spans are recorded into an exporter already shut down. `OTEL_EXPORTER_OTLP_ENDPOINT` is in the
@@ -141,7 +148,11 @@ async function bootRoles(boot: {
141
148
  // different lifetime — so this is the production boot's alone (axiom 6).
142
149
  // At the FRONT of the unwind list, so the stop and a failed boot's rollback alike release it
143
150
  // last: the drain's own spans and the final counter snapshot still have somewhere to go.
144
- acquired.unshift(startOtlpExport(options.env));
151
+ // The config first, for `database.slowStatementMs`: `app.config.ts` declares, it registers no hook.
152
+ const appConfig = await loadAppConfig(options.root);
153
+ acquired.unshift(
154
+ startOtlpExport(options.env, { slowStatementMs: appConfig?.database.slowStatementMs }),
155
+ );
145
156
  // The image's compiled stylesheets, before the first page is imported — importing one IS
146
157
  // compiling its sheet — and the count of what this boot compiles anyway.
147
158
  adoptPrebuiltStyles(options.root);
@@ -158,17 +169,17 @@ async function bootRoles(boot: {
158
169
  logger.error('ultimate app module failed to load', { role, ...finding });
159
170
  }
160
171
  refuseHalfLoadedApp(role, loaded.findings);
172
+ timeline.phase('app-load');
161
173
  // After the app's modules and before any role serves: a role Postgres exempts from row security is
162
174
  // refused here (`X_DB_ROW_SECURITY_BYPASSED`), never discovered on another tenant's first read.
163
175
  // PGlite's one session is a superuser: there the boot serves as `x_app` instead of refusing.
164
176
  const embedded = runtime.services.db.mode === 'embedded';
165
- const appConfig = await loadAppConfig(options.root);
166
177
  acquired.push(await armRowSecurity(rowSecurityDeclared(appConfig), { embedded }));
167
178
  // `failureCapture.enabled`: a 5xx keeps a replayable bundle for `x repro` (off by default).
168
179
  acquired.push(armFailureCapture(appConfig, { store: runtime.failureStore }));
169
- // After the app's modules: an app swaps the store at import time, after `startServices`.
170
- warnIfIdempotencyProcessScoped();
180
+ timeline.phase('app-checks');
171
181
  const buildId = await buildIdFor(options, role);
182
+ timeline.phase('build-id');
172
183
  // Before the first socket opens: everything above this line fails loudly into the container's
173
184
  // own logs, everything below it is a served request, a claimed job or a routed frame.
174
185
  // Released with the boot, so a second boot in this process starts from the app's reporter alone.
@@ -181,9 +192,16 @@ async function bootRoles(boot: {
181
192
  role === 'web'
182
193
  ? await (await import('./serve-web')).webSurface(options, runtime, buildId)
183
194
  : undefined;
184
- if (web !== undefined) acquired.push(web.release);
185
- // The web role alone — it is where a second factor is asked for — and once per pod boot.
186
- if (role === 'web') await warnUnsealedMfaSecrets(runtime.db);
195
+ if (web !== undefined) {
196
+ acquired.push(web.release);
197
+ timeline.phase('web');
198
+ }
199
+ // After the app's modules — an app swaps the idempotency store at import time, after
200
+ // `startServices` — and each only in the roles its table row names (`serve-boot-warnings.ts`).
201
+ await warnAtBoot(role, {
202
+ idempotency: () => warnIfIdempotencyProcessScoped(),
203
+ mfa: () => warnUnsealedMfaSecrets(runtime.db),
204
+ });
187
205
  // Islands and stylesheets are the image build's to make (`x build --target prebuilt`). A role
188
206
  // that made either here served correctly and paid for it — seconds of CPU and a compiler's
189
207
  // memory, on every start of every replica — so it says so once, with the Dockerfile line.
@@ -230,6 +248,7 @@ async function bootRoles(boot: {
230
248
  ...(replicaOverride === undefined ? {} : { overrides: replicaOverride }),
231
249
  });
232
250
  acquired.push(() => running.stop());
251
+ timeline.phase('roles');
233
252
  return {
234
253
  kind: 'served',
235
254
  role,
@@ -0,0 +1,90 @@
1
+ // `x g cron-job` — a job and the task that fires it, from one `cronJob()` declaration: a factory
2
+ // over `job()` and `task()`, never a ninth primitive. The handle IS the job and `.schedule` its
3
+ // task, so the scheduler's last firing and the queue's rows follow the one pinned name.
4
+
5
+ import type { FeatureTarget } from './entity';
6
+ import type { GeneratedFile, NameSet } from './naming';
7
+ import { names } from './naming';
8
+
9
+ const source = (
10
+ name: NameSet,
11
+ ): string => `// ${name.camel}: a job and the task that fires it, from one declaration. \`cronJob()\` is a factory
12
+ // over job() and task(), so \`${name.camel}.schedule\` is a task like any other, named
13
+ // \`${name.kebab}.schedule\`. List this module in apps/web/api/index.ts's \`jobs:\` to register it.
14
+
15
+ import { cronJob } from '@ultimat3/jobs';
16
+
17
+ export const ${name.camel} = cronJob({
18
+ // Pinned: the scheduler keys \`.schedule\`'s last firing by this name, the queue its rows.
19
+ name: '${name.kebab}',
20
+ cron: '0 3 * * *',
21
+ // REQUIRED IANA zone: "server time" is not a timezone, and an unzoned cron drifts at every DST
22
+ // switch. Per-member local times are a fan-out from here, one enqueue per zone.
23
+ tz: 'UTC',
24
+ // A schedule has no request behind it, so there is no org to inherit. \`'none'\` STRIPS the org,
25
+ // so a tenant-scoped read added below fails closed (X_TENANCY_ACTOR_ORG_REQUIRED) instead of
26
+ // reading whichever org a worker last held.
27
+ tenant: 'none',
28
+ retry: { attempts: 3, backoff: 'exponential' },
29
+ async run({ step, ctx }) {
30
+ // One durable step per unit of work: a retry replays the finished ones from storage, so put
31
+ // each write in its own \`step.run\` under a stable name.
32
+ const ranAt = await step.run('run', () => ctx.now().toISOString());
33
+ return { ranAt };
34
+ },
35
+ });
36
+ `;
37
+
38
+ const jobSuite = (
39
+ name: NameSet,
40
+ ): string => `// ${name.camel}'s durable identity: a job, its schedule in an explicit zone, and one live run per
41
+ // name. The body is the unit suite's, next door.
42
+
43
+ import { memoryJobDriver } from '@ultimat3/jobs';
44
+ import { beforeAll, expect, jobTest, swapAdapter } from '@ultimat3/testing';
45
+ import { ${name.camel} } from './${name.kebab}';
46
+
47
+ // The queue is a process-global adapter port, so it is swapped for this file and put back after.
48
+ beforeAll(() => swapAdapter('jobs', memoryJobDriver()));
49
+
50
+ jobTest('${name.camel} is a job, fired by its own schedule in an explicit zone', () => {
51
+ expect(${name.camel}.kind).toBe('job');
52
+ expect(${name.camel}.schedule.kind).toBe('task');
53
+ expect(${name.camel}.schedule.name).toBe('${name.kebab}.schedule');
54
+ expect(${name.camel}.schedule.tz).toBe('UTC');
55
+ expect(${name.camel}.retry.attempts).toBeGreaterThan(1);
56
+ });
57
+
58
+ jobTest('${name.camel} enqueues once, and dedupes a second run while one is live', async () => {
59
+ const first = await ${name.camel}.enqueue({});
60
+ expect(first.deduped).toBe(false);
61
+ const again = await ${name.camel}.enqueue({});
62
+ expect(again.deduped).toBe(true);
63
+ });
64
+ `;
65
+
66
+ const unitSuite = (
67
+ name: NameSet,
68
+ ): string => `// ${name.camel}'s BODY, run by a worker in this process against the in-memory queue: one
69
+ // occurrence completes, and its one step runs once.
70
+
71
+ import { expect, unitTest } from '@ultimat3/testing';
72
+ import { ${name.camel} } from './${name.kebab}';
73
+
74
+ unitTest('one occurrence runs its step once and completes', async ({ runJobs }) => {
75
+ const trace = await runJobs(${name.camel}, {});
76
+ expect(trace.executions.map((run) => run.outcome)).toEqual(['completed']);
77
+ expect(trace.steps.run?.executions).toBe(1);
78
+ });
79
+ `;
80
+
81
+ /** The job with its schedule, its job-suite test and its unit test, in the feature's `jobs/`. */
82
+ export function cronJobFiles(rawName: string, target: FeatureTarget): readonly GeneratedFile[] {
83
+ const name = names(rawName);
84
+ const dir = `${target.surfaceDir}/${target.feature}/jobs`;
85
+ return [
86
+ { path: `${dir}/${name.kebab}.ts`, contents: source(name) },
87
+ { path: `${dir}/${name.kebab}.job.test.ts`, contents: jobSuite(name) },
88
+ { path: `${dir}/${name.kebab}.test.ts`, contents: unitSuite(name) },
89
+ ];
90
+ }