Files
sim/scripts/setup/lifecycle.ts
T
Theodore Li 1a4bfe4c59 fix(setup,compose): bundle Redis, fix socket reconnect, and harden the setup wizard (#5964)
* feat(compose,setup): bundle Redis, always configure it, fix lifecycle detection

Compose shipped no redis service at all — REDIS_URL was ${REDIS_URL:-} in both app and realtime, so every self-hosted stack ran without it. Storage silently falls back to PostgreSQL, but the pub/sub channels (live Chat task-status, table events) have no fallback, so live updates never arrived.

- compose (prod + local): add a redis:7-alpine service with a healthcheck, default REDIS_URL to redis://redis:6379, and make app/realtime depend on it being healthy. Not published to the host — only the containers need it, and binding 6379 would collide with a local Redis. An external REDIS_URL in root .env still overrides. Deliberately not written into root .env: doctor pings REDIS_URL from the host, and a compose-internal hostname would fail that probe the same way DATABASE_URL would.
- dev mode: configure Redis in quick too. Quick uses a new non-interactive ensureRedis (adopt whatever answers, else start the managed container, warn only if Docker is unavailable); custom keeps the ladder, with corrected copy — the old prompt claimed Redis was only for multi-replica.
- lifecycle: detect compose stacks via 'docker compose ls' instead of probing '-f <file> ps' in the working directory. Compose derives the project name from the directory it was started in, so the old probe found a stack only when run from the checkout that launched it (a globally linked sim never could) and listed the same stack once per candidate file. compose ls reports the real project and its config file, so one stack yields one install from anywhere; non-Sim projects are filtered by compose filename. Every compose op now runs in that stack's directory.
- lifecycle: distinguish 'Docker unreachable' from 'nothing installed'. With the daemon down, status reported containers as 'absent' and suggested re-running setup; it now says Docker is down and marks state unknown.

* fix(setup): don't start managed Postgres with a password the volume will ignore

POSTGRES_PASSWORD only applies when initdb runs on an empty data directory. The sim-postgres-data volume outlives its container (sim down keeps it, docker rm keeps it, and the wizard's own recreate path keeps it), and inspectManagedContainer recovers the password from the *container*, not the volume — so once the container is gone the password is unrecoverable.

Setup then generated a fresh password and ran against the initialized volume. Postgres kept its original password and rejected every connection with 'password authentication failed for user postgres', which surfaced as a misleading 'container did not become healthy'.

Detect an already-bootstrapped volume (PG_VERSION present) before choosing a password, and ask: supply the existing password, or delete the volume and start fresh (double-confirmed, since that destroys data). Refusing both fails with the exact docker volume rm command instead of looping.

* improvement(setup): default to Docker Compose and sharpen the run-mode copy

Compose was listed first but only preselected when Docker happened to be running — with Docker stopped the cursor sat on 'Local dev', steering people toward a source checkout when they wanted to run Sim. Compose mode calls ensureDocker(true), which offers to start Docker Desktop, so a stopped daemon is no reason to change the default.

Also tightens the hints to say what each mode is for: run bundled Sim (fastest way to start), work on Sim itself, test a production-style k8s deploy.

* fix(compose): point the browser socket at :3002 so it stops reconnecting

The stack publishes the app on 3000 and realtime on 3002 with no reverse proxy between them, but NEXT_PUBLIC_SOCKET_URL defaulted to empty — which tells the browser client to use the page origin. :3000/socket.io answers 308 (a Next redirect), not a Socket.IO handshake, so the client failed and retried forever. Default it to http://localhost:3002; a proxied deployment overrides it (or sets it empty to use the page origin).

Also give COPILOT_API_KEY and SIM_AGENT_API_URL empty defaults so every compose command stops printing 'variable is not set' warnings. The app already falls back to the prod copilot backend when SIM_AGENT_API_URL is blank.

* feat(setup): pass SIM_AGENT_API_URL through, and warn on a half-set mothership

Sim devs testing against a non-prod mothership export SIM_CLI_AUTH_ORIGIN so the Chat key is minted there, but nothing carried the matching backend URL into the install — the app kept defaulting to prod copilot, which rejects a staging key with 'Invalid API key'.

Persist SIM_AGENT_API_URL when it is exported, so later docker compose up / dev runs stay on that backend instead of reverting to prod once the shell is gone:

  SIM_CLI_AUTH_ORIGIN=https://www.staging.sim.ai \
  SIM_AGENT_API_URL=https://www.staging.copilot.sim.ai \
  bun run setup

Setting only the auth origin is the trap, so that combination warns. Neither set is the self-hoster default and stays silent — no prompts, no flags.

* fix(setup): survive a vanished port owner, and stop flagging our own containers

Two failures from one compose re-run:

- 'Kill it for me' crashed setup with 'kill() failed: ESRCH: No such process'. The owner list is an lsof snapshot, so the process can exit before the signal lands — which is the outcome we wanted, not an error. ESRCH now counts as freed, EPERM warns that it must be stopped by hand, and anything else warns; the loop re-probes either way instead of aborting a setup that had already written .env.

- Compose mode demanded 3000/3002 be free even when this stack was the one holding them, so re-running setup against a running install reported its own realtime container as a blocker and offered to kill Docker's listener. 'docker compose up -d' reconciles its own containers, so skip the check when the project already has some. A foreign process is still caught, and a foreign container still surfaces as a bind error from compose.

* fix(csp,setup): permit the socket origin the client actually uses; encode DSN passwords

Review round on #5964:

- The socket reconnect was a CSP bug, not a URL bug. getSocketUrl() already falls back to localhost:3002 for a localhost page, but generateRuntimeCSP gated that same fallback on isDev — and compose runs NODE_ENV=production, so connect-src omitted ws://localhost:3002 and the browser blocked the handshake. Key the fallback on the app URL being localhost instead, mirroring getSocketUrl. Revert the compose NEXT_PUBLIC_SOCKET_URL default: an explicit value suppresses the page-origin fallback that reverse-proxied self-hosts depend on, and ':-' treats empty as unset so the documented escape hatch could not work either. LOCALHOST_HOSTNAMES is duplicated locally because csp.ts is loaded by next.config.ts before @/ aliases resolve.
- Percent-encode the password when building the Postgres DSN. A user-supplied password containing @ : / # does not merely re-parse to the wrong host — it fails to parse as a URL at all, so a correct password surfaced as a connection failure.
- Tell 'Postgres rejected this password' apart from 'Postgres never started'. On the keep-the-volume path a wrong password left a healthy server and the old generic 'container did not become healthy' error, which is the confusion this change set exists to remove.

Adds a CSP regression test for the unset-socket-URL production case; verified it fails against the previous condition.

* improvement(setup): make k8s mode end somewhere usable, and show install progress

Two things made k8s mode the least satisfying path.

The services are ClusterIP, so a successful install left nothing on :3000 — 'Sim is ready' was true about the cluster and useless to the user, who had to notice and run a port-forward by hand. Compose opens a browser and dev offers to start the server; k8s now offers the forward the same way and runs it in the foreground so Ctrl-C ends it. Realtime gets its own forward (kubectl takes one resource per invocation) or the editor socket fails; it is a child in the same process group, so the terminal's Ctrl-C reaches it, and it is killed explicitly when the app forward exits.

'helm --wait' then blocked for minutes with a single static spinner, so a slow image pull looked identical to a wedged install. Run helm asynchronously and poll the cluster, so the spinner reports '3/3 pods ready · 1 starting'. CronJob-owned pods are excluded: the chart schedules a lot of them (36 on a running cluster here) and they finish as Completed, which would swamp the count and make readiness jitter for reasons unrelated to the install. Restarting pods are surfaced too — a cold cluster restarts realtime while Postgres comes up, and a silent spinner made that look like nothing was happening.

* fix(setup): identify Sim compose projects by content, not filename

Cursor (High): composeInstalls treated any project whose config basename was docker-compose.prod.yml or docker-compose.local.yml as a Sim install. Those names are common, and sim reset runs 'compose down -v' — so a stranger's stack could have had its volumes destroyed.

I introduced that reach. The previous ROOT-scoped '-f' probe was implicitly safe because it could only ever see the project in this checkout; switching to a global 'compose ls' to find stacks started elsewhere means projects must be identified by content instead. Read the config file Docker recorded and require a Sim marker (the published app image, or the app Dockerfile this repo builds), so both the prod and local variants match while an unrelated file with the same name does not. An unreadable or since-deleted file is left unmanaged rather than assumed ours.

Verified against a decoy nginx compose file using our exact filename: ignored, while both real Sim compose files still match.

* fix(setup): scope the compose port skip to published ports; print both k8s forwards

Review round on #5964:

- ensureComposePortsFree skipped conflict handling whenever the project had any container running, so leftover db/redis (which publish neither app port) waved through a foreign process on :3000 — it then surfaced as a raw compose bind error instead of the prompt. Read the host ports the project actually publishes and skip only those; the remaining ports still get the full check. Reading from the containers rather than the file matters because what counts is what is bound right now.
- The post-install note and the skip path documented only the app forward, while offerPortForward runs two. Skipping the prompt or copying the printed command left the editor's socket dead — the exact failure this change set exists to fix. Both commands now come from one forwardCommands() helper, so what is printed and what is run cannot drift.

* fix(setup): one source for the k8s forwards, and surface a dead realtime forward

Third round on the same theme, so fix it at the root rather than at another call site.

- lifecycle's k8sReachHints (used by sim start/restart) still restated an app-only forward, recreating the dead editor socket the setup path had just been fixed for. forwardCommands is now exported and consumed there, so every place that tells a user how to reach a ClusterIP release derives it from one definition.
- The realtime forward was spawned with stdio ignored and never checked, so a busy :3002 or a missing service killed it silently while the app forward kept running — indistinguishable from success until the editor won't connect. Keep its stderr, warn on an exit we did not ask for, and stay quiet on the intentional kill.

* fix(setup): pin the compose project on every lifecycle op

composeInstalls records the real project name from 'compose ls' and status and the destructive confirms print it, but every op ran 'compose -f <file>' with only cwd set — so Compose re-derived the project from that directory. The derived name is frequently not the recorded one: a directory is lowercased and stripped of dots (Sim.Demo_Test derives simdemo_test), and an explicit -p or COMPOSE_PROJECT_NAME at creation diverges outright. stop/down/reset could therefore act on a different project than the one named in the confirm, and reset runs 'down -v'.

Route every op through composeArgs(), which pins '-p <recorded project>'. cwd stays, since the file's own relative paths still resolve against it. Verified with a stack started as -p pinned-name from a directory deriving simdemo_test: the old form found 0 of its containers, the pinned form finds them.

* fix(setup): warn on both halves of a mothership mismatch

mothershipOverride warned only when SIM_CLI_AUTH_ORIGIN was set without SIM_AGENT_API_URL, while its own copy said to set both or neither. The reverse is the same failure mirrored: with only SIM_AGENT_API_URL set, the Chat key is still minted against the default prod auth origin and then validated against the override, which rejects it — silently, which is exactly what this helper exists to prevent.

Warn on either asymmetry, and read the default origin from one constant shared with the handoff so the message can't claim an origin the code no longer uses.

* fix(setup): warn about a half-set mothership before minting the key

mothershipOverride ran two steps after promptCopilotKey, so a half-set override minted a key against one environment, stored it, and only then warned that the other environment would reject it. Worse on a re-run: promptCopilotKey offers to keep an existing COPILOT_API_KEY and defaults to yes, so the bad key survives.

Move the override ahead of the key prompt in both compose and dev, so the warning arrives while it can still change the outcome — the user can abort and set the missing half before anything is minted. Nothing in the override depends on the key, so the order is free.
2026-07-25 17:48:45 -04:00

497 lines
18 KiB
TypeScript

import { spawnSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { DB_CONTAINER, type Detection, REDIS_CONTAINER, runDetection } from './detect.ts'
import { archiveEnvFile, ROOT } from './env-files.ts'
import { SetupError } from './errors.ts'
import { forwardCommands, isLocalKubeContext } from './modes/k8s.ts'
import { httpHealth } from './probes.ts'
import * as p from './prompter.ts'
import { glyph, theme } from './theme.ts'
const APP_URL = 'http://localhost:3000'
const REALTIME_HEALTH = 'http://localhost:3002/health'
const POSTGRES_VOLUME = 'sim-postgres-data'
const COMPOSE_FILES = ['docker-compose.prod.yml', 'docker-compose.local.yml'] as const
const K8S_RELEASE = 'sim-dev'
const K8S_NAMESPACE = 'sim-dev'
export const LIFECYCLE_COMMANDS = [
'start',
'stop',
'restart',
'status',
'logs',
'down',
'reset',
] as const
export type LifecycleCommand = (typeof LIFECYCLE_COMMANDS)[number]
export function isLifecycleCommand(value: string): value is LifecycleCommand {
return (LIFECYCLE_COMMANDS as readonly string[]).includes(value)
}
/**
* POSIX-quote a value for a copyable shell hint — a kube-context can contain
* whitespace or metacharacters that would break a copied command.
*/
function shq(value: string): string {
if (/^[A-Za-z0-9._/-]+$/.test(value)) return value
return `'${value.replace(/'/g, `'\\''`)}'`
}
/** Is the Docker daemon reachable? Distinguishes "nothing installed" from "can't see". */
function dockerReachable(): boolean {
return spawnSync('docker', ['info'], { stdio: 'ignore' }).status === 0
}
/** Non-throwing docker probe; returns trimmed stdout or null on any failure. */
function dockerText(args: string[], cwd: string = ROOT): string | null {
const result = spawnSync('docker', args, { cwd, encoding: 'utf8' })
return result.status === 0 ? result.stdout.trim() : null
}
/** Docker command whose output the user should see (up, logs); returns exit code. */
function dockerInherit(args: string[], cwd: string = ROOT): number {
return spawnSync('docker', args, { cwd, stdio: 'inherit' }).status ?? 1
}
/** Docker command that must succeed; throws a SetupError with stderr on failure. */
function dockerRun(args: string[], failMessage: string, cwd: string = ROOT): void {
const result = spawnSync('docker', args, { cwd, encoding: 'utf8' })
if (result.status !== 0) {
throw new SetupError(`${failMessage}: ${result.stderr.trim() || result.stdout.trim()}`)
}
}
interface ComposeInstall {
kind: 'compose'
/** Absolute path to the compose file Docker recorded for the project. */
file: string
/** Directory the stack was brought up from — every compose op runs here. */
dir: string
project: string
}
interface DevInstall {
kind: 'dev'
postgres: boolean
redis: boolean
}
interface K8sInstall {
kind: 'k8s'
context: string
/** False when the context's API server is outside the local allowlist — flagged before destructive ops. */
local: boolean
}
type Install = ComposeInstall | DevInstall | K8sInstall
interface ComposeProject {
Name: string
Status: string
ConfigFiles: string
}
/**
* Markers that a compose file is actually Sim's: the published app image
* (docker-compose.prod.yml) or the app Dockerfile this repo builds
* (docker-compose.local.yml).
*/
const SIM_COMPOSE_MARKERS = ['ghcr.io/simstudioai/simstudio', 'docker/app.Dockerfile'] as const
/**
* `docker-compose.prod.yml` is a common filename, so the name alone cannot say a
* project is ours — and `sim reset` runs `compose down -v`, which would destroy
* an unrelated stack's volumes. Read the file Docker recorded for the project and
* require a Sim marker inside it. The old ROOT-scoped `-f` probe was implicitly
* safe because it could only ever see the local project; discovering projects
* globally means identifying them by content instead.
*/
function isSimComposeFile(file: string): boolean {
if (!(COMPOSE_FILES as readonly string[]).includes(path.basename(file))) return false
try {
const contents = readFileSync(file, 'utf8')
return SIM_COMPOSE_MARKERS.some((marker) => contents.includes(marker))
} catch {
// Unreadable or deleted since the stack started — better to not manage it
// than to guess from the filename.
return false
}
}
/**
* Ask Docker which compose projects exist rather than guessing from the working
* directory. Compose derives a project name from the directory it was started
* in, so probing `-f <file> ps` only ever finds a stack when you happen to stand
* in the checkout that launched it — a globally linked `sim` would never see one
* — and it reports the same stack once per candidate file, since both files map
* to the same directory-derived project. `compose ls` records the real project
* and the exact config file, so one running stack yields exactly one install
* wherever it was started from.
*/
function composeInstalls(): ComposeInstall[] {
const raw = dockerText(['compose', 'ls', '-a', '--format', 'json'])
if (!raw) return []
let projects: ComposeProject[]
try {
projects = JSON.parse(raw)
} catch {
return []
}
const installs: ComposeInstall[] = []
for (const project of projects) {
// ConfigFiles is a comma-separated list when a stack was started with -f more than once.
const file = (project.ConfigFiles ?? '')
.split(',')
.map((entry) => entry.trim())
.find(isSimComposeFile)
if (!file) continue
installs.push({
kind: 'compose',
file,
dir: path.dirname(file),
project: project.Name,
})
}
return installs
}
/**
* Compose args for an op on a detected install. `-p` is not optional: without it
* Compose re-derives the project from the working directory, and that name is
* frequently NOT the one `compose ls` reported — a directory is lowercased and
* stripped of dots (`Sim.Demo` becomes `simdemo`), and an explicit `-p` or
* COMPOSE_PROJECT_NAME at creation time diverges outright. Acting on a
* re-derived name means `stop`/`down`/`reset` can target a different project
* than the one named in the confirm — and `reset` runs `down -v`. Pinning the
* recorded name makes the op hit exactly what was detected; cwd stays because
* the file's own relative paths (build contexts, env_file) resolve against it.
*/
function composeArgs(install: ComposeInstall, ...verb: string[]): string[] {
return ['compose', '-p', install.project, '-f', install.file, ...verb]
}
/** Dev mode owns the split env files and, usually, the managed Postgres/Redis. */
function devInstall(detection: Detection): DevInstall | null {
const postgres = detection.dbContainer?.managed ?? false
const redis = detection.redisContainer?.managed ?? false
const splitEnv = detection.envFiles.sim || detection.envFiles.realtime || detection.envFiles.db
if (!postgres && !redis && !splitEnv) return null
return { kind: 'dev', postgres, redis }
}
/**
* Detection is factual: a release either exists on the current context or it
* doesn't. Setup lets the user explicitly confirm a context whose API server is
* outside the local allowlist, so gating detection on locality would strand that
* release — `status`/`start`/`stop`/`down`/`reset` would all claim there is no
* Kubernetes install. Instead the locality is recorded and surfaced: every
* destructive path names the target (and flags a non-local one) before acting.
*/
function k8sInstall(detection: Detection): K8sInstall | null {
const context = detection.kubeContext
if (!context) return null
const status = spawnSync(
'helm',
['status', K8S_RELEASE, '--kube-context', context, '-n', K8S_NAMESPACE],
{ stdio: 'ignore' }
)
if (status.status !== 0) return null
return { kind: 'k8s', context, local: isLocalKubeContext(context) }
}
function detectInstalls(detection: Detection): Install[] {
const installs: Install[] = [...composeInstalls()]
const dev = devInstall(detection)
if (dev) installs.push(dev)
const k8s = k8sInstall(detection)
if (k8s) installs.push(k8s)
return installs
}
function describeInstall(install: Install): string {
if (install.kind === 'compose')
return `Docker Compose (project ${install.project} in ${install.dir})`
if (install.kind === 'dev') return 'Local dev (managed Postgres/Redis)'
// Naming a non-local cluster is the guard against acting on the wrong one after
// an ambient context switch — every destructive confirm renders this string.
const scope = install.local ? '' : ' — NOT a verified-local cluster'
return `Kubernetes (context ${install.context}${scope})`
}
/** One install → use it; several → let the user pick; none → null. */
async function resolveInstall(installs: Install[]): Promise<Install | null> {
if (installs.length <= 1) return installs[0] ?? null
const choice = await p.select({
message: 'Multiple installs detected — which one?',
options: installs.map((install, index) => ({
value: String(index),
label: describeInstall(install),
})),
initialValue: '0',
})
return installs[Number(choice)]
}
function managedNames(install: DevInstall): string[] {
const names: string[] = []
if (install.postgres) names.push(DB_CONTAINER)
if (install.redis) names.push(REDIS_CONTAINER)
return names
}
/**
* Reuses the wizard's forward commands rather than restating them — reaching a
* ClusterIP release needs both, and an app-only hint here would leave the
* editor's socket dead exactly the way the setup path used to.
*/
function k8sReachHints(context: string): string {
return [
...forwardCommands(context),
`kubectl --context ${shq(context)} -n ${K8S_NAMESPACE} get pods`,
].join('\n')
}
function start(install: Install): void {
if (install.kind === 'compose') {
const spin = p.spinner()
spin.start('Starting containers…')
dockerRun(composeArgs(install, 'up', '-d'), 'docker compose up failed', install.dir)
spin.stop('Containers up')
p.note(
[`open ${APP_URL}`, 'follow logs: sim logs', 'stop: sim stop'].join('\n'),
'Running'
)
return
}
if (install.kind === 'dev') {
const names = managedNames(install)
for (const name of names) dockerRun(['start', name], `docker start ${name} failed`)
if (names.length) p.log.step(`Started ${names.join(', ')}`)
p.note(
['start the dev server: bun run dev:full', 'stop DB/Redis: sim stop'].join('\n'),
'Ready'
)
return
}
p.note(k8sReachHints(install.context), 'Kubernetes is managed with kubectl')
}
function stop(install: Install): void {
if (install.kind === 'compose') {
const spin = p.spinner()
spin.start('Stopping containers…')
dockerRun(composeArgs(install, 'stop'), 'docker compose stop failed', install.dir)
spin.stop('Containers stopped (data kept)')
p.note(['start again: sim start', 'remove: sim down'].join('\n'), 'Stopped')
return
}
if (install.kind === 'dev') {
const names = managedNames(install)
for (const name of names) dockerRun(['stop', name], `docker stop ${name} failed`)
if (names.length) p.log.step(`Stopped ${names.join(', ')}`)
p.note(
'The dev server runs in the foreground — stop it with Ctrl-C in its terminal.',
'Dev server'
)
return
}
const c = shq(install.context)
p.note(
[
`scale down: kubectl --context ${c} -n ${K8S_NAMESPACE} scale deploy --all --replicas=0`,
`scale up: kubectl --context ${c} -n ${K8S_NAMESPACE} scale deploy --all --replicas=1`,
'tear down: sim down',
].join('\n'),
'Kubernetes'
)
}
function restart(install: Install): void {
if (install.kind === 'compose') {
const spin = p.spinner()
spin.start('Restarting containers…')
dockerRun(composeArgs(install, 'restart'), 'docker compose restart failed', install.dir)
spin.stop('Containers restarted')
p.note(`open ${APP_URL}`, 'Running')
return
}
if (install.kind === 'dev') {
const names = managedNames(install)
for (const name of names) dockerRun(['restart', name], `docker restart ${name} failed`)
if (names.length) p.log.step(`Restarted ${names.join(', ')}`)
p.note('Restart the dev server manually (Ctrl-C, then bun run dev:full).', 'Dev server')
return
}
p.note(k8sReachHints(install.context), 'Kubernetes is managed with kubectl')
}
function showLogs(install: Install): void {
if (install.kind === 'compose') {
dockerInherit(composeArgs(install, 'logs', '-f', '--tail', '100'), install.dir)
return
}
if (install.kind === 'dev') {
const names = managedNames(install)
p.note(
[
'the dev server logs stream in its own terminal (bun run dev:full)',
...names.map((name) => `container: docker logs -f ${name}`),
].join('\n'),
'Logs'
)
return
}
spawnSync(
'kubectl',
['--context', install.context, '-n', K8S_NAMESPACE, 'logs', '-f', `deploy/${K8S_RELEASE}-app`],
{ stdio: 'inherit' }
)
}
async function down(install: Install): Promise<void> {
const ok = await p.confirm({
message: `Remove ${describeInstall(install)} containers? Data volumes are kept.`,
initialValue: false,
})
if (!ok) {
p.log.info('Left it running.')
return
}
if (install.kind === 'compose') {
dockerRun(composeArgs(install, 'down'), 'docker compose down failed', install.dir)
p.log.step('Containers removed (volumes kept)')
return
}
if (install.kind === 'dev') {
const names = managedNames(install)
if (names.length) {
dockerRun(['rm', '-f', ...names], 'docker rm failed')
p.log.step(`Removed ${names.join(', ')} (Postgres volume ${POSTGRES_VOLUME} kept)`)
} else {
p.log.info('No managed containers to remove.')
}
return
}
const result = spawnSync(
'helm',
['uninstall', K8S_RELEASE, '--kube-context', install.context, '-n', K8S_NAMESPACE],
{ stdio: 'inherit' }
)
if (result.status !== 0) throw new SetupError('helm uninstall failed')
p.log.step(`Uninstalled ${K8S_RELEASE}`)
}
async function reset(install: Install | null): Promise<void> {
// Name the exact target: k8s acts on the ambient context, so spelling out which
// cluster (or compose file / dev containers) is about to be wiped keeps a reset
// from silently hitting the wrong same-named install after a context switch.
const target = install ? ` ${describeInstall(install)} will be removed.` : ''
const ok = await p.confirm({
message: theme.error(
`Reset archives your .env files and wipes managed data (volumes).${target} Continue?`
),
initialValue: false,
})
if (!ok) {
p.log.info('Reset cancelled.')
return
}
for (const target of ['sim', 'realtime', 'db', 'root'] as const) {
const backup = archiveEnvFile(target)
if (backup) p.log.step(`Archived ${backup}`)
}
if (install?.kind === 'compose') {
dockerRun(composeArgs(install, 'down', '-v'), 'docker compose down -v failed', install.dir)
p.log.step('Containers and volumes removed')
} else if (install?.kind === 'dev') {
const names = managedNames(install)
if (names.length) spawnSync('docker', ['rm', '-f', ...names], { cwd: ROOT, stdio: 'ignore' })
spawnSync('docker', ['volume', 'rm', POSTGRES_VOLUME], { cwd: ROOT, stdio: 'ignore' })
p.log.step('Managed containers and Postgres volume removed')
} else if (install?.kind === 'k8s') {
const uninstall = spawnSync(
'helm',
['uninstall', K8S_RELEASE, '--kube-context', install.context, '-n', K8S_NAMESPACE],
{ stdio: 'inherit' }
)
// Env files are already archived, so a failed uninstall leaves a live release
// with no local config — the worst thing to do is call that a success.
if (uninstall.status !== 0) {
throw new SetupError(
`env files were archived, but helm uninstall failed — the ${K8S_RELEASE} release is still running.`,
[
`retry: ${theme.command(`helm uninstall ${K8S_RELEASE} --kube-context ${shq(install.context)} -n ${K8S_NAMESPACE}`)}`,
`check the release: ${theme.command(`helm status ${K8S_RELEASE} --kube-context ${shq(install.context)} -n ${K8S_NAMESPACE}`)}`,
]
)
}
p.log.step(`Uninstalled ${K8S_RELEASE}`)
}
p.note(`start fresh with ${theme.command('sim setup')}`, 'Reset complete')
}
async function status(): Promise<void> {
const detection = await runDetection()
const installs = detectInstalls(detection)
const docker = dockerReachable()
console.log(`\n${theme.heading('◆ Sim status')}\n`)
// Every container probe goes through Docker, so when the daemon is down the
// honest answer is "unknown", not "absent" — and a compose stack is invisible
// entirely. Saying "no install detected" there sends the user to re-run setup
// for what is really a stopped Docker Desktop.
if (!docker) {
console.log(
` ${glyph.warn} Docker is not reachable — container and Compose state below is unknown.`
)
console.log(` ${theme.muted('start Docker Desktop (or OrbStack), then re-run this.')}\n`)
}
if (installs.length === 0) {
console.log(
docker
? ` ${glyph.warn} No Sim install detected — run ${theme.command('sim setup')}.`
: ` ${glyph.warn} No install detected, but that may just be Docker being down.`
)
return
}
for (const install of installs) console.log(` ${glyph.pass} ${describeInstall(install)}`)
const containerState = (state: { state: 'running' | 'stopped' } | null) =>
docker ? (state ? state.state : 'absent') : 'unknown (docker down)'
console.log()
console.log(` postgres (${DB_CONTAINER}): ${containerState(detection.dbContainer)}`)
console.log(` redis (${REDIS_CONTAINER}): ${containerState(detection.redisContainer)}`)
const [app, realtime] = await Promise.all([
httpHealth(`${APP_URL}/api/health`),
httpHealth(REALTIME_HEALTH),
])
console.log()
console.log(` app (:3000) ${app ? glyph.pass : glyph.fail}`)
console.log(` realtime (:3002) ${realtime ? glyph.pass : glyph.fail}`)
}
export async function runLifecycle(command: LifecycleCommand): Promise<void> {
if (command === 'status') return status()
const installs = detectInstalls(await runDetection())
// Reset stays useful with nothing running — it still archives stray .env files.
if (command === 'reset') return reset(await resolveInstall(installs))
const install = await resolveInstall(installs)
if (!install) {
p.log.warn(`No Sim install detected. Run ${theme.command('sim setup')} first.`)
return
}
switch (command) {
case 'start':
return start(install)
case 'stop':
return stop(install)
case 'restart':
return restart(install)
case 'logs':
return showLogs(install)
case 'down':
return down(install)
}
}