@open-mercato/cli 0.11.1-develop.8784.1.e9d95a72f5 → 0.11.1-develop.8843.1.b02f9b125d

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 (210) hide show
  1. package/.turbo/turbo-build.log +8 -2
  2. package/AGENTS.md +2 -0
  3. package/dist/agentic/guides/architecture.md +1 -0
  4. package/dist/agentic/guides/module-facts.json +2453 -1146
  5. package/dist/agentic/guides/module-facts.v2.json +2453 -1146
  6. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  7. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  8. package/dist/agentic/guides/modules/ai_assistant/owned-contract-module-metadata.md +1 -1
  9. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  10. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  11. package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
  12. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  13. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  14. package/dist/agentic/guides/modules/auth/index.md +1 -1
  15. package/dist/agentic/guides/modules/auth/owned-contract-module-metadata.md +1 -1
  16. package/dist/agentic/guides/modules/availability/index.md +1 -1
  17. package/dist/agentic/guides/modules/backups/index.md +1 -1
  18. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  19. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  20. package/dist/agentic/guides/modules/cart/index.md +1 -1
  21. package/dist/agentic/guides/modules/cart/owned-contract-module-metadata.md +1 -1
  22. package/dist/agentic/guides/modules/catalog/di-registrations-rich.md +11 -8
  23. package/dist/agentic/guides/modules/catalog/di-service-tokens.md +5 -5
  24. package/dist/agentic/guides/modules/catalog/exact-override-targets.md +11 -8
  25. package/dist/agentic/guides/modules/catalog/index.md +2 -2
  26. package/dist/agentic/guides/modules/catalog/owned-contract-module-metadata.md +1 -1
  27. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  28. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  29. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  30. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  31. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  32. package/dist/agentic/guides/modules/channel_gmail/owned-contract-module-metadata.md +1 -1
  33. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  34. package/dist/agentic/guides/modules/channel_imap/owned-contract-module-metadata.md +1 -1
  35. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  36. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  37. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  38. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  39. package/dist/agentic/guides/modules/communication_channels/exact-override-targets.md +2 -2
  40. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  41. package/dist/agentic/guides/modules/communication_channels/owned-contract-module-metadata.md +1 -1
  42. package/dist/agentic/guides/modules/communication_channels/workers.md +2 -2
  43. package/dist/agentic/guides/modules/configs/acl-features.md +2 -1
  44. package/dist/agentic/guides/modules/configs/backend-pages.md +1 -0
  45. package/dist/agentic/guides/modules/configs/entities.md +0 -1
  46. package/dist/agentic/guides/modules/configs/exact-override-targets.md +2 -0
  47. package/dist/agentic/guides/modules/configs/host-extension-points.md +10 -0
  48. package/dist/agentic/guides/modules/configs/index.md +5 -3
  49. package/dist/agentic/guides/modules/configs/owned-contract-module-metadata.md +1 -1
  50. package/dist/agentic/guides/modules/configs/setup.md +1 -1
  51. package/dist/agentic/guides/modules/configs/umes-diagnostics.md +9 -0
  52. package/dist/agentic/guides/modules/configs/umes-hosts.md +9 -1
  53. package/dist/agentic/guides/modules/content/index.md +1 -1
  54. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  55. package/dist/agentic/guides/modules/customer_accounts/active-extension-bindings.md +1 -1
  56. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  57. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  58. package/dist/agentic/guides/modules/customers/acl-features.md +2 -1
  59. package/dist/agentic/guides/modules/customers/active-extension-bindings.md +2 -0
  60. package/dist/agentic/guides/modules/customers/contribution-resolutions.md +2 -0
  61. package/dist/agentic/guides/modules/customers/di-registrations-rich.md +8 -5
  62. package/dist/agentic/guides/modules/customers/domain-commands.md +1 -1
  63. package/dist/agentic/guides/modules/customers/exact-override-targets.md +11 -5
  64. package/dist/agentic/guides/modules/customers/index.md +5 -5
  65. package/dist/agentic/guides/modules/customers/owned-contract-module-metadata.md +1 -1
  66. package/dist/agentic/guides/modules/customers/umes-contributions.md +2 -0
  67. package/dist/agentic/guides/modules/dashboards/active-extension-bindings.md +0 -10
  68. package/dist/agentic/guides/modules/dashboards/contribution-resolutions.md +0 -10
  69. package/dist/agentic/guides/modules/dashboards/exact-override-targets.md +0 -10
  70. package/dist/agentic/guides/modules/dashboards/index.md +5 -5
  71. package/dist/agentic/guides/modules/dashboards/umes-contributions.md +0 -10
  72. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  73. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  74. package/dist/agentic/guides/modules/devices/index.md +1 -1
  75. package/dist/agentic/guides/modules/devices/owned-contract-module-metadata.md +1 -1
  76. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  77. package/dist/agentic/guides/modules/directory/index.md +1 -1
  78. package/dist/agentic/guides/modules/documents/index.md +1 -1
  79. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  80. package/dist/agentic/guides/modules/ecommerce/owned-contract-module-metadata.md +1 -1
  81. package/dist/agentic/guides/modules/entities/index.md +1 -1
  82. package/dist/agentic/guides/modules/entities/owned-contract-module-metadata.md +1 -1
  83. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  84. package/dist/agentic/guides/modules/events/index.md +1 -1
  85. package/dist/agentic/guides/modules/events/owned-contract-module-metadata.md +1 -1
  86. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  87. package/dist/agentic/guides/modules/forms/index.md +1 -1
  88. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  89. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  90. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  91. package/dist/agentic/guides/modules/generators/index.md +1 -1
  92. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  93. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  94. package/dist/agentic/guides/modules/integrations/owned-contract-module-metadata.md +1 -1
  95. package/dist/agentic/guides/modules/ledger/index.md +1 -1
  96. package/dist/agentic/guides/modules/maintenance/contribution-resolutions.md +11 -0
  97. package/dist/agentic/guides/modules/maintenance/events.md +14 -0
  98. package/dist/agentic/guides/modules/maintenance/exact-override-targets.md +11 -0
  99. package/dist/agentic/guides/modules/maintenance/index.md +17 -0
  100. package/dist/agentic/guides/modules/maintenance/owned-contract-module-metadata.md +11 -0
  101. package/dist/agentic/guides/modules/maintenance/umes-contributions.md +11 -0
  102. package/dist/agentic/guides/modules/maintenance/umes-hosts.md +14 -0
  103. package/dist/agentic/guides/modules/messages/index.md +1 -1
  104. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  105. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  106. package/dist/agentic/guides/modules/payment_gateways/exact-override-targets.md +3 -3
  107. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  108. package/dist/agentic/guides/modules/payment_gateways/setup.md +1 -1
  109. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  110. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  111. package/dist/agentic/guides/modules/phone_calls/owned-contract-module-metadata.md +1 -1
  112. package/dist/agentic/guides/modules/planner/index.md +1 -1
  113. package/dist/agentic/guides/modules/portal/index.md +1 -1
  114. package/dist/agentic/guides/modules/progress/index.md +1 -1
  115. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  116. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  117. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  118. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  119. package/dist/agentic/guides/modules/resources/index.md +1 -1
  120. package/dist/agentic/guides/modules/sales/active-extension-bindings.md +8 -0
  121. package/dist/agentic/guides/modules/sales/contribution-resolutions.md +8 -0
  122. package/dist/agentic/guides/modules/sales/di-registrations-rich.md +31 -30
  123. package/dist/agentic/guides/modules/sales/di-service-tokens.md +5 -5
  124. package/dist/agentic/guides/modules/sales/exact-override-targets.md +39 -30
  125. package/dist/agentic/guides/modules/sales/index.md +5 -5
  126. package/dist/agentic/guides/modules/sales/owned-contract-module-metadata.md +1 -1
  127. package/dist/agentic/guides/modules/sales/umes-contributions.md +8 -0
  128. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  129. package/dist/agentic/guides/modules/search/index.md +1 -1
  130. package/dist/agentic/guides/modules/search/owned-contract-module-metadata.md +1 -1
  131. package/dist/agentic/guides/modules/security/index.md +1 -1
  132. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  133. package/dist/agentic/guides/modules/shipping_carriers/active-extension-bindings.md +1 -1
  134. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  135. package/dist/agentic/guides/modules/sso/index.md +1 -1
  136. package/dist/agentic/guides/modules/staff/active-extension-bindings.md +2 -1
  137. package/dist/agentic/guides/modules/staff/contribution-resolutions.md +1 -0
  138. package/dist/agentic/guides/modules/staff/exact-override-targets.md +1 -0
  139. package/dist/agentic/guides/modules/staff/index.md +8 -8
  140. package/dist/agentic/guides/modules/staff/umes-contributions.md +1 -0
  141. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  142. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  143. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  144. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  145. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  146. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  147. package/dist/agentic/guides/modules/translations/index.md +1 -1
  148. package/dist/agentic/guides/modules/upgrade_actions/cli-commands.md +11 -0
  149. package/dist/agentic/guides/modules/upgrade_actions/contribution-resolutions.md +12 -0
  150. package/dist/agentic/guides/modules/upgrade_actions/entities.md +11 -0
  151. package/dist/agentic/guides/modules/upgrade_actions/exact-override-targets.md +12 -0
  152. package/dist/agentic/guides/modules/upgrade_actions/index.md +18 -0
  153. package/dist/agentic/guides/modules/upgrade_actions/owned-contract-module-metadata.md +11 -0
  154. package/dist/agentic/guides/modules/upgrade_actions/umes-contributions.md +12 -0
  155. package/dist/agentic/guides/modules/upgrade_actions/umes-hosts.md +11 -0
  156. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  157. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  158. package/dist/agentic/guides/modules/wms/index.md +1 -1
  159. package/dist/agentic/guides/modules/workflows/domain-commands.md +3 -0
  160. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  161. package/dist/agentic/guides/production-deployment.md +6 -0
  162. package/dist/agentic/guides/reference-module-facts.json +1 -1
  163. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +17 -9
  164. package/dist/agentic/guides/upstream/manifest.json +2 -2
  165. package/dist/agentic/shared/AGENTS.md.template +1 -1
  166. package/dist/agentic/shared/ai/harness/cases.json +7 -7
  167. package/dist/lib/generators/extensions/dashboard-widgets.js +46 -4
  168. package/dist/lib/generators/extensions/dashboard-widgets.js.map +2 -2
  169. package/dist/lib/generators/extensions/workflows.js +25 -2
  170. package/dist/lib/generators/extensions/workflows.js.map +2 -2
  171. package/dist/lib/generators/module-facts.js +2 -0
  172. package/dist/lib/generators/module-facts.js.map +2 -2
  173. package/dist/lib/generators/module-registry.js +35 -6
  174. package/dist/lib/generators/module-registry.js.map +2 -2
  175. package/dist/lib/module-coupling/analyze.js +391 -0
  176. package/dist/lib/module-coupling/analyze.js.map +7 -0
  177. package/dist/lib/module-diagnostics.js +160 -0
  178. package/dist/lib/module-diagnostics.js.map +7 -0
  179. package/dist/lib/module-index.js +103 -0
  180. package/dist/lib/module-index.js.map +7 -0
  181. package/dist/lib/testing/ephemeral-database-guard.js +89 -0
  182. package/dist/lib/testing/ephemeral-database-guard.js.map +7 -0
  183. package/dist/lib/testing/integration-discovery.js +20 -15
  184. package/dist/lib/testing/integration-discovery.js.map +3 -3
  185. package/dist/mercato.js +45 -5
  186. package/dist/mercato.js.map +2 -2
  187. package/package.json +7 -7
  188. package/src/__tests__/init-ephemeral-database.test.ts +112 -0
  189. package/src/__tests__/mercato.test.ts +15 -0
  190. package/src/__tests__/rotation-json-output.test.ts +13 -0
  191. package/src/lib/__tests__/module-diagnostics.test.ts +207 -0
  192. package/src/lib/__tests__/modules-config.test.ts +1 -0
  193. package/src/lib/generators/__tests__/module-facts.customers.fixture.test.ts +2 -1
  194. package/src/lib/generators/__tests__/module-facts.owned-contracts.test.ts +2 -2
  195. package/src/lib/generators/__tests__/module-registry-requires-enforcement.test.ts +18 -0
  196. package/src/lib/generators/__tests__/output-snapshots.test.ts +19 -0
  197. package/src/lib/generators/__tests__/registry-variant-parity.test.ts +95 -19
  198. package/src/lib/generators/__tests__/structural-contracts.test.ts +18 -0
  199. package/src/lib/generators/extensions/dashboard-widgets.ts +49 -3
  200. package/src/lib/generators/extensions/workflows.ts +26 -2
  201. package/src/lib/generators/module-facts.ts +2 -0
  202. package/src/lib/generators/module-registry.ts +55 -7
  203. package/src/lib/module-coupling/analyze.ts +464 -0
  204. package/src/lib/module-diagnostics.ts +182 -0
  205. package/src/lib/module-index.ts +133 -0
  206. package/src/lib/testing/__tests__/ephemeral-database-guard.test.ts +88 -0
  207. package/src/lib/testing/__tests__/integration-discovery.test.ts +26 -2
  208. package/src/lib/testing/ephemeral-database-guard.ts +105 -0
  209. package/src/lib/testing/integration-discovery.ts +19 -11
  210. package/src/mercato.ts +47 -5
@@ -0,0 +1,133 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { resolveModuleIdentity, type ModuleIdentity } from '@open-mercato/shared/modules/module-locators'
4
+ import { extractModuleRequiresFromSource } from './generators/module-registry'
5
+ import { MODULE_CODE_EXTENSIONS } from './generators/scanner'
6
+ import { discoverModulesInPackage } from './module-package'
7
+ import { createResolver, type ModuleEntry, type PackageResolver } from './resolver'
8
+
9
+ export type IndexedModule = ModuleIdentity & {
10
+ packageName: string
11
+ version: string | null
12
+ roots: string[]
13
+ enabled: boolean
14
+ requires: string[]
15
+ optionalRequires: string[]
16
+ notAnalyzed?: string
17
+ }
18
+
19
+ function existingDirectories(paths: string[]): string[] {
20
+ return [...new Set(paths)].filter((candidate) => fs.existsSync(candidate) && fs.statSync(candidate).isDirectory())
21
+ }
22
+
23
+ function moduleIndexFile(roots: string[]): string | undefined {
24
+ return roots.flatMap((root) => MODULE_CODE_EXTENSIONS.map((extension) => path.join(root, `index${extension}`)))
25
+ .find((candidate) => fs.existsSync(candidate))
26
+ }
27
+
28
+ function readModule(resolver: PackageResolver, entry: ModuleEntry, enabled: boolean): IndexedModule {
29
+ const packageName = entry.from ?? '@open-mercato/core'
30
+ const packageRoot = resolver.getPackageRoot(packageName)
31
+ const { appBase, pkgBase } = resolver.getModulePaths(entry)
32
+ const roots = existingDirectories(packageName === '@app' ? [appBase] : [appBase, pkgBase])
33
+ const indexFile = moduleIndexFile(roots)
34
+ const requires = indexFile ? extractModuleRequiresFromSource(indexFile) : null
35
+ const optionalRequires = indexFile ? extractModuleRequiresFromSource(indexFile, 'optionalRequires') : null
36
+ const notAnalyzed = !indexFile
37
+ ? 'module index source is unavailable'
38
+ : requires?.status === 'unresolvable'
39
+ ? requires.reason
40
+ : optionalRequires?.status === 'unresolvable'
41
+ ? optionalRequires.reason
42
+ : undefined
43
+ let version: string | null = null
44
+ try {
45
+ const manifest: { version?: unknown } = JSON.parse(fs.readFileSync(path.join(
46
+ packageName === '@app' ? resolver.getAppDir() : packageRoot, 'package.json',
47
+ ), 'utf8'))
48
+ if (typeof manifest.version === 'string') version = manifest.version
49
+ } catch {
50
+ // Module diagnostics remain available even if package version metadata is absent.
51
+ }
52
+ return {
53
+ id: entry.id,
54
+ packageName,
55
+ version,
56
+ roots,
57
+ enabled,
58
+ locators: [...new Set([entry.locator, entry.packageName, packageName].filter((locator): locator is string => !!locator && locator !== '@app'))],
59
+ requires: requires?.status === 'declared' ? requires.requires : [],
60
+ optionalRequires: optionalRequires?.status === 'declared' ? optionalRequires.requires : [],
61
+ ...(notAnalyzed ? { notAnalyzed } : {}),
62
+ }
63
+ }
64
+
65
+ export function buildModuleIndex(resolver: PackageResolver = createResolver(), includeInactive = true): IndexedModule[] {
66
+ const enabled = resolver.loadEnabledModules()
67
+ const result = enabled.map((entry) => readModule(resolver, entry, true))
68
+ if (!includeInactive) return result
69
+
70
+ const keys = new Set(result.map((entry) => `${entry.packageName}:${entry.id}`))
71
+ const appModules = path.join(resolver.getAppDir(), 'src', 'modules')
72
+ if (fs.existsSync(appModules)) {
73
+ const enabledIds = new Set(enabled.map((entry) => entry.id))
74
+ for (const entry of fs.readdirSync(appModules, { withFileTypes: true })) {
75
+ if (!entry.isDirectory() || entry.name.startsWith('.') || enabledIds.has(entry.name)) continue
76
+ result.push(readModule(resolver, { id: entry.name, from: '@app' }, false))
77
+ }
78
+ }
79
+
80
+ const packages = new Map(resolver.discoverPackages().map((pkg) => [pkg.name, pkg.path]))
81
+ const appManifest = path.join(resolver.getAppDir(), 'package.json')
82
+ try {
83
+ const manifest: { dependencies?: Record<string, string>; optionalDependencies?: Record<string, string> } =
84
+ JSON.parse(fs.readFileSync(appManifest, 'utf8'))
85
+ for (const packageName of Object.keys({ ...manifest.dependencies, ...manifest.optionalDependencies })) {
86
+ if (!packages.has(packageName)) packages.set(packageName, resolver.getPackageRoot(packageName))
87
+ }
88
+ } catch {
89
+ // Missing app package metadata does not prevent inspecting known installed packages.
90
+ }
91
+
92
+ for (const [packageName, packageRoot] of packages) {
93
+ for (const entry of discoverModulesInPackage(packageRoot)) {
94
+ if (keys.has(`${packageName}:${entry.moduleId}`)) continue
95
+ result.push(readModule(resolver, { id: entry.moduleId, from: packageName }, false))
96
+ }
97
+ }
98
+ return result.sort((left, right) => left.id.localeCompare(right.id) || left.packageName.localeCompare(right.packageName))
99
+ }
100
+
101
+ export function resolveIndexedModule(requirement: string, modules: IndexedModule[]): IndexedModule | undefined {
102
+ // The enabled instance takes precedence over any other installed provider for the same id.
103
+ const activeFirst = [...modules.filter((entry) => entry.enabled), ...modules.filter((entry) => !entry.enabled)]
104
+ return resolveModuleIdentity(requirement, activeFirst)
105
+ }
106
+
107
+ export function missingModuleRequirements(
108
+ entry: IndexedModule,
109
+ modules: IndexedModule[],
110
+ ): Array<{ requirement: string; path: string[] }> {
111
+ const visited = new Set([entry.id])
112
+ const missing = new Map<string, string[]>()
113
+
114
+ function visit(source: IndexedModule, trail: string[]): void {
115
+ for (const requirement of source.requires) {
116
+ const target = resolveIndexedModule(requirement, modules)
117
+ const nextTrail = [...trail, target?.id ?? requirement]
118
+ if ((!target || !target.enabled) && !missing.has(requirement)) missing.set(requirement, nextTrail)
119
+ if (!target || visited.has(target.id)) continue
120
+ visited.add(target.id)
121
+ visit(target, nextTrail)
122
+ }
123
+ }
124
+
125
+ visit(entry, [entry.id])
126
+ return [...missing].map(([requirement, path]) => ({ requirement, path }))
127
+ }
128
+
129
+ export function inactiveModuleDependencies(modules: IndexedModule[]): Array<{ source: IndexedModule; target: string }> {
130
+ return modules.filter((module) => module.enabled).flatMap((source) => source.optionalRequires
131
+ .filter((target) => !resolveIndexedModule(target, modules)?.enabled)
132
+ .map((target) => ({ source, target })))
133
+ }
@@ -0,0 +1,88 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { chmodSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import {
6
+ assertEphemeralDatabaseConnection,
7
+ assertEphemeralDatabaseOwnership,
8
+ readEphemeralDatabaseGuard,
9
+ type EphemeralDatabaseGuard,
10
+ } from '../ephemeral-database-guard'
11
+
12
+ describe('ephemeral database initialization ownership', () => {
13
+ const databaseUrl = 'postgresql://owned:private-password@127.0.0.1:6543/owned_database'
14
+ const guard: EphemeralDatabaseGuard = {
15
+ version: 1,
16
+ databaseName: 'owned_database',
17
+ connectionDigest: createHash('sha256').update('postgresql://owned@127.0.0.1:6543/owned_database').digest('hex'),
18
+ ownershipMarker: 'open-mercato-ephemeral:38ee43df-19e4-444e-b5c5-8e56b55c9d0c',
19
+ }
20
+ let directory: string
21
+ let proofPath: string
22
+
23
+ beforeEach(() => {
24
+ directory = mkdtempSync(path.join(os.tmpdir(), 'ephemeral-db-guard-'))
25
+ proofPath = path.join(directory, 'guard.json')
26
+ writeFileSync(proofPath, JSON.stringify(guard), { mode: 0o600 })
27
+ })
28
+
29
+ afterEach(() => {
30
+ rmSync(directory, { recursive: true, force: true })
31
+ })
32
+
33
+ it('keeps ordinary init compatible and reads the private argument proof', () => {
34
+ expect(readEphemeralDatabaseGuard(['--reinstall'])).toBeNull()
35
+ expect(readEphemeralDatabaseGuard([`--ephemeral-database-guard=${proofPath}`])).toEqual(guard)
36
+ })
37
+
38
+ it('rejects missing, duplicate, malformed and public proofs', () => {
39
+ expect(() => readEphemeralDatabaseGuard(['--ephemeral-database-guard'])).toThrow('ownership proof file')
40
+ expect(() => readEphemeralDatabaseGuard([`--ephemeral-database-guard=${proofPath}`, `--ephemeral-database-guard=${proofPath}`])).toThrow('ownership proof file')
41
+ writeFileSync(proofPath, JSON.stringify({ ...guard, ownershipMarker: '' }))
42
+ expect(() => readEphemeralDatabaseGuard([`--ephemeral-database-guard=${proofPath}`])).toThrow('proof is invalid')
43
+ if (process.platform !== 'win32') {
44
+ chmodSync(proofPath, 0o644)
45
+ expect(() => readEphemeralDatabaseGuard([`--ephemeral-database-guard=${proofPath}`])).toThrow('private regular file')
46
+ }
47
+ })
48
+
49
+ it('does not follow a replacement symlink', () => {
50
+ const alias = path.join(directory, 'alias.json')
51
+ symlinkSync(proofPath, alias)
52
+ expect(() => readEphemeralDatabaseGuard([`--ephemeral-database-guard=${alias}`])).toThrow('private regular file')
53
+ })
54
+
55
+ it('rejects stripped or dotenv fallback destinations without exposing credentials', () => {
56
+ expect(() => assertEphemeralDatabaseConnection(guard, undefined)).toThrow('explicit database connection')
57
+ expect(() => assertEphemeralDatabaseConnection(guard, 'postgresql://fallback:other-secret@127.0.0.1:6544/control_database')).toThrow('not the owned disposable target')
58
+ expect(() => assertEphemeralDatabaseConnection(guard, databaseUrl)).not.toThrow()
59
+ try {
60
+ assertEphemeralDatabaseConnection(guard, databaseUrl.replace('owned_database', 'wrong_database'))
61
+ } catch (error) {
62
+ expect(String(error)).not.toContain('private-password')
63
+ expect(String(error)).not.toContain('wrong_database')
64
+ }
65
+ })
66
+
67
+ it('binds the owned target identity rather than the credential', () => {
68
+ expect(() => assertEphemeralDatabaseConnection(guard, 'postgresql://owned:rotated-secret@127.0.0.1:6543/owned_database')).not.toThrow()
69
+ expect(() => assertEphemeralDatabaseConnection(guard, 'postgresql://other_role:private-password@127.0.0.1:6543/owned_database')).toThrow('not the owned disposable target')
70
+ })
71
+
72
+ it('reads the connected database identity and ownership marker before accepting it', async () => {
73
+ const query = jest.fn().mockResolvedValue({ rows: [{ database_name: guard.databaseName, ownership_marker: guard.ownershipMarker }] })
74
+ await expect(assertEphemeralDatabaseOwnership(guard, { query })).resolves.toBeUndefined()
75
+ expect(query).toHaveBeenCalledTimes(1)
76
+ expect(query.mock.calls[0][0]).toMatch(/^SELECT current_database\(\)/)
77
+ })
78
+
79
+ it.each([
80
+ { database_name: 'control_database', ownership_marker: guard.ownershipMarker },
81
+ { database_name: guard.databaseName, ownership_marker: null },
82
+ { database_name: guard.databaseName, ownership_marker: 'another-owner' },
83
+ ])('refuses a connected database without matching positive ownership: %j', async (identity) => {
84
+ const query = jest.fn().mockResolvedValue({ rows: [identity] })
85
+ await expect(assertEphemeralDatabaseOwnership(guard, { query })).rejects.toThrow('ownership could not be verified')
86
+ expect(query.mock.calls.every(([statement]) => String(statement).startsWith('SELECT'))).toBe(true)
87
+ })
88
+ })
@@ -1,7 +1,7 @@
1
1
  import os from 'node:os'
2
2
  import path from 'node:path'
3
- import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
4
- import { discoverIntegrationSpecFiles, isAppOwnedIntegrationSpecPath } from '../integration-discovery'
3
+ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
4
+ import { discoverIntegrationSpecFiles, isAppOwnedIntegrationSpecPath, resolveModuleDependenciesForSpec } from '../integration-discovery'
5
5
 
6
6
  async function writeTestFile(projectRoot: string, relativePath: string, content = 'export {}\n'): Promise<void> {
7
7
  const absolutePath = path.join(projectRoot, relativePath)
@@ -19,6 +19,7 @@ describe('integration discovery', () => {
19
19
  'OM_TEST_APP_ROOT',
20
20
  'OM_INTEGRATION_APP_ONLY',
21
21
  'OM_INTEGRATION_SKIP_METADATA_FILTERS',
22
+ 'OM_INTEGRATION_DISCOVERY_SELECTION_REPORT',
22
23
  ] as const
23
24
  const previousTestEnvValues = new Map<string, string | undefined>()
24
25
 
@@ -88,6 +89,16 @@ describe('integration discovery', () => {
88
89
  ])
89
90
  })
90
91
 
92
+ it('keeps optional module probes runnable when their peer is disabled', async () => {
93
+ const spec = 'apps/mercato/src/modules/sales/__integration__/TC-SALES-003.spec.ts'
94
+ await writeTestFile(tempRoot, spec, "export const integrationMeta = { optionalModules: ['currencies'] }")
95
+
96
+ expect(discoverIntegrationSpecFiles(tempRoot, path.join(tempRoot, '.ai', 'qa', 'tests'))).toEqual([
97
+ expect.objectContaining({ path: spec, requiredModules: [] }),
98
+ ])
99
+ expect(resolveModuleDependenciesForSpec(tempRoot, spec, { includeOptional: true })).toEqual(['currencies'])
100
+ })
101
+
91
102
  it('loads enterprise integration tests only when enterprise modules are enabled', async () => {
92
103
  await writeTestFile(tempRoot, 'packages/core/src/modules/sales/.gitkeep')
93
104
  await writeTestFile(
@@ -162,6 +173,19 @@ describe('integration discovery', () => {
162
173
  ])
163
174
  })
164
175
 
176
+ it('writes the normal filtered test selection for preset verification', async () => {
177
+ const selected = 'packages/core/src/modules/catalog/__integration__/TC-CAT-001.spec.ts'
178
+ await writeTestFile(tempRoot, selected)
179
+ await writeTestFile(tempRoot, 'packages/core/src/modules/catalog/__integration__/TC-CAT-002.spec.ts',
180
+ "export const meta = { dependsOnModules: ['missing'] }")
181
+ const report = path.join(tempRoot, 'selection.json')
182
+ process.env.OM_INTEGRATION_DISCOVERY_SELECTION_REPORT = report
183
+
184
+ discoverIntegrationSpecFiles(tempRoot, path.join(tempRoot, '.ai', 'qa', 'tests'))
185
+
186
+ expect(JSON.parse(await readFile(report, 'utf8'))).toEqual({ projectRoot: tempRoot, paths: [selected] })
187
+ })
188
+
165
189
  it('uses OM_TEST_APP_ROOT and its actual modules.ts for dependency filtering', async () => {
166
190
  const standaloneRoot = path.join(tempRoot, 'standalone-app')
167
191
  await writeTestFile(
@@ -0,0 +1,105 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { lstatSync, readFileSync } from 'node:fs'
3
+ import { mkdir, writeFile } from 'node:fs/promises'
4
+ import path from 'node:path'
5
+
6
+ type DatabaseIdentity = { database_name: unknown; ownership_marker: unknown }
7
+
8
+ export type EphemeralDatabaseConnection = {
9
+ query: (statement: string) => Promise<{ rows: DatabaseIdentity[] }>
10
+ }
11
+
12
+ export type EphemeralDatabaseGuard = {
13
+ version: 1
14
+ databaseName: string
15
+ connectionDigest: string
16
+ ownershipMarker: string
17
+ }
18
+
19
+ const identityQuery = "SELECT current_database() AS database_name, shobj_description(oid, 'pg_database') AS ownership_marker FROM pg_database WHERE datname = current_database()"
20
+
21
+ function connectionTarget(databaseUrl: string | undefined): string {
22
+ if (!databaseUrl) throw new Error('[internal] Ephemeral initialization requires an explicit database connection.')
23
+ let parsed: URL
24
+ try {
25
+ parsed = new URL(databaseUrl)
26
+ } catch {
27
+ throw new Error('[internal] Ephemeral database connection is invalid.')
28
+ }
29
+ if (!['postgres:', 'postgresql:'].includes(parsed.protocol) || !parsed.hostname || parsed.pathname.length < 2) {
30
+ throw new Error('[internal] Ephemeral database connection is invalid.')
31
+ }
32
+ const databaseName = decodeURIComponent(parsed.pathname.slice(1))
33
+ const port = parsed.port || '5432'
34
+ return `postgresql://${decodeURIComponent(parsed.username)}@${parsed.hostname.toLowerCase()}:${port}/${databaseName}`
35
+ }
36
+
37
+ function connectionDigest(databaseUrl: string | undefined): string {
38
+ return createHash('sha256').update(connectionTarget(databaseUrl)).digest('hex')
39
+ }
40
+
41
+ export function readEphemeralDatabaseGuard(args: string[]): EphemeralDatabaseGuard | null {
42
+ const prefix = '--ephemeral-database-guard='
43
+ const values = args.filter((argument) => argument === '--ephemeral-database-guard' || argument.startsWith(prefix))
44
+ if (values.length === 0) return null
45
+ if (values.length !== 1 || !values[0].startsWith(prefix) || !values[0].slice(prefix.length)) {
46
+ throw new Error('[internal] Ephemeral initialization requires one database ownership proof file.')
47
+ }
48
+ const proofPath = values[0].slice(prefix.length)
49
+ const metadata = lstatSync(proofPath)
50
+ if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 4096
51
+ || (process.platform !== 'win32' && ((metadata.mode & 0o077) !== 0 || metadata.uid !== process.getuid?.()))) {
52
+ throw new Error('[internal] Ephemeral database ownership proof must be a private regular file.')
53
+ }
54
+ const value: unknown = JSON.parse(readFileSync(proofPath, 'utf8'))
55
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
56
+ throw new Error('[internal] Ephemeral database ownership proof is invalid.')
57
+ }
58
+ const record = value as Record<string, unknown>
59
+ if (record.version !== 1 || typeof record.databaseName !== 'string' || !record.databaseName
60
+ || typeof record.connectionDigest !== 'string' || !/^[a-f0-9]{64}$/.test(record.connectionDigest)
61
+ || typeof record.ownershipMarker !== 'string' || !/^open-mercato-ephemeral:[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(record.ownershipMarker)) {
62
+ throw new Error('[internal] Ephemeral database ownership proof is invalid.')
63
+ }
64
+ return { version: 1, databaseName: record.databaseName, connectionDigest: record.connectionDigest, ownershipMarker: record.ownershipMarker }
65
+ }
66
+
67
+ export function assertEphemeralDatabaseConnection(guard: EphemeralDatabaseGuard, databaseUrl: string | undefined): void {
68
+ if (connectionDigest(databaseUrl) !== guard.connectionDigest) {
69
+ throw new Error('[internal] Refusing initialization: the effective database connection is not the owned disposable target.')
70
+ }
71
+ }
72
+
73
+ export async function assertEphemeralDatabaseOwnership(guard: EphemeralDatabaseGuard, client: EphemeralDatabaseConnection): Promise<void> {
74
+ const identity = (await client.query(identityQuery)).rows[0]
75
+ if (identity?.database_name !== guard.databaseName || identity?.ownership_marker !== guard.ownershipMarker) {
76
+ throw new Error('[internal] Refusing initialization: database ownership could not be verified.')
77
+ }
78
+ }
79
+
80
+ export async function createEphemeralDatabaseGuard(databaseUrl: string, databaseName: string, directory: string): Promise<string> {
81
+ const digest = connectionDigest(databaseUrl)
82
+ if (decodeURIComponent(new URL(databaseUrl).pathname.slice(1)) !== databaseName) {
83
+ throw new Error('[internal] Disposable database identity does not match its allocation.')
84
+ }
85
+ const { Client } = await import('pg')
86
+ const client = new Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5000 })
87
+ const ownershipMarker = `open-mercato-ephemeral:${randomUUID()}`
88
+ try {
89
+ await client.connect()
90
+ const identity = (await client.query<DatabaseIdentity>(identityQuery)).rows[0]
91
+ if (identity?.database_name !== databaseName) {
92
+ throw new Error('[internal] Connected database identity does not match its allocation.')
93
+ }
94
+ const quotedName = `"${databaseName.replace(/"/g, '""')}"`
95
+ await client.query(`COMMENT ON DATABASE ${quotedName} IS '${ownershipMarker}'`)
96
+ const guard: EphemeralDatabaseGuard = { version: 1, databaseName, connectionDigest: digest, ownershipMarker }
97
+ await assertEphemeralDatabaseOwnership(guard, client)
98
+ await mkdir(directory, { recursive: true, mode: 0o700 })
99
+ const proofPath = path.join(directory, `${randomUUID()}.json`)
100
+ await writeFile(proofPath, JSON.stringify(guard), { mode: 0o600, flag: 'wx' })
101
+ return proofPath
102
+ } finally {
103
+ await client.end()
104
+ }
105
+ }
@@ -29,6 +29,7 @@ const DISCOVERY_IGNORED_DIRS = new Set([
29
29
  ])
30
30
  const INTEGRATION_META_FILE_NAMES = ['meta.ts', 'index.ts'] as const
31
31
  const INTEGRATION_META_DEPENDENCY_KEYS = ['dependsOnModules', 'requiredModules', 'requiresModules'] as const
32
+ const INTEGRATION_META_ALL_DEPENDENCY_KEYS = [...INTEGRATION_META_DEPENDENCY_KEYS, 'optionalModules'] as const
32
33
  const INTEGRATION_META_REQUIRED_ENV_KEYS = ['requiredEnvVars', 'requiresEnvVars'] as const
33
34
  const INTEGRATION_META_REQUIRED_ANY_ENV_KEYS = ['requiredAnyEnvVars', 'requiresAnyEnvVars'] as const
34
35
  const DEFAULT_OVERLAY_ROOT = 'packages/enterprise'
@@ -315,8 +316,9 @@ function extractStringArrayFromSource(source: string, keys: readonly string[]):
315
316
  return Array.from(collected)
316
317
  }
317
318
 
318
- function extractDependencyListFromSource(source: string): string[] {
319
- return extractStringArrayFromSource(source, INTEGRATION_META_DEPENDENCY_KEYS).map(normalizeModuleId)
319
+ function extractDependencyListFromSource(source: string, includeOptional: boolean): string[] {
320
+ const keys = includeOptional ? INTEGRATION_META_ALL_DEPENDENCY_KEYS : INTEGRATION_META_DEPENDENCY_KEYS
321
+ return extractStringArrayFromSource(source, keys).map(normalizeModuleId)
320
322
  }
321
323
 
322
324
  function extractRequiredEnvVarsFromSource(source: string): string[] {
@@ -327,9 +329,9 @@ function extractRequiredAnyEnvVarsFromSource(source: string): string[] {
327
329
  return extractStringArrayFromSource(source, INTEGRATION_META_REQUIRED_ANY_ENV_KEYS)
328
330
  }
329
331
 
330
- function readDependenciesFromMetadataFile(absolutePath: string): string[] {
332
+ function readDependenciesFromMetadataFile(absolutePath: string, includeOptional: boolean): string[] {
331
333
  try {
332
- return extractDependencyListFromSource(readFileSync(absolutePath, 'utf8'))
334
+ return extractDependencyListFromSource(readFileSync(absolutePath, 'utf8'), includeOptional)
333
335
  } catch {
334
336
  return []
335
337
  }
@@ -360,7 +362,11 @@ function resolveIntegrationRootDirectory(relativeSpecPath: string): string | nul
360
362
  return segments.slice(0, integrationDirectoryIndex + 1).join('/')
361
363
  }
362
364
 
363
- function resolveRequiredModulesForSpec(projectRoot: string, relativeSpecPath: string): string[] {
365
+ export function resolveModuleDependenciesForSpec(
366
+ projectRoot: string,
367
+ relativeSpecPath: string,
368
+ { includeOptional = false }: { includeOptional?: boolean } = {},
369
+ ): string[] {
364
370
  const requiredModules = new Set<string>()
365
371
  const normalizedSpecPath = normalizePath(relativeSpecPath)
366
372
  const absoluteSpecPath = path.join(projectRoot, normalizedSpecPath)
@@ -384,15 +390,15 @@ function resolveRequiredModulesForSpec(projectRoot: string, relativeSpecPath: st
384
390
  for (const directoryPath of traversal) {
385
391
  for (const metadataFileName of INTEGRATION_META_FILE_NAMES) {
386
392
  const metadataPath = path.join(directoryPath, metadataFileName)
387
- readDependenciesFromMetadataFile(metadataPath).forEach((dependency) => requiredModules.add(dependency))
393
+ readDependenciesFromMetadataFile(metadataPath, includeOptional).forEach((dependency) => requiredModules.add(dependency))
388
394
  }
389
395
  }
390
396
  }
391
397
 
392
- readDependenciesFromMetadataFile(absoluteSpecPath).forEach((dependency) => requiredModules.add(dependency))
398
+ readDependenciesFromMetadataFile(absoluteSpecPath, includeOptional).forEach((dependency) => requiredModules.add(dependency))
393
399
  const specFileName = path.basename(normalizedSpecPath, '.spec.ts')
394
400
  const perTestMetadataPath = path.join(path.dirname(absoluteSpecPath), `${specFileName}.meta.ts`)
395
- readDependenciesFromMetadataFile(perTestMetadataPath).forEach((dependency) => requiredModules.add(dependency))
401
+ readDependenciesFromMetadataFile(perTestMetadataPath, includeOptional).forEach((dependency) => requiredModules.add(dependency))
396
402
 
397
403
  return Array.from(requiredModules)
398
404
  }
@@ -494,7 +500,7 @@ export function discoverIntegrationSpecFiles(projectRoot: string, legacyIntegrat
494
500
  path: relativePath,
495
501
  moduleName: extractModuleNameFromIntegrationPath(relativePath),
496
502
  isOverlay: isOverlayIntegrationPath(relativePath, overlayRoot),
497
- requiredModules: resolveRequiredModulesForSpec(projectRoot, relativePath),
503
+ requiredModules: resolveModuleDependenciesForSpec(projectRoot, relativePath),
498
504
  requiredEnvVars: resolveRequiredEnvVarsForSpec(projectRoot, relativePath),
499
505
  requiredAnyEnvVars: resolveRequiredAnyEnvVarsForSpec(projectRoot, relativePath),
500
506
  })
@@ -508,7 +514,7 @@ export function discoverIntegrationSpecFiles(projectRoot: string, legacyIntegrat
508
514
  path: relativePath,
509
515
  moduleName: extractModuleNameFromIntegrationPath(relativePath),
510
516
  isOverlay: isOverlayIntegrationPath(relativePath, overlayRoot),
511
- requiredModules: resolveRequiredModulesForSpec(projectRoot, relativePath),
517
+ requiredModules: resolveModuleDependenciesForSpec(projectRoot, relativePath),
512
518
  requiredEnvVars: resolveRequiredEnvVarsForSpec(projectRoot, relativePath),
513
519
  requiredAnyEnvVars: resolveRequiredAnyEnvVarsForSpec(projectRoot, relativePath),
514
520
  })
@@ -533,7 +539,7 @@ export function discoverIntegrationSpecFiles(projectRoot: string, legacyIntegrat
533
539
  }
534
540
  }
535
541
 
536
- return discovered
542
+ const selected = discovered
537
543
  .filter((file) => {
538
544
  if (file.requiredModules.some((moduleId) => !enabledModules.has(normalizeModuleId(moduleId)))) {
539
545
  return false
@@ -568,4 +574,6 @@ export function discoverIntegrationSpecFiles(projectRoot: string, legacyIntegrat
568
574
  return enabledModules.has(normalizeModuleId(file.moduleName))
569
575
  })
570
576
  .sort((left, right) => left.path.localeCompare(right.path))
577
+ writeDiscoverySelectionReport(projectRoot, selected)
578
+ return selected
571
579
  }
package/src/mercato.ts CHANGED
@@ -12,6 +12,7 @@ import { getRedisUrl, getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/sh
12
12
  import { formatInitSummary } from './lib/init-summary'
13
13
  import { resolveInitDerivedSecrets, resolveInitSuperadminCredentials } from './lib/init-secrets'
14
14
  import { decideExistingDatabase, formatSkipIfInitializedMessage } from './lib/init-existing-database'
15
+ import { assertEphemeralDatabaseConnection, assertEphemeralDatabaseOwnership, readEphemeralDatabaseGuard } from './lib/testing/ephemeral-database-guard'
15
16
  import {
16
17
  resolveAutoSpawnWorkersMode,
17
18
  resolveLazySpawnMode,
@@ -222,6 +223,9 @@ function detectDatabaseConnectionIssue(
222
223
 
223
224
  function formatCliFailureMessage(modName: string, cmdName: string, error: unknown): string {
224
225
  const fallbackMessage = getFallbackErrorMessage(error)
226
+ if (modName === 'entities' && cmdName === 'rotate-encryption-key' && process.env.OM_ROTATION_PROGRESS !== 'json') {
227
+ return fallbackMessage.replace(/^\[internal\] /, '')
228
+ }
225
229
  const databaseIssue = detectDatabaseConnectionIssue(error)
226
230
 
227
231
  const isDatabaseCommand = modName === 'db' && ['migrate', 'generate', 'greenfield'].includes(cmdName)
@@ -1079,6 +1083,18 @@ export async function run(argv = process.argv) {
1079
1083
  try {
1080
1084
  const initArgs = parts.slice(1).filter(Boolean)
1081
1085
  const reinstall = initArgs.includes('--reinstall') || initArgs.includes('-r')
1086
+ const ephemeralDatabaseGuard = readEphemeralDatabaseGuard(initArgs)
1087
+ if (ephemeralDatabaseGuard) {
1088
+ assertEphemeralDatabaseConnection(ephemeralDatabaseGuard, process.env.DATABASE_URL)
1089
+ const { Client } = await import('pg')
1090
+ const verificationClient = new Client({ connectionString: process.env.DATABASE_URL, ssl: getSslConfig(), connectionTimeoutMillis: 5000 })
1091
+ try {
1092
+ await verificationClient.connect()
1093
+ await assertEphemeralDatabaseOwnership(ephemeralDatabaseGuard, verificationClient)
1094
+ } finally {
1095
+ await verificationClient.end()
1096
+ }
1097
+ }
1082
1098
  process.env.OM_INIT_FLOW = 'true'
1083
1099
  if (reinstall) {
1084
1100
  process.env.OM_INIT_REINSTALL = 'true'
@@ -1148,11 +1164,15 @@ export async function run(argv = process.argv) {
1148
1164
  console.error('DATABASE_URL is not set. Aborting reinstall.')
1149
1165
  return 1
1150
1166
  }
1151
- const dbExists = await ensureDatabaseExists(dbUrl)
1167
+ const dbExists = ephemeralDatabaseGuard ? true : await ensureDatabaseExists(dbUrl)
1152
1168
  if (!dbExists) return 1
1153
1169
  const client = new Client({ connectionString: dbUrl, ssl: getSslConfig() })
1154
1170
  try {
1155
1171
  await client.connect()
1172
+ if (ephemeralDatabaseGuard) {
1173
+ assertEphemeralDatabaseConnection(ephemeralDatabaseGuard, dbUrl)
1174
+ await assertEphemeralDatabaseOwnership(ephemeralDatabaseGuard, client)
1175
+ }
1156
1176
  // Collect all user tables in the configured schema (uses search_path from DATABASE_URL)
1157
1177
  const res = await client.query(`SELECT tablename FROM pg_tables WHERE schemaname = current_schema()`)
1158
1178
  const dropTargets = new Set<string>((res.rows || []).map((r: any) => String(r.tablename)))
@@ -1190,7 +1210,7 @@ export async function run(argv = process.argv) {
1190
1210
  // a stray ioredis client with auto-reconnect would otherwise spam
1191
1211
  // ETIMEDOUT errors for the rest of the process lifetime.
1192
1212
  const redisUrl = getRedisUrl()
1193
- if (redisUrl) {
1213
+ if (redisUrl && !ephemeralDatabaseGuard) {
1194
1214
  const Redis = (await import('ioredis')).default
1195
1215
  const redis = new Redis({
1196
1216
  ...parseRedisUrl(redisUrl),
@@ -1211,6 +1231,8 @@ export async function run(argv = process.argv) {
1211
1231
  } finally {
1212
1232
  try { redis.disconnect() } catch {}
1213
1233
  }
1234
+ } else if (ephemeralDatabaseGuard) {
1235
+ console.log('[internal] Redis flush skipped: ephemeral database initialization does not own Redis.')
1214
1236
  } else {
1215
1237
  console.log(' Redis flush skipped (REDIS_URL not configured).')
1216
1238
  }
@@ -1226,7 +1248,7 @@ export async function run(argv = process.argv) {
1226
1248
  }
1227
1249
 
1228
1250
  const { Client } = await import('pg')
1229
- const dbExists = await ensureDatabaseExists(dbUrl)
1251
+ const dbExists = ephemeralDatabaseGuard ? true : await ensureDatabaseExists(dbUrl)
1230
1252
  if (!dbExists) return 1
1231
1253
  const client = new Client({ connectionString: dbUrl, ssl: getSslConfig() })
1232
1254
  try {
@@ -1571,16 +1593,23 @@ export async function run(argv = process.argv) {
1571
1593
  const commandArgs = remaining.filter(Boolean)
1572
1594
 
1573
1595
  if (!subcommand || subcommand === 'help' || subcommand === '--help' || subcommand === '-h') {
1574
- console.log('Usage: yarn mercato module <add|enable|eject|search|info|scaffold> ...')
1596
+ console.log('Usage: yarn mercato module <add|enable|eject|search|info|list|doctor|scaffold> ...')
1575
1597
  console.log(' yarn mercato module add <packageSpec> [--module <moduleId>] [--eject] [--allow-third-party]')
1576
1598
  console.log(' yarn mercato module enable <packageName> [--module <moduleId>] [--eject] [--allow-third-party]')
1577
1599
  console.log(' yarn mercato module eject <moduleId>')
1578
1600
  console.log(' yarn mercato module search [<query>] [--category <id>] [--kind <kind>] [--all-lines] [--limit <n>] [--json]')
1579
1601
  console.log(' yarn mercato module info <package-or-module-id> [--json]')
1602
+ console.log(' yarn mercato module list [--all] [--json]')
1603
+ console.log(' yarn mercato module doctor [--strict] [--json]')
1580
1604
  console.log(' yarn mercato module scaffold <moduleId> --entity <entity> --fields "<fields>" [--with-ui] [--target app|packages/core] [--features-prefix <prefix>] [--dry-run]')
1581
1605
  return 0
1582
1606
  }
1583
1607
 
1608
+ if (subcommand === 'list' || subcommand === 'doctor') {
1609
+ const { runModuleDiagnostics } = await import('./lib/module-diagnostics')
1610
+ return runModuleDiagnostics(subcommand, commandArgs)
1611
+ }
1612
+
1584
1613
  if (subcommand === 'search' || subcommand === 'info') {
1585
1614
  const { runModuleSearch, runModuleInfo } = await import('./lib/module-search')
1586
1615
  const { readEnabledModules } = await import('./lib/modules-config')
@@ -2105,7 +2134,16 @@ export async function run(argv = process.argv) {
2105
2134
  watchRequest?.logCascade
2106
2135
  ? (reason) => console.log(`[generate:watch] Cascading; groups=openapi; reason=${reason}`)
2107
2136
  : undefined)
2108
- if (!quiet) console.log('All generators completed.')
2137
+ if (!quiet) {
2138
+ try {
2139
+ const { buildModuleIndex, inactiveModuleDependencies } = await import('./lib/module-index')
2140
+ const inactive = inactiveModuleDependencies(buildModuleIndex(undefined, false)).length
2141
+ if (inactive > 0) console.log(`[generate] ${inactive} inactive optional module capabilities. Run yarn mercato module doctor.`)
2142
+ } catch {
2143
+ // Module diagnostics are informational and must not make generate fail.
2144
+ }
2145
+ console.log('All generators completed.')
2146
+ }
2109
2147
  },
2110
2148
  },
2111
2149
  {
@@ -2881,6 +2919,10 @@ export async function run(argv = process.argv) {
2881
2919
 
2882
2920
  const mod = all.find((m) => m.id === modName)
2883
2921
  if (!mod) {
2922
+ if (modName === 'maintenance') {
2923
+ console.error('Maintenance mode requires the Enterprise maintenance module. Set OM_ENABLE_ENTERPRISE_MODULES=true and regenerate the app after enabling Enterprise.')
2924
+ return 1
2925
+ }
2884
2926
  console.error(`❌ Module not found: "${modName}"`)
2885
2927
  return 1
2886
2928
  }