#!/usr/bin/env bash # SessionStart: keep an apm-consumed install level with its remote. # # Packages declared as unpinned git refs resolve against the remote default # branch, so the deployed .claude/skills/ and .claude/agents/ go stale the # moment anyone merges. The staleness bites when a session loads skills, which # is why this runs at SessionStart rather than off a git hook — a pull is # neither necessary nor sufficient for the install to have drifted. # # Refreshes in place and asks the host to re-scan, so the running session picks # the new content up without a restart. # # Inert in any project that does not consume packages through apm. set -uo pipefail # Anchor on the project root, not the session's cwd. Claude Code exports # CLAUDE_PROJECT_DIR for SessionStart hooks; a session opened in a subdirectory # would otherwise miss the lockfile, no-op silently, and — worse — run the apm # calls below against that wrong directory. Fall back to the cwd when the # variable is absent, which keeps the hook inert-but-harmless under a host that # does not set it. project_dir="${CLAUDE_PROJECT_DIR:-$PWD}" # No lockfile means nothing was installed through apm here — e.g. a host that # installed this plugin natively. Say nothing and cost nothing. [[ -f "$project_dir/apm.lock.yaml" ]] || exit 0 # Every apm call below is bounded, and stock macOS ships no `timeout`; Homebrew # coreutils installs it as `gtimeout`. Without either, nothing can be bounded, # so the hook stays silent on every path rather than risk holding the session # open — or misreporting an apm whose version it could not read. It is chosen # before the apm, so no notice is printed either. The budget test in # tests/test-apm-current-hook.sh sums every `"$to" N` and `timeout N` here. if command -v timeout > /dev/null 2>&1; then to=timeout elif command -v gtimeout > /dev/null 2>&1; then to=gtimeout else exit 0 fi # Choose the apm once, and use it for every call below (ADR-0034): # 1. the repo's own pin, run as `uv run`, when the project pins apm-cli AND # uv is on PATH; # 2. otherwise the `apm` on PATH; # 3. otherwise nothing: exit silently. # # "Pins apm-cli" means a pyproject.toml whose text carries a quoted apm-cli # requirement (`"apm-cli==0.39.3"`, `'apm_cli>=0.39'`, ...) AND a uv.lock next # to it. It is a text match, not a TOML parse: the hook must not depend on a # Python being on PATH, and a quoted `apm-cli` requirement string has no other # plausible meaning in a pyproject.toml. The uv.lock is required because # `--frozen` runs from the lock and has nothing to run without one; a pin with # no lock falls through to PATH apm and its version check. # # uv is only ever invoked as `uv run`, and with `--no-sync`: a plain `uv run` # syncs the environment first, which installs packages and can reach the # network, and a SessionStart hook must do neither. `--offline` closes the # remaining gap (uv fetching a Python). Even `--no-sync` creates an empty # .venv when none exists, so a project environment that is missing altogether # (`$UV_PROJECT_ENVIRONMENT`, else /.venv) gets a fixed "not synced" # notice and uv is never called. One that exists but was never synced has no # apm of its own, so `uv run` falls through to whatever apm is on PATH, and the # version check below catches an old one and tells the reader to sync. # # apm_label names the chosen binary in advice text. It selects between fixed # literals and is never built from command output. apm_cmd is never seeded # empty: every branch below either sets it or exits, which keeps its expansions # safe under `set -u` on bash 3.2 (tests/test-vale-wrap.sh scans for this). # Only ever emit fixed text plus a digit-checked count — never interpolate # command output into the JSON, which would need escaping this cannot do safely. emit() { printf '{"hookSpecificOutput":{"hookEventName":"SessionStart","reloadSkills":%s,"additionalContext":"%s"}}\n' "$1" "$2" } apm_label="" if [[ -f "$project_dir/pyproject.toml" && -f "$project_dir/uv.lock" ]] \ && grep -qiE "[\"']apm[-_.]cli[^a-z0-9_.-]" "$project_dir/pyproject.toml" 2> /dev/null \ && command -v uv > /dev/null 2>&1; then uv_env="${UV_PROJECT_ENVIRONMENT:-$project_dir/.venv}" [[ "$uv_env" == /* ]] || uv_env="$project_dir/$uv_env" if [[ ! -d "$uv_env" ]]; then emit false "This project pins apm with uv but its environment has not been synced, so the apm install was not checked for staleness. Run: uv sync --frozen" exit 0 fi apm_cmd=(uv run --project "$project_dir" --frozen --no-sync --offline apm) apm_label="uv" elif command -v apm > /dev/null 2>&1; then apm_cmd=(apm) apm_label="path" else exit 0 fi # Every apm call below must see the same directory the guard just checked — # `apm outdated` and `apm update` both resolve the lockfile from the cwd. cd "$project_dir" || exit 0 # apm older than 0.39.2 refuses a lockfile v4 and would then report it as up to # date, so its `outdated` verdict is worthless (ADR-0034). Below the minimum, or # when the version cannot be read at all, say so in a fixed line and skip the # check: a silent pass here is exactly the false "up to date" to avoid. Only the # first dotted triple is taken, and only its digits are compared. # # Returns 0 when new enough, 1 when the version was read and is too old, and 2 # when it could not be read (the call failed or timed out, or printed no # version), so the notice can say which. version_ok() { local version_output version version_output="$("$to" 15 "${apm_cmd[@]}" --version 2> /dev/null)" || return 2 version="$(grep -oE '[0-9]+\.[0-9]+\.[0-9]+' <<< "$version_output" | head -n 1)" [[ "$version" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]] || return 2 local -a have=("${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}") need=(0 39 2) local i for i in 0 1 2; do ((10#${have[i]} > need[i])) && return 0 ((10#${have[i]} < need[i])) && return 1 done return 0 } version_ok version_status=$? if [[ $version_status -ne 0 ]]; then if [[ "$apm_label" == "uv" && $version_status -eq 1 ]]; then emit false "\`uv run apm\` is older than apm 0.39.2, so the apm install was not checked for staleness (older apm refuses lockfile v4 and would report it as up to date). The project environment is probably not synced to its pin. Run: uv sync --frozen" elif [[ "$apm_label" == "uv" ]]; then emit false "Could not read the version of \`uv run apm\` (it failed or timed out), so the apm install was not checked for staleness. Check that this works: uv run apm --version, or run: uv sync --frozen" elif [[ $version_status -eq 1 ]]; then emit false "\`apm\` on PATH is older than apm 0.39.2, so the apm install was not checked for staleness (older apm refuses lockfile v4 and would report it as up to date). Upgrade the apm on PATH to 0.39.2 or later, or pin apm-cli in this project with uv." else emit false "Could not read the version of \`apm\` on PATH (it failed or timed out), so the apm install was not checked for staleness. Check that this works: apm --version" fi exit 0 fi # `apm outdated` exits 0 whether or not anything is stale, so the answer has to # come from its output. Measured ~0.7s against six remote refs on apm 0.28.0 # from PATH, and ~3.6s through `uv run` on 0.39.3; a hung remote must not hold # the session open. # # There is no --json/machine-readable flag on `apm outdated` (verified against # apm 0.28.0 and 0.39.3), so the phrase match is forced rather than chosen. Note the # singular: apm prints "1 outdated dependency found" when exactly one package is # behind, so matching only "dependencies" would silently miss a one-package # drift. tests/test-apm-current-hook.sh pins both spellings against the real apm. outdated_output="$("$to" 60 "${apm_cmd[@]}" outdated 2>&1)" || exit 0 grep -qE 'outdated dependenc(y|ies) found' <<< "$outdated_output" || exit 0 stale_count="$(grep -oE '[0-9]+ outdated dependenc(y|ies) found' <<< "$outdated_output" | grep -oE '^[0-9]+' || true)" [[ "$stale_count" =~ ^[0-9]+$ ]] || stale_count="some" # What to do with the rewritten lock depends on the branch (ADR-0019): on the # default branch it is a real update to commit or discard; on a feature branch it # is churn unrelated to the branch and should be discarded. The branch name only # selects between fixed strings and is never interpolated. Outside a git checkout, # or on a detached HEAD, the neutral advice stands. # # So does an UNSET origin/HEAD, which is the common state: git only writes it on # clone, and `git remote add` never does. The fallback here used to be `main`, # which is a guess, and it is wrong in exactly the repos that would notice — a # checkout whose default branch is `master` was told "this is a feature branch, # so discard it" while standing on its default branch, i.e. told to throw away a # real lock update. There is no cheap way to learn the remote's default without # the network, so nothing is asserted: the advice stays neutral and the reader # decides. lock_advice="commit it or discard it deliberately." current_branch="$(git symbolic-ref --short -q HEAD 2> /dev/null || true)" default_branch="$(git symbolic-ref --short -q refs/remotes/origin/HEAD 2> /dev/null || true)" default_branch="${default_branch#origin/}" if [[ -n "$current_branch" && -n "$default_branch" ]]; then if [[ "$current_branch" == "$default_branch" ]]; then lock_advice="this is the default branch, so commit it or discard it deliberately." else if [[ "$apm_label" == "uv" ]]; then lock_advice="this is a feature branch, so discard it: git checkout -- apm.lock.yaml && uv run apm install" else lock_advice="this is a feature branch, so discard it: git checkout -- apm.lock.yaml && apm install" fi fi fi manual_update="apm update --yes" [[ "$apm_label" == "uv" ]] && manual_update="uv run apm update --yes" if "$to" 300 "${apm_cmd[@]}" update --yes > /dev/null 2>&1; then emit true "apm install was ${stale_count} package(s) behind the remote default branch and has been refreshed automatically; skills and agents were redeployed and re-scanned. apm.lock.yaml has been rewritten and is now a modified file in the working tree - ${lock_advice}" else emit false "apm install is ${stale_count} package(s) behind the remote default branch and the automatic refresh failed. Deployed skills and agents may be stale. Run: ${manual_update}" fi exit 0