@open-mercato/starter 0.10.1-develop.7983.1.fd91207efe → 0.10.1-develop.7990.1.82d0a183c5

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,18 @@ 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
+ 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
38
 
39
39
  `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
40
 
41
+ ## Setup logs
42
+
43
+ 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.
44
+
45
+ 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.
46
+
47
+ 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.
48
+
41
49
  ## Design rules
42
50
 
43
51
  - **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.
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.7990.1.82d0a183c5",
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,318 @@
1
+ import assert from 'node:assert/strict'
2
+ import { EventEmitter } from 'node:events'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import test from 'node:test'
7
+
8
+ import { createSetupLogs } from '../setup-logs.mjs'
9
+
10
+ function harness({ isTTY = true, flowing = false, raw = false, ...options } = {}) {
11
+ const input = new EventEmitter()
12
+ Object.assign(input, {
13
+ isTTY,
14
+ isRaw: raw,
15
+ readableFlowing: flowing,
16
+ setRawMode(value) { this.isRaw = value },
17
+ resume() { this.readableFlowing = true },
18
+ pause() { this.readableFlowing = false },
19
+ })
20
+ const chunks = []
21
+ const output = { isTTY, columns: 80, write: (chunk) => chunks.push(chunk) }
22
+ const logs = createSetupLogs({ input, output, env: {}, ...options })
23
+ return { input, output, chunks, logs, text: () => chunks.map(String).join('') }
24
+ }
25
+
26
+ test('compact setup folds, replays with d, streams live, and folds again with D', () => {
27
+ const { input, logs, text } = harness()
28
+ logs.start()
29
+ assert.doesNotMatch(text(), /DEBUG LOGS/)
30
+ assert.match(text(), /Press \[d\] to show or hide raw logs/)
31
+ logs.log('migration %s', 'ready')
32
+ assert.doesNotMatch(text(), /migration ready/)
33
+ input.emit('data', Buffer.from('d'))
34
+ assert.match(text(), /📖 Raw logs shown/)
35
+ assert.match(text(), /migration ready/)
36
+ logs.raw('live output\n')
37
+ assert.match(text(), /live output/)
38
+ const beforeHide = text()
39
+ input.emit('data', 'D')
40
+ assert.equal(text(), beforeHide, 'folding does not add a redundant notice')
41
+ logs.log('hidden again')
42
+ assert.doesNotMatch(text(), /hidden again/)
43
+ logs.stop()
44
+ })
45
+
46
+ test('chunk boundaries and split UTF-8 characters survive buffered replay', () => {
47
+ const { input, logs, text } = harness()
48
+ logs.start()
49
+ logs.raw('first par')
50
+ logs.raw('t\nsecond ')
51
+ const emoji = Buffer.from('✅')
52
+ logs.raw(emoji.subarray(0, 1))
53
+ logs.raw(emoji.subarray(1))
54
+ logs.show('failure details')
55
+ assert.match(text(), /first part\n second ✅/)
56
+ logs.raw(' done\n')
57
+ assert.match(text(), /second ✅ done\n/)
58
+ input.emit('data', 'd')
59
+ logs.stop()
60
+ })
61
+
62
+ test('buffer keeps only the newest lines and caps an unterminated line', () => {
63
+ const { logs, text } = harness()
64
+ logs.start()
65
+ for (let index = 0; index < 250; index++) logs.log(`line:${index}:end`)
66
+ logs.raw('x'.repeat(50000))
67
+ logs.show()
68
+ assert.doesNotMatch(text(), /line:49:end/)
69
+ assert.match(text(), /line:50:end/)
70
+ assert.match(text(), /line:249:end/)
71
+ assert.equal(text().match(/x/g)?.length, 4096)
72
+ logs.stop()
73
+ })
74
+
75
+ test('start, suspend, resume and stop restore raw mode, flow and listeners', () => {
76
+ for (const previousRaw of [true, false]) {
77
+ for (const previousFlowing of [true, false]) {
78
+ const { input, logs } = harness({ raw: previousRaw, flowing: previousFlowing })
79
+ input.encoding = 'latin1'
80
+ logs.start()
81
+ logs.start()
82
+ assert.equal(input.listenerCount('data'), 1)
83
+ assert.equal(input.isRaw, true)
84
+ assert.equal(input.readableFlowing, true)
85
+ logs.suspend()
86
+ assert.equal(input.listenerCount('data'), 0)
87
+ assert.equal(input.isRaw, previousRaw)
88
+ assert.equal(input.readableFlowing, previousFlowing)
89
+ assert.equal(input.encoding, 'latin1')
90
+ logs.resume()
91
+ assert.equal(input.listenerCount('data'), 1)
92
+ logs.stop()
93
+ logs.stop()
94
+ assert.equal(input.listenerCount('data'), 0)
95
+ assert.equal(input.isRaw, previousRaw)
96
+ assert.equal(input.readableFlowing, previousFlowing)
97
+ }
98
+ }
99
+ })
100
+
101
+ test('Ctrl+C uses the interrupt callback and suspended prompts do not consume d', () => {
102
+ let interrupts = 0
103
+ const { input, logs, text } = harness({ onInterrupt: () => interrupts++ })
104
+ logs.start()
105
+ input.emit('data', '\u0003')
106
+ assert.equal(interrupts, 1)
107
+ logs.suspend()
108
+ input.emit('data', 'd')
109
+ assert.doesNotMatch(text(), /📖 Raw logs shown/)
110
+ logs.resume()
111
+ input.emit('data', 'd')
112
+ assert.match(text(), /📖 Raw logs shown/)
113
+ logs.stop()
114
+ })
115
+
116
+ test('empty buffer has the same hint as dev and NO_COLOR removes ANSI', () => {
117
+ const { logs, text } = harness({ env: { NO_COLOR: '1' } })
118
+ logs.start()
119
+ logs.show()
120
+ assert.match(text(), /📭 No buffered logs yet/)
121
+ assert.doesNotMatch(text(), /\u001b\[/)
122
+ logs.stop()
123
+ })
124
+
125
+ test('noninteractive, verbose, CI and dumb terminals preserve raw output without toggles', () => {
126
+ for (const options of [
127
+ { isTTY: false },
128
+ { verbose: true },
129
+ { nonInteractive: true },
130
+ { env: { CI: 'true' } },
131
+ { env: { TERM: 'dumb' } },
132
+ { env: { MERCATO_DEV_OUTPUT: 'verbose' } },
133
+ ]) {
134
+ const { logs, input, chunks, text } = harness(options)
135
+ assert.equal(logs.interactive, false)
136
+ logs.start()
137
+ logs.resume()
138
+ const bytes = Buffer.from('raw\r\n✅\n')
139
+ logs.raw(bytes)
140
+ logs.log('status %d', 2)
141
+ logs.show('failure')
142
+ logs.stop()
143
+ assert.equal(chunks[0], bytes)
144
+ assert.equal(text(), 'raw\r\n✅\nstatus 2\n')
145
+ assert.equal(input.listenerCount('data'), 0)
146
+ }
147
+ })
148
+
149
+ function temporaryRepo(t) {
150
+ const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mercato-setup-logs-'))
151
+ t.after(() => fs.rmSync(repoRoot, { recursive: true, force: true }))
152
+ return repoRoot
153
+ }
154
+
155
+ test('full output is saved while the terminal buffer stays bounded, including across restarts', (t) => {
156
+ const repoRoot = temporaryRepo(t)
157
+ const { logs, text } = harness({ repoRoot, env: { OM_DEV_RUN_ID: 'test-run' } })
158
+ logs.start()
159
+ const file = path.join(repoRoot, '.mercato', 'logs', 'test-run-setup-raw.log')
160
+ assert.equal(logs.logFile, file)
161
+ assert.match(text(), /📝 Verbose logs/)
162
+ assert.ok(text().includes(file))
163
+ const full = Array.from({ length: 400 }, (_, index) => `line ${index}\n`).join('') + 'x'.repeat(50000)
164
+ logs.raw(full)
165
+ logs.stop()
166
+ assert.equal(fs.readFileSync(file, 'utf8'), full)
167
+ logs.start()
168
+ logs.raw(Buffer.from('\nlast output\n'))
169
+ logs.stop()
170
+ assert.equal(logs.logFile, file)
171
+ assert.equal(fs.readFileSync(file, 'utf8'), `${full}\nlast output\n`)
172
+ })
173
+
174
+ test('CI and verbose modes announce and save the same raw file while passing output through', (t) => {
175
+ for (const options of [{ env: { CI: 'true' } }, { verbose: true }]) {
176
+ const repoRoot = temporaryRepo(t)
177
+ const { logs, text } = harness({ repoRoot, ...options })
178
+ logs.start()
179
+ logs.raw('stdout\nstderr\n')
180
+ logs.stop()
181
+ assert.match(text(), /📝 Verbose logs/)
182
+ assert.match(text(), /stdout\nstderr\n/)
183
+ assert.equal(fs.readFileSync(logs.logFile, 'utf8'), 'stdout\nstderr\n')
184
+ }
185
+ })
186
+
187
+ test('log path controls use the dev conventions and run IDs cannot escape the log directory', (t) => {
188
+ const repoRoot = temporaryRepo(t)
189
+ const { logs } = harness({
190
+ repoRoot,
191
+ name: 'infra',
192
+ env: { OM_DEV_LOG_DIR: 'custom-logs', OM_DEV_RUN_ID: '../../outside' },
193
+ })
194
+ logs.start()
195
+ logs.stop()
196
+ assert.equal(path.dirname(logs.logFile), path.join(repoRoot, 'custom-logs'))
197
+ assert.ok(logs.logFile.endsWith('-infra-raw.log'))
198
+ for (const disabled of ['0', 'false']) {
199
+ const { logs: disabledLogs, text } = harness({ repoRoot, env: { OM_DEV_LOG_TEE: disabled } })
200
+ disabledLogs.start()
201
+ disabledLogs.raw('not saved\n')
202
+ disabledLogs.stop()
203
+ assert.equal(disabledLogs.logFile, null)
204
+ assert.doesNotMatch(text(), /Verbose logs/)
205
+ }
206
+ })
207
+
208
+ test('file creation failure warns once and leaves terminal output usable', (t) => {
209
+ const repoRoot = temporaryRepo(t)
210
+ fs.writeFileSync(path.join(repoRoot, '.mercato'), 'not a directory')
211
+ const { logs, text } = harness({ repoRoot, isTTY: false })
212
+ logs.start()
213
+ logs.raw('still running\n')
214
+ logs.raw('next line\n')
215
+ logs.stop()
216
+ assert.equal(logs.logFile, null)
217
+ assert.equal(text().match(/Could not save setup logs/g).length, 1)
218
+ assert.match(text(), /still running\nnext line\n/)
219
+ })
220
+
221
+ test('append failure does not abort setup or prevent raw logs from being revealed', (t) => {
222
+ const repoRoot = temporaryRepo(t)
223
+ const { logs, text } = harness({ repoRoot })
224
+ logs.start()
225
+ fs.rmSync(logs.logFile)
226
+ fs.mkdirSync(logs.logFile)
227
+ logs.raw('details after disk failure\n')
228
+ logs.show('command failed')
229
+ logs.stop()
230
+ assert.match(text(), /Could not save setup logs/)
231
+ assert.match(text(), /details after disk failure/)
232
+ })
233
+
234
+ test('record saves summaries without duplicating them in terminal output or buffered replay', (t) => {
235
+ const repoRoot = temporaryRepo(t)
236
+ const { logs, text } = harness({ repoRoot })
237
+ logs.start()
238
+ logs.record('Step %d: build', 6)
239
+ logs.log('compiler output')
240
+ logs.show()
241
+ logs.stop()
242
+ assert.doesNotMatch(text(), /Step 6: build/)
243
+ assert.match(text(), /compiler output/)
244
+ assert.equal(fs.readFileSync(logs.logFile, 'utf8'), 'Step 6: build\ncompiler output\n')
245
+ })
246
+
247
+
248
+ test('reopening logs or revealing a failure never repeats output already displayed', (t) => {
249
+ const repoRoot = temporaryRepo(t)
250
+ const { input, logs, text } = harness({ repoRoot })
251
+ logs.start()
252
+ logs.log('compiler detail: packages ready')
253
+ input.emit('data', 'd')
254
+ logs.log('live compiler detail')
255
+ input.emit('data', 'd')
256
+ logs.log('new migration diagnostic')
257
+ logs.show('Database failed')
258
+ logs.stop()
259
+ for (const detail of ['compiler detail: packages ready', 'live compiler detail', 'new migration diagnostic']) {
260
+ assert.equal(text().split(detail).length - 1, 1, detail + ' appears once')
261
+ }
262
+ assert.doesNotMatch(text(), /Raw logs hidden/)
263
+ assert.equal(fs.readFileSync(logs.logFile, 'utf8'), 'compiler detail: packages ready\nlive compiler detail\nnew migration diagnostic\n')
264
+ })
265
+
266
+ test('folding a partial live line adds only a newline before resuming progress', () => {
267
+ const { input, logs, text } = harness()
268
+ logs.start()
269
+ logs.raw('compiler par')
270
+ input.emit('data', 'd')
271
+ logs.raw('tial')
272
+ const beforeHide = text()
273
+ input.emit('data', 'd')
274
+ assert.equal(text(), beforeHide + '\n')
275
+ logs.raw('new hidden tail')
276
+ input.emit('data', 'd')
277
+ assert.equal(text().split('compiler partial').length - 1, 1)
278
+ assert.match(text(), /new hidden tail/)
279
+ logs.stop()
280
+ })
281
+
282
+
283
+ test('compact emoji hints and setup messages share padding without backgrounds or borders', () => {
284
+ const { logs, text } = harness()
285
+ logs.start()
286
+ logs.raw('compiler par')
287
+ logs.show()
288
+ logs.raw('tial\nnext line\n')
289
+ logs.stop()
290
+ assert.match(text(), / 📋 Press \[d\]/)
291
+ assert.doesNotMatch(text(), /\x1b\[(?:4[0-9]|10[0-7])|━|DEBUG LOGS/)
292
+ assert.doesNotMatch(text(), /\x1b\[46/)
293
+ assert.match(text(), /\n compiler partial\n next line\n/)
294
+ })
295
+
296
+
297
+ test('starter-generated details align with raw child output without altering the saved file', (t) => {
298
+ const repoRoot = temporaryRepo(t)
299
+ const { logs, text } = harness({ repoRoot })
300
+ logs.start()
301
+ logs.log(' generated status')
302
+ logs.raw('child diagnostic\n')
303
+ logs.show()
304
+ logs.stop()
305
+ assert.match(text(), /\n generated status\n child diagnostic\n/)
306
+ assert.equal(fs.readFileSync(logs.logFile, 'utf8'), ' generated status\nchild diagnostic\n')
307
+ })
308
+
309
+
310
+ test('live carriage-return progress keeps the same left margin', () => {
311
+ const { logs, text } = harness()
312
+ logs.start()
313
+ logs.show()
314
+ const before = text()
315
+ logs.raw('first\rsecond\r\nthird')
316
+ assert.equal(text().slice(before.length), ' first\r second\r\n third')
317
+ logs.stop()
318
+ })
@@ -0,0 +1,307 @@
1
+ import assert from 'node:assert/strict'
2
+ import { spawnSync } from 'node:child_process'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { EventEmitter } from 'node:events'
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import test from 'node:test'
9
+
10
+ import { runStreaming, stopStreamingChild } from '../compose.mjs'
11
+ import { STARTER_STATE_DIR } from '../constants.mjs'
12
+ import { startInfraServices } from '../infra-preflight.mjs'
13
+ import { createSetupLogs } from '../setup-logs.mjs'
14
+ import { databaseStep, runSteps, StepBlocked, workspaceBuildStep } from '../steps.mjs'
15
+
16
+ function deferred() {
17
+ let resolve
18
+ const promise = new Promise((done) => { resolve = done })
19
+ return { promise, resolve }
20
+ }
21
+
22
+ function stubLogs() {
23
+ const events = []
24
+ const rawLines = []
25
+ const recorded = []
26
+ let active = false
27
+ return {
28
+ events, rawLines, recorded,
29
+ get active() { return active },
30
+ start() { events.push('start'); active = true },
31
+ stop() { events.push('stop'); active = false },
32
+ suspend() { events.push('suspend'); active = false },
33
+ resume() { events.push('resume'); active = true },
34
+ show(reason) { events.push(`show:${reason}`) },
35
+ raw(chunk) { rawLines.push(String(chunk)) },
36
+ log(...args) { rawLines.push(args.join(' ')) },
37
+ record(...args) { recorded.push(args.join(' ')) },
38
+ }
39
+ }
40
+
41
+ function temporaryRepo(t) {
42
+ const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mercato-setup-streaming-'))
43
+ t.after(() => fs.rmSync(repoRoot, { recursive: true, force: true }))
44
+ return repoRoot
45
+ }
46
+
47
+ test('runStreaming captures stdout and stderr while the child runs, then waits for close', async () => {
48
+ const chunks = []
49
+ const firstOutput = deferred()
50
+ let finished = false
51
+ const running = runStreaming(process.execPath, ['-e', "process.stdout.write('build started\\n'); setTimeout(() => { process.stderr.write('build diagnostic\\n'); process.exitCode = 0 }, 80)"], {
52
+ logs: { raw(chunk) { chunks.push(String(chunk)); firstOutput.resolve() } },
53
+ }).then((code) => { finished = true; return code })
54
+ await firstOutput.promise
55
+ assert.equal(finished, false, 'output arrives before the child completes')
56
+ assert.equal(await running, 0)
57
+ assert.match(chunks.join(''), /build started/)
58
+ assert.match(chunks.join(''), /build diagnostic/)
59
+ })
60
+
61
+ test('runStreaming preserves nonzero exits and reports spawn errors', async () => {
62
+ const chunks = []
63
+ const status = await runStreaming(process.execPath, ['-e', "process.stderr.write('failed command\\n'); process.exitCode = 7"], {
64
+ logs: { raw(chunk) { chunks.push(String(chunk)) } },
65
+ })
66
+ assert.equal(status, 7)
67
+ assert.equal(chunks.join(''), 'failed command\n')
68
+ await assert.rejects(runStreaming(path.join(os.tmpdir(), 'mercato-nonexistent-command'), [], { logs: stubLogs() }), /could not be executed/)
69
+ })
70
+
71
+ test('runSteps keeps progress visible, folds routine details, and suspends toggles for prompts', async () => {
72
+ const visible = []
73
+ const originalLog = (...args) => visible.push(args.join(' '))
74
+ const logs = stubLogs()
75
+ const ctx = { log: originalLog, logs, flags: {} }
76
+ const outcome = await runSteps([
77
+ {
78
+ id: 'build', title: 'Build packages',
79
+ async check(context) { context.log('routine build probe'); return { ok: false, detail: 'packages need rebuilding' } },
80
+ async apply(context) { context.log('compiler detail'); assert.equal(logs.active, true); context.installChanged = true },
81
+ },
82
+ {
83
+ id: 'provider', title: 'AI provider', interactive: true,
84
+ async apply(context) { assert.equal(logs.active, false); context.log('Choose a provider:') },
85
+ },
86
+ { id: 'ready', title: 'Ready', async check() { return { ok: true, detail: 'already configured' } } },
87
+ ], ctx)
88
+ assert.deepEqual(outcome, { ok: true })
89
+ assert.match(visible.join('\n'), /Step 1\/3.*Build packages/)
90
+ assert.match(visible.join('\n'), /packages need rebuilding/)
91
+ assert.match(visible.join('\n'), /Choose a provider:/)
92
+ assert.match(visible.join('\n'), /already configured.*skipped/)
93
+ assert.doesNotMatch(visible.join('\n'), /routine build probe|compiler detail/)
94
+ assert.deepEqual(logs.rawLines, ['routine build probe', 'compiler detail'])
95
+ assert.match(logs.recorded.join('\n'), /Step 1\/3.*Build packages/)
96
+ assert.deepEqual(logs.events, ['start', 'suspend', 'resume', 'stop'])
97
+ assert.equal(ctx.log, originalLog)
98
+ assert.equal(ctx.installChanged, true, 'step mutations survive output routing')
99
+ assert.equal(logs.active, false)
100
+ })
101
+
102
+ test('runSteps reveals failure output before diagnostics and always restores the original logger', async () => {
103
+ for (const error of [new Error('compiler failed'), new StepBlocked('build', ['Install the missing prerequisite'])]) {
104
+ const order = []
105
+ const originalLog = (...args) => order.push(args.join(' '))
106
+ const logs = stubLogs()
107
+ logs.show = (reason) => { order.push(`revealed:${reason}`) }
108
+ const ctx = { log: originalLog, logs, flags: {} }
109
+ const outcome = await runSteps([
110
+ { id: 'build', title: 'Build', async apply(context) { context.log('raw failure detail'); throw error } },
111
+ { id: 'later', title: 'Later', async apply() { assert.fail('pipeline must stop after failure') } },
112
+ ], ctx)
113
+ assert.equal(outcome.ok, false)
114
+ assert.equal(outcome[error instanceof StepBlocked ? 'blockedStep' : 'failedStep'], 'build')
115
+ const revealIndex = order.findIndex((line) => line.startsWith('revealed:'))
116
+ const diagnosticIndex = order.findIndex((line) => line.includes(error instanceof StepBlocked ? 'blocked —' : 'compiler failed'))
117
+ assert.ok(revealIndex >= 0 && diagnosticIndex > revealIndex)
118
+ assert.equal(logs.events.at(-1), 'stop')
119
+ assert.equal(ctx.log, originalLog)
120
+ }
121
+ })
122
+
123
+ test('a real log controller releases raw input listeners after both success and failure', async () => {
124
+ for (const fail of [false, true]) {
125
+ const input = new EventEmitter()
126
+ Object.assign(input, {
127
+ isTTY: true, isRaw: false, readableFlowing: false,
128
+ setRawMode(value) { this.isRaw = value },
129
+ resume() { this.readableFlowing = true },
130
+ pause() { this.readableFlowing = false },
131
+ })
132
+ const output = { isTTY: true, columns: 80, write() {} }
133
+ const logs = createSetupLogs({ input, output, env: {} })
134
+ await runSteps([{ id: 'work', title: 'Work', async apply() { if (fail) throw new Error('failed') } }], { logs, log() {}, flags: {} })
135
+ assert.equal(input.listenerCount('data'), 0)
136
+ assert.equal(input.isRaw, false)
137
+ assert.equal(input.readableFlowing, false)
138
+ }
139
+ })
140
+
141
+ test('workspace build awaits each async command and stops before generation on failure', async () => {
142
+ const firstBuild = deferred()
143
+ const invoked = []
144
+ const ctx = { runYarnImpl: async (_ctx, args) => { invoked.push(args[0]); if (invoked.length === 1) await firstBuild.promise } }
145
+ const running = workspaceBuildStep.apply(ctx)
146
+ assert.deepEqual(invoked, ['build:packages'])
147
+ firstBuild.resolve()
148
+ await running
149
+ assert.deepEqual(invoked, ['build:packages', 'generate', 'build:packages'])
150
+
151
+ const failed = []
152
+ await assert.rejects(workspaceBuildStep.apply({ runYarnImpl: async (_ctx, args) => { failed.push(args[0]); throw new Error('build broke') } }), /build broke/)
153
+ assert.deepEqual(failed, ['build:packages'])
154
+ })
155
+
156
+ test('database setup does not mark pending or failed migrations as complete', async (t) => {
157
+ const repoRoot = temporaryRepo(t)
158
+ const migration = deferred()
159
+ const invocations = []
160
+ const ctx = {
161
+ repoRoot, env: {}, flags: { noInfra: true }, log() {},
162
+ dbMigrationsMarker: 'db-migrations-test', dbMarker: 'db-initialized-test', migrationsFingerprint: 'fingerprint',
163
+ runStreamingImpl: async (_command, args) => { invocations.push(args[0]); return migration.promise },
164
+ }
165
+ const migrationsFile = path.join(repoRoot, STARTER_STATE_DIR, ctx.dbMigrationsMarker)
166
+ const initializedFile = path.join(repoRoot, STARTER_STATE_DIR, ctx.dbMarker)
167
+ const running = databaseStep.apply(ctx)
168
+ assert.equal(fs.existsSync(migrationsFile), false)
169
+ assert.equal(fs.existsSync(initializedFile), false)
170
+ migration.resolve(2)
171
+ await assert.rejects(running, /db:migrate failed \(exit 2\)/)
172
+ assert.deepEqual(invocations, ['db:migrate'])
173
+ assert.equal(fs.existsSync(migrationsFile), false)
174
+ assert.equal(fs.existsSync(initializedFile), false)
175
+ })
176
+
177
+ test('database setup records successful migration but never a failed initialization', async (t) => {
178
+ const repoRoot = temporaryRepo(t)
179
+ const ctx = {
180
+ repoRoot, env: {}, flags: { noInfra: true }, log() {},
181
+ dbMigrationsMarker: 'db-migrations-test', dbMarker: 'db-initialized-test', migrationsFingerprint: 'fingerprint',
182
+ runStreamingImpl: async (_command, args) => args[0] === 'db:migrate' ? 0 : 3,
183
+ }
184
+ await assert.rejects(databaseStep.apply(ctx), /initialize.*failed \(exit 3\)/)
185
+ assert.equal(fs.readFileSync(path.join(repoRoot, STARTER_STATE_DIR, ctx.dbMigrationsMarker), 'utf8'), 'fingerprint\n')
186
+ assert.equal(fs.existsSync(path.join(repoRoot, STARTER_STATE_DIR, ctx.dbMarker)), false)
187
+ })
188
+
189
+ test('infrastructure awaits asynchronous image preparation before streaming compose up', async () => {
190
+ const preparation = deferred()
191
+ const order = []
192
+ const services = [{ service: 'postgres', port: 5432, envKey: 'POSTGRES_PORT' }]
193
+ const running = startInfraServices({
194
+ composeArgs: (args) => ['compose', ...args], services, cwd: '/repo',
195
+ detect: () => ({ ok: true }), portProbe: async () => false, log() {},
196
+ spawnSyncImpl: (_command, args) => {
197
+ assert.ok(args.includes('ps'), 'sync runner is only used for short probes')
198
+ return { status: 0, stdout: '[]' }
199
+ },
200
+ beforeUp: async () => { order.push('prepare:start'); await preparation.promise; order.push('prepare:done') },
201
+ runStreamingImpl: async (command, args, options) => {
202
+ order.push('compose:up')
203
+ assert.equal(command, 'docker')
204
+ assert.deepEqual(args, ['compose', 'up', '-d', '--wait'])
205
+ assert.equal(options.cwd, '/repo')
206
+ return { status: 0 }
207
+ },
208
+ })
209
+ // The port check yields before image preparation begins.
210
+ await new Promise((resolve) => setImmediate(resolve))
211
+ assert.deepEqual(order, ['prepare:start'])
212
+ preparation.resolve()
213
+ assert.deepEqual(await running, { ok: true, reused: [] })
214
+ assert.deepEqual(order, ['prepare:start', 'prepare:done', 'compose:up'])
215
+ })
216
+
217
+ test('d reveals logs while a real child is still running', async () => {
218
+ const input = new EventEmitter()
219
+ Object.assign(input, {
220
+ isTTY: true, isRaw: false, readableFlowing: false,
221
+ setRawMode(value) { this.isRaw = value },
222
+ resume() { this.readableFlowing = true },
223
+ pause() { this.readableFlowing = false },
224
+ })
225
+ const output = []
226
+ const logs = createSetupLogs({ input, output: { isTTY: true, columns: 80, write(chunk) { output.push(String(chunk)) } }, env: {} })
227
+ const firstOutput = deferred()
228
+ let finished = false
229
+ logs.start()
230
+ try {
231
+ const running = runStreaming(process.execPath, ['-e', "process.stdout.write('migration started\\n'); setTimeout(() => process.stdout.write('migration done\\n'), 80)"], {
232
+ logs: { raw(chunk) { logs.raw(chunk); firstOutput.resolve() } },
233
+ }).then((code) => { finished = true; return code })
234
+ await firstOutput.promise
235
+ assert.equal(finished, false)
236
+ assert.doesNotMatch(output.join(''), /migration started/)
237
+ input.emit('data', 'd')
238
+ assert.match(output.join(''), /migration started/)
239
+ assert.equal(await running, 0)
240
+ assert.match(output.join(''), /migration done/)
241
+ } finally {
242
+ logs.stop()
243
+ }
244
+ })
245
+
246
+ test('async infrastructure failure retains unhealthy service guidance', async () => {
247
+ let listed = 0
248
+ const outcome = await startInfraServices({
249
+ composeArgs: (args) => ['compose', ...args],
250
+ services: [{ service: 'postgres', port: 5432, envKey: 'POSTGRES_PORT' }],
251
+ detect: () => ({ ok: true }), portProbe: async () => false, log() {},
252
+ spawnSyncImpl: () => ({ status: 0, stdout: ++listed === 1 ? '[]' : JSON.stringify([{ Service: 'postgres', State: 'running', Health: 'unhealthy' }]) }),
253
+ runStreamingImpl: async () => ({ status: 1 }),
254
+ })
255
+ assert.equal(outcome.ok, false)
256
+ assert.equal(outcome.problem.code, 'unhealthy')
257
+ assert.equal(outcome.problem.services[0].service, 'postgres')
258
+ assert.equal(outcome.problem.logsCommand, 'docker compose logs postgres')
259
+ })
260
+
261
+
262
+ test('streamed children inherit stdin outside compact mode and release signal listeners', async () => {
263
+ const before = ['SIGINT', 'SIGTERM'].map((name) => process.listenerCount(name))
264
+ for (const interactive of [true, false]) {
265
+ let options
266
+ const child = new EventEmitter()
267
+ const running = runStreaming(process.execPath, [], {
268
+ logs: { interactive, raw() {} },
269
+ spawnImpl(_command, _args, passed) { options = passed; queueMicrotask(() => child.emit('close', 0)); return child },
270
+ })
271
+ assert.equal(options.stdio[0], interactive ? 'ignore' : 'inherit')
272
+ assert.equal(await running, 0)
273
+ }
274
+ assert.deepEqual(['SIGINT', 'SIGTERM'].map((name) => process.listenerCount(name)), before)
275
+ })
276
+
277
+ test('interrupts stop the Windows child tree and POSIX process group, with a child fallback', () => {
278
+ const calls = []
279
+ const child = { pid: 12345, kill: (signal) => calls.push(['child', signal]) }
280
+ stopStreamingChild(child, 'SIGINT', { platform: 'win32', spawnSyncImpl(command, args, options) {
281
+ calls.push([command, args, options.windowsHide]); return { status: 0 }
282
+ } })
283
+ assert.deepEqual(calls, [['taskkill', ['/pid', '12345', '/T', '/F'], true]])
284
+ calls.length = 0
285
+ stopStreamingChild(child, 'SIGTERM', { platform: 'linux', killImpl: (pid, signal) => calls.push([pid, signal]) })
286
+ assert.deepEqual(calls, [[-12345, 'SIGTERM']])
287
+ calls.length = 0
288
+ stopStreamingChild(child, 'SIGINT', { platform: 'win32', spawnSyncImpl: () => ({ status: 1 }) })
289
+ assert.deepEqual(calls, [['child', 'SIGINT']])
290
+ })
291
+
292
+
293
+ test('infra CLI saves actionable preflight diagnostics even when no child produces logs', (t) => {
294
+ const repoRoot = temporaryRepo(t)
295
+ fs.writeFileSync(path.join(repoRoot, 'package.json'), JSON.stringify({ name: 'open-mercato' }))
296
+ const result = spawnSync(process.execPath, [fileURLToPath(new URL('../cli.mjs', import.meta.url)), 'infra', 'up'], {
297
+ cwd: repoRoot,
298
+ env: { ...process.env, PATH: repoRoot, OM_DEV_RUN_ID: 'preflight', OM_DEV_LOG_DIR: '.mercato/logs', OM_DEV_LOG_TEE: '1' },
299
+ encoding: 'utf8', timeout: 10000,
300
+ })
301
+ assert.equal(result.status, 2, result.stderr)
302
+ const file = path.join(repoRoot, '.mercato', 'logs', 'preflight-infra-raw.log')
303
+ const saved = fs.readFileSync(file, 'utf8')
304
+ assert.match(result.stdout, /Verbose logs.*preflight-infra-raw.log/)
305
+ assert.match(saved, /Docker CLI.*not found|docker.*not found/i)
306
+ assert.match(saved, /yarn om doctor/)
307
+ })