#!/usr/bin/env bash # Tests for plugins/kyberforge/.apm/hooks/check-apm-current.sh — the SessionStart # hook that keeps an apm-consumed install level with its remote. # # `apm` and `uv` are mocked throughout (seam A: fake binaries first on PATH, # asserting on exit code and stdout, plus the fakes' own call logs): the hook's # contract is "pick the apm, read `apm outdated`, decide, emit SessionStart # JSON", and that is testable without a network or a real install. The real # apm appears once, at the end, to pin the phrase the hook greps for. set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" HOOK="$REPO_ROOT/plugins/kyberforge/.apm/hooks/check-apm-current.sh" HOOKS_JSON="$REPO_ROOT/plugins/kyberforge/.apm/hooks/hooks.json" PASS=0 FAIL=0 pass() { echo " PASS: $1"; PASS=$((PASS + 1)); } fail() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); } command -v python3 > /dev/null 2>&1 || { echo "python3 required"; exit 77; } FAKE_BIN="$(mktemp -d)" WORK="$(mktemp -d)" trap 'rm -rf "$FAKE_BIN" "$WORK"' EXIT # The hook asks git which branch it is on. Stop git's discovery at the temp # root so a $TMPDIR that happens to sit inside a checkout cannot leak a branch # into the fixtures that are meant to be outside one. export GIT_CEILING_DIRECTORIES GIT_CEILING_DIRECTORIES="$(dirname "$WORK")" # Mock `apm`. $1 chooses what `apm outdated` reports; $2 the exit code of # `apm update`. Sentinel files record whether update was actually invoked and # which directory the calls ran in — the hook must run them against the same # directory its lockfile guard checked, not the session's cwd. # `apm --version` answers 0.39.3 unless $3 says otherwise: the hook skips the # outdated check on anything older than 0.39.2 (ADR-0034). make_apm() { local outdated_line="$1" update_exit="$2" version="${3:-0.39.3}" cat > "$FAKE_BIN/apm" << EOF #!/usr/bin/env bash pwd > "$WORK/apm-cwd" case "\$1" in --version) echo "Agent Package Manager (APM) CLI version $version"; exit 0 ;; outdated) echo "$outdated_line"; exit 0 ;; update) touch "$WORK/update-was-called"; exit $update_exit ;; esac exit 0 EOF chmod +x "$FAKE_BIN/apm" } # CLAUDE_PROJECT_DIR is cleared rather than merely left alone: a session in this # repo exports it, and an inherited value would point every case at the real # repo root (which has a real apm.lock.yaml) instead of the fixture. The # project-directory cases below set it deliberately. run_hook() { (cd "$WORK" && env -u CLAUDE_PROJECT_DIR PATH="$FAKE_BIN:$PATH" bash "$HOOK" 2>/dev/null); } # Same, with an explicit cwd and CLAUDE_PROJECT_DIR. $1 is the cwd; $2 the value # for CLAUDE_PROJECT_DIR, or the literal `-` to leave it unset. run_hook_in() { local cwd="$1" project_dir="$2" if [[ "$project_dir" == "-" ]]; then (cd "$cwd" && env -u CLAUDE_PROJECT_DIR PATH="$FAKE_BIN:$PATH" bash "$HOOK" 2>/dev/null) else (cd "$cwd" && env CLAUDE_PROJECT_DIR="$project_dir" PATH="$FAKE_BIN:$PATH" bash "$HOOK" 2>/dev/null) fi } json_field() { python3 -c 'import json,sys; print(json.load(sys.stdin)["hookSpecificOutput"][sys.argv[1]])' "$1"; } # --------------------------------------------------------------------------- echo "--- inert without an apm-consumed install ---" # --------------------------------------------------------------------------- make_apm "[!] 6 outdated dependencies found" 0 rm -f "$WORK/apm.lock.yaml" "$WORK/update-was-called" out="$(run_hook)"; rc=$? [[ $rc -eq 0 ]] && pass "exits 0 with no apm.lock.yaml" || fail "should exit 0 with no apm.lock.yaml" [[ -z "$out" ]] && pass "emits nothing with no apm.lock.yaml" || fail "should stay silent with no apm.lock.yaml" [[ ! -f "$WORK/update-was-called" ]] && pass "does not run apm update with no apm.lock.yaml" \ || fail "must not touch a project that does not use apm" # A native (non-apm) install of this plugin hits exactly this path, so it is the # guard that keeps the hook from acting on someone else's repo. touch "$WORK/apm.lock.yaml" # --------------------------------------------------------------------------- echo "" echo "--- inert when apm is absent ---" # --------------------------------------------------------------------------- rm -f "$WORK/update-was-called" out="$( (cd "$WORK" && PATH="$(dirname "$(command -v bash)")" bash "$HOOK" 2>/dev/null) )"; rc=$? [[ $rc -eq 0 ]] && pass "exits 0 when apm is not on PATH" || fail "should exit 0 when apm is missing" [[ -z "$out" ]] && pass "emits nothing when apm is not on PATH" || fail "should stay silent when apm is missing" # --------------------------------------------------------------------------- echo "" echo "--- install already current ---" # --------------------------------------------------------------------------- make_apm "[*] All dependencies are up-to-date" 0 rm -f "$WORK/update-was-called" out="$(run_hook)"; rc=$? [[ $rc -eq 0 ]] && pass "exits 0 when current" || fail "should exit 0 when current" [[ -z "$out" ]] && pass "emits nothing when current" || fail "should stay silent when current" [[ ! -f "$WORK/update-was-called" ]] && pass "does not run apm update when current" \ || fail "must not update when nothing is stale" # --------------------------------------------------------------------------- echo "" echo "--- stale, refresh succeeds ---" # --------------------------------------------------------------------------- make_apm "[!] 6 outdated dependencies found" 0 rm -f "$WORK/update-was-called" out="$(run_hook)"; rc=$? [[ $rc -eq 0 ]] && pass "exits 0 when stale" || fail "should exit 0 when stale" [[ -f "$WORK/update-was-called" ]] && pass "runs apm update when stale" || fail "should run apm update when stale" if echo "$out" | python3 -m json.tool > /dev/null 2>&1; then pass "emits valid JSON" [[ "$(echo "$out" | json_field hookEventName)" == "SessionStart" ]] \ && pass "declares hookEventName SessionStart" || fail "wrong hookEventName" [[ "$(echo "$out" | json_field reloadSkills)" == "True" ]] \ && pass "asks the host to reload skills after a successful refresh" || fail "reloadSkills should be true" grep -q "6 package" <<< "$(json_field additionalContext <<< "$out")" \ && pass "reports the stale package count" || fail "should report the count" # The lockfile rewrite is the surprising part of auto-updating; the notice has # to say so or a dirty worktree looks like something else went wrong. grep -q "apm.lock.yaml" <<< "$(json_field additionalContext <<< "$out")" \ && pass "warns that apm.lock.yaml was rewritten" || fail "should warn about the lockfile rewrite" else fail "emits valid JSON" fi # --------------------------------------------------------------------------- echo "" echo "--- lock advice follows the branch ---" # --------------------------------------------------------------------------- # ADR-0019: on the default branch the rewritten lock is a real update to commit or # discard; on a feature branch it is unrelated churn to discard. Outside a git # checkout (the fixture above) the neutral advice stands. advice_of() { json_field additionalContext <<< "$1"; } grep -q "commit it or discard it deliberately" <<< "$(advice_of "$out")" \ && pass "gives neutral lock advice outside a git checkout" \ || fail "outside a git checkout the advice should stay neutral" if command -v git > /dev/null 2>&1; then REPO="$WORK/repo" mkdir -p "$REPO" git -C "$REPO" init -q -b main git -C "$REPO" -c user.email=probe@example.invalid -c user.name=probe \ commit -q --allow-empty -m init touch "$REPO/apm.lock.yaml" # origin/HEAD is unset here — git writes it on clone and `git remote add` does # not — so the hook cannot know what the default branch is and must not guess. # It used to assume `main`, which is why the `master` case further down was a # live defect. out="$(run_hook_in "$REPO" "$REPO")" advice="$(advice_of "$out")" grep -q "commit it or discard it deliberately" <<< "$advice" \ && pass "with origin/HEAD unset, keeps the neutral lock advice" \ || fail "with origin/HEAD unset the advice should stay neutral: $advice" # Needles are the two DECISION phrases, not the bare words: the fixed prefix # of every notice already says "behind the remote default branch". grep -qE "this is (the default|a feature) branch, so" <<< "$advice" \ && fail "with origin/HEAD unset the hook must not claim to know which branch this is: $advice" \ || pass "with origin/HEAD unset, claims nothing about which branch this is" git -C "$REPO" update-ref refs/remotes/origin/main HEAD git -C "$REPO" symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main out="$(run_hook_in "$REPO" "$REPO")" grep -q "default branch, so commit it or discard it deliberately" <<< "$(advice_of "$out")" \ && pass "on main, says to commit or discard the lock deliberately" \ || fail "on main the advice should be commit-or-discard: $(advice_of "$out")" git -C "$REPO" checkout -q -b feature/x out="$(run_hook_in "$REPO" "$REPO")" advice="$(advice_of "$out")" grep -qF "feature branch, so discard it: git checkout -- apm.lock.yaml && apm install" <<< "$advice" \ && pass "on a feature branch, says to discard the lock and reinstall" \ || fail "on a feature branch the advice should be discard-and-install: $advice" grep -q "commit it" <<< "$advice" \ && fail "on a feature branch the advice must not suggest committing the lock" \ || pass "on a feature branch, does not suggest committing the lock" echo "$out" | python3 -m json.tool > /dev/null 2>&1 \ && pass "feature-branch notice is valid JSON" || fail "feature-branch notice broke the JSON" # A remote whose default branch is not `main` is honoured via origin/HEAD. git -C "$REPO" update-ref refs/remotes/origin/feature/x HEAD git -C "$REPO" symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/feature/x out="$(run_hook_in "$REPO" "$REPO")" grep -q "default branch, so commit it" <<< "$(advice_of "$out")" \ && pass "reads the default branch from origin/HEAD when it is set" \ || fail "should treat origin/HEAD's branch as the default: $(advice_of "$out")" # The regression the `${default_branch:-main}` fallback caused: a repo whose # default branch is `master`, with origin/HEAD unset (no clone wrote it), was # standing on its DEFAULT branch and was told to discard the lock as feature # churn. Assuming `main` is the only way to reach that verdict, so the case is # pinned on the branch name that makes the assumption wrong. MASTER_REPO="$WORK/master-repo" mkdir -p "$MASTER_REPO" git -C "$MASTER_REPO" init -q -b master git -C "$MASTER_REPO" -c user.email=probe@example.invalid -c user.name=probe \ commit -q --allow-empty -m init touch "$MASTER_REPO/apm.lock.yaml" out="$(run_hook_in "$MASTER_REPO" "$MASTER_REPO")" advice="$(advice_of "$out")" grep -qF "feature branch, so discard it" <<< "$advice" \ && fail "on master with origin/HEAD unset the hook assumed main and told the reader to discard a real lock update: $advice" \ || pass "on master with origin/HEAD unset, does not misread the default branch as a feature branch" grep -q "commit it or discard it deliberately" <<< "$advice" \ && pass "on master with origin/HEAD unset, falls back to the neutral lock advice" \ || fail "on master with origin/HEAD unset the advice should be neutral: $advice" else echo " (git not on PATH — branch-specific advice cases not run)" fi # --------------------------------------------------------------------------- echo "" echo "--- stale, refresh fails ---" # --------------------------------------------------------------------------- make_apm "[!] 3 outdated dependencies found" 1 out="$(run_hook)"; rc=$? [[ $rc -eq 0 ]] && pass "exits 0 when the refresh fails" || fail "must never fail the session start" if echo "$out" | python3 -m json.tool > /dev/null 2>&1; then pass "emits valid JSON on failure" [[ "$(echo "$out" | json_field reloadSkills)" == "False" ]] \ && pass "does not ask for a skill reload when nothing was deployed" || fail "reloadSkills should be false" grep -q "apm update" <<< "$(json_field additionalContext <<< "$out")" \ && pass "tells the reader how to refresh by hand" || fail "should name the manual command" else fail "emits valid JSON on failure" fi # --------------------------------------------------------------------------- echo "" echo "--- unparseable count degrades instead of breaking the JSON ---" # --------------------------------------------------------------------------- make_apm "[!] lots of outdated dependencies found" 0 out="$(run_hook)" echo "$out" | python3 -m json.tool > /dev/null 2>&1 \ && pass "still emits valid JSON when the count cannot be parsed" || fail "JSON broke on an unparseable count" # --------------------------------------------------------------------------- echo "" echo "--- anchors on the project root, not the session cwd ---" # --------------------------------------------------------------------------- # `[[ -f apm.lock.yaml ]]` resolves against the cwd, and a session started in a # subdirectory of an apm-consuming repo therefore no-opped silently — and would # have run `apm outdated`/`apm update` against that wrong directory had the # guard passed. Claude Code exports CLAUDE_PROJECT_DIR for SessionStart hooks, # so that is the anchor; the cwd is only the fallback. ELSEWHERE="$WORK/elsewhere" mkdir -p "$ELSEWHERE" rm -f "$ELSEWHERE/apm.lock.yaml" make_apm "[!] 6 outdated dependencies found" 0 rm -f "$WORK/update-was-called" "$WORK/apm-cwd" out="$(run_hook_in "$ELSEWHERE" "$WORK")" [[ -f "$WORK/update-was-called" ]] \ && pass "finds the lockfile via CLAUDE_PROJECT_DIR when the cwd is elsewhere" \ || fail "a session started in a subdirectory must still see the project's lockfile" [[ "$(cat "$WORK/apm-cwd" 2>/dev/null)" == "$WORK" ]] \ && pass "runs apm in the directory the guard checked, not the cwd" \ || fail "apm ran in '$(cat "$WORK/apm-cwd" 2>/dev/null)' — must run in the resolved project directory" grep -q "6 package" <<< "$(json_field additionalContext <<< "$out")" \ && pass "reports the count found via CLAUDE_PROJECT_DIR" || fail "should report the count" # The fallback is not cosmetic: a host that installed this plugin natively sets # no CLAUDE_PROJECT_DIR, and the hook must stay inert-but-harmless there rather # than erroring on an unset variable (the script runs under `set -u`). rm -f "$WORK/update-was-called" "$WORK/apm-cwd" out="$(run_hook_in "$WORK" "-")" [[ -f "$WORK/update-was-called" ]] \ && pass "falls back to the cwd when CLAUDE_PROJECT_DIR is unset" \ || fail "must still work with no CLAUDE_PROJECT_DIR in the environment" [[ "$(cat "$WORK/apm-cwd" 2>/dev/null)" == "$WORK" ]] \ && pass "runs apm in the cwd under the fallback" \ || fail "apm ran in '$(cat "$WORK/apm-cwd" 2>/dev/null)' — should be the cwd" rm -f "$WORK/update-was-called" "$WORK/apm-cwd" out="$(run_hook_in "$ELSEWHERE" "$ELSEWHERE")"; rc=$? [[ $rc -eq 0 ]] && pass "exits 0 when neither the project dir nor the cwd has a lockfile" \ || fail "should exit 0 when there is no lockfile anywhere" [[ -z "$out" ]] && pass "stays silent when neither the project dir nor the cwd has a lockfile" \ || fail "should stay silent when there is no lockfile anywhere" [[ ! -f "$WORK/update-was-called" ]] \ && pass "does not run apm update when there is no lockfile anywhere" \ || fail "must not touch a project that does not use apm" # --------------------------------------------------------------------------- echo "" echo "--- which apm: repo-pinned uv, else PATH, else nothing (ADR-0034) ---" # --------------------------------------------------------------------------- # Seam A: every binary the hook may call is a fake first on a PATH that holds # nothing else of interest. The machine's real uv and apm must not leak into # these cases — a real uv would make "pin but no uv" untestable — so PATH is # built from a whitelist of the system tools the hook and the fakes need. TOOLS="$(mktemp -d)" UV_BIN="$(mktemp -d)" PIN_BIN="$(mktemp -d)" PATH_APM_BIN="$(mktemp -d)" PINNED="$(mktemp -d)" trap 'rm -rf "$FAKE_BIN" "$WORK" "$TOOLS" "$UV_BIN" "$PIN_BIN" "$PATH_APM_BIN" "$PINNED" "${PROBE:-}"' EXIT for tool in bash grep timeout git cat touch head; do src="$(command -v "$tool" || true)" [[ -n "$src" ]] && ln -s "$src" "$TOOLS/$tool" done # A fake apm at $1 that records, under $2, which phases ran. $3 is the # `apm outdated` line, $4 the `apm update` exit code, $5 the version string. make_fake_apm() { local bin_dir="$1" tag="$2" outdated_line="$3" update_exit="$4" version="$5" cat > "$bin_dir/apm" << EOF #!/usr/bin/env bash echo "\$*" >> "$WORK/$tag-calls" case "\$1" in --version) printf '%s\n' "$version"; exit 0 ;; outdated) cat "$WORK/$tag-outdated.txt"; exit 0 ;; update) exit $update_exit ;; esac exit 0 EOF printf '%s\n' "$outdated_line" > "$WORK/$tag-outdated.txt" chmod +x "$bin_dir/apm" } # The fake uv logs every invocation verbatim and only knows `run`: anything # else exits 2. For `run` it skips uv's own options up to the `apm` argument # and execs the pinned fake apm, which is NOT on PATH — so the pinned apm is # reachable only through `uv run`. cat > "$UV_BIN/uv" << EOF #!/usr/bin/env bash printf '%s\n' "\$*" >> "$WORK/uv-calls" [[ "\${1:-}" == run ]] || exit 2 [[ -f "$WORK/uv-run-fails" ]] && exit 1 shift while [[ \$# -gt 0 && "\$1" != apm ]]; do case "\$1" in --project) shift 2 ;; *) shift ;; esac done [[ "\${1:-}" == apm ]] || exit 2 shift exec "$PIN_BIN/apm" "\$@" EOF chmod +x "$UV_BIN/uv" # The pin: a pyproject.toml naming apm-cli plus a uv.lock, as ADR-0034 lays out. cat > "$PINNED/pyproject.toml" << 'EOF' [project] name = "consumer" version = "0" requires-python = ">=3.11" [tool.uv] package = false [dependency-groups] dev = ["apm-cli==0.39.3"] EOF touch "$PINNED/uv.lock" "$PINNED/apm.lock.yaml" # A synced project environment. Without one the hook must not call uv at all. mkdir -p "$PINNED/.venv" STALE="[!] 4 outdated dependencies found" CURRENT="[*] All dependencies are up-to-date" V_NEW="Agent Package Manager (APM) CLI version 0.39.3" reset_calls() { rm -f "$WORK"/uv-calls "$WORK"/pin-calls "$WORK"/path-calls; } calls_of() { cat "$WORK/$1-calls" 2>/dev/null || true; } # $1: space-separated PATH components drawn from uv, apm. Always ends in TOOLS. run_pinned() { local p="" part for part in $1; do case "$part" in uv) p+="$UV_BIN:" ;; apm) p+="$PATH_APM_BIN:" ;; esac done (cd "$PINNED" && env -u CLAUDE_PROJECT_DIR -u UV_PROJECT_ENVIRONMENT PATH="${p}${RUN_TOOLS:-$TOOLS}" bash "$HOOK" 2>/dev/null) } ctx_of() { json_field additionalContext <<< "$1" 2>/dev/null || true; } # Every recorded uv call must be `uv run` against the project, frozen, and with # syncing off: a SessionStart hook must never install into the environment. assert_uv_calls_run_only() { local label="$1" n=0 bad=0 line while IFS= read -r line; do [[ -n "$line" ]] || continue n=$((n + 1)) [[ "$line" == "run "* ]] || bad=1 [[ " $line " == *" sync "* ]] && bad=1 [[ " $line " == *" --frozen "* && " $line " == *" --no-sync "* && " $line " == *" --offline "* ]] || bad=1 [[ " $line " == *" --project $PINNED "* ]] || bad=1 done < <(calls_of uv) if [[ $n -eq 0 ]]; then fail "$label: expected uv to be called at least once, it was not" elif [[ $bad -eq 0 ]]; then pass "$label: all $n uv call(s) are \`uv run --project --frozen --no-sync --offline\`, none is a sync" else fail "$label: uv was called with something other than a frozen no-sync \`run\`: $(tr '\n' '|' <<< "$(calls_of uv)")" fi } # --- pin plus uv: uses `uv run`, for both the check and the update --- make_fake_apm "$PIN_BIN" pin "$STALE" 1 "$V_NEW" make_fake_apm "$PATH_APM_BIN" path "$STALE" 1 "$V_NEW" reset_calls out="$(run_pinned "uv apm")"; rc=$? [[ $rc -eq 0 ]] && pass "pin + uv: exits 0" || fail "pin + uv: exit $rc" grep -q "^outdated" <<< "$(calls_of pin)" && grep -q "^update" <<< "$(calls_of pin)" \ && pass "pin + uv: runs the outdated check and the update through \`uv run\`" \ || fail "pin + uv: the pinned apm should see outdated and update, saw: $(calls_of pin | tr '\n' '|')" [[ -z "$(calls_of path)" ]] && pass "pin + uv: never touches the PATH apm" \ || fail "pin + uv: PATH apm was called: $(calls_of path | tr '\n' '|')" grep -qF "Run: uv run apm update --yes" <<< "$(ctx_of "$out")" \ && pass "pin + uv: the failed-refresh advice names \`uv run apm\`" \ || fail "pin + uv: advice should name uv run apm: $(ctx_of "$out")" assert_uv_calls_run_only "pin + uv, stale" # --- stale and current on the uv path --- make_fake_apm "$PIN_BIN" pin "$STALE" 0 "$V_NEW" reset_calls out="$(run_pinned "uv")" [[ "$(json_field reloadSkills <<< "$out" 2>/dev/null)" == "True" ]] \ && grep -q "4 package" <<< "$(ctx_of "$out")" \ && pass "uv path, stale: refreshes and reports the count" \ || fail "uv path, stale: expected a successful-refresh notice, got: $out" assert_uv_calls_run_only "uv path, stale" make_fake_apm "$PIN_BIN" pin "$CURRENT" 0 "$V_NEW" reset_calls out="$(run_pinned "uv")"; rc=$? [[ $rc -eq 0 && -z "$out" ]] && pass "uv path, current: silent, exit 0" \ || fail "uv path, current: expected silence, got rc=$rc: $out" grep -q "^update" <<< "$(calls_of pin)" && fail "uv path, current: must not update" \ || pass "uv path, current: does not update" assert_uv_calls_run_only "uv path, current" # A feature branch's discard advice names the binary that will reinstall. git -C "$PINNED" init -q -b main git -C "$PINNED" -c user.email=probe@example.invalid -c user.name=probe commit -q --allow-empty -m init git -C "$PINNED" update-ref refs/remotes/origin/main HEAD git -C "$PINNED" symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main git -C "$PINNED" checkout -q -b feature/y make_fake_apm "$PIN_BIN" pin "$STALE" 0 "$V_NEW" reset_calls out="$(run_pinned "uv")" grep -qF "git checkout -- apm.lock.yaml && uv run apm install" <<< "$(ctx_of "$out")" \ && pass "uv path, feature branch: the discard advice names \`uv run apm install\`" \ || fail "uv path, feature branch: advice should name uv run apm install: $(ctx_of "$out")" rm -rf "$PINNED/.git" # --- pinned apm too old (an unsynced env falls through to an old apm) --- make_fake_apm "$PIN_BIN" pin "$CURRENT" 0 "Agent Package Manager (APM) CLI version 0.28.0" reset_calls out="$(run_pinned "uv")"; rc=$? [[ $rc -eq 0 ]] && pass "uv path, apm 0.28.0: exits 0" || fail "uv path, apm 0.28.0: exit $rc" grep -q "^outdated" <<< "$(calls_of pin)" && fail "uv path, apm 0.28.0: ran the outdated check on a too-old apm" \ || pass "uv path, apm 0.28.0: runs no outdated check" grep -qF "\`uv run apm\` is older than apm 0.39.2" <<< "$(ctx_of "$out")" \ && grep -qF "Run: uv sync --frozen" <<< "$(ctx_of "$out")" \ && pass "uv path, apm 0.28.0: prints the fixed too-old line naming \`uv run apm\`" \ || fail "uv path, apm 0.28.0: expected the uv too-old line, got: $out" assert_uv_calls_run_only "uv path, too old" # --- pin but no uv: falls back to the PATH apm --- make_fake_apm "$PIN_BIN" pin "$STALE" 0 "$V_NEW" make_fake_apm "$PATH_APM_BIN" path "$STALE" 1 "$V_NEW" reset_calls out="$(run_pinned "apm")"; rc=$? [[ $rc -eq 0 ]] && pass "pin, no uv: exits 0" || fail "pin, no uv: exit $rc" grep -q "^outdated" <<< "$(calls_of path)" && grep -q "^update" <<< "$(calls_of path)" \ && pass "pin, no uv: falls back to the PATH apm for the check and the update" \ || fail "pin, no uv: PATH apm should run, saw: $(calls_of path | tr '\n' '|')" [[ -z "$(calls_of pin)" ]] && pass "pin, no uv: the pinned apm is not reached" \ || fail "pin, no uv: pinned apm ran without uv" ctx="$(ctx_of "$out")" grep -qF "Run: apm update --yes" <<< "$ctx" && ! grep -qF "uv run" <<< "$ctx" \ && pass "pin, no uv: advice names the bare \`apm\`, not \`uv run apm\`" \ || fail "pin, no uv: advice should name apm only: $ctx" # --- pin declared but no uv.lock: `--frozen` has nothing to run from --- rm -f "$PINNED/uv.lock" reset_calls out="$(run_pinned "uv apm")" [[ -z "$(calls_of uv)" ]] && grep -q "^outdated" <<< "$(calls_of path)" \ && pass "pin without uv.lock: does not call uv, uses the PATH apm" \ || fail "pin without uv.lock: expected PATH apm only, uv saw: $(calls_of uv | tr '\n' '|')" touch "$PINNED/uv.lock" # --- no pin, with a PATH apm: uv on PATH is ignored --- mv "$PINNED/pyproject.toml" "$PINNED/pyproject.toml.off" make_fake_apm "$PATH_APM_BIN" path "$STALE" 0 "$V_NEW" reset_calls out="$(run_pinned "uv apm")" [[ -z "$(calls_of uv)" ]] && pass "no pin: never calls uv even when it is on PATH" \ || fail "no pin: uv was called: $(calls_of uv | tr '\n' '|')" grep -q "^update" <<< "$(calls_of path)" && [[ "$(json_field reloadSkills <<< "$out" 2>/dev/null)" == "True" ]] \ && pass "no pin, PATH path, stale: refreshes through the PATH apm" \ || fail "no pin, PATH path, stale: expected a refresh via PATH apm, got: $out" make_fake_apm "$PATH_APM_BIN" path "$CURRENT" 0 "$V_NEW" reset_calls out="$(run_pinned "uv apm")"; rc=$? [[ $rc -eq 0 && -z "$out" ]] && ! grep -q "^update" <<< "$(calls_of path)" \ && pass "no pin, PATH path, current: silent, no update" \ || fail "no pin, PATH path, current: expected silence, got rc=$rc: $out" # A pyproject.toml that does not mention apm-cli is not a pin. printf '[project]\nname = "other"\ndependencies = ["apm-client-lib>=1"]\n' > "$PINNED/pyproject.toml" make_fake_apm "$PATH_APM_BIN" path "$CURRENT" 0 "$V_NEW" reset_calls run_pinned "uv apm" > /dev/null [[ -z "$(calls_of uv)" ]] && pass "a pyproject.toml without apm-cli is not read as a pin" \ || fail "apm-client-lib was mistaken for an apm-cli pin" rm -f "$PINNED/pyproject.toml" mv "$PINNED/pyproject.toml.off" "$PINNED/pyproject.toml" # --- no apm at all: silent, exit 0, with or without the pin --- reset_calls out="$(run_pinned "")"; rc=$? [[ $rc -eq 0 && -z "$out" ]] && pass "no uv, no apm: silent, exit 0" \ || fail "no uv, no apm: expected silence, got rc=$rc: $out" # --- PATH apm below 0.39.2: fixed too-old line, no outdated check --- for v in 0.28.0 0.39.1 "no version here"; do make_fake_apm "$PATH_APM_BIN" path "$STALE" 0 "Agent Package Manager (APM) CLI version $v" want="\`apm\` on PATH is older than apm 0.39.2" if [[ "$v" == "no version here" ]]; then make_fake_apm "$PATH_APM_BIN" path "$STALE" 0 "$v" want="Could not read the version of \`apm\` on PATH" fi reset_calls out="$(run_pinned "apm")"; rc=$? ctx="$(ctx_of "$out")" if [[ $rc -eq 0 ]] && ! grep -qE "^(outdated|update)" <<< "$(calls_of path)" \ && grep -qF "$want" <<< "$ctx" \ && [[ "$(json_field reloadSkills <<< "$out" 2>/dev/null)" == "False" ]]; then pass "PATH apm reporting '$v': fixed notice ($want), no outdated check, no update" else fail "PATH apm reporting '$v': expected the too-old line and no outdated call; rc=$rc calls=$(calls_of path | tr '\n' '|') out=$out" fi done grep -qF "uv run" <<< "$ctx" && fail "PATH too-old line must not name uv run: $ctx" \ || pass "PATH too-old line names the bare apm only" # The boundary is inclusive: 0.39.2 is new enough, and so is a later minor. for v in 0.39.2 0.40.0 1.0.0; do make_fake_apm "$PATH_APM_BIN" path "$STALE" 0 "Agent Package Manager (APM) CLI version $v" reset_calls run_pinned "apm" > /dev/null grep -q "^outdated" <<< "$(calls_of path)" \ && pass "PATH apm $v: new enough, runs the outdated check" \ || fail "PATH apm $v: should be accepted as new enough" done # --- pin and uv, but no project environment: never call uv --- # `uv run --no-sync` would create an empty .venv in the consumer's repo. rm -rf "$PINNED/.venv" make_fake_apm "$PIN_BIN" pin "$STALE" 0 "$V_NEW" make_fake_apm "$PATH_APM_BIN" path "$STALE" 0 "$V_NEW" reset_calls out="$(run_pinned "uv apm")"; rc=$? [[ $rc -eq 0 ]] && grep -qF "its environment has not been synced" <<< "$(ctx_of "$out")" \ && grep -qF "Run: uv sync --frozen" <<< "$(ctx_of "$out")" \ && pass "pin + uv, no .venv: prints the fixed not-synced notice" \ || fail "pin + uv, no .venv: expected the not-synced notice, got rc=$rc: $out" [[ -z "$(calls_of uv)" && -z "$(calls_of path)" ]] \ && pass "pin + uv, no .venv: calls neither uv nor the PATH apm" \ || fail "pin + uv, no .venv: uv saw '$(calls_of uv | tr '\n' '|')', PATH apm saw '$(calls_of path | tr '\n' '|')'" [[ ! -e "$PINNED/.venv" ]] && pass "pin + uv, no .venv: creates no .venv" \ || fail "pin + uv, no .venv: a .venv appeared in the project" # UV_PROJECT_ENVIRONMENT relocates the environment; an existing one there counts. ALT_ENV="$WORK/alt-env" mkdir -p "$ALT_ENV" reset_calls out="$(cd "$PINNED" && env -u CLAUDE_PROJECT_DIR UV_PROJECT_ENVIRONMENT="$ALT_ENV" PATH="$UV_BIN:$TOOLS" bash "$HOOK" 2>/dev/null)" grep -q "^outdated" <<< "$(calls_of pin)" \ && pass "UV_PROJECT_ENVIRONMENT pointing at an existing env: takes the uv path" \ || fail "UV_PROJECT_ENVIRONMENT should satisfy the environment check, got: $out" reset_calls out="$(cd "$PINNED" && env -u CLAUDE_PROJECT_DIR UV_PROJECT_ENVIRONMENT="$WORK/no-such-env" PATH="$UV_BIN:$TOOLS" bash "$HOOK" 2>/dev/null)" [[ -z "$(calls_of uv)" ]] && grep -qF "has not been synced" <<< "$(ctx_of "$out")" \ && pass "UV_PROJECT_ENVIRONMENT pointing at nothing: not-synced notice, no uv call" \ || fail "UV_PROJECT_ENVIRONMENT pointing at nothing should not call uv, got: $out" mkdir -p "$PINNED/.venv" # --- pin and uv, but `uv run` itself fails --- for how in "uv run exits non-zero" "no pinned apm to exec"; do make_fake_apm "$PIN_BIN" pin "$STALE" 0 "$V_NEW" if [[ "$how" == "uv run exits non-zero" ]]; then touch "$WORK/uv-run-fails"; else rm -f "$PIN_BIN/apm"; fi reset_calls out="$(run_pinned "uv")"; rc=$? ctx="$(ctx_of "$out")" [[ $rc -eq 0 ]] && grep -qF "Could not read the version of \`uv run apm\` (it failed or timed out)" <<< "$ctx" \ && ! grep -qF "not synced" <<< "$ctx" \ && pass "pin + uv, $how: exits 0 with the fixed unreadable-version notice, not the not-synced one" \ || fail "pin + uv, $how: expected the unreadable-version notice, got rc=$rc: $out" assert_uv_calls_run_only "pin + uv, $how" rm -f "$WORK/uv-run-fails" done # --- no timeout binary: nothing can be bounded, so stay silent --- NO_TO="$WORK/tools-no-timeout" G_TO="$WORK/tools-gtimeout" mkdir -p "$NO_TO" "$G_TO" for tool in bash grep git cat touch head; do [[ -e "$TOOLS/$tool" ]] && ln -s "$(readlink "$TOOLS/$tool")" "$NO_TO/$tool" && ln -s "$(readlink "$TOOLS/$tool")" "$G_TO/$tool" done ln -s "$(readlink "$TOOLS/timeout")" "$G_TO/gtimeout" make_fake_apm "$PATH_APM_BIN" path "$STALE" 0 "$V_NEW" reset_calls out="$(RUN_TOOLS="$NO_TO" run_pinned "apm")"; rc=$? [[ $rc -eq 0 && -z "$out" && -z "$(calls_of path)" ]] \ && pass "no timeout or gtimeout on PATH: silent, exit 0, apm not called" \ || fail "no timeout binary: expected silence and no apm call, got rc=$rc calls=$(calls_of path | tr '\n' '|') out=$out" reset_calls out="$(RUN_TOOLS="$G_TO" run_pinned "apm")" grep -q "^update" <<< "$(calls_of path)" && [[ "$(json_field reloadSkills <<< "$out" 2>/dev/null)" == "True" ]] \ && pass "only gtimeout on PATH (Homebrew coreutils on macOS): uses it and refreshes" \ || fail "gtimeout should stand in for timeout, got calls=$(calls_of path | tr '\n' '|') out=$out" # --- hostile command output never reaches the advice text --- # Every advice string is a fixed literal; only a digit-checked count is # spliced in. Output stuffed with ANSI escapes, command substitutions, # backticks, separators and quotes must leave no trace in what is emitted. HOSTILE=$'\e[31m[!] 7 outdated dependencies found\e[0m $(touch '"$WORK"'/pwned) `touch '"$WORK"'/pwned2`; rm -rf / ; "}]}\\ \x01' for route in uv apm; do if [[ "$route" == uv ]]; then make_fake_apm "$PIN_BIN" pin "$HOSTILE" 1 "$V_NEW"$'\n\e[0m$(id) `id`;' else mv "$PINNED/pyproject.toml" "$PINNED/pyproject.toml.off" make_fake_apm "$PATH_APM_BIN" path "$HOSTILE" 1 "$V_NEW"$'\n\e[0m$(id) `id`;' fi reset_calls out="$(run_pinned "$route")"; rc=$? ctx="$(ctx_of "$out")" if [[ $rc -eq 0 ]] && echo "$out" | python3 -m json.tool > /dev/null 2>&1 && [[ -n "$ctx" ]]; then pass "hostile output via $route: still exits 0 with valid JSON" else fail "hostile output via $route: rc=$rc, output not valid JSON: $(cat -v <<< "$out")" fi leaked="" for needle in $'\e' '$(' 'pwned' 'rm -rf' '\\' $'\x01' '}]}' 'id`'; do grep -qF -- "$needle" <<< "$out" && leaked+="[$needle]" done [[ -z "$leaked" ]] && pass "hostile output via $route: none of it reaches the emitted text" \ || fail "hostile output via $route: leaked $(cat -v <<< "$leaked") into: $(cat -v <<< "$out")" [[ ! -e "$WORK/pwned" && ! -e "$WORK/pwned2" ]] && pass "hostile output via $route: nothing in it was executed" \ || fail "hostile output via $route: a substitution in apm's output was executed" expected="apm install is 7 package(s) behind the remote default branch and the automatic refresh failed. Deployed skills and agents may be stale. Run: apm update --yes" [[ "$route" == uv ]] && expected="${expected%apm update --yes}uv run apm update --yes" [[ "$ctx" == "$expected" ]] \ && pass "hostile output via $route: the notice is exactly the fixed literal plus the digit-checked count" \ || fail "hostile output via $route: notice differs from the fixed literal: $(cat -v <<< "$ctx")" [[ -f "$PINNED/pyproject.toml.off" ]] && mv "$PINNED/pyproject.toml.off" "$PINNED/pyproject.toml" done # --------------------------------------------------------------------------- echo "" echo "--- hooks.json wiring ---" # --------------------------------------------------------------------------- # apm resolves script paths relative to the package root, and `apm pack` keeps # only *.json from .apm/hooks/ — so a ${CLAUDE_PLUGIN_ROOT}/hooks/... reference # points at a directory the script never reaches. It must be .apm/-relative. referenced="$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d["hooks"]["SessionStart"][0]["hooks"][0]["command"])' "$HOOKS_JSON")" [[ "$referenced" == '${CLAUDE_PLUGIN_ROOT}/.apm/hooks/check-apm-current.sh' ]] \ && pass "hooks.json references the script at its .apm/ path" \ || fail "hooks.json references '$referenced' — must be \${CLAUDE_PLUGIN_ROOT}/.apm/hooks/check-apm-current.sh" [[ -x "$HOOK" ]] && pass "hook script is executable" || fail "hook script must be executable" matcher="$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d["hooks"]["SessionStart"][0]["matcher"])' "$HOOKS_JSON")" [[ "$matcher" == "startup" ]] && pass "fires on startup only" \ || fail "matcher is '$matcher' — resume/clear/compact would re-run this every compaction" # The host's timeout must strictly exceed everything the script can spend, or # the host SIGKILLs the hook mid-`apm update` and leaves a half-redeployed # .claude/skills/ with no notice emitted — the silent failure this hook exists # to prevent. Asserted as an invariant over both files rather than against a # literal, so raising either internal `timeout` without raising the host budget # fails here instead of reintroducing the gap quietly. # # Every `timeout N` or `"$to" N` in the script counts (the hook resolves # `timeout` or `gtimeout` into $to), comments included: a stray "timeout # 300" in prose only makes this stricter, which is the safe direction. script_budget=0 timeout_count=0 while read -r n; do [[ -n "$n" ]] || continue script_budget=$((script_budget + n)) timeout_count=$((timeout_count + 1)) done < <(grep -oE '(\btimeout|"\$to") [0-9]+\b' "$HOOK" | grep -oE '[0-9]+$') hook_timeout="$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d["hooks"]["SessionStart"][0]["hooks"][0]["timeout"])' "$HOOKS_JSON")" if [[ $timeout_count -eq 0 ]]; then fail "found no 'timeout N' or '\"\$to\" N' in $HOOK — the budget assertion below would be vacuous" else pass "parsed $timeout_count internal timeout(s) totalling ${script_budget}s from the hook script" [[ $hook_timeout -gt $script_budget ]] \ && pass "hooks.json timeout (${hook_timeout}s) exceeds the script's own budget (${script_budget}s)" \ || fail "hooks.json timeout is ${hook_timeout}s but the script can spend ${script_budget}s — the host would SIGKILL it mid-update" fi # --------------------------------------------------------------------------- echo "" echo "--- the greped phrase, against the real apm ---" # --------------------------------------------------------------------------- # Everything above mocks `apm`, so an apm release that reworded its summary line # would revert this hook to its pre-fix behaviour with a fully green suite. # `apm outdated` has no --json/machine-readable flag (verified against 0.28.0), # so the phrase match cannot be replaced — it can only be pinned. # # The probe stages a genuinely outdated dependency with no network: a local git # repo stands in for the upstream, reached through `url..insteadOf` # rewrites of every URL spelling apm may build (it picks ssh or https depending # on ambient auth config, so all three are mapped). apm appends `.git` to the # repo URL, which is why the local repo is named `upstream.git` and the rewrite # target omits the suffix. HOME is redirected so no user-level apm cache or # credential state can influence the result. # # The genuine output is then replayed into the real hook through the mock, so # what is asserted is the hook's own matching logic against real apm text — # no pattern is duplicated here to drift out of sync. SKIP_REASON="" if ! command -v apm > /dev/null 2>&1 || ! command -v git > /dev/null 2>&1; then SKIP_REASON="SKIP: apm and git are both required to verify the hook's phrase match against real \`apm outdated\` output — everything above ran, this axis did not" echo " $SKIP_REASON" else PROBE="$(mktemp -d)" trap 'rm -rf "$FAKE_BIN" "$WORK" "$TOOLS" "$UV_BIN" "$PIN_BIN" "$PATH_APM_BIN" "$PINNED" "$PROBE"' EXIT UPSTREAM="$PROBE/upstream.git" git init -q "$UPSTREAM" git -C "$UPSTREAM" -c user.email=probe@example.invalid -c user.name=probe \ commit -q --allow-empty -m one LOCKED_SHA="$(git -C "$UPSTREAM" rev-parse HEAD)" git -C "$UPSTREAM" -c user.email=probe@example.invalid -c user.name=probe \ commit -q --allow-empty -m two BRANCH="$(git -C "$UPSTREAM" symbolic-ref --short HEAD)" { for repo in alpha beta; do printf '[url "%s/upstream"]\n' "$PROBE" printf '\tinsteadOf = git@apm-probe.invalid:probe/%s\n' "$repo" printf '\tinsteadOf = https://apm-probe.invalid/probe/%s\n' "$repo" printf '\tinsteadOf = ssh://git@apm-probe.invalid/probe/%s\n' "$repo" done } > "$PROBE/gitconfig" mkdir -p "$PROBE/consumer" "$PROBE/home" # $1 = how many stale dependencies to stage. Writes a lockfile and echoes what # the real `apm outdated` printed for it. real_apm_outdated() { local want="$1" repo { echo "lockfile_version: '1'" echo "generated_at: '2026-01-01T00:00:00+00:00'" echo "apm_version: 0.0.0" echo "dependencies:" for repo in $( [[ "$want" == 1 ]] && echo alpha || echo alpha beta ); do echo "- host: apm-probe.invalid" echo " name: probe-$repo" echo " package_type: apm_package" echo " repo_url: probe/$repo" echo " resolved_ref: $BRANCH" echo " resolved_commit: $LOCKED_SHA" echo " version: 1.0.0" done echo "deployments: []" } > "$PROBE/consumer/apm.lock.yaml" ( cd "$PROBE/consumer" && env HOME="$PROBE/home" \ GIT_CONFIG_GLOBAL="$PROBE/gitconfig" \ GIT_CONFIG_NOSYSTEM=1 \ GIT_TERMINAL_PROMPT=0 \ apm outdated 2>&1 ) } # Replay genuine output through the hook. A harness that stages nothing would # make every assertion below vacuously true, so the staged row is checked # first and a failure to stage is a FAIL, not a quiet pass. for want in 1 2; do genuine="$(real_apm_outdated "$want" || true)" if ! grep -q "outdated" <<< "$genuine"; then fail "probe staged no outdated dependency against the real apm (harness broken, not the hook): $(tr '\n' ' ' <<< "$genuine" | cut -c1-160)" continue fi printf '%s\n' "$genuine" > "$PROBE/genuine-$want.txt" cat > "$FAKE_BIN/apm" << EOF #!/usr/bin/env bash pwd > "$WORK/apm-cwd" case "\$1" in --version) echo "Agent Package Manager (APM) CLI version 0.39.3"; exit 0 ;; outdated) cat "$PROBE/genuine-$want.txt"; exit 0 ;; update) touch "$WORK/update-was-called"; exit 0 ;; esac exit 0 EOF chmod +x "$FAKE_BIN/apm" rm -f "$WORK/update-was-called" out="$(run_hook)" if [[ -n "$out" ]] && grep -q "$want package" <<< "$(json_field additionalContext 2>/dev/null <<< "$out")"; then pass "detects staleness in real \`apm outdated\` output and counts $want package(s)" else fail "real apm reported $want outdated dependency/dependencies but the hook did not act on it — apm reworded its summary line. Real output: $(tr '\n' ' ' < "$PROBE/genuine-$want.txt" | tail -c 120)" fi done fi # --------------------------------------------------------------------------- echo "" echo "Results: $PASS passed, $FAIL failed" [[ $FAIL -eq 0 ]] || exit 1 # A skip only after everything runnable has run and passed: the mocked axis is # still worth executing on a machine without apm, but the suite must not read # as green when the real-apm axis was not verified. run-tests.sh reports 77 as # SKIPPED and, at pre-push (--strict), as a setup error naming this reason. [[ -z "$SKIP_REASON" ]] || exit 77 exit 0