#!/usr/bin/env bash # apm-audit-ci pre-push hook. # # Runs `apm audit --ci` once per manifest -- the root one and each plugin # package -- because the root-only invocation audits the marketplace manifest # and nothing else, and `apm pack --check-clean` does not parse plugin # `dependencies:` blocks either. Full rationale: docs/spec/gates.md, # "apm-audit-ci". # # WHY THIS IS A SCRIPT AND NOT THE ONE-LINE `for` LOOP IT REPLACED # # apm treats any directory holding both apm.yml and apm.lock.yaml as an INSTALL # ROOT. A plugin package is not one: it is content to be installed elsewhere. # While every plugin declared `dependencies: {apm: [], mcp: []}` the distinction # never surfaced, because the plugin-level `lockfile-exists` check reported # `No dependencies declared -- lockfile not required` and passed vacuously. # # plugins/onedev was the first package to declare a real dependency (it pinned # OneDev's TOD skills; removed 2026-11-11, plugins/mattpocock is the live case), # which armed that check and left no green state: # # * no apm.lock.yaml in the package -> `lockfile-exists` fails with # "apm.yml declares dependencies but apm.lock.yaml is absent" # * an apm.lock.yaml in the package -> `lockfile-exists` passes and thereby # arms the rest of the root check set (nine more on apm 0.28.0, fourteen # on 0.39.3), and `drift` then fails demanding the # dependency's skills be DEPLOYED inside the package # (plugins//.agents/skills/...), which is meaningless for a package # and additionally litters it with an apm_modules/ tree # # So this hook waives exactly one failure: a plugin package whose ONLY failing # check is `lockfile-exists`. Verified against apm 0.28.0, and re-verified # against 0.39.3 (spike #269, on #268): both matched strings below are unchanged, # and no other check fails in any plugin directory. # # WHAT IS DELIBERATELY NOT WAIVED # # Dropping `--ci` in package directories would have been the smaller change and # is WRONG. Verified on apm 0.28.0, and again on 0.39.3 (#272), against a # scratch package whose dependency entry carried no git/path/registry field: # `apm audit --ci` exits 1 naming the field (a failing manifest-parse row on # 0.39.3), while plain `apm audit` exits 0 with "nothing to scan" ("No # recognized deployed primitives found" on 0.39.3, "No apm.lock.yaml found" # on 0.28.0). Malformed-dependency detection is the reason gates.md gives # for auditing packages at all, and a package WITH dependencies is the only kind # that can carry a malformed dependency entry -- so the check would have been # discarded precisely where it earns its keep. # # The waiver is therefore narrow on three axes, and fails closed on each: # 1. the root manifest is never waived for it (the root's own, separate # waiver is described below) # 2. the failing check must be `lockfile-exists` and no other -- the # "1 of 1 check(s) failed" assertion is what makes that true, since any # second failing check changes the count and the run fails normally # 3. output apm does not produce in the recognised shape is a failure # # Matching on apm's stdout is the weak point: an apm upgrade that rewords either # line silently turns the waiver off, which fails the push rather than hiding a # defect. If that happens, re-verify against the new output and update the two # patterns below rather than widening them. # # THE SECOND WAIVER: A PLUGIN NOT YET ON origin/main (ROOT MANIFEST ONLY) # # Root apm.yml's first-party dependencies resolve from the remote's `main` # (ADR-0019), so the lock cannot record a plugin until that plugin has landed. # check-executables-allow-sync.sh meanwhile requires a hook- or bin-shipping # plugin to have its git+path entry in root apm.yml before it can be pushed at # all. Together they make a first-landing executable-shipping plugin # unpushable: the entry is mandatory, and the root `ref-consistency` check then # fails it as `/plugins/: not found in lockfile`. Verified on # apm 0.39.3 (#179): a failing ref-consistency cuts the root run short at three # checks (lockfile-exists, ref-consistency, drift), so the sole-failure line is # `1 of 3 check(s) failed`. # # So the root manifest's audit is waived when, and only when, ALL of these hold: # 1. the failure count is exactly "1 of 3 check(s) failed" and the one # failing row is ref-consistency -- any second failure changes the count # 2. the ref-consistency details block exists and EVERY line in it reads # `/plugins/: not found in lockfile`, where is # the one root apm.yml's own git+path entry for plugins/ yields, # derived by check-executables-allow-sync.sh's rule # 3. plugins//apm.yml exists in the working tree # 4. plugins//apm.yml is absent from the LOCAL origin/main ref -- no # fetch, the hook stays offline -- and origin/main must resolve # 5. a re-run of `apm audit --ci` against the root with those plugins' # `dependencies.apm` entries removed passes with "All 15 check(s) passed" # Anything else, including output in a shape not recognised here, fails the # push. The waiver lapses for a plugin by itself: once it is on origin/main, # condition 4 is false and the follow-up lock PR has to record it. # # WHY THE RE-RUN (CONDITION 5) # # The cut-short run is exactly the problem: while ref-consistency fails, apm # never runs the other twelve root checks (content-integrity, # hook-approval-pins, local-bundle-hooks, exec-status-current, # deployed-files-present, ...), so waiving the three-check run alone would let # a defect in any of them through. Removing the unlanded plugins' entries is # the one change that makes ref-consistency pass, and apm then runs the full # set. Verified on apm 0.39.3 (#179): this branch's root, so reduced, prints # "All 15 check(s) passed". The count is asserted, not just the exit code, so # an apm that runs fewer checks, or adds one, fails closed until re-verified. # # The re-run happens in a SCRATCH COPY, never in place. The working tree minus # .git and .venv is copied with tar into a mktemp -d dir, apm.yml is reduced # there, and apm runs there. An in-place swap of apm.yml guarded by a trap was # the alternative and is weaker: no trap survives SIGKILL or a power cut, and # for the swap's duration a concurrent apm (the SessionStart hook, another # shell) would read the reduced manifest. The copy never writes the working # tree at all, so it is byte-identical afterwards whatever happens; at worst a # killed run leaks a temp dir. What the copy holds, and why: # * everything apm reads for the root audit -- apm.yml, apm.lock.yaml, # apm_modules/ (the cache-only replay's source), .claude/ and every other # deployed tree (deployed-files-present, content-integrity, drift), and # the plugins/ sources the marketplace and local entries name. Copying the # whole tree rather than a hand-picked list means a check that starts # reading another path cannot silently see an empty one. # * NOT .git: from a linked worktree it is a pointer file into the shared # gitdir, and a git command run in the copy could then refresh that # worktree's real index. A fresh `git init` stands in for it, carrying the # two pieces of git state apm reads: the origin remote's URL (org-policy # discovery; the copy prints the same policy line the real root does) and # the repo's info/exclude, copied from `git rev-parse --git-path # info/exclude` (which resolves to the shared gitdir in a linked worktree) # when it exists. deployed-files-present runs `git check-ignore` on each # lock-recorded path that is absent, and an absent path ignored only # through info/exclude must not count as missing in the copy either. # .gitignore files travel with the tree, and core.excludesFile is the same # user-level config for both runs. # * NOT .venv: apm runs through `uv run --project `, so the # environment is the real one; .venv is no apm input and most of the size. # * NOT .claude/worktrees: Claude Code's linked worktrees, each a full # checkout that can carry its own .venv. They are ignored through # info/exclude, and no root check reads them: deployed-files-present and # content-integrity look up lock-recorded paths, none of which is under # .claude/worktrees, and drift compares the replay's deployed files # against the same paths in the tree. Leaving them out hides nothing the # real audit would see. # Only list items under `dependencies:` > `apm:` whose `path:` names a waived # plugin are removed (comments and every other line kept), and the result is # checked to differ from the original by deletions only, each waived entry gone. set -uo pipefail # apm is the repo-pinned one, run through scripts/lib/apm.sh as # `uv run --project --frozen apm` (ADR-0034). Sourcing the helper # also scrubs git's repo-locating env before apm runs: pushed from a linked # worktree, the hook inherits an absolute GIT_DIR, and apm's drift replay runs # `git init` / `git checkout` in a temp dir with it -- flipping core.bare=true # and moving the worktree's HEAD (issue #204). See clean-git-env.sh for the # full account. # shellcheck source=scripts/lib/apm.sh source "$(dirname "${BASH_SOURCE[0]}")/lib/apm.sh" require_apm_version || exit 1 readonly WAIVED_CHECK='declares dependencies but apm.lock.yaml is absent' readonly SOLE_FAILURE='1 of 1 check(s) failed' readonly REF_SOLE_FAILURE='1 of 3 check(s) failed' readonly REF_FAILED_ROW='^\| \[x\] +\| ref-consistency +\|' readonly REF_DETAILS_HEADER=' ref-consistency details:' # The name must start alphanumeric, which rules out `.` and `..`; `..` # anywhere else is rejected separately in ref_waivable. readonly REF_DETAIL='^ - (.+)/plugins/([A-Za-z0-9][A-Za-z0-9._-]*): not found in lockfile$' readonly ROOT_FULL_PASS='All 15 check(s) passed' # dep_identity -- the identity root apm.yml's git+path entry # for plugins/ yields: ///plugins/. The URL rule # is check-executables-allow-sync.sh's identity(): drop the scheme (or turn an # scp-like host:path into host/path), any user@, a trailing / and .git. Empty # when there is no such entry. A line scan of the one shape root apm.yml uses # (`dependencies:` > `apm:` > `- git:` / `path:` items), not a YAML parse: an # entry in any other shape yields nothing, and so fails closed. dep_identity() { local want="plugins/$1" url url="$(awk -v want="$want" ' function unq(v) { sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) if (v ~ /^".*"$/ || v ~ /^\047.*\047$/) v = substr(v, 2, length(v) - 2) return v } function flush() { if (g != "" && p == want) print g; g = ""; p = "" } /^[ \t]*(#|$)/ { next } /^[^ ]/ { flush(); in_deps = ($0 ~ /^dependencies:/); in_apm = 0; next } !in_deps { next } /^ [^ ]/ { flush(); in_apm = ($0 ~ /^ apm:/); next } !in_apm { next } /^ - / { flush(); sub(/^ - /, " ") } /^ git:/ { v = $0; sub(/^ git:/, "", v); g = unq(v); next } /^ path:/ { v = $0; sub(/^ path:/, "", v); p = unq(v); sub(/^\.\//, "", p); sub(/\/$/, "", p); next } END { flush() } ' apm.yml 2>/dev/null | head -n 1)" [ -n "$url" ] || return 0 if [[ "$url" == *://* ]]; then url="${url#*://}" elif [[ "$url" == *:* ]]; then url="${url/://}" fi url="${url#*@}" url="${url%/}" url="${url%.git}" printf '%s/%s' "$url" "$want" } # ref_waivable -- succeeds, printing each waived plugin dir name # on its own line, only when the root output is exactly the unlanded-plugin # ref-consistency failure described in the header. Otherwise prints why on # stderr and fails. ref_waivable() { local output="$1" details line identity name names="" grep -qF "$REF_SOLE_FAILURE" <<<"$output" || return 1 grep -qE "$REF_FAILED_ROW" <<<"$output" || return 1 [ "$(grep -cxF "$REF_DETAILS_HEADER" <<<"$output")" -eq 1 ] || return 1 # The details block: every line after the header up to the first blank one. details="$(awk -v h="$REF_DETAILS_HEADER" ' $0 == h { on = 1; next } on && /^[ \t]*$/ { exit } on { print } ' <<<"$output")" [ -n "$details" ] || return 1 if ! git rev-parse --verify --quiet 'origin/main^{commit}' >/dev/null; then echo 'apm audit --ci: ref-consistency not waived: origin/main does not resolve locally, so whether a plugin has landed is unknown' >&2 return 1 fi while IFS= read -r line; do if [[ ! "$line" =~ $REF_DETAIL ]]; then echo "apm audit --ci: ref-consistency not waived: unrecognised detail line: $line" >&2 return 1 fi identity="${BASH_REMATCH[1]}" name="${BASH_REMATCH[2]}" if [[ "$name" == *..* ]]; then echo "apm audit --ci: ref-consistency not waived: plugin name '$name' contains '..'" >&2 return 1 fi if [ "$identity/plugins/$name" != "$(dep_identity "$name")" ]; then echo "apm audit --ci: ref-consistency not waived: $identity/plugins/$name is not root apm.yml's git+path entry for plugins/$name" >&2 return 1 fi if [ ! -f "plugins/$name/apm.yml" ]; then echo "apm audit --ci: ref-consistency not waived: plugins/$name/apm.yml is not in the working tree" >&2 return 1 fi if git cat-file -e "origin/main:plugins/$name/apm.yml" 2>/dev/null; then echo "apm audit --ci: ref-consistency not waived: plugins/$name is already on origin/main, so the lock must record it" >&2 return 1 fi names+="$name"$'\n' done <<<"$details" printf '%s' "$names" } # reduce_manifest -- prints apm.yml (cwd) with every # `dependencies:` > `apm:` list item whose `path:` is plugins/ for a # listed name removed, and every other line unchanged. Same line scan, and the # same one shape, as dep_identity. reduce_manifest() { REDUCE_NAMES="$1" awk ' BEGIN { n = split(ENVIRON["REDUCE_NAMES"], a, "\n"); for (i = 1; i <= n; i++) if (a[i] != "") drop["plugins/" a[i]] = 1 } function flush() { if (buf != "" && !(p in drop)) printf "%s", buf; buf = ""; p = ""; in_item = 0 } /^[^ \t#]/ && $0 !~ /^$/ { flush(); in_deps = ($0 ~ /^dependencies:/); in_apm = 0; print; next } !in_deps { print; next } /^ [^ #]/ { flush(); in_apm = ($0 ~ /^ apm:/); print; next } !in_apm { print; next } /^ - / { flush(); in_item = 1; buf = $0 "\n" v = $0; sub(/^ - /, "", v) if (v ~ /^path:/) { sub(/^path:/, "", v); setp(v) } next } in_item && /^ / { if ($0 ~ /^ path:/) { v = $0; sub(/^ path:/, "", v); setp(v) } buf = buf $0 "\n"; next } { flush(); print } function setp(v) { sub(/^[ \t]+/, "", v); sub(/[ \t]+$/, "", v) if (v ~ /^".*"$/ || v ~ /^\047.*\047$/) v = substr(v, 2, length(v) - 2) sub(/^\.\//, "", v); sub(/\/$/, "", v); p = v } END { flush() } ' apm.yml } SCRATCH="" cleanup() { [ -z "$SCRATCH" ] || rm -rf "$SCRATCH"; } trap cleanup EXIT trap 'exit 130' INT trap 'exit 143' TERM HUP # reduced_root_audit -- condition 5 of the second waiver: # re-runs the root audit in a scratch copy with the named plugins' dependency # entries removed (header, "WHY THE RE-RUN"). Succeeds only when that run exits # 0 and reports the full root check set passing; otherwise prints why, and # apm's output, on stderr and fails. reduced_root_audit() { local names="$1" origin exclude name rerun rc delta SCRATCH="$(mktemp -d "${TMPDIR:-/tmp}/apm-audit-ci.XXXXXX")" || return 1 if ! tar -C . --exclude=./.git --exclude=./.venv --exclude=./.claude/worktrees -cf - . | tar -C "$SCRATCH" -xf -; then echo 'apm audit --ci: ref-consistency not waived: could not copy the tree for the re-run' >&2 return 1 fi if ! reduce_manifest "$names" >"$SCRATCH/apm.yml"; then echo 'apm audit --ci: ref-consistency not waived: could not reduce apm.yml for the re-run' >&2 return 1 fi # Deletions only: diff's normal format prints a `NdM` / `N,MdK` header and # `< ` lines for each deleted range, and anything else is an addition or a # change. A here-string, not a pipe into grep -q (see the axis-1 comment # below), and an empty delta fails too: something must have been removed. delta="$(diff apm.yml "$SCRATCH/apm.yml")" if grep -qvE '^([0-9]+(,[0-9]+)?d[0-9]+|< .*|<)$' <<<"$delta"; then echo 'apm audit --ci: ref-consistency not waived: reducing apm.yml changed more than the waived entries' >&2 return 1 fi while IFS= read -r name; do [ -n "$name" ] || continue if [ -n "$(cd "$SCRATCH" && dep_identity "$name")" ]; then echo "apm audit --ci: ref-consistency not waived: could not remove plugins/$name's entry for the re-run" >&2 return 1 fi done <<<"$names" if ! git init -q "$SCRATCH"; then echo 'apm audit --ci: ref-consistency not waived: could not git init the re-run copy' >&2 return 1 fi if origin="$(git remote get-url origin 2>/dev/null)"; then git -C "$SCRATCH" remote add origin "$origin" || return 1 fi # The real repo's ignore rules for deployed-files-present (header, "NOT # .git"). --git-path resolves to the shared gitdir from a linked worktree. exclude="$(git rev-parse --path-format=absolute --git-path info/exclude 2>/dev/null)" || exclude="" if [ -n "$exclude" ] && [ -f "$exclude" ]; then if ! mkdir -p "$SCRATCH/.git/info" || ! cp "$exclude" "$SCRATCH/.git/info/exclude"; then echo 'apm audit --ci: ref-consistency not waived: could not copy info/exclude into the re-run copy' >&2 return 1 fi fi rc=0 rerun="$(cd "$SCRATCH" && run_apm audit --ci 2>&1)" || rc=$? if [ "$rc" -ne 0 ] || ! grep -qF "$ROOT_FULL_PASS" <<<"$rerun"; then printf '%s\n' "$rerun" >&2 echo "apm audit --ci: ref-consistency not waived: the root re-run without the unlanded plugins did not report '$ROOT_FULL_PASS' (exit $rc)" >&2 return 1 fi rm -rf "$SCRATCH" SCRATCH="" } status=0 for manifest_dir in . plugins/*/; do output="$(cd "$manifest_dir" && run_apm audit --ci 2>&1)" exit_code=$? if [ "$exit_code" -eq 0 ]; then continue fi # The root's one waiver: plugins not yet on origin/main (header, second # waiver). if [ "$manifest_dir" = "." ] && waived="$(ref_waivable "$output")" && reduced_root_audit "$waived"; then printf 'apm audit --ci: root re-run without the unlanded plugins: %s\n' "$ROOT_FULL_PASS" while IFS= read -r name; do printf 'apm audit --ci: waived ref-consistency for plugins/%s (not yet on origin/main; ADR-0019)\n' \ "$name" done <<<"$waived" continue fi # Axis 1: the root is never waived for lockfile-exists. # Here-strings, not `printf ... | grep -q`: under `set -o pipefail` grep -q # exits on its first match, SIGPIPEs the writer, and the writer's death # becomes the pipeline's status -- a race tests/test-no-pipefail-early-exit-grep.sh # scans every tracked script for. if [ "$manifest_dir" != "." ] && grep -qF "$WAIVED_CHECK" <<<"$output" && grep -qF "$SOLE_FAILURE" <<<"$output"; then printf 'apm audit --ci: waived lockfile-exists in %s (package, not an install root)\n' \ "$manifest_dir" continue fi printf '%s\n' "$output" >&2 printf 'apm audit --ci failed in %s\n' "$manifest_dir" >&2 status=1 done exit "$status"