Merge origin/main into the Oct 8 triage wave

# Conflicts:
#	extension/sidepanel-terminal.js
#	test/gstack-doctor.test.ts
This commit is contained in:
garrytan committed 2026-10-08 15:57:20 +00:00
commit f10032f174
40 files changed
+1511 -80

No files matched your search

+33 -7
View File
@@ -1,10 +1,10 @@
import { afterEach, expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { spawnSync } from 'node:child_process';
import { prepareMethodology } from '../bin/gstack-autoplan-snapshot';
import { canonicalDestination, prepareMethodology } from '../bin/gstack-autoplan-snapshot';
const ROOT = resolve(import.meta.dir, '..');
const TOOL = join(ROOT, 'bin/gstack-autoplan-snapshot.ts');
@@ -41,7 +41,7 @@ test('actual raw R input initializes before scope and reaches a complete CEO dis
expect(missing.status).toBe(1);
expect(missing.stderr).toContain('Expected one Implementation plan section');
const initialized = invoke('init', f.source, f.source, f.restore);
expect(initialized.activePlan).toBe(f.source);
expect(initialized.activePlan).toBe(canonicalDestination(f.source));
expect(initialized.originalBytes).toBe(4607);
expect(initialized.originalSha256).toBe(hash(original));
expect(readFileSync(f.restore)).toEqual(original);
@@ -64,8 +64,8 @@ test('assigned active path preserves the separate original source and exact rest
if (emptyAssigned) writeFileSync(f.active, '');
const sourceMtime = statSync(f.source).mtimeMs;
const initialized = invoke('init', f.source, f.active, f.restore);
expect(initialized.activePlan).toBe(f.active);
expect(initialized.restorePath).toBe(f.restore);
expect(initialized.activePlan).toBe(canonicalDestination(f.active));
expect(initialized.restorePath).toBe(canonicalDestination(f.restore));
expect(readFileSync(f.source)).toEqual(original);
expect(statSync(f.source).mtimeMs).toBe(sourceMtime);
expect(readFileSync(f.restore)).toEqual(original);
@@ -79,8 +79,8 @@ test('the observed missing harness plans directory is initialized without a sepa
const active = join(f.dir, 'harness', 'plans', 'assigned.md');
const restore = join(f.dir, 'state', 'project', 'restore.md');
const initialized = invoke('init', f.source, active, restore);
expect(initialized.activePlan).toBe(active);
expect(initialized.restorePath).toBe(restore);
expect(initialized.activePlan).toBe(canonicalDestination(active));
expect(initialized.restorePath).toBe(canonicalDestination(restore));
expect(initialized.scope.dxRequired).toBe(true);
expect(readFileSync(f.source)).toEqual(original);
expect(readFileSync(restore)).toEqual(original);
@@ -241,3 +241,29 @@ catch (error) { console.error(error.message); process.exitCode = 1; }
expect(existsSync(active)).toBe(false);
expect(existsSync(restore)).toBe(false);
});
test.skipIf(process.platform === 'win32')('PAX-3638 Fix A: init through a symlinked plan directory reports the canonical destinations', () => {
const f = fixture();
const real = join(f.dir, 'real'), alias = join(f.dir, 'alias');
mkdirSync(real); symlinkSync(real, alias, 'dir');
const active = join(alias, 'nested', 'active.md'), restore = join(alias, 'restore.md');
const canonicalActive = join(realpathSync(real), 'nested', 'active.md');
expect(canonicalDestination(active)).toBe(canonicalActive);
expect(canonicalDestination(restore)).toBe(join(realpathSync(real), 'restore.md'));
const initialized = invoke('init', f.source, active, restore);
expect(initialized.activePlan).toBe(canonicalActive);
expect(initialized.restorePath).toBe(join(realpathSync(real), 'restore.md'));
expect(initialized.activePlan).not.toBe(active);
expect(readFileSync(canonicalActive, 'utf8')).toContain('## Implementation plan\n');
});
test('PAX-3638 Fix A: canonicalDestination is pure path math and leaves a leaf link or directory to initializePlan', () => {
const f = fixture();
const dirLeaf = join(f.dir, 'a-directory'); mkdirSync(dirLeaf);
expect(canonicalDestination(dirLeaf)).toBe(join(realpathSync(f.dir), 'a-directory'));
expect(existsSync(join(f.dir, 'missing', 'deeper'))).toBe(false);
expect(canonicalDestination(join(f.dir, 'missing', 'deeper', 'x.md'))).toBe(join(realpathSync(f.dir), 'missing', 'deeper', 'x.md'));
expect(existsSync(join(f.dir, 'missing'))).toBe(false);
// initializePlan still refuses a directory destination.
expect(cli('init', f.source, dirLeaf, f.restore).status).not.toBe(0);
});
+88
View File
@@ -1508,3 +1508,91 @@ describe('Autoplan ownership in a linked git worktree session', () => {
expect(output.hookSpecificOutput.permissionDecisionReason).toContain('code foreign_cwd');
});
});
describe('PAX-3638: symlinked plan directory and superseded failed inits', () => {
const skipWin = process.platform === 'win32';
/** The init Bash command spells active/restore through a symlinked directory; the journaled JSON stays canonical. */
function aliasFixture() {
const f = fixture();
const aliasDir = `${f.cwd}-alias`; dirs.push(aliasDir);
fs.symlinkSync(f.cwd, aliasDir, 'dir');
const aliasActive = path.join(aliasDir, 'active.md'), aliasRestore = path.join(aliasDir, 'restore.md');
const command = `bun "${ROOT}/bin/gstack-autoplan-snapshot.ts" init "${f.source}" "${aliasActive}" "${aliasRestore}"`;
(f.events[0] as any).input.command = command;
expect(f.init.activePlan).toBe(f.active); // canonical, unlike the argv above
expect(aliasActive).not.toBe(f.active);
const erroredInit = (id: string) => [
{ ...(structuredClone(f.events[0]!) as any), toolUseId: id },
{ ...(structuredClone(f.events[1]!) as any), toolUseId: id, isError: true, content: 'Error: Initialization source must be nonempty UTF-8 text' },
];
const ready = () => { f.message(); f.current(); f.reorder(); };
return { ...f, aliasDir, aliasActive, aliasRestore, command, erroredInit, ready };
}
test.skipIf(skipWin)('PAX-3638 Fix A: alias argv binds to init canonical paths', () => {
const f = aliasFixture(); f.ready();
expect(f.evaluate()).toEqual({ allow: true });
});
test.skipIf(skipWin)('PAX-3638 Fix B: errored first init followed by a correct init binds', () => {
const f = aliasFixture(); f.events.unshift(...f.erroredInit('bad-init') as any); f.ready();
expect(f.evaluate()).toEqual({ allow: true });
});
test.skipIf(skipWin)('PAX-3638 Fix C: errored init with no later success is init_failed and says re-run', () => {
const f = aliasFixture(); (f.events[1] as any).isError = true; f.ready();
const decision = f.evaluate() as any, reason: string = decision.reason;
expect(decision.allow).toBe(false); expect(reason).toContain('(code init_failed,');
expect(reason).toContain('re-run');
expect(reason).toContain('The most recent snapshot init call failed');
});
test.skipIf(skipWin)('PAX-3638 Fix B: a trailing errored init after a good bind is init_failed', () => {
const f = aliasFixture(); f.events.splice(2, 0, ...f.erroredInit('late-bad-init') as any); f.ready();
expect(f.evaluate()).toMatchObject({ allow: false, reason: expect.stringContaining('(code init_failed,') });
});
test.skipIf(skipWin)('PAX-3638 Fix B: a later good init supersedes a trailing errored one', () => {
const f = aliasFixture(); f.events.splice(2, 0, ...f.erroredInit('late-bad-init') as any);
f.events.splice(4, 0, { ...(structuredClone(f.events[0]!) as any), toolUseId: 'again' },
{ ...(structuredClone(f.events[1]!) as any), toolUseId: 'again', content: JSON.stringify({ ...f.init, reused: true }) });
f.ready();
expect(f.evaluate()).toEqual({ allow: true });
});
for (const field of ['activePlan', 'restorePath'] as const)
test.skipIf(skipWin)(`PAX-3638 Fix C: retargeted ${field} is init_mismatch without a re-run hint`, () => {
const f = aliasFixture(); (f.events[1] as any).content = JSON.stringify({ ...f.init, [field]: f.source }); f.ready();
const decision = f.evaluate() as any, reason: string = decision.reason;
expect(decision.allow).toBe(false); expect(reason).toContain('(code init_mismatch,');
expect(reason).toContain('do not match the canonical form of its own command arguments');
expect(reason).not.toContain('re-run');
});
test.skipIf(skipWin)('PAX-3638 Fix B: zero results for an init use still denies', () => {
const f = aliasFixture(); f.events.splice(1, 1); f.ready();
expect(f.evaluate()).toMatchObject({ allow: false, reason: expect.stringContaining('(code init_mismatch,') });
});
test.skipIf(skipWin)('PAX-3638 Fix A: an argv that cannot be canonicalized is init_mismatch, not a hook crash', () => {
const f = aliasFixture();
(f.events[0] as any).input.command = `bun "${ROOT}/bin/gstack-autoplan-snapshot.ts" init "${f.source}" "${f.source}/not-a-dir/active.md" "${f.aliasRestore}"`;
f.ready();
expect(f.evaluate()).toMatchObject({ allow: false, reason: expect.stringContaining('(code init_mismatch,') });
});
test.skipIf(skipWin)('PAX-3638 Fix A: a mistyped tool path is unbindable, and a later correct init still binds', () => {
const f = aliasFixture();
const bad = { ...(structuredClone(f.events[0]!) as any), toolUseId: 'typo' };
bad.input.command = bad.input.command.replace('gstack-autoplan-snapshot.ts', 'gstack-autoplan-snapshto.ts');
f.events.unshift(bad); f.ready();
expect(f.evaluate()).toEqual({ allow: true });
});
test.skipIf(skipWin)('PAX-3638 Fix A2: a pending Edit through the alias spelling is the same file', () => {
const f = aliasFixture(); f.message();
f.use('alias-edit', 'Edit', { file_path: f.aliasActive, old_string: 'Keep documented behavior.', new_string: 'Implement new behavior.' });
f.current(); f.reorder();
expect(f.evaluate()).toMatchObject({ allow: false, reason: expect.stringContaining('(code mutation_pending,') });
});
});
+61
View File
@@ -0,0 +1,61 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
// #2595: setup and gstack-doctor detect Smart App Control by launching each
// compiled binary with --version. Each entry must answer before any server
// start, discovery scan or network call, or the probe would misclassify a
// healthy build. Runs the source entries; the compiled binaries embed them.
const ROOT = path.resolve(import.meta.dir, '..');
const tmps: string[] = [];
afterEach(() => { for (const t of tmps.splice(0)) fs.rmSync(t, { recursive: true, force: true }); });
function runVersion(entry: string) {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-version-probe-'));
tmps.push(tmp);
const home = path.join(tmp, 'home');
fs.mkdirSync(home);
const r = spawnSync(process.execPath, ['run', path.join(ROOT, entry), '--version'], {
cwd: tmp,
env: {
...process.env,
HOME: home,
USERPROFILE: home,
BROWSE_STATE_FILE: path.join(tmp, 'state', '.gstack', 'browse.json'),
GSTACK_STATE_ROOT: path.join(tmp, 'gstack-state'),
HTTPS_PROXY: 'http://127.0.0.1:9',
HTTP_PROXY: 'http://127.0.0.1:9',
},
encoding: 'utf8',
timeout: 30_000,
});
return { ...r, tmp, home };
}
describe('compiled-binary entries answer --version early (#2595)', () => {
for (const entry of ['browse/src/cli.ts', 'browse/src/find-browse.ts', 'design/src/cli.ts', 'make-pdf/src/cli.ts', 'bin/gstack-global-discover.ts']) {
test(`${entry} --version exits 0 with one line and no side effects`, () => {
const r = runVersion(entry);
expect(r.status).toBe(0);
expect(r.stdout.trim().split('\n')).toHaveLength(1);
expect(r.stdout.trim()).not.toBe('');
expect(r.stderr).not.toContain('Starting server');
expect(r.stderr).not.toMatch(/Unknown|Usage/);
expect(fs.existsSync(path.join(r.tmp, 'state'))).toBe(false);
expect(fs.existsSync(path.join(r.tmp, 'gstack-state'))).toBe(false);
// `bun run` itself may create its runtime cache under the home; the entry writes nothing.
expect(fs.readdirSync(r.home).filter(name => name !== '.bun' && name !== 'AppData')).toEqual([]);
});
}
test('find-browse --version does not search for browse', () => {
expect(runVersion('browse/src/find-browse.ts').stdout).not.toContain('browse/dist/browse');
});
test('gstack-global-discover --version prints the checkout VERSION', () => {
const version = fs.readFileSync(path.join(ROOT, 'VERSION'), 'utf8').trim();
expect(runVersion('bin/gstack-global-discover.ts').stdout.trim()).toBe(version);
});
});
+76
View File
@@ -0,0 +1,76 @@
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { runBashScript } from './helpers/bash-script';
// #3071: CSO is optional, so a failed CSO build or publish must not abort
// scripts/build.sh before the browse server bundle and the completion stamp.
// GSTACK_STRICT_BUILD=1 (CI) keeps it fatal. Runs build.sh's real CSO block
// with scripts/build-cso.sh replaced by a stub that fails at a chosen stage.
const ROOT = path.resolve(import.meta.dir, '..');
const BUILD = fs.readFileSync(path.join(ROOT, 'scripts/build.sh'), 'utf8');
const START = 'if [ "${GSTACK_SETUP_RUNNING:-0}" = "1" ] && [ "${GSTACK_SETUP_SKIP_CSO_BUILD:-0}" = "1" ]; then';
const END = '\nbash browse/scripts/build-node-server.sh';
const block = BUILD.slice(BUILD.indexOf(START), BUILD.indexOf(END));
const tmps: string[] = [];
afterEach(() => { for (const t of tmps.splice(0)) fs.rmSync(t, { recursive: true, force: true }); });
function run(strict: string | undefined, status = 1) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-build-cso-nonfatal-'));
tmps.push(dir);
fs.mkdirSync(path.join(dir, 'bin'));
fs.mkdirSync(path.join(dir, 'scripts'));
fs.writeFileSync(path.join(dir, 'scripts/build-cso.sh'), [
'echo "stub CSO output (log=$GSTACK_CSO_BUILD_LOG)"',
'echo "Staged CSO core is not one executable regular file." >&2',
"printf 'result=failed\\nstage=publish\\n' > bin/.gstack-cso-build-result",
`exit ${status}`, '',
].join('\n'));
const env: Record<string, string> = { PATH: process.env.PATH ?? '' };
if (strict !== undefined) env.GSTACK_STRICT_BUILD = strict;
const r = runBashScript(`set -e\nROOT=${JSON.stringify(dir)}\nBUN_CMD=bun\n${block}\necho BUILD-CONTINUED`, { cwd: dir, env, timeout: 15_000 });
return { ...r, dir, log: path.join(dir, 'bin/.gstack-cso-build.log') };
}
// The block runs under any bash; Windows paths in the messages would only add
// quoting noise, and the Windows lane covers this in windows-setup-e2e.
describe.skipIf(process.platform === 'win32')('scripts/build.sh: CSO failure is non-fatal unless GSTACK_STRICT_BUILD=1 (#3071)', () => {
test('a CSO publish failure is reported with its stage, log and retry, and the build continues', () => {
const r = run(undefined);
expect(r.status).toBe(0);
expect(r.stdout).toContain('BUILD-CONTINUED');
expect(r.stderr).toContain('CSO unavailable: the publish step failed; the rest of the build continues.');
expect(r.stderr).toContain(`Log: ${r.log}`);
expect(r.stderr).toContain(`Retry: cd ${r.dir} && bun run build:cso`);
const log = fs.readFileSync(r.log, 'utf8');
expect(log).toContain(`stub CSO output (log=${r.log})`);
expect(log).toContain('Staged CSO core is not one executable regular file.');
});
test('GSTACK_STRICT_BUILD=0 is the same non-fatal path', () => {
expect(run('0').status).toBe(0);
});
test('GSTACK_STRICT_BUILD=1 makes the same failure fatal', () => {
const r = run('1');
expect(r.status).toBe(1);
expect(r.stdout).not.toContain('BUILD-CONTINUED');
expect(r.stderr).toContain('CSO publish failed and GSTACK_STRICT_BUILD=1 makes it fatal.');
});
test('a successful CSO build prints no unavailable line', () => {
const r = run('1', 0);
expect(r.status).toBe(0);
expect(r.stderr).not.toContain('CSO unavailable');
});
});
describe('scripts/build.sh: CSO step order (#3071)', () => {
test('the server bundle and stamp still come after the CSO step', () => {
const cso = BUILD.indexOf('bash scripts/build-cso.sh');
expect(BUILD.indexOf('bash browse/scripts/build-node-server.sh')).toBeGreaterThan(cso);
expect(BUILD.indexOf('mv -f "$BUILD_STAMP_TMP" "$BUILD_STAMP"')).toBeGreaterThan(cso);
});
});
+129
View File
@@ -0,0 +1,129 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { runBashScript } from './helpers/bash-script';
// #3071: scripts/build-cso.sh records each run's outcome in
// bin/.gstack-cso-build-result for setup's summary and gstack-doctor, and the
// parent clears its EXIT trap before exec'ing the native publisher so only the
// locked child cleans the stage. The real script runs; only compilation and
// the publisher lock are substituted (same seam as test/cso-distribution.test.ts).
const ROOT = resolve(import.meta.dir, '..');
const temps: string[] = [];
afterEach(() => { for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true }); });
const quote = (s: string) => "'" + s.replaceAll("'", "'\\''") + "'";
function fixture() {
const dir = mkdtempSync(join(tmpdir(), 'gstack-cso-result-')); temps.push(dir);
for (const sub of ['scripts', 'bin', 'lib/cso']) mkdirSync(join(dir, sub), { recursive: true });
copyFileSync(join(ROOT, 'scripts/build-cso.sh'), join(dir, 'scripts/build-cso.sh'));
writeFileSync(join(dir, 'VERSION'), '9.9.9.9\n');
writeFileSync(join(dir, 'publish lock'), '#!/bin/sh\nset -eu\nshift\nexport GSTACK_CSO_PUBLISH_LOCKED=1\nexec "$@"\n');
chmodSync(join(dir, 'publish lock'), 0o755);
const compiler = [
'#!/bin/sh', 'set -eu',
'count_file="$CSO_FIXTURE/compiler.count"; count=0',
'[ ! -f "$count_file" ] || count=$(cat "$count_file")',
'count=$((count+1)); printf "%s\\n" "$count" > "$count_file"',
'if [ "${CSO_FAIL_COMPILER_N:-0}" = "$count" ]; then echo "fixture compiler failed" >&2; exit 42; fi',
'output=""',
'while [ "$#" -gt 0 ]; do case "$1" in --outfile|-o) shift; output="$1" ;; esac; shift; done',
'if [ -n "$output" ]; then',
' case "$output" in',
' *gstack-cso-publish-lock*) cp "$CSO_FIXTURE/publish lock" "$output" ;;',
' *) printf "#!/bin/sh\\nprintf NEW\\\\n\\n" > "$output" ;;',
' esac',
' chmod +x "$output"',
'fi', '',
].join('\n');
writeFileSync(join(dir, 'compiler'), compiler); chmodSync(join(dir, 'compiler'), 0o755);
return dir;
}
function seedOld(dir: string, installed = '9.9.9.8 (0123456789ab)') {
for (const name of ['gstack-cso-launcher', 'gstack-cso-core', 'gstack-cso-watchdog']) {
writeFileSync(join(dir, 'bin', name), '#!/bin/sh\nprintf OLD\\\\n\n'); chmodSync(join(dir, 'bin', name), 0o755);
}
writeFileSync(join(dir, 'bin', '.gstack-cso-generation'), '0'.repeat(64) + '\n');
writeFileSync(join(dir, 'bin', '.gstack-cso-build-result'), `result=ok\nstage=publish\nreason=committed\nrevision=${installed}\ninstalled=${installed}\nlauncher=yes\ndiagnostic=old\n`);
}
function build(dir: string, env = '') {
return runBashScript(`${env} GIT_CEILING_DIRECTORIES=${quote(dirname(dir))} CSO_FIXTURE=${quote(dir)} BUN_CMD=${quote(join(dir, 'compiler'))} CSO_CC=${quote(join(dir, 'compiler'))} bash ${quote(join(dir, 'scripts/build-cso.sh'))}`, { timeout: 15_000 });
}
function record(dir: string): Record<string, string> {
const out: Record<string, string> = {};
for (const line of readFileSync(join(dir, 'bin', '.gstack-cso-build-result'), 'utf8').trim().split('\n')) {
const at = line.indexOf('=');
out[line.slice(0, at)] = line.slice(at + 1);
}
return out;
}
const stages = (dir: string) => readdirSync(join(dir, 'bin')).filter(name => name.startsWith('.gstack-cso-stage.'));
const launcherOutput = (dir: string) => readFileSync(join(dir, 'bin', 'gstack-cso-launcher'), 'utf8');
describe.skipIf(process.platform === 'win32')('build-cso.sh build-result record (#3071)', () => {
test('a successful build records ok with this revision installed', () => {
const dir = fixture();
const r = build(dir, `GSTACK_CSO_BUILD_LOG=${quote(join(dir, 'cso.log'))}`);
expect(r.status, r.stderr).toBe(0);
expect(record(dir)).toMatchObject({ result: 'ok', stage: 'publish', revision: '9.9.9.9', installed: '9.9.9.9', launcher: 'yes', diagnostic: join(dir, 'cso.log') });
expect(stages(dir)).toEqual([]);
});
test('a fresh build failure records the build stage with no usable launcher', () => {
const dir = fixture();
const r = build(dir, 'CSO_FAIL_COMPILER_N=1');
expect(r.status).toBe(42);
expect(record(dir)).toMatchObject({ result: 'failed', stage: 'build', reason: 'exit 42', installed: '', launcher: 'no' });
expect(stages(dir)).toEqual([]);
});
test('a failed upgrade keeps the previous generation and names its revision', () => {
const dir = fixture(); seedOld(dir);
const r = build(dir, 'GSTACK_CSO_BUILD_TESTING=1 GSTACK_CSO_BUILD_TEST_FAIL_AFTER=publish-core');
expect(r.status).toBe(86);
expect(launcherOutput(dir)).toContain('OLD');
expect(record(dir)).toMatchObject({ result: 'failed', stage: 'publish', reason: 'exit 86', revision: '9.9.9.9', installed: '9.9.9.8 (0123456789ab)', launcher: 'yes' });
expect(stages(dir)).toEqual([]);
});
test('a publish killed mid-flight leaves an interrupted publish record', () => {
const dir = fixture(); seedOld(dir);
const r = build(dir, 'GSTACK_CSO_BUILD_TESTING=1 GSTACK_CSO_BUILD_TEST_KILL_AFTER=publish-core');
expect(r.status).not.toBe(0);
expect(record(dir)).toMatchObject({ result: 'failed', stage: 'publish', reason: 'interrupted' });
expect(existsSync(join(dir, 'bin', 'gstack-cso-launcher'))).toBe(false);
});
test('a missing publisher at exec time cleans the stage and keeps the old generation', () => {
const dir = fixture(); seedOld(dir);
const r = build(dir, 'GSTACK_CSO_BUILD_TESTING=1 GSTACK_CSO_BUILD_TEST_REMOVE_LOCKER_AFTER=before-exec');
expect(r.status).toBe(127);
expect(r.stderr).toContain('CSO publication could not start');
expect(stages(dir)).toEqual([]);
expect(launcherOutput(dir)).toContain('OLD');
expect(record(dir)).toMatchObject({ result: 'failed', stage: 'publish', reason: 'exit 127', installed: '9.9.9.8 (0123456789ab)', launcher: 'yes' });
});
});
describe('build-cso.sh publisher handoff (#3071)', () => {
const source = readFileSync(join(ROOT, 'scripts/build-cso.sh'), 'utf8');
test('the parent checks the publisher, then clears its EXIT trap, then execs', () => {
const exec = source.indexOf('exec "$CSO_STAGE_LOCKER"');
const clear = source.lastIndexOf('trap - EXIT', exec);
const check = source.lastIndexOf('cso_valid_artifact "$CSO_STAGE_LOCKER"', clear);
expect(exec).toBeGreaterThan(0);
expect(clear).toBeGreaterThan(check);
expect(check).toBeGreaterThan(0);
expect(source.slice(check, exec)).toContain('shopt -s execfail');
expect(source.slice(exec)).toContain('cso_cleanup "$cso_exec_status"');
});
test('the Windows build prefers PowerShell 7 and falls back to Windows PowerShell', () => {
expect(source).toContain('CSO_POWERSHELL="$(command -v pwsh 2>/dev/null || command -v powershell.exe 2>/dev/null || true)"');
expect(source).not.toMatch(/^\s*powershell\.exe /m);
});
});
+1 -1
View File
@@ -90,6 +90,6 @@ describe('bounded verification attempts', () => {
const { MAX_VERIFICATION_ATTEMPT_MS } = await import('../lib/cso/contracts');
for (const stack of ['node', 'bun', 'python']) expect(verificationAttemptMs(stack)).toBe(300_000);
expect(verificationAttemptMs('rails')).toBe(MAX_VERIFICATION_ATTEMPT_MS);
expect(MAX_VERIFICATION_ATTEMPT_MS).toBe(900_000);
expect(MAX_VERIFICATION_ATTEMPT_MS).toBe(1_800_000);
});
});
+1 -1
View File
@@ -141,7 +141,7 @@ describe('CSO native Windows build contract', () => {
test('Windows builds use MSVC with a static CRT and no Bun-hosted public launcher', () => {
const build = fs.readFileSync(path.join(ROOT, 'scripts/build-cso.sh'), 'utf8');
const msvc = fs.readFileSync(path.join(ROOT, 'scripts/build-cso-windows.ps1'), 'utf8');
expect(build).toContain('powershell.exe -NoProfile -NonInteractive');
expect(build).toContain('"$CSO_POWERSHELL" -NoProfile -NonInteractive');
expect(build).toContain('build-cso-windows.ps1');
expect(build).toContain('-OutputPath "$(cygpath -w "$CSO_STAGE_LAUNCHER")"');
expect(build).toContain('-LockOutputPath "$(cygpath -w "$CSO_STAGE_LOCKER")"');
+66 -1
View File
@@ -16,6 +16,8 @@ import * as path from 'path';
// setup builds browse/dist/browse.exe on Windows (Git Bash), browse/dist/browse elsewhere.
const BROWSE_BIN = process.platform === 'win32' ? 'browse/dist/browse.exe' : 'browse/dist/browse';
const EXE = process.platform === 'win32' ? '.exe' : '';
const OTHER_BINS = ['browse/dist/find-browse', 'design/dist/design', 'make-pdf/dist/pdf', 'bin/gstack-global-discover'].map(rel => rel + EXE);
const REPO = path.resolve(import.meta.dir, '..');
const COPIED = [
@@ -23,6 +25,7 @@ const COPIED = [
'bin/gstack-doctor', 'bin/gstack-codex-status.sh', 'bin/gstack-state-root.sh', 'bin/gstack-install-registry.sh',
'bin/gstack-render-claude.sh', 'bin/gstack-bun-version.sh', 'bin/gstack-hook-check', 'bin/gstack-config',
'autoplan/SKILL.md', // its frontmatter registers the autoplan hook the hooks-row test breaks
'bin/gstack-launch-probe.sh',
];
const bases: string[] = [];
afterEach(() => { for (const b of bases.splice(0)) fs.rmSync(b, { recursive: true, force: true }); });
@@ -80,7 +83,10 @@ function makeFixture(): Fixture {
]);
const hooks = spawnSync('bash', [path.join(root, 'bin/gstack-hook-check'), '--list', root], { encoding: 'utf8', timeout: 20_000 }).stdout.trim().split('\n');
for (const hook of hooks) write(path.join(root, hook), '#!/bin/sh\nexit 0\n', 0o755);
for (const rel of [BROWSE_BIN, 'browse/dist/server-node.mjs', 'browse/dist/.build-complete']) write(path.join(root, rel), 'built\n', 0o755);
// The doctor launches each compiled binary's --version (#2595), so the
// stand-ins answer it like the real binaries do.
for (const rel of [BROWSE_BIN, ...OTHER_BINS]) write(path.join(root, rel), '#!/bin/sh\necho built\n', 0o755);
for (const rel of ['browse/dist/server-node.mjs', 'browse/dist/.build-complete']) write(path.join(root, rel), 'built\n', 0o755);
const version = fs.readFileSync(path.join(root, 'VERSION'), 'utf8').trim();
write(path.join(state, 'installs.tsv'),
['claude', 'global', '-', path.join(home, '.claude/skills'), root, root, version, 'false', 'committed', '2026-10-07T00:00:00Z'].join('\t') + '\n');
@@ -361,3 +367,62 @@ describe('bug-report template and README (DX-2, DX-12)', () => {
expect(section).toContain('`~/.claude/skills/gstack/bin/gstack-doctor`');
});
});
// #2595/#2124 and #3071: compiled binaries by launch state, and CSO from the
// build-result record. A blocked binary is simulated by the application-control
// message reporters captured (#2595), which works on every OS.
describe('gstack-doctor launch and CSO rows', () => {
const BLOCKED = `#!/bin/sh\necho "Program 'x.exe' failed to run: An Application Control policy has blocked this file" >&2\nexit 1\n`;
const record = (f: Fixture, text: string) => write(path.join(f.root, 'bin/.gstack-cso-build-result'), text);
const cso = (f: Fixture) => { for (const name of ['gstack-cso-launcher', 'gstack-cso-core']) write(path.join(f.root, 'bin', name + EXE), '#!/bin/sh\necho cso\n', 0o755); };
test('healthy binaries are ok; a blocked browse says blocked, not "not built"', () => {
const f = makeFixture();
let r = doctor(f);
expect(r.row('binaries').state).toBe('ok');
expect(r.row('binaries').detail).toContain('(4 of 4)');
write(path.join(f.root, BROWSE_BIN), BLOCKED, 0o755);
r = doctor(f);
expect(r.row('browse bundle').state).toBe('warn');
expect(r.row('browse bundle').detail).toContain('built, but blocked at launch (Program');
expect(r.row('browse bundle').detail).not.toContain('not built');
expect(r.row('browse bundle').fix).toContain(process.platform === 'win32' ? 'Smart App Control' : 'the OS refused to execute it');
expect(r.status).toBe(0);
});
test('blocked, broken and missing binaries are told apart', () => {
const f = makeFixture();
write(path.join(f.root, OTHER_BINS[1]), BLOCKED, 0o755);
let r = doctor(f);
expect(r.row('binaries').detail).toContain('blocked at launch: design');
expect(r.row('binaries').detail).toContain('unavailable: /design-consultation');
write(path.join(f.root, OTHER_BINS[1]), '#!/bin/sh\necho ok\n', 0o755);
write(path.join(f.root, OTHER_BINS[2]), '#!/bin/sh\necho "usage" >&2\nexit 2\n', 0o755);
r = doctor(f);
expect(r.row('binaries').detail).toBe('launched but failed: pdf (exit 2: usage)');
expect(r.row('binaries').fix).toBe(`cd ${bashPath(f.root)} && bun run build`);
fs.rmSync(path.join(f.root, OTHER_BINS[2]));
r = doctor(f);
expect(r.row('binaries').detail).toBe('not built: pdf');
});
test('the CSO row reads the build-result record', () => {
const f = makeFixture();
const none = doctor(f).row('cso');
expect(none.state).toBe('not configured');
expect(none.detail).toBe('native helper not built; /cso reports not assessed');
expect(none.fix).toContain('./setup (it names any missing build prerequisite)');
record(f, 'result=failed\nstage=build\nreason=exit 42\nrevision=1.2 (abc)\ninstalled=\nlauncher=no\ndiagnostic=/x/cso.log\n');
let r = doctor(f);
expect(r.row('cso').state).toBe('warn');
expect(r.row('cso').detail).toBe('unavailable: the build step failed (exit 42); /cso reports not assessed');
expect(r.row('cso').fix).toContain('bun run build:cso && ./setup (log: /x/cso.log;');
cso(f);
record(f, 'result=failed\nstage=publish\nreason=exit 1\nrevision=1.2 (abc)\ninstalled=1.1 (def)\nlauncher=yes\ndiagnostic=/x/cso.log\n');
expect(doctor(f).row('cso').detail).toBe('publish step failed (exit 1) for 1.2 (abc); previous CSO kept: 1.1 (def)');
record(f, 'result=ok\nstage=publish\nreason=committed\nrevision=1.2 (abc)\ninstalled=1.2 (abc)\nlauncher=yes\ndiagnostic=x\n');
r = doctor(f);
expect(r.row('cso')).toEqual({ state: 'ok', detail: 'native helper 1.2 (abc)', fix: '' });
expect(r.status).toBe(0);
});
});
+75
View File
@@ -0,0 +1,75 @@
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { runBashScript } from './helpers/bash-script';
// #2595/#2124: Smart App Control blocks unsigned binaries at launch and Git
// Bash reports it as "Permission denied" (exit 126). bin/gstack-launch-probe.sh
// runs each binary's --version and tells blocked from broken from healthy.
// The exact Windows text is unverified (no SAC machine); these cases use the
// shapes reporters captured in #2595 and #2124.
const ROOT = path.resolve(import.meta.dir, '..');
const PROBE = path.join(ROOT, 'bin/gstack-launch-probe.sh');
const tmps: string[] = [];
afterEach(() => { for (const t of tmps.splice(0)) fs.rmSync(t, { recursive: true, force: true }); });
function fakeBinary(body: string | null, mode = 0o755) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-launch-probe-'));
tmps.push(dir);
const file = path.join(dir, 'tool');
if (body !== null) fs.writeFileSync(file, `#!/bin/sh\n${body}\n`, { mode });
return file;
}
function probe(file: string) {
const r = runBashScript(`. ${JSON.stringify(PROBE)}\ngstack_launch_probe ${JSON.stringify(file)}\nprintf 'state=%s\\ndetail=%s\\n' "$_glp_state" "$_glp_detail"`, { timeout: 30_000 });
expect(r.status).toBe(0);
return { state: r.stdout.match(/^state=(.*)$/m)![1], detail: r.stdout.match(/^detail=(.*)$/m)![1] };
}
// POSIX execute bits stand in for a refused launch; Windows has no such bit,
// and a real SAC block cannot be produced in CI.
describe.skipIf(process.platform === 'win32')('gstack-launch-probe.sh classification', () => {
test('a binary that answers --version is native', () => {
expect(probe(fakeBinary('[ "$1" = --version ] && echo 1.2.3'))).toEqual({ state: 'native', detail: '1.2.3' });
});
test('a binary the OS refuses to execute is blocked (Git Bash "Permission denied", exit 126)', () => {
const r = probe(fakeBinary('echo never', 0o644));
expect(r.state).toBe('blocked');
expect(r.detail).toContain('Permission denied');
});
test('an application-control message is blocked even with another exit code', () => {
const r = probe(fakeBinary("echo \"Program 'browse.exe' failed to run: An Application Control policy has blocked this file\" >&2; exit 1"));
expect(r.state).toBe('blocked');
expect(r.detail).toContain('An Application Control policy has blocked this file');
});
test('a binary that launches and exits non-zero is broken, not blocked', () => {
expect(probe(fakeBinary('echo "Unknown argument: --version" >&2; exit 3'))).toEqual({ state: 'broken', detail: 'exit 3: Unknown argument: --version' });
});
test('an absent binary is missing', () => {
expect(probe(fakeBinary(null)).state).toBe('missing');
});
test('probe_all groups blocked, broken and missing binaries by repo path', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-launch-root-'));
tmps.push(root);
const write = (rel: string, body: string, mode = 0o755) => {
fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
fs.writeFileSync(path.join(root, rel), `#!/bin/sh\n${body}\n`, { mode });
};
write('browse/dist/browse.exe', 'echo x', 0o644);
write('browse/dist/find-browse.exe', 'echo ok');
write('design/dist/design.exe', 'echo ok');
write('make-pdf/dist/pdf.exe', 'exit 2');
const r = runBashScript(`. ${JSON.stringify(PROBE)}\ngstack_launch_probe_all ${JSON.stringify(root)} .exe\nprintf 'blocked=[%s]\\nbroken=[%s]\\nmissing=[%s]\\n' "$_glp_blocked" "$_glp_broken" "$_glp_missing"`, { timeout: 30_000 });
expect(r.stdout).toContain('blocked=[browse/dist/browse\t');
expect(r.stdout).toContain('broken=[make-pdf/dist/pdf\texit 2');
expect(r.stdout).toContain('missing=[bin/gstack-global-discover]');
expect(r.stdout).not.toContain('design/dist/design');
});
});
+147
View File
@@ -0,0 +1,147 @@
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { runBashScript } from './helpers/bash-script';
// #3071: an optional CSO failure no longer aborts setup. The prerequisite
// probe prefers PowerShell 7 and keeps an unknown failure's own output; the
// summary reads bin/.gstack-cso-build-result and names the failed stage, the
// diagnostic and the retry; only GSTACK_STRICT_BUILD=1 makes an incomplete CSO
// set fatal. Runs setup's real blocks with tools stubbed.
const ROOT = path.resolve(import.meta.dir, '..');
const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf8');
const fn = (name: string) => {
const start = setup.indexOf(`\n${name}() {`);
const end = setup.indexOf('\n}\n', start);
if (start < 0 || end < 0) throw new Error(`missing setup function ${name}`);
return setup.slice(start + 1, end + 3);
};
const between = (from: string, to: string) => {
const start = setup.indexOf(from);
const end = setup.indexOf(to, start);
if (start < 0 || end < 0) throw new Error(`missing setup block ${from}`);
return setup.slice(start, end);
};
const SUMMARY_END = '#cso-build-or-publish-failed"\nfi\n';
const SUMMARY = between('# ─── CSO native-helper summary', SUMMARY_END) + SUMMARY_END;
const GATE = between('_CSO_READY=0\n', 'if [ "$_CSO_READY" -eq 1 ]; then');
const tmps: string[] = [];
afterEach(() => { for (const t of tmps.splice(0)) fs.rmSync(t, { recursive: true, force: true }); });
const temp = (prefix: string) => { const d = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); tmps.push(d); return d; };
const stub = (dir: string, name: string, body: string) => fs.writeFileSync(path.join(dir, name), `#!/bin/sh\n${body}\n`, { mode: 0o755 });
function probe(tools: Record<string, string>) {
const dir = temp('gstack-cso-probe-');
for (const [name, body] of Object.entries(tools)) stub(dir, name, body);
stub(dir, 'cygpath', 'shift; echo "$1"');
return runBashScript([
'IS_WINDOWS=1', `SOURCE_GSTACK_DIR="${ROOT}"`,
'bun_cmd() { echo "--no-compile-autoload-dotenv --no-compile-autoload-bunfig --no-compile-autoload-tsconfig --no-compile-autoload-package-json"; }',
fn('_cso_unavailable'), fn('probe_cso_build_prerequisites'),
'probe_cso_build_prerequisites',
'printf "available=%s\\nreason=%s\\ndetail=%s\\n" "$CSO_BUILD_AVAILABLE" "$CSO_FAIL_REASON" "$CSO_PROBE_DETAIL"',
].join('\n'), { env: { ...process.env, PATH: `${dir}:${process.env.PATH}` }, timeout: 30_000 });
}
function summary(record: string | null, opts: { launcher?: boolean; probe?: [reason: string, detail: string] } = {}) {
const dir = temp('gstack-cso-summary-');
fs.mkdirSync(path.join(dir, 'bin'));
if (record !== null) fs.writeFileSync(path.join(dir, 'bin/.gstack-cso-build-result'), record);
if (opts.launcher) for (const name of ['gstack-cso-launcher', 'gstack-cso-core']) stub(path.join(dir, 'bin'), name, 'echo OLD');
const probe = opts.probe ? `CSO_BUILD_AVAILABLE=0\nCSO_FAIL_REASON='${opts.probe[0]}'\nCSO_PROBE_DETAIL='${opts.probe[1]}'` : 'CSO_BUILD_AVAILABLE=1';
const r = runBashScript(['QUIET=0', '_EXE=""', `SOURCE_GSTACK_DIR="${dir}"`, probe, 'log() { echo "$@"; }', SUMMARY].join('\n'), { timeout: 15_000 });
expect(r.status).toBe(0);
return { out: r.stdout, dir };
}
describe.skipIf(process.platform === 'win32')('setup: Windows CSO probe uses PowerShell 7 and keeps unknown failures (#3071)', () => {
test('pwsh is preferred over Windows PowerShell 5.1', () => {
const r = probe({ pwsh: 'exit 0', 'powershell.exe': 'echo "5.1 must not run" >&2; exit 1' });
expect(r.stdout).toContain('available=1\n');
});
test('a crashed probe keeps its exit status and output instead of blaming the MSVC toolchain', () => {
const r = probe({ pwsh: 'echo "Fatal error. 0xC0000005"; exit 139' });
expect(r.stdout).toContain('reason=windows-toolchain-probe\n');
expect(r.stdout).toContain('detail=pwsh exited 139: Fatal error. 0xC0000005\n');
});
test('the missing Visual Studio message still maps to the install instruction', () => {
const r = probe({ pwsh: "echo 'CSO Windows build requires Visual Studio 2022 Build Tools with the Desktop development with C++ workload.' >&2; exit 1" });
expect(r.stdout).toContain('reason=windows-msvc-toolchain\n');
});
test.skipIf(Bun.which('pwsh') !== null)('without pwsh the probe falls back to powershell.exe', () => {
const r = probe({ 'powershell.exe': 'echo "Native CSO Windows compiler probe failed (2)." >&2; exit 1' });
expect(r.stdout).toContain('reason=windows-msvc-compile\n');
});
});
describe.skipIf(process.platform === 'win32')('setup: CSO summary reads the build-result record per stage (#3071)', () => {
const failed = (stage: string, reason: string, installed = '') =>
`result=failed\nstage=${stage}\nreason=${reason}\nrevision=1.91.99.0 (abcdef123456)\ninstalled=${installed}\nlauncher=${installed ? 'yes' : 'no'}\ndiagnostic=/src/bin/.gstack-cso-build.log\n`;
test('a probe failure keeps the prerequisite instruction and names the probe stage', () => {
const { out } = summary(null, { probe: ['windows-toolchain-probe', 'pwsh exited 139: Fatal error'] });
expect(out).toContain('CSO unavailable: its native helper was not built (windows-toolchain-probe).');
expect(out).toContain('Failed stage: probe.');
expect(out).toContain('fix the PowerShell toolchain probe failure (pwsh exited 139: Fatal error)');
});
test('a fresh build failure names the stage, the log and the retry, never a prerequisite install', () => {
const { out, dir } = summary(failed('build', 'exit 42'));
expect(out).toContain("CSO unavailable: the native helper's build step failed (exit 42), so /cso will report not assessed.");
expect(out).toContain('Diagnostic: /src/bin/.gstack-cso-build.log');
expect(out).toContain('Everything else is installed and works.');
expect(out).toContain(`Retry: cd ${dir} && bun run build:cso && ./setup`);
expect(out).toContain('troubleshooting.md#cso-build-or-publish-failed');
expect(out).not.toContain('To enable /cso');
expect(out).not.toMatch(/prerequisite|\binstall (?:a|the|Visual|Git|Bun)\b/i);
});
test('a failed publish that kept the earlier helper says previous CSO kept', () => {
const { out } = summary(failed('publish', 'exit 1', '1.91.34.0 (f67c478f05d8)'), { launcher: true });
expect(out).toContain('CSO publish step failed (exit 1) for 1.91.99.0 (abcdef123456); previous CSO kept: 1.91.34.0 (f67c478f05d8).');
expect(out).not.toContain('CSO unavailable');
});
test('a recorded old helper whose files are gone is reported unavailable', () => {
expect(summary(failed('publish', 'exit 1', '1.91.34.0'), { launcher: false }).out).toContain("CSO unavailable: the native helper's publish step failed (exit 1)");
});
test('an interrupted publish says so', () => {
expect(summary(failed('publish', 'interrupted')).out).toContain("publish step was interrupted");
});
test('a successful build or a legacy install without a record prints nothing', () => {
expect(summary('result=ok\nstage=publish\nreason=committed\nrevision=1\ninstalled=1\nlauncher=yes\ndiagnostic=x\n').out).toBe('');
expect(summary(null).out).toBe('');
});
});
test('a probe failure removes a stale build record and writes nothing into the source checkout', () => {
const block = between('if [ "$CSO_BUILD_AVAILABLE" -eq 0 ]; then\n rm -f', '\nfi\n');
expect(block).toContain('rm -f "$SOURCE_GSTACK_DIR/bin/.gstack-cso-build-result"');
expect(block).not.toContain('>');
});
describe.skipIf(process.platform === 'win32')('setup: an incomplete CSO set is fatal only under GSTACK_STRICT_BUILD=1 (#3071)', () => {
function gate(strict?: string) {
const dir = temp('gstack-cso-gate-');
fs.mkdirSync(path.join(dir, 'bin'));
const env: Record<string, string> = { PATH: process.env.PATH ?? '' };
if (strict !== undefined) env.GSTACK_STRICT_BUILD = strict;
return runBashScript(['set -e', 'CSO_BUILD_AVAILABLE=1', 'IS_WINDOWS=0', '_EXE=""', `SOURCE_GSTACK_DIR="${dir}"`, GATE, 'echo "ready=$_CSO_READY"'].join('\n'), { env, timeout: 15_000 });
}
test('by default setup continues without CSO', () => {
const r = gate();
expect(r.status).toBe(0);
expect(r.stdout).toContain('ready=0');
});
test('GSTACK_STRICT_BUILD=1 stops setup', () => {
const r = gate('1');
expect(r.status).toBe(1);
expect(r.stderr).toContain('CSO build completed without its required native artifact set (GSTACK_STRICT_BUILD=1)');
});
});
+5 -1
View File
@@ -28,7 +28,11 @@ afterEach(() => { for (const t of tmps.splice(0)) fs.rmSync(t, { recursive: true
function probe(powershellOutput: string) {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-cso-win-'));
tmps.push(tmp);
fs.writeFileSync(path.join(tmp, 'powershell.exe'), `#!/bin/sh\ncat <<'OUT' >&2\n${powershellOutput}\nOUT\nexit 1\n`, { mode: 0o755 });
// setup resolves pwsh before powershell.exe (#3071); stub both so a runner's
// real PowerShell 7 never answers the probe.
for (const name of ['pwsh', 'powershell.exe']) {
fs.writeFileSync(path.join(tmp, name), `#!/bin/sh\ncat <<'OUT' >&2\n${powershellOutput}\nOUT\nexit 1\n`, { mode: 0o755 });
}
fs.writeFileSync(path.join(tmp, 'cygpath'), '#!/bin/sh\nshift; echo "$1"\n', { mode: 0o755 });
return runBashScript([
'IS_WINDOWS=1', `SOURCE_GSTACK_DIR="${ROOT}"`,
+85
View File
@@ -0,0 +1,85 @@
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { runBashScript } from './helpers/bash-script';
// #2595/#2124: on Windows, setup launches each compiled binary's --version
// after the build and explains a Smart App Control block: the blocked
// binaries, the skills that need them, #2595, the shell and WSL status, how to
// undo it and the troubleshooting link. Runs setup's real function against
// stand-in binaries; a real SAC block cannot be produced in CI.
const ROOT = path.resolve(import.meta.dir, '..');
const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf8');
const fn = (name: string) => {
const start = setup.indexOf(`\n${name}() {`);
const end = setup.indexOf('\n}\n', start);
if (start < 0 || end < 0) throw new Error(`missing setup function ${name}`);
return setup.slice(start + 1, end + 3);
};
const tmps: string[] = [];
afterEach(() => { for (const t of tmps.splice(0)) fs.rmSync(t, { recursive: true, force: true }); });
const temp = (prefix: string) => { const d = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); tmps.push(d); return d; };
const stub = (dir: string, name: string, body: string) => fs.writeFileSync(path.join(dir, name), `#!/bin/sh\n${body}\n`, { mode: 0o755 });
test('setup runs the launch summary only on Windows, after the CSO summary', () => {
const call = setup.indexOf('if [ "$IS_WINDOWS" -eq 1 ]; then\n _windows_launch_summary\nfi');
expect(call).toBeGreaterThan(setup.indexOf('# ─── CSO native-helper summary'));
});
describe.skipIf(process.platform === 'win32')('setup: Windows Smart App Control hint (#2595)', () => {
function run(binaries: Record<string, string>, wsl: boolean) {
const src = temp('gstack-sac-src-');
const tools = temp('gstack-sac-tools-');
fs.mkdirSync(path.join(src, 'bin'));
fs.copyFileSync(path.join(ROOT, 'bin/gstack-launch-probe.sh'), path.join(src, 'bin/gstack-launch-probe.sh'));
for (const [rel, body] of Object.entries(binaries)) {
fs.mkdirSync(path.dirname(path.join(src, rel)), { recursive: true });
fs.writeFileSync(path.join(src, rel), `#!/bin/sh\n${body}\n`, { mode: body === 'BLOCKED' ? 0o644 : 0o755 });
}
stub(tools, 'uname', 'echo MINGW64_NT-10.0-26200');
if (wsl) stub(tools, 'wsl.exe', 'exit 0');
const r = runBashScript(['QUIET=0', `SOURCE_GSTACK_DIR="${src}"`, 'log() { echo "$@"; }', fn('_windows_launch_summary'), '_windows_launch_summary'].join('\n'),
{ env: { ...process.env, PATH: `${tools}:${process.env.PATH}` }, timeout: 60_000 });
expect(r.status).toBe(0);
return { out: r.stdout, src };
}
const healthy = 'echo 1.0';
test('blocked binaries are named with their skills, #2595, the shell, WSL status, undo and the docs link', () => {
const { out } = run({
'browse/dist/browse.exe': 'BLOCKED',
'browse/dist/find-browse.exe': healthy,
'design/dist/design.exe': healthy,
'make-pdf/dist/pdf.exe': "echo \"Program 'pdf.exe' failed to run: An Application Control policy has blocked this file\" >&2; exit 1",
'bin/gstack-global-discover.exe': healthy,
}, false);
expect(out).toContain('Windows blocked compiled gstack binaries at launch (Smart App Control or another application-control policy, #2595):');
expect(out).toMatch(/browse\/dist\/browse\.exe: .*Permission denied.* -> \/browse, \/qa, /);
expect(out).toContain('make-pdf/dist/pdf.exe: Program \'pdf.exe\' failed to run: An Application Control policy has blocked this file -> /make-pdf');
expect(out).toContain('code integrity, not file permissions');
expect(out).toContain('You ran setup from Git Bash, where the block applies; WSL is not installed (wsl --install)');
expect(out).toContain('To undo: once Windows allows the binaries, re-run ./setup');
expect(out).toContain('troubleshooting.md#windows-smart-app-control');
expect(out).not.toContain('design/dist/design.exe');
});
test('WSL presence is reported', () => {
expect(run({ 'browse/dist/browse.exe': 'BLOCKED' }, true).out).toContain('WSL is installed, and gstack inside WSL is not affected');
});
test('a binary that launches and fails is a build problem, not Smart App Control', () => {
const { out, src } = run({
'browse/dist/browse.exe': healthy, 'browse/dist/find-browse.exe': healthy, 'design/dist/design.exe': healthy,
'make-pdf/dist/pdf.exe': healthy, 'bin/gstack-global-discover.exe': 'echo "Unknown argument: --version" >&2; exit 1',
}, false);
expect(out).not.toContain('Smart App Control or another');
expect(out).toContain('bin/gstack-global-discover.exe: exit 1: Unknown argument: --version -> /retro global');
expect(out).toContain(`Rebuild: cd ${src} && bun run build`);
});
test('healthy binaries print nothing', () => {
const all = Object.fromEntries(['browse/dist/browse.exe', 'browse/dist/find-browse.exe', 'design/dist/design.exe', 'make-pdf/dist/pdf.exe', 'bin/gstack-global-discover.exe'].map(rel => [rel, healthy]));
expect(run(all, false).out).toBe('');
});
});