Answers #168: what apm 0.28.0 can ship as a hook, which targets honour argument-level deny/ask, portable alternatives, and a layered design. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_012CqgnwEGtmfsjcoG9QwByN
16 KiB
Enforcement hooks: what apm can ship, and portable alternatives
Research for holocron issue #168 (map #166, "Infra and agent-team packages"). Captured 2026-11-12.
Question. Can the infra package enforce, not just instruct, the map's safety stance? The stance
blocks kubectl apply/delete, helm upgrade, unchecked ansible-playbook, tofu apply, vault
decryption, and reads of vault password files unless a human has approved. If it can, through what
mechanism?
Short answer. Partly. apm can ship one PreToolUse-style hook that reaches Claude Code,
Copilot (CLI and cloud agent), Codex and Gemini CLI, and each of those can deny a shell command
after inspecting its text. Only Claude Code and Copilot CLI can turn the block into an ask, which
is a real human approval. Every provider documents its hooks as best-effort guardrails rather than a
security boundary. Hooks see only the command text, so sh -c, a script the agent writes and then
runs, or a Python subprocess gets past them. Real enforcement has to come from credentials the agent
does not hold: a read-only kubeconfig, no apply credentials for tofu, an unreadable vault password
file and branch protection. Use the hook as the fast, explainable first layer, not the boundary.
Sources were the installed apm 0.28.0 source (apm_cli/, read from the pipx venv), the apm docs,
and each provider's official docs. Context7 was unavailable in this session (invalid API key), so
every citation below is a primary source fetched directly.
1. What apm ships as a hook, and where it lands
Authoring. Hook files are JSON keyed by lifecycle event, in .apm/hooks/ or a root hooks/.
apm accepts the Claude shape (PreToolUse, nested matcher and hooks) and the Copilot shape
(preToolUse, flat entries with bash/powershell/timeoutSec). ${PLUGIN_ROOT} and
${CLAUDE_PLUGIN_ROOT} resolve to the package root and are rewritten per target
(apm: Hooks and commands;
apm_cli/integration/hook_integrator.py module docstring). kyberforge's SessionStart hook
(plugins/kyberforge/.apm/hooks/hooks.json) is exactly this. apm merges it into
.claude/settings.json with the command rewritten to
${CLAUDE_PROJECT_DIR}/.claude/hooks/kyberforge/.apm/hooks/check-apm-current.sh (ADR-0019, and the
deployed .claude/settings.json).
Deployment per target (apm docs table, confirmed against _MERGE_HOOK_TARGETS and
integration/targets.py):
| Target | Deployed to | Mode | Notes from source (apm 0.28.0) |
|---|---|---|---|
| claude | .claude/settings.json |
merged | Reshaped to the nested matcher schema, default matcher * (_to_claude_hook_entries). |
| copilot | .github/hooks/<pkg>-<name>.json |
one file per hook | Events renamed to camelCase, version: 1 added (hook_integrator.py ~L1087). |
| codex | .codex/hooks.json |
merged | require_dir=True: skipped unless .codex/ already exists. No event rename and no reshape (Codex uses Claude's names and shape). |
| gemini | .gemini/settings.json |
merged | require_dir=True. PreToolUse becomes BeforeTool and timeouts become milliseconds (_to_gemini_hook_entries). |
| cursor | .cursor/hooks.json |
merged | require_dir=True, version: 1 added. No entry in _HOOK_EVENT_MAP and no shape transform (see section 4). |
| opencode | none | skipped | "OpenCode has no hooks concept" (targets.py). |
Executable-trust gate. Hooks are an executable primitive. When the consuming apm.yml has an
executables: block, a hook deploys only if the consumer approves it (apm approve). Without the
block, every executable deploys silently (apm_cli/security/executables.py docstring; ADR-0019).
That gate works in the safety stance's favour: a consumer can see, and has to approve, the guard
hook.
What apm does not ship:
- Permission rules, sandbox settings, or any
settings.jsonkey other thanhooks. No source path writespermissionsorsandbox. A repo-authored key in.claude/settings.jsonis permanentapm audit --cidrift (ADR-0018, AGENTS.md). - Tool-name translation in matchers. A
"matcher": "Bash"is written verbatim to every target, but the shell tool isBashin Claude and Codex,Shellin Cursor (Cursor hooks), andrun_shell_commandin Gemini (Gemini hooks reference). Copilot's flat format has no matcher at all. bin/onPATH. A package'sbin/deploys at user scope only, for the Claude target only, into the skill directory'sbin/(skill_integrator.py~L1571–1670, "bin/ deploy is user-scope only"). It is not a channel for portable wrapper scripts.
2. Can a pre-tool hook inspect arguments and deny or ask? Per target
| Provider | Event | Sees the command? | Deny | Ask (human approval) | Failure mode |
|---|---|---|---|---|---|
| Claude Code | PreToolUse |
tool_input.command |
exit 2 (stderr is the reason) or permissionDecision: "deny" |
Yes, permissionDecision: "ask" |
Fails open on error or timeout unless "onFailure": "block". Runs in subagents too. |
| Copilot CLI / cloud agent | preToolUse (PreToolUse alias) |
toolArgs (camelCase) or tool_input (PascalCase) |
permissionDecision: "deny" |
CLI yes. Cloud agent treats ask as deny. |
Crashes and non-zero exits fail closed; timeouts fail open. |
| Copilot in VS Code | preToolUse |
toolArgs |
deny |
Documented only loosely | Preview. Also reads the repo's .claude/settings.json hooks. |
| Codex | PreToolUse (covers shell and unified exec as Bash, plus apply_patch and MCP) |
tool_input.command |
exit 2 or permissionDecision: "deny" |
No: ask is "parsed but not supported yet" and the tool call continues |
Errors and timeouts can let the tool run. Project hooks are skipped until a human trusts them (hash-pinned). |
| Gemini CLI | BeforeTool |
tool_input (raw tool args) |
exit 2 or decision: "deny"/"block" |
Not documented | Other exit codes are non-fatal and the call continues. Project hooks are fingerprinted, with a warning on change. |
| Cursor | beforeShellExecution / preToolUse |
command / tool_input.command |
exit 2 or permission: "deny" |
beforeShellExecution yes. preToolUse accepts ask in its schema but does not enforce it. |
Fails open by default; failClosed: true per hook. |
| OpenCode | none | n/a | n/a | n/a | No hooks. |
Sources: Claude Code hooks, Copilot hooks reference, VS Code agent hooks, Codex hooks (redirected from developers.openai.com), Gemini CLI hooks and its reference, Cursor hooks.
Every vendor says hooks are not a boundary. Codex: "Treat tool hooks as a useful guardrail, not
a complete enforcement boundary". Claude's if field docs: "use the permission system rather than a
hook to enforce a hard allow or deny". Claude permissions: a Bash rule "isn't a security boundary
around the program", and the docs point to the sandbox for enforcement that doesn't depend on the
command text (Claude permissions).
Exit code 2 plus a stderr reason is the lowest common denominator for deny. Claude, Codex, Gemini and Cursor document it, and Copilot fails closed on any non-zero exit. A single script can therefore deny portably. Only ask differs per provider.
3. Portable alternatives where hooks don't reach
| Layer | Mechanism | Strength | apm-shippable? |
|---|---|---|---|
| Host permission rules | Claude permissions.deny/ask (Bash(kubectl apply *), Read(**/.vault_pass*)). Deny, then ask, then allow; a hook allow cannot override a deny or ask rule. Compound commands and subshells are split. |
Matches the text Claude writes. It "doesn't match the same program invoked in a different form" (path, sh -c). |
No. Settings keys are not an apm primitive and would be drift in .claude/settings.json. Use managed settings, user settings or settings.local.json. |
| Claude sandbox | sandbox.filesystem.denyRead on the vault password file, allowUnsandboxedCommands: false, failIfUnavailable: true. OS-level (bubblewrap/Seatbelt) and covers child processes. |
Strong for file reads, whatever the command text. Command hooks and MCP servers run outside it. | No (settings). Claude only. |
| Wrapper scripts on PATH | kubectl/helm/tofu shims that refuse mutating verbs. |
Weak: bypassed by an absolute path, command -p or a different PATH. Breaks humans who share the PATH. |
No portable channel (apm bin/ is user-scope, Claude-only, not on PATH). Not recommended. |
| pre-commit / pre-push | e.g. reject a committed file that should be vault-encrypted but lacks the $ANSIBLE_VAULT header. |
Catches mistakes at commit time. Client-side and skippable with --no-verify. Cannot stop a runtime apply. |
Out of scope for apm (.pre-commit-config.yaml in the infra repo). |
| Kubernetes RBAC | Agent kubeconfig bound to the built-in view ClusterRole. "This role does not allow viewing Secrets, since reading the contents of Secrets enables access to ServiceAccount credentials" (k8s RBAC). |
Boundary. kubectl apply/delete and helm upgrade fail server-side, whatever the shell form. It also keeps the Sealed Secrets controller key out of reach. kubectl diff needs server-side dry-run, which may need more than view (not verified here). |
No: infra and credential setup. |
| Separate apply credentials | tofu: the agent gets plan-only or read-only provider and state credentials, and apply runs with credentials held by the human or CI. Ansible: no vault password and no privileged SSH key in the agent's environment. | Boundary. | No: infra and credential setup. |
| Forge branch protection | The Flux-watched branch accepts only reviewed merges, and the agent's Gitea token cannot push or merge to it. | Boundary for the GitOps path. | No: Gitea settings. |
4. Gaps named per provider
- Claude Code: best covered. The hook deploys and is honoured, with argument-level deny and real
ask. Gaps: the hook fails open on error unlessonFailure: blockis set. A user'sdisableAllHooksturns off project hooks, and onlyallowManagedHooksOnlywith managed hooks prevents that. The permission rules and sandbox that would harden it are not apm-deliverable. - Copilot CLI: well covered. Deny and ask both work, and errors fail closed. On the cloud
agent
askbecomesdeny, so HITL commands are simply blocked there, which is the correct outcome. VS Code reads both.github/hooks/and.claude/settings.json. A package installed for bothcopilotandclaudetargets therefore runs the guard twice in VS Code. That is harmless for a deny-only idempotent script, but noisy. - Codex: deny only.
asksilently degrades to allow (the run is marked failed and the tool call continues). The script must therefore emitdenyfor HITL commands on Codex, neverask. apm skips the hook entirely unless.codex/exists, and Codex skips it until a human trusts it. A fresh install is unguarded until someone runs/hooksto review it. - Gemini CLI: deny only, and the matcher does not translate. A
Bashmatcher never fires onrun_shell_command, so ship the hook with no matcher (or*) and dispatch inside the script. apm skips it unless.gemini/exists. - Cursor: not reliably reachable through apm 0.28.0. The installed source applies no event
rename and no reshape for
cursor, so a Claude-shapedPreToolUseentry lands verbatim in.cursor/hooks.json, while Cursor's native events are camelCase with a flat{command, matcher}schema. The apm docs say "Cursor accepts Claude aliases and maps them to native names". Cursor's docs say it "supports loading hooks from third-party tools like Claude Code", but the page fetched here did not detail the mapping. I'm not certain this works. Verify with a real Cursor install before claiming coverage. Even when it works,preToolUsedoes not enforceaskand fails open unlessfailClosed: true. - OpenCode and other hookless targets: no hook layer. Only the credential layers apply.
5. Recommended layered design
- Instructions (intent). Infra skills state the stance and tell the agent to propose the command and stop. This costs nothing, but it is not enforcement.
- One portable guard hook shipped by the infra package (fast feedback, best-effort).
- A single
.apm/hooks/file on thePreToolUse/preToolUseevent, with no tool matcher. The script normalises the payload (tool_input.command,toolArgs,command) and ignores non-shell tools. - Always deny:
kubectl apply|delete|patch|replace|edit|create,helm install|upgrade| uninstall|rollback,ansible-vault decrypt|view|edit|rekey,kubeseal --recovery-unseal, and commands naming the vault password file. - HITL (
ansible-playbookwithout--check/-C,tofu apply|destroy,git pushto the Flux branch): emitaskwhere it is honoured (Claude Code, Copilot CLI) anddenyeverywhere else, with a reason telling the agent to hand the command to the human. - Signal the decision with exit 2 plus stderr as well as the JSON, so a provider that ignores
the JSON still blocks. Keep the script POSIX
shandjq-optional. - Consumers approve it through the apm executable-trust gate (version-blind grant, ADR-0019 correction).
- A single
- Host hardening, documented and not shipped. The package README or skill tells the operator
what to set per provider. Claude: deny and ask rules, plus sandbox
denyReadon the vault password file withallowUnsandboxedCommands: false, ideally in managed settings withallowManagedHooksOnlyso the guard cannot be disabled. Codex: trust the hook after review. - Credentials (the actual boundary). A
view-role kubeconfig for agent sessions, apply credentials for tofu that the agent never holds, a vault password file that the agent's OS user cannot read, and an agent forge token without push or merge rights on the Flux branch. These hold whatever the shell form and on every provider, including hookless ones. - Repo gates. The infra repo's pre-commit catches unencrypted secrets. Forge branch protection and CI catch what client hooks miss.
Trade-off. Layer 4 is outside apm and needs per-environment setup, so the package can document it but not install it. That is the price of actual enforcement. Layers 1–3 alone are bypassable by construction.
6. Open issue for the map: --check needs the vault
The stance allows ansible-playbook --check --diff freely but forbids reading vault password files.
A playbook that loads vaulted variables needs the vault secret to run at all, check mode included.
That is my understanding of Ansible's variable loading; I did not verify it against the Ansible docs
in this pass. Any layer that truly stops the agent's processes reading the password file (sandbox
denyRead, file permissions) will therefore also break the agent's check runs. The hook layer
cannot tell the agent reading the file from Ansible reading it on the agent's behalf. Possible
resolutions: run checks in CI, use a --vault-password-file client script that prompts the human,
or accept that Ansible (not the agent) reads it and enforce only "no direct read or decrypt
command". This needs a decision ticket on map #166.