Files
Holocron/scripts/apm-audit-ci.sh
T
Defame1297andClaude Opus 5.5 e14fca123d fix(gates): re-run the full root audit after the unlanded-plugin waiver
Why: on apm 0.39.3 a failing ref-consistency stops the root run after
three checks, so while the unlanded-plugin waiver applied, the other twelve
root checks (content-integrity, hook-approval-pins, local-bundle-hooks,
exec-status-current, deployed-files-present, ...) never ran.

Implementation notes: once the waiver's conditions hold, the hook copies
the working tree (minus .git and .venv) into a mktemp dir. There it drops
only the waived plugins' dependencies.apm items, checks the diff is
deletions only, and runs git init with the same origin. It then runs
apm audit --ci in the copy, and passes only on exit 0 with
"All 15 check(s) passed". A copy was chosen over a trap-guarded in-place
swap of apm.yml: it never writes the working tree, so the tree stays
byte-identical even after SIGKILL. The plugin name must now start
alphanumeric and contain no "..".

Impact: tests cover a failing, short, or non-zero re-run; a one-of-three
failure on another row; a duplicated details header; and dotted names.
Each guard was mutation-checked. On this branch the re-run reports all 15
checks passing.

Refs: #179

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNugst7K9Bd2FTR4Mi
2026-12-06 10:07:49 +00:00

364 lines
17 KiB
Bash
Executable File

#!/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/<pkg>/.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 `<identity>/plugins/<name>: 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
# `<identity>/plugins/<name>: not found in lockfile`, where <identity> is
# the one root apm.yml's own git+path entry for plugins/<name> yields,
# derived by check-executables-allow-sync.sh's rule
# 3. plugins/<name>/apm.yml exists in the working tree
# 4. plugins/<name>/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` with the same origin URL
# stands in for it -- apm reads only the origin remote, for org-policy
# discovery, and the copy prints the same policy line the real root does.
# * NOT .venv: apm runs through `uv run --project <repo root>`, so the
# environment is the real one; .venv is no apm input and most of the size.
# 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 <repo root> --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 <plugin dir name> -- the identity root apm.yml's git+path entry
# for plugins/<name> yields: <host>/<owner>/<repo>/plugins/<name>. 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 <audit output> -- 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 <names, one per line> -- prints apm.yml (cwd) with every
# `dependencies:` > `apm:` list item whose `path:` is plugins/<name> 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 <names, one per line> -- 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 name rerun rc delta
SCRATCH="$(mktemp -d "${TMPDIR:-/tmp}/apm-audit-ci.XXXXXX")" || return 1
if ! tar -C . --exclude=./.git --exclude=./.venv -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
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"