Merge pull request 'feat(rtk): add an rtk plugin that routes Bash calls through rtk' (#284) from feat/179-rtk-plugin into main

Reviewed-on: #284
This commit was merged in pull request #284.
This commit is contained in:
Defame1297 committed 2026-12-06 15:30:58 +00:00
commit 0b04fa1e66
14 files changed
+882 -5

No files matched your search

+7
View File
@@ -90,6 +90,13 @@
"version": "0.5.0", "version": "0.5.0",
"category": "Productivity", "category": "Productivity",
"source": "./plugins/plan" "source": "./plugins/plan"
},
{
"name": "rtk",
"description": "A Claude Code hook that routes Bash tool calls through rtk, the token-saving command wrapper, when rtk is installed.",
"version": "0.1.0",
"category": "Developer Tools",
"source": "./plugins/rtk"
} }
] ]
} }
+4
View File
@@ -155,3 +155,7 @@ Under the `run-tests` pre-push hook, git exported `GIT_DIR` to the hook, so a ba
## 2026-11-26 — A hook's GIT_DIR leaks through any tool that runs git ## 2026-11-26 — A hook's GIT_DIR leaks through any tool that runs git
#204: pushing from a linked worktree left the shared `.git/config` with `core.bare=true` and the worktree on a detached HEAD at the lock-pinned commit. git exports an absolute `GIT_DIR` to hooks run from a linked worktree. `apm-audit-ci` ran `apm audit --ci`, and its drift replay (apm 0.28.0) runs `git init` and `git checkout` in a temp dir with an env copied from `os.environ`. The inherited `GIT_DIR` won, so both operations hit this repo instead of the temp dir. The 2026-11-13 fix did not cover this: it scrubbed the env only inside `tests/run-tests.sh`, and the apm hooks never pass through that file. Fix: `scripts/lib/clean-git-env.sh` unsets the repo-locating vars, and both `scripts/apm-audit-ci.sh` and the new `scripts/apm-pack-check-clean.sh` source it before calling apm. `tests/test-apm-hooks-git-env.sh` reproduces the leak with a stub `apm`. Rule: any hook that shells out to a tool that runs git must scrub `GIT_*` first. Scrubbing one entry point does not protect the others. *2026-12-02 (#272):* apm 0.39.3's `apm_cli/utils/git_env.py` provides `git_subprocess_env`, which strips `GIT_DIR` and the other repo-locating vars. The leak was not re-tested on 0.39.3, and the scrub stays, because the rule is about the hook, not about one tool version. #204: pushing from a linked worktree left the shared `.git/config` with `core.bare=true` and the worktree on a detached HEAD at the lock-pinned commit. git exports an absolute `GIT_DIR` to hooks run from a linked worktree. `apm-audit-ci` ran `apm audit --ci`, and its drift replay (apm 0.28.0) runs `git init` and `git checkout` in a temp dir with an env copied from `os.environ`. The inherited `GIT_DIR` won, so both operations hit this repo instead of the temp dir. The 2026-11-13 fix did not cover this: it scrubbed the env only inside `tests/run-tests.sh`, and the apm hooks never pass through that file. Fix: `scripts/lib/clean-git-env.sh` unsets the repo-locating vars, and both `scripts/apm-audit-ci.sh` and the new `scripts/apm-pack-check-clean.sh` source it before calling apm. `tests/test-apm-hooks-git-env.sh` reproduces the leak with a stub `apm`. Rule: any hook that shells out to a tool that runs git must scrub `GIT_*` first. Scrubbing one entry point does not protect the others. *2026-12-02 (#272):* apm 0.39.3's `apm_cli/utils/git_env.py` provides `git_subprocess_env`, which strips `GIT_DIR` and the other repo-locating vars. The leak was not re-tested on 0.39.3, and the scrub stays, because the rule is about the hook, not about one tool version.
## 2026-12-06 — Two correct gates can make a first landing unpushable
#179: `check-executables-allow-sync` requires a new hook-shipping plugin's git+path entry in root `apm.yml`, while root deps resolve from the remote's `main` (ADR-0019), so `apm-audit-ci`'s `ref-consistency` fails until the plugin lands — no state of the branch passes both. Fix: a narrow, self-expiring waiver in `scripts/apm-audit-ci.sh` keyed on the plugin being absent from local `origin/main`. Rule: when adding a gate that reads the remote's `main`, check what a first landing of the thing it guards looks like.
+1 -1
View File
@@ -8,7 +8,7 @@ Content ships as installable plugins, each an apm (Agent Package Manager) packag
| Path | What it holds | | Path | What it holds |
| --- | --- | | --- | --- |
| `plugins/` | The apm packages — `bin`, `core`, `git`, `gitea`, `kyberforge`, `lint`, `mattpocock`, `delivery`, `ansible`, `gitops`, `k8s`, `plan` — each carrying skills, and where relevant agents, hooks, and bundled assets | | `plugins/` | The apm packages — `bin`, `core`, `git`, `gitea`, `kyberforge`, `lint`, `mattpocock`, `delivery`, `ansible`, `gitops`, `k8s`, `plan`, `rtk` — each carrying skills, and where relevant agents, hooks, and bundled assets |
| `providers/claude-code/` | Claude Code adapter, deployed to `~/.claude/` via `scripts/install.sh` | | `providers/claude-code/` | Claude Code adapter, deployed to `~/.claude/` via `scripts/install.sh` |
| `core/` | Provider-agnostic always-on content — `core/AGENTS.md` and `core/instructions/` | | `core/` | Provider-agnostic always-on content — `core/AGENTS.md` and `core/instructions/` |
| `docs/` | Specs (`docs/spec/`), architectural decisions (`docs/adr/`), governance, research, and notes | | `docs/` | Specs (`docs/spec/`), architectural decisions (`docs/adr/`), governance, research, and notes |
+10
View File
@@ -51,6 +51,9 @@ dependencies:
# Ticket and idea planning, up to an agent-ready spec and breakdown. # Ticket and idea planning, up to an agent-ready spec and breakdown.
- git: https://git.rkdr.net/Mortis/Holocron.git - git: https://git.rkdr.net/Mortis/Holocron.git
path: plugins/plan path: plugins/plan
# Routes Bash tool calls through rtk when it is installed (#179).
- git: https://git.rkdr.net/Mortis/Holocron.git
path: plugins/rtk
mcp: [] mcp: []
# Turns apm's executable-trust gate ON. Without this block the gate is disabled # Turns apm's executable-trust gate ON. Without this block the gate is disabled
@@ -89,6 +92,9 @@ executables:
# git ships the hook that refuses a push to main. # git ships the hook that refuses a push to main.
git.rkdr.net/Mortis/Holocron/plugins/git#1.4.0: git.rkdr.net/Mortis/Holocron/plugins/git#1.4.0:
hooks: true hooks: true
# rtk ships the hook that routes Bash tool calls through rtk.
git.rkdr.net/Mortis/Holocron/plugins/rtk#0.1.0:
hooks: true
marketplace: marketplace:
# apm's Claude marketplace mapper only emits description:/version: into the # apm's Claude marketplace mapper only emits description:/version: into the
@@ -167,3 +173,7 @@ marketplace:
- name: plan - name: plan
source: ./plugins/plan source: ./plugins/plan
category: Productivity category: Productivity
- name: rtk
source: ./plugins/rtk
category: Developer Tools
@@ -2,6 +2,22 @@
**Status:** Accepted (2026-09-20) **Status:** Accepted (2026-09-20)
*Amended 2026-12-06 ([rtk routing hook](https://git.rkdr.net/Mortis/Holocron/issues/179)): "the root
manifest is never waived" below now holds for `lockfile-exists` only. The root has one narrow
waiver: `ref-consistency` for a plugin not yet on `origin/main`. Root `apm.yml`'s first-party
dependencies resolve from the remote's `main` (ADR-0019), so the lock cannot record a plugin before it
lands. `check-executables-allow-sync` meanwhile requires a hook- or bin-shipping plugin's git+path
entry before it can be pushed, so without the waiver such a plugin could never land. The waiver applies
only when all of these hold: the output reads `1 of 3 check(s) failed` and its one failing row is
`ref-consistency`; the details block appears exactly once and every line in it is `<identity>/plugins/<name>: not found
in lockfile`, for root `apm.yml`'s own entry and a name that starts alphanumeric and holds no `..`;
`plugins/<name>/apm.yml` is in the working tree and absent from the local `origin/main`, which must
resolve. On apm 0.39.3 a failing `ref-consistency` stops the root run after three checks, so the hook then
re-runs `apm audit --ci` on a scratch copy of the tree with those plugins' `dependencies.apm` entries
removed, and the push passes only if that run reports `All 15 check(s) passed`. The working tree is
never written. The waiver lapses for each plugin once it is on `origin/main`, when the follow-up PR that
records it in the lock is required.*
*Amended 2026-12-02 (holocron#272): re-verified on apm 0.39.3 in a scratch copy of *Amended 2026-12-02 (holocron#272): re-verified on apm 0.39.3 in a scratch copy of
`plugins/mattpocock`. Without a package lock, the same line and `1 of 1 check(s) failed` appear, so `plugins/mattpocock`. Without a package lock, the same line and `1 of 1 check(s) failed` appear, so
the waiver is unchanged. With one from `apm lock`, the rest of the root set arms (fourteen more the waiver is unchanged. With one from `apm lock`, the rest of the root set arms (fourteen more
@@ -127,6 +127,11 @@ passed. Failed tasks are shown in the PR comment for the approver to judge. Deci
cluster or state and print no secret: anything not on the list is denied, so an unlisted mutating cluster or state and print no secret: anything not on the list is denied, so an unlisted mutating
subcommand fails safe. Codex cannot ask, so odd jobs are subcommand fails safe. Codex cannot ask, so odd jobs are
denied there; an unrecognised runtime is treated the same way. denied there; an unrecognised runtime is treated the same way.
- *Amended 2026-12-05 ([rtk routing hook](https://git.rkdr.net/Mortis/Holocron/issues/179)): the
opt-in `rtk` plugin ships a Claude Code hook that rewrites Bash commands through `rtk hook claude`
and may return `permissionDecision: allow`, skipping the permission prompt. Accepted, because hooks
are guardrails, not the boundary; `git`'s push guard still sees `rtk git push`, as `rtk` is one of
its wrappers.*
- *Amended 2026-12-04 ([git push-to-main hook](https://git.rkdr.net/Mortis/Holocron/issues/178)): `git` - *Amended 2026-12-04 ([git push-to-main hook](https://git.rkdr.net/Mortis/Holocron/issues/178)): `git`
ships its own guardrail hook beside `delivery`'s, refusing a `git push` to `main` on Claude Code ships its own guardrail hook beside `delivery`'s, refusing a `git push` to `main` on Claude Code
only. It fails open and has an opt-out; branch protection stays the real control.* only. It fails open and has an opt-out; branch protection stays the real control.*
+34 -2
View File
@@ -72,7 +72,7 @@ version-blind, so a stale key deploys fine (see [apm gates](#apm-gates)).
| Hook | Guards | | Hook | Guards |
|---|---| |---|---|
| `apm-audit-ci` | `scripts/apm-audit-ci.sh` — `apm audit --ci` once per manifest, root plus each plugin package under `plugins/`, waiving only a package's `lockfile-exists` (see [below](#apm-audit-ci)) | | `apm-audit-ci` | `scripts/apm-audit-ci.sh` — `apm audit --ci` once per manifest, root plus each plugin package under `plugins/`, waiving only a package's `lockfile-exists` and the root's `ref-consistency` for a plugin not yet on `origin/main` (see [below](#apm-audit-ci)) |
| `apm-pack-check-clean` | `scripts/apm-pack-check-clean.sh` — `apm pack --check-versions --check-clean --dry-run` with a scrubbed git env (see [`apm-audit-ci`](#apm-audit-ci)) — the compiled marketplace still matches what `apm.yml` + `.apm/` would generate, and per-package versions agree with the `per_package` strategy | | `apm-pack-check-clean` | `scripts/apm-pack-check-clean.sh` — `apm pack --check-versions --check-clean --dry-run` with a scrubbed git env (see [`apm-audit-ci`](#apm-audit-ci)) — the compiled marketplace still matches what `apm.yml` + `.apm/` would generate, and per-package versions agree with the `per_package` strategy |
**Host validators** (needs the `claude` CLI on PATH) **Host validators** (needs the `claude` CLI on PATH)
@@ -1232,7 +1232,39 @@ The cause is that apm treats any directory holding both `apm.yml` and `apm.lock.
root**, and a plugin package is not one. `scripts/apm-audit-ci.sh` therefore waives `lockfile-exists` root**, and a plugin package is not one. `scripts/apm-audit-ci.sh` therefore waives `lockfile-exists`
and nothing else, and only for a non-root manifest: it asserts the string `1 of 1 check(s) failed`, and nothing else, and only for a non-root manifest: it asserts the string `1 of 1 check(s) failed`,
so any second failing check changes the count and the run fails normally, and output it does not so any second failing check changes the count and the run fails normally, and output it does not
recognise fails closed. The root manifest is never waived. Recorded as ADR-0026. recognise fails closed. The root manifest is never waived for `lockfile-exists`. Recorded as ADR-0026.
**The root has one waiver of its own: `ref-consistency` for a plugin not yet on `origin/main`.**
Root `apm.yml`'s first-party dependencies resolve from the remote's `main` (ADR-0019), so the lock
cannot record a plugin before it lands, while `check-executables-allow-sync` refuses a push of a
hook- or bin-shipping plugin whose git+path entry is missing from root `apm.yml`. Without a waiver a
first-landing executable-shipping plugin is unpushable: root `ref-consistency` fails with
`<identity>/plugins/<name>: not found in lockfile`. On apm 0.39.3 a failing `ref-consistency` cuts
the root run to three checks (holocron#179), so the hook waives it only when the output reads `1 of
3 check(s) failed`, the one failing row is `ref-consistency`, and every line of its details block is
that `not found in lockfile` form for an identity equal to root `apm.yml`'s own git+path entry for
`plugins/<name>` (derived by `check-executables-allow-sync`'s rule). Each `plugins/<name>/apm.yml`
must also exist in the working tree and be absent from the **local** `origin/main`, which must
resolve; nothing is fetched. A plugin name must start with a letter or digit and may not contain
`..`. Any other output fails closed. The waiver lapses for a plugin by itself: once it is on
`origin/main`, the follow-up PR that records it in the lock is required.
**The waiver re-runs the full root check set before it passes.** The cut-short run never reaches the
other twelve root checks (`content-integrity`, `hook-approval-pins`, `local-bundle-hooks`,
`exec-status-current`, `deployed-files-present` and the rest), so the three-check result alone
would let a defect in any of them through. Once the conditions above hold, the hook copies the working
tree (minus `.git` and `.venv`) into a `mktemp -d` directory with `tar`. In the copy it drops only the
`dependencies:` > `apm:` items whose `path:` names a waived plugin, checks that the reduced
`apm.yml` differs from the original by those deletions alone, and runs `git init` with the same
`origin` URL, the only git state apm reads. It then runs `apm audit --ci` there. The push passes only
if that run exits 0 and prints `All 15 check(s) passed`. On this branch (holocron#179, apm 0.39.3) it
does, and the hook prints `root re-run without the unlanded plugins: All 15 check(s) passed`. A copy
was chosen over swapping `apm.yml` in place under a `trap`: the copy never writes the working tree, so
the tree stays byte-identical even after `SIGKILL`, and a concurrent apm never sees a reduced
manifest. `.git` is not copied because in a linked worktree it points into the shared gitdir. `.venv`
is not copied because apm runs from the real one via `uv run --project`. The scratch directory is
removed on exit, including on `INT`, `TERM` and `HUP`. The script header records the full reasoning.
`tests/test-apm-audit-ci-waiver.sh` covers the waiver, the re-run, and each of its guards.
**Dropping `--ci` for package directories was considered and rejected.** It is the smaller change **Dropping `--ci` for package directories was considered and rejected.** It is the smaller change
and it is wrong. Verified on apm 0.28.0, and again on 0.39.3 (holocron#272), against a scratch and it is wrong. Verified on apm 0.28.0, and again on 0.39.3 (holocron#272), against a scratch
+16
View File
@@ -0,0 +1,16 @@
{
"hooks": {
"PreToolUse": [
{
"hooks": [
{
"command": "${CLAUDE_PLUGIN_ROOT}/.apm/hooks/route-through-rtk.sh",
"timeout": 10,
"type": "command"
}
],
"matcher": "Bash"
}
]
}
}
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# PreToolUse hook: route a Bash tool call through `rtk hook claude`, which may
# rewrite the command to its rtk-prefixed form. rtk's output is passed through
# when rtk succeeds. The hook always exits 0: a PreToolUse exit 2 blocks the tool
# call, and rtk exits 2 on a usage error (e.g. an rtk without `hook claude`), so
# any rtk failure is swallowed and the call proceeds unchanged. Without rtk on
# PATH it does nothing. Limits: the rtk plugin's README.
set -euo pipefail
# apm could deploy this file to other runtimes, where it must do nothing.
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/"
case "$here" in
*/.claude/hooks/*) ;;
*) exit 0 ;;
esac
command -v rtk > /dev/null 2>&1 || exit 0
# stdin (the hook payload) is inherited by rtk inside the substitution.
out="$(rtk hook claude)" || exit 0
[[ -z "$out" ]] || printf '%s\n' "$out"
exit 0
+84
View File
@@ -0,0 +1,84 @@
# rtk
A Claude Code hook that routes Bash tool calls through rtk, the token-saving command wrapper, when rtk is installed.
## Install
apm is the only supported install path (ADR-0024). Declare this package in the consuming project's `apm.yml`:
```yaml
dependencies:
apm:
- git: https://git.rkdr.net/Mortis/Holocron.git
path: plugins/rtk
```
Then:
```bash
apm install
```
The entry above is unpinned and tracks the remote's default branch. To pin a release, add `ref: rtk-v<x.y.z>` after `path:`; see [Pinning a plugin to a release](../../README.md#pinning-a-plugin-to-a-release).
The plugin is opt-in: nothing else in the marketplace depends on it. It does not run `rtk init` and changes no rtk configuration.
**Native plugin installs do not work.** This package ships no per-plugin manifest and no flat content directories, so a host that installs it natively gets nothing — and Claude Code raises no error while doing it (ADR-0024).
## Contents
| Component | Path | Description |
|---|---|---|
| Hooks | `.apm/hooks/` | `route-through-rtk.sh`, see [Routing hook](#routing-hook) |
`.apm/` is the authoring source and the only thing apm deploys (ADR-0024).
## Routing hook
On Claude Code, a `PreToolUse` hook on the Bash tool passes each call to `rtk hook claude`. rtk decides whether to rewrite the command, for example `git status` to `rtk git status`, and the hook passes rtk's answer back to Claude Code unchanged. A command rtk does not handle runs as written.
- **Without rtk on `PATH`,** the hook exits 0 and prints nothing, so the command runs as written.
- **Claude Code only.** The package targets `claude`, and the script does nothing unless it runs from a `.claude/hooks/` path.
- **Tested with rtk 0.42.4.** Older versions may lack `rtk hook claude`.
### Rewritten commands may come back pre-approved
rtk's answer can carry `permissionDecision: allow`, which skips Claude Code's permission prompt for the rewritten command. The hook passes that through. Hooks here are guardrails, not the safety boundary (ADR-0032); if you rely on the permission prompt for Bash, do not install this plugin.
### Overlap with a global rtk hook
`rtk init -g` installs rtk's own hook into `~/.claude/settings.json`. Check for one with:
```bash
rtk init --show
```
Running both is harmless: rtk leaves a command that already starts with `rtk` alone, so the second hook does nothing. It still runs rtk twice per Bash call, so keep one of the two — this plugin for a per-project install that apm keeps up to date, or the global hook for every project on the machine.
### Approval
The hook is an executable primitive, so whether it deploys depends on the `executables:` block in the consuming project's `apm.yml`:
- **No `executables:` block:** hooks deploy without approval.
- **With an `executables:` block:** the hook is parked until it is granted. Grant it in one of two ways, then run `apm install` and commit the `executables` entry:
- `apm approve` writes the entry and pins it to the hook's content, so a later change to the script needs approval again.
- A hand-written entry under the full package identity is not pinned:
```yaml
executables:
allow:
git.rkdr.net/Mortis/Holocron/plugins/rtk:
hooks: true
```
The first `apm approve` in a project creates the block and so turns the gate on. The next install then parks every other package's unapproved executables.
This repo hand-writes its grant in the root `apm.yml` and does not run `apm approve`.
### "ambiguous duplicate APM-owned hook entry"
apm raises this error when `.claude/settings.json` holds more byte-identical copies of an APM-owned hook entry than `.claude/apm-hooks.json` records. It happens when the same hook entry is pasted in by hand or merged in twice. To fix it, remove the duplicate entries from `.claude/settings.json`, keeping none of the hand-added copies, then run `apm install` again.
## Author
Defame1297
+29
View File
@@ -0,0 +1,29 @@
name: rtk
version: 0.1.0
description: A Claude Code hook that routes Bash tool calls through rtk, the token-saving command wrapper, when rtk is installed.
author:
name: Mortis
url: https://git.rkdr.net/Mortis/
license: MIT
homepage: https://git.rkdr.net/Mortis/Holocron/src/branch/main/plugins/rtk
repository: https://git.rkdr.net/Mortis/Holocron/src/branch/main/plugins/rtk
keywords:
- rtk
- hooks
- tokens
# Which agent platforms to deploy to.
# Resolution order: --target flag > this field > auto-detect from filesystem.
# Accepted values: agent-skills, antigravity, claude, codex, copilot, cursor, gemini, grok-build, kiro, opencode, windsurf
# Claude only: the hook speaks `rtk hook claude`. The script also refuses to act
# outside .claude/hooks/, in case a consumer forces another target.
targets:
- claude
type: hybrid
dependencies:
apm: []
mcp: []
includes: auto
devDependencies:
apm: []
scripts: {}
+259 -2
View File
@@ -47,7 +47,8 @@
# discarded precisely where it earns its keep. # discarded precisely where it earns its keep.
# #
# The waiver is therefore narrow on three axes, and fails closed on each: # The waiver is therefore narrow on three axes, and fails closed on each:
# 1. the root manifest is never waived, whatever it reports # 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 # 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 # "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 # second failing check changes the count and the run fails normally
@@ -57,6 +58,72 @@
# line silently turns the waiver off, which fails the push rather than hiding a # 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 # defect. If that happens, re-verify against the new output and update the two
# patterns below rather than widening them. # 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 set -uo pipefail
@@ -74,6 +141,184 @@ require_apm_version || exit 1
readonly WAIVED_CHECK='declares dependencies but apm.lock.yaml is absent' readonly WAIVED_CHECK='declares dependencies but apm.lock.yaml is absent'
readonly SOLE_FAILURE='1 of 1 check(s) failed' 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 status=0
@@ -85,7 +330,19 @@ for manifest_dir in . plugins/*/; do
continue continue
fi fi
# Axis 1: the root is never waived. # 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 # 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 # 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 # becomes the pipeline's status -- a race tests/test-no-pipefail-early-exit-grep.sh
+273
View File
@@ -0,0 +1,273 @@
#!/usr/bin/env bash
# Tests scripts/apm-audit-ci.sh's root ref-consistency waiver: a plugin whose
# git+path entry is in root apm.yml but which is not yet on origin/main (#179,
# ADR-0019). See docs/spec/gates.md, "apm-audit-ci".
#
# Same seam as tests/test-apm-gate-invocation.sh: a stub `apm`, reached through
# the APM override so no uv or real apm runs. The stub prints canned `audit
# --ci` output for the root manifest ($STUB_ROOT_OUTPUT, exit 1) and passes in
# every plugin directory. The waiver's re-run is told apart by where it runs:
# under $TMPDIR, the script's mktemp scratch copy, where the stub saves the manifest it was given ($STUB_RERUN_LOG) and prints
# $STUB_RERUN_OUTPUT (default: the full root pass) with exit $STUB_RERUN_RC
# (default 0). The fixture is a throwaway git repo whose
# refs/remotes/origin/main is set with update-ref -- nothing is fetched.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
AUDIT="$REPO_ROOT/scripts/apm-audit-ci.sh"
PASS=0
FAIL=0
pass() { echo " PASS: $1"; PASS=$((PASS + 1)); }
fail() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }
unset APM GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_OBJECT_DIRECTORY GIT_COMMON_DIR
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
BIN="$TMP/bin"
mkdir -p "$BIN"
cat > "$BIN/apm" << 'EOF'
#!/usr/bin/env bash
if [[ "${1:-}" == --version ]]; then
echo "Agent Package Manager (APM) CLI version 0.39.3"
exit 0
fi
if [[ -f apm.lock.yaml.root-marker ]]; then
if [[ "$PWD" != "$TMPDIR"/* ]]; then
printf '%s\n' "$STUB_ROOT_OUTPUT"
exit 1
fi
[[ -z "${STUB_RERUN_LOG:-}" ]] || cp apm.yml "$STUB_RERUN_LOG"
printf '%s\n' "${STUB_RERUN_OUTPUT-[*] All 15 check(s) passed}"
exit "${STUB_RERUN_RC:-0}"
fi
exit 0
EOF
chmod +x "$BIN/apm"
IDENTITY="git.rkdr.net/Mortis/Holocron"
# The output apm 0.39.3 printed for this branch's root manifest (#179).
root_output() { # <failing count line> <extra failing row> <detail lines...>
local count="$1" extra="$2"
shift 2
printf '%s\n' \
'[+] No drift detected' \
'+------------------------------------------------------------------------------+' \
'| Status | Check | Message |' \
'|----------+-----------------+-------------------------------------------------|' \
'| [+] | lockfile-exists | Lockfile present |' \
"| [x] | ref-consistency | $# ref mismatch -- run 'apm install' to update |" \
'| | | lockfile |'
if [[ -n "$extra" ]]; then printf '%s\n' "$extra"; else
printf '%s\n' '| [+] | drift | no drift detected against lockfile |'
fi
printf '%s\n' \
'+------------------------------------------------------------------------------+' \
'' \
' ref-consistency details:'
local d
for d in "$@"; do printf ' - %s\n' "$d"; done
printf '%s\n' '' "$count"
}
# make_fixture <dir> — a repo with root apm.yml naming plugins/core and
# plugins/rtk, both plugin dirs present, origin/main at a commit holding
# plugins/core only.
make_fixture() {
local dir="$1"
mkdir -p "$dir/plugins/core" "$dir/plugins/rtk"
cat > "$dir/apm.yml" << EOF
name: fixture
dependencies:
apm:
- git: https://$IDENTITY.git
path: plugins/core
# Routes Bash tool calls through rtk.
- git: https://$IDENTITY.git
path: plugins/rtk
mcp: []
EOF
printf 'name: core\nversion: 1.0.0\n' > "$dir/plugins/core/apm.yml"
touch "$dir/apm.lock.yaml.root-marker"
git -C "$dir" init -q
git -C "$dir" add apm.yml plugins/core/apm.yml
git -C "$dir" -c user.name=t -c user.email=t@t commit -qm base
git -C "$dir" update-ref refs/remotes/origin/main HEAD
printf 'name: rtk\nversion: 0.1.0\n' > "$dir/plugins/rtk/apm.yml"
}
RC=0
OUT=""
# TMPDIR is a fresh per-run dir, so the re-run's scratch copy can be checked
# for cleanup.
TMPD="$TMP/tmpdir"
run_audit() { # <dir> <root output> [VAR=value ...]
local dir="$1" root="$2"
shift 2
RC=0
rm -rf "$TMPD"
mkdir -p "$TMPD"
OUT="$(cd "$dir" && env APM="$BIN/apm" STUB_ROOT_OUTPUT="$root" TMPDIR="$TMPD" "$@" \
bash "$AUDIT" 2>&1)" || RC=$?
}
tmp_clean() { [[ -z "$(ls -A "$TMPD")" ]]; }
WAIVER_LINE='apm audit --ci: waived ref-consistency for plugins/rtk (not yet on origin/main; ADR-0019)'
SOLE='[x] 1 of 3 check(s) failed'
RTK_DETAIL="$IDENTITY/plugins/rtk: not found in lockfile"
echo "--- waived: one plugin not yet on origin/main ---"
F="$TMP/waived"
make_fixture "$F"
cp "$F/apm.yml" "$TMP/apm.yml.orig"
run_audit "$F" "$(root_output "$SOLE" "" "$RTK_DETAIL")" STUB_RERUN_LOG="$TMP/rerun.yml"
[[ $RC -eq 0 ]] && pass "exits 0" || fail "exited $RC: $OUT"
grep -qxF "$WAIVER_LINE" <<< "$OUT" && pass "prints the waiver line" || fail "no waiver line: $OUT"
grep -qxF 'apm audit --ci: root re-run without the unlanded plugins: All 15 check(s) passed' <<< "$OUT" \
&& pass "reports the full-set re-run" || fail "no re-run line: $OUT"
# The re-run's manifest is the original minus exactly the rtk item.
if [[ -f "$TMP/rerun.yml" ]] && diff "$TMP/apm.yml.orig" "$TMP/rerun.yml" > "$TMP/rerun.diff"; then
fail "the re-run saw an unreduced apm.yml"
elif [[ "$(cat "$TMP/rerun.diff" 2>/dev/null)" == "$(printf '%s\n' '7,8d6' \
"< - git: https://$IDENTITY.git" '< path: plugins/rtk')" ]]; then
pass "the re-run's apm.yml drops only the plugins/rtk entry"
else
fail "unexpected re-run manifest: $(cat "$TMP/rerun.diff" 2>/dev/null)"
fi
cmp -s "$TMP/apm.yml.orig" "$F/apm.yml" && [[ -z "$(git -C "$F" status --porcelain -- apm.yml)" ]] \
&& pass "leaves the working tree's apm.yml byte-identical" || fail "apm.yml changed"
tmp_clean && pass "removes the scratch copy" || fail "scratch left behind: $(ls -A "$TMPD")"
echo ""
echo "--- not waived: the full-set re-run fails ---"
run_audit "$F" "$(root_output "$SOLE" "" "$RTK_DETAIL")" STUB_RERUN_RC=1 \
STUB_RERUN_OUTPUT="$(printf '%s\n' '| [x] | content-integrity | hidden Unicode |' '[x] 1 of 15 check(s) failed')"
[[ $RC -ne 0 ]] && ! grep -qF "waived ref-consistency" <<< "$OUT" \
&& grep -qF "content-integrity" <<< "$OUT" \
&& pass "fails, showing the re-run's failing check" || fail "must fail (rc=$RC): $OUT"
cmp -s "$TMP/apm.yml.orig" "$F/apm.yml" && pass "apm.yml still byte-identical" || fail "apm.yml changed"
tmp_clean && pass "removes the scratch copy on failure too" || fail "scratch left behind: $(ls -A "$TMPD")"
run_audit "$F" "$(root_output "$SOLE" "" "$RTK_DETAIL")" STUB_RERUN_RC=1
[[ $RC -ne 0 ]] && ! grep -qF "waived ref-consistency" <<< "$OUT" \
&& pass "fails when the re-run exits non-zero despite a passing summary" || fail "must fail (rc=$RC): $OUT"
run_audit "$F" "$(root_output "$SOLE" "" "$RTK_DETAIL")" STUB_RERUN_OUTPUT='[*] All 14 check(s) passed'
[[ $RC -ne 0 ]] && ! grep -qF "waived ref-consistency" <<< "$OUT" \
&& pass "fails when the re-run runs fewer than the full set" || fail "must fail (rc=$RC): $OUT"
run_audit "$F" "$(root_output "$SOLE" "" "$RTK_DETAIL")" STUB_RERUN_OUTPUT=''
[[ $RC -ne 0 ]] && ! grep -qF "waived ref-consistency" <<< "$OUT" \
&& pass "fails when the re-run prints no summary" || fail "must fail (rc=$RC): $OUT"
echo ""
echo "--- not waived: the plugin is already on origin/main ---"
F="$TMP/landed"
make_fixture "$F"
git -C "$F" add plugins/rtk/apm.yml
git -C "$F" -c user.name=t -c user.email=t@t commit -qm landed
git -C "$F" update-ref refs/remotes/origin/main HEAD
run_audit "$F" "$(root_output "$SOLE" "" "$RTK_DETAIL")"
[[ $RC -ne 0 ]] && grep -qF "plugins/rtk is already on origin/main" <<< "$OUT" \
&& pass "fails, naming the landed plugin" || fail "must fail (rc=$RC): $OUT"
echo ""
echo "--- not waived: a second check also fails ---"
F="$TMP/second"
make_fixture "$F"
run_audit "$F" "$(root_output '[x] 2 of 3 check(s) failed' \
'| [x] | drift | 1 file(s) differ |' "$RTK_DETAIL")"
[[ $RC -ne 0 ]] && ! grep -qF "waived ref-consistency" <<< "$OUT" \
&& pass "fails when drift fails too" || fail "must fail (rc=$RC): $OUT"
echo ""
echo "--- not waived: one of three fails, but it is not ref-consistency ---"
F="$TMP/otherrow"
make_fixture "$F"
run_audit "$F" "$(root_output "$SOLE" \
'| [x] | drift | 1 file(s) differ |' "$RTK_DETAIL" |
sed 's/^| \[x\] | ref-consistency/| [+] | ref-consistency/')"
[[ $RC -ne 0 ]] && ! grep -qF "waived ref-consistency" <<< "$OUT" \
&& pass "fails when the sole failing row is drift" || fail "must fail (rc=$RC): $OUT"
echo ""
echo "--- not waived: a duplicated details header ---"
F="$TMP/duphdr"
make_fixture "$F"
run_audit "$F" "$(root_output "$SOLE" "" "$RTK_DETAIL"
printf '%s\n' '' ' ref-consistency details:' ' - github.com/acme/skills: not found in lockfile')"
[[ $RC -ne 0 ]] && ! grep -qF "waived ref-consistency" <<< "$OUT" \
&& pass "fails when a second details block could hide a detail" || fail "must fail (rc=$RC): $OUT"
echo ""
echo "--- not waived: a plugin name that is . or .., or holds .. ---"
F="$TMP/dotnames"
make_fixture "$F"
# Each entry goes inside the apm: list, above ` mcp: []`, so dep_identity
# finds it and only the name guards stand between it and a waiver.
for n in .. . .hidden a..b; do
awk -v e=" - git: https://$IDENTITY.git"$'\n'" path: plugins/$n" \
'/^ mcp:/ { print e } { print }' "$F/apm.yml" > "$F/apm.yml.new"
mv "$F/apm.yml.new" "$F/apm.yml"
mkdir -p "$F/plugins/$n"
[[ -f "$F/plugins/$n/apm.yml" ]] || printf 'name: x\n' > "$F/plugins/$n/apm.yml"
done
for n in .. . .hidden; do
run_audit "$F" "$(root_output "$SOLE" "" "$IDENTITY/plugins/$n: not found in lockfile")"
[[ $RC -ne 0 ]] && grep -qF "unrecognised detail line" <<< "$OUT" \
&& pass "fails on plugins/$n" || fail "must fail on plugins/$n (rc=$RC): $OUT"
done
run_audit "$F" "$(root_output "$SOLE" "" "$IDENTITY/plugins/a..b: not found in lockfile")"
[[ $RC -ne 0 ]] && grep -qF "contains '..'" <<< "$OUT" \
&& pass "fails on plugins/a..b" || fail "must fail on plugins/a..b (rc=$RC): $OUT"
echo ""
echo "--- not waived: a mismatch outside plugins/ ---"
F="$TMP/nonplugin"
make_fixture "$F"
run_audit "$F" "$(root_output "$SOLE" "" "github.com/acme/skills: not found in lockfile")"
[[ $RC -ne 0 ]] && grep -qF "unrecognised detail line" <<< "$OUT" \
&& pass "fails on a non-plugins detail" || fail "must fail (rc=$RC): $OUT"
run_audit "$F" "$(root_output "$SOLE" "" "$RTK_DETAIL" "github.com/acme/skills: not found in lockfile")"
[[ $RC -ne 0 ]] && ! grep -qF "waived ref-consistency" <<< "$OUT" \
&& pass "fails when an unlanded plugin is mixed with a non-plugins detail" \
|| fail "must fail on a mixed block (rc=$RC): $OUT"
run_audit "$F" "$(root_output "$SOLE" "" "$IDENTITY/plugins/rtk: ref main != abc123")"
[[ $RC -ne 0 ]] && pass "fails on a plugins/ detail of another kind" || fail "must fail (rc=$RC): $OUT"
echo ""
echo "--- not waived: the identity is not root apm.yml's entry ---"
run_audit "$F" "$(root_output "$SOLE" "" "git.example.com/Other/Repo/plugins/rtk: not found in lockfile")"
[[ $RC -ne 0 ]] && grep -qF "is not root apm.yml's git+path entry" <<< "$OUT" \
&& pass "fails on a foreign identity" || fail "must fail (rc=$RC): $OUT"
echo ""
echo "--- not waived: plugins/<name>/apm.yml is absent ---"
F="$TMP/absent"
make_fixture "$F"
rm "$F/plugins/rtk/apm.yml"
run_audit "$F" "$(root_output "$SOLE" "" "$RTK_DETAIL")"
[[ $RC -ne 0 ]] && grep -qF "plugins/rtk/apm.yml is not in the working tree" <<< "$OUT" \
&& pass "fails when the plugin manifest is missing" || fail "must fail (rc=$RC): $OUT"
echo ""
echo "--- fails closed: origin/main does not resolve ---"
F="$TMP/noorigin"
make_fixture "$F"
git -C "$F" update-ref -d refs/remotes/origin/main
run_audit "$F" "$(root_output "$SOLE" "" "$RTK_DETAIL")"
[[ $RC -ne 0 ]] && grep -qF "origin/main does not resolve locally" <<< "$OUT" \
&& pass "fails without origin/main" || fail "must fail (rc=$RC): $OUT"
echo ""
echo "--- fails closed: unrecognised output ---"
F="$TMP/garbled"
make_fixture "$F"
run_audit "$F" "something apm never printed"
[[ $RC -ne 0 ]] && pass "fails on output of an unknown shape" || fail "must fail (rc=$RC): $OUT"
run_audit "$F" "$(root_output "$SOLE" "")"
[[ $RC -ne 0 ]] && pass "fails on an empty details block" || fail "must fail (rc=$RC): $OUT"
echo ""
echo "Results: $PASS passed, $FAIL failed"
[[ "$FAIL" -eq 0 ]]
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env bash
# Tests for plugins/rtk/.apm/hooks/route-through-rtk.sh, the PreToolUse hook
# that routes a Bash tool call through `rtk hook claude` (#179).
#
# The hook acts only when run from a .claude/hooks/ path, so it is copied to the
# path apm deploys it to and driven with real payloads, against a stub rtk, no
# rtk at all, and the real rtk when one is installed.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HOOKS_DIR="$REPO_ROOT/plugins/rtk/.apm/hooks"
SRC="$HOOKS_DIR/route-through-rtk.sh"
PASS=0
FAIL=0
pass() { PASS=$((PASS + 1)); }
fail() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); }
[[ -f "$SRC" ]] || { echo "FAIL: $SRC does not exist"; exit 1; }
REAL_RTK="$(command -v rtk || true)"
TIMEOUT="$(command -v timeout)"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
for d in .claude/hooks/rtk/.apm/hooks elsewhere; do
mkdir -p "$WORK/$d"
cp "$SRC" "$WORK/$d/"
done
HOOK="$WORK/.claude/hooks/rtk/.apm/hooks/route-through-rtk.sh"
# A PATH with only what the hook and the stub need: no rtk on it.
mkdir -p "$WORK/base-bin"
for tool in bash cat dirname; do
ln -s "$(command -v "$tool")" "$WORK/base-bin/$tool"
done
# A stub rtk that records its arguments and stdin and prints a marker.
mkdir -p "$WORK/stub-bin"
cat > "$WORK/stub-bin/rtk" << STUB
#!/usr/bin/env bash
printf '%s\n' "\$*" > "$WORK/stub-args"
cat > "$WORK/stub-stdin"
echo stub-output
STUB
chmod +x "$WORK/stub-bin/rtk"
payload() {
printf '{"tool_name":"Bash","tool_input":{"command":"%s"}}' "$1"
}
# run <hook> <PATH> <command>: sets OUT and RC.
run() {
RC=0
OUT="$(payload "$3" | PATH="$2" "$TIMEOUT" 10 "$1" 2> "$WORK/stderr")" || RC=$?
}
echo "== Stub rtk receives 'hook claude' and the payload"
rm -f "$WORK/stub-args" "$WORK/stub-stdin"
run "$HOOK" "$WORK/stub-bin:$WORK/base-bin" "git status"
if [[ $RC -eq 0 && "$OUT" == stub-output ]]; then pass; else fail "want rc 0 and stub output, got $RC: $OUT"; fi
if [[ "$(cat "$WORK/stub-args" 2> /dev/null)" == "hook claude" ]]; then pass; else fail "stub args: $(cat "$WORK/stub-args" 2> /dev/null)"; fi
if [[ "$(cat "$WORK/stub-stdin" 2> /dev/null)" == "$(payload "git status")" ]]; then pass; else fail "stub stdin: $(cat "$WORK/stub-stdin" 2> /dev/null)"; fi
# stub_rtk <name> <body>: writes a stub rtk with <body> to $WORK/<name>/rtk.
stub_rtk() {
mkdir -p "$WORK/$1"
printf '#!/usr/bin/env bash\ncat > /dev/null\n%s\n' "$2" > "$WORK/$1/rtk"
chmod +x "$WORK/$1/rtk"
}
stub_rtk fail2-bin "echo 'error: unrecognized subcommand' >&2; exit 2"
stub_rtk fail1-bin "exit 1"
stub_rtk silent-bin "exit 0"
echo "== rtk exits 2 (usage error): exit 0, no stdout, never blocks"
run "$HOOK" "$WORK/fail2-bin:$WORK/base-bin" "git status"
if [[ $RC -eq 0 && -z "$OUT" ]]; then pass; else fail "rtk exit 2: want exit 0 and no stdout, got $RC: $OUT"; fi
echo "== rtk exits 1: exit 0, no stdout"
run "$HOOK" "$WORK/fail1-bin:$WORK/base-bin" "git status"
if [[ $RC -eq 0 && -z "$OUT" ]]; then pass; else fail "rtk exit 1: want exit 0 and no stdout, got $RC: $OUT"; fi
echo "== rtk prints nothing: exit 0, no stdout at all (not even a newline)"
RC=0
payload "git status" | PATH="$WORK/silent-bin:$WORK/base-bin" "$TIMEOUT" 10 "$HOOK" > "$WORK/raw-out" 2> "$WORK/stderr" || RC=$?
if [[ $RC -eq 0 && ! -s "$WORK/raw-out" ]]; then pass; else fail "silent rtk: want exit 0 and zero-byte stdout, got $RC: $(od -c "$WORK/raw-out")"; fi
echo "== rtk absent: exit 0, no output"
run "$HOOK" "$WORK/base-bin" "git status"
if [[ $RC -eq 0 && -z "$OUT" && ! -s "$WORK/stderr" ]]; then pass; else fail "want silent exit 0, got $RC: $OUT $(cat "$WORK/stderr")"; fi
echo "== Runtime: acts only from .claude/hooks/"
rm -f "$WORK/stub-args"
run "$WORK/elsewhere/route-through-rtk.sh" "$WORK/stub-bin:$WORK/base-bin" "git status"
if [[ $RC -eq 0 && -z "$OUT" && ! -e "$WORK/stub-args" ]]; then pass; else fail "elsewhere: want silent exit 0, got $RC: $OUT"; fi
echo "== Real rtk"
if [[ -z "$REAL_RTK" ]]; then
echo " SKIP: rtk is not installed; the real-rtk cases did not run"
else
REAL_PATH="$(dirname "$REAL_RTK"):$WORK/base-bin"
run "$HOOK" "$REAL_PATH" "git status"
if [[ $RC -eq 0 && "$OUT" == *'"command":"rtk git status"'* ]]; then pass; else fail "git status: want rewrite, got $RC: $OUT"; fi
# Depends on rtk's built-in rules as of 0.42.4: `echo` has no rewrite rule,
# so rtk passes it through with no output. A later rtk may add one.
run "$HOOK" "$REAL_PATH" "echo hello"
if [[ $RC -eq 0 && -z "$OUT" ]]; then pass; else fail "echo hello: want no output, got $RC: $OUT"; fi
fi
echo "== hooks.json"
if python3 - "$HOOKS_DIR/hooks.json" << 'PY'
import json, sys
(entry,) = json.load(open(sys.argv[1]))["hooks"]["PreToolUse"]
(hook,) = entry["hooks"]
assert entry["matcher"] == "Bash"
assert hook["command"] == "${CLAUDE_PLUGIN_ROOT}/.apm/hooks/route-through-rtk.sh"
PY
then pass; else fail "hooks.json does not wire the script as expected"; fi
echo
echo "Passed: $PASS Failed: $FAIL"
[[ $FAIL -eq 0 && $PASS -gt 0 ]]