@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
@@ -1,3 +1,4 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
1
2
  import fs from 'node:fs'
2
3
  import path from 'node:path'
3
4
 
@@ -5,6 +6,9 @@ type ServerStartLockRecord = {
5
6
  pid: number
6
7
  port: string | null
7
8
  startedAt: string
9
+ processStartTime: string | null
10
+ bootId: string | null
11
+ token: string | null
8
12
  }
9
13
 
10
14
  export type ServerStartLockHandle = {
@@ -12,9 +16,28 @@ export type ServerStartLockHandle = {
12
16
  release: () => void
13
17
  }
14
18
 
15
- function readServerStartLock(lockPath: string): ServerStartLockRecord | null {
19
+ const BOOT_ID_PATH = '/proc/sys/kernel/random/boot_id'
20
+ const STAT_FIRST_FIELD_AFTER_COMMAND = 3
21
+ const STAT_START_TIME_FIELD = 22
22
+ const TAKEOVER_BUSY_WAIT_MS = 25
23
+ const MAX_TAKEOVER_ATTEMPTS = 400
24
+
25
+ function readOptionalString(value: unknown): string | null {
26
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null
27
+ }
28
+
29
+ function readRawFile(filePath: string): string | null {
30
+ try {
31
+ return fs.readFileSync(filePath, 'utf8')
32
+ } catch (error) {
33
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
34
+ throw error
35
+ }
36
+ }
37
+
38
+ function parseServerStartLock(raw: string | null): ServerStartLockRecord | null {
39
+ if (raw === null) return null
16
40
  try {
17
- const raw = fs.readFileSync(lockPath, 'utf8')
18
41
  const parsed = JSON.parse(raw) as Partial<ServerStartLockRecord>
19
42
  if (typeof parsed.pid !== 'number' || !Number.isInteger(parsed.pid) || parsed.pid <= 0) {
20
43
  return null
@@ -23,12 +46,42 @@ function readServerStartLock(lockPath: string): ServerStartLockRecord | null {
23
46
  pid: parsed.pid,
24
47
  port: typeof parsed.port === 'string' && parsed.port.trim().length > 0 ? parsed.port : null,
25
48
  startedAt: typeof parsed.startedAt === 'string' ? parsed.startedAt : '',
49
+ processStartTime: readOptionalString(parsed.processStartTime),
50
+ bootId: readOptionalString(parsed.bootId),
51
+ token: readOptionalString(parsed.token),
26
52
  }
27
53
  } catch {
28
54
  return null
29
55
  }
30
56
  }
31
57
 
58
+ /**
59
+ * Reads the start time of `pid` (field 22 of `/proc/<pid>/stat`). The command name
60
+ * in field 2 may contain spaces or parentheses, so only the text after the last `)`
61
+ * is split. Returns `null` when the platform has no `/proc` (macOS, Windows) or the
62
+ * entry cannot be read or parsed.
63
+ */
64
+ export function readProcessStartTime(pid: number): string | null {
65
+ try {
66
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')
67
+ const commandEnd = stat.lastIndexOf(')')
68
+ if (commandEnd < 0) return null
69
+ const fields = stat.slice(commandEnd + 1).trim().split(/\s+/)
70
+ const startTime = fields[STAT_START_TIME_FIELD - STAT_FIRST_FIELD_AFTER_COMMAND]
71
+ return startTime && /^\d+$/.test(startTime) ? startTime : null
72
+ } catch {
73
+ return null
74
+ }
75
+ }
76
+
77
+ function readBootId(): string | null {
78
+ try {
79
+ return readOptionalString(fs.readFileSync(BOOT_ID_PATH, 'utf8'))
80
+ } catch {
81
+ return null
82
+ }
83
+ }
84
+
32
85
  function isProcessAlive(pid: number): boolean {
33
86
  try {
34
87
  process.kill(pid, 0)
@@ -38,6 +91,98 @@ function isProcessAlive(pid: number): boolean {
38
91
  }
39
92
  }
40
93
 
94
+ /**
95
+ * A lock is held only while the process that wrote it is still running. A live pid
96
+ * alone is not enough: the lock file sits in the app directory and survives a
97
+ * container restart, while pid numbering starts again, so the recorded pid soon
98
+ * belongs to an unrelated process. When the lock carries the boot id and the
99
+ * process start time, both must still match. When either side cannot be read
100
+ * (old lock format, no `/proc`), the pid check alone decides, as before.
101
+ */
102
+ function isLockOwnerAlive(lock: ServerStartLockRecord): boolean {
103
+ if (!isProcessAlive(lock.pid)) return false
104
+
105
+ if (lock.bootId) {
106
+ const currentBootId = readBootId()
107
+ if (currentBootId && currentBootId !== lock.bootId) return false
108
+ }
109
+
110
+ if (lock.processStartTime) {
111
+ const currentStartTime = readProcessStartTime(lock.pid)
112
+ if (currentStartTime && currentStartTime !== lock.processStartTime) return false
113
+ }
114
+
115
+ return true
116
+ }
117
+
118
+ /**
119
+ * Treats a record written by this very pid as dead: this process never holds a
120
+ * lock or a takeover guard while it inspects one, so a matching pid can only come
121
+ * from a previous run (pid numbering restarts with the container).
122
+ */
123
+ function isHeldByAnotherLiveProcess(record: ServerStartLockRecord | null): record is ServerStartLockRecord {
124
+ return record !== null && record.pid !== process.pid && isLockOwnerAlive(record)
125
+ }
126
+
127
+ /**
128
+ * Creates `target` with `content` only if it does not exist yet. The content is
129
+ * written to a private temporary file first and hard-linked into place, so other
130
+ * processes never observe a half-written file. Returns `false` when `target`
131
+ * already exists.
132
+ */
133
+ function publishExclusive(target: string, content: string): boolean {
134
+ const tempPath = `${target}.${process.pid}.${randomUUID()}.tmp`
135
+ fs.writeFileSync(tempPath, content, { encoding: 'utf8', flag: 'wx' })
136
+ try {
137
+ fs.linkSync(tempPath, target)
138
+ return true
139
+ } catch (error) {
140
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
141
+ throw error
142
+ } finally {
143
+ fs.rmSync(tempPath, { force: true })
144
+ }
145
+ }
146
+
147
+ function sleepSync(ms: number): void {
148
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
149
+ }
150
+
151
+ /**
152
+ * Removes the stale lock generation `staleRaw` unless another process has already
153
+ * replaced it. Several starts can inspect the same stale lock at once, and a plain
154
+ * unlink would let a late one delete the lock a faster one has just written. Only
155
+ * the process that exclusively creates the takeover guard for this generation may
156
+ * remove it, and it re-reads the lock under the guard first. A guard left behind
157
+ * by a process that died mid-takeover is skipped in favour of the next slot.
158
+ *
159
+ * Returns `false` when a live process holds the guard and the caller must retry.
160
+ */
161
+ function removeStaleGeneration(lockPath: string, staleRaw: string, ownRaw: string): boolean {
162
+ const generation = createHash('sha256').update(staleRaw).digest('hex').slice(0, 16)
163
+ const skippedGuards: string[] = []
164
+ let ownedGuard: string | null = null
165
+ try {
166
+ for (let slot = 0; ; slot += 1) {
167
+ const guardPath = `${lockPath}.${generation}.${slot}.takeover`
168
+ if (publishExclusive(guardPath, ownRaw)) {
169
+ ownedGuard = guardPath
170
+ break
171
+ }
172
+ const guardRaw = readRawFile(guardPath)
173
+ if (guardRaw === null || isHeldByAnotherLiveProcess(parseServerStartLock(guardRaw))) return false
174
+ skippedGuards.push(guardPath)
175
+ }
176
+ if (readRawFile(lockPath) === staleRaw) {
177
+ fs.rmSync(lockPath, { force: true })
178
+ }
179
+ for (const guardPath of skippedGuards) fs.rmSync(guardPath, { force: true })
180
+ return true
181
+ } finally {
182
+ if (ownedGuard !== null) fs.rmSync(ownedGuard, { force: true })
183
+ }
184
+ }
185
+
41
186
  export function getServerStartLockPath(appDir: string): string {
42
187
  return path.join(appDir, '.mercato', 'server-start.lock')
43
188
  }
@@ -51,29 +196,33 @@ export function acquireServerStartLock(
51
196
  pid: process.pid,
52
197
  port: typeof options.port === 'string' && options.port.trim().length > 0 ? options.port.trim() : null,
53
198
  startedAt: new Date().toISOString(),
199
+ processStartTime: readProcessStartTime(process.pid),
200
+ bootId: readBootId(),
201
+ token: randomUUID(),
54
202
  }
203
+ const ownRaw = JSON.stringify(lockRecord)
55
204
 
56
205
  fs.mkdirSync(path.dirname(lockPath), { recursive: true })
57
206
 
58
- for (;;) {
59
- try {
60
- fs.writeFileSync(lockPath, JSON.stringify(lockRecord), { encoding: 'utf8', flag: 'wx' })
61
- break
62
- } catch (error) {
63
- const writeError = error as NodeJS.ErrnoException
64
- if (writeError.code !== 'EEXIST') {
65
- throw writeError
66
- }
207
+ for (let attempt = 0; !publishExclusive(lockPath, ownRaw); attempt += 1) {
208
+ const existingRaw = readRawFile(lockPath)
209
+ if (existingRaw === null) continue
210
+
211
+ const existingLock = parseServerStartLock(existingRaw)
212
+ if (isHeldByAnotherLiveProcess(existingLock)) {
213
+ const portSuffix = existingLock.port ? ` on port ${existingLock.port}` : ''
214
+ throw new Error(
215
+ `[server] Another Open Mercato production server is already running for ${appDir} (pid ${existingLock.pid}${portSuffix}). Stop it before starting another instance.`,
216
+ )
217
+ }
67
218
 
68
- const existingLock = readServerStartLock(lockPath)
69
- if (existingLock && existingLock.pid !== process.pid && isProcessAlive(existingLock.pid)) {
70
- const portSuffix = existingLock.port ? ` on port ${existingLock.port}` : ''
219
+ if (!removeStaleGeneration(lockPath, existingRaw, ownRaw)) {
220
+ if (attempt >= MAX_TAKEOVER_ATTEMPTS) {
71
221
  throw new Error(
72
- `[server] Another Open Mercato production server is already running for ${appDir} (pid ${existingLock.pid}${portSuffix}). Stop it before starting another instance.`,
222
+ `[server] Another process is still replacing the stale server start lock for ${appDir}. Try again.`,
73
223
  )
74
224
  }
75
-
76
- fs.rmSync(lockPath, { force: true })
225
+ sleepSync(TAKEOVER_BUSY_WAIT_MS)
77
226
  }
78
227
  }
79
228
 
@@ -82,8 +231,10 @@ export function acquireServerStartLock(
82
231
  if (released) return
83
232
  released = true
84
233
 
85
- const currentLock = readServerStartLock(lockPath)
86
- if (currentLock?.pid === process.pid) {
234
+ // Compare the token, not the pid: after a takeover the file belongs to
235
+ // another process even if it reuses this pid in a later container run.
236
+ const currentLock = parseServerStartLock(readRawFile(lockPath))
237
+ if (currentLock?.token === lockRecord.token) {
87
238
  fs.rmSync(lockPath, { force: true })
88
239
  }
89
240
  }
@@ -1,3 +1,5 @@
1
+ import { isDatabaseRuntimeEnabled, runWithFreshDatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'
2
+ import { resolveDeclaredDatabaseJobContext, validateDeclaredDatabaseBinding } from '@open-mercato/shared/lib/db/declarations'
1
3
  import type { JobContext, JobHandler } from '@open-mercato/queue'
2
4
  import type { ModuleWorker } from '@open-mercato/shared/modules/registry'
3
5
  import {
@@ -8,6 +10,7 @@ import { bindRequestScopeContainer, runInOwnedRequestScope, runWithRequestScopeC
8
10
 
9
11
  export type WorkerJobContainer = {
10
12
  resolve: <T = unknown>(name: string) => T
13
+ dispose?: () => void | Promise<void>
11
14
  /**
12
15
  * #8268 review Major 1 (re-review): optional — the factory's real container,
13
16
  * when it has one, so a worker that needs `.register()` (several command
@@ -41,35 +44,43 @@ export function createPerJobWorkerHandler(
41
44
  workers: ModuleWorker[],
42
45
  createContainer: WorkerJobContainerFactory,
43
46
  ): JobHandler {
44
- return (job, ctx: JobContext) => runInOwnedRequestScope(async (): Promise<void> => {
45
- const container = await createContainer()
46
- bindRequestScopeContainer(container)
47
- try {
48
- for (const worker of workers) {
49
- await withModuleResourceUsage(
50
- {
51
- moduleId: worker.moduleId ?? inferModuleIdFromResourceId(worker.id),
52
- surface: 'worker',
53
- operation: worker.id,
54
- resourceId: worker.id,
55
- },
56
- () => runWithRequestScopeContainer(container, () => worker.handler(job, {
57
- ...ctx,
58
- resolve: container.resolve.bind(container),
59
- // See `WorkerJobContainer.register`'s own doc — present only when the
60
- // factory handed back a real container, never a `{ resolve }`-only one.
61
- container: typeof container.register === 'function' ? container : undefined,
62
- })),
63
- )
64
- }
65
- } finally {
47
+ return async (job, ctx: JobContext) => {
48
+ const execute = () => runInOwnedRequestScope(async () => {
49
+ const container = await createContainer()
50
+ bindRequestScopeContainer(container)
66
51
  try {
67
- const em = container.resolve('em') as ClearableEntityManager | null
68
- em?.clear?.()
69
- } catch {
70
- // Best-effort: clearing the identity map is a memory optimization and
71
- // must never mask a job's own outcome.
52
+ for (const worker of workers) {
53
+ await withModuleResourceUsage(
54
+ {
55
+ moduleId: worker.moduleId ?? inferModuleIdFromResourceId(worker.id),
56
+ surface: 'worker',
57
+ operation: worker.id,
58
+ resourceId: worker.id,
59
+ },
60
+ () => runWithRequestScopeContainer(container, () => worker.handler(job, {
61
+ ...ctx,
62
+ resolve: container.resolve.bind(container),
63
+ container: typeof container.register === 'function' ? container : undefined,
64
+ })),
65
+ )
66
+ }
67
+ } finally {
68
+ try {
69
+ const em = container.resolve('em') as ClearableEntityManager | null
70
+ em?.clear?.()
71
+ } catch {
72
+ // Best-effort: clearing the identity map is a memory optimization and
73
+ // must never mask a job's own outcome.
74
+ }
75
+ await container.dispose?.()
72
76
  }
77
+ })
78
+ if (!isDatabaseRuntimeEnabled()) return execute()
79
+ const context = await resolveDeclaredDatabaseJobContext({ queue: ctx.queueName, workerIds: workers.map((worker) => worker.id), payload: job.payload, metadata: job.metadata })
80
+ if (context.kind === 'tenant') {
81
+ const valid = await runWithFreshDatabaseExecutionContext({ kind: 'identity', tenantId: context.tenantId, source: 'identity', operation: 'worker-tenant-binding' }, () => validateDeclaredDatabaseBinding({ context }, { requireValidator: true }))
82
+ if (!valid) throw new Error('[internal] Worker requires a persisted active tenant')
73
83
  }
74
- })
84
+ return runWithFreshDatabaseExecutionContext(context, execute)
85
+ }
75
86
  }
package/src/mercato.ts CHANGED
@@ -7,11 +7,25 @@ import type { Module, ModuleWorker } from '@open-mercato/shared/modules/registry
7
7
  import { getCliModules, hasCliModules, registerCliModules } from './registry'
8
8
  export { getCliModules, hasCliModules, registerCliModules }
9
9
  import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
10
+ import { createCliMaintenanceClient } from './lib/db/maintenance-client'
11
+ import { requiresDatabaseRuntimeForMigration } from './lib/cli-bootstrap-mode'
12
+ import { runDatabaseTenantSetup } from '@open-mercato/shared/lib/db/setup'
13
+ import { runWithFreshDatabaseExecutionContext, isDatabaseRuntimeEnabled } from '@open-mercato/shared/lib/db/runtime'
14
+ import { runDatabaseCliCommand } from '@open-mercato/shared/lib/db/cli'
10
15
  import { getSslConfig } from '@open-mercato/shared/lib/db/ssl'
11
16
  import { getRedisUrl, getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/shared/lib/redis/connection'
12
17
  import { formatInitSummary } from './lib/init-summary'
13
18
  import { resolveInitDerivedSecrets, resolveInitSuperadminCredentials } from './lib/init-secrets'
14
- import { decideExistingDatabase, formatSkipIfInitializedMessage } from './lib/init-existing-database'
19
+ import { createInitTranslator } from './lib/init-i18n'
20
+ import {
21
+ decideExistingDatabase,
22
+ formatIncompleteInitializationMessage,
23
+ formatSkipIfInitializedMessage,
24
+ hasIncompleteInitialization,
25
+ openInitializationSession,
26
+ withInitializationClient,
27
+ type InitializationSession,
28
+ } from './lib/init-existing-database'
15
29
  import { assertEphemeralDatabaseConnection, assertEphemeralDatabaseOwnership, readEphemeralDatabaseGuard } from './lib/testing/ephemeral-database-guard'
16
30
  import {
17
31
  resolveAutoSpawnWorkersMode,
@@ -290,6 +304,7 @@ function formatInitFailureMessage(error: unknown): string {
290
304
  }
291
305
 
292
306
  async function ensureDatabaseExists(dbUrl: string): Promise<boolean> {
307
+ if (isDatabaseRuntimeEnabled()) return true
293
308
  let parsed: URL
294
309
  try {
295
310
  parsed = new URL(dbUrl)
@@ -814,7 +829,7 @@ async function runModuleCommand(
814
829
  }
815
830
  }
816
831
 
817
- await resolved.command.run(args)
832
+ await runDatabaseCliCommand(resolved.command, args, `${moduleName}:${commandName}`)
818
833
  return true
819
834
  }
820
835
 
@@ -1080,6 +1095,7 @@ export async function run(argv = process.argv) {
1080
1095
 
1081
1096
  console.log('šŸš€ Initializing Open Mercato app...\n')
1082
1097
 
1098
+ let initializationSession: InitializationSession | undefined
1083
1099
  try {
1084
1100
  const initArgs = parts.slice(1).filter(Boolean)
1085
1101
  const reinstall = initArgs.includes('--reinstall') || initArgs.includes('-r')
@@ -1158,7 +1174,6 @@ export async function run(argv = process.argv) {
1158
1174
  // Load env variables so DATABASE_URL is available
1159
1175
  await ensureEnvLoaded()
1160
1176
  console.log('ā™»ļø Reinstall mode enabled: dropping all database tables...')
1161
- const { Client } = await import('pg')
1162
1177
  const dbUrl = process.env.DATABASE_URL
1163
1178
  if (!dbUrl) {
1164
1179
  console.error('DATABASE_URL is not set. Aborting reinstall.')
@@ -1166,7 +1181,7 @@ export async function run(argv = process.argv) {
1166
1181
  }
1167
1182
  const dbExists = ephemeralDatabaseGuard ? true : await ensureDatabaseExists(dbUrl)
1168
1183
  if (!dbExists) return 1
1169
- const client = new Client({ connectionString: dbUrl, ssl: getSslConfig() })
1184
+ const client = await createCliMaintenanceClient(dbUrl)
1170
1185
  try {
1171
1186
  await client.connect()
1172
1187
  if (ephemeralDatabaseGuard) {
@@ -1247,37 +1262,37 @@ export async function run(argv = process.argv) {
1247
1262
  return 1
1248
1263
  }
1249
1264
 
1250
- const { Client } = await import('pg')
1251
1265
  const dbExists = ephemeralDatabaseGuard ? true : await ensureDatabaseExists(dbUrl)
1252
1266
  if (!dbExists) return 1
1253
- const client = new Client({ connectionString: dbUrl, ssl: getSslConfig() })
1267
+ const client = await createCliMaintenanceClient(dbUrl)
1254
1268
  try {
1255
1269
  await client.connect()
1256
1270
  const tableCheck = await client.query<{ regclass: string | null }>(
1257
- `SELECT to_regclass('public.users') AS regclass`,
1271
+ `SELECT to_regclass('users') AS regclass`,
1258
1272
  )
1259
- const hasUsersTable = Boolean(tableCheck.rows?.[0]?.regclass)
1260
- if (hasUsersTable) {
1261
- const countResult = await client.query<{ count: string }>(
1262
- 'SELECT COUNT(*)::text AS count FROM users',
1273
+ const countResult = tableCheck.rows[0]?.regclass
1274
+ ? await client.query<{ count: string }>('SELECT COUNT(*)::text AS count FROM users')
1275
+ : null
1276
+ const existingUsersCount = Number.parseInt(countResult?.rows[0]?.count ?? '0', 10)
1277
+ if (existingUsersCount > 0 && await hasIncompleteInitialization(client)) {
1278
+ console.error(formatIncompleteInitializationMessage(dbUrl))
1279
+ return 1
1280
+ }
1281
+ const existingDatabase = decideExistingDatabase(existingUsersCount, skipIfInitialized)
1282
+ if (existingDatabase === 'skip') {
1283
+ for (const line of formatSkipIfInitializedMessage(existingUsersCount, dbUrl)) console.log(line)
1284
+ return 0
1285
+ }
1286
+ if (existingDatabase === 'abort') {
1287
+ console.error(
1288
+ `āŒ Initialization aborted: found ${existingUsersCount} existing user(s) in the database.`,
1263
1289
  )
1264
- const existingUsersCount = Number.parseInt(countResult.rows?.[0]?.count ?? '0', 10)
1265
- const existingDatabase = decideExistingDatabase(existingUsersCount, skipIfInitialized)
1266
- if (existingDatabase === 'skip') {
1267
- for (const line of formatSkipIfInitializedMessage(existingUsersCount, dbUrl)) console.log(line)
1268
- return 0
1269
- }
1270
- if (existingDatabase === 'abort') {
1271
- console.error(
1272
- `āŒ Initialization aborted: found ${existingUsersCount} existing user(s) in the database.`,
1273
- )
1274
- console.error(
1275
- ' To reset and initialize from scratch, run: yarn mercato init --reinstall',
1276
- )
1277
- console.error(' Standalone shortcut: yarn setup --reinstall')
1278
- console.error(' Shortcut script: yarn reinstall')
1279
- return 1
1280
- }
1290
+ console.error(
1291
+ ' To reset and initialize from scratch, run: yarn mercato init --reinstall',
1292
+ )
1293
+ console.error(' Standalone shortcut: yarn setup --reinstall')
1294
+ console.error(' Shortcut script: yarn reinstall')
1295
+ return 1
1281
1296
  }
1282
1297
  } finally {
1283
1298
  try {
@@ -1321,10 +1336,26 @@ export async function run(argv = process.argv) {
1321
1336
  // Step 5: Build all modules for CLI commands
1322
1337
  const allModules = await buildAllModules()
1323
1338
 
1339
+ const dbUrl = process.env.DATABASE_URL
1340
+ if (!dbUrl) throw new Error('[internal] DATABASE_URL is missing after initialization preflight')
1341
+ const session = await openInitializationSession(dbUrl)
1342
+ initializationSession = session
1343
+ if (session.clearedInterruptedAttempt) {
1344
+ console.log(createInitTranslator(process.env)('cli.init.messages.interruptedAttemptCleared'))
1345
+ }
1346
+ const runBeforeUsersExist = async (action: () => Promise<unknown>) => {
1347
+ try {
1348
+ await action()
1349
+ } catch (error) {
1350
+ await session.cancelWithoutUsers()
1351
+ throw error
1352
+ }
1353
+ }
1354
+
1324
1355
  // Step 6: Restore configuration defaults
1325
1356
  if (allModules.some((module) => module.id === 'configs')) {
1326
1357
  console.log('āš™ļø Restoring module defaults...')
1327
- await runModuleCommand(allModules, 'configs', 'restore-defaults', [])
1358
+ await runBeforeUsersExist(() => runModuleCommand(allModules, 'configs', 'restore-defaults', []))
1328
1359
  console.log('āœ… Module defaults restored\n')
1329
1360
  }
1330
1361
 
@@ -1393,20 +1424,17 @@ export async function run(argv = process.argv) {
1393
1424
  if (skipPasswordPolicy) {
1394
1425
  setupArgs.push('--skip-password-policy')
1395
1426
  }
1396
- await runModuleCommand(allModules, 'auth', 'setup', setupArgs)
1397
- // Query DB to get tenant/org IDs using pg directly
1398
- const { Client } = await import('pg')
1399
- const dbUrl = process.env.DATABASE_URL
1400
- const pgClient = new Client({ connectionString: dbUrl, ssl: getSslConfig() })
1401
- await pgClient.connect()
1402
- const orgResult = await pgClient.query(
1403
- `SELECT o.id as org_id, o.tenant_id FROM organizations o
1404
- JOIN users u ON u.organization_id = o.id
1405
- LIMIT 1`
1406
- )
1407
- await pgClient.end()
1408
- const tenantId = orgResult?.rows?.[0]?.tenant_id ?? null
1409
- const orgId = orgResult?.rows?.[0]?.org_id ?? null
1427
+ await runBeforeUsersExist(() => runModuleCommand(allModules, 'auth', 'setup', setupArgs))
1428
+ const initializedOrganization = await withInitializationClient(dbUrl, async (client) => {
1429
+ const orgResult = await client.query<{ tenant_id: string; org_id: string }>(
1430
+ `SELECT o.id AS org_id, o.tenant_id FROM organizations o
1431
+ JOIN users u ON u.organization_id = o.id
1432
+ LIMIT 1`,
1433
+ )
1434
+ return orgResult.rows[0]
1435
+ })
1436
+ const tenantId = initializedOrganization?.tenant_id
1437
+ const orgId = initializedOrganization?.org_id
1410
1438
  if (!tenantId || !orgId) {
1411
1439
  throw new Error('Auth setup failed to create a tenant/org. Aborting init.')
1412
1440
  }
@@ -1447,13 +1475,13 @@ export async function run(argv = process.argv) {
1447
1475
  // Seed module defaults (structural data: dictionaries, tax rates, units, etc.)
1448
1476
  console.log('šŸ“š Seeding module defaults...')
1449
1477
  const { createRequestContainer } = await import('@open-mercato/shared/lib/di/container')
1450
- const seedContainer = await createRequestContainer()
1478
+ const seedContainer = await runWithFreshDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'seed-bootstrap' }, () => createRequestContainer())
1451
1479
  const seedEm = seedContainer.resolve('em') as any
1452
1480
  const seedCtx = { em: seedEm, tenantId, organizationId: orgId, container: seedContainer }
1453
1481
  for (const mod of allModules) {
1454
1482
  if (mod.setup?.seedDefaults) {
1455
1483
  console.log(` šŸ“¦ ${mod.id}...`)
1456
- await mod.setup.seedDefaults(seedCtx)
1484
+ await runDatabaseTenantSetup(seedCtx, (context) => mod.setup!.seedDefaults!(context))
1457
1485
  }
1458
1486
  }
1459
1487
  console.log('āœ… Module defaults seeded\n')
@@ -1462,7 +1490,7 @@ export async function run(argv = process.argv) {
1462
1490
  // ensureDefaultRoleAcls runs before seedDefaults (in setupTenantAndPrimaryUser),
1463
1491
  // so custom roles don't exist yet at that point. This second pass picks them up.
1464
1492
  const { ensureCustomRoleAcls } = await import('@open-mercato/core/modules/auth/lib/setup-app')
1465
- await ensureCustomRoleAcls(seedEm, tenantId, allModules)
1493
+ await runDatabaseTenantSetup({ em: seedEm, tenantId, organizationId: orgId }, (context) => ensureCustomRoleAcls(context.em, tenantId, allModules))
1466
1494
 
1467
1495
  if (skipExamples) {
1468
1496
  console.log('🚫 Example data seeding skipped (--no-examples)\n')
@@ -1472,7 +1500,7 @@ export async function run(argv = process.argv) {
1472
1500
  for (const mod of allModules) {
1473
1501
  if (mod.setup?.seedExamples) {
1474
1502
  console.log(` šŸ“¦ ${mod.id}...`)
1475
- await mod.setup.seedExamples(seedCtx)
1503
+ await runDatabaseTenantSetup(seedCtx, (context) => mod.setup!.seedExamples!(context))
1476
1504
  }
1477
1505
  }
1478
1506
  console.log('āœ… Example data seeded\n')
@@ -1532,6 +1560,8 @@ export async function run(argv = process.argv) {
1532
1560
  console.log('')
1533
1561
  }
1534
1562
 
1563
+ await session.complete()
1564
+
1535
1565
  const adminPasswordOverride = derivedSecrets.adminPassword
1536
1566
  const employeePasswordOverride = derivedSecrets.employeePassword
1537
1567
  const createdUsers: Array<{ label: string; icon: string; email: string }> = []
@@ -1564,6 +1594,8 @@ export async function run(argv = process.argv) {
1564
1594
  } catch (error: unknown) {
1565
1595
  console.error('āŒ Initialization failed:', formatInitFailureMessage(error))
1566
1596
  return 1
1597
+ } finally {
1598
+ await initializationSession?.close().catch(() => undefined)
1567
1599
  }
1568
1600
  }
1569
1601
 
@@ -1723,11 +1755,14 @@ export async function run(argv = process.argv) {
1723
1755
  }
1724
1756
 
1725
1757
  const { createRequestContainer } = await import('@open-mercato/shared/lib/di/container')
1726
- const seedContainer = await createRequestContainer()
1758
+ const seedContainer = await runWithFreshDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'seed-bootstrap' }, () => createRequestContainer())
1727
1759
  const seedEm = seedContainer.resolve('em') as any
1728
1760
 
1729
1761
  const { Organization } = await import('@open-mercato/core/modules/directory/data/entities')
1730
- const orgs = await seedEm.find(Organization, { deletedAt: null }, { populate: ['tenant'] as const })
1762
+ const orgs = !isDatabaseRuntimeEnabled() ? await seedEm.find(Organization, { deletedAt: null }, { populate: ['tenant'] as const }) : await runWithFreshDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'seed-discovery' }, async () => {
1763
+ const discovery = await createRequestContainer()
1764
+ try { return await discovery.resolve<import('@mikro-orm/postgresql').EntityManager>('em').find(Organization, { deletedAt: null }, { populate: ['tenant'] as const }) } finally { await discovery.dispose() }
1765
+ })
1731
1766
 
1732
1767
  if (orgs.length === 0) {
1733
1768
  console.error('āŒ No organizations found. Run yarn initialize first.')
@@ -1744,12 +1779,12 @@ export async function run(argv = process.argv) {
1744
1779
  for (const mod of modulesToSeed) {
1745
1780
  if (mod.setup?.seedDefaults) {
1746
1781
  console.log(` šŸ“¦ ${mod.id}...`)
1747
- await mod.setup.seedDefaults(seedCtx)
1782
+ await runDatabaseTenantSetup(seedCtx, (context) => mod.setup!.seedDefaults!(context))
1748
1783
  }
1749
1784
  }
1750
1785
 
1751
1786
  const { ensureCustomRoleAcls } = await import('@open-mercato/core/modules/auth/lib/setup-app')
1752
- await ensureCustomRoleAcls(seedEm, tenantId, allModules)
1787
+ await runDatabaseTenantSetup({ em: seedEm, tenantId, organizationId }, (context) => ensureCustomRoleAcls(context.em, tenantId, allModules))
1753
1788
  }
1754
1789
 
1755
1790
  console.log('\nāœ… seed:defaults complete.')
@@ -2249,8 +2284,12 @@ export async function run(argv = process.argv) {
2249
2284
  },
2250
2285
  {
2251
2286
  command: 'migrate',
2252
- help: 'Applies every pending migration to the database DATABASE_URL points at.\nThis mutates the database — check .env before running it.',
2287
+ databaseAccess: 'maintenance',
2288
+ help: 'Applies every pending migration using the configured database connection.\nTenant boundaries use the maintenance login. This mutates the database — check .env before running it.',
2253
2289
  run: async () => {
2290
+ if (requiresDatabaseRuntimeForMigration() && !isDatabaseRuntimeEnabled()) {
2291
+ throw new Error('[internal] Tenant boundaries were requested but are not registered. Enable the tenant_boundaries module and run yarn generate before migrating.')
2292
+ }
2254
2293
  const { createResolver } = await import('./lib/resolver')
2255
2294
  const { dbMigrate } = await import('./lib/db')
2256
2295
  const resolver = createResolver()
@@ -2977,7 +3016,7 @@ export async function run(argv = process.argv) {
2977
3016
  }
2978
3017
  try {
2979
3018
  const commandExitCode = await runWithCapturedExitCode(async () => {
2980
- await cmd.run(rest)
3019
+ await runDatabaseCliCommand(cmd, rest, `${modName}:${cmdName}`)
2981
3020
  })
2982
3021
  if (!quietGeneration && (modName !== 'deploy' || cmdName !== 'railway')) {
2983
3022
  const ms = Date.now() - started
@@ -1,15 +0,0 @@
1
- # scheduler — CLI commands
2
-
3
- [Back to module index](index.md)
4
-
5
- ## CLI commands
6
-
7
- | ID / path | Source |
8
- |---|---|
9
- | list | [cli.ts](../../../../node_modules/@open-mercato/scheduler/src/modules/scheduler/cli.ts) |
10
- | status | [cli.ts](../../../../node_modules/@open-mercato/scheduler/src/modules/scheduler/cli.ts) |
11
- | run | [cli.ts](../../../../node_modules/@open-mercato/scheduler/src/modules/scheduler/cli.ts) |
12
- | start | [cli.ts](../../../../node_modules/@open-mercato/scheduler/src/modules/scheduler/cli.ts) |
13
- | audit-queue-targets | [cli.ts](../../../../node_modules/@open-mercato/scheduler/src/modules/scheduler/cli.ts) |
14
-
15
- <!-- end module facts section: scheduler/cli-commands -->