@ultimat3/cli 31.47.1 → 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 (276) 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 +100 -19
  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 +36 -0
  28. package/src/cmd-heavy.ts +244 -0
  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 +15 -4
  40. package/src/cmd-upgrade-spec.ts +8 -1
  41. package/src/cmd-upgrade.ts +32 -5
  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 +26 -0
  46. package/src/codemods/docs-worker-commands.ts +26 -0
  47. package/src/codemods/index.ts +6 -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-advisory-floors.ts +30 -8
  77. package/src/doctor-api-listing.ts +114 -0
  78. package/src/doctor-guarded.ts +41 -0
  79. package/src/doctor-port.ts +90 -17
  80. package/src/doctor-probe.ts +36 -5
  81. package/src/doctor-processes-probe.ts +127 -0
  82. package/src/doctor-processes.ts +136 -0
  83. package/src/doctor-warnings.ts +17 -0
  84. package/src/error-codes-agents.ts +35 -0
  85. package/src/error-codes-processes.ts +30 -0
  86. package/src/error-codes-tooling.ts +11 -3
  87. package/src/error-codes.ts +12 -13
  88. package/src/errors-suite.ts +27 -0
  89. package/src/errors.ts +18 -22
  90. package/src/exec.ts +11 -3
  91. package/src/exercise-registration.ts +4 -3
  92. package/src/framework-env.ts +7 -3
  93. package/src/generate-files.ts +1 -0
  94. package/src/generate-grant-findings.ts +7 -5
  95. package/src/generate-grants.ts +9 -8
  96. package/src/generate-kinds.ts +30 -6
  97. package/src/generate-roles-file.ts +30 -0
  98. package/src/generate-slice-policy.ts +3 -3
  99. package/src/guards.ts +2 -2
  100. package/src/heavy-cores.ts +51 -0
  101. package/src/heavy-env.ts +21 -0
  102. package/src/heavy-errors.ts +54 -0
  103. package/src/heavy-flock.ts +73 -0
  104. package/src/heavy-holders.ts +78 -0
  105. package/src/heavy-ledger.ts +400 -0
  106. package/src/heavy-memory.ts +67 -0
  107. package/src/heavy-pressure.ts +104 -0
  108. package/src/heavy-weights.ts +47 -0
  109. package/src/heavy.ts +308 -0
  110. package/src/i18n-registration.ts +22 -2
  111. package/src/island-harness.ts +2 -2
  112. package/src/job-budget.ts +4 -2
  113. package/src/job-registration.ts +64 -8
  114. package/src/jobs-queue-known.ts +43 -0
  115. package/src/local-cli.ts +6 -5
  116. package/src/mcp-errors-agents.ts +20 -0
  117. package/src/mcp-errors-doctor.ts +27 -0
  118. package/src/mcp-errors-processes.ts +23 -0
  119. package/src/mcp-errors.ts +18 -29
  120. package/src/mcp-host.ts +2 -2
  121. package/src/merge-driver-catalog.ts +58 -0
  122. package/src/merge-driver-config.ts +43 -0
  123. package/src/merge-driver-lines.ts +140 -0
  124. package/src/merge-state.ts +105 -0
  125. package/src/messages-db.ts +22 -1
  126. package/src/messages-processes.ts +13 -0
  127. package/src/messages-upgrade.ts +6 -0
  128. package/src/messages.ts +62 -1
  129. package/src/output-findings.ts +48 -21
  130. package/src/parse.ts +37 -6
  131. package/src/policy-facts.ts +38 -21
  132. package/src/policy-row.ts +99 -0
  133. package/src/port-pair-free.ts +28 -0
  134. package/src/registry-lines.ts +110 -0
  135. package/src/registry.ts +4 -0
  136. package/src/retain-sweep.ts +1 -1
  137. package/src/role-replicator.ts +9 -4
  138. package/src/role-select.ts +86 -0
  139. package/src/role-start.ts +13 -55
  140. package/src/role-sync.ts +10 -5
  141. package/src/runtime-cache-frame.ts +46 -0
  142. package/src/runtime-cache-ttl.ts +23 -0
  143. package/src/runtime-cache.ts +56 -18
  144. package/src/runtime-database-ssl.ts +84 -0
  145. package/src/runtime-idempotency-scope.ts +16 -2
  146. package/src/runtime-jobs-share.ts +52 -0
  147. package/src/runtime-jobs.ts +43 -12
  148. package/src/runtime-overrides.ts +4 -2
  149. package/src/runtime-queue.ts +18 -3
  150. package/src/runtime-services.ts +8 -1
  151. package/src/schema-drift.ts +19 -2
  152. package/src/schema-dump-drift.ts +4 -1
  153. package/src/serve-boot-probe.ts +30 -2
  154. package/src/serve-boot.ts +11 -1
  155. package/src/serve-env.ts +39 -3
  156. package/src/serve.ts +61 -10
  157. package/src/stop-run-start.ts +12 -0
  158. package/src/supervise-boot.ts +61 -0
  159. package/src/supervise-cgroup.ts +84 -0
  160. package/src/supervise-child.ts +206 -0
  161. package/src/supervise-count.ts +244 -0
  162. package/src/supervise-errors.ts +83 -0
  163. package/src/supervise-facts.ts +40 -0
  164. package/src/supervise-messages.ts +84 -0
  165. package/src/supervise-policy.ts +46 -0
  166. package/src/supervise-pool.ts +10 -0
  167. package/src/supervise-probe.ts +158 -0
  168. package/src/supervise-run.ts +54 -0
  169. package/src/supervise.ts +383 -0
  170. package/src/templates/generate-purge.ts +6 -6
  171. package/src/templates/guard-animated-layout-property.ts +2 -2
  172. package/src/templates/guard-bare-error.ts +1 -1
  173. package/src/templates/guard-error-declared.ts +2 -2
  174. package/src/templates/guard-focus-visible.ts +1 -1
  175. package/src/templates/guard-image-dimensions.ts +2 -2
  176. package/src/templates/guard-island-mount-clears.ts +1 -1
  177. package/src/templates/guard-native-confirm.ts +1 -1
  178. package/src/templates/guard-raw-breakpoint.ts +2 -2
  179. package/src/templates/guard-raw-colour.ts +2 -2
  180. package/src/templates/guard-raw-fetch.ts +1 -1
  181. package/src/templates/guard-raw-interval.ts +1 -1
  182. package/src/templates/guard-raw-length.ts +3 -3
  183. package/src/templates/guard-raw-motion.ts +1 -1
  184. package/src/templates/guard-raw-shadow.ts +1 -1
  185. package/src/templates/guard-raw-z-index.ts +1 -1
  186. package/src/templates/guard-released-forms.ts +59 -13
  187. package/src/templates/guard-repo-await-in-loop.ts +1 -1
  188. package/src/templates/guard-repo-raw-sql.ts +4 -4
  189. package/src/templates/guard-repo-unbounded.ts +1 -1
  190. package/src/templates/guard-runtime-pin.ts +1 -1
  191. package/src/templates/guard-semantic-interactive.ts +2 -2
  192. package/src/templates/guard-unbounded-fanout.ts +1 -1
  193. package/src/templates/guard-undeclared-custom-property.ts +3 -3
  194. package/src/templates/guard-undefined-style-class.ts +3 -3
  195. package/src/templates/guard-unzoned-date.ts +3 -3
  196. package/src/templates/query-slice.ts +82 -0
  197. package/src/templates/query.ts +76 -30
  198. package/src/templates/resource-page.ts +3 -2
  199. package/src/templates/scaffold-bin.ts +2 -0
  200. package/src/templates/scaffold-claude-agents.ts +9 -6
  201. package/src/templates/scaffold-claude-commands.ts +7 -1
  202. package/src/templates/scaffold-claude.ts +4 -4
  203. package/src/templates/scaffold-container-compose.ts +47 -7
  204. package/src/templates/scaffold-docs.ts +11 -6
  205. package/src/templates/scaffold-gitattributes.ts +18 -1
  206. package/src/templates/scaffold-helm-templates.ts +9 -0
  207. package/src/templates/scaffold-repo.ts +4 -1
  208. package/src/templates/scaffold-test-services.ts +33 -11
  209. package/src/templates/shapes/offline.ts +0 -7
  210. package/src/templates/shapes/realtime.ts +2 -6
  211. package/src/templates/sign-in-action-tests.ts +6 -4
  212. package/src/templates/sign-in-challenge.ts +62 -0
  213. package/src/templates/sign-in-oidc-mfa.ts +31 -0
  214. package/src/templates/sign-in-oidc.ts +11 -3
  215. package/src/templates/sign-in-password.ts +18 -56
  216. package/src/test-batches.ts +9 -3
  217. package/src/test-shards.ts +117 -37
  218. package/src/test-slots.ts +35 -161
  219. package/src/test-verdict.ts +79 -0
  220. package/src/test-workers.ts +15 -0
  221. package/src/upgrade-gate-codemods.ts +5 -3
  222. package/src/upgrade-gate.ts +19 -1
  223. package/src/upgrade-merge-drivers.ts +25 -0
  224. package/src/upgrade-report.ts +18 -4
  225. package/src/upgrade-scope.ts +62 -0
  226. package/src/verify-checks.ts +6 -11
  227. package/src/verify-coverage-run.ts +9 -5
  228. package/src/verify-deadline.ts +18 -2
  229. package/src/verify-heavy-steps.ts +26 -0
  230. package/src/verify-live.ts +38 -14
  231. package/src/verify-only.ts +67 -0
  232. package/src/verify-progress.ts +7 -3
  233. package/src/verify-run.ts +20 -2
  234. package/src/verify-services-stack.ts +165 -0
  235. package/src/verify-services.ts +84 -2
  236. package/src/verify-test-run.ts +9 -9
  237. package/src/verify-tests.ts +35 -22
  238. package/src/verify-typecheck.ts +25 -2
  239. package/wiki/Actions.md +2 -1
  240. package/wiki/Admin-Dashboard.md +2 -2
  241. package/wiki/Agents.md +5 -5
  242. package/wiki/Auth.md +15 -5
  243. package/wiki/Bare-VM.md +1 -1
  244. package/wiki/Building-Your-Own-Base.md +15 -2
  245. package/wiki/CI-Parallel-Gate.md +4 -4
  246. package/wiki/CLI-Reference.md +127 -48
  247. package/wiki/Caching-And-Invalidation.md +2 -2
  248. package/wiki/Client-Navigation.md +1 -1
  249. package/wiki/Configuration.md +32 -13
  250. package/wiki/Deployment.md +44 -4
  251. package/wiki/Entities-And-Migrations.md +5 -1
  252. package/wiki/FAQ.md +1 -1
  253. package/wiki/Getting-Started.md +2 -2
  254. package/wiki/Home.md +2 -1
  255. package/wiki/I18n.md +5 -3
  256. package/wiki/Installation.md +12 -11
  257. package/wiki/Interface-Rules.md +1 -1
  258. package/wiki/Jobs-And-Workflows.md +24 -4
  259. package/wiki/Known-Gaps.md +2 -2
  260. package/wiki/MCP-And-AI.md +8 -5
  261. package/wiki/Mail.md +1 -1
  262. package/wiki/Many-Agents.md +127 -0
  263. package/wiki/Migrations-And-Backfills.md +18 -0
  264. package/wiki/Notify.md +1 -1
  265. package/wiki/Observability.md +13 -0
  266. package/wiki/Queries-And-Live-Queries.md +2 -2
  267. package/wiki/Realtime.md +10 -1
  268. package/wiki/Routes-And-Render-Modes.md +1 -1
  269. package/wiki/Scheduled-Tasks.md +4 -1
  270. package/wiki/Testing.md +12 -9
  271. package/wiki/Timezones-And-Dates.md +5 -1
  272. package/wiki/Troubleshooting.md +1 -0
  273. package/wiki/Tutorial-01-First-App.md +5 -5
  274. package/wiki/Tutorial-02-First-Feature.md +1 -1
  275. package/wiki/Tutorial-03-Auth-And-Admin.md +7 -6
  276. package/wiki/Upgrading.md +37 -0
@@ -0,0 +1,104 @@
1
+ // The CPU half of admission: a run that fits in memory still waits while the machine's CPU is
2
+ // saturated and another heavy run is going. The thresholds, their measurement and the decision live
3
+ // here; `heavy-ledger.ts` asks it only for the queue's head, so first-come order is kept.
4
+
5
+ // why: Bun ships no synchronous file read, and `/proc/pressure/cpu` is read on every poll.
6
+ import { readFileSync } from 'node:fs';
7
+ // why: Bun exposes no available-parallelism primitive.
8
+ import { availableParallelism } from 'node:os';
9
+ import { runnableTasks } from './heavy-cores';
10
+ import type { HeavyEnv } from './heavy-env';
11
+ import { HEAVY_CPU_ENV, isCi } from './heavy-env';
12
+ import { msg } from './messages';
13
+
14
+ /**
15
+ * Measured on the 8-core shared box, 2026-11-18, `As of` Linux 7.0: four admitted runs held 14.3 of
16
+ * 15.9 GB while load was 74-94 with 69-84 runnable tasks, and `cpu some avg10` read 95.8. Memory was
17
+ * not the bound; CPU was, and every run on it slowed. `some` is the share of time at least one task
18
+ * waited for a CPU: an 8-core box running one 4-core typecheck stays far below 80, and at 80 most of
19
+ * every second already has a queue. avg10 is the shortest window the kernel keeps. ONE reading; a
20
+ * re-measure that moves it changes only these numbers.
21
+ */
22
+ export const CPU_SOME_BUSY_PERCENT = 80;
23
+ /** No PSI (macOS, older kernels): 69 runnable on 8 cores was 8.6 a core; 2 a core is a run queue. */
24
+ export const RUNNABLE_PER_CORE_BUSY = 2;
25
+ /**
26
+ * How long the queue's head waits on CPU alone before it goes anyway. A holder can run for hours
27
+ * while outside work keeps the CPU busy; this bounds the wait to one admission per window.
28
+ */
29
+ export const CPU_WAIT_LIMIT_MS = 5 * 60_000;
30
+
31
+ export interface CpuReading {
32
+ readonly source: 'psi' | 'runnable';
33
+ /** `cpu some avg10` in percent, or runnable tasks per core. */
34
+ readonly value: number;
35
+ readonly limit: number;
36
+ readonly busy: boolean;
37
+ }
38
+
39
+ /** `some avg10=95.83 …` → 95.83. */
40
+ export function parseCpuSome(text: string): number | undefined {
41
+ const match = /^some avg10=(\d+(?:\.\d+)?)/m.exec(text);
42
+ return match === null ? undefined : Number(match[1]);
43
+ }
44
+
45
+ const readPsi = (): string => readFileSync('/proc/pressure/cpu', 'utf8');
46
+
47
+ /** PSI where the kernel has it, else runnable tasks per core. Never throws. */
48
+ export function readCpuPressure(
49
+ input: { readonly read?: () => string; readonly cores?: number; readonly runnable?: number } = {},
50
+ ): CpuReading {
51
+ let some: number | undefined;
52
+ try {
53
+ some = parseCpuSome((input.read ?? readPsi)());
54
+ } catch {
55
+ some = undefined; // No PSI here.
56
+ }
57
+ if (some !== undefined) {
58
+ return {
59
+ source: 'psi',
60
+ value: some,
61
+ limit: CPU_SOME_BUSY_PERCENT,
62
+ busy: some >= CPU_SOME_BUSY_PERCENT,
63
+ };
64
+ }
65
+ const cores = Math.max(1, input.cores ?? availableParallelism());
66
+ const perCore = Math.round(((input.runnable ?? runnableTasks()) / cores) * 10) / 10;
67
+ return {
68
+ source: 'runnable',
69
+ value: perCore,
70
+ limit: RUNNABLE_PER_CORE_BUSY,
71
+ busy: perCore >= RUNNABLE_PER_CORE_BUSY,
72
+ };
73
+ }
74
+
75
+ /**
76
+ * Whether the head may start on CPU grounds. Never `wait` with nothing admitted: pressure from work
77
+ * outside the ledger must not stop the only run, and a ledger with no holder cannot deadlock.
78
+ */
79
+ export function cpuAdmission(input: {
80
+ readonly reading: CpuReading | undefined;
81
+ /** Reservations admitted now. */
82
+ readonly running: number;
83
+ /** How long the head has waited on CPU alone. */
84
+ readonly blockedMs: number;
85
+ }): 'admit' | 'wait' {
86
+ if (input.reading?.busy !== true || input.running === 0) return 'admit';
87
+ return input.blockedMs >= CPU_WAIT_LIMIT_MS ? 'admit' : 'wait';
88
+ }
89
+
90
+ /**
91
+ * Off in CI (single-tenant), off inside a test run (a fixture must not wait on the machine it runs
92
+ * on; `ambient` is this process's own env), and off with `ULTIMATE_HEAVY_CPU=0`.
93
+ */
94
+ export function cpuGateOn(env: HeavyEnv, ambient: HeavyEnv = Bun.env): boolean {
95
+ if (isCi(env) || env[HEAVY_CPU_ENV] === '0') return false;
96
+ return env['NODE_ENV'] !== 'test' && ambient['NODE_ENV'] !== 'test';
97
+ }
98
+
99
+ /** `CPU pressure 96% (new runs wait at 80%)`. */
100
+ export const cpuText = (reading: CpuReading): string =>
101
+ msg(reading.source === 'psi' ? 'cli.heavy.cpu.psi' : 'cli.heavy.cpu.runnable', {
102
+ value: reading.source === 'psi' ? Math.round(reading.value) : reading.value,
103
+ limit: reading.limit,
104
+ });
@@ -0,0 +1,47 @@
1
+ // What each heavy command reserves: its MEASURED peak, whole process tree, rounded up to 64 MB. A
2
+ // weight is a claim the ledger's bound rests on, so each carries the command that re-reads it, run
3
+ // on a clean `git archive` snapshot through `bun run scripts/heavy-peak.ts -- <command>`.
4
+ // Measured 2026-11-18, 8 cores / 31 GB, Bun 1.4.4, TypeScript 7.0.2, GOMAXPROCS=RAYON_NUM_THREADS=4.
5
+
6
+ import { WORKER_BYTES } from './test-workers';
7
+
8
+ const MIB = 2 ** 20;
9
+
10
+ /** `tsc -b --pretty false` from cold over this repository's 32 projects: 5,973 MB, 120 s. */
11
+ export const TYPECHECK_BUILD_PEAK_MB = 6016;
12
+
13
+ /** `tsc -p . --pretty false --noEmit` in `examples/dummy`, one program: 763 MB, 8 s. */
14
+ export const TYPECHECK_APP_PEAK_MB = 768;
15
+
16
+ /** `-b` walks every project of a monorepo; `-p .` is the one program of a scaffolded app. */
17
+ export const typecheckPeakMb = (argv: readonly string[]): number =>
18
+ argv.includes('-b') ? TYPECHECK_BUILD_PEAK_MB : TYPECHECK_APP_PEAK_MB;
19
+
20
+ /** `biome check .` at this repository's root: 2,072 MB (1,855 in `examples/dummy`). */
21
+ export const LINT_PEAK_MB = 2112;
22
+
23
+ /**
24
+ * One `bun test` worker: the planner's figure (`WORKER_BYTES`, with its table in `test-workers.ts`).
25
+ * Re-read here: `bun test ./packages/core ./packages/schema ./packages/entity ./packages/action`,
26
+ * one process tree, peaked at 1,229 MB.
27
+ */
28
+ export const TEST_WORKER_PEAK_MB = Math.ceil(WORKER_BYTES / MIB);
29
+
30
+ /**
31
+ * What a test run costs beside its workers: the `x` parent and the first database boot. One worker
32
+ * in `examples/dummy` peaked at 1,915 MB (`x test unit --workers 1`) and 1,964 MB with coverage
33
+ * (`ULTIMATE_HEAVY_CORES=1 x verify --only unit`), which is this plus one worker.
34
+ */
35
+ export const TEST_RUN_BASE_MB = 704;
36
+
37
+ /**
38
+ * `x test e2e` in `examples/dummy`, app server and browser: 2,871 MB. That run ended red on the
39
+ * snapshot, so the figure is a floor and this keeps a margin above it.
40
+ */
41
+ export const E2E_LANE_PEAK_MB = 3072;
42
+
43
+ /** At most this many selected files run free: a worker's own files never queue behind a gate. */
44
+ export const FREE_RUN_FILES = 3;
45
+
46
+ /** `x heavy run` with no `--mb`: an unknown command is assumed to cost a whole-repo typecheck. */
47
+ export const DEFAULT_RUN_MB = TYPECHECK_BUILD_PEAK_MB;
package/src/heavy.ts ADDED
@@ -0,0 +1,308 @@
1
+ // Admission to the machine, as the rest of the CLI sees it: whether the ledger applies to this
2
+ // process, and the three ways in. Never a reason for work to fail: a ledger that cannot run is said
3
+ // once on stderr and the command goes ahead.
4
+
5
+ // why: Bun ships no lstat with ownership, and the fixed path below needs one.
6
+ import { lstatSync, mkdirSync, realpathSync } from 'node:fs';
7
+ // why: Bun ships no path-join primitive.
8
+ import { join } from 'node:path';
9
+ import { isUltimateError } from '@ultimat3/core';
10
+ import { coreCap, nativeToolEnv } from './heavy-cores';
11
+ import type { HeavyEnv } from './heavy-env';
12
+ import { HEAVY_DIR_ENV, HEAVY_HOLD_ENV, isCi } from './heavy-env';
13
+ import { HeavyLedgerUnavailableError, HeavyWaitExpiredError } from './heavy-errors';
14
+ import type { TryLock } from './heavy-flock';
15
+ import { flockBinding } from './heavy-flock';
16
+ import type { Held, LedgerEntry, LedgerWait, Reservation } from './heavy-ledger';
17
+ import { isHeld, lockPath, prepareLedger, reserve } from './heavy-ledger';
18
+ import { ledgerCapacityMb } from './heavy-memory';
19
+ import { cpuGateOn, cpuText, readCpuPressure } from './heavy-pressure';
20
+ import { msg } from './messages';
21
+ import { writeErrorLine } from './write-line';
22
+
23
+ export type HeavyOff = 'ci' | 'test-run' | 'disabled' | 'nested' | 'unsupported';
24
+
25
+ export type HeavyState =
26
+ | {
27
+ readonly on: true;
28
+ readonly dir: string;
29
+ readonly capacityMb: number;
30
+ readonly tryLock: TryLock;
31
+ }
32
+ | { readonly on: false; readonly off: HeavyOff; readonly detail?: string };
33
+
34
+ /** One per machine and uid. A FIXED path: `TMPDIR` differs per session, and two ledgers are no bound. */
35
+ export const defaultLedgerDir = (uid: number | undefined = process.getuid?.()): string =>
36
+ `/tmp/ultimate-heavy-${String(uid ?? 0)}`;
37
+
38
+ /** `/tmp` is world-writable: refuse a directory someone else planted at our fixed path. */
39
+ function requireOwnDir(dir: string): void {
40
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
41
+ const stat = lstatSync(dir);
42
+ if (!stat.isDirectory() || (process.getuid !== undefined && stat.uid !== process.getuid())) {
43
+ throw new HeavyLedgerUnavailableError(`${dir} is not a directory this user owns`);
44
+ }
45
+ prepareLedger(dir);
46
+ }
47
+
48
+ const said = new Set<string>();
49
+ const warnOnce = (line: string): void => {
50
+ if (said.has(line)) return;
51
+ said.add(line);
52
+ writeErrorLine(line);
53
+ };
54
+
55
+ const describe = (error: unknown): string =>
56
+ isUltimateError(error)
57
+ ? `${error.code}: ${error.cause}\n fix: ${error.fix}`
58
+ : new HeavyLedgerUnavailableError(error instanceof Error ? error.message : 'unknown').message;
59
+
60
+ /** Whether admission applies here. Throws only coded errors; `admission` turns them into a line. */
61
+ export async function heavyState(env: HeavyEnv): Promise<HeavyState> {
62
+ if (isCi(env)) return { on: false, off: 'ci' };
63
+ const explicitDir = env[HEAVY_DIR_ENV];
64
+ // A fixture's `x test` runs inside `bun test`, whose NODE_ENV every child inherits: queueing it
65
+ // behind real work would turn a test's timeout into a machine-load verdict. `Bun.env` as well: a
66
+ // fixture calling in-process with its own small env is just as much inside the test run, and a
67
+ // timed-out one left its ticket at the head of the machine's queue until the worker exited.
68
+ const inTestRun = env['NODE_ENV'] === 'test' || Bun.env['NODE_ENV'] === 'test';
69
+ if (inTestRun && explicitDir === undefined) return { on: false, off: 'test-run' };
70
+ const capacityMb = ledgerCapacityMb(env);
71
+ if (capacityMb === 0) return { on: false, off: 'disabled' };
72
+ const binding = await flockBinding();
73
+ if (!binding.ok) return { on: false, off: 'unsupported', detail: binding.reason };
74
+ const hold = env[HEAVY_HOLD_ENV];
75
+ if (hold !== undefined && hold !== '' && isHeld(hold, binding.tryLock)) {
76
+ return { on: false, off: 'nested' };
77
+ }
78
+ const dir = explicitDir ?? defaultLedgerDir();
79
+ requireOwnDir(dir);
80
+ return { on: true, dir, capacityMb, tryLock: binding.tryLock };
81
+ }
82
+
83
+ async function admission(env: HeavyEnv): Promise<HeavyState> {
84
+ try {
85
+ return await heavyState(env);
86
+ } catch (error) {
87
+ warnOnce(describe(error));
88
+ return { on: false, off: 'unsupported', detail: 'see the line above' };
89
+ }
90
+ }
91
+
92
+ const PATH_SHOWN = 48;
93
+ const printable = (text: string): string => text.replace(/\p{Cc}/gu, ' ').slice(0, 120);
94
+
95
+ export const ageOf = (ms: number): string => {
96
+ const seconds = Math.max(0, Math.round(ms / 1000));
97
+ return seconds < 60
98
+ ? `${String(seconds)}s`
99
+ : `${String(Math.floor(seconds / 60))}m${String(seconds % 60).padStart(2, '0')}s`;
100
+ };
101
+
102
+ /** A directory's END names the checkout; a long path keeps that and loses its start. */
103
+ const shortPath = (path: string): string =>
104
+ path.length <= PATH_SHOWN ? printable(path) : `…${printable(path.slice(-PATH_SHOWN))}`;
105
+
106
+ export const describeEntry = (entry: LedgerEntry, now: number): string =>
107
+ `${printable(entry.label)} (${shortPath(entry.cwd)}, ${String(entry.mb)} MB, ${ageOf(now - entry.at)})`;
108
+
109
+ /** The waiter's one line. Stderr always: stdout may be a `--json` document. */
110
+ export const waitLine = (label: string, wait: LedgerWait, now: number = Date.now()): string =>
111
+ // No holder to name is the instant between two admissions, not a mystery owner.
112
+ msg(
113
+ wait.cpu !== undefined
114
+ ? 'cli.heavy.waitingCpu'
115
+ : wait.holds.length === 0
116
+ ? 'cli.heavy.waitingAdmission'
117
+ : 'cli.heavy.waiting',
118
+ {
119
+ label: printable(label),
120
+ need: wait.needMb,
121
+ position: wait.position,
122
+ queued: wait.queued,
123
+ used: wait.usedMb,
124
+ capacity: wait.capacityMb,
125
+ holders: wait.holds.map((entry) => describeEntry(entry, now)).join('; '),
126
+ cpu: wait.cpu === undefined ? '' : cpuText(wait.cpu),
127
+ },
128
+ );
129
+
130
+ // Time this process has spent queued, so a gate step's deadline can stop counting it.
131
+ let finishedWaitMs = 0;
132
+ const waitStarts = new Set<number>();
133
+
134
+ /** Monotonic milliseconds spent waiting for admission, ongoing waits included. */
135
+ export const heavyWaitClock = (now: number = performance.now()): number => {
136
+ let total = finishedWaitMs;
137
+ for (const start of waitStarts) total += now - start;
138
+ return total;
139
+ };
140
+
141
+ async function timedWait<T>(wait: () => Promise<T>): Promise<T> {
142
+ const start = performance.now();
143
+ waitStarts.add(start);
144
+ try {
145
+ return await wait();
146
+ } finally {
147
+ waitStarts.delete(start);
148
+ finishedWaitMs += performance.now() - start;
149
+ }
150
+ }
151
+
152
+ export interface HeavyRequest {
153
+ readonly label: string;
154
+ readonly cwd: string;
155
+ readonly env: HeavyEnv;
156
+ readonly unitMb: number;
157
+ readonly baseMb?: number;
158
+ readonly units?: number;
159
+ readonly minUnits?: number;
160
+ /** Give up after this long in the queue (`x heavy run --max-wait`). */
161
+ readonly maxWaitMs?: number;
162
+ }
163
+
164
+ /** A reservation, or nothing when admission does not apply or could not work. */
165
+ async function enter(request: HeavyRequest, state: HeavyState): Promise<Reservation | undefined> {
166
+ if (!state.on) return undefined;
167
+ try {
168
+ return await timedWait(() =>
169
+ reserve({
170
+ dir: state.dir,
171
+ capacityMb: state.capacityMb,
172
+ tryLock: state.tryLock,
173
+ unitMb: request.unitMb,
174
+ ...(request.baseMb === undefined ? {} : { baseMb: request.baseMb }),
175
+ units: request.units ?? 1,
176
+ minUnits: request.minUnits ?? request.units ?? 1,
177
+ ...(request.maxWaitMs === undefined ? {} : { maxWaitMs: request.maxWaitMs }),
178
+ ...(cpuGateOn(request.env) ? { cpu: () => readCpuPressure() } : {}),
179
+ label: request.label,
180
+ cwd: request.cwd,
181
+ onWait: (wait) => writeErrorLine(waitLine(request.label, wait)),
182
+ }),
183
+ );
184
+ } catch (error) {
185
+ // The caller set this bound: running anyway, unadmitted, is what it asked not to happen.
186
+ if (error instanceof HeavyWaitExpiredError) throw error;
187
+ warnOnce(describe(error));
188
+ return undefined;
189
+ }
190
+ }
191
+
192
+ /** What a holder's child is spawned with: the hold's name, and the locks it must keep alive. */
193
+ export interface HeavyChild {
194
+ readonly env: Readonly<Record<string, string>>;
195
+ readonly fds: readonly number[];
196
+ }
197
+
198
+ const childOf = (env: HeavyEnv, state: HeavyState, held: Held | undefined): HeavyChild => ({
199
+ env: {
200
+ ...toolEnv(env, state),
201
+ ...(held === undefined ? {} : { [HEAVY_HOLD_ENV]: held.path }),
202
+ },
203
+ fds: held === undefined ? [] : [held.fd],
204
+ });
205
+
206
+ /** What a native tool's child is spawned with: the thread cap, unless this run has no ceiling. */
207
+ function toolEnv(env: HeavyEnv, state: HeavyState): Record<string, string> {
208
+ const capped = state.on || state.off === 'nested' || state.off === 'unsupported';
209
+ return capped ? nativeToolEnv(env, coreCap(env)) : {};
210
+ }
211
+
212
+ /** Runner options carrying `child`; untouched when it adds nothing, as under CI and in a test. */
213
+ export function withChild<T extends { readonly cwd: string }>(
214
+ options: T,
215
+ child: HeavyChild,
216
+ ):
217
+ | T
218
+ | (T & {
219
+ readonly env: Readonly<Record<string, string>>;
220
+ readonly inheritFds: readonly number[];
221
+ }) {
222
+ return Object.keys(child.env).length === 0 && child.fds.length === 0
223
+ ? options
224
+ : { ...options, env: child.env, inheritFds: child.fds };
225
+ }
226
+
227
+ /** Run `work` inside one reservation; everything it spawns gets `child`. */
228
+ export async function withHeavy<T>(
229
+ request: HeavyRequest,
230
+ work: (child: HeavyChild) => Promise<T>,
231
+ ): Promise<T> {
232
+ const state = await admission(request.env);
233
+ const held = await enter(request, state);
234
+ try {
235
+ return await work(childOf(request.env, state, held));
236
+ } finally {
237
+ held?.release();
238
+ }
239
+ }
240
+
241
+ /** `name` for one checkout, whichever path reached it, in the ledger's directory. */
242
+ const checkoutLockPath = (dir: string, name: string, root: string): string =>
243
+ join(dir, 'locks', `${name}-${Bun.hash(realpathSync(root)).toString(36)}.lock`);
244
+
245
+ /**
246
+ * One `name` at a time in this checkout (two `tsc -b` race one `dist/`). Taken AFTER the ledger, by
247
+ * every caller: a process holding this lock must never queue for memory, or a nested run holding
248
+ * memory and waiting for the lock would close a cycle.
249
+ */
250
+ export async function withCheckoutLock<T>(
251
+ input: { readonly name: string; readonly root: string; readonly env: HeavyEnv },
252
+ child: HeavyChild,
253
+ work: (child: HeavyChild) => Promise<T>,
254
+ ): Promise<T> {
255
+ // Nested runs still exclude each other here, so the state's `nested` is not an exemption.
256
+ const state = await admission({ ...input.env, [HEAVY_HOLD_ENV]: undefined });
257
+ if (!state.on) return work(child);
258
+ let held: Held | undefined;
259
+ try {
260
+ const path = checkoutLockPath(state.dir, input.name, input.root);
261
+ held = await timedWait(() =>
262
+ lockPath(path, `${input.name} in ${input.root}`, state.tryLock, (holder) =>
263
+ writeErrorLine(msg('cli.heavy.lockWait', { name: input.name, holder: printable(holder) })),
264
+ ),
265
+ );
266
+ } catch (error) {
267
+ warnOnce(describe(error));
268
+ }
269
+ try {
270
+ // The compiler keeps the lock too: a killed wrapper must not let a second one start beside it.
271
+ return await work(held === undefined ? child : { ...child, fds: [...child.fds, held.fd] });
272
+ } finally {
273
+ held?.release();
274
+ }
275
+ }
276
+
277
+ export interface WorkerLease {
278
+ readonly count: number;
279
+ readonly env?: Readonly<Record<string, string>>;
280
+ /** Locked descriptors each worker process must inherit. */
281
+ readonly fds?: readonly number[];
282
+ release(): void;
283
+ }
284
+
285
+ /**
286
+ * Up to `want` test workers, as many as the core cap and the ledger allow right now, at least one.
287
+ * `exact` is an explicit `--workers`: the caller's width, and it waits for all of it.
288
+ */
289
+ export async function leaseWorkers(
290
+ want: number,
291
+ request: Omit<HeavyRequest, 'units' | 'minUnits'> & { readonly exact?: boolean },
292
+ ): Promise<WorkerLease> {
293
+ const state = await admission(request.env);
294
+ const unbounded = !state.on && state.off !== 'nested' && state.off !== 'unsupported';
295
+ const cap = request.exact === true || unbounded ? undefined : coreCap(request.env);
296
+ const units = Math.max(1, cap === undefined ? want : Math.min(want, cap));
297
+ const held = await enter(
298
+ { ...request, units, minUnits: request.exact === true ? units : 1 },
299
+ state,
300
+ );
301
+ const child = childOf(request.env, state, held);
302
+ return {
303
+ count: held?.units ?? units,
304
+ env: child.env,
305
+ fds: child.fds,
306
+ release: () => held?.release(),
307
+ };
308
+ }
@@ -166,6 +166,26 @@ export async function checkRegistration(input: RegistrationInput): Promise<Regis
166
166
  export const unanswered = (catalog: Catalog, keys: readonly string[]): readonly string[] =>
167
167
  keys.filter((key) => !Object.hasOwn(catalog, key) || isLoudMiss(catalog[key]));
168
168
 
169
+ /**
170
+ * What `x i18n sync <locale>` writes for a key source names, per locale (`cmd-i18n.ts`'s
171
+ * `runSync`). The code's own comment said "as ⟦key⟧" of every locale and every key: a non-default
172
+ * locale gets the default's string marked, and an admin key in the default locale gets a real
173
+ * label — a reader who went looking for the ⟦ it promised found none.
174
+ */
175
+ const SOURCE_KEYS_WRITTEN =
176
+ 'writes each key above as a placeholder to replace with the real string: ⟦key⟧ in the default locale, ⟦the default locale’s string⟧ in any other';
177
+
178
+ /** The same, for a key a mounted admin derives (`adminCatalog`, `adminKeyLabel`). */
179
+ const ADMIN_KEYS_WRITTEN =
180
+ 'writes each key above: in the default locale the label x g resource --admin generates, a real string to keep or reword; in any other locale that label inside ⟦…⟧, to translate';
181
+
182
+ /** The finding with the code's own COMMAND and a comment that is true of what it writes. */
183
+ function missingKeysFinding(locale: Locale, missing: readonly string[], written: string): Finding {
184
+ const finding = findingFrom(catalogMissingKeys(locale, missing));
185
+ const [command = finding.fix] = finding.fix.split(' #');
186
+ return { ...finding, fix: `${command} # ${written}` };
187
+ }
188
+
169
189
  /**
170
190
  * `X_CATALOG_MISSING_KEYS` — the same fact, a catalog without keys it is asked for — with the
171
191
  * cause naming who asks. The fix stays the code's own, `x i18n sync <locale>`: it writes these keys
@@ -177,7 +197,7 @@ function adminKeysFinding(locale: Locale, missing: readonly string[]): Finding {
177
197
  const shown = missing.slice(0, 12).map((key) => `"${key}"`);
178
198
  const more = missing.length > shown.length ? `, +${missing.length - shown.length} more` : '';
179
199
  return {
180
- ...findingFrom(catalogMissingKeys(locale, missing)),
200
+ ...missingKeysFinding(locale, missing, ADMIN_KEYS_WRITTEN),
181
201
  cause: `${path} is missing ${missing.length} key(s) the mounted admin renders (defineAdmin derives them, so no source file names one): ${shown.join(', ')}${more}`,
182
202
  at: path,
183
203
  };
@@ -289,7 +309,7 @@ export function missingKeyFindings(report: ExtractReport): readonly Finding[] {
289
309
  const missing = report.locales
290
310
  .filter((audit) => audit.missing.length > 0)
291
311
  .map((audit) => ({
292
- ...findingFrom(catalogMissingKeys(audit.locale, audit.missing)),
312
+ ...missingKeysFinding(audit.locale, audit.missing, SOURCE_KEYS_WRITTEN),
293
313
  at: catalogPath(audit.locale),
294
314
  }));
295
315
  // A select or ordinal family with no `_other` renders `⟦key⟧` for every value it does not name:
@@ -97,8 +97,8 @@ export function harnessPage(input: HarnessPageInput): string {
97
97
  timeZone: input.target.timeZone,
98
98
  })}</script>`,
99
99
  '</head><body>',
100
- `<div id="x-shot-frame"><div ${emitIslandAttributes(directive)}></div></div>`,
101
- emitIslandProps(directive),
100
+ // The props script INSIDE the island's element, as the render walk writes it for a page.
101
+ `<div id="x-shot-frame"><div ${emitIslandAttributes(directive)}>${emitIslandProps(directive)}</div></div>`,
102
102
  hydrateRuntime([directive]),
103
103
  '</body></html>',
104
104
  ].join('');
package/src/job-budget.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  DRAIN_DEADLINE_DEFAULT_MS,
9
9
  finiteCount,
10
10
  isUltimateError,
11
+ laterHooksReserveMs,
11
12
  WORKER_DRAIN_DEADLINE_MAX_MS,
12
13
  WORKER_RETIRE_DEFAULT_MS,
13
14
  } from '@ultimat3/core';
@@ -27,7 +28,8 @@ type WorkerDrain = Pick<Partial<DrainConfig>, 'deadlineMs' | 'workerDeadlineMs'
27
28
 
28
29
  /**
29
30
  * The retire when on, for it aborts nothing; else when a SIGTERM drain CANCELS a held job, which is
30
- * the cut-off's `cancelAt` (`worker-drain-cutoff.ts`), a margin before the deadline itself.
31
+ * the cut-off's `cancelAt` (`worker-drain-cutoff.ts`): a margin before core's in-flight wait ends,
32
+ * which is itself the later hooks' reserve before the deadline (`ShutdownReason.inflightUntil`).
31
33
  */
32
34
  export function workerBudgetMs(drain: WorkerDrain | undefined): number {
33
35
  // Screened here, not trusted: `defineConfig` screens an app's config, but this is exported, and a
@@ -44,7 +46,7 @@ export function workerBudgetMs(drain: WorkerDrain | undefined): number {
44
46
  drain?.workerDeadlineMs ?? drain?.deadlineMs ?? DRAIN_DEADLINE_DEFAULT_MS,
45
47
  1,
46
48
  );
47
- return cutoffTimes(deadline, 0).cancelAt;
49
+ return cutoffTimes(deadline, 0, deadline - laterHooksReserveMs(deadline)).cancelAt;
48
50
  }
49
51
 
50
52
  function outlastsFinding(job: BudgetedJob, limitMs: number, budgetMs: number): Finding {
@@ -3,17 +3,27 @@
3
3
  // and every dead-letter trace — moves with the import order (`X_JOB_UNREGISTERED`). And an entity
4
4
  // declaring `partitionBy` with no `partitions()` job registered (`X_PARTITIONS_UNMAINTAINED`).
5
5
 
6
+ // why: Bun ships no path API; `posix` because the fix prints an import specifier on every OS.
7
+ import { join, posix } from 'node:path';
6
8
  import { ERROR_DOCS_URL } from '@ultimat3/core';
7
9
  import {
10
+ isJobHandle,
8
11
  isPartitionsJob,
12
+ isTaskHandle,
9
13
  partitionedEntities,
10
14
  registeredJobs,
11
15
  registeredTasks,
12
16
  } from '@ultimat3/jobs';
13
17
  import { loadApp } from './app-load';
14
18
  import type { AppLoader } from './app-permissions';
19
+ import { API_INDEX } from './app-root';
15
20
  import type { Finding } from './output';
16
21
 
22
+ /** The load, plus the modules it imported: where a positional job's file is looked up. */
23
+ type JobAppLoader = (
24
+ root: string,
25
+ ) => Promise<Awaited<ReturnType<AppLoader>> & { readonly files?: readonly string[] }>;
26
+
17
27
  /** What `job()` and `task()` name a declaration nobody named (`packages/jobs/src/job.ts`). */
18
28
  const POSITIONAL = /^anonymous-(job|task)-\d+$/;
19
29
 
@@ -24,16 +34,59 @@ export function positionalNames(
24
34
  return names.filter((name) => POSITIONAL.test(name)).sort();
25
35
  }
26
36
 
27
- export function unregisteredJobFinding(name: string): Finding {
28
- const kind = name.startsWith('anonymous-task-') ? 'tasks' : 'jobs';
37
+ /** `nudge-post` → `nudgePost`: the name the import line binds, a valid identifier either way. */
38
+ const moduleAlias = (file: string): string => {
39
+ const base = posix.basename(file).replace(/\.tsx?$/, '');
40
+ const [head = '', ...rest] = base.split(/[^A-Za-z0-9]+/).filter((word) => word !== '');
41
+ const alias = [head, ...rest.map((word) => word.charAt(0).toUpperCase() + word.slice(1))].join(
42
+ '',
43
+ );
44
+ return /^[A-Za-z_]/.test(alias) ? alias : `module${alias}`;
45
+ };
46
+
47
+ /** The import the API index needs, relative to it and without the extension. */
48
+ const importLine = (file: string, alias: string): string => {
49
+ const path = posix.relative(posix.dirname(API_INDEX), file).replace(/\.tsx?$/, '');
50
+ return `import * as ${alias} from '${path.startsWith('.') ? path : `./${path}`}';`;
51
+ };
52
+
53
+ /**
54
+ * `file` is the module exporting the job, when one does: the positional name moves between runs, so
55
+ * the path is the only thing that tells several agents in one checkout whose job this is.
56
+ */
57
+ export function unregisteredJobFinding(name: string, file?: string): Finding {
58
+ const task = name.startsWith('anonymous-task-');
59
+ const alias = file === undefined ? '<module>' : moduleAlias(file);
60
+ const line =
61
+ file === undefined ? `import * as ${alias} from '<its file>';` : importLine(file, alias);
62
+ const where = file === undefined ? '' : ` declared in ${file}`;
29
63
  return {
30
64
  code: 'X_JOB_UNREGISTERED',
31
- cause: `${name} is a ${kind === 'tasks' ? 'task' : 'job'} no defineApi() call names, so it carries the positional name ${kind === 'tasks' ? 'task()' : 'job()'} minted — on the queue row, in the manifest and in every dead-letter trace, and it moves when the import order does`,
32
- fix: `import * as <module> from '<its file>'; // in apps/web/api/index.ts, and <module> added to ${kind}: [...] there — then x manifest`,
33
- at: 'apps/web/api/index.ts',
65
+ cause: `${name}${where} is a ${task ? 'task' : 'job'} no defineApi() call names, so it carries the positional name ${task ? 'task()' : 'job()'} minted — on the queue row, in the manifest and in every dead-letter trace, and it moves when the import order does`,
66
+ fix: `${line} // in ${API_INDEX}, and ${alias} added to ${task ? 'tasks' : 'jobs'}: [...] there — then x manifest`,
67
+ at: file ?? API_INDEX,
34
68
  };
35
69
  }
36
70
 
71
+ /**
72
+ * Which loaded module exports each positional handle. The imports answer from the module cache: the
73
+ * load just evaluated these files. A handle no module exports has no file to name.
74
+ */
75
+ async function declaringFiles(
76
+ root: string,
77
+ files: readonly string[],
78
+ ): Promise<ReadonlyMap<string, string>> {
79
+ const found = new Map<string, string>();
80
+ for (const file of files) {
81
+ const module = (await import(join(root, file))) as Record<string, unknown>;
82
+ for (const value of Object.values(module)) {
83
+ if (!isJobHandle(value) && !isTaskHandle(value)) continue;
84
+ if (POSITIONAL.test(value.name) && !found.has(value.name)) found.set(value.name, file);
85
+ }
86
+ }
87
+ return found;
88
+ }
89
+
37
90
  /**
38
91
  * The step's answer. Loads the app the way every other gate step does — the registries are only
39
92
  * whole after the scan — and says nothing when the load failed: a short registry is the load's
@@ -41,11 +94,14 @@ export function unregisteredJobFinding(name: string): Finding {
41
94
  */
42
95
  export async function unregisteredJobFindings(
43
96
  root: string,
44
- load: AppLoader = loadApp,
97
+ load: JobAppLoader = loadApp,
45
98
  ): Promise<readonly Finding[]> {
46
- if ((await load(root)).findings.length > 0) return [];
99
+ const app = await load(root);
100
+ if (app.findings.length > 0) return [];
101
+ const names = positionalNames();
102
+ const files = names.length === 0 ? new Map() : await declaringFiles(root, app.files ?? []);
47
103
  return [
48
- ...positionalNames().map(unregisteredJobFinding),
104
+ ...names.map((name) => unregisteredJobFinding(name, files.get(name))),
49
105
  ...unmaintainedPartitionFindings(
50
106
  partitionedEntities().map((described) => described.table),
51
107
  registeredJobs(),