@open-mercato/starter 0.10.1-develop.7983.1.fd91207efe → 0.10.1-develop.7994.1.c9f31972aa

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.
package/README.md CHANGED
@@ -34,10 +34,22 @@ No Node yet? The package ships pre-Node bootstraps that install a **portable, ch
34
34
  | `reset` | Destructive cleanup (containers, volumes, starter state) — asks first. |
35
35
  | `infra up\|down` | Just the infra containers. |
36
36
 
37
- Useful flags: `--non-interactive`, `--skip-llm-prompt`, `--skip-db`, `--no-infra` (no Docker calls at all, also passed on to `yarn dev`), `--rebuild`, `--clean`, `--profile <name>`, `-- <args for yarn dev>`.
37
+ AI provider configuration is optional: press Enter or choose `0` at the provider prompt to continue without AI. Non-interactive setup also continues without a key. Configure a provider in `.env` later to enable AI chat.
38
+
39
+ If setup finds ports owned by pre-existing services, it shows the container names and states and asks whether to continue using the URLs in `.env`. Accepting leaves those containers under your control and prevents the dev runtime from restarting them. Restarting or unhealthy services produce warnings; their actual connection failures still stop database setup. Declining, or running non-interactively without `--no-infra`, stops setup with `yarn om stop` guidance for the checkout that started the stack.
40
+
41
+ Useful flags: `--verbose`, `--non-interactive`, `--skip-llm-prompt`, `--skip-db`, `--no-infra` (no Docker calls at all, also passed on to `yarn dev`), `--rebuild`, `--clean`, `--profile <name>`, `-- <args for yarn dev>`.
38
42
 
39
43
  `up --clean` forces a full re-converge: it clears the completed-step markers (install, build, migrations) and rebuilds the OpenCode service image, without touching any data — the one-time database seed stays done, and `reset` remains the destructive variant. Conversely, a plain `up` now also skips the database step entirely when the database is initialized and no `Migration*.ts` file changed since the last run (new migrations are detected by fingerprint and applied automatically).
40
44
 
45
+ ## Setup logs
46
+
47
+ Like `yarn dev` and `yarn dev:greenfield`, interactive `yarn setup` and `yarn infra:up` keep routine logs folded behind a dim emoji `[d]` hint without a frame or background. Stage headers, progress, banner text and raw output share a consistent left margin. Original `── Step n/N` headers stay visible; only the `Expected:` label is bold yellow. An animated `⚙️ working…` row shows elapsed time until the completion status replaces it. The spinner pauses while raw logs are shown and never overlaps provider prompts. ✅ / ℹ️ / ❌ summaries stay visible. Press **d** to show newly buffered output and stream new logs; press **d** again to hide them without an extra notice. Already displayed output is not replayed on subsequent toggles or failures. Failures reveal the buffered diagnostics automatically. AI-provider prompts remain interactive, and setup restores the terminal before starting the dev runtime.
48
+
49
+ Complete setup and infrastructure output is saved to `.mercato/logs/<run>-setup-raw.log` or `<run>-infra-raw.log`; the command prints the path when it starts. The file includes step summaries and full child-process stdout/stderr even while folded; only the last 200 hidden lines are retained for on-screen replay. Provider answers are never captured. These are local diagnostic files and can contain initialization details, so review them before sharing.
50
+
51
+ Use `yarn setup --verbose` or `yarn infra:up --verbose` for live raw output. CI, redirected output, `--non-interactive`, and `TERM=dumb` also stream directly. The existing dev logging settings apply: `MERCATO_DEV_OUTPUT=verbose`, `OM_DEV_LOG_DIR`, `OM_DEV_RUN_ID`, and `OM_DEV_LOG_TEE=0` (disable log files). `NO_COLOR` disables banner colors.
52
+
41
53
  ## Design rules
42
54
 
43
55
  - **Node stdlib only, no build step.** The CLI must run from a fresh clone before any `yarn install` — that is what makes it usable behind broken proxies.
@@ -49,3 +61,11 @@ Useful flags: `--non-interactive`, `--skip-llm-prompt`, `--skip-db`, `--no-infra
49
61
  ## Company tailoring
50
62
 
51
63
  Organizations customize behavior (mirrors, CA bundles, extra checks/steps, env defaults) via `starters/company/config.mjs` in the repo — see `starters/company/README.md`. The package stays generic; the repo carries the policy.
64
+
65
+ ## Service connection verification
66
+
67
+ Before migrations or initialization, setup checks PostgreSQL with `SELECT 1`,
68
+ each configured Redis URL with authenticated `PING`, and Meilisearch through
69
+ the protected indexes API using `MEILISEARCH_API_KEY`. Invalid credentials or
70
+ unreachable services stop setup and name the relevant setting without printing
71
+ passwords or tokens. Existing-service consent never bypasses these checks.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/starter",
3
- "version": "0.10.1-develop.7983.1.fd91207efe",
3
+ "version": "0.10.1-develop.7994.1.c9f31972aa",
4
4
  "description": "One-command, cross-platform bootstrap for Open Mercato dev environments: prerequisite doctor, corporate TLS trust, idempotent setup steps, and a supervised hybrid or fully containerized stack.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,412 @@
1
+ import assert from 'node:assert/strict'
2
+ import { EventEmitter } from 'node:events'
3
+ import { test } from 'node:test'
4
+
5
+ import { findContainerPortOwners, formatInfraProblem, requestExistingServicesConsent, startInfraServices, suggestFreePorts } from '../infra-preflight.mjs'
6
+ import { devRuntimeArgs } from '../infra.mjs'
7
+ import { infraUpStep, runSteps } from '../steps.mjs'
8
+ import { ensureInfra } from '../../../create-app/template/scripts/infra.mjs'
9
+ import { createSetupLogs } from '../setup-logs.mjs'
10
+
11
+ test('existing-service consent suspends compact input and displays guidance on every outcome', async () => {
12
+ for (const answer of [true, false, 'error']) {
13
+ const input = new EventEmitter()
14
+ Object.assign(input, { isTTY: true, isRaw: false, readableFlowing: false,
15
+ setRawMode(value) { this.isRaw = value }, resume() { this.readableFlowing = true }, pause() { this.readableFlowing = false } })
16
+ const terminal = []
17
+ const logs = createSetupLogs({ input, env: {}, output: { isTTY: true, write(line) { terminal.push(String(line)) } } })
18
+ const visible = []
19
+ const ctx = {
20
+ logs, mode: 'hybrid', flags: { noInfra: false, profiles: [] }, log: (line) => visible.push(String(line)),
21
+ runComposeImpl: () => ({ status: 0, stdout: '' }),
22
+ startInfraImpl: async () => ({ ok: false, problem: conflict() }),
23
+ confirmExistingServicesImpl: async (_problem, options) => {
24
+ assert.equal(input.isRaw, false)
25
+ assert.equal(input.listenerCount('data'), 0)
26
+ options.log('Review the existing services before consenting')
27
+ input.emit('data', 'd')
28
+ assert.ok(!terminal.join('').includes('Raw logs shown'))
29
+ if (answer === 'error') throw new Error('consent input failed')
30
+ return answer
31
+ },
32
+ }
33
+ const outcome = await runSteps([infraUpStep], ctx)
34
+ assert.equal(outcome.ok, answer === true)
35
+ assert.ok(visible.includes('Review the existing services before consenting'))
36
+ assert.equal(input.isRaw, false)
37
+ assert.equal(input.listenerCount('data'), 0)
38
+ assert.equal(input.readableFlowing, false)
39
+ assert.equal(ctx.promptLog, undefined)
40
+ if (answer === true) assert.equal(ctx.flags.noInfra, true)
41
+ }
42
+ })
43
+
44
+ const SERVICES = [
45
+ { service: 'postgres', port: 5432, envKey: 'POSTGRES_PORT' },
46
+ { service: 'redis', port: 6379, envKey: 'REDIS_PORT' },
47
+ ]
48
+
49
+ function fakeContainerScan(entries) {
50
+ const calls = []
51
+ const spawnSyncImpl = (command, args) => {
52
+ calls.push({ command, args })
53
+ if (args[0] === 'ps') return { status: 0, stdout: entries.map((_, index) => index.toString(16).padStart(12, '0')).join('\n') }
54
+ if (args[0] === 'inspect') return { status: 0, stdout: entries.map((entry) => JSON.stringify(entry)).join('\n') }
55
+ throw new Error(`Unexpected Docker command: ${args[0]}`)
56
+ }
57
+ return { calls, spawnSyncImpl }
58
+ }
59
+
60
+ function owner(overrides = {}) {
61
+ return {
62
+ ...SERVICES[0],
63
+ containerName: 'mercato-postgres',
64
+ state: 'running',
65
+ health: 'healthy',
66
+ ...overrides,
67
+ }
68
+ }
69
+
70
+ function conflict(ports = [owner()]) {
71
+ return { code: 'port-conflict', ports }
72
+ }
73
+
74
+ test('container discovery finds published port owners across Compose project identities without mutating Docker', () => {
75
+ const fake = fakeContainerScan([
76
+ { name: '/previous-postgres', status: 'running', health: 'healthy', ports: { '5432/tcp': [{ HostIp: '0.0.0.0', HostPort: '5432' }] } },
77
+ { name: '/unrelated-postgres', status: 'running', health: 'healthy', ports: { '5432/tcp': [{ HostIp: '127.0.0.1', HostPort: '55432' }] } },
78
+ { name: '/stopped-redis', status: 'exited', health: '', ports: { '6379/tcp': [{ HostIp: '0.0.0.0', HostPort: '6379' }] } },
79
+ ])
80
+
81
+ const found = findContainerPortOwners(SERVICES, fake)
82
+
83
+ assert.deepEqual(found, [owner({ containerName: 'previous-postgres' })])
84
+ assert.deepEqual(fake.calls.map(({ args }) => args[0]), ['ps', 'inspect'])
85
+ assert.ok(fake.calls[0].args.includes('status=running'))
86
+ assert.ok(fake.calls[0].args.includes('status=restarting'))
87
+ assert.ok(fake.calls[1].args.includes('--format'))
88
+ assert.ok(fake.calls.every(({ command }) => command === 'docker'))
89
+ })
90
+
91
+ test('container discovery retains restarting owners and de-duplicates IPv4 and IPv6 bindings', () => {
92
+ const fake = fakeContainerScan([
93
+ { name: '/mercato-postgres', status: 'restarting', health: 'unhealthy', ports: { '5432/tcp': [
94
+ { HostIp: '0.0.0.0', HostPort: '5432' },
95
+ { HostIp: '::', HostPort: '5432' },
96
+ ] } },
97
+ ])
98
+
99
+ assert.deepEqual(findContainerPortOwners(SERVICES, fake), [owner({ state: 'restarting', health: 'unhealthy' })])
100
+ })
101
+
102
+ test('container discovery does not infer an owner when Docker inspection fails', () => {
103
+ const calls = []
104
+ const found = findContainerPortOwners(SERVICES, {
105
+ spawnSyncImpl: (command, args) => {
106
+ calls.push(args[0])
107
+ return args[0] === 'ps'
108
+ ? { status: 0, stdout: 'abcdef123456\n' }
109
+ : { status: 1, stdout: '', stderr: 'container disappeared' }
110
+ },
111
+ })
112
+
113
+ assert.deepEqual(found, [])
114
+ assert.deepEqual(calls, ['ps', 'inspect'])
115
+ })
116
+
117
+ test('restarting cross-project containers block startup even while their TCP port is briefly closed', async () => {
118
+ const calls = []
119
+ const restarting = owner({ state: 'restarting', health: 'unhealthy' })
120
+ const outcome = await startInfraServices({
121
+ services: SERVICES,
122
+ composeArgs: (extra) => ['compose', ...extra],
123
+ detect: () => ({ ok: true }),
124
+ spawnSyncImpl: (command, args) => {
125
+ calls.push(args)
126
+ return { status: 0, stdout: '' }
127
+ },
128
+ portProbe: async () => false,
129
+ containerProbe: () => [restarting],
130
+ beforeUp: () => assert.fail('image preparation must not run while an existing container owns the port'),
131
+ log: () => {},
132
+ })
133
+
134
+ assert.equal(outcome.ok, false)
135
+ assert.equal(outcome.problem.code, 'port-conflict')
136
+ assert.deepEqual(outcome.problem.ports, [{ ...restarting, suggestedPort: restarting.port + 1 }])
137
+ assert.ok(calls.every((args) => !args.includes('up') && !args.includes('stop') && !args.includes('down')))
138
+ })
139
+
140
+ test('port conflicts suggest the next free port, skipping taken ones and ports suggested for another service', async () => {
141
+ const taken = new Set([5433, 6380])
142
+ const suggested = await suggestFreePorts(
143
+ [{ service: 'postgres', envKey: 'POSTGRES_PORT', port: 5432 }, { service: 'redis', envKey: 'REDIS_PORT', port: 6379 }],
144
+ { probe: async (port) => taken.has(port), reserved: [5432, 6379, 5435] },
145
+ )
146
+ assert.deepEqual(suggested.map((entry) => entry.suggestedPort), [5434, 6381])
147
+ const skipped = await suggestFreePorts([{ service: 'postgres', envKey: 'POSTGRES_PORT', port: 5432 }], { probe: async () => false, reserved: [5433] })
148
+ assert.equal(skipped[0].suggestedPort, 5434, 'a port configured for another service in the stack is never suggested')
149
+ const text = formatInfraProblem({ code: 'port-conflict', ports: suggested }, { output: { isTTY: false }, env: {} }).join('\n')
150
+ assert.match(text, /set POSTGRES_PORT=5434 in \.env/)
151
+ assert.match(text, /\(:5432 -> :5434\)/)
152
+ })
153
+
154
+ test('running services in this Compose project do not become foreign port conflicts', async () => {
155
+ const inspectedServices = []
156
+ const outcome = await startInfraServices({
157
+ services: SERVICES,
158
+ composeArgs: (extra) => ['compose', ...extra],
159
+ detect: () => ({ ok: true }),
160
+ spawnSyncImpl: (command, args) => ({
161
+ status: 0,
162
+ stdout: args.includes('ps') ? JSON.stringify({ Service: 'postgres', State: 'running', Health: 'healthy' }) : '',
163
+ }),
164
+ portProbe: async () => false,
165
+ containerProbe: (services) => {
166
+ inspectedServices.push(...services)
167
+ return []
168
+ },
169
+ log: () => {},
170
+ })
171
+
172
+ assert.equal(outcome.ok, true)
173
+ assert.deepEqual(outcome.reused, ['postgres'])
174
+ assert.ok(inspectedServices.every(({ service }) => service !== 'postgres'))
175
+ })
176
+
177
+ test('existing-services consent defaults to no and never prompts without an interactive terminal', async () => {
178
+ const messages = []
179
+ const question = async () => assert.fail('non-interactive setup must not prompt')
180
+ const options = { question, log: (line) => messages.push(line) }
181
+
182
+ assert.equal(await requestExistingServicesConsent(conflict(), { ...options, nonInteractive: true }), false)
183
+ assert.equal(await requestExistingServicesConsent(conflict(), { input: { isTTY: false }, log: options.log }), false)
184
+ assert.equal(await requestExistingServicesConsent(conflict(), { ...options, question: async () => '' }), false)
185
+ assert.equal(await requestExistingServicesConsent(conflict(), { ...options, question: async () => 'no' }), false)
186
+ assert.match(messages.join('\n'), /yarn om stop/)
187
+ })
188
+
189
+ test('existing-services consent requires explicit yes and discloses restarting or unhealthy containers', async () => {
190
+ for (const answer of ['y', 'yes']) {
191
+ const messages = []
192
+ const accepted = await requestExistingServicesConsent(conflict([owner({ state: 'restarting', health: 'unhealthy' })]), {
193
+ question: async () => answer,
194
+ log: (line) => messages.push(line),
195
+ })
196
+
197
+ assert.equal(accepted, true)
198
+ assert.match(messages.join('\n'), /mercato-postgres/)
199
+ assert.match(messages.join('\n'), /restart|unhealthy/i)
200
+ assert.match(messages.join('\n'), /yarn om stop/)
201
+ }
202
+ })
203
+
204
+ test('accepted existing infrastructure continues setup without restarting it and forwards no-infra to dev', async () => {
205
+ const calls = []
206
+ const problem = conflict()
207
+ const ctx = {
208
+ repoRoot: '/repo',
209
+ mode: 'hybrid',
210
+ flags: { noInfra: false, nonInteractive: false, profiles: [] },
211
+ log: () => {},
212
+ runComposeImpl: () => ({ status: 0, stdout: '' }),
213
+ startInfraImpl: async () => {
214
+ calls.push('inspect-existing')
215
+ return { ok: false, problem }
216
+ },
217
+ ensureOpencodeImageImpl: () => assert.fail('accepted existing infrastructure must not rebuild images'),
218
+ confirmExistingServicesImpl: async (found) => {
219
+ assert.deepEqual(found, problem)
220
+ calls.push('consent')
221
+ return true
222
+ },
223
+ }
224
+
225
+ const outcome = await runSteps([
226
+ infraUpStep,
227
+ { id: 'continued', title: 'Continue setup', async apply() { calls.push('continue') } },
228
+ ], ctx)
229
+
230
+ assert.equal(outcome.ok, true)
231
+ assert.equal(ctx.existingInfraAccepted, true)
232
+ assert.equal(ctx.flags.noInfra, true)
233
+ assert.deepEqual(calls, ['inspect-existing', 'consent', 'continue'])
234
+ assert.deepEqual(devRuntimeArgs([], ctx.flags), ['--no-infra'])
235
+ })
236
+
237
+ test('declined infrastructure reuse stops setup and gives the non-destructive stop command', async () => {
238
+ const messages = []
239
+ const outcome = await runSteps([
240
+ infraUpStep,
241
+ { id: 'continued', title: 'Continue setup', async apply() { assert.fail('declined reuse must stop setup') } },
242
+ ], {
243
+ repoRoot: '/repo',
244
+ mode: 'hybrid',
245
+ flags: { noInfra: false, nonInteractive: true, profiles: [] },
246
+ log: (line) => messages.push(line),
247
+ runComposeImpl: () => ({ status: 0, stdout: '' }),
248
+ startInfraImpl: async () => ({ ok: false, problem: conflict() }),
249
+ confirmExistingServicesImpl: async () => false,
250
+ ensureOpencodeImageImpl: () => assert.fail('declined reuse must not mutate images'),
251
+ })
252
+
253
+ assert.equal(outcome.ok, false)
254
+ assert.equal(outcome.failedStep, 'infra-up')
255
+ assert.match(messages.join('\n'), /yarn om stop/)
256
+ })
257
+
258
+
259
+ test('standalone setup accepts existing services only after explicit confirmation', async () => {
260
+ const problem = conflict([owner({ state: 'restarting', health: 'unhealthy' })])
261
+ const calls = []
262
+ const outcome = await ensureInfra({
263
+ projectDir: '/missing-standalone-fixture',
264
+ env: {},
265
+ allowExistingServices: true,
266
+ startImpl: async () => {
267
+ calls.push('detect')
268
+ return { ok: false, problem }
269
+ },
270
+ confirmExistingServices: async (found) => {
271
+ assert.deepEqual(found, problem)
272
+ calls.push('consent')
273
+ return true
274
+ },
275
+ log: () => {},
276
+ error: () => assert.fail('accepted services must not produce a setup failure'),
277
+ })
278
+
279
+ assert.deepEqual(outcome, { ok: true, existingServices: true })
280
+ assert.deepEqual(calls, ['detect', 'consent'])
281
+ })
282
+
283
+ test('standalone setup preserves the conflict when reuse is declined or not enabled', async () => {
284
+ for (const allowExistingServices of [true, false]) {
285
+ let confirmations = 0
286
+ const failure = { ok: false, problem: conflict() }
287
+ const outcome = await ensureInfra({
288
+ projectDir: '/missing-standalone-fixture',
289
+ env: {},
290
+ allowExistingServices,
291
+ startImpl: async () => failure,
292
+ confirmExistingServices: async () => {
293
+ confirmations += 1
294
+ return false
295
+ },
296
+ log: () => {},
297
+ error: () => {},
298
+ })
299
+
300
+ assert.deepEqual(outcome, failure)
301
+ assert.equal(confirmations, allowExistingServices ? 1 : 0)
302
+ assert.equal(outcome.existingServices, undefined)
303
+ }
304
+ })
305
+
306
+ test('standalone setup does not offer reuse for an unavailable Docker daemon', async () => {
307
+ const failure = { ok: false, problem: { code: 'daemon-stopped', detail: 'engine unavailable' } }
308
+ const outcome = await ensureInfra({
309
+ projectDir: '/missing-standalone-fixture',
310
+ env: {},
311
+ allowExistingServices: true,
312
+ startImpl: async () => failure,
313
+ confirmExistingServices: async () => assert.fail('a runtime failure cannot authorize existing-service reuse'),
314
+ log: () => {},
315
+ error: () => {},
316
+ })
317
+
318
+ assert.deepEqual(outcome, failure)
319
+ })
320
+
321
+ test('standalone setup requires consent before using a reachable configured database without Docker', async () => {
322
+ const failure = { ok: false, problem: { code: 'daemon-stopped', detail: 'engine unavailable' } }
323
+ for (const accepted of [false, true]) {
324
+ let confirmations = 0
325
+ const outcome = await ensureInfra({
326
+ projectDir: '/missing-standalone-fixture',
327
+ env: { DATABASE_URL: 'postgres://postgres:postgres@db.example.test:5544/open_mercato' },
328
+ allowExistingServices: true,
329
+ startImpl: async () => failure,
330
+ databaseProbe: async (port, options) => {
331
+ assert.equal(port, 5544)
332
+ assert.equal(options.host, 'db.example.test')
333
+ return true
334
+ },
335
+ confirmExistingServices: async (problem) => {
336
+ confirmations += 1
337
+ assert.equal(problem.configuredServices, true)
338
+ assert.deepEqual(problem.services, [{ service: 'postgres', host: 'db.example.test', port: 5544, state: 'reachable' }])
339
+ return accepted
340
+ },
341
+ log: () => {},
342
+ error: () => {},
343
+ })
344
+
345
+ assert.deepEqual(outcome, accepted ? { ok: true, existingServices: true } : failure)
346
+ assert.equal(confirmations, 1)
347
+ }
348
+ })
349
+
350
+ for (const state of ['running', 'restarting']) {
351
+ test(`setup preserves existing ${state} unhealthy project services before consent`, async () => {
352
+ for (const mode of ['monorepo', 'standalone']) {
353
+ const calls = []
354
+ const startImpl = async (options) => startInfraServices({
355
+ ...options,
356
+ detect: () => ({ ok: true }),
357
+ spawnSyncImpl: (_command, args) => {
358
+ calls.push(args)
359
+ if (!args.includes('ps')) assert.fail('setup must inspect existing unhealthy services without changing containers')
360
+ return { status: 0, stdout: JSON.stringify({ Service: 'postgres', Name: 'existing-postgres', State: state, Health: 'unhealthy' }) }
361
+ },
362
+ beforeUp: () => assert.fail('image preparation must wait for the existing-service decision'),
363
+ portProbe: async () => false,
364
+ containerProbe: () => [],
365
+ processProbe: () => [],
366
+ })
367
+ const confirm = async (problem) => {
368
+ assert.equal(problem.code, 'unhealthy')
369
+ assert.equal(problem.existingServices, true)
370
+ assert.equal(problem.services[0].containerName, 'existing-postgres')
371
+ return true
372
+ }
373
+ if (mode === 'standalone') {
374
+ const outcome = await ensureInfra({ projectDir: '/missing-standalone-fixture', env: {}, allowExistingServices: true, startImpl, confirmExistingServices: confirm, log: () => {}, error: () => assert.fail('reuse must continue') })
375
+ assert.deepEqual(outcome, { ok: true, existingServices: true })
376
+ } else {
377
+ const ctx = { repoRoot: '/repo', mode: 'hybrid', flags: { noInfra: false, nonInteractive: false, profiles: [] }, log: () => {}, startInfraImpl: async (_root, options) => startImpl({ ...options, services: SERVICES, composeArgs: (extra) => ['compose', ...extra] }), confirmExistingServicesImpl: confirm }
378
+ await infraUpStep.apply(ctx)
379
+ assert.equal(ctx.flags.noInfra, true)
380
+ assert.deepEqual(devRuntimeArgs([], ctx.flags), ['--no-infra'])
381
+ }
382
+ assert.equal(calls.length, 1)
383
+ }
384
+ })
385
+ }
386
+
387
+ test('direct infrastructure startup retains its explicit unhealthy-service retry', async () => {
388
+ let prepared = false
389
+ const calls = []
390
+ const outcome = await startInfraServices({
391
+ services: SERVICES,
392
+ composeArgs: (extra) => ['compose', ...extra],
393
+ detect: () => ({ ok: true }),
394
+ spawnSyncImpl: (_command, args) => {
395
+ calls.push(args)
396
+ return { status: 0, stdout: args.includes('ps') ? JSON.stringify({ Service: 'postgres', State: 'running', Health: 'unhealthy' }) : '' }
397
+ },
398
+ beforeUp: () => { prepared = true },
399
+ portProbe: async () => false,
400
+ containerProbe: () => [],
401
+ log: () => {},
402
+ })
403
+ assert.equal(outcome.ok, true)
404
+ assert.equal(prepared, true)
405
+ assert.ok(calls.some((args) => args.includes('up')))
406
+ })
407
+
408
+ test('a failed new startup cannot claim it left existing services untouched', async () => {
409
+ const failure = { ok: false, problem: { code: 'unhealthy', services: [{ service: 'postgres', state: 'running', health: 'unhealthy' }] } }
410
+ const outcome = await ensureInfra({ projectDir: '/missing-standalone-fixture', env: {}, allowExistingServices: true, startImpl: async () => failure, confirmExistingServices: async () => assert.fail('post-startup health failure must remain an error'), log: () => {}, error: () => {} })
411
+ assert.deepEqual(outcome, failure)
412
+ })
@@ -0,0 +1,108 @@
1
+ import assert from 'node:assert/strict'
2
+ import fs from 'node:fs'
3
+ import test from 'node:test'
4
+ import {
5
+ findPortProcessOwners,
6
+ formatInfraProblem,
7
+ parseListenerProcesses,
8
+ requestExistingServicesConsent,
9
+ startInfraServices,
10
+ } from '../infra-preflight.mjs'
11
+
12
+ const service = { service: 'postgres', port: 5432, envKey: 'POSTGRES_PORT' }
13
+ const listener = { pid: 1234, command: 'com.docker.backend' }
14
+ const problem = { code: 'port-conflict', ports: [{ ...service, processes: [listener], containerName: 'mercato-postgres' }] }
15
+
16
+ test('lsof listener records preserve host PIDs and process names without terminal controls', () => {
17
+ assert.deepEqual(parseListenerProcesses('p1234\nccom.docker.backend\np321\ncnode\np321\ncnode\np0\ncignored\np42\nc\u001b[31munsafe\tname\n'), [
18
+ listener, { pid: 321, command: 'node' }, { pid: 42, command: 'unsafe name' },
19
+ ])
20
+ })
21
+
22
+ test('macOS listener discovery is a bounded read-only argument-array invocation', () => {
23
+ let call
24
+ assert.deepEqual(findPortProcessOwners(5432, { platform: 'darwin', spawnSyncImpl: (command, args, options) => {
25
+ call = { command, args, options }
26
+ return { status: 0, stdout: 'p1234\nccom.docker.backend\n' }
27
+ } }), [listener])
28
+ assert.equal(call.command, 'lsof')
29
+ assert.deepEqual(call.args, ['-nP', '-iTCP:5432', '-sTCP:LISTEN', '-Fpc'])
30
+ assert.equal(call.options.timeout, 2000)
31
+ assert.equal(call.options.shell, undefined)
32
+ })
33
+
34
+ test('Linux falls back to ss and Windows reads structured owning-process IDs', () => {
35
+ const commands = []
36
+ const linux = findPortProcessOwners(5432, { platform: 'linux', spawnSyncImpl: (command) => {
37
+ commands.push(command)
38
+ return command === 'lsof' ? { error: { code: 'ENOENT' } } : { status: 0, stdout: 'LISTEN 0 128 0.0.0.0:5432 0.0.0.0:* users:(("postgres",pid=987,fd=7))' }
39
+ } })
40
+ assert.deepEqual(commands, ['lsof', 'ss'])
41
+ assert.deepEqual(linux, [{ pid: 987, command: 'postgres' }])
42
+ const windows = findPortProcessOwners(5432, { platform: 'win32', spawnSyncImpl: (command, args) => {
43
+ assert.equal(command, 'powershell.exe')
44
+ assert.ok(args.includes('-NonInteractive'))
45
+ assert.match(args.at(-1), /Get-NetTCPConnection -State Listen -LocalPort 5432/)
46
+ return { status: 0, stdout: '{"pid":456,"command":"postgres"}' }
47
+ } })
48
+ assert.deepEqual(windows, [{ pid: 456, command: 'postgres' }])
49
+ })
50
+
51
+ test('missing permissions, invalid ports and malformed process output never block diagnosis', () => {
52
+ for (const port of [0, -1, 65536, '5432', '1;kill']) {
53
+ assert.deepEqual(findPortProcessOwners(port, { spawnSyncImpl: () => assert.fail('invalid port must not execute') }), [])
54
+ }
55
+ assert.deepEqual(findPortProcessOwners(5432, { platform: 'darwin', spawnSyncImpl: () => { throw new Error('permission denied') } }), [])
56
+ assert.deepEqual(parseListenerProcesses('not JSON', { format: 'powershell' }), [])
57
+ })
58
+
59
+ test('conflict preflight attaches host listener PIDs without running compose up or image preparation', async () => {
60
+ const calls = []
61
+ const result = await startInfraServices({
62
+ services: [service], composeArgs: (extra) => ['compose', ...extra], detect: () => ({ ok: true }),
63
+ spawnSyncImpl: (_command, args) => { calls.push(args); return { status: 0, stdout: '[]' } },
64
+ containerProbe: () => [{ ...service, containerName: 'previous-postgres', state: 'running' }],
65
+ processProbe: () => [listener], portProbe: async () => true,
66
+ beforeUp: () => assert.fail('must not prepare or mutate containers'), log: () => {},
67
+ })
68
+ assert.deepEqual(result.problem.ports[0].processes, [listener])
69
+ assert.equal(calls.length, 1)
70
+ assert.ok(calls[0].includes('ps'))
71
+ })
72
+
73
+ test('conflicts render separated listener, service/port and environment guidance in plain logs', () => {
74
+ const lines = formatInfraProblem(problem, { output: { isTTY: false }, env: {} })
75
+ const output = lines.join('\n')
76
+ assert.match(output, /Port 5432 \(postgres\) is already in use\./)
77
+ assert.match(output, /Listener PID: 1234 \(com\.docker\.backend\); container: mercato-postgres/)
78
+ assert.match(output, /POSTGRES_PORT in \.env/)
79
+ assert.ok(lines.includes(''))
80
+ assert.doesNotMatch(output, /\u001b\[/)
81
+ const unknown = formatInfraProblem({ code: 'port-conflict', ports: [service] }, { output: { isTTY: false }, env: {} }).join('\n')
82
+ assert.match(unknown, /Listener PID: unavailable/)
83
+ })
84
+
85
+ test('interactive diagnostics color service, port, variables and commands and honor NO_COLOR', () => {
86
+ const options = { output: { isTTY: true }, env: { TERM: 'xterm-256color' } }
87
+ const output = formatInfraProblem(problem, options).join('\n')
88
+ assert.ok(output.includes('\u001b[36mpostgres\u001b[0m'))
89
+ assert.ok(output.includes('\u001b[33m5432\u001b[0m'))
90
+ assert.ok(output.includes('\u001b[35mPOSTGRES_PORT\u001b[0m'))
91
+ assert.ok(output.includes('\u001b[32myarn setup --no-infra\u001b[0m'))
92
+ assert.ok(output.includes('\u001b[32m`yarn om stop`\u001b[0m'))
93
+ for (const env of [{ NO_COLOR: '' }, { TERM: 'dumb' }]) assert.doesNotMatch(formatInfraProblem(problem, { ...options, env }).join('\n'), /\u001b\[/)
94
+ })
95
+
96
+ test('consent separates warning emojis and the continuing paragraph from the answer', async () => {
97
+ const lines = []
98
+ assert.equal(await requestExistingServicesConsent(problem, { input: { isTTY: true }, output: { isTTY: false }, env: {}, question: async () => 'y', log: (line) => lines.push(line) }), true)
99
+ assert.ok(lines.some((line) => line.startsWith(' ⚠️ mercato-postgres')))
100
+ const continuing = lines.findIndex((line) => line.includes('Continuing with'))
101
+ assert.equal(lines[continuing - 1], '')
102
+ assert.ok(lines[continuing].startsWith(' ⚠️ '))
103
+ assert.match(lines.join('\n'), /Listener PID: 1234/)
104
+ })
105
+
106
+ test('standalone preflight stays byte-identical to the shared starter implementation', () => {
107
+ assert.deepEqual(fs.readFileSync(new URL('../infra-preflight.mjs', import.meta.url)), fs.readFileSync(new URL('../../../create-app/template/scripts/dev-infra-preflight.mjs', import.meta.url)))
108
+ })