@ultimat3/cli 31.48.0 → 31.50.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 (287) hide show
  1. package/CLAUDE.md +30 -23
  2. package/README.md +96 -4
  3. package/package.json +30 -30
  4. package/src/api-registration.ts +45 -14
  5. package/src/api-routes.ts +1 -0
  6. package/src/app-load.ts +7 -3
  7. package/src/app-openapi.ts +7 -1
  8. package/src/app-root.ts +7 -1
  9. package/src/budgets.ts +2 -1
  10. package/src/clean-services.ts +142 -0
  11. package/src/cmd-auth.ts +3 -0
  12. package/src/cmd-clean-spec.ts +10 -3
  13. package/src/cmd-clean.ts +23 -9
  14. package/src/cmd-db-backfill.ts +6 -0
  15. package/src/cmd-db-branch.ts +10 -4
  16. package/src/cmd-db-recount.ts +5 -12
  17. package/src/cmd-db-rollback.ts +77 -0
  18. package/src/cmd-db-spec.ts +18 -2
  19. package/src/cmd-db-status.ts +5 -10
  20. package/src/cmd-db.ts +105 -33
  21. package/src/cmd-deploy-verify.ts +14 -6
  22. package/src/cmd-docs-topic.ts +94 -0
  23. package/src/cmd-docs.ts +15 -1
  24. package/src/cmd-doctor.ts +109 -41
  25. package/src/cmd-drill.ts +80 -18
  26. package/src/cmd-env.ts +30 -8
  27. package/src/cmd-errors-app.ts +63 -0
  28. package/src/cmd-errors.ts +50 -14
  29. package/src/cmd-generate.ts +17 -4
  30. package/src/cmd-heavy-spec.ts +9 -1
  31. package/src/cmd-heavy.ts +111 -27
  32. package/src/cmd-i18n.ts +33 -1
  33. package/src/cmd-jobs.ts +27 -1
  34. package/src/cmd-merge-driver-spec.ts +12 -0
  35. package/src/cmd-merge-driver.ts +95 -0
  36. package/src/cmd-new.ts +23 -3
  37. package/src/cmd-policy-spec.ts +9 -1
  38. package/src/cmd-policy.ts +72 -17
  39. package/src/cmd-stop.ts +18 -4
  40. package/src/cmd-tasks-run.ts +87 -0
  41. package/src/cmd-tasks-spec.ts +10 -3
  42. package/src/cmd-tasks.ts +8 -5
  43. package/src/cmd-test.ts +2 -1
  44. package/src/cmd-upgrade-spec.ts +8 -1
  45. package/src/cmd-upgrade.ts +15 -1
  46. package/src/cmd-verify.ts +9 -41
  47. package/src/codemods/agents-doc-row.ts +73 -0
  48. package/src/codemods/define-error-leaf.ts +37 -12
  49. package/src/codemods/docs-many-agents.ts +11 -15
  50. package/src/codemods/docs-worker-commands.ts +26 -0
  51. package/src/codemods/engine-fs.ts +9 -2
  52. package/src/codemods/index.ts +4 -0
  53. package/src/codemods/merge-drivers.ts +147 -0
  54. package/src/command.ts +3 -0
  55. package/src/db-applied-edits.ts +117 -0
  56. package/src/db-dev-wire.ts +18 -0
  57. package/src/db-diagnostics.ts +5 -10
  58. package/src/db-generate.ts +82 -7
  59. package/src/db-migrate-pass.ts +51 -0
  60. package/src/db-migrate-through-dev.ts +209 -0
  61. package/src/db-rollback-consent.ts +128 -0
  62. package/src/db-rollback-pass.ts +76 -0
  63. package/src/db-seed-generate.ts +5 -1
  64. package/src/db-seed.ts +7 -1
  65. package/src/deploy-verify-findings.ts +3 -0
  66. package/src/deploy-verify-grade.ts +3 -0
  67. package/src/deploy-verify-processes.ts +32 -0
  68. package/src/dev-boot.ts +3 -0
  69. package/src/dev-db-migrate.ts +155 -0
  70. package/src/dev-db-rollback.ts +33 -0
  71. package/src/dev-db-settled.ts +22 -0
  72. package/src/dev-lock-errors.ts +78 -0
  73. package/src/dev-lock-holder-dir.ts +64 -0
  74. package/src/dev-lock-live.ts +44 -0
  75. package/src/dev-lock.ts +59 -84
  76. package/src/dev-policy.ts +11 -8
  77. package/src/dev-rebuild-schema.ts +116 -13
  78. package/src/dev-rebuild.ts +13 -4
  79. package/src/dev-route-table.ts +7 -0
  80. package/src/dispatch.ts +21 -1
  81. package/src/doctor-api-listing.ts +114 -0
  82. package/src/doctor-guarded.ts +41 -0
  83. package/src/doctor-port.ts +90 -17
  84. package/src/doctor-probe.ts +36 -5
  85. package/src/doctor-processes-probe.ts +127 -0
  86. package/src/doctor-processes.ts +136 -0
  87. package/src/doctor-warnings.ts +17 -0
  88. package/src/error-codes-agents.ts +35 -0
  89. package/src/error-codes-processes.ts +30 -0
  90. package/src/error-codes-tooling.ts +2 -0
  91. package/src/error-codes.ts +12 -13
  92. package/src/errors-suite.ts +27 -0
  93. package/src/errors.ts +18 -22
  94. package/src/exercise-registration.ts +4 -3
  95. package/src/exercise-services.ts +13 -3
  96. package/src/framework-env.ts +7 -3
  97. package/src/framework-schema.ts +15 -5
  98. package/src/generate-files.ts +1 -0
  99. package/src/generate-grant-findings.ts +7 -5
  100. package/src/generate-grants.ts +9 -8
  101. package/src/generate-kinds.ts +30 -6
  102. package/src/generate-roles-file.ts +30 -0
  103. package/src/generate-slice-policy.ts +3 -3
  104. package/src/guard-sources.ts +1 -2
  105. package/src/guards.ts +2 -2
  106. package/src/heavy-env.ts +2 -0
  107. package/src/heavy-errors.ts +18 -0
  108. package/src/heavy-holders.ts +78 -0
  109. package/src/heavy-ledger.ts +56 -14
  110. package/src/heavy-pressure.ts +104 -0
  111. package/src/heavy.ts +31 -13
  112. package/src/i18n-registration.ts +22 -2
  113. package/src/island-harness.ts +2 -2
  114. package/src/job-budget.ts +4 -2
  115. package/src/job-registration.ts +64 -8
  116. package/src/jobs-queue-known.ts +43 -0
  117. package/src/mcp-errors-agents.ts +20 -0
  118. package/src/mcp-errors-doctor.ts +27 -0
  119. package/src/mcp-errors-processes.ts +23 -0
  120. package/src/mcp-errors.ts +15 -29
  121. package/src/mcp-host.ts +2 -2
  122. package/src/merge-driver-catalog.ts +58 -0
  123. package/src/merge-driver-config.ts +43 -0
  124. package/src/merge-driver-lines.ts +140 -0
  125. package/src/merge-state.ts +105 -0
  126. package/src/messages-db.ts +22 -1
  127. package/src/messages-processes.ts +13 -0
  128. package/src/messages-upgrade.ts +10 -0
  129. package/src/messages.ts +54 -4
  130. package/src/output-findings.ts +48 -21
  131. package/src/page-navigation.ts +5 -2
  132. package/src/parse.ts +37 -6
  133. package/src/policy-facts.ts +38 -21
  134. package/src/policy-row.ts +99 -0
  135. package/src/port-pair-free.ts +28 -0
  136. package/src/pwa-artifacts.ts +1 -1
  137. package/src/registry-lines.ts +110 -0
  138. package/src/registry.ts +2 -0
  139. package/src/retain-sweep.ts +1 -1
  140. package/src/retained-assets-boot.ts +1 -1
  141. package/src/role-replicator.ts +4 -1
  142. package/src/role-select.ts +86 -0
  143. package/src/role-start.ts +13 -55
  144. package/src/role-sync.ts +10 -5
  145. package/src/runtime-assets-site.ts +2 -2
  146. package/src/runtime-assets.ts +1 -1
  147. package/src/runtime-cache-frame.ts +46 -0
  148. package/src/runtime-cache-ttl.ts +23 -0
  149. package/src/runtime-cache.ts +33 -16
  150. package/src/runtime-database-ssl.ts +84 -0
  151. package/src/runtime-idempotency-scope.ts +16 -2
  152. package/src/runtime-jobs-share.ts +52 -0
  153. package/src/runtime-jobs.ts +43 -12
  154. package/src/runtime-queue.ts +18 -3
  155. package/src/runtime-render-document.ts +1 -2
  156. package/src/runtime-services.ts +8 -1
  157. package/src/schema-drift.ts +19 -2
  158. package/src/schema-dump-drift.ts +4 -1
  159. package/src/serve-boot-probe.ts +30 -2
  160. package/src/serve-boot.ts +11 -1
  161. package/src/serve-env.ts +39 -3
  162. package/src/serve.ts +61 -10
  163. package/src/site-asset-routes.ts +2 -2
  164. package/src/site-assets.ts +5 -158
  165. package/src/stop-run-start.ts +12 -0
  166. package/src/supervise-boot.ts +61 -0
  167. package/src/supervise-cgroup.ts +84 -0
  168. package/src/supervise-child.ts +206 -0
  169. package/src/supervise-count.ts +244 -0
  170. package/src/supervise-errors.ts +83 -0
  171. package/src/supervise-facts.ts +40 -0
  172. package/src/supervise-messages.ts +84 -0
  173. package/src/supervise-policy.ts +46 -0
  174. package/src/supervise-pool.ts +10 -0
  175. package/src/supervise-probe.ts +158 -0
  176. package/src/supervise-run.ts +54 -0
  177. package/src/supervise.ts +383 -0
  178. package/src/sw-precache-plan.ts +1 -1
  179. package/src/templates/generate-purge.ts +6 -6
  180. package/src/templates/guard-animated-layout-property.ts +2 -2
  181. package/src/templates/guard-bare-error.ts +1 -1
  182. package/src/templates/guard-error-declared.ts +2 -2
  183. package/src/templates/guard-focus-visible.ts +1 -1
  184. package/src/templates/guard-image-dimensions.ts +2 -2
  185. package/src/templates/guard-island-mount-clears.ts +1 -1
  186. package/src/templates/guard-native-confirm.ts +1 -1
  187. package/src/templates/guard-raw-breakpoint.ts +2 -2
  188. package/src/templates/guard-raw-colour.ts +2 -2
  189. package/src/templates/guard-raw-fetch.ts +1 -1
  190. package/src/templates/guard-raw-interval.ts +1 -1
  191. package/src/templates/guard-raw-length.ts +3 -3
  192. package/src/templates/guard-raw-motion.ts +97 -1
  193. package/src/templates/guard-raw-shadow.ts +1 -1
  194. package/src/templates/guard-raw-z-index.ts +1 -1
  195. package/src/templates/guard-released-forms.ts +58 -9
  196. package/src/templates/guard-repo-await-in-loop.ts +1 -1
  197. package/src/templates/guard-repo-raw-sql.ts +4 -4
  198. package/src/templates/guard-repo-unbounded.ts +1 -1
  199. package/src/templates/guard-runtime-pin.ts +1 -1
  200. package/src/templates/guard-semantic-interactive.ts +2 -2
  201. package/src/templates/guard-unbounded-fanout.ts +1 -1
  202. package/src/templates/guard-undeclared-custom-property.ts +3 -3
  203. package/src/templates/guard-undefined-style-class.ts +3 -3
  204. package/src/templates/guard-unzoned-date.ts +3 -3
  205. package/src/templates/query-slice.ts +82 -0
  206. package/src/templates/query.ts +76 -30
  207. package/src/templates/resource-page.ts +3 -2
  208. package/src/templates/scaffold-bin.ts +2 -0
  209. package/src/templates/scaffold-claude-commands.ts +6 -0
  210. package/src/templates/scaffold-claude.ts +4 -4
  211. package/src/templates/scaffold-container-compose.ts +47 -7
  212. package/src/templates/scaffold-docs.ts +7 -3
  213. package/src/templates/scaffold-gitattributes.ts +18 -1
  214. package/src/templates/scaffold-helm-templates.ts +9 -0
  215. package/src/templates/scaffold-repo.ts +5 -2
  216. package/src/templates/scaffold-test-services.ts +33 -11
  217. package/src/templates/shapes/offline.ts +0 -7
  218. package/src/templates/shapes/realtime.ts +2 -6
  219. package/src/templates/sign-in-action-tests.ts +6 -4
  220. package/src/templates/sign-in-challenge.ts +62 -0
  221. package/src/templates/sign-in-oidc-mfa.ts +31 -0
  222. package/src/templates/sign-in-oidc.ts +11 -3
  223. package/src/templates/sign-in-password.ts +18 -56
  224. package/src/test-only-shipped.ts +29 -2
  225. package/src/test-shards.ts +134 -42
  226. package/src/test-verdict.ts +79 -0
  227. package/src/test-workers.ts +15 -0
  228. package/src/upgrade-coverage-ratchet.ts +95 -0
  229. package/src/upgrade-gate-codemods.ts +5 -3
  230. package/src/upgrade-gate.ts +42 -4
  231. package/src/upgrade-merge-drivers.ts +25 -0
  232. package/src/upgrade-report.ts +32 -4
  233. package/src/upgrade-scope.ts +62 -0
  234. package/src/verify-checks.ts +2 -8
  235. package/src/verify-coverage-run.ts +4 -1
  236. package/src/verify-e2e.ts +21 -3
  237. package/src/verify-live.ts +38 -14
  238. package/src/verify-only.ts +67 -0
  239. package/src/verify-progress.ts +7 -3
  240. package/src/verify-run.ts +20 -2
  241. package/src/verify-services-stack.ts +165 -0
  242. package/src/verify-services.ts +84 -2
  243. package/src/verify-test-run.ts +6 -7
  244. package/src/verify-tests.ts +8 -2
  245. package/src/verify-typecheck.ts +25 -2
  246. package/src/workspace-checks.ts +4 -1
  247. package/wiki/Actions.md +66 -3
  248. package/wiki/Admin-Dashboard.md +2 -2
  249. package/wiki/Agents.md +5 -5
  250. package/wiki/Auth.md +20 -6
  251. package/wiki/Bare-VM.md +1 -1
  252. package/wiki/CI-Parallel-Gate.md +2 -1
  253. package/wiki/CLI-Reference.md +115 -42
  254. package/wiki/Caching-And-Invalidation.md +1 -1
  255. package/wiki/Client-Navigation.md +35 -5
  256. package/wiki/Configuration.md +12 -10
  257. package/wiki/Deployment.md +44 -4
  258. package/wiki/Entities-And-Migrations.md +17 -3
  259. package/wiki/FAQ.md +1 -1
  260. package/wiki/Getting-Started.md +2 -2
  261. package/wiki/Home.md +3 -3
  262. package/wiki/I18n.md +6 -4
  263. package/wiki/Installation.md +12 -11
  264. package/wiki/Interface-Rules.md +3 -1
  265. package/wiki/Jobs-And-Workflows.md +24 -4
  266. package/wiki/Known-Gaps.md +2 -2
  267. package/wiki/MCP-And-AI.md +48 -13
  268. package/wiki/Many-Agents.md +69 -2
  269. package/wiki/Migrations-And-Backfills.md +18 -0
  270. package/wiki/Notify.md +5 -3
  271. package/wiki/Observability.md +13 -0
  272. package/wiki/Outbound-HTTP.md +53 -2
  273. package/wiki/Policies-And-Authz.md +1 -1
  274. package/wiki/Queries-And-Live-Queries.md +2 -2
  275. package/wiki/Realtime.md +24 -7
  276. package/wiki/Routes-And-Render-Modes.md +2 -2
  277. package/wiki/Scheduled-Tasks.md +4 -1
  278. package/wiki/Static-Assets.md +5 -3
  279. package/wiki/Testing.md +64 -7
  280. package/wiki/Theming.md +6 -3
  281. package/wiki/Timezones-And-Dates.md +5 -1
  282. package/wiki/Troubleshooting.md +1 -0
  283. package/wiki/Tutorial-01-First-App.md +3 -3
  284. package/wiki/Tutorial-02-First-Feature.md +1 -1
  285. package/wiki/Tutorial-03-Auth-And-Admin.md +7 -6
  286. package/wiki/UI-Components.md +1 -0
  287. package/wiki/Upgrading.md +38 -0
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. `..`
@@ -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
 
@@ -1,10 +1,12 @@
1
1
  // The runtime services a server's boot installs (`runtime-services.ts`) that `x exercise` stands in
2
- // for: a storage disk, a fleet-wide rate-limit store and the Web Push runtime, over the pass's
3
- // scratch database. Without them every primitive reading one stopped on a boot-only refusal and
2
+ // for: a storage disk, a fleet-wide rate-limit store, the fleet-wide auth limiter and the Web Push
3
+ // runtime, over the pass's scratch database. Without them every primitive reading one stopped on a boot-only refusal and
4
4
  // the app had to declare `{ off }` for it — the pass's job, not the app's.
5
5
 
6
+ import { postgresAuthLimiter } from '@ultimat3/auth';
7
+ import { installAuthLimiters } from '@ultimat3/auth/adapter';
6
8
  import type { AppConfig, PgExecutor } from '@ultimat3/core';
7
- import { ENVIRONMENT_KEY } from '@ultimat3/core';
9
+ import { ENVIRONMENT_KEY, systemClock } from '@ultimat3/core';
8
10
  import { postgresRateLimitStore } from '@ultimat3/http';
9
11
  import { installRateLimitStore } from '@ultimat3/http/adapter';
10
12
  import {
@@ -76,6 +78,14 @@ export async function installExerciseServices(inputs: ExerciseServiceInputs): Pr
76
78
  // `scope: 'shared'`, as the boot's: a `rateLimit: { scope: 'shared' }` declaration is judged
77
79
  // against the installed store, and one process' memory refused it with X_RATE_LIMIT_NOT_SHARED.
78
80
  released.push(installRateLimitStore(postgresRateLimitStore({ executor: inputs.executor })));
81
+ // The boot's auth limiter for the same reason: `defineAuth({ rateLimit: { scope: 'shared' } })`
82
+ // judged against one process' memory refused every action that reserves an attempt with
83
+ // X_AUTH_LIMITER_NOT_SHARED. Built per declared policy, over the scratch `x_auth_lockouts`.
84
+ released.push(
85
+ installAuthLimiters((policy) =>
86
+ postgresAuthLimiter({ executor: inputs.executor, clock: systemClock, policy }),
87
+ ),
88
+ );
79
89
  // Last, and the one that can refuse (a half VAPID pair): what is already in is undone first.
80
90
  released.push(await installPush(inputs));
81
91
  } catch (error) {
@@ -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' }) !==
@@ -6,7 +6,12 @@
6
6
  // A framework table an app has to install by hand is a table that will be missing in production on
7
7
  // the one code path that needs it, and it surfaces as a Postgres `42P01` from inside a worker.
8
8
 
9
- import { SQL_AUDIT_TABLE, SQL_IDEMPOTENCY_TABLE, SQL_METER_TABLE } from '@ultimat3/action';
9
+ import {
10
+ SQL_AUDIT_TABLE,
11
+ SQL_IDEMPOTENCY_TABLE,
12
+ SQL_METER_KEY_TABLE,
13
+ SQL_METER_TABLE,
14
+ } from '@ultimat3/action';
10
15
  import {
11
16
  ADMIN_AUDIT_TABLE,
12
17
  ERROR_GROUPS_TABLE,
@@ -100,12 +105,17 @@ export const FRAMEWORK_SCHEMA: readonly FrameworkSchema[] = Object.freeze([
100
105
  tables: Object.freeze(['x_audit']),
101
106
  ddl: Object.freeze([SQL_AUDIT_TABLE]),
102
107
  }),
103
- // The counters behind `meter:`. One row per tenant × meter × period declaration, rolled over in
104
- // place, so it ships no purge: the table is bounded by its subjects, never by time.
108
+ // The counters behind `meter:` and `drawMeter`. One row per tenant × meter × period declaration,
109
+ // rolled over in place, so it ships no purge: the table is bounded by its subjects, never by
110
+ // time. `x_meter_key` holds one row per counted keyed draw, about two periods of them per active
111
+ // counter: a keyed draw that counts prunes its counter's older rows, and an idle counter keeps
112
+ // its last rows until its next one.
113
+ // `SQL_METER_KEY_TABLE` also creates `x_meter_key_counted`, the function a refused keyed draw
114
+ // reads its key through: not a table, so it is in no `tables` list.
105
115
  Object.freeze({
106
116
  pkg: '@ultimat3/action',
107
- tables: Object.freeze(['x_meter']),
108
- ddl: Object.freeze([SQL_METER_TABLE]),
117
+ tables: Object.freeze(['x_meter', 'x_meter_key']),
118
+ ddl: Object.freeze([SQL_METER_TABLE, SQL_METER_KEY_TABLE]),
109
119
  }),
110
120
  Object.freeze({
111
121
  pkg: '@ultimat3/http',
@@ -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'}');`;
@@ -90,9 +90,8 @@ export function guardSources(
90
90
  const source = await textOf(path);
91
91
  // Imported here, not at the top: Sass loads on the first compile, and a gate run whose
92
92
  // guards compile nothing must not pay for the compiler (`sass-lazy.test.ts`).
93
- const { compileStylesheet } = await import('@ultimat3/render/server');
93
+ const { compileStylesheet, siteAssetTable } = await import('@ultimat3/render/server');
94
94
  const { setAssetResolver } = await import('@ultimat3/render');
95
- const { siteAssetTable } = await import('./site-assets');
96
95
  // A sheet's `asset()` resolves through the table `loadApp` installs for the build — the same
97
96
  // table, so a file the app holds compiles and one it does not is `X_ASSET_MISSING`. Installed
98
97
  // around the one synchronous compile and handed back after: no await runs in between, so no
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
  });
package/src/heavy-env.ts CHANGED
@@ -9,6 +9,8 @@ export const HEAVY_DIR_ENV = 'ULTIMATE_HEAVY_DIR';
9
9
  export const HEAVY_MEMORY_ENV = 'ULTIMATE_HEAVY_MEMORY';
10
10
  /** The local core ceiling, replacing `LOCAL_CORE_CAP`. */
11
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';
12
14
  /** Set on a holder's children: the reservation file they run inside. A protocol, not a knob. */
13
15
  export const HEAVY_HOLD_ENV = 'ULTIMATE_HEAVY_HOLD';
14
16
 
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { UltimateError } from '@ultimat3/core';
5
5
  import { HEAVY_MEMORY_ENV } from './heavy-env';
6
+ import type { LedgerWait } from './heavy-ledger';
6
7
  import { quoteArg } from './shell-quote';
7
8
 
8
9
  export class HeavyLedgerUnavailableError extends UltimateError {
@@ -34,3 +35,20 @@ export class HeavyCommandNotFoundError extends UltimateError {
34
35
  });
35
36
  }
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
+ }
@@ -0,0 +1,78 @@
1
+ // Which processes keep a reservation alive: every process with its lock file open, as the OS sees
2
+ // it. The ledger records only the wrapper's pid, and after `kill -9` of the wrapper the memory is
3
+ // held by the command it started, so a recorded pid cannot say what would free it.
4
+
5
+ // why: Bun ships no directory listing, readlink or realpath primitive.
6
+ import { existsSync, readdirSync, readlinkSync, realpathSync } from 'node:fs';
7
+ // why: Bun ships no path-join primitive.
8
+ import { join } from 'node:path';
9
+ import type { Runner } from './exec';
10
+
11
+ const PROC = '/proc';
12
+
13
+ function realOrSame(path: string): string {
14
+ try {
15
+ return realpathSync(path);
16
+ } catch {
17
+ return path; // Released while being asked about: nothing will match it, which is the answer.
18
+ }
19
+ }
20
+
21
+ function hasOpen(procRoot: string, pid: string, target: string): boolean {
22
+ const fds = join(procRoot, pid, 'fd');
23
+ try {
24
+ return readdirSync(fds).some((fd) => {
25
+ try {
26
+ return readlinkSync(join(fds, fd)) === target;
27
+ } catch {
28
+ return false; // The descriptor closed between the listing and the read.
29
+ }
30
+ });
31
+ } catch {
32
+ return false; // The process exited, or belongs to another user.
33
+ }
34
+ }
35
+
36
+ const parsePids = (text: string): readonly number[] =>
37
+ text
38
+ .split('\n')
39
+ .map((line) => line.trim())
40
+ .filter((line) => /^\d+$/.test(line))
41
+ .map(Number);
42
+
43
+ /**
44
+ * The pids with `file` open, this process excepted, or `undefined` when the OS will not say: `/proc`
45
+ * where it exists, `lsof` elsewhere (macOS; Windows has no ledger).
46
+ */
47
+ export async function holderPids(
48
+ file: string,
49
+ runner: Runner,
50
+ cwd: string,
51
+ procRoot: string = PROC,
52
+ ): Promise<readonly number[] | undefined> {
53
+ if (existsSync(join(procRoot, 'self', 'fd'))) {
54
+ const target = realOrSame(file);
55
+ return readdirSync(procRoot)
56
+ .filter((name) => /^\d+$/.test(name) && Number(name) !== process.pid)
57
+ .filter((pid) => hasOpen(procRoot, pid, target))
58
+ .map(Number)
59
+ .sort((a, b) => a - b);
60
+ }
61
+ try {
62
+ // `lsof` exits 1 for "nobody has it open", so its stdout is read whatever the status.
63
+ const result = await runner(['lsof', '-t', file], { cwd });
64
+ return parsePids(result.stdout).filter((pid) => pid !== process.pid);
65
+ } catch {
66
+ return undefined; // No `lsof` on this machine.
67
+ }
68
+ }
69
+
70
+ /** The fallback when no holder list exists. Signal 0 delivers nothing; it only asks. */
71
+ export function isProcessRunning(pid: number): boolean {
72
+ try {
73
+ process.kill(pid, 0);
74
+ return true;
75
+ } catch {
76
+ return false;
77
+ }
78
+ }