@open-mercato/starter 0.10.1-develop.7994.1.c9f31972aa → 0.10.1-develop.8022.1.b6753de892

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.
@@ -68,6 +68,38 @@ test('runStreaming preserves nonzero exits and reports spawn errors', async () =
68
68
  await assert.rejects(runStreaming(path.join(os.tmpdir(), 'mercato-nonexistent-command'), [], { logs: stubLogs() }), /could not be executed/)
69
69
  })
70
70
 
71
+ test('interrupting an ephemeral build unwinds through service cleanup before exiting', { skip: process.platform === 'win32' ? 'requires POSIX signal delivery' : false }, (t) => {
72
+ const repoRoot = temporaryRepo(t)
73
+ const envFile = path.join(repoRoot, '.env')
74
+ const original = 'DATABASE_URL=postgres://original/db\n'
75
+ fs.writeFileSync(envFile, original)
76
+ const script = `
77
+ import fs from 'node:fs'
78
+ import { runStreaming } from ${JSON.stringify(new URL('../compose.mjs', import.meta.url).href)}
79
+ import { runSteps, workspaceBuildStep } from ${JSON.stringify(new URL('../steps.mjs', import.meta.url).href)}
80
+ const envFile = ${JSON.stringify(envFile)}
81
+ const original = fs.readFileSync(envFile, 'utf8')
82
+ const ctx = {
83
+ repoRoot: ${JSON.stringify(repoRoot)}, flags: { serviceMode: 'ephemeral' }, log() {},
84
+ runStreamingImpl: (_command, _args, options) => runStreaming(process.execPath,
85
+ ['-e', "process.kill(process.ppid, 'SIGTERM'); setInterval(() => {}, 1000)"], options),
86
+ }
87
+ process.once('SIGTERM', () => { ctx.cancelled = true })
88
+ fs.writeFileSync(envFile, 'DATABASE_URL=postgres://ephemeral/db\\n')
89
+ try {
90
+ const outcome = await runSteps([workspaceBuildStep], ctx)
91
+ if (outcome.ok) throw new Error('interrupted setup unexpectedly succeeded')
92
+ } finally {
93
+ fs.writeFileSync(envFile, original)
94
+ }
95
+ process.exitCode = 143
96
+ `
97
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', timeout: 15_000 })
98
+ assert.equal(result.error, undefined)
99
+ assert.equal(result.status, 143, result.stderr)
100
+ assert.equal(fs.readFileSync(envFile, 'utf8'), original)
101
+ })
102
+
71
103
  test('runSteps keeps progress visible, folds routine details, and suspends toggles for prompts', async () => {
72
104
  const visible = []
73
105
  const originalLog = (...args) => visible.push(args.join(' '))
@@ -159,6 +191,7 @@ test('database setup does not mark pending or failed migrations as complete', as
159
191
  const invocations = []
160
192
  const ctx = {
161
193
  repoRoot, env: {}, flags: { noInfra: true }, log() {},
194
+ assertDatabaseWriteAllowedImpl: async () => ({ remote: false }),
162
195
  dbMigrationsMarker: 'db-migrations-test', dbMarker: 'db-initialized-test', migrationsFingerprint: 'fingerprint',
163
196
  runStreamingImpl: async (_command, args) => { invocations.push(args[0]); return migration.promise },
164
197
  }
@@ -178,6 +211,7 @@ test('database setup records successful migration but never a failed initializat
178
211
  const repoRoot = temporaryRepo(t)
179
212
  const ctx = {
180
213
  repoRoot, env: {}, flags: { noInfra: true }, log() {},
214
+ assertDatabaseWriteAllowedImpl: async () => ({ remote: false }),
181
215
  dbMigrationsMarker: 'db-migrations-test', dbMarker: 'db-initialized-test', migrationsFingerprint: 'fingerprint',
182
216
  runStreamingImpl: async (_command, args) => args[0] === 'db:migrate' ? 0 : 3,
183
217
  }
@@ -186,6 +220,39 @@ test('database setup records successful migration but never a failed initializat
186
220
  assert.equal(fs.existsSync(path.join(repoRoot, STARTER_STATE_DIR, ctx.dbMarker)), false)
187
221
  })
188
222
 
223
+ test('database setup keeps the initialization credentials visible when output is folded', async (t) => {
224
+ const repoRoot = temporaryRepo(t)
225
+ const rule = `\u001b[48;2;57;62;70m${'━'.repeat(30)}\u001b[0m`
226
+ const panel = [
227
+ rule,
228
+ `\u001b[48;2;57;62;70m${' '.repeat(30)}\u001b[0m`,
229
+ `\u001b[48;2;57;62;70m 🔑 DEVELOPMENT ACCOUNTS \u001b[0m`,
230
+ `\u001b[48;2;57;62;70m Email: admin@acme.com\u001b[0m`,
231
+ `\u001b[48;2;57;62;70m Password: secret \u001b[0m`,
232
+ rule,
233
+ ]
234
+ const folded = []
235
+ const visible = []
236
+ const logs = { interactive: true, raw: (chunk) => folded.push(chunk), suspend() {}, resume() {}, resumeActivity() {} }
237
+ const ctx = {
238
+ repoRoot, env: {}, flags: { noInfra: true }, log() {}, logs,
239
+ promptLog: (line) => visible.push(line),
240
+ assertDatabaseWriteAllowedImpl: async () => ({ remote: false }),
241
+ dbMigrationsMarker: 'db-migrations-test', dbMarker: 'db-initialized-test', migrationsFingerprint: 'fingerprint',
242
+ runStreamingImpl: async (_command, args, options) => {
243
+ if (args[0] === 'initialize') {
244
+ const output = ['Seeding demo data...', ...panel, 'Done.\n'].join('\n')
245
+ options.logs.raw(output.slice(0, 120))
246
+ options.logs.raw(output.slice(120))
247
+ }
248
+ return 0
249
+ },
250
+ }
251
+ await databaseStep.apply(ctx)
252
+ assert.ok(folded.join('').includes('Password: secret'))
253
+ assert.deepEqual(visible, panel.map((line) => ` ${line}`))
254
+ })
255
+
189
256
  test('infrastructure awaits asynchronous image preparation before streaming compose up', async () => {
190
257
  const preparation = deferred()
191
258
  const order = []
@@ -6,7 +6,7 @@ import path from 'node:path'
6
6
  import { spawnSync } from 'node:child_process'
7
7
  import test from 'node:test'
8
8
  import vm from 'node:vm'
9
- import { createSpinner } from '../ui.mjs'
9
+ import { createSpinner, statusLine } from '../ui.mjs'
10
10
  import { createSetupLogs } from '../setup-logs.mjs'
11
11
  import { llmProviderStep, runSteps } from '../steps.mjs'
12
12
 
@@ -21,6 +21,19 @@ test('stage headings restore the original prefix and style only Expected:', () =
21
21
  assert.match(result.stdout, /\x1b\[1m\x1b\[33mExpected:\x1b\[0m\x1b\[0m migrations \+ seed/)
22
22
  })
23
23
 
24
+ test('status lines use emoji that every terminal draws two columns wide', () => {
25
+ const lines = []
26
+ for (const kind of ['ok', 'warn', 'fail', 'info']) statusLine(kind, 'message', { log: (line) => lines.push(line.replace(/\u001b\[[0-9;]*m/g, '')) })
27
+ assert.deepEqual(lines, [' ✅ message', ' ❗ message', ' ❌ message', ' 💡 message'])
28
+ })
29
+
30
+ test('setup output avoids variation-selector emoji whose width differs between terminals', () => {
31
+ const sourceDir = new URL('../', import.meta.url)
32
+ const offenders = fs.readdirSync(sourceDir).filter((name) => name.endsWith('.mjs'))
33
+ .filter((name) => fs.readFileSync(new URL(name, sourceDir), 'utf8').includes('️'))
34
+ assert.deepEqual(offenders, [])
35
+ })
36
+
24
37
  test('working spinner animates with elapsed time, pauses, and is replaced on completion', () => {
25
38
  const output = []
26
39
  const statuses = []
@@ -70,7 +83,7 @@ test('stage activity stops on success, skip and failure and never starts over a
70
83
  setActivity(activity) { if (activity) { events.push('attach'); activity.resume() } }, resumeActivity() {},
71
84
  }
72
85
  const ctx = { flags: {}, logs, log: (line) => events.push(String(line)), createSpinnerImpl(label) {
73
- assert.equal(label, '⚙️ working…')
86
+ assert.equal(label, '🔧 working…')
74
87
  events.push('create')
75
88
  return { pause() { events.push('pause') }, resume() { events.push('resume') }, stop() { events.push('stop') } }
76
89
  } }
@@ -11,7 +11,7 @@ import { DEFAULT_OPENCODE_BASE_IMAGE, DEFAULT_PORTS, resolveStackPorts } from '.
11
11
  import { addEnvValue, readEnvValue, setEnvValue } from '../env-file.mjs'
12
12
  import { ensureLlmProvider, syncProviderConfigToAppEnv } from '../providers.mjs'
13
13
  import { ensureWindowsUtf8Console, resolveSpawnCommand } from '../spawn.mjs'
14
- import { StepBlocked, buildToolchainStep, containerRuntimeStep, databaseStep, hostGatewayStep, infraUpStep, clearConvergenceState, databaseIsInitialized, listMigrationModules, migrationsFingerprint, probePostgresCredentials, readAppliedMigrationModules, resolveOpencodeBaseImage, runSteps, workspaceBuildStep } from '../steps.mjs'
14
+ import { StepBlocked, buildToolchainStep, containerRuntimeStep, databaseStep, hostGatewayStep, infraUpStep, serviceConfigurationStep, serviceConnectionsStep, buildUpSteps, clearConvergenceState, databaseIsInitialized, listMigrationModules, migrationsFingerprint, probePostgresCredentials, readAppliedMigrationModules, resolveOpencodeBaseImage, runSteps, workspaceBuildStep } from '../steps.mjs'
15
15
  import { ensureEnvFiles } from '../env-setup.mjs'
16
16
  import { describeInfraProblem, devRuntimeArgs, externalDatabaseHost, removeLeftoverComposeResources, resolveUpMode, startInfra } from '../infra.mjs'
17
17
  import { detectDockerRuntime, detectWsl, findPortConflicts, findUnhealthyServices, formatInfraProblem, startInfraServices } from '../infra-preflight.mjs'
@@ -205,7 +205,7 @@ test('resolveSpawnCommand rejects cmd metacharacters instead of degrading into i
205
205
  })
206
206
 
207
207
  function quietCtx(overrides = {}) {
208
- return { log: () => {}, flags: {}, company: { steps: { disable: [], extra: [] } }, ...overrides }
208
+ return { assertDatabaseWriteAllowedImpl: async () => ({ remote: false }), log: () => {}, flags: {}, company: { steps: { disable: [], extra: [] } }, ...overrides }
209
209
  }
210
210
 
211
211
  test('runSteps skips satisfied steps, applies unsatisfied ones, and stops on StepBlocked with guidance', async () => {
@@ -887,7 +887,7 @@ test('the database step initializes with --skip-if-initialized so a re-run never
887
887
  repoRoot: repo,
888
888
  env: {},
889
889
  flags: { noInfra: true },
890
- logs: { raw() {} },
890
+ logs: { raw() {}, suspend() {}, resume() {} },
891
891
  runStreamingImpl: (command, args, options) => {
892
892
  invocations.push({ command, args, env: options.env })
893
893
  return 0
@@ -909,6 +909,106 @@ test('the database step initializes with --skip-if-initialized so a re-run never
909
909
  })
910
910
 
911
911
 
912
+ test('service configuration uses app URLs and root Compose env before build and database', async () => {
913
+ const repo = makeFakeRepo()
914
+ let called
915
+ let cleaned = false
916
+ const ctx = {
917
+ repoRoot: repo,
918
+ mode: 'hybrid',
919
+ flags: { serviceMode: 'ephemeral', noInfra: true },
920
+ env: { KEEP: 'value' },
921
+ log() {},
922
+ company: { steps: { disable: [], extra: [] } },
923
+ async configureServiceModeImpl(options) {
924
+ called = options
925
+ return { ok: true, env: { DATABASE_URL: 'postgres://temporary' }, cleanup: async () => { cleaned = true } }
926
+ },
927
+ }
928
+ const steps = buildUpSteps(ctx).map((step) => step.id)
929
+ assert.ok(steps.indexOf('service-configuration') > steps.indexOf('workspace-install'))
930
+ assert.ok(steps.indexOf('service-configuration') < steps.indexOf('workspace-build'))
931
+ assert.ok(steps.indexOf('service-configuration') < steps.indexOf('database'))
932
+ await serviceConfigurationStep.apply(ctx)
933
+ assert.equal(called.mode, 'ephemeral')
934
+ assert.equal(called.projectDir, path.join(repo, 'apps', 'mercato'))
935
+ assert.deepEqual(called.envFiles, [path.join(repo, '.env')])
936
+ assert.deepEqual(called.services.map((service) => service.service), ['postgres', 'redis', 'meilisearch'])
937
+ assert.equal(ctx.env.DATABASE_URL, 'postgres://temporary')
938
+ assert.equal(ctx.env.KEEP, 'value')
939
+ await ctx.cleanupServices()
940
+ assert.equal(cleaned, true)
941
+ })
942
+
943
+ test('reuse and ephemeral service choices skip Compose-dependent steps', () => {
944
+ for (const serviceMode of ['reuse', 'ephemeral']) {
945
+ const ctx = { mode: 'hybrid', flags: { noInfra: true, serviceMode } }
946
+ assert.equal(containerRuntimeStep.appliesTo(ctx), false)
947
+ assert.equal(infraUpStep.appliesTo(ctx), false)
948
+ assert.equal(hostGatewayStep.appliesTo(ctx), false)
949
+ assert.deepEqual(devRuntimeArgs([], ctx.flags), ['--no-infra'])
950
+ }
951
+ })
952
+
953
+ test('failed service configuration does not reach subsequent setup steps', async () => {
954
+ let laterStepRan = false
955
+ const outcome = await runSteps([serviceConfigurationStep, {
956
+ id: 'database', title: 'database',
957
+ async apply() { laterStepRan = true },
958
+ }], {
959
+ repoRoot: makeFakeRepo(), mode: 'hybrid', flags: { serviceMode: 'ephemeral' }, env: {}, log() {},
960
+ async configureServiceModeImpl() { throw new Error('Docker unavailable') },
961
+ })
962
+ assert.equal(outcome.ok, false)
963
+ assert.equal(outcome.failedStep, 'service-configuration')
964
+ assert.equal(laterStepRan, false)
965
+ })
966
+
967
+
968
+ test('cancelling an earlier asynchronous step prevents services and database setup', async () => {
969
+ let servicesStarted = false
970
+ let databaseRan = false
971
+ const ctx = { repoRoot: makeFakeRepo(), mode: 'hybrid', flags: { serviceMode: 'ephemeral' }, env: {}, log() {}, cancelled: false,
972
+ async configureServiceModeImpl() { servicesStarted = true; return { ok: true, env: {} } },
973
+ }
974
+ const outcome = await runSteps([
975
+ { id: 'earlier', title: 'earlier', async apply(context) { await Promise.resolve(); context.cancelled = true } },
976
+ serviceConfigurationStep,
977
+ { id: 'database', title: 'database', async apply() { databaseRan = true } },
978
+ ], ctx)
979
+ assert.equal(outcome.ok, false)
980
+ assert.equal(servicesStarted, false)
981
+ assert.equal(databaseRan, false)
982
+ })
983
+
984
+ test('random-port reconfiguration reconverges healthy Compose services before database setup', async () => {
985
+ const calls = []
986
+ const ctx = quietCtx({
987
+ repoRoot: makeFakeRepo(), mode: 'hybrid', flags: { serviceMode: 'random', profiles: [], noInfra: false }, env: {},
988
+ async configureServiceModeImpl() { calls.push('configure'); return { ok: true, env: {} } },
989
+ runComposeImpl() { return { status: 0, stdout: ['postgres', 'redis', 'meilisearch', 'opencode'].map((service) => JSON.stringify({ Service: service, State: 'running', Health: 'healthy' })).join('\n') } },
990
+ async startInfraImpl() { calls.push('converge'); return { ok: true } },
991
+ })
992
+ const outcome = await runSteps([serviceConfigurationStep, infraUpStep, { id: 'database', title: 'database', async apply() { calls.push('database') } }], ctx)
993
+ assert.equal(outcome.ok, true)
994
+ assert.deepEqual(calls, ['configure', 'converge', 'database'])
995
+ })
996
+
997
+
998
+ test('credential verification runs after infrastructure and blocks database setup on rejection', async () => {
999
+ const ctx = quietCtx({ repoRoot: makeFakeRepo(), mode: 'hybrid', flags: { serviceMode: 'reuse' }, env: {}, company: { steps: { disable: [], extra: [] } },
1000
+ async verifyServiceConnectionsImpl() { throw new Error('PostgreSQL rejected configured credentials; check DATABASE_URL in .env') },
1001
+ })
1002
+ const ids = buildUpSteps(ctx).map((step) => step.id)
1003
+ assert.ok(ids.indexOf('service-connections') > ids.indexOf('infra-up'))
1004
+ assert.ok(ids.indexOf('service-connections') < ids.indexOf('database'))
1005
+ let databaseRan = false
1006
+ const outcome = await runSteps([serviceConnectionsStep, { id: 'database', title: 'database', async apply() { databaseRan = true } }], ctx)
1007
+ assert.equal(outcome.ok, false)
1008
+ assert.equal(outcome.failedStep, 'service-connections')
1009
+ assert.equal(databaseRan, false)
1010
+ })
1011
+
912
1012
  test('infrastructure starting detail is separated from its step heading by a blank line', async () => {
913
1013
  const messages = []
914
1014
  await runSteps([{ id: 'infra-up', title: 'Infrastructure', check: async () => ({ ok: false, detail: 'starting: postgres' }), apply: async () => {} }], quietCtx({ log: (line) => messages.push(line) }))
package/src/cli.mjs CHANGED
@@ -23,6 +23,8 @@ import readline from 'node:readline'
23
23
 
24
24
  import { composeArgs, detectDocker, resolveRepoRoot, runCompose, runStreaming, spawnStreaming } from './compose.mjs'
25
25
  import { readEnvValue } from './env-file.mjs'
26
+ import { chooseServiceMode, printManualSetup } from './service-modes.mjs'
27
+ import { FRESH_CLONE_NO_INFRA_COMMAND, acquireSetupSession, selectStarterServiceMode } from './setup-session.mjs'
26
28
  import { FULLAPP_DEV_COMPOSE_FILE, STARTER_STATE_DIR, resolveStackPorts, stackUrls } from './constants.mjs'
27
29
  import { loadCompanyConfig } from './company.mjs'
28
30
  import { printDoctorReport, runDoctor } from './doctor.mjs'
@@ -56,6 +58,8 @@ function parseArgs(argv) {
56
58
  skipLlmPrompt: false,
57
59
  skipDb: false,
58
60
  noInfra: false,
61
+ serviceArgs: [],
62
+ remoteDatabaseArgs: [],
59
63
  rebuild: false,
60
64
  clean: false,
61
65
  volumes: false,
@@ -96,7 +100,15 @@ function parseArgs(argv) {
96
100
  flags.skipDb = true
97
101
  break
98
102
  case '--no-infra':
99
- flags.noInfra = true
103
+ case '--reuse-services':
104
+ case '--ephemeral':
105
+ case '--random-ports':
106
+ case '--infra':
107
+ flags.serviceArgs.push(arg)
108
+ break
109
+ case '--allow-remote-database':
110
+ flags.remoteDatabaseArgs.push(arg)
111
+ if (args[0] && !args[0].startsWith('-')) flags.remoteDatabaseArgs.push(args.shift())
100
112
  break
101
113
  case '--rebuild':
102
114
  flags.rebuild = true
@@ -121,6 +133,7 @@ function parseArgs(argv) {
121
133
  if (command === 'infra') flags.infraAction = arg
122
134
  break
123
135
  default:
136
+ if (arg.startsWith('--allow-remote-database=')) { flags.remoteDatabaseArgs.push(arg); break }
124
137
  console.error(`Unknown option: ${arg} (see starters/README.md)`)
125
138
  process.exit(1)
126
139
  }
@@ -162,7 +175,50 @@ async function confirm(question, { nonInteractive }) {
162
175
 
163
176
  async function commandUp(flags) {
164
177
  const selectedMode = resolveMode(flags.mode)
165
- const mode = resolveUpMode(selectedMode, flags)
178
+ const containerized = flags.mode === 'docker' && flags.serviceArgs.length === 0
179
+ let session = null
180
+ if (!containerized) {
181
+ try {
182
+ session = await acquireSetupSession(repoRoot, { interactive: flags.nonInteractive ? false : undefined })
183
+ } catch (error) {
184
+ console.error(`❌ ${error instanceof Error ? error.message : String(error)}`)
185
+ console.error(' No service configuration, .env file or container was changed.')
186
+ process.exitCode = 2
187
+ return
188
+ }
189
+ }
190
+ const state = { handedOff: false }
191
+ try {
192
+ return await runUp(flags, { selectedMode, containerized, session, state })
193
+ } finally {
194
+ if (!state.handedOff) session?.release()
195
+ }
196
+ }
197
+
198
+ async function runUp(flags, { selectedMode, containerized, session, state }) {
199
+ if (containerized) {
200
+ flags.serviceMode = 'compose'
201
+ } else {
202
+ try {
203
+ flags.serviceMode = await chooseServiceMode({
204
+ argv: [...flags.serviceArgs, ...(flags.nonInteractive ? ['--non-interactive'] : [])],
205
+ selectDefault: () => selectStarterServiceMode(repoRoot),
206
+ })
207
+ } catch (error) {
208
+ if (!error.problem) throw error
209
+ console.error(`❌ ${error.message}`)
210
+ printInfraProblem(error.problem, { optOutCommand: FRESH_CLONE_NO_INFRA_COMMAND })
211
+ process.exitCode = 2
212
+ return
213
+ }
214
+ }
215
+ flags.noInfra = ['reuse', 'ephemeral'].includes(flags.serviceMode)
216
+ if (flags.serviceMode === 'ephemeral' && flags.detach) {
217
+ console.error('Ephemeral services belong to a foreground setup session. Omit --detach or use --random-ports for persistent local services.')
218
+ process.exitCode = 2
219
+ return
220
+ }
221
+ const mode = flags.serviceMode === 'random' ? 'hybrid' : resolveUpMode(selectedMode, flags)
166
222
  if (flags.clean) {
167
223
  // Full re-converge: drop the completed-step markers (keeps the mode, all
168
224
  // data, and the one-time initialize state — `reset` is the destructive
@@ -172,11 +228,38 @@ async function commandUp(flags) {
172
228
  console.log(color.dim(` --clean: cleared ${cleared.length} convergence marker(s) — install, build, and migrations will re-run (data untouched).`))
173
229
  }
174
230
  const ctx = await createStepContext(repoRoot, { mode, flags })
231
+ if (session) Object.assign(ctx.env, session.childEnv)
232
+ let devChild
233
+ let signalExitCode
234
+ let shutdownTimer
235
+ let closing = false
236
+ const finish = async (code) => {
237
+ if (closing) return
238
+ closing = true
239
+ clearTimeout(shutdownTimer)
240
+ try { await ctx.cleanupServices?.() }
241
+ catch (error) { console.error(`Could not clean up ephemeral services: ${error.message}`); code = 1 }
242
+ session?.release()
243
+ process.exit(code)
244
+ }
245
+ if (flags.serviceMode === 'ephemeral') {
246
+ for (const [signal, code] of [['SIGINT', 130], ['SIGTERM', 143]]) {
247
+ process.once(signal, () => {
248
+ signalExitCode = code
249
+ ctx.cancelled = true
250
+ if (devChild) {
251
+ devChild.kill(signal)
252
+ shutdownTimer = setTimeout(() => devChild.kill('SIGKILL'), 5000)
253
+ shutdownTimer.unref()
254
+ }
255
+ })
256
+ }
257
+ }
175
258
  printBanner(`dev environment starter — mode: ${mode}${ctx.company.name ? ` — company profile: ${ctx.company.name}` : ''}`)
176
259
  console.log(color.dim(` Repo: ${repoRoot}`))
177
260
  console.log(color.dim(' Every step is idempotent — re-running always resumes where it stopped.'))
178
261
  if (selectedMode !== mode) {
179
- console.log(color.dim(' --no-infra: using the host runtime for this run so no Docker command is invoked.'))
262
+ console.log(color.dim(' Using the host runtime for the selected service mode.'))
180
263
  }
181
264
 
182
265
  if (mode === 'docker') return commandUpDocker(ctx, flags)
@@ -187,7 +270,10 @@ async function commandUp(flags) {
187
270
  'Fix the item above and re-run the same command — completed steps are skipped.',
188
271
  'Full environment audit with an IT handout: yarn om doctor (or: npx @open-mercato/starter doctor)',
189
272
  ])
190
- process.exit(2)
273
+ await ctx.cleanupServices?.()
274
+ printManualSetup({ monorepo: true })
275
+ process.exitCode = signalExitCode ?? 2
276
+ return
191
277
  }
192
278
 
193
279
  const ports = resolveStackPorts(repoRoot)
@@ -198,21 +284,26 @@ async function commandUp(flags) {
198
284
  console.log(` MCP: ${color.cyan(urls.mcp)}`)
199
285
  console.log(` OpenCode: ${color.cyan(`http://127.0.0.1:${ports.opencode}`)}`)
200
286
  console.log(color.dim(` Superadmin sign-in: ${readEnvValue(path.join(repoRoot, '.env'), 'OM_INIT_SUPERADMIN_EMAIL')?.trim() || 'superadmin@acme.com'} / ${readEnvValue(path.join(repoRoot, '.env'), 'OM_INIT_SUPERADMIN_PASSWORD')?.trim() || 'secret'}`))
201
- console.log(color.dim(' Stop: Ctrl+C (infra containers keep running; `stop` shuts everything down)'))
287
+ console.log(color.dim(flags.serviceMode === 'ephemeral'
288
+ ? ' Stop: Ctrl+C (ephemeral services are removed and their previous configuration is restored)'
289
+ : flags.serviceMode === 'reuse' ? ' Stop: Ctrl+C (your existing services are left running)' : ' Stop: Ctrl+C (Compose containers keep running; `stop` shuts them down)'))
202
290
  console.log('')
203
291
 
204
- const devArgs = devRuntimeArgs(flags.passthrough, { noInfra: ctx.flags.noInfra })
292
+ const devArgs = devRuntimeArgs([...flags.passthrough, ...(ctx.remoteDatabaseArgument ? [ctx.remoteDatabaseArgument] : flags.remoteDatabaseArgs)], { noInfra: flags.noInfra })
205
293
  if (flags.detach) {
206
- startDetached(repoRoot, devArgs, { env: ctx.env })
294
+ const pid = startDetached(repoRoot, devArgs, { env: ctx.env })
295
+ session?.registerChild({ pid }, 'dev-runner')
207
296
  console.log('Manage it with the status / logs / stop subcommands.')
208
297
  return
209
298
  }
210
299
  const dev = yarnInvocation(ctx, ['dev', ...devArgs])
211
- const child = spawnStreaming(dev.command, dev.args, { cwd: repoRoot, env: ctx.env })
212
- child.on('close', (code) => process.exit(code ?? 0))
213
- child.on('error', (error) => {
300
+ devChild = spawnStreaming(dev.command, dev.args, { cwd: repoRoot, env: ctx.env })
301
+ state.handedOff = true
302
+ session?.registerChild(devChild, 'dev-runner')
303
+ devChild.on('close', (code) => { void finish(signalExitCode ?? code ?? 0) })
304
+ devChild.on('error', (error) => {
214
305
  console.error(`❌ Could not start yarn dev: ${error.message}`)
215
- process.exit(1)
306
+ void finish(1)
216
307
  })
217
308
  }
218
309
 
@@ -220,7 +311,7 @@ async function commandUpDocker(ctx, flags) {
220
311
  // Containerized mode: converge trust/env, then let compose own the stack.
221
312
  const steps = buildUpSteps(ctx).filter((step) => ['prerequisites', 'container-runtime', 'corporate-certs', 'env-files', 'llm-provider'].includes(step.id))
222
313
  const outcome = await runSteps(steps, ctx)
223
- if (!outcome.ok) process.exit(2)
314
+ if (!outcome.ok) { printManualSetup({ monorepo: true }); process.exit(2) }
224
315
 
225
316
  ensureMcpSharedDir(repoRoot)
226
317
  const composeFile = FULLAPP_DEV_COMPOSE_FILE
@@ -296,7 +387,7 @@ async function commandStop(flags) {
296
387
  process.exit(status)
297
388
  }
298
389
  }
299
- console.log('ℹ️ Infra containers left running (--keep-infra or no docker). Foreground `yarn dev` sessions stop with Ctrl+C.')
390
+ console.log('💡 Infra containers left running (--keep-infra or no docker). Foreground `yarn dev` sessions stop with Ctrl+C.')
300
391
  }
301
392
 
302
393
  async function commandStatus(flags) {
@@ -340,7 +431,7 @@ async function commandReset(flags) {
340
431
  // down only sees THIS project's resources; fixed-name containers/volumes
341
432
  // created by another checkout of the repo survive it — sweep by name.
342
433
  if (!removeLeftoverComposeResources(repoRoot, { composeFile })) {
343
- console.warn('⚠️ Some volumes could not be removed — the next run would reuse the old data. Fix the items above and re-run reset.')
434
+ console.warn('❗ Some volumes could not be removed — the next run would reuse the old data. Fix the items above and re-run reset.')
344
435
  }
345
436
  }
346
437
  fs.rmSync(path.join(repoRoot, STARTER_STATE_DIR), { recursive: true, force: true })
@@ -405,8 +496,10 @@ async function commandInfra(flags) {
405
496
  }
406
497
  }
407
498
 
408
- function printInfraProblem(problem, log = console.error) {
409
- const [title, ...rest] = describeInfraProblem(problem)
499
+ function printInfraProblem(problem, options = {}) {
500
+ const log = typeof options === 'function' ? options : console.error
501
+ if (typeof options === 'function') options = {}
502
+ const [title, ...rest] = describeInfraProblem(problem, options)
410
503
  log(`❌ ${title}`)
411
504
  for (const line of rest) log(` ${line}`)
412
505
  }
@@ -434,7 +527,10 @@ async function main() {
434
527
  }
435
528
  }
436
529
 
437
- await main().catch((error) => {
438
- console.error(`❌ ${error instanceof Error ? error.message : String(error)}`)
439
- process.exitCode = 1
440
- })
530
+ try {
531
+ await main()
532
+ } catch (error) {
533
+ console.error(`\n❌ Setup failed: ${error instanceof Error ? error.message : String(error)}`)
534
+ printManualSetup({ monorepo: true })
535
+ process.exitCode = 2
536
+ }
package/src/company.mjs CHANGED
@@ -64,7 +64,7 @@ export async function loadCompanyConfig(repoRoot, { warn = console.warn } = {})
64
64
  const module = await import(pathToFileURL(filePath).href)
65
65
  config = mergeConfig(config, module.default)
66
66
  } catch (error) {
67
- warn(`⚠️ Ignoring starters/company/${candidate} — it failed to load: ${error instanceof Error ? error.message : String(error)}`)
67
+ warn(`❗ Ignoring starters/company/${candidate} — it failed to load: ${error instanceof Error ? error.message : String(error)}`)
68
68
  }
69
69
  }
70
70
  return config
package/src/compose.mjs CHANGED
@@ -129,7 +129,7 @@ export function stopStreamingChild(child, signal, { platform = process.platform,
129
129
 
130
130
  // Async output capture keeps the setup log toggle responsive during long
131
131
  // installs/builds. With no sink, preserve inherited stdio (CI / verbose).
132
- export function runStreaming(command, commandArgs, { cwd, env, logs, spawnImpl = spawn } = {}) {
132
+ export function runStreaming(command, commandArgs, { cwd, env, logs, exitOnSignal = true, spawnImpl = spawn } = {}) {
133
133
  const resolved = resolveSpawnCommand(command, commandArgs)
134
134
  return new Promise((resolve, reject) => {
135
135
  const child = spawnImpl(resolved.command, resolved.args, {
@@ -141,16 +141,22 @@ export function runStreaming(command, commandArgs, { cwd, env, logs, spawnImpl =
141
141
  detached: Boolean(logs) && process.platform !== 'win32',
142
142
  ...resolved.spawnOptions,
143
143
  })
144
+ let signalCode
145
+ let shutdownTimer
144
146
  const interrupt = (signal) => {
147
+ signalCode = signal === 'SIGINT' ? 130 : 143
145
148
  logs?.stop()
146
149
  stopStreamingChild(child, signal, { grouped: Boolean(logs) })
147
- process.exit(signal === 'SIGINT' ? 130 : 143)
150
+ if (exitOnSignal) process.exit(signalCode)
151
+ shutdownTimer = setTimeout(() => stopStreamingChild(child, 'SIGKILL', { grouped: Boolean(logs) }), 5000)
152
+ shutdownTimer.unref()
148
153
  }
149
154
  const onSigint = () => interrupt('SIGINT')
150
155
  const onSigterm = () => interrupt('SIGTERM')
151
156
  process.once('SIGINT', onSigint)
152
157
  process.once('SIGTERM', onSigterm)
153
158
  const cleanup = () => {
159
+ clearTimeout(shutdownTimer)
154
160
  process.removeListener('SIGINT', onSigint)
155
161
  process.removeListener('SIGTERM', onSigterm)
156
162
  }
@@ -159,6 +165,6 @@ export function runStreaming(command, commandArgs, { cwd, env, logs, spawnImpl =
159
165
  child.stdout?.on('data', (chunk) => logs?.raw(chunk))
160
166
  child.stderr?.on('data', (chunk) => logs?.raw(chunk))
161
167
  child.once('error', (error) => { cleanup(); reject(new Error(`${command} could not be executed: ${error.message}`)) })
162
- child.once('close', (code) => { cleanup(); resolve(code ?? 1) })
168
+ child.once('close', (code) => { cleanup(); resolve(signalCode ?? code ?? 1) })
163
169
  })
164
170
  }
package/src/constants.mjs CHANGED
@@ -81,5 +81,5 @@ export const FULLAPP_DEV_COMPOSE_FILE = path.join('starters', 'docker', 'compose
81
81
  // image is the thin local build FROM it, tagged opencode-mvp. Keep the default
82
82
  // tag in sync with the compose files' OPENCODE_BASE_IMAGE default and the
83
83
  // docker/opencode/Dockerfile ARG.
84
- export const DEFAULT_OPENCODE_BASE_IMAGE = 'docker.io/openmercatocom/open-mercato-opencode:1.18.3'
84
+ export const DEFAULT_OPENCODE_BASE_IMAGE = 'docker.io/openmercatocom/open-mercato-opencode:1.18.3@sha256:1ccc9d47dd46234dd6a4ad914662a226c96a21413c0d286e61bcc248745917f7'
85
85
  export const OPENCODE_SERVICE_IMAGE = 'opencode-mvp'
@@ -0,0 +1,80 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import net from 'node:net'
4
+ import { createRequire } from 'node:module'
5
+ import { createInterface } from 'node:readline/promises'
6
+ import { parseEnv } from 'node:util'
7
+
8
+ function settingsFor(projectDir, envFiles, env) {
9
+ const settings = {}
10
+ for (const file of [...envFiles, path.join(projectDir, '.env')]) {
11
+ try { Object.assign(settings, parseEnv(fs.readFileSync(file, 'utf8'))) }
12
+ catch (error) { if (error.code !== 'ENOENT') throw new Error('Cannot read database configuration before authorizing writes.') }
13
+ }
14
+ return { ...settings, ...env }
15
+ }
16
+
17
+ function loadPostgres(projectDir) {
18
+ for (const manifest of [path.join(projectDir, 'package.json'), path.join(projectDir, 'node_modules', '@open-mercato', 'cli', 'package.json'), path.join(projectDir, '..', '..', 'packages', 'cli', 'package.json')]) {
19
+ try { return createRequire(manifest)('pg') }
20
+ catch (error) { if (error.code !== 'MODULE_NOT_FOUND') throw error }
21
+ }
22
+ throw new Error('Install project dependencies before authorizing database writes: yarn install.')
23
+ }
24
+
25
+ export function collectRemoteDatabaseFlags(argv) {
26
+ const flags = []
27
+ for (let index = 0; index < argv.length; index += 1) {
28
+ const argument = argv[index]
29
+ if (argument.startsWith('--allow-remote-database=')) flags.push(argument)
30
+ else if (argument === '--allow-remote-database') {
31
+ flags.push(argument)
32
+ if (argv[index + 1] && !argv[index + 1].startsWith('-')) flags.push(argv[++index])
33
+ }
34
+ }
35
+ return flags
36
+ }
37
+
38
+ export function resolveDatabaseWriteTarget({ projectDir = process.cwd(), envFiles = [], env = process.env, databaseUrl, loadModule = loadPostgres } = {}) {
39
+ const settings = settingsFor(projectDir, envFiles, env)
40
+ const connectionString = databaseUrl ?? settings.DATABASE_URL
41
+ if (!connectionString) throw new Error('DATABASE_URL must be configured before database writes.')
42
+ let parameters
43
+ try {
44
+ const { Client } = loadModule(projectDir)
45
+ parameters = new Client({ connectionString, host: settings.PGHOST, port: settings.PGPORT, database: settings.PGDATABASE, user: settings.PGUSER }).connectionParameters
46
+ } catch { throw new Error('Cannot resolve the PostgreSQL write target. Check DATABASE_URL and install project dependencies.') }
47
+ const host = String(parameters.host ?? '').toLowerCase()
48
+ const database = String(parameters.database ?? '')
49
+ const port = Number(parameters.port)
50
+ if (!host || !database || !Number.isInteger(port) || port < 1 || port > 65535 || /[\x00-\x1f\x7f]/.test(host + database)) throw new Error('Cannot resolve a valid PostgreSQL write target from DATABASE_URL.')
51
+ const plainHost = host.replace(/^\[|\]$/g, '')
52
+ const local = plainHost === 'localhost' || plainHost === '::1' || (net.isIP(plainHost) === 4 && plainHost.split('.')[0] === '127') || plainHost.startsWith('/')
53
+ const renderedHost = net.isIP(plainHost) === 6 ? `[${plainHost}]` : host
54
+ return {
55
+ remote: !local,
56
+ target: `${renderedHost}:${port}/${encodeURIComponent(database)}`,
57
+ connectionEnv: { DATABASE_URL: connectionString, PGHOST: String(parameters.host), PGPORT: String(parameters.port), PGDATABASE: String(parameters.database), PGUSER: String(parameters.user ?? ''), PGPASSWORD: typeof parameters.password === 'string' ? parameters.password : '' },
58
+ }
59
+ }
60
+
61
+ export async function assertDatabaseWriteAllowed({ argv = [], input = process.stdin, output = process.stdout, ...options } = {}) {
62
+ const resolved = resolveDatabaseWriteTarget(options)
63
+ if (!resolved.remote) return resolved
64
+ const flags = collectRemoteDatabaseFlags(argv)
65
+ let acknowledgement
66
+ let requested = false
67
+ for (let index = 0; index < flags.length; index += 1) {
68
+ if (flags[index].startsWith('--allow-remote-database=')) { requested = true; acknowledgement = flags[index].slice('--allow-remote-database='.length) }
69
+ else if (flags[index] === '--allow-remote-database') { requested = true; acknowledgement = flags[index + 1] && !flags[index + 1].startsWith('-') ? flags[++index] : undefined }
70
+ }
71
+ if (requested && acknowledgement === undefined && input.isTTY && output.isTTY && !options.env?.CI) {
72
+ const prompt = createInterface({ input, output })
73
+ try { acknowledgement = await prompt.question(`Remote database writes affect ${resolved.target}. Type that exact target to authorize migrations and initialization: `) }
74
+ finally { prompt.close() }
75
+ }
76
+ if (!requested || acknowledgement !== resolved.target) {
77
+ throw new Error(`Remote database writes are blocked for ${resolved.target}. To authorize this exact target, pass --allow-remote-database=${resolved.target}. Local service reuse remains the default; no database changes were made.`)
78
+ }
79
+ return { ...resolved, argument: `--allow-remote-database=${resolved.target}` }
80
+ }