@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
@@ -3,12 +3,16 @@
3
3
  // the CLI is the surface an agent reads first — a failure here has to be actionable without a doc
4
4
  // lookup or a second round-trip. The classes that throw these codes live in `./errors`.
5
5
  import { registerErrorCodes } from '@ultimat3/core';
6
+ import type { CliAgentsErrorCode } from './error-codes-agents';
7
+ import { CLI_AGENTS_ERROR_CODES, CLI_AGENTS_ERROR_TITLES } from './error-codes-agents';
6
8
  import type { CliBoundaryErrorCode } from './error-codes-boundary';
7
9
  import { CLI_BOUNDARY_ERROR_CODES, CLI_BOUNDARY_ERROR_TITLES } from './error-codes-boundary';
8
10
  import type { CliDoctorErrorCode } from './error-codes-doctor';
9
11
  import { CLI_DOCTOR_ERROR_CODES, CLI_DOCTOR_ERROR_TITLES } from './error-codes-doctor';
10
12
  import type { CliPackageErrorCode } from './error-codes-package';
11
13
  import { CLI_PACKAGE_ERROR_CODES, CLI_PACKAGE_ERROR_TITLES } from './error-codes-package';
14
+ import type { CliProcessesErrorCode } from './error-codes-processes';
15
+ import { CLI_PROCESSES_ERROR_CODES, CLI_PROCESSES_ERROR_TITLES } from './error-codes-processes';
12
16
  import type { CliShotErrorCode } from './error-codes-shot';
13
17
  import { CLI_SHOT_ERROR_CODES, CLI_SHOT_ERROR_TITLES } from './error-codes-shot';
14
18
  import type { CliToolingErrorCode } from './error-codes-tooling';
@@ -82,11 +86,6 @@ export const CLI_OWNED_ERROR_CODES = [
82
86
  // its health check with nothing in the log that names the cause.
83
87
  'X_ROLE_UNKNOWN',
84
88
  'X_PORT_INVALID',
85
- 'X_DEV_ALREADY_RUNNING',
86
- // The OTHER thing the preflight can find, and it was reported as the one above: an unreadable
87
- // lock this process could not remove made `DevAlreadyRunningError` name THIS pid as the holder,
88
- // so the remedy printed was `kill <self>` — unrunnable, and a cause that was simply untrue.
89
- 'X_DEV_LOCK_UNREADABLE',
90
89
  // The boot's own consistency check. `startServices` captures the drivers it built, and
91
90
  // `loadApp` runs AFTER it — so an app module calling `installJobDriver(theirs)` moved the ambient
92
91
  // slot and left the captured object alone: every `handle.enqueue()` went to their queue while
@@ -94,7 +93,6 @@ export const CLI_OWNED_ERROR_CODES = [
94
93
  // the enqueue side. Nothing failed. Refused here rather than documented, per axiom 3.
95
94
  'X_RUNTIME_DRIVER_SPLIT',
96
95
  'X_GENERATE_CONFLICT',
97
- 'X_PORT_IN_USE',
98
96
  'X_DB_GEN_FAILED',
99
97
  // The two directions of the drift a hash cannot see, and they are two repairs. The `drift` step
100
98
  // compared a schema-source HASH to a `.hash` sidecar and never read what the migration recorded,
@@ -238,9 +236,8 @@ export const CLI_OWNED_ERROR_CODES = [
238
236
  'X_PROFILE_ROUTE_FAILED',
239
237
  'X_ROWS_SLICE_ENTITY',
240
238
  'X_GUARD_BUILT_IN',
241
- 'X_REPRO_BUNDLE_INVALID',
242
- 'X_UPGRADE_LOCKED',
243
239
  'X_APP_MIGRATIONS_UNAPPLIED',
240
+ 'X_TASK_RUN_PRODUCTION',
244
241
  ] as const;
245
242
 
246
243
  /**
@@ -276,9 +273,11 @@ export const CLI_BORROWED_ERROR_CODES = [
276
273
  /** Every code the CLI can throw: the ones it owns plus the one it borrows. */
277
274
  export const CLI_ERROR_CODES = [
278
275
  ...CLI_OWNED_ERROR_CODES,
276
+ ...CLI_AGENTS_ERROR_CODES,
279
277
  ...CLI_BOUNDARY_ERROR_CODES,
280
278
  ...CLI_DOCTOR_ERROR_CODES,
281
279
  ...CLI_PACKAGE_ERROR_CODES,
280
+ ...CLI_PROCESSES_ERROR_CODES,
282
281
  ...CLI_SHOT_ERROR_CODES,
283
282
  ...CLI_TOOLING_ERROR_CODES,
284
283
  ...CLI_VERIFY_ERROR_CODES,
@@ -289,9 +288,11 @@ export const CLI_ERROR_CODES = [
289
288
  type CliListedErrorCode = (typeof CLI_OWNED_ERROR_CODES)[number];
290
289
  export type CliOwnedErrorCode =
291
290
  | CliListedErrorCode
291
+ | CliAgentsErrorCode
292
292
  | CliBoundaryErrorCode
293
293
  | CliDoctorErrorCode
294
294
  | CliPackageErrorCode
295
+ | CliProcessesErrorCode
295
296
  | CliShotErrorCode
296
297
  | CliToolingErrorCode
297
298
  | CliVerifyErrorCode;
@@ -340,11 +341,8 @@ export const CLI_ERROR_TITLES: Readonly<Record<CliListedErrorCode, string>> = {
340
341
  X_DEPLOY_FAILED: 'a deploy step failed',
341
342
  X_ROLE_UNKNOWN: 'ROLE names something that is not a role',
342
343
  X_PORT_INVALID: 'PORT is not a TCP port number',
343
- X_DEV_ALREADY_RUNNING: 'another x dev already owns this checkout',
344
- X_DEV_LOCK_UNREADABLE: 'the dev lock file cannot be read or removed',
345
344
  X_RUNTIME_DRIVER_SPLIT: 'the ambient driver is not the one this process serves',
346
345
  X_GENERATE_CONFLICT: 'a generator would overwrite a file',
347
- X_PORT_IN_USE: 'the dev port is taken',
348
346
  X_DB_GEN_FAILED: 'x db gen failed',
349
347
  X_DB_SCHEMA_UNMIGRATED: 'an entity declaration no migration recorded',
350
348
  X_DB_SCHEMA_UNDECLARED: 'a migration records schema no entity declares',
@@ -467,10 +465,9 @@ export const CLI_ERROR_TITLES: Readonly<Record<CliListedErrorCode, string>> = {
467
465
  X_PROFILE_ROUTE_FAILED: 'the profiled route answered an error',
468
466
  X_ROWS_SLICE_ENTITY: "the slice's entity is not the scaffolded table",
469
467
  X_GUARD_BUILT_IN: 'x g guard named a shipped guard',
470
- X_REPRO_BUNDLE_INVALID: 'the file is not a repro bundle this version can open',
471
- X_UPGRADE_LOCKED: 'another x upgrade holds this app',
472
468
  X_APP_MIGRATIONS_UNAPPLIED:
473
469
  'a serving role booted over a database missing migrations this build ships',
470
+ X_TASK_RUN_PRODUCTION: 'x tasks run refused to fire a task in production unasked',
474
471
  };
475
472
 
476
473
  // One unconditional call, so a second package claiming one of the CLI's codes throws
@@ -479,9 +476,11 @@ registerErrorCodes(
479
476
  Object.fromEntries(
480
477
  Object.entries({
481
478
  ...CLI_ERROR_TITLES,
479
+ ...CLI_AGENTS_ERROR_TITLES,
482
480
  ...CLI_BOUNDARY_ERROR_TITLES,
483
481
  ...CLI_DOCTOR_ERROR_TITLES,
484
482
  ...CLI_PACKAGE_ERROR_TITLES,
483
+ ...CLI_PROCESSES_ERROR_TITLES,
485
484
  ...CLI_SHOT_ERROR_TITLES,
486
485
  ...CLI_TOOLING_ERROR_TITLES,
487
486
  ...CLI_VERIFY_ERROR_TITLES,
@@ -0,0 +1,27 @@
1
+ // `x test` over a selection that matched nothing. Its fix never prints the bare command: pasted as
2
+ // printed, that starts every suite, which a worker on a file set must not (`wiki/Many-Agents.md`).
3
+
4
+ import { UltimateError } from '@ultimat3/core';
5
+
6
+ /**
7
+ * `x test` discovered nothing. A green run over zero files is the most expensive false pass, so
8
+ * the selection that found nothing is named in full — a caller that cannot see whether the type
9
+ * or the filter emptied the set has to guess which one to drop.
10
+ */
11
+ export class NoTestFilesError extends UltimateError {
12
+ constructor(input: { root: string; type?: string; filter?: string }) {
13
+ const parts = [
14
+ input.type === undefined ? undefined : `of type ${input.type}`,
15
+ input.filter === undefined ? undefined : `matching "${input.filter}"`,
16
+ ].filter((part): part is string => part !== undefined);
17
+ const where = parts.length === 0 ? '' : ` ${parts.join(' ')}`;
18
+ super({
19
+ code: 'X_TEST_NO_FILES',
20
+ cause: `no *.test.ts files${where} under ${input.root}`,
21
+ fix:
22
+ parts.length === 0
23
+ ? 'x test --json # run it from the repo root'
24
+ : 'x test --affected --dirty # the tests your edits reach; or a path that exists: x test --filter <path>',
25
+ });
26
+ }
27
+ }
package/src/errors.ts CHANGED
@@ -5,6 +5,20 @@ import { UltimateError } from '@ultimat3/core';
5
5
  import type { Finding } from './output';
6
6
  import { quoteArg } from './shell-quote';
7
7
 
8
+ /** Commands whose bare form runs everything. */
9
+ const WHOLE_RUN: ReadonlySet<string> = new Set(['test', 'verify']);
10
+
11
+ /** Commands that act when run bare (stop, delete, roll out, rewrite, re-pin, inject a fault). */
12
+ const ACTS_BARE = new Set('stop clean deploy fix upgrade drill'.split(' '));
13
+
14
+ /** The suggested command as a fix: its help when bare it starts a whole suite or changes state. */
15
+ const suggestedCommandFix = (suggestion: string): string =>
16
+ WHOLE_RUN.has(suggestion)
17
+ ? `x ${suggestion} --help # the nearest command; bare, it runs every suite`
18
+ : ACTS_BARE.has(suggestion)
19
+ ? `x ${suggestion} --help # the nearest command; bare, it acts at once`
20
+ : `x ${quoteArg(suggestion.split(' '))}`;
21
+
8
22
  /** An unknown command or subcommand. Carries a suggestion so the retry is one keystroke away. */
9
23
  export class UnknownCommandError extends UltimateError {
10
24
  /** `why`: the decision behind a name that is deliberately not a command, said after the list. */
@@ -17,7 +31,7 @@ export class UnknownCommandError extends UltimateError {
17
31
  super({
18
32
  code: 'X_CLI_UNKNOWN_COMMAND',
19
33
  cause: `"x ${input.path}" is not a command (known: ${input.known.join(', ')})${input.why === undefined ? '' : ` — ${input.why}`}`,
20
- fix: input.suggestion === undefined ? 'x help' : `x ${quoteArg(input.suggestion.split(' '))}`,
34
+ fix: input.suggestion === undefined ? 'x help' : suggestedCommandFix(input.suggestion),
21
35
  });
22
36
  }
23
37
  }
@@ -138,12 +152,14 @@ export class NotInAppError extends UltimateError {
138
152
  adopter?: boolean;
139
153
  /** `from`'s `package.json` has an `x` script (the framework repo): `bun run x -- … --cwd`. */
140
154
  xScript?: boolean;
155
+ /** The words as typed — subcommand, positionals, flags — less the two the fix writes itself. */
156
+ typed?: readonly string[];
141
157
  }) {
142
158
  const [first] = input.below ?? [];
143
159
  const found = (input.below ?? []).join(', ');
144
160
  // Word by word: `'vapid create'` pasted as one quoted token is a command `x` does not have.
145
161
  // Assembled from arrays of screened words, so no value is spliced where a shell runs it.
146
- const argv = input.command.split(' ').map(quoteArg);
162
+ const argv = (input.typed ?? input.command.split(' ')).map(quoteArg);
147
163
  const words = argv.join(' ');
148
164
  super({
149
165
  code: 'X_NOT_IN_APP',
@@ -178,26 +194,6 @@ export class BunVersionError extends UltimateError {
178
194
  }
179
195
  }
180
196
 
181
- /**
182
- * `x test` discovered nothing. A green run over zero files is the most expensive false pass, so
183
- * the selection that found nothing is named in full — a caller that cannot see whether the type
184
- * or the filter emptied the set has to guess which one to drop.
185
- */
186
- export class NoTestFilesError extends UltimateError {
187
- constructor(input: { root: string; type?: string; filter?: string }) {
188
- const parts = [
189
- input.type === undefined ? undefined : `of type ${input.type}`,
190
- input.filter === undefined ? undefined : `matching "${input.filter}"`,
191
- ].filter((part): part is string => part !== undefined);
192
- const where = parts.length === 0 ? '' : ` ${parts.join(' ')}`;
193
- super({
194
- code: 'X_TEST_NO_FILES',
195
- cause: `no *.test.ts files${where} under ${input.root}`,
196
- fix: parts.length === 0 ? 'x test --json # run it from the repo root' : 'x test',
197
- });
198
- }
199
- }
200
-
201
197
  /**
202
198
  * A generated path resolves outside the directory it is being written into — the scaffold gate's
203
199
  * sandbox, the app root `x g` writes into, or the catalog root a `--locales` segment names. `..`
package/src/exec.ts CHANGED
@@ -32,6 +32,11 @@ export interface ExecOptions {
32
32
  */
33
33
  readonly env?: Readonly<Record<string, string | undefined>>;
34
34
  readonly stdin?: string;
35
+ /**
36
+ * Descriptors the child inherits, from fd 3 up: the machine ledger's locks (`heavy-ledger.ts`),
37
+ * which must outlive this process when it is killed and the child is not.
38
+ */
39
+ readonly inheritFds?: readonly number[];
35
40
  /**
36
41
  * Told the child's pid the moment it exists. A gate step's deadline records it here
37
42
  * (`verify-deadline.ts`): on Windows no process's environment is readable, so the tag sweep
@@ -91,9 +96,12 @@ function spawnOrRefuse(command: readonly string[], options: ExecOptions) {
91
96
  return Bun.spawn([head, ...rest], {
92
97
  cwd: options.cwd,
93
98
  env: options.env === undefined ? Bun.env : mergedEnv(options.env),
94
- stdin: options.stdin === undefined ? 'ignore' : new TextEncoder().encode(options.stdin),
95
- stdout: 'pipe',
96
- stderr: 'pipe',
99
+ stdio: [
100
+ options.stdin === undefined ? 'ignore' : new TextEncoder().encode(options.stdin),
101
+ 'pipe',
102
+ 'pipe',
103
+ ...(options.inheritFds ?? []),
104
+ ],
97
105
  });
98
106
  } catch (error) {
99
107
  throw new UltimateError({
@@ -8,8 +8,9 @@ import { exerciseFiles } from './templates/scaffold-exercise';
8
8
  export const EXERCISE_FILE = 'apps/web/exercise.ts';
9
9
 
10
10
  /**
11
- * The password sign-in's two actions the pass cannot drive, by the file that declares each. One line
12
- * each in the app's file, inside Biome's 100 columns: `login()` refuses the drawn address and password.
11
+ * The sign-in actions the pass cannot drive, by the file that declares each; the second leg is both
12
+ * shapes'. One line each in the app's file, inside Biome's 100 columns: `login()` refuses the drawn
13
+ * address and password.
13
14
  */
14
15
  const SIGN_IN_OFF: ReadonlyMap<string, readonly [string, string]> = new Map([
15
16
  [
@@ -18,7 +19,7 @@ const SIGN_IN_OFF: ReadonlyMap<string, readonly [string, string]> = new Map([
18
19
  ],
19
20
  [
20
21
  'apps/web/app/auth/actions/confirm-session.ts',
21
- ['confirmSession', 'answers the challenge createSession holds; the pass holds none'],
22
+ ['confirmSession', 'answers the challenge the first leg holds; the pass holds none'],
22
23
  ],
23
24
  ]);
24
25
 
@@ -32,8 +32,9 @@ export const deployed = (env: EnvTable): boolean => devSecretsRefused({ env });
32
32
  /**
33
33
  * Does `env` NAME a deployed environment — `ULTIMATE_ENV`, else `NODE_ENV`, resolving to
34
34
  * `staging` or `production`? `x doctor`'s gate, and deliberately not `deployed`: the two commands
35
- * answer different questions. `x env check` asks what a deployed boot does with a table, and the
36
- * boot fails closed, so an unnamed table is a deploy there. `x doctor` asks about THIS machine,
35
+ * answer different questions. `x env check` asks what a boot does with a table: an unnamed one is
36
+ * checked as `x dev` runs it (development), except under `CI`, where the boot fails closed and it
37
+ * is a deploy (`cmd-env.ts`'s `checkedAsDev`). `x doctor` asks about THIS machine,
37
38
  * and a developer shell that names nothing is not a deploy — reporting the shipped keys there would
38
39
  * put two findings in front of every developer on day one. An unknown `ULTIMATE_ENV` names
39
40
  * nothing (`tryResolveEnvironment`): the boot refuses it first, and doctor must not crash on it.
@@ -43,7 +44,10 @@ export const namedDeployed = (env: EnvTable): boolean => {
43
44
  return environment === 'staging' || environment === 'production';
44
45
  };
45
46
 
46
- /** Does `env` name no environment? The boot then reads it as production, and `x env check` says so. */
47
+ /**
48
+ * Does `env` name no environment? The boot then reads it as production; `x env check` checks it so
49
+ * under `CI` only, and as development elsewhere — and says which.
50
+ */
47
51
  export const namesNoEnvironment = (env: EnvTable): boolean =>
48
52
  // Core's reading, twice: only a table that names nothing answers with whichever fallback it got.
49
53
  tryResolveEnvironment({ env, fallback: 'production' }) !==
@@ -240,6 +240,7 @@ export function generate(options: GenerateOptions): readonly GeneratedFile[] {
240
240
  ...target,
241
241
  live: options.live === true,
242
242
  ...(options.locales === undefined ? {} : { locales: options.locales }),
243
+ ...(options.slicePolicy === undefined ? {} : { slicePolicy: options.slicePolicy }),
243
244
  ...(options.sliceEntity === undefined ? {} : { sliceEntity: options.sliceEntity }),
244
245
  ...(options.sliceRepo === undefined ? {} : { sliceRepo: options.sliceRepo }),
245
246
  }),
@@ -13,6 +13,7 @@ import {
13
13
  policyGrantsFor,
14
14
  writtenTables,
15
15
  } from './generate-grants';
16
+ import { rolesFileOf } from './generate-roles-file';
16
17
  import type { Finding } from './output';
17
18
  import { ROLES_FILE } from './permission-grants';
18
19
 
@@ -61,11 +62,12 @@ export async function ungrantedByGenerator(
61
62
  const admin = (await writtenTables(root, written, disk)).flatMap(adminGrantsFor);
62
63
  const grants = [...(await policyGrantsFor(root, written, disk)), ...admin];
63
64
  if (grants.length === 0) return [];
64
- const source = await disk.read(ROLES_FILE);
65
+ const rolesFile = await rolesFileOf(root, disk);
66
+ const source = rolesFile === undefined ? undefined : await disk.read(rolesFile);
65
67
  // The file whose declarations nobody granted: where a reader starts when the map is not ours.
66
68
  const declaredIn =
67
69
  written.find((path) => path.endsWith('/policy.ts')) ?? written[0] ?? ROLES_FILE;
68
- if (source === undefined) {
70
+ if (rolesFile === undefined || source === undefined) {
69
71
  return [
70
72
  {
71
73
  code: 'X_PERMISSION_UNGRANTED',
@@ -80,9 +82,9 @@ export async function ungrantedByGenerator(
80
82
  return [
81
83
  {
82
84
  code: 'X_PERMISSION_UNGRANTED',
83
- cause: `${ROLES_FILE} has no role, no "grants: [...]" list or no definePermissions([...]) these could be safely added to, so nothing granted: ${linesFor(missing)}`,
84
- fix: `{ ${roleEntries(missing)} } // merge into the role map in ${ROLES_FILE}, declaring any the map does not know in definePermissions([...]) — then x verify --only policy`,
85
- at: ROLES_FILE,
85
+ cause: `${rolesFile} has no role, no "grants: [...]" list or no definePermissions([...]) these could be safely added to, so nothing granted: ${linesFor(missing)}`,
86
+ fix: `{ ${roleEntries(missing)} } // merge into the role map in ${rolesFile}, declaring any the map does not know in definePermissions([...]) — then x verify --only policy`,
87
+ at: rolesFile,
86
88
  },
87
89
  ];
88
90
  }
@@ -1,7 +1,7 @@
1
1
  // `x g policy` / `x g resource` grant what they declare. A generated `policy.ts` declares
2
2
  // `<feature>:read` and `<feature>:write`; nothing granted them, so every generated endpoint
3
- // answered 403 to every actor a role mints. The edit lands in the scaffold's one role map,
4
- // `apps/web/shared/roles.ts`: `:read` to `member`, `:write` to `admin` (which inherits member).
3
+ // answered 403 to every actor a role mints. The edit lands in the app's one role map
4
+ // (`generate-roles-file.ts`): `:read` to `member`, `:write` to `admin` (which inherits member).
5
5
  //
6
6
  // And a generated ENTITY is a screen at `/admin/<table>`, behind `<table>:read|write|delete` —
7
7
  // three permissions `defineAdmin()` derives from the table's own name. They are declared in the
@@ -9,7 +9,7 @@
9
9
 
10
10
  import type { GenerateDisk } from './generate-disk';
11
11
  import { appDisk } from './generate-disk';
12
- import { ROLES_FILE } from './permission-grants';
12
+ import { rolesFileOf } from './generate-roles-file';
13
13
  import { absentFrom, appendToList, maskOf, readList, readProperties } from './source-list-edit';
14
14
  import { isEntityModule } from './templates/entity-module';
15
15
 
@@ -155,7 +155,7 @@ export function insertGrants(
155
155
  }
156
156
 
157
157
  /** Every `definePermissions([` in the masked text: the index of each call's opening `[`. */
158
- const declarationLists = (masked: string): readonly number[] =>
158
+ export const declarationLists = (masked: string): readonly number[] =>
159
159
  [...masked.matchAll(/\bdefinePermissions\(\s*\[/g)].map(
160
160
  (found) => found.index + found[0].length - 1,
161
161
  );
@@ -216,8 +216,9 @@ export async function grantGeneratedPermissions(
216
216
  ): Promise<readonly string[]> {
217
217
  const admin = (await writtenTables(root, written, disk)).flatMap(adminGrantsFor);
218
218
  const grants = [...(await policyGrantsFor(root, written, disk)), ...admin];
219
- const before = grants.length === 0 ? undefined : await disk.read(ROLES_FILE);
220
- if (before === undefined) return [];
219
+ const file = grants.length === 0 ? undefined : await rolesFileOf(root, disk);
220
+ const before = file === undefined ? undefined : await disk.read(file);
221
+ if (file === undefined || before === undefined) return [];
221
222
  const unplaced = insertGrants(before, grants).skipped;
222
223
  const placeable = grants.filter((grant) => !unplaced.includes(grant));
223
224
  const declared = insertPermissions(
@@ -228,6 +229,6 @@ export async function grantGeneratedPermissions(
228
229
  const grantable = placeable.filter((grant) => !declared.skipped.includes(grant.permission));
229
230
  const { source } = insertGrants(declared.source, grantable);
230
231
  if (source === before) return [];
231
- await disk.write(ROLES_FILE, source);
232
- return [ROLES_FILE];
232
+ await disk.write(file, source);
233
+ return [file];
233
234
  }
@@ -83,6 +83,26 @@ export function assertLiveSupported(kind: Generator, live: boolean, name: string
83
83
  });
84
84
  }
85
85
 
86
+ /** What the caller typed after the generator: its `<name>` and `--feature`, when given. */
87
+ export interface TypedRest {
88
+ readonly name?: string | undefined;
89
+ readonly feature?: string | undefined;
90
+ }
91
+
92
+ /** One shell word, unquoted: a name or slice that would need quoting is not reused as typed. */
93
+ const ONE_WORD = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
94
+
95
+ /**
96
+ * The rest of the near-miss's line: the caller's own name (and slice) when they paste as one word,
97
+ * else the generator's example. `x g acton foo` answered `x g action publish-post --feature post`,
98
+ * which in a scaffold holding `post` writes an action nobody asked for.
99
+ */
100
+ const retyped = (kind: Generator, typed: TypedRest): string => {
101
+ if (typed.name === undefined || !ONE_WORD.test(typed.name)) return exampleName(kind);
102
+ const feature = typed.feature !== undefined && ONE_WORD.test(typed.feature);
103
+ return feature ? `${typed.name} --feature ${typed.feature}` : typed.name;
104
+ };
105
+
86
106
  /**
87
107
  * The generator a spelling reaches, or a refusal that leads with the one it is nearest.
88
108
  *
@@ -91,8 +111,9 @@ export function assertLiveSupported(kind: Generator, live: boolean, name: string
91
111
  * because it carries no `<name>`. `nearestName` is what `parse.ts` already does with a mistyped
92
112
  * command, over this file's own list.
93
113
  *
94
- * Two rules hold the fix line to a command that runs. A near miss is completed with that
95
- * generator's own `EXAMPLE_NAME`, because `x g route <name>` pasted into a shell is a redirect.
114
+ * Two rules hold the fix line to a command that runs. A near miss is completed with the name the
115
+ * caller typed (`retyped`), else that generator's own `EXAMPLE_NAME` — never a `<name>`, because
116
+ * `x g route <name>` pasted into a shell is a redirect.
96
117
  * A word near NOTHING gets `x help g` rather than an invented lead — the same rule `parse.test.ts`
97
118
  * pins for a command that resembles nothing, and the reason `nearestName` is never asked about an
98
119
  * ABSENT kind: the empty string is within the cutoff of `job`, so `x g` would "suggest" a
@@ -101,7 +122,7 @@ export function assertLiveSupported(kind: Generator, live: boolean, name: string
101
122
  * And a THIRD rule, for the word that is not there at all: no generator is a missing subcommand,
102
123
  * never an unknown command — see the branch below.
103
124
  */
104
- export function readKind(raw: string | undefined): Generator {
125
+ export function readKind(raw: string | undefined, typed: TypedRest = {}): Generator {
105
126
  const kinds: readonly string[] = GENERATORS;
106
127
  if (raw !== undefined && kinds.includes(raw)) return raw as Generator;
107
128
  // A MISSING generator is not an unknown command. `x g --json` answered `X_CLI_UNKNOWN_COMMAND:
@@ -119,7 +140,8 @@ export function readKind(raw: string | undefined): Generator {
119
140
  throw new UnknownCommandError({
120
141
  path: `g ${raw}`.trim(),
121
142
  known: GENERATORS,
122
- suggestion: suggestion === undefined ? 'help g' : `g ${suggestion} ${EXAMPLE_NAME[suggestion]}`,
143
+ suggestion:
144
+ suggestion === undefined ? 'help g' : `g ${suggestion} ${retyped(suggestion, typed)}`,
123
145
  ...(decided === undefined
124
146
  ? {}
125
147
  : { why: `${decided.factory}() has no generator: ${decided.none}` }),
@@ -273,8 +295,10 @@ function refuseBadIdentifier(raw: string, kind: Generator): void {
273
295
  * a `Record` object literal answers an `Object.prototype` member for a key nobody declared, and
274
296
  * this string is pasted into a shell. Two callers, one read.
275
297
  */
276
- const exampleFor = (kind: Generator): string =>
277
- `x g ${kind} ${Object.hasOwn(EXAMPLE_NAME, kind) ? EXAMPLE_NAME[kind] : '<name>'}`;
298
+ const exampleName = (kind: Generator): string =>
299
+ Object.hasOwn(EXAMPLE_NAME, kind) ? EXAMPLE_NAME[kind] : '<name>';
300
+
301
+ const exampleFor = (kind: Generator): string => `x g ${kind} ${exampleName(kind)}`;
278
302
 
279
303
  /**
280
304
  * `resource:verb`, or nothing is written. `--permission` reaches the generated page in three
@@ -0,0 +1,30 @@
1
+ // Which file `x g` edits the role map in. The scaffold's `apps/web/shared/roles.ts` when it is
2
+ // there; otherwise the ONE module beside it that calls `defineRoles(` — the reference app keeps
3
+ // its map in `shared/policies.ts`, and a fixed path granted nothing there on every run.
4
+
5
+ import { stripComments } from '@ultimat3/core';
6
+ import type { GenerateDisk } from './generate-disk';
7
+ import { ROLES_FILE } from './permission-grants';
8
+ import { isTest } from './source-files';
9
+
10
+ /** Where an app's role map can live without the app being loaded: the shared leaf, one level. */
11
+ const SHARED_GLOB = 'apps/web/shared/*.ts';
12
+
13
+ /**
14
+ * `undefined` when no file, or more than one, declares the map: a generator never picks between
15
+ * two, and the finding then says what nobody granted. Read off disk, not the registry — `x g` does
16
+ * not load the app, and the edit that follows is of this source text in either case.
17
+ */
18
+ export async function rolesFileOf(root: string, disk: GenerateDisk): Promise<string | undefined> {
19
+ if ((await disk.read(ROLES_FILE)) !== undefined) return ROLES_FILE;
20
+ const declaring: string[] = [];
21
+ for await (const path of new Bun.Glob(SHARED_GLOB).scan({ cwd: root })) {
22
+ const file = path.replaceAll('\\', '/');
23
+ if (isTest(file)) continue;
24
+ const source = await disk.read(file);
25
+ if (source !== undefined && /\bdefineRoles\s*\(/.test(stripComments(source))) {
26
+ declaring.push(file);
27
+ }
28
+ }
29
+ return declaring.length === 1 ? declaring[0] : undefined;
30
+ }
@@ -1,4 +1,4 @@
1
- // Single responsibility: the refusal `x g action` / `x g mutator` raise when the slice they were
1
+ // Single responsibility: the refusal `x g action` / `x g mutator` / `x g query` raise when the slice they were
2
2
  // pointed at has a hand-written `policy.ts` without the exports the generated file imports.
3
3
  // Declared outside `templates/` (source the CLI emits) and beside nothing else, as
4
4
  // `generate-feature.ts`'s `FeatureUnknownError` is: `errors.ts` sits at its line ceiling.
@@ -11,7 +11,7 @@ export class SlicePolicyIncompleteError extends UltimateError {
11
11
  readonly policy: string;
12
12
  readonly feature: string;
13
13
  readonly missing: readonly string[];
14
- readonly kind: 'action' | 'mutator';
14
+ readonly kind: 'action' | 'mutator' | 'query';
15
15
  }) {
16
16
  super({
17
17
  code: 'X_SLICE_POLICY_INCOMPLETE',
@@ -26,4 +26,4 @@ export class SlicePolicyIncompleteError extends UltimateError {
26
26
  const exportLine = (name: string, feature: string): string =>
27
27
  name.endsWith('Tag')
28
28
  ? `export const ${name} = tag('${feature}');`
29
- : `export const ${name} = can('${feature}:write');`;
29
+ : `export const ${name} = can('${feature}:${name.endsWith('Read') ? 'read' : 'write'}');`;
package/src/guards.ts CHANGED
@@ -124,7 +124,7 @@ const failed = (path: string, cause: string): Finding => ({
124
124
  const invalid = (path: string, cause: string): Finding => ({
125
125
  code: 'X_GUARD_INVALID',
126
126
  cause,
127
- fix: `export a \`guard\` object — { summary, check } — from ${path}, then: x verify`,
127
+ fix: `export a \`guard\` object — { summary, check } — from ${path}, then: x verify --only boundaries --json`,
128
128
  docs: ERROR_DOCS_URL,
129
129
  at: path,
130
130
  });
@@ -157,7 +157,7 @@ const notADirectory: Finding = {
157
157
  const findingInvalid = (path: string, cause: string): Finding => ({
158
158
  code: 'X_GUARD_FINDING_INVALID',
159
159
  cause: `${path} returned a finding that is not one: ${cause}`,
160
- fix: `{ code: 'X_<YOURS>', cause: '<what is wrong>', fix: '<a command or a file>' } // what ${path} returns, then: x verify`,
160
+ fix: `{ code: 'X_<YOURS>', cause: '<what is wrong>', fix: '<a command or a file>' } // what ${path} returns, then: x verify --only boundaries --json`,
161
161
  docs: ERROR_DOCS_URL,
162
162
  at: path,
163
163
  });
@@ -0,0 +1,51 @@
1
+ // How many cores a local run may take: every one in CI, at most `LOCAL_CORE_CAP` on a shared box, and
2
+ // fewer while other sessions' runnable tasks already fill the machine. Oversubscribed cores do not
3
+ // finish work sooner; they turn timing-sensitive tests red.
4
+
5
+ // why: Bun ships no synchronous file read for `/proc/loadavg`.
6
+ import { readFileSync } from 'node:fs';
7
+ // why: Bun exposes no available-parallelism primitive.
8
+ import { availableParallelism } from 'node:os';
9
+ import type { HeavyEnv } from './heavy-env';
10
+ import { HEAVY_CORES_ENV, isCi } from './heavy-env';
11
+
12
+ export const LOCAL_CORE_CAP = 4;
13
+ /** A busy machine still gets this much, or one run behind a burst never makes progress. */
14
+ export const BUSY_CORE_FLOOR = 2;
15
+
16
+ /** The instantaneous runnable count: `/proc/loadavg`'s `running/total`. The load average lags. */
17
+ export function parseRunnable(loadavg: string): number | undefined {
18
+ const match = /^\S+\s+\S+\s+\S+\s+(\d+)\/\d+\s/.exec(loadavg);
19
+ return match === null ? undefined : Number(match[1]);
20
+ }
21
+
22
+ /** Runnable tasks now, this reader excluded; 0 where the kernel does not report them. */
23
+ export function runnableTasks(read: () => string = () => readFileSync('/proc/loadavg', 'utf8')) {
24
+ try {
25
+ return Math.max(0, (parseRunnable(read()) ?? 1) - 1);
26
+ } catch {
27
+ return 0;
28
+ }
29
+ }
30
+
31
+ /** `undefined` means no ceiling: a CI runner, whose every core is this run's. */
32
+ export function coreCap(
33
+ env: HeavyEnv,
34
+ cores: number = availableParallelism(),
35
+ runnable: number = runnableTasks(),
36
+ ): number | undefined {
37
+ const raw = Number(env[HEAVY_CORES_ENV]);
38
+ if (Number.isInteger(raw) && raw > 0) return raw;
39
+ if (isCi(env)) return undefined;
40
+ const ceiling = Math.min(LOCAL_CORE_CAP, Math.max(1, cores));
41
+ return Math.min(ceiling, Math.max(BUSY_CORE_FLOOR, cores - runnable));
42
+ }
43
+
44
+ /** Thread caps for the native tools: tsc is Go, biome is rayon. An exported value wins. */
45
+ export function nativeToolEnv(env: HeavyEnv, cap: number | undefined): Record<string, string> {
46
+ if (cap === undefined) return {};
47
+ return {
48
+ ...(env['GOMAXPROCS'] === undefined ? { GOMAXPROCS: String(cap) } : {}),
49
+ ...(env['RAYON_NUM_THREADS'] === undefined ? { RAYON_NUM_THREADS: String(cap) } : {}),
50
+ };
51
+ }
@@ -0,0 +1,21 @@
1
+ // Every environment variable the machine ledger reads or sets, and the one reading of `CI`. A leaf:
2
+ // the worker planner and the error classes need these names without loading the ledger.
3
+
4
+ export type HeavyEnv = Readonly<Record<string, string | undefined>>;
5
+
6
+ /** The ledger's directory. Set by a test or an unusual machine; also opts a test run back in. */
7
+ export const HEAVY_DIR_ENV = 'ULTIMATE_HEAVY_DIR';
8
+ /** What the ledger admits in total (`8g`), replacing half of RAM. `0` turns it off. */
9
+ export const HEAVY_MEMORY_ENV = 'ULTIMATE_HEAVY_MEMORY';
10
+ /** The local core ceiling, replacing `LOCAL_CORE_CAP`. */
11
+ export const HEAVY_CORES_ENV = 'ULTIMATE_HEAVY_CORES';
12
+ /** `0` turns the CPU half of admission off (`heavy-pressure.ts`); memory still applies. */
13
+ export const HEAVY_CPU_ENV = 'ULTIMATE_HEAVY_CPU';
14
+ /** Set on a holder's children: the reservation file they run inside. A protocol, not a knob. */
15
+ export const HEAVY_HOLD_ENV = 'ULTIMATE_HEAVY_HOLD';
16
+
17
+ /** A CI runner is single-tenant: nothing to queue behind, and every core is the run's. */
18
+ export const isCi = (env: HeavyEnv): boolean => {
19
+ const value = env['CI'];
20
+ return value !== undefined && value !== '' && value !== '0' && value !== 'false';
21
+ };
@@ -0,0 +1,54 @@
1
+ // The failures of the machine memory ledger. Admission is a courtesy between processes, so the two
2
+ // environment failures are reported and the work goes ahead; only `x heavy run` refuses anything.
3
+
4
+ import { UltimateError } from '@ultimat3/core';
5
+ import { HEAVY_MEMORY_ENV } from './heavy-env';
6
+ import type { LedgerWait } from './heavy-ledger';
7
+ import { quoteArg } from './shell-quote';
8
+
9
+ export class HeavyLedgerUnavailableError extends UltimateError {
10
+ constructor(reason: string) {
11
+ super({
12
+ code: 'X_HEAVY_LEDGER_UNAVAILABLE',
13
+ cause: `the machine memory ledger cannot be used: ${reason}; this run continues unadmitted`,
14
+ fix: 'x heavy status --json',
15
+ });
16
+ }
17
+ }
18
+
19
+ export class HeavyMemoryInvalidError extends UltimateError {
20
+ constructor(raw: string) {
21
+ super({
22
+ code: 'X_HEAVY_MEMORY_INVALID',
23
+ cause: `${HEAVY_MEMORY_ENV}=${JSON.stringify(raw)} is not a byte size`,
24
+ fix: 'export ULTIMATE_HEAVY_MEMORY=8g # or 0 to turn the ledger off',
25
+ });
26
+ }
27
+ }
28
+
29
+ export class HeavyCommandNotFoundError extends UltimateError {
30
+ constructor(command: string) {
31
+ super({
32
+ code: 'X_HEAVY_COMMAND_NOT_FOUND',
33
+ cause: `${JSON.stringify(command)} is not an executable on PATH`,
34
+ fix: `bun --print ${quoteArg(`Bun.which(${JSON.stringify(command)})`)} # null: install it or correct the name, then: x heavy run -- <command>`,
35
+ });
36
+ }
37
+ }
38
+
39
+ /** `--max-wait` ran out in the queue. The one refusal admission makes, and only when asked to. */
40
+ export class HeavyWaitExpiredError extends UltimateError {
41
+ constructor(input: {
42
+ readonly label: string;
43
+ readonly maxWaitMs: number;
44
+ readonly wait: LedgerWait;
45
+ }) {
46
+ const { wait } = input;
47
+ const holders = wait.holds.map((entry) => entry.label).join(', ') || 'an admission in progress';
48
+ super({
49
+ code: 'X_HEAVY_WAIT_EXPIRED',
50
+ cause: `${JSON.stringify(input.label)} was not admitted within --max-wait ${String(input.maxWaitMs / 1000)}s and did not start: it needs ${String(wait.needMb)} MB, was ${String(wait.position)} of ${String(wait.queued)} in the queue, and ${String(wait.usedMb)} of ${String(wait.capacityMb)} MB are held by ${holders}${wait.cpu === undefined ? '' : ', and the CPU was saturated'}; run it again later or with a longer --max-wait`,
51
+ fix: 'x heavy status --json',
52
+ });
53
+ }
54
+ }