@ultimat3/cli 31.48.0 → 31.49.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 (260) hide show
  1. package/CLAUDE.md +30 -23
  2. package/README.md +96 -4
  3. package/package.json +29 -29
  4. package/src/api-registration.ts +28 -14
  5. package/src/app-load.ts +6 -1
  6. package/src/app-root.ts +7 -1
  7. package/src/clean-services.ts +142 -0
  8. package/src/cmd-auth.ts +3 -0
  9. package/src/cmd-clean-spec.ts +10 -3
  10. package/src/cmd-clean.ts +23 -9
  11. package/src/cmd-db-backfill.ts +6 -0
  12. package/src/cmd-db-branch.ts +10 -4
  13. package/src/cmd-db-recount.ts +5 -12
  14. package/src/cmd-db-rollback.ts +77 -0
  15. package/src/cmd-db-spec.ts +18 -2
  16. package/src/cmd-db-status.ts +5 -10
  17. package/src/cmd-db.ts +105 -33
  18. package/src/cmd-deploy-verify.ts +14 -6
  19. package/src/cmd-docs-topic.ts +94 -0
  20. package/src/cmd-docs.ts +15 -1
  21. package/src/cmd-doctor.ts +109 -41
  22. package/src/cmd-drill.ts +80 -18
  23. package/src/cmd-env.ts +30 -8
  24. package/src/cmd-errors-app.ts +63 -0
  25. package/src/cmd-errors.ts +50 -14
  26. package/src/cmd-generate.ts +17 -4
  27. package/src/cmd-heavy-spec.ts +9 -1
  28. package/src/cmd-heavy.ts +111 -27
  29. package/src/cmd-jobs.ts +27 -1
  30. package/src/cmd-merge-driver-spec.ts +12 -0
  31. package/src/cmd-merge-driver.ts +95 -0
  32. package/src/cmd-new.ts +23 -3
  33. package/src/cmd-policy-spec.ts +9 -1
  34. package/src/cmd-policy.ts +72 -17
  35. package/src/cmd-stop.ts +18 -4
  36. package/src/cmd-tasks-run.ts +87 -0
  37. package/src/cmd-tasks-spec.ts +10 -3
  38. package/src/cmd-tasks.ts +8 -5
  39. package/src/cmd-test.ts +2 -1
  40. package/src/cmd-upgrade-spec.ts +8 -1
  41. package/src/cmd-upgrade.ts +15 -1
  42. package/src/cmd-verify.ts +9 -41
  43. package/src/codemods/agents-doc-row.ts +73 -0
  44. package/src/codemods/define-error-leaf.ts +37 -12
  45. package/src/codemods/docs-many-agents.ts +11 -15
  46. package/src/codemods/docs-worker-commands.ts +26 -0
  47. package/src/codemods/index.ts +4 -0
  48. package/src/codemods/merge-drivers.ts +66 -0
  49. package/src/command.ts +3 -0
  50. package/src/db-applied-edits.ts +117 -0
  51. package/src/db-dev-wire.ts +18 -0
  52. package/src/db-diagnostics.ts +5 -10
  53. package/src/db-generate.ts +82 -7
  54. package/src/db-migrate-pass.ts +51 -0
  55. package/src/db-migrate-through-dev.ts +209 -0
  56. package/src/db-rollback-consent.ts +128 -0
  57. package/src/db-rollback-pass.ts +76 -0
  58. package/src/db-seed-generate.ts +5 -1
  59. package/src/db-seed.ts +7 -1
  60. package/src/deploy-verify-findings.ts +3 -0
  61. package/src/deploy-verify-grade.ts +3 -0
  62. package/src/deploy-verify-processes.ts +32 -0
  63. package/src/dev-boot.ts +3 -0
  64. package/src/dev-db-migrate.ts +155 -0
  65. package/src/dev-db-rollback.ts +33 -0
  66. package/src/dev-db-settled.ts +22 -0
  67. package/src/dev-lock-errors.ts +78 -0
  68. package/src/dev-lock-holder-dir.ts +64 -0
  69. package/src/dev-lock-live.ts +44 -0
  70. package/src/dev-lock.ts +59 -84
  71. package/src/dev-policy.ts +11 -8
  72. package/src/dev-rebuild-schema.ts +116 -13
  73. package/src/dev-rebuild.ts +13 -4
  74. package/src/dev-route-table.ts +7 -0
  75. package/src/dispatch.ts +21 -1
  76. package/src/doctor-api-listing.ts +114 -0
  77. package/src/doctor-guarded.ts +41 -0
  78. package/src/doctor-port.ts +90 -17
  79. package/src/doctor-probe.ts +36 -5
  80. package/src/doctor-processes-probe.ts +127 -0
  81. package/src/doctor-processes.ts +136 -0
  82. package/src/doctor-warnings.ts +17 -0
  83. package/src/error-codes-agents.ts +35 -0
  84. package/src/error-codes-processes.ts +30 -0
  85. package/src/error-codes-tooling.ts +2 -0
  86. package/src/error-codes.ts +12 -13
  87. package/src/errors-suite.ts +27 -0
  88. package/src/errors.ts +18 -22
  89. package/src/exercise-registration.ts +4 -3
  90. package/src/framework-env.ts +7 -3
  91. package/src/generate-files.ts +1 -0
  92. package/src/generate-grant-findings.ts +7 -5
  93. package/src/generate-grants.ts +9 -8
  94. package/src/generate-kinds.ts +30 -6
  95. package/src/generate-roles-file.ts +30 -0
  96. package/src/generate-slice-policy.ts +3 -3
  97. package/src/guards.ts +2 -2
  98. package/src/heavy-env.ts +2 -0
  99. package/src/heavy-errors.ts +18 -0
  100. package/src/heavy-holders.ts +78 -0
  101. package/src/heavy-ledger.ts +56 -14
  102. package/src/heavy-pressure.ts +104 -0
  103. package/src/heavy.ts +31 -13
  104. package/src/i18n-registration.ts +22 -2
  105. package/src/island-harness.ts +2 -2
  106. package/src/job-budget.ts +4 -2
  107. package/src/job-registration.ts +64 -8
  108. package/src/jobs-queue-known.ts +43 -0
  109. package/src/mcp-errors-agents.ts +20 -0
  110. package/src/mcp-errors-doctor.ts +27 -0
  111. package/src/mcp-errors-processes.ts +23 -0
  112. package/src/mcp-errors.ts +15 -29
  113. package/src/mcp-host.ts +2 -2
  114. package/src/merge-driver-catalog.ts +58 -0
  115. package/src/merge-driver-config.ts +43 -0
  116. package/src/merge-driver-lines.ts +140 -0
  117. package/src/merge-state.ts +105 -0
  118. package/src/messages-db.ts +22 -1
  119. package/src/messages-processes.ts +13 -0
  120. package/src/messages-upgrade.ts +6 -0
  121. package/src/messages.ts +54 -4
  122. package/src/output-findings.ts +48 -21
  123. package/src/parse.ts +37 -6
  124. package/src/policy-facts.ts +38 -21
  125. package/src/policy-row.ts +99 -0
  126. package/src/port-pair-free.ts +28 -0
  127. package/src/registry-lines.ts +110 -0
  128. package/src/registry.ts +2 -0
  129. package/src/retain-sweep.ts +1 -1
  130. package/src/role-replicator.ts +4 -1
  131. package/src/role-select.ts +86 -0
  132. package/src/role-start.ts +13 -55
  133. package/src/role-sync.ts +10 -5
  134. package/src/runtime-cache-frame.ts +46 -0
  135. package/src/runtime-cache-ttl.ts +23 -0
  136. package/src/runtime-cache.ts +33 -16
  137. package/src/runtime-database-ssl.ts +84 -0
  138. package/src/runtime-idempotency-scope.ts +16 -2
  139. package/src/runtime-jobs-share.ts +52 -0
  140. package/src/runtime-jobs.ts +43 -12
  141. package/src/runtime-queue.ts +18 -3
  142. package/src/runtime-services.ts +8 -1
  143. package/src/schema-drift.ts +19 -2
  144. package/src/schema-dump-drift.ts +4 -1
  145. package/src/serve-boot-probe.ts +30 -2
  146. package/src/serve-boot.ts +11 -1
  147. package/src/serve-env.ts +39 -3
  148. package/src/serve.ts +61 -10
  149. package/src/stop-run-start.ts +12 -0
  150. package/src/supervise-boot.ts +61 -0
  151. package/src/supervise-cgroup.ts +84 -0
  152. package/src/supervise-child.ts +206 -0
  153. package/src/supervise-count.ts +244 -0
  154. package/src/supervise-errors.ts +83 -0
  155. package/src/supervise-facts.ts +40 -0
  156. package/src/supervise-messages.ts +84 -0
  157. package/src/supervise-policy.ts +46 -0
  158. package/src/supervise-pool.ts +10 -0
  159. package/src/supervise-probe.ts +158 -0
  160. package/src/supervise-run.ts +54 -0
  161. package/src/supervise.ts +383 -0
  162. package/src/templates/generate-purge.ts +6 -6
  163. package/src/templates/guard-animated-layout-property.ts +2 -2
  164. package/src/templates/guard-bare-error.ts +1 -1
  165. package/src/templates/guard-error-declared.ts +2 -2
  166. package/src/templates/guard-focus-visible.ts +1 -1
  167. package/src/templates/guard-image-dimensions.ts +2 -2
  168. package/src/templates/guard-island-mount-clears.ts +1 -1
  169. package/src/templates/guard-native-confirm.ts +1 -1
  170. package/src/templates/guard-raw-breakpoint.ts +2 -2
  171. package/src/templates/guard-raw-colour.ts +2 -2
  172. package/src/templates/guard-raw-fetch.ts +1 -1
  173. package/src/templates/guard-raw-interval.ts +1 -1
  174. package/src/templates/guard-raw-length.ts +3 -3
  175. package/src/templates/guard-raw-motion.ts +1 -1
  176. package/src/templates/guard-raw-shadow.ts +1 -1
  177. package/src/templates/guard-raw-z-index.ts +1 -1
  178. package/src/templates/guard-released-forms.ts +54 -8
  179. package/src/templates/guard-repo-await-in-loop.ts +1 -1
  180. package/src/templates/guard-repo-raw-sql.ts +4 -4
  181. package/src/templates/guard-repo-unbounded.ts +1 -1
  182. package/src/templates/guard-runtime-pin.ts +1 -1
  183. package/src/templates/guard-semantic-interactive.ts +2 -2
  184. package/src/templates/guard-unbounded-fanout.ts +1 -1
  185. package/src/templates/guard-undeclared-custom-property.ts +3 -3
  186. package/src/templates/guard-undefined-style-class.ts +3 -3
  187. package/src/templates/guard-unzoned-date.ts +3 -3
  188. package/src/templates/query-slice.ts +82 -0
  189. package/src/templates/query.ts +76 -30
  190. package/src/templates/resource-page.ts +3 -2
  191. package/src/templates/scaffold-bin.ts +2 -0
  192. package/src/templates/scaffold-claude-commands.ts +6 -0
  193. package/src/templates/scaffold-claude.ts +4 -4
  194. package/src/templates/scaffold-container-compose.ts +47 -7
  195. package/src/templates/scaffold-docs.ts +7 -3
  196. package/src/templates/scaffold-gitattributes.ts +18 -1
  197. package/src/templates/scaffold-helm-templates.ts +9 -0
  198. package/src/templates/scaffold-repo.ts +4 -1
  199. package/src/templates/scaffold-test-services.ts +33 -11
  200. package/src/templates/shapes/offline.ts +0 -7
  201. package/src/templates/shapes/realtime.ts +2 -6
  202. package/src/templates/sign-in-action-tests.ts +6 -4
  203. package/src/templates/sign-in-challenge.ts +62 -0
  204. package/src/templates/sign-in-oidc-mfa.ts +31 -0
  205. package/src/templates/sign-in-oidc.ts +11 -3
  206. package/src/templates/sign-in-password.ts +18 -56
  207. package/src/test-shards.ts +114 -34
  208. package/src/test-verdict.ts +79 -0
  209. package/src/test-workers.ts +15 -0
  210. package/src/upgrade-gate-codemods.ts +5 -3
  211. package/src/upgrade-gate.ts +19 -1
  212. package/src/upgrade-merge-drivers.ts +25 -0
  213. package/src/upgrade-report.ts +18 -4
  214. package/src/upgrade-scope.ts +62 -0
  215. package/src/verify-checks.ts +2 -8
  216. package/src/verify-coverage-run.ts +4 -1
  217. package/src/verify-live.ts +38 -14
  218. package/src/verify-only.ts +67 -0
  219. package/src/verify-progress.ts +7 -3
  220. package/src/verify-run.ts +20 -2
  221. package/src/verify-services-stack.ts +165 -0
  222. package/src/verify-services.ts +84 -2
  223. package/src/verify-test-run.ts +6 -7
  224. package/src/verify-tests.ts +8 -2
  225. package/src/verify-typecheck.ts +25 -2
  226. package/wiki/Actions.md +2 -1
  227. package/wiki/Admin-Dashboard.md +2 -2
  228. package/wiki/Agents.md +5 -5
  229. package/wiki/Auth.md +15 -5
  230. package/wiki/Bare-VM.md +1 -1
  231. package/wiki/CI-Parallel-Gate.md +2 -1
  232. package/wiki/CLI-Reference.md +107 -40
  233. package/wiki/Caching-And-Invalidation.md +1 -1
  234. package/wiki/Client-Navigation.md +1 -1
  235. package/wiki/Configuration.md +10 -9
  236. package/wiki/Deployment.md +44 -4
  237. package/wiki/Entities-And-Migrations.md +5 -1
  238. package/wiki/FAQ.md +1 -1
  239. package/wiki/Getting-Started.md +2 -2
  240. package/wiki/Home.md +1 -1
  241. package/wiki/I18n.md +5 -3
  242. package/wiki/Installation.md +12 -11
  243. package/wiki/Jobs-And-Workflows.md +24 -4
  244. package/wiki/Known-Gaps.md +1 -1
  245. package/wiki/MCP-And-AI.md +8 -5
  246. package/wiki/Many-Agents.md +69 -2
  247. package/wiki/Migrations-And-Backfills.md +18 -0
  248. package/wiki/Notify.md +1 -1
  249. package/wiki/Observability.md +13 -0
  250. package/wiki/Queries-And-Live-Queries.md +2 -2
  251. package/wiki/Realtime.md +10 -1
  252. package/wiki/Routes-And-Render-Modes.md +1 -1
  253. package/wiki/Scheduled-Tasks.md +4 -1
  254. package/wiki/Testing.md +7 -4
  255. package/wiki/Timezones-And-Dates.md +5 -1
  256. package/wiki/Troubleshooting.md +1 -0
  257. package/wiki/Tutorial-01-First-App.md +3 -3
  258. package/wiki/Tutorial-02-First-Feature.md +1 -1
  259. package/wiki/Tutorial-03-Auth-And-Admin.md +7 -6
  260. package/wiki/Upgrading.md +37 -0
@@ -0,0 +1,46 @@
1
+ // When a crashed child comes back, and when the supervisor stops trying. Pure: the loop in
2
+ // `supervise.ts` hands in the clock's reading and the child's uptime, and keeps what comes back.
3
+
4
+ import { backoffDelay, DRAIN_TIMEOUT_EXIT_CODE } from '@ultimat3/core';
5
+
6
+ /** The first restart waits a second, then 2, 4, 8… */
7
+ export const BACKOFF_BASE_MS = 1_000;
8
+ export const BACKOFF_CAP_MS = 30_000;
9
+ /** A child up this long before it crashed was healthy: its backoff starts over. */
10
+ export const STABLE_UPTIME_MS = 60_000;
11
+ /** This many unexpected exits of one child inside the window is a crash loop. */
12
+ export const CRASH_LIMIT = 5;
13
+ export const CRASH_WINDOW_MS = 5 * 60_000;
14
+
15
+ export interface CrashHistory {
16
+ /** Crashes since the child last stayed up `STABLE_UPTIME_MS`. */
17
+ readonly consecutive: number;
18
+ /** When each crash inside the window happened, oldest first. */
19
+ readonly at: readonly number[];
20
+ }
21
+
22
+ export const NO_CRASHES: CrashHistory = { consecutive: 0, at: [] };
23
+
24
+ export interface RestartDecision {
25
+ readonly history: CrashHistory;
26
+ readonly delayMs: number;
27
+ /** `CRASH_LIMIT` inside `CRASH_WINDOW_MS`: drain the siblings and exit 1. */
28
+ readonly loop: boolean;
29
+ }
30
+
31
+ export function afterCrash(history: CrashHistory, now: number, uptimeMs: number): RestartDecision {
32
+ const consecutive = (uptimeMs >= STABLE_UPTIME_MS ? 0 : history.consecutive) + 1;
33
+ const at = [...history.at.filter((when) => now - when < CRASH_WINDOW_MS), now];
34
+ return {
35
+ history: { consecutive, at },
36
+ // Core's one curve, no jitter: a supervisor restarting its own children has no herd to spread.
37
+ delayMs: backoffDelay({ attempt: consecutive, base: BACKOFF_BASE_MS, max: BACKOFF_CAP_MS }),
38
+ loop: at.length >= CRASH_LIMIT,
39
+ };
40
+ }
41
+
42
+ /** Exit codes, aggregated over the children of one stop: core's 70 wins, then any failure. */
43
+ export function aggregateExit(codes: readonly (number | null)[], killedAtCeiling: boolean): number {
44
+ if (killedAtCeiling || codes.includes(DRAIN_TIMEOUT_EXIT_CODE)) return DRAIN_TIMEOUT_EXIT_CODE;
45
+ return codes.every((code) => code === 0) ? 0 : 1;
46
+ }
@@ -0,0 +1,10 @@
1
+ // The container's database pool — `DATABASE_POOL_MAX`, else the role's profile — which the
2
+ // supervisor splits across its children (`childShare`) and the count never exceeds.
3
+
4
+ import type { Role } from '@ultimat3/core';
5
+ import { POOL_PROFILES, poolMaxFromEnv } from '@ultimat3/db';
6
+ import type { ServeOptions } from './serve-types';
7
+
8
+ /** The container's pool: `DATABASE_POOL_MAX`, else the role's profile — what the children split. */
9
+ export const containerPool = (options: ServeOptions, role: Role): number =>
10
+ poolMaxFromEnv(options.env).max ?? POOL_PROFILES[role].max;
@@ -0,0 +1,158 @@
1
+ // The supervised container's `METRICS_PORT`: `/healthz` (the supervisor is alive and not in a
2
+ // crash loop), `/readyz` (every child that is not draining said ready), and `/metrics` — each
3
+ // child's loopback scrape, merged under one HELP/TYPE per family with a `child="<i>"` label.
4
+
5
+ import { METRICS_CONTENT_TYPE, METRICS_PATH, markListening } from '@ultimat3/core';
6
+ import { bindScrapePort } from './metrics-endpoint';
7
+ import type { ChildView, SupervisorView } from './supervise';
8
+
9
+ /** One child's scrape may not hold the container's: a saturated child answers late (measured). */
10
+ export const CHILD_SCRAPE_TIMEOUT_MS = 2_000;
11
+
12
+ const METRIC_NAME = /^[a-zA-Z_:][a-zA-Z0-9_:]*/;
13
+ const COMMENT = /^#\s+(HELP|TYPE)\s+([a-zA-Z_:][a-zA-Z0-9_:]*)(?:\s|$)/;
14
+
15
+ /** `name{a="1"} 2` → `name{child="i",a="1"} 2`; `name 2` → `name{child="i"} 2`. */
16
+ export function labelSample(line: string, index: number): string {
17
+ const name = METRIC_NAME.exec(line)?.[0];
18
+ if (name === undefined) return line;
19
+ const label = `child="${String(index)}"`;
20
+ const rest = line.slice(name.length);
21
+ if (!rest.startsWith('{')) return `${name}{${label}}${rest}`;
22
+ return `${name}{${label}${rest.startsWith('{}') ? '' : ','}${rest.slice(1)}`;
23
+ }
24
+
25
+ interface Family {
26
+ help: string | undefined;
27
+ type: string | undefined;
28
+ readonly samples: string[];
29
+ }
30
+
31
+ /**
32
+ * Every child's exposition as one: a family's HELP and TYPE once (the first child's), then its
33
+ * samples from every child in child order. A sample belongs to the family the comment above it
34
+ * named — a histogram's `_bucket`, `_sum` and `_count` stay under their family.
35
+ */
36
+ export function mergeMetrics(
37
+ bodies: readonly { readonly index: number; readonly body: string }[],
38
+ ): string {
39
+ const families = new Map<string, Family>();
40
+ const familyOf = (name: string): Family => {
41
+ let family = families.get(name);
42
+ if (family === undefined) {
43
+ family = { help: undefined, type: undefined, samples: [] };
44
+ families.set(name, family);
45
+ }
46
+ return family;
47
+ };
48
+ for (const { index, body } of bodies) {
49
+ let current: string | undefined;
50
+ for (const line of body.split('\n')) {
51
+ if (line.trim() === '') continue;
52
+ const comment = COMMENT.exec(line);
53
+ if (comment !== null) {
54
+ const [, kind, name = ''] = comment;
55
+ current = name;
56
+ const family = familyOf(name);
57
+ if (kind === 'HELP') family.help ??= line;
58
+ else family.type ??= line;
59
+ continue;
60
+ }
61
+ if (line.startsWith('#')) continue;
62
+ const name = METRIC_NAME.exec(line)?.[0];
63
+ if (name === undefined) continue;
64
+ const owner = current !== undefined && name.startsWith(current) ? current : name;
65
+ familyOf(owner).samples.push(labelSample(line, index));
66
+ }
67
+ }
68
+ const out: string[] = [];
69
+ for (const family of families.values()) {
70
+ if (family.help !== undefined) out.push(family.help);
71
+ if (family.type !== undefined) out.push(family.type);
72
+ out.push(...family.samples);
73
+ }
74
+ return out.length === 0 ? '' : `${out.join('\n')}\n`;
75
+ }
76
+
77
+ /** Whether a child's loopback `/healthz` answers 200 in time. */
78
+ export async function childHealthy(metricsUrl: string): Promise<boolean> {
79
+ try {
80
+ const response = await fetch(`${metricsUrl}/healthz`, {
81
+ signal: AbortSignal.timeout(CHILD_SCRAPE_TIMEOUT_MS),
82
+ });
83
+ await response.body?.cancel();
84
+ return response.status === 200;
85
+ } catch {
86
+ return false;
87
+ }
88
+ }
89
+
90
+ async function scrape(child: ChildView): Promise<{ index: number; body: string } | undefined> {
91
+ if (child.metricsUrl === undefined) return undefined;
92
+ try {
93
+ const response = await fetch(`${child.metricsUrl}${METRICS_PATH}`, {
94
+ signal: AbortSignal.timeout(CHILD_SCRAPE_TIMEOUT_MS),
95
+ });
96
+ if (!response.ok) {
97
+ // Given back now, as `childHealthy` does: unread, the stream and its socket stay held.
98
+ await response.body?.cancel();
99
+ return undefined;
100
+ }
101
+ return { index: child.index, body: await response.text() };
102
+ } catch {
103
+ // A child that is restarting or saturated is absent from this scrape, never the scrape's end.
104
+ return undefined;
105
+ }
106
+ }
107
+
108
+ export interface SupervisorProbeInput {
109
+ readonly port: number;
110
+ readonly hostname: string;
111
+ readonly role: string;
112
+ readonly view: SupervisorView;
113
+ }
114
+
115
+ export interface SupervisorProbe {
116
+ readonly url: string;
117
+ stop(): void;
118
+ }
119
+
120
+ const verdict = (ok: boolean, state: string, role: string): Response =>
121
+ Response.json(
122
+ { state, ready: ok, role },
123
+ { status: ok ? 200 : 503, headers: { 'cache-control': 'no-store' } },
124
+ );
125
+
126
+ /** Opened before the first child spawns, so the platform's probes reach a socket from the start. */
127
+ export function startSupervisorProbe(input: SupervisorProbeInput): SupervisorProbe {
128
+ const server = bindScrapePort(input.port, 'refuse', (port) =>
129
+ Bun.serve({
130
+ port,
131
+ hostname: input.hostname,
132
+ async fetch(request: Request): Promise<Response> {
133
+ const path = new URL(request.url).pathname;
134
+ if (path === '/healthz') {
135
+ const live = input.view.live();
136
+ return verdict(live, live ? 'live' : 'crash-loop', input.role);
137
+ }
138
+ if (path === '/readyz') {
139
+ const ready = input.view.ready();
140
+ return verdict(ready, ready ? 'ready' : 'not-ready', input.role);
141
+ }
142
+ if (path !== METRICS_PATH) return new Response('not found', { status: 404 });
143
+ const bodies = await Promise.all(input.view.children().map(scrape));
144
+ return new Response(mergeMetrics(bodies.filter((body) => body !== undefined)), {
145
+ headers: { 'content-type': METRICS_CONTENT_TYPE, 'cache-control': 'no-store' },
146
+ });
147
+ },
148
+ }),
149
+ );
150
+ const stopListening = markListening(server.url.origin);
151
+ return {
152
+ url: server.url.origin,
153
+ stop(): void {
154
+ server.stop(true);
155
+ stopListening();
156
+ },
157
+ };
158
+ }
@@ -0,0 +1,54 @@
1
+ // The supervisor at work: `METRICS_PORT` opened for the whole container first, then the children,
2
+ // until they are gone — answering the container's exit code. Loaded by `runRole` only when the
3
+ // resolved count is more than one, so a lone process never evaluates it.
4
+
5
+ import type { Role } from '@ultimat3/core';
6
+ import { drainDeadlineMs, readinessGraceMs } from '@ultimat3/core';
7
+ import { containerBinding, metricsPortFor, portFromEnv } from './serve-env';
8
+ import type { ServeOptions } from './serve-types';
9
+ import type { SuperviseInput, Supervisor, SupervisorView } from './supervise';
10
+ import { supervise } from './supervise';
11
+ import { containerPool } from './supervise-pool';
12
+ import { childHealthy, startSupervisorProbe } from './supervise-probe';
13
+
14
+ /** The process seams `supervise()` defaults to the real ones: a test hands in fakes. */
15
+ export type SupervisedSeams = Pick<SuperviseInput, 'spawn' | 'signals' | 'timers'>;
16
+
17
+ /** Runs `count` children of this very entry point; answers the container's exit code. */
18
+ export async function runSupervised(
19
+ options: ServeOptions,
20
+ role: Role,
21
+ count: number,
22
+ seams: SupervisedSeams = {},
23
+ ): Promise<number> {
24
+ let supervisor: Supervisor | undefined;
25
+ const view: SupervisorView = {
26
+ children: () => supervisor?.view.children() ?? [],
27
+ ready: () => supervisor?.view.ready() ?? false,
28
+ live: () => supervisor?.view.live() ?? true,
29
+ };
30
+ const port = options.port ?? portFromEnv(options.env);
31
+ // FIRST, as a lone process opens its own: the platform's probes find a socket from the start.
32
+ const probe = startSupervisorProbe({
33
+ port: metricsPortFor(options.env, port, options.metricsPort),
34
+ hostname: containerBinding(options.env, options.hostname).hostname,
35
+ role,
36
+ view,
37
+ });
38
+ try {
39
+ supervisor = supervise({
40
+ ...seams,
41
+ count,
42
+ role,
43
+ // The role this process resolved, whatever `options.role` overrode: a child re-reads `ROLE`.
44
+ env: { ...options.env, ROLE: role },
45
+ pool: containerPool(options, role),
46
+ // Until each child reports its own: the framework default, which an app may only raise.
47
+ budgetMs: readinessGraceMs() + drainDeadlineMs(),
48
+ healthy: childHealthy,
49
+ });
50
+ return await supervisor.done;
51
+ } finally {
52
+ probe.stop();
53
+ }
54
+ }
@@ -0,0 +1,383 @@
1
+ // One production container as N child processes on one port: spawn them, restart a crashed one
2
+ // with backoff, forward the platform's signals, bound their drain, and answer one exit code. The
3
+ // shape is `dev-supervisor.ts`'s — `Bun.spawn` with an `ipc` child — plus what production needs.
4
+
5
+ import type { Role } from '@ultimat3/core';
6
+ import { childShare, logger } from '@ultimat3/core';
7
+ import { POOL_MAX_ENV } from '@ultimat3/db';
8
+ import { ProcessCrashLoopError } from './supervise-errors';
9
+ import type { DrainMessage, DrainSignal } from './supervise-messages';
10
+ import { drainMessage, readChildMessage } from './supervise-messages';
11
+ import {
12
+ afterCrash,
13
+ aggregateExit,
14
+ CRASH_WINDOW_MS,
15
+ type CrashHistory,
16
+ NO_CRASHES,
17
+ } from './supervise-policy';
18
+
19
+ /** Set on each child: `<index>/<count>` (`supervisedChild` in `@ultimat3/core` reads it). */
20
+ export const CHILD_ENV = 'ULTIMATE_CHILD';
21
+ /** Past a child's own drain bound, from its `draining` ack, before it is SIGKILLed. */
22
+ export const CHILD_DRAIN_SLACK_MS = 2_000;
23
+ /** Past the longest bound, from the signal: a CPU-saturated child acks up to 5.2 s late. */
24
+ export const OUTER_SLACK_MS = 6_000;
25
+ /** A child's loopback `/healthz`, asked this often once it is ready. */
26
+ export const HEALTH_POLL_MS = 5_000;
27
+ /**
28
+ * Failed polls in a row before a child is restarted by drain: three polls span 10 s, past the
29
+ * 1.9–5.2 s a CPU-saturated child was measured to answer late — busy is not dead.
30
+ */
31
+ export const HEALTH_FAILURES = 3;
32
+
33
+ export interface ChildHandle {
34
+ readonly pid: number;
35
+ /** The exit code, or `null` for a child a signal killed. */
36
+ readonly exited: Promise<number | null>;
37
+ kill(signal: DrainSignal | 'SIGKILL'): void;
38
+ send(message: DrainMessage): void;
39
+ }
40
+
41
+ export type SpawnChild = (input: {
42
+ readonly index: number;
43
+ readonly env: Record<string, string | undefined>;
44
+ readonly onMessage: (message: unknown) => void;
45
+ }) => ChildHandle;
46
+
47
+ export interface SupervisorTimers {
48
+ now(): number;
49
+ setTimeout(run: () => void, ms: number): unknown;
50
+ clearTimeout(handle: unknown): void;
51
+ }
52
+
53
+ export type SignalName = DrainSignal | 'exit';
54
+ export interface SignalHub {
55
+ on(signal: SignalName, listener: () => void): void;
56
+ off(signal: SignalName, listener: () => void): void;
57
+ }
58
+
59
+ export type ChildState = 'starting' | 'ready' | 'draining' | 'waiting' | 'exited';
60
+
61
+ export interface ChildView {
62
+ readonly index: number;
63
+ readonly state: ChildState;
64
+ readonly metricsUrl: string | undefined;
65
+ }
66
+
67
+ export interface SupervisorView {
68
+ children(): readonly ChildView[];
69
+ /** At least one child ready, every other one ready or draining, and the container not stopping. */
70
+ ready(): boolean;
71
+ /** Alive and not giving up on a crash loop. */
72
+ live(): boolean;
73
+ }
74
+
75
+ export interface SuperviseInput {
76
+ readonly count: number;
77
+ readonly role: Role;
78
+ readonly env: Readonly<Record<string, string | undefined>>;
79
+ /** The container's pool, split across the children (`childShare`). */
80
+ readonly pool: number;
81
+ /** A child's drain bound until it reports its own (`ready`/`draining`). */
82
+ readonly budgetMs: number;
83
+ readonly spawn?: SpawnChild;
84
+ readonly timers?: SupervisorTimers;
85
+ readonly signals?: SignalHub;
86
+ /** Whether a child's loopback `/healthz` answers 200 (`childHealthy` in `supervise-probe.ts`). */
87
+ readonly healthy?: (metricsUrl: string) => Promise<boolean>;
88
+ }
89
+
90
+ export interface Supervisor {
91
+ readonly view: SupervisorView;
92
+ /** The container's exit code: 0, 70 (a child's drain timed out or was killed), 1 (crash loop). */
93
+ readonly done: Promise<number>;
94
+ }
95
+
96
+ interface Slot {
97
+ readonly index: number;
98
+ state: ChildState;
99
+ child: ChildHandle | undefined;
100
+ metricsUrl: string | undefined;
101
+ budgetMs: number;
102
+ startedAt: number;
103
+ history: CrashHistory;
104
+ timers: unknown[];
105
+ failures: number;
106
+ killed: boolean;
107
+ exit: number | null;
108
+ }
109
+
110
+ const spawnBun: SpawnChild = ({ env, onMessage }) => {
111
+ // A server child has no deadline of its own: its bound is the supervisor's, and a hard kill at
112
+ // that bound is this abort — the drain's ceiling, or a child that would not drain.
113
+ const bound = new AbortController();
114
+ const proc = Bun.spawn([process.execPath, ...process.argv.slice(1)], {
115
+ env,
116
+ stdin: 'ignore',
117
+ stdout: 'inherit',
118
+ stderr: 'inherit',
119
+ serialization: 'json',
120
+ ipc: (message) => onMessage(message),
121
+ signal: bound.signal,
122
+ killSignal: 'SIGKILL',
123
+ });
124
+ return {
125
+ pid: proc.pid,
126
+ exited: proc.exited.then(() => (proc.signalCode === null ? proc.exitCode : null)),
127
+ kill: (signal) => (signal === 'SIGKILL' ? bound.abort() : proc.kill(signal)),
128
+ send: (message) => {
129
+ proc.send(message);
130
+ },
131
+ };
132
+ };
133
+
134
+ const realTimers: SupervisorTimers = {
135
+ now: () => performance.now(),
136
+ setTimeout: (run, ms) => setTimeout(run, ms),
137
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
138
+ };
139
+
140
+ const processSignals: SignalHub = {
141
+ on: (signal, listener) => process.on(signal, listener),
142
+ off: (signal, listener) => process.off(signal, listener),
143
+ };
144
+
145
+ const say = (level: 'info' | 'warn' | 'error', msg: string, fields: Record<string, unknown>) =>
146
+ logger[level](msg, { child: 'supervisor', ...fields });
147
+
148
+ export function supervise(input: SuperviseInput): Supervisor {
149
+ const spawn = input.spawn ?? spawnBun;
150
+ const timers = input.timers ?? realTimers;
151
+ const signals = input.signals ?? processSignals;
152
+ const slots: Slot[] = Array.from({ length: input.count }, (_, index) => ({
153
+ index,
154
+ state: 'waiting',
155
+ child: undefined,
156
+ metricsUrl: undefined,
157
+ budgetMs: input.budgetMs,
158
+ startedAt: 0,
159
+ history: NO_CRASHES,
160
+ timers: [],
161
+ failures: 0,
162
+ killed: false,
163
+ exit: null,
164
+ }));
165
+ let stopping: DrainSignal | undefined;
166
+ let ceiling: unknown;
167
+ let killedAtCeiling = false;
168
+ let failure: ProcessCrashLoopError | 'fatal' | undefined;
169
+ let finished = false;
170
+ let resolve!: (code: number) => void;
171
+ const done = new Promise<number>((settle) => {
172
+ resolve = settle;
173
+ });
174
+
175
+ // Only PENDING handles stay on the slot: a fired one leaves it, or a healthy child's polls
176
+ // (one per HEALTH_POLL_MS) would pile up until its next exit.
177
+ const later = (slot: Slot, ms: number, run: () => void): void => {
178
+ const handle = timers.setTimeout(() => {
179
+ const at = slot.timers.indexOf(handle);
180
+ if (at !== -1) slot.timers.splice(at, 1);
181
+ run();
182
+ }, ms);
183
+ slot.timers.push(handle);
184
+ };
185
+ const clear = (slot: Slot): void => {
186
+ for (const handle of slot.timers.splice(0)) timers.clearTimeout(handle);
187
+ };
188
+
189
+ /** Once per child: both bounds can land on one tick. Only a stop's kill makes the exit 70. */
190
+ const killHard = (slot: Slot, msg: string): void => {
191
+ if (slot.child === undefined || slot.killed) return;
192
+ slot.killed = true;
193
+ if (stopping !== undefined) killedAtCeiling = true;
194
+ say('warn', msg, { index: slot.index });
195
+ slot.child.kill('SIGKILL');
196
+ };
197
+
198
+ const finishIfGone = (): void => {
199
+ if (finished || stopping === undefined || slots.some((slot) => slot.child !== undefined))
200
+ return;
201
+ finished = true;
202
+ for (const [signal, listener] of handlers) signals.off(signal, listener);
203
+ timers.clearTimeout(ceiling);
204
+ const code =
205
+ failure !== undefined
206
+ ? 1
207
+ : aggregateExit(
208
+ slots.map((slot) => slot.exit),
209
+ killedAtCeiling,
210
+ );
211
+ say(code === 0 ? 'info' : 'warn', 'ultimate processes stopped', { code });
212
+ resolve(code);
213
+ };
214
+
215
+ /**
216
+ * One stop per container. A retire (SIGUSR2, worker only) may be followed by the platform's
217
+ * SIGTERM, which is forwarded and arms the ceiling; anything after that is the same stop.
218
+ */
219
+ const stop = (signal: DrainSignal): void => {
220
+ const upgrade = stopping === 'SIGUSR2' && signal !== 'SIGUSR2';
221
+ if (stopping !== undefined && !upgrade) return;
222
+ stopping = signal;
223
+ for (const slot of slots) {
224
+ if (slot.child === undefined) {
225
+ clear(slot);
226
+ slot.state = 'exited';
227
+ continue;
228
+ }
229
+ slot.child.kill(signal);
230
+ }
231
+ // A retire (SIGUSR2) is bounded by the platform's own kill timer; a stop by ours.
232
+ if (signal !== 'SIGUSR2') {
233
+ const longest = Math.max(input.budgetMs, ...slots.map((slot) => slot.budgetMs));
234
+ ceiling = timers.setTimeout(() => {
235
+ for (const slot of slots) killHard(slot, 'ultimate child killed at the drain ceiling');
236
+ }, longest + OUTER_SLACK_MS);
237
+ }
238
+ finishIfGone();
239
+ };
240
+
241
+ const onMessage = (slot: Slot, raw: unknown): void => {
242
+ const message = readChildMessage(raw);
243
+ if (message === undefined) return;
244
+ if (message.event === 'ready') {
245
+ if (slot.state === 'starting') slot.state = 'ready';
246
+ slot.metricsUrl = message.metricsUrl;
247
+ slot.budgetMs = message.budgetMs;
248
+ return;
249
+ }
250
+ if (message.event === 'draining') {
251
+ slot.state = 'draining';
252
+ slot.budgetMs = message.budgetMs;
253
+ // The child's own bound starts at its ack: a saturated child hears the signal seconds late.
254
+ later(slot, message.budgetMs + CHILD_DRAIN_SLACK_MS, () =>
255
+ killHard(slot, 'ultimate child killed past its drain bound'),
256
+ );
257
+ return;
258
+ }
259
+ if (message.event === 'fatal') {
260
+ failure = 'fatal';
261
+ say('error', 'ultimate child refused to serve', { index: slot.index, code: message.code });
262
+ stop('SIGTERM');
263
+ }
264
+ };
265
+
266
+ const onExit = (slot: Slot, code: number | null): void => {
267
+ clear(slot);
268
+ slot.child = undefined;
269
+ slot.metricsUrl = undefined;
270
+ slot.exit = code;
271
+ if (stopping !== undefined) {
272
+ slot.state = 'exited';
273
+ finishIfGone();
274
+ return;
275
+ }
276
+ const now = timers.now();
277
+ const decision = afterCrash(slot.history, now, now - slot.startedAt);
278
+ slot.history = decision.history;
279
+ if (decision.loop) {
280
+ const error = new ProcessCrashLoopError({
281
+ index: slot.index,
282
+ code,
283
+ crashes: decision.history.at.length,
284
+ windowMs: CRASH_WINDOW_MS,
285
+ });
286
+ failure = error;
287
+ say('error', error.code, { code: error.code, cause: error.cause, fix: error.fix });
288
+ stop('SIGTERM');
289
+ return;
290
+ }
291
+ slot.state = 'waiting';
292
+ say('warn', 'ultimate child exited', {
293
+ index: slot.index,
294
+ exitCode: code,
295
+ restartInMs: decision.delayMs,
296
+ });
297
+ later(slot, decision.delayMs, () => start(slot));
298
+ };
299
+
300
+ const poll = (slot: Slot, child: ChildHandle): void => {
301
+ later(slot, HEALTH_POLL_MS, () => {
302
+ if (slot.child !== child || stopping !== undefined) return;
303
+ const url = slot.metricsUrl;
304
+ if (slot.state !== 'ready' || url === undefined || input.healthy === undefined) {
305
+ poll(slot, child);
306
+ return;
307
+ }
308
+ void input.healthy(url).then((ok) => {
309
+ if (slot.child !== child) return;
310
+ slot.failures = ok ? 0 : slot.failures + 1;
311
+ if (slot.failures >= HEALTH_FAILURES) {
312
+ say('warn', 'ultimate child unhealthy, restarting it', { index: slot.index });
313
+ slot.state = 'draining';
314
+ child.send(drainMessage('SIGTERM'));
315
+ // A child too wedged to ack is bounded as a stop is: its exit is then restarted.
316
+ later(slot, slot.budgetMs + OUTER_SLACK_MS, () =>
317
+ killHard(slot, 'ultimate child killed: it did not drain after failing its health'),
318
+ );
319
+ return;
320
+ }
321
+ poll(slot, child);
322
+ });
323
+ });
324
+ };
325
+
326
+ const start = (slot: Slot): void => {
327
+ if (stopping !== undefined) return;
328
+ const child = spawn({
329
+ index: slot.index,
330
+ env: {
331
+ ...input.env,
332
+ [CHILD_ENV]: `${String(slot.index)}/${String(input.count)}`,
333
+ [POOL_MAX_ENV]: String(childShare(input.pool, slot.index, input.count)),
334
+ },
335
+ onMessage: (message) => onMessage(slot, message),
336
+ });
337
+ slot.child = child;
338
+ slot.state = 'starting';
339
+ slot.startedAt = timers.now();
340
+ slot.failures = 0;
341
+ slot.killed = false;
342
+ void child.exited.then((code) => {
343
+ if (slot.child === child) onExit(slot, code);
344
+ });
345
+ if (input.healthy !== undefined) poll(slot, child);
346
+ };
347
+
348
+ // Before the first spawn: Bun as PID 1 IGNORES a SIGTERM nobody handles (measured), and a
349
+ // signal landing between two spawns must still reach the child already running.
350
+ const handlers: [SignalName, () => void][] = [
351
+ ['SIGTERM', () => stop('SIGTERM')],
352
+ ['SIGINT', () => stop('SIGINT')],
353
+ ['SIGUSR2', () => (input.role === 'worker' ? stop('SIGUSR2') : undefined)],
354
+ // An uncaught throw here: each child is asked to drain (a SIGKILL of this process is answered
355
+ // by the children themselves, on IPC disconnect — `supervise-child.ts`).
356
+ [
357
+ 'exit',
358
+ () => {
359
+ for (const slot of slots) slot.child?.kill('SIGTERM');
360
+ },
361
+ ],
362
+ ];
363
+ for (const [signal, listener] of handlers) signals.on(signal, listener);
364
+ say('info', 'ultimate processes starting', { count: input.count, role: input.role });
365
+ for (const slot of slots) start(slot);
366
+
367
+ return {
368
+ done,
369
+ view: {
370
+ children: () =>
371
+ slots.map((slot) => ({
372
+ index: slot.index,
373
+ state: slot.state,
374
+ metricsUrl: slot.metricsUrl,
375
+ })),
376
+ ready: () =>
377
+ stopping === undefined &&
378
+ slots.some((slot) => slot.state === 'ready') &&
379
+ slots.every((slot) => slot.state === 'ready' || slot.state === 'draining'),
380
+ live: () => !(failure instanceof ProcessCrashLoopError),
381
+ },
382
+ };
383
+ }
@@ -67,16 +67,16 @@ jobTest('${name.camel} enqueues once, and dedupes a second sweep while one is li
67
67
 
68
68
  const unitSuite = (
69
69
  name: NameSet,
70
- ): string => `// ${name.camel}'s BODY, run by a worker in this process: one pass completes and reports what it
71
- // removed — a number, never a guess, so \`x jobs show\` can print it.
70
+ ): string => `// ${name.camel}'s DECLARATION: the durable name its rows are keyed by, and that it is a job. The
71
+ // pass itself deletes with SQL over whole tables, so it needs a migrated database and is not run
72
+ // here: the unit step has none, and \`x jobs show\` prints what a real pass removed.
72
73
 
73
74
  import { expect, unitTest } from '@ultimat3/testing';
74
75
  import { ${name.camel} } from './${name.kebab}';
75
76
 
76
- unitTest('one pass completes and reports how many rows it removed', async ({ runJobs }) => {
77
- const trace = await runJobs(${name.camel}, {});
78
- expect(trace.executions.map((run) => run.outcome)).toEqual(['completed']);
79
- expect(trace.executions[0]?.result).toMatchObject({ removed: 0 });
77
+ unitTest('${name.camel} is the job named ${name.kebab}', () => {
78
+ expect(${name.camel}.kind).toBe('job');
79
+ expect(${name.camel}.name).toBe('${name.kebab}');
80
80
  });
81
81
  `;
82
82