@open-mercato/cli 0.11.1-develop.8910.1.d07a49d70a → 0.11.1-develop.8929.1.493f6c653c

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 (188) hide show
  1. package/.turbo/turbo-build.log +6 -2
  2. package/dist/agentic/guides/module-facts.json +356 -399
  3. package/dist/agentic/guides/module-facts.v2.json +356 -399
  4. package/dist/agentic/guides/modules/agent_orchestrator/active-extension-bindings.md +1 -1
  5. package/dist/agentic/guides/modules/agent_orchestrator/exact-override-targets.md +1 -1
  6. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  7. package/dist/agentic/guides/modules/agent_orchestrator/workers.md +1 -1
  8. package/dist/agentic/guides/modules/ai_assistant/exact-override-targets.md +2 -2
  9. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  10. package/dist/agentic/guides/modules/ai_assistant/workers.md +2 -2
  11. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  12. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  13. package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
  14. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  15. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  16. package/dist/agentic/guides/modules/auth/entities.md +1 -0
  17. package/dist/agentic/guides/modules/auth/index.md +2 -2
  18. package/dist/agentic/guides/modules/auth/umes-hosts.md +1 -0
  19. package/dist/agentic/guides/modules/availability/index.md +1 -1
  20. package/dist/agentic/guides/modules/backups/index.md +1 -1
  21. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  22. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  23. package/dist/agentic/guides/modules/cart/index.md +1 -1
  24. package/dist/agentic/guides/modules/catalog/domain-commands.md +0 -1
  25. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  26. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  27. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  28. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  29. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  30. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  31. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  32. package/dist/agentic/guides/modules/channel_ms365/index.md +1 -1
  33. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  34. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  35. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  36. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  37. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  38. package/dist/agentic/guides/modules/configs/index.md +1 -1
  39. package/dist/agentic/guides/modules/content/index.md +1 -1
  40. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  41. package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +4 -4
  42. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  43. package/dist/agentic/guides/modules/customer_accounts/workers.md +4 -4
  44. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  45. package/dist/agentic/guides/modules/customers/index.md +1 -1
  46. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  47. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  48. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  49. package/dist/agentic/guides/modules/devices/index.md +1 -1
  50. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  51. package/dist/agentic/guides/modules/directory/index.md +1 -1
  52. package/dist/agentic/guides/modules/documents/index.md +1 -1
  53. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  54. package/dist/agentic/guides/modules/entities/index.md +1 -1
  55. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  56. package/dist/agentic/guides/modules/events/index.md +1 -1
  57. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  58. package/dist/agentic/guides/modules/forms/index.md +1 -1
  59. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  60. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  61. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  62. package/dist/agentic/guides/modules/generators/index.md +1 -1
  63. package/dist/agentic/guides/modules/gus_regon/index.md +1 -1
  64. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  65. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  66. package/dist/agentic/guides/modules/ledger/index.md +1 -1
  67. package/dist/agentic/guides/modules/maintenance/index.md +1 -1
  68. package/dist/agentic/guides/modules/messages/index.md +1 -1
  69. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  70. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  71. package/dist/agentic/guides/modules/payment_gateways/exact-override-targets.md +1 -1
  72. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  73. package/dist/agentic/guides/modules/payment_gateways/workers.md +1 -1
  74. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  75. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  76. package/dist/agentic/guides/modules/planner/index.md +1 -1
  77. package/dist/agentic/guides/modules/portal/index.md +1 -1
  78. package/dist/agentic/guides/modules/progress/index.md +1 -1
  79. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  80. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  81. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  82. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  83. package/dist/agentic/guides/modules/resources/index.md +1 -1
  84. package/dist/agentic/guides/modules/sales/exact-override-targets.md +4 -4
  85. package/dist/agentic/guides/modules/sales/index.md +1 -1
  86. package/dist/agentic/guides/modules/sales/setup.md +1 -1
  87. package/dist/agentic/guides/modules/sales_invoices_gl_posting/index.md +1 -1
  88. package/dist/agentic/guides/modules/scheduler/di-registrations-rich.md +3 -3
  89. package/dist/agentic/guides/modules/scheduler/di-service-tokens.md +3 -3
  90. package/dist/agentic/guides/modules/scheduler/exact-override-targets.md +4 -9
  91. package/dist/agentic/guides/modules/scheduler/index.md +3 -4
  92. package/dist/agentic/guides/modules/scheduler/workers.md +1 -1
  93. package/dist/agentic/guides/modules/search/di-registrations-rich.md +4 -4
  94. package/dist/agentic/guides/modules/search/di-service-tokens.md +13 -0
  95. package/dist/agentic/guides/modules/search/exact-override-targets.md +4 -4
  96. package/dist/agentic/guides/modules/search/index.md +3 -2
  97. package/dist/agentic/guides/modules/security/index.md +1 -1
  98. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  99. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  100. package/dist/agentic/guides/modules/sso/index.md +1 -1
  101. package/dist/agentic/guides/modules/staff/index.md +1 -1
  102. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  103. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  104. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  105. package/dist/agentic/guides/modules/sync_shopify/index.md +1 -1
  106. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  107. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  108. package/dist/agentic/guides/modules/tenant_boundaries/generator-plugins.md +11 -0
  109. package/dist/agentic/guides/modules/tenant_boundaries/index.md +13 -0
  110. package/dist/agentic/guides/modules/tenant_boundaries/owned-contract-module-metadata.md +11 -0
  111. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  112. package/dist/agentic/guides/modules/translations/index.md +1 -1
  113. package/dist/agentic/guides/modules/upgrade_actions/index.md +1 -1
  114. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  115. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  116. package/dist/agentic/guides/modules/wms/index.md +1 -1
  117. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  118. package/dist/agentic/guides/reference-module-facts.json +2 -2
  119. package/dist/agentic/guides/reference-modules/example/index.md +1 -1
  120. package/dist/agentic/guides/upstream/manifest.json +1 -1
  121. package/dist/agentic/shared/AGENTS.md.template +3 -3
  122. package/dist/agentic/shared/ai/harness/cases.json +4 -4
  123. package/dist/bin.js +6 -3
  124. package/dist/bin.js.map +2 -2
  125. package/dist/i18n/de.json +5 -1
  126. package/dist/i18n/en.json +5 -1
  127. package/dist/i18n/es.json +5 -1
  128. package/dist/i18n/ko.json +5 -1
  129. package/dist/i18n/pl.json +5 -1
  130. package/dist/lib/cli-bootstrap-mode.js +10 -1
  131. package/dist/lib/cli-bootstrap-mode.js.map +2 -2
  132. package/dist/lib/db/commands.js +18 -3
  133. package/dist/lib/db/commands.js.map +2 -2
  134. package/dist/lib/db/maintenance-client.js +72 -0
  135. package/dist/lib/db/maintenance-client.js.map +7 -0
  136. package/dist/lib/generate-watch-structure.js +2 -1
  137. package/dist/lib/generate-watch-structure.js.map +2 -2
  138. package/dist/lib/generators/database-declarations.js +21 -0
  139. package/dist/lib/generators/database-declarations.js.map +7 -0
  140. package/dist/lib/generators/module-registry.js +19 -3
  141. package/dist/lib/generators/module-registry.js.map +2 -2
  142. package/dist/lib/init-existing-database.js +91 -1
  143. package/dist/lib/init-existing-database.js.map +2 -2
  144. package/dist/lib/init-i18n.js +13 -0
  145. package/dist/lib/init-i18n.js.map +7 -0
  146. package/dist/lib/init-secrets.js +2 -10
  147. package/dist/lib/init-secrets.js.map +2 -2
  148. package/dist/lib/scheduler-supervisor.js +47 -7
  149. package/dist/lib/scheduler-supervisor.js.map +2 -2
  150. package/dist/lib/server-start-lock.js +120 -21
  151. package/dist/lib/server-start-lock.js.map +2 -2
  152. package/dist/lib/worker-job-handler.js +36 -26
  153. package/dist/lib/worker-job-handler.js.map +2 -2
  154. package/dist/mercato.js +93 -54
  155. package/dist/mercato.js.map +3 -3
  156. package/package.json +7 -7
  157. package/src/__tests__/mercato.test.ts +166 -9
  158. package/src/bin.ts +10 -4
  159. package/src/i18n/de.json +5 -1
  160. package/src/i18n/en.json +5 -1
  161. package/src/i18n/es.json +5 -1
  162. package/src/i18n/ko.json +5 -1
  163. package/src/i18n/pl.json +5 -1
  164. package/src/lib/__tests__/cli-bootstrap-mode.test.ts +76 -1
  165. package/src/lib/__tests__/generate-watch-structure.test.ts +26 -0
  166. package/src/lib/__tests__/rotation-kms-warning-presentation.test.ts +1 -1
  167. package/src/lib/__tests__/scheduler-supervisor.test.ts +107 -0
  168. package/src/lib/__tests__/server-start-lock.test.ts +400 -0
  169. package/src/lib/__tests__/worker-job-handler.database.test.ts +76 -0
  170. package/src/lib/cli-bootstrap-mode.ts +12 -2
  171. package/src/lib/db/__tests__/commands.migrate-reindex.test.ts +72 -1
  172. package/src/lib/db/__tests__/maintenance-client.test.ts +70 -0
  173. package/src/lib/db/commands.ts +20 -6
  174. package/src/lib/db/maintenance-client.ts +54 -0
  175. package/src/lib/generate-watch-structure.ts +2 -1
  176. package/src/lib/generators/__tests__/database-declarations.test.ts +69 -0
  177. package/src/lib/generators/__tests__/incremental-registry.test.ts +1 -1
  178. package/src/lib/generators/__tests__/module-subset.test.ts +17 -1
  179. package/src/lib/generators/database-declarations.ts +19 -0
  180. package/src/lib/generators/module-registry.ts +23 -4
  181. package/src/lib/init-existing-database.ts +107 -0
  182. package/src/lib/init-i18n.ts +11 -0
  183. package/src/lib/init-secrets.ts +2 -12
  184. package/src/lib/scheduler-supervisor.ts +40 -7
  185. package/src/lib/server-start-lock.ts +170 -19
  186. package/src/lib/worker-job-handler.ts +39 -28
  187. package/src/mercato.ts +92 -53
  188. package/dist/agentic/guides/modules/scheduler/cli-commands.md +0 -15
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/cli",
3
- "version": "0.11.1-develop.8910.1.d07a49d70a",
3
+ "version": "0.11.1-develop.8929.1.493f6c653c",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -60,10 +60,10 @@
60
60
  "@mikro-orm/decorators": "^7.1.14",
61
61
  "@mikro-orm/migrations": "^7.1.14",
62
62
  "@mikro-orm/postgresql": "^7.1.14",
63
- "@open-mercato/events": "0.11.1-develop.8910.1.d07a49d70a",
64
- "@open-mercato/queue": "0.11.1-develop.8910.1.d07a49d70a",
65
- "@open-mercato/shared": "0.11.1-develop.8910.1.d07a49d70a",
66
- "@open-mercato/telemetry": "0.11.1-develop.8910.1.d07a49d70a",
63
+ "@open-mercato/events": "0.11.1-develop.8929.1.493f6c653c",
64
+ "@open-mercato/queue": "0.11.1-develop.8929.1.493f6c653c",
65
+ "@open-mercato/shared": "0.11.1-develop.8929.1.493f6c653c",
66
+ "@open-mercato/telemetry": "0.11.1-develop.8929.1.493f6c653c",
67
67
  "cross-spawn": "^7.0.6",
68
68
  "minisearch": "7.2.0",
69
69
  "pg": "8.23.0",
@@ -75,10 +75,10 @@
75
75
  "typescript-js": "npm:typescript@6.0.3"
76
76
  },
77
77
  "peerDependencies": {
78
- "@open-mercato/shared": "0.11.1-develop.8910.1.d07a49d70a"
78
+ "@open-mercato/shared": "0.11.1-develop.8929.1.493f6c653c"
79
79
  },
80
80
  "devDependencies": {
81
- "@open-mercato/shared": "0.11.1-develop.8910.1.d07a49d70a",
81
+ "@open-mercato/shared": "0.11.1-develop.8929.1.493f6c653c",
82
82
  "@types/jest": "^30.0.0",
83
83
  "jest": "^30.4.2",
84
84
  "ts-jest": "^29.4.12"
@@ -774,6 +774,26 @@ describe('--help never triggers side effects (issue #5581)', () => {
774
774
  describe('db command failure output', () => {
775
775
  const originalDatabaseUrl = process.env.DATABASE_URL
776
776
 
777
+ it('refuses opt-in migration if bootstrap did not register the database runtime', async () => {
778
+ const originalTenantRls = process.env.OM_TENANT_RLS
779
+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation()
780
+ const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation()
781
+ try {
782
+ registerCliModules([])
783
+ process.env.OM_TENANT_RLS = 'on'
784
+
785
+ const exitCode = await run(['node', 'mercato', 'db', 'migrate'])
786
+
787
+ expect(exitCode).toBe(1)
788
+ expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('Tenant boundaries were requested but are not registered.'))
789
+ } finally {
790
+ if (originalTenantRls === undefined) delete process.env.OM_TENANT_RLS
791
+ else process.env.OM_TENANT_RLS = originalTenantRls
792
+ consoleErrorSpy.mockRestore()
793
+ consoleLogSpy.mockRestore()
794
+ }
795
+ })
796
+
777
797
  beforeEach(() => {
778
798
  jest.restoreAllMocks()
779
799
  process.env.DATABASE_URL = 'postgres://postgres:secret@127.0.0.1:5432/open_mercato'
@@ -1001,6 +1021,11 @@ describe('module command exit signal propagation', () => {
1001
1021
  })
1002
1022
  })
1003
1023
 
1024
+ function initDatabaseQuery(rows: Array<Record<string, string>>) {
1025
+ return jest.fn(async (sql: string) =>
1026
+ sql.includes('pg_try_advisory_lock') ? { rowCount: 1, rows: [{ locked: true }] } : { rowCount: 1, rows })
1027
+ }
1028
+
1004
1029
  describe('init command failure output', () => {
1005
1030
  const originalDatabaseUrl = process.env.DATABASE_URL
1006
1031
 
@@ -1140,9 +1165,8 @@ describe('init command failure output', () => {
1140
1165
  jest.doMock('pg', () => ({
1141
1166
  Client: jest.fn().mockImplementation(() => ({
1142
1167
  connect: jest.fn().mockResolvedValue(undefined),
1143
- query: jest.fn().mockResolvedValue({
1144
- rows: [{ org_id: 'org-1', tenant_id: 'tenant-1' }],
1145
- }),
1168
+ on: jest.fn(),
1169
+ query: initDatabaseQuery([{ org_id: 'org-1', tenant_id: 'tenant-1' }]),
1146
1170
  end: jest.fn().mockResolvedValue(undefined),
1147
1171
  })),
1148
1172
  }))
@@ -1248,7 +1272,8 @@ describe('init command failure output', () => {
1248
1272
  jest.doMock('pg', () => ({
1249
1273
  Client: jest.fn().mockImplementation(() => ({
1250
1274
  connect: jest.fn().mockResolvedValue(undefined),
1251
- query: jest.fn().mockResolvedValue({ rows: [] }),
1275
+ on: jest.fn(),
1276
+ query: initDatabaseQuery([]),
1252
1277
  end: jest.fn().mockResolvedValue(undefined),
1253
1278
  })),
1254
1279
  }))
@@ -1313,8 +1338,14 @@ describe('init command failure output', () => {
1313
1338
 
1314
1339
  function mockInitDependencies({
1315
1340
  authSetup,
1341
+ databaseQuery = initDatabaseQuery([{ org_id: 'org-1', tenant_id: 'tenant-1' }]),
1342
+ restoreDefaults = jest.fn().mockResolvedValue(undefined),
1343
+ seedEncryption = jest.fn().mockResolvedValue(undefined),
1316
1344
  }: {
1317
1345
  authSetup: jest.Mock
1346
+ databaseQuery?: jest.Mock
1347
+ restoreDefaults?: jest.Mock
1348
+ seedEncryption?: jest.Mock
1318
1349
  }) {
1319
1350
  jest.doMock('child_process', () => ({
1320
1351
  execSync: jest.fn(),
@@ -1322,9 +1353,8 @@ describe('init command failure output', () => {
1322
1353
  jest.doMock('pg', () => ({
1323
1354
  Client: jest.fn().mockImplementation(() => ({
1324
1355
  connect: jest.fn().mockResolvedValue(undefined),
1325
- query: jest.fn().mockResolvedValue({
1326
- rows: [{ org_id: 'org-1', tenant_id: 'tenant-1' }],
1327
- }),
1356
+ on: jest.fn(),
1357
+ query: databaseQuery,
1328
1358
  end: jest.fn().mockResolvedValue(undefined),
1329
1359
  })),
1330
1360
  }))
@@ -1351,7 +1381,7 @@ describe('init command failure output', () => {
1351
1381
  modules: [
1352
1382
  {
1353
1383
  id: 'configs',
1354
- cli: [{ command: 'restore-defaults', run: jest.fn().mockResolvedValue(undefined) }],
1384
+ cli: [{ command: 'restore-defaults', run: restoreDefaults }],
1355
1385
  },
1356
1386
  {
1357
1387
  id: 'auth',
@@ -1362,7 +1392,7 @@ describe('init command failure output', () => {
1362
1392
  },
1363
1393
  {
1364
1394
  id: 'entities',
1365
- cli: [{ command: 'seed-encryption', run: jest.fn().mockResolvedValue(undefined) }],
1395
+ cli: [{ command: 'seed-encryption', run: seedEncryption }],
1366
1396
  },
1367
1397
  {
1368
1398
  id: 'query_index',
@@ -1385,6 +1415,132 @@ describe('init command failure output', () => {
1385
1415
  )
1386
1416
  }
1387
1417
 
1418
+ type InitializationScenario = {
1419
+ outcome: string
1420
+ staleMarker?: boolean
1421
+ lockAvailable?: boolean
1422
+ failDefaults?: boolean
1423
+ failAuth?: boolean
1424
+ failEncryption?: boolean
1425
+ exitCodes: [number, number]
1426
+ markerCompleted: [boolean | undefined, boolean | undefined]
1427
+ calls: { restoreDefaults: number; authSetup: number; seedEncryption: number }
1428
+ logs?: string[]
1429
+ errors?: string[]
1430
+ }
1431
+
1432
+ it.each<InitializationScenario>([
1433
+ {
1434
+ outcome: 'completed',
1435
+ exitCodes: [0, 0],
1436
+ markerCompleted: [true, true],
1437
+ calls: { restoreDefaults: 1, authSetup: 1, seedEncryption: 1 },
1438
+ logs: ['Database already initialized'],
1439
+ },
1440
+ {
1441
+ outcome: 'encryption failure',
1442
+ failEncryption: true,
1443
+ exitCodes: [1, 1],
1444
+ markerCompleted: [false, false],
1445
+ calls: { restoreDefaults: 1, authSetup: 1, seedEncryption: 1 },
1446
+ errors: ['Initialization has started but has not completed', '--reinstall'],
1447
+ },
1448
+ {
1449
+ outcome: 'defaults failure',
1450
+ failDefaults: true,
1451
+ exitCodes: [1, 0],
1452
+ markerCompleted: [undefined, true],
1453
+ calls: { restoreDefaults: 2, authSetup: 1, seedEncryption: 1 },
1454
+ },
1455
+ {
1456
+ outcome: 'auth failure before users',
1457
+ failAuth: true,
1458
+ exitCodes: [1, 0],
1459
+ markerCompleted: [undefined, true],
1460
+ calls: { restoreDefaults: 2, authSetup: 2, seedEncryption: 1 },
1461
+ },
1462
+ {
1463
+ outcome: 'a killed attempt that created no users',
1464
+ staleMarker: true,
1465
+ exitCodes: [0, 0],
1466
+ markerCompleted: [true, true],
1467
+ calls: { restoreDefaults: 1, authSetup: 1, seedEncryption: 1 },
1468
+ logs: ['Cleared an interrupted initialization attempt', 'Database already initialized'],
1469
+ },
1470
+ {
1471
+ outcome: 'a live concurrent attempt',
1472
+ staleMarker: true,
1473
+ lockAvailable: false,
1474
+ exitCodes: [1, 1],
1475
+ markerCompleted: [false, false],
1476
+ calls: { restoreDefaults: 0, authSetup: 0, seedEncryption: 0 },
1477
+ errors: ['Another initialization already started'],
1478
+ },
1479
+ ])('handles initialization after $outcome', async (scenario) => {
1480
+ const consoleError = jest.spyOn(console, 'error').mockImplementation()
1481
+ const consoleLog = jest.spyOn(console, 'log').mockImplementation()
1482
+ const previousLocale = process.env.LC_ALL
1483
+ process.env.LC_ALL = 'en'
1484
+ let usersCount = 0
1485
+ let marker: { id: string; completed: boolean } | undefined = scenario.staleMarker
1486
+ ? { id: 'interrupted-attempt', completed: false }
1487
+ : undefined
1488
+ const authSetup = jest.fn(async () => { usersCount = 1 })
1489
+ if (scenario.failAuth) authSetup.mockRejectedValueOnce(new Error('auth setup failed'))
1490
+ const restoreDefaults = jest.fn().mockResolvedValue(undefined)
1491
+ if (scenario.failDefaults) restoreDefaults.mockRejectedValueOnce(new Error('defaults restore failed'))
1492
+ const seedEncryption = scenario.failEncryption
1493
+ ? jest.fn().mockRejectedValue(new Error('encryption seeding failed'))
1494
+ : jest.fn().mockResolvedValue(undefined)
1495
+ const databaseQuery = jest.fn(async (sql: string, params?: string[]) => {
1496
+ if (sql.includes('pg_database')) return { rows: [{ exists: 1 }] }
1497
+ if (sql.includes('to_regclass')) {
1498
+ expect(sql).toMatch(/to_regclass\('(users|app_initializations)'\)/)
1499
+ return { rows: [{ regclass: 'present' }] }
1500
+ }
1501
+ if (sql.includes('pg_try_advisory_lock')) return { rows: [{ locked: scenario.lockAvailable !== false }] }
1502
+ if (sql.includes('COUNT(*)')) return { rows: [{ count: String(usersCount) }] }
1503
+ if (sql.startsWith('SELECT completed_at')) return { rows: marker ? [{ pending: !marker.completed }] : [] }
1504
+ if (sql.startsWith('INSERT INTO app_initializations')) {
1505
+ if (marker) return { rowCount: 0, rows: [] }
1506
+ marker = { id: params![0], completed: false }
1507
+ return { rowCount: 1, rows: [] }
1508
+ }
1509
+ if (sql.startsWith('DELETE FROM app_initializations')) {
1510
+ expect(sql).toContain('NOT EXISTS (SELECT 1 FROM users)')
1511
+ const matches = sql.includes('WHERE name') ? true : marker?.id === params?.[0]
1512
+ if (!marker || !matches || marker.completed || usersCount > 0) return { rowCount: 0, rows: [] }
1513
+ marker = undefined
1514
+ return { rowCount: 1, rows: [] }
1515
+ }
1516
+ if (sql.startsWith('UPDATE app_initializations')) {
1517
+ if (!marker || marker.id !== params?.[0]) return { rowCount: 0, rows: [] }
1518
+ marker.completed = true
1519
+ return { rowCount: 1, rows: [] }
1520
+ }
1521
+ return { rows: [{ org_id: 'org-1', tenant_id: 'tenant-1' }] }
1522
+ })
1523
+ mockInitDependencies({ authSetup, databaseQuery, restoreDefaults, seedEncryption })
1524
+ try {
1525
+ const mercato = await import('../mercato')
1526
+ expect(await mercato.run(['node', 'mercato', 'init', '--no-examples'])).toBe(scenario.exitCodes[0])
1527
+ expect(marker?.completed).toBe(scenario.markerCompleted[0])
1528
+ expect(await mercato.run(['node', 'mercato', 'init', '--skip-if-initialized'])).toBe(scenario.exitCodes[1])
1529
+ expect(marker?.completed).toBe(scenario.markerCompleted[1])
1530
+ expect(restoreDefaults).toHaveBeenCalledTimes(scenario.calls.restoreDefaults)
1531
+ expect(authSetup).toHaveBeenCalledTimes(scenario.calls.authSetup)
1532
+ expect(seedEncryption).toHaveBeenCalledTimes(scenario.calls.seedEncryption)
1533
+ const logs = consoleLog.mock.calls.flat().join('\n')
1534
+ const errors = consoleError.mock.calls.flat().join('\n')
1535
+ for (const expected of scenario.logs ?? []) expect(logs).toContain(expected)
1536
+ for (const expected of scenario.errors ?? []) expect(errors).toContain(expected)
1537
+ if (scenario.exitCodes[1] !== 0) expect(logs).not.toContain('Database already initialized')
1538
+ } finally {
1539
+ if (previousLocale === undefined) delete process.env.LC_ALL
1540
+ else process.env.LC_ALL = previousLocale
1541
+ }
1542
+ })
1543
+
1388
1544
  it.each(['--reinstall', '--no-demo-users'])('rejects unsafe production init before side effects with %s', async (flag) => {
1389
1545
  const previousEnv = { ...process.env }
1390
1546
  jest.spyOn(console, 'error').mockImplementation()
@@ -1677,6 +1833,7 @@ describe('init on an already initialized database', () => {
1677
1833
  jest.doMock('pg', () => ({
1678
1834
  Client: jest.fn().mockImplementation(() => ({
1679
1835
  connect: jest.fn().mockResolvedValue(undefined),
1836
+ on: jest.fn(),
1680
1837
  end: jest.fn().mockResolvedValue(undefined),
1681
1838
  query: jest.fn().mockImplementation(async (sql: string) => {
1682
1839
  if (sql.includes('pg_database')) return { rows: [{ exists: 1 }] }
package/src/bin.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { isTelemetryBackendEnabled } from '@open-mercato/shared/lib/telemetry/runtime'
8
8
  import { installNextSubpathResolveHook } from '@open-mercato/shared/lib/bootstrap/next-subpath-resolve-hook'
9
- import { resolveCliBootstrapMode, type CliBootstrapMode } from './lib/cli-bootstrap-mode.js'
9
+ import { requiresDatabaseRuntimeForMigration, resolveCliBootstrapMode, type CliBootstrapMode } from './lib/cli-bootstrap-mode.js'
10
10
  import { flushBeforeExit } from './lib/flush-before-exit.js'
11
11
  import { runWithRotationKmsWarningPresentation } from './lib/rotation-kms-warning-presentation.js'
12
12
  // `run` is imported dynamically inside `main()` so telemetry can initialize
@@ -27,7 +27,7 @@ function assertNode24Runtime(): void {
27
27
  )
28
28
  }
29
29
 
30
- async function tryBootstrap(mode: Exclude<CliBootstrapMode, 'none'>): Promise<boolean> {
30
+ async function tryBootstrap(mode: Extract<CliBootstrapMode, 'dev-supervisor' | 'full'>): Promise<boolean> {
31
31
  try {
32
32
  // Use the CLI resolver to find the app directory (handles monorepo detection)
33
33
  const { createResolver } = await import('./lib/resolver.js')
@@ -78,9 +78,9 @@ async function main(): Promise<void> {
78
78
  // as `next/dynamic` or `next/link` does not resolve (#7102). Install the
79
79
  // retry-with-`.js` hook before any package dist can be imported.
80
80
  installNextSubpathResolveHook()
81
- const bootstrapMode = resolveCliBootstrapMode(process.argv)
81
+ const requestedBootstrapMode = resolveCliBootstrapMode(process.argv)
82
82
 
83
- if (bootstrapMode !== 'none') {
83
+ if (requestedBootstrapMode !== 'none') {
84
84
  // Load the app's `.env` BEFORE initTelemetry(): `run()` only dotenv-loads it
85
85
  // later (ensureEnvLoaded), which is too late — TELEMETRY_BACKEND set only in
86
86
  // `.env` would silently resolve to `noop` for worker/scheduler processes.
@@ -88,7 +88,13 @@ async function main(): Promise<void> {
88
88
  // instrumentation load-order guarantee below.
89
89
  const { loadAppEnv } = await import('./lib/load-env.js')
90
90
  await loadAppEnv()
91
+ }
91
92
 
93
+ const bootstrapMode = requestedBootstrapMode === 'database-migrate'
94
+ ? (requiresDatabaseRuntimeForMigration() ? 'full' : 'none')
95
+ : requestedBootstrapMode
96
+
97
+ if (bootstrapMode !== 'none') {
92
98
  // Initialize telemetry BEFORE bootstrapping the app graph. Bootstrap and the
93
99
  // per-command handlers load MikroORM's Postgres driver → `pg`, and the
94
100
  // OpenTelemetry pg/undici auto-instrumentation only records spans for a
package/src/i18n/de.json CHANGED
@@ -1,4 +1,8 @@
1
1
  {
2
+ "cli.init.errors.concurrentInitialization": "Für diese Datenbank wurde bereits eine andere Initialisierung gestartet. Prüfen Sie deren Ergebnis vor einem erneuten Versuch.",
3
+ "cli.init.errors.incompleteInitialization": "Die Initialisierung von {database} wurde gestartet, aber noch nicht abgeschlossen. Prüfen Sie die bisherigen Initialisierungsprotokolle. Verwenden Sie --reinstall nur, wenn Sie die Datenbank löschen und neu beginnen möchten.",
4
+ "cli.init.errors.initializationStateMissing": "Der Abschluss dieses Initialisierungsversuchs konnte nicht gespeichert werden. Prüfen Sie die Datenbank und die Initialisierungsprotokolle vor einem erneuten Versuch.",
2
5
  "cli.init.errors.superadminPasswordPolicy": "Das Superadmin-Passwort für die Produktion erfüllt die konfigurierte Passwortrichtlinie nicht. Flags zum Umgehen der Passwortrichtlinie gelten nur außerhalb der Produktion.",
3
- "cli.init.errors.superadminPasswordRequired": "Die Produktionsinitialisierung erfordert ein eindeutiges Superadmin-Passwort über OM_INIT_SUPERADMIN_PASSWORD oder --password; integrierte Platzhalter sind nicht zulässig."
6
+ "cli.init.errors.superadminPasswordRequired": "Die Produktionsinitialisierung erfordert ein eindeutiges Superadmin-Passwort über OM_INIT_SUPERADMIN_PASSWORD oder --password; integrierte Platzhalter sind nicht zulässig.",
7
+ "cli.init.messages.interruptedAttemptCleared": "♻️ Ein unterbrochener Initialisierungsversuch ohne angelegte Benutzer wurde entfernt."
4
8
  }
package/src/i18n/en.json CHANGED
@@ -1,4 +1,8 @@
1
1
  {
2
+ "cli.init.errors.concurrentInitialization": "Another initialization already started for this database. Check its result before retrying.",
3
+ "cli.init.errors.incompleteInitialization": "Initialization has started but has not completed for {database}. Check the prior initialization logs. Use --reinstall only if you intend to erase the database and start over.",
4
+ "cli.init.errors.initializationStateMissing": "Could not record completion for this initialization attempt. Check the database and initialization logs before retrying.",
2
5
  "cli.init.errors.superadminPasswordPolicy": "Production superadmin password does not meet the configured password policy. Password-policy bypass flags apply only outside production.",
3
- "cli.init.errors.superadminPasswordRequired": "Production initialization requires a unique superadmin password via OM_INIT_SUPERADMIN_PASSWORD or --password; built-in placeholders are not allowed."
6
+ "cli.init.errors.superadminPasswordRequired": "Production initialization requires a unique superadmin password via OM_INIT_SUPERADMIN_PASSWORD or --password; built-in placeholders are not allowed.",
7
+ "cli.init.messages.interruptedAttemptCleared": "♻️ Cleared an interrupted initialization attempt that had not created any users."
4
8
  }
package/src/i18n/es.json CHANGED
@@ -1,4 +1,8 @@
1
1
  {
2
+ "cli.init.errors.concurrentInitialization": "Ya se inició otra inicialización para esta base de datos. Compruebe su resultado antes de volver a intentarlo.",
3
+ "cli.init.errors.incompleteInitialization": "La inicialización de {database} se inició pero sigue incompleta. Consulte los registros de la inicialización anterior. Use --reinstall solo si desea borrar la base de datos y empezar de nuevo.",
4
+ "cli.init.errors.initializationStateMissing": "No se pudo registrar la finalización de este intento de inicialización. Compruebe la base de datos y los registros de inicialización antes de volver a intentarlo.",
2
5
  "cli.init.errors.superadminPasswordPolicy": "La contraseña de superadministrador en producción no cumple la política de contraseñas configurada. Las opciones para omitir la política solo se aplican fuera de producción.",
3
- "cli.init.errors.superadminPasswordRequired": "La inicialización en producción requiere una contraseña única de superadministrador mediante OM_INIT_SUPERADMIN_PASSWORD o --password; no se permiten los valores predeterminados de ejemplo."
6
+ "cli.init.errors.superadminPasswordRequired": "La inicialización en producción requiere una contraseña única de superadministrador mediante OM_INIT_SUPERADMIN_PASSWORD o --password; no se permiten los valores predeterminados de ejemplo.",
7
+ "cli.init.messages.interruptedAttemptCleared": "♻️ Se eliminó un intento de inicialización interrumpido que no había creado ningún usuario."
4
8
  }
package/src/i18n/ko.json CHANGED
@@ -1,4 +1,8 @@
1
1
  {
2
+ "cli.init.errors.concurrentInitialization": "이 데이터베이스의 다른 초기화가 이미 시작되었습니다. 다시 시도하기 전에 그 결과를 확인하세요.",
3
+ "cli.init.errors.incompleteInitialization": "{database}의 초기화가 시작되었지만 완료되지 않았습니다. 이전 초기화 로그를 확인하세요. 데이터베이스를 지우고 처음부터 시작하려는 경우에만 --reinstall을 사용하세요.",
4
+ "cli.init.errors.initializationStateMissing": "이번 초기화 시도의 완료 상태를 기록하지 못했습니다. 다시 시도하기 전에 데이터베이스와 초기화 로그를 확인하세요.",
2
5
  "cli.init.errors.superadminPasswordPolicy": "프로덕션 슈퍼관리자 비밀번호가 설정된 비밀번호 정책을 충족하지 않습니다. 비밀번호 정책 우회 플래그는 프로덕션 외 환경에서만 적용됩니다.",
3
- "cli.init.errors.superadminPasswordRequired": "프로덕션 초기화에는 OM_INIT_SUPERADMIN_PASSWORD 또는 --password로 지정한 고유한 슈퍼관리자 비밀번호가 필요합니다. 기본 예시 비밀번호는 사용할 수 없습니다."
6
+ "cli.init.errors.superadminPasswordRequired": "프로덕션 초기화에는 OM_INIT_SUPERADMIN_PASSWORD 또는 --password로 지정한 고유한 슈퍼관리자 비밀번호가 필요합니다. 기본 예시 비밀번호는 사용할 수 없습니다.",
7
+ "cli.init.messages.interruptedAttemptCleared": "♻️ 사용자를 생성하지 않은 채 중단된 초기화 시도를 정리했습니다."
4
8
  }
package/src/i18n/pl.json CHANGED
@@ -1,4 +1,8 @@
1
1
  {
2
+ "cli.init.errors.concurrentInitialization": "Dla tej bazy danych rozpoczęto już inną inicjalizację. Sprawdź jej wynik przed ponowną próbą.",
3
+ "cli.init.errors.incompleteInitialization": "Inicjalizacja bazy {database} została rozpoczęta, ale nie została ukończona. Sprawdź dzienniki poprzedniej inicjalizacji. Użyj --reinstall tylko wtedy, gdy chcesz usunąć bazę danych i zacząć od nowa.",
4
+ "cli.init.errors.initializationStateMissing": "Nie udało się zapisać zakończenia tej próby inicjalizacji. Przed ponowną próbą sprawdź bazę danych i dzienniki inicjalizacji.",
2
5
  "cli.init.errors.superadminPasswordPolicy": "Hasło superadministratora w środowisku produkcyjnym nie spełnia skonfigurowanej polityki haseł. Flagi pomijające politykę haseł działają tylko poza środowiskiem produkcyjnym.",
3
- "cli.init.errors.superadminPasswordRequired": "Inicjalizacja produkcyjna wymaga unikalnego hasła superadministratora podanego przez OM_INIT_SUPERADMIN_PASSWORD lub --password; wbudowane hasła przykładowe są niedozwolone."
6
+ "cli.init.errors.superadminPasswordRequired": "Inicjalizacja produkcyjna wymaga unikalnego hasła superadministratora podanego przez OM_INIT_SUPERADMIN_PASSWORD lub --password; wbudowane hasła przykładowe są niedozwolone.",
7
+ "cli.init.messages.interruptedAttemptCleared": "♻️ Usunięto przerwaną próbę inicjalizacji, która nie utworzyła żadnych użytkowników."
4
8
  }
@@ -1,4 +1,9 @@
1
- import { resolveCliBootstrapMode } from '../cli-bootstrap-mode'
1
+ import { spawnSync } from 'node:child_process'
2
+ import { mkdtemp, rm } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import path from 'node:path'
5
+ import { build } from 'esbuild'
6
+ import { requiresDatabaseRuntimeForMigration, resolveCliBootstrapMode } from '../cli-bootstrap-mode'
2
7
 
3
8
  describe('resolveCliBootstrapMode', () => {
4
9
  it('uses the lightweight manifest only for the exact server dev command', () => {
@@ -16,7 +21,77 @@ describe('resolveCliBootstrapMode', () => {
16
21
  it('preserves existing bootstrap-free commands', () => {
17
22
  expect(resolveCliBootstrapMode(['node', 'mercato', 'generate'])).toBe('none')
18
23
  expect(resolveCliBootstrapMode(['node', 'mercato', 'db', 'generate'])).toBe('none')
24
+ expect(resolveCliBootstrapMode(['node', 'mercato', 'db', 'migrate', '--help'])).toBe('none')
25
+ expect(resolveCliBootstrapMode(['node', 'mercato', 'db', 'migrate', '-h'])).toBe('none')
19
26
  expect(resolveCliBootstrapMode(['node', 'mercato', 'help'])).toBe('none')
20
27
  expect(resolveCliBootstrapMode(['node', 'mercato'])).toBe('none')
21
28
  })
29
+
30
+ it('routes migration through environment loading before deciding whether to bootstrap', () => {
31
+ expect(resolveCliBootstrapMode(['node', 'mercato', 'db', 'migrate'])).toBe('database-migrate')
32
+ })
33
+ })
34
+
35
+ describe('requiresDatabaseRuntimeForMigration', () => {
36
+ it.each([undefined, ' ', 'off', 'FALSE', '0'])('preserves ordinary migration with %s', (value) => {
37
+ expect(requiresDatabaseRuntimeForMigration({ OM_TENANT_RLS: value })).toBe(false)
38
+ })
39
+
40
+ it.each(['on', ' YES ', 'invalid'])('requires registration for configured mode %s', (value) => {
41
+ expect(requiresDatabaseRuntimeForMigration({ OM_TENANT_RLS: value })).toBe(true)
42
+ })
43
+ })
44
+
45
+ it('loads the RLS opt-in from the CLI environment before bootstrapping and dispatching migration', async () => {
46
+ const directory = await mkdtemp(path.join(tmpdir(), 'om-cli-migrate-bootstrap-'))
47
+ try {
48
+ const binary = path.join(directory, 'bin.mjs')
49
+ const fixtures: Record<string, string> = {
50
+ '@open-mercato/telemetry': 'export const initTelemetry = async () => {}',
51
+ '@open-mercato/shared/lib/telemetry/runtime': 'export const isTelemetryBackendEnabled = () => false',
52
+ '@open-mercato/shared/lib/bootstrap/next-subpath-resolve-hook': 'export const installNextSubpathResolveHook = () => {}',
53
+ '@open-mercato/shared/lib/bootstrap/dynamicLoader': 'export const bootstrapFromAppRoot = async () => { console.log("registered runtime"); return { modules: [] } }',
54
+ './lib/dev-supervisor-manifest.js': 'export const canUseLightweightDevSupervisor = () => false; export const loadDevSupervisorManifest = () => null; export const registerDevSupervisorManifest = () => {}',
55
+ './lib/flush-before-exit.js': 'export const flushBeforeExit = async () => {}',
56
+ './lib/load-env.js': 'export const loadAppEnv = async () => { process.env.OM_TENANT_RLS = process.env.TEST_APP_RLS; console.log("loaded env") }',
57
+ './lib/resolver.js': 'export const createResolver = () => ({ getAppDir: () => "/fixture-app" })',
58
+ './lib/rotation-kms-warning-presentation.js': 'export const runWithRotationKmsWarningPresentation = (argv, main) => main()',
59
+ './mercato.js': 'export const registerCliModules = () => {}; export const run = async () => { console.log("dispatched"); return 0 }',
60
+ }
61
+ await build({
62
+ entryPoints: [path.resolve(__dirname, '../../bin.ts')],
63
+ outfile: binary,
64
+ bundle: true,
65
+ platform: 'node',
66
+ format: 'esm',
67
+ plugins: [{
68
+ name: 'fixture-bootstrap',
69
+ setup(builder) {
70
+ builder.onResolve({ filter: /.*/ }, ({ path: specifier }) => {
71
+ if (specifier in fixtures) return { path: specifier, namespace: 'fixture' }
72
+ if (specifier === '@open-mercato/shared/lib/boolean') {
73
+ return { path: path.resolve(__dirname, '../../../../shared/src/lib/boolean.ts') }
74
+ }
75
+ })
76
+ builder.onLoad({ filter: /.*/, namespace: 'fixture' }, ({ path: specifier }) => ({ contents: fixtures[specifier], loader: 'js' }))
77
+ },
78
+ }],
79
+ })
80
+
81
+ const on = spawnSync(process.execPath, [binary, 'db', 'migrate'], {
82
+ env: { ...process.env, TEST_APP_RLS: 'on' }, encoding: 'utf8', timeout: 5000,
83
+ })
84
+ expect(on.stderr).toBe('')
85
+ expect(on.status).toBe(0)
86
+ expect(on.stdout.trim().split('\n')).toEqual(['loaded env', 'registered runtime', 'dispatched'])
87
+
88
+ const off = spawnSync(process.execPath, [binary, 'db', 'migrate'], {
89
+ env: { ...process.env, TEST_APP_RLS: 'off' }, encoding: 'utf8', timeout: 5000,
90
+ })
91
+ expect(off.stderr).toBe('')
92
+ expect(off.status).toBe(0)
93
+ expect(off.stdout.trim().split('\n')).toEqual(['loaded env', 'dispatched'])
94
+ } finally {
95
+ await rm(directory, { recursive: true, force: true })
96
+ }
22
97
  })
@@ -712,6 +712,32 @@ describe('structured generator inputs', () => {
712
712
  expect(changesSince(merged).changes).toContainEqual(expect.objectContaining({ category: 'i18n', kind: 'delete', path: locale }))
713
713
  })
714
714
 
715
+ it('plans regeneration for built-in database declarations without a plugin descriptor', () => {
716
+ const database = path.join(pkg, 'database.ts')
717
+ const before = capture()
718
+
719
+ write(database, 'export const databaseDeclarations = {}')
720
+ const added = changesSince(before)
721
+ expect(added.changes).toContainEqual(
722
+ expect.objectContaining({ category: 'generator-plugin', kind: 'add', path: database }),
723
+ )
724
+ expect(planGenerateWatchChanges(added.changes).mode).toBe('full')
725
+
726
+ write(database, 'export const databaseDeclarations = { bindingValidators: [] }')
727
+ const changed = changesSince(added.next)
728
+ expect(changed.changes).toContainEqual(
729
+ expect.objectContaining({ category: 'generator-plugin', kind: 'change', path: database }),
730
+ )
731
+ expect(planGenerateWatchChanges(changed.changes).mode).toBe('full')
732
+
733
+ fs.rmSync(database)
734
+ const removed = changesSince(changed.next)
735
+ expect(removed.changes).toContainEqual(
736
+ expect.objectContaining({ category: 'generator-plugin', kind: 'delete', path: database }),
737
+ )
738
+ expect(planGenerateWatchChanges(removed.changes).mode).toBe('full')
739
+ })
740
+
715
741
  it('reads built-in-style static plugin descriptors and watches arbitrary nested contributions', () => {
716
742
  write(path.join(pkg, 'generators.ts'), `
717
743
  import type { GeneratorPlugin } from '@open-mercato/shared/modules/generators'
@@ -45,7 +45,7 @@ test.each([['entities', 'rotate-encryption-key', true], ['entities', 'list', fal
45
45
  './lib/dev-supervisor-manifest.js': 'export const canUseLightweightDevSupervisor=()=>false; export const loadDevSupervisorManifest=()=>null; export const registerDevSupervisorManifest=()=>{}',
46
46
  '@open-mercato/shared/lib/telemetry/runtime': 'export const isTelemetryBackendEnabled = () => false',
47
47
  '@open-mercato/shared/lib/bootstrap/next-subpath-resolve-hook': 'export const installNextSubpathResolveHook = () => {}',
48
- './lib/cli-bootstrap-mode.js': "export const resolveCliBootstrapMode = () => 'full'",
48
+ './lib/cli-bootstrap-mode.js': "export const resolveCliBootstrapMode = () => 'full'; export const requiresDatabaseRuntimeForMigration = () => false",
49
49
  './lib/flush-before-exit.js': 'export const flushBeforeExit = async () => {}',
50
50
  './lib/resolver.js': 'export const createResolver = () => ({getAppDir: () => "/fixture-app"})',
51
51
  './lib/load-env.js': warningImport + 'export const loadAppEnv = async () => { process.env.OM_ROTATION_PROGRESS="json"; writeKmsWarning(["environment custody warning"]) }',
@@ -2,6 +2,7 @@ import { EventEmitter } from 'node:events'
2
2
  import type { ChildProcess } from 'node:child_process'
3
3
  import {
4
4
  startLazySchedulerSupervisor,
5
+ probeEnabledSchedules,
5
6
  type LazySchedulerSupervisorProbeFn,
6
7
  type LazySchedulerSupervisorSpawnFn,
7
8
  } from '../scheduler-supervisor'
@@ -197,3 +198,109 @@ describe('startLazySchedulerSupervisor', () => {
197
198
  await handle.close()
198
199
  })
199
200
  })
201
+
202
+
203
+ const probeConnect = jest.fn()
204
+ const probeQuery = jest.fn()
205
+ const probeEnd = jest.fn()
206
+ const probeReady = jest.fn()
207
+ const probeDispose = jest.fn()
208
+ const probeRelease = jest.fn()
209
+ const configureProbePool = jest.fn()
210
+ const probeFreshContext = jest.fn((_context: unknown, callback: () => unknown) => callback())
211
+ const probeEnabled = jest.fn(() => false)
212
+ const probeUrl = jest.fn((_purpose: string, fallback: string) => fallback)
213
+
214
+ jest.mock('pg', () => ({ Client: jest.fn(() => ({ connect: probeConnect, query: probeQuery, end: probeEnd })) }))
215
+ jest.mock('@open-mercato/shared/lib/db/runtime', () => ({
216
+ isDatabaseRuntimeEnabled: () => probeEnabled(),
217
+ resolveDatabaseConnectionUrl: (purpose: string, fallback: string) => probeUrl(purpose, fallback),
218
+ runWithFreshDatabaseExecutionContext: (context: unknown, callback: () => unknown) => probeFreshContext(context, callback),
219
+ configureDatabasePool: (pool: unknown, descriptor: unknown) => configureProbePool(pool, descriptor),
220
+ }))
221
+
222
+ describe('probeEnabledSchedules database boundary', () => {
223
+ beforeEach(() => {
224
+ jest.clearAllMocks()
225
+ probeEnabled.mockReturnValue(true)
226
+ probeUrl.mockReturnValue('postgresql://maintenance@localhost/disposable')
227
+ probeConnect.mockResolvedValue(undefined)
228
+ probeEnd.mockResolvedValue(undefined)
229
+ probeReady.mockResolvedValue(undefined)
230
+ probeQuery.mockResolvedValue({ rows: [{ enabled_schedules: '3', due_schedules: 1 }] })
231
+ configureProbePool.mockImplementation((pool: { connect: () => Promise<unknown> }) => {
232
+ pool.connect = async () => ({ query: probeQuery, release: probeRelease })
233
+ return { ready: probeReady, dispose: probeDispose }
234
+ })
235
+ })
236
+
237
+ it('selects maintenance URL and awaits the supported pool verifier before querying', async () => {
238
+ const result = await probeEnabledSchedules({ DATABASE_URL: 'postgresql://runtime@localhost/disposable' })
239
+ expect(result).toEqual({ enabledSchedules: 3, dueSchedules: 1, error: false })
240
+ expect(probeUrl).toHaveBeenCalledWith('maintenance', 'postgresql://runtime@localhost/disposable')
241
+ expect(require('pg').Client).toHaveBeenCalledWith(expect.objectContaining({ connectionString: 'postgresql://maintenance@localhost/disposable' }))
242
+ expect(probeFreshContext).toHaveBeenCalledWith({ kind: 'maintenance', tenantId: null, source: 'scheduler', operation: 'scheduler.lazy-probe' }, expect.any(Function))
243
+ expect(configureProbePool).toHaveBeenCalledWith(expect.any(Object), { id: 'scheduler-lazy-probe', purpose: 'maintenance', tables: ['scheduled_jobs'] })
244
+ expect(probeReady.mock.invocationCallOrder[0]).toBeLessThan(probeQuery.mock.invocationCallOrder[0])
245
+ expect(probeRelease).toHaveBeenCalledTimes(1)
246
+ expect(probeEnd).toHaveBeenCalledTimes(1)
247
+ expect(probeDispose).toHaveBeenCalledTimes(1)
248
+ })
249
+
250
+ it('refuses discovery when maintenance role verification fails and cleans up', async () => {
251
+ probeReady.mockRejectedValue(new Error('unsafe maintenance role'))
252
+ const result = await probeEnabledSchedules({ DATABASE_URL: 'runtime' })
253
+ expect(result).toMatchObject({ error: true, errorMessage: 'unsafe maintenance role' })
254
+ expect(probeQuery).not.toHaveBeenCalled()
255
+ expect(probeRelease).not.toHaveBeenCalled()
256
+ expect(probeEnd).toHaveBeenCalledTimes(1)
257
+ expect(probeDispose).toHaveBeenCalledTimes(1)
258
+ })
259
+
260
+ it('allocates and disposes a separate probe lifecycle for every occurrence', async () => {
261
+ await probeEnabledSchedules({ DATABASE_URL: 'runtime' })
262
+ await probeEnabledSchedules({ DATABASE_URL: 'runtime' })
263
+ expect(configureProbePool).toHaveBeenCalledTimes(2)
264
+ expect(configureProbePool.mock.calls[0][0]).not.toBe(configureProbePool.mock.calls[1][0])
265
+ expect(probeFreshContext).toHaveBeenCalledTimes(2)
266
+ expect(probeDispose).toHaveBeenCalledTimes(2)
267
+ })
268
+
269
+ it.each([false, true])('drains the actual guarded probe pool after query failure=%s', async (queryFails) => {
270
+ const { installTenantPoolBoundary } = jest.requireActual<typeof import('../../../../enterprise/src/lib/rls/runtime/pool')>('../../../../enterprise/src/lib/rls/runtime/pool')
271
+ const { runWithFreshTenantBoundary } = jest.requireActual<typeof import('../../../../enterprise/src/lib/rls/runtime/scope')>('../../../../enterprise/src/lib/rls/runtime/scope')
272
+ probeFreshContext.mockImplementation((context, callback) => runWithFreshTenantBoundary(context as import('@open-mercato/shared/lib/db/runtime').DatabaseExecutionContext, callback))
273
+ configureProbePool.mockImplementation((pool: import('../../../../enterprise/src/lib/rls/runtime/pool').BoundaryPool) => {
274
+ expect(pool.ended).toBe(false)
275
+ const lifecycle = installTenantPoolBoundary(pool, { configurationKey: 'scheduler-probe-regression' })
276
+ return { ready: lifecycle.ready, dispose: () => {
277
+ expect(probeEnd).toHaveBeenCalledTimes(1)
278
+ expect(pool.ended).toBe(true)
279
+ lifecycle.dispose()
280
+ probeDispose()
281
+ } }
282
+ })
283
+ if (queryFails) probeQuery.mockImplementation(async (sql: string) => {
284
+ if (sql.includes('scheduled_jobs')) throw new Error('schedule query failed')
285
+ return { rows: [] }
286
+ })
287
+ try {
288
+ const result = await probeEnabledSchedules({ DATABASE_URL: 'runtime' })
289
+ expect(result).toEqual(queryFails
290
+ ? { enabledSchedules: 0, dueSchedules: 0, error: true, errorMessage: 'schedule query failed' }
291
+ : { enabledSchedules: 3, dueSchedules: 1, error: false })
292
+ expect(probeDispose).toHaveBeenCalledTimes(1)
293
+ } finally {
294
+ probeFreshContext.mockImplementation((_context, callback) => callback())
295
+ }
296
+ })
297
+
298
+ it('keeps the direct runtime URL and existing missing-table behavior when disabled', async () => {
299
+ probeEnabled.mockReturnValue(false)
300
+ probeQuery.mockRejectedValue(Object.assign(new Error('missing'), { code: '42P01' }))
301
+ await expect(probeEnabledSchedules({ DATABASE_URL: 'runtime' })).resolves.toEqual({ enabledSchedules: 0, dueSchedules: 0, error: false })
302
+ expect(require('pg').Client).toHaveBeenCalledWith(expect.objectContaining({ connectionString: 'runtime' }))
303
+ expect(configureProbePool).not.toHaveBeenCalled()
304
+ expect(probeFreshContext).not.toHaveBeenCalled()
305
+ })
306
+ })