From f629bd560db75aaa05952da7f51bf7e7e367bdf7 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 8 Oct 2026 06:23:53 +0000 Subject: [PATCH] fix(hook-check): cover skill frontmatter hooks, sourced helpers, conflict markers and the caller's tsconfig Rewrite of #3066. bin/gstack-hook-check only listed setup's hooks plus /autoplan's by name, so the /careful and /freeze PreToolUse checks (also run by /guard and /investigate), /plan-ceo-review's hand-off hook and the helpers they source were never parse-checked before Claude Code ran them. - The hook list is setup's _hook_command_path arguments plus every gstack path on a `command:` line in a generated */SKILL.md frontmatter (9 hooks, up from 6). The generated files are read rather than the .tmpl sources because the /autoplan and /plan-ceo-review commands come from resolvers. - Each shell hook's gstack-tree helpers (`.`/`source` lines, assignments and shellcheck source= directives, followed transitively) are parsed too: careful/bin/hook-extract.sh and bin/gstack-state-root.sh for /careful and /freeze. - The shim, its helpers, each TypeScript entry and every local module the bundle used (bun build --metafile; entry only when bun lacks it) are scanned for conflict-marker lines, which still parse inside heredocs, strings and template literals. - bun build runs from the gstack root, so the caller's broken tsconfig.json or bunfig.toml no longer fails every TypeScript hook. Lists are newline separated, so a root with spaces works. Tests in test/setup-hook-syntax-gate.test.ts cover each case; the gstack-doctor fixture now copies autoplan/SKILL.md, whose frontmatter registers the hook its hooks-row test breaks. docs/troubleshooting.md describes the wider check. Co-authored-by: Benjamin D. Smith <7134745+BenjaminDSmithy@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-hook-check | 96 ++++++++++++++++++++++++++--- docs/troubleshooting.md | 25 +++++--- test/gstack-doctor.test.ts | 1 + test/setup-hook-syntax-gate.test.ts | 78 +++++++++++++++++++++-- 4 files changed, 178 insertions(+), 22 deletions(-) diff --git a/bin/gstack-hook-check b/bin/gstack-hook-check index 3601e8d47..ca9727f12 100755 --- a/bin/gstack-hook-check +++ b/bin/gstack-hook-check @@ -13,14 +13,21 @@ # # The hook list comes from the registration code: every # `_hook_command_path ` argument in /setup (or the setup named by -# --setup, when another tree's setup registers 's hooks), plus the autoplan -# phase-publication hook (registered by its skill frontmatter). -# test/setup-hook-syntax-gate.test.ts keeps the two equal. +# --setup, when another tree's setup registers 's hooks), plus every +# gstack path on a `command:` line in a skill's frontmatter (/*/SKILL.md: +# /autoplan, /careful, /freeze, /guard, /investigate, /plan-ceo-review). Claude +# Code runs those while the skill is active, and a broken PreToolUse one blocks +# the tool call. test/setup-hook-syntax-gate.test.ts keeps the lists equal. # -# Each shim is parsed by the interpreter its shebang names (bash -n, sh -n). -# Each TypeScript entry the shim runs (a `.ts` beside it) is bundled with -# its local imports into a temp directory, packages external, so a broken or -# missing local import fails; a missing entry fails. +# Each shim is parsed by the interpreter its shebang names (bash -n, sh -n), +# and so is every gstack shell file it sources, transitively. Each TypeScript +# entry the shim runs (a `.ts` beside it) is bundled with its local +# imports into a temp directory, packages external, so a broken or missing +# local import fails; a missing entry fails. Bundles run from , so the +# caller's tsconfig.json and bunfig.toml are never read. The shim, its sourced +# helpers, each entry and every local module the entry bundles are scanned for +# merge conflict marker lines, which still parse inside a heredoc, a string, a +# comment or a template literal. # # Output, one line per hook: # ok @@ -44,11 +51,18 @@ if [ -z "$ROOT" ] || [ ! -d "$ROOT" ]; then echo "usage: gstack-hook-check [--setup ] [--list] " >&2 exit 2 fi +case "$ROOT" in /*) ;; *) ROOT="$PWD/$ROOT" ;; esac +[ "$ROOT" = / ] || ROOT=${ROOT%/} SETUP_FILE="${SETUP_FILE:-$ROOT/setup}" +# Frontmatter is the block between a SKILL.md's first two `---` lines. hook_list() { sed -n 's/.*\$(_hook_command_path \([A-Za-z0-9._/-]*\).*/\1/p' "$SETUP_FILE" 2>/dev/null - echo autoplan/bin/phase-publication-hook + for skill in "$ROOT"/*/SKILL.md; do + [ -f "$skill" ] || continue + tr -d '\r' < "$skill" | awk 'NR == 1 && !/^---/ { exit } NR > 1 && /^---/ { exit } /^[[:space:]]*command:/' \ + | grep -oE 'skills/gstack/[A-Za-z0-9._/-]+' | sed 's|^skills/gstack/||' + done } HOOKS=$(hook_list | awk '!seen[$0]++') @@ -79,9 +93,50 @@ first_message() { printf '%s\n' "$_msg" } +# Lists below are newline-separated, so a root with spaces stays one word. +NL=' +' +IFS=$NL FAILED=0 fail() { echo "fail $1 $2: $3"; FAILED=1; } +# sourced_by — the gstack files sources: each `*.sh` path on a +# `.`/`source` line, in a variable assignment, or in a `# shellcheck source=` +# directive. A path resolves from , then beside , then beside +# without its first segment (a `$DIR/` prefix); only files inside +# count. +sourced_by() { + _sdir=$(dirname "$1") + grep -E '^[[:space:]]*#[[:space:]]*shellcheck[[:space:]].*source=|(^|[;&|({[:space:]])(\.|source)[[:space:]]|^[[:space:]]*(local |export |readonly )?[A-Za-z_][A-Za-z0-9_]*=' "$1" \ + | grep -oE '[A-Za-z0-9._/-]*\.sh([^A-Za-z0-9_]|$)' | sed -E 's/\.sh.*$/.sh/' | awk '!seen[$0]++' | while IFS= read -r _tok; do + for _cand in "$ROOT/$_tok" "$_sdir/$_tok" "$_sdir/${_tok#*/}"; do + [ -f "$_cand" ] || continue + _cand="$(cd "$(dirname "$_cand")" && pwd)/$(basename "$_cand")" + case "$_cand" in "$ROOT"/*) [ "$_cand" != "$1" ] && echo "$_cand"; break ;; esac + done + done +} + +# helpers_of — sourced_by, followed transitively. +helpers_of() { + _seen="$NL$1$NL" _queue=$1 + while [ -n "$_queue" ]; do + _next="" + for _f in $_queue; do + for _c in $(sourced_by "$_f"); do + case "$_seen" in *"$NL$_c$NL"*) continue ;; esac + _seen="$_seen$_c$NL" + echo "$_c" + _next="$_next$_c$NL" + done + done + _queue=$_next + done +} + +META=0 +"$BUN" build --help 2>/dev/null | grep -q -- '--metafile' && META=1 + for hook in $HOOKS; do shim="$ROOT/$hook" if [ ! -f "$shim" ]; then echo "missing $hook"; continue; fi @@ -100,6 +155,14 @@ for hook in $HOOKS; do fail "$hook" "$(first_location "$shim" "$err")" "$(first_message "$err")" hook_ok=0 fi + scan="$shim" + for helper in $(helpers_of "$shim"); do + if ! err=$("$interp" -n "$helper" 2>&1); then + fail "$hook" "$(first_location "$helper" "$err")" "$(first_message "$err")" + hook_ok=0 + fi + scan="$scan$NL$helper" + done dir=$(dirname "$shim") for entry in $(grep -v '^[[:space:]]*#' "$shim" | grep -oE '[A-Za-z0-9._-]+\.ts([^A-Za-z0-9_]|$)' | sed -E 's/\.ts.*$/.ts/' | awk '!seen[$0]++'); do if [ ! -f "$dir/$entry" ]; then @@ -107,10 +170,25 @@ for hook in $HOOKS; do hook_ok=0 continue fi - if ! err=$("$BUN" build --target=bun --packages=external --outdir "$TMP_OUT/$(basename "$hook")" "$dir/$entry" 2>&1 >/dev/null); then + meta="$TMP_OUT/meta.json" metaflag="" + rm -f "$meta" + [ "$META" -eq 1 ] && metaflag="--metafile=$meta" + if ! err=$(cd "$ROOT" && "$BUN" build --target=bun --packages=external --outdir "$TMP_OUT/$(basename "$hook")" \ + ${metaflag:+"$metaflag"} "$dir/$entry" 2>&1 >/dev/null); then fail "$hook" "$(first_location "$dir/$entry" "$err")" "$(first_message "$err")" hook_ok=0 fi + scan="$scan$NL$dir/$entry" + [ -f "$meta" ] || continue + for rel in $(cd "$ROOT" && "$BUN" -e 'for (const f of Object.keys(JSON.parse(await Bun.file(process.argv[1]).text()).inputs)) console.log(f)' "$meta" 2>/dev/null); do + case "$rel" in /*|../*) ;; *) scan="$scan$NL$ROOT/$rel" ;; esac + done + done + for file in $(printf '%s\n' "$scan" | awk '!seen[$0]++'); do + marker=$(grep -nE '^(<<<<<<<|=======|>>>>>>>)( |$)' "$file" 2>/dev/null | head -1 | cut -d: -f1) + [ -n "$marker" ] || continue + fail "$hook" "$file:$marker" "unresolved merge conflict marker" + hook_ok=0 done [ "$hook_ok" -eq 1 ] && echo "ok $hook" done diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 6aa2ceac9..8453983fb 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -615,13 +615,21 @@ Bun first. **Meaning.** Claude Code runs gstack's hook shims through `/bin/sh`, and a hook that does not parse exits 2, which blocks the tool call it guards in every -session. Setup parse-checks every hook it registers (the shim, and the -TypeScript it runs with its local imports). It registers the hooks that parse, -skips the ones listed, finishes the rest of the install, and exits non-zero. -Claude Code runs hooks straight from `~/.claude/skills/gstack`, so a skipped -hook that an earlier setup registered keeps running the broken file until it -is fixed. This is a gstack bug, or a half-applied edit or merge in your -checkout: report the printed `:`. +session. Setup parse-checks every hook it registers and every hook a skill's +frontmatter runs (`/autoplan`, `/careful`, `/freeze`, `/guard`, `/investigate` +and `/plan-ceo-review`): the shim, the gstack shell helpers it sources (such as +`careful/bin/hook-extract.sh` and `bin/gstack-state-root.sh`), and the +TypeScript it runs with its local imports. A merge conflict marker line in any +of those files fails as `unresolved merge conflict marker`, even when the file +still parses (markers inside a heredoc, a string or a template literal do). +The TypeScript is bundled from the gstack checkout, so the `tsconfig.json` or +`bunfig.toml` of the project you run it from is never read. It registers the +hooks that parse, skips the ones listed, finishes the rest of the install, and +exits non-zero. Claude Code runs hooks straight from `~/.claude/skills/gstack`, +so a skipped hook that an earlier setup registered, or that a skill runs, +keeps running the broken file until it is fixed. This is a gstack bug, or a +half-applied edit or merge in your checkout: report the printed +`:`. **Fix.** @@ -637,7 +645,8 @@ cd ~/.claude/skills/gstack && ./setup ### `gstack auto-update: update held (hook-does-not-parse: :: ); nothing was installed or changed, and your current hooks keep running. ...` **Meaning.** Team-mode auto-update fetched a release with a hook that does not -parse. It checked the incoming revision before moving your checkout, so your +parse or still holds a merge conflict marker (the same check setup runs). It +checked the incoming revision before moving your checkout, so your checkout, installed skills and registered hooks stay at the current revision. gstack checks again at the next update check and installs the first release whose hooks parse. This is a gstack bug: report the printed `:`. diff --git a/test/gstack-doctor.test.ts b/test/gstack-doctor.test.ts index cd19a717f..970f0a638 100644 --- a/test/gstack-doctor.test.ts +++ b/test/gstack-doctor.test.ts @@ -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 }); }); diff --git a/test/setup-hook-syntax-gate.test.ts b/test/setup-hook-syntax-gate.test.ts index 4ab686509..cc9d88139 100644 --- a/test/setup-hook-syntax-gate.test.ts +++ b/test/setup-hook-syntax-gate.test.ts @@ -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);