diff --git a/bin/gstack-team-init b/bin/gstack-team-init index 2c92c82b4..5bba62a07 100755 --- a/bin/gstack-team-init +++ b/bin/gstack-team-init @@ -124,24 +124,38 @@ if [ "$MODE" = "required" ]; then HOOKS_DIR="$REPO_ROOT/.claude/hooks" SETTINGS="$REPO_ROOT/.claude/settings.json" - # Create enforcement hook script + # Create the enforcement hook. Claude Code and Copilot CLI may run hook + # commands through sh, cmd.exe or PowerShell, so the hook is CommonJS run by + # node, and the registered command holds no shell variable syntax: it reads + # CLAUDE_PROJECT_DIR through process.env. `.cjs` keeps a project's + # package.json "type" from changing how node loads it. mkdir -p "$HOOKS_DIR" - cat > "$HOOKS_DIR/check-gstack.sh" << 'HOOK_EOF' -#!/bin/bash -# Block skill usage when gstack is not installed globally. -# -# Resolve the install root the way gstack skill preambles do: the GSTACK_ROOT -# env var first, then every host's global install location, then the migrated -# repo location. Block only when NONE exist (#2500 — hardcoding -# ~/.claude/skills/gstack false-blocked Codex-host and migrated-repo installs). -_GSTACK_ROOT="" -for _D in "${GSTACK_ROOT:-}" "$HOME/.claude/skills/gstack" "$HOME/.codex/skills/gstack" "$HOME/.factory/skills/gstack" "$HOME/.kiro/skills/gstack" "$HOME/.config/opencode/skills/gstack" "$HOME/.slate/skills/gstack" "$HOME/.cursor/skills/gstack" "$HOME/.openclaw/skills/gstack" "$HOME/.hermes/skills/gstack" "$HOME/.gbrain/skills/gstack" "$HOME/.copilot/skills/gstack" "$HOME/.gstack/repos/gstack"; do - [ -z "$_GSTACK_ROOT" ] && [ -n "$_D" ] && [ -d "$_D/bin" ] && _GSTACK_ROOT="$_D" -done + cat > "$HOOKS_DIR/check-gstack.cjs" << 'HOOK_EOF' +'use strict'; +// Block skill usage when gstack is not installed globally. +// +// Resolve the install root the way gstack skill preambles do: the GSTACK_ROOT +// env var first, then every host's global install location, then the migrated +// repo location. Block only when NONE exist (#2500 — hardcoding +// ~/.claude/skills/gstack false-blocked Codex-host and migrated-repo installs). +const fs = require('fs'); +const os = require('os'); +const path = require('path'); -if [ -z "$_GSTACK_ROOT" ]; then - cat >&2 <<'MSG' -BLOCKED: gstack is not installed globally. +const home = process.env.HOME || process.env.USERPROFILE || os.homedir(); +const roots = [process.env.GSTACK_ROOT || ''].concat([ + '.claude/skills/gstack', '.codex/skills/gstack', '.factory/skills/gstack', '.kiro/skills/gstack', + '.config/opencode/skills/gstack', '.slate/skills/gstack', '.cursor/skills/gstack', '.openclaw/skills/gstack', + '.hermes/skills/gstack', '.gbrain/skills/gstack', '.copilot/skills/gstack', '.gstack/repos/gstack', +].map((rel) => path.join(home, rel))); +const gstackRoot = roots.find((root) => { + try { return root !== '' && fs.statSync(path.join(root, 'bin')).isDirectory(); } catch { return false; } +}); + +if (gstackRoot) { + process.stdout.write('{}\n'); +} else { + process.stderr.write(`BLOCKED: gstack is not installed globally. gstack is required for AI-assisted work in this repo. @@ -150,24 +164,27 @@ Install it: cd ~/.claude/skills/gstack && ./setup --team Then restart your AI coding tool. -MSG - # Exit 2 denies on Claude Code (#2413) and on Copilot CLI, which treats a - # preToolUse exit 2 as deny (#2229). - echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"gstack is required but not installed. See stderr for install instructions."}}' - exit 2 -fi - -echo '{}' +`); + // Exit 2 denies on Claude Code (#2413) and on Copilot CLI, which treats a + // preToolUse exit 2 as deny (#2229). + process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', + permissionDecisionReason: 'gstack is required but not installed. See stderr for install instructions.' } }) + '\n'); + process.exitCode = 2; +} HOOK_EOF - chmod +x "$HOOKS_DIR/check-gstack.sh" - GENERATED+=(".claude/hooks/check-gstack.sh") - echo " + .claude/hooks/check-gstack.sh — enforcement hook" + chmod +x "$HOOKS_DIR/check-gstack.cjs" + GENERATED+=(".claude/hooks/check-gstack.cjs") + echo " + .claude/hooks/check-gstack.cjs — enforcement hook" # Add hook to project-level settings.json - if command -v bun >/dev/null 2>&1; then - GSTACK_SETTINGS_PATH="$SETTINGS" bun -e " + HOOK_COMMAND="node -e \"require(require('path').resolve(process.env.CLAUDE_PROJECT_DIR || '.', '.claude', 'hooks', 'check-gstack.cjs'))\"" + if ! command -v bun >/dev/null 2>&1; then + echo " ! bun not found — manually add this PreToolUse hook (matcher Skill|skill) to .claude/settings.json:" + echo " $HOOK_COMMAND" + elif GSTACK_SETTINGS_PATH="$SETTINGS" GSTACK_HOOK_COMMAND="$HOOK_COMMAND" bun -e " const fs = require('fs'); const settingsPath = process.env.GSTACK_SETTINGS_PATH; + const command = process.env.GSTACK_HOOK_COMMAND; let settings = {}; try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch {} @@ -177,32 +194,43 @@ HOOK_EOF // Claude Code's skill tool is Skill; Copilot CLI's is skill, which no // Claude tool name maps to, so a bare 'Skill' never fired there (#2229). - // An entry an older team-init wrote is upgraded in place, never duplicated. + // A registration an older team-init wrote (the .sh hook, matcher Skill) + // is replaced in place: exactly one check-gstack handler remains, and + // unrelated hooks in the same entry are kept. const MATCHER = 'Skill|skill'; - const ours = settings.hooks.PreToolUse.filter(entry => - (entry.matcher === 'Skill' || entry.matcher === MATCHER) && - entry.hooks && entry.hooks.some(h => h.command && h.command.includes('check-gstack')) - ); - for (const entry of ours) entry.matcher = MATCHER; - - if (ours.length === 0) { - settings.hooks.PreToolUse.push({ - matcher: MATCHER, - hooks: [{ - type: 'command', - command: '\"\$CLAUDE_PROJECT_DIR/.claude/hooks/check-gstack.sh\"' - }] - }); - } + const isOurs = h => h && typeof h.command === 'string' && h.command.includes('check-gstack'); + let placed = false; + settings.hooks.PreToolUse = settings.hooks.PreToolUse.filter(entry => { + if (entry.matcher !== 'Skill' && entry.matcher !== MATCHER) return true; + if (!Array.isArray(entry.hooks) || !entry.hooks.some(isOurs)) return true; + entry.matcher = MATCHER; + const kept = []; + for (const h of entry.hooks) { + if (!isOurs(h)) kept.push(h); + else if (!placed) { kept.push({ type: 'command', command }); placed = true; } + } + entry.hooks = kept; + return kept.length > 0; + }); + if (!placed) settings.hooks.PreToolUse.push({ matcher: MATCHER, hooks: [{ type: 'command', command }] }); const tmp = settingsPath + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + '\n'); fs.renameSync(tmp, settingsPath); - " 2>/dev/null + "; then GENERATED+=(".claude/settings.json") echo " + .claude/settings.json — PreToolUse hook registered" + # The bash hook an older team-init wrote goes only once its replacement is + # registered; a tracked one is staged as a deletion by the git add below. + if [ -e "$HOOKS_DIR/check-gstack.sh" ]; then + rm -f "$HOOKS_DIR/check-gstack.sh" + git -C "$REPO_ROOT" ls-files --error-unmatch -- .claude/hooks/check-gstack.sh >/dev/null 2>&1 \ + && GENERATED+=(".claude/hooks/check-gstack.sh") + echo " - .claude/hooks/check-gstack.sh — replaced by check-gstack.cjs" + fi else - echo " ! bun not found — manually add the PreToolUse hook to .claude/settings.json" + echo " ! could not update .claude/settings.json — add this PreToolUse hook (matcher Skill|skill) manually:" + echo " $HOOK_COMMAND" fi fi diff --git a/test/gstack-team-init-hook-schema.test.ts b/test/gstack-team-init-hook-schema.test.ts index f5ff08a4f..ee8cef78e 100644 --- a/test/gstack-team-init-hook-schema.test.ts +++ b/test/gstack-team-init-hook-schema.test.ts @@ -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', () => { diff --git a/test/routing-probe.test.ts b/test/routing-probe.test.ts index 6fb15f131..e71e83458 100644 --- a/test/routing-probe.test.ts +++ b/test/routing-probe.test.ts @@ -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) {'); }); }); diff --git a/test/team-init-hook-shell-neutral.test.ts b/test/team-init-hook-shell-neutral.test.ts new file mode 100644 index 000000000..385c4003d --- /dev/null +++ b/test/team-init-hook-shell-neutral.test.ts @@ -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): 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); + }); + } +}); diff --git a/test/team-mode.test.ts b/test/team-mode.test.ts index cee5b095a..a7fe7b817 100644 --- a/test/team-mode.test.ts +++ b/test/team-mode.test.ts @@ -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) => { + 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 });