From cfd9a5d406c634e9fdd53e78546f48925c3c2492 Mon Sep 17 00:00:00 2001 From: Ashish Jha Date: Mon, 16 Nov 2026 16:48:54 +0530 Subject: [PATCH 1/2] fix: exit non-zero when doctor, stop --all or snapshot delete fail These commands reported failure but still exited 0, so a script or CI job couldn't tell that anything went wrong: - doctor printed "N critical issue(s) found" and exited 0. - stop --all carried on past a container it couldn't remove (and a proxy it couldn't stop), then printed "Sandbox shut down cleanly." and exited 0. - snapshot delete printed "not found or could not be deleted" and exited 0. Each now sets process.exitCode = 1 on failure, so output still flushes and the rest of stop's shutdown still runs. stop names what it couldn't stop instead of claiming a clean shutdown. doctor warnings alone still exit 0. CLI tests run the real entry point with a fake docker on PATH and a temp HOME; the three failure cases fail on main and pass here. Fixes #21 --- docs/cli-reference.md | 6 +++ src/commands/doctor.ts | 13 +++++- src/commands/snapshot.ts | 1 + src/commands/stop.ts | 56 +++++++++++++++---------- tests/cli.test.ts | 88 +++++++++++++++++++++++++++++++++++++++- 5 files changed, 141 insertions(+), 23 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 440b6e1..c5a7ef5 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -183,6 +183,8 @@ silo stop [--name ] [--all] 4. Writes `proxy.running = false` to config 5. Removes the `silo-sandbox-net` Docker network (if no other containers attached) +Exits 1 if any container or the proxy could not be stopped. The rest of the shutdown still runs. + **Stopping a named agent:** When `--name` is used, only that specific container is stopped. The proxy and network remain active for other agents. **Stopping all agents:** When `--all` is used, all containers with the `managed-by=silo` Docker label are discovered and stopped. @@ -626,6 +628,8 @@ Delete a saved snapshot. silo snapshot delete "clean-install" ``` +Exits 1 if the snapshot doesn't exist or can't be deleted. + --- ### `silo doctor` @@ -638,6 +642,8 @@ silo doctor Checks: Node.js version, Docker availability, Docker daemon status, config file existence, proxy health, container status. +Exits 1 if any check fails. Warnings alone exit 0, so `silo doctor` can gate a script or CI job. + --- ### `silo quickstart` diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts index ccb153c..ae8f63e 100644 --- a/src/commands/doctor.ts +++ b/src/commands/doctor.ts @@ -98,7 +98,7 @@ export async function runDoctor(): Promise { fix: "Run `silo onboard` to set up SILO", }); // Can't check more without config - printResults(results); + reportResults(results); return; } @@ -346,7 +346,18 @@ export async function runDoctor(): Promise { }); } + reportResults(results); +} + +/** + * Print the results and set a failing exit code when any check failed, so + * `silo doctor` can gate scripts and CI. Warnings alone still exit 0. + */ +function reportResults(results: CheckResult[]): void { printResults(results); + if (results.some((r) => r.status === "fail")) { + process.exitCode = 1; + } } // --------------------------------------------------------------------------- diff --git a/src/commands/snapshot.ts b/src/commands/snapshot.ts index 6b0e729..468a888 100644 --- a/src/commands/snapshot.ts +++ b/src/commands/snapshot.ts @@ -240,6 +240,7 @@ export async function runSnapshotDelete( spinner.succeed(`Snapshot "${chalk.cyan(snapshotName)}" deleted.`); } catch { spinner.fail(`Snapshot "${snapshotName}" not found or could not be deleted.`); + process.exitCode = 1; } log.blank(); diff --git a/src/commands/stop.ts b/src/commands/stop.ts index 290c57d..23a27c9 100644 --- a/src/commands/stop.ts +++ b/src/commands/stop.ts @@ -27,10 +27,15 @@ export async function runStop(opts: StopOptions = {}): Promise { await assertDockerAvailable(); let stoppedSomething = false; + // What couldn't be stopped. Anything here means a non-zero exit, so scripts + // and uninstall.sh don't carry on as if the sandbox were down. + const failures: string[] = []; if (opts.all) { // ── Stop ALL silo-managed containers ──────────────────────────────── - stoppedSomething = await stopAllAgents(); + const result = await stopAllAgents(); + stoppedSomething = result.stopped; + failures.push(...result.failed); } else { // ── Stop a single container ──────────────────────────────────────── const containerName = opts.name ? `silo-${opts.name}` : config.sandbox.containerName; @@ -50,6 +55,7 @@ export async function runStop(opts: StopOptions = {}): Promise { } catch (err) { spinner.fail("Failed to stop proxy daemon"); log.error(err instanceof Error ? err.message : String(err)); + failures.push("inference proxy"); } } else { log.info("Proxy daemon is not running — skipping."); @@ -66,7 +72,11 @@ export async function runStop(opts: StopOptions = {}): Promise { await cleanupSiloNetwork(); } - if (stoppedSomething) { + if (failures.length > 0) { + log.blank(); + log.error(`Could not stop: ${failures.join(", ")}.`); + process.exitCode = 1; + } else if (stoppedSomething) { log.blank(); log.success("Sandbox shut down cleanly."); } @@ -99,35 +109,39 @@ async function stopSingleAgent(containerName: string): Promise { return false; } -async function stopAllAgents(): Promise { +async function stopAllAgents(): Promise<{ stopped: boolean; failed: string[] }> { + let names: string[]; try { const { stdout } = await execa("docker", [ "ps", "-a", "--filter", "label=managed-by=silo", "--format", "{{.Names}}", ]); + names = stdout.trim().split("\n").filter(Boolean); + } catch (err) { + log.error(`Could not list SILO containers: ${err instanceof Error ? err.message : String(err)}`); + return { stopped: false, failed: ["container list"] }; + } - const names = stdout.trim().split("\n").filter(Boolean); - if (names.length === 0) { - log.info("No SILO agent containers found."); - return false; - } + if (names.length === 0) { + log.info("No SILO agent containers found."); + return { stopped: false, failed: [] }; + } - let stopped = false; - for (const name of names) { - const spinner = ora(`Stopping "${name}"…`).start(); - try { - await stopContainer(name); - spinner.succeed(`Removed "${name}"`); - stopped = true; - } catch (err) { - spinner.fail(`Failed to stop "${name}": ${err instanceof Error ? err.message : String(err)}`); - } + let stopped = false; + const failed: string[] = []; + for (const name of names) { + const spinner = ora(`Stopping "${name}"…`).start(); + try { + await stopContainer(name); + spinner.succeed(`Removed "${name}"`); + stopped = true; + } catch (err) { + spinner.fail(`Failed to stop "${name}": ${err instanceof Error ? err.message : String(err)}`); + failed.push(name); } - return stopped; - } catch { - return false; } + return { stopped, failed }; } // --------------------------------------------------------------------------- diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 7d6c919..0372333 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeAll, afterAll } from "vitest"; import { execa } from "execa"; -import { mkdtempSync, rmSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -47,3 +47,89 @@ describe("CLI exit codes", () => { 30_000, ); }); + +// --------------------------------------------------------------------------- +// Commands that fail must exit non-zero, so scripts and CI can rely on them. +// A fake `docker` on PATH stands in for the daemon. FAKE_DOCKER_FAIL picks what +// fails: "all", "rmi", or "rm:". +// --------------------------------------------------------------------------- + +const FAKE_DOCKER = `#!/bin/sh +[ "$FAKE_DOCKER_FAIL" = "all" ] && { echo "Cannot connect to the Docker daemon" >&2; exit 1; } +case "$1" in + info|version|stop) exit 0 ;; + ps) printf 'silo-a\\nsilo-b\\n'; exit 0 ;; + rm) for a in "$@"; do [ "rm:$a" = "$FAKE_DOCKER_FAIL" ] && { echo "Error: could not remove $a" >&2; exit 1; }; done; exit 0 ;; + rmi) [ "$FAKE_DOCKER_FAIL" = "rmi" ] && { echo "Error: No such image" >&2; exit 1; }; exit 0 ;; + *) exit 1 ;; +esac +`; + +describe("exit codes when a command fails", () => { + let fakeBin: string; + let configuredHome: string; + + beforeAll(async () => { + fakeBin = mkdtempSync(join(tmpdir(), "silo-fake-docker-")); + writeFileSync(join(fakeBin, "docker"), FAKE_DOCKER); + chmodSync(join(fakeBin, "docker"), 0o755); + + // A real, valid config written through the config manager. + configuredHome = mkdtempSync(join(tmpdir(), "silo-cli-home-")); + mkdirSync(join(configuredHome, "ws")); + const write = ` + const { writeConfig } = await import("./src/config/manager.ts"); + const { SiloConfigSchema } = await import("./src/config/schema.ts"); + writeConfig(SiloConfigSchema.parse({ + version: "1", + llm: { provider: "openai", apiKey: "sk-test-key", model: "gpt-4o" }, + sandbox: { image: "silo-sandbox:latest", containerName: "silo-agent", + workspacePath: ${JSON.stringify(join(configuredHome, "ws"))}, cpuLimit: "1.0", memoryLimit: "1g", autoOpenLogs: false }, + }));`; + await execa("node", ["--import", "tsx", "--input-type=module", "-e", write], { + cwd: repoRoot, + env: { HOME: configuredHome }, + }); + }, 30_000); + + afterAll(() => { + rmSync(fakeBin, { recursive: true, force: true }); + rmSync(configuredHome, { recursive: true, force: true }); + }); + + function siloWith(homeDir: string, fail: string, ...args: string[]) { + return execa("node", ["--import", "tsx", "src/cli.ts", ...args], { + cwd: repoRoot, + env: { HOME: homeDir, PATH: `${fakeBin}:${process.env.PATH}`, FAKE_DOCKER_FAIL: fail }, + reject: false, + }); + } + + it("doctor exits 1 when a check fails", async () => { + const result = await siloWith(home, "all", "doctor"); + expect(result.stdout + result.stderr).toMatch(/critical issue/); + expect(result.exitCode).toBe(1); + }, 30_000); + + it("snapshot delete exits 1 when the snapshot can't be deleted", async () => { + const result = await siloWith(configuredHome, "rmi", "snapshot", "delete", "missing"); + expect(result.exitCode).toBe(1); + }, 30_000); + + it("stop --all exits 1 when a container can't be stopped", async () => { + const result = await siloWith(configuredHome, "rm:silo-b", "stop", "--all"); + expect(result.stdout + result.stderr).toMatch(/Could not stop: silo-b/); + expect(result.exitCode).toBe(1); + }, 30_000); + + it("stop --all still exits 0 when everything stops", async () => { + const result = await siloWith(configuredHome, "", "stop", "--all"); + expect(result.stdout + result.stderr).toMatch(/shut down cleanly/); + expect(result.exitCode).toBe(0); + }, 30_000); + + it("snapshot delete still exits 0 when the snapshot is deleted", async () => { + const result = await siloWith(configuredHome, "", "snapshot", "delete", "present"); + expect(result.exitCode).toBe(0); + }, 30_000); +}); From c8d412d01685927d7ed9cdf1ae3958f8815021a7 Mon Sep 17 00:00:00 2001 From: Ashish Jha Date: Mon, 16 Nov 2026 18:02:50 +0530 Subject: [PATCH 2/2] test: give each throwaway HOME its own config directory On Linux, conf keeps its config under $XDG_CONFIG_HOME when that is set, regardless of HOME, and CI runners set it. Every CLI test therefore read and wrote the runner's real config directory: the config written for the snapshot/stop tests leaked into the doctor test's HOME, failed to decrypt (its key is derived from a different HOME) and doctor aborted with "Unsupported state or unable to authenticate data". macOS ignores XDG_CONFIG_HOME, so this only showed up in CI. Point XDG_CONFIG_HOME inside each temp HOME for every spawned CLI. --- tests/cli.test.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 0372333..0c5f7a0 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -11,6 +11,13 @@ import { fileURLToPath } from "node:url"; const repoRoot = fileURLToPath(new URL("..", import.meta.url)); let home: string; +// conf stores the config under $XDG_CONFIG_HOME on Linux when it's set (CI +// runners set it), ignoring HOME. Pin it inside each throwaway HOME, or every +// test shares, and writes to, the runner's real config directory. +function isolatedEnv(homeDir: string): Record { + return { HOME: homeDir, XDG_CONFIG_HOME: join(homeDir, ".config") }; +} + beforeAll(() => { home = mkdtempSync(join(tmpdir(), "silo-cli-test-")); }); @@ -22,7 +29,7 @@ afterAll(() => { function silo(...args: string[]) { return execa("node", ["--import", "tsx", "src/cli.ts", ...args], { cwd: repoRoot, - env: { HOME: home }, + env: isolatedEnv(home), reject: false, }); } @@ -88,7 +95,7 @@ describe("exit codes when a command fails", () => { }));`; await execa("node", ["--import", "tsx", "--input-type=module", "-e", write], { cwd: repoRoot, - env: { HOME: configuredHome }, + env: isolatedEnv(configuredHome), }); }, 30_000); @@ -100,7 +107,7 @@ describe("exit codes when a command fails", () => { function siloWith(homeDir: string, fail: string, ...args: string[]) { return execa("node", ["--import", "tsx", "src/cli.ts", ...args], { cwd: repoRoot, - env: { HOME: homeDir, PATH: `${fakeBin}:${process.env.PATH}`, FAKE_DOCKER_FAIL: fail }, + env: { ...isolatedEnv(homeDir), PATH: `${fakeBin}:${process.env.PATH}`, FAKE_DOCKER_FAIL: fail }, reject: false, }); }