@ultimat3/cli 30.9.0 → 31.1.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 (215) hide show
  1. package/CLAUDE.md +80 -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-base.ts +51 -0
  6. package/src/affected.ts +34 -11
  7. package/src/app-boundaries.ts +88 -9
  8. package/src/app-load-async.ts +133 -0
  9. package/src/app-load-batch.ts +203 -0
  10. package/src/app-load-prebuilt.ts +147 -0
  11. package/src/app-load-register.ts +175 -0
  12. package/src/app-load.ts +143 -175
  13. package/src/app-loader-imports.ts +31 -0
  14. package/src/app-root.ts +13 -0
  15. package/src/app-runtime.ts +5 -1
  16. package/src/boundary-findings.ts +12 -0
  17. package/src/browser-launcher-port.ts +3 -7
  18. package/src/browser-launcher.ts +1 -1
  19. package/src/budgets-scan.ts +8 -0
  20. package/src/budgets.ts +10 -1
  21. package/src/build-registry-background.ts +59 -0
  22. package/src/build-registry.ts +207 -0
  23. package/src/cdp-shot-clock.ts +3 -11
  24. package/src/cdp-shot-driver.ts +3 -2
  25. package/src/cdp-shot-element.ts +3 -2
  26. package/src/cdp-shot-page.ts +2 -2
  27. package/src/cdp-shot-watch.ts +4 -3
  28. package/src/ci-log.ts +76 -13
  29. package/src/cmd-affected-spec.ts +7 -3
  30. package/src/cmd-affected.ts +91 -77
  31. package/src/cmd-auth.ts +3 -3
  32. package/src/cmd-ci.ts +6 -3
  33. package/src/cmd-db-recount.ts +15 -0
  34. package/src/cmd-drill.ts +10 -6
  35. package/src/cmd-exercise.ts +2 -1
  36. package/src/cmd-generate-spec.ts +6 -0
  37. package/src/cmd-generate.ts +22 -4
  38. package/src/cmd-mail.ts +1 -1
  39. package/src/cmd-pr-spec.ts +1 -1
  40. package/src/cmd-pr.ts +72 -1
  41. package/src/cmd-routes.ts +2 -2
  42. package/src/cmd-secrets-spec.ts +4 -1
  43. package/src/cmd-shot.ts +14 -262
  44. package/src/cmd-test-spec.ts +2 -2
  45. package/src/cmd-verify-spec.ts +21 -1
  46. package/src/cmd-verify.ts +16 -4
  47. package/src/coverage-source.ts +4 -1
  48. package/src/db-diagnostics.ts +8 -1
  49. package/src/dev-boot.ts +29 -15
  50. package/src/dev-dashboard-invalidations.ts +43 -0
  51. package/src/dev-dashboard.ts +13 -16
  52. package/src/dev-n-plus-one.ts +7 -3
  53. package/src/dev-rebuild.ts +2 -1
  54. package/src/dev-route-table.ts +1 -1
  55. package/src/dev-traces.ts +16 -15
  56. package/src/document-options.ts +12 -1
  57. package/src/drift-store.ts +55 -0
  58. package/src/error-catalog.ts +8 -3
  59. package/src/error-codes-boundary.ts +32 -0
  60. package/src/error-codes-package.ts +38 -0
  61. package/src/error-codes.ts +28 -40
  62. package/src/errors.ts +17 -7
  63. package/src/exercise-database.ts +13 -1
  64. package/src/exercise-findings.ts +36 -18
  65. package/src/exercise-services.ts +84 -0
  66. package/src/exercise-subject.ts +38 -13
  67. package/src/failure-capture-boot.ts +9 -5
  68. package/src/framework-schema.ts +5 -5
  69. package/src/generate-exercise.ts +1 -1
  70. package/src/generate-files.ts +27 -7
  71. package/src/generate-kinds.ts +5 -0
  72. package/src/generate-refresh.ts +53 -0
  73. package/src/generate-workspace.ts +169 -0
  74. package/src/generate-write.ts +8 -2
  75. package/src/hold.ts +19 -8
  76. package/src/image-prepare.ts +6 -2
  77. package/src/index.ts +5 -20
  78. package/src/island-bundle.ts +7 -3
  79. package/src/island-capture.ts +2 -2
  80. package/src/island-harness.ts +1 -1
  81. package/src/job-registration.ts +43 -6
  82. package/src/jobs-driver.ts +4 -5
  83. package/src/mcp-errors.ts +20 -4
  84. package/src/mcp-host.ts +5 -1
  85. package/src/mcp-ui-interact.ts +3 -0
  86. package/src/messages-gate.ts +10 -0
  87. package/src/new-shapes-generate.ts +1 -1
  88. package/src/otlp-export.ts +94 -29
  89. package/src/output.ts +24 -10
  90. package/src/page-sync.ts +3 -1
  91. package/src/pr-activity.ts +150 -0
  92. package/src/pr-bots.ts +109 -0
  93. package/src/pr-threads.ts +7 -2
  94. package/src/role-load.ts +17 -11
  95. package/src/role-start.ts +5 -4
  96. package/src/role-sync.ts +7 -8
  97. package/src/route-islands-preload.ts +46 -0
  98. package/src/route-islands.ts +6 -2
  99. package/src/runtime-admin.ts +5 -1
  100. package/src/runtime-bindings.ts +25 -19
  101. package/src/runtime-boot-ports.ts +66 -0
  102. package/src/runtime-bus.ts +29 -5
  103. package/src/runtime-cache-bus.ts +53 -0
  104. package/src/runtime-cache.ts +43 -13
  105. package/src/runtime-isr-outcome.ts +5 -4
  106. package/src/runtime-jobs.ts +2 -2
  107. package/src/runtime-keys.ts +37 -0
  108. package/src/runtime-overrides.ts +148 -42
  109. package/src/runtime-port-bindings-queue.ts +36 -0
  110. package/src/runtime-port-bindings.ts +117 -0
  111. package/src/runtime-ports.ts +164 -0
  112. package/src/runtime-purge.ts +41 -28
  113. package/src/runtime-push.ts +7 -3
  114. package/src/runtime-queue.ts +70 -55
  115. package/src/runtime-realtime.ts +5 -5
  116. package/src/runtime-render-document.ts +4 -1
  117. package/src/runtime-services.ts +110 -158
  118. package/src/runtime-storage-boot.ts +111 -0
  119. package/src/runtime-storage-upload.ts +9 -7
  120. package/src/runtime-storage.ts +7 -1
  121. package/src/serve-boot.ts +8 -4
  122. package/src/serve-entry.ts +3 -0
  123. package/src/serve-env.ts +47 -14
  124. package/src/serve-prebuilt-paths.ts +3 -0
  125. package/src/serve-prebuilt.ts +15 -4
  126. package/src/serve.ts +2 -2
  127. package/src/shot-gpu.ts +61 -0
  128. package/src/shot-route.ts +95 -0
  129. package/src/shot-run.ts +189 -0
  130. package/src/shot-verdict.ts +5 -0
  131. package/src/static-cards.ts +3 -2
  132. package/src/static-report.ts +2 -2
  133. package/src/style-bundle.ts +1 -1
  134. package/src/sync-authenticator.ts +17 -18
  135. package/src/templates/action-tests.ts +4 -4
  136. package/src/templates/backfill.ts +5 -8
  137. package/src/templates/entity.ts +3 -0
  138. package/src/templates/github/ci.yml.ts +3 -1
  139. package/src/templates/github/dependabot.yml.ts +73 -0
  140. package/src/templates/job.ts +13 -22
  141. package/src/templates/naming.ts +20 -1
  142. package/src/templates/pinned/docker-compose.yml +1 -1
  143. package/src/templates/query.ts +7 -8
  144. package/src/templates/route.ts +5 -3
  145. package/src/templates/scaffold-api.ts +1 -1
  146. package/src/templates/scaffold-auth.ts +5 -3
  147. package/src/templates/scaffold-claude-commands.ts +6 -3
  148. package/src/templates/scaffold-claude.ts +4 -4
  149. package/src/templates/scaffold-container-compose.ts +2 -4
  150. package/src/templates/scaffold-domain-package.ts +1 -1
  151. package/src/templates/scaffold-entries.ts +6 -1
  152. package/src/templates/scaffold-helm-fences.ts +3 -2
  153. package/src/templates/scaffold-helm.ts +35 -6
  154. package/src/templates/scaffold-repo.ts +47 -135
  155. package/src/templates/scaffold-runtime-ports.ts +62 -0
  156. package/src/templates/scaffold-verify-floor.ts +97 -0
  157. package/src/templates/shapes/overlay.ts +1 -1
  158. package/src/templates/sign-in-oidc.ts +5 -3
  159. package/src/templates/sign-in-shared.ts +28 -10
  160. package/src/templates/workspace.ts +75 -0
  161. package/src/test-ignores.ts +5 -2
  162. package/src/test-select.ts +4 -1
  163. package/src/tsconfig-aliases.ts +85 -0
  164. package/src/upgrade-gate.ts +30 -5
  165. package/src/upgrade-report.ts +7 -1
  166. package/src/verify-changed-facts.ts +53 -0
  167. package/src/verify-changed-scope.ts +162 -0
  168. package/src/verify-changed.ts +174 -0
  169. package/src/verify-checks.ts +33 -19
  170. package/src/verify-drift-owner.ts +30 -0
  171. package/src/verify-e2e.ts +2 -1
  172. package/src/verify-factories.ts +86 -0
  173. package/src/verify-run.ts +13 -11
  174. package/src/verify-step.ts +13 -0
  175. package/src/verify-tests.ts +58 -6
  176. package/src/workspace-external-deps.ts +164 -0
  177. package/src/write-line.ts +21 -6
  178. package/wiki/Actions.md +2 -2
  179. package/wiki/Adapters.md +400 -0
  180. package/wiki/Admin-Dashboard.md +1 -1
  181. package/wiki/Agents.md +9 -9
  182. package/wiki/Auth.md +78 -2
  183. package/wiki/Building-Your-Own-Base.md +1 -1
  184. package/wiki/CLI-Reference.md +45 -14
  185. package/wiki/Caching-And-Invalidation.md +17 -5
  186. package/wiki/Compared.md +8 -2
  187. package/wiki/Configuration.md +14 -14
  188. package/wiki/Deployment.md +28 -1
  189. package/wiki/Entities-And-Migrations.md +47 -1
  190. package/wiki/FAQ.md +8 -2
  191. package/wiki/Feature-Flags.md +1 -1
  192. package/wiki/Home.md +3 -2
  193. package/wiki/Jobs-And-Workflows.md +107 -6
  194. package/wiki/Known-Gaps.md +4 -3
  195. package/wiki/MCP-And-AI.md +18 -4
  196. package/wiki/Mail.md +14 -5
  197. package/wiki/Migrations-And-Backfills.md +29 -4
  198. package/wiki/Money.md +2 -0
  199. package/wiki/N-Plus-One-Detection.md +24 -22
  200. package/wiki/Notify.md +28 -4
  201. package/wiki/Observability.md +121 -15
  202. package/wiki/Queries-And-Live-Queries.md +2 -2
  203. package/wiki/Realtime.md +9 -4
  204. package/wiki/Routes-And-Render-Modes.md +5 -0
  205. package/wiki/Scraping.md +57 -11
  206. package/wiki/Shapes.md +2 -2
  207. package/wiki/Stability.md +7 -5
  208. package/wiki/Storage-And-Uploads.md +56 -4
  209. package/wiki/Testing.md +65 -52
  210. package/wiki/Troubleshooting.md +1 -1
  211. package/wiki/Tutorial-01-First-App.md +1 -1
  212. package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
  213. package/wiki/Tutorial-05-Deploy-Free.md +1 -1
  214. package/wiki/Tutorial-06-Growing-Up.md +8 -8
  215. package/wiki/Upgrading.md +136 -5
@@ -0,0 +1,175 @@
1
+ // Registering one imported app module, once per process: its route, its actions, its queries, and
2
+ // — for a process that rescans — its pin in the reload graph. The scan (`app-load.ts`) and the
3
+ // prebuilt registry's boot (`app-load-prebuilt.ts`) both register through here, so a module
4
+ // registers the same way whichever of them imported it.
5
+
6
+ import { isAction, isMutator } from '@ultimat3/action';
7
+ import { registerActions } from '@ultimat3/action/loader';
8
+ import { getEntity } from '@ultimat3/entity';
9
+ import { isJobHandle, isTaskHandle } from '@ultimat3/jobs';
10
+ import { isQuery } from '@ultimat3/query';
11
+ import { registerQueries } from '@ultimat3/query/loader';
12
+ import type { RouteConfig } from '@ultimat3/render';
13
+ import { isRouteConfig, pageComponentOf, registerRoute } from '@ultimat3/render';
14
+ import { pinModule, resetReloadGraph } from './app-reload-graph';
15
+ import { API_INDEX } from './app-root';
16
+ import type { Finding } from './output';
17
+ import { findingFrom } from './output';
18
+
19
+ // A module is imported and registered once per PROCESS: `import()` caches, and a registry rejects
20
+ // a second registration of a name. So a rescan refreshes the facts DERIVED from the registries —
21
+ // the manifest and its build id — and, for exactly one kind of module, the registration itself. A
22
+ // rescan first evicts every changed module, and everything that imports it, from Bun's registry
23
+ // (`app-reload-graph.ts`), so the scan's own `import()` evaluates the new chain; a ROUTE module
24
+ // that comes back as a different instance has its entry replaced. A module that defines a
25
+ // primitive (an action, a query, an entity, a job, a task) is pinned instead — its exports are held
26
+ // by every importer and a second instance would be a duplicate name in its registry — so those
27
+ // edits still need a restart. Until 2026-09-27 only the route module itself was re-imported, under
28
+ // `?x-reload=<hash>`, and every component it imports stayed the cached one: `x dev` logged
29
+ // "reloaded" and served the old component.
30
+ const registered = new Set<string>();
31
+ // A registration failure is sticky: the file is never retried, so the finding is replayed.
32
+ const failures = new Map<string, Finding>();
33
+ // Route modules only: the module instance each one registered from. A rescan that imports the same
34
+ // instance registers nothing; a different one (the file or something it imports was evicted) is
35
+ // the page the author saved.
36
+ const routeModules = new Map<string, Record<string, unknown>>();
37
+
38
+ /** Test seam, and what `x dev` would call if it ever restarted the registries in-process. */
39
+ export function resetAppLoad(): void {
40
+ registered.clear();
41
+ failures.clear();
42
+ routeModules.clear();
43
+ resetReloadGraph();
44
+ }
45
+
46
+ /** Whether any module has registered in this process: a scan after one is a rescan. */
47
+ export const registeredAny = (): boolean => registered.size > 0;
48
+
49
+ /** Whether `absolute` has never been through `registerModule` — registered or failed. */
50
+ export const isFirstPass = (absolute: string): boolean =>
51
+ !registered.has(absolute) && !failures.has(absolute);
52
+
53
+ /**
54
+ * Whether `value` is an entity the registry holds — the entry, or the `core` an `entity()` module
55
+ * exports. Asked of the registry by the value's own name, so it is O(1) and never stale: a scan
56
+ * registers module by module while later modules are still evaluating and registering entities,
57
+ * and a set built once (as until 2026-11-09) missed every entity declared after it.
58
+ */
59
+ export function isRegisteredEntity(value: unknown): boolean {
60
+ if (typeof value !== 'object' || value === null) return false;
61
+ const named: unknown = Reflect.get(value, '$name') ?? Reflect.get(value, 'name');
62
+ if (typeof named !== 'string') return false;
63
+ const entry = getEntity(named);
64
+ return entry !== undefined && (entry === value || entry.core === value);
65
+ }
66
+
67
+ /** One module's registration: what `registerModule` needs beyond the module itself. */
68
+ export interface ModuleRegistration {
69
+ readonly absolute: string;
70
+ /** App-root-relative, POSIX. */
71
+ readonly file: string;
72
+ /** A process that rescans: pins primitive-defining modules, re-registers changed routes. */
73
+ readonly track: boolean;
74
+ }
75
+
76
+ /**
77
+ * Registers a module once; every later call replays whatever the first one reported — except for
78
+ * a route module, which a later call re-registers when the import handed back a new instance.
79
+ */
80
+ export function registerModule(
81
+ module: Record<string, unknown>,
82
+ at: ModuleRegistration,
83
+ ): Finding | undefined {
84
+ const { absolute, file, track } = at;
85
+ const previous = failures.get(absolute);
86
+ if (previous !== undefined) return previous;
87
+ if (registered.has(absolute)) return track ? reloadRoute(absolute, file, module) : undefined;
88
+ registered.add(absolute);
89
+ try {
90
+ const config = module['config'];
91
+ const route = isRouteConfig(config) ? config : undefined;
92
+ if (route !== undefined) {
93
+ registerRouteModule(file, module, route);
94
+ routeModules.set(absolute, module);
95
+ }
96
+ // A pin is the reload graph's: it stops an eviction a process that never rescans never runs,
97
+ // and deciding it walks every export of every module against the entity registry.
98
+ if (track && (definesPrimitive(module, route !== undefined) || file === API_INDEX)) {
99
+ pinModule(absolute);
100
+ }
101
+ registerActions(module);
102
+ registerQueries(module);
103
+ return undefined;
104
+ } catch (error) {
105
+ const finding: Finding = { ...findingFrom(error), at: file };
106
+ failures.set(absolute, finding);
107
+ return finding;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * A module whose instance must be the one every importer and every registry holds. A route module
113
+ * may export an action beside its page — it has always been re-imported, and its actions stayed
114
+ * registered from the first instance — so only an entity, a job or a task pins a route.
115
+ */
116
+ function definesPrimitive(module: Record<string, unknown>, route: boolean): boolean {
117
+ const defines = (value: unknown): boolean =>
118
+ isJobHandle(value) ||
119
+ isTaskHandle(value) ||
120
+ (!route && (isAction(value) || isQuery(value) || isMutator(value))) ||
121
+ isRegisteredEntity(value);
122
+ return Object.values(module).some((value) => {
123
+ // A brand check reads a property, and an export may be a proxy whose every read throws until
124
+ // the env is set — examples/dummy's typed client throws X_ENV_MISSING without APP_URL. A value
125
+ // that cannot be asked is not a primitive: every primitive is a plain branded object.
126
+ try {
127
+ return defines(value);
128
+ } catch {
129
+ return false;
130
+ }
131
+ });
132
+ }
133
+
134
+ /** The route half of a registration, and the whole of a re-registration. */
135
+ function registerRouteModule(
136
+ file: string,
137
+ module: Record<string, unknown>,
138
+ config: RouteConfig,
139
+ ): void {
140
+ // The page component comes from the same module as its config, resolved by render's own
141
+ // rule — the CLI does not decide which export is a page any more than it decides what a
142
+ // route is. A module with no component registers without one, and renders a bare shell.
143
+ const component = pageComponentOf(module);
144
+ registerRoute({
145
+ file,
146
+ config,
147
+ ...(component === undefined ? {} : { component }),
148
+ });
149
+ }
150
+
151
+ /**
152
+ * A registered route module, on a rescan: re-registered when the import handed back a different
153
+ * instance — the file or something it imports was evicted — and left alone otherwise. A save that
154
+ * will not import never reaches here (the scan reports it, not sticky), so the last page that did
155
+ * import is the one served meanwhile.
156
+ */
157
+ function reloadRoute(
158
+ absolute: string,
159
+ file: string,
160
+ module: Record<string, unknown>,
161
+ ): Finding | undefined {
162
+ const held = routeModules.get(absolute);
163
+ if (held === undefined || held === module) return undefined;
164
+ try {
165
+ const config = module['config'];
166
+ // A file that stopped being a route is not un-registered — the table has no verb for it, and a
167
+ // deleted file needs a restart either way. Its instance is recorded so the same save is not
168
+ // re-registered on every later tick.
169
+ if (isRouteConfig(config)) registerRouteModule(file, module, config);
170
+ routeModules.set(absolute, module);
171
+ return undefined;
172
+ } catch (error) {
173
+ return { ...findingFrom(error), at: file };
174
+ }
175
+ }
package/src/app-load.ts CHANGED
@@ -5,22 +5,15 @@
5
5
 
6
6
  // Bun ships no `Bun.*` path API: `join`/`resolve` reach the files a scan imports.
7
7
  import { join, resolve } from 'node:path';
8
- import { isAction, isMutator, listActions, registerActions } from '@ultimat3/action';
8
+ import { listActions } from '@ultimat3/action';
9
9
  import { APP_CONFIG_FILE } from '@ultimat3/core';
10
- import { describeEntities, registeredEntities } from '@ultimat3/entity';
10
+ import { describeEntities } from '@ultimat3/entity';
11
11
  import type { AppLocaleSet } from '@ultimat3/i18n/app-catalogs';
12
12
  import { appLocaleSet, UNDECLARED_LOCALES } from '@ultimat3/i18n/app-catalogs';
13
- import { isJobHandle, isTaskHandle, registeredJobs, registeredTasks } from '@ultimat3/jobs';
13
+ import { registeredJobs, registeredTasks } from '@ultimat3/jobs';
14
14
  import type { ErrorCodeFact } from '@ultimat3/manifest';
15
- import { isQuery, listQueries, registerQueries } from '@ultimat3/query';
16
- import type { RouteConfig } from '@ultimat3/render';
17
- import {
18
- isRouteConfig,
19
- pageComponentOf,
20
- registerRoute,
21
- routeEntries,
22
- setAssetResolver,
23
- } from '@ultimat3/render';
15
+ import { listQueries } from '@ultimat3/query';
16
+ import { routeEntries, setAssetResolver } from '@ultimat3/render';
24
17
  // For the SIDE EFFECT, and it is this module's to hold: importing `@ultimat3/render/server`
25
18
  // installs the `.tsx`/`.scss` Bun plugin, a plugin only transforms modules loaded AFTER it, and
26
19
  // every app module below is loaded by the dynamic `import()` in this file. Before the render
@@ -29,14 +22,11 @@ import {
29
22
  // accident one refactor away from compiling every app's `.tsx` to `React.createElement`. The named
30
23
  // import is a value import, so the side effect holds without the bare line it replaced.
31
24
  import { setStylesheetRoot } from '@ultimat3/render/server';
25
+ import { asyncModules } from './app-load-async';
26
+ import { importInOrder } from './app-load-batch';
27
+ import { isFirstPass, registeredAny, registerModule } from './app-load-register';
32
28
  import { unresolvedImportFinding } from './app-load-unresolved';
33
- import {
34
- evictChanged,
35
- pinModule,
36
- resetReloadGraph,
37
- trackModule,
38
- trackStylesheets,
39
- } from './app-reload-graph';
29
+ import { evictChanged, trackModule, trackStylesheets } from './app-reload-graph';
40
30
  import { API_INDEX } from './app-root';
41
31
  import { collectDeclaredCodes } from './error-contract';
42
32
  import type { Finding } from './output';
@@ -104,32 +94,8 @@ export interface LoadedApp {
104
94
  readonly findings: readonly Finding[];
105
95
  }
106
96
 
107
- // A module is imported and registered once per PROCESS: `import()` caches, and a registry rejects
108
- // a second registration of a name. So a rescan refreshes the facts DERIVED from the registries —
109
- // the manifest and its build id — and, for exactly one kind of module, the registration itself. A
110
- // rescan first evicts every changed module, and everything that imports it, from Bun's registry
111
- // (`app-reload-graph.ts`), so the loop's own `import()` evaluates the new chain; a ROUTE module
112
- // that comes back as a different instance has its entry replaced. A module that defines a
113
- // primitive (an action, a query, an entity, a job, a task) is pinned instead — its exports are held
114
- // by every importer and a second instance would be a duplicate name in its registry — so those
115
- // edits still need a restart. Until 2026-09-27 only the route module itself was re-imported, under
116
- // `?x-reload=<hash>`, and every component it imports stayed the cached one: `x dev` logged
117
- // "reloaded" and served the old component.
118
- const registered = new Set<string>();
119
- // A registration failure is sticky: the file is never retried, so the finding is replayed.
120
- const failures = new Map<string, Finding>();
121
- // Route modules only: the module instance each one registered from. A rescan that imports the same
122
- // instance registers nothing; a different one (the file or something it imports was evicted) is
123
- // the page the author saved.
124
- const routeModules = new Map<string, Record<string, unknown>>();
125
-
126
- /** Test seam, and what `x dev` would call if it ever restarted the registries in-process. */
127
- export function resetAppLoad(): void {
128
- registered.clear();
129
- failures.clear();
130
- routeModules.clear();
131
- resetReloadGraph();
132
- }
97
+ // Registration, and the once-per-process state behind it, is `app-load-register.ts`'s.
98
+ export { resetAppLoad } from './app-load-register';
133
99
 
134
100
  /**
135
101
  * One glob's hits in code-unit order of their POSIX spelling — never the host's. Sorted raw, `\`
@@ -197,6 +163,27 @@ export interface ScanOptions {
197
163
  * `loadAppForRole`, which decides what the role imports.
198
164
  */
199
165
  export async function scanAppModules(root: string, options: ScanOptions): Promise<AppScan> {
166
+ prepareAppImport(root);
167
+ // A rescan: whatever changed on disk since the last one, and everything importing it, leaves
168
+ // Bun's module registry before the loop below imports it again.
169
+ const rescan = options.track && registeredAny();
170
+ if (rescan) await evictChanged(root);
171
+ const candidates = (await appModulePaths(root)).filter((absolute) =>
172
+ isScannedModule(root, absolute),
173
+ );
174
+ // `include` is asked before each import, of the process as the PREVIOUS import left it — the
175
+ // role load and the gate's probe both read that state — so a scan that asks it is serial. A
176
+ // rescan is too: it imports what it evicted, and every other module answers from the cache.
177
+ const scan =
178
+ options.include === undefined && !rescan
179
+ ? await scanBatched(root, candidates, options.track)
180
+ : await scanSerial(root, candidates, options);
181
+ scan.files.sort();
182
+ return scan;
183
+ }
184
+
185
+ /** What every import of the app's modules needs first: the scan's, and the prebuilt registry's. */
186
+ export function prepareAppImport(root: string): void {
200
187
  // Before any import: a stylesheet's surface is read below the app root, never off its absolute
201
188
  // path — under the container's `WORKDIR /app` that path's first segment is `app/`, and every
202
189
  // sheet, the site's included, classified as app CSS.
@@ -205,28 +192,115 @@ export async function scanAppModules(root: string, options: ScanOptions): Promis
205
192
  // `x dev`, the container and the static build alike — one install, three processes.
206
193
  const assets = siteAssetTable(root);
207
194
  setAssetResolver((path) => assets.resolve(path).url);
208
- const files: string[] = [];
209
- const findings: Finding[] = [];
210
- // A rescan: whatever changed on disk since the last one, and everything importing it, leaves
211
- // Bun's module registry before the loop below imports it again.
212
- if (options.track && registered.size > 0) await evictChanged(root);
195
+ }
196
+
197
+ /** Mutable while a scan fills it; handed out as an `AppScan`. */
198
+ interface ScanResult {
199
+ readonly files: string[];
200
+ readonly findings: Finding[];
201
+ }
202
+
203
+ /**
204
+ * Whether the scan imports `absolute` at all — the one rule, for the scan, the prebuilt registry
205
+ * and `x g`'s "does this write change the manifest?" (`generate-refresh.ts`).
206
+ */
207
+ export function isScannedModule(root: string, absolute: string): boolean {
208
+ // A SEGMENT, never a substring: an app checked out under
209
+ // `~/dev/node_modules-experiments/myapp` answered `includes('node_modules')` for every
210
+ // file it holds, so this loop imported none of them and the app registered nothing.
211
+ // The ROOT-RELATIVE path is tested, never the absolute one: an app checked out under
212
+ // `~/work/my.test.app` matched `.test.` on every file and loaded none of them.
213
+ const file = posixRelative(root, absolute);
214
+ if (hasPathSegment(absolute, 'node_modules') || isTest(file)) return false;
215
+ return !(
216
+ ENTRY_POINT.test(file) ||
217
+ EXERCISE_FILE.test(file) ||
218
+ CLIENT_ENTRY_POINT.test(file) ||
219
+ STATES_FILE.test(file)
220
+ );
221
+ }
213
222
 
214
- for (const absolute of await appModulePaths(root)) {
215
- // A SEGMENT, never a substring: an app checked out under
216
- // `~/dev/node_modules-experiments/myapp` answered `includes('node_modules')` for every
217
- // file it holds, so this loop imported none of them and the app registered nothing.
218
- // The ROOT-RELATIVE path is tested, never the absolute one: an app checked out under
219
- // `~/work/my.test.app` matched `.test.` on every file and loaded none of them.
223
+ /**
224
+ * Whether the scan would import the file at `path` (app-root-relative) if it existed: one of the
225
+ * scan's globs matches it and `isScannedModule` admits it. For a caller holding a path, not a
226
+ * glob's answer — `x g` asking whether a file it wrote is an app module (`generate-refresh.ts`).
227
+ */
228
+ export function isAppModulePath(root: string, path: string): boolean {
229
+ const file = toPosix(path);
230
+ return (
231
+ APP_GLOBS.some((pattern) => new Bun.Glob(pattern).match(file)) &&
232
+ isScannedModule(root, resolve(root, file))
233
+ );
234
+ }
235
+
236
+ /** Every module the scan would import, in its order — what `x build` writes the registry from. */
237
+ export async function scannedModulePaths(root: string): Promise<readonly string[]> {
238
+ return (await appModulePaths(root)).filter((absolute) => isScannedModule(root, absolute));
239
+ }
240
+
241
+ /** A module that would not import, keyed by its file. */
242
+ const importFinding = (error: unknown, root: string, file: string): Finding =>
243
+ unresolvedImportFinding(error, root) ?? { ...findingFrom(error), at: file };
244
+
245
+ /** Reads at most this many sources at once: a 12k-module app opened 12k descriptors otherwise. */
246
+ const READ_BATCH = 64;
247
+
248
+ /**
249
+ * Every candidate imported in `importInOrder`'s batches and registered as it evaluates — before
250
+ * the next module evaluates, as `scanSerial` does. The sources of a tracked scan are all read
251
+ * BEFORE any import, for the reason `scanSerial` reads each one before its own: what is recorded
252
+ * is bound to the bytes that module was evaluated from.
253
+ */
254
+ async function scanBatched(
255
+ root: string,
256
+ candidates: readonly string[],
257
+ track: boolean,
258
+ ): Promise<ScanResult> {
259
+ if (track) {
260
+ const first = candidates.filter(isFirstPass);
261
+ for (let start = 0; start < first.length; start += READ_BATCH) {
262
+ const batch = first.slice(start, start + READ_BATCH);
263
+ const sources = await Promise.all(batch.map((absolute) => Bun.file(absolute).text()));
264
+ for (const [index, absolute] of batch.entries()) {
265
+ await trackModule(absolute, sources[index] as string, root);
266
+ }
267
+ }
268
+ }
269
+ const registered = new Map<number, Finding>();
270
+ const register = (index: number, module: Record<string, unknown>): void => {
271
+ const absolute = candidates[index] as string;
272
+ const file = posixRelative(root, absolute);
273
+ const finding = registerModule(module, { absolute, file, track });
274
+ if (finding !== undefined) registered.set(index, finding);
275
+ };
276
+ // A module that can suspend is imported on its own, or a sibling would evaluate before it ends.
277
+ const alone = await asyncModules(root, candidates);
278
+ const imported = await importInOrder(candidates, alone, register);
279
+ const result: ScanResult = { files: [], findings: [] };
280
+ for (const [index, absolute] of candidates.entries()) {
220
281
  const file = posixRelative(root, absolute);
221
- if (hasPathSegment(absolute, 'node_modules') || isTest(file)) continue;
222
- if (
223
- ENTRY_POINT.test(file) ||
224
- EXERCISE_FILE.test(file) ||
225
- CLIENT_ENTRY_POINT.test(file) ||
226
- STATES_FILE.test(file)
227
- ) {
282
+ const one = imported[index];
283
+ if (one === undefined) continue;
284
+ if (!one.ok) {
285
+ result.findings.push(importFinding(one.error, root, file));
228
286
  continue;
229
287
  }
288
+ result.files.push(file);
289
+ const finding = registered.get(index);
290
+ if (finding !== undefined) result.findings.push(finding);
291
+ }
292
+ return result;
293
+ }
294
+
295
+ /** One module at a time: `include` asked, the source read, the module imported and registered. */
296
+ async function scanSerial(
297
+ root: string,
298
+ candidates: readonly string[],
299
+ options: ScanOptions,
300
+ ): Promise<ScanResult> {
301
+ const result: ScanResult = { files: [], findings: [] };
302
+ for (const absolute of candidates) {
303
+ const file = posixRelative(root, absolute);
230
304
  if (options.include !== undefined && !(await options.include(absolute))) continue;
231
305
  // The source is read BEFORE the import, on the file's first pass — a rescan of a registered
232
306
  // module reads nothing here. What is recorded is bound to the bytes the module was evaluated
@@ -234,23 +308,21 @@ export async function scanAppModules(root: string, options: ScanOptions): Promis
234
308
  // the two bound V1's component to V2's hash, so the next scan saw nothing to do and served V1
235
309
  // until the save after. Read first, the worst case is one re-import the next tick, of a file
236
310
  // that did change. An untracked scan reads nothing here: no save lands in an image.
237
- const first = !registered.has(absolute) && !failures.has(absolute);
311
+ const first = isFirstPass(absolute);
238
312
  const snapshot = options.track && first ? await Bun.file(absolute).text() : undefined;
239
313
  if (first && snapshot !== undefined) await trackModule(absolute, snapshot, root);
240
314
  let module: Record<string, unknown>;
241
315
  try {
242
316
  module = (await import(absolute)) as Record<string, unknown>;
243
317
  } catch (error) {
244
- findings.push(unresolvedImportFinding(error, root) ?? { ...findingFrom(error), at: file });
318
+ result.findings.push(importFinding(error, root, file));
245
319
  continue;
246
320
  }
247
- files.push(file);
248
- const finding = await register(absolute, file, module, options.track);
249
- if (finding !== undefined) findings.push(finding);
321
+ result.files.push(file);
322
+ const finding = registerModule(module, { absolute, file, track: options.track });
323
+ if (finding !== undefined) result.findings.push(finding);
250
324
  }
251
-
252
- files.sort();
253
- return { files, findings };
325
+ return result;
254
326
  }
255
327
 
256
328
  export async function loadApp(root: string): Promise<LoadedApp> {
@@ -309,110 +381,6 @@ const emptyAppFinding = (root: string): Finding => ({
309
381
  at: APP_CONFIG_FILE,
310
382
  });
311
383
 
312
- /**
313
- * Registers a module once; every later call replays whatever the first one reported — except for
314
- * a route module, which a later call re-registers when the import handed back a new instance.
315
- */
316
- async function register(
317
- absolute: string,
318
- file: string,
319
- module: Record<string, unknown>,
320
- track: boolean,
321
- ): Promise<Finding | undefined> {
322
- const previous = failures.get(absolute);
323
- if (previous !== undefined) return previous;
324
- if (registered.has(absolute)) return track ? reloadRoute(absolute, file, module) : undefined;
325
- registered.add(absolute);
326
- try {
327
- const config = module['config'];
328
- const route = isRouteConfig(config) ? config : undefined;
329
- if (route !== undefined) {
330
- registerRouteModule(file, module, route);
331
- routeModules.set(absolute, module);
332
- }
333
- // A pin is the reload graph's: it stops an eviction a process that never rescans never runs,
334
- // and deciding it walks every export of every module against the entity registry.
335
- if (track && (definesPrimitive(module, route !== undefined) || file === API_INDEX)) {
336
- pinModule(absolute);
337
- }
338
- registerActions(module);
339
- registerQueries(module);
340
- return undefined;
341
- } catch (error) {
342
- const finding: Finding = { ...findingFrom(error), at: file };
343
- failures.set(absolute, finding);
344
- return finding;
345
- }
346
- }
347
-
348
- /**
349
- * A module whose instance must be the one every importer and every registry holds. A route module
350
- * may export an action beside its page — it has always been re-imported, and its actions stayed
351
- * registered from the first instance — so only an entity, a job or a task pins a route.
352
- */
353
- function definesPrimitive(module: Record<string, unknown>, route: boolean): boolean {
354
- // The registry holds an entry per entity; the value a module exports is the entry's `core`.
355
- const entities = new Set<unknown>(registeredEntities().flatMap((entry) => [entry, entry.core]));
356
- const defines = (value: unknown): boolean =>
357
- entities.has(value) ||
358
- isJobHandle(value) ||
359
- isTaskHandle(value) ||
360
- (!route && (isAction(value) || isQuery(value) || isMutator(value)));
361
- return Object.values(module).some((value) => {
362
- // A brand check reads a property, and an export may be a proxy whose every read throws until
363
- // the env is set — examples/dummy's typed client throws X_ENV_MISSING without APP_URL. A value
364
- // that cannot be asked is not a primitive: every primitive is a plain branded object.
365
- try {
366
- return defines(value);
367
- } catch {
368
- return false;
369
- }
370
- });
371
- }
372
-
373
- /** The route half of a registration, and the whole of a re-registration. */
374
- function registerRouteModule(
375
- file: string,
376
- module: Record<string, unknown>,
377
- config: RouteConfig,
378
- ): void {
379
- // The page component comes from the same module as its config, resolved by render's own
380
- // rule — the CLI does not decide which export is a page any more than it decides what a
381
- // route is. A module with no component registers without one, and renders a bare shell.
382
- const component = pageComponentOf(module);
383
- registerRoute({
384
- file,
385
- config,
386
- ...(component === undefined ? {} : { component }),
387
- });
388
- }
389
-
390
- /**
391
- * A registered route module, on a rescan: re-registered when the import handed back a different
392
- * instance — the file or something it imports was evicted — and left alone otherwise. A save that
393
- * will not import never reaches here (the loop reports it, not sticky), so the last page that did
394
- * import is the one served meanwhile.
395
- */
396
- function reloadRoute(
397
- absolute: string,
398
- file: string,
399
- module: Record<string, unknown>,
400
- ): Finding | undefined {
401
- const held = routeModules.get(absolute);
402
- if (held === undefined || held === module) return undefined;
403
- try {
404
- const config = module['config'];
405
- // A file that stopped being a route is not un-registered — the table has no verb for it, and a
406
- // deleted file needs a restart either way. Its instance is recorded so the same save is not
407
- // re-registered on every later tick.
408
- if (isRouteConfig(config)) registerRouteModule(file, module, config);
409
- routeModules.set(absolute, module);
410
- return undefined;
411
- } catch (error) {
412
- return { ...findingFrom(error), at: file };
413
- }
414
- }
415
-
416
384
  /**
417
385
  * `packages/db/src/errors.ts` → `packages/db`; `apps/web/app/posts/errors.ts` → `apps/web` — on
418
386
  * either separator. A manifest written on Windows split a `\`-path on `/`, kept the whole file as
@@ -0,0 +1,31 @@
1
+ // `X_BOUNDARY_LOADER_IMPORT`: an app module importing a registration loader. `defineApi` is an app's
2
+ // one registration path (axiom 1); `@ultimat3/{action,query}/loader` are `x`'s module scan's. The one
3
+ // boundary rule that also reads an app's TESTS — where an agent reaches for the loader first.
4
+
5
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
6
+ import type { SourceFile } from './app-boundaries';
7
+ import { commentSafe } from './comment-safe';
8
+ import { scanRuntimeImports } from './import-scan';
9
+ import type { Finding } from './output';
10
+
11
+ const LOADER_SUBPATH = /^@ultimat3\/(action|query)\/loader$/;
12
+ const LOADER_KEY: Readonly<Record<string, string>> = { action: 'actions', query: 'queries' };
13
+
14
+ /** One finding per loader import in `files`. Pure: runtime imports only, specifiers as written. */
15
+ export function loaderImportFindings(files: readonly SourceFile[]): readonly Finding[] {
16
+ const findings: Finding[] = [];
17
+ for (const file of files) {
18
+ for (const specifier of scanRuntimeImports(file)) {
19
+ const loader = LOADER_SUBPATH.exec(specifier)?.[1];
20
+ if (loader === undefined) continue;
21
+ findings.push({
22
+ code: 'X_BOUNDARY_LOADER_IMPORT',
23
+ cause: `an app module imports "${specifier}" — its registration functions are the boot's, and a call here is a second registration path beside defineApi`,
24
+ fix: `export const api = defineApi({ ${LOADER_KEY[loader] ?? 'actions'}: [yourModule] }); # in apps/web/api/index.ts — list the module there, then delete the import from ${commentSafe(file.path)}`,
25
+ docs: ERROR_DOCS_URL,
26
+ at: file.path,
27
+ });
28
+ }
29
+ }
30
+ return findings;
31
+ }
package/src/app-root.ts CHANGED
@@ -63,6 +63,7 @@ export function requireAppRoot(command: string, from: string): AppRoot {
63
63
  from: dir,
64
64
  below: appDirsBelow(dir),
65
65
  adopter: dependsOnFramework(dir),
66
+ xScript: hasXScript(dir),
66
67
  });
67
68
  }
68
69
  return root;
@@ -94,6 +95,18 @@ function dependsOnFramework(from: string): boolean {
94
95
  }
95
96
  }
96
97
 
98
+ /** Whether `from`'s manifest declares an `x` script — the framework repo's root does. Never throws. */
99
+ function hasXScript(from: string): boolean {
100
+ try {
101
+ const manifest: unknown = JSON.parse(readFileSync(join(from, 'package.json'), 'utf8'));
102
+ if (typeof manifest !== 'object' || manifest === null || !('scripts' in manifest)) return false;
103
+ const { scripts } = manifest;
104
+ return typeof scripts === 'object' && scripts !== null && 'x' in scripts;
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+
97
110
  /** Semver-lite compare, sufficient because both sides are plain `major.minor.patch`. */
98
111
  export function versionAtLeast(found: string, required: string): boolean {
99
112
  const parse = (input: string): readonly number[] =>
@@ -9,6 +9,7 @@
9
9
  import { existsSync } from 'node:fs';
10
10
  // why: Bun exposes no path-join primitive; each candidate is joined to the app root.
11
11
  import { join } from 'node:path';
12
+ import { assertRuntimeKeys } from './runtime-keys';
12
13
  import type { RuntimeOverrides } from './runtime-overrides';
13
14
 
14
15
  /** The one file an app writes, per app directory. */
@@ -40,7 +41,10 @@ export async function loadAppRuntime(root: string): Promise<RuntimeOverrides | u
40
41
  for (const file of files.sort()) {
41
42
  const module = (await import(join(root, file))) as Record<string, unknown>;
42
43
  const exported = module[APP_RUNTIME_EXPORT];
43
- if (isRecord(exported)) return exported as RuntimeOverrides;
44
+ if (isRecord(exported)) {
45
+ assertRuntimeKeys(file, exported);
46
+ return exported as RuntimeOverrides;
47
+ }
44
48
  }
45
49
  return undefined;
46
50
  }
@@ -3,9 +3,14 @@
3
3
  // was another command to run for the real one (plan 101 slice 11 j). The planner is the same one
4
4
  // `x fix boundary` prints from, so the gate and the command cannot disagree about the cut.
5
5
 
6
+ // why: a synchronous directory probe; Bun.file answers files.
7
+ import { existsSync } from 'node:fs';
8
+ // why: Bun exposes no path-join primitive; the probe takes a joined path.
9
+ import { join } from 'node:path';
6
10
  import type { SourceFile } from './app-boundaries';
7
11
  import { appImportGraph, checkImportRules, readAppSources } from './app-boundaries';
8
12
  import { siblingModuleFindings } from './app-layout';
13
+ import { loaderImportFindings } from './app-loader-imports';
9
14
  import { appTransportFindings } from './app-transport';
10
15
  import { planBoundaryCuts } from './boundary-cuts';
11
16
  import { handRolledSocketFindings } from './hand-rolled-socket';
@@ -52,5 +57,12 @@ export async function appBoundaryFindings(
52
57
  ...islandDisposerFindings(files),
53
58
  ...handRolledSocketFindings(files),
54
59
  ...(await packageBoundaryFindings(root)),
60
+ // The one rule an app's tests answer to as well (`app-loader-imports.ts`).
61
+ ...loaderImportFindings(await appTests(root)),
55
62
  ];
56
63
  }
64
+
65
+ /** The app's test files, for the loader rule — none where there is no `apps/` to glob. */
66
+ async function appTests(root: string): Promise<readonly SourceFile[]> {
67
+ return existsSync(join(root, 'apps')) ? readAppSources(root, 'tests') : [];
68
+ }