Files
holocron/tests/test-check-apm-agents-valid.sh
Defame1297 620f20b0fd refactor(kyberforge)!: merge skill-audit and agent-audit into factory-audit
Why

The two audit skills carried 1,724 lines of byte-identical duplication: the ADR-0020 boundary
resolver (1,061), vale-wrap.sh (526), the Vale style rules (44) and the Contributing-files parser
(93). Nothing shared them — they were held in sync by a 413-line pre-push gate and its 797-line
test suite. Sync-by-gate had already failed once: at 484357a the two parser copies drifted into
different spellings of the bullet loop while a docstring asserted they were identical. That drift
was behaviour-neutral and was re-unified by hand at 598a7c3, so the copies were identical at merge
time — but nothing had caught it, and the next drift need not be neutral.

Implementation Notes

Self-containment binds BETWEEN skills, not within one. The agentskills.io spec forbids reaching
across skill directories, which is why two separate skills needed embedded copies; two files inside
ONE skill may source a third. That is the whole reason the merge removes duplication rather than
relocating it.

The union of both bodies measured 1,532 words against BODY_MAX_WORDS=900, and only 211 of those
words were shared, so SKILL.md is a dispatch body. Step 0 resolves the flow from the target path
before any validation, and its table mirrors validate.sh's detection exactly: a directory holding
SKILL.md or a SKILL.md file (skill); a *.agent.md, or a .md directly under an agents/ directory
(agent); anything else stops without running a validator. Steps 1-3 live in
references/skill-flow.md and references/agent-flow.md, and gotchas that apply to one flow live in
that flow's file, since it is loaded on every invocation anyway. If validate.sh reports on the
other artifact type, the body restarts at Step 0.

Named factory-audit rather than forge-audit because forge is a live skill, and a family prefix that
matches a live sibling reads as ownership rather than membership.

The description carries one arrow per boundary target, because ADR-0020 resolves only the first
target after an arrow. It drops the quoted "audit this skill"-style phrases, which restated
"audited" in a second register (ADR-0020's duplicate-register rule). 241 characters, Gotchas 16%
of the body: no size SUGGESTIONs.

The boundary resolver stays embedded in two files rather than imported: a cache-installed plugin
cannot read outside its own directory, and the repo-root hook resolves via .pre-commit-hooks.yaml
where entry[0] is the only token pre-commit rewrites, so no single file is reachable by both.
tests/test-adr0020-contract.sh hashes both copies for byte-identity, and asserts validate.sh sources
the resolver and that no third copy exists.

The entry scripts classify the target from its resolved parent directory, so a bare agent filename
typed inside agents/ works; resolve SCRIPT_DIR CDPATH-safely; and exit 2 when a lib-*.sh is
missing, rather than dying with exit 1, the tier the flows relay as real findings.

The provenance run functions stash their findings code in KYBERFORGE_PROV_RC and
return 0, so validate-provenance.sh calls them UNTESTED. Testing a function's
status (`f || RC=$?`) disables errexit for its entire body, and no subshell or
`set -e` inside can re-arm it once the call sits in a condition context
(measured, both spellings). Their error paths use `exit`, which is unaffected
either way; this keeps errexit armed for anything added later.

Case 0's readability guard reads the file instead of asking `[[ -r ]]`. `-r` is
access(2), which answers yes for uid 0 even on a mode-000 file, and this repo's
dev environment is root -- so the guard could never fire where it exists to fire.
A read attempt is also the stricter question, catching EIO. This is the reasoning
scripts/check-vale-style-sync.sh carried before this commit deleted it; the
hazard did not go with it.

All three entry scripts are CDPATH-safe, vale-wrap.sh included: both of its cd sites are cleared,
the --config resolution and the directory-mirror walk, where an exported CDPATH would otherwise
print a decoy path into the -print0 stream and build the mirror from the decoy's files. The two
remaining bare cd calls take absolute paths, which CDPATH is never consulted for.

Impact

BREAKING: skill-audit and agent-audit no longer exist as invocable skills. kyberforge goes to
2.0.0 (catalog 0.4.7).

Check logic is unchanged: differential runs of the old and new validators across every skill and
agent produced byte-identical stdout, stderr and exit codes, and the reconstructed Python payloads
differ only in comments and the references/field-inventory.md -> agent-field-inventory.md rename.
One doctrine governs the tiers: exit 0 is audited and clean, exit 1 is audited with findings OR a
target present but unreadable, exit 2 is that nothing was audited at all. Edge paths DID change,
deliberately (full table in ADR-0025):
- a missing target exits 2 (never ran), not 1, under its own "does not exist" message; detection is
  by path shape, so a shape-matching path that is simply absent used to reach the validator and come
  back as a FAIL against a file that never existed;
- an unshaped target exits 2 under the generic "matches neither" message, and a directory with no
  SKILL.md under a third, distinct one -- three exit-2 messages, not one;
- a dangling symlink or a symlink loop stays exit 1: it is present but broken, which is a finding
  about the artifact rather than a usage error;
- a SKILL.md file path is audited as its skill directory instead of refused;
- a .md agent outside an agents/ directory is refused rather than audited;
- a missing script library, a missing python3, a missing PyYAML, and no argument at all each exit 2.
  validate-provenance.sh already exited 2 for the last two; validate.sh now matches it.

.pre-commit-hooks.yaml is a published contract consumed by external repos. Both hook IDs and both
files: regexes are unchanged; only entry: and description: moved.

scripts/check-vale-style-sync.sh (413), scripts/sync-vale-styles.sh (21),
tests/test-check-vale-style-sync.sh (797) and agent-audit/scripts/README.md (47) are deleted. The
checker made 17 assertions: 6 compared the two Vale copies and are moot; 10 are rehomed into
tests/test-vale-wrap.sh (case 0, cases 28-31, and the suite's Vale-absent skip); and the
cross-manifest files: agreement check, which selected hooks by entry: and so could not survive both
hooks sharing one, is ported as case 33 pairing hooks by id:. Cases 28, 30 and 33 carry mutation
self-tests; narrowing the local skill prefilter to 6 of 38 SKILL.md files now fails the suite.

Skills go 39 to 38. Pre-push goes 9 repo-authored hooks to 8.

ADR: 0025
BREAKING-CHANGE: the skill-audit and agent-audit skills are removed. Both flows are served by
  factory-audit, which auto-detects whether it was handed a skill directory or an agent file.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YR2CjVumUbEGWcMikcoXBD
2026-09-16 09:13:57 +00:00

283 lines
12 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
# Tests for scripts/check-apm-agents-valid.sh — the gate that runs factory-audit's
# validate.sh over the repo's REAL plugin-scope agent files. Since ADR-0025 merged
# skill-audit and agent-audit, that validate.sh is one auto-detecting entry point;
# every target this gate hands it is an agent file, so every run below takes the
# agent branch and sources lib-checks-agent.sh.
#
# Case 1 runs against the real repo. Every other case runs against a synthetic
# fixture, for the same reason scripts/check-scope-walkup-sync.sh's tests do: the
# RED cases have to mutate an agent file, and mutating the real tree from a test
# is not on.
#
# The point of case 1b is that case 1's exit 0 is EARNED. Exit 0 is also what
# this script would print if it validated nothing at all, which is the exact
# defect it exists to close — so the clean run's own count is asserted against
# the index rather than taken on trust.
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SCRIPT="$REPO_ROOT/scripts/check-apm-agents-valid.sh"
PASS=0
FAIL=0
pass() { echo " PASS: $1"; PASS=$((PASS + 1)); }
fail() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }
# validate.sh is a python3 program. Without python3 the script under test fails
# closed by design, which is correct behavior but makes every case here assert
# the same missing-dependency message instead of what it is meant to assert.
if ! command -v python3 >/dev/null 2>&1; then
echo "SKIP: python3 is not installed — factory-audit's validate.sh cannot run, so these cases would only re-assert the missing-dependency guard"
exit 77
fi
FIXTURES=()
cleanup() { [[ ${#FIXTURES[@]} -eq 0 ]] || rm -rf "${FIXTURES[@]}"; }
trap cleanup EXIT
# Per-run scratch dir for captured output. tests/run-tests.sh fans test scripts
# out concurrently, so a fixed path under the shared system temp directory is
# mutable state shared between two simultaneous runs.
RUN_TMP="$(mktemp -d)"
FIXTURES+=("$RUN_TMP")
# Builds a minimal REPO_ROOT: factory-audit's validator and the field inventory it
# reads at load time, plus one plugin carrying a valid agent file. The validator
# is no longer self-contained — ADR-0025 replaced the embedded resolver with a
# sourced lib-boundary-resolver.sh and moved the agent checks into
# lib-checks-agent.sh — so the fixture copies the two libraries the agent branch
# sources as well. Copying validate.sh alone would make every case below fail on
# a missing source file rather than on what it is meant to assert.
#
# The inventory is `agent-field-inventory.md`: factory-audit prefixes every
# flow-specific reference file with skill-/agent-, and validate.sh reads this one
# by that name at load time.
#
# The plugin's
# apm.yml needs a top-level `type:` line — that is the marker validate.sh's
# walk-up uses to resolve plugin scope, and without it the fixture would resolve
# to project scope and fail looking for a .github/agents counterpart.
#
# `pwd -P` because the script under test compares its REPO_ROOT against
# `git rev-parse --show-toplevel`, which is always physical. On a platform where
# the system temp dir is a symlink (macOS /tmp -> /private/tmp) a logical path
# would silently fail that equality and take the un-derived branch, quietly
# turning case 4 into a no-op.
make_fixture() {
local dir
dir="$(cd "$(mktemp -d)" && pwd -P)"
local fa="$dir/plugins/kyberforge/.apm/skills/factory-audit"
local src="$REPO_ROOT/plugins/kyberforge/.apm/skills/factory-audit"
mkdir -p "$fa/scripts" "$fa/references" "$dir/plugins/lint/.apm/agents"
cp "$src/scripts/validate.sh" \
"$src/scripts/lib-boundary-resolver.sh" \
"$src/scripts/lib-checks-agent.sh" \
"$fa/scripts/"
cp "$src/references/agent-field-inventory.md" "$fa/references/"
cat > "$dir/plugins/lint/apm.yml" <<'YAML'
name: lint
version: 0.0.1
type: hybrid
YAML
cat > "$dir/plugins/lint/.apm/agents/lint-runner.agent.md" <<'MD'
---
name: lint-runner
description: Runs a linter sweep over a target scope and reports findings back to the caller.
---
Run the linter over the scope the caller names and report what it found.
MD
echo "$dir"
}
# --- 1. Exits 0 against this repo's real agent files ---
echo ""
echo "--- exits 0 against this repo's real agent files ---"
if bash "$SCRIPT" "$REPO_ROOT" > "$RUN_TMP/clean.out" 2>&1; then
pass "exits 0 against this repo's four real plugin-scope agent files"
else
fail "exited non-zero against this repo's real (already-fixed) agent files"
sed 's/^/ /' "$RUN_TMP/clean.out"
fi
# --- 1b. That exit 0 was earned: the count matches the index, and is non-zero ---
echo ""
echo "--- the clean run's reported count matches git ls-files ---"
TRACKED_COUNT="$(git -C "$REPO_ROOT" ls-files -- 'plugins/*/.apm/agents/*.agent.md' | grep -c . || true)"
REPORTED_COUNT="$(sed -n 's/^APM agent validation passed: \([0-9]\{1,\}\) plugin-scope.*/\1/p' "$RUN_TMP/clean.out")"
if [[ -z "$REPORTED_COUNT" ]]; then
fail "the clean run printed no 'APM agent validation passed: N ...' summary line — the script's contract with this test is gone"
sed 's/^/ /' "$RUN_TMP/clean.out"
elif [[ "$TRACKED_COUNT" -eq 0 ]]; then
fail "git ls-files found 0 tracked agent files — this test's own expectation is broken, not the script's"
elif [[ "$REPORTED_COUNT" -ne "$TRACKED_COUNT" ]]; then
fail "the clean run validated $REPORTED_COUNT file(s) but $TRACKED_COUNT are tracked"
else
pass "validated $REPORTED_COUNT file(s), matching the $TRACKED_COUNT tracked in the index"
fi
# --- 2. An invalid agent file fails, and both the file and the reason are named ---
echo ""
echo "--- an invalid agent file fails, naming the file and the reason ---"
FIX2="$(make_fixture)"
FIXTURES+=("$FIX2")
# `tools:` is deliberately absent from field-inventory.md's apm-agent-allowlist:
# its value shape differs per harness and apm compile copies frontmatter verbatim
# to every target (ADR-0016).
python3 - "$FIX2/plugins/lint/.apm/agents/lint-runner.agent.md" <<'PY'
import sys
p = sys.argv[1]
s = open(p).read()
open(p, 'w').write(s.replace('---\n', '---\ntools: Read, Write\n', 1))
PY
if bash "$SCRIPT" "$FIX2" > "$RUN_TMP/invalid.out" 2>&1; then
fail "an agent file with a non-allowlisted frontmatter field still exited 0"
sed 's/^/ /' "$RUN_TMP/invalid.out"
elif ! grep -q 'plugins/lint/\.apm/agents/lint-runner\.agent\.md' "$RUN_TMP/invalid.out"; then
fail "failed as expected but did not name the offending file"
sed 's/^/ /' "$RUN_TMP/invalid.out"
elif ! grep -q "field 'tools' is not in the vendor-neutral APM agent allowlist" "$RUN_TMP/invalid.out"; then
fail "failed as expected and named the file but did not carry validate.sh's reason through"
sed 's/^/ /' "$RUN_TMP/invalid.out"
else
pass "an invalid agent file exits 1, naming both the file and validate.sh's reason"
fi
# --- 3. Zero discovered files is an error, not a pass ---
echo ""
echo "--- zero discovered agent files is an error ---"
FIX3="$(make_fixture)"
FIXTURES+=("$FIX3")
rm -f "$FIX3/plugins/lint/.apm/agents/lint-runner.agent.md"
if bash "$SCRIPT" "$FIX3" > "$RUN_TMP/empty.out" 2>&1; then
fail "a tree with zero agent files exited 0 — the floor is gone and the gate is vacuous"
sed 's/^/ /' "$RUN_TMP/empty.out"
elif ! grep -q 'found 0 plugin-scope agent file' "$RUN_TMP/empty.out"; then
fail "a tree with zero agent files exited non-zero but not for the zero-file reason"
sed 's/^/ /' "$RUN_TMP/empty.out"
else
pass "a tree with zero agent files exits 1 and says so"
fi
# --- 4. A tracked file missing from the worktree fails, derived from the index ---
# This is the check a hardcoded count cannot make: the file is gone but the count
# of what remains would still look plausible.
echo ""
echo "--- a tracked-but-deleted agent file fails against the derived expectation ---"
FIX4="$(make_fixture)"
FIXTURES+=("$FIX4")
cat > "$FIX4/plugins/lint/.apm/agents/second-agent.agent.md" <<'MD'
---
name: second-agent
description: A second agent, present only so its deletion leaves a plausible-looking non-empty set behind.
---
Do the second thing.
MD
git -C "$FIX4" init -q
git -C "$FIX4" add -A
git -C "$FIX4" -c user.email=t@example.invalid -c user.name=t commit -qm "fixture"
rm -f "$FIX4/plugins/lint/.apm/agents/second-agent.agent.md"
if bash "$SCRIPT" "$FIX4" > "$RUN_TMP/missing.out" 2>&1; then
fail "a tracked agent file deleted from the worktree still exited 0"
sed 's/^/ /' "$RUN_TMP/missing.out"
elif grep -q 'not a git worktree root' "$RUN_TMP/missing.out"; then
fail "the fixture did not resolve as its own git worktree root, so the derived check never ran"
sed 's/^/ /' "$RUN_TMP/missing.out"
elif ! grep -q 'second-agent\.agent\.md' "$RUN_TMP/missing.out"; then
fail "failed as expected but did not name the tracked file that went missing"
sed 's/^/ /' "$RUN_TMP/missing.out"
else
pass "a tracked agent file deleted from the worktree exits 1 and is named"
fi
# --- 5. An untracked agent file is still validated ---
# The derived expectation is one-directional on purpose (tracked ⊆ discovered).
# Work in progress must not fail the gate for being uncommitted — but it must
# still be validated, or the gate would be trivially bypassed by not committing.
echo ""
echo "--- an untracked, invalid agent file still fails the gate ---"
FIX5="$(make_fixture)"
FIXTURES+=("$FIX5")
git -C "$FIX5" init -q
git -C "$FIX5" add -A
git -C "$FIX5" -c user.email=t@example.invalid -c user.name=t commit -qm "fixture"
cat > "$FIX5/plugins/lint/.apm/agents/wip-agent.agent.md" <<'MD'
---
name: wip-agent
tools: Read, Write
description: An uncommitted work-in-progress agent carrying a non-allowlisted field.
---
Do the work-in-progress thing.
MD
if bash "$SCRIPT" "$FIX5" > "$RUN_TMP/untracked.out" 2>&1; then
fail "an untracked, invalid agent file was not validated — the gate can be bypassed by not committing"
sed 's/^/ /' "$RUN_TMP/untracked.out"
elif ! grep -q 'wip-agent\.agent\.md' "$RUN_TMP/untracked.out"; then
fail "failed but did not name the untracked file"
sed 's/^/ /' "$RUN_TMP/untracked.out"
else
pass "an untracked, invalid agent file exits 1 and is named"
fi
# --- 5b. An untracked but VALID agent file does not fail ---
echo ""
echo "--- an untracked, valid agent file passes ---"
FIX5B="$(make_fixture)"
FIXTURES+=("$FIX5B")
git -C "$FIX5B" init -q
git -C "$FIX5B" add -A
git -C "$FIX5B" -c user.email=t@example.invalid -c user.name=t commit -qm "fixture"
cat > "$FIX5B/plugins/lint/.apm/agents/wip-ok.agent.md" <<'MD'
---
name: wip-ok
description: An uncommitted work-in-progress agent that is nonetheless entirely valid.
---
Do the valid work-in-progress thing.
MD
if bash "$SCRIPT" "$FIX5B" > "$RUN_TMP/untracked-ok.out" 2>&1; then
pass "an untracked but valid agent file does not fail the gate"
else
fail "an untracked but valid agent file failed the gate — uncommitted work must not be an error"
sed 's/^/ /' "$RUN_TMP/untracked-ok.out"
fi
# --- 6. A nonexistent REPO_ROOT fails loudly ---
echo ""
echo "--- a nonexistent REPO_ROOT fails loudly ---"
if bash "$SCRIPT" "$RUN_TMP/does-not-exist" > "$RUN_TMP/norepo.out" 2>&1; then
fail "a nonexistent REPO_ROOT exited 0"
sed 's/^/ /' "$RUN_TMP/norepo.out"
elif ! grep -q 'is not a directory' "$RUN_TMP/norepo.out"; then
fail "a nonexistent REPO_ROOT failed for the wrong reason"
sed 's/^/ /' "$RUN_TMP/norepo.out"
else
pass "a nonexistent REPO_ROOT exits 1 and says which path it was"
fi
# --- 7. A missing validator is a hard failure, never a silent pass ---
# The whole gate is void without validate.sh, and exit 0 here would be
# indistinguishable from a run where every agent passed.
echo ""
echo "--- a missing validate.sh fails rather than validating nothing ---"
FIX7="$(make_fixture)"
FIXTURES+=("$FIX7")
rm -f "$FIX7/plugins/kyberforge/.apm/skills/factory-audit/scripts/validate.sh"
if bash "$SCRIPT" "$FIX7" > "$RUN_TMP/novalidator.out" 2>&1; then
fail "a missing validate.sh exited 0 — the gate silently validated nothing"
sed 's/^/ /' "$RUN_TMP/novalidator.out"
elif ! grep -q 'validator not found' "$RUN_TMP/novalidator.out"; then
fail "a missing validate.sh failed for the wrong reason"
sed 's/^/ /' "$RUN_TMP/novalidator.out"
else
pass "a missing validate.sh exits 1 and names the stale path"
fi
echo ""
echo "Results: $PASS passed, $FAIL failed"
[[ $FAIL -eq 0 ]]