@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
@@ -0,0 +1,142 @@
1
+ // `x clean --services`: stop this checkout's test stack, and list every other one on the machine.
2
+ // Others are only ever listed: on a machine shared by agents, another stack may be in use right now,
3
+ // and each line carries the command that stops it.
4
+
5
+ // why: Bun ships no synchronous existence check.
6
+ import { existsSync } from 'node:fs';
7
+ // why: Bun ships no path-join primitive.
8
+ import { join } from 'node:path';
9
+ import { renderThrowable } from '@ultimat3/core';
10
+ import type { Runner } from './exec';
11
+ import { execOutput } from './exec';
12
+ import { msg } from './messages';
13
+ import type { Finding, JsonValue } from './output';
14
+ import { TEST_COMPOSE_PATH } from './templates/scaffold-test-services';
15
+ import type { TestStack } from './verify-services-stack';
16
+ import {
17
+ jsonRows,
18
+ otherRoots,
19
+ readStack,
20
+ rootOfCompose,
21
+ SERVICES_LIST,
22
+ SERVICES_STOP,
23
+ STACKS_LIST,
24
+ } from './verify-services-stack';
25
+
26
+ export interface ServicesCleanup {
27
+ readonly data: JsonValue;
28
+ readonly lines: readonly string[];
29
+ readonly finding?: Finding;
30
+ }
31
+
32
+ interface OtherStack {
33
+ readonly project: string;
34
+ readonly status: string;
35
+ readonly root: string;
36
+ readonly gone: boolean;
37
+ }
38
+
39
+ const refused = (command: readonly string[], why: string): Finding => ({
40
+ code: 'X_TEST_SERVICES_UNAVAILABLE',
41
+ cause: `\`${command.join(' ')}\` could not run — ${why}`,
42
+ fix: `${command.join(' ')} # needs Docker running`,
43
+ at: TEST_COMPOSE_PATH,
44
+ });
45
+
46
+ /** Test stacks of other checkouts. Best effort: failing to list them stops nothing of ours. */
47
+ async function otherStacks(root: string, own: string | undefined, runner: Runner) {
48
+ try {
49
+ const result = await runner(STACKS_LIST, { cwd: root });
50
+ if (!result.ok) return [];
51
+ return jsonRows(result.stdout).flatMap((row): OtherStack[] => {
52
+ const [project, status, files] = [row['Name'], row['Status'], row['ConfigFiles']];
53
+ if (typeof project !== 'string' || typeof files !== 'string' || project === own) return [];
54
+ const other = rootOfCompose(files);
55
+ if (other === undefined || other === root) return [];
56
+ const state = typeof status === 'string' ? status : '';
57
+ return [{ project, status: state, root: other, gone: !existsSync(other) }];
58
+ });
59
+ } catch {
60
+ return [];
61
+ }
62
+ }
63
+
64
+ /** `undefined` when the stack stopped; otherwise the refusal naming why. */
65
+ async function stop(root: string, runner: Runner): Promise<Finding | undefined> {
66
+ try {
67
+ const result = await runner(SERVICES_STOP, { cwd: root });
68
+ return result.ok
69
+ ? undefined
70
+ : refused(
71
+ SERVICES_STOP,
72
+ `it exited ${String(result.code)}: ${execOutput(result).slice(-400)}`,
73
+ );
74
+ } catch (error) {
75
+ return refused(SERVICES_STOP, renderThrowable(error));
76
+ }
77
+ }
78
+
79
+ type Action = 'none' | 'stopped' | 'would-stop' | 'kept' | 'failed';
80
+
81
+ async function settle(
82
+ stack: TestStack | undefined,
83
+ input: { readonly root: string; readonly runner: Runner; readonly dryRun: boolean },
84
+ ): Promise<{ readonly action: Action; readonly owner?: string; readonly finding?: Finding }> {
85
+ if (stack === undefined) return { action: 'none' };
86
+ const [owner] = otherRoots(stack, input.root);
87
+ if (owner !== undefined) return { action: 'kept', owner };
88
+ if (input.dryRun) return { action: 'would-stop' };
89
+ const finding = await stop(input.root, input.runner);
90
+ return finding === undefined ? { action: 'stopped' } : { action: 'failed', finding };
91
+ }
92
+
93
+ export async function cleanServices(input: {
94
+ readonly root: string;
95
+ readonly runner: Runner;
96
+ readonly dryRun: boolean;
97
+ }): Promise<ServicesCleanup> {
98
+ const { root, runner } = input;
99
+ let stack: TestStack | undefined;
100
+ if (existsSync(join(root, TEST_COMPOSE_PATH))) {
101
+ const read = await readStack(root, runner);
102
+ if (!read.answered) {
103
+ return {
104
+ data: { action: 'failed' },
105
+ lines: [],
106
+ finding: refused(SERVICES_LIST, 'Docker gave no answer about this app’s stack'),
107
+ };
108
+ }
109
+ stack = read.stack;
110
+ }
111
+ const outcome = await settle(stack, input);
112
+ const others = await otherStacks(root, stack?.project, runner);
113
+ const project = stack?.project ?? '';
114
+ const services = stack?.services.join(', ') ?? '';
115
+ return {
116
+ data: {
117
+ action: outcome.action,
118
+ ...(stack === undefined ? {} : { project, services: [...stack.services] }),
119
+ ...(outcome.owner === undefined ? {} : { owner: outcome.owner }),
120
+ others: others.map((other) => ({ ...other })),
121
+ },
122
+ lines: [
123
+ ...(outcome.action === 'failed'
124
+ ? []
125
+ : [
126
+ msg(`cli.clean.services.${outcome.action}`, {
127
+ project,
128
+ services,
129
+ owner: outcome.owner ?? '',
130
+ }),
131
+ ]),
132
+ ...others.map((other) =>
133
+ msg(other.gone ? 'cli.clean.services.otherGone' : 'cli.clean.services.other', {
134
+ project: other.project,
135
+ status: other.status,
136
+ root: other.root,
137
+ }),
138
+ ),
139
+ ],
140
+ ...(outcome.finding === undefined ? {} : { finding: outcome.finding }),
141
+ };
142
+ }
package/src/cmd-auth.ts CHANGED
@@ -11,6 +11,7 @@ import { requireAppRoot } from './app-root';
11
11
  import { authSpec } from './cmd-auth-spec';
12
12
  import type { CliCommand, CommandContext } from './command';
13
13
  import { ok } from './command';
14
+ import { refuseEmbeddedWriteBesideDev } from './dev-lock-live';
14
15
  import { msg } from './messages';
15
16
  import type { CommandResult } from './output';
16
17
  import { openAppQueue } from './runtime-boot-ports';
@@ -25,6 +26,8 @@ export interface OpenAuthStore extends MfaSecretStore {
25
26
  * exits holding the PGlite lock breaks the next command run against this app.
26
27
  */
27
28
  async function openAppAuthStore(root: string, ctx: CommandContext): Promise<OpenAuthStore> {
29
+ // Sealing rewrites `x_users` rows through this boot: never as a second PGlite writer.
30
+ await refuseEmbeddedWriteBesideDev(root, ctx.env, ['auth', 'seal-mfa']);
28
31
  // `runtime.ts` read: sealing asks the master key, and a KMS app's key is its `secretSource`'s.
29
32
  const queue = await openAppQueue(root, ctx.env);
30
33
  return { adapter: postgresAuthAdapter(queue.db), close: () => queue.stop() };
@@ -6,8 +6,15 @@ import type { CommandSpec } from './parse';
6
6
  export const cleanSpec: CommandSpec = {
7
7
  name: 'clean',
8
8
  summary:
9
- 'remove what test runs leave behind: migrated test templates, .x/cache, stray .x folders, stale probe databases',
10
- usage: 'x clean [--dry-run] [--json]',
9
+ 'remove what test runs leave behind: migrated test templates, .x/cache, stray .x folders, stale probe databases; --services stops the test stack too',
10
+ usage: 'x clean [--dry-run] [--services] [--json]',
11
11
  requiresApp: true,
12
- flags: [{ name: 'dry-run', type: 'boolean', summary: 'name what would go, remove nothing' }],
12
+ flags: [
13
+ { name: 'dry-run', type: 'boolean', summary: 'name what would go, remove nothing' },
14
+ {
15
+ name: 'services',
16
+ type: 'boolean',
17
+ summary: "also stop this checkout's test stack, and list the machine's others",
18
+ },
19
+ ],
13
20
  };
package/src/cmd-clean.ts CHANGED
@@ -6,9 +6,10 @@
6
6
  // `TEST_DATABASE_URL` set — the probe databases whose run is over. The test runner sweeps the same
7
7
  // set before every run, keeping the newest two of each cache (`test-housekeeping.ts`); this is the
8
8
  // same sweep, keeping none. Never touched: `.x/pgdata` (the dev database), `.x/storage`, the build
9
- // output.
9
+ // output. `--services` adds this checkout's test stack (`clean-services.ts`).
10
10
 
11
11
  import { requireAppRoot } from './app-root';
12
+ import { cleanServices } from './clean-services';
12
13
  import { cleanSpec } from './cmd-clean-spec';
13
14
  import type { CliCommand, CommandContext } from './command';
14
15
  import { msg } from './messages';
@@ -23,17 +24,30 @@ export const cleanCommand: CliCommand = {
23
24
  const dryRun = flagBool(ctx.args, 'dry-run');
24
25
  const report = await tidyTestState({ root, mode: 'all', env: ctx.env, dryRun });
25
26
  const count = report.paths.length + report.databases.length;
27
+ const services = flagBool(ctx.args, 'services')
28
+ ? await cleanServices({ root, runner: ctx.runner, dryRun })
29
+ : undefined;
30
+ const finding = services?.finding;
26
31
  return {
27
- ok: true,
32
+ ok: finding === undefined,
28
33
  command: 'clean',
29
34
  summary:
30
- count === 0
31
- ? msg('cli.clean.nothing')
32
- : msg(dryRun ? 'cli.clean.would' : 'cli.clean.removed', {
33
- paths: report.paths.length,
34
- databases: report.databases.length,
35
- }),
36
- data: { dryRun, paths: [...report.paths], databases: [...report.databases] },
35
+ finding !== undefined
36
+ ? finding.cause
37
+ : count === 0
38
+ ? msg('cli.clean.nothing')
39
+ : msg(dryRun ? 'cli.clean.would' : 'cli.clean.removed', {
40
+ paths: report.paths.length,
41
+ databases: report.databases.length,
42
+ }),
43
+ ...(finding === undefined ? {} : { findings: [finding] }),
44
+ ...(services === undefined ? {} : { lines: [...services.lines] }),
45
+ data: {
46
+ dryRun,
47
+ paths: [...report.paths],
48
+ databases: [...report.databases],
49
+ ...(services === undefined ? {} : { services: services.data }),
50
+ },
37
51
  };
38
52
  },
39
53
  };
@@ -19,6 +19,7 @@ import {
19
19
  renderPlanTable,
20
20
  runBackfills,
21
21
  } from './db-backfill';
22
+ import { refuseEmbeddedWriteBesideDev } from './dev-lock-live';
22
23
  import { BadFlagError } from './errors';
23
24
  import { withJobDriver } from './jobs-driver';
24
25
  import { backfillToJson } from './jobs-json';
@@ -219,6 +220,11 @@ async function runBackfillPass(
219
220
  const { findings: loadFindings } = await loadApp(root);
220
221
  const environment = resolveEnvironment({ env: ctx.env });
221
222
  const write = flagBool(ctx.args, 'write');
223
+ // `--write` enqueues through this command's own boot: a second PGlite writer beside `x dev`.
224
+ if (write) {
225
+ const named = names === 'all' ? [] : names;
226
+ await refuseEmbeddedWriteBesideDev(root, ctx.env, ['db', 'backfill', ...named, '--write']);
227
+ }
222
228
  return withJobDriver(root, ctx, async (driver) => {
223
229
  const rows = await runBackfills({
224
230
  driver,
@@ -31,6 +31,7 @@ import type { CommandResult, Finding } from './output';
31
31
  import { flagString, retiredVerbReplacement } from './parse';
32
32
  import type { DevServices } from './runtime-bindings';
33
33
  import { resolveServices } from './runtime-bindings';
34
+ import { withAppTls } from './runtime-database-ssl';
34
35
  import { portFromEnv } from './serve';
35
36
  import { renderTable } from './table';
36
37
 
@@ -66,7 +67,12 @@ function branchRetry(word: string, name: string | undefined): string {
66
67
  * would leave two idle sessions holding the source open against itself; and cloning a real
67
68
  * database routinely outlives the 10s a `web` profile allows.
68
69
  */
69
- async function withBranchClient<T>(url: string, fn: (client: DbClient) => Promise<T>): Promise<T> {
70
+ async function withBranchClient<T>(
71
+ services: DevServices,
72
+ fn: (client: DbClient) => Promise<T>,
73
+ ): Promise<T> {
74
+ // `database.ssl`, as the boot's own pool obeys it: this connection never goes through `startDb`.
75
+ const url = await withAppTls(services.root, services.db.url, Bun.env);
70
76
  const client = postgresClient({ url, role: 'migrate', applicationName: 'x-db-branch' });
71
77
  try {
72
78
  return await fn(client);
@@ -79,7 +85,7 @@ async function withBranchClient<T>(url: string, fn: (client: DbClient) => Promis
79
85
  const branchesOf = (services: DevServices): Promise<readonly BranchRow[]> =>
80
86
  services.db.mode === 'embedded'
81
87
  ? listPgliteBranches(services.db.url)
82
- : withBranchClient(services.db.url, listExternalBranches);
88
+ : withBranchClient(services, listExternalBranches);
83
89
 
84
90
  const failure = (summary: string, finding: Finding): CommandResult => ({
85
91
  ok: false,
@@ -161,7 +167,7 @@ async function runCreate(
161
167
  branch =
162
168
  services.db.mode === 'embedded'
163
169
  ? await createPgliteBranch(services.db.url, name)
164
- : await withBranchClient(services.db.url, (client) => createExternalBranch(client, name));
170
+ : await withBranchClient(services, (client) => createExternalBranch(client, name));
165
171
  } catch (error) {
166
172
  return failure(msg('cli.db.branch.failed'), stepFinding(error, 'X_DB_BRANCH_FAILED'));
167
173
  }
@@ -197,7 +203,7 @@ async function runDelete(services: DevServices, name: string): Promise<CommandRe
197
203
  const dropped =
198
204
  services.db.mode === 'embedded'
199
205
  ? await dropPgliteBranch(services.db.url, name)
200
- : await withBranchClient(services.db.url, (client) => dropExternalBranch(client, name));
206
+ : await withBranchClient(services, (client) => dropExternalBranch(client, name));
201
207
  if (!dropped) return notABranch(services, name);
202
208
  return {
203
209
  ok: true,
@@ -19,13 +19,14 @@ import { loadApp } from './app-load';
19
19
  import { loadAppRuntime } from './app-runtime';
20
20
  import type { CommandContext } from './command';
21
21
  import { withOpenedDb } from './db-client-displace';
22
- import { DevAlreadyRunningError, liveDevLock } from './dev-lock';
22
+ import { refuseBesideDev } from './dev-lock-live';
23
23
  import { BadFlagError } from './errors';
24
24
  import { msg } from './messages';
25
25
  import type { CommandResult } from './output';
26
26
  import { flagBool } from './parse';
27
27
  import { resolveServices } from './runtime-bindings';
28
28
  import { installBootPorts } from './runtime-boot-ports';
29
+ import { databaseSslOf } from './runtime-database-ssl';
29
30
  import { startDb } from './runtime-queue';
30
31
  import { quoteArg } from './shell-quote';
31
32
 
@@ -144,20 +145,12 @@ async function recount(ctx: CommandContext, root: string): Promise<CommandResult
144
145
  const { parent, counter } = counterNamed(target);
145
146
  const write = flagBool(ctx.args, 'write');
146
147
  const services = resolveServices(root, ctx.env);
147
- if (services.db.mode === 'embedded') {
148
- const holder = liveDevLock(services.stateDir);
149
- if (holder !== undefined) {
150
- throw new DevAlreadyRunningError({
151
- lock: holder,
152
- stateDir: services.stateDir,
153
- embeddedDb: true,
154
- });
155
- }
156
- }
148
+ if (services.db.mode === 'embedded') await refuseBesideDev(services.stateDir);
149
+ const ssl = await databaseSslOf(services);
157
150
  // `startDb` installs its client as the process's `db()`; `withOpenedDb` puts back what was there
158
151
  // (closing a lazy default it dropped) and closes both pools, as `db-diagnostics.ts` does.
159
152
  return withOpenedDb(
160
- () => startDb(services, ctx.env),
153
+ () => startDb(services, ctx.env, ssl),
161
154
  async (client) => {
162
155
  const report = await recountInBatches(client, parent.$table, counter, { write });
163
156
  const drift = report.rows;
@@ -0,0 +1,77 @@
1
+ // `x db rollback [--steps n]`: reverse the most recently applied migration(s) by running the
2
+ // `-- down` half each file carries, through `@ultimat3/db`'s `rollback()` — the same lock, ledger
3
+ // and per-migration transaction `x db migrate` uses. The files stay: deleting one is an edit.
4
+
5
+ import { isNonTransactional, type Migration } from '@ultimat3/db';
6
+ import type { CommandContext } from './command';
7
+ import { ROLLBACK_STEPS } from './db-dev-wire';
8
+ import { stepFinding } from './db-finding';
9
+ import { rollbackPass } from './db-rollback-pass';
10
+ import { intFlagOr } from './flag-number';
11
+ import { msg } from './messages';
12
+ import { MIGRATIONS_DIR, readMigrations } from './migrations';
13
+ import type { CommandResult } from './output';
14
+
15
+ export async function runRollbackCommand(
16
+ ctx: CommandContext,
17
+ root: string,
18
+ ): Promise<CommandResult> {
19
+ // Read before anything is opened: `--steps 0` and `--steps all` never reach the ledger.
20
+ const steps = intFlagOr(ctx.args, ROLLBACK_STEPS, 1);
21
+ let reverted: readonly string[];
22
+ try {
23
+ reverted = await rollbackPass(root, ctx.env, steps);
24
+ } catch (error) {
25
+ return {
26
+ ok: false,
27
+ command: 'db',
28
+ summary: msg('cli.db.rollback.failed'),
29
+ // The engine's refusals carry their own code and fix; what is left is the step failing for a
30
+ // reason no framework error claimed, which is `x db migrate`'s code for the same engine.
31
+ findings: [stepFinding(error, 'X_DB_MIGRATE_FAILED')],
32
+ };
33
+ }
34
+ const files = reverted.map((id) => `${MIGRATIONS_DIR}/${id}.sql`);
35
+ // `x db gen` writes a change that needs a step outside the transaction as TWO migrations, and one
36
+ // step back reverses only that second half: said, or the column is still there with no reason.
37
+ const base = reverted.length === 0 ? undefined : pairedBase(reverted, await readMigrations(root));
38
+ return {
39
+ ok: true,
40
+ command: 'db',
41
+ summary:
42
+ reverted.length === 0
43
+ ? msg('cli.db.rollback.none')
44
+ : msg('cli.db.rollback.done', { count: reverted.length, ids: reverted.join(', ') }),
45
+ findings: [],
46
+ // A reversed migration is PENDING again while its file is on disk: said, with both next moves.
47
+ lines: [
48
+ ...files.map((file) => ` ${file}`),
49
+ ...(files.length === 0 ? [] : [msg('cli.db.rollback.kept')]),
50
+ ...(base === undefined
51
+ ? []
52
+ : [msg('cli.db.rollback.deferredHalf', { id: `${base}${FOLLOW_UP}`, base })]),
53
+ ],
54
+ data: { reverted: [...reverted], steps, files },
55
+ };
56
+ }
57
+
58
+ /** The suffix `x db gen` gives the second step of a pair (`@ultimat3/db`'s `assembleSteps`). */
59
+ const FOLLOW_UP = '_concurrently';
60
+
61
+ /**
62
+ * The still-applied first half, when the oldest reversed id is the `<id>_concurrently` step one
63
+ * `x db gen` wrote beside `<id>`. Any other non-transactional migration — a diff that only builds
64
+ * or drops indexes is ONE such file under the plain id — is whole: no second step back is owed.
65
+ */
66
+ export function pairedBase(
67
+ reverted: readonly string[],
68
+ migrations: readonly Migration[],
69
+ ): string | undefined {
70
+ const oldest = reverted.at(-1);
71
+ if (oldest === undefined || !oldest.endsWith(FOLLOW_UP)) return undefined;
72
+ const base = oldest.slice(0, -FOLLOW_UP.length);
73
+ if (reverted.includes(base)) return undefined;
74
+ const half = migrations.find((migration) => migration.id === oldest);
75
+ if (half === undefined || !isNonTransactional(half.up)) return undefined;
76
+ return migrations.some((migration) => migration.id === base) ? base : undefined;
77
+ }
@@ -7,6 +7,7 @@ import type { CommandSpec } from './parse';
7
7
  export const DB_SUBCOMMANDS = [
8
8
  'gen',
9
9
  'migrate',
10
+ 'rollback',
10
11
  'reset',
11
12
  'seed',
12
13
  'branch',
@@ -18,9 +19,9 @@ export const DB_SUBCOMMANDS = [
18
19
 
19
20
  export const dbSpec: CommandSpec = {
20
21
  name: 'db',
21
- summary: 'gen, migrate, reset, seed, branch, backfill, diagnostics, recount, status',
22
+ summary: 'gen, migrate, rollback, reset, seed, branch, backfill, diagnostics, recount, status',
22
23
  usage:
23
- 'x db gen "add publish_at" [--drop-redundant] | migrate | reset | seed [<name>] [--tier reference|dev] [--dry-run] | seed --generate [--rows n] [--seed n] [--dry-run] | branch list | branch create <name> | branch delete <name> | backfill [<name>|--all] [--write] [--force] | backfill --pending | backfill --list [--name n] [--status s] [--limit n] | diagnostics [--limit n] | recount <entity>.<column> [--write] | status',
24
+ 'x db gen "add publish_at" [--drop-redundant] [--merge-fork] | migrate | rollback [--steps n] | reset | seed [<name>] [--tier reference|dev] [--dry-run] | seed --generate [--rows n] [--seed n] [--dry-run] | branch list | branch create <name> | branch delete <name> | backfill [<name>|--all] [--write] [--force] | backfill --pending | backfill --list [--name n] [--status s] [--limit n] | diagnostics [--limit n] | recount <entity>.<column> [--write] | status',
24
25
  requiresApp: true,
25
26
  subcommands: DB_SUBCOMMANDS,
26
27
  // Declared from the constant `runBranchCommand` validates against, never a second literal: it
@@ -111,6 +112,13 @@ export const dbSpec: CommandSpec = {
111
112
  'backfill, diagnostics: max ledger rows, or rows per diagnostics section (default 20)',
112
113
  subcommands: ['backfill', 'diagnostics'],
113
114
  },
115
+ {
116
+ name: 'steps',
117
+ type: 'string',
118
+ summary:
119
+ 'rollback: how many applied migrations to reverse, most recently applied first (default 1)',
120
+ subcommands: ['rollback'],
121
+ },
114
122
  // Declared because `X_MIGRATION_IRREVERSIBLE`'s own fix line names it. A `fix:` is copied
115
123
  // and run verbatim, so a flag the parser refuses would make the error unfollowable.
116
124
  {
@@ -126,6 +134,14 @@ export const dbSpec: CommandSpec = {
126
134
  summary: 'gen: drop each implicit index another index already leads with, concurrently',
127
135
  subcommands: ['gen'],
128
136
  },
137
+ // Declared because `X_MIGRATION_FORKED`'s own fix line names it. Never implied: it rewrites a
138
+ // sidecar, and a chain that is not forked has no use for it.
139
+ {
140
+ name: 'merge-fork',
141
+ type: 'boolean',
142
+ summary: 'gen: repair a forked chain in the newest snapshot; no SQL changes, nothing deleted',
143
+ subcommands: ['gen'],
144
+ },
129
145
  // Declared because `X_MIGRATION_ROLLING_UNSAFE`'s own fix line names it.
130
146
  {
131
147
  name: 'rolling-unsafe',
@@ -21,12 +21,13 @@ import {
21
21
  dbStatusJson,
22
22
  dbStatusLines,
23
23
  } from './db-status';
24
- import { DevAlreadyRunningError, liveDevLock } from './dev-lock';
24
+ import { refuseBesideDev } from './dev-lock-live';
25
25
  import { readStamp, thisBuild } from './framework-schema-apply';
26
26
  import { msg } from './messages';
27
27
  import { readMigrations } from './migrations';
28
28
  import type { CommandResult } from './output';
29
29
  import { resolveServices } from './runtime-bindings';
30
+ import { databaseSslOf } from './runtime-database-ssl';
30
31
  import { startDb } from './runtime-queue';
31
32
 
32
33
  /** The stamp, then the ledger; a missing ledger (`42P01`) is a fact, every other failure throws. */
@@ -46,16 +47,10 @@ async function readFromApp(ctx: CommandContext, root: string): Promise<DbStatusR
46
47
  if (services.db.mode === 'embedded') {
47
48
  if (!existsSync(pgliteDataDir(services.db.url))) return { stamp: null, ledger: undefined };
48
49
  // PGlite's data directory has one writer: an `x dev` holding it is refused, as diagnostics is.
49
- const holder = liveDevLock(services.stateDir);
50
- if (holder !== undefined) {
51
- throw new DevAlreadyRunningError({
52
- lock: holder,
53
- stateDir: services.stateDir,
54
- embeddedDb: true,
55
- });
56
- }
50
+ await refuseBesideDev(services.stateDir);
57
51
  }
58
- return withOpenedDb(() => startDb(services, ctx.env), readDbStatus);
52
+ const ssl = await databaseSslOf(services);
53
+ return withOpenedDb(() => startDb(services, ctx.env, ssl), readDbStatus);
59
54
  }
60
55
 
61
56
  export async function runDbStatus(ctx: CommandContext, root: string): Promise<CommandResult> {