A mistake caught an hour later on the build server, after someone has already spent time reviewing it. This catches it on your machine, before the commit.
Add "Pre-commit checks" from ntent to this repo.
Fetch https://ntent.app/r/f/pre-commit as plain text. Write it verbatim to scripts/git-hooks/pre-commit. Then make it executable.
Then check it: Stage a file that fails a check this tier installs and the commit is refused, naming the check and the fix. At tier 1 that is check-env: add a variable to the env schema and not to .env.example. The hardcoded-colour case needs the tier 2 lint rules. From tier 2, edit a test file a built journey cites in contract.json and stage only that file: the contract gate runs anyway and refuses the commit, naming the journey. Rename or delete it instead and the same happens. Accept the journey again in the same commit and it passes, with a notice under the passed line that the test and the record moved together. The notice can be avoided by spreading the change over several commits, and a merge or a rebase does not run this hook at all: CI is the check there.Reads https://ntent.app/r/f/pre-commit
Read the code
#!/bin/bash
#
# Pre-commit gate.
#
# Wired by: git config core.hooksPath scripts/git-hooks
# which package.json runs for you: "prepare": "git config core.hooksPath scripts/git-hooks"
#
# Bypass in a real emergency: git commit --no-verify
# That is documented on purpose. A bypass people have to discover in a panic is
# a bypass they will keep using afterwards.
#
# FOUR THINGS MAKE THIS DIFFERENT FROM THE USUAL PRE-COMMIT HOOK.
#
# 1. It checks THE STAGED SNAPSHOT, not the files on disk. With a partial stage
# those are different, and checking the wrong one is worse than checking
# nothing: an unstaged fix hides a broken line that is actually being
# committed, and the hook reports a pass on code nobody has run. See SNAPSHOT.
#
# 2. It dispatches on the staged file list, DELETIONS INCLUDED. A commit that
# only touches the README does not run the i18n checker. This is what keeps
# the median commit under a couple of seconds, and commit speed is the whole
# game: a hook that takes 40 seconds gets bypassed, and a bypassed hook
# enforces nothing. What it must not do is confuse "nothing left to read"
# with "nothing to check": see the two lists below.
#
# 3. It runs the checks this repo actually installed. The tiers are cumulative,
# so a tier 1 repo has this file and none of the tier 3 checkers. A gate that
# dies on a missing module makes every commit impossible, which is how a hook
# gets deleted in week one. Missing checkers are named and skipped, never
# silently ignored: a skip you cannot see is a gate that quietly stopped.
#
# 4. It stops at the first failure. One actionable message beats a wall of
# output, and the second failure is often caused by the first.
#
# WHICH GATES TAKE THE STAGED PATHS, AND WHICH READ THE WHOLE REPO.
#
# Handed the staged paths, so they block on this commit's files and count the
# rest as debt: typecheck (errors in touched files), lint (changed lines), env,
# components, tokens and clips. A repo with old problems must be able to make
# a one-line edit, and the field study's blocked commits were mostly that.
#
# Read the whole repo, whatever is staged: api, i18n, contrast, rules, backend,
# migrations, contract and fixtures. Their findings are facts about the set, not
# about a file: a key missing from another locale, a colour pair whose halves
# live in different rules, a rulebook row for a check that was deleted, a
# migration against the schema built from all the others. Narrowing them to the
# staged files would hide findings this commit causes. They are triggered by the
# paths they read, so a commit that touches none of those never pays for them.
# Their old debt can still block an unrelated edit under that trigger. That is
# a known cost, accepted for now; narrowing one is a change to that checker.
#
# Every gate here must be satisfiable offline by anyone with a clone. A check
# that needs credentials, network, or a tool a fresh clone lacks belongs in the
# session-start nag instead. See chapter 2.
set -u
repo_root="$(git rev-parse --show-toplevel)"
# Where this install lives: two folders above this hook, which is
# <install>/scripts/git-hooks/pre-commit. That is the repo root for most repos,
# and a package folder (backend/) when ntent was installed in a package of a
# larger repository. install_prefix is its path inside the repo, '' or
# 'backend/'. The migrations gate is the one that needs it: it compares the
# install's files with git history, and git paths start at the repo root.
# Worked out before the cd, because $0 may be relative to where git started us.
hook_dir="$(cd "$(dirname "$0")" 2>/dev/null && pwd -P)"
install_root="$(dirname "$(dirname "$hook_dir")")"
real_top="$(cd "$repo_root" && pwd -P)"
case "$install_root" in
"$real_top"/*) install_prefix="${install_root#"$real_top"/}/" ;;
*) install_root="$repo_root" ; install_prefix="" ;;
esac
cd "$repo_root" || exit 1
# For root-run command sources (a checker that has to reach git or the real
# tree rather than the snapshot). Set before the snapshot moves the cwd. It is
# the install's folder, which is where those sources run.
export NTENT_REPO_ROOT="$install_root"
# TWO LISTS, AND THE DIFFERENCE BETWEEN THEM IS A WHOLE CLASS OF BUG.
#
# `changed` is every path this commit touches, deletions included, and it is
# what decides which gates run. Deleting a module breaks the build exactly as
# surely as editing one does: delete an imported file and the compiler says
# TS2307, while a hook filtering deletions out sees an empty list and exits 0 on
# a commit that does not compile. What is being removed is part of the change.
#
# `present` is the subset that still exists in the snapshot, and it is the only
# list safe to hand to a command that opens the files it is given. A checker
# that rescans the repo gets neither: it just needs to be told to run.
#
# core.quotepath=off, because git otherwise prints a name with a non-ASCII
# character as a quoted octal escape ("src/caf\303\251.ts"), which no pattern
# below matches. Every path-triggered gate then skipped the commit, and the
# hook printed a pass. Every listing of names in this file carries it.
#
# --no-renames, because git otherwise folds a rename into its new name and the
# old path is in neither list. A file moved out of a watched folder then
# triggered nothing, and a test moved away from the path an acceptance record
# cites was committed with the record still pointing at a file that was gone.
# With the flag a rename is what it is on disk: one path removed, one added.
# `present` holds the same names as before, since a renamed file was always in
# it under its new name.
#
# One thing these lists still get wrong: a name holding a double quote or a
# backslash is printed C-quoted whatever quotepath says, so no pattern below
# matches it. The contract gate reads the names again NUL-separated, see
# staged_exactly, because there a miss lets an edited test through. The other
# gates do not, and for such a name they are skipped.
changed="$(git -c core.quotepath=off diff --cached --name-only --no-renames --diff-filter=ACMRD)"
present="$(git -c core.quotepath=off diff --cached --name-only --no-renames --diff-filter=ACMR)"
[ -z "$changed" ] && exit 0
status=0
ran=""
skipped=""
# Gates that ran and read nothing, as "name(reason)". Kept apart from `ran`
# because "gates passed: lint" after "no ESLint config" tells the committer a
# check vouched for code it never opened.
unchecked=""
# A HOOK OR CHECKER A FRESH CLONE WILL NOT GET.
#
# An install into a path .gitignore covers works on the machine that made it:
# the files are on disk, the hook runs, every gate passes. `git add -A` then
# skips them, and the next person to clone gets no hook and no checkers, with
# nothing anywhere saying so. A warning and not a refusal, because the commit
# in front of us is fine and the fix is in .gitignore. Asked of the real
# repository, before the snapshot, which only holds what is tracked.
warn_ignored_install () {
local hook_rel f ignored args=()
case "$hook_dir" in
"$real_top"/*) hook_rel="${hook_dir#"$real_top"/}/pre-commit" ;;
*) return 0 ;;
esac
for f in "$hook_rel" "${install_prefix}"scripts/check-*.mjs "${install_prefix}"scripts/verify-*.mjs ; do
[ -e "$f" ] && args+=("$f")
done
[ "${#args[@]}" -gt 0 ] || return 0
ignored="$(git -c core.quotepath=off check-ignore "${args[@]}" 2>/dev/null)" || return 0
[ -n "$ignored" ] || return 0
if git check-ignore -q "${install_prefix}scripts/" 2>/dev/null ; then
echo " warning: ${install_prefix}scripts/ is gitignored, so a fresh clone gets no hook and no checkers."
echo " Take it out of .gitignore, or this repo is only protected on this machine."
return 0
fi
while IFS= read -r f ; do
[ -n "$f" ] || continue
if [ "$f" = "$hook_rel" ] ; then
echo " warning: $f is gitignored, so a fresh clone gets no hook."
else
echo " warning: $f is gitignored, so a fresh clone does not get it."
fi
done <<EOF
$ignored
EOF
}
warn_ignored_install
# ------------------------------------------------------------- SNAPSHOT ----
#
# Check what is being committed, not what is lying around.
#
# The bug this fixes, which every hook that lints the staged paths in place has: stage
# a file containing `debugger;`, then fix it in the editor without staging. The
# hook reads the fixed file from disk, passes, and commits the broken one. The
# reverse costs you too: an unstaged experiment blocks a commit that is fine.
#
# git checkout-index writes the index out as it stands, so the snapshot IS the
# commit. Dependencies are symlinked in rather than reinstalled, which is what
# keeps this at a second or two. Nothing here touches your worktree, so unlike
# the `git stash --keep-index` version of this trick, an interrupted hook cannot
# lose uncommitted work.
#
# If any of it fails we fall back to the worktree and SAY SO, because a hook
# that silently downgrades what it checks is the thing this file is about.
snapshot=""
work=""
# Under $TMPDIR, named for the hook. A bare `mktemp -d` ignores $TMPDIR on macOS,
# so a leftover could not be told from another program's, or tested for. If
# $TMPDIR names a folder that is not there, fall back to the system default
# rather than lose the snapshot.
make_temp () { mktemp -d "${TMPDIR:-/tmp}/ntent-hook.XXXXXX" 2>/dev/null || mktemp -d 2>/dev/null ; }
cleanup () {
[ -n "$snapshot" ] && rm -rf "$snapshot"
[ -n "$work" ] && rm -rf "$work"
return 0
}
trap cleanup EXIT
build_snapshot () {
local dir nm
dir="$(make_temp)" || return 1
git checkout-index --all --force --prefix="$dir/" 2>/dev/null || { rm -rf "$dir" ; return 1 ; }
# Link the installed dependencies in. Absolute targets, so the symlinks
# resolve from inside the snapshot. Depth 4 covers a workspace's packages
# without descending into node_modules itself.
while IFS= read -r nm ; do
[ -n "$nm" ] || continue
mkdir -p "$dir/$(dirname "$nm")" 2>/dev/null
[ -e "$dir/$nm" ] || ln -s "$repo_root/$nm" "$dir/$nm" 2>/dev/null
done <<EOF
$(find . -maxdepth 4 -type d -name node_modules -not -path '*/node_modules/*' 2>/dev/null | sed 's|^\./||')
EOF
snapshot="$dir"
return 0
}
# GITIGNORED FILES THE TYPECHECK NEEDS.
#
# The snapshot is the index, and the index holds tracked files only. A project's
# generated types are almost always gitignored: next-env.d.ts, .svelte-kit/, a
# generated Prisma or API client, .next/types. Without them tsc reports an error
# in every file that imports one, on a commit that did nothing to cause it, and
# a hook that fails every commit gets bypassed.
#
# Typechecking the worktree in place would have them, but then a partial stage
# is checked as it sits on disk, which is the bug the snapshot exists to fix.
# So the ignored top-level entries (a directory is one entry) are symlinked in,
# the way node_modules already is. Only for the typecheck, and only then: the
# other gates read tracked files, and a commit that touches no TypeScript does
# not pay for the listing. The install's own scripts/ is left out on purpose.
# If it is gitignored the checkers must stay invisible here, or the commit
# would pass on files a fresh clone does not have. See warn_ignored_install.
ignored_linked=0
link_ignored () {
local p
[ -n "$snapshot" ] || return 0
[ "$ignored_linked" -eq 0 ] || return 0
ignored_linked=1
while IFS= read -r p ; do
p="${p%/}"
[ -n "$p" ] || continue
case "$p" in
.git|.git/*|"${install_prefix}scripts"|"${install_prefix}scripts"/*) continue ;;
esac
if [ -e "$snapshot/$p" ] || [ -L "$snapshot/$p" ] ; then continue ; fi
mkdir -p "$snapshot/$(dirname "$p")" 2>/dev/null
ln -s "$repo_root/$p" "$snapshot/$p" 2>/dev/null
done <<EOF
$(git -C "$repo_root" -c core.quotepath=off ls-files --others --ignored --exclude-standard --directory 2>/dev/null)
EOF
}
if [ "${SKIP_SNAPSHOT:-}" = "1" ] ; then
echo " note: SKIP_SNAPSHOT=1. Checking the worktree, so a partial stage is not"
echo " what gets checked. Unset it before you trust a pass."
elif build_snapshot ; then
cd "$snapshot" || exit 1
else
echo " note: could not snapshot the index, so the checks below read the files"
echo " on disk. With a partial stage that is not what you are committing."
fi
# ---------------------------------------------------------------- HELPERS ---
# run_gate <name> <path-regex> <command> <fix-hint> [required-file ...]
#
# The fix hint is not decoration. "Validation failed" is a gate people route
# around; "add the key to messages/en.json and re-stage" is a gate people thank
# you for. Making the hint a required argument is how you guarantee one exists.
#
# Anything after the hint is a file the command needs. Absent means this repo has
# not installed that check yet, which is a skip with a printed reason, not a
# failure: at tier 1 the i18n and component checkers genuinely are not here.
# The files are looked up under $gate_prefix, which is empty except around a
# gate whose checker is installed in a package folder.
run_gate () {
local name="$1" pattern="$2" cmd="$3" hint="$4" ; shift 4
local need
[ "$status" -eq 0 ] || return 0
printf '%s\n' "$changed" | grep -qE "$pattern" || return 0
for need in "$@" ; do
if [ ! -e "${gate_prefix:-}$need" ] ; then
skipped="${skipped:+$skipped }${name}(no ${need})"
return 0
fi
done
ran="${ran:+$ran }$name"
if ! eval "$cmd" ; then
echo "" >&2
echo " x ${name} failed." >&2
echo " ${hint}" >&2
echo "" >&2
status=1
fi
}
# The nearest ancestor directory holding one of these files. Falls back to the
# repo root, so a file under no config is still handled rather than skipped.
nearest () {
local dir="$(dirname "$1")" name
shift
while [ "$dir" != "." ] && [ "$dir" != "/" ] ; do
for name in "$@" ; do
[ -f "$dir/$name" ] && { printf '%s\n' "$dir" ; return 0 ; }
done
dir="$(dirname "$dir")"
done
printf '.\n'
}
# Files from one of the two lists matching a pattern, grouped by the directory
# that owns their config, as "<dir>\t<file>" pairs. The caller picks the list,
# because a project-wide command wants the deletions and a per-file one cannot
# have them.
owners_for () {
local list="$1" pattern="$2" ; shift 2
printf '%s\n' "$list" | grep -E "$pattern" | while IFS= read -r f ; do
[ -n "$f" ] || continue
printf '%s\t%s\n' "$(nearest "$f" "$@")" "$f"
done
}
# A gate that ran but read nothing: take it out of the passed list and say so
# on its own line. Called from inside a gate function, which runs in this shell,
# so it can reach `ran` after run_gate has added the gate to it.
mark_unchecked () {
local r=" $ran "
r="${r/ $1 / }"
r="${r# }"
ran="${r% }"
unchecked="${unchecked:+$unchecked }$1($2)"
}
# A list of names, one per line, into the global array ARR, one element per
# line, so a name with a space in it stays one argument. Word-splitting the list
# (`for f in $files`, `cmd $files`) dropped such a path and handed the checker
# two bogus ones, and the commit passed having read none of it. Bash 3.2 has no
# mapfile. An empty list is an empty array, and the empty-array expansion that
# `set -u` accepts on 3.2 is ${ARR[@]+"${ARR[@]}"}, which is what callers use.
ARR=()
lines_to_array () {
local line
ARR=()
while IFS= read -r line ; do
[ -n "$line" ] && ARR+=("$line")
done <<EOF
$1
EOF
return 0
}
# Was this path in the commit only as a deletion?
was_deleted () {
printf '%s\n' "$changed" | grep -qxF -- "$1" || return 1
printf '%s\n' "$present" | grep -qxF -- "$1" && return 1
return 0
}
# HOW A CHECKER SAYS "I READ NOTHING" WHILE STILL EXITING 0.
#
# Some checkers must exit 0 when they read nothing: a fresh clone has no
# gitleaks and has to be able to commit. The hook still must not list them
# under "gates passed". The checker names one line of reason in the file that
# NTENT_UNCHECKED_FILE points at, and the hook reads it. One source of truth:
# the checker knows what it read, and the hook does not re-derive it by
# looking for the binary or guessing at extensions. A checker that does not
# know the variable, or an older one, writes nothing and is treated as before.
unchecked_file=""
fresh_unchecked_file () {
[ -n "$work" ] || work="$(make_temp)"
unchecked_file="$work/unchecked"
: > "$unchecked_file"
}
unchecked_reason () { head -1 "$unchecked_file" 2>/dev/null || true ; }
# A regex-literal path: only the metacharacters a filename can hold.
env_escape () { printf '%s\n' "$1" | sed 's/[.[\*^$()+?{}|]/\\&/g' ; }
# ASK A CHECKER WHERE ITS FILES ARE.
#
# The checkers print what they scan with --print-config, as `<key><TAB><value>`
# lines, and the gates below build their triggers from it. A checker written
# before the flag existed is not asked: it would ignore the flag and run its
# whole scan to print nothing we can use, on every commit. The caller falls back
# to the old src/ patterns when it gets no watchDir line.
checker_config () {
[ -f "$1" ] || return 0
grep -q -- '--print-config' "$1" 2>/dev/null || return 0
node "$1" --print-config 2>/dev/null || true
}
cfg_values () { printf '%s\n' "$1" | awk -F'\t' -v k="$2" '$1 == k { print $2 }' ; }
# A regex matching paths under any of the dirs ($1, one per line), each followed
# by $2. '.' is the repo root, so everything matches. Empty when there are no dirs.
dirs_pattern () {
local d out=""
while IFS= read -r d ; do
d="${d%/}"
d="${d#./}"
[ -n "$d" ] || continue
if [ "$d" = "." ] ; then
out="${out:+$out|}^$2"
else
out="${out:+$out|}^$(env_escape "$d")/$2"
fi
done <<EOF
$1
EOF
printf '%s' "$out"
}
# WHICH COMMAND RUNS A TOOL.
#
# This file used to say `pnpm exec`, which in an npm or yarn repo is a refusal:
# pnpm reads packageManager, sees npm, and exits before running anything. The
# hook then printed "Fix the type errors above" with no type error in sight.
#
# So the project's own binary comes first, from the package up to the root:
# whatever installed it, running it directly is the same everywhere and costs no
# package-manager start-up. Only without one is the manager asked, which is the
# packageManager field, then the lockfile, nearest first. With neither there is
# no way to know, and TOOL_CMD is left empty for the caller to say so.
TOOL_CMD=()
package_manager_in () {
local d="$1" pm=""
if [ -f "$d/package.json" ] ; then
pm="$(sed -n 's/.*"packageManager"[[:space:]]*:[[:space:]]*"\([a-z]*\)@.*/\1/p' "$d/package.json" | head -1)"
fi
if [ -z "$pm" ] ; then
if [ -f "$d/pnpm-lock.yaml" ] ; then pm=pnpm
elif [ -f "$d/yarn.lock" ] ; then pm=yarn
elif [ -f "$d/bun.lockb" ] || [ -f "$d/bun.lock" ] ; then pm=bun
elif [ -f "$d/package-lock.json" ] ; then pm=npm
fi
fi
printf '%s' "$pm"
}
tool_cmd_for () {
local dir="$1" tool="$2" d pm=""
TOOL_CMD=()
d="$dir"
while : ; do
if [ -x "$d/node_modules/.bin/$tool" ] ; then
TOOL_CMD=("$PWD/$d/node_modules/.bin/$tool")
return 0
fi
[ "$d" = "." ] && break
d="$(dirname "$d")"
done
d="$dir"
while : ; do
pm="$(package_manager_in "$d")"
[ -n "$pm" ] && break
[ "$d" = "." ] && break
d="$(dirname "$d")"
done
case "$pm" in
pnpm) TOOL_CMD=(pnpm exec "$tool") ;;
yarn) TOOL_CMD=(yarn run "$tool") ;;
npm) TOOL_CMD=(npx --no-install "$tool") ;;
bun) TOOL_CMD=(bun x "$tool") ;;
*) return 1 ;;
esac
}
# "1 type error" or "3 type errors".
count_of () { [ "$1" -eq 1 ] && printf '1 %s' "$2" || printf '%s %ss' "$1" "$2" ; }
# ---------------------------------------------------------------- GATES ----
# Order matters only in that cheap checks go first, so a broken commit fails
# fast rather than after the slow one.
# TYPECHECK, EACH FILE AGAINST THE PROJECT THAT OWNS IT.
#
# `tsc --noEmit` from the root typechecks the ROOT project, which in a monorepo
# is not the project the staged file belongs to: it either checks nothing or
# checks it under the wrong settings, and both read as a pass. Resolving the
# nearest tsconfig.json and running `-p` against it is the same behaviour in a
# single-package repo and the correct one everywhere else.
#
# A repo with no tsconfig anywhere is not a TypeScript repo. Skip, and say so.
#
# The owners come from `changed`, deletions included: tsc checks the project,
# not a file list, and the project is exactly what a deleted module breaks.
# `nearest` walks up from the path, so it resolves for a file that is gone.
#
# WHAT BLOCKS. tsc still checks the whole project, because a type error is a
# fact about how files fit together. But only errors in the files this commit
# touches stop it. In the field study 42 of 74 blocked one-line edits were
# typecheck failing on errors that were in the repo before the edit, and a hook
# that blocks on someone else's old mistake gets bypassed. Errors elsewhere are
# counted and printed as a note.
#
# The limit, accepted: an edit can break a file it does not touch, by changing
# what that file imports. Two cases are still caught. A deleted or renamed
# module leaves its importers failing with a message that quotes the module's
# name, so an error whose message quotes the name of a path this commit changes
# blocks too: a module specifier that resolves to a changed path, from the file
# that has the error (or, for an alias, ends in that path), see mentions().
# Anything subtler, such as a changed signature breaking a caller two files
# away, is left to CI. Catching it here would mean typechecking HEAD as well and
# diffing the two, which doubles the slowest step of every commit.
#
# The shipped probe is never counted: it holds deliberate violations.
#
# The awk reads tsc's plain format (--pretty false): `path(line,col): error TSn:`
# with indented continuation lines. A line without a path is a project-level
# error, such as a tsconfig that matches nothing, and always blocks.
tsc_classify='
function stripext(p) { sub(/\.(d\.ts|tsx|ts|mts|cts|jsx|js|mjs|cjs|json)$/, "", p); return p }
function norm(p, n, parts, i, k, out, stack) {
n = split(p, parts, "/")
k = 0
for (i = 1; i <= n; i++) {
if (parts[i] == "" || parts[i] == ".") continue
if (parts[i] == "..") { if (k > 0) k--; continue }
stack[++k] = parts[i]
}
out = ""
for (i = 1; i <= k; i++) out = out (i > 1 ? "/" : "") stack[i]
return out
}
function quotes(c) { return c == "\047" || c == "\"" || c == "`" }
# Does a quoted module specifier in the message name a path this commit changes?
# A relative one is resolved from the file that has the error, and has to land on
# the changed path exactly. Matching the bare name instead made `utils` or
# `page` convict any old error that quoted some other ../utils. An alias
# (@/lib/utils) cannot be resolved without the tsconfig, so its whole path has
# to be a tail of the changed one, segment for segment. A package name with no
# slash is never a changed path.
function mentions(msg, file, rest, k, q, after, e, spec, alias, dir, r, m, s2) {
dir = file
if (!sub(/\/[^\/]*$/, "", dir)) dir = ""
rest = msg
while ((k = match(rest, "[\047\"`]")) > 0) {
q = substr(rest, RSTART, 1)
after = substr(rest, RSTART + 1)
e = index(after, q)
if (e == 0) break
spec = substr(after, 1, e - 1)
rest = substr(after, e + 1)
gsub(/^["`]+|["`]+$/, "", spec)
if (spec == "" || spec ~ /[ \t]/) continue
if (spec ~ /^\./) {
r = stripext(norm(dir "/" spec))
if (r in mod) return 1
} else {
alias = (spec ~ /^[@~#]\//)
s2 = spec
sub(/^[@~#]\//, "", s2)
s2 = stripext(s2)
if (s2 == "" || !(alias || s2 ~ /\//)) continue
for (m in mod) {
if (m == s2) return 1
if (length(m) > length(s2) && substr(m, length(m) - length(s2)) == "/" s2) return 1
}
}
}
return 0
}
BEGIN {
n = split(ENVIRON["NTENT_CHANGED"], list, "\n")
for (i = 1; i <= n; i++) {
p = list[i]
if (p == "") continue
own[p] = 1
b = stripext(p)
mod[b] = 1
if (b ~ /\/index$/) { d = b; sub(/\/index$/, "", d); mod[d] = 1 }
}
}
/^[^ \t].*: error TS[0-9]+:/ || /^error TS[0-9]+:/ {
cur = 0
if (match($0, /\([0-9]+,[0-9]+\): error TS/)) {
path = prefix substr($0, 1, RSTART - 1)
if (path ~ /(^|\/)scripts\/probes\//) { other++; next }
if (path in own) cur = 1
else {
msg = substr($0, RSTART)
if (mentions(msg, path)) cur = 1
}
} else cur = 1
if (cur) print
else other++
next
}
/^[ \t]/ { if (cur) print; next }
END { print "@@others " other + 0 }
'
typecheck_staged () {
local pairs dir out trc res nrc blocking others prefix first why="" checked=0 rc=0
pairs="$(owners_for "$changed" '\.(ts|tsx)$' tsconfig.json)"
[ -n "$pairs" ] || return 0
link_ignored
lines_to_array "$(printf '%s\n' "$pairs" | cut -f1 | sort -u)"
for dir in ${ARR[@]+"${ARR[@]}"} ; do
if [ ! -f "$dir/tsconfig.json" ] ; then
echo " note: no tsconfig.json above $dir, so those files are not typechecked."
why="${why:+$why; }no tsconfig.json"
continue
fi
if ! tool_cmd_for "$dir" tsc ; then
echo " note: could not start tsc: no node_modules/.bin/tsc here, and no packageManager or lockfile to say how to run it."
why="${why:+$why; }could not start tsc: no node_modules/.bin/tsc"
continue
fi
# Captured, because what blocks depends on which file each error is in.
out="$(cd "$dir" && "${TOOL_CMD[@]}" --noEmit -p tsconfig.json --pretty false 2>&1)"
trc=$?
if [ "$trc" -eq 0 ] ; then
checked=1
continue
fi
# Not one `error TS` line: tsc never got as far as reading the project. That
# is the tool failing to start, not a type error, and it must not be reported
# as one.
if ! printf '%s\n' "$out" | grep -qE 'error TS[0-9]+:' ; then
first="$(printf '%s\n' "$out" | grep -v '^[[:space:]]*$' | head -1 | cut -c1-200)"
echo " note: could not start tsc: ${first:-it exited $trc with no output}"
why="${why:+$why; }could not start tsc: ${first:-exit $trc}"
continue
fi
checked=1
prefix=""
[ "$dir" = "." ] || prefix="$dir/"
res="$(printf '%s\n' "$out" | NTENT_CHANGED="$changed" awk -v prefix="$prefix" "$tsc_classify")"
others="$(printf '%s\n' "$res" | sed -n 's/^@@others //p')"
blocking="$(printf '%s\n' "$res" | grep -v '^@@others ')"
if [ -n "$others" ] && [ "$others" -gt 0 ] ; then
echo " note: $(count_of "$others" 'type error') already in files this commit does not touch, not blocking."
fi
if [ -n "$blocking" ] ; then
printf '%s\n' "$blocking" >&2
rc=1
break
fi
done
[ "$checked" -eq 1 ] || [ "$rc" -ne 0 ] || mark_unchecked typecheck "$why"
return "$rc"
}
run_gate "typecheck" \
'\.(ts|tsx)$' \
'typecheck_staged' \
'Fix the type errors above. Errors in files this commit does not touch are not counted.'
# ESLint, EACH FILE AGAINST THE CONFIG THAT OWNS IT.
#
# In a single-package repo this is one run and behaves exactly as the obvious
# one-liner did. In a monorepo it is the difference between the hook agreeing
# with `pnpm lint` and the hook being quietly stricter than it.
#
# The failure, found on a real repo: `pnpm lint` runs ESLint once per package,
# from that package's directory. A single run from the root does not, and a
# root config that deliberately registers no framework plugins — which is what
# you write when two apps sit on different framework majors and each registers
# its own, since a flat config may claim a plugin name only once — then fails
# every staged file carrying an `eslint-disable-next-line` for a rule only the
# package config knows. "Definition for rule ... was not found", on a file
# `pnpm lint` calls clean.
#
# That is the shape this whole file exists to avoid. A gate stricter than the
# documented command does not get fixed, it gets bypassed.
#
# WHAT BLOCKS. An error on a line this commit adds or changes. The same file
# usually carries old problems, and in the field study 13 blocked one-line edits
# were lint errors on lines the edit never touched. Those are counted and
# printed as a note. The changed lines come from `git diff --cached -U0` and the
# problem lines from ESLint's JSON report; a file with no hunks (a pure rename)
# has no changed lines. A fatal parse error blocks wherever it is, since nothing
# else in that file was checked. Warnings never block, as before.
#
# The shipped probe is left out of the list. It is deliberately full of
# violations, and check-probes is what reads it.
# Reads ESLint's JSON report ($1) and the staged diff ($2) and prints the
# problems that block, then a `@@others <n>` line counting the ones that do not.
# Exit 0 nothing blocks, 1 something does, 3 the report was not JSON.
eslint_classify='
const fs = require("node:fs")
const path = require("node:path")
const [reportFile, diffFile] = process.argv.slice(1)
let report
try { report = JSON.parse(fs.readFileSync(reportFile, "utf8")) } catch { process.exit(3) }
if (!Array.isArray(report)) process.exit(3)
const touched = new Map()
let current = null
for (const line of fs.readFileSync(diffFile, "utf8").split("\n")) {
let m
// git ends the name with a tab when it holds a space, so the header does not run into a date.
if ((m = /^\+\+\+ b\/(.*)$/.exec(line))) { current = []; touched.set(m[1].replace(/\t$/, ""), current) }
else if (line.startsWith("+++ ")) current = null
else if (current && (m = /^@@ -\S+ \+(\d+)(?:,(\d+))? @@/.exec(line))) {
const start = Number(m[1])
const count = m[2] === undefined ? 1 : Number(m[2])
if (count > 0) current.push([start, start + count - 1])
}
}
let others = 0
const out = []
for (const file of report) {
const rel = path.relative(process.cwd(), file.filePath).split(path.sep).join("/")
const ranges = touched.get(rel) ?? []
const mine = []
for (const msg of file.messages ?? []) {
if (msg.severity !== 2) continue
const from = msg.line ?? 0
const to = msg.endLine ?? from
if (msg.fatal || ranges.some(([a, b]) => from <= b && to >= a)) mine.push(msg)
else others++
}
if (!mine.length) continue
out.push(rel)
for (const m of mine) out.push((" " + (m.line ?? 0) + ":" + (m.column ?? 0) + " error " + m.message + " " + (m.ruleId ?? "")).trimEnd())
out.push("")
}
process.stdout.write(out.join("\n") + "\n@@others " + others + "\n")
process.exit(out.length ? 1 : 0)
'
# Group the staged files by owner, then one run per owner, from inside it.
# Stops at the first failing group, for the reason the gates stop at the first
# failing gate: one actionable message beats a wall of output.
eslint_staged () {
local pairs dir f rc=0 linted=0 why="" lintable out errf trc res nrc blocking others first
local lint_files=()
lintable="$(printf '%s\n' "$present" | grep -vE '(^|/)scripts/probes/')"
# `present`, because ESLint is handed paths and has to be able to open them.
pairs="$(owners_for "$lintable" '\.(ts|tsx|js|jsx)$' \
eslint.config.mjs eslint.config.js eslint.config.cjs eslint.config.ts)"
if [ -z "$pairs" ] ; then
if printf '%s\n' "$present" | grep -qE '(^|/)scripts/probes/.*\.(ts|tsx|js|jsx)$' ; then
echo " note: the only lintable files in this commit are the shipped probes, which"
echo " are wrong on purpose, so ESLint is not asked about them."
mark_unchecked lint "only the shipped probes"
else
echo " note: the lintable paths in this commit are deletions, so there is"
echo " nothing for ESLint to read."
mark_unchecked lint "only deletions"
fi
return 0
fi
lines_to_array "$(printf '%s\n' "$pairs" | cut -f1 | sort -u)"
for dir in ${ARR[@]+"${ARR[@]}"} ; do
# `nearest` falls back to the repo root, which may hold no config either.
# A repo that does not lint is not a failing repo; it is a repo without
# that check, and it gets told so once rather than a resolver error.
if ! ls "$dir"/eslint.config.* >/dev/null 2>&1 ; then
echo " note: no ESLint config at or above $dir, so those files are not linted."
why="${why:+$why; }no ESLint config"
continue
fi
if ! tool_cmd_for "$dir" eslint ; then
echo " note: could not start eslint: no node_modules/.bin/eslint here, and no packageManager or lockfile to say how to run it."
why="${why:+$why; }could not start eslint: no node_modules/.bin/eslint"
continue
fi
# Paths relative to the owner, because that is where ESLint is about to run.
# An array, so a path with a space in it, or a [id] folder, is one argument.
lines_to_array "$(printf '%s\n' "$pairs" | awk -F'\t' -v d="$dir" '$1 == d { print $2 }')"
lint_files=()
for f in ${ARR[@]+"${ARR[@]}"} ; do
[ "$dir" = "." ] || f="${f#"$dir"/}"
lint_files+=("$f")
done
[ -n "$work" ] || work="$(make_temp)"
out="$(cd "$dir" && "${TOOL_CMD[@]}" --format json ${lint_files[@]+"${lint_files[@]}"} 2>"$work/eslint.err")"
trc=$?
if [ "$trc" -eq 0 ] ; then
linted=1
continue
fi
printf '%s' "$out" > "$work/eslint.json"
[ -s "$work/diff" ] || git -C "$repo_root" -c core.quotepath=off diff --cached -U0 --no-color --diff-filter=ACMR > "$work/diff" 2>/dev/null
res="$(node -e "$eslint_classify" "$work/eslint.json" "$work/diff")"
nrc=$?
if [ "$nrc" -eq 3 ] ; then
first="$(cat "$work/eslint.err" "$work/eslint.json" | grep -v '^[[:space:]]*$' | head -1 | cut -c1-200)"
echo " note: could not run eslint: ${first:-it exited $trc with no output}"
why="${why:+$why; }could not run eslint: ${first:-exit $trc}"
continue
fi
linted=1
others="$(printf '%s\n' "$res" | sed -n 's/^@@others //p')"
blocking="$(printf '%s\n' "$res" | grep -v '^@@others ')"
if [ -n "$others" ] && [ "$others" -gt 0 ] ; then
echo " note: $(count_of "$others" 'lint problem') already on lines this commit does not touch, not blocking."
fi
if [ "$nrc" -ne 0 ] ; then
printf '%s\n' "$blocking" >&2
rc=1
break
fi
done
[ "$linted" -eq 1 ] || [ "$rc" -ne 0 ] || mark_unchecked lint "$why"
return "$rc"
}
run_gate "lint" \
'\.(ts|tsx|js|jsx)$' \
'eslint_staged' \
'Fix the lint errors above. Each message says which rule and why it exists. Problems on lines this commit does not touch are not counted.'
# Exit 2 is the checker saying it read no locale file. The reasons are several
# (no locale directory yet, or a directory of .po, YAML or TS locales it does
# not read), so this does not guess: the checker prints one line saying which,
# and this adds only the entry on the checked-nothing line. A repo that chose
# the locales capability on day one has the checker before it has a second
# language, and a gate that refuses every commit until messages/en.json exists
# is a gate that gets deleted. A note, not a refusal. Exit 1 is a missing key,
# and a missing key blocks.
i18n_staged () {
local rc=0
node scripts/check-locale-keys.mjs --check || rc=$?
if [ "$rc" -eq 2 ] ; then
mark_unchecked i18n "read no locale file"
return 0
fi
return "$rc"
}
# The trigger is the checker's own: the locale directory and the source dirs it
# reads for t() calls. The old pattern is the fallback for an older checker.
i18n_pattern='^(messages/|src/)'
i18n_dirs="$(cfg_values "$(checker_config scripts/check-locale-keys.mjs)" watchDir)"
[ -z "$i18n_dirs" ] || i18n_pattern="$(dirs_pattern "$i18n_dirs" '')"
run_gate "i18n" \
"$i18n_pattern" \
'i18n_staged' \
'Add the key to every locale file, then re-stage.' \
scripts/check-locale-keys.mjs
# ASK THE CHECKER WHERE ITS FILES ARE.
#
# Every source file, not just the schema, because the checker scans all of them
# for process.env reads: scoping the trigger to the schema meant a new direct
# read in a component was found by nothing until someone next edited env.ts.
#
# And the paths come from `--print-config` rather than from this file. Moving
# CONFIG.schemaFile is documented and supported, and a hook that hardcoded
# src/env.ts answered that by treating the check as not installed. Silently:
# the commit passed, the checker was right there, and running it by hand failed.
# A prerequisite worth having is one resolved from the same place the check
# reads it from. The defaults below are the fallback for an older check-env.mjs
# that does not understand the flag.
env_schema='src/env.ts'
env_example='.env.example'
env_pattern='^(src/|\.env\.example$)'
if [ -f scripts/check-env.mjs ] ; then
env_cfg="$(node scripts/check-env.mjs --print-config 2>/dev/null)"
env_from_cfg () { printf '%s\n' "$env_cfg" | awk -F'\t' -v k="$1" '$1 == k { print $2 }' ; }
cfg_schema="$(env_from_cfg schemaFile)"
if [ -n "$cfg_schema" ] ; then
env_schema="$cfg_schema"
env_pattern=""
for d in $(env_from_cfg sourceDir) ; do
env_pattern="${env_pattern:+$env_pattern|}^$(env_escape "$d")/"
done
env_example="$(env_from_cfg exampleFile)"
for f in "$env_example" "$env_schema" ; do
[ -n "$f" ] || continue
env_pattern="${env_pattern:+$env_pattern|}^$(env_escape "$f")\$"
done
# What the client-secret check reads beyond the schema: the bundler configs
# that exist, and the directories whose every file ships to the browser.
for f in $(env_from_cfg watchFile) ; do
env_pattern="${env_pattern:+$env_pattern|}^$(env_escape "$f")\$"
done
for d in $(env_from_cfg clientDir) ; do
env_pattern="${env_pattern:+$env_pattern|}^$(env_escape "${d%/}")/"
done
fi
fi
# The staged files under the trigger are handed over, so the schema half
# blocks only on reads this commit adds or keeps. The rest of the repo's
# findings come back as a count. The client-secret half reads the bundle
# config and client dirs whole either way.
#
# A commit that only deletes files under the trigger has no staged path to hand
# over, and the checker then reads the whole repo and blocks on every old
# unvalidated read in it: a deletion refused over code the commit never touched.
# The one deletion that does change the answer is the schema or the example
# file, since the two are compared with each other and with every read, so that
# case runs whole. Any other deletion cannot add a read, so the gate says it
# read nothing.
env_staged () {
local files
files="$(printf '%s\n' "$present" | grep -E "$env_pattern")"
if [ -z "$files" ] ; then
if was_deleted "$env_schema" || { [ -n "$env_example" ] && was_deleted "$env_example" ; } ; then
node scripts/check-env.mjs --check
return $?
fi
mark_unchecked env "only deletions"
return 0
fi
lines_to_array "$files"
node scripts/check-env.mjs --check ${ARR[@]+"${ARR[@]}"}
}
run_gate "env" \
"$env_pattern" \
'env_staged' \
"Add the variable to $env_schema AND the example file, with a comment saying where to get it." \
scripts/check-env.mjs
# API. Triggered by the route files under CONFIG.routeDirs, which is all the
# checker reads. The old src/app/api/ is the fallback for an older checker.
api_pattern='^src/app/api/'
api_cfg="$(checker_config scripts/check-api-routes.mjs)"
api_dirs="$(cfg_values "$api_cfg" watchDir)"
if [ -n "$api_dirs" ] ; then
api_names=""
for n in $(cfg_values "$api_cfg" watchName) ; do
api_names="${api_names:+$api_names|}$(env_escape "$n")"
done
api_tail=""
[ -z "$api_names" ] || api_tail="(.*/)?($api_names)\$"
api_pattern="$(dirs_pattern "$api_dirs" "$api_tail")"
fi
# Exit 2 is a checker that read no route file at all: it reads Next route
# handlers only, and says so. A note, so a repo whose API lives elsewhere can
# commit, and it stays off the passed line.
api_staged () {
local rc=0
node scripts/check-api-routes.mjs --check || rc=$?
if [ "$rc" -eq 2 ] ; then
echo " note: the API check read no route file. The line above says why."
mark_unchecked api "no route file it reads"
return 0
fi
return "$rc"
}
run_gate "api" \
"$api_pattern" \
'api_staged' \
'Add the schema, the auth check, or a marker comment giving the reason it is exempt.' \
scripts/check-api-routes.mjs
# SECRETS. No credential in the commit. It is not path-triggered, because a
# credential can land in any file, a doc and a fixture as readily as a script.
#
# It runs from the REAL repository, not the snapshot: gitleaks reads the staged
# diff out of git, and the snapshot is a bare copy of the tree with no .git in
# it. The script itself is the snapshot's, so a staged edit to the checker is
# the version that runs.
#
# Where gitleaks is not installed the checker warns and exits 0, and says so.
# A fresh clone must be able to commit, and the CI leg (`--all`, which fails
# without the binary) covers the push. But nothing was scanned, so the gate
# goes on the checked-nothing line, not the passed one: the checker says so in
# the file named by NTENT_UNCHECKED_FILE, see fresh_unchecked_file. Exit 1 is a
# finding, and a finding blocks. Do not `--no-verify` past a real credential:
# rotate it.
secrets_staged () {
local here="$PWD" rc=0 why
fresh_unchecked_file
( cd "$repo_root" && NTENT_UNCHECKED_FILE="$unchecked_file" node "$here/scripts/check-secrets.mjs" --check ) || rc=$?
why="$(unchecked_reason)"
[ "$rc" -ne 0 ] || [ -z "$why" ] || mark_unchecked secrets "$why"
return "$rc"
}
run_gate "secrets" \
'.' \
'secrets_staged' \
'A credential is in the staged diff (redacted above). Take it out AND rotate it: it may already be in a model context or a log.' \
scripts/check-secrets.mjs
# TOKENS. The registry calls this a gate, and until this line existed it was
# wired to nothing: a raw hex in a stylesheet passed every commit while the
# setup page said "blocks the commit". CSS as well as components, because a raw
# colour goes in either.
#
# The staged paths are passed in rather than letting it rescan the repo. Faster,
# and it means the gate is about the commit rather than about everything that
# was already there.
#
# Exit 2 is check-tokens saying it could not check anything: no stylesheet, a
# stylesheet that is not a token build, or nothing it scans in what was staged.
# It says which, in the file named by NTENT_UNCHECKED_FILE, and that is what the
# note repeats: the note used to claim "nothing in this commit" for all of them.
# A note, not a refusal. Exit 1 is a finding, and a finding blocks.
#
# The paths it is handed are the ones under the dirs it scans, which come from
# its --print-config. A staged file outside them is not something a full run
# would read, and handing it over anyway made the gate stricter than the check.
# The same pattern is the trigger. The fallback, for a checker too old to print
# its config, is any stylesheet or script anywhere, as before.
tokens_pattern='\.(css|ts|tsx|js|jsx)$'
tokens_dirs="$(cfg_values "$(checker_config scripts/check-tokens.mjs)" watchDir)"
[ -z "$tokens_dirs" ] || tokens_pattern="$(dirs_pattern "$tokens_dirs" '.*\.(css|ts|tsx|js|jsx)$')"
tokens_staged () {
local files rc=0 why
files="$(printf '%s\n' "$present" | grep -E "$tokens_pattern")"
if [ -z "$files" ] ; then
mark_unchecked tokens "only deletions"
return 0
fi
lines_to_array "$files"
fresh_unchecked_file
NTENT_UNCHECKED_FILE="$unchecked_file" node scripts/check-tokens.mjs --check ${ARR[@]+"${ARR[@]}"} || rc=$?
why="$(unchecked_reason)"
if [ "$rc" -eq 2 ] ; then
[ -n "$why" ] || why="it exited 2 and said nothing more"
echo " note: the token check read nothing: $why."
mark_unchecked tokens "$why"
return 0
fi
if [ "$rc" -eq 0 ] && [ -n "$why" ] ; then mark_unchecked tokens "$why" ; fi
return "$rc"
}
run_gate "tokens" \
"$tokens_pattern" \
'tokens_staged' \
'Use a token, or record a reviewed waiver with a reason and an expiry.' \
scripts/check-tokens.mjs
# Probes. Only when the lint setup itself changes, which is the moment a rule
# silently stops being loaded. Running it on every commit would be slow for no
# added information: the selectors do not change when a component does.
run_gate "probes" \
'(eslint\.config\.|scripts/eslint-rules\.mjs|scripts/probes/)' \
'node scripts/check-probes.mjs' \
'A house rule is not firing or not loaded. The output names which and where.' \
scripts/check-probes.mjs scripts/probes
# SELF-TEST. A check's own tests, whenever the check itself is staged, which is
# the only moment they can tell you anything new. The failure is the probes'
# failure one level down: a checker edit that quietly stops a rule matching
# prints a clean run, and a clean run reads as coverage. The test beside it is
# what notices.
#
# Only the staged checkers' own tests, found by name beside them: check-x.mjs
# runs check-x.test.mjs, and a staged test runs itself. One file at a time, so
# a failure names its file. A staged checker with no test is named and let
# through: the hook cannot write the test for you, and refusing would make
# every checker without one uncommittable.
#
# A test that dies on a package this checkout has not installed is a skip with
# the reason printed, never a refusal. That is "cannot run", not "found a bug",
# and a fresh install must be able to commit. A missing RELATIVE module is not
# skipped: that is the checker broken, which is exactly what this is for.
selftest_staged () {
local f t u out missing untested="" ran_any=0 rc=0 dup
local tests=()
lines_to_array "$(printf '%s\n' "$present" | grep -E '^scripts/(check-[^/]*|verify-[^/]*|lib/[^/]*)\.mjs$')"
for f in ${ARR[@]+"${ARR[@]}"} ; do
case "$f" in
*.test.mjs) t="$f" ;;
*) t="${f%.mjs}.test.mjs" ;;
esac
if [ -f "$t" ] ; then
dup=0
for u in ${tests[@]+"${tests[@]}"} ; do [ "$u" = "$t" ] && dup=1 ; done
[ "$dup" -eq 1 ] || tests+=("$t")
else
untested="${untested:+$untested, }$f"
fi
done
[ -n "$untested" ] && echo " note: no test beside $untested, so its own tests did not run."
# NODE_TEST_CONTEXT unset, because a hook run from inside a test runner
# inherits it, and a nested `node --test` that has it streams its results to
# that runner and exits 0 whatever they were.
for t in ${tests[@]+"${tests[@]}"} ; do
if out="$(env -u NODE_TEST_CONTEXT node --test "$t" 2>&1)" ; then
ran_any=1
continue
fi
missing="$(printf '%s\n' "$out" | sed -nE "s/.*Cannot find (package|module) '([^./][^']*)'.*/\2/p" | head -1)"
if [ -n "$missing" ] ; then
echo " note: $t needs $missing, which this checkout has not installed, so it did not run."
continue
fi
printf '%s\n' "$out" >&2
echo "" >&2
echo " x $t failed." >&2
rc=1
break
done
# Nothing ran, so nothing passed: keep this gate out of the passed line.
[ "$ran_any" -eq 1 ] || [ "$rc" -ne 0 ] || ran="$(printf '%s\n' "$ran" | sed 's/ *selftest$//')"
return "$rc"
}
run_gate "selftest" \
'^scripts/(check-[^/]*|verify-[^/]*|lib/[^/]*)\.mjs$' \
'selftest_staged' \
'A staged check no longer passes its own tests. Fix the check. The test changes only when the person has said the rule moved, and then the commit message says so.'
# Triggered by the dirs the checker scans and the ones it classes as private or
# shared, from its --print-config. The old src/ list is the fallback.
components_pattern='^src/(app|components|features)/'
components_dirs="$(cfg_values "$(checker_config scripts/check-stray-components.mjs)" watchDir)"
[ -z "$components_dirs" ] || components_pattern="$(dirs_pattern "$components_dirs" '')"
# The staged files are handed over, so the gate blocks on findings this
# commit is part of, and whole-repo debt is a count. Exit 2 is a checker that
# read no component it can parse (.vue, .svelte and .astro are not read): a
# note, kept off the passed line. A malformed allowlist is exit 1 and blocks.
#
# Nothing staged that the checker reads exits 0, since that is a commit with
# nothing to check and not a broken repo, but it says so in the file named by
# NTENT_UNCHECKED_FILE and so stays off the passed line too. A commit that only
# deletes components is the same: a deletion cannot make a component shared or
# duplicated, so there is no whole-repo run to fall back to, and the checker
# is not started with no paths, which would be a strict run over old debt.
components_staged () {
local files rc=0 why
files="$(printf '%s\n' "$present" | grep -E "$components_pattern")"
if [ -z "$files" ] ; then
mark_unchecked components "only deletions"
return 0
fi
lines_to_array "$files"
fresh_unchecked_file
NTENT_UNCHECKED_FILE="$unchecked_file" node scripts/check-stray-components.mjs --check ${ARR[@]+"${ARR[@]}"} || rc=$?
why="$(unchecked_reason)"
if [ "$rc" -eq 2 ] ; then
echo " note: the component check read no component it can parse. The line above says why."
mark_unchecked components "no component it can read"
return 0
fi
if [ "$rc" -eq 0 ] && [ -n "$why" ] ; then mark_unchecked components "$why" ; fi
return "$rc"
}
run_gate "components" \
"$components_pattern" \
'components_staged' \
'Promote the component to the shared components folder (the finding above names it), or allowlist it with a reason.' \
scripts/check-stray-components.mjs
# fixtures/ included, because that is where the plan puts captured payloads and
# where the checker reads them from. Leaving it out meant adding a fixture that
# no longer parsed was not checked until someone touched the schema.
#
# The dirs the checker names (its fixtureDir and the folder its schemaModule is
# in) are added to the usual ones, so schemas at lib/schemas/ trigger it too.
fixtures_pattern='^(fixtures/|packages/schemas/|packages/fixtures/|src/lib/schemas)'
fixtures_dirs="$(cfg_values "$(checker_config scripts/verify-fixtures.mjs)" watchDir)"
[ -z "$fixtures_dirs" ] || fixtures_pattern="${fixtures_pattern}|$(dirs_pattern "$fixtures_dirs" '')"
run_gate "fixtures" \
"$fixtures_pattern" \
'node scripts/verify-fixtures.mjs' \
'A schema no longer parses its fixture. One of the two is wrong; decide which.' \
scripts/verify-fixtures.mjs
# References only, so no TypeScript parse and no walk of the app: milliseconds
# on a commit that edits the contract. Coverage stays a nudge below, because
# it moves as you build. A dangling reference does not.
#
# THE TEST FILES A BUILT JOURNEY CITES TRIGGER IT TOO. An acceptance record pins
# the sha256 of each test file in its evidence, and --refs works the hash out
# again. If only contract.json triggered the gate, a commit that edits the test
# and nothing else would never meet its pin: the cheapest way to make a failing
# test pass would stay open. So the checker is asked which paths the staged
# contract cites, with --print-config, as `evidence<TAB><path><TAB><journey>`
# lines, and a staged path that is one of them runs the gate.
#
# Matched whole, one name against one name, not built into a pattern: a path
# with a bracket or a plus in it needs no escaping. The staged names are read
# again for this, NUL-separated, because the lists at the top hold a name with a
# double quote or a backslash in git's quoted form, which is never equal to the
# cited path. A cited path never holds a space or a tab, because it is the first
# word of its evidence line, so a staged name with a space in it is simply never
# equal to one. The checker refuses a cited path that is a symlink or is spelt
# in another case than the file, which is what makes an exact match enough.
#
# NOT KNOWING IS NOT "NOTHING IS CITED". If the checker knows the flag and then
# exits non-zero or prints no watch line, the contract could not be read or the
# checker is broken, and which tests are cited is unknown. The gate then runs on
# this commit whatever it stages, and --refs says what is wrong. It used to be
# read as an empty list, and a test edited alone went through. A checker written
# before the flag is not asked, and only the contract triggers the gate, as
# before.
#
# contract_cited keeps the matches, one "<path><TAB><journey>" per line, for
# the notice under RESULT.
contract_pattern='^contract\.json$'
contract_checker=scripts/check-contract-coverage.mjs
contract_cited=""
contract_blind=0
tab="$(printf '\t')"
# Is this exact path one the commit adds, changes or removes?
staged_exactly () {
local f
while IFS= read -r -d '' f ; do
[ "$f" = "$1" ] && return 0
done < <(git -C "$repo_root" diff --cached --name-only --no-renames --diff-filter=ACMRD -z 2>/dev/null)
return 1
}
contract_cfg=""
contract_asks=0
if [ -f "$contract_checker" ] && grep -q -- '--print-config' "$contract_checker" 2>/dev/null ; then
contract_asks=1
contract_cfg="$(node "$contract_checker" --print-config 2>/dev/null)" || contract_blind=1
printf '%s\n' "$contract_cfg" | grep -q "^watch$tab" || contract_blind=1
fi
while IFS="$tab" read -r cfg_key cfg_path cfg_journey ; do
[ "$cfg_key" = "evidence" ] || continue
[ -n "$cfg_path" ] || continue
staged_exactly "$cfg_path" || continue
contract_cited="${contract_cited:+$contract_cited
}${cfg_path}${tab}${cfg_journey}"
done <<EOF
$contract_cfg
EOF
# '.' is every commit, which here means this one: a cited file is staged, or
# the checker could not say which files are.
if [ -n "$contract_cited" ] || [ "$contract_blind" -eq 1 ] ; then contract_pattern='.' ; fi
# WHAT THE LAST COMMIT'S CONTRACT CITED. A commit can edit a test and stop
# citing it in one go: move the journey back to partial, or swap the evidence
# line for a manual one. The staged contract then names no such test, the gate
# passes, and the list above is empty, so the notice had nothing to say. So when
# contract.json is staged, the contract at HEAD is asked the same question, with
# the staged checker, in a folder that holds nothing else. A staged path it
# cited and the staged contract does not is kept for the notice. This needs git,
# so it runs here and not in the snapshot. It is for a notice only: if HEAD has
# no contract, or its contract cannot be read, there is nothing to add.
contract_uncited=""
if [ "$contract_asks" -eq 1 ] && printf '%s\n' "$changed" | grep -qxF -- 'contract.json' \
&& git -C "$repo_root" cat-file -e 'HEAD:contract.json' 2>/dev/null ; then
[ -n "$work" ] || work="$(make_temp)"
if mkdir -p "$work/head" 2>/dev/null && git -C "$repo_root" show 'HEAD:contract.json' > "$work/head/contract.json" 2>/dev/null ; then
# pwd -P: the checker only runs its main when the path it was started by is
# its real one, and the temp folder is behind a symlink on macOS.
contract_checker_abs="$(pwd -P)/$contract_checker"
while IFS="$tab" read -r cfg_key cfg_path cfg_journey ; do
[ "$cfg_key" = "evidence" ] || continue
[ -n "$cfg_path" ] || continue
printf '%s\n' "$contract_cfg" | grep -qF -- "evidence${tab}${cfg_path}${tab}" && continue
printf '%s\n' "$contract_uncited" | grep -qF -- "${cfg_path}${tab}" && continue
staged_exactly "$cfg_path" || continue
contract_uncited="${contract_uncited:+$contract_uncited
}${cfg_path}${tab}${cfg_journey}"
done <<EOF
$( cd "$work/head" && node "$contract_checker_abs" --print-config 2>/dev/null )
EOF
fi
fi
run_gate "contract" \
"$contract_pattern" \
'node scripts/check-contract-coverage.mjs --refs' \
'The contract contradicts itself: an id that resolves to nothing, a journey marked built on an open question, a journey marked built with no acceptance record, evidence that names a test file or script that is not there, or a test file a built journey was accepted on that has no pin or no longer matches it. Each finding names its fix.' \
scripts/check-contract-coverage.mjs contract.json
# BACKEND. The database keeps the model's promises. Runs only when something
# it reads is staged: a migration, a schema source, contract.json, or the
# checker. The paths come from --print-config, like the env gate, so moving
# CONFIG.sources keeps the gate wired.
#
# It runs in the snapshot. It reads files and boots PGlite from node_modules,
# which the snapshot links in; it needs no git and no other runtime.
#
# Exit 2 blocks, except when there is nothing to check yet. A table the check
# could not seed is not a pass, and the allowlist in CONFIG is where an
# accepted gap goes, with a reason and a date.
backend_pattern='^(supabase/migrations/|contract\.json$|scripts/check-backend\.mjs$)'
backend_inputs='unknown' # stays unknown when --print-config fails: then --check runs and says why
if [ -f scripts/check-backend.mjs ] ; then
if backend_cfg="$(node scripts/check-backend.mjs --print-config 2>/dev/null)" && [ -n "$backend_cfg" ] ; then
backend_watch=""
for p in $(printf '%s\n' "$backend_cfg" | awk -F'\t' '$1 == "watch" { print $2 }') ; do
case "$p" in
*/) backend_watch="${backend_watch:+$backend_watch|}^$(env_escape "$p")" ;;
*) backend_watch="${backend_watch:+$backend_watch|}^$(env_escape "$p")\$" ;;
esac
done
# An empty pattern would match every commit, so no watch lines keeps the default.
[ -n "$backend_watch" ] && backend_pattern="$backend_watch"
backend_inputs="$(printf '%s\n' "$backend_cfg" | awk -F'\t' '$1 == "inputCount" { print $2 }')"
[ -n "$backend_inputs" ] || backend_inputs='unknown'
fi
fi
backend_staged () {
local rc=0
if [ "$backend_inputs" = "0" ] ; then
echo " note: the backend check found no migrations to read yet."
mark_unchecked backend "no migrations to read yet"
return 0
fi
node scripts/check-backend.mjs --check || rc=$?
if [ "$rc" -eq 2 ] ; then
echo " the backend check could not check everything. The lines above say what and why." >&2
return 1
fi
return "$rc"
}
# A repo that never took the database capability has no check-backend.mjs and
# no reason to. Naming it as "not installed" on every commit that touches
# contract.json nags 45 of 48 field-study repos about something they chose not
# to have. The gap is only worth naming where the repo looks like it has a
# database: a supabase folder, or a migrations folder of any of the usual kinds,
# tracked or about to be. Looked up in the snapshot, so it is what the commit
# holds. A repo that has the checker is unaffected.
looks_like_database () {
[ -d supabase ] && return 0
local d
for d in prisma/migrations drizzle db/migrate alembic/versions migrations db/migrations ; do
[ -d "$d" ] && return 0
done
return 1
}
if [ -f scripts/check-backend.mjs ] || looks_like_database ; then
run_gate "backend" \
"$backend_pattern" \
'backend_staged' \
'Fix the finding in a new migration. If a table cannot be tested, give CONFIG.seed a value, or add it to CONFIG.untested with a reason and an until date.' \
scripts/check-backend.mjs
fi
# MIGRATIONS. A drop or a type change is a written decision. Runs when a
# migration or a schema source is staged, with the paths taken from
# check-migrations --print-config, which reads the same CONFIG.sources as the
# backend gate, so moving them moves both. The contract does not trigger it.
#
# Unlike the backend gate it needs git: it compares the index with the base
# branch. The snapshot has no .git, so it runs from the REAL repository, with
# the snapshot's copy of the script, like the secrets gate. --staged reads the
# index, not the worktree, and the decision log from the index too.
#
# Exit 2 blocks, as for the backend gate: a base that does not resolve or a
# schema that would not build is not a pass. No commits yet is exit 0 from the
# script itself. --allow-empty makes "no migration file on either side" a note
# instead: the hook runs when the checker itself is staged, which is also the
# first commit of an install that has no migration yet. The root is the hook's
# own install, so it cannot be the wrong folder the way a hand-run one can.
#
# In a package install the watch paths are the package's, and the staged paths
# are the repo's, so both the pattern and the script's location carry the prefix.
migrations_prefix="$(env_escape "$install_prefix")"
migrations_pattern="^${migrations_prefix}supabase/migrations/" # the default when --print-config fails: then --check runs and says why
if [ -f "${install_prefix}scripts/check-migrations.mjs" ] ; then
if migrations_cfg="$( cd "${install_prefix:-.}" && node scripts/check-migrations.mjs --print-config 2>/dev/null )" && [ -n "$migrations_cfg" ] ; then
migrations_watch=""
for p in $(printf '%s\n' "$migrations_cfg" | awk -F'\t' '$1 == "watch" { print $2 }') ; do
case "$p" in
*/) migrations_watch="${migrations_watch:+$migrations_watch|}^${migrations_prefix}$(env_escape "$p")" ;;
*) migrations_watch="${migrations_watch:+$migrations_watch|}^${migrations_prefix}$(env_escape "$p")\$" ;;
esac
done
# An empty pattern would match every commit, so no watch lines keeps the default.
[ -n "$migrations_watch" ] && migrations_pattern="$migrations_watch"
fi
migrations_pattern="${migrations_pattern}|^${migrations_prefix}scripts/check-migrations\.mjs\$"
fi
migrations_staged () {
local here="$PWD" rc=0
( cd "$repo_root" && node "$here/${install_prefix}scripts/check-migrations.mjs" --check --staged --allow-empty --root "$install_root" ) || rc=$?
if [ "$rc" -eq 2 ] ; then
echo " the migration check could not compare with the base branch. The lines above say what and why." >&2
return 1
fi
return "$rc"
}
# The checker is looked up under the install's folder: the same line, spelled
# scripts/check-migrations.mjs, for a root install and a package one.
gate_prefix="$install_prefix"
run_gate "migrations" \
"$migrations_pattern" \
'migrations_staged' \
'Write the drop or type change down: an entry in DECISIONS.md naming the migration file and the table or column in backticks. Or revert the edit to the old migration and write a new one.' \
scripts/check-migrations.mjs
gate_prefix=""
# RULES. Whether AGENTS.md still describes the repo: every command it names
# exists, every check in scripts/ has a row, and every row that says pre-commit
# is a gate this file runs. So it runs when any of those can move.
#
# Exit 2 is the check saying it has nothing to hold the file to, and the usual
# reason is a fresh install: AGENTS.md is still the template, which describes
# an example repo. Refusing the first commit after setup over that is how a
# hook gets deleted. A note, not a refusal. Exit 1 is the file being wrong
# about this repo, and that blocks.
rules_staged () {
local rc=0
node scripts/check-rules-doc.mjs --check || rc=$?
if [ "$rc" -eq 2 ] ; then
echo " note: the rules check had nothing to hold AGENTS.md to. It says why above."
mark_unchecked rules "nothing to hold AGENTS.md to"
return 0
fi
return "$rc"
}
run_gate "rules" \
'^(AGENTS\.md|CLAUDE\.md|package\.json|scripts/)' \
'rules_staged' \
'AGENTS.md no longer matches the repo. Correct whichever is wrong, the doc or the repo; each finding names both sides.' \
scripts/check-rules-doc.mjs
# CLIPS. Every overflow clip says what it clips, because the next person has to
# know that to know whether it can go. The staged paths are passed in, like the
# tokens gate: a commit is asked about the files it touches, so an old codebase
# explains its clips one file at a time rather than all on the first commit.
#
# Exit 2 is the checker saying it read nothing: every staged path was under a
# directory it skips, which by default is the vendored src/components/ui. A
# note, not a refusal. Exit 1 is a clip with nothing saying why, and it blocks.
#
# Trigger and file list both come from the dirs the checker prints, like the
# tokens gate. src/ is the fallback for an older checker.
clips_pattern='^src/.*\.(css|ts|tsx)$'
clips_dirs="$(cfg_values "$(checker_config scripts/check-clip-comments.mjs)" watchDir)"
[ -z "$clips_dirs" ] || clips_pattern="$(dirs_pattern "$clips_dirs" '.*\.(css|ts|tsx)$')"
clips_staged () {
local files rc=0
files="$(printf '%s\n' "$present" | grep -E "$clips_pattern")"
if [ -z "$files" ] ; then
mark_unchecked clips "only deletions"
return 0
fi
lines_to_array "$files"
node scripts/check-clip-comments.mjs --check ${ARR[@]+"${ARR[@]}"} || rc=$?
if [ "$rc" -eq 2 ] ; then
echo " note: the clip check had nothing it reads in this commit."
mark_unchecked clips "nothing it reads in this commit"
return 0
fi
return "$rc"
}
run_gate "clips" \
"$clips_pattern" \
'clips_staged' \
'Say what each clip holds in, in a comment on its line or directly above it.' \
scripts/check-clip-comments.mjs scripts/lib/waivers.mjs
# CONTRAST. Legibility is a property of a pair, so the token gate above, which
# asks whether one value is allowed, cannot see it. Runs when a stylesheet is
# staged, and when the checker itself is, because that is where the pairs, the
# allowlist and the debt register live. It reads the whole stylesheet rather
# than the staged list: a pair's colours can come from anywhere in it.
#
# Exit 2 means only that there is nothing here to measure yet: no stylesheet,
# or every pair was optional and skipped. A note, not a refusal, so a repo can
# install the check before it has a stylesheet. Everything else blocks, and
# that includes a broken config: an allowlist entry with no reason, malformed
# debt, a pair naming a role the stylesheet lacks, a value the checker cannot
# read. Those were exit 2 once, and the note let them commit, which is the one
# thing an allowlist that demands reasons exists to stop.
contrast_staged () {
local rc=0
node scripts/check-contrast.mjs --check || rc=$?
if [ "$rc" -eq 2 ] ; then
echo " note: the contrast check found nothing to measure yet. The line above says why."
mark_unchecked contrast "nothing to measure yet"
return 0
fi
return "$rc"
}
run_gate "contrast" \
'(\.css$|^scripts/check-contrast\.mjs$)' \
'contrast_staged' \
'Move a colour until the pair clears, or record it in CONFIG.debt with what it costs a user and the date.' \
scripts/check-contrast.mjs
# PROJECT GATES. An optional scripts/git-hooks/gates.local holds a project's own
# gates, one run_gate line each, so adding one never means editing this file:
#
# run_gate "<name>" "<path-regex>" "<command>" "<fix-hint>" [required-file ...]
#
# They run after the built-in gates, in the snapshot, so it is the committed
# file that is read. They list on the passed, unchecked and skipped lines like
# any other, and a failing one blocks and is named: "x <name> failed." A command
# that read nothing says so with: mark_unchecked <name> "<reason>"
#
# PARSED, NOT SOURCED. A line is run only if it starts "run_gate ". A comment or
# a blank line is skipped, and any other line blocks and is quoted, so a stray
# command or a merge-conflict marker never runs at this file's top level. A
# gate's command is shell, as the built-in gates' are; the file is the project's
# own, committed and reviewed like this hook, so that is no new trust.
local_gates="${install_prefix}scripts/git-hooks/gates.local"
if [ -f "$local_gates" ] ; then
# On descriptor 3, so a gate's command cannot read the rest of the file.
while IFS= read -r gate_line <&3 || [ -n "$gate_line" ] ; do
gate_line="${gate_line#"${gate_line%%[![:space:]]*}"}"
case "$gate_line" in
''|'#'*) continue ;;
'run_gate '*) eval "$gate_line" ;;
*) echo " x gates.local: not a run_gate line, so not run: $gate_line" >&2 ; status=1 ;;
esac
[ "$status" -eq 0 ] || break
done 3< "$local_gates"
fi
# ---------------------------------------------------------------- NUDGES ---
# Never set status. These report something worth knowing that the committer
# cannot necessarily fix right now, so they must not block.
if [ -f scripts/check-contract-coverage.mjs ] &&
printf '%s\n' "$changed" | grep -qE '^(contract\.json|src/types/)' ; then
node scripts/check-contract-coverage.mjs 2>/dev/null | grep -E 'Overall|UNMEASURED' || true
fi
if printf '%s\n' "$changed" | grep -qE '^(prisma/migrations|supabase/migrations|drizzle|db/migrate|alembic/versions|migrations)/' ; then
echo " note: a migration is staged. Its header comment should answer:"
echo " is it reversible, does it lock, what is the backfill, how do we roll back."
fi
# ---------------------------------------------------------------- RESULT ---
if [ "$status" -eq 0 ] ; then
[ -n "$ran" ] && echo " gates passed: $ran"
fi
# A TEST AND ITS ACCEPTANCE RECORD, MOVED IN ONE COMMIT.
#
# The contract gate passing on a commit that stages a cited test file together
# with contract.json means the record and the test still agree, and it cannot
# say who made them agree. Accepting a journey again after its test changed is
# the honest path, and moving the pin to fit an edited test looks exactly the
# same from here. So the hook says what it saw and leaves the question with the
# person. A notice, never a refusal: it needs only the staged paths and the
# checker's list, and it prints on a first acceptance too, where the answer is
# plainly yes.
contract_notice () {
local p j said=0
printf '%s\n' "$changed" | grep -qxF -- 'contract.json' || return 0
case " $ran " in *" contract "*) ;; *) return 0 ;; esac
# A test the last commit's contract cited and this one's does not. See
# WHAT THE LAST COMMIT'S CONTRACT CITED.
while IFS="$tab" read -r p j ; do
[ -n "$p" ] || continue
echo " notice: this commit changes $p, a test journey \"$j\" was accepted on"
echo " in the last commit, and the contract in this commit no longer holds it to that test."
echo " If the journey was let go so the test could change,"
echo " a person should have agreed to that. If nobody did, undo the commit and ask."
done <<EOF
$contract_uncited
EOF
[ -n "$contract_cited" ] || return 0
while IFS="$tab" read -r p j ; do
[ -n "$p" ] || continue
echo " notice: this commit changes $p, a test journey \"$j\" was accepted on,"
said=1
done <<EOF
$contract_cited
EOF
[ "$said" -eq 1 ] || return 0
echo " and contract.json with it. If the acceptance record moved to fit the test,"
echo " a person should have agreed to that. If nobody did, undo the commit and ask."
}
[ "$status" -ne 0 ] || contract_notice
# Their own line, and printed pass or fail. A gate that ran and read nothing has
# vouched for nothing, and a pass line that lists it is the hook saying more
# than it knows.
if [ -n "$unchecked" ] ; then
echo " ran but checked nothing: $unchecked"
fi
# Printed pass or fail. A checker this repo has not installed is a real gap in
# what was just verified, and the commit message is the only place anyone would
# ever see it.
if [ -n "$skipped" ] ; then
echo " not installed, so not checked: $skipped"
fi
exit "$status"
How to tell it works: Stage a file that fails a check this tier installs and the commit is refused, naming the check and the fix. At tier 1 that is check-env: add a variable to the env schema and not to .env.example. The hardcoded-colour case needs the tier 2 lint rules. From tier 2, edit a test file a built journey cites in contract.json and stage only that file: the contract gate runs anyway and refuses the commit, naming the journey. Rename or delete it instead and the same happens. Accept the journey again in the same commit and it passes, with a notice under the passed line that the test and the record moved together. The notice can be avoided by spreading the change over several commits, and a merge or a rebase does not run this hook at all: CI is the check there.