@ultimat3/cli 31.48.0 → 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 (260) 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 +80 -18
  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 +9 -1
  28. package/src/cmd-heavy.ts +111 -27
  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 +2 -1
  40. package/src/cmd-upgrade-spec.ts +8 -1
  41. package/src/cmd-upgrade.ts +15 -1
  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 +11 -15
  46. package/src/codemods/docs-worker-commands.ts +26 -0
  47. package/src/codemods/index.ts +4 -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-api-listing.ts +114 -0
  77. package/src/doctor-guarded.ts +41 -0
  78. package/src/doctor-port.ts +90 -17
  79. package/src/doctor-probe.ts +36 -5
  80. package/src/doctor-processes-probe.ts +127 -0
  81. package/src/doctor-processes.ts +136 -0
  82. package/src/doctor-warnings.ts +17 -0
  83. package/src/error-codes-agents.ts +35 -0
  84. package/src/error-codes-processes.ts +30 -0
  85. package/src/error-codes-tooling.ts +2 -0
  86. package/src/error-codes.ts +12 -13
  87. package/src/errors-suite.ts +27 -0
  88. package/src/errors.ts +18 -22
  89. package/src/exercise-registration.ts +4 -3
  90. package/src/framework-env.ts +7 -3
  91. package/src/generate-files.ts +1 -0
  92. package/src/generate-grant-findings.ts +7 -5
  93. package/src/generate-grants.ts +9 -8
  94. package/src/generate-kinds.ts +30 -6
  95. package/src/generate-roles-file.ts +30 -0
  96. package/src/generate-slice-policy.ts +3 -3
  97. package/src/guards.ts +2 -2
  98. package/src/heavy-env.ts +2 -0
  99. package/src/heavy-errors.ts +18 -0
  100. package/src/heavy-holders.ts +78 -0
  101. package/src/heavy-ledger.ts +56 -14
  102. package/src/heavy-pressure.ts +104 -0
  103. package/src/heavy.ts +31 -13
  104. package/src/i18n-registration.ts +22 -2
  105. package/src/island-harness.ts +2 -2
  106. package/src/job-budget.ts +4 -2
  107. package/src/job-registration.ts +64 -8
  108. package/src/jobs-queue-known.ts +43 -0
  109. package/src/mcp-errors-agents.ts +20 -0
  110. package/src/mcp-errors-doctor.ts +27 -0
  111. package/src/mcp-errors-processes.ts +23 -0
  112. package/src/mcp-errors.ts +15 -29
  113. package/src/mcp-host.ts +2 -2
  114. package/src/merge-driver-catalog.ts +58 -0
  115. package/src/merge-driver-config.ts +43 -0
  116. package/src/merge-driver-lines.ts +140 -0
  117. package/src/merge-state.ts +105 -0
  118. package/src/messages-db.ts +22 -1
  119. package/src/messages-processes.ts +13 -0
  120. package/src/messages-upgrade.ts +6 -0
  121. package/src/messages.ts +54 -4
  122. package/src/output-findings.ts +48 -21
  123. package/src/parse.ts +37 -6
  124. package/src/policy-facts.ts +38 -21
  125. package/src/policy-row.ts +99 -0
  126. package/src/port-pair-free.ts +28 -0
  127. package/src/registry-lines.ts +110 -0
  128. package/src/registry.ts +2 -0
  129. package/src/retain-sweep.ts +1 -1
  130. package/src/role-replicator.ts +4 -1
  131. package/src/role-select.ts +86 -0
  132. package/src/role-start.ts +13 -55
  133. package/src/role-sync.ts +10 -5
  134. package/src/runtime-cache-frame.ts +46 -0
  135. package/src/runtime-cache-ttl.ts +23 -0
  136. package/src/runtime-cache.ts +33 -16
  137. package/src/runtime-database-ssl.ts +84 -0
  138. package/src/runtime-idempotency-scope.ts +16 -2
  139. package/src/runtime-jobs-share.ts +52 -0
  140. package/src/runtime-jobs.ts +43 -12
  141. package/src/runtime-queue.ts +18 -3
  142. package/src/runtime-services.ts +8 -1
  143. package/src/schema-drift.ts +19 -2
  144. package/src/schema-dump-drift.ts +4 -1
  145. package/src/serve-boot-probe.ts +30 -2
  146. package/src/serve-boot.ts +11 -1
  147. package/src/serve-env.ts +39 -3
  148. package/src/serve.ts +61 -10
  149. package/src/stop-run-start.ts +12 -0
  150. package/src/supervise-boot.ts +61 -0
  151. package/src/supervise-cgroup.ts +84 -0
  152. package/src/supervise-child.ts +206 -0
  153. package/src/supervise-count.ts +244 -0
  154. package/src/supervise-errors.ts +83 -0
  155. package/src/supervise-facts.ts +40 -0
  156. package/src/supervise-messages.ts +84 -0
  157. package/src/supervise-policy.ts +46 -0
  158. package/src/supervise-pool.ts +10 -0
  159. package/src/supervise-probe.ts +158 -0
  160. package/src/supervise-run.ts +54 -0
  161. package/src/supervise.ts +383 -0
  162. package/src/templates/generate-purge.ts +6 -6
  163. package/src/templates/guard-animated-layout-property.ts +2 -2
  164. package/src/templates/guard-bare-error.ts +1 -1
  165. package/src/templates/guard-error-declared.ts +2 -2
  166. package/src/templates/guard-focus-visible.ts +1 -1
  167. package/src/templates/guard-image-dimensions.ts +2 -2
  168. package/src/templates/guard-island-mount-clears.ts +1 -1
  169. package/src/templates/guard-native-confirm.ts +1 -1
  170. package/src/templates/guard-raw-breakpoint.ts +2 -2
  171. package/src/templates/guard-raw-colour.ts +2 -2
  172. package/src/templates/guard-raw-fetch.ts +1 -1
  173. package/src/templates/guard-raw-interval.ts +1 -1
  174. package/src/templates/guard-raw-length.ts +3 -3
  175. package/src/templates/guard-raw-motion.ts +1 -1
  176. package/src/templates/guard-raw-shadow.ts +1 -1
  177. package/src/templates/guard-raw-z-index.ts +1 -1
  178. package/src/templates/guard-released-forms.ts +54 -8
  179. package/src/templates/guard-repo-await-in-loop.ts +1 -1
  180. package/src/templates/guard-repo-raw-sql.ts +4 -4
  181. package/src/templates/guard-repo-unbounded.ts +1 -1
  182. package/src/templates/guard-runtime-pin.ts +1 -1
  183. package/src/templates/guard-semantic-interactive.ts +2 -2
  184. package/src/templates/guard-unbounded-fanout.ts +1 -1
  185. package/src/templates/guard-undeclared-custom-property.ts +3 -3
  186. package/src/templates/guard-undefined-style-class.ts +3 -3
  187. package/src/templates/guard-unzoned-date.ts +3 -3
  188. package/src/templates/query-slice.ts +82 -0
  189. package/src/templates/query.ts +76 -30
  190. package/src/templates/resource-page.ts +3 -2
  191. package/src/templates/scaffold-bin.ts +2 -0
  192. package/src/templates/scaffold-claude-commands.ts +6 -0
  193. package/src/templates/scaffold-claude.ts +4 -4
  194. package/src/templates/scaffold-container-compose.ts +47 -7
  195. package/src/templates/scaffold-docs.ts +7 -3
  196. package/src/templates/scaffold-gitattributes.ts +18 -1
  197. package/src/templates/scaffold-helm-templates.ts +9 -0
  198. package/src/templates/scaffold-repo.ts +4 -1
  199. package/src/templates/scaffold-test-services.ts +33 -11
  200. package/src/templates/shapes/offline.ts +0 -7
  201. package/src/templates/shapes/realtime.ts +2 -6
  202. package/src/templates/sign-in-action-tests.ts +6 -4
  203. package/src/templates/sign-in-challenge.ts +62 -0
  204. package/src/templates/sign-in-oidc-mfa.ts +31 -0
  205. package/src/templates/sign-in-oidc.ts +11 -3
  206. package/src/templates/sign-in-password.ts +18 -56
  207. package/src/test-shards.ts +114 -34
  208. package/src/test-verdict.ts +79 -0
  209. package/src/test-workers.ts +15 -0
  210. package/src/upgrade-gate-codemods.ts +5 -3
  211. package/src/upgrade-gate.ts +19 -1
  212. package/src/upgrade-merge-drivers.ts +25 -0
  213. package/src/upgrade-report.ts +18 -4
  214. package/src/upgrade-scope.ts +62 -0
  215. package/src/verify-checks.ts +2 -8
  216. package/src/verify-coverage-run.ts +4 -1
  217. package/src/verify-live.ts +38 -14
  218. package/src/verify-only.ts +67 -0
  219. package/src/verify-progress.ts +7 -3
  220. package/src/verify-run.ts +20 -2
  221. package/src/verify-services-stack.ts +165 -0
  222. package/src/verify-services.ts +84 -2
  223. package/src/verify-test-run.ts +6 -7
  224. package/src/verify-tests.ts +8 -2
  225. package/src/verify-typecheck.ts +25 -2
  226. package/wiki/Actions.md +2 -1
  227. package/wiki/Admin-Dashboard.md +2 -2
  228. package/wiki/Agents.md +5 -5
  229. package/wiki/Auth.md +15 -5
  230. package/wiki/Bare-VM.md +1 -1
  231. package/wiki/CI-Parallel-Gate.md +2 -1
  232. package/wiki/CLI-Reference.md +107 -40
  233. package/wiki/Caching-And-Invalidation.md +1 -1
  234. package/wiki/Client-Navigation.md +1 -1
  235. package/wiki/Configuration.md +10 -9
  236. package/wiki/Deployment.md +44 -4
  237. package/wiki/Entities-And-Migrations.md +5 -1
  238. package/wiki/FAQ.md +1 -1
  239. package/wiki/Getting-Started.md +2 -2
  240. package/wiki/Home.md +1 -1
  241. package/wiki/I18n.md +5 -3
  242. package/wiki/Installation.md +12 -11
  243. package/wiki/Jobs-And-Workflows.md +24 -4
  244. package/wiki/Known-Gaps.md +1 -1
  245. package/wiki/MCP-And-AI.md +8 -5
  246. package/wiki/Many-Agents.md +69 -2
  247. package/wiki/Migrations-And-Backfills.md +18 -0
  248. package/wiki/Notify.md +1 -1
  249. package/wiki/Observability.md +13 -0
  250. package/wiki/Queries-And-Live-Queries.md +2 -2
  251. package/wiki/Realtime.md +10 -1
  252. package/wiki/Routes-And-Render-Modes.md +1 -1
  253. package/wiki/Scheduled-Tasks.md +4 -1
  254. package/wiki/Testing.md +7 -4
  255. package/wiki/Timezones-And-Dates.md +5 -1
  256. package/wiki/Troubleshooting.md +1 -0
  257. package/wiki/Tutorial-01-First-App.md +3 -3
  258. package/wiki/Tutorial-02-First-Feature.md +1 -1
  259. package/wiki/Tutorial-03-Auth-And-Admin.md +7 -6
  260. package/wiki/Upgrading.md +37 -0
package/src/parse.ts CHANGED
@@ -122,11 +122,40 @@ export const wantsJson = (argv: readonly string[]): boolean =>
122
122
  const HELP_ALIASES = new Set(['--help', '-h', 'help']);
123
123
  const VERSION_ALIASES = new Set(['--version', '-v', '-V']);
124
124
 
125
+ // What an unknown top-level word most likely MEANT, ahead of what it merely resembles. Edit
126
+ // distance answered `x migrate` with `x upgrade` and `x start` with `x stop`: a `fix:` is pasted
127
+ // and run, so a guess that changes state is worse than no guess.
128
+ /**
129
+ * A word other toolchains use, as the `x` argv that does it. Each is held to the shipped parser by
130
+ * `parse.test.ts`, so an entry cannot outlive the command it names.
131
+ */
132
+ export const COMMAND_INTENTS: Readonly<Record<string, readonly string[]>> = Object.freeze({
133
+ migrate: ['db', 'migrate'],
134
+ seed: ['db', 'seed'],
135
+ start: ['dev'],
136
+ serve: ['dev'],
137
+ server: ['dev'],
138
+ lint: ['verify', '--only', 'lint'],
139
+ typecheck: ['verify', '--only', 'typecheck'],
140
+ tsc: ['verify', '--only', 'typecheck'],
141
+ check: ['verify'],
142
+ });
143
+
144
+ /** The suggestion for `word` (`'db migrate'`), when `commands` has the command it starts with. */
145
+ export function intentFor(word: string, commands: readonly string[]): string | undefined {
146
+ const argv = Object.hasOwn(COMMAND_INTENTS, word) ? COMMAND_INTENTS[word] : undefined;
147
+ const [command] = argv ?? [];
148
+ return argv !== undefined && command !== undefined && commands.includes(command)
149
+ ? argv.join(' ')
150
+ : undefined;
151
+ }
152
+
125
153
  function resolveCommand(token: string, specs: readonly CommandSpec[]): CommandSpec {
126
154
  const found = specs.find((spec) => spec.name === token || (spec.aliases ?? []).includes(token));
127
155
  if (found !== undefined) return found;
128
156
  const names = specs.map((spec) => spec.name);
129
- const suggestion = nearestName(token, names);
157
+ // What the word means before what it resembles: `migrate` is two edits from `upgrade`.
158
+ const suggestion = intentFor(token, names) ?? nearestName(token, names);
130
159
  throw new UnknownCommandError(
131
160
  suggestion === undefined
132
161
  ? { path: token, known: names }
@@ -351,11 +380,13 @@ function readSubcommand(spec: CommandSpec, positionals: readonly string[]): Reso
351
380
  if (spec.defaultSubcommandTakesPositional === true && suggestion === undefined) {
352
381
  return { name: spec.defaultSubcommand, consumed: false };
353
382
  }
354
- throw new UnknownCommandError(
355
- suggestion === undefined
356
- ? { path: `${spec.name} ${token}`, known: allowed }
357
- : { path: `${spec.name} ${token}`, known: allowed, suggestion: `${spec.name} ${suggestion}` },
358
- );
383
+ // Near nothing: the command's own page, which lists the subcommands it REGISTERS — the command
384
+ // was right, so the top-level `x help` sent the reader back through every other one.
385
+ throw new UnknownCommandError({
386
+ path: `${spec.name} ${token}`,
387
+ known: allowed,
388
+ suggestion: suggestion === undefined ? `help ${spec.name}` : `${spec.name} ${suggestion}`,
389
+ });
359
390
  }
360
391
 
361
392
  function blank(command: string, specs: readonly CommandSpec[], json: boolean): ParsedArgs {
@@ -4,11 +4,12 @@
4
4
 
5
5
  import type { AnyAction } from '@ultimat3/action';
6
6
  import { describeActions, getAction } from '@ultimat3/action';
7
- import type { MatrixRow, Policy } from '@ultimat3/policy';
7
+ import type { Policy } from '@ultimat3/policy';
8
8
  import { knownPermissions, policyMatrix, roleDefinitions, rolesGranting } from '@ultimat3/policy';
9
9
  import type { AnyQuery } from '@ultimat3/query';
10
10
  import { describeQueries, getQuery } from '@ultimat3/query';
11
11
  import { devActors } from './dev-policy';
12
+ import { decided, type ExplainRow, rowWithoutInput } from './policy-row';
12
13
 
13
14
  const isDefined = <T>(value: T | undefined): value is T => value !== undefined;
14
15
 
@@ -81,6 +82,12 @@ export function listPolicy(): PolicyListFacts {
81
82
  export type DeclarationKind = 'action' | 'query';
82
83
  export type SubjectKind = 'permission' | DeclarationKind;
83
84
 
85
+ /** What `x policy explain --input '<json>'` supplies: the request's input, parsed. */
86
+ export interface ExplainOptions {
87
+ /** Absent: no input was given, and a rule that reads one is `needs-input`. */
88
+ readonly input?: { readonly value: unknown } | undefined;
89
+ }
90
+
84
91
  export interface DeclarationExplanation {
85
92
  readonly name: string;
86
93
  readonly kind: DeclarationKind;
@@ -94,12 +101,13 @@ export interface DeclarationExplanation {
94
101
  readonly permissions: readonly string[];
95
102
  readonly label: string;
96
103
  /**
97
- * Whether this policy can be decided at all outside a request. `false` when evaluating it
98
- * with no request input threw — a predicate dereferencing `input.post.id` has nothing to
99
- * dereference here — and `rows` is then empty, because a partial matrix reads as a verdict.
104
+ * Whether this policy could be evaluated at all. `false` only when it threw on the input
105
+ * `--input` supplied — a row rule dereferencing a row there is none of, a field the JSON did not
106
+ * carry — and `rows` is then empty, because a partial matrix reads as a verdict. With no input
107
+ * given a throwing predicate is a `needs-input` row instead: the missing input is why it threw.
100
108
  */
101
109
  readonly decidable: boolean;
102
- readonly rows: readonly MatrixRow[];
110
+ readonly rows: readonly ExplainRow[];
103
111
  }
104
112
 
105
113
  export interface SubjectExplanation {
@@ -118,17 +126,21 @@ type DeclarationMatrix = Pick<DeclarationExplanation, 'decidable' | 'rows'>;
118
126
  * "every role plus anonymous" builder here is the duplicate axiom 1 bans, and it would drift
119
127
  * from the panel's own set the first time a role is renamed.
120
128
  *
121
- * Actor by actor inside a `try`, because there is no request input outside a request and
122
- * `policyMatrix` does not catch: a predicate reading `input.post.id` threw a bare `TypeError`
123
- * straight out of `x policy explain`. One throw makes the whole declaration undecidable rather
124
- * than half-reported — the rows a synthetic `{}` did produce are not the request's verdicts.
125
- * `policyMatrix` stays the only decider; nothing here re-derives one.
129
+ * With `--input` the policy is evaluated on it, actor by actor inside a `try`: `policyMatrix` does
130
+ * not catch, and a row rule dereferencing the row this command has none of threw a bare
131
+ * `TypeError` straight out of `x policy explain`. One throw makes the whole declaration
132
+ * undecidable rather than half-reported.
126
133
  */
127
- const matrixFor = (policy: Policy): DeclarationMatrix => {
128
- const rows: MatrixRow[] = [];
134
+ const matrixFor = (policy: Policy, options: ExplainOptions): DeclarationMatrix => {
135
+ const { input } = options;
136
+ if (input === undefined) {
137
+ return { decidable: true, rows: devActors().map((actor) => rowWithoutInput(policy, actor)) };
138
+ }
139
+ const rows: ExplainRow[] = [];
129
140
  for (const actor of devActors()) {
130
141
  try {
131
- rows.push(...policyMatrix(policy, { actors: [actor], input: {} }).rows);
142
+ const matrix = policyMatrix(policy, { actors: [actor], input: input.value });
143
+ rows.push(...matrix.rows.map(decided));
132
144
  } catch {
133
145
  return { decidable: false, rows: [] };
134
146
  }
@@ -136,7 +148,7 @@ const matrixFor = (policy: Policy): DeclarationMatrix => {
136
148
  return { decidable: true, rows };
137
149
  };
138
150
 
139
- const explainAction = (action: AnyAction): DeclarationExplanation => {
151
+ const explainAction = (action: AnyAction, options: ExplainOptions): DeclarationExplanation => {
140
152
  const descriptor = action.describe();
141
153
  return {
142
154
  name: descriptor.name,
@@ -144,11 +156,11 @@ const explainAction = (action: AnyAction): DeclarationExplanation => {
144
156
  capability: descriptor.capability,
145
157
  permissions: descriptor.permissions,
146
158
  label: action.policy.label,
147
- ...matrixFor(action.policy),
159
+ ...matrixFor(action.policy, options),
148
160
  };
149
161
  };
150
162
 
151
- const explainQuery = (query: AnyQuery): DeclarationExplanation => {
163
+ const explainQuery = (query: AnyQuery, options: ExplainOptions): DeclarationExplanation => {
152
164
  const descriptor = query.describe();
153
165
  return {
154
166
  name: descriptor.name,
@@ -156,7 +168,7 @@ const explainQuery = (query: AnyQuery): DeclarationExplanation => {
156
168
  capability: descriptor.capability,
157
169
  permissions: descriptor.permissions,
158
170
  label: query.policy.label,
159
- ...matrixFor(query.policy),
171
+ ...matrixFor(query.policy, options),
160
172
  };
161
173
  };
162
174
 
@@ -188,7 +200,10 @@ export function knownPolicySubjects(): readonly string[] {
188
200
  ];
189
201
  }
190
202
 
191
- export function explainPolicy(name: string): SubjectExplanation | undefined {
203
+ export function explainPolicy(
204
+ name: string,
205
+ options: ExplainOptions = {},
206
+ ): SubjectExplanation | undefined {
192
207
  const resolved = resolveSubject(name);
193
208
  if (resolved === undefined) return undefined;
194
209
  if (resolved.kind === 'permission') {
@@ -198,12 +213,12 @@ export function explainPolicy(name: string): SubjectExplanation | undefined {
198
213
  .filter((descriptor) => enforces(descriptor, permission))
199
214
  .map((descriptor) => getAction(descriptor.name))
200
215
  .filter(isDefined)
201
- .map(explainAction),
216
+ .map((action) => explainAction(action, options)),
202
217
  ...describeQueries()
203
218
  .filter((descriptor) => enforces(descriptor, permission))
204
219
  .map((descriptor) => getQuery(descriptor.name))
205
220
  .filter(isDefined)
206
- .map(explainQuery),
221
+ .map((query) => explainQuery(query, options)),
207
222
  ];
208
223
  return {
209
224
  subject: name,
@@ -213,7 +228,9 @@ export function explainPolicy(name: string): SubjectExplanation | undefined {
213
228
  };
214
229
  }
215
230
  const declaration =
216
- resolved.kind === 'action' ? explainAction(resolved.action) : explainQuery(resolved.query);
231
+ resolved.kind === 'action'
232
+ ? explainAction(resolved.action, options)
233
+ : explainQuery(resolved.query, options);
217
234
  return {
218
235
  subject: name,
219
236
  kind: resolved.kind,
@@ -0,0 +1,99 @@
1
+ // One actor's verdict on a policy, with or without the request's input: the row both `x policy
2
+ // explain` and the `/_x` policy panel draw. Without input, a predicate that READS input is
3
+ // `needs-input` — never the deny a stand-in `{}` produced. `policyMatrix` stays the only decider.
4
+
5
+ import type { MatrixRow, NamedActor, Policy } from '@ultimat3/policy';
6
+ import { decideBeforeInput, policyMatrix, reasonOf } from '@ultimat3/policy';
7
+
8
+ /**
9
+ * `needs-input` is NOT a denial: the actor passes every clause that reads only the actor, and a
10
+ * predicate then read the request's input — which this command was not given. Reported as a deny
11
+ * it sent the reader to edit a correct policy: every input-scoped rule (all that `x g resource`
12
+ * writes) read "predicate returned false" about the admin who had just succeeded over HTTP.
13
+ */
14
+ export type ExplainVerdict = 'allow' | 'deny' | 'needs-input';
15
+
16
+ /** A `MatrixRow` that can also say "not decided". `allowed` is `null` exactly when it was not. */
17
+ export interface ExplainRow extends Omit<MatrixRow, 'allowed'> {
18
+ readonly verdict: ExplainVerdict;
19
+ readonly allowed: boolean | null;
20
+ }
21
+
22
+ export const decided = (row: MatrixRow): ExplainRow => ({
23
+ ...row,
24
+ verdict: row.allowed ? 'allow' : 'deny',
25
+ });
26
+
27
+ /**
28
+ * A stand-in for the input nobody supplied, which records being READ. Every trap a predicate can
29
+ * reach it through answers "nothing there" — what `{}` answered — and sets the flag, so a verdict
30
+ * that came out of reading it is known to be a verdict about no request at all. `[]` as the
31
+ * target is the array-shaped one: `Array.isArray` sees through a proxy to its target.
32
+ */
33
+ function absentInput(target: object = {}): { readonly value: object; read(): boolean } {
34
+ let touched = false;
35
+ const touch = <T>(answer: T): T => {
36
+ touched = true;
37
+ return answer;
38
+ };
39
+ const value = new Proxy(target, {
40
+ get: () => touch(undefined),
41
+ has: () => touch(false),
42
+ ownKeys: () => touch([]),
43
+ getOwnPropertyDescriptor: () => touch(undefined),
44
+ });
45
+ return { value, read: () => touched };
46
+ }
47
+
48
+ /** The row over one stand-in, or `undefined` when a predicate threw on it. */
49
+ function rowOver(policy: Policy, entry: NamedActor, input: unknown): MatrixRow | undefined {
50
+ try {
51
+ return policyMatrix(policy, { actors: [entry], input }).rows[0];
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Did the verdict depend on the input? Read through a trap, or — for a whole-value check
59
+ * (`Array.isArray(input)`, `input === null`, `typeof input`) that reaches no trap — moved when the
60
+ * stand-in's shape did. A predicate over the actor alone answers the same for every one of them.
61
+ */
62
+ function inputDecided(policy: Policy, entry: NamedActor, row: MatrixRow | undefined): boolean {
63
+ const array = absentInput([]);
64
+ const others = [array.value, null, ''].map((input) => rowOver(policy, entry, input));
65
+ return (
66
+ array.read() ||
67
+ // A throw is `undefined`, so throwing on one stand-in and not another is a move too.
68
+ others.some((other) => other?.allowed !== row?.allowed)
69
+ );
70
+ }
71
+
72
+ /**
73
+ * One actor with no input to hand the policy. The before-input gate (`decideBeforeInput`, the one
74
+ * the HTTP surface runs before it parses a body) says whether a predicate has to run for this
75
+ * actor at all; when one does, the full evaluation runs over `absentInput()`, and a predicate
76
+ * that read it, threw reading it, or answered otherwise for another stand-in is `needs-input`,
77
+ * never a deny. A predicate that reads only the actor decides as it would on a request.
78
+ * `policyMatrix` stays the only decider.
79
+ */
80
+ export function rowWithoutInput(policy: Policy, entry: NamedActor): ExplainRow {
81
+ const input = absentInput();
82
+ const row = rowOver(policy, entry, input.value);
83
+ const before = decideBeforeInput(policy, { actor: entry.actor });
84
+ const dependent = before === undefined && (input.read() || inputDecided(policy, entry, row));
85
+ if (row !== undefined && !dependent) return decided(row);
86
+ // Decided whatever the input is, and a predicate past the deciding clause threw on the stand-in.
87
+ if (before !== undefined) {
88
+ const { allowed } = before;
89
+ return decided({ actor: entry.name, allowed, reason: reasonOf(before), deciding: null });
90
+ }
91
+ const clause = row?.deciding ?? policy.label;
92
+ return {
93
+ actor: entry.name,
94
+ verdict: 'needs-input',
95
+ allowed: null,
96
+ deciding: row?.deciding ?? null,
97
+ reason: `not denied — every actor-only clause passes, and ${clause} has a predicate that reads the request input`,
98
+ };
99
+ }
@@ -0,0 +1,28 @@
1
+ // The port a "port in use" fix names. On a machine running several dev servers the next pair is
2
+ // often taken as well, and a fix that fails the same way is not a fix. Not `@ultimat3/testing`'s
3
+ // `freePortPair`, which binds; this one only asks.
4
+
5
+ import { PORT_RANGE, portPairAfter } from './flag-number';
6
+
7
+ /** How far to look: past this the machine is unusual and the plain suggestion is as good. */
8
+ const PAIRS_TRIED = 64;
9
+
10
+ /**
11
+ * The first pair after `port` with both ports free, walking the way `portPairAfter` points (down at
12
+ * the top of the range). `x dev --port N` binds N and N + 1, so both are asked. The answer is true
13
+ * when asked: another process can still take it.
14
+ */
15
+ export async function freeDevPortPair(
16
+ port: number,
17
+ isFree: (port: number) => boolean | Promise<boolean>,
18
+ ): Promise<number> {
19
+ const first = portPairAfter(port);
20
+ const step = first > port ? 2 : -2;
21
+ let candidate = first;
22
+ for (let tried = 0; tried < PAIRS_TRIED; tried += 1) {
23
+ if (candidate < 1 || candidate + 1 >= PORT_RANGE.max) break;
24
+ if ((await isFree(candidate)) && (await isFree(candidate + 1))) return candidate;
25
+ candidate += step;
26
+ }
27
+ return first;
28
+ }
@@ -0,0 +1,110 @@
1
+ // The four registries every generated feature adds to, held one entry per line. Two branches that
2
+ // each add a feature then touch different lines, so `x merge-driver` can keep both; a list on one
3
+ // line is the same line changed twice, which no merge can tell from a real disagreement. `x new`
4
+ // writes this shape and the `registry-lines` codemod carries an existing app to it.
5
+
6
+ import { stripComments } from '@ultimat3/core';
7
+ import { apiListsOf, insertApiList } from './api-registration';
8
+ import { API_INDEX } from './app-root';
9
+ import { declarationLists } from './generate-grants';
10
+ import { ROLES_FILE } from './permission-grants';
11
+ import { maskOf, readList, readProperties } from './source-list-edit';
12
+ import { HANDLE_FILE } from './templates/scaffold-db-client';
13
+
14
+ const EXERCISE_FILE = 'apps/web/exercise.ts';
15
+
16
+ /** Inside the bracket, it is also what keeps Biome from joining the list back onto one line. */
17
+ export const REGISTRY_LINE_COMMENT =
18
+ '// One entry per line: branches that each add one merge cleanly (x merge-driver).';
19
+
20
+ /** Every file `withRegistryLines` holds to the shape. */
21
+ export const REGISTRY_FILES: readonly string[] = [
22
+ API_INDEX,
23
+ ROLES_FILE,
24
+ EXERCISE_FILE,
25
+ HANDLE_FILE,
26
+ ];
27
+
28
+ const API_LISTS = ['actions', 'queries', 'jobs', 'tasks'] as const;
29
+
30
+ const indentAt = (source: string, at: number): string =>
31
+ /^[ \t]*/.exec(source.slice(source.lastIndexOf('\n', at) + 1))?.[0] ?? '';
32
+
33
+ const startsItsLine = (source: string, at: number): boolean =>
34
+ source.slice(source.lastIndexOf('\n', at - 1) + 1, at).trim() === '';
35
+
36
+ /**
37
+ * The list opening at `open`, a row per entry under the comment. A list this cannot restate
38
+ * without moving the author's text — a comment beside entries on one line, two entries sharing a
39
+ * row — is left as it is: it still works, it just merges by hand.
40
+ */
41
+ export function listWithLines(source: string, open: number): string {
42
+ const list = readList(source, maskOf(source), open);
43
+ if (list === undefined) return source;
44
+ const span = source.slice(list.open, list.close + 1);
45
+ if (span.includes(REGISTRY_LINE_COMMENT)) return source;
46
+ const indent = indentAt(source, open);
47
+ const comment = `${indent} ${REGISTRY_LINE_COMMENT}`;
48
+ if (span.includes('\n')) {
49
+ const lineEnd = source.indexOf('\n', open);
50
+ const opensAlone = source.slice(open + 1, lineEnd).trim() === '';
51
+ if (!opensAlone || list.entries.some((entry) => !startsItsLine(source, entry.start))) {
52
+ return source;
53
+ }
54
+ return `${source.slice(0, lineEnd + 1)}${comment}\n${source.slice(lineEnd + 1)}`;
55
+ }
56
+ if (stripComments(source).slice(list.open, list.close + 1) !== span) return source;
57
+ const rows = list.entries.map((entry) => `${indent} ${entry.text},\n`).join('');
58
+ const bracket = source[list.close] as string;
59
+ const body = `${source[open] as string}\n${comment}\n${rows}${indent}${bracket}`;
60
+ return `${source.slice(0, open)}${body}${source.slice(list.close + 1)}`;
61
+ }
62
+
63
+ function apiWithLines(source: string): string {
64
+ let next = source;
65
+ for (const key of API_LISTS) {
66
+ // A list every branch can add to exists before either does: two branches each creating
67
+ // `tasks:` is one key written twice, the one shape no line merge can keep.
68
+ next = apiListsOf(next)?.(key) === undefined ? (insertApiList(next, key, '[]') ?? next) : next;
69
+ const list = apiListsOf(next)?.(key);
70
+ if (list !== undefined) next = listWithLines(next, list.open);
71
+ }
72
+ return next;
73
+ }
74
+
75
+ /** Applied from the last list back, so an edit never moves an offset still to be used. */
76
+ const eachFromLast = (source: string, opens: readonly number[]): string =>
77
+ [...opens].sort((a, b) => b - a).reduce(listWithLines, source);
78
+
79
+ function grantLists(source: string): readonly number[] {
80
+ const masked = maskOf(source);
81
+ const call = /\bdefineRoles\(\s*\{/.exec(masked);
82
+ if (call === null) return [];
83
+ return readProperties(source, masked, call.index + call[0].length - 1).flatMap((role) => {
84
+ if (masked[role.value] !== '{') return [];
85
+ const grants = readProperties(source, masked, role.value).find((p) => p.key === 'grants');
86
+ return grants !== undefined && masked[grants.value] === '[' ? [grants.value] : [];
87
+ });
88
+ }
89
+
90
+ const rolesWithLines = (source: string): string =>
91
+ eachFromLast(source, [...declarationLists(maskOf(source)), ...grantLists(source)]);
92
+
93
+ /** An EMPTY object only: a filled one is already a row per entry, which Biome keeps. */
94
+ function emptyObjectWithLines(source: string, opening: RegExp): string {
95
+ const masked = maskOf(source);
96
+ const found = opening.exec(masked);
97
+ if (found === null) return source;
98
+ const open = found.index + found[0].length - 1;
99
+ const list = readList(source, masked, open);
100
+ return list?.entries.length === 0 ? listWithLines(source, open) : source;
101
+ }
102
+
103
+ /** `source`, the registry at `path`, in the one-entry-per-line shape. Any other path: unchanged. */
104
+ export function withRegistryLines(path: string, source: string): string {
105
+ if (path === API_INDEX) return apiWithLines(source);
106
+ if (path === ROLES_FILE) return rolesWithLines(source);
107
+ if (path === EXERCISE_FILE) return emptyObjectWithLines(source, /\bdefineExercise\(\s*\{/);
108
+ if (path === HANDLE_FILE) return emptyObjectWithLines(source, /\bconst entities\s*=\s*\{/);
109
+ return source;
110
+ }
package/src/registry.ts CHANGED
@@ -40,6 +40,7 @@ import { logsSpec } from './cmd-logs-spec';
40
40
  import { mailSpec } from './cmd-mail-spec';
41
41
  import { manifestSpec } from './cmd-manifest-spec';
42
42
  import { mcpSpec } from './cmd-mcp-spec';
43
+ import { mergeDriverSpec } from './cmd-merge-driver-spec';
43
44
  import { newSpec } from './cmd-new-spec';
44
45
  import { policySpec } from './cmd-policy-spec';
45
46
  import { prSpec } from './cmd-pr-spec';
@@ -133,6 +134,7 @@ export const LAZY_COMMANDS: readonly LazyCommand[] = [
133
134
  lazy(graphSpec, async () => (await import('./cmd-graph')).graphCommand),
134
135
  lazy(impactSpec, async () => (await import('./cmd-impact')).impactCommand),
135
136
  lazy(tokenSpec, async () => (await import('./cmd-token')).tokenCommand),
137
+ lazy(mergeDriverSpec, async () => (await import('./cmd-merge-driver')).mergeDriverCommand),
136
138
  lazy(configSpec, async () => (await import('./cmd-config')).configCommand),
137
139
  lazy(logsSpec, async () => (await import('./cmd-logs')).logsCommand),
138
140
  lazy(cacheSpec, async () => (await import('./cmd-cache')).cacheCommand),
@@ -11,7 +11,7 @@ export function retainUnsweptFinding(entity: string): Finding {
11
11
  return {
12
12
  code: 'X_ENTITY_RETAIN_UNSWEPT',
13
13
  cause: `entity "${entity}" declares retain, and no purge() registered in this app sweeps it — rows past its window are kept forever`,
14
- fix: "export const retention = purge({ entities: 'declared' }) — in a jobs module named in jobs: [...] in apps/web/api/index.ts, then x verify",
14
+ fix: "export const retention = purge({ entities: 'declared' }) — in a jobs module named in jobs: [...] in apps/web/api/index.ts, then x manifest",
15
15
  at: 'apps/web/api/index.ts',
16
16
  };
17
17
  }
@@ -20,6 +20,7 @@ import {
20
20
  } from '@ultimat3/realtime/server';
21
21
  import { BadFlagError } from './errors';
22
22
  import type { DevServices, Env } from './runtime-bindings';
23
+ import { envWithAppTls } from './runtime-database-ssl';
23
24
 
24
25
  export interface StartReplicatorOptions {
25
26
  readonly services: DevServices;
@@ -181,7 +182,9 @@ export async function startReplicator(options: StartReplicatorOptions): Promise<
181
182
  const entities = replicatedRelations();
182
183
  if (entities.length === 0) throw noEntitiesRefusal(options.dev);
183
184
 
184
- const selection = selectChangeFeed(options.env, { entities });
185
+ // `database.ssl` reaches this session too: it dials from the env, never through `startDb`.
186
+ const env = await envWithAppTls(options.services.root, options.env);
187
+ const selection = selectChangeFeed(env, { entities });
185
188
  const slot = selection.slot ?? '';
186
189
  const key = replicatorLockKey(slot);
187
190
  const heartbeat = loopHeartbeat('realtime.replicator', {
@@ -0,0 +1,86 @@
1
+ // `x dev --role`: which roles one dev process runs. Every value that is not a runnable selection
2
+ // is a flag error carrying the working invocation, never a silently narrowed or empty set.
3
+
4
+ import type { AppConfig, Role } from '@ultimat3/core';
5
+ import { ConfigInvalidError, isRole, logger, ROLES } from '@ultimat3/core';
6
+ import { BadFlagError } from './errors';
7
+ import { DEV_ROLES } from './role-start-types';
8
+ import { roleDeclared } from './serve-env';
9
+ import { quoteArg } from './shell-quote';
10
+
11
+ /**
12
+ * What `--role` accepts. The replicator is here but not in `DEV_ROLES`: opt-in, because it takes
13
+ * the one replication slot a database has, and a default that did that would mean two developers
14
+ * pointed at one staging database silently fighting over it.
15
+ */
16
+ export const SELECTABLE_ROLES: readonly Role[] = [...DEV_ROLES, 'replicator'];
17
+
18
+ /**
19
+ * `--role web,worker` picks a subset. An unknown or out-of-scope role is a flag error with the
20
+ * working invocation in the fix line, never a silently ignored value — which is what it was.
21
+ */
22
+ export function selectRoles(flag: string | undefined): readonly Role[] {
23
+ if (flag === undefined || flag.trim().length === 0) return DEV_ROLES;
24
+ const wanted = flag
25
+ .split(',')
26
+ .map((part) => part.trim())
27
+ .filter((part) => part.length > 0);
28
+ // `--role ,` names nothing: read as "no roles" it booted an `x dev` that served nothing.
29
+ if (wanted.length === 0) {
30
+ throw new BadFlagError({
31
+ flag: 'role',
32
+ command: 'dev',
33
+ reason: `it names no role (one or more of: ${SELECTABLE_ROLES.join(', ')})`,
34
+ fix: `x dev --role ${quoteArg(DEV_ROLES.join(','))}`,
35
+ });
36
+ }
37
+ const selected: Role[] = [];
38
+ for (const name of wanted) {
39
+ if (!isRole(name)) {
40
+ throw new BadFlagError({
41
+ flag: 'role',
42
+ command: 'dev',
43
+ reason: `"${name}" is not a role (known: ${ROLES.join(', ')})`,
44
+ fix: `x dev --role ${quoteArg(DEV_ROLES.join(','))}`,
45
+ });
46
+ }
47
+ if (!SELECTABLE_ROLES.includes(name)) {
48
+ throw new BadFlagError({
49
+ flag: 'role',
50
+ command: 'dev',
51
+ reason: `"${name}" does not run under x dev (it runs once, as \`x db migrate\`)`,
52
+ fix: `x dev --role ${quoteArg(DEV_ROLES.join(','))}`,
53
+ });
54
+ }
55
+ if (!selected.includes(name)) selected.push(name);
56
+ }
57
+ return SELECTABLE_ROLES.filter((role) => selected.includes(role));
58
+ }
59
+
60
+ /**
61
+ * The selection narrowed to the roles `app.config.ts` declares — the rule the container's `ROLE` is
62
+ * refused by (`roleDeclared`, `serve-env.ts`), so dev never fires a cron task, or binds a sync
63
+ * node, that the deploy will not run. What it drops is named in one line; a selection of nothing
64
+ * BUT undeclared roles is refused, as `rolesUnderRealtime` refuses one that would serve nothing.
65
+ */
66
+ export function rolesDeclaredForDev(
67
+ selected: readonly Role[],
68
+ config: AppConfig | undefined,
69
+ ): readonly Role[] {
70
+ const kept = selected.filter((role) => roleDeclared(role, config));
71
+ if (kept.length === selected.length || config === undefined) return selected;
72
+ const dropped = selected.filter((role) => !kept.includes(role));
73
+ if (kept.length === 0) {
74
+ throw new ConfigInvalidError({
75
+ cause: `role ${dropped.join(',')} was asked for and roles in app.config.ts lists ${config.roles.join(', ')}, so this process would serve nothing`,
76
+ fix: `x dev --role ${quoteArg(config.roles.filter((role) => role !== 'migrate').join(','))}`,
77
+ meta: { key: 'roles', roles: dropped, declared: [...config.roles] },
78
+ });
79
+ }
80
+ // info: once per boot — what this process does NOT run, which nothing else would say.
81
+ logger.info(`roles in app.config.ts does not list ${dropped.join(', ')}: not starting them`, {
82
+ dropped,
83
+ declared: [...config.roles],
84
+ });
85
+ return kept;
86
+ }