diff options
Diffstat (limited to 'languages')
29 files changed, 2204 insertions, 21 deletions
diff --git a/languages/bash/CLAUDE.md b/languages/bash/CLAUDE.md new file mode 100644 index 0000000..2511c47 --- /dev/null +++ b/languages/bash/CLAUDE.md @@ -0,0 +1,71 @@ +# CLAUDE.md + +## Project + +Bash/shell project. Customize this section with your own description, layout, +and conventions. + +**Typical layout:** +- `bin/` or top-level `*.sh` — entry-point scripts +- `lib/*.sh` — sourced function libraries (no `set -e`; the caller owns the shell) +- `tests/*.bats` — bats-core tests beside the scripts they exercise + +## Build & Test Commands + +If the project has a Makefile, document targets here. Common pattern: + +```bash +make test # run the bats suite +make test FILE=tests/x.bats # one file +make lint # shellcheck across the tree +make fmt # shfmt -w (if the project adopts shfmt) +``` + +Direct equivalents: `bats -r tests/`, `shellcheck script.sh`, +`shfmt -d script.sh` (diff), `shfmt -w script.sh` (write). + +## Language Rules + +See rule files in `.claude/rules/`: +- `bash.md` — code style and patterns (strict mode, quoting, `[[ ]]`, traps) +- `bash-testing.md` — bats conventions +- `verification.md` — verify-before-claim-done discipline + +## Git Workflow + +Commit conventions: see `.claude/rules/commits.md` (author identity, +no AI attribution, message format). + +Pre-commit hook in `githooks/` scans for secrets and runs `shellcheck` on staged +shell files. Activate on a fresh clone with `git config core.hooksPath githooks`. + +## Problem-Solving Approach + +Investigate before fixing. When diagnosing a bug: +1. Read the relevant script and trace what actually happens +2. Identify the root cause, not a surface symptom +3. Write a failing bats test that captures the correct behavior +4. Fix, then re-run tests + +## Testing Discipline + +TDD is the default: write a failing test before any implementation. If you can't +write the test, you don't yet understand the change. Details in +`.claude/rules/bash-testing.md`. + +## Editing Discipline + +A PostToolUse hook runs `shellcheck` on every shell file after Edit/Write/ +MultiEdit and blocks on a violation — read the SCxxxx code and fix it (each has a +wiki page). The hook covers `.sh`, `.bash`, and extensionless files with a shell +shebang. Formatting (`shfmt`) is recommended but not enforced by the hook, since +shell has no single canonical style; adopt one per project via `.editorconfig`. + +## What Not to Do + +- Don't add features beyond what was asked +- Don't refactor surrounding code when fixing a bug +- Don't leave expansions unquoted or use `[ ]` where `[[ ]]` fits +- Don't add comments to code you didn't change +- Don't commit `.env` files, credentials, or API keys — the pre-commit hook + catches common patterns but isn't a substitute for care diff --git a/languages/bash/claude/hooks/validate-bash.sh b/languages/bash/claude/hooks/validate-bash.sh new file mode 100755 index 0000000..4e75f40 --- /dev/null +++ b/languages/bash/claude/hooks/validate-bash.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Validate shell files after Edit/Write/MultiEdit. +# PostToolUse hook: receives tool-call JSON on stdin. +# +# On success: exit 0 silent. +# On failure: emit JSON with hookSpecificOutput.additionalContext so Claude +# sees a structured error in its context, THEN exit 2 to block the tool +# pipeline. stderr still echoes the error for terminal visibility. +# +# Gate: shellcheck. It catches the bugs that define shell — unquoted +# expansions, unset variables, masked exit codes — and is the high-value, +# universally-agreed check. Formatting (shfmt) is deliberately NOT enforced +# here: shell has no single canonical style (tabs vs spaces), so blocking on +# it would impose a contested choice. bash.md recommends shfmt; this hook +# enforces correctness. +# +# Scope: .sh and .bash files, plus extensionless files whose first line is a +# sh/bash shebang (the CLI tools that fill a shell-heavy repo carry no +# extension). + +set -u + +# Emit a JSON failure payload and exit 2. Arguments: +# $1 — short failure type (e.g. "SHELLCHECK FAILED") +# $2 — file path +# $3 — tool output (error body) +fail_json() { + local ctx + ctx="$(printf '%s: %s\n\n%s\n\nFix before proceeding.' "$1" "$2" "$3" \ + | jq -Rs .)" + cat <<EOF +{"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": $ctx}} +EOF + printf '%s: %s\n%s\n' "$1" "$2" "$3" >&2 + exit 2 +} + +f="$(jq -r '.tool_input.file_path // .tool_response.filePath // empty')" +[ -z "$f" ] && exit 0 +[ -f "$f" ] || exit 0 + +# Is this a shell file? By extension, or by shebang when it has no extension. +# Match on the basename, not the full path — a temp/parent dir can carry a dot +# (e.g. validate-bash-bats.XXXX/) and misfire the "*.*" extension test. +is_shell=0 +base="${f##*/}" +case "$base" in + *.sh | *.bash) is_shell=1 ;; + *.*) is_shell=0 ;; # some other extension — not ours + *) + # No extension: sniff the shebang. + if head -1 "$f" 2>/dev/null | grep -qE '^#!.*\b(bash|sh)\b'; then + is_shell=1 + fi + ;; +esac +[ "$is_shell" -eq 1 ] || exit 0 + +# No shellcheck on this machine — nothing to validate, don't block the edit. +command -v shellcheck >/dev/null 2>&1 || exit 0 + +if ! out="$(shellcheck "$f" 2>&1)"; then + fail_json "SHELLCHECK FAILED" "$f" "$out" +fi + +exit 0 diff --git a/languages/bash/claude/rules/bash-testing.md b/languages/bash/claude/rules/bash-testing.md new file mode 100644 index 0000000..c904927 --- /dev/null +++ b/languages/bash/claude/rules/bash-testing.md @@ -0,0 +1,71 @@ +# Bash Testing Rules + +Applies to: `**/*.bats` + +Implements the core principles from `testing.md`. All rules there apply here — +this file covers shell-specific patterns. + +## Framework: bats-core + +Use [bats-core](https://bats-core.readthedocs.io/) for shell tests. A test file +is `<thing>.bats`; each test is a `@test "description" { ... }` block; a non-zero +exit inside the block fails the test. Run a file with `bats path/to/file.bats`, +or a tree with `bats -r tests/`. + +Drive the script under test with `run`: it captures `$status` (exit code), +`$output` (combined stdout+stderr), and `$lines[]` (output split by line) +without the failure aborting the test. Assert on those. + +```bash +@test "greet: prints the name passed in" { + run bash "$SCRIPT" --name Ada + [ "$status" -eq 0 ] + [[ "$output" == *"Hello, Ada"* ]] +} +``` + +## Test the Real Script, Through Its Interface + +Run the actual script file — never copy its logic into the test. Invoke it the +way a caller does (`run bash "$SCRIPT" <args>`, or `run "$SCRIPT"` when it's +executable) and assert on exit status and output. A test that re-implements the +script's logic passes even when the script breaks. + +For a script that sources a library of functions, source the library in `setup` +and call the functions directly — that's the unit level; the `run` invocation is +the integration level. + +## Normal, Boundary, Error — the Three Categories + +Cover all three from `testing.md` per script: + +- Normal: the expected arguments and inputs produce the expected output and a + zero exit. +- Boundary: empty argument, missing optional flag, single-item vs many, + whitespace and unicode in inputs, a path with a space. +- Error: missing required argument, nonexistent input file, a dependency + absent. Assert the exit code and that the error names the problem — not the + exact wording (`testing.md`'s error-behavior rule). + +## Isolation and Determinism + +- `setup()` makes a fresh `mktemp -d` per test; `teardown()` removes it. No test + leans on another's leftovers, and tests pass in any order. +- Mock an external command by putting a stub earlier on `PATH`: write a small + script named like the command into a temp dir, `chmod +x`, and prepend that + dir to `PATH` for the `run`. This is how you simulate a tool being absent, + returning an error, or emitting canned output — without touching the network + or the real tool. +- Never hardcode dates; generate them relative to `date` (see the + `task-review-staleness.bats` pattern in this repo for relative-date fixtures). +- Mock at the boundary (network, the external CLI, the clock). Don't mock the + script's own functions — those are the work. + +## What Not to Do + +- Don't assert exact error-message prose; assert the exit code plus a value the + message must contain. +- Don't share mutable state between tests through a fixed temp path. +- Don't test that `shellcheck` or `bats` themselves work — trust the tools. +- Don't skip the error cases because the happy path passes; the error paths are + where shell scripts actually break. diff --git a/languages/bash/claude/rules/bash.md b/languages/bash/claude/rules/bash.md new file mode 100644 index 0000000..042138a --- /dev/null +++ b/languages/bash/claude/rules/bash.md @@ -0,0 +1,83 @@ +# Bash Code Rules + +Applies to: `**/*.sh`, `**/*.bash`, and extensionless files with a `sh`/`bash` shebang + +Shell-specific style and structure. Pairs with `bash-testing.md` for tests and +the generic `verification.md` / `commits.md` rules. When in doubt, defer to +[ShellCheck](https://www.shellcheck.net/wiki/) (every SCxxxx code has a wiki +page explaining the fix) and Google's +[Shell Style Guide](https://google.github.io/styleguide/shellguide.html). + +## ShellCheck Is the Gate, Not a Suggestion + +The bundle's PostToolUse hook runs `shellcheck` on every edited shell file and +blocks on a violation; the pre-commit hook re-checks staged files. ShellCheck +catches the bugs that define shell: unquoted expansions that word-split, unset +variables, `[ ]` pitfalls, masked exit codes. Fix the finding rather than +silence it. When a warning is a genuine false positive, disable it narrowly with +a `# shellcheck disable=SCxxxx` directive on the line above and a comment saying +why, never a file-wide blanket disable. + +## The Header: Strict Mode + +Every script starts with `#!/usr/bin/env bash` and `set -euo pipefail`: + +- `-e` exits on an unhandled non-zero command. Handle the expected-failure cases + explicitly (`cmd || true`, an `if`, a `case`) so the exit is a real error. +- `-u` treats an unset variable as an error. Use `"${VAR:-default}"` for the + ones that are legitimately optional. +- `-o pipefail` makes a pipeline fail if any stage fails, not just the last. + +A script meant to be *sourced* (a library) skips `set -e` — it would change the +caller's shell. Libraries guard their own commands instead. + +## Quote Everything + +- Double-quote every expansion: `"$var"`, `"$@"`, `"${arr[@]}"`, + `"$(command)"`. Unquoted is the single largest source of shell bugs — a path + with a space becomes two arguments. +- `"$@"` (quoted) passes arguments through untouched; `$*` and unquoted `$@` + word-split. Use `"$@"` unless you specifically want the joined string. +- Loop over arrays and `find -print0 | while IFS= read -r -d ''`, never over + unquoted command substitution or `ls` output. + +## Test, Compare, Branch + +- Use `[[ ]]` for tests, not `[ ]` / `test`. `[[ ]]` doesn't word-split its + operands, supports `&&`/`||`/`=~`, and has fewer quoting traps. +- Arithmetic goes in `(( ))` or `$(( ))`, not `[ ]` with `-eq`. +- `$(command)`, never backticks — nests cleanly and reads better. +- Prefer `printf` over `echo` for anything but a fixed literal string; + `echo` mangles values that start with `-` or contain backslashes. + +## Functions and Scope + +- Declare function-local variables with `local`. A bare assignment in a + function writes a global and leaks across calls. +- `local var; var="$(cmd)"` on two lines when you need the command's exit + status: `local var="$(cmd)"` masks `cmd`'s exit code behind `local`'s. +- Keep functions focused. A function that fetches, parses, and writes is three + functions; the test difficulty in `bash-testing.md` is the tell. +- Put `main "$@"` at the bottom for a script with more than a couple of + functions, so definition order doesn't dictate execution order. + +## Robustness + +- `trap 'rm -rf "$tmpdir"' EXIT` right after creating a temp resource, so + cleanup runs on every exit path including errors. +- Make a temp file or dir with `mktemp` / `mktemp -d`, never a fixed + `/tmp/name` (race + collision). +- Check that a required command exists before the work: `command -v jq + >/dev/null || { echo "jq required" >&2; exit 1; }`. +- Never parse `ls` output and don't `cat` a file into a pipe you could read + directly. Glob, or use `find`, or read the file in place. + +## What Not to Do + +- Don't leave an expansion unquoted to "save a quote" — quote it. +- Don't use `[ ]` when `[[ ]]` is available, or backticks when `$()` is. +- Don't silence a ShellCheck warning file-wide to clear it; fix it or disable + the one code with a reason. +- Don't refactor surrounding code while fixing a bug — keep the diff scoped. +- Don't commit credentials or API keys — the pre-commit hook catches common + patterns but isn't a substitute for care. diff --git a/languages/bash/claude/settings.json b/languages/bash/claude/settings.json new file mode 100644 index 0000000..b725603 --- /dev/null +++ b/languages/bash/claude/settings.json @@ -0,0 +1,68 @@ +{ + "attribution": { + "commit": "", + "pr": "" + }, + "permissions": { + "allow": [ + "Bash(make)", + "Bash(make help)", + "Bash(make targets)", + "Bash(make test)", + "Bash(make test *)", + "Bash(make lint)", + "Bash(make fmt)", + "Bash(shellcheck *)", + "Bash(shfmt *)", + "Bash(bats)", + "Bash(bats *)", + "Bash(git status)", + "Bash(git status *)", + "Bash(git diff)", + "Bash(git diff *)", + "Bash(git log)", + "Bash(git log *)", + "Bash(git show)", + "Bash(git show *)", + "Bash(git blame *)", + "Bash(git branch)", + "Bash(git branch -v)", + "Bash(git branch -a)", + "Bash(git branch --list *)", + "Bash(git remote)", + "Bash(git remote -v)", + "Bash(git remote show *)", + "Bash(git ls-files *)", + "Bash(git rev-parse *)", + "Bash(git cat-file *)", + "Bash(git stash list)", + "Bash(git stash show *)", + "Bash(jq *)", + "Bash(date)", + "Bash(date *)", + "Bash(which *)", + "Bash(file *)", + "Bash(ls)", + "Bash(ls *)", + "Bash(wc *)", + "Bash(du *)", + "Bash(readlink *)", + "Bash(realpath *)", + "Bash(basename *)", + "Bash(dirname *)" + ] + }, + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { + "type": "command", + "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-bash.sh" + } + ] + } + ] + } +} diff --git a/languages/bash/githooks/pre-commit b/languages/bash/githooks/pre-commit new file mode 100755 index 0000000..1520690 --- /dev/null +++ b/languages/bash/githooks/pre-commit @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# Pre-commit hook: secret scan + shellcheck on staged shell files. +# Use `git commit --no-verify` to bypass for confirmed false positives. + +set -u + +REPO_ROOT="$(git rev-parse --show-toplevel)" +cd "$REPO_ROOT" || exit 1 + +# --- 1. Secret scan --- +# Patterns for common credentials. Scans only added lines in the staged diff. +# +# Two passes because case-sensitivity differs. AWS keys are uppercase, sk- keys +# lowercase, PEM headers fixed, so those match case-SENSITIVELY: under -i, +# AKIA[0-9A-Z]{16} matches any mixed-case 20-char run, which random base64 in an +# embedded image blob hits ~6% of the time per 100KB and blocks real commits. +# Only the keyword=value patterns need -i. +SECRET_PATTERNS_CS='(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9_-]{20,}|-----BEGIN (RSA|DSA|EC|OPENSSH|PGP)( PRIVATE)?( KEY| KEY BLOCK)?-----)' +SECRET_PATTERNS_CI='(api[_-]?key|api[_-]?secret|auth[_-]?token|secret[_-]?key|bearer[_-]?token|access[_-]?token|password)[[:space:]]*[:=][[:space:]]*["'"'"'][^"'"'"']{16,}["'"'"']' + +# Read the diff on its own so a git failure is distinguishable from "grep +# matched nothing". Both end in a non-zero status, but only one of them means +# there is nothing to scan; piping them together and swallowing the result with +# `|| true` made a broken git look like a clean commit — the scan searched an +# empty string, found nothing, and the secret went in. +if ! staged_diff="$(git diff --cached -U0 --diff-filter=AM)"; then + echo "pre-commit: cannot read the staged diff — refusing to skip the secret scan" >&2 + exit 1 +fi + +# The greps keep their `|| true`: exiting 1 on no match is their normal result. +added_lines="$(printf '%s\n' "$staged_diff" | grep '^+' | grep -v '^+++' || true)" + +cs_hits="$(printf '%s\n' "$added_lines" | grep -nE "$SECRET_PATTERNS_CS" || true)" +ci_hits="$(printf '%s\n' "$added_lines" | grep -niE "$SECRET_PATTERNS_CI" || true)" +# awk dedupes lines both passes matched, keeping first-seen order. +secret_hits="$(printf '%s\n%s' "$cs_hits" "$ci_hits" \ + | grep -v '^[[:space:]]*$' | awk '!seen[$0]++' || true)" + +if [ -n "$secret_hits" ]; then + echo "pre-commit: potential secret in staged changes:" >&2 + echo "$secret_hits" >&2 + echo "" >&2 + echo "Review the lines above. If this is a false positive (test fixture, documentation)," >&2 + echo "bypass with: git commit --no-verify" >&2 + exit 1 +fi + +# --- 2. shellcheck on staged .sh / .bash files --- +# Same split as the secret scan above: a git failure must not read as "no files +# staged", which would skip the language check silently. +if ! staged_names="$(git diff --cached --name-only --diff-filter=AM)"; then + echo "pre-commit: cannot read the staged file list — refusing to skip the check" >&2 + exit 1 +fi + +staged_sh="$(printf '%s\n' "$staged_names" | grep -E '\.(sh|bash)$' || true)" + +if [ -n "$staged_sh" ] && command -v shellcheck >/dev/null 2>&1; then + failed="" + while IFS= read -r f; do + [ -z "$f" ] && continue + [ -f "$f" ] || continue + if ! shellcheck "$f" >/dev/null 2>&1; then + failed="${failed}${f}"$'\n' + fi + done <<< "$staged_sh" + + if [ -n "$failed" ]; then + printf 'pre-commit: shellcheck failed on staged files:\n\n%s\n' "$failed" >&2 + echo "Run: shellcheck <file> and fix the findings, then re-stage." >&2 + exit 1 + fi +fi + +exit 0 diff --git a/languages/bash/gitignore-add.txt b/languages/bash/gitignore-add.txt new file mode 100644 index 0000000..899f5ba --- /dev/null +++ b/languages/bash/gitignore-add.txt @@ -0,0 +1,4 @@ +# Claude Code — local tooling, delivered by install/sync, not committed +.claude/ +CLAUDE.md +githooks/ diff --git a/languages/bash/tests/validate-bash.bats b/languages/bash/tests/validate-bash.bats new file mode 100644 index 0000000..9f268a1 --- /dev/null +++ b/languages/bash/tests/validate-bash.bats @@ -0,0 +1,96 @@ +#!/usr/bin/env bats +# +# Tests for languages/bash/claude/hooks/validate-bash.sh — the PostToolUse hook +# that runs shellcheck on edited shell files and blocks on a violation. +# +# The hook reads tool-call JSON on stdin and extracts the file path, so each +# test pipes a JSON payload naming a real file it wrote into a temp dir. The +# shellcheck dependency is real (integration): clean files pass, genuinely +# broken ones fail. Tests needing shellcheck skip when it's absent so the suite +# stays portable. + +HOOK="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)/claude/hooks/validate-bash.sh" + +setup() { + TEST_DIR="$(mktemp -d -t validate-bash-bats.XXXXXX)" +} + +teardown() { + rm -rf "$TEST_DIR" +} + +# Build a tool-call JSON payload naming a file_path. +payload() { + printf '{"tool_input": {"file_path": "%s"}}' "$1" +} + +# ---- Normal ---------------------------------------------------------- + +@test "validate-bash: a clean .sh file passes silently (exit 0)" { + command -v shellcheck >/dev/null 2>&1 || skip "shellcheck not installed" + printf '#!/usr/bin/env bash\nset -euo pipefail\necho "ok"\n' > "$TEST_DIR/clean.sh" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/clean.sh")" + [ "$status" -eq 0 ] + [ -z "$output" ] +} + +# ---- Error ----------------------------------------------------------- + +@test "validate-bash: a shellcheck violation blocks (exit 2, names shellcheck)" { + command -v shellcheck >/dev/null 2>&1 || skip "shellcheck not installed" + # SC2086: unquoted expansion that word-splits — a real shellcheck warning. + printf '#!/usr/bin/env bash\nf=$1\nrm $f\n' > "$TEST_DIR/bad.sh" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/bad.sh")" + [ "$status" -eq 2 ] + [[ "$output" == *"SHELLCHECK"* ]] +} + +# ---- Boundary -------------------------------------------------------- + +@test "validate-bash: a non-shell file is ignored (exit 0)" { + printf 'print("hello")\n' > "$TEST_DIR/script.py" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/script.py")" + [ "$status" -eq 0 ] + [ -z "$output" ] +} + +@test "validate-bash: an extensionless file with a bash shebang is validated" { + command -v shellcheck >/dev/null 2>&1 || skip "shellcheck not installed" + printf '#!/usr/bin/env bash\nf=$1\nrm $f\n' > "$TEST_DIR/cli-tool" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/cli-tool")" + [ "$status" -eq 2 ] + [[ "$output" == *"SHELLCHECK"* ]] +} + +@test "validate-bash: an extensionless non-shell file is ignored (exit 0)" { + printf 'just some text\nno shebang here\n' > "$TEST_DIR/notes" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/notes")" + [ "$status" -eq 0 ] + [ -z "$output" ] +} + +@test "validate-bash: empty file_path is a no-op (exit 0)" { + run bash "$HOOK" <<< '{"tool_input": {}}' + [ "$status" -eq 0 ] + [ -z "$output" ] +} + +@test "validate-bash: a missing file is a no-op (exit 0)" { + run bash "$HOOK" <<< "$(payload "$TEST_DIR/does-not-exist.sh")" + [ "$status" -eq 0 ] + [ -z "$output" ] +} + +@test "validate-bash: shellcheck absent does not block the edit (exit 0)" { + # PATH with jq + coreutils symlinked but no shellcheck → hook can't validate, + # must not block. + STUB="$TEST_DIR/bin" + mkdir -p "$STUB" + for b in bash jq head cat printf grep sed; do + src="$(command -v "$b" 2>/dev/null)" && ln -sf "$src" "$STUB/$b" + done + printf '#!/usr/bin/env bash\nf=$1\nrm $f\n' > "$TEST_DIR/bad.sh" + run env PATH="$STUB" bash "$HOOK" <<< "$(payload "$TEST_DIR/bad.sh")" + [ "$status" -eq 0 ] + [ -z "$output" ] +} diff --git a/languages/default-CLAUDE.md b/languages/default-CLAUDE.md new file mode 100644 index 0000000..a5b6925 --- /dev/null +++ b/languages/default-CLAUDE.md @@ -0,0 +1,64 @@ +# CLAUDE.md + +## Project + +Describe this project: what it is, its layout, and its conventions. This +default was seeded by `install-lang` because the installed bundle ships no +language-specific CLAUDE.md — it deliberately names no language, so replace +this section with an accurate description rather than inheriting a wrong one. + +**Typical layout (edit to match):** +- entry points — the file(s) that run first +- source directories — where the real code lives +- tests — beside the code, or under a `tests/` tree + +## Build & Test Commands + +If the project has a Makefile, document its targets here. A common shape: + +```bash +make test # run the test suite +make lint # run the linter / formatter check +make build # build the project +``` + +Otherwise, document the direct commands a contributor runs to test and build. + +## Language Rules + +Shared rules live in `.claude/rules/` (installed from `claude-rules/`): +- `commits.md` — author identity, no AI attribution, message format +- `testing.md` — TDD discipline and test-quality standards +- `verification.md` — verify-before-claim-done discipline + +If a language bundle was installed, its own rule files (code style, testing +conventions) sit alongside these in `.claude/rules/`. + +## Git Workflow + +Commit conventions: see `.claude/rules/commits.md`. + +If a `githooks/` pre-commit hook was installed, activate it on a fresh clone +with `git config core.hooksPath githooks`. + +## Problem-Solving Approach + +Investigate before fixing. When diagnosing a bug: +1. Read the relevant code and trace what actually happens +2. Identify the root cause, not a surface symptom +3. Write a failing test that captures the correct behavior +4. Fix, then re-run tests + +## Testing Discipline + +TDD is the default: write a failing test before any implementation. If you +can't write the test, you don't yet understand the change. Details in +`.claude/rules/testing.md`. + +## What Not to Do + +- Don't add features beyond what was asked +- Don't refactor surrounding code when fixing a bug +- Don't add comments to code you didn't change +- Don't create abstractions for one-time operations +- Don't commit credentials or API keys diff --git a/languages/elisp/claude/hooks/validate-el.sh b/languages/elisp/claude/hooks/validate-el.sh index 2529fcc..870eefe 100755 --- a/languages/elisp/claude/hooks/validate-el.sh +++ b/languages/elisp/claude/hooks/validate-el.sh @@ -39,8 +39,6 @@ f="$(jq -r '.tool_input.file_path // .tool_response.filePath // empty')" [ -z "$f" ] && exit 0 [ "${f##*.}" = "el" ] || exit 0 -MAX_AUTO_TEST_FILES=20 # skip if more matches than this (large test suites) - # --- Phase 1: syntax + byte-compile --- case "$f" in */init.el|*/early-init.el) @@ -55,6 +53,7 @@ case "$f" in # under a tests/ subdir) so cross-project edits compile against their # own modules, not just this project's. if ! output="$(emacs --batch --no-site-file --no-site-lisp \ + --eval '(setq load-prefer-newer t)' \ -L "$(dirname "$f")" \ -L "$(dirname "$f")/.." \ -L "$PROJECT_ROOT" \ @@ -95,15 +94,17 @@ case "$f" in esac count="${#tests[@]}" -if [ "$count" -ge 1 ] && [ "$count" -le "$MAX_AUTO_TEST_FILES" ]; then +if [ "$count" -ge 1 ]; then load_args=() for t in "${tests[@]}"; do load_args+=("-l" "$t"); done if ! output="$(emacs --batch --no-site-file --no-site-lisp \ + --eval '(setq load-prefer-newer t)' \ -L "$PROJECT_ROOT" \ -L "$PROJECT_ROOT/modules" \ -L "$PROJECT_ROOT/tests" \ -L "$PROJECT_ROOT/themes" \ --eval '(package-initialize)' \ + --eval "(cd \"$PROJECT_ROOT/tests\")" \ -l ert "${load_args[@]}" \ --eval "(ert-run-tests-batch-and-exit '(not (tag :slow)))" 2>&1)"; then # Terminal gets a compact summary (the run tally + the failing test names); diff --git a/languages/elisp/claude/rules/elisp-testing.md b/languages/elisp/claude/rules/elisp-testing.md index 7c3a9ef..1ac76a0 100644 --- a/languages/elisp/claude/rules/elisp-testing.md +++ b/languages/elisp/claude/rules/elisp-testing.md @@ -43,6 +43,8 @@ The bundle ships a coverage summary at `.claude/scripts/coverage-summary.el` and The number to watch is the missing-file count. A module no test loads never appears in the SimpleCov report, so a line-weighted total skips it silently — the suite looks healthier than it is. The summary counts every `modules/*.el` on disk that's absent from the report as 0%, so an untested module drags the project number down where you can see it. Copy the fragment's targets into your own Makefile to adopt it; the bundle never edits your Makefile. +This is a local-only helper by design. `.claude/scripts/` is gitignored in code projects, so `coverage-summary.el` is untracked and CI never runs `make coverage-summary` against it — it's a developer-run check, not a CI gate. A gitignored install is intentional, not a coverage gap; don't move the script to a tracked `scripts/` dir to make CI pick it up. + ## TDD Workflow Write the failing test first. A failing test proves you understand the change. Assume the bug is in production code until the test proves otherwise — never fix the test before proving the test is wrong. diff --git a/languages/elisp/claude/scripts/coverage-summary.el b/languages/elisp/claude/scripts/coverage-summary.el index eb30c66..ed7ecfc 100644 --- a/languages/elisp/claude/scripts/coverage-summary.el +++ b/languages/elisp/claude/scripts/coverage-summary.el @@ -11,8 +11,15 @@ ;; by file rather than by line, so untested modules are visible. ;; ;; Self-contained on purpose — it ships into a project's =.claude/scripts/= and -;; must run with nothing but stock Emacs (`json' is built in). The SimpleCov -;; JSON shape it parses is: +;; must run with nothing but stock Emacs (`json' is built in). +;; +;; Local-only helper (Craig, 2026-06-28). =.claude/scripts/= is gitignored in +;; code projects, so this file is not tracked and CI cannot run +;; `make coverage-summary' against it. That is intentional: it stays a +;; developer-run helper, not shipped to a tracked =scripts/= dir and not a CI +;; gate. A gitignored install here is the design, not a coverage gap. +;; +;; The SimpleCov JSON shape it parses is: ;; { <suite>: { "coverage": { <abs-path>: [null | 0 | int, ...] } } } ;; where a null entry is a non-executable line, 0 is executable-but-unhit, and ;; any positive integer is a hit. Data unions across multiple suite keys. @@ -91,11 +98,15 @@ missing or malformed." (defun cj/coverage-summary--source-files (source-dir project-root) "Return *.el files directly under SOURCE-DIR, relative to PROJECT-ROOT. -Sorted; compiled files and subdirectories are out of scope." +Sorted. Compiled files and subdirectories are out of scope, as are generated +package files (`*-autoloads.el', `*-pkg.el') -- a build tool writes those, no +test covers them, and counting them as untested source skews the number." (let ((source-dir (file-name-as-directory (expand-file-name source-dir))) (project-root (file-name-as-directory (expand-file-name project-root)))) - (sort (mapcar (lambda (p) (file-relative-name p project-root)) - (directory-files source-dir t "\\.el\\'")) + (sort (seq-remove + (lambda (p) (string-match-p "\\(?:-autoloads\\|-pkg\\)\\.el\\'" p)) + (mapcar (lambda (p) (file-relative-name p project-root)) + (directory-files source-dir t "\\.el\\'"))) #'string<))) (defun cj/coverage-summary--missing (tracked source-dir project-root) diff --git a/languages/elisp/githooks/pre-commit b/languages/elisp/githooks/pre-commit index 909cde2..a87bedf 100755 --- a/languages/elisp/githooks/pre-commit +++ b/languages/elisp/githooks/pre-commit @@ -5,15 +5,37 @@ set -u REPO_ROOT="$(git rev-parse --show-toplevel)" -cd "$REPO_ROOT" +cd "$REPO_ROOT" || exit 1 # --- 1. Secret scan --- # Patterns for common credentials. Scans only added lines in the staged diff. -SECRET_PATTERNS='(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9_-]{20,}|-----BEGIN (RSA|DSA|EC|OPENSSH|PGP)( PRIVATE)?( KEY| KEY BLOCK)?-----|(api[_-]?key|api[_-]?secret|auth[_-]?token|secret[_-]?key|bearer[_-]?token|access[_-]?token|password)[[:space:]]*[:=][[:space:]]*["'"'"'][^"'"'"']{16,}["'"'"'])' +# +# Two passes because case-sensitivity differs. AWS keys are uppercase, sk- keys +# lowercase, PEM headers fixed, so those match case-SENSITIVELY: under -i, +# AKIA[0-9A-Z]{16} matches any mixed-case 20-char run, which random base64 in an +# embedded image blob hits ~6% of the time per 100KB and blocks real commits. +# Only the keyword=value patterns need -i. +SECRET_PATTERNS_CS='(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9_-]{20,}|-----BEGIN (RSA|DSA|EC|OPENSSH|PGP)( PRIVATE)?( KEY| KEY BLOCK)?-----)' +SECRET_PATTERNS_CI='(api[_-]?key|api[_-]?secret|auth[_-]?token|secret[_-]?key|bearer[_-]?token|access[_-]?token|password)[[:space:]]*[:=][[:space:]]*["'"'"'][^"'"'"']{16,}["'"'"']' -secret_hits="$(git diff --cached -U0 --diff-filter=AM \ - | grep '^+' | grep -v '^+++' \ - | grep -iEn "$SECRET_PATTERNS" || true)" +# Read the diff on its own so a git failure is distinguishable from "grep +# matched nothing". Both end in a non-zero status, but only one of them means +# there is nothing to scan; piping them together and swallowing the result with +# `|| true` made a broken git look like a clean commit — the scan searched an +# empty string, found nothing, and the secret went in. +if ! staged_diff="$(git diff --cached -U0 --diff-filter=AM)"; then + echo "pre-commit: cannot read the staged diff — refusing to skip the secret scan" >&2 + exit 1 +fi + +# The greps keep their `|| true`: exiting 1 on no match is their normal result. +added_lines="$(printf '%s\n' "$staged_diff" | grep '^+' | grep -v '^+++' || true)" + +cs_hits="$(printf '%s\n' "$added_lines" | grep -nE "$SECRET_PATTERNS_CS" || true)" +ci_hits="$(printf '%s\n' "$added_lines" | grep -niE "$SECRET_PATTERNS_CI" || true)" +# awk dedupes lines both passes matched, keeping first-seen order. +secret_hits="$(printf '%s\n%s' "$cs_hits" "$ci_hits" \ + | grep -v '^[[:space:]]*$' | awk '!seen[$0]++' || true)" if [ -n "$secret_hits" ]; then echo "pre-commit: potential secret in staged changes:" >&2 @@ -25,7 +47,14 @@ if [ -n "$secret_hits" ]; then fi # --- 2. Paren check on staged .el files --- -staged_el="$(git diff --cached --name-only --diff-filter=AM | grep '\.el$' || true)" +# Same split as the secret scan above: a git failure must not read as "no files +# staged", which would skip the language check silently. +if ! staged_names="$(git diff --cached --name-only --diff-filter=AM)"; then + echo "pre-commit: cannot read the staged file list — refusing to skip the check" >&2 + exit 1 +fi + +staged_el="$(printf '%s\n' "$staged_names" | grep '\.el$' || true)" if [ -n "$staged_el" ]; then paren_fail="" diff --git a/languages/elisp/tests/test-coverage-summary.el b/languages/elisp/tests/test-coverage-summary.el index 5be03b3..a4525db 100644 --- a/languages/elisp/tests/test-coverage-summary.el +++ b/languages/elisp/tests/test-coverage-summary.el @@ -109,6 +109,33 @@ is a JSON array string like \"[1, 0, null]\"." (ert-deftest cs-file-pct-fully-covered () (should (= 100.0 (cj/coverage-summary--file-pct 4 4)))) +;; --- source-file scan and under-dir filtering ------------------------------ + +(ert-deftest cs-source-files-is-non-recursive () + "Only top-level *.el under SOURCE-DIR are source; files in subdirectories +are out of scope." + (cs-test--with-project + (list :sources '(("top.el" . ";; t") ("sub/nested.el" . ";; n")) + :report (cs-test--report '(("top.el" . "[1]")))) + (let ((sources (mapcar #'file-name-nondirectory + (cj/coverage-summary--source-files src root)))) + (should (member "top.el" sources)) + (should-not (member "nested.el" sources))))) + +(ert-deftest cs-under-dir-filters-outside-source-and-rekeys () + "Report entries outside SOURCE-DIR are dropped; survivors are keyed +relative to PROJECT-ROOT." + (cs-test--with-project + (list :sources '(("in.el" . ";; i")) + :report (cs-test--report '(("in.el" . "[1, 1]") + ("../out.el" . "[1, 0]")))) + (let* ((table (cj/coverage-summary--under-dir + (cj/coverage-summary--parse-file report) src root)) + (keys (let (ks) (maphash (lambda (k _v) (push k ks)) table) ks))) + (should (equal keys (list (file-relative-name + (expand-file-name "src/in.el" root) root)))) + (should (= 1 (hash-table-count table)))))) + ;; --- missing-file detection (the kernel) ----------------------------------- (ert-deftest cs-missing-finds-ondisk-file-absent-from-report () @@ -135,6 +162,24 @@ is a JSON array string like \"[1, 0, null]\"." (missing (cj/coverage-summary--missing tracked src root))) (should (null missing))))) +(ert-deftest cs-missing-excludes-generated-package-files () + "Generated -autoloads.el / -pkg.el are not source, so a build tool writing +them does not drag the number down; a genuinely untested source is still +flagged (the filter is not over-broad)." + (cs-test--with-project + (list :sources '(("real.el" . ";; r") ("untested.el" . ";; u") + ("proj-autoloads.el" . ";; gen") + ("proj-pkg.el" . ";; gen")) + :report (cs-test--report '(("real.el" . "[1, 1]")))) + (let* ((table (cj/coverage-summary--under-dir + (cj/coverage-summary--parse-file report) src root)) + (tracked (let (ks) (maphash (lambda (k _v) (push k ks)) table) ks)) + (missing (mapcar #'file-name-nondirectory + (cj/coverage-summary--missing tracked src root)))) + (should (member "untested.el" missing)) + (should-not (member "proj-autoloads.el" missing)) + (should-not (member "proj-pkg.el" missing))))) + ;; --- project number (unit-weighted, missing as 0%) ------------------------- (ert-deftest cs-project-pct-unit-weighted-with-missing-as-zero () diff --git a/languages/elisp/tests/test-pre-commit-hook.bats b/languages/elisp/tests/test-pre-commit-hook.bats new file mode 100644 index 0000000..413c71d --- /dev/null +++ b/languages/elisp/tests/test-pre-commit-hook.bats @@ -0,0 +1,126 @@ +#!/usr/bin/env bats +# Tests for githooks/pre-commit — the secret scan and paren check. +# +# The scan reads its input through a pipeline: +# +# added_lines="$(git diff --cached ... | grep '^+' | grep -v '^+++' || true)" +# +# `grep` exits 1 when it matches nothing, which is the ordinary case, so the +# `|| true` has to stay. But with no `pipefail` it also swallows a failure of +# `git diff` itself, and an empty `added_lines` makes the scan search nothing, +# find nothing, and report clean. A gate that passes without looking is the +# failure this file exists to pin: the fail-open test drives a broken `git diff` +# and asserts the hook refuses rather than exiting 0. +# +# Each test builds a throwaway git repo in BATS_TEST_TMPDIR, so nothing touches +# the real repository or its hooks. + +setup() { + HOOK="${BATS_TEST_DIRNAME}/../githooks/pre-commit" + REPO="${BATS_TEST_TMPDIR}/repo" + mkdir -p "$REPO" + cd "$REPO" || return 1 + git init -q . + git config user.email t@example.com + git config user.name Test + # Split so the fixtures never appear as credential-shaped literals here. + AWS_TAIL="IOSFODNN7EXAMPLE" + WORD_TAIL="word" +} + +# Put a stub `git` ahead of the real one that fails for the staged-diff call +# and delegates everything else, so only the pipeline under test breaks. +break_staged_diff() { + mkdir -p "${BATS_TEST_TMPDIR}/bin" + cat > "${BATS_TEST_TMPDIR}/bin/git" <<'STUB' +#!/usr/bin/env bash +if [ "${1:-}" = "diff" ] && [ "${2:-}" = "--cached" ] && [ "${3:-}" = "-U0" ]; then + echo "simulated git failure" >&2 + exit 128 +fi +exec /usr/bin/git "$@" +STUB + chmod +x "${BATS_TEST_TMPDIR}/bin/git" + PATH="${BATS_TEST_TMPDIR}/bin:$PATH" +} + +# ------------------------------- Normal cases ------------------------------- + +@test "secret scan: blocks a staged AWS key" { + # Assembled at runtime: a literal key-shaped string in this file would trip + # the very hook under test on every commit that touches it, and this repo + # mirrors to a public remote. + printf 'aws = "%s"\n' "AKIA${AWS_TAIL}" > creds.txt + git add creds.txt + run "$HOOK" + [ "$status" -eq 1 ] + [[ "$output" == *"potential secret"* ]] +} + +@test "secret scan: blocks a staged keyword=value password" { + printf '%s = "%s"\n' "pass${WORD_TAIL}" "correcthorsebatterystaple" > conf.txt + git add conf.txt + run "$HOOK" + [ "$status" -eq 1 ] + [[ "$output" == *"potential secret"* ]] +} + +@test "secret scan: allows an ordinary staged file" { + printf 'just some prose\n' > notes.txt + git add notes.txt + run "$HOOK" + [ "$status" -eq 0 ] +} + +# ------------------------------ Boundary cases ------------------------------ + +@test "secret scan: allows a commit with nothing staged" { + run "$HOOK" + [ "$status" -eq 0 ] +} + +@test "paren check: blocks an unbalanced staged .el file" { + printf '(defun broken ()\n (message "no close"\n' > bad.el + git add bad.el + run "$HOOK" + [ "$status" -eq 1 ] + [[ "$output" == *"paren check failed"* ]] +} + +@test "paren check: allows a balanced staged .el file" { + printf '(defun fine ()\n (message "ok"))\n' > good.el + git add good.el + run "$HOOK" + [ "$status" -eq 0 ] +} + +# -------------------------------- Error cases ------------------------------- + +@test "secret scan: refuses to pass when the staged diff cannot be read" { + # The scan must not report clean after searching nothing. Without a + # pipefail-aware guard the broken diff yields an empty added_lines and the + # hook exits 0, letting a real secret through unscanned. + printf 'aws = "%s"\n' "AKIA${AWS_TAIL}" > creds.txt + git add creds.txt + break_staged_diff + run "$HOOK" + [ "$status" -ne 0 ] +} + +@test "paren check: refuses to pass when the staged file list cannot be read" { + printf '(defun broken ()\n (message "no close"\n' > bad.el + git add bad.el + mkdir -p "${BATS_TEST_TMPDIR}/bin2" + cat > "${BATS_TEST_TMPDIR}/bin2/git" <<'STUB' +#!/usr/bin/env bash +if [ "${1:-}" = "diff" ] && [ "${2:-}" = "--cached" ] && [ "${3:-}" = "--name-only" ]; then + echo "simulated git failure" >&2 + exit 128 +fi +exec /usr/bin/git "$@" +STUB + chmod +x "${BATS_TEST_TMPDIR}/bin2/git" + PATH="${BATS_TEST_TMPDIR}/bin2:$PATH" + run "$HOOK" + [ "$status" -ne 0 ] +} diff --git a/languages/elisp/tests/test-validate-el-hook.bats b/languages/elisp/tests/test-validate-el-hook.bats new file mode 100644 index 0000000..d4d6f23 --- /dev/null +++ b/languages/elisp/tests/test-validate-el-hook.bats @@ -0,0 +1,100 @@ +#!/usr/bin/env bats +# Tests for .claude/hooks/validate-el.sh — the auto-test runner. +# +# The runner used to skip entirely above MAX_AUTO_TEST_FILES=20, with no else +# branch: nothing printed, exit 0, indistinguishable from a passing run. That +# was live for the three largest families here (calendar-sync 63 test files, +# music 45, ai-term 35), so every edit to those ran parens and byte-compile and +# zero tests, silently. +# +# The cap was removed rather than made loud, because its premise did not hold. +# Measured on this machine, running a whole family takes about a second: +# ai-term 208 tests in 1.0s, music 403 in 1.7s, calendar-sync 633 in 0.9s. It +# was also concealing a real cross-test pollution bug in calendar-sync that +# only appears when that family runs in one process. +# +# These tests pin that no file count is skipped. Each builds a synthetic +# project in BATS_TEST_TMPDIR and points CLAUDE_PROJECT_DIR at it, so nothing +# runs against the real tree. + +setup() { + # Bundle layout: the hook ships at claude/hooks/ here and installs to + # .claude/hooks/ in a consuming project. This test was written against the + # installed layout, so re-homing it needed the path adjusted. + HOOK="${BATS_TEST_DIRNAME}/../claude/hooks/validate-el.sh" + PROJ="${BATS_TEST_TMPDIR}/proj" + mkdir -p "$PROJ/modules" "$PROJ/tests" + export CLAUDE_PROJECT_DIR="$PROJ" + printf '(provide (quote widget))\n' > "$PROJ/modules/widget.el" +} + +# N green test files matching the widget stem. +make_tests() { + local n="$1" i + for ((i = 1; i <= n; i++)); do + printf '(require (quote ert))\n(ert-deftest test-widget-%d () (should t))\n' \ + "$i" > "$PROJ/tests/test-widget-${i}.el" + done +} + +# One failing test file, to prove the run is real rather than merely quiet. +make_failing_test() { + printf '(require (quote ert))\n(ert-deftest test-widget-bad () (should nil))\n' \ + > "$PROJ/tests/test-widget-bad.el" +} + +hook_input() { + printf '{"tool_input":{"file_path":"%s"}}' "$PROJ/modules/widget.el" +} + +run_hook() { + run bash -c "$(printf '%q' "$HOOK") <<< '$(hook_input)'" +} + +# ------------------------------- Normal cases ------------------------------- + +@test "a small family runs and passes quietly" { + make_tests 3 + run_hook + [ "$status" -eq 0 ] +} + +@test "a failing test blocks, so a quiet pass means the tests really ran" { + make_tests 3 + make_failing_test + run_hook + [ "$status" -eq 2 ] + [[ "$output" == *"TESTS FAILED"* ]] +} + +# ------------------------------ Boundary cases ------------------------------ + +@test "at the old cap of 20 files: runs" { + make_tests 20 + run_hook + [ "$status" -eq 0 ] +} + +@test "past the old cap: still runs, no longer skipped" { + make_tests 21 + run_hook + [ "$status" -eq 0 ] + [[ "${output,,}" != *"skipped"* ]] +} + +@test "well past the old cap: a failure in file 63 is still caught" { + # The regression this guards: at 63 files the runner used to skip, so a red + # test in a big family reported clean. calendar-sync is exactly this size. + make_tests 63 + make_failing_test + run_hook + [ "$status" -eq 2 ] + [[ "$output" == *"TESTS FAILED"* ]] +} + +# -------------------------------- Error cases ------------------------------- + +@test "no matching tests: exits clean without running anything" { + run_hook + [ "$status" -eq 0 ] +} diff --git a/languages/go/githooks/pre-commit b/languages/go/githooks/pre-commit index a3d6f3f..7d93949 100755 --- a/languages/go/githooks/pre-commit +++ b/languages/go/githooks/pre-commit @@ -5,15 +5,37 @@ set -u REPO_ROOT="$(git rev-parse --show-toplevel)" -cd "$REPO_ROOT" +cd "$REPO_ROOT" || exit 1 # --- 1. Secret scan --- # Patterns for common credentials. Scans only added lines in the staged diff. -SECRET_PATTERNS='(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9_-]{20,}|-----BEGIN (RSA|DSA|EC|OPENSSH|PGP)( PRIVATE)?( KEY| KEY BLOCK)?-----|(api[_-]?key|api[_-]?secret|auth[_-]?token|secret[_-]?key|bearer[_-]?token|access[_-]?token|password)[[:space:]]*[:=][[:space:]]*["'"'"'][^"'"'"']{16,}["'"'"'])' +# +# Two passes because case-sensitivity differs. AWS keys are uppercase, sk- keys +# lowercase, PEM headers fixed, so those match case-SENSITIVELY: under -i, +# AKIA[0-9A-Z]{16} matches any mixed-case 20-char run, which random base64 in an +# embedded image blob hits ~6% of the time per 100KB and blocks real commits. +# Only the keyword=value patterns need -i. +SECRET_PATTERNS_CS='(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9_-]{20,}|-----BEGIN (RSA|DSA|EC|OPENSSH|PGP)( PRIVATE)?( KEY| KEY BLOCK)?-----)' +SECRET_PATTERNS_CI='(api[_-]?key|api[_-]?secret|auth[_-]?token|secret[_-]?key|bearer[_-]?token|access[_-]?token|password)[[:space:]]*[:=][[:space:]]*["'"'"'][^"'"'"']{16,}["'"'"']' -secret_hits="$(git diff --cached -U0 --diff-filter=AM \ - | grep '^+' | grep -v '^+++' \ - | grep -iEn "$SECRET_PATTERNS" || true)" +# Read the diff on its own so a git failure is distinguishable from "grep +# matched nothing". Both end in a non-zero status, but only one of them means +# there is nothing to scan; piping them together and swallowing the result with +# `|| true` made a broken git look like a clean commit — the scan searched an +# empty string, found nothing, and the secret went in. +if ! staged_diff="$(git diff --cached -U0 --diff-filter=AM)"; then + echo "pre-commit: cannot read the staged diff — refusing to skip the secret scan" >&2 + exit 1 +fi + +# The greps keep their `|| true`: exiting 1 on no match is their normal result. +added_lines="$(printf '%s\n' "$staged_diff" | grep '^+' | grep -v '^+++' || true)" + +cs_hits="$(printf '%s\n' "$added_lines" | grep -nE "$SECRET_PATTERNS_CS" || true)" +ci_hits="$(printf '%s\n' "$added_lines" | grep -niE "$SECRET_PATTERNS_CI" || true)" +# awk dedupes lines both passes matched, keeping first-seen order. +secret_hits="$(printf '%s\n%s' "$cs_hits" "$ci_hits" \ + | grep -v '^[[:space:]]*$' | awk '!seen[$0]++' || true)" if [ -n "$secret_hits" ]; then echo "pre-commit: potential secret in staged changes:" >&2 @@ -27,8 +49,14 @@ fi # --- 2. gofmt check on staged .go files --- # gofmt -l lists files that aren't gofmt-clean. Skip generated and vendored # files the same way the rest of the toolchain does. -staged_go="$(git diff --cached --name-only --diff-filter=AM \ - | grep '\.go$' \ +# Same split as the secret scan above: a git failure must not read as "no files +# staged", which would skip the language check silently. +if ! staged_names="$(git diff --cached --name-only --diff-filter=AM)"; then + echo "pre-commit: cannot read the staged file list — refusing to skip the check" >&2 + exit 1 +fi + +staged_go="$(printf '%s\n' "$staged_names" | grep '\.go$' \ | grep -vE '(^|/)vendor/' || true)" if [ -n "$staged_go" ] && command -v gofmt >/dev/null 2>&1; then diff --git a/languages/python/CLAUDE.md b/languages/python/CLAUDE.md new file mode 100644 index 0000000..a2d0a82 --- /dev/null +++ b/languages/python/CLAUDE.md @@ -0,0 +1,80 @@ +# CLAUDE.md + +## Project + +Python project. Customize this section with your own description, layout, +and conventions. + +**Typical layout:** +- `src/<package>/` or a top-level package directory — importable code +- `tests/` — pytest tests mirroring the package layout +- `pyproject.toml` — dependencies, tool config (ruff, pytest, coverage) + +## Build & Test Commands + +If the project has a Makefile, document targets here. Common pattern: + +```bash +make test # run the pytest suite +make test FILE=tests/x.py # one file +make coverage # suite + coverage report +make lint # ruff across the tree +make typecheck # mypy (if the project adopts it) +make fmt # ruff format / black +``` + +Direct equivalents: `python3 -m pytest`, `pytest tests/test_x.py::test_name`, +`ruff check .`, `ruff format --diff .`, `mypy src/`. + +## Language Rules + +See rule files in `.claude/rules/`: +- `python-testing.md` — pytest conventions and fixture discipline +- `verification.md` — verify-before-claim-done discipline + +## Git Workflow + +Commit conventions: see `.claude/rules/commits.md` (author identity, +no AI attribution, message format). + +Pre-commit hook in `githooks/` scans for secrets, syntax-checks staged Python, +and runs `ruff` when it's installed. Activate on a fresh clone with +`git config core.hooksPath githooks`. + +## Problem-Solving Approach + +Investigate before fixing. When diagnosing a bug: +1. Read the relevant module and trace what actually happens +2. Identify the root cause, not a surface symptom +3. Write a failing test that captures the correct behavior +4. Fix, then re-run tests + +## Testing Discipline + +TDD is the default: write a failing test before any implementation. If you can't +write the test, you don't yet understand the change. Details in +`.claude/rules/python-testing.md`. + +## Editing Discipline + +A PostToolUse hook syntax-checks every Python file after Edit/Write/MultiEdit +and blocks on a parse error, then runs `ruff` when it's installed. The hook +covers `.py`, `.pyi`, and extensionless files with a python shebang. + +Type checking is not enforced by the hook — it needs the whole package and its +dependencies resolved, which is a build-scale operation rather than a +per-keystroke one. Run it via `make typecheck`. + +Formatting is likewise not enforced: a project picks its own line length and +quote style, so blocking on an unconfigured default would impose a contested +choice. Adopt one per project in `pyproject.toml`. + +## What Not to Do + +- Don't add features beyond what was asked +- Don't refactor surrounding code when fixing a bug +- Don't use a bare `except:` or swallow an exception without handling it +- Don't use a mutable default argument (`def f(xs=[])`) +- Don't add comments to code you didn't change +- Don't commit `.env` files, credentials, or API keys — the pre-commit hook + catches common patterns but isn't a substitute for care diff --git a/languages/python/claude/hooks/validate-python.sh b/languages/python/claude/hooks/validate-python.sh new file mode 100755 index 0000000..e43ad77 --- /dev/null +++ b/languages/python/claude/hooks/validate-python.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# Validate Python files after Edit/Write/MultiEdit. +# PostToolUse hook: receives tool-call JSON on stdin. +# +# On success: exit 0 silent. +# On failure: emit JSON with hookSpecificOutput.additionalContext so Claude +# sees a structured error in its context, THEN exit 2 to block the tool +# pipeline. stderr still echoes the error for terminal visibility. +# +# Phase 1: syntax — python3 compiles the file. Always available wherever this +# hook can meaningfully run, so it's the floor rather than an optional +# gate: a file that doesn't parse is never worth passing on. +# Phase 2: ruff — lint, when installed. Catches undefined names, unused +# imports, and the rest of the pyflakes set. Absent ruff doesn't block +# the edit, matching how the bash bundle treats shellcheck. +# +# Formatters (black, ruff format) are deliberately NOT enforced here. A project +# picks its own line length and quote style, so blocking on an unconfigured +# default would impose a contested choice. python.md recommends a formatter; +# this hook enforces correctness. +# +# Type checking (mypy, pyright) is also out: it needs the whole package and its +# dependencies resolved, which is a build-scale operation, not a per-keystroke +# one. Run it via `make lint` / `make typecheck`. +# +# Scope: .py and .pyi files, plus extensionless files whose first line is a +# python shebang (the CLI tools that fill a script-heavy repo carry no +# extension). + +set -u + +# Emit a JSON failure payload and exit 2. Arguments: +# $1 — short failure type (e.g. "PYTHON SYNTAX ERROR") +# $2 — file path +# $3 — tool output (error body) +fail_json() { + local ctx + ctx="$(printf '%s: %s\n\n%s\n\nFix before proceeding.' "$1" "$2" "$3" \ + | jq -Rs .)" + cat <<EOF +{"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": $ctx}} +EOF + printf '%s: %s\n%s\n' "$1" "$2" "$3" >&2 + exit 2 +} + +f="$(jq -r '.tool_input.file_path // .tool_response.filePath // empty')" +[ -z "$f" ] && exit 0 +[ -f "$f" ] || exit 0 + +# Is this a Python file? By extension, or by shebang when it has no extension. +# Match on the basename, not the full path — a temp/parent dir can carry a dot +# (e.g. my.project/) and misfire the "*.*" extension test. +is_python=0 +base="${f##*/}" +case "$base" in + *.py | *.pyi) is_python=1 ;; + *.*) is_python=0 ;; # some other extension — not ours + *) + # No extension: sniff the shebang. + if head -1 "$f" 2>/dev/null | grep -qE '^#!.*\bpython[0-9.]*\b'; then + is_python=1 + fi + ;; +esac +[ "$is_python" -eq 1 ] || exit 0 + +# No python3 on this machine — nothing to validate, don't block the edit. +command -v python3 >/dev/null 2>&1 || exit 0 + +# --- Phase 1: syntax --- +# compile() rather than py_compile so no __pycache__ lands beside the source; +# the hook is a checker and must not leave build artifacts in the tree. +if ! out="$(python3 -c ' +import sys +p = sys.argv[1] +with open(p, "rb") as fh: + src = fh.read() +try: + compile(src, p, "exec") +except SyntaxError as e: + print(f"{e.msg} ({p}, line {e.lineno})", file=sys.stderr) + sys.exit(1) +' "$f" 2>&1)"; then + fail_json "PYTHON SYNTAX ERROR" "$f" "$out" +fi + +# --- Phase 2: lint (optional) --- +command -v ruff >/dev/null 2>&1 || exit 0 + +if ! out="$(ruff check "$f" 2>&1)"; then + fail_json "RUFF FAILED" "$f" "$out" +fi + +exit 0 diff --git a/languages/python/claude/settings.json b/languages/python/claude/settings.json new file mode 100644 index 0000000..9c6b2a9 --- /dev/null +++ b/languages/python/claude/settings.json @@ -0,0 +1,79 @@ +{ + "attribution": { + "commit": "", + "pr": "" + }, + "permissions": { + "allow": [ + "Bash(make)", + "Bash(make help)", + "Bash(make targets)", + "Bash(make test)", + "Bash(make test *)", + "Bash(make lint)", + "Bash(make fmt)", + "Bash(make coverage)", + "Bash(make coverage-summary)", + "Bash(make typecheck)", + "Bash(pytest)", + "Bash(pytest *)", + "Bash(python3 -m pytest *)", + "Bash(ruff check *)", + "Bash(ruff format --diff *)", + "Bash(black --check *)", + "Bash(black --diff *)", + "Bash(mypy *)", + "Bash(python3 -m py_compile *)", + "Bash(python3 --version)", + "Bash(pip list)", + "Bash(pip show *)", + "Bash(git status)", + "Bash(git status *)", + "Bash(git diff)", + "Bash(git diff *)", + "Bash(git log)", + "Bash(git log *)", + "Bash(git show)", + "Bash(git show *)", + "Bash(git blame *)", + "Bash(git branch)", + "Bash(git branch -v)", + "Bash(git branch -a)", + "Bash(git branch --list *)", + "Bash(git remote)", + "Bash(git remote -v)", + "Bash(git remote show *)", + "Bash(git ls-files *)", + "Bash(git rev-parse *)", + "Bash(git cat-file *)", + "Bash(git stash list)", + "Bash(git stash show *)", + "Bash(jq *)", + "Bash(date)", + "Bash(date *)", + "Bash(which *)", + "Bash(file *)", + "Bash(ls)", + "Bash(ls *)", + "Bash(wc *)", + "Bash(du *)", + "Bash(readlink *)", + "Bash(realpath *)", + "Bash(basename *)", + "Bash(dirname *)" + ] + }, + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { + "type": "command", + "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-python.sh" + } + ] + } + ] + } +} diff --git a/languages/python/githooks/pre-commit b/languages/python/githooks/pre-commit new file mode 100755 index 0000000..03536db --- /dev/null +++ b/languages/python/githooks/pre-commit @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# Pre-commit hook: secret scan + syntax/lint check on staged Python files. +# Use `git commit --no-verify` to bypass for confirmed false positives. + +set -u + +REPO_ROOT="$(git rev-parse --show-toplevel)" +cd "$REPO_ROOT" || exit 1 + +# --- 1. Secret scan --- +# Patterns for common credentials. Scans only added lines in the staged diff. +# +# Two passes because case-sensitivity differs. AWS keys are uppercase, sk- keys +# lowercase, PEM headers fixed, so those match case-SENSITIVELY: under -i, +# AKIA[0-9A-Z]{16} matches any mixed-case 20-char run, which random base64 in an +# embedded image blob hits ~6% of the time per 100KB and blocks real commits. +# Only the keyword=value patterns need -i. +SECRET_PATTERNS_CS='(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9_-]{20,}|-----BEGIN (RSA|DSA|EC|OPENSSH|PGP)( PRIVATE)?( KEY| KEY BLOCK)?-----)' +SECRET_PATTERNS_CI='(api[_-]?key|api[_-]?secret|auth[_-]?token|secret[_-]?key|bearer[_-]?token|access[_-]?token|password)[[:space:]]*[:=][[:space:]]*["'"'"'][^"'"'"']{16,}["'"'"']' + +# Read the diff on its own so a git failure is distinguishable from "grep +# matched nothing". Both end in a non-zero status, but only one of them means +# there is nothing to scan; piping them together and swallowing the result with +# `|| true` made a broken git look like a clean commit — the scan searched an +# empty string, found nothing, and the secret went in. +if ! staged_diff="$(git diff --cached -U0 --diff-filter=AM)"; then + echo "pre-commit: cannot read the staged diff — refusing to skip the secret scan" >&2 + exit 1 +fi + +# The greps keep their `|| true`: exiting 1 on no match is their normal result. +added_lines="$(printf '%s\n' "$staged_diff" | grep '^+' | grep -v '^+++' || true)" + +cs_hits="$(printf '%s\n' "$added_lines" | grep -nE "$SECRET_PATTERNS_CS" || true)" +ci_hits="$(printf '%s\n' "$added_lines" | grep -niE "$SECRET_PATTERNS_CI" || true)" +# awk dedupes lines both passes matched, keeping first-seen order. +secret_hits="$(printf '%s\n%s' "$cs_hits" "$ci_hits" \ + | grep -v '^[[:space:]]*$' | awk '!seen[$0]++' || true)" + +if [ -n "$secret_hits" ]; then + echo "pre-commit: potential secret in staged changes:" >&2 + echo "$secret_hits" >&2 + echo "" >&2 + echo "Review the lines above. If this is a false positive (test fixture, documentation)," >&2 + echo "bypass with: git commit --no-verify" >&2 + exit 1 +fi + +# --- 2. Syntax check on staged Python files --- +# Same split as the secret scan above: a git failure must not read as "no files +# staged", which would skip the language check silently. +if ! staged_names="$(git diff --cached --name-only --diff-filter=AM)"; then + echo "pre-commit: cannot read the staged file list — refusing to skip the check" >&2 + exit 1 +fi + +staged_py="$(printf '%s\n' "$staged_names" | grep -E '\.pyi?$' || true)" + +if [ -n "$staged_py" ] && command -v python3 >/dev/null 2>&1; then + failed="" + while IFS= read -r f; do + [ -z "$f" ] && continue + [ -f "$f" ] || continue + # compile() rather than py_compile so no __pycache__ lands in the tree. + if ! python3 -c 'import sys; compile(open(sys.argv[1], "rb").read(), sys.argv[1], "exec")' "$f" >/dev/null 2>&1; then + failed="${failed}${f}"$'\n' + fi + done <<< "$staged_py" + + if [ -n "$failed" ]; then + printf 'pre-commit: Python syntax errors in staged files:\n\n%s\n' "$failed" >&2 + echo "Run: python3 -m py_compile <file> to see the error, then re-stage." >&2 + exit 1 + fi +fi + +# --- 3. ruff on staged Python files (when installed) --- +if [ -n "$staged_py" ] && command -v ruff >/dev/null 2>&1; then + failed="" + while IFS= read -r f; do + [ -z "$f" ] && continue + [ -f "$f" ] || continue + if ! ruff check "$f" >/dev/null 2>&1; then + failed="${failed}${f}"$'\n' + fi + done <<< "$staged_py" + + if [ -n "$failed" ]; then + printf 'pre-commit: ruff failed on staged files:\n\n%s\n' "$failed" >&2 + echo "Run: ruff check <file> and fix the findings, then re-stage." >&2 + exit 1 + fi +fi + +exit 0 diff --git a/languages/python/tests/pre-commit.bats b/languages/python/tests/pre-commit.bats new file mode 100644 index 0000000..1ac82ee --- /dev/null +++ b/languages/python/tests/pre-commit.bats @@ -0,0 +1,138 @@ +#!/usr/bin/env bats +# +# Tests for languages/python/githooks/pre-commit — the secret scan plus +# syntax/lint gate that runs on staged Python files. +# +# The secret scan is the security-critical half and is language-independent, so +# it gets the same coverage here as in the bash bundle: a real key blocks, a +# clean diff passes, and the case-sensitivity split that keeps base64 blobs from +# false-positiving is exercised directly. +# +# Each test builds a throwaway git repo, stages content, and runs the hook from +# inside it — the hook reads `git diff --cached`, so a real index is required. + +HOOK="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)/githooks/pre-commit" + +setup() { + TEST_DIR="$(mktemp -d -t pre-commit-py-bats.XXXXXX)" + cd "$TEST_DIR" || exit 1 + git init -q . + git config user.email t@example.com + git config user.name Test + # A base commit so `git diff --cached` has a parent to diff against. + echo "seed" > seed.txt + git add seed.txt + git commit -qm seed +} + +teardown() { + cd / || true + rm -rf "$TEST_DIR" +} + +# ---- Normal ---------------------------------------------------------- + +@test "pre-commit(py): a clean staged Python file passes (exit 0)" { + printf 'def f(x):\n return x + 1\n' > ok.py + git add ok.py + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +@test "pre-commit(py): an empty staging area passes (exit 0)" { + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +# ---- Error: the secret scan ------------------------------------------ + +@test "pre-commit(py): an AWS key in a staged file blocks (exit 1)" { + printf 'KEY = "AKIAIOSFODNN7EXAMPLE"\n' > conf.py + git add conf.py + run bash "$HOOK" + [ "$status" -eq 1 ] + [[ "$output" == *"potential secret"* ]] +} + +@test "pre-commit(py): an sk- style token blocks (exit 1)" { + printf 'TOKEN = "sk-abcdefghijklmnopqrstuvwxyz0123"\n' > conf.py + git add conf.py + run bash "$HOOK" + [ "$status" -eq 1 ] +} + +@test "pre-commit(py): a quoted api_key assignment blocks (exit 1)" { + printf 'api_key = "abcdefghijklmnopqrstuvwxyz"\n' > conf.py + git add conf.py + run bash "$HOOK" + [ "$status" -eq 1 ] +} + +@test "pre-commit(py): a private-key header blocks (exit 1)" { + printf 'PEM = """-----BEGIN RSA PRIVATE KEY-----"""\n' > conf.py + git add conf.py + run bash "$HOOK" + [ "$status" -eq 1 ] +} + +# ---- Boundary: the case-sensitivity split ---------------------------- + +@test "pre-commit(py): a mixed-case base64 blob does NOT false-positive" { + # The AWS pattern is uppercase-only by design. Under -i it would match any + # 20-char mixed-case run, which random base64 hits often enough to block + # real commits. This is the regression test for that split. + printf 'BLOB = "AKIAbcdefGHIJklmnOPqr0123456789abcdefGHIJ"\n' > data.py + git add data.py + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +@test "pre-commit(py): a short quoted password value does NOT block" { + # The keyword patterns require 16+ chars, so a placeholder stays quiet. + printf 'password = "short"\n' > conf.py + git add conf.py + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +@test "pre-commit(py): a secret only in a REMOVED line does not block" { + printf 'KEY = "AKIAIOSFODNN7EXAMPLE"\n' > conf.py + git add conf.py + git commit -qm "add key" + rm conf.py + git add -A + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +# ---- Error: the syntax gate ------------------------------------------ + +@test "pre-commit(py): a staged Python syntax error blocks (exit 1)" { + printf 'def f(:\n return 1\n' > bad.py + git add bad.py + run bash "$HOOK" + [ "$status" -eq 1 ] + [[ "$output" == *"syntax"* ]] +} + +@test "pre-commit(py): a .pyi stub with a syntax error blocks (exit 1)" { + printf 'def f( -> int: ...\n' > bad.pyi + git add bad.pyi + run bash "$HOOK" + [ "$status" -eq 1 ] +} + +@test "pre-commit(py): a broken NON-Python file does not trip the syntax gate" { + printf 'this is (((not python\n' > notes.txt + git add notes.txt + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +@test "pre-commit(py): the syntax gate leaves no __pycache__ in the repo" { + printf 'def f():\n return 1\n' > ok.py + git add ok.py + run bash "$HOOK" + [ "$status" -eq 0 ] + [ ! -d __pycache__ ] +} diff --git a/languages/python/tests/validate-python.bats b/languages/python/tests/validate-python.bats new file mode 100644 index 0000000..b5e4957 --- /dev/null +++ b/languages/python/tests/validate-python.bats @@ -0,0 +1,117 @@ +#!/usr/bin/env bats +# +# Tests for languages/python/claude/hooks/validate-python.sh — the PostToolUse +# hook that syntax-checks edited Python files and blocks on a violation. +# +# The hook reads tool-call JSON on stdin and extracts the file path, so each +# test pipes a JSON payload naming a real file it wrote into a temp dir. +# +# The syntax gate is python3's own compiler, which is present wherever the hook +# can meaningfully run, so those tests never skip. The lint gate (ruff) is +# optional and its tests skip when it's absent, matching the bash bundle's +# treatment of shellcheck. + +HOOK="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)/claude/hooks/validate-python.sh" + +setup() { + TEST_DIR="$(mktemp -d -t validate-python-bats.XXXXXX)" +} + +teardown() { + rm -rf "$TEST_DIR" +} + +payload() { + printf '{"tool_input": {"file_path": "%s"}}' "$1" +} + +# ---- Normal ---------------------------------------------------------- + +@test "validate-python: a clean .py file passes silently (exit 0)" { + printf 'def f(x):\n return x + 1\n' > "$TEST_DIR/clean.py" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/clean.py")" + [ "$status" -eq 0 ] + [ -z "$output" ] +} + +@test "validate-python: a .pyi stub is validated too" { + printf 'def f(x: int) -> int: ...\n' > "$TEST_DIR/clean.pyi" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/clean.pyi")" + [ "$status" -eq 0 ] +} + +# ---- Error ----------------------------------------------------------- + +@test "validate-python: a syntax error blocks (exit 2, names the failure)" { + printf 'def f(:\n return 1\n' > "$TEST_DIR/bad.py" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/bad.py")" + [ "$status" -eq 2 ] + [[ "$output" == *"SYNTAX"* ]] +} + +@test "validate-python: the block payload is valid JSON carrying the context" { + printf 'def f(:\n' > "$TEST_DIR/bad.py" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/bad.py")" + [ "$status" -eq 2 ] + # The first line of stdout must parse as JSON and carry the hook event name. + echo "$output" | head -1 | jq -e '.hookSpecificOutput.hookEventName == "PostToolUse"' +} + +@test "validate-python: a ruff violation blocks when ruff is installed" { + command -v ruff >/dev/null 2>&1 || skip "ruff not installed" + # F821: reference to an undefined name — syntactically valid, lint-caught. + printf 'def f():\n return undefined_name\n' > "$TEST_DIR/lint.py" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/lint.py")" + [ "$status" -eq 2 ] + [[ "$output" == *"RUFF"* ]] +} + +# ---- Boundary -------------------------------------------------------- + +@test "validate-python: a non-Python file is ignored (exit 0)" { + printf 'not python at all (((\n' > "$TEST_DIR/notes.txt" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/notes.txt")" + [ "$status" -eq 0 ] +} + +@test "validate-python: an extensionless file with a python shebang is validated" { + printf '#!/usr/bin/env python3\ndef f(:\n' > "$TEST_DIR/cli-tool" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/cli-tool")" + [ "$status" -eq 2 ] +} + +@test "validate-python: an extensionless non-python file is ignored (exit 0)" { + printf '#!/usr/bin/env bash\necho hi\n' > "$TEST_DIR/shell-tool" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/shell-tool")" + [ "$status" -eq 0 ] +} + +@test "validate-python: a dotted parent directory does not misfire the extension test" { + mkdir -p "$TEST_DIR/my.project" + printf '#!/usr/bin/env python3\ndef f(:\n' > "$TEST_DIR/my.project/cli-tool" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/my.project/cli-tool")" + [ "$status" -eq 2 ] +} + +@test "validate-python: empty file_path is a no-op (exit 0)" { + run bash "$HOOK" <<< '{"tool_input": {}}' + [ "$status" -eq 0 ] +} + +@test "validate-python: a missing file is a no-op (exit 0)" { + run bash "$HOOK" <<< "$(payload "$TEST_DIR/does-not-exist.py")" + [ "$status" -eq 0 ] +} + +@test "validate-python: an empty .py file passes (valid, compiles to nothing)" { + : > "$TEST_DIR/empty.py" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/empty.py")" + [ "$status" -eq 0 ] +} + +@test "validate-python: compiling leaves no __pycache__ beside the file" { + printf 'def f():\n return 1\n' > "$TEST_DIR/clean.py" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/clean.py")" + [ "$status" -eq 0 ] + [ ! -d "$TEST_DIR/__pycache__" ] +} diff --git a/languages/typescript/CLAUDE.md b/languages/typescript/CLAUDE.md new file mode 100644 index 0000000..1794115 --- /dev/null +++ b/languages/typescript/CLAUDE.md @@ -0,0 +1,82 @@ +# CLAUDE.md + +## Project + +TypeScript/JavaScript project. Customize this section with your own +description, layout, and conventions. + +**Typical layout:** +- `src/` — source modules +- `tests/` or `*.test.ts` beside the source — test files +- `package.json` — scripts and dependencies +- `tsconfig.json` — compiler options + +## Build & Test Commands + +If the project has a Makefile, document targets here. Common pattern: + +```bash +make test # run the test suite +make coverage # suite + coverage report +make typecheck # tsc --noEmit across the project +make lint # eslint +make build # production build +``` + +Direct equivalents: `npm test`, `npx tsc --noEmit`, `npx eslint src/`, +`npx prettier --check .`, `node --test`. + +## Language Rules + +See rule files in `.claude/rules/`: +- `typescript-testing.md` — test conventions and mocking discipline +- `verification.md` — verify-before-claim-done discipline + +## Git Workflow + +Commit conventions: see `.claude/rules/commits.md` (author identity, +no AI attribution, message format). + +Pre-commit hook in `githooks/` scans for secrets and parse-checks staged TS/JS. +Activate on a fresh clone with `git config core.hooksPath githooks`. + +## Problem-Solving Approach + +Investigate before fixing. When diagnosing a bug: +1. Read the relevant module and trace what actually happens +2. Identify the root cause, not a surface symptom +3. Write a failing test that captures the correct behavior +4. Fix, then re-run tests + +## Testing Discipline + +TDD is the default: write a failing test before any implementation. If you can't +write the test, you don't yet understand the change. Details in +`.claude/rules/typescript-testing.md`. + +## Editing Discipline + +A PostToolUse hook parse-checks every TS/JS file after Edit/Write/MultiEdit and +blocks on a syntax error. It covers `.ts`, `.tsx`, `.mts`, `.cts`, `.js`, +`.jsx`, `.mjs`, and `.cjs`. + +Two checkers, because one tool can't do both jobs: `node --check` for +JavaScript, `tsc` filtered to syntax diagnostics for TypeScript. Do not +substitute `node --check` for the TypeScript path — it ignores +`--experimental-strip-types`, so it rejects valid TypeScript and accepts broken +TypeScript (measured on node v26.4.0). + +Full type checking is not enforced by the hook: it needs the whole project graph +and its dependencies resolved, which is a build-scale operation rather than a +per-keystroke one. Run it via `make typecheck`. Formatting is likewise not +enforced; adopt a style per project in the project's own config. + +## What Not to Do + +- Don't add features beyond what was asked +- Don't refactor surrounding code when fixing a bug +- Don't reach for `any` to silence a type error — narrow the type instead +- Don't use `==` where `===` is meant +- Don't add comments to code you didn't change +- Don't commit `.env` files, credentials, or API keys — the pre-commit hook + catches common patterns but isn't a substitute for care diff --git a/languages/typescript/claude/hooks/validate-typescript.sh b/languages/typescript/claude/hooks/validate-typescript.sh new file mode 100755 index 0000000..b76f1df --- /dev/null +++ b/languages/typescript/claude/hooks/validate-typescript.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +# Validate TypeScript/JavaScript files after Edit/Write/MultiEdit. +# PostToolUse hook: receives tool-call JSON on stdin. +# +# On success: exit 0 silent. +# On failure: emit JSON with hookSpecificOutput.additionalContext so Claude +# sees a structured error in its context, THEN exit 2 to block the tool +# pipeline. stderr still echoes the error for terminal visibility. +# +# Gate: parseability. A file that doesn't parse is never worth passing on. +# Full type checking is deliberately NOT enforced here — it needs the whole +# project graph and its dependencies resolved, which is a build-scale +# operation, not a per-keystroke one. A type error that parses cleanly passes +# this hook; `make typecheck` / `tsc --noEmit` over the project owns it. +# +# Formatting (prettier) is also out: a project picks its own style, so blocking +# on an unconfigured default would impose a contested choice. +# +# Two checkers, because one tool can't do both jobs: +# +# .js/.jsx/.mjs/.cjs → `node --check`, a straight parse. +# .ts/.tsx/.mts/.cts → `tsc`, filtered to syntax-category diagnostics. +# +# `node --check` must NOT be used on TypeScript. It ignores +# --experimental-strip-types, so it is wrong in *both* directions: it rejects +# valid TS (an `interface` declaration reads as a syntax error) and accepts +# broken TS (a genuinely unparseable file exits 0). Measured on node v26.4.0, +# 2026-07-23. tsc is the only correct parser for these extensions. +# +# The tsc call is filtered to TS1xxx codes, which is TypeScript's syntactic +# diagnostic range; TS2xxx and up are semantic (type) errors and are out of +# scope by the paragraph above. Without the filter this hook would block every +# unresolved import in a file whose dependencies aren't installed yet. + +set -u + +# Emit a JSON failure payload and exit 2. Arguments: +# $1 — short failure type (e.g. "TYPESCRIPT SYNTAX ERROR") +# $2 — file path +# $3 — tool output (error body) +fail_json() { + local ctx + ctx="$(printf '%s: %s\n\n%s\n\nFix before proceeding.' "$1" "$2" "$3" \ + | jq -Rs .)" + cat <<EOF +{"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": $ctx}} +EOF + printf '%s: %s\n%s\n' "$1" "$2" "$3" >&2 + exit 2 +} + +f="$(jq -r '.tool_input.file_path // .tool_response.filePath // empty')" +[ -z "$f" ] && exit 0 +[ -f "$f" ] || exit 0 + +# Classify by extension. Match on the basename, not the full path — a parent +# dir can carry a dot (e.g. my.project/) and confuse a path-wide match. +kind="" +base="${f##*/}" +case "$base" in + *.ts | *.tsx | *.mts | *.cts) kind="ts" ;; + *.js | *.jsx | *.mjs | *.cjs) kind="js" ;; + *) exit 0 ;; +esac + +if [ "$kind" = "js" ]; then + command -v node >/dev/null 2>&1 || exit 0 + if ! out="$(node --check "$f" 2>&1)"; then + fail_json "JAVASCRIPT SYNTAX ERROR" "$f" "$out" + fi + exit 0 +fi + +# TypeScript. Prefer a project-local tsc so the project's own version decides, +# falling back to one on PATH. +tsc_bin="" +if [ -x "./node_modules/.bin/tsc" ]; then + tsc_bin="./node_modules/.bin/tsc" +elif command -v tsc >/dev/null 2>&1; then + tsc_bin="tsc" +else + exit 0 # no TypeScript compiler available — don't block the edit +fi + +# --moduleDetection force so a file with no import/export still parses as a +# module rather than tripping global-scope collisions against lib types. +out="$("$tsc_bin" --noEmit --skipLibCheck --target es2022 --moduleDetection force "$f" 2>&1 || true)" +syntax_errors="$(printf '%s\n' "$out" | grep -E 'error TS1[0-9]{3}:' || true)" + +if [ -n "$syntax_errors" ]; then + fail_json "TYPESCRIPT SYNTAX ERROR" "$f" "$syntax_errors" +fi + +exit 0 diff --git a/languages/typescript/claude/settings.json b/languages/typescript/claude/settings.json new file mode 100644 index 0000000..f4c9211 --- /dev/null +++ b/languages/typescript/claude/settings.json @@ -0,0 +1,80 @@ +{ + "attribution": { + "commit": "", + "pr": "" + }, + "permissions": { + "allow": [ + "Bash(make)", + "Bash(make help)", + "Bash(make targets)", + "Bash(make test)", + "Bash(make test *)", + "Bash(make lint)", + "Bash(make fmt)", + "Bash(make coverage)", + "Bash(make coverage-summary)", + "Bash(make typecheck)", + "Bash(make build)", + "Bash(npm test)", + "Bash(npm test *)", + "Bash(npm run *)", + "Bash(npm ci)", + "Bash(npm ls *)", + "Bash(node --check *)", + "Bash(node --test *)", + "Bash(node --version)", + "Bash(tsc --noEmit *)", + "Bash(npx tsc --noEmit *)", + "Bash(eslint *)", + "Bash(prettier --check *)", + "Bash(git status)", + "Bash(git status *)", + "Bash(git diff)", + "Bash(git diff *)", + "Bash(git log)", + "Bash(git log *)", + "Bash(git show)", + "Bash(git show *)", + "Bash(git blame *)", + "Bash(git branch)", + "Bash(git branch -v)", + "Bash(git branch -a)", + "Bash(git branch --list *)", + "Bash(git remote)", + "Bash(git remote -v)", + "Bash(git remote show *)", + "Bash(git ls-files *)", + "Bash(git rev-parse *)", + "Bash(git cat-file *)", + "Bash(git stash list)", + "Bash(git stash show *)", + "Bash(jq *)", + "Bash(date)", + "Bash(date *)", + "Bash(which *)", + "Bash(file *)", + "Bash(ls)", + "Bash(ls *)", + "Bash(wc *)", + "Bash(du *)", + "Bash(readlink *)", + "Bash(realpath *)", + "Bash(basename *)", + "Bash(dirname *)" + ] + }, + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { + "type": "command", + "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-typescript.sh" + } + ] + } + ] + } +} diff --git a/languages/typescript/githooks/pre-commit b/languages/typescript/githooks/pre-commit new file mode 100755 index 0000000..fd494d2 --- /dev/null +++ b/languages/typescript/githooks/pre-commit @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +# Pre-commit hook: secret scan + syntax check on staged TypeScript/JavaScript files. +# Use `git commit --no-verify` to bypass for confirmed false positives. + +set -u + +REPO_ROOT="$(git rev-parse --show-toplevel)" +cd "$REPO_ROOT" || exit 1 + +# --- 1. Secret scan --- +# Patterns for common credentials. Scans only added lines in the staged diff. +# +# Two passes because case-sensitivity differs. AWS keys are uppercase, sk- keys +# lowercase, PEM headers fixed, so those match case-SENSITIVELY: under -i, +# AKIA[0-9A-Z]{16} matches any mixed-case 20-char run, which random base64 in an +# embedded image blob hits ~6% of the time per 100KB and blocks real commits. +# Only the keyword=value patterns need -i. +SECRET_PATTERNS_CS='(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9_-]{20,}|-----BEGIN (RSA|DSA|EC|OPENSSH|PGP)( PRIVATE)?( KEY| KEY BLOCK)?-----)' +SECRET_PATTERNS_CI='(api[_-]?key|api[_-]?secret|auth[_-]?token|secret[_-]?key|bearer[_-]?token|access[_-]?token|password)[[:space:]]*[:=][[:space:]]*["'"'"'][^"'"'"']{16,}["'"'"']' + +# Read the diff on its own so a git failure is distinguishable from "grep +# matched nothing". Both end in a non-zero status, but only one of them means +# there is nothing to scan; piping them together and swallowing the result with +# `|| true` made a broken git look like a clean commit — the scan searched an +# empty string, found nothing, and the secret went in. +if ! staged_diff="$(git diff --cached -U0 --diff-filter=AM)"; then + echo "pre-commit: cannot read the staged diff — refusing to skip the secret scan" >&2 + exit 1 +fi + +# The greps keep their `|| true`: exiting 1 on no match is their normal result. +added_lines="$(printf '%s\n' "$staged_diff" | grep '^+' | grep -v '^+++' || true)" + +cs_hits="$(printf '%s\n' "$added_lines" | grep -nE "$SECRET_PATTERNS_CS" || true)" +ci_hits="$(printf '%s\n' "$added_lines" | grep -niE "$SECRET_PATTERNS_CI" || true)" +# awk dedupes lines both passes matched, keeping first-seen order. +secret_hits="$(printf '%s\n%s' "$cs_hits" "$ci_hits" \ + | grep -v '^[[:space:]]*$' | awk '!seen[$0]++' || true)" + +if [ -n "$secret_hits" ]; then + echo "pre-commit: potential secret in staged changes:" >&2 + echo "$secret_hits" >&2 + echo "" >&2 + echo "Review the lines above. If this is a false positive (test fixture, documentation)," >&2 + echo "bypass with: git commit --no-verify" >&2 + exit 1 +fi + +# --- 2. Syntax check on staged TS/JS files --- +# Two checkers, because one tool can't do both jobs. `node --check` ignores +# --experimental-strip-types, so on TypeScript it is wrong in BOTH directions: +# it rejects valid TS (an `interface` reads as a syntax error) and accepts +# broken TS. Measured on node v26.4.0, 2026-07-23. tsc is the only correct +# parser for .ts; node is correct and much faster for .js. +# Same split as the secret scan above: a git failure must not read as "no files +# staged", which would skip the language check silently. +if ! staged_names="$(git diff --cached --name-only --diff-filter=AM)"; then + echo "pre-commit: cannot read the staged file list — refusing to skip the check" >&2 + exit 1 +fi + +staged_js="$(printf '%s\n' "$staged_names" | grep -E '\.(js|jsx|mjs|cjs)$' || true)" +staged_ts="$(printf '%s\n' "$staged_names" | grep -E '\.(ts|tsx|mts|cts)$' || true)" + +failed="" + +if [ -n "$staged_js" ] && command -v node >/dev/null 2>&1; then + while IFS= read -r f; do + [ -z "$f" ] && continue + [ -f "$f" ] || continue + if ! node --check "$f" >/dev/null 2>&1; then + failed="${failed}${f}"$'\n' + fi + done <<< "$staged_js" +fi + +if [ -n "$staged_ts" ]; then + tsc_bin="" + if [ -x "./node_modules/.bin/tsc" ]; then + tsc_bin="./node_modules/.bin/tsc" + elif command -v tsc >/dev/null 2>&1; then + tsc_bin="tsc" + fi + + if [ -n "$tsc_bin" ]; then + while IFS= read -r f; do + [ -z "$f" ] && continue + [ -f "$f" ] || continue + # Filter to TS1xxx, TypeScript's syntactic diagnostic range. TS2xxx and + # up are type errors, which need the whole project graph and are the + # build's job, not this hook's. + out="$("$tsc_bin" --noEmit --skipLibCheck --target es2022 \ + --moduleDetection force "$f" 2>&1 || true)" + if printf '%s\n' "$out" | grep -qE 'error TS1[0-9]{3}:'; then + failed="${failed}${f}"$'\n' + fi + done <<< "$staged_ts" + fi +fi + +if [ -n "$failed" ]; then + printf 'pre-commit: syntax errors in staged files:\n\n%s\n' "$failed" >&2 + echo "Fix the parse errors above, then re-stage." >&2 + exit 1 +fi + +exit 0 diff --git a/languages/typescript/tests/pre-commit.bats b/languages/typescript/tests/pre-commit.bats new file mode 100644 index 0000000..5519baa --- /dev/null +++ b/languages/typescript/tests/pre-commit.bats @@ -0,0 +1,150 @@ +#!/usr/bin/env bats +# +# Tests for languages/typescript/githooks/pre-commit — the secret scan plus +# syntax/lint gate that runs on staged TS/JS files. +# +# The secret scan is the security-critical half and is language-independent, so +# it gets the same coverage here as in the bash bundle: a real key blocks, a +# clean diff passes, and the case-sensitivity split that keeps base64 blobs from +# false-positiving is exercised directly. +# +# Each test builds a throwaway git repo, stages content, and runs the hook from +# inside it — the hook reads `git diff --cached`, so a real index is required. + +HOOK="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)/githooks/pre-commit" + +setup() { + TEST_DIR="$(mktemp -d -t pre-commit-ts-bats.XXXXXX)" + cd "$TEST_DIR" || exit 1 + git init -q . + git config user.email t@example.com + git config user.name Test + # A base commit so `git diff --cached` has a parent to diff against. + echo "seed" > seed.txt + git add seed.txt + git commit -qm seed +} + +teardown() { + cd / || true + rm -rf "$TEST_DIR" +} + +# ---- Normal ---------------------------------------------------------- + +@test "pre-commit(ts): a clean staged JS file passes (exit 0)" { + printf 'export const f = (x) => x + 1;\n' > ok.js + git add ok.js + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +@test "pre-commit(ts): an empty staging area passes (exit 0)" { + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +# ---- Error: the secret scan ------------------------------------------ + +@test "pre-commit(ts): an AWS key in a staged file blocks (exit 1)" { + printf 'const KEY = "AKIAIOSFODNN7EXAMPLE";\n' > conf.ts + git add conf.ts + run bash "$HOOK" + [ "$status" -eq 1 ] + [[ "$output" == *"potential secret"* ]] +} + +@test "pre-commit(ts): an sk- style token blocks (exit 1)" { + printf 'const TOKEN = "sk-abcdefghijklmnopqrstuvwxyz0123";\n' > conf.ts + git add conf.ts + run bash "$HOOK" + [ "$status" -eq 1 ] +} + +@test "pre-commit(ts): a quoted api_key assignment blocks (exit 1)" { + printf 'const api_key = "abcdefghijklmnopqrstuvwxyz";\n' > conf.ts + git add conf.ts + run bash "$HOOK" + [ "$status" -eq 1 ] +} + +@test "pre-commit(ts): a private-key header blocks (exit 1)" { + printf 'const PEM = "-----BEGIN RSA PRIVATE KEY-----";\n' > conf.ts + git add conf.ts + run bash "$HOOK" + [ "$status" -eq 1 ] +} + +# ---- Boundary: the case-sensitivity split ---------------------------- + +@test "pre-commit(ts): a mixed-case base64 blob does NOT false-positive" { + # The AWS pattern is uppercase-only by design. Under -i it would match any + # 20-char mixed-case run, which random base64 hits often enough to block + # real commits. This is the regression test for that split. + printf 'const BLOB = "AKIAbcdefGHIJklmnOPqr0123456789abcdefGHIJ";\n' > data.ts + git add data.ts + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +@test "pre-commit(ts): a short quoted password value does NOT block" { + # The keyword patterns require 16+ chars, so a placeholder stays quiet. + printf 'const password = "short";\n' > conf.ts + git add conf.ts + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +@test "pre-commit(ts): a secret only in a REMOVED line does not block" { + printf 'const KEY = "AKIAIOSFODNN7EXAMPLE";\n' > conf.ts + git add conf.ts + git commit -qm "add key" + rm conf.ts + git add -A + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +# ---- Error: the syntax gate ------------------------------------------ + +@test "pre-commit(ts): a staged JS syntax error blocks (exit 1)" { + command -v node >/dev/null 2>&1 || skip "node not installed" + printf 'const x = ;\n' > bad.js + git add bad.js + run bash "$HOOK" + [ "$status" -eq 1 ] + [[ "$output" == *"syntax"* ]] +} + +@test "pre-commit(ts): a staged TS syntax error blocks (exit 1)" { + command -v tsc >/dev/null 2>&1 || skip "tsc not installed" + printf 'export function f( {\n return 1;\n}\n' > bad.ts + git add bad.ts + run bash "$HOOK" + [ "$status" -eq 1 ] +} + +@test "pre-commit(ts): valid TS-only syntax is NOT read as broken JS" { + command -v tsc >/dev/null 2>&1 || skip "tsc not installed" + # The regression guard for the node --check trap: `node --check` rejects + # valid TypeScript, so using it on .ts would block every real commit. + printf 'interface P { a: string }\nexport const p: P = { a: "x" };\n' > types.ts + git add types.ts + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +@test "pre-commit(ts): a TYPE error that parses does not block (out of scope)" { + command -v tsc >/dev/null 2>&1 || skip "tsc not installed" + printf 'const n: number = "nope";\nexport { n };\n' > typeerr.ts + git add typeerr.ts + run bash "$HOOK" + [ "$status" -eq 0 ] +} + +@test "pre-commit(ts): a broken NON-TS/JS file does not trip the syntax gate" { + printf 'this is (((not javascript\n' > notes.txt + git add notes.txt + run bash "$HOOK" + [ "$status" -eq 0 ] +} diff --git a/languages/typescript/tests/validate-typescript.bats b/languages/typescript/tests/validate-typescript.bats new file mode 100644 index 0000000..c5da5d4 --- /dev/null +++ b/languages/typescript/tests/validate-typescript.bats @@ -0,0 +1,125 @@ +#!/usr/bin/env bats +# +# Tests for languages/typescript/claude/hooks/validate-typescript.sh — the +# PostToolUse hook that syntax-checks edited TS/JS files and blocks on a +# violation. +# +# The hook reads tool-call JSON on stdin and extracts the file path, so each +# test pipes a JSON payload naming a real file it wrote into a temp dir. +# +# The syntax gate needs node, so those tests skip when node is absent. Full +# type checking is deliberately out of scope for the hook (it needs the whole +# project graph), so a type error that is syntactically valid must pass. + +HOOK="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)/claude/hooks/validate-typescript.sh" + +setup() { + TEST_DIR="$(mktemp -d -t validate-ts-bats.XXXXXX)" +} + +teardown() { + rm -rf "$TEST_DIR" +} + +payload() { + printf '{"tool_input": {"file_path": "%s"}}' "$1" +} + +# ---- Normal ---------------------------------------------------------- + +@test "validate-typescript: a clean .ts file passes silently (exit 0)" { + command -v node >/dev/null 2>&1 || skip "node not installed" + printf 'export function f(x: number): number {\n return x + 1;\n}\n' > "$TEST_DIR/clean.ts" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/clean.ts")" + [ "$status" -eq 0 ] + [ -z "$output" ] +} + +@test "validate-typescript: a clean .js file passes silently (exit 0)" { + command -v node >/dev/null 2>&1 || skip "node not installed" + printf 'export function f(x) {\n return x + 1;\n}\n' > "$TEST_DIR/clean.js" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/clean.js")" + [ "$status" -eq 0 ] +} + +@test "validate-typescript: a .tsx file is validated too" { + command -v node >/dev/null 2>&1 || skip "node not installed" + printf 'export const A = 1;\n' > "$TEST_DIR/clean.tsx" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/clean.tsx")" + [ "$status" -eq 0 ] +} + +# ---- Error ----------------------------------------------------------- + +@test "validate-typescript: a syntax error blocks (exit 2, names the failure)" { + command -v node >/dev/null 2>&1 || skip "node not installed" + printf 'export function f( {\n return 1;\n}\n' > "$TEST_DIR/bad.ts" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/bad.ts")" + [ "$status" -eq 2 ] + [[ "$output" == *"SYNTAX"* ]] +} + +@test "validate-typescript: the block payload is valid JSON carrying the context" { + command -v node >/dev/null 2>&1 || skip "node not installed" + printf 'const x = ;\n' > "$TEST_DIR/bad.js" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/bad.js")" + [ "$status" -eq 2 ] + echo "$output" | head -1 | jq -e '.hookSpecificOutput.hookEventName == "PostToolUse"' +} + +# ---- Boundary -------------------------------------------------------- + +@test "validate-typescript: a type error that parses is NOT blocked (out of scope)" { + command -v node >/dev/null 2>&1 || skip "node not installed" + # Assigning a string to a number is a type error, not a syntax error. The + # hook checks parseability only; tsc over the project graph owns this. + printf 'const n: number = "not a number";\nexport { n };\n' > "$TEST_DIR/typeerr.ts" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/typeerr.ts")" + [ "$status" -eq 0 ] +} + +@test "validate-typescript: TS-only syntax in a .ts file parses (not read as JS)" { + command -v node >/dev/null 2>&1 || skip "node not installed" + # Interfaces and type annotations are invalid JS. Stripping types must happen + # before the parse, or every real .ts file would be reported as broken. + printf 'interface P { a: string }\nexport const p: P = { a: "x" };\n' > "$TEST_DIR/types.ts" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/types.ts")" + [ "$status" -eq 0 ] +} + +@test "validate-typescript: a non-TS/JS file is ignored (exit 0)" { + printf 'not javascript at all (((\n' > "$TEST_DIR/notes.txt" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/notes.txt")" + [ "$status" -eq 0 ] +} + +@test "validate-typescript: a .json file is ignored (exit 0)" { + printf '{"a": 1}\n' > "$TEST_DIR/data.json" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/data.json")" + [ "$status" -eq 0 ] +} + +@test "validate-typescript: empty file_path is a no-op (exit 0)" { + run bash "$HOOK" <<< '{"tool_input": {}}' + [ "$status" -eq 0 ] +} + +@test "validate-typescript: a missing file is a no-op (exit 0)" { + run bash "$HOOK" <<< "$(payload "$TEST_DIR/does-not-exist.ts")" + [ "$status" -eq 0 ] +} + +@test "validate-typescript: an empty .ts file passes" { + command -v node >/dev/null 2>&1 || skip "node not installed" + : > "$TEST_DIR/empty.ts" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/empty.ts")" + [ "$status" -eq 0 ] +} + +@test "validate-typescript: a file in a dotted parent dir is still matched" { + command -v node >/dev/null 2>&1 || skip "node not installed" + mkdir -p "$TEST_DIR/my.project" + printf 'const x = ;\n' > "$TEST_DIR/my.project/bad.ts" + run bash "$HOOK" <<< "$(payload "$TEST_DIR/my.project/bad.ts")" + [ "$status" -eq 2 ] +} |
