mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-20 15:13:47 +01:00
Merge oct8-setup: hook-check coverage, team hook cross-platform, gbrain MCP on Windows, verified Bun installs, Actions pins (triage wave)
This commit is contained in:
commit
5a2dec3f1b
24 files changed
+646
-106
No files matched your search
@@ -180,3 +180,34 @@ describe('ci image codex authentication', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('other CI Bun installs match the image (#1713, #1706)', () => {
|
||||
const docker = fs.readFileSync(DOCKERFILE, 'utf-8');
|
||||
const imageSha = bunArchiveArms(docker).get('amd64');
|
||||
const imageVersion = docker.match(/^ARG BUN_VERSION=(\S+)$/m)?.[1];
|
||||
const engines = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf-8')).engines.bun;
|
||||
|
||||
for (const rel of ['.gitlab-ci.yml', 'scripts/ubicloud/setup-free-suite.sh']) {
|
||||
const source = fs.readFileSync(path.join(ROOT, rel), 'utf-8');
|
||||
|
||||
test(`${rel} downloads the verified linux-x64 archive instead of piping an installer into a shell`, () => {
|
||||
expect(curlPipedToShell(source)).toEqual([]);
|
||||
const download = source.indexOf('/releases/download/bun-v$BUN_VERSION/bun-linux-x64.zip');
|
||||
const verify = source.indexOf('sha256sum -c');
|
||||
const unpack = source.indexOf('unzip -q');
|
||||
expect(download).toBeGreaterThan(-1);
|
||||
expect(verify).toBeGreaterThan(download);
|
||||
expect(unpack).toBeGreaterThan(verify);
|
||||
expect(source).toContain('test "$(bun --version)" = "$BUN_VERSION"');
|
||||
});
|
||||
|
||||
test(`${rel} pins the same Bun version and SHA-256 as Dockerfile.ci`, () => {
|
||||
expect(imageSha).toMatch(/^[0-9a-f]{64}$/);
|
||||
const hashes = [...source.matchAll(/echo "([0-9a-f]{64}) /g)].map((m) => m[1]);
|
||||
expect(hashes).toEqual([imageSha!]);
|
||||
const version = source.match(/^\s*BUN_VERSION[=:]\s*"?([\d.]+)"?\s*$/m)?.[1];
|
||||
expect(version).toBe(imageVersion!);
|
||||
expect(engines).toBe(`>=${imageVersion}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -22,6 +22,7 @@ const COPIED = [
|
||||
'setup', 'VERSION',
|
||||
'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
|
||||
];
|
||||
const bases: string[] = [];
|
||||
afterEach(() => { for (const b of bases.splice(0)) fs.rmSync(b, { recursive: true, force: true }); });
|
||||
|
||||
@@ -36,11 +36,14 @@ describe('gstack-team-init required: PreToolUse hook schema (#2413)', () => {
|
||||
fs.rmSync(fakeHomePresent, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// Run the command exactly as registered in settings.json, the way a hook
|
||||
// runner does: through a shell, with CLAUDE_PROJECT_DIR set.
|
||||
function runHook(home: string): { status: number; stdout: string; stderr: string } {
|
||||
const hookPath = path.join(repoDir, '.claude', 'hooks', 'check-gstack.sh');
|
||||
const settings = JSON.parse(fs.readFileSync(path.join(repoDir, '.claude', 'settings.json'), 'utf-8'));
|
||||
const command = settings.hooks.PreToolUse[0].hooks[0].command;
|
||||
try {
|
||||
const stdout = execSync(`bash "${hookPath}"`, {
|
||||
env: { ...process.env, HOME: home },
|
||||
const stdout = execSync(command, {
|
||||
env: { ...process.env, HOME: home, CLAUDE_PROJECT_DIR: repoDir, GSTACK_ROOT: '' },
|
||||
encoding: 'utf-8',
|
||||
timeout: 30_000,
|
||||
});
|
||||
@@ -52,11 +55,12 @@ describe('gstack-team-init required: PreToolUse hook schema (#2413)', () => {
|
||||
}
|
||||
|
||||
test('generates the hook and registers it in settings.json', () => {
|
||||
expect(fs.existsSync(path.join(repoDir, '.claude', 'hooks', 'check-gstack.sh'))).toBe(true);
|
||||
expect(fs.existsSync(path.join(repoDir, '.claude', 'hooks', 'check-gstack.cjs'))).toBe(true);
|
||||
const settings = JSON.parse(
|
||||
fs.readFileSync(path.join(repoDir, '.claude', 'settings.json'), 'utf-8'),
|
||||
);
|
||||
expect(JSON.stringify(settings)).toContain('check-gstack.sh');
|
||||
expect(JSON.stringify(settings)).toContain('check-gstack.cjs');
|
||||
expect(settings.hooks.PreToolUse[0].hooks[0].command).not.toContain('$');
|
||||
});
|
||||
|
||||
test('gstack absent: exits 2 (blocking) with schema-valid deny JSON', () => {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* HAS_ROUTING: no and got nagged to create CLAUDE.md.
|
||||
*
|
||||
* 2. gstack-team-init's required-mode enforcement (the CLAUDE.md
|
||||
* verification snippet and the generated check-gstack.sh hook) must
|
||||
* verification snippet and the generated check-gstack.cjs hook) must
|
||||
* resolve the install root across GSTACK_ROOT + every host's global
|
||||
* install location, never hardcode ~/.claude/skills/gstack. The drift
|
||||
* test pins the probe list against the hosts registry so a new host
|
||||
@@ -118,8 +118,14 @@ describe('team-init resolves GSTACK_ROOT across every host (#2500)', () => {
|
||||
});
|
||||
|
||||
test('generated hook blocks only when NO install root resolves', () => {
|
||||
// The hook's block branch must gate on the resolved root being empty,
|
||||
// not on any single hardcoded directory.
|
||||
expect(teamInit).toContain('if [ -z "$_GSTACK_ROOT" ]; then');
|
||||
// The hook (CommonJS, so it runs under any hook shell) probes GSTACK_ROOT
|
||||
// and every host's global root, and its block branch gates on none
|
||||
// resolving, not on any single hardcoded directory.
|
||||
const hook = teamInit.slice(teamInit.indexOf("cat > \"$HOOKS_DIR/check-gstack.cjs\""), teamInit.indexOf('\nHOOK_EOF\n'));
|
||||
expect(hook).toContain('process.env.GSTACK_ROOT');
|
||||
for (const config of ALL_HOST_CONFIGS) expect(hook).toContain(`'${config.globalRoot}'`);
|
||||
expect(hook).toContain("'.gstack/repos/gstack'");
|
||||
expect(hook).toContain('const gstackRoot = roots.find(');
|
||||
expect(hook).toContain('if (gstackRoot) {');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* /setup-gbrain's local stdio MCP registration (#2007, #1963). On Windows the
|
||||
* bun `gbrain.exe` binstub starts bun in a new console, so registering it made
|
||||
* every Claude Code session open a visible terminal; the skill registers
|
||||
* `bun.exe <gbrain entry> serve` instead, and `gbrain.exe` by its full name
|
||||
* when bun.exe or the entry is missing. POSIX keeps the binstub.
|
||||
*
|
||||
* Runs the generated fence under bash with stub `uname` and `claude` and a
|
||||
* temp HOME. The console behavior itself needs a real Windows machine.
|
||||
*/
|
||||
import { afterAll, describe, expect, test } from 'bun:test';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, '..');
|
||||
const SKILL = fs.readFileSync(path.join(ROOT, 'setup-gbrain', 'SKILL.md'), 'utf-8');
|
||||
|
||||
function localStdioFence(): string {
|
||||
const section = SKILL.indexOf('### Paths 1, 2a, 2b, 3 (Local stdio)\n\nRegister at **user scope**');
|
||||
expect(section).toBeGreaterThan(-1);
|
||||
const start = SKILL.indexOf('```bash\n', section) + '```bash\n'.length;
|
||||
return SKILL.slice(start, SKILL.indexOf('\n```', start));
|
||||
}
|
||||
|
||||
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-gbrain-mcp-'));
|
||||
afterAll(() => fs.rmSync(base, { recursive: true, force: true }));
|
||||
|
||||
function register(uname: string, files: string[], env: (home: string) => Record<string, string> = () => ({})) {
|
||||
const dir = fs.mkdtempSync(path.join(base, 'case-'));
|
||||
const home = path.join(dir, 'home');
|
||||
const stubs = path.join(dir, 'stubs');
|
||||
const log = path.join(dir, 'claude-argv');
|
||||
fs.mkdirSync(stubs, { recursive: true });
|
||||
for (const rel of files) {
|
||||
fs.mkdirSync(path.dirname(path.join(home, rel)), { recursive: true });
|
||||
fs.writeFileSync(path.join(home, rel), '');
|
||||
}
|
||||
fs.writeFileSync(path.join(stubs, 'uname'), `#!/bin/bash\necho ${uname}\n`, { mode: 0o755 });
|
||||
fs.writeFileSync(path.join(stubs, 'claude'), `#!/bin/bash\ncase "$2" in add) printf '%s\\n' "$@" > "${log}" ;; list) echo 'gbrain: stub - ✓ Connected' ;; esac\nexit 0\n`, { mode: 0o755 });
|
||||
const r = spawnSync('bash', ['-c', localStdioFence()], {
|
||||
env: { PATH: `${stubs}:/usr/bin:/bin`, HOME: home, ...env(home) },
|
||||
encoding: 'utf-8',
|
||||
timeout: 20_000,
|
||||
});
|
||||
expect(r.status).toBe(0);
|
||||
return { home, argv: fs.readFileSync(log, 'utf-8').trim().split('\n') };
|
||||
}
|
||||
|
||||
const BUN_EXE = '.bun/bin/bun.exe';
|
||||
const ENTRY = '.bun/install/global/node_modules/gbrain/src/cli.ts';
|
||||
|
||||
describe('setup-gbrain local stdio MCP registration', () => {
|
||||
test('Windows (MINGW64): registers bun.exe with the gbrain entry, not the binstub', () => {
|
||||
const { home, argv } = register('MINGW64_NT-10.0-26100', [BUN_EXE, ENTRY]);
|
||||
expect(argv).toEqual(['mcp', 'add', '--scope', 'user', 'gbrain', '--', path.join(home, BUN_EXE), path.join(home, ENTRY), 'serve']);
|
||||
});
|
||||
|
||||
test('Windows honors BUN_INSTALL', () => {
|
||||
const files = ['custom-bun/bin/bun.exe', 'custom-bun/install/global/node_modules/gbrain/src/cli.ts'];
|
||||
const { home, argv } = register('MSYS_NT-10.0', files, (h) => ({ BUN_INSTALL: path.join(h, 'custom-bun') }));
|
||||
expect(argv).toEqual(['mcp', 'add', '--scope', 'user', 'gbrain', '--', ...files.map((f) => path.join(home, f)), 'serve']);
|
||||
});
|
||||
|
||||
test('Windows without the entry: registers gbrain.exe by its full name', () => {
|
||||
const { home, argv } = register('MINGW64_NT-10.0', [BUN_EXE]);
|
||||
expect(argv).toEqual(['mcp', 'add', '--scope', 'user', 'gbrain', '--', path.join(home, '.bun/bin/gbrain.exe'), 'serve']);
|
||||
});
|
||||
|
||||
test('Linux keeps the binstub registration', () => {
|
||||
const { home, argv } = register('Linux', [BUN_EXE, ENTRY]);
|
||||
expect(argv).toEqual(['mcp', 'add', '--scope', 'user', 'gbrain', '--', path.join(home, '.bun/bin/gbrain'), 'serve']);
|
||||
});
|
||||
});
|
||||
@@ -47,7 +47,13 @@ afterEach(() => { for (const b of bases.splice(0)) fs.rmSync(b, { recursive: tru
|
||||
|
||||
const HOOKS = listHooks(ROOT);
|
||||
|
||||
/** A gstack tree with the real hook shims and trivial TypeScript entries. */
|
||||
/** Skills whose frontmatter registers a hook command. */
|
||||
const SKILLS_WITH_HOOKS = fs.readdirSync(ROOT).filter((dir) => {
|
||||
const skill = path.join(ROOT, dir, 'SKILL.md');
|
||||
return fs.existsSync(skill) && /^---\n[\s\S]*?^\s*command:[\s\S]*?\n---/m.test(fs.readFileSync(skill, 'utf8'));
|
||||
});
|
||||
|
||||
/** A gstack tree with the real hook shims and skill frontmatter, sourced helpers, and trivial TypeScript entries. */
|
||||
function fixtureTree(root: string) {
|
||||
for (const hook of HOOKS) {
|
||||
fs.mkdirSync(path.dirname(path.join(root, hook)), { recursive: true });
|
||||
@@ -55,6 +61,14 @@ function fixtureTree(root: string) {
|
||||
fs.chmodSync(path.join(root, hook), 0o755);
|
||||
if (fs.existsSync(path.join(ROOT, `${hook}.ts`))) fs.writeFileSync(path.join(root, `${hook}.ts`), 'export const ok = 1;\n');
|
||||
}
|
||||
for (const dir of SKILLS_WITH_HOOKS) {
|
||||
fs.mkdirSync(path.join(root, dir), { recursive: true });
|
||||
fs.copyFileSync(path.join(ROOT, dir, 'SKILL.md'), path.join(root, dir, 'SKILL.md'));
|
||||
}
|
||||
for (const helper of ['careful/bin/hook-extract.sh', 'bin/gstack-state-root.sh']) {
|
||||
fs.mkdirSync(path.dirname(path.join(root, helper)), { recursive: true });
|
||||
fs.copyFileSync(path.join(ROOT, helper), path.join(root, helper));
|
||||
}
|
||||
fs.copyFileSync(path.join(ROOT, 'setup'), path.join(root, 'setup'));
|
||||
}
|
||||
|
||||
@@ -70,13 +84,19 @@ function check(root: string) {
|
||||
}
|
||||
|
||||
describe('gstack-hook-check: the hook list is the registration code', () => {
|
||||
test('equals every hook setup resolves for registration plus the frontmatter-registered autoplan hook', () => {
|
||||
test('equals every hook setup resolves for registration plus every gstack path a skill frontmatter command runs', () => {
|
||||
const registered = [...SETUP.matchAll(/_hook_command_path (\S+)/g)].map(m => m[1]!.replace(/\W+$/, ''));
|
||||
const frontmatter = [...fs.readFileSync(path.join(ROOT, 'autoplan', 'SKILL.md'), 'utf8')
|
||||
.matchAll(/skills\/gstack\/(autoplan\/bin\/[a-z-]+-hook)\b/g)].map(m => m[1]!);
|
||||
const frontmatter = fs.readdirSync(ROOT).flatMap((dir) => {
|
||||
const skill = path.join(ROOT, dir, 'SKILL.md');
|
||||
if (!fs.existsSync(skill)) return [];
|
||||
const front = fs.readFileSync(skill, 'utf8').match(/^---\n([\s\S]*?)\n---/)?.[1] ?? '';
|
||||
return front.split('\n').filter(line => /^\s*command:/.test(line))
|
||||
.flatMap(line => [...line.matchAll(/skills\/gstack\/([\w./-]+)/g)].map(m => m[1]!));
|
||||
});
|
||||
const expected = [...new Set([...registered, ...frontmatter])].sort();
|
||||
expect(registered.length).toBeGreaterThanOrEqual(5);
|
||||
expect(frontmatter.length).toBeGreaterThan(0);
|
||||
for (const hook of ['autoplan/bin/phase-publication-hook', 'careful/bin/check-careful.sh',
|
||||
'freeze/bin/check-freeze.sh', 'plan-ceo-review/bin/mode-handoff-hook']) expect(frontmatter).toContain(hook);
|
||||
expect([...HOOKS].sort()).toEqual(expected);
|
||||
});
|
||||
|
||||
@@ -147,6 +167,54 @@ describe('gstack-hook-check: what fails', () => {
|
||||
expect(r.out).toContain(`fail hosts/claude/hooks/auq-error-fallback-hook ${entry}:1: missing TypeScript entry`);
|
||||
});
|
||||
|
||||
test('a sourced helper that does not parse fails at the helper', () => {
|
||||
const root = tmpBase();
|
||||
fixtureTree(root);
|
||||
const helper = path.join(root, 'careful/bin/hook-extract.sh');
|
||||
fs.appendFileSync(helper, 'if then\n');
|
||||
const r = check(root);
|
||||
expect(r.code).toBe(1);
|
||||
expect(r.out).toMatch(new RegExp(`^fail careful/bin/check-careful.sh ${helper}:\\d+: syntax error`, 'm'));
|
||||
expect(r.out).toMatch(new RegExp(`^fail freeze/bin/check-freeze.sh ${helper}:\\d+: syntax error`, 'm'));
|
||||
});
|
||||
|
||||
test('a conflict marker inside a heredoc of a transitively sourced helper still parses, and fails', () => {
|
||||
const root = tmpBase();
|
||||
fixtureTree(root);
|
||||
const helper = path.join(root, 'bin/gstack-state-root.sh');
|
||||
const lines = fs.readFileSync(helper, 'utf8').split('\n').length;
|
||||
fs.appendFileSync(helper, ": <<'EOF'\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> branch\nEOF\n");
|
||||
expect(spawnSync('bash', ['-n', helper], { timeout: 10_000 }).status).toBe(0);
|
||||
const r = check(root);
|
||||
expect(r.code).toBe(1);
|
||||
expect(r.out).toContain(`fail careful/bin/check-careful.sh ${helper}:${lines + 1}: unresolved merge conflict marker`);
|
||||
expect(r.out).toContain(`fail bin/gstack-session-update ${helper}:${lines + 1}: unresolved merge conflict marker`);
|
||||
});
|
||||
|
||||
test('a conflict marker in a module the TypeScript entry imports fails, even inside a template literal', () => {
|
||||
const root = tmpBase();
|
||||
fixtureTree(root);
|
||||
const dir = path.join(root, 'hosts/claude/hooks');
|
||||
fs.writeFileSync(path.join(dir, 'question-log-hook.ts'), "import { msg } from './hook-msg';\nconsole.log(msg);\n");
|
||||
fs.writeFileSync(path.join(dir, 'hook-msg.ts'), 'export const msg = `\n<<<<<<< HEAD\na\n=======\nb\n>>>>>>> other\n`;\n');
|
||||
const r = check(root);
|
||||
expect(r.code).toBe(1);
|
||||
expect(r.out).toContain(`fail hosts/claude/hooks/question-log-hook ${path.join(dir, 'hook-msg.ts')}:2: unresolved merge conflict marker`);
|
||||
});
|
||||
|
||||
test("the caller's tsconfig.json and bunfig.toml are not read, and a root with spaces works", () => {
|
||||
const base = tmpBase();
|
||||
const root = path.join(base, 'gstack root');
|
||||
fixtureTree(root);
|
||||
const caller = path.join(base, 'project');
|
||||
fs.mkdirSync(caller);
|
||||
fs.writeFileSync(path.join(caller, 'tsconfig.json'), '{ "compilerOptions": { ,,, ');
|
||||
fs.writeFileSync(path.join(caller, 'bunfig.toml'), '[[[ not toml');
|
||||
const r = spawnSync('bash', [CHECK, root], { cwd: caller, encoding: 'utf8', timeout: 30_000 });
|
||||
expect(`${r.stdout}${r.stderr}`).not.toContain('fail ');
|
||||
expect(r.status).toBe(0);
|
||||
});
|
||||
|
||||
test('a missing shim is reported as missing, not failed (setup already skips registering it)', () => {
|
||||
const root = tmpBase();
|
||||
fixtureTree(root);
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Required team mode registers its PreToolUse hook as a command string that
|
||||
* the hook runner hands to whatever shell it uses: sh on macOS and Linux,
|
||||
* cmd.exe or PowerShell on Windows and under Copilot CLI. The old
|
||||
* `"$CLAUDE_PROJECT_DIR/.claude/hooks/check-gstack.sh"` only worked in a POSIX
|
||||
* shell, so on Windows an intended allow or deny became a hook error (#2217).
|
||||
*
|
||||
* This reads the hook source and the registered command straight out of
|
||||
* bin/gstack-team-init (no bash needed) and runs the command through the
|
||||
* platform's default shell (`shell: true`: /bin/sh here, cmd.exe on Windows),
|
||||
* plus PowerShell when one is installed, from a project path with a space.
|
||||
*/
|
||||
import { afterAll, describe, expect, test } from 'bun:test';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
|
||||
const TEAM_INIT = fs.readFileSync(new URL('../bin/gstack-team-init', import.meta.url), 'utf-8');
|
||||
|
||||
const HOOK_START = 'cat > "$HOOKS_DIR/check-gstack.cjs" << \'HOOK_EOF\'\n';
|
||||
const hookSource = TEAM_INIT.slice(TEAM_INIT.indexOf(HOOK_START) + HOOK_START.length, TEAM_INIT.indexOf('\nHOOK_EOF\n'));
|
||||
const commandLiteral = TEAM_INIT.match(/^\s*HOOK_COMMAND="((?:[^"\\]|\\.)*)"$/m)?.[1] ?? '';
|
||||
const command = commandLiteral.replace(/\\(["\\$`])/g, '$1');
|
||||
|
||||
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'team-hook-neutral-'));
|
||||
afterAll(() => fs.rmSync(base, { recursive: true, force: true }));
|
||||
const project = path.join(base, 'my project');
|
||||
fs.mkdirSync(path.join(project, '.claude', 'hooks'), { recursive: true });
|
||||
fs.writeFileSync(path.join(project, '.claude', 'hooks', 'check-gstack.cjs'), hookSource);
|
||||
const elsewhere = path.join(base, 'elsewhere');
|
||||
fs.mkdirSync(elsewhere);
|
||||
|
||||
function hookEnv(home: Record<string, string>): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = { ...process.env, CLAUDE_PROJECT_DIR: project, ...home };
|
||||
delete env.GSTACK_ROOT;
|
||||
if (!('HOME' in home)) delete env.HOME;
|
||||
return env;
|
||||
}
|
||||
|
||||
type Runner = (env: NodeJS.ProcessEnv) => { status: number | null; stdout: string; stderr: string };
|
||||
const viaDefaultShell: Runner = (env) => spawnSync(command, { shell: true, cwd: elsewhere, env, encoding: 'utf-8', timeout: 20_000 });
|
||||
const powershell = process.platform === 'win32' ? 'powershell' : Bun.which('pwsh');
|
||||
const viaPowerShell: Runner = (env) =>
|
||||
spawnSync(powershell!, ['-NoProfile', '-NonInteractive', '-Command', command], { cwd: elsewhere, env, encoding: 'utf-8', timeout: 30_000 });
|
||||
|
||||
describe('required team hook: shell-neutral registration', () => {
|
||||
test('the extracted command is a node launcher with no shell variable syntax', () => {
|
||||
expect(hookSource).toContain("'use strict';");
|
||||
expect(command).toStartWith('node -e "');
|
||||
expect(command).toContain('process.env.CLAUDE_PROJECT_DIR');
|
||||
expect(commandLiteral).not.toContain('$');
|
||||
expect(command).not.toContain('%');
|
||||
});
|
||||
|
||||
// `powershell -Command` reports a failing native command as exit 1, so only
|
||||
// the default shell sees the hook's own exit 2; the deny JSON is the same.
|
||||
for (const [name, runner, enabled, denyStatus] of [
|
||||
['the default shell', viaDefaultShell, true, 2],
|
||||
['PowerShell', viaPowerShell, Boolean(powershell), 1],
|
||||
] as const) {
|
||||
test.skipIf(!enabled)(`through ${name}: deny with exit 2 when no install resolves, {} when one does`, () => {
|
||||
const home = path.join(base, `home-${name.replace(/\W+/g, '-')}`);
|
||||
fs.mkdirSync(home, { recursive: true });
|
||||
|
||||
const denied = runner(hookEnv({ HOME: home, USERPROFILE: home }));
|
||||
expect(denied.status).toBe(denyStatus);
|
||||
expect(JSON.parse(denied.stdout.trim()).hookSpecificOutput).toMatchObject({ hookEventName: 'PreToolUse', permissionDecision: 'deny' });
|
||||
expect(denied.stderr).toContain('BLOCKED: gstack is not installed globally.');
|
||||
|
||||
fs.mkdirSync(path.join(home, '.claude/skills/gstack/bin'), { recursive: true });
|
||||
const allowed = runner(hookEnv({ HOME: home, USERPROFILE: home }));
|
||||
expect(allowed.stderr).toBe('');
|
||||
expect(allowed.stdout.trim()).toBe('{}');
|
||||
expect(allowed.status).toBe(0);
|
||||
|
||||
const viaProfile = runner(hookEnv({ USERPROFILE: home }));
|
||||
expect(viaProfile.stdout.trim()).toBe('{}');
|
||||
expect(viaProfile.status).toBe(0);
|
||||
});
|
||||
}
|
||||
});
|
||||
+88
-1
@@ -233,7 +233,7 @@ describe('gstack-team-init', () => {
|
||||
|
||||
test('required: creates enforcement hook', () => {
|
||||
run(`${TEAM_INIT} required`, { cwd: tmpDir });
|
||||
const hookPath = path.join(tmpDir, '.claude', 'hooks', 'check-gstack.sh');
|
||||
const hookPath = path.join(tmpDir, '.claude', 'hooks', 'check-gstack.cjs');
|
||||
expect(fs.existsSync(hookPath)).toBe(true);
|
||||
const hook = fs.readFileSync(hookPath, 'utf-8');
|
||||
expect(hook).toContain('BLOCKED: gstack is not installed');
|
||||
@@ -267,6 +267,93 @@ describe('gstack-team-init', () => {
|
||||
expect(pre.map((e: { matcher: string }) => e.matcher)).toEqual(['Bash', 'Skill|skill']);
|
||||
});
|
||||
|
||||
const registeredCommand = () => {
|
||||
const pre = JSON.parse(fs.readFileSync(path.join(tmpDir, '.claude', 'settings.json'), 'utf-8')).hooks.PreToolUse;
|
||||
return pre.flatMap((e: { hooks: { command: string }[] }) => e.hooks.map(h => h.command)).find((c: string) => c.includes('check-gstack'));
|
||||
};
|
||||
|
||||
test('required: the registered command is shell-neutral (no shell variable syntax, node reads CLAUDE_PROJECT_DIR)', () => {
|
||||
run(`${TEAM_INIT} required`, { cwd: tmpDir });
|
||||
const command = registeredCommand();
|
||||
expect(command).toStartWith('node -e "');
|
||||
expect(command).toContain('process.env.CLAUDE_PROJECT_DIR');
|
||||
expect(command).toContain('check-gstack.cjs');
|
||||
expect(command).not.toContain('$');
|
||||
expect(command).not.toContain('%');
|
||||
expect(command).not.toContain('.sh');
|
||||
});
|
||||
|
||||
test('required: the registered command, run from another directory, allows when gstack resolves and denies when not', () => {
|
||||
run(`${TEAM_INIT} required`, { cwd: tmpDir });
|
||||
const command = registeredCommand();
|
||||
const home = mkTmpDir();
|
||||
const elsewhere = mkTmpDir();
|
||||
const hook = (env: Record<string, string>) => {
|
||||
const r = Bun.spawnSync(['sh', '-c', command], { cwd: elsewhere, env: { PATH: process.env.PATH!, CLAUDE_PROJECT_DIR: tmpDir, ...env }, timeout: 10_000 });
|
||||
return { code: r.exitCode, out: r.stdout.toString().trim(), err: r.stderr.toString() };
|
||||
};
|
||||
try {
|
||||
const denied = hook({ HOME: home });
|
||||
expect(denied.code).toBe(2);
|
||||
expect(JSON.parse(denied.out).hookSpecificOutput.permissionDecision).toBe('deny');
|
||||
expect(denied.err).toContain('BLOCKED: gstack is not installed globally.');
|
||||
|
||||
expect(hook({ HOME: home, GSTACK_ROOT: path.join(ROOT) })).toEqual({ code: 0, out: '{}', err: '' });
|
||||
fs.mkdirSync(path.join(home, '.codex', 'skills', 'gstack', 'bin'), { recursive: true });
|
||||
expect(hook({ HOME: home })).toEqual({ code: 0, out: '{}', err: '' });
|
||||
// No HOME (a Windows hook runner): USERPROFILE is next.
|
||||
expect(hook({ USERPROFILE: home })).toEqual({ code: 0, out: '{}', err: '' });
|
||||
} finally {
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
fs.rmSync(elsewhere, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('required: re-running over a legacy .sh registration leaves exactly one handler and removes the tracked .sh', () => {
|
||||
const hooksDir = path.join(tmpDir, '.claude', 'hooks');
|
||||
fs.mkdirSync(hooksDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(hooksDir, 'check-gstack.sh'), '#!/bin/bash\necho "{}"\n', { mode: 0o755 });
|
||||
const legacy = { type: 'command', command: '"$CLAUDE_PROJECT_DIR/.claude/hooks/check-gstack.sh"' };
|
||||
fs.writeFileSync(path.join(tmpDir, '.claude', 'settings.json'), JSON.stringify({ hooks: { PreToolUse: [
|
||||
{ matcher: 'Skill', hooks: [{ type: 'command', command: 'team-audit' }, legacy] },
|
||||
{ matcher: 'Skill|skill', hooks: [legacy] },
|
||||
{ matcher: 'Bash', hooks: [{ type: 'command', command: 'my-own-hook' }] },
|
||||
] } }));
|
||||
execSync('git add .claude && git commit -q -m legacy', { cwd: tmpDir, timeout: 30_000 });
|
||||
|
||||
const first = run(`${TEAM_INIT} required`, { cwd: tmpDir });
|
||||
expect(first.exitCode).toBe(0);
|
||||
expect(fs.existsSync(path.join(hooksDir, 'check-gstack.sh'))).toBe(false);
|
||||
expect(first.stdout).toMatch(/git add .*\.claude\/hooks\/check-gstack\.sh/);
|
||||
run(`${TEAM_INIT} required`, { cwd: tmpDir });
|
||||
|
||||
const pre = JSON.parse(fs.readFileSync(path.join(tmpDir, '.claude', 'settings.json'), 'utf-8')).hooks.PreToolUse;
|
||||
expect(pre).toEqual([
|
||||
{ matcher: 'Skill|skill', hooks: [{ type: 'command', command: 'team-audit' }, { type: 'command', command: registeredCommand() }] },
|
||||
{ matcher: 'Bash', hooks: [{ type: 'command', command: 'my-own-hook' }] },
|
||||
]);
|
||||
expect(registeredCommand()).not.toContain('$');
|
||||
});
|
||||
|
||||
test('required: without bun the legacy .sh stays, since nothing re-registers its replacement', () => {
|
||||
const hooksDir = path.join(tmpDir, '.claude', 'hooks');
|
||||
fs.mkdirSync(hooksDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(hooksDir, 'check-gstack.sh'), '#!/bin/bash\necho "{}"\n', { mode: 0o755 });
|
||||
const bin = mkTmpDir();
|
||||
try {
|
||||
for (const tool of ['git', 'bash', 'cat', 'mkdir', 'chmod', 'grep', 'dirname', 'rm']) {
|
||||
const real = execSync(`command -v ${tool}`, { encoding: 'utf-8', shell: '/bin/bash' }).trim();
|
||||
fs.symlinkSync(real, path.join(bin, tool));
|
||||
}
|
||||
const r = run(`${bin}/bash ${TEAM_INIT} required`, { cwd: tmpDir, env: { PATH: bin } });
|
||||
expect(r.exitCode).toBe(0);
|
||||
expect(r.stdout).toContain('bun not found');
|
||||
expect(fs.existsSync(path.join(hooksDir, 'check-gstack.sh'))).toBe(true);
|
||||
} finally {
|
||||
fs.rmSync(bin, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('idempotent: running twice does not duplicate CLAUDE.md section', () => {
|
||||
run(`${TEAM_INIT} optional`, { cwd: tmpDir });
|
||||
run(`${TEAM_INIT} optional`, { cwd: tmpDir });
|
||||
|
||||
Reference in new issue
Block a user