@ultimat3/cli 30.8.0 → 31.0.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 (197) hide show
  1. package/CLAUDE.md +75 -64
  2. package/README.md +4 -1
  3. package/package.json +30 -29
  4. package/src/admin-registration.ts +1 -1
  5. package/src/affected.ts +5 -1
  6. package/src/app-boundaries.ts +88 -9
  7. package/src/app-load-async.ts +133 -0
  8. package/src/app-load-batch.ts +203 -0
  9. package/src/app-load-prebuilt.ts +147 -0
  10. package/src/app-load-register.ts +175 -0
  11. package/src/app-load.ts +143 -175
  12. package/src/app-loader-imports.ts +31 -0
  13. package/src/app-root.ts +13 -0
  14. package/src/app-runtime.ts +5 -1
  15. package/src/boundary-findings.ts +12 -0
  16. package/src/browser-launcher-port.ts +3 -7
  17. package/src/browser-launcher.ts +1 -1
  18. package/src/budgets-scan.ts +8 -0
  19. package/src/budgets.ts +10 -1
  20. package/src/build-registry-background.ts +59 -0
  21. package/src/build-registry.ts +207 -0
  22. package/src/cdp-shot-clock.ts +3 -11
  23. package/src/cdp-shot-driver.ts +3 -2
  24. package/src/cdp-shot-element.ts +3 -2
  25. package/src/cdp-shot-page.ts +2 -2
  26. package/src/cdp-shot-watch.ts +4 -3
  27. package/src/cmd-auth.ts +3 -3
  28. package/src/cmd-db-recount.ts +15 -0
  29. package/src/cmd-drill.ts +10 -6
  30. package/src/cmd-exercise.ts +2 -1
  31. package/src/cmd-generate-spec.ts +6 -0
  32. package/src/cmd-generate.ts +22 -4
  33. package/src/cmd-mail.ts +1 -1
  34. package/src/cmd-routes.ts +2 -2
  35. package/src/cmd-secrets-spec.ts +4 -1
  36. package/src/cmd-shot.ts +14 -4
  37. package/src/cmd-verify-spec.ts +21 -1
  38. package/src/cmd-verify.ts +16 -4
  39. package/src/coverage-source.ts +4 -1
  40. package/src/db-diagnostics.ts +8 -1
  41. package/src/dev-boot.ts +29 -15
  42. package/src/dev-dashboard-invalidations.ts +43 -0
  43. package/src/dev-dashboard.ts +13 -16
  44. package/src/dev-n-plus-one.ts +7 -3
  45. package/src/dev-rebuild.ts +2 -1
  46. package/src/dev-route-table.ts +1 -1
  47. package/src/dev-traces.ts +16 -15
  48. package/src/document-options.ts +12 -1
  49. package/src/drift-store.ts +55 -0
  50. package/src/error-catalog.ts +8 -3
  51. package/src/error-codes-boundary.ts +32 -0
  52. package/src/error-codes.ts +23 -19
  53. package/src/errors.ts +17 -7
  54. package/src/exercise-database.ts +13 -1
  55. package/src/exercise-findings.ts +36 -18
  56. package/src/exercise-services.ts +84 -0
  57. package/src/exercise-subject.ts +38 -13
  58. package/src/failure-capture-boot.ts +9 -5
  59. package/src/framework-schema.ts +5 -5
  60. package/src/generate-exercise.ts +1 -1
  61. package/src/generate-files.ts +27 -7
  62. package/src/generate-kinds.ts +5 -0
  63. package/src/generate-refresh.ts +53 -0
  64. package/src/generate-workspace.ts +169 -0
  65. package/src/generate-write.ts +8 -2
  66. package/src/hold.ts +19 -8
  67. package/src/image-prepare.ts +6 -2
  68. package/src/index.ts +5 -20
  69. package/src/island-bundle.ts +7 -3
  70. package/src/island-capture.ts +2 -2
  71. package/src/island-harness.ts +1 -1
  72. package/src/job-registration.ts +43 -6
  73. package/src/jobs-driver.ts +4 -5
  74. package/src/mcp-errors.ts +18 -4
  75. package/src/mcp-host.ts +5 -1
  76. package/src/mcp-ui-interact.ts +3 -0
  77. package/src/messages-gate.ts +4 -0
  78. package/src/new-shapes-generate.ts +1 -1
  79. package/src/otlp-export.ts +94 -29
  80. package/src/output.ts +3 -7
  81. package/src/page-sync.ts +3 -1
  82. package/src/role-load.ts +17 -11
  83. package/src/role-start.ts +5 -4
  84. package/src/role-sync.ts +7 -8
  85. package/src/route-islands-preload.ts +46 -0
  86. package/src/route-islands.ts +6 -2
  87. package/src/runtime-admin.ts +5 -1
  88. package/src/runtime-bindings.ts +25 -19
  89. package/src/runtime-boot-ports.ts +66 -0
  90. package/src/runtime-bus.ts +29 -5
  91. package/src/runtime-cache-bus.ts +53 -0
  92. package/src/runtime-cache.ts +43 -13
  93. package/src/runtime-isr-outcome.ts +5 -4
  94. package/src/runtime-jobs.ts +2 -2
  95. package/src/runtime-keys.ts +37 -0
  96. package/src/runtime-overrides.ts +148 -42
  97. package/src/runtime-port-bindings-queue.ts +36 -0
  98. package/src/runtime-port-bindings.ts +117 -0
  99. package/src/runtime-ports.ts +164 -0
  100. package/src/runtime-purge.ts +41 -28
  101. package/src/runtime-push.ts +7 -3
  102. package/src/runtime-queue.ts +70 -55
  103. package/src/runtime-realtime.ts +5 -5
  104. package/src/runtime-render-document.ts +4 -1
  105. package/src/runtime-services.ts +110 -158
  106. package/src/runtime-storage-boot.ts +111 -0
  107. package/src/runtime-storage-upload.ts +9 -7
  108. package/src/runtime-storage.ts +7 -1
  109. package/src/serve-boot.ts +8 -4
  110. package/src/serve-entry.ts +3 -0
  111. package/src/serve-env.ts +47 -14
  112. package/src/serve-prebuilt-paths.ts +3 -0
  113. package/src/serve-prebuilt.ts +15 -4
  114. package/src/serve.ts +2 -2
  115. package/src/static-cards.ts +3 -2
  116. package/src/static-report.ts +2 -2
  117. package/src/style-bundle.ts +1 -1
  118. package/src/sync-authenticator.ts +17 -18
  119. package/src/templates/action-tests.ts +4 -4
  120. package/src/templates/backfill.ts +5 -8
  121. package/src/templates/entity.ts +3 -0
  122. package/src/templates/github/ci.yml.ts +3 -1
  123. package/src/templates/github/dependabot.yml.ts +73 -0
  124. package/src/templates/job.ts +13 -22
  125. package/src/templates/naming.ts +20 -1
  126. package/src/templates/pinned/docker-compose.yml +1 -1
  127. package/src/templates/query.ts +7 -8
  128. package/src/templates/route.ts +5 -3
  129. package/src/templates/scaffold-api.ts +1 -1
  130. package/src/templates/scaffold-auth.ts +5 -3
  131. package/src/templates/scaffold-claude-commands.ts +6 -3
  132. package/src/templates/scaffold-claude.ts +4 -4
  133. package/src/templates/scaffold-container-compose.ts +2 -4
  134. package/src/templates/scaffold-domain-package.ts +1 -1
  135. package/src/templates/scaffold-entries.ts +6 -1
  136. package/src/templates/scaffold-helm-fences.ts +3 -2
  137. package/src/templates/scaffold-helm.ts +35 -6
  138. package/src/templates/scaffold-repo.ts +47 -135
  139. package/src/templates/scaffold-runtime-ports.ts +62 -0
  140. package/src/templates/scaffold-verify-floor.ts +97 -0
  141. package/src/templates/shapes/overlay.ts +1 -1
  142. package/src/templates/sign-in-oidc.ts +5 -3
  143. package/src/templates/sign-in-shared.ts +28 -10
  144. package/src/templates/workspace.ts +75 -0
  145. package/src/test-ignores.ts +5 -2
  146. package/src/test-select.ts +4 -1
  147. package/src/upgrade-gate.ts +30 -5
  148. package/src/upgrade-report.ts +7 -1
  149. package/src/verify-changed-facts.ts +53 -0
  150. package/src/verify-changed-scope.ts +161 -0
  151. package/src/verify-changed.ts +174 -0
  152. package/src/verify-checks.ts +31 -19
  153. package/src/verify-drift-owner.ts +30 -0
  154. package/src/verify-e2e.ts +2 -1
  155. package/src/verify-factories.ts +86 -0
  156. package/src/verify-run.ts +13 -11
  157. package/src/verify-step.ts +13 -0
  158. package/src/verify-tests.ts +58 -6
  159. package/src/write-line.ts +21 -6
  160. package/wiki/Actions.md +2 -2
  161. package/wiki/Adapters.md +400 -0
  162. package/wiki/Admin-Dashboard.md +2 -1
  163. package/wiki/Agents.md +9 -9
  164. package/wiki/Auth.md +78 -2
  165. package/wiki/Building-Your-Own-Base.md +1 -1
  166. package/wiki/CLI-Reference.md +34 -7
  167. package/wiki/Caching-And-Invalidation.md +17 -5
  168. package/wiki/Compared.md +8 -2
  169. package/wiki/Configuration.md +14 -14
  170. package/wiki/Deployment.md +28 -1
  171. package/wiki/Entities-And-Migrations.md +48 -2
  172. package/wiki/FAQ.md +8 -2
  173. package/wiki/Feature-Flags.md +1 -1
  174. package/wiki/Home.md +3 -2
  175. package/wiki/Jobs-And-Workflows.md +107 -6
  176. package/wiki/Known-Gaps.md +4 -3
  177. package/wiki/MCP-And-AI.md +18 -4
  178. package/wiki/Mail.md +14 -5
  179. package/wiki/Migrations-And-Backfills.md +31 -4
  180. package/wiki/Money.md +2 -0
  181. package/wiki/N-Plus-One-Detection.md +24 -22
  182. package/wiki/Notify.md +28 -4
  183. package/wiki/Observability.md +121 -15
  184. package/wiki/Queries-And-Live-Queries.md +2 -2
  185. package/wiki/Realtime.md +9 -4
  186. package/wiki/Routes-And-Render-Modes.md +5 -0
  187. package/wiki/Scraping.md +57 -11
  188. package/wiki/Shapes.md +2 -2
  189. package/wiki/Stability.md +7 -5
  190. package/wiki/Storage-And-Uploads.md +56 -4
  191. package/wiki/Testing.md +69 -56
  192. package/wiki/Troubleshooting.md +1 -1
  193. package/wiki/Tutorial-01-First-App.md +1 -1
  194. package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
  195. package/wiki/Tutorial-05-Deploy-Free.md +1 -1
  196. package/wiki/Tutorial-06-Growing-Up.md +8 -8
  197. package/wiki/Upgrading.md +129 -4
@@ -29,6 +29,8 @@ export const GENERATORS = [
29
29
  'guard',
30
30
  'sign-in',
31
31
  'chart-alerts',
32
+ 'app',
33
+ 'package',
32
34
  ] as const;
33
35
 
34
36
  export type Generator = (typeof GENERATORS)[number];
@@ -286,4 +288,7 @@ const EXAMPLE_NAME: Readonly<Record<Generator, string>> = {
286
288
  'sign-in': '--password',
287
289
  // No name either: an app has one chart. `--print` runs with or without one.
288
290
  'chart-alerts': '--print',
291
+ // A workspace: `apps/admin`, `packages/domain`.
292
+ app: 'admin',
293
+ package: 'domain',
289
294
  };
@@ -0,0 +1,53 @@
1
+ // Whether an `x g` run's files can change a fact `x.manifest.json` holds — and so whether the run
2
+ // has to load the whole app to re-project it. Every manifest fact is read off a registry the app
3
+ // scan fills, except the `X_*` codes, which are read off the source: a file the scan never imports
4
+ // and that declares no code cannot move either, so the run skips the load (plan 101, slice 22 B5).
5
+
6
+ // why: Bun ships no path API; the scan's own rule takes an absolute path.
7
+ import { resolve } from 'node:path';
8
+ import { isAppModulePath } from './app-load';
9
+ import { isTest } from './source-files';
10
+ import { scanCodes } from './ts-scan';
11
+
12
+ /** Source the codes walk reads; anything else is data, a stylesheet or a doc. */
13
+ const SOURCE = /\.[cm]?[jt]sx?$/;
14
+
15
+ /**
16
+ * Whether one written or edited file can change the manifest. Unreadable (a dry run's planned file
17
+ * is not on disk) is answered from `planned` when the caller has its bytes, and is `true` when it
18
+ * has none: a refresh too many costs seconds, one too few is a stale contract.
19
+ */
20
+ async function moves(
21
+ root: string,
22
+ path: string,
23
+ planned: ReadonlyMap<string, string>,
24
+ ): Promise<boolean> {
25
+ // The app root's own files — `package.json`, `app.config.ts` — are the manifest's identity.
26
+ if (!path.includes('/')) return true;
27
+ // Neither imported nor walked for codes (`collectDeclaredCodes` skips them too).
28
+ if (isTest(path)) return false;
29
+ if (isAppModulePath(root, path)) return true;
30
+ if (!SOURCE.test(path)) return !/\.(?:s?css|md|json)$/.test(path);
31
+ const text =
32
+ planned.get(path) ??
33
+ (await Bun.file(resolve(root, path))
34
+ .text()
35
+ .catch(() => undefined));
36
+ return text === undefined || scanCodes(text, path).length > 0;
37
+ }
38
+
39
+ /**
40
+ * Whether any of `paths` (app-root-relative) can change `x.manifest.json`. A `.json` file is no
41
+ * manifest input: a catalog's keys are not in it, and a workspace manifest's edit always arrives
42
+ * with the module whose import it declares.
43
+ */
44
+ export async function manifestCanChange(
45
+ root: string,
46
+ paths: readonly string[],
47
+ planned: ReadonlyMap<string, string> = new Map(),
48
+ ): Promise<boolean> {
49
+ for (const path of paths) {
50
+ if (await moves(root, path, planned)) return true;
51
+ }
52
+ return false;
53
+ }
@@ -0,0 +1,169 @@
1
+ // `x g app <name>` / `x g package <name>` — one more workspace in the repo — and `--app`, the app
2
+ // workspace an app-local generator writes into. Both name a directory under `apps/` or
3
+ // `packages/`, and `@<scope>/<name>` is the package either is installed as, so one name is one
4
+ // workspace across both kinds.
5
+
6
+ // why: Bun has no synchronous exists, and every check here runs before a single file is planned.
7
+ import { existsSync } from 'node:fs';
8
+ // why: Bun ships no path-join primitive.
9
+ import { basename, join } from 'node:path';
10
+ import { isJsonObject, renderFixShellArg, UltimateError } from '@ultimat3/core';
11
+ import { generateSpec } from './cmd-generate-spec';
12
+ import type { CommandContext } from './command';
13
+ import { invocationOf } from './command';
14
+ import { BadFlagError } from './errors';
15
+ import { DEFAULT_APP, generate } from './generate-files';
16
+ import type { Generator } from './generate-kinds';
17
+ import { readName } from './generate-kinds';
18
+ import { planWrites, writeFiles } from './generate-write';
19
+ import { msg } from './messages';
20
+ import type { CommandResult } from './output';
21
+ import type { ParsedArgs } from './parse';
22
+ import { flagBool } from './parse';
23
+ import { quoteArg } from './shell-quote';
24
+ import { kebab } from './templates';
25
+
26
+ /** The two workspace kinds, and the directory each lives under. */
27
+ const WORKSPACE_DIR = { app: 'apps', package: 'packages' } as const;
28
+
29
+ export type WorkspaceKind = keyof typeof WORKSPACE_DIR;
30
+
31
+ export const isWorkspaceKind = (kind: Generator): kind is WorkspaceKind =>
32
+ kind === 'app' || kind === 'package';
33
+
34
+ /**
35
+ * Generators whose every write and follow-up edit stays inside the app they land in. The rest
36
+ * register in files only `apps/web` has — the API index, the roles, the exercise file, the db
37
+ * handle — so under another app they would write half a slice there and half here.
38
+ */
39
+ const APP_LOCAL: ReadonlySet<Generator> = new Set<Generator>(['route', 'island', 'query']);
40
+
41
+ /** The next commands after a new workspace: link it, then gate only what changed. */
42
+ export const WORKSPACE_NEXT = ['bun install', 'bunx x verify --changed --dirty'] as const;
43
+
44
+ /** One name, one workspace: `apps/<n>` and `packages/<n>` are both `@<scope>/<n>`. */
45
+ export class WorkspaceNameTakenError extends UltimateError {
46
+ constructor(input: {
47
+ readonly kind: WorkspaceKind;
48
+ readonly name: string;
49
+ readonly held: string;
50
+ }) {
51
+ const suffix = input.kind === 'app' ? 'app' : 'shared';
52
+ super({
53
+ code: 'X_WORKSPACE_NAME_TAKEN',
54
+ cause: `${input.held}/ already exists, and apps/${input.name} and packages/${input.name} would both be installed as @<scope>/${input.name} — bun install cannot hold two workspaces under one name`,
55
+ fix: `${input.kind === 'app' ? 'x g app' : 'x g package'} ${renderFixShellArg(`${input.name}-${suffix}`, '<another name>')}`,
56
+ meta: { kind: input.kind, name: input.name, held: input.held },
57
+ });
58
+ }
59
+ }
60
+
61
+ /**
62
+ * The repo's scope: `@acme/root` → `acme`, a bare `acme` → `acme`. A root manifest with no name
63
+ * falls back to the directory's, which is what `x new` named it after.
64
+ */
65
+ async function repoScope(root: string): Promise<string> {
66
+ const parsed: unknown = await Bun.file(join(root, 'package.json'))
67
+ .json()
68
+ .catch(() => undefined);
69
+ const name = isJsonObject(parsed) && typeof parsed['name'] === 'string' ? parsed['name'] : '';
70
+ const scope = name.startsWith('@') ? (name.slice(1).split('/')[0] ?? '') : name;
71
+ return kebab(scope === '' ? basename(root) : scope);
72
+ }
73
+
74
+ /** The `x g` flags a workspace generator reads; every other one is a slice's, so is refused. */
75
+ const WORKSPACE_READS: ReadonlySet<string> = new Set(['force', 'dry-run']);
76
+
77
+ /**
78
+ * Any slice flag — `--feature`, `--surface`, `--live`, `--admin`, `--locales`, `--at`, `--app`,
79
+ * `--permission`, … — set to something but its default: a workspace is no slice, so each would be
80
+ * accepted and change nothing. Projected from the spec, so a flag added there is refused here too.
81
+ */
82
+ function refuseSliceFlags(args: ParsedArgs, kind: WorkspaceKind, name: string): void {
83
+ for (const flag of generateSpec.flags ?? []) {
84
+ if (WORKSPACE_READS.has(flag.name)) continue;
85
+ const value = args.flags.get(flag.name);
86
+ if (value === undefined || value === flag.default) continue;
87
+ throw new BadFlagError({
88
+ flag: flag.name,
89
+ command: `g ${kind}`,
90
+ reason: `a ${kind} is a workspace, not a slice, so --${flag.name} would change nothing; it reads --force and --dry-run only`,
91
+ fix: `${kind === 'app' ? 'x g app' : 'x g package'} ${renderFixShellArg(name, '<name>')}`,
92
+ });
93
+ }
94
+ }
95
+
96
+ /** `x g app|package <name>`: planned, refused or written, with the two commands that follow. */
97
+ export async function runWorkspace(
98
+ ctx: CommandContext,
99
+ root: string,
100
+ kind: WorkspaceKind,
101
+ ): Promise<CommandResult> {
102
+ const name = kebab(readName(ctx.args.positionals[1], kind));
103
+ refuseSliceFlags(ctx.args, kind, name);
104
+ const other: WorkspaceKind = kind === 'app' ? 'package' : 'app';
105
+ const held = `${WORKSPACE_DIR[other]}/${name}`;
106
+ if (existsSync(join(root, held))) throw new WorkspaceNameTakenError({ kind, name, held });
107
+ const files = generate({ kind, name, scope: await repoScope(root) });
108
+ const force = flagBool(ctx.args, 'force');
109
+ const invocation = [invocationOf(ctx, 'g'), kind, quoteArg(name)].join(' ');
110
+ const dryRun = flagBool(ctx.args, 'dry-run');
111
+ const report = dryRun
112
+ ? await planWrites(root, files, force, invocation, name)
113
+ : await writeFiles(root, files, force, invocation, name);
114
+ const ok = report.conflicts.length === 0;
115
+ const next = ok && !dryRun ? [...WORKSPACE_NEXT] : [];
116
+ const count = report.written.length;
117
+ return {
118
+ ok,
119
+ command: 'g',
120
+ summary: dryRun
121
+ ? msg('cli.generate.planned', { count, kind, name })
122
+ : ok
123
+ ? msg('cli.generate.wroteNext', { count, kind, name, next: next.join(' && ') })
124
+ : msg('cli.generate.wrote', { count, kind, name }),
125
+ data: { files: report.written, ...(dryRun ? { dryRun: true } : {}), ...(ok ? { next } : {}) },
126
+ lines: report.written.map((path) => msg('cli.file.added', { path })),
127
+ findings: report.conflicts,
128
+ };
129
+ }
130
+
131
+ /**
132
+ * `--app`: the app workspace an app-local generator writes into, `web` when absent. Refused when
133
+ * it is no single directory name, when the generator registers in `apps/web` (the run without the
134
+ * flag is the fix), and when `apps/<app>` is not there (`x g app <app>` makes it).
135
+ */
136
+ export function readApp(
137
+ raw: string | undefined,
138
+ root: string,
139
+ kind: Generator,
140
+ name: string,
141
+ ): string {
142
+ if (raw === undefined || raw === DEFAULT_APP) return DEFAULT_APP;
143
+ const without = `x g ${kind} ${quoteArg(name)}`;
144
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(raw)) {
145
+ throw new BadFlagError({
146
+ flag: 'app',
147
+ command: `g ${kind}`,
148
+ reason: `"${raw}" is not an app directory name (a-z, 0-9, -) under apps/`,
149
+ fix: without,
150
+ });
151
+ }
152
+ if (!APP_LOCAL.has(kind)) {
153
+ throw new BadFlagError({
154
+ flag: 'app',
155
+ command: `g ${kind}`,
156
+ reason: `a ${kind} registers in files only apps/${DEFAULT_APP} holds (the API index, the roles, the exercise file, the db handle); --app takes ${[...APP_LOCAL].join(', ')}`,
157
+ fix: without,
158
+ });
159
+ }
160
+ if (!existsSync(join(root, WORKSPACE_DIR.app, raw))) {
161
+ throw new BadFlagError({
162
+ flag: 'app',
163
+ command: `g ${kind}`,
164
+ reason: `apps/${raw}/ does not exist`,
165
+ fix: `x g app ${quoteArg(raw)}`,
166
+ });
167
+ }
168
+ return raw;
169
+ }
@@ -5,8 +5,8 @@
5
5
 
6
6
  // why: `resolve`/`sep` and not `join`: only resolving the assembled path can prove it stayed
7
7
  // inside the app root, and `node:path` is the only API that resolves one. `node:fs` for the exists
8
- // check.
9
- import { existsSync } from 'node:fs';
8
+ // check, and the synchronous read a `replaces-pristine` file is compared through.
9
+ import { existsSync, readFileSync } from 'node:fs';
10
10
  import { dirname, join, resolve, sep } from 'node:path';
11
11
  import { ERROR_DOCS_URL } from '@ultimat3/core';
12
12
  import { commentSafe } from './comment-safe';
@@ -212,6 +212,12 @@ function planFile(
212
212
  ? { kind: 'skip' }
213
213
  : { kind: 'write', file, absolute, contents: file.contents };
214
214
  }
215
+ // The scaffold's own copy, untouched, is replaced without asking; an edited one is the author's.
216
+ if (file.merge === 'replaces-pristine' && existsSync(absolute)) {
217
+ if (readFileSync(absolute, 'utf8') === file.pristine) {
218
+ return { kind: 'write', file, absolute, contents: file.contents };
219
+ }
220
+ }
215
221
  if (!force && existsSync(absolute)) {
216
222
  return {
217
223
  kind: 'conflict',
package/src/hold.ts CHANGED
@@ -4,7 +4,9 @@
4
4
  // in-flight, close) instead of killing a query mid-round-trip.
5
5
 
6
6
  import {
7
+ DRAIN_TIMEOUT_EXIT_CODE,
7
8
  drain,
9
+ drainExitCode,
8
10
  installSignalHandlers,
9
11
  isDraining,
10
12
  isUltimateError,
@@ -15,7 +17,8 @@ import {
15
17
 
16
18
  export interface HoldOptions {
17
19
  /**
18
- * What to call once the release is done, with `0`. Omit and nothing is called.
20
+ * What to call once the release is done, with the exit code: `0`, or `DRAIN_TIMEOUT_EXIT_CODE`
21
+ * (70) when the drain or the release abandoned work. Omit and nothing is called.
19
22
  *
20
23
  * There is exactly one caller: `runRole` in `serve.ts`, which is what `apps/web/server.ts`
21
24
  * awaits — the one entry point with nothing above it to end the process. `bin.ts` ends in
@@ -94,8 +97,14 @@ function armHold(name: string, release: () => Promise<void>, options: HoldOption
94
97
  await drain();
95
98
  unregister();
96
99
  uninstall();
97
- await releaseWithin(name, release, releaseBudgetMs(deadlineAt - systemClock.monotonic()));
98
- options.exit?.(0);
100
+ const released = await releaseWithin(
101
+ name,
102
+ release,
103
+ releaseBudgetMs(deadlineAt - systemClock.monotonic()),
104
+ );
105
+ // 70, never 0, when the drain or this release abandoned work: the exit code is the
106
+ // platform's only record that a write may be half done (core's `drainExitCode`).
107
+ options.exit?.(released ? drainExitCode() : DRAIN_TIMEOUT_EXIT_CODE);
99
108
  })();
100
109
  return held;
101
110
  };
@@ -139,7 +148,7 @@ export async function holdWhileBooting<T extends { stop(): Promise<void> }>(
139
148
  } catch (error) {
140
149
  // A boot that failed BECAUSE a drain began under it — a rollout superseding a pod still
141
150
  // booting, whose server then met `markReady()`'s `X_LIFECYCLE_DRAINED` — is a pod doing what
142
- // it was told: finish the drain, say so once at info, exit 0. It printed a stack trace and
151
+ // it was told: finish the drain, say so once at info, exit `drainExitCode()`. It printed a stack trace and
143
152
  // exited non-zero, twice a week in production, paging on a normal rollout. A failure with no
144
153
  // drain under way is still the boot's own refusal, rethrown untouched.
145
154
  if (isDraining() && options.exit !== undefined) {
@@ -149,7 +158,8 @@ export async function holdWhileBooting<T extends { stop(): Promise<void> }>(
149
158
  name,
150
159
  code: isUltimateError(error) ? error.code : 'uncoded',
151
160
  });
152
- options.exit(0);
161
+ // The drain's own answer, never a literal 0: 70 when it abandoned work at its deadline.
162
+ options.exit(drainExitCode());
153
163
  } else {
154
164
  armed.disarm();
155
165
  }
@@ -193,7 +203,7 @@ export const releaseBudgetMs = (remainingMs: number): number =>
193
203
  Number.isFinite(remainingMs) ? Math.max(MIN_RELEASE_MS, remainingMs) : MIN_RELEASE_MS;
194
204
 
195
205
  /**
196
- * `release()` raced against its own budget.
206
+ * `release()` raced against its own budget: `true` when it finished, `false` when abandoned.
197
207
  *
198
208
  * A local race and not core's `settleWithin`, which is internal to `lifecycle-deadline.ts` and not
199
209
  * on core's barrel. The semantics are deliberately the same, including the one that matters: a
@@ -204,7 +214,7 @@ async function releaseWithin(
204
214
  name: string,
205
215
  release: () => Promise<void>,
206
216
  budgetMs: number,
207
- ): Promise<void> {
217
+ ): Promise<boolean> {
208
218
  // Screened by `releaseBudgetMs`, which is the one answer to "how long does a teardown get" —
209
219
  // a second `Math.max` here would be a second, quieter one.
210
220
  let timer: ReturnType<typeof setTimeout> | undefined;
@@ -213,7 +223,7 @@ async function releaseWithin(
213
223
  });
214
224
  try {
215
225
  const outcome = await Promise.race([release().then(() => 'released' as const), abandoned]);
216
- if (outcome === 'released') return;
226
+ if (outcome === 'released') return true;
217
227
  logger.warn('X_SHUTDOWN_TIMEOUT', {
218
228
  code: 'X_SHUTDOWN_TIMEOUT',
219
229
  // Rounded: `deadlineAt - monotonic()` is a float, and `4923.185900000001ms` in a shutdown
@@ -221,6 +231,7 @@ async function releaseWithin(
221
231
  cause: `the "${name}" release was still running ${Math.round(budgetMs)}ms after the drain finished and has been ABANDONED — the process exits without it, so anything it held may not be closed`,
222
232
  fix: 'raise the budget past the slowest teardown — configureLifecycle({ deadlineMs: 600_000 }) for a 10-minute one — and set terminationGracePeriodSeconds to at least as many seconds',
223
233
  });
234
+ return false;
224
235
  } finally {
225
236
  if (timer !== undefined) clearTimeout(timer);
226
237
  }
@@ -1,7 +1,7 @@
1
1
  // The two halves of an image build that are this framework's. On the host, `x build --target
2
2
  // docker` stamps the image with the manifest's build id. INSIDE the image build, `x build --target
3
- // prebuilt` writes what every web pod would otherwise make on every boot: the island chunks and
4
- // the compiled stylesheets (`serve-prebuilt-paths.ts` names the store and why it is where it is).
3
+ // prebuilt` writes what every web pod would otherwise make on every boot: the island chunks, the
4
+ // compiled stylesheets and the module registry (`serve-prebuilt-paths.ts` names the store).
5
5
 
6
6
  // why: Bun ships no recursive remove; a previous store must not survive beside the new one.
7
7
  import { rm } from 'node:fs/promises';
@@ -10,6 +10,7 @@ import { join } from 'node:path';
10
10
  import { sassCompilations, setSassCacheDir } from '@ultimat3/render/server';
11
11
  import { scanAppModules } from './app-load';
12
12
  import { appManifest } from './app-manifest';
13
+ import { prebuildRegistry } from './build-registry';
13
14
  import { buildIslands } from './island-bundle';
14
15
  import { writeIslandStore } from './island-store';
15
16
  import type { Finding } from './output';
@@ -46,6 +47,9 @@ export async function prebuildImage(root: string): Promise<PrebuiltImage> {
46
47
  setSassCacheDir(join(root, PREBUILT_SASS_DIR));
47
48
  const compiled = sassCompilations();
48
49
  const scan = await scanAppModules(root, { track: false });
50
+ // What a serving role imports instead of scanning (`app-load-prebuilt.ts`) — none over a load
51
+ // with a finding, so that boot scans and refuses with the module's own cause.
52
+ await prebuildRegistry(root, scan);
49
53
  const bundle = await buildIslands(root);
50
54
  await writeIslandStore(root, bundle);
51
55
  return {
package/src/index.ts CHANGED
@@ -21,14 +21,13 @@ export { appManifest, writeAppManifest } from './app-manifest';
21
21
  export { requireAppRoot } from './app-root';
22
22
  export type { RouteStats } from './budgets';
23
23
  export { checkBudgets, FRAMEWORK_INLINE_SCRIPTS, FRAMEWORK_SCRIPTS } from './budgets';
24
- export { BUILD_ENTRY, BUILD_TARGETS, BuildEntryMissingError, readTarget } from './cmd-build';
24
+ export { BUILD_ENTRY, BUILD_TARGETS, readTarget } from './cmd-build';
25
25
  export { dbCommand } from './cmd-db';
26
26
  export { planDeploy } from './cmd-deploy';
27
27
  export { startDev } from './cmd-dev';
28
28
  export type { DoctorProbe } from './cmd-doctor';
29
29
  export type { GenerateOptions, Generator } from './cmd-generate';
30
30
  export { GENERATORS, generate, writeFiles } from './cmd-generate';
31
- export { JOBS_SUBCOMMANDS } from './cmd-jobs';
32
31
  export { newCommand, planNewApp, writeNewApp } from './cmd-new';
33
32
  export { PLANNED_COMMANDS, PLANNED_SUBCOMMANDS, plannedSubcommand } from './cmd-planned';
34
33
  export { runVerify, VERIFY_STEPS, verifyCommand, verifyStepNames } from './cmd-verify';
@@ -44,7 +43,7 @@ export { generateAppMigration } from './db-generate';
44
43
  export { SCHEMA_DUMP_DIR } from './db-schema-dump';
45
44
  export type { SchemaDumpRefresh } from './db-schema-refresh';
46
45
  export { refreshSchemaDump } from './db-schema-refresh';
47
- export { QuerySubscribesUnknownError, replicaIdentityTables } from './db-subscribes';
46
+ export { replicaIdentityTables } from './db-subscribes';
48
47
  export { dispatch } from './dispatch';
49
48
  export { checkSourceDrift, reconcileSchemaHash, writeSchemaHash } from './drift';
50
49
  export { registeredErrorCodes } from './error-catalog';
@@ -58,25 +57,14 @@ export {
58
57
  collectDeclaredCodes,
59
58
  documentedCodes,
60
59
  fixProblem,
61
- staticFix,
62
60
  } from './error-contract';
63
61
  export { checkErrorCodesThrown } from './error-unthrown';
64
62
  export {
65
63
  BadFlagError,
66
- BunVersionError,
67
- CatalogExistsError,
68
- DeclarationUnknownError,
69
- ErrorCodeUnknownError,
70
- FixTargetUnknownError,
71
- JobUnknownError,
72
64
  MissingPositionalError,
73
65
  MissingSubcommandError,
74
- NoTestFilesError,
75
- NotInAppError,
76
66
  PortInvalidError,
77
- RoleUnknownError,
78
67
  UnknownCommandError,
79
- VerifyFailedError,
80
68
  } from './errors';
81
69
  export type { ExecOptions, ExecResult, Runner } from './exec';
82
70
  export { exec, execOutput } from './exec';
@@ -123,7 +111,7 @@ export type { PrerenderedPage, PrerenderReport } from './prerender';
123
111
  export { DEFAULT_ORIGIN, isPrerenderable, prerenderSite } from './prerender';
124
112
  export type { PwaArtifacts } from './pwa-artifacts';
125
113
  export { loadPwaArtifacts } from './pwa-artifacts';
126
- export { COMMANDS, cliVersion, SPECS } from './registry';
114
+ export { cliVersion, SPECS } from './registry';
127
115
  export type { RunningRoles, WebBinding } from './role-start';
128
116
  export { DEV_BINDING, DEV_ROLES, startRoles } from './role-start';
129
117
  // `shotCommand`, `prCommand` and `ciCommand` are deliberately NOT re-exported here. They reach
@@ -160,15 +148,13 @@ export { quoteArg } from './shell-quote';
160
148
  export type { SiteSettings } from './site-config';
161
149
  export { loadSiteSettings, publicOrigin } from './site-config';
162
150
  export type { SiteSeo, SiteSeoOptions, SiteSeoSitemap } from './site-seo';
163
- export { ROBOTS_PATH, SITEMAP_PATH, siteSeo } from './site-seo';
151
+ export { siteSeo } from './site-seo';
164
152
  export { writeSiteSeo } from './site-seo-write';
165
153
  export { eachSourceFile, isGenerated, isTest, SOURCE_GLOBS } from './source-files';
166
154
  export type { SkippedRoute, StaticReport } from './static-report';
167
155
  export { parseStaticReport } from './static-report';
168
156
  export type { MigratedDatabaseOptions } from './test-database';
169
- export { migratedDatabase, migratedTemplate } from './test-database';
170
- export type { HousekeepingOptions, HousekeepingReport } from './test-housekeeping';
171
- export { tidyTestState } from './test-housekeeping';
157
+ export { migratedDatabase } from './test-database';
172
158
  export { filesIn, testArgs } from './test-shards';
173
159
  export { defaultWorkers } from './test-workers';
174
160
  export { scanCodeDeclarations, scanCodeFixSites, scanCodes } from './ts-scan';
@@ -181,7 +167,6 @@ export { VERIFY_STEP_NAMES } from './verify-step';
181
167
  export type { TestType } from './verify-tests';
182
168
  export {
183
169
  checkFileSizes,
184
- checkLockstep,
185
170
  checkPackageShape,
186
171
  LINE_CEILING,
187
172
  PACKAGE_FILES,
@@ -23,6 +23,7 @@
23
23
  import { basename, join, posix, relative, sep } from 'node:path';
24
24
  import { ISLAND_EXTENSION, islandModuleId } from '@ultimat3/render';
25
25
  import { loadAppConfig } from './app-config-load';
26
+ import type { IslandResolve } from './document-options';
26
27
  import { IslandBuildFailedError } from './errors';
27
28
  import { refuseDuplicatedModules } from './island-duplicate-refusal';
28
29
  import { entryMissing, onlyMissing } from './island-entry-missing';
@@ -108,7 +109,7 @@ export interface IslandBundle {
108
109
  * Every island on that page goes through it, so an unbuildable specifier fails the render rather
109
110
  * than emitting a `data-x-entry` no browser can import.
110
111
  */
111
- resolverFor(routeFile: string): (src: string) => string;
112
+ resolverFor(routeFile: string): IslandResolve;
112
113
  /** Every realtime island of THIS app, by file: what a document's page boot and holds are read from. */
113
114
  readonly realtime: ReadonlyMap<string, IslandRealtime>;
114
115
  /** The chunk a URL names — for serving it, and for naming the island a budget finding blames. */
@@ -465,14 +466,17 @@ export function islandBundle(
465
466
  chunks,
466
467
  shared,
467
468
  realtime,
468
- resolverFor(routeFile: string): (src: string) => string {
469
+ resolverFor(routeFile: string): IslandResolve {
469
470
  const dir = posix.dirname(routeFile);
470
- return (src: string): string => {
471
+ const resolve = (src: string): string => {
471
472
  const target = posix.normalize(posix.join(dir, src));
472
473
  const chunk = byFile.get(target);
473
474
  if (chunk === undefined) throw entryMissing(routeFile, src, target, chunks);
474
475
  return chunk.url;
475
476
  };
477
+ // What the document preloads for each island it rendered (`route-islands-preload.ts`).
478
+ const importsOf = (url: string): readonly string[] => byUrl.get(url)?.imports ?? [];
479
+ return Object.assign(resolve, { importsOf });
476
480
  },
477
481
  chunkAt: (url: string): IslandChunk | undefined => byUrl.get(url),
478
482
  assetAt: (url: string): IslandChunk | SharedChunk | undefined =>
@@ -5,10 +5,10 @@
5
5
  // why: no Bun native joins a path; `Bun.write` takes one already joined.
6
6
  import { join } from 'node:path';
7
7
  import { finiteCount } from '@ultimat3/core';
8
+ import { systemClock } from '@ultimat3/core/adapter';
8
9
  import type { IslandShotTarget, IslandViewport } from '@ultimat3/testing';
9
10
  import { islandStatesFile } from '@ultimat3/testing';
10
11
  import type { CaptureClip, ShotDriver, ShotSession } from './browser-launcher-port';
11
- import { systemShotClock } from './cdp-shot-clock';
12
12
  import { ISLAND_HARNESS_PATH } from './island-harness';
13
13
  import { readinessProbe } from './island-harness-script';
14
14
  import { IslandRequestUnstubbedError, IslandUnphotographableError } from './island-shot-errors';
@@ -194,7 +194,7 @@ export async function captureIslandState(
194
194
  session = await driver.open({
195
195
  name: 'x shot --island',
196
196
  rules: { allowHosts: allowHostsFrom(server.url, options.extraHosts) },
197
- clock: systemShotClock,
197
+ clock: systemClock,
198
198
  timeoutMs: options.timeoutMs,
199
199
  ...(options.cookies === undefined || options.cookies.length === 0
200
200
  ? {}
@@ -5,13 +5,13 @@
5
5
 
6
6
  // why: no Bun native takes a path apart; the surface is a segment of an app-root-relative path.
7
7
  import { basename } from 'node:path';
8
+ import { SURFACES } from '@ultimat3/core';
8
9
  import type { IslandDirective, Surface } from '@ultimat3/render';
9
10
  import {
10
11
  emitIslandAttributes,
11
12
  emitIslandProps,
12
13
  hydrateRuntime,
13
14
  islandModuleId,
14
- SURFACES,
15
15
  } from '@ultimat3/render';
16
16
  import type { IslandShotTarget, IslandState } from '@ultimat3/testing';
17
17
  import { harnessScript } from './island-harness-script';
@@ -1,9 +1,10 @@
1
- // The `manifest` step's job half: a job or a task still carrying the positional name `job()` or
2
- // `task()` minted (`anonymous-job-2`) was never handed to `defineApi`. That name is what the queue
3
- // row, `x.manifest.json`, `x jobs show` and every dead-letter trace carry, and it moves whenever the
4
- // import order does — so a retry scheduled under one deploy's name lands on another deploy's job.
1
+ // The `manifest` step's job half: a job or task under the positional name `job()`/`task()` minted
2
+ // (`anonymous-job-2`) was never handed to `defineApi`, and that name — on the queue row, the manifest
3
+ // and every dead-letter trace — moves with the import order (`X_JOB_UNREGISTERED`). And an entity
4
+ // declaring `partitionBy` with no `partitions()` job registered (`X_PARTITIONS_UNMAINTAINED`).
5
5
 
6
- import { registeredJobs, registeredTasks } from '@ultimat3/jobs';
6
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
7
+ import { partitionedEntities, registeredJobs, registeredTasks } from '@ultimat3/jobs';
7
8
  import { loadApp } from './app-load';
8
9
  import type { AppLoader } from './app-permissions';
9
10
  import type { Finding } from './output';
@@ -38,5 +39,41 @@ export async function unregisteredJobFindings(
38
39
  load: AppLoader = loadApp,
39
40
  ): Promise<readonly Finding[]> {
40
41
  if ((await load(root)).findings.length > 0) return [];
41
- return positionalNames().map(unregisteredJobFinding);
42
+ return [
43
+ ...positionalNames().map(unregisteredJobFinding),
44
+ ...unmaintainedPartitionFindings(
45
+ partitionedEntities().map((described) => described.table),
46
+ registeredJobs(),
47
+ ),
48
+ ];
49
+ }
50
+
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
+ /**
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`.
61
+ */
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
+ export function unmaintainedPartitionFindings(
66
+ tables: readonly string[],
67
+ jobs: readonly JobShape[],
68
+ ): readonly Finding[] {
69
+ if (tables.length === 0 || jobs.some(isPartitionsJob)) return [];
70
+ return [
71
+ {
72
+ code: 'X_PARTITIONS_UNMAINTAINED',
73
+ cause: `${[...tables].sort().join(', ')} declare${tables.length === 1 ? 's' : ''} partitionBy and no partitions() job is registered: no partition is created ahead, so the first insert past the last migrated one fails, and retention never drops one`,
74
+ fix: 'x verify --only manifest --json # after exporting partitions() from @ultimat3/jobs in a module listed under jobs in apps/web/api/index.ts, and its .schedule under tasks',
75
+ docs: ERROR_DOCS_URL,
76
+ at: 'apps/web/api/index.ts',
77
+ },
78
+ ];
42
79
  }
@@ -6,8 +6,7 @@ import type { JobDriver } from '@ultimat3/jobs';
6
6
  import { jobDriver } from '@ultimat3/jobs';
7
7
  import type { CommandContext } from './command';
8
8
  import type { CommandResult } from './output';
9
- import { resolveServices } from './runtime-bindings';
10
- import { startQueue } from './runtime-queue';
9
+ import { openAppQueue } from './runtime-boot-ports';
11
10
 
12
11
  /**
13
12
  * `x jobs` needs the app's real driver. Reuse an already-running one first — inside `x dev` or
@@ -23,11 +22,11 @@ export async function withJobDriver(
23
22
  ): Promise<CommandResult> {
24
23
  const ambient = jobDriver();
25
24
  if (ambient !== undefined) return fn(ambient);
26
- const services = resolveServices(root, ctx.env);
27
25
  // The command's own environment on both halves: `resolveServices` reads DATABASE_URL off it, so
28
26
  // a queue that resolved its standby from `process.env` would talk to a pair the same call had
29
- // just decided against.
30
- const queue = await startQueue(services, undefined, ctx.env);
27
+ // just decided against. And the app's `runtime.ts`: its `jobs` port is the queue to inspect, its
28
+ // clock and secret source the ones the app runs on.
29
+ const queue = await openAppQueue(root, ctx.env);
31
30
  try {
32
31
  return await fn(queue.jobs);
33
32
  } finally {