Skip to content

Commit a1ea4e3

Browse files
omercangumusCopilottamirdresher
authored
fix(cli): return failure status from doctor (#2376)
Warnings remain non-fatal, and standalone validation checks exit-code propagation. Closes #2362 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Tamir Dresher <tamir.dresher@gmail.com>
1 parent d4c5a23 commit a1ea4e3

5 files changed

Lines changed: 119 additions & 1 deletion

File tree

‎.changeset/doctor-exit-status.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@bradygaster/squad-cli': patch
3+
---
4+
5+
Return a failing exit status from `squad doctor` when checks fail.

‎packages/squad-cli/src/cli/commands/doctor.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1228,4 +1228,7 @@ export async function doctorCommand(cwd?: string): Promise<void> {
12281228
const mode = getDoctorMode(resolvedCwd);
12291229
const checks = await runDoctor(resolvedCwd);
12301230
printDoctorReport(checks, mode);
1231+
if (checks.some(check => check.status === 'fail')) {
1232+
process.exitCode = 1;
1233+
}
12311234
}

‎scripts/release/validate-standalone-bundle.mjs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,19 @@ writeFileSync(
8080

8181
let lifecycle;
8282
let workspaceReleaseMs = 0;
83+
let doctorExitCodes;
8384
try {
85+
const doctorTarget = process.platform === 'win32' ? runtimeCommand : launcher;
86+
doctorExitCodes = {
87+
primary: verifyDoctorFailure(doctorTarget, smokeRoot),
88+
};
89+
if (process.platform === 'win32') {
90+
doctorExitCodes.cmd = verifyDoctorFailure(launcher, smokeRoot);
91+
doctorExitCodes.powershell = verifyDoctorFailure(path.join(bundleDir, 'squad.ps1'), smokeRoot);
92+
}
93+
if (new Set(Object.values(doctorExitCodes)).size !== 1) {
94+
throw new Error(`Standalone doctor launchers returned different exit codes: ${JSON.stringify(doctorExitCodes)}`);
95+
}
8496
const probes = await Promise.all([
8597
probeBridge('squad_state', smokeRoot, homeDir),
8698
probeBridge('squad_state_duplicate', smokeRoot, homeDir),
@@ -118,6 +130,7 @@ const report = {
118130
sha256: archiveSha256,
119131
},
120132
lifecycle,
133+
doctorExitCodes,
121134
rootDeleteRejection: rootDelete,
122135
};
123136
mkdirSync(path.dirname(outputPath), { recursive: true });
@@ -143,6 +156,29 @@ function runCapture(command, args, shell) {
143156
return result.stdout.trim();
144157
}
145158

159+
function verifyDoctorFailure(command, cwd) {
160+
const escapedCommand = command.replace(/'/g, "''");
161+
const result = process.platform === 'win32'
162+
? spawnSync('powershell.exe', [
163+
'-NoProfile',
164+
'-NonInteractive',
165+
'-Command',
166+
`& '${escapedCommand}' doctor; exit $LASTEXITCODE`,
167+
], { cwd, encoding: 'utf8', windowsHide: true, timeout: 60_000 })
168+
: spawnSync(command, ['doctor'], { cwd, encoding: 'utf8', windowsHide: true, timeout: 60_000 });
169+
const output = `${result.stdout ?? ''}\n${result.stderr ?? ''}`;
170+
if (result.error || result.status === null || result.status === 0) {
171+
throw new Error(
172+
`Standalone doctor did not propagate a failed check (status=${result.status}): `
173+
+ `${result.error?.message ?? output}`,
174+
);
175+
}
176+
if (!/Summary:.*[1-9]\d* failed/.test(output)) {
177+
throw new Error(`Standalone doctor exited unsuccessfully without reporting failed checks: ${output}`);
178+
}
179+
return result.status;
180+
}
181+
146182
function spawnLauncher(args, cwd, env) {
147183
if (process.platform === 'win32') {
148184
return spawn(launcher, args, {

‎test/cli/doctor.test.ts‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
1010
import { mkdir, readFile, rm, writeFile } from 'fs/promises';
1111
import { join, resolve } from 'path';
1212
import { existsSync, mkdirSync } from 'fs';
13-
import { execFileSync } from 'child_process';
13+
import { execFileSync, spawnSync } from 'child_process';
1414
import { randomBytes } from 'crypto';
1515
import {
1616
runDoctor,
@@ -21,11 +21,15 @@ import {
2121
checkHistoryArchiveIntegrity,
2222
} from '@bradygaster/squad-cli/commands/doctor';
2323
import type { DoctorCheck } from '@bradygaster/squad-cli/commands/doctor';
24+
import { clearResolveSquadCache } from '@bradygaster/squad-sdk/resolution';
2425
import { FSStorageProvider, OrphanBranchBackend } from '@bradygaster/squad-sdk';
2526
import { getPackageVersion } from '../../packages/squad-cli/src/cli/core/version.js';
2627
import { ensureCastingRegistryPair } from '@bradygaster/squad-sdk/casting';
2728

2829
const TEST_ROOT = join(process.cwd(), `.test-doctor-${randomBytes(4).toString('hex')}`);
30+
const TEST_PROFILE = join(process.cwd(), `.test-doctor-profile-${randomBytes(4).toString('hex')}`);
31+
const CLI_ENTRY = resolve(process.cwd(), 'packages/squad-cli/dist/cli-entry.js');
32+
let originalHomeEnv: { HOME: string | undefined; USERPROFILE: string | undefined };
2933

3034
async function scaffold(root: string): Promise<void> {
3135
const sq = join(root, '.squad');
@@ -58,18 +62,40 @@ function initTestGit(root: string): void {
5862
execFileSync('git', ['config', 'core.autocrlf', 'false'], { cwd: root });
5963
}
6064

65+
function runDoctorCli(cwd: string) {
66+
return spawnSync(process.execPath, [CLI_ENTRY, 'doctor'], {
67+
cwd,
68+
encoding: 'utf8',
69+
timeout: 30_000,
70+
windowsHide: true,
71+
});
72+
}
73+
6174
describe('squad doctor', () => {
6275
beforeEach(async () => {
6376
if (existsSync(TEST_ROOT)) {
6477
await rm(TEST_ROOT, { recursive: true, force: true });
6578
}
6679
await mkdir(TEST_ROOT, { recursive: true });
80+
await mkdir(TEST_PROFILE, { recursive: true });
81+
originalHomeEnv = { HOME: process.env['HOME'], USERPROFILE: process.env['USERPROFILE'] };
82+
process.env['HOME'] = TEST_PROFILE;
83+
process.env['USERPROFILE'] = TEST_PROFILE;
84+
clearResolveSquadCache();
6785
});
6886

6987
afterEach(async () => {
88+
if (originalHomeEnv.HOME === undefined) delete process.env['HOME'];
89+
else process.env['HOME'] = originalHomeEnv.HOME;
90+
if (originalHomeEnv.USERPROFILE === undefined) delete process.env['USERPROFILE'];
91+
else process.env['USERPROFILE'] = originalHomeEnv.USERPROFILE;
92+
clearResolveSquadCache();
7093
if (existsSync(TEST_ROOT)) {
7194
await rm(TEST_ROOT, { recursive: true, force: true });
7295
}
96+
if (existsSync(TEST_PROFILE)) {
97+
await rm(TEST_PROFILE, { recursive: true, force: true });
98+
}
7399
});
74100

75101
it('reports all green on a healthy local setup', async () => {
@@ -89,6 +115,32 @@ describe('squad doctor', () => {
89115
expect(checks.some((c: DoctorCheck) => c.name === 'copilot-sdk session.js ESM patch')).toBe(true);
90116
});
91117

118+
it('keeps warning-only doctor results successful', async () => {
119+
const projectRoot = join(TEST_ROOT, 'warning-only-project');
120+
await scaffold(projectRoot);
121+
await mkdir(join(projectRoot, '.git'), { recursive: true });
122+
const checks = await runDoctor(projectRoot);
123+
expect(checks.some(check => check.status === 'warn')).toBe(true);
124+
expect(checks.some(check => check.status === 'fail')).toBe(false);
125+
126+
const result = runDoctorCli(projectRoot);
127+
expect(result.error).toBeUndefined();
128+
expect(result.status, result.stderr || result.stdout).toBe(0);
129+
expect(result.stdout).toMatch(/Summary:.*0 failed, [1-9]\d* warnings/);
130+
}, 20_000);
131+
132+
it('returns a failing CLI exit code when doctor checks fail', async () => {
133+
const projectRoot = join(TEST_ROOT, 'failing-project');
134+
await scaffold(projectRoot);
135+
await mkdir(join(projectRoot, '.git'), { recursive: true });
136+
await rm(join(projectRoot, '.squad', 'routing.md'));
137+
138+
const result = runDoctorCli(projectRoot);
139+
expect(result.error).toBeUndefined();
140+
expect(result.status, result.stderr || result.stdout).toBe(1);
141+
expect(result.stdout).toMatch(/Summary:.*[1-9]\d* failed/);
142+
}, 20_000);
143+
92144
it('fails doctor and names the history when an archive pointer is dangling', async () => {
93145
await scaffold(TEST_ROOT);
94146
initTestGit(TEST_ROOT);

‎test/standalone-build.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@ import path from 'node:path';
1313

1414
const REPO_ROOT = process.cwd();
1515
const BUILD_SCRIPT = path.join(REPO_ROOT, 'scripts', 'build-standalone.mjs');
16+
const VALIDATE_SCRIPT = path.join(REPO_ROOT, 'scripts', 'release', 'validate-standalone-bundle.mjs');
1617
const INSTALL_SCRIPT = path.join(REPO_ROOT, 'scripts', 'install.sh');
1718

1819
const build = readFileSync(BUILD_SCRIPT, 'utf-8');
20+
const validate = readFileSync(VALIDATE_SCRIPT, 'utf-8');
1921
const install = readFileSync(INSTALL_SCRIPT, 'utf-8');
2022

2123
describe('build-standalone.mjs — runtime extraction', () => {
@@ -117,6 +119,20 @@ describe('build-standalone.mjs — Windows squad.exe', () => {
117119
});
118120
});
119121

122+
describe('standalone validation — doctor exit status', () => {
123+
it('runs the packaged Windows executable through PowerShell and propagates LASTEXITCODE', () => {
124+
expect(validate).toContain("spawnSync('powershell.exe'");
125+
expect(validate).toContain('runtimeCommand');
126+
expect(validate).toContain('process.platform === \'win32\' ? runtimeCommand : launcher');
127+
expect(validate).toContain("exit $LASTEXITCODE");
128+
expect(validate).toMatch(/verifyDoctorFailure\(doctorTarget, smokeRoot\)/);
129+
expect(validate).toMatch(/verifyDoctorFailure\(launcher, smokeRoot\)/);
130+
expect(validate).toMatch(/verifyDoctorFailure\(path\.join\(bundleDir, 'squad\.ps1'\), smokeRoot\)/);
131+
expect(validate).toContain('new Set(Object.values(doctorExitCodes))');
132+
expect(validate).toMatch(/Summary:\.\*\[1-9\]\\d\* failed/);
133+
});
134+
});
135+
120136
describe('build-standalone.mjs — launchers', () => {
121137
it('exports SQUAD_STANDALONE_HOME from every launcher', () => {
122138
// Without this the CLI cannot tell it is running from a bundle, and
@@ -129,6 +145,12 @@ describe('build-standalone.mjs — launchers', () => {
129145
expect(build).toContain('$env:SQUAD_STANDALONE_HOME = $root');
130146
});
131147

148+
it('preserves the CLI exit status in every generated launcher', () => {
149+
expect(build).toContain('exit /b %ERRORLEVEL%');
150+
expect(build).toContain('exit $LASTEXITCODE');
151+
expect(build).toContain('exec "$node_bin" "$root/${CLI_ENTRY}" "$@"');
152+
});
153+
132154
it('resolves symlinks in the posix launcher so PATH installs work', () => {
133155
// install.sh symlinks <prefix>/bin/squad -> <prefix>/lib/squad/squad, so
134156
// the launcher must resolve $0 before locating the runtime and app.

0 commit comments

Comments
 (0)