Introduction
agentstacks sets up agentic coding tools from one tool-neutral copy of skills, agents, commands,
hooks and rules. Every such tool wants its setup in its own shape: Claude Code reads .claude/,
and the next tool will want something else. agentstacks keeps one copy and writes it into each tool
you use. Before anything is written, you see exactly what will change.
- A pack is what the agent gets: a named, versioned bundle of tool-neutral content.
- A tool extension is how one tool gets it: a Lua adapter that turns packs into that tool's files. It runs under airsl with no file, network or process access, and it only proposes operations.
planshows every operation.applyis the only step that touches disk, and it records pinned versions and a hash of every written file inagentstacks.lock.doctorchecks the project against that lock.
Status
agentstacks is at 1.1. It ships official extensions for Claude Code, Muse Code and OpenCode and
five official packs: core, sdlc, journal, guideline-rust and guideline-python. The
Muse Code (musecode) extension is released in packs-v1.1.0. The pack format and the
extension API are frozen as api = 1;
the stability page says what that promises. A project written for the 0.x
releases moves with agentstacks update, see Moving a Project from 0.x. You
can also add your own tool with agentstacks ext add and check it with agentstacks ext test; see
Writing a Tool Extension.
claudevs
A Claude Code plugin is a folder of hooks, skills, agents and scripts. Most of it is code that runs when Claude Code asks it to, and you rarely see it run until something goes wrong in a live session.
claudevs runs that code ahead of time, with no model in the loop, so the same input gives the same
answer every time. You describe a case in YAML or Lua, such as "this hook blocks this command", and
claudevs test checks it. claudevs check goes further and runs the whole gate: manifest
validation, wiring, the cases, and the cases again against the plugin as it looks once installed.
claudevs used to live in the claudestacks repository. It moved here with its book chapters, and it is released from this repository. Start with claudevs Getting Started.
How the book is laid out
- agentstacks: Getting Started, The Packs, moving from the claudestacks plugins, then the reference chapters: the command line, plan and apply, writing a tool extension, and the architecture.
- claudevs: getting started, writing cases, the
checkgate, embedding the engine, and how it works inside. - Appendix: the claudevs command-line reference.
Coming from the claudestacks plugins? Start with Moving from the claudestacks Plugins.
Getting Started
Two steps take a project from nothing to a working setup:
- Install agentstacks: a prebuilt binary, or
cargo install. - Set up a first project:
init,plan,apply,doctorandupdate, with the output each prints.
Moving from the claudestacks plugins instead? Read Moving from the claudestacks Plugins.
Installation
A prebuilt binary
No Rust toolchain is needed:
curl -LsSf https://airsstack.github.io/agentstacks/install.sh | sh
curl -LsSf https://airsstack.github.io/agentstacks/install.sh | AGENTSTACKS_VERSION=1.0.0 sh
The first line installs the latest release. The second installs the version you name.
agentstacks needs airsl on PATH, so the script checks for it. When it finds airsl, it leaves it
as it is and prints:
agentstacks-install: airsl found at <path>; leaving it as it is
When airsl is missing, it installs the latest airsl and prints:
agentstacks-install: agentstacks needs airsl, which is not installed; installing the latest airsl with https://airsstack.github.io/airsl/install.sh
An airsl that is found is never replaced or upgraded, even when it is too old. agentstacks plan
then names the version it needs.
The binaries go to ~/.local/bin, unless AGENTSTACKS_CLI_INSTALL_DIR is set. Archives exist for
macOS and Linux, on x86_64 and aarch64. There is no Windows build.
From crates.io
cargo install agentstacks-cli
Note: this route does not install airsl, which plan needs (≥0.1.5). Install it with:
curl -LsSf https://airsstack.github.io/airsl/install.sh | sh
Check it works
agentstacks --version
prints agentstacks 1.0.0. airsl --version reports 0.1.5 or newer.
Where agentstacks keeps things
The git cache of fetched packs and extensions lives under one root: $AIRSSTACK_HOME when
it is set and non-empty, otherwise ~/.airsstack. In a sandboxed environment that cannot
write to your home directory, set it to a writable directory:
export AIRSSTACK_HOME=/path/writable/airsstack
The same variable moves the journal vault and snapshot stores, and the hooks already honour it.
Next, set up a first project.
claudevs installs separately: see its installation.
A First Project
This chapter sets up Claude Code in a project with three official packs: core, sdlc and
guideline-rust. (sdlc requires core, so the two always come together.) The counts and
files shown are those of packs-v1.1.0.
Init
In the project directory:
agentstacks init --tool claude --pack core --pack sdlc --pack guideline-rust
--tool opencode sets up OpenCode the same way, --tool musecode sets up Muse Code, and the flags
may be given together. To use an extension from a checkout of this repository instead of a release,
copy it into your project, for example extensions/opencode to ext/opencode, and pass
--tool ext/opencode (a tool path must stay inside the project).
init writes agentstacks.toml, prints the plan as counts per owner (the full one-line-per-file
list is agentstacks plan --verbose), and asks before applying. The plan ends:
76 to write, 0 to delete, 0 unchanged, 1 skipped
Answering yes applies at once, as --yes does, and prints:
applied: 76 written, 0 deleted
note: start a new session — hooks, skills and agents load at session start
Hooks, skills and agents load when a session starts, so a setup applied into an already
running session takes effect in the next one. Preview an init without writing anything
with agentstacks init --tool … --pack … --dry-run, which prints the would-be
agentstacks.toml and its plan.
With no terminal and no --yes, init still writes agentstacks.toml but applies nothing. It
ends with:
76 to write, 0 to delete, 0 unchanged, 1 skipped
stdin is not a terminal; pass --yes to apply
agentstacks.toml written; nothing applied (run apply)
Then agentstacks apply --yes applies it and ends with applied: 76 written, 0 deleted
and the new-session note above.
The project file
The agentstacks.toml that init wrote is the committed record of what the project uses:
api = 1
[tools.claude]
git = "https://github.com/airsstack/agentstacks"
tag = "packs-v1.1.0"
subdir = "extensions/claude"
[packs.core]
git = "https://github.com/airsstack/agentstacks"
tag = "packs-v1.1.0"
subdir = "packs/core"
[packs.guideline-rust]
git = "https://github.com/airsstack/agentstacks"
tag = "packs-v1.1.0"
subdir = "packs/guideline-rust"
[packs.sdlc]
git = "https://github.com/airsstack/agentstacks"
tag = "packs-v1.1.0"
subdir = "packs/sdlc"
What was skipped
The one skipped item is shown in the plan:
skip core/hook/3: claude shows no hook output to the model at session end
An item a tool cannot express is shown as a skip with its reason, never dropped.
Plan, doctor, update
agentstacks plan shows what an apply would change now. Right after the apply, nothing:
0 to write, 0 to delete, 76 unchanged, 1 skipped
agentstacks doctor checks the project against agentstacks.lock and prints:
healthy
agentstacks update looks for a newer packs-v1.* tag. While packs-v1.1.0 is the newest, it
ends with:
nothing to update
Commit
Commit agentstacks.toml, agentstacks.lock and .claude/. A teammate runs agentstacks apply
and gets the same setup.
Next: The Command Line describes the prompt, --yes and the exit codes, and
Plan, Apply and the Lock describes what each step does.
The Packs
A pack is what the agent gets: a named, versioned bundle of tool-neutral skills, agents, commands, hooks and rules. Each tool's extension renders it in that tool's own format. The five official packs come with agentstacks:
| Pack | What it is | Needs |
|---|---|---|
core | coder, reviewer and explorer agents, an orchestrate skill that runs them in order, and the hooks: reply rules, project snapshots and the dispatcher that points the agent at the right guideline | airsl ≥0.1.5 |
sdlc | an AI-native software development lifecycle: intent, design, plan, execute, each step leaving a committed Markdown file, with a status board | core and airsl ≥0.1.5 |
journal | a memory for coding agents that you can read: notes in one Obsidian-compatible vault on your machine | core and airsl ≥0.1.5 |
guideline-rust | Rust engineering rules and a Definition of Done in one skill | nothing |
guideline-python | Python engineering rules and a Definition of Done in one skill | nothing |
sdlc or journal without core is refused. For sdlc:
agentstacks.toml: packs.sdlc: sdlc requires pack "core", which agentstacks.toml does not list (add it: --pack core)
The packs are released together as packs-v* tags. agentstacks update moves a project to the
newest release of the api it speaks (packs-v1.* for api 1). One page per pack follows.
core
The core pack. It adds three agents (coder, reviewer, explorer) and an
orchestrate skill that runs them in order, so a task is coded, checked and reviewed before it
reaches you. It also carries the pack's hooks: reply rules, project snapshots and the dispatcher
that points the agent at the right guideline.
Install
Its hooks run on airsl and exit silently when it is missing, so install that first:
curl -LsSf https://airsstack.github.io/airsl/install.sh | sh
Then, in your project:
agentstacks init --tool claude --pack core
Every skill is prefixed with the pack name, so discuss runs as /core-discuss.
Attribution
The reply rules in the discuss skill's communication protocol replace an earlier terseness
mode that was inspired by the caveman plugin.
That earlier mode kept its state in ~/.airsstack/cc/concise.json. Nothing reads that file any
more; it can be deleted.
License
Apache-2.0. See LICENSE.
sdlc
The sdlc pack: an AI-native software development lifecycle for coding agents. A change goes from
intent to design to plan to execute, each step leaves its result in a committed Markdown file, and
a status board reads those files and tells you which step is next. It follows Anthropic's
AI-native SDLC playbook at the scale of one
author. Roadmaps, milestones and architecture decision records are optional layers above the chains.
Install
agentstacks init --tool claude --pack core --pack sdlc
Every skill is prefixed with the pack name, so design runs as /sdlc-design. The pack works
without airsl, but its status board and session-start summary come from it. Some steps use the
agents from the core pack, so install that too.
Documentation
The artifact layout, states and frontmatter keys are in
references/artifact-chain.md; the file shapes are in
references/templates.md.
Attribution
Stage model, artifact shapes and feedback loops follow Anthropic's
AI-native SDLC playbook. The
execution discipline descends from claudestacks-sdd, adapted from
superpowers.
License
Apache-2.0. See LICENSE.
journal
The journal pack: a memory for coding agents that you can read. Notes are plain Markdown files in
one Obsidian-compatible vault on your machine (~/.airsstack/journal by default). The agent writes
them, you read and edit them, and the agent recalls them later instead of working the same thing
out again.
Install
Every hook and script in the pack runs on airsl, so install that first:
curl -LsSf https://airsstack.github.io/airsl/install.sh | sh
The pack requires core, and its review command uses the context-handoff skill from that pack.
Install both:
agentstacks init --tool claude --pack core --pack journal
On OpenCode, pass --tool opencode (or several tools). capture and note read the session through
opencode session export, which needs opencode on PATH and OpenCode's background service
running; otherwise they write without the transcript and say why.
On Muse Code, pass --tool musecode. The pack ships no transcript lookup for it, so capture and
note write without the transcript and key the note to the first eight characters of the session id.
Documentation
The note format is in references/note-schema.md. Each command that
captures, recalls or reviews notes is a skill under skills/, rendered as
/journal-<name>.
guideline-rust
The guideline-rust pack: Rust engineering rules and a Definition of Done in one skill, rendered as
/guideline-rust-guidelines. The core pack's enforcement hook points the agent at it when it reads
or edits a Rust file or Cargo.toml in a project with a Cargo.toml, and the core pack's coder
and reviewer agents run its Definition of Done. The pack has no hooks and no scripts.
Install
agentstacks init --tool claude --pack guideline-rust
Add the core pack as well: its dispatcher is what points the agent at this skill, and its agents
are what run the Definition of Done. On its own the skill still loads on request.
Documentation
The gate and the index of rules are in skills/guidelines/SKILL.md;
each rule is a file under skills/guidelines/references/.
License
Apache-2.0. See LICENSE.
guideline-python
The guideline-python pack: Python engineering rules and a Definition of Done in one skill, rendered
as /guideline-python-guidelines. The core pack's enforcement hook points the agent at it when it
reads or edits a .py or .pyi file or pyproject.toml in a project with a pyproject.toml, and
the core pack's coder and reviewer agents run its Definition of Done. The pack has no hooks and
no scripts.
Install
agentstacks init --tool claude --pack guideline-python
Add the core pack as well: its dispatcher is what points the agent at this skill, and its agents
are what run the Definition of Done. On its own the skill still loads on request.
Documentation
The gate and the index of rules are in skills/guidelines/SKILL.md;
each rule is a file under skills/guidelines/references/.
License
Apache-2.0. See LICENSE.
Moving from the claudestacks Plugins
This chapter is for you if you installed plugins from the claudestacks marketplace in Claude Code. The plugins became packs: the same skills, agents and hooks, installed into each project by agentstacks instead of machine-wide by the plugin system.
What maps to what
| claudestacks plugin | agentstacks pack |
|---|---|
claudestacks | core |
claudestacks-sdlc | sdlc |
claudestacks-journal | journal |
claudestacks-guideline-rust | guideline-rust |
claudestacks-guideline-python | guideline-python |
claudestacks-cmux | not converted: keep the plugin if you use it |
Install agentstacks
curl -LsSf https://airsstack.github.io/agentstacks/install.sh | sh
It installs airsl when that is missing. See Installation for the other routes.
Remove the plugins
Remove the plugins first, so their skills and hooks do not run twice beside the packs. For each plugin:
claude plugin uninstall <plugin>@claudestacks --scope <scope>
Use the scope you installed it at (the default is user). Or remove the whole marketplace:
claude plugin marketplace remove claudestacks
That uninstalls every plugin installed from it, claudestacks-cmux included.
Set up each project
In each project, pick the packs you used. sdlc and journal require core.
agentstacks init --tool claude --pack core --pack sdlc --pack journal --pack guideline-rust
Review the plan, answer the apply prompt, then commit agentstacks.toml, agentstacks.lock and
.claude/. A First Project walks through each step.
Packs install per project, never machine-wide.
What changed
Commands and agents have new names, because a native install has no plugin namespace and the extension names things by pack.
| Old (plugin) | New (pack) |
|---|---|
/claudestacks:x | /core-x |
/claudestacks:statusline | /core-statusline |
/claudestacks-sdlc:x | /sdlc-x |
/claudestacks-journal:journal-x | /journal-x |
/claudestacks-journal:journal-capture | /journal-capture |
/claudestacks-journal:journal-helped | /journal-helped |
/claudestacks-journal:journal-link | /journal-link |
/claudestacks-journal:journal-note | /journal-note |
/claudestacks-journal:journal-recall | /journal-recall |
/claudestacks-journal:journal-review | /journal-review |
/claudestacks-journal:journal-setup | /journal-setup |
/claudestacks-guideline-rust:rust-guidelines | /guideline-rust-guidelines |
/claudestacks-guideline-python:python-guidelines | /guideline-python-guidelines |
claudestacks:coder | core-coder |
claudestacks-sdlc:chain-reader | sdlc-chain-reader |
claudestacks-journal:journal-capture | journal-capture |
claudestacks-journal:journal-curator | journal-curator |
claudestacks-journal:journal-note | journal-note |
claudestacks-journal:journal-recall | journal-recall |
The other changes:
- airsl must be on
PATHand at least 0.1.5.plananddoctorreport a missing or old airsl. The hook wrappers' fallback lookup ($AIRSL_BIN,~/.local/bin,~/.cargo/bin) is gone. style_reinjectis set inagentstacks.toml, under[packs.core.options], not in the plugin's user configuration.- The statusline skill is
/core-statusline. It always detects its source as inside the project and recommends project scope. - The enforce hook finds guideline packs installed in the same project, not plugins in the registry.
sdlcrequirescore. The plugin declared no dependency, but its skills name core's agents and its agent-stop hook runs core's check.journalrequirescoretoo.- The enforce pointer names
/guideline-rust-guidelines, where it used to sayclaudestacks-guideline-rust:rust-guidelines. - The enforce doctor has no gate 1 and no parity section. Its "no manifests" stop reads
no pack ships a usable enforcement.json. - The SessionEnd reminder appears in
planas a skip. Its output was discarded before too. - A
SubagentHandbackviolation is now a deny with a reason, where it used to be exit 2 with the text on stderr. Both block the call and return the reason to the subagent, which retries. Only the error text differs: it no longer shows the hook command in brackets.
What stays
.claudestacks/sdlc/chain files are read and written at the same paths.- The journal vault stays at
$AIRSSTACK_HOME/journal(default~/.airsstack/journal). - The snapshot store stays at
${AIRSSTACK_HOME:-~/.airsstack}/snapshots/.
claudevs users
claudevs is released from this repository now. Install the prebuilt binary:
curl -LsSf https://airsstack.github.io/agentstacks/claudevs.sh | sh
cargo install claudevs-cli is unchanged. The old claudestacks installer URL will forward
here. See the claudevs Installation.
Moving a Project from 0.x
This page is for you if a project already runs on agentstacks 0.x. 1.0 reads the same
agentstacks.toml and agentstacks.lock. The one change is the api number: 0.x wrote api = 0
and 1.0 speaks api = 1. agentstacks update moves a project from one to the other.
Install 1.0 first
Install the new binary before anything else, so it replaces the 0.x one:
curl -LsSf https://airsstack.github.io/agentstacks/install.sh | sh
See Installation for the other routes. Check which one you have with
agentstacks --version.
Run update
In the project:
agentstacks update
update sees api = 0 and prints that first, then each official pack and extension that has a
newer release. The 1.0 binary only takes releases of its own major version, so a project at
packs-v0.2.0 moves to the newest packs-v1.* tag:
api: 0 → 1
packs.core: packs-v0.2.0 → packs-v1.0.0
tools.claude: packs-v0.2.0 → packs-v1.0.0
agentstacks.toml updated
It then rewrites agentstacks.toml with the new tags and api = 1, keeping your comments, and
plans, asks and applies like apply does. The Command Line lists the steps and
the exit codes.
A 0.x project is moved even when no tag is newer: it prints api: 0 → 1 first, then a note
row for each git source with nothing newer, and never nothing to update.
The first apply after the move shows some update steps for files the packs wrote before. Those
are the hook runtime, the tool's translator and, for OpenCode, its plugin, whose header names the
api. They say api 1
now, and the lock holds the old text, so they are not edits of yours.
Until you run update
plan and apply refuse a project that still says api = 0, and ext add does too. Each prints:
agentstacks.toml: api 0 is from agentstacks 0.x (run agentstacks update)
doctor is unaffected. It reads only agentstacks.lock, which 1.x reads as it is at either api,
so on a project that has not moved it reports drift as before. An apply that has nothing to write
leaves a lock at api = 0 as it was, and that is harmless; the next apply that writes anything
writes api = 1.
Path and third-party sources
update moves your agentstacks.toml. It does not change a pack or an extension you wrote or took
from somewhere else. Each of those carries its own api in pack.toml or extension.toml, and 1.0
refuses one that is still at api = 0. The plan at the end of update shows it:
packs/demo/pack.toml: demo: api 0 is from agentstacks 0.x (this agentstacks speaks 1; set api = 1, or use a newer release of it)
ext/claude/extension.toml: extension.api: 0 is from agentstacks 0.x (this agentstacks speaks 1; set api = 1, or use a newer release of it)
When the pack's name is missing or invalid, the first starts packs/demo/pack.toml: pack.api: 0 is from agentstacks 0.x instead. Because agentstacks.toml was already rewritten, update ends with
agentstacks.toml updated; fix the above and run apply and exits 1.
What to do:
- A source you own (a
pathsource): changeapi = 0toapi = 1in itspack.tomlorextension.toml. Check what else 1.0 expects in The Extension API and Hooks, then runagentstacks apply. - A third-party git source: its author has to publish a release at
api = 1. Move to that tag withagentstacks update, or edit thetaginagentstacks.tomlby hand. Until then, 1.0 cannot install it.
The official repository is the one at https://github.com/airsstack/agentstacks, byte for byte.
Any other URL, a mirror or one with a .git suffix included, keeps the plain latest-tag rule and
may offer a tag of any major version.
If a 0.x binary is still around
A 0.x binary does not know api = 1. If one runs against a project after the move, or runs
update once packs-v1.0.0 exists, it refuses what it fetches or reads, for example:
agentstacks.toml: api 1 not supported (this agentstacks speaks 0)
or the same shape for the lock (agentstacks.lock: api 1 not supported (this agentstacks speaks 0)),
a pack (<pack>: api 1 not supported (this agentstacks speaks 0)) and an extension
(extension.api: 1 not supported (this agentstacks speaks 0)). Install 1.0 and the
refusal goes. If a 0.x update already moved the tags to packs-v1.0.0, that is fine: the 1.0
update sees api = 0 still in the file, prints api: 0 → 1, rewrites only that and plans.
Once the project is on api = 1, the stability promise applies to it.
The Command Line
What the agentstacks commands do, what they print and which exit code each outcome gives. The
binary is a composition root and a presentation layer: every rule and flow lives in the library
(see architecture.md), and the planning and apply steps behind the commands are in
plan-and-apply.md.
1. Commands
agentstacks [-C <DIR>] <COMMAND>
init --tool <TOOL>... --pack <PACK>... [--yes | --dry-run]
plan [--summary | --verbose]
apply [--yes]
doctor
update [--yes]
ext add <SOURCE> [--tag <TAG> | --rev <REV>] [--subdir <DIR>] [--yes]
ext test <EXTENSION> [--pack <DIR>]...
| Command | Does |
|---|---|
init | Writes agentstacks.toml, then plans, shows the plan and applies it. Refuses when agentstacks.toml exists, except with --dry-run, which proceeds and writes nothing: it prints agentstacks.toml (dry run — not written), the rendered file and its plan (planned as a fresh project, against no lock). |
plan --verbose | The full one-line-per-file plan; without it (or with --summary) the plan shows counts per owner. |
plan | Prints the plan. Writes nothing. |
apply | Prints the plan, asks, then applies the same plan it showed. It never plans twice. |
doctor | Reports drift against the lock. |
update | Rewrites each newer tag in agentstacks.toml, then plans, shows and applies like apply. |
ext add | Adds a tool extension (a git URL with --tag or --rev, a project directory, or an official tool name) to agentstacks.toml, prints agentstacks.toml: added tools.<name>, then plans, shows and applies like update, with the same follow-ups and exit codes. |
ext test | Checks an extension against the built-in conformance pack in a temporary project: runs its Lua tests, plans, applies and plans again, and prints the plan, applied: <n> written, <m> deleted, second plan: nothing to change and a last line passed or failed. Writes nothing into the project or the extension directory. <EXTENSION> and each --pack are resolved against -C. Exits 1 when the last line is failed or the run stopped before a verdict. |
initrequires--tooland--packat least once each.ext test's--packis optional and may repeat; no other command takes--tool.-C <DIR>sets the project directory, resolved from the current directory. It works before or after the subcommand. Without it the project is the current directory. Parent directories are not searched.- When
<DIR>cannot be opened, the CLI prints<dir>: <io::Error Display>and exits 1. - Usage errors are clap's own: a missing required argument, an unknown subcommand or no subcommand
exits 2 on stderr.
--helpand--versionprint on stdout and exit 0.
2. Streams and exit codes
| Stream | Output |
|---|---|
| stdout | the plan; the doctor report; the update list; nothing to change; nothing to update; agentstacks.toml: added tools.<name>; agentstacks.toml updated; applied: …; the ext test report ending in passed or failed |
| stderr | refusals; the prompt; stdin is not a terminal; pass --yes to apply; nothing applied (apply only); the agentstacks.toml written; … and agentstacks.toml updated; … follow-ups; for ext test, what airsl test printed on its own stderr when the Lua tests fail, relayed as it came |
Refusals are printed one Diagnostic per line, sorted.
| Code | When |
|---|---|
| 0 | success: a plan shown, an apply done, nothing to change, a declined prompt, a healthy doctor, an update with nothing newer, an ext test that ends in passed |
| 1 | any diagnostic, any doctor finding, stdin is not a terminal; pass --yes to apply, an ext test that ends in failed or stops before a verdict |
| 2 | clap usage error |
3. init
init takes one or more --tool and --pack arguments:
| Argument | Meaning |
|---|---|
contains / or starts with . | a project-relative path, written as path = "<argument>" |
| anything else | an official name |
- Official packs:
core,sdlc,journal,guideline-rust,guideline-python. Official tools:claude,musecode,opencode. To use an extension from a checkout instead of a release, copy its directory (for exampleextensions/opencode) into the project and pass that path, such as--tool ext/opencode. - An official name expands to
git = "https://github.com/airsstack/agentstacks", the latestpacks-v<api>.*tag (the newest release whose major version is theapithis agentstacks speaks, sopacks-v1.*forapi = 1), andsubdir = "packs/<name>"(a tool:extensions/<name>). - A path's table key is the
namein that directory'spack.tomlorextension.toml. - Git URLs are not arguments. Add one to
agentstacks.tomlby hand. - A repeated identical argument is written once. Two different arguments that resolve to the same
key are refused at the later one:
--pack "./packs/core": pack "core" is already given by --pack "core". - A name stays a name even when a directory of that name exists: only
/or a leading.makes a path. initadds no dependencies. A missing required pack is left to the plan's set check.
Steps:
- Refuse when
agentstacks.tomlexists:agentstacks.toml: already exists (edit it and run apply). - Classify and resolve every argument. If any is refused, print every refusal and write nothing.
- Render and write
agentstacks.toml. - Plan, show, ask and apply, as in section 4.
The rendered file lists tools first in name order, then packs in name order, with keys in the order
git, tag, subdir (or path) and a blank line before each table.
Refusals
| Case | Message |
|---|---|
| file exists | agentstacks.toml: already exists (edit it and run apply) |
| unknown name | --pack "x": not an official pack; pass a path, or add a git source to agentstacks.toml / --tool "x": not an official tool; pass a path, or add a git source to agentstacks.toml |
| no release tag | --pack "core": no packs-v1 release tag in https://github.com/airsstack/agentstacks |
git missing from PATH | one refusal for all official arguments: init: git not found on PATH (needed by --tool "claude", --pack "core") |
| path absolute / climbs out | --pack "/x": absolute paths are not portable / --pack "../x": must stay inside the project |
| path resolves outside through a symlink | --pack "./x": resolves outside the project |
| path I/O | <path as written>: <io::Error Display> |
| write fails | agentstacks.toml: <io::Error Display> |
A path source in a pack or extension is named in refusals by the path as written in
agentstacks.toml, not by its absolute path.
After the file is written
init leaves agentstacks.toml in place when the plan is refused or declined, and says so on
stderr:
| Outcome | stderr | Exit |
|---|---|---|
| plan refused | the refusals, then agentstacks.toml written; fix the above and run apply | 1 |
| declined | agentstacks.toml written; nothing applied (run apply) | 0 |
no terminal, no --yes | stdin is not a terminal; pass --yes to apply, then agentstacks.toml written; nothing applied (run apply) | 1 |
| applied | as section 6 | 0 |
| apply failed, or the lock read failed | the diagnostics, then agentstacks.toml written; fix the above and run apply | 1 |
4. plan and apply
plan prints the plan and exits 0. A refused plan prints its refusals and exits 1. apply prints
the plan, runs the confirmation (section 5), and on yes applies that same plan.
A project written for the 0.x releases is refused by both, with nothing planned and
nothing written: agentstacks.toml: api 0 is from agentstacks 0.x (run agentstacks update). Any other
api that is not 1 gives agentstacks.toml: api <n> not supported (this agentstacks speaks 1). See
moving a project from 0.x.
Plan text
By default the plan is a summary: one <owner> <w> to write, <d> to delete, <u> unchanged
row per owner (shared last), then the skip rows, the airsl row and notes, and the final
count line. --verbose shows the full text below: one row per file, with diffs. The
commands that show a plan before applying (apply, init, update, ext add) show the
summary; ext test shows the full text.
agentstacks plan
create .claude/skills/core-status/SKILL.md core
update .claude/agentstacks/runtime.lua claude
delete .claude/agents/team-lint-old.md team-lint
update .claude/settings.json shared
--- .claude/settings.json
+++ .claude/settings.json
@@ -3,5 +3,17 @@
…
skip core/hook/2: claude gives hooks the session id in the event (event.session_id), not as {{var session_id}}
airsl 0.1.4 (pinned)
note native/cluade: not for claude
3 to write, 1 to delete, 12 unchanged, 1 skipped
(The … stands for the rest of the diff.)
| Row | Rule |
|---|---|
| step | Every step whose action is Create, Update, Restore, Delete or Forget, in the plan's path order. Unchanged is counted, not listed. Two spaces, the action in lower case padded to 8, a space, the path padded to the longest listed path, two spaces, then the owner. The owner is the pack or extension name, or shared when the step has none. |
| diff | Below an Update step that had an old text: a unified diff with three lines of context and the path as both headers, each line indented four spaces. Bytes that are not UTF-8 are decoded lossily. Identical texts give no lines. |
| skip | skip <subject>: <reason>. The subject is the item id, or <pack>/<rel> for a core root-file skip. |
| airsl | airsl <v> (pinned) when the locked and installed versions are equal; airsl <locked> → <installed> when they differ; airsl <installed> (new pin) when the lock had none. |
| binary | none. A missing binary already stops the plan, and found binaries are not listed. |
| note | note <Note Display> |
| summary | <w> to write, <d> to delete, <u> unchanged, <s> skipped, then , <f> forgotten when f is above 0. w counts Create, Update and Restore; d counts Delete; u counts Unchanged; s counts skips; f counts Forget. |
Empty sections are left out, together with the blank line before them. There is no colour.
5. Confirmation
init, apply and update share one sequence after the plan is shown:
nothing to change? ── yes ─► print plan + "nothing to change", exit 0, no question, nothing written
│ no
--yes? ── yes ─► apply
│ no
stdin a terminal? ── no ─► "stdin is not a terminal; pass --yes to apply", exit 1
│ yes
"Apply? [y/N] " on stderr, read one line
trimmed, case-insensitive "y" or "yes" ─► apply
anything else, empty, end of input, or a read error ─► decline line, exit 0
The decline line is nothing applied for apply. init and update print only their follow-up
line instead (agentstacks.toml written; nothing applied (run apply) and agentstacks.toml updated; nothing applied (run apply)).
- Nothing to change means no listed step, and the lock the plan would write equals the current lock text. An absent lock is never equal.
- Lock read error: the current lock is read first. A failure prints
agentstacks.lock: <io::Error Display>, exits 1, asks nothing and applies nothing.initandupdateadd their follow-up line (sections 3 and 7). - A piped stdin and
/dev/nullare not terminals, so without--yesthey refuse.
6. After apply
| Result | Output | Exit |
|---|---|---|
| applied | stdout applied: <w> written, <d> deleted, then, when anything changed, note: start a new session — hooks, skills and agents load at session start | 0 |
| failed | the diagnostics, e.g. <path>: changed after plan; run plan again | 1 |
7. update
- List the newer tags. A refusal is printed and exits 1.
- Print each entry on stdout:
<key>: <current> → <new>for a new tag,note <UpdateNote Display>for a note.<key>ispacks.coreortools.claude. A project written for the 0.x releases (api = 0) first printsapi: 0 → 1. - With no new tag and the
apialready current, printnothing to update, exit 0 and write nothing. A 0.x project is not in this case: it is moved toapi = 1even when no tag is newer. - Rewrite
agentstacks.tomlwith each new tag and, for a 0.x project, withapi = 1, comments kept, and printagentstacks.toml updated. A refusal exits 1 with the file unchanged and no plan. - Plan, show, confirm and apply exactly as
applydoes (sections 4 to 6), then add the follow-up on stderr.
| Step 5 outcome | stderr follow-up | Exit |
|---|---|---|
| plan refused, apply failed, or lock read failed | agentstacks.toml updated; fix the above and run apply | 1 |
| declined | agentstacks.toml updated; nothing applied (run apply) | 0 |
no terminal, no --yes | stdin is not a terminal; pass --yes to apply, then agentstacks.toml updated; nothing applied (run apply) | 1 |
| applied, or nothing to change | none | 0 |
Step 4 refusals:
| Case | Message |
|---|---|
| re-read fails | agentstacks.toml: <io::Error Display> |
api no longer the legacy 0 at re-read | agentstacks.toml: api changed during update (run update again) |
| re-read text no longer parses | the project file's own parse refusals |
| a tag missing at re-read | agentstacks.toml: packs.core: no tag to update (run update again) |
| a tag that differs from the listed current tag | agentstacks.toml: packs.core: tag changed during update (run update again) |
| write fails | agentstacks.toml: <io::Error Display> |
After step 4, agentstacks.toml names a new tag while the lock still pins the old revision. The plan
reconciles that entry as stale and resolves it again, so update needs no special case.
8. doctor
Prints each finding on stdout, one per line, in the order returned, for example
changed: .claude/agents/core-coder.md or airsl: 0.1.5 installed, lock pins 0.1.4. With no findings it
prints healthy and exits 0. Any finding exits 1.
doctor reads the lock and the files it names, never agentstacks.toml, and checks the
airsl runtime when the project needs it: the lock pins airsl, a locked file is a hook
runtime (runtime.lua), or there is no usable lock to tell from. Missing airsl is reported
with the install command, with or without a lock pin
(airsl: not found on PATH (install: curl -LsSf https://airsstack.github.io/agentstacks/install.sh | sh), airsl: not found on PATH (lock pins <v>) (install: curl -LsSf https://airsstack.github.io/agentstacks/install.sh | sh));
a parseable installed version is healthy without a pin, an exact match is required with
one, and a project with neither a pin nor a hook runtime is healthy without airsl.
A lock written by a 0.x release is read like a current one: its api is not a finding.
9. ext add
agentstacks [-C <DIR>] ext add <SOURCE> [--tag <TAG> | --rev <REV>] [--subdir <DIR>] [--yes]
<SOURCE> is classified by its text alone:
<SOURCE> | Meaning |
|---|---|
contains :// or starts with git@ | a git URL; needs --tag or --rev, and takes --subdir |
contains / or starts with . | a project-relative path, written as path = "<SOURCE>" |
| anything else | an official tool name (claude, musecode, opencode) |
--tagand--revexclude each other (clap, exit 2).--tag,--revand--subdirapply only to a git URL.- An official name is written as the official repository at its newest
packs-v1.*tag, withsubdir = "extensions/<name>", the same rule asinit(section 3). - The table key is the
namein the extension'sextension.toml. The extension is fetched or read and loaded before anything is written, so a refused extension never reachesagentstacks.toml.
Steps:
- Read
agentstacks.tomland refuse a legacy or unsupportedapi. - Resolve the source and load the extension. Every refusal is printed and nothing is written.
- Re-read
agentstacks.toml; refuse when it changed since step 1. - Add
[tools.<name>], keeping comments, and printagentstacks.toml: added tools.<name>on stdout. - Plan, show, confirm and apply exactly as
updatedoes (sections 4 to 6), with the same follow-ups on stderr (agentstacks.toml updated; …) and exit codes as theupdatetable in section 7. A refused plan keeps the new table.
A refusal in steps 1 to 4 exits 1 with no plan and the file as it was.
Refusals
| Case | Message |
|---|---|
| file missing or unreadable | agentstacks.toml: <io::Error Display> |
| legacy project | agentstacks.toml: api 0 is from agentstacks 0.x (run agentstacks update) |
other api | agentstacks.toml: api <n> not supported (this agentstacks speaks 1) |
| unknown name | ext add "x": not an official tool; pass a path or a git URL |
| git URL with neither flag | ext add "<url>": a git URL needs --tag or --rev |
| flag with a name or path | ext add "<source>": --tag applies only to a git URL (likewise --rev, --subdir; one line per flag) |
| empty value | ext add "<url>": --tag: empty (likewise --rev, --subdir) |
--rev not a commit id | ext add "<url>": --rev: not a commit id |
--subdir climbs out | ext add "<url>": --subdir: must stay inside the repository |
| path absolute / climbs out | ext add "/x": absolute paths are not portable / ext add "../x": must stay inside the project |
| path resolves outside through a symlink | ext add "./x": resolves outside the project |
| path I/O | <path as written>: <io::Error Display> |
git missing from PATH | ext add: git not found on PATH (needed by ext add "<source>") |
| git fails | ext add: git <subcommand> failed: <stderr> |
--subdir missing in the repository | ext add "<url>": "<dir>" not found at <rev> / ext add "<url>": "<dir>" is a file, not a directory |
| no tag of this major | ext add "claude": no packs-v1 release tag in https://github.com/airsstack/agentstacks |
| the extension is refused | the loader's own refusals, located at its files, such as ext/mytool/extension.toml: extension.api: 2 not supported (this agentstacks speaks 1) |
| tool already listed | agentstacks.toml: tools.<name> already exists (edit it there) |
| file changed meanwhile | agentstacks.toml: changed during ext add (run it again) |
| write fails | agentstacks.toml: <io::Error Display> |
10. ext test
agentstacks [-C <DIR>] ext test <EXTENSION> [--pack <DIR>]...
Checks a tool extension the way plan and apply will use it, without touching the project or the
extension. It needs airsl on PATH. <EXTENSION> and each --pack are directories, resolved
against -C (or the current directory) and shown in refusals as written. --pack adds your own
pack to the temporary project beside the built-in conformance pack; a pack with that name, or two
packs with one name, are refused. The command never reads the project's agentstacks.toml.
Steps, in order:
airslis onPATH.- The extension directory is opened and loaded like any extension.
- When the extension holds a Lua test file (
*_test.luaortest_*.lua),airsl testruns in its directory. - Each
--packis opened and named, and the temporary project is created: the extension, the conformance pack, your packs and anagentstacks.tomllisting them. - The project is planned.
- The plan is applied.
- The project is planned again; the second plan must hold no step that writes, deletes or forgets (a skip is allowed).
- The verdict.
A failure of step 1 or 2 stops the run with no verdict. A failure of step 4, 5 or 6 stops it with the
verdict failed. A failing step 3 or 7 does not stop the run and makes the verdict failed.
Output
stdout holds, in order and only for the steps that ran:
ext test demo 1.2.0
lua tests: 71 passed, 0 failed (5 files)
agentstacks plan
create …
2 to write, 0 to delete, 0 unchanged, 0 skipped
applied: 2 written, 0 deleted
second plan: nothing to change
passed
| Line | Rule |
|---|---|
ext test <name> <version> | the extension's name and version from extension.toml |
lua tests: … | lua tests: <last line airsl test printed> on success (lua tests: passed when it printed nothing); lua tests: none when the extension holds no test file; lua tests: failed followed by what airsl test printed on stdout |
| the plan | as in section 4 |
applied: <w> written, <d> deleted | after step 6 |
second plan: nothing to change | step 7 passed |
second plan: <w> to write, <d> to delete (apply is not repeatable) | step 7 failed, followed by the second plan; , <f> forgotten follows <d> to delete when the second plan forgets f entries |
passed or failed | the last line; absent when step 1 or 2 stopped the run |
stderr holds the refusals, and what airsl test printed on its own stderr when the Lua tests fail.
The exit code is 0 for passed and 1 for failed or for no verdict.
Refusals
| Case | Message |
|---|---|
airsl missing | ext test: airsl not found on PATH (needed for the Lua tests and the hooks) |
airsl test cannot start | ext test: airsl test: <io::Error Display>, with lua tests: failed on stdout |
| a directory cannot be opened | <path as written>: <io::Error Display> |
| the extension is refused | the loader's own refusals, located at its files |
--pack has no pack.toml | --pack "<dir>": not a pack (no pack.toml) |
--pack repeats a name | --pack "<dir>": pack "<name>" is already given by --pack "<first>" |
--pack named conformance | --pack "<dir>": pack "conformance" is already given by the built-in conformance pack |
| a symlink or special file in a tree | <path>: symlinks are not allowed in a pack and the like |
| plan or apply refused | the plan's own refusals (for example the extension does not cover an item), with verdict failed |
The temporary project is removed when the command returns.
Plan, Apply and the Lock
How the core turns a project into a plan a human reads, applies it as the only writer, and checks it later. This guide is for core contributors. The layering it sits in is architecture.md. What an extension proposes is in extensions.md, and how hooks run is in hooks.md.
The core is tool-neutral: it knows no tool's file shapes. Where a message names a tool
(claude/adapter.lua, .claude/settings.json), it is an example: claude extension.
Where the code lives:
| Piece | Location |
|---|---|
| rules | crates/agentstacks/src/types/ (op, plan, resolve, json, protocol) |
| flows | crates/agentstacks/src/app/ (plan, apply, doctor, update) |
| ports | crates/agentstacks/src/port/ (FileTree, Workspace, Git, Binary, Adapter) |
| adapters | crates/agentstacks/src/fs/, process/, host/ |
1. The flow
app/plan runs these ten steps. Each asks a port for facts and hands them to a rule in types/.
1 read agentstacks.toml + agentstacks.lock Workspace
2 reconcile lock vs toml → what to fetch types/resolve
3 fetch / read sources, tree hashes Git, Workspace
4 load + check the set (the pack and extension format checks) types
5 per tool, in name order: values → render → plan Adapter
per removed tool: values → plan with zero packs
6 validate ops, coverage, duplicates types/op
7 binary checks: packs' requires.binaries, extension require_binary, airsl Binary
8 read each target's disk state Workspace
9 decide each path's step types/plan
10 return Plan, or every refusal none
Step 1 also refuses a project written for the 0.x releases, with the refusal that names
agentstacks update (the command line). The lock is still read,
and nothing else runs.
A refusal in steps 1 to 7 skips steps 8 and 9. No step is decided, so no false delete appears.
Order of tools. Listed tools run in name order, then removed tools in name order. Each listed
tool's core writes are recorded just before its plan dispatch, so the order decides which proposal
is the earlier one. Two messages name the earlier proposer when it is the core:
- the earlier proposer is the core's
runtime.lua:path "<p>" is already proposed by core (runtime.lua of claude) - a core write that meets an earlier tool's path:
agentstacks.toml: tools.opencode: path "<p>" is already proposed by claude
A Plan holds:
- steps, each with path, action, owner and op origin, plus the new bytes; for a shared file, the old bytes too, so the CLI can show a diff;
- skips with their reasons;
- binary checks;
- notes;
- the disk state each step was decided on;
- the new lock contents.
Notes list what the pack format loaders ignore, and a source that was resolved again. Three messages:
<pack>/<path>: ignored (dot entry)native/cluade: not for claudeagentstacks.toml: packs.core: source changed, resolved again
Refusals are collected, never first-only, and sorted. A plan with any refusal applies nothing.
2. Operations
The kinds and their fields are in extensions.md, and their validation in extensions.md. In short:
| Kind | Proposed by | Effect |
|---|---|---|
write, copy, skip, require_binary | extension | put bytes at a path, put a pack file's bytes at a path, install nothing with a reason, require a binary |
write (core) | core | each pack root file goes to <root>/<pack>/<rel>; runtime.lua goes to <root>/runtime.lua when a pack of this tool has a lua hook or a native lua hook, whether or not the extension later skips it |
require_binary (core) | core | each pack's requires.binaries; airsl when any locked pack declares requires.airsl |
delete | core | a locked file no longer proposed |
by, the lock's owner of a file, is derived: a copy, or a write whose covers all belong to one pack,
is owned by that pack; a core write of a root file is owned by its pack; any other write is owned by
the tool. A shared file has no by.
3. Steps
Disk states, read through Workspace: absent, a regular file (bytes, hash, mode), or not a
regular file.
Shared means the path is in this tool's extension.reads and the extension read it in this run.
A shared file is never written to the lock, so doctor never sees it, and a pack or tool removal
handles it by rerunning the extension.
| Proposed path | In the lock | Disk | Step |
|---|---|---|---|
| any | any | not a regular file | refused <path>: is not a regular file |
| shared | none | absent, and read returned absent | create |
| shared | none | equals what read returned | update, or unchanged when the new bytes equal the disk; old bytes kept for the diff. A lock entry for it, if any, is dropped |
| shared | none | differs from what read returned | refused <path>: changed after it was read; run plan again |
| not shared | yes | absent | restore |
| not shared | yes | hash = lock hash | update, or unchanged when equal |
| not shared | yes | hash ≠ lock hash, bytes = new bytes | unchanged (the user made the same edit; the lock takes the new hash) |
| not shared | yes | hash ≠ lock hash, bytes ≠ new bytes | refused <path>: changed since the last apply |
| not shared | no | absent | create |
| not shared | no | bytes = new bytes | unchanged (adopted into the lock) |
| not shared | no | bytes ≠ new bytes | refused <path>: exists and was not written by agentstacks |
| Locked path no longer proposed | Disk | Step |
|---|---|---|
| any | the path itself is now a symlink (dangling or pointing outside included) | forget; the user replaced it, so it is left alone. Checked before any other row |
| any | absent | forget (dropped from the lock) |
| any | hash = lock hash | delete |
| any | hash ≠ lock hash | refused <path>: changed since the last apply; not deleting it |
| any | not a regular file | refused <path>: is not a regular file |
Checked examples:
| Situation | Step |
|---|---|
first apply; .claude/skills/core-status/SKILL.md absent | create |
| user edited that file after apply; pack unchanged | refused .claude/skills/core-status/SKILL.md: changed since the last apply |
| user deleted it | restore |
pack team-lint removed from toml; its file .claude/agents/team-lint-old.md untouched | delete |
.claude/settings.json holds the user's permissions; the claude extension read it and proposes it with hooks added | update (shared), diff shown, not locked |
.claude/settings.json absent; the extension read nil and proposes it | create (shared), new-file mode |
.claude/agents/core-coder.md exists, never written by agentstacks, different content | refused .claude/agents/core-coder.md: exists and was not written by agentstacks |
a proposed path is a symlink to /etc/hosts | refused <path>: resolves outside the project |
4. Inside the project
Every proposed path, deleted path and read path is resolved by Workspace with one rule:
- If the path is a symlink, follow it. A dangling symlink is "not a regular file".
- Otherwise canonicalise the deepest existing ancestor.
- The result must start with the canonical project root. Otherwise: refused
<path>: resolves outside the project(forread, at the caller's line).
A symlink that stays inside the project is written through: the write goes to its canonical target and the link survives. The lock records the normalised proposed path, never the canonical one.
Two details of the built Workspace: a dangling symlink at stage or swap is an I/O NotFound
(symlink leads nowhere), and a path that resolves to the project directory itself is refused at
stage and swap (resolves to the project directory).
A path source directory goes through the same rule. Outside: refused
agentstacks.toml: packs.team-lint.path: resolves outside the project.
5. Removed pack and removed tool
A pack removed from agentstacks.toml gets delete steps for its locked files, under the rules of
section 3.
A tool removed from agentstacks.toml runs its locked extension once with zero packs, so it cleans
its own shared-file entries:
- the extension is resolved from the lock, and its git tree is checked against its lock
treelike any locked entry; - its ops are still checked against each other;
- only its writes to paths it read in that run (shared files) are kept, and only those meet the other tools' proposals. Every other proposal is dropped and never reaches the duplicate check, and no core write is made for its root;
- all of its locked files then get delete steps under the rules of section 3;
- nothing from that tool is locked.
6. Apply
app/apply takes the Plan that app/plan returned, the same Plan the CLI showed. It never
re-plans.
1 refuse a Plan that holds refusals
2 stage: for each create/update/restore write <dir>/.<name>.agentstacks-tmp
(parents created; a leftover temp of the same name is overwritten)
3 check: every target's disk state still equals the state the Plan recorded
(for a shared file: what read returned); any differs →
remove the temps, refused `<path>: changed after plan; run plan again`
4 swap: rename each temp onto its (canonical) target; perform each delete
5 lock: write agentstacks.lock last (`types::lock::write_lock`), via temp + rename
- Temps sit beside the canonical target. The lock temp is
.agentstacks.lock.agentstacks-tmp, and the lock keeps its mode. - A path that resolves outside the project at apply time is refused:
<path>: resolves outside the project. - A write step with no content is refused
<path>: has no content to write. A plan built from valid proposals never holds one. - The check compares content hashes only, so a mode-only change between plan and apply is not "changed".
Modes:
- A new or restored file gets the mode
std::fs::writecreates. - An updated file keeps its old mode. A rename installs the temp's mode, so
fscopies the old permissions onto the temp before the rename.
Failures:
| Step | Result |
|---|---|
| 2 or 3 | the temps written so far are removed, nothing is swapped, the lock is untouched; I/O failure: <path>: <io::Error Display>. Directories already created are left |
| 4 | stop; remove the remaining temps; write the lock with only what landed (renamed files carry their new hash, the rest keep their old entries); report <path>: <io::Error Display> |
| 5 | agentstacks.lock: <io::Error Display>. The files have landed, so the next plan finds each one equal to its new bytes (the "bytes = new bytes" rows of section 3), and the lock heals |
The lock after a step 4 failure: [[tool]], [[pack]] and [airsl] take the new values.
[[file]] holds new entries for files that landed and old entries for those that did not. forget
steps and every unchanged step apply, because they never touch the disk.
Directories a delete leaves empty are left in place.
Lock content:
[[tool]]and[[pack]]with rev and tree;[[file]]for every non-shared path in a create, update, restore or unchanged step, with itsby;[airsl] versionexactly when a locked pack declaresrequires.airsl, socheck_airsl_presencepasses.
7. The lock
agentstacks.lock records tools, packs, the non-shared files with their by, and [airsl].
Shared files are never recorded.
-
The lock is written with
api = 1. It is read atapi = 0too, so the lock of a project built by a 0.x release loads as it is, and the nextapplyrewrites it atapi = 1. Any otherapiis refused:agentstacks.lock: api 2 not supported (this agentstacks speaks 1). A lock atapi = 0is not adoctorfinding. -
There is no
[[merge]]table. The key is unknown:agentstacks.lock: merge: unknown key. -
A
[[file]].pathcontaining\is refused when the lock is read:agentstacks.lock: file[0].path: "a\b" must use / as the separator. -
A lock path naming
agentstacks.tomloragentstacks.lockis refused:agentstacks.lock: file[0].path: "agentstacks.lock" is managed by agentstacks(the same shape foragentstacks.toml). -
check_airsl_presenceruns on the new lock contents only. The lock read in step 1 of the flow is not checked with it.
8. Doctor
app/doctor is offline. It reads the lock and the disk and returns findings; none means healthy. It
needs no extension, because shared files are not in the lock.
| Check | Finding |
|---|---|
| a lock exists | agentstacks.lock: not found (run apply) (then no other check) |
| lock parses | the lock's own refusals |
each [[file]] exists | missing: <path> |
each [[file]] is a regular file (a symlink to one inside the project counts) | not a regular file: <path> |
each [[file]] hash matches | changed: <path> |
[airsl] present: the binary is on PATH | airsl: not found on PATH (lock pins 0.1.4) |
its --version parses | airsl: --version printed "<text>", expected "airsl <version>" |
| installed version = lock version | airsl: 0.1.5 installed, lock pins 0.1.4 |
Two more findings: a [[file]] that resolves outside the project is outside the project: <path>,
and an I/O failure is <path>: <io::Error Display>.
A locked path that normalises to nothing (such as ., which names the project directory itself)
cannot form a project path, and is reported not a regular file: <path>.
Findings follow the lock's path order, then airsl.
9. Sources
Reconciliation
agentstacks.toml | agentstacks.lock | Result |
|---|---|---|
| entry | none | new: resolve (git: tag → rev; path: read) |
| entry | entry with the same source fields (git, tag, rev, subdir / path) | use the lock's rev; the git tree must equal the lock's tree, else refused agentstacks.toml: packs.core: tree sha256:<a> at rev <rev> differs from the lock's sha256:<b>; a changed path tree is a normal change, shown in the plan |
| entry | entry with different source fields | stale: resolve as new; plan note agentstacks.toml: packs.core: source changed, resolved again |
| none | pack entry | removed: its files get delete steps |
| none | tool entry | removed: section 5 |
A moved remote tag does not move a locked entry. The lock's rev wins, and no network is used.
update is the only way to move it.
"Same source fields" compares normalised values (./packs/core equals packs/core). Messages quote
a value as written.
Git
Every command runs with GIT_TERMINAL_PROMPT=0 and -c core.autocrlf=false, and passes the URL
after --. subdir is normalised before use. The variables that name a repository (GIT_DIR and
its kin) are removed from the environment, so an inherited one cannot redirect a command. The code is
crates/agentstacks/src/process/git/.
| Step | Command |
|---|---|
| list tags | git ls-remote --tags --refs -- <url> 'refs/tags/<prefix>*' → lines <40hex>\t<ref>; empty output with exit 0 when nothing matches |
| fetch a tag | git init --bare -q <tmp>; git -C <tmp> fetch --no-tags --depth 1 -- <url> refs/tags/<tag>:refs/tags/<tag>; rev = rev-parse --verify --end-of-options refs/tags/<tag>^{commit} (annotated tags need ^{commit}) |
| fetch a rev | git -C <tmp> fetch --no-tags --depth 1 -- <url> <rev> |
| list files | git -C <repo> ls-tree -r -z --full-tree <rev> -- <subdir>; records <mode> SP <type> SP <oid> TAB <path> NUL, byte-ordered |
| read blobs | git -C <repo> cat-file --batch; bytes unconverted even with core.autocrlf=true |
For a source with no subdir, ls-tree omits the pathspec and lists the whole tree.
The source's tree is read into memory once and served through the FileTree port. Git modes map as:
100644 and 100755 are a file, 120000 is a symlink (so the pack format's "symlinks are not
allowed" refusal applies), and any other mode (a gitlink, 160000, included) is other. A git
source's tree label, which prefixes its load messages, is the subdir as written, or . without
one.
| Failure | Refusal |
|---|---|
git not on PATH | once: agentstacks.toml: git not found on PATH (needed by packs.core, tools.claude) |
| git exits non-zero | agentstacks.toml: packs.core: git <subcommand> failed: <git's stderr, trimmed>, e.g. … fatal: could not read Username for 'https://github.com': terminal prompts disabled, … fatal: couldn't find remote ref refs/tags/packs-v9.9.9 |
URL starting with - | never reaches a flag: git refuses it itself, fatal: strange pathname '-oops' blocked |
subdir lists nothing at that rev | agentstacks.toml: packs.core.subdir: "packs/nope" not found at <tag or rev> |
subdir names a file | agentstacks.toml: packs.core.subdir: "packs/core/pack.toml" is a file, not a directory |
| a removed tool whose locked source is neither cached nor fetchable | the git refusal above; the plan is refused, and nothing is removed until the source is reachable |
Git or airsl output that does not parse (a cat-file frame, a <oid> missing answer, rev-parse
output that is not a commit id, an ls-tree record or an ls-remote line) is decoded as lossy UTF-8
and trimmed of surrounding whitespace. airsl exiting non-zero counts as unparseable. The refusals:
agentstacks.toml: packs.core: git <subcommand> printed output agentstacks cannot read: "<first line>"agentstacks.toml: airsl --version printed "<text>", expected "airsl <version>"(<text>trimmed)
The decode and trim cover quoted text and ls-remote lines. ls-tree -z paths stay raw bytes.
Cache
- Layout:
<root>/cache/git/<hex sha256 of url>/<rev>.git(bare), where the root is$AIRSSTACK_HOMEwhen it is set and non-empty, otherwise~/.airsstack. A locked rev whose<rev>.gitexists resolves without network. The directory helper iscrates/agentstacks/src/fs/cache.rs, the one piece offstheprocessadapter uses. - Filling it:
- Fetch into
<url dir>/tmp-<pid>-<n>(<n>counts up within the process). A tag fetch learns its rev here. - Rename it to
<rev>.git. A rename onto an existing non-empty directory fails withDirectoryNotEmpty; another run cached it first, so the temp is removed and the existing one is used.
- Fetch into
- A leftover cache temp of the same name is removed and reused.
- A failed cache rename is reported at the
<rev>.gittarget. - Home directory:
$AIRSSTACK_HOMEwhen set and non-empty (an empty value counts as unset, as in the hooks'${AIRSSTACK_HOME:-$HOME/.airsstack}), otherwise$HOME/.airsstackas the root. When neither is set, reported once:agentstacks.toml: AIRSSTACK_HOME and HOME are not set, so the cache (~/.airsstack/cache) has no home. A cache write that fails (a sandboxed home, say) is reported at its path with the remedy:<path>: <error> (set AIRSSTACK_HOME to a writable directory to move the cache). - Temps left by a killed process are never cleaned up.
There is no lock file for the cache. Concurrency is handled by fetching into a temporary directory and renaming it into place.
Generated-file stamps
Each official extension stamps the files it writes in Markdown and Lua: for Markdown
<!-- generated by agentstacks — change agentstacks.toml and re-run apply, do not edit -->,
for Lua -- generated by agentstacks — change agentstacks.toml and re-run apply, do not edit,
placed after the frontmatter of a Markdown file that has one, otherwise as the first line.
JSON files (shared settings), copied pack files and every other format are not stamped,
because JSON admits no comments and a copy stays verbatim. The stamped bytes are what the
plan hashes and the lock records, so re-planning an applied project is nothing to change.
10. Update
app/update finds the latest tag for each git source. latest_tag(tags, prefix, major) returns
Option<tag>; major is an optional required major version, and None keeps every major:
- List
refs/tags/<prefix>*. - Take each tag's suffix after
prefix. Keep those that parse as semver and are not pre-releases. With a required major, keep only those of that major. - Return the highest by semver. If none remains, return
None. Equal precedence (build metadata only) returns the greater tag in byte order.
Splitting a current tag into prefix and version: the version starts at the leftmost ASCII digit whose remainder parses as semver.
packs-v0.1.0→ prefixpacks-v, version0.1.0x-1.2.3-4.5.6→ prefixx-, version1.2.3-4.5.6
| Case | Result |
|---|---|
| current tag has no such split | note agentstacks.toml: packs.core: tag "main-latest" has no version to update from |
latest_tag returns None, or nothing newer than the current tag | note agentstacks.toml: packs.core: no newer tag than packs-v0.1.0 |
source pinned by rev | note agentstacks.toml: packs.core: pinned to rev <rev>, not updated |
path source | nothing |
app/update returns one entry per git source: its key, the current tag, and the new tag or the
note. Entries follow key order: packs.*, then tools.*.
For the official repository (the URL equal to https://github.com/airsstack/agentstacks byte for
byte, so a .git suffix makes it a third-party source) and the prefix packs-v, major is the
api this agentstacks speaks: a 1.x binary updates packs-v0.2.0 to the newest packs-v1.* and
never to packs-v2.*. Every other source passes None. The init shorthand and ext add
follow the same rule, and init refuses with no packs-v1 release tag in <url> when no tag of that major exists.
The library owns writing a new tag into agentstacks.toml (app/update), shorthand expansion
(prefix packs-v) and its refusal when latest_tag returns None (app/newest, app/init).
11. Binaries and the airsl pin
| Requirement | Check | Refusal |
|---|---|---|
a pack's requires.binaries | PATH lookup through Binary | agentstacks.toml: packs.core: binary "rg" not found on PATH |
an extension's require_binary | PATH lookup | claude/adapter.lua:7: require_binary: "node" not found on PATH |
airsl, when any locked pack declares requires.airsl | airsl --version → airsl 0.1.4, parsed as airsl <semver> | not found: agentstacks.toml: airsl not found on PATH (needed by core, sdlc) / unparseable: agentstacks.toml: airsl --version printed "<text>", expected "airsl <version>" / out of range: agentstacks.toml: airsl 0.1.3 installed, packs need >=0.1.4 |
A binary required by both a pack and an extension is reported once for each.
"On PATH" means a regular file with an execute bit. Empty PATH entries are skipped, and an unset
PATH finds nothing. A symlink on PATH counts when it resolves to an executable regular file.
The installed airsl version is written to [airsl] version. A newer version in range moves the pin,
and the plan shows airsl 0.1.4 → 0.1.5. A missing airsl after install is caught in two ways: the
tool's own error for a missing command (under OpenCode, the shim's one-time notice to the model,
see OpenCode), and doctor (section 8).
12. Where a refusal is located
Every refusal is a Diagnostic with a Location: a file, plus a line or key path. It is displayed
as <file>:<line>: <what> or <file>: <key>: <what>, and sorted.
| Location file | Used for | Example | Raised in |
|---|---|---|---|
<tool>/<extension file> with line | op arguments, read, require, json.edit | claude/adapter.lua:12: write: path: expected string, got number | host (reading) + types/op (rule) |
<tool>/<entry> with key | the values result | claude/adapter.lua: values.root: required | host + types/op |
<tool>/<entry>, no line | coverage, missing handler, Lua failure | claude/adapter.lua: core/agent/coder got no operation (copy it, write it, or skip it with a reason) | types/op, host |
<path> (project-relative) | file steps | <path>: changed since the last apply | types/plan, with the resolution from Workspace |
<path> | apply race, I/O | <path>: changed after plan; run plan again | app/apply, fs |
agentstacks.toml with key | sources, a pack's binaries | agentstacks.toml: packs.core: git fetch failed: <stderr> | process, types/resolve |
agentstacks.toml, no key | git, airsl and cache-home checks | agentstacks.toml: airsl not found on PATH (needed by core, sdlc) | types/op, from a Binary answer |
agentstacks.lock | lock write | agentstacks.lock: <io::Error Display> | fs |
| pack, extension, project and lock files | the format messages | none | types |
<extension file> is the file's path inside the extension, for example claude/lib/settings.lua:3.
Any I/O failure with no message of its own (the cache, a reads path, the lock, agentstacks.toml,
or spawning git or airsl) is <path>: <io::Error Display> at the path involved. A failed spawn:
agentstacks.toml: packs.core: git: <io::Error Display>agentstacks.toml: airsl: <io::Error Display>
13. Not done
- A merge or run-command operation.
- Tool-specific code in the core.
- Writing
agentstacks.toml(the CLI does). - Network access in
doctor. - A lock file for the cache, and cleaning up cache temps left by a killed process.
- Exact preservation of number spelling or of the inner layout of a shared JSON file.
- Pure-policy pack hooks.
- Removing directories a delete leaves empty.
- Case-insensitive file systems: paths are compared by bytes, so
A.mdanda.mdare two paths.
Writing a Tool Extension
This page is written for an AI coding agent to follow, step by step. A human can hand it over with one line:
Build an agentstacks extension for
<tool>. Follow https://raw.githubusercontent.com/airsstack/agentstacks/main/book/src/ch06-00-authoring.md
Everything here is api = 1, which is frozen for every 1.x release: what stays and what a 1.x
release may add is on the stability page. If your extension uses something
a later 1.x release added, declare the oldest agentstacks it works with in [requires] (step 2).
Read first
Fetch these before writing code. They are the contract; this page only tells you the order of work.
| Document | What it gives you |
|---|---|
| ch06-01-extensions.md | the api = 1 Lua surface: manifest, [requires], events, operations, coverage, validation, every refusal |
| ch06-02-hooks.md | the hook command line, the shared runtime, the neutral event and result, the translator contract |
| adapter.lua | the official Claude Code extension, a complete worked example |
| demo pack | a small pack (one skill, one agent, one lua hook, one message hook) to test with |
What you build
<tool>/
extension.toml manifest: name, version, api = 1, entry, reads, [requires]
adapter.lua the only file that calls agentstacks.*; answers `values` and `plan`
lib/<rule>.lua pure rules: no agentstacks.*, no require; plain data in, data out
lib/<rule>_test.lua one test file per rule module, run with `airsl test`
Rules you must not break
- Propose only. The extension has no file, network or process access. It calls
agentstacks.write,copy,skipandrequire_binary; the core validates, shows and applies. - Cover every item. Each skill file, agent, hook, native file and native hook in the
planpayload gets awrite, acopyor askip. A missing one refuses the whole plan. - Unsupported is visible. What the tool cannot express becomes
agentstacks.skipwith a reason a user can act on. Never drop an item silently. - No grants. Ask for nothing. A shared config file the user also edits is declared in
extension.tomlreads, read withagentstacks.read, edited withagentstacks.json.editand written whole. There is no merge operation. - Lua only, under airsl. If the tool demands another hook language, write a thin shim that only runs the hook command and forwards the payload and result (hooks.md section 9).
Steps
1. Learn the tool
Write down, with a source for each, where the tool keeps project skills, agents (subagents), commands, rules and hook config; the file format of each; its hook events and payload fields; and how a hook blocks or adds context. List what it cannot express: those become skips.
2. Write extension.toml
[extension]
name = "mytool"
version = "0.1.0"
api = 1
description = "Renders packs into MyTool project config"
entry = "adapter.lua"
# reads = [".mytool/settings.json"] # only for a config file shared with the user
# Only when the extension uses something a later 1.x release added:
# [requires]
# agentstacks = ">=1.2"
api = 1 is required. A [requires] agentstacks range that excludes the running agentstacks is
the only refusal returned, so an older agentstacks says to install a newer one instead of failing on
a key it does not know (extensions.md section 2).
3. Start from a working adapter
This adapter installs skills and agents, and skips every hook. It was run with airsl 0.1.5 and
agentstacks 1.0.0: airsl test mytool gave 1 passed, 0 failed (1 files), and
agentstacks ext test ./ext/mytool applied five files in a temporary project, skipped eight
items and ended in passed.
-- lib/paths.lua: pure rules; no agentstacks.* here.
local M = {}
M.ROOT = ".mytool/agentstacks"
function M.skill_dir(name)
return ".mytool/skills/" .. name
end
function M.agent_file(name)
return ".mytool/agents/" .. name .. ".md"
end
return M
-- adapter.lua: the only file that calls agentstacks.*; the rules live in lib/.
local paths = agentstacks.require("lib.paths")
local NO_HOOKS = "mytool has no hooks"
agentstacks.on("values", function(q)
local out = { root = paths.ROOT, skills = {}, agents = {}, vars = {} }
for _, p in ipairs(q.packs) do
for _, s in ipairs(p.skills or {}) do
out.skills[p.name .. "/" .. s] = {
invoke = "/" .. p.name .. "-" .. s,
dir = paths.skill_dir(p.name .. "-" .. s),
}
end
for _, a in ipairs(p.agents or {}) do
out.agents[p.name .. "/" .. a] = p.name .. "-" .. a
end
end
return out
end)
agentstacks.on("plan", function(q)
for _, p in ipairs(q.packs) do
for _, skill in ipairs(p.skills or {}) do
for _, f in ipairs(skill.files) do
agentstacks.copy({ path = skill.dir .. "/" .. f.rel, file = f.id })
end
end
for _, a in ipairs(p.agents or {}) do
local file = paths.agent_file(p.name .. "-" .. a.name)
agentstacks.write({ path = file, content = a.text, covers = { a.id } })
end
for _, h in ipairs(p.hooks or {}) do
agentstacks.skip({ item = h.id, reason = NO_HOOKS })
end
local native = p.native or {}
for _, f in ipairs(native.files or {}) do
agentstacks.copy({ path = ".mytool/" .. f.rel, file = f.id })
end
for _, h in ipairs(native.hooks or {}) do
agentstacks.skip({ item = h.id, reason = NO_HOOKS })
end
end
end)
Then replace each placeholder with the tool's real format:
| Item | Start | Make it real |
|---|---|---|
| skill | copy keeps the neutral frontmatter | write SKILL.md with the tool's frontmatter built from skill.meta, covers = { <SKILL.md id> }; copy the other files |
| agent | body only | prepend the tool's frontmatter built from a.meta; skip with a reason when a field cannot map |
| vars | none | return a value for each name in q.vars ({{var}} tokens), for example $TMPDIR |
| hooks | skipped | step 5 |
4. Put rules in lib/ and test them
Keep every decision (frontmatter fields, event mapping, quoting) in a lib/ module that takes
plain values and returns plain values. The adapter passes data in; a module never calls
agentstacks.*.
A test file sits beside its module, requires it by bare name and returns a table of test functions:
-- lib/paths_test.lua
local paths = require("paths")
return {
skill_dir_is_under_mytool = function()
assert(paths.skill_dir("demo-greet") == ".mytool/skills/demo-greet")
end,
}
Run airsl test <tool>. It must report 0 failed. agentstacks ext test (step 6) runs the same
tests when the extension holds a *_test.lua file.
5. Hooks
Skip hooks until skills and agents work. Then, per hooks.md:
- Command. Each lua hook arrives with
command, an argv. Turn it into the tool's command string with the tool's own quoting, run from the project directory. Example: claude extension,cd "$CLAUDE_PROJECT_DIR" && "airsl" "run" …. - Filter by the hook's
matchandagentsin the tool's own config. The runtime does not filter. - Message hooks (
kind = "message") never reach the runtime: render them natively, for example as a command that prints the tool's context output. translate.lua. When any lua hook is covered by a write, write<root>/translate.lua. It returnsM.event(payload)(the tool's payload to the neutral event, a list of neutral events when one tool call holds several, ornil) andM.result(result, payload)(the neutral result to the tool's output string, ornil).- Blocking. A hook result
{ block = "<reason>" }from a hook declaredmay_blockmust become the tool's own deny output. Map{ context = "<text>" }to the tool's context output. - Unsupported events become skips with a reason.
6. Run it for real
Run the check. It builds a temporary project from your extension and a built-in conformance pack, runs your Lua tests, plans, applies and plans again, and writes nothing into your directory:
agentstacks ext test ./ext/mytool # the conformance pack only
agentstacks ext test ./ext/mytool --pack ./packs/demo # and your own pack too
The last line must be passed, with second plan: nothing to change above it. failed or no
verdict exits 1. The report and every refusal are in the command line.
Then, in a scratch directory holding a copy of your extension and a pack (the demo pack works), use it like a user would:
agentstacks init --tool ./ext/mytool --pack ./packs/demo --yes # writes agentstacks.toml, applies
agentstacks plan # 0 to write
agentstacks doctor # healthy
Then fire each generated hook command the way the tool would: its JSON payload on stdin, from the
project directory. Check that context is added and a may_block hook really blocks. Finally, run
the tool itself on the scratch project and confirm it loads the skills, agents and hooks.
7. Before you call it done
-
airsl test <tool>reports0 failed. -
agentstacks ext test ./ext/<tool>ends inpassed. -
agentstacks planon the demo pack has no refusal; every item is written, copied or skipped. - Every skip reason tells the user what the tool cannot do.
-
agentstacks apply --yes, thenagentstacks planshows0 to write;doctorsayshealthy. -
A user's own entries in a shared config file survive
apply, and removing the tool removes only your entries. -
Each hook fires in the real tool, and a
may_blockhook blocks.
8. Share it
A user adds your extension to a project with agentstacks ext add (see
the command line): a git URL with --tag or --rev and --subdir for
the directory inside the repository, or a directory of the project.
Common refusals
| You see | Fix |
|---|---|
mytool/adapter.lua: demo/hook/0 got no operation (copy it, write it, or skip it with a reason) | cover that item with write, copy or skip |
mytool/adapter.lua: lua hooks need .mytool/agentstacks/translate.lua (write it) | write <root>/translate.lua (step 5) |
mytool/adapter.lua:12: write: path ".x" is already proposed at adapter.lua:9 | two operations target one path; merge them into one write |
mytool/adapter.lua:9: read: ".env" is not in extension.reads | add the path to reads in extension.toml |
mytool/adapter.lua:1: require: invalid module name "lib/x" (use dots: lib.x) | agentstacks.require("lib.x") |
mytool/extension.toml: requires.agentstacks: ">=99" does not match agentstacks 1.0.0 (install a newer agentstacks) | install a newer agentstacks, or lower the range to the oldest release your extension works with |
mytool/extension.toml: extension.api: 0 is from agentstacks 0.x (this agentstacks speaks 1; set api = 1, or use a newer release of it) | set api = 1 (and check the extension against the API) |
The full refusal list is in extensions.md sections 9 to 12.
The Extension API
A tool extension is the Lua that turns packs into one tool's files. This guide is the contract an
extension author codes against. Everything in it is api = 1. What api = 1 promises, and what a
1.x release may add, is on the stability page.
Every message below is shown with the claude extension as the example (claude/adapter.lua), the
way the core prints it for that tool. Another tool prints its own name and file in its place.
How the pieces fit together is in architecture.md. The core's side of planning and applying is in plan-and-apply.md. The hook runtime an extension feeds is in hooks.md.
1. What an extension is and is not
An extension only proposes. It has no file, network or process access. It registers two handlers,
the core calls them, and what they return is a list of operations the core validates. plan shows
every operation, and apply is the only writer.
- There is no merge operation and no run-command operation. A config file shared with the user is
read (declared in
extension.tomlreads), edited withagentstacks.json.editand proposed whole. See section 11. - The operations are
write,copy,skipandrequire_binary. The core addsdeleteand its own writes (section 7). - Everything here is
api = 1.
2. extension.toml
The manifest is checked by Extension::load (crates/agentstacks/src/types/extension/loaded.rs).
Its reads key is optional: a list of project paths the extension may read with agentstacks.read.
# example: claude extension
[extension]
name = "claude"
version = "1.0.0"
api = 1
description = "Renders packs into Claude Code project config"
entry = "adapter.lua"
reads = [".claude/settings.json"]
The optional [requires] table holds one key, agentstacks, a version range. Declare it when the
extension uses something a later 1.x release added (see the stability
page):
# example: an extension that needs a feature added in 1.2
[extension]
name = "mytool"
version = "0.1.0"
api = 1
description = "Renders packs into MyTool project config"
entry = "adapter.lua"
[requires]
agentstacks = ">=1.2"
An agentstacks outside the range refuses the extension, and that is the only refusal returned. The
operators =, >, >=, <, <=, ~, ^ and wildcards are accepted. Refusals:
| Case | Refusal |
|---|---|
| the range excludes this agentstacks | extension.toml: requires.agentstacks: ">=99" does not match agentstacks 1.0.0 (install a newer agentstacks) |
| not a version range | extension.toml: requires.agentstacks: "nope" is not a version range |
| not a string | extension.toml: requires.agentstacks: expected string, got integer |
requires is not a table | extension.toml: requires: expected table, got string |
another key in requires | extension.toml: requires.foo: unknown key |
Each reads entry follows the lock's file path rule: relative, inside the project, / as the separator.
Entries are normalised (./a is a, a//b is a/b) before the duplicate check. A repeated entry
is quoted as written. Refusals:
| Case | Refusal |
|---|---|
| not an array | extension.toml: extension.reads: expected array, got string |
| an entry that is not a string | extension.toml: extension.reads[0]: expected string, got integer |
| an absolute path | extension.toml: extension.reads[0]: "/x" must be relative |
| a path that leaves the project | extension.toml: extension.reads[0]: "../x" must stay inside the project |
| a repeated entry | extension.toml: extension.reads[1]: ".claude/settings.json" listed twice |
a \ in an entry | extension.toml: extension.reads[0]: "a\b" must use / as the separator |
| an empty entry | extension.toml: extension.reads[0]: empty |
Naming agentstacks.toml or agentstacks.lock in reads is allowed, because reading them is
harmless. Writing to them is not allowed (section 9).
3. Load
- The core resolves the extension's source (
agentstacks.toml, a git tag or a project path) and loads it withExtension::load, which checksextension.toml. api = 1is required by the manifest. An extension written for the 0.x releases is refused asextension.api: 0 is from agentstacks 0.x (this agentstacks speaks 1; set api = 1, or use a newer release of it), and any other number asextension.api: <n> not supported (this agentstacks speaks 1).- Every
.luafile of the extension is read into memory. Lua never touches the disk.
A .lua file that is not UTF-8 is refused: <tool>/<file>: not valid UTF-8.
4. Sandbox
The extension runs under the airsl engine with the pure policy and an explicit stdlib set:
Json, Ext with the events values and plan, and agentstacks. The host lives in
crates/agentstacks/src/host/, and it is the only place Lua runs.
| What | |
|---|---|
| Removed | print and warn, the two output channels |
| Absent | require (use agentstacks.require, section 10), load, dofile, os, io, coroutine, and every airsl module not in the set |
| Present | Lua's remaining base functions (pcall, error, pairs, ipairs, type, tostring, setmetatable, rawget, …), plus string, table, math and utf8; airsstack.json and airsstack.ext; airsstack.agentstacks, also set as the global agentstacks |
Limits:
- 10,000,000 instructions per evaluation or dispatch;
- 16 MiB of memory, and data the host hands to Lua counts toward it.
The budget resets on each dispatch. The breach messages are:
script `spin` exceeded its instruction limit of 10000000script `adapter.lua` exceeded its memory limit of 16777216 bytes
A breach caught by the extension's own pcall is that extension's business: the dispatch then
succeeds.
5. The agentstacks table
| Function | Phase | Returns |
|---|---|---|
agentstacks.on(event, fn) | any | registers a handler for values or plan. A registration replaces the earlier one and takes effect at the next dispatch |
agentstacks.require(name) | any | the module's return value (section 10) |
agentstacks.write{path, content, covers} | plan | nothing; records an operation |
agentstacks.copy{path, file} | plan | nothing; records an operation |
agentstacks.skip{item, reason} | plan | nothing; records an operation |
agentstacks.require_binary{name} | plan | nothing; records an operation |
agentstacks.read(path) | plan | the file's bytes as a Lua string, or nil when no regular file is there |
agentstacks.json.edit(text, path, value) | any | new text (section 11) |
agentstacks.on looks the engine's registry up when it is called: while modules install, the global
airsstack does not exist yet.
read rules:
- The path must be listed in
extension.reads:".env" is not in extension.reads. - It must resolve inside the project, else
claude/adapter.lua:9: read: ".claude/settings.json" resolves outside the project. - The bytes are returned as they are, non-UTF-8 included. A Lua string holds raw bytes.
- An I/O failure reading a
readspath is<path>: <io::Error Display>. It is reported only when the extension reads that path, and it sticks like the otherreadrefusals. - The core records what each read returned (the hash, or "absent"). The record decides whether a file is shared (plan-and-apply.md).
6. Events
The flow, once per tool:
- The entry file runs at the top level. This registers handlers.
- The core dispatches
values. - The core renders the packs.
- The core dispatches
plan.
dispatch has three outcomes: no handler, a handler that returns nil, and a handler that returns
a table. A second agentstacks.on for the same event replaces the first: the last one wins.
values
The payload the extension receives. Example: claude extension.
{ "api": 1, "tool": "claude",
"packs": [ { "name": "core", "version": "0.3.0", "skills": ["status"], "agents": ["coder"] } ],
"vars": ["session_id", "tmpdir"] }
vars holds the {{var}} names this tool's packs use, sorted by name.
The result is a table that says where this tool puts things and what each token stands for:
-- example: claude extension
agentstacks.on("values", function(q)
local out = { root = ".claude/agentstacks", skills = {}, agents = {}, vars = { tmpdir = "${TMPDIR:-/tmp}" } }
for _, p in ipairs(q.packs) do
for _, s in ipairs(p.skills) do
out.skills[p.name .. "/" .. s] = {
invoke = "/" .. p.name .. "-" .. s,
dir = ".claude/skills/" .. p.name .. "-" .. s,
}
end
for _, a in ipairs(p.agents) do out.agents[p.name .. "/" .. a] = p.name .. "-" .. a end
end
return out
end)
The core fills every token from it:
| Token | Value used |
|---|---|
{{root}}, {{root <pack>}} | <root>/<pack> |
{{skill p/s}} | skills["p/s"].invoke |
{{skill_dir p/s}} | skills["p/s"].dir |
{{agent p/a}} | agents["p/a"] |
{{var v}} | vars[v] |
{{option o}} | resolved by the core from the pack's options |
Missing values. When a token has no value, the item that holds it is skipped by the core and left
out of the plan payload. The skip reason is, for example, claude gave no value for {{skill core/status}}.
With several missing values the reason names the first missing token in text order, and a missing
skill entry comes before any token.
- Skill: the item is the whole skill (group), because a half-installed skill is broken. A skill with
no
skills[...]entry at all is skipped too:claude gave no install location for skill core/status. - Agent, hook (any field:
text,args,run, grant paths), native file, native hook: the item itself. - Root file: a core skip of that file.
The result arrives as JSON, so Lua's types come back as these words: object is table, array is
list, null is nil, plus number, string and boolean. An empty Lua table arrives as an
object.
Refusals for the values result (location <tool>/<entry>, the key path starts at values):
| Rule | Refusal |
|---|---|
a values handler exists | claude/adapter.lua: registers no values handler |
| result is a table | claude/adapter.lua: values: expected table, got nil |
root required, a string, a valid path | claude/adapter.lua: values.root: required / claude/adapter.lua: values.root: "/x" must be relative |
skills, agents, vars are tables with string keys | claude/adapter.lua: values.agents: expected table, got list |
| their keys name items and vars of this payload | claude/adapter.lua: values.skills."core/x": not a skill in this run / claude/adapter.lua: values.vars.home: not a var in this run |
invoke, dir, agent value, var value are strings; dir a valid path | claude/adapter.lua: values.skills."core/status".dir: expected string, got number |
| unknown key, at any level | claude/adapter.lua: values.foo: unknown key / claude/adapter.lua: values.skills."core/status".icon: unknown key |
values.root and each dir follow the path rows of section 9 under their key. .
normalises to empty. The managed-file rule does not apply. More refusals:
claude/adapter.lua: values.root: empty… values.root: "../x" must stay inside the project… values.root: "a\b" must use / as the separatorclaude/adapter.lua: values.agents."core/x": not an agent in this run
A values.skills entry needs both invoke and dir: claude/adapter.lua: values.skills."core/status".dir: required
(the same shape for invoke). Absent values.skills, agents or vars are accepted. Their items
then fall under missing values.
plan
Every text in the payload is already rendered, and each id is a string to copy back. Example: claude extension.
{ "api": 1, "tool": "claude", "root": ".claude/agentstacks",
"packs": [ { "name": "core", "version": "0.3.0",
"skills": [ { "id": "core/skill/status", "name": "status", "dir": ".claude/skills/core-status",
"meta": { "description": "…", "invocation": "user" },
"files": [ { "id": "core/skill/status/SKILL.md", "rel": "SKILL.md", "text": "<body after frontmatter>" },
{ "id": "core/skill/status/logo.png", "rel": "logo.png" } ] } ],
"agents": [ { "id": "core/agent/coder", "name": "coder", "meta": { "description": "…", "model": "balanced" }, "text": "<body>" } ],
"hooks": [ { "id": "core/hook/0", "kind": "lua", "event": "tool.before", "match": ["read", "edit", "write"],
"may_block": false, "command": ["airsl", "run", "…"] },
{ "id": "core/hook/1", "kind": "message", "event": "session.end", "text": "Reminder: run /snapshot-save …" } ],
"native": { "files": [ { "id": "core/native/claude/x.md", "rel": "x.md", "text": "…" } ],
"hooks": [ { "id": "core/native-hook/0", "event": "SubagentStop", "match": "…", "may_block": false, "command": ["…"] } ] } } ] }
textis present for a UTF-8 file and absent for a binary one, which is installed withcopy. ForSKILL.mdand agents,textis the body only, andmetaholds the frontmatter fields, withnativelimited to this tool's entry.matchandagentsare given as lists, as the pack hook format holds them. A hook that has none has nomatchoragentskey.commandis the argv of the hook command line (hooks.md).- A native hook always carries
kind(luaormessage),event(named as the tool names it),matchas the list the pack format reader holds (left out when the hook has none), andmay_blockwithcommand(a lua hook) ortext(a message hook). It has noagents. - A native hook's
matchis passed through as written, so one that matches an agent must name it by its installed name,<pack>-<agent>(for examplecore-coder), not the name in the pack.
In the example above, the native hook entry is shown shortened. As built, it reads:
{ "id": "core/native-hook/0", "kind": "lua", "event": "SubagentStop", "match": ["…"],
"may_block": false, "command": ["…"] }
The return value of plan is ignored. With no handler: claude/adapter.lua: registers no plan handler.
Order. Listed tools run in name order, then removed tools in name order. Each listed tool's core
writes are recorded just before its plan dispatch. That order decides which tool's call gets
… already proposed by <tool>.
7. Operations
| Kind | Proposed by | Fields | Effect |
|---|---|---|---|
write | extension | path, content (bytes), covers (list of item ids, optional) | put exactly these bytes at path |
copy | extension | path, file (a file id from the plan payload) | put that pack file's final bytes at path. For a rendered file that is the whole rendered file; for SKILL.md or an agent, the neutral frontmatter is included. Otherwise the raw bytes. It covers file |
skip | extension | item (an item id), reason (non-empty) | nothing is installed; plan shows the reason |
require_binary | extension | name | plan refuses when name is not on PATH |
write (core) | core | none | each pack root file goes to <root>/<pack>/<rel>; runtime.lua goes to <root>/runtime.lua when a pack of this tool has a lua hook or a native lua hook (whether or not the extension later skips it) |
require_binary (core) | core | none | each pack's requires.binaries; airsl with the intersected range when any locked pack declares requires.airsl |
delete | core | path | a locked file no longer proposed |
runtime.lua is written when a pack of the tool has any lua hook, neutral or native, even if the
extension later skips it.
by, the lock's owner of a file (a pack or tool name), is derived and never passed:
- a copy, or a write whose
coversall belong to one pack, is owned by that pack; - a core write of a root file is owned by its pack;
- any other write (no
covers,coversspanning several packs,runtime.lua) is owned by the tool.
A shared file (plan-and-apply.md) is never locked, so it has no by.
8. Item ids and coverage
Ids are strings the plan payload hands out. The extension copies them and never builds one.
| Item | Id | Covered by |
|---|---|---|
| skill file | core/skill/status/SKILL.md, core/skill/status/references/x.md | a copy of it, a write listing it in covers, or a skip of it or of its skill |
| skill (group) | core/skill/status | used only by skip; covers all of its files |
| agent | core/agent/coder | write with covers, or skip |
hook (pack.toml) | core/hook/0 (index in [[hooks]]) | write with covers, or skip |
| native file | core/native/claude/x.md (only this tool's native/<tool>/) | copy, write with covers, or skip |
| native hook | core/native-hook/0 (index in native/<tool>/hooks.toml) | write with covers, or skip |
Every item the extension receives must be covered by an operation (write, copy or skip), otherwise the plan is refused. Root files are not items, because the core writes them. Items the core already skipped (section 6) are left out of the payload and need no cover.
| Case | Result |
|---|---|
| an item covered by no op | refused, one per item, in id byte order (core/hook/10 before core/hook/2): claude/adapter.lua: core/skill/status/references/x.md got no operation (copy it, write it, or skip it with a reason) |
| an item both skipped and copied or written; a skill group skipped while one of its files is copied or written | refused at the later call: claude/adapter.lua:14: skip: item "core/skill/status" is already covered at adapter.lua:9. After a skip, a copy or write reads <tool>/<file>:<line>: <function>: covers "<id>", which <file>:<line> skipped, where a copy's <id> is its file |
| the same item skipped twice | accepted; the plan shows the first reason |
the same file copied to two paths; two writes covering the same item; a repeated id inside one covers | accepted |
lua hooks covered by a write, but no write to <root>/translate.lua | refused: claude/adapter.lua: lua hooks need <root>/translate.lua (write it), with <root> filled in |
"Already covered at" names the first covering op.
The translate.lua rule applies when runtime.lua is written and at least one lua hook is covered
by a write. The contract for that file is in hooks.md.
Two more refusals keep ids to their kind:
copy.filemust name a file id:copy: file "core/agent/coder" is not a filecoversmay not name a skill group:write: covers[1]: "core/skill/status" is a skill; list its files
9. Validation
An operation is checked the moment the Lua function is called. The refusal names the caller's file
and line (a refusal raised with no Lua frame on the stack is located at <tool> alone, see below),
and has this shape (<function> is the agentstacks function called):
claude/adapter.lua:12: write: path: expected string, got number
The phase check (only allowed inside the plan handler) runs before every other check. After it,
a call raises one refusal: the first failing check, in the table order below. The location is the
nearest Lua frame on the stack, so pcall(agentstacks.write, t) is located at the pcall line.
A call made from a required module names that module.
A call with no Lua frame on the stack, for example agentstacks.on('plan', agentstacks.write)
where the host calls write itself, is refused with <tool>: <function> must be called from the extension's Lua code, for example claude: write must be called from the extension's Lua code.
Any refusal with no Lua frame is located at <tool> alone, with no file or line: the phase check
for such a call reads claude: write: only allowed inside the plan handler.
| Rule | Refusal (after <tool>/<file>:<line>: <function>: ) |
|---|---|
called outside the plan handler (ops and read) | only allowed inside the plan handler |
argument is one table (read takes one string) | expected table, got string / expected string, got number |
required field present (nil counts as missing) | path: required (same shape for content, file, item, reason, name) |
| field type matches exactly; no coercion | path: expected string, got number / covers: expected table, got string / covers[2]: expected string, got boolean |
covers is a list | covers: expected a list |
| no unknown field | foo: unknown key |
path is UTF-8 | path: not valid UTF-8 |
path shape: the lock's file path rule, plus / as separator | path: empty / path "/x" must be relative / path "../x" must stay inside the project / path "a\b" must use / as the separator |
path is not one of agentstacks' own files | path "agentstacks.lock" is managed by agentstacks (same for agentstacks.toml) |
path not proposed twice in one plan, by any op of any tool or by the core | path ".claude/x" is already proposed at adapter.lua:9 / … already proposed by opencode / … already proposed by core (root file of core) |
file, item, covers[i] name an id in this run's payload | file "core/skill/x/SKILL.md" is not in this plan (same shape for item, covers[1]) |
skip.reason not empty or whitespace-only | reason: empty |
require_binary.name is a valid binary name | name: "Git" is not a valid name |
read path in extension.reads | ".env" is not in extension.reads |
The generic argument shapes, for arguments that have no row of their own:
<fn>: <field>: expected <type>, got <type><fn>: <field>: expected a list<fn>: <field>: not valid UTF-8<fn>: keys must be strings, got <type>require: expected string, got <type>
A path that normalises to nothing (., ./) is path: empty.
When the earlier proposer is the core's own runtime.lua: path "<p>" is already proposed by core (runtime.lua of claude).
Normalisation. Every op path, every reads entry and every values path (root, dir) is
normalised on receipt by removing . and empty segments. The duplicate check, the lock lookup and
the lock's [[file]].path all use the normalised form.
Accepted without refusal:
- an empty
content(an empty file); - an empty
covers(same as none); - the same
require_binaryname more than once (checked once per tool).
Type words are Lua's: nil, boolean, number, string, table, function, userdata,
thread. An integer and a float are both number.
Strictness. Arguments are matched by their Lua type, with no coercion: path = 5 is refused,
not turned into "5". Unknown keys are refused. content keeps its raw bytes.
Refusals stick. The host records each op refusal when it happens. The plan is refused even when
the Lua code catches the error with pcall, and the refused op is not recorded.
10. agentstacks.require
require stays absent. Modules load through agentstacks.require(name).
namemust match^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$.- It maps to
<name with . replaced by />.luaamong the extension's in-memory files. - It is loaded once, with chunk name
@<path>, and the result is cached. - Errors carry the module's file and line, for example
lib/util.lua:2: boom. loadstays with the host and is never exposed.
| Rule | Refusal (location: the caller) |
|---|---|
| name shape | claude/adapter.lua:1: require: invalid module name "lib/x" (use dots: lib.x) |
| file exists | claude/adapter.lua:1: require: module "lib.x" not found in extension claude |
| not the entry file | claude/adapter.lua:1: require: "adapter" is the entry file |
| no cycle | claude/lib/b.lua:1: require: module "lib.a" requires itself (lib.a → lib.b → lib.a) |
A cycle is reported at the require call that closes it, here claude/lib/b.lua:1. The
(use dots: …) hint appears only when the name contains /, which becomes .. Otherwise the
message is claude/adapter.lua:1: require: invalid module name "x y".
require refusals are ordinary Lua errors and do not stick. Uncaught, they show their located
message, not the wrapper of section 12. A module that raised while
loading is not cached: requiring it again runs it again.
11. agentstacks.json.edit
edit(text, path, value) returns new text. path is a list of object keys, value is a Lua value,
and nil removes the key. The core knows no config format: a shared file is read (declared in
reads), edited with this pure helper and rewritten whole.
| Rule | Behaviour / refusal (location: <tool>/<file>:<line>: json.edit: …) |
|---|---|
| arguments | json.edit: text: expected string, got nil / json.edit: path: expected table, got string |
text empty or whitespace-only | treated as {} |
text parses as JSON | else json.edit: <serde_json message> (for example trailing comma at line 1 column 8) |
| top level is an object | else json.edit: top level must be an object |
path is a non-empty list of strings | json.edit: path: empty / json.edit: path[2]: expected string, got number |
setting: every key before the last names an object, and a missing one is created as {} | json.edit: "hooks" is not an object |
removing (nil): a missing key or parent | no change; the text is returned as it came in |
| existing keys keep their position; a new key goes last | none |
| indent | the leading whitespace of the first indented line after the first line, if it is all spaces or one tab; otherwise two spaces |
| line endings | \n; CRLF input comes back as LF |
| trailing newline | kept when the input ended with \n, absent otherwise |
| numbers | re-printed in serde_json's normal form: 12345678901234567890123 becomes 1.2345678901234568e+22, 0.10 becomes 0.1 |
| duplicate keys | the last one wins |
More behaviour:
- Removing through a parent that exists but is not an object refuses like setting:
json.edit: "hooks" is not an object. - Whitespace-only text takes its indent and trailing newline from the original text.
- With several failing rows, the first row of the table wins.
- The generic shapes:
json.edit: text: not valid UTF-8,json.edit: path: expected a list,json.edit: value: <type> cannot be JSON,json.edit: value: -inf cannot be JSON,json.edit: value: table contains itself,json.edit: value: key is not valid UTF-8. - A value nested more than 128 levels deep:
json.edit: value: nested more than 128 levels deep. json.editrefusals are ordinary Lua errors: an extension may catch them withpcall, they do not stick, and an uncaught one fails the dispatch.
Converting the Lua value is hand-written, because a generic conversion drops data:
| Lua value | JSON | Refusal |
|---|---|---|
table with keys exactly 1..n | array | none |
| table with only string keys | object, keys sorted (Lua has no key order, so the output stays deterministic) | none |
| empty table | {}. No [] can be produced: to empty a list, remove its key | none |
| any other table | none | json.edit: value: table mixes list and keyed entries |
| integer, float, string (UTF-8), boolean | number, number, string, boolean | json.edit: value: NaN cannot be JSON (also inf) / json.edit: value: string is not valid UTF-8 |
| function, userdata, thread | none | json.edit: value: function cannot be JSON |
A checked example. Example: claude extension, editing .claude/settings.json.
local old = '{\n "permissions": {"allow": ["Bash(x:*)"]},\n "hooks": {}\n}\n'
agentstacks.json.edit(old, {"hooks", "PreToolUse"}, { { matcher = "Read" } })
{
"permissions": {
"allow": [
"Bash(x:*)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Read"
}
]
}
}
The indent is 4 spaces and the trailing newline is kept. The inner layout is pretty-printed: the
one-line "allow" array becomes multi-line.
Numbers in a shared JSON file are re-printed in serde_json's normal form, and the plan's diff shows any change. Exact number spelling and the inner layout are not preserved.
12. Errors and locations
| Case | What the user sees |
|---|---|
| our op refused | the message of section 9 (sticky) |
json.edit refused | a normal Lua error: an extension may catch it with pcall, and an uncaught one fails the dispatch |
| any other Lua failure | <tool>/<entry>: + the first line of airsl's error Display, e.g. claude/adapter.lua: lua error in adapter.lua: syntax error: adapter.lua:1: <name> or '...' expected near <eof>, claude/adapter.lua: lua error in plan: runtime error: adapter.lua:3: path must be relative (a dispatch names the event) (example: claude extension) |
| limit breach | claude/adapter.lua: script `plan` exceeded its instruction limit of 10000000 |
agentstacks.on with another event | airsl's own text, e.g. claude/adapter.lua: lua error in adapter.lua: event `nope` is not one this host dispatches; declared events: plan, values. The declared events are kept sorted |
Any extension error refuses the whole plan. Nothing is written.
Where a refusal is located (the first three rows of the core's locations table):
| Location file | Used for | Example |
|---|---|---|
<tool>/<extension file> with line | op arguments, read, require, json.edit | claude/adapter.lua:12: write: path: expected string, got number |
<tool>/<entry> with key | the values result | claude/adapter.lua: values.root: required |
<tool>/<entry>, no line | coverage, missing handler, Lua failure | claude/adapter.lua: core/agent/coder got no operation (copy it, write it, or skip it with a reason) |
<extension file> is the file's path inside the extension, for example claude/lib/settings.lua:3.
The full table is in plan-and-apply.md.
13. require_binary
| Requirement | Check | Refusal |
|---|---|---|
an extension's require_binary | PATH lookup | claude/adapter.lua:7: require_binary: "node" not found on PATH |
A binary required by both a pack and an extension is reported once for each. The same name more than once in one extension is checked once.
14. The extension's duties outside Lua
The core builds the hook command line and the runtime. The rest is the extension's, because only the tool knows its own config:
- Run the hook argv from the project directory. Make the tool run the hook's argv with the
project directory as its working directory, and turn the argv into the tool's command string with
its own quoting. Example: claude extension,
cd "$CLAUDE_PROJECT_DIR" && …. See hooks.md. - Write
<root>/translate.luato the translator contract in hooks.md. - Filter by
matchandagentsin the tool's own config. The runtime does not filter. - Render message hooks natively. A message hook never reaches the runtime.
- Write a shim with
writewhen the tool demands another hook language. Example: OpenCode plugins are JavaScript or TypeScript; the opencode extension writes a JavaScript shim that only runs the argv and forwards the payload and result (hooks.md).
Hooks
How a pack hook runs, from the tool's command to the hook's result. This guide is for pack authors
and extension authors. Everything in it is api = 1. What api = 1 promises, and what a 1.x
release may add, is on the stability page.
A pack declares a hook once, in tool-neutral terms. The core builds one command line for it, the
extension makes the tool run that command, and a runtime the core ships calls the hook's Lua module.
The tool-specific parts, turning the tool's payload into a neutral event and the hook's result back
into the tool's output, belong to the extension's translate.lua.
Written for extension authors in extensions.md. The core's side of planning is in plan-and-apply.md.
1. Layout
Every tool that has a lua hook gets three files under <root>, the directory its extension names:
<root>/runtime.lua written by the core (below)
<root>/translate.lua written by the extension (required)
<root>/<pack>/hooks/enforce.lua a root file, written by the core
runtime.luais written by the core, the same bytes for every tool (crates/agentstacks/assets/runtime.lua).translate.luais written by the extension, one per tool.<root>/<pack>/hooks/...are the pack's own files, written by the core as root files.
airsl's require root is the script's directory. A hook run of {{root core}}/hooks/enforce.lua
therefore becomes the module core.hooks.enforce.
2. Rules for a pack hook
A hook in pack.toml (or in native/<tool>/hooks.toml) is checked when the pack loads.
grants.policy = "pure"is refused inapi = 1.confinedis the only allowed value:hooks[1].grants.policy: "pure" is not supported in api 1 (airsl has no require under pure, airsstack/airsl#12)hooks[1].grants.policy: "foo" (expected confined)
- Each segment of the
runpath (after the{{root <pack>}}form, with.luaremoved from the last one) must be require-able: letters, digits,_and-only. This also applies tonative/<tool>/hooks.toml.hooks[1].run: "{{root core}}/hooks/my.hook.lua" segment "my.hook" may use only letters, digits, _ and -
The run-segment refusal quotes run as written and reports only the first bad segment. It applies
only to a run that ends in .lua, because other values are already refused by the .lua rule.
3. Command line
The core builds this argv for each lua hook:
airsl run --fail-open --policy confined
[--allow-read <p>]… [--allow-write <p>]… [--allow-env <N>]… [--allow-exec <b>]…
<root>/runtime.lua <module> <may_block: 0|1> <kind: neutral|native> [args…]
- The core builds it with project-relative paths. A pack hook's grants map one to one onto the
--allow-*flags. - The extension's duty: make the tool run this command with the project directory as its
working directory. Example: claude extension,
cd "$CLAUDE_PROJECT_DIR" && …. - A project-relative grant then resolves against that working directory:
--allow-read .tool/agentstacks/corelets the hook read.tool/agentstacks/core/data.txt. Without the grant, a read is denied:fs.read denied: … is outside the granted read roots: none are granted. --fail-openis fixed. A missing module exits0silently. Without it, airsl printsmodule `core.hooks.missing` not found under …and exits 1.- Elements may hold a
{{var}}value the extension supplied (an expression such as$TMPDIR). Turning the argv into the tool's command string, quoting included, is the extension's job.
4. runtime.lua
The core writes <root>/runtime.lua when a pack of the tool has any lua hook, neutral or native,
whether or not the extension later skips it. This is its full text, byte for byte:
-- agentstacks hook runtime, api 1.
-- usage: airsl run ... runtime.lua <hook-module> <may_block: 0|1> <kind: neutral|native> [args...]
local translate = require("translate")
local name, may_block, kind = arg[1], arg[2] == "1", arg[3]
local args = {}
for i = 4, #arg do
args[#args + 1] = arg[i]
end
local payload = airsstack.hook.payload()
local hook
-- Runs the hook on one event; a block from a hook that is not may_block is dropped with a line.
local function run(event)
hook = hook or require(name)
event.args = args
local result = hook(event)
if type(result) == "table" and result.block ~= nil and not may_block then
airsstack.stdio.error("agentstacks: hook " .. name .. " tried to block but is not declared may_block; reason: "
.. tostring(result.block) .. "\n")
result.block = nil
end
return result
end
local result
if kind == "native" then
result = run({ payload = payload })
else
local event = translate.event(payload)
if event == nil then
return
end
if event.event ~= nil then
result = run(event)
else
-- A list of events: the hook runs once per event, in order, until one blocks.
local contexts = {}
for _, each in ipairs(event) do
local one = run(each)
if type(one) == "table" then
if one.context ~= nil then
contexts[#contexts + 1] = tostring(one.context)
end
if one.block ~= nil then
result = { block = one.block }
break
end
end
end
if #contexts > 0 then
result = result or {}
result.context = table.concat(contexts, "\n")
end
end
end
local out = translate.result(result, payload)
if out ~= nil then
airsstack.stdio.write(out)
end
What it does for each run:
| Run | Output |
|---|---|
| context | {"context":"event=tool.before session=s1 args=--manifest,x.json read=true:hello\n …"} |
block from a hook that isn't may_block | stdout empty; stderr agentstacks: hook core.hooks.blk tried to block but is not declared may_block; reason: edits to tool.before are not allowed |
same hook with may_block 1 | {"decision":"block","reason":"edits to tool.before are not allowed"} |
| native | {"context":"native payload tool_name=Edit event=nil"} |
context and block from a hook that isn't may_block | stdout {"context":"keep this context"}; the block line on stderr |
translator returns nil (an event it does not map) | no output, exit 0 |
The table above is an example: claude extension (its translate.lua, with tool_name=Edit as the
tool's own payload field). A real tool's translator decides the actual output text.
M.event may return a list of events instead of one. The rules:
| Case | Result |
|---|---|
M.event returns a table with event set | one event; the result is what the hook returned, except that a block from a hook that is not may_block is dropped with the stderr line |
M.event returns a list (a table with no event key) | the hook runs once per element, in order; each gets args |
a list, may_block 1, an element blocks | the loop stops; the result is { block = <that block> }, plus context = <contexts so far, joined with "\n"> when any element returned one (the blocking element's context included) |
a list, may_block 0, an element blocks | the stderr line as above, the block dropped, the loop goes on |
| a list where no hook returns context or block, where every block was dropped and no context came back, or an empty list | M.result gets nil |
| native kind | one event { payload = <raw>, args = … } |
| a context that is not a string | in a list it is joined after tostring; a single event passes it through unchanged |
The hook module is required only when a hook runs, so a translator returning nil never loads it.
airsstack.stdio (error, write) and airsstack.hook.payload exist under confined.
5. Neutral protocol
Event (built by the translator):
| Field | When |
|---|---|
event | always: one of the hook events of the pack format (session.start, session.end, prompt.submit, tool.before, tool.after, agent.stop) |
session_id, cwd | always |
agent | always; nil = the main agent |
agent_id | optional; the tool's id for the agent instance, nil when the tool has none |
args | always (added by the runtime) |
source | session.start: startup, resume, clear or compact |
prompt | prompt.submit |
tool (read, edit or write), path | tool.before, tool.after |
last_message | agent.stop |
There is no raw payload on a neutral event. A native hook gets { payload = <raw>, args = … }.
Result (returned by the hook): nil, { context = "<text>" }, { block = "<reason>" }, or both.
Native hooks reach the extension in the same hook shape as a pack hook: kind, event, match as
the list the pack format reader holds, may_block, and command (a lua hook) or text (a message
hook).
6. Translator contract
<root>/translate.lua is one file per tool, written by the extension. It returns a module with two
functions:
M.event(payload)returns the neutral event, a list of neutral events, ornilfor an event that is not for this runtime (the hook is then not run). A list makes the runtime run the hook once per event (section 4).M.result(result or nil, payload)returns the string to print, ornil.payloadis the raw payload for neutral and native hooks alike. The runtime passes it because the payload can be read only once.
The file is required when runtime.lua is written and at least one lua hook is covered by a write.
Without it the plan is refused: claude/adapter.lua: lua hooks need <root>/translate.lua (write it),
with <root> filled in.
7. may_block
A hook declares may_block to say it may stop the tool. A block from a hook that is not declared
may_block is dropped with one line on stderr, and any context it returned is kept. The
behaviour table in section 4 shows both outcomes.
8. Filtering and message hooks
Filtering by match and agents is the extension's job, in the tool's own config. The runtime does
not filter.
Message hooks (kind = "message") never reach the runtime. The extension renders them natively.
9. Shims for other hook languages
When a tool demands another hook language, the extension writes a thin shim. Example: OpenCode
hooks are JavaScript plugins (.js), so its shim is JavaScript. The shim only runs the command line
of section 3 and forwards the payload and the result. It is an ordinary write,
shown in the plan like any other file: the core gives it nothing new.
10. airsl on the machine
Hook commands run on the airsl binary found on PATH. When a locked pack declares requires.airsl,
the core adds a require_binary for airsl with the range the packs need, and records the installed
version in the lock's [airsl] table (the pin). After install, doctor is the check that airsl is
still there and still the pinned version. The tables and messages are in
plan-and-apply.md and
plan-and-apply.md.
OpenCode
What the official opencode extension does: the files it writes, the variables it gives packs, how
hooks reach OpenCode, what it skips, and what it cannot do. It is checked against OpenCode v2.4.1
(V2 project config). It runs on the same api = 1 as every extension, under the promise on the stability
page; see the extension API and
hooks.
Use it with agentstacks init --tool opencode --pack <p>.
1. Vars
A pack text can use these {{var <name>}} forms. The extension gives only the names a pack uses.
| Var | Value | Note |
|---|---|---|
project_dir | ${AGENTSTACKS_PROJECT_DIR} | set by the hook shim in the agent's shell and in hook processes |
session_id | ${OPENCODE_SESSION_ID} | set in the shell tool; OpenCode never substitutes it in text, so the model uses it in shell commands |
arguments | <arguments> | a command fills it; OpenCode never substitutes $ARGUMENTS in a skill |
tmpdir | ${TMPDIR:-/tmp} | expanded by the shell |
home | $HOME | expanded by the shell |
airsstack_home | ${AIRSSTACK_HOME:-$HOME/.airsstack} | expanded by the shell |
The root for pack files is .opencode/agentstacks. A skill <p>/<s> lives in
.opencode/skills/<p>-<s> and is invoked as /<p>-<s>. An agent <p>/<a> is named <p>-<a>.
2. Files
| Item | What is written |
|---|---|
skill SKILL.md | .opencode/skills/<p>-<s>/SKILL.md, with frontmatter and the text |
| the skill's command | .opencode/commands/<p>-<s>.md; a skipped skill gets no command |
| other skill file | copied next to SKILL.md |
| agent | .opencode/agents/<p>-<a>.md, with frontmatter and the text. Its tools become permissions: deny everything, allow paths outside the project, then allow each listed tool. |
| native file | native/opencode/<rel> is copied to .opencode/<rel> |
| hooks | covered by .opencode/plugins/agentstacks.js, or skipped (section 5) |
.opencode/plugins/agentstacks.js | always written; with no hook it still sets AGENTSTACKS_PROJECT_DIR |
.opencode/agentstacks/translate.lua | written when at least one Lua hook became an entry |
A path joins the pack and item names with -, so core/status and sdlc/status never clash. Two
items whose joined names are equal (pack a-b skill c, pack a skill b-c), or a native file on
a generated path, propose the same path twice, and the core refuses it.
3. Hook mapping
Each hook becomes one entry in the shim or one skip. Packs are read in payload order. Within a pack, neutral hooks come first, then native hooks.
| Neutral event | Runs on | OpenCode tools |
|---|---|---|
tool.before, tool.after | the same event | from match: read is read; edit is edit and patch; write is write and patch. No match means read, edit, write, patch |
prompt.submit | prompt.submit | none |
session.start | session.start | none; renders with no match or a match holding startup, else skipped |
session.end, agent.stop | skipped | none |
Native event (in native/opencode/hooks.toml) | Runs on | OpenCode tools |
|---|---|---|
tool.execute.before, tool.execute.after | the same event | the native match as written; none or empty means every tool |
session.prompt | session.prompt | none; a non-empty match is skipped |
| any other | skipped | none |
A hook is native when it comes from the pack's native hooks, whatever its event is called.
4. Delivery
The shim runs each Lua entry as /bin/sh -c <command> from the project root. The hook gets a JSON
payload on stdin and answers with JSON on stdout. Stderr is discarded. Entries run one after another
in table order, and the first block stops the run.
| OpenCode hook | Entries run | How the result is delivered |
|---|---|---|
| shell creation | none | sets AGENTSTACKS_PROJECT_DIR to the project root, for the main agent and subagents |
tool.execute.before | tool.before, tool.execute.before for that tool | a block stops the tool, and the model sees the block text as the tool's error. Context is held until the tool finishes |
tool.execute.after (completed calls only) | tool.after, tool.execute.after | held and new context is joined and added to the tool's result as one text item. A block shows the model an error with the text |
session.prompt (top-level sessions only) | session.start on the first prompt of a session in this process, then prompt.submit and session.prompt on every prompt | context is added to the prompt after a blank line. A session.start block is added as context |
A hook that prints nothing, prints text that is not a JSON object, or fails to start gives no
context and no block. A hook that runs longer than 60 seconds is killed and gives no context and no
block. A subagent's first prompt runs no session.start and no prompt.submit.
4.1 Missing airsl
Every Lua hook runs airsl. If airsl is gone from PATH after install, the shell exits 127 and the
hook gives nothing. So every Lua hook is off, guards included: a may_block hook blocks nothing.
The shim then tells the model once per OpenCode process, at the next top-level prompt, by adding this notice after any other context:
agentstacks: airsl is not on PATH, so the agentstacks Lua hooks are not running. Install airsl, then run agentstacks doctor.
- A failure first seen in a tool hook is told at the next prompt.
- A later prompt in the same process does not repeat it. A new process tells it again if airsl is still missing.
opencode runwithout--standaloneuses a background service that outlives the command. With it the notice comes once per service start.- The notice stays in the session history as part of that prompt.
- An airsl without an execute bit makes the shell exit 126, and the model is not told.
plananddoctorcount such a file as missing.
agentstacks doctor also checks the airsl pin against the binary it finds.
5. Skips
An item the extension cannot express becomes a skip with a reason. Rules are checked in this order; the first that applies gives the reason.
| # | Case | Applies to | Reason |
|---|---|---|---|
| 1 | a hook on session.end | neutral hooks | opencode has no hook when a session ends |
| 2 | a hook on agent.stop | neutral hooks | opencode has no hook when a subagent stops |
| 3 | a hook on session.start whose non-empty match does not hold startup (no match renders) | neutral hooks | opencode runs session.start hooks only for a new session (source "startup"), which this hook does not match |
| 4 | a may_block Lua hook on prompt.submit (neutral) or session.prompt (native); a message hook there renders | both | opencode cannot block a prompt |
| 5 | a hook on session.prompt with a non-empty match | native hooks | opencode has no matcher for session.prompt |
| 6 | a hook on any event but tool.execute.before, tool.execute.after and session.prompt | native hooks | opencode has no native hook event "<event>" (use tool.execute.before, tool.execute.after or session.prompt) |
| 7 | a hook whose text or argv holds ${OPENCODE_SESSION_ID} | both | opencode gives hooks the session id in the event (event.session_id), not as {{var session_id}} |
| 8 | a Lua argument with a $ left after every var form is removed | both | opencode runs hook commands through sh, which would expand the literal $ in argument "<arg>" |
| 9 | a native key with a character other than A-Z, a-z, 0-9, _ or - | skills, agents | native.opencode key "<key>" cannot be written as frontmatter |
<event>, <arg> and <key> stand for the hook's event, the argument and the key. A native hook
whose event is session.end, agent.stop, session.start or prompt.submit gets rule 6, naming
its event.
With the five official packs, these hooks are skipped: the compact hook of core's session.start
(rule 3), core's session.end message, its two agent.stop hooks, and the agent.stop hooks of
sdlc and journal. The other session.start hooks of core, sdlc and journal are rendered.
6. Not carried over from Claude
| Claude feature | OpenCode | Visible as |
|---|---|---|
SessionEnd, SubagentStop hooks | none | skips 1 and 2 |
SessionStart sources resume, clear, compact | only startup | skip of hooks that match only compact; see section 7 |
block on UserPromptSubmit | a hook that throws on a prompt only shows UnexpectedStatus: 500 | skip 4 |
| model tier, effort | none; a subagent uses the parent's model | not written |
argument-hint | none | not written |
/skill args | the generated command /<p>-<s> args |
7. Behaviour to know
- Resumed sessions. OpenCode does not tell a resumed session from a new one. A session resumed
with
-cin a new process runssession.startagain, with the sourcestartup. - Compaction. There is no
session.startafter compaction. - Hidden skills. A skill with
invocation: useris written withdisable-model-invocation: true. It is hidden from the model's list, not refused: if the model calls it by id, it loads. - Permission check. The before hook runs before OpenCode's permission check. A
may_blockhook can block a call the user would have been asked about, and a call that then fails drops its held context. The shim never reads or changes permissions. - Nested projects. OpenCode loads
.opencode/from every parent directory, so two agentstacks projects, one inside the other, would load two shims. This is not supported. - Several tools. With
claudeandopencodeboth listed, OpenCode also reads.claude/skills/. Skills only Claude has, such ascore-statusline, or skills the opencode extension skipped, then show up in OpenCode with Claude's var forms. SetOPENCODE_DISABLE_CLAUDE_CODE=1to stop OpenCode reading.claude/skills/. Withmusecodeandopencodeboth listed, OpenCode also reads.agents/skills/, where the musecode extension writes its skills. A skill in both has one id and the.opencodecopy wins. A skill the opencode extension skips but the musecode extension writes shows up in OpenCode with Muse Code's var forms. - Subdirectories. OpenCode started in a subdirectory still finds
.opencode/. Hooks run from the project root;cwdin the payload is the subdirectory.
8. Limits
- A
patchheader with leading spaces is applied by OpenCode but not seen by hooks. - A
patchthat touches one blocked file and one allowed file is blocked as a whole, because it is one tool call. - Whether a real model follows a command's "Load the skill" line, or a skill's
<arguments>placeholder, is model behaviour. - A hook's stderr is discarded, including the runtime's line that a hook tried to block but is not
declared
may_block. - With airsl missing, every Lua hook is off, guards included (section 4.1).
- Context added to a prompt becomes part of the stored user message. The user sees it in the history, and OpenCode's title request reads it.
- Files written by
shell,generate_imageorgenerate_videopass no tool hook as a read, edit or write. - With several tools listed, skills written for Claude or Muse Code show in OpenCode (section 7).
Writing a Pack
This page is written for an AI coding agent to follow, step by step. A human can hand it over with one line:
Build an agentstacks pack for
<what the pack gives an agent>. Follow https://raw.githubusercontent.com/airsstack/agentstacks/main/book/src/ch06-04-pack-authoring.md
Everything here is api = 1: the pack format is frozen for all of 1.x. What that promises is on
the stability page. A pack is the other half of an extension: a pack says
what the agent gets, in tool-neutral terms, and a tool extension says how a tool gets it.
Writing an extension is Writing a Tool Extension.
Read first
Fetch these before writing files. They are the contract; this page only tells you the order of work.
| Document | What it gives you |
|---|---|
| ch06-05-pack-format.md | the pack format: layout, every pack.toml field, tokens, frontmatter, hooks and events, options, native/<tool>/, every refusal |
| ch06-02-hooks.md | how a hook runs, and the neutral event and result a Lua hook gets and returns |
| packs/guideline-rust | a worked example: one skill with references, a render file and an exclude |
| packs/core | a larger example: agents, options, message and Lua hooks, native/claude/hooks.toml |
What you build
<pack>/
pack.toml the manifest: name, version, api = 1, requires, options, hooks
skills/<name>/SKILL.md one directory per skill, frontmatter then a Markdown body
agents/<name>.md one file per agent, frontmatter then a Markdown body
hooks/<hook>.lua a hook script, run under airsl
hooks/<hook>_test.lua its test, run with `airsl test`; excluded from what is installed
native/<tool>/ optional: files and hooks for one tool only
Rules you must not break
- Tool-neutral first. Write skills, agents and hooks once, with tokens (
{{skill lint}}) where a tool's own name or path would go. Put what only one tool understands undernative/<tool>/or a skill'snative:key, never in the neutral text. - Tokens, not paths. Point at another skill with
{{skill name}}, at an installed file with{{root}}/..., at a skill's directory with{{skill_dir name}}. Never write.claude/or any other tool's directory in neutral content. - Declare what you use. A pack that installs a
.luafile declaresrequires.airsl. A hook that runs a program lists it inrequires.binariesand ingrants.exec. A pack that points at another pack lists it inrequires.packs. - Hooks get nothing by default. A Lua hook runs confined. Grant each path and environment
variable it needs, no more.
trustedis not allowed in a pack. - Lua only, under airsl. A hook is a Lua script. A tool that wants another language is the extension's problem, not the pack's.
- Unsupported is visible. A pack never needs to hide what a tool cannot do. The extension turns it into a skip with a reason.
Steps
1. Lay out the pack
Pick a name (lowercase letters, digits and -, starting with a letter) and make the directories.
This page builds team-lint: one skill, one agent, one message hook, one Lua hook, one option.
mkdir -p packs/team-lint/{skills/lint,agents,hooks,native/claude}
2. Write pack.toml
exclude = ["**/*_test.lua"]
[pack]
name = "team-lint"
version = "1.0.0"
api = 1
description = "Team lint rules"
[requires]
agentstacks = ">=1.0"
airsl = ">=0.1.5"
exclude is written before the first [table] header so it stays a top-level key. api = 1 is the
only value this agentstacks accepts. airsl is required because the pack will install a .lua
file. requires.agentstacks is covered in step 8.
3. Add a skill
skills/lint/SKILL.md:
---
name: lint
description: Lint the files you changed and fix what it reports
invocation: user
argument_hint: "[path]"
---
Lint {{var arguments}} (or the files you changed). Allow at most {{option max_warnings}} warnings.
Hand anything you cannot fix to {{agent linter}}.
name is the directory name, written literally. invocation: user means only the user starts the
skill; leave it out to let the agent start it too. {{var arguments}} is what the user typed after
the skill's name, and it is valid in a SKILL.md only. Any other file in the skill's directory
(references/*.md, scripts) is installed with the skill, and {{skill_dir lint}} names the
directory.
4. Add an agent
agents/linter.md:
---
name: linter
description: Reads lint output and proposes the smallest fix
model: balanced
effort: medium
tools: [read, grep, shell]
---
You are {{agent linter}}. Follow {{skill lint}}.
model is fast, balanced or deep; effort is low, medium or high; tools is a list
from read, write, edit, grep, glob, shell and skill. The words are neutral: each tool
extension maps them to the tool's own.
5. Add an option
An option lets a project change a value without editing the pack. Add to pack.toml after
[requires]:
[options.max_warnings]
type = "integer"
default = 0
description = "Warnings the lint skill tolerates"
{{option max_warnings}} in the skill becomes 0, or the value the project sets under
[packs.team-lint.options] in agentstacks.toml.
6. Add hooks
A message hook shows the agent text at an event. A Lua hook runs a script. Append to pack.toml:
[[hooks]]
kind = "message"
event = "session.start"
match = ["startup", "resume"]
text = "Run {{skill lint}} before you commit."
[[hooks]]
kind = "lua"
event = "tool.after"
match = ["edit", "write"]
run = "hooks/remind.lua"
args = ["{{option max_warnings}}"]
hooks/remind.lua returns a function. It gets the neutral event and returns nil, or a table with
context, block, or both (Hooks, section 5):
return function(event)
return { context = "Edited " .. tostring(event.path) .. ": run the lint skill." }
end
hooks/remind_test.lua tests it, beside it. A test file requires the module by its bare name and
returns a table of test functions; exclude keeps it out of the install:
local hook = require("remind")
return {
names_the_edited_file = function()
local result = hook({ event = "tool.after", path = "src/a.rs" })
assert(result.context == "Edited src/a.rs: run the lint skill.", result.context)
end,
}
The six events, which match values each takes, and the rest of the hook keys (may_block,
grants) are in section 5 of the pack format. A hook that needs
to read a file or run a program says so with grants; it gets nothing otherwise.
Run the tests where the hook lives: airsl test packs/team-lint should report 0 failed, and
airsl check packs/team-lint should compile every file.
7. Add native/<tool>/
Put what one tool alone understands under native/<tool>/. A hook in the tool's own event words
goes in native/claude/hooks.toml:
[[hooks]]
kind = "message"
event = "UserPromptSubmit"
text = "Lint is part of done."
The core does not check a native event or match; the extension for that tool does. A native hook
the tool cannot express becomes a skip with a reason in the plan, so check the plan (step 9) for a
skip line. Files in native/<tool>/ are installed for that tool only, and neutral content must
not point at them with {{root}}.
8. Say which agentstacks you need
[requires]
agentstacks = ">=1.0"
A pack written for api = 1 works with every agentstacks 1.x, so >=1.0 is a floor you can always
write. When a later 1.N release adds something you use (a new optional key, a new var), write
>=1.N instead: an older agentstacks then refuses the pack with requires.agentstacks: ">=1.N" does not match agentstacks <version> (install a newer agentstacks) rather than failing on a key it
does not know. See the stability page.
9. Try it
In a scratch project that holds a copy of your pack, install it with an official tool:
agentstacks init --tool claude --pack ./packs/team-lint --yes
agentstacks plan # 0 to write
agentstacks doctor # healthy
init writes agentstacks.toml with [packs.team-lint] path = "./packs/team-lint", checks the
pack and applies it. It was run on this pack with a copy of the official claude extension
(--tool ./ext/claude) and wrote six files, .claude/skills/team-lint-lint/SKILL.md,
.claude/agents/team-lint-linter.md, the hook script under .claude/agentstacks/team-lint/hooks/
and the runtime files and .claude/settings.json that run the hooks; plan then showed 0 to write and doctor said healthy. Open the files and read them: the skill's {{var arguments}}
became $ARGUMENTS, {{agent linter}} became team-lint-linter, and {{option max_warnings}}
became 0.
Read every skip line of the plan. Each one is something the tool cannot express, with its reason;
decide whether it matters for the pack. Change a file of the pack and run agentstacks plan again;
it shows the update.
To run the pack through an extension and the built-in conformance pack together, use
agentstacks ext test <extension-dir> --pack ./packs/team-lint. It installs both in a temporary
project, never in yours, and ends in passed or failed (The Command Line).
10. Publish it and add it to a project
A pack is a directory in a git repository. Commit it, tag a release and push the tag:
git tag v1.0.0
git push origin v1.0.0
init and ext add have no shorthand for a pack in your repository. ext add adds tool
extensions only, and init --pack takes an official name or a directory. To use the pack from git,
write a [packs.<name>] table into the project's agentstacks.toml by hand, with the repository,
a tag and the directory the pack is in:
api = 1
[tools.claude]
git = "https://github.com/airsstack/agentstacks"
tag = "packs-v1.0.0"
subdir = "extensions/claude"
[packs.team-lint]
git = "https://github.com/acme/lint-packs"
tag = "v1.0.0"
subdir = "packs/team-lint"
The key after packs. must be the name in pack.toml; a key that differs is refused with
source contains pack "<name>". Use rev (a commit) in place of tag, never both. To set an
option, add a [packs.team-lint.options] table with the values
(section 6 of the pack format). Then run agentstacks plan and
agentstacks apply. The tag, the commit and the tree hash of the source are pinned in
agentstacks.lock. agentstacks update moves a third-party source to the newest tag with the same
prefix (v1.0.0 to v1.0.1; a tag with another prefix such as other-2.0.0 is not chosen). The
official repository's own tags are limited to packs-v1.*
(see The Command Line).
This was run end to end on team-lint with a local git repository (git = "file:///..."): the
plan showed six files, and the [packs.team-lint.options] value max_warnings = 5 appeared in the
installed skill.
11. Before you call it done
-
pack.tomlhasapi = 1, a validnameandversion, and adescription. -
agentstacks planon the pack has no refusal; eachskiphas a reason you accept. -
agentstacks apply --yes, thenagentstacks planshows0 to write;doctorsayshealthy. -
airsl test <pack>reports0 failed, andairsl check <pack>compiles every file. -
Tests and anything else that is not for the agent are in
exclude. -
No path or name of one tool in neutral content: tokens everywhere, tool-specific files under
native/<tool>/. -
Every hook grant is the least it needs, and every program it runs is in
requires.binaries. -
requires.packslists every pack a token or arunpoints into, andrequires.airslis set. -
A
README.mdis inexcludeunless the agent should read it.
Common refusals
Wording is as the CLI prints it. A row that starts at pack.toml or at a file inside the pack is
shown without the pack's path, which the CLI prints in front of it (./packs/team-lint/pack.toml: ...). The wording is not covered by the stability promise, the location is.
| You see | Fix |
|---|---|
./packs/team-lint: not a pack (no pack.toml) | the directory has no pack.toml at its root |
pack.toml: team-lint: api 0 is from agentstacks 0.x (this agentstacks speaks 1; set api = 1, or use a newer release of it) | set api = 1 |
pack.toml: requires.airsl: required (the pack contains .lua files) | add airsl = ">=0.1.5" to [requires] |
skills/lint/SKILL.md: name "other" does not match "lint" | name is the directory name |
agents/linter.md:9: pack "team-lint" has no skill "nope" | fix the token, or add the skill |
agents/linter.md:9: var "arguments" is only valid in SKILL.md | use {{var arguments}} in a SKILL.md only |
pack.toml: hooks[0].match: not allowed on session.end | that event takes no match |
pack.toml: hooks[1].run: "hooks/my.remind.lua" segment "my.remind" may use only letters, digits, _ and - | rename the file; a segment is letters, digits, _ and - |
pack.toml: hooks[1].grants.exec[0]: "git" is not in requires.binaries | add binaries = ["git"] to [requires] |
pack.toml: exclude[0]: "**/SKILL.md" excludes skills/lint/SKILL.md | narrow the glob; a SKILL.md cannot be excluded |
agentstacks.toml: packs.team-lint: option "max_warnings" is required | give the option a default, or set it in the project |
The full list, with the rule behind each, is in The Pack Format.
The Pack Format
The contract for a pack at api = 1: the layout of the directory, every field of pack.toml, the
{{...}} tokens, the frontmatter of skills and agents, hooks and their events, options, the
native/<tool>/ directories, and requires.agentstacks. A pack is tool-neutral content; the tool
extension decides how each item lands in a tool's own files.
Every refusal quoted below was produced by the agentstacks 1.0 binary or is pinned by a test in
crates/agentstacks/src. Each is shown after the file's path, or with the path where the location is the point. What
api = 1 promises, and what it does not (the exact wording of a refusal is not covered), is on
the stability page. To write a pack step by step, follow
Writing a Pack. Hook mechanics are in Hooks, and
what an extension does with a pack is in The Extension API.
1. Layout
<pack>/
pack.toml required: the manifest
skills/<name>/SKILL.md one directory per skill; any other files in it belong to the skill
agents/<name>.md one file per agent
native/<tool>/ files and hooks for one tool only (section 8)
<anything else> root files: scripts, data, README.md, hooks/*.lua
| Rule | Refusal |
|---|---|
the directory holds a pack.toml | ./packs/x: not a pack (no pack.toml) |
a skill directory holds a SKILL.md | ./packs/x/skills/lint: missing SKILL.md |
skills/ holds only skill directories | ./packs/x/skills/loose.md: only skill directories belong in skills/ |
agents/ holds only <name>.md files | ./packs/x/agents/sub.txt: agents/ holds only <name>.md files |
native/ holds only tool directories | ./packs/x/native/loose.md: only tool directories belong in native/ |
commands/ and rules/ are reserved | ./packs/x/commands: reserved, not supported in api 1 |
| no symlink anywhere | ./packs/x/link.md: symlinks are not allowed in a pack |
| a rendered file is UTF-8 | ./packs/x/data.json: not valid UTF-8, cannot render |
| the pack installs something: a skill, an agent or a hook | ./packs/x: pack declares nothing to install |
- Names. A skill, agent, pack or tool name is 1 to 64 bytes of
a-z,0-9and-, starting with a letter:"Team-Lint" is not a valid name. A skill and an agent may share a name. An option name uses_where the others use-(section 6). - Dot entries (a file or directory whose name starts with
.) are ignored, never entered and never refused. An empty directory contributes nothing. - What is installed. Every file except
pack.tomland eachnative/<tool>/hooks.toml, less whatexcluderemoves. A skill's files go to the tool's skill directory, an agent file becomes the tool's agent, and every root file goes under the pack's install root, a directory the extension names (see{{root}}in section 3). - What is rendered. Every installed
.mdfile, and each filerenderlists. Rendering replaces the tokens of section 3. Any other file is installed byte for byte, so a script or a JSON file never changes.
2. pack.toml
exclude = ["README.md", "**/*_test.lua"]
render = ["data/settings.json"]
[pack]
name = "team-lint"
version = "1.0.0"
api = 1
description = "Team lint rules"
[requires]
packs = ["core"]
agentstacks = ">=1.0"
airsl = ">=0.1.5"
binaries = ["git"]
[options.max_warnings]
type = "integer"
default = 0
description = "Warnings the lint skill tolerates"
[[hooks]]
kind = "message"
event = "session.start"
text = "Run {{skill lint}} before you commit."
render and exclude are keys of the top-level table, so write them before the first [table]
header: a key written after a header belongs to that table. The top level holds only pack,
requires, render, exclude, options and hooks; any other key is foo: unknown key, and so
is an unknown key in [pack] (pack.foo: unknown key). A file is read to the end: every refusal
of it is reported at once, except that a TOML syntax error is the file's only refusal.
[pack]
| Key | Required | Rule | Refusal |
|---|---|---|---|
name | yes | a pack name | pack.name: "Team-Lint" is not a valid name |
version | yes | major.minor.patch semver | pack.version: "1.2" is not semver |
api | yes | the integer 1 | team-lint: api 2 not supported (this agentstacks speaks 1) |
description | yes | text that is not blank | pack.description: empty |
A missing key is pack.name: required, and a value of the wrong type is
pack.api: expected integer, got float. A pack written for agentstacks 0.x says api = 0; the
refusal is team-lint: api 0 is from agentstacks 0.x (this agentstacks speaks 1; set api = 1, or use a newer release of it).
When the pack's name is itself invalid, the same two refusals are located at pack.api instead of
using the name.
render and exclude
render lists files to render besides the Markdown. exclude lists globs of files to leave out.
Both hold paths relative to the pack, written with /.
| Rule | Refusal |
|---|---|
a render path is relative | render[0]: "/x" must be relative |
| it stays inside the pack | render[1]: "../x" must stay inside the pack |
it is not code: .lua and .sh are installed verbatim | render[2]: "x.lua" is code; code is installed verbatim |
| it names a file of the pack | render[0]: "data.json" does not exist |
it is a file the pack installs (not pack.toml, not a hooks.toml) | render[0]: "pack.toml" is never installed |
no exclude glob matches it | render[0]: "README.md" is also excluded |
an exclude entry is a glob | exclude[0]: "[" is not a valid glob |
an exclude entry is relative | exclude[1]: "/tmp/**" must be relative |
exclude leaves pack.toml, every SKILL.md, every agent file and every own-pack hook script in place | exclude[0]: "**/SKILL.md" excludes skills/lint/SKILL.md |
A glob is matched against each file's path from the pack root. * and ? stay inside one path
segment; only ** crosses /. An excluded file is not installed and not read for tokens, so a
test file (**/*_test.lua) can sit beside the script it tests and never ship. A path with ., //
or a trailing / in it is refused with the rule it breaks ("a//b" must not have an empty segment).
[requires]
| Key | Meaning | Refusal |
|---|---|---|
packs | packs that must also be in the project | requires.packs[0]: a pack cannot require itself; requires.packs[2]: "core" listed twice |
agentstacks | the agentstacks versions the pack works with (section 9) | requires.agentstacks: "nope" is not a version range |
airsl | the airsl versions the pack's Lua needs | requires.airsl: required (the pack contains .lua files) when the pack installs any .lua file and sets none |
binaries | programs the pack needs on PATH | requires.binaries[1]: "git" listed twice |
A range uses one of =, >, >=, <, <=, ~, ^ or *, and may hold several comparators
(>=0.1.5, <0.3). airsl is needed because hooks and scripts run under airsl. An unknown key in
the table is requires.foo: unknown key.
What a project's set of packs must satisfy together is checked after every pack loads, and is
refused at agentstacks.toml:
| Rule | Refusal |
|---|---|
| each required pack is listed in the project | agentstacks.toml: packs.team-lint: team-lint requires pack "core", which agentstacks.toml does not list (add it: --pack core) |
| packs do not require each other in a loop | agentstacks.toml: requires cycle: a → b → a |
the airsl ranges of all packs overlap | agentstacks.toml: airsl: a needs >=0.2, b needs <0.2 |
| the installed airsl is inside them | agentstacks.toml: airsl 0.1.5 installed, packs need >=9.0 |
each binaries entry is on PATH | agentstacks.toml: packs.team-lint: binary "git" not found on PATH |
the key under [packs.<key>] is the name inside the source | agentstacks.toml: packs.zzz: source contains pack "a" |
3. Tokens and vars
A token is {{kind target}} in the text of a pack. Rendering replaces it with a value for the tool
being set up. The kind is the first word; the target is the rest, separated by spaces or tabs.
| Token | Replaced with | Target |
|---|---|---|
{{skill name}} | how the tool invokes the skill, such as /team-lint-lint for Claude Code | a skill, [pack/]name |
{{agent name}} | the tool's name for the agent | an agent, [pack/]name |
{{skill_dir name}} | the directory the skill is installed in | a skill, [pack/]name |
{{root}}, {{root pack}} | the install root of this pack, or of the named pack | none, or a pack name |
{{var name}} | a value the extension supplies | one of the vars below |
{{option name}} | the value of one of this pack's options | an option of this pack |
The vars are session_id, arguments, tmpdir, home, airsstack_home and project_dir. What
each becomes is the extension's choice ($ARGUMENTS for Claude Code's arguments). A var an
extension does not supply is a visible skip, never a silent drop. {{var arguments}} is valid only
in a SKILL.md. An option renders as true or false, a decimal integer, or the string as written.
\{{ is a literal {{ that is not a token. A }} with no opener is plain text.
Where tokens are read: installed .md files (a SKILL.md and an agent file from the line after
the closing ---), files listed in render, the description and argument_hint values of
frontmatter, and the fields of hooks: text, args, run and the paths of grants. Tokens are
not read in name, in the values under native, in a file that is not rendered, or in an excluded
file.
| Rule | Refusal |
|---|---|
| the kind is one of the six | agents/linter.md:9: unknown token kind "skil" |
| the token closes on its line | unterminated token |
| the token is not empty | empty token |
| a kind that needs a target has one | token "skill" needs a target |
| a kind takes one target | token "root" takes one target |
a target is [pack/]name | "a/b/c" is not a valid target (expected [pack/]name) |
root names a pack, not an item | token "root" takes a pack name, not "core/x" |
| the var exists | unknown var "cwd" (known: session_id, arguments, tmpdir, home, airsstack_home, project_dir) |
arguments is used in a SKILL.md | agents/linter.md:9: var "arguments" is only valid in SKILL.md |
| an option token names this pack's option | option tokens name this pack's options only |
| the option is declared | skills/lint/SKILL.md:8: pack "team-lint" has no option "nope" |
| a skill or agent of this pack exists | agents/linter.md:9: pack "team-lint" has no skill "nope" |
neutral content does not reach into native/ | skills/lint/SKILL.md:10: neutral content must not reference native/ |
| a token names another pack only if the pack requires it | agents/linter.md:9: {{skill core/review}} targets pack "core", which team-lint does not require. Add it to requires.packs or remove the ref. |
A token for another pack is also refused when that pack is required and ships no such item. The
native/ row applies to a {{root}} token followed by /native: a pack's native files are for
one tool, so content that every tool installs may not point at them.
4. Frontmatter
A SKILL.md and an agent file start with a YAML block between two --- lines, the first on line 1.
A file with no block is skills/lint/SKILL.md: missing frontmatter. Each key is checked: every
error of the file is reported together, and an unknown key is unknown key "colour".
Skill (skills/<name>/SKILL.md):
| Key | Required | Value |
|---|---|---|
name | yes | the directory name, written literally: name "other" does not match "lint", name must be a literal |
description | yes | text; tokens are allowed |
invocation | no | user (only the user starts it) or any (the default): invocation: "anyone" (expected user, any) |
argument_hint | no | text; tokens are allowed |
native | no | a mapping of tool name to tool-specific values, kept opaque |
Agent (agents/<name>.md):
| Key | Required | Value |
|---|---|---|
name | yes | the file name without .md, written literally |
description | yes | text; tokens are allowed |
model | no | fast, balanced or deep: model: "sonnet" (expected fast, balanced, deep) |
effort | no | low, medium or high: effort: "max" (expected low, medium, high) |
tools | no | a list from read, write, edit, grep, glob, shell, skill: tools[1]: unknown "bash"; a repeat is "read" listed twice |
native | no | as for a skill |
The words are tool-neutral. The extension maps a model word and each tools entry to the tool's
own names, and skips with a reason what the tool cannot express. A value starting with { must be
quoted in YAML; the refusal for an unquoted token says so.
The native mapping is for values that only one tool understands. Its keys must be tool names
(native.Claude: "Claude" is not a valid tool name), and the extension for that tool reads its
entry. The core never looks inside.
5. Hooks
A hook is one [[hooks]] table in pack.toml: an event, an optional selector and an action.
Hooks says how the core runs one; this is what a pack may write.
| Key | Applies to | Rule |
|---|---|---|
kind | all | message or lua: hooks[0].kind: "sh" (expected message, lua) |
event | all | one of the six neutral events below: hooks[1].event: "tool.pre" unknown |
match | events with selectors | a list of the values the event accepts; absent means every value |
agents | agent.stop | a list of agents of this pack; absent means any agent |
text | message | required, not empty; tokens are allowed |
run | lua | required, a .lua file; tokens are allowed |
args | lua | a list of strings; tokens are allowed |
may_block | lua | true or false (the default); a hook that is not may_block cannot block |
grants | lua | what the script may touch; nothing is granted by default |
Every Lua hook runs fail-open, so there is no fail_open key (hooks[2].fail_open: unknown key).
Events
| Event | When | match values | agents |
|---|---|---|---|
session.start | a session starts | startup, resume, clear, compact | no |
session.end | a session ends | none | no |
prompt.submit | the user submits a prompt | none | no |
tool.before | before a tool call | read, edit, write | no |
tool.after | after a tool call | read, edit, write | no |
agent.stop | an agent stops | none | yes |
The vocabulary is frozen for all of 1.x: a new event or match word needs api = 2 (see
the stability page). The extension maps each event to the tool's own, and
skips a hook with a reason when the tool has no such event.
| Rule | Refusal |
|---|---|
match only on session.start, tool.before, tool.after | hooks[0].match: not allowed on session.end |
each match value is one the event accepts | hooks[1].match[0]: "bash" not valid for tool.after |
a match or agents list is not empty | hooks[1].match: empty list never fires |
| no value is listed twice | hooks[1].match[1]: "edit" listed twice |
agents only on agent.stop | hooks[1].agents: only allowed on agent.stop |
each agents entry is an agent of the pack | hooks[1].agents[0]: pack "team-lint" has no agent "nobody" |
a message hook has no run, args, grants | hooks[0].run: not allowed on a message hook |
| a message hook does not block | hooks[0].may_block: message hooks cannot block |
a lua hook has no text | hooks[1].text: not allowed on a lua hook |
run
run is a Lua file, written in one of three forms:
| Form | Names |
|---|---|
hooks/x.lua | a root file of this pack |
{{root}}/hooks/x.lua | the same file |
{{root core}}/hooks/x.lua | a root file of pack core, which this pack must require |
The path must name an installed root file: not pack.toml, and nothing under skills/, agents/
or native/. Each segment, with .lua taken off the last, uses only letters, digits, _ and -,
because the runtime requires the script as a dotted module name.
| Rule | Refusal |
|---|---|
it is a .lua file | hooks[1].run: "remind.sh" is not a .lua file |
| it is written in a form above | hooks[1].run: must be pack-relative, {{root}}/… or {{root <pack>}}/… |
| each segment is a module name | hooks[1].run: "hooks/my.remind.lua" segment "my.remind" may use only letters, digits, _ and - |
| the file exists in this pack | hooks[1].run: "hooks/remind.lua" does not exist |
| in another pack, it is an installed root file there | "hooks/x.lua" does not exist in core |
grants
[hooks.grants]
read = ["{{root}}"]
write = ["{{var tmpdir}}"]
env = ["TMPDIR"]
exec = ["git"]
| Key | Value | Refusal |
|---|---|---|
policy | confined, the default and the only one allowed | "trusted" is not allowed for pack hooks; "pure" is not supported in api 1 (airsl has no require under pure, airsstack/airsl#12); "x" (expected confined) |
read, write | paths: absolute, or starting with {{root}}, {{skill_dir ...}} or {{var ...}} | hooks[1].grants.read[0]: "data" must be absolute or start with a token |
env | environment variable names (^[A-Z_][A-Z0-9_]*$) | "home" is not an environment variable name |
exec | airsl, or a binary in requires.binaries | hooks[1].grants.exec[0]: "git" is not in requires.binaries |
A repeat in env or exec is "x" listed twice.
6. Options
An option is a setting a project can change. A pack declares it under [options.<name>]; a skill
or a hook reads it with {{option name}}.
[options.max_warnings]
type = "integer"
default = 0
description = "Warnings the lint skill tolerates"
| Key | Required | Rule | Refusal |
|---|---|---|---|
| table name | snake_case: letters, digits and _, starting with a letter | options.archive-keep: "archive-keep" is not a valid option name | |
type | yes | boolean, integer (64-bit) or string | options.x.type: required; options.x.type: "number" (expected boolean, integer, string) |
default | no | a value of the declared type | options.max_warnings.default: expects integer, got string |
description | yes | text | options.x.description: required |
A project sets a value in agentstacks.toml:
[packs.team-lint]
git = "https://github.com/acme/lint-packs"
tag = "v1.0.0"
subdir = "packs/team-lint"
[packs.team-lint.options]
max_warnings = 5
The value must have the declared type, an option with no default must be set, and a key the pack does not declare is refused:
| Rule | Refusal |
|---|---|
| a required option is set | agentstacks.toml: packs.team-lint: option "max_warnings" is required |
| the value has the declared type | agentstacks.toml: packs.team-lint.options.max_warnings: option max_warnings expects integer, got string |
| the key is declared | agentstacks.toml: packs.team-lint.options.extra: no option "extra" |
7. native/<tool>/
Content for one tool only. <tool> is a tool name (claude, musecode, opencode); the extension of that
tool reads the directory. A directory no installed tool claims is shown as a note in the plan,
note native/other: not for claude.
- Every file in it is installed, relative to the tool's own directory, and rendered when it is
Markdown.
hooks.tomlis not installed as a file. native/<tool>/hooks.tomldeclares hooks in the tool's own event vocabulary:
[[hooks]]
kind = "message"
event = "UserPromptSubmit"
text = "Lint is part of done."
A native hook has the keys of a neutral one, with two differences: event and match are opaque
text that the core never checks (the extension for the tool does), and agents is not accepted
(native/claude/hooks.toml: hooks[0].agents: unknown key). Kinds, run, args, may_block and grants follow section 5,
and exec is checked against the pack's own requires.binaries. The file's only top-level key is
hooks; an empty file declares none. The file itself is parsed, never installed.
Neutral content may not point into native/ with a {{root}} token (section 3). Whether the tool
knows an event is the extension's to say: a native hook it cannot express becomes a skip with a
reason, as team-lint/native-hook/0: claude treats hook output at agent stop as feedback that keeps the agent running
shows.
8. Official packs as examples
| Pack | Shows |
|---|---|
guideline-rust | a skill with references, a render file and an exclude; no hooks, no Lua |
core | agents, options, message and Lua hooks with grants, native/claude/hooks.toml |
| conformance | one of every item kind, token kind and hook event, with requires.agentstacks |
9. requires.agentstacks
[requires]
agentstacks = ">=1.0"
Declare it when the pack uses something a 1.N release added. A pack that omits it works with every
agentstacks that speaks api = 1. The range is checked first, before anything else in the pack is
read: an agentstacks the range excludes refuses the pack with one line and goes no further, because
a pack written for a later release may use things this one does not know.
| Rule | Refusal |
|---|---|
| the value is a range | requires.agentstacks: "nope" is not a version range |
| the running agentstacks is in it | requires.agentstacks: ">=9.0" does not match agentstacks 1.0.0 (install a newer agentstacks) |
The second line is the only refusal reported for a pack whose range excludes the running version. Once the range is fixed or agentstacks is updated, the rest of the pack is checked.
The 1.x Stability Promise
agentstacks 1.0 freezes the pack format and the extension API as api = 1. This page says what
that means: what keeps working, what a 1.x release may add, what it may not, and what the promise
does not cover.
Anything that works on agentstacks 1.N works on every 1.M with M ≥ N. A pack or an extension you
write for api = 1 keeps working until 2.0.
What is covered
- The pack format: the layout,
pack.toml, skill and agent frontmatter, tokens and vars, the hook schema and the event vocabulary, andnative/<tool>/. - The extension API:
extension.toml, the sandbox and its limits, theagentstackstable, thevaluesandplanevents and their payload fields, the operations, and the coverage and validation rules. The Extension API is the contract. - The hook runtime: the command line, the behaviour of
runtime.lua, the neutral event and result, and the translator contract. Hooks is the contract. agentstacks.toml.agentstacks.lock: its format is frozen for all of 1.x. Every 1.x reads and writes the same lock, and reads a lock written withapi = 0.- The command line: the commands, their flags and their exit codes.
What a 1.x minor release may add
Additions only, and none of them can break a 1.0 pack or extension:
- new optional keys that only the core reads;
- new payload fields, which extensions ignore;
- new
agentstacks.*functions; - new vars, because a var an extension does not supply is already a visible skip (see The Extension API);
- new commands and flags;
- allowing a refused value that creates no new item, such as
grants.policy = "pure".
What needs api = 2
These stay frozen for all of 1.x, because each would give a working 1.0 extension an item it cannot cover:
- new item kinds, such as
commands/andrules/, which are reserved today; - new neutral events;
- new
match, agenttoolsormodelwords; - any other change that would give a 1.0 extension an item it cannot cover.
What was settled before the freeze
| # | Finding | Settled as |
|---|---|---|
| R1 | grants.policy = "pure" is refused while airsl#12 is open, and its text names the api | Allowing it later is an addition. |
| R2 | commands/ and rules/ are reserved, and their refusal names the api | Supporting them needs api = 2. |
| R3 | A hook with no match gets every value | The vocabularies are frozen, so no value an extension does not know can appear in 1.x. |
| R4 | Item ids such as core/hook/0 | Ids are opaque strings: copy them back, never parse them. |
| R5 | The exact text of refusals and messages | Not covered. Only the location and key shapes are. |
| R6 | A future packs-v2.* release would be fetched by the shorthand and by update | They only take packs-v1.* tags from the official repository (see The Command Line). |
| R7 | A key added in 1.N to agentstacks.toml is unknown key to 1.0 | A team that uses a 1.N key needs agentstacks 1.N everywhere. There is no gate for it. |
What authors do
When a pack or an extension uses something a 1.N release added, declare it:
[requires]
agentstacks = ">=1.N"
An agentstacks that is older than the range refuses the pack or extension with
"<range>" does not match agentstacks <version> (install a newer agentstacks) under the key
requires.agentstacks, instead of failing later on a key it does not know.
What is not covered
- The exact wording of refusals, notes and prompts.
- The layout of the plan text.
- The text of
--help. - The Rust API of the
agentstackslibrary crate. It is the engine of the command line, and only the command line is covered. - claudevs, which has its own releases.
2.0
2.0 is the only release that may remove or change a covered behaviour. It would ship as
api = 2, with its own move from 1.x.
Muse Code
What the official musecode extension does: the files it writes, the variables it gives packs, how
hooks reach Muse Code, what it skips, and what it cannot do. It is checked against Muse Code
1.4.25-R9361.1. It runs on the same api = 1 as every extension; see
the extension API and hooks.
Use it with agentstacks init --tool musecode --pack <p>, or add it to a project with
agentstacks ext add musecode. The extension is released in packs-v1.1.0.
Start Muse Code in the project root and trust the workspace: project config loads only from a
trusted workspace. After apply, start a new session, because Muse Code reads its hooks, skills and
agents when a session starts.
The extension declares one file for reading, .muse/hooks.json, which the user and the extension
share (section 4.2).
1. Vars
A pack text can use these {{var <name>}} forms. The extension gives only the names a pack uses.
| Var | Value | Note |
|---|---|---|
project_dir | . | right while the shell is in the project root; hooks run in the directory Muse Code was started in |
session_id | ${MUSE_SESSION_ID} | set in the bash tool's environment; Muse Code never substitutes it in text, so the model uses it in shell commands |
arguments | <arguments> | Muse Code never substitutes $ARGUMENTS in a skill; the TUI appends the arguments after the skill text |
tmpdir | ${TMPDIR:-/tmp} | expanded by the shell |
home | $HOME | expanded by the shell |
airsstack_home | ${AIRSSTACK_HOME:-$HOME/.airsstack} | expanded by the shell; in a hook it is always the default (section 8) |
The root for pack files is .muse/agentstacks. A skill <p>/<s> lives in .agents/skills/<p>-<s>
and is invoked as /<p>-<s>. An agent <p>/<a> is named <p>-<a>.
2. Files
| Item | What is written |
|---|---|
skill SKILL.md | .agents/skills/<p>-<s>/SKILL.md, with frontmatter and the text |
| other skill file | copied next to SKILL.md |
| agent | .agents/agents/<p>-<a>.md, with frontmatter and the text |
| native file | native/musecode/<rel> is copied to .agents/<rel> |
| hooks | .muse/hooks.json, shared with the user (section 4.2) |
.muse/agentstacks/translate.lua | written when at least one Lua hook is covered by the write of the hooks file |
.muse/agentstacks/runtime.lua, root files | written by the core |
A path joins the pack and item names with -, so core/status and sdlc/status never clash. Two
items whose joined names are equal (pack a-b skill c, pack a skill b-c), or a native file on
a generated path, propose the same path twice, and the core refuses it.
2.1 Frontmatter
Every value is written as JSON, which Muse Code reads as a YAML value. The generated keys come
first, in the order below. A native key of the same name replaces a generated one; the other
native keys follow, sorted by name.
A skill gets:
| Key | Value | When |
|---|---|---|
name | <p>-<s> | always |
description | the skill's description | always |
disable-model-invocation | true | invocation: user: the skill is hidden from the model's list, and the user still runs it as /<p>-<s> |
argument-hint | the skill's argument hint | when set; shown as hint text after the command |
An agent gets:
| Key | Value | When |
|---|---|---|
name | <p>-<a> | always |
description | the agent's description | always |
tools | the agent's tools, mapped as below | when the agent lists tools |
effort | the agent's effort | when set |
The neutral tool words map to Muse Code's tool names in the order the pack lists them: read to
read_file, edit to edit_file, write to write_file, grep and glob to search, shell
to bash, skill to read_skill. A name already written is not repeated. An empty list is written
as tools: []. The model key is never written: a neutral model tier is not a Muse Code model id.
3. Hook mapping
Each hook becomes one handler in .muse/hooks.json or one skip. Packs are read in payload order.
Within a pack, neutral hooks come first, then native hooks.
| Neutral event | Muse Code event | Matcher |
|---|---|---|
session.start | SessionStart | the match words joined with |; none when match is absent. Muse Code matches it on the session source |
session.end | SessionEnd | none |
prompt.submit | UserPromptSubmit | none; Muse Code refuses a matcher on this event |
tool.before, tool.after | PreToolUse, PostToolUse | from match: read is Read, edit is Edit, write is Write, joined with |. No match means Read|Edit|Write. Muse Code matches these on its read_file, edit_file and write_file tools |
agent.stop | SubagentStop | none; a hook that lists agents is skipped (rule H3) |
A native hook (in native/musecode/hooks.toml) keeps its event name as written. Its match is
joined with |, and it has no matcher when match is absent or empty.
A Lua hook becomes /bin/sh -c '<quoted argv>' # agentstacks: each argument is wrapped in double
quotes with \, " and ` escaped, the arguments are joined with spaces, and every ' in the
result is written as '\''. A message hook becomes printf '%s\n' '<json>' # agentstacks, where
the JSON carries the text as additionalContext. The # agentstacks tail marks a handler as ours:
plan and apply replace and remove only handlers that end with it.
4. Delivery
4.1 The translator
A Lua hook runs through the hook runtime, which loads .muse/agentstacks/translate.lua. The
translator turns Muse Code's payload into a neutral event and turns the hook's result into the JSON
Muse Code reads from stdout. A neutral event carries event, session_id and cwd, plus these
fields where the event has them: source, prompt, tool, path and last_message. The path is
the one the model wrote, made absolute against cwd when it is relative. Tools other than
read_file, edit_file and write_file run no hook. No payload field names the running agent, so
agent and agent_id are never set.
4.2 The hooks file
.muse/hooks.json is shared with the user, so it is never locked and is rewritten whole. An empty
or blank file counts as {}. A file that is not JSON, not an object, or whose hooks is not an
object is refused with the core's message. For each event the extension touches, it keeps the user's groups, removes only the handlers
ending in # agentstacks, drops a group that is left empty, and appends its own groups in payload
order. An event whose array it cannot rewrite is left alone, and each hook of ours on it is skipped
(section 5).
Every group the extension writes has a string matcher or none and handlers with type and
command only, so it never gives Muse Code a reason to drop the file.
4.3 How results reach the model
| Event | Result | What happens |
|---|---|---|
PreToolUse | block | the call is refused, and the model sees tool blocked by hook: <reason> |
PreToolUse | context, alone or beside a block | a developer message after the tool output (after the blocked output when the call is refused) |
PostToolUse, UserPromptSubmit, SessionStart | context | a developer message after the tool output or the prompt; at session start the context is in the first request |
PostToolUse | block | the model sees the reason in place of the tool output |
UserPromptSubmit | block | the run is cancelled before the model is called |
SubagentStop | block | the agent runs again |
SessionStart | block | the block text is joined into the context, because a session start cannot block |
Context returned by a neutral Lua agent.stop or session.end hook is dropped; only a block on
agent.stop has an effect. A hook that returns no context and no block adds nothing. A hook's
failure, a missing airsl included, is silent and the hook fails open: the call goes ahead.
agentstacks doctor checks airsl and its pin (see hooks).
5. Skips
An item the extension cannot express becomes a skip with a reason. In each table the rules are checked in the order listed; the first that applies gives the reason.
Frontmatter rules. F2 to F5 check the values as written, after a native key has replaced a generated
one. A native name or description that is not a string is written as given and not checked.
| # | Case | Applies to | Reason |
|---|---|---|---|
| F1 | a native key with a character other than A-Z, a-z, 0-9, _ or - | skills, agents | native.musecode key "<key>" cannot be written as frontmatter |
| F2 | the skill name is longer than 128 characters | skills | musecode skill names are at most 128 characters (this one has <n>) |
| F3 | the agent name is not lowercase letter words joined by - | agents | musecode agent names are lowercase letter words joined by - (got "<name>") |
| F4 | the agent description is longer than 4096 bytes | agents | musecode drops an agent whose description is over 4096 bytes (this one has <n>) |
| F5 | the whole SKILL.md text is longer than 262144 bytes | skills | musecode refuses a SKILL.md over 262144 bytes (this one has <n>) |
A skill skipped by F1, F2 or F5 is skipped whole, with its other files. The pack and item names are
each at most 64 bytes, so <p>-<s> can reach 129 characters and meet F2.
Hook rules.
| # | Case | Applies to | Reason |
|---|---|---|---|
| H1 | the hook's text or an argument holds ${MUSE_SESSION_ID} | both | musecode gives hooks the session id in the event (event.session_id), not as {{var session_id}} |
| H2 | a message hook on session.end | neutral hooks | musecode shows no hook output to the model at session end |
| H3 | an agent.stop hook with agents | neutral hooks | musecode gives hooks no agent name at agent stop, so it cannot run this hook for only the listed agents |
| H4 | a message hook on agent.stop | neutral hooks | musecode passes no hook message to the model at agent stop |
| H5 | a native hook on an event Muse Code does not run (list below) | native hooks | musecode does not run hooks on "<event>" |
| H6 | a native message hook on an event whose context does not reach the model (list below) | native hooks | musecode passes no hook message to the model on <event> |
| H7 | a native hook with a non-empty match on UserPromptSubmit or Stop | native hooks | musecode refuses a matcher on <event> |
| H8 | a Lua argument with a $ left after every var form is removed | both | musecode runs hook commands through sh, which would expand the literal $ in argument "<arg>" |
Muse Code runs a native hook on these events: SessionStart, UserPromptSubmit, PreToolUse,
PermissionRequest, PostToolUse, PostToolUseFailure, PostToolBatch, PreLLMCall,
PostLLMCall, PreCompact, PostCompact, SubagentStart, SubagentStop, Stop, StopFailure,
SessionEnd, Notification and SessionFork. Any other name gets H5.
A native message hook renders on SessionStart, SubagentStart, UserPromptSubmit, PreToolUse,
PostToolUse and PostToolUseFailure: on those events a message reached the model in a run. On any
other event it gets H6, including PostToolBatch, PreLLMCall and PostLLMCall, whose delivery
was not shown.
<event>, <arg>, <key>, <name> and <n> stand for the hook's event, the argument, the key,
the name and the measured size. H1, H2, H6 and H8 keep the claude extension's wording with claude
replaced by musecode.
Hooks-file rule. When an event array in .muse/hooks.json cannot be rewritten (it holds a null, an
empty list, or a value that is not a list of hook groups), the event is left alone and each hook of
ours on it, both kinds, gets this reason, with the event name in place of <event>:
.muse/hooks.json: hooks.<event> holds entries the musecode extension cannot rewrite (a null, an empty list, or a value that is not a list of hook groups).
The core's own skips (missing values, see the extension API) apply as for every extension.
With the five official packs, these hooks are skipped: core's session.end message (H2) and the
agent.stop handoff checks of core, sdlc and journal (H3). Core's other agent.stop hook, which
lists no agents, renders. The two native hooks in the packs are for claude only.
6. Not carried over from Claude
| Claude feature | Muse Code | Visible as |
|---|---|---|
SubagentStop matcher by agent name | no agent name in hook payloads | skip H3 |
agent_type and agent_id on events | none | every event reads as the main agent's |
| model tier | Muse Code model ids only | not written |
cd "$CLAUDE_PROJECT_DIR" | hooks run in the launch directory | project_dir is . |
$ARGUMENTS in a skill | never substituted; the TUI appends the arguments | <arguments> |
/skill args in headless runs | muse exec sends /name args as plain text | documented |
7. Behaviour to know
- Start in the project root. From a subdirectory Muse Code does not load the project's config.
- Trust the workspace. Project config loads only in a trusted workspace.
- New session after
apply. Muse Code reads.muse/hooks.jsonwhen a session starts; skills and agents are read by a new run. - Hidden skills. A skill with
invocation: useris written withdisable-model-invocation: true. It is hidden from the model's list; the user still runs it as/<p>-<s>. - Shell. Muse Code runs a hook command through the shell named by
SHELL; the/bin/sh -cwrapper makes the argument quoting the same for every shell. Commands were checked under zsh, sh and bash. ASHELLthat cannot start fails every hook, silently.
8. Limits
- With
--workspace <root>from a subdirectory, hooks run in that subdirectory, so relative grants,project_dirand the translator's absolute paths point there. A plain start in a subdirectory loads no project config. Start in the project root. - A user group in
.muse/hooks.jsonthat Muse Code finds invalid makes it drop the whole file, ours included. - A native Lua hook on an event other than
SessionStart,UserPromptSubmit,PreToolUse,PostToolUseandSubagentStopruns, but its context or block is not delivered. - No hook knows which agent is running:
agent.stophooks for named agents are skipped (H3), and tool hooks in a subagent read as the main agent's. SubagentStopfires several times per turn for Muse Code's owngoal-reminderagent.- In hooks,
AIRSSTACK_HOMEis always the default$HOME/.airsstack: Muse Code passes hooks only an allowed list of variables. Thebashtool sees the user's value. {{var project_dir}}is.: right while the shell is in the project root.- A hook's failure, a missing airsl included, is silent and fails open.
muse execdoes not expand/<skill> args; only the TUI does.- With
claudelisted, Claude-only skills show in Muse Code; they can be turned off one at a time. Withopencodelisted, skills only the musecode extension writes (in.agents/skills/) show in OpenCode. - Hook commands were checked under
SHELLzsh, sh and bash only. - Muse Code's shell sandbox may refuse a skill's script a write outside the workspace, for example
under
$HOME/.airsstack. This is not probed; choose the permission profile that fits.
9. The check
cargo make musecode-check runs the extension inside the pinned real Muse Code against a local mock
model, in an isolated home. It is not part of cargo make dod: it needs Node and a download, so CI
runs it as its own job. Its scenarios live in crates/agentstacks-cli/tests/musecode-check/.
Under the Hood
crates/agentstacks follows a ports-and-adapters (hexagonal) layout. All logic sits inside, behind
ports, and is tested with fakes. Only the adapters touch the disk, git, the airsl binary or Lua.
┌──────────────── inside (no OS, no airsl) ───────────────┐
│ │
fs/ ──impl──► port/ ◄──uses── app/ ──uses──► types/ │
process/ ──impl──► traits use cases domain: │
host/ ──impl──► + fakes plan, apply, data + pure │
│ doctor, update rules │
└─────────────────────────────────────────────────────────┘
outside: adapters ▲
└── agentstacks-cli wires the real adapters in
process/ ──uses──► fs/cache (the one edge from one adapter to another)
types/ ──uses──► port::{FileTree, EntryKind} (the read-only tree the format loaders take)
Modules
| Module | Holds | State |
|---|---|---|
types/ | the domain: the pack, extension, project and lock formats, and pure rules (operations, source resolution, plan steps, JSON text edit, the hook protocol, the ext test check rules) | built |
port/ | traits only, each with a fake for tests: FileTree, Workspace, Scratch, Git, Binary, Adapter | built |
app/ | use cases, generic over ports: plan, apply, doctor, update, init, and ext (ext add, ext test) | built |
fs/ | adapter: FileTree and Workspace on the real disk, and Scratch (a directory outside the project, a temporary project that is removed on drop) | built |
process/ | adapter: Git on the git CLI, Binary on airsl --version and airsl test <dir> | built |
host/ | adapter: Adapter on the airsl sandbox, where extension Lua runs | built |
The command-line crate agentstacks-cli is the composition root: it builds the real adapters and
passes them to app/.
Dependency rule
types → port::{FileTree, EntryKind} only
port → types
app → port, types
fs, process, host → port, types; process → fs::cache only
Inside (types, port, app) never imports an adapter and never calls std::fs, std::process
or std::net. crates/agentstacks/tests/isolation.rs enforces this.
types/may name onlyFileTreeandEntryKindfromcrate::port, the read-only tree port the pack, extension and project loaders take.tests/isolation.rsallows exactly those two names insidesrc/types, pluscrate::port::FakeFileTreein#[cfg(test)]code.process/may usefs::cache, the cache-directory helper, and nothing else fromfs/. It is the only edge from one adapter to another.
Dependency policy
deny.toml exempts airsl's subtree from the duplicate-version ban with skip-tree, because
airsl 0.1.5 pins sha2 0.10 and toml 0.8 while agentstacks uses sha2 0.11 and toml 1. The
exemption can go once airsl moves to those versions. Zlib is in the allowed licences, for
foldhash, which serde_json's preserve_order feature pulls in.
Where logic lives
| Layer | Holds | Example |
|---|---|---|
types/ | rules: pure decisions, data in, answer out | "the file's hash differs from the lock, so the step is refused" |
app/ | flows: the order of steps; it calls a port, hands the result to a rule, then calls the next port | read the lock, resolve sources, run the extension, decide each file's step |
port/ | abstraction: traits and fakes, no logic | Workspace::resolve(path) |
| adapters | translation: no decisions | bytes on disk, git output, Lua values ↔ Operation |
One rule, traced through the layers:
"a file changed since the last apply is refused"
types decide_locked(lock_hash, state, new) → no action, so the step is StepError::Changed:
"<path>: changed since the last apply"
pure: three values in, one answer out
app plan asks port::Workspace::resolve(path) for the disk state
flow: no rule of its own
fs StdWorkspace::resolve returns the real disk state
translation
Testing
| What | How | Needs disk, git or airsl |
|---|---|---|
every rule (types/) | unit tests on plain values | no |
every flow (app/): plan, apply order, conflicts, stale lock, doctor | unit tests with FakeWorkspace, FakeGit, FakeBinary, FakeAdapter, FakeScratch | no |
| each adapter | one contract test: does the real adapter behave like its fake? | yes, only these |
Logic is never tested only through an end-to-end run. If a rule can only be reached end to end, it is in the wrong layer.
Rust rules applied
| Rule | Applied as |
|---|---|
| one job per module, no God object | each module above has one job; app/ holds flows, never rules |
| one type per concept | Operation is defined once, in types/; host/ returns it, never a copy |
| static dispatch | ports are generic parameters (W: Workspace); the one dyn is airsl's ModuleSet::insert(Box<dyn HostModule>), which airsl's API requires |
mod.rs is export-only | every mod.rs holds only its docs and mod / pub use lines |
| naming | one-word folder and file names, no _ |
Getting Started
claudevs tests Claude Code plugins without a model in the loop. It runs a plugin's hooks and scripts
the way Claude Code would, checks that the plugin's files are wired together, and reports one pass or
fail answer. This chapter takes you from nothing to a passing claudevs check, then breaks a hook on
purpose and fixes it.
There are two ways to use claudevs. You can run the claudevs binary from a plugin's own
repository, or you can call the claudevs crate from Rust code that wants the same checks. This
chapter uses the binary. The crate is the subject of Embedding.
| Plugin author | Rust caller | |
|---|---|---|
| What you use | the claudevs binary | the claudevs crate |
| Needs | sh and git on PATH; claude for the validate stage | sh and git on PATH |
| Start with | the pages below | Embedding |
claude is optional. Only the validate stage of claudevs check hands work to it. Without it, that
one stage is skipped and the run goes on.
The pages
| Page | What you do |
|---|---|
| Installation | Install the claudevs binary |
| A First Plugin | Write a small plugin with one hook, and ask claudevs doctor what it lacks |
| A First Case | Write a case for the hook and run it |
| Running the Gate | Run claudevs check, break the hook, fix it, and test the installed copy |
The pages build on each other, so read them in order. Each one runs in the same scratch directory and adds to the plugin the one before it left.
Examples
The repository holds nine small plugins that claudevs check runs. Each has a README.md that says
what it shows and how its check ends. Two of them are worked through in
Running the Gate, and the others are linked from the chapters that use
them. The full set is in
crates/claudevs/examples/.
Installation
You need one binary, claudevs. There are three ways to get it. Pick one.
A prebuilt binary
This needs no Rust toolchain. It downloads the installer for the latest release and runs it:
curl -LsSf https://airsstack.github.io/agentstacks/claudevs.sh | sh
From crates.io
This builds the binary on your machine:
cargo install --locked claudevs-cli
From a checkout
From the root of a clone of the repository, this builds the version in the clone:
cargo install --locked --path crates/claudevs-cli
These commands reach a service or replace the claudevs already installed on your machine, so the
page shows no output for them.
Check it works
Run the binary and ask for its version:
claudevs --version
claudevs 0.1.2
Your version may differ from the one printed here.
What it needs at run time
Hooks run through sh, and cases need git on PATH. Hook commands in hooks.json start as
sh -c <command>. The default project a case runs in is a git repository that claudevs creates
with git, so that a hook which looks at project state cannot take a silent "not found" path. A
fixture is a git repository only when it carries a .gitinit file, as Scripts and
Flows explains.
claude is optional. Only the validate stage inside claudevs check delegates to it. If it is
missing, that stage is skipped and the run does not fail. Running the Gate
shows the check output both ways.
Next, write a first plugin.
A First Plugin
This page builds a small plugin with one hook, then asks claudevs doctor what the plugin and its
surroundings lack. Make an empty directory and work inside it. Every command in this chapter runs from
that directory, which is the one that holds my-marketplace.
The plugin
The plugin guards .env files. It refuses any edit to one, and asks before touching anything under
secrets/. Every other path passes without a word. It has a manifest, a hook declaration and a hook
script:
my-marketplace/
└── my-plugin/
├── .claude-plugin/plugin.json
└── hooks/
├── hooks.json
└── protect-env.sh
my-marketplace/my-plugin/.claude-plugin/plugin.json:
{
"name": "my-plugin",
"version": "0.1.0",
"description": "Guards .env files from edits",
"author": { "name": "You" }
}
my-marketplace/my-plugin/hooks/hooks.json runs the script before the Edit and Write tools:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/protect-env.sh\"" }
]
}
]
}
}
my-marketplace/my-plugin/hooks/protect-env.sh:
#!/bin/sh
# Refuses edits to .env files and asks before touching anything under secrets/.
# Every other path passes silently.
payload=$(cat)
case "$payload" in
*'"file_path":"'*'.env"'*)
echo "protect-env: refusing to edit a .env file" >&2
exit 2
;;
*'"file_path":"secrets/'*|*'/secrets/'*)
printf '%s\n' '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"protect-env: files under secrets/ need confirmation"}}'
;;
esac
exit 0
Claude Code sends the hook a JSON payload on standard input. The script reads it and looks for the
file_path field. Exit code 2 is how a PreToolUse hook says no.
Ask what is missing
claudevs doctor reports what the plugin and its environment lack:
claudevs doctor my-marketplace/my-plugin
The command exits with status 1. This is what it prints:
ok claude binary: present; `check` delegates its validate stage
ok plugin manifest: my-plugin 0.1.0
warn cases: no case files found under `my-marketplace/my-plugin/tests` (cases are `*.yaml`, `*_test.lua` or `test_*.lua` in tests/)
gap marketplace: marketplace `my-marketplace/my-plugin/../.claude-plugin/marketplace.json`: no `.claude-plugin/marketplace.json` in any ancestor directory; the installed layout is keyed by the marketplace that hosts the plugin
gap install layout: marketplace `my-marketplace/my-plugin/../.claude-plugin/marketplace.json`: no `.claude-plugin/marketplace.json` in any ancestor directory; the installed layout is keyed by the marketplace that hosts the plugin
2 gaps, 1 warning
A gap is something the environment around the plugin lacks. Here there is no marketplace above the
plugin, so there is no simulated install layout either. A gap makes the exit status 1. A warn is an
observation about the plugin's own content. Here it says no case files exist yet. A warning does not
change the exit status. Without claude on PATH, the first line is a gap too, and it names the
stage that gets skipped.
Put the plugin in a marketplace
Claude Code installs a plugin from a marketplace, and claudevs simulates that install. Give the
plugin one by adding my-marketplace/.claude-plugin/marketplace.json:
{
"name": "my-marketplace",
"owner": { "name": "You" },
"plugins": []
}
The installed layout is keyed by the name of the nearest marketplace manifest, found by walking up from the plugin. Ask again:
claudevs doctor my-marketplace/my-plugin
The command now exits with status 0:
ok claude binary: present; `check` delegates its validate stage
ok plugin manifest: my-plugin 0.1.0
warn cases: no case files found under `my-marketplace/my-plugin/tests` (cases are `*.yaml`, `*_test.lua` or `test_*.lua` in tests/)
ok marketplace: my-marketplace
ok install layout: simulated at /var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/.tmpPPmD7A/cache/my-marketplace/my-plugin/0.1.0
0 gaps, 1 warning
Both gaps are gone. The simulated install path is a temporary directory, so yours will differ. The warning stays until you write a case, which is the next page.
Next, write a first case.
A First Case
A case says what a hook should do when it receives a given event. This page writes one case for
protect-env.sh and runs it.
Write your first case
Cases live in the plugin's tests/ directory. Create
my-marketplace/my-plugin/tests/blocks-env-file.yaml:
event: PreToolUse
payload:
tool_input:
file_path: .env
expect:
decision: deny
stderr_contains: refusing to edit a .env file
event is what makes this a hook case. Its payload is laid over the default payload that
claudevs builds for PreToolUse, so the case only has to name the field it cares about. Here that
is the file the tool wants to edit.
expect is what the hook must do. decision: deny is satisfied by exit code 2 on PreToolUse.
stderr_contains checks that the hook said why on standard error.
claudevs finds YAML files under tests/ and treats each as a case. A case's name is its file stem,
so this one is named blocks-env-file.
Run it
claudevs test my-marketplace/my-plugin
The command exits with status 0:
ok blocks-env-file
1 passed, 0 failed (1 cases, 0 native suites)
claudevs started the hook the way Claude Code would, sent it the payload, and compared what came
back with expect. One case passed. "0 native suites" counts test commands that the plugin declares
for itself; this plugin has none, and Native Suites covers them.
A case can assert more than a decision. Writing Cases goes through the rest, starting with Hook Decisions.
Next, run the whole gate.
Running the Gate
claudevs test runs your cases. claudevs check runs everything that should be true before you ship
the plugin, and the case suite is one part of it. This page runs the gate, breaks the hook so a case
fails, reads the failure, and fixes it.
Run the gate
claudevs check my-marketplace/my-plugin
The command exits with status 0:
ok validate
Validating plugin manifest: /private/tmp/claudevs-demo/my-marketplace/my-plugin/.claude-plugin/plugin.json
Plugin directory checks for /private/tmp/claudevs-demo/my-marketplace/my-plugin. The plugin directory is the catalog that plugins are submitted to; this is a subset of what it runs.
✘ Found 2 problems the plugin directory refuses a submission for:
❯ README.md: README missing (README_MISSING). This plugin has no README.md. People who install it and the directory's automated review read the README to learn what it does; the first line of a README in the plugin folder also stands in as the listing summary when plugin.json has no description.
Fix: Add a README.md to the plugin folder describing what the plugin does, how to use it, and any setup it needs, in at least 40 words. A README at the repository root also counts for a plugin in a sub-folder.
❯ LICENSE: License missing (LICENSE_MISSING). This plugin has no LICENSE file and plugin.json has no `license`. The directory requires one of them.
Fix: Add a LICENSE file to the plugin folder, or set `license` (an SPDX id) in plugin.json. A LICENSE at the repository root also counts for a plugin in a sub-folder.
⚠ Found 1 plugin directory warning:
❯ .claude-plugin/plugin.json icon: No icon (ICON_MISSING). No icon found in the plugin. The validator looked for `icon` in plugin.json and for a file at .claude-plugin/icon.png or .svg, assets/icon.png or .svg, or a similar path.
Fix: Add a square PNG to the plugin folder at .claude-plugin/icon.png, or set `icon` in plugin.json to the path of a square PNG or JPEG in the plugin: 512 to 2048 px on each side, under 2 MB. SVG and WebP are not accepted. That file may become the listing icon only once: the first time the plugin is saved or submitted in the developer portal. Adding or changing it later does not change the icon.
These plugin directory checks do not change the result below. To fail on problems the directory refuses a submission for, run this command with --profile directory.
The directory also runs a safety scan and a policy review that this command does not.
✔ Validation passed
ok wiring
0 errors, 0 warnings
ok test
ok blocks-env-file
1 passed, 0 failed (1 cases, 0 native suites)
ok test --installed
ok blocks-env-file
1 passed, 0 failed (1 cases, 0 native suites)
4 stages run, 0 failed, 0 skipped
check runs four stages in order:
validatehands the manifest toclaude plugin validate. The lines under it are written byclaude, so their wording changes with the version ofclaudeyou have. Here it also lists directory submission notes. They do not change the result, and the stage ends withValidation passed.wiringchecks the plugin's files against each other, for instance that a path inhooks.jsonpoints at a file that exists.testruns the case suite, asclaudevs testdid on the last page.test --installedruns the same cases again from the simulated install layout.
Without claude on PATH, the first stage is skipped and the run still ends with status 0:
skip validate
cannot run `claude`: No such file or directory (os error 2)
ok wiring
0 errors, 0 warnings
ok test
ok blocks-env-file
1 passed, 0 failed (1 cases, 0 native suites)
ok test --installed
ok blocks-env-file
1 passed, 0 failed (1 cases, 0 native suites)
3 stages run, 0 failed, 1 skipped
Break the hook
In protect-env.sh, change exit 2 to exit 1. Then run the cases:
claudevs test my-marketplace/my-plugin
The command exits with status 1:
FAIL blocks-env-file
decision: expected Deny, got None
payload: {"cwd":"/var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/.tmpy8YU7n","hook_event_name":"PreToolUse","session_id":"claudevs-test","tool_input":{"file_path":".env"},"tool_name":"Edit"}
handler: sh "${CLAUDE_PLUGIN_ROOT}/hooks/protect-env.sh"
0 passed, 1 failed (1 cases, 0 native suites)
There are three lines to read after the case name:
- The mismatch itself: the case expected a deny and the hook produced no decision.
- The payload the hook received, with the default fields filled in. The
cwdis a temporary project directory, so yours will differ. - The handler that ran.
Exit 1 is not a PreToolUse denial as far as claudevs is concerned. Only exit 2 counts, so the
case reports no decision at all. The example
02_hook_decision_broken
works through this failure in full.
Fix it and test the installed copy
Change exit 1 back to exit 2. Then run the cases against the installed copy:
claudevs test --installed my-marketplace/my-plugin
The command exits with status 0:
ok blocks-env-file
1 passed, 0 failed (1 cases, 0 native suites)
--installed runs the same cases against a throwaway copy of the plugin, made at a path shaped like
cache/<marketplace>/<plugin>/<version>/. CLAUDE_PLUGIN_ROOT points at that copy instead of your
source directory. A hook that reads a file outside its own plugin passes test and fails only here.
The example
08_installed_broken
is a plugin that does exactly that.
You now have a plugin, a case and a passing gate. Writing Cases covers what else a case can assert, and the check gate covers what each stage does and how to run it in CI.
Writing Cases
A case is a small file that says what one part of your plugin should do. claudevs test runs every
case under the plugin's tests/ directory and reports each one as ok or FAIL. A case states what
it means, such as "this hook denies the edit", and leaves the exit codes and JSON shapes to claudevs.
These pages assume you have a plugin and have run one case, as in A First Plugin and A First Case. Each page is a set of recipes, and each recipe carries a small plugin you can type in and run.
flowchart LR
A[tests/ directory] --> B{File type}
B -->|*.yaml| C[One case per file]
B -->|*_test.lua or test_*.lua| D[Many cases per file]
E[claudevs.toml] --> F[Native suites]
C --> G[claudevs test]
D --> G
F --> G
| Page | What you write |
|---|---|
| Hook Decisions | Cases that check what a hook decides, adds or leaves unsaid |
| Scripts and Flows | Cases that run a script with an environment, or several steps in one project |
| Cases in Lua | Cases generated in a loop, and cases you script by hand |
| Native Suites | A test command your plugin already has, run next to the cases |
| Selecting Cases and Reading Skips | Running some cases, and what a skip line means |
A case file is found by its name and place. A .yaml or .yml file under tests/ is one case, named
by its file stem. A file ending in _test.lua or starting with test_ returns a table of named cases.
Anything under tests/fixtures/ is data for the cases and is never run as one.
A YAML case runs in a fresh temporary project, so one case cannot change what the next one sees. A Lua
case that calls t.script runs its program in the plugin directory unless it passes a cwd, so give it
t.project() when the program writes files. Each
recipe on these pages is also a directory under
crates/claudevs/examples
that you can run as it stands. The full list of case fields is in the claudevs CLI
reference.
Hook Decisions
A hook case sends a hook one event and a payload, then checks what the hook did. You name the event, write only the payload fields you care about, and state the result in plain words. This page asserts a decision, then context a hook adds, then a hook that stays silent.
The recipes use one small plugin, guard. It wires two hooks. protect-env.sh guards file edits and
deploy-reminder.sh adds a reminder to deploy prompts:
guard/
├── .claude-plugin/plugin.json
├── hooks/
│ ├── hooks.json
│ ├── protect-env.sh
│ └── deploy-reminder.sh
└── tests/
hooks/hooks.json connects each event to its script:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/protect-env.sh\"" }
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{ "type": "command", "command": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/deploy-reminder.sh\"" }
]
}
]
}
}
The manifest is an ordinary plugin.json, as in A First Plugin. Run
claudevs test from the guard directory after each recipe.
Assert a hook's decision
hooks/protect-env.sh refuses an edit to a .env file by exiting with code 2. It asks for
confirmation before touching anything under secrets/ by printing a JSON decision, and it stays
silent for every other path:
#!/bin/sh
# Refuses edits to .env files and asks before touching anything under secrets/.
payload=$(cat)
case "$payload" in
*'"file_path":"'*'.env"'*)
echo "protect-env: refusing to edit a .env file" >&2
exit 2
;;
*'"file_path":"secrets/'*)
printf '%s\n' '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"protect-env: files under secrets/ need confirmation"}}'
;;
esac
exit 0
tests/blocks-env-file.yaml sends an edit to .env and expects a denial:
event: PreToolUse
payload:
tool_input:
file_path: .env
expect:
decision: deny
stderr_contains: refusing to edit a .env file
tests/asks-for-secrets.yaml expects the hook to ask instead:
event: PreToolUse
payload:
tool_input:
file_path: secrets/api-key.txt
expect:
decision: ask
Run them:
$ claudevs test
ok asks-for-secrets
ok blocks-env-file
2 passed, 0 failed (2 cases, 0 native suites)
The payload you write is laid over a default payload for the event, so each case names only the
fields it changes. The default for PreToolUse carries the tool name Edit and a file inside the
temporary project. That is why neither case sets tool_name.
A decision is allow, deny, ask or defer. The two hooks reach their decisions in different
ways, one by exit code and one by JSON, and both cases read the same. On PreToolUse, exit code 2
alone reads as deny. A JSON envelope on stdout can also carry a decision, in any of three shapes:
hookSpecificOutput.permissionDecision, hookSpecificOutput.decision.behavior, or a top-level
decision field spelled "block". You write decision: deny in each case and the hook keeps the
freedom to choose its spelling.
When a case fails, claudevs lists every mismatch, the payload it sent and the handler it ran. The
fix is in the hook or in the case, whichever is wrong. See the
example
for a plugin that passes these cases, and its
broken twin
for one that does not.
Assert context a hook adds
A hook can add context to the conversation. hooks/deploy-reminder.sh does it when a prompt mentions
a deploy, by printing a JSON envelope with additionalContext:
#!/bin/sh
# Adds a reminder when the prompt mentions a deploy; says nothing otherwise.
payload=$(cat)
case "$payload" in
*deploy*)
printf '%s\n' '{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"deploy-reminder: production deploys need a change ticket"}}'
;;
esac
exit 0
tests/deploy-prompt-gets-reminder.yaml sets the prompt and checks the context:
event: UserPromptSubmit
payload:
prompt: deploy the api to production
expect:
context_contains: change ticket
$ claudevs test
ok asks-for-secrets
ok blocks-env-file
ok deploy-prompt-gets-reminder
3 passed, 0 failed (3 cases, 0 native suites)
context_contains matches a substring of the injected context. Context comes from
hookSpecificOutput.additionalContext in a JSON envelope. On SessionStart and UserPromptSubmit
only, a hook's plain stdout with no envelope also counts. A PreToolUse hook that prints plain text
adds no context, so a context_contains case against it fails.
The session context
example
adds a SessionStart hook that prints a banner as plain text, with a case for it.
Assert a hook stays silent
Most prompts should pass without a word from the hook. expect: output: none checks that. This is
tests/ordinary-prompt-stays-silent.yaml:
event: UserPromptSubmit
expect:
output: none
It sets no payload, so the prompt is the default one, hello, which does not mention a deploy.
$ claudevs test
ok asks-for-secrets
ok blocks-env-file
ok deploy-prompt-gets-reminder
ok ordinary-prompt-stays-silent
4 passed, 0 failed (4 cases, 0 native suites)
The case fails if the hook returns a decision or any context. Plain stdout counts as context only on
SessionStart and UserPromptSubmit, and other output, such as text on stderr, does not count at all.
How a hook run is read lists what does. The
expectation is accepted only on a hook case. A script or flow case that sets it is refused before it
runs, because only a hook run records whether anything was emitted.
Two more fields are rarely needed. A case field named hook picks one handler by a substring of its
command when several handlers match the same event. payload_raw replaces the generated stdin with a
literal string, for a hook that has to survive input that is not JSON. The
claudevs CLI reference lists both.
Next, Scripts and Flows tests what is not a hook.
Scripts and Flows
Not everything a plugin does is a hook. A skill often tells Claude to run a script, and a script runs in a project with files, a git repository and an environment. Two kinds of case cover that. A script case runs one command. A flow case runs several commands in order, in one shared project.
The recipes use a plugin called notes with two scripts:
notes/
├── .claude-plugin/plugin.json
├── scripts/
│ ├── greet.sh
│ └── new-note.sh
└── tests/
scripts/greet.sh prints a greeting for whoever GREETING_NAME names, and stops with a message when
the variable is missing:
#!/bin/sh
# Greets whoever GREETING_NAME names.
printf 'hello, %s\n' "${GREETING_NAME:?GREETING_NAME is required}"
scripts/new-note.sh creates notes/<slug>.md in the current git repository, and refuses to run
anywhere else:
#!/bin/sh
# Creates notes/<slug>.md in the current git repository.
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || {
echo "new-note: not inside a git repository" >&2
exit 1
}
title="$1"
slug=$(printf '%s' "$title" | tr ' ' '-')
mkdir -p notes
printf '# %s\n' "$title" > "notes/$slug.md"
echo "created notes/$slug.md"
The scripts need git on your PATH, because new-note.sh calls it and the flow below starts a git
repository.
Test a script with its environment
A script case has an invocation instead of an event. tests/greets-by-name.yaml runs greet.sh
with one environment variable set:
invocation:
argv: [sh, -c, 'sh "$CLAUDE_PLUGIN_ROOT/scripts/greet.sh"']
env:
GREETING_NAME: claudevs
expect:
exit: 0
stdout_contains: hello, claudevs
$ claudevs test
ok greets-by-name
1 passed, 0 failed (1 cases, 0 native suites)
argv is the program and its arguments. It is spawned directly, with no shell, so $CLAUDE_PLUGIN_ROOT
in a bare argument stays as typed. This case starts sh -c itself so that the variable is expanded. The
child runs in the case's temporary project, and its environment holds your own environment plus
CLAUDE_PLUGIN_ROOT (the plugin directory), CLAUDE_PROJECT_DIR (the temporary project) and every
env entry the case sets.
{project} in any argv or env value is replaced with the path of the temporary project before the
child starts. Use it when a script takes the project as an argument.
A script case can assert exit, stdout_contains, stderr_contains and files_exist. It cannot
assert output: none. That check is for hooks, and a script or flow case that sets it fails to load.
The message says the expectation is a hook assertion.
The example adds a skill that documents both scripts.
Test a multi-step flow in a project
A flow case has steps. tests/new-note-flow.yaml creates a note, then adds a second one from a
fixture, then lists the result:
project: notes-repo
steps:
- run:
argv: [sh, -c, 'sh "$CLAUDE_PLUGIN_ROOT/scripts/new-note.sh" "first note"']
expect:
exit: 0
stdout_contains: created notes/first-note.md
- apply_fixture: imported-notes
- run:
argv: [ls, notes]
expect:
exit: 0
stdout_contains: imported.md
files_exist:
- notes/first-note.md
- notes/imported.md
The case needs two fixture directories under tests/fixtures/. A fixture is a directory that is copied
into the project:
tests/fixtures/
├── notes-repo/
│ ├── .gitinit
│ └── README.md
└── imported-notes/
└── notes/
└── imported.md
.gitinit is an empty marker file. It makes claudevs run git init in the copy and make one commit,
and the marker itself is not copied. README.md contains # Notes repository, and imported.md
contains # Imported note. Anything under tests/fixtures/ is data and is never read as a case.
$ claudevs test
ok greets-by-name
ok new-note-flow
2 passed, 0 failed (2 cases, 0 native suites)
project: notes-repo seeds one project, and every step shares it. A run step can carry its own
expect, and that expectation must hold for the flow to continue. When one fails, the flow stops there
and later steps do not run. apply_fixture copies another fixture directory over the same project
without running anything. The top-level expect is judged against the last run step, and its
files_exist paths are relative to the project.
Without a project: field, a case runs in a default project: a git repository with a minimal
Cargo.toml and one committed file, file.txt.
Cases in Lua
A YAML case is one fixed case. When you need ten similar cases, or a case that makes a decision part way through, write it in Lua. A Lua case file returns a table, and each entry in it is a case. An entry that is a plain table is a data case with the same fields a YAML case has. An entry that is a function is a scripted case that drives the harness by hand.
The recipes use a plugin called pushguard. It blocks force pushes with a PreToolUse hook on Bash:
pushguard/
├── .claude-plugin/plugin.json
├── hooks/
│ ├── hooks.json
│ └── block-force-push.sh
└── tests/
hooks/hooks.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/block-force-push.sh\"" }
]
}
]
}
}
hooks/block-force-push.sh:
#!/bin/sh
# Blocks force pushes; every other Bash command passes silently.
payload=$(cat)
case "$payload" in
*'git push'*'--force'*|*'git push'*' -f'*)
echo "block-force-push: force pushes are not allowed" >&2
exit 2
;;
esac
exit 0
Generate cases in Lua
A force push has two spellings, --force and -f. tests/force_push_test.lua builds one case for
each from a table, in a loop:
local cases = {}
for name, command in pairs({
long_flag = "git push --force origin main",
short_flag = "git push -f origin main",
}) do
cases["blocks_force_push_" .. name] = {
event = "PreToolUse",
payload = { tool_name = "Bash", tool_input = { command = command } },
expect = { decision = "deny", stderr_contains = "force pushes are not allowed" },
}
end
return cases
$ claudevs test
ok blocks_force_push_long_flag
ok blocks_force_push_short_flag
2 passed, 0 failed (2 cases, 0 native suites)
A file is a Lua case file when its name ends in _test.lua or starts with test_. The key of each
entry is the case name, and a case name uses only A-Z, a-z, 0-9, ., _ and -. A new
spelling to cover is one more line in the table.
Script a case with t
Some checks do not fit a fixed expect. An entry whose value is a function is a scripted case. It
receives t, a handle onto the harness, and passes by returning. A failed assert fails the case, the
same way a mismatched expect fails a data case.
Add this above return cases in the same file. It runs the hook on a plain push and checks that the
hook returned no decision and no context:
cases.plain_push_emits_nothing = function(t)
local reply = t.hook("PreToolUse", {
tool_name = "Bash",
tool_input = { command = "git push origin main" },
})
assert(reply.exit == 0, "expected exit 0, got " .. tostring(reply.exit))
assert(not reply.emitted, "a plain push should emit nothing")
end
$ claudevs test
ok blocks_force_push_long_flag
ok blocks_force_push_short_flag
ok plain_push_emits_nothing
3 passed, 0 failed (3 cases, 0 native suites)
t.hook(ref, payload) runs a hook and returns its exit, stdout and stderr, along with
decision and context when the run carried them, and emitted, which is true when the hook returned a decision or context. Text on stderr alone leaves
it false. ref is an event name, or a substring of one handler's command. The other functions on t
are t.script, t.skill_command, t.json, t.project, t.fixture and t.apply_fixture. The
claudevs CLI reference describes each, and the
example
uses t.skill_command, t.script and t.json to check that a skill's command prints the version in
the plugin manifest.
The Lua itself runs confined, with no access to files or processes. The functions on t run outside
that confinement, though, and t.script can start any program. Treat a case file as code you run, in
the same way you treat a shell script from the same author.
Convert a YAML case to Lua
You can turn a YAML case into its Lua form. Say tests/allows-plain-push.yaml already exists:
event: PreToolUse
payload:
tool_name: Bash
tool_input:
command: git push origin main
expect:
exit: 0
output: none
claudevs migrate prints the Lua form to stdout and changes nothing:
$ claudevs migrate tests/allows-plain-push.yaml
return {
["allows-plain-push"] = {
event = "PreToolUse",
expect = {
exit = 0,
output = "none",
},
payload = {
tool_input = {
command = "git push origin main",
},
tool_name = "Bash",
},
},
}
With --write, it writes the file next to the YAML one and deletes the YAML file:
$ claudevs migrate --write tests/allows-plain-push.yaml
tests/allows-plain-push.yaml -> tests/allows_plain_push_test.lua
The new file is named <stem>_test.lua, with every - in the stem replaced by _. The case keeps its
original name, because the name is the table key, so the report does not change:
$ claudevs test
ok allows-plain-push
ok blocks_force_push_long_flag
ok blocks_force_push_short_flag
ok plain_push_emits_nothing
4 passed, 0 failed (4 cases, 0 native suites)
Native Suites
A plugin may already have its own test command, such as a script that checks shell syntax or a Lua test runner. You do not have to port it to cases. A native suite tells claudevs to run that command alongside the cases and fail the run when the command fails.
The recipe uses a plugin called banner. A SessionStart hook prints a one-line banner, and a script
checks that every hook script parses:
banner/
├── .claude-plugin/plugin.json
├── claudevs.toml
├── hooks/
│ ├── hooks.json
│ └── session-banner.sh
└── tests/
├── native/
│ └── syntax-check.sh
└── session-banner.yaml
Run the plugin's own test command
hooks/hooks.json wires the banner hook:
{
"hooks": {
"SessionStart": [
{ "hooks": [ { "type": "command", "command": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/session-banner.sh\"" } ] }
]
}
}
hooks/session-banner.sh:
#!/bin/sh
echo "session-banner: native suite example"
tests/native/syntax-check.sh is the plugin's own test command. It parses each hook script with
sh -n, which reads a script without running it:
#!/bin/sh
# Parses every hook script without running it.
status=0
for script in hooks/*.sh; do
if sh -n "$script"; then
echo "ok $script"
else
status=1
fi
done
exit $status
claudevs.toml sits at the plugin root and declares the command:
[[native]]
run = "sh tests/native/syntax-check.sh"
A native suite sits beside at least one case. claudevs test looks for case files first, and with none
it stops with exit code 2 before it runs any native suite:
$ claudevs test
claudevs: no case files found under `/private/tmp/claudevs-cases/banner/tests` (cases are `*.yaml`, `*_test.lua` or `test_*.lua` in tests/)
The directory in that message is wherever your plugin is. tests/native/syntax-check.sh is not a case,
because only *.yaml, *.yml, *_test.lua and test_*.lua files are. So add one small case,
tests/session-banner.yaml:
event: SessionStart
expect:
context_contains: native suite
$ claudevs test
ok session-banner
ok native: sh tests/native/syntax-check.sh (exit 0)
1 passed, 0 failed (1 cases, 1 native suites)
claudevs runs each [[native]] entry's run string with sh -c, from the plugin directory. That is
why hooks/*.sh in the script finds the hooks without a path. Only the exit code is asserted, 0 for a
pass. The command's output is hidden while it passes. run is the only key an entry accepts, and any
other key stops the run with exit code 2 and a message that names it. Add more [[native]] tables to
run more commands.
See a native suite fail
When the command exits with anything but 0, the run fails and the command's output is shown under its
line. Add a broken line to the end of hooks/session-banner.sh:
#!/bin/sh
echo "session-banner: native suite example"
if [ then
$ claudevs test
ok session-banner
FAIL native: sh tests/native/syntax-check.sh (exit 1)
hooks/session-banner.sh: line 4: syntax error: unexpected end of file
1 passed, 1 failed (1 cases, 1 native suites)
The wording of the syntax error comes from your shell, so it can differ from this one. The exit code of
claudevs test is 1. Remove the broken line to return to the passing run.
The native suite example runs this plugin as it stands.
Selecting Cases and Reading Skips
Two small things finish the chapter. You can run part of a suite while you work on one case, and you
can read a skip line in a report, which is not a failure and is not a pass either.
Run only some cases
--case keeps a case only when its name contains the given text. In the guard plugin from Hook
Decisions, which has four cases:
$ claudevs test --case blocks
ok blocks-env-file
1 passed, 0 failed (1 cases, 0 native suites)
The match is a plain substring, not a pattern, and it applies to the case name: the file stem for a YAML case, the table key for a Lua case. Text that matches nothing is not an error:
$ claudevs test --case nothing-has-this-name
0 passed, 0 failed (0 cases, 0 native suites)
The exit code is 0, so a misspelt filter looks like a green run. Read the count before you trust it.
--case filters cases and leaves native suites alone. In the banner
plugin, a filter that matches no case still runs the suite:
$ claudevs test --case nothing-has-this-name
ok native: sh tests/native/syntax-check.sh (exit 0)
0 passed, 0 failed (0 cases, 1 native suites)
The first example has three cases to try the filter on.
Read a skip
claudevs check runs four stages, and a stage reports ok, FAIL or skip. A skip means the stage
could not run on this machine, and the reason follows on the next line. Here is a plugin called bare
that has a manifest and nothing else, checked on a machine where claude is not on the PATH. The
command puts only /usr/bin and /bin on the PATH for this one run:
$ PATH=/usr/bin:/bin "$(command -v claudevs)" check
skip validate
cannot run `claude`: No such file or directory (os error 2)
ok wiring
0 errors, 0 warnings
skip test
no case files found under `/private/tmp/claudevs-cases/bare/tests` (cases are `*.yaml`, `*_test.lua` or `test_*.lua` in tests/)
skip test --installed
marketplace `./../.claude-plugin/marketplace.json`: no `.claude-plugin/marketplace.json` in any ancestor directory; the installed layout is keyed by the marketplace that hosts the plugin
1 stage run, 0 failed, 3 skipped
The exit code is 0. A skip never fails check. Each of the three skips names something the machine
lacks, and each has one fix:
| Skip | What is missing | The fix |
|---|---|---|
validate says cannot run claude | the claude binary on PATH | put claude on PATH |
test says no case files found | a case under tests/ | write a case, as in A First Case |
test --installed says no .claude-plugin/marketplace.json in any ancestor directory | a marketplace above the plugin | put the plugin in a marketplace, as in A First Plugin |
With a case, a marketplace above the plugin and claude installed, the same plugin runs all four
stages. A skip says nothing about whether your plugin works. A stage that skipped checked nothing, so a
run that ends in 0 failed, 3 skipped has tested far less than one that ends in 0 failed, 0 skipped.
Only check turns these gaps into skips. claudevs test with no case files ends with exit code 2, and
so does claudevs test --installed with no marketplace above the plugin. Running one stage by hand
means you asked for it, so a missing piece is an error.
The examples README
shows which results hold with and without claude.
A skip is an environment gap
claudevs reports a skip when the cause is the machine and not the plugin: no case files yet, no
marketplace above the plugin to key an install path by, no claude to validate with. None of those is a
fault in the plugin, so none of them fails the stage.
A malformed plugin.json is treated differently, on purpose. It would be easy to skip a stage that
cannot read the manifest it needs. But a plugin whose manifest cannot be read has a real defect, and
skipping it would let that plugin pass on any machine where claude is also missing and validate has
already skipped. So a plugin inside a marketplace, with a plugin.json that is not valid JSON, fails
test --installed even when claude is missing and validate has skipped.
An environment gap and a plugin defect can look alike from the outside. claudevs tells them apart by asking whether the cause is the machine or the manifest.
A temporary directory that claudevs cannot create is a problem with the machine too, but check does
not turn it into a skip. When a case needs a project, the run ends with exit code 2 and a message that
names the directory.
A failed stage does not stop the ones after it, so a FAIL and a skip can sit in the same report.
Stages covers the errors that do stop the run.
The check Gate
claudevs check is the command that answers one question about a plugin: is it sound? It runs four
stages in order and reports how each one went. A plugin is sound when none of them fails.
| Stage | What it looks at |
|---|---|
validate | The manifest and the plugin's skills, agents and commands, through claude plugin validate. |
wiring | Static checks over the plugin's files: paths that must exist, scripts nothing uses, and the matchers in hooks.json. |
test | Your cases, run against the plugin where it sits in your checkout. |
test --installed | The same cases, run against a copy laid out the way Claude Code installs a plugin. |
Here is a plugin that passes all four. Run it from the repository root:
$ claudevs check --json crates/claudevs/examples/01_hook_decision | jq -c '.stages[] | {name, status}'
{"name":"validate","status":"passed"}
{"name":"wiring","status":"passed"}
{"name":"test","status":"passed"}
{"name":"test --installed","status":"passed"}
--json asks for a report a program can read. The jq line keeps each stage's name and verdict. The
human report is the default; Stages shows one.
This chapter has three pages.
- Stages explains why a failed stage does not stop the run, what the installed layout catches that
your checkout hides, and what happens when
claudeis not on the machine. - Wiring explains what the static checks look for, and why a matcher claudevs cannot evaluate is a warning and not an error.
- Running in CI reads the JSON report and uses the exit code as the gate.
The cases that test runs are the subject of Writing Cases.
Stages
By the end of this page you will know why check never stops at the first failure, what the second
run of your cases is for, and what check does on a machine without claude.
A failed stage does not stop the run
A failed stage does not stop the ones after it. check runs validation, wiring, your cases, and your
cases again from the installed layout, then reports all four.
An error is different from a failure. When claudevs cannot judge the plugin at all, check stops with
one message and exit code 2 and prints no report. A hooks/hooks.json that is not valid JSON while a
hook case runs does this, and so does a case that names a fixture that does not exist. The exit
codes list the rest.
flowchart LR
A[validate] --> B[wiring] --> C[test] --> D["test --installed"] --> E[report]
The 07_wiring_broken
example shows why that matters. Its hooks.json points at a script that does not exist, so wiring
fails. No case exercises that hook, so both runs of the cases still pass.
$ claudevs check --json crates/claudevs/examples/07_wiring_broken | jq -c '.stages[] | {name, status}'
{"name":"validate","status":"passed"}
{"name":"wiring","status":"failed"}
{"name":"test","status":"passed"}
{"name":"test --installed","status":"passed"}
Stopping at the first failure would have hidden that the rest of the plugin is fine. It would just as easily hide a second, unrelated failure in a later stage. One run shows you every problem.
Each stage ends in one of three states: passed, failed or skipped. A skip names something the
machine lacks, such as claude or a case file. It never fails the run.
What the installed layout catches
Claude Code installs a plugin at cache/<marketplace>/<plugin>/<version>/, a path with nothing beside
it but the plugin's own files. test runs your cases against the plugin where it already sits in
your checkout, which can have other things nearby. test --installed copies only the plugin into the
installed shape and runs the same cases again, with CLAUDE_PLUGIN_ROOT pointing at the copy.
The two runs catch different defects because they start from different neighborhoods. A hook that
reaches for a file one directory above its plugin root works in a checkout, where that directory
exists. It breaks once only the plugin is copied into place.
08_installed_broken
is exactly that hook.
$ claudevs check --json crates/claudevs/examples/08_installed_broken > report.json
$ jq -c '.stages[] | {name, status}' report.json
{"name":"validate","status":"passed"}
{"name":"wiring","status":"passed"}
{"name":"test","status":"passed"}
{"name":"test --installed","status":"failed"}
$ jq -r '.stages[] | select(.name == "test --installed") | .detail' report.json
FAIL blocks-rm-rf
stderr: expected to contain `blocked-by-policy`, got "cat: /private/var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/.tmp3YuMpF/cache/claudevs-examples/installed-broken/0.1.0/../shared/policy-message.txt: No such file or directory\n\n"
payload: {"cwd":"/var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/.tmpplvq6y","hook_event_name":"PreToolUse","session_id":"claudevs-test","tool_input":{"command":"rm -rf build","file_path":"/var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/.tmpplvq6y/file.txt"},"tool_name":"Bash"}
handler: sh "${CLAUDE_PLUGIN_ROOT}/hooks/block-rm-rf.sh"
0 passed, 1 failed (1 cases, 0 native suites)
The temporary directory names change on every run, and your paths will differ. The failure itself is
the same: the hook reads ../shared/policy-message.txt, and the copy has no shared/ next to it.
wiring does not catch this. It reads references written as ${CLAUDE_PLUGIN_ROOT}/…, with braces,
and this script writes the variable without them. Keep the file inside the plugin and both runs pass.
Why validation is handed to claude
claudevs delegates manifest validation to claude plugin validate and does not reimplement it.
Anything the claude binary already checks is one less thing claudevs has to keep in sync with a
runtime it does not control.
Delegating also lets the stage degrade gracefully. When claude is not on the machine, validate is
skipped with a reason, and check still runs its own stages. Hide claude from PATH to see it:
$ env PATH=/usr/bin:/bin "$(command -v claudevs)" check crates/claudevs/examples/01_hook_decision
skip validate
cannot run `claude`: No such file or directory (os error 2)
ok wiring
0 errors, 0 warnings
ok test
ok allows-other-files
ok asks-for-secrets
ok blocks-env-file
3 passed, 0 failed (3 cases, 0 native suites)
ok test --installed
ok allows-other-files
ok asks-for-secrets
ok blocks-env-file
3 passed, 0 failed (3 cases, 0 native suites)
3 stages run, 0 failed, 1 skipped
This is the human report. Each stage is marked ok, FAIL or skip, and the last line counts the
stages that ran. A skipped stage is not counted as run.
How strict the delegate is stays a separate choice from whether it runs. By default it is lenient, so
a warning such as a missing author does not hold back the stages that would catch a real defect.
Running in CI shows how to turn those warnings into
failures.
Wiring
By the end of this page you will know what the wiring stage looks at, which findings fail it, and
why a matcher claudevs cannot evaluate is a warning.
What the stage checks
wiring reads your plugin's files and runs nothing. It has three checkers, and each reports
findings.
| Checker | Severity | It reports |
|---|---|---|
refs | error | A ${CLAUDE_PLUGIN_ROOT}/… reference to a file that does not exist, or one that climbs out of the plugin root. |
invocations | warning | A script in the plugin that nothing else mentions. |
matchers | error or warning | A hooks.json that is not JSON, or has no hooks object, is an error. An unknown event name, a matcher on an event that takes none, and a matcher claudevs cannot evaluate are warnings. |
Only an error fails the stage. A warning is printed and the stage still passes. The refs checker
reads the braced form ${CLAUDE_PLUGIN_ROOT}. It does not read $CLAUDE_PLUGIN_ROOT without braces.
Here is refs failing on
07_wiring_broken,
whose PostToolUse hook runs format-on-write.sh while the script in hooks/ is format.sh:
$ claudevs check --json crates/claudevs/examples/07_wiring_broken | jq -r '.stages[] | select(.name == "wiring") | .detail'
error refs hooks/hooks.json:9 `${CLAUDE_PLUGIN_ROOT}/hooks/format-on-write.sh` does not exist
1 error, 0 warnings
Each finding is one line: severity, checker, file with a line number when there is one, then the message. The last line counts errors and warnings.
Why a matcher claudevs cannot evaluate is a warning
A matcher value in hooks.json is not a Rust regular expression, even where it looks like one. The
hooks reference defines two modes. A value made only of letters, digits, _, -, spaces, , and |
is an exact string, or a list of exact strings separated by | or ,. Any other character makes the
whole value a regular expression, matched anywhere in the name. claudevs judges a matcher's shape
against those modes and does not compile every value with Rust's regex engine.
FileChanged and StopFailure use a narrower exact set: letters, digits, _ and |. A hyphen,
space or comma in one of their matchers puts it in the regular-expression mode.
Once a value falls into the pattern mode, claudevs does compile it, because that is how it matches
the value when it runs your cases. Rust's regex engine and the one the runtime uses do not accept
exactly the same syntax. Rust has no look-around and no backreferences, so a pattern that works in
Claude Code can fail to compile here.
When that happens, claudevs cannot tell whether the runtime accepts the pattern. It reports a
warning that names the divergence, and never an error against the plugin. An error would punish the
plugin for a gap in claudevs and not for a defect in the plugin.
To see it, copy the 01_hook_decision example to a scratch directory and change the matcher in the
copy's hooks/hooks.json from Edit|Write to (?!Read)(Edit|Write):
$ cp -R crates/claudevs/examples/01_hook_decision /tmp/lookahead-demo
$ claudevs check --json /tmp/lookahead-demo > report.json
$ jq -r '.stages[] | select(.name == "wiring") | .detail' report.json
warn matchers hooks/hooks.json claudevs cannot evaluate matcher `(?!Read)(Edit|Write)` (regex parse error:
(?!Read)(Edit|Write)
^^^
error: look-around, including look-ahead and look-behind, is not supported), so it cannot tell whether the runtime accepts it
0 errors, 1 warning
wiring passes. The warning does not change what the matcher means in Claude Code, but it changes
what claudevs can do with it. A value it cannot evaluate matches nothing, so no case reaches that
hook, and test fails:
$ jq -c '.stages[] | {name, status}' report.json
{"name":"validate","status":"passed"}
{"name":"wiring","status":"passed"}
{"name":"test","status":"failed"}
{"name":"test --installed","status":"skipped"}
test --installed is skipped because the copy in /tmp has no marketplace manifest above it to key
the installed layout by. The warning tells you the failing cases are about the matcher, not about your
hook script. To keep the hook under test, write the matcher so Rust can compile it.
Running in CI
By the end of this page you will have a short script that fails a CI job when claudevs check
fails, names the stage that failed, and optionally treats manifest warnings as failures.
Use JSON in CI
--json replaces the human report with a JSON document on stdout. Its one top-level key is stages,
an array with one entry per stage. Each entry has a name, a status and a detail.
$ claudevs check --json crates/claudevs/examples/07_wiring_broken | jq '.stages[] | select(.name == "wiring")'
{
"name": "wiring",
"status": "failed",
"detail": " error refs hooks/hooks.json:9 `${CLAUDE_PLUGIN_ROOT}/hooks/format-on-write.sh` does not exist\n\n1 error, 0 warnings\n"
}
status is "passed", "failed" or "skipped". detail is the same text the human report shows
for that stage. It is a string, not a further layer of JSON.
The report carries no verdict of its own. The verdict is the exit code of claudevs check.
| Exit code | Meaning |
|---|---|
| 0 | No stage failed. A skipped stage does not count against the run. |
| 1 | At least one stage failed. |
| 2 | claudevs could not run the check, for example because the path is not a directory. |
$ claudevs check --json no-such-dir; echo "exit $?"
claudevs: walk plugin `no-such-dir`: No such file or directory (os error 2)
exit 2
The exit code is easy to lose. In a pipeline, the shell reports the last command's status, and that
is jq's:
$ claudevs check --json crates/claudevs/examples/07_wiring_broken | jq -r '.stages[] | select(.status == "failed") | .name'; echo "exit $?"
wiring
exit 0
claudevs exited 1 there and the pipeline still reported 0. Either run the shell with
set -o pipefail so a failing command anywhere in the pipeline fails it, or keep the report in a file
and carry the exit code yourself. This is the second way, saved as ci-gate.sh:
claudevs check --json crates/claudevs/examples/07_wiring_broken > report.json
status=$?
jq -r '.stages[] | select(.status == "failed") | .name' report.json
exit "$status"
$ bash ci-gate.sh; echo "exit $?"
wiring
exit 1
The script prints the name of every failed stage and exits with claudevs's own code. In your own
job, point it at your plugin instead of the example.
Fail on manifest warnings
By default the validate stage is lenient. A warning from claude plugin validate, such as a
manifest with no author, is shown and the stage still passes. Pass --strict to make the same
warning fail the stage, for callers who want warnings to gate a release.
To see the difference, copy the 01_hook_decision example to a scratch directory and delete the
author line from the copy's .claude-plugin/plugin.json. Remove the comma after the line above it
too, so the file is still valid JSON.
$ cp -R crates/claudevs/examples/01_hook_decision /tmp/no-author
$ claudevs check --json /tmp/no-author > report.json; echo "exit $?"
exit 0
$ jq -c '.stages[] | {name, status}' report.json
{"name":"validate","status":"passed"}
{"name":"wiring","status":"passed"}
{"name":"test","status":"passed"}
{"name":"test --installed","status":"skipped"}
The same plugin with --strict:
$ claudevs check --strict --json /tmp/no-author > report.json; echo "exit $?"
exit 1
$ jq -c '.stages[] | {name, status}' report.json
{"name":"validate","status":"failed"}
{"name":"wiring","status":"passed"}
{"name":"test","status":"passed"}
{"name":"test --installed","status":"skipped"}
$ jq -r '.stages[0].detail | rtrimstr("\n") | split("\n") | last' report.json
✘ Validation failed (--strict treats warnings as errors)
--strict changes only the validate stage. The other three stages report the same as before.
test --installed is skipped in both runs because the copy in /tmp has no marketplace manifest
above it. The flag also changes nothing when claude is not on PATH, because the stage is skipped
before it could be strict.
Skips are also covered in Selecting Cases and Reading Skips. The whole command line is in the claudevs CLI reference.
Embedding
The claudevs command line is a thin shell over a Rust library. You can depend on that library and
run a plugin's cases from your own program. You get the same report, verdicts and exit codes the
binary produces, as typed values you can inspect.
Use it when you want to wrap the harness in your own tool, or assert on plugin behavior from a Rust
test. If you only want to run cases from a terminal or CI, the claudevs binary
is enough.
| Page | What you do |
|---|---|
| Your First Suite | Run a plugin's suite, read the report and turn it into an exit code |
| Recipes | Produce JSON, filter cases, run check and doctor, drive one case at a time |
Every snippet in this chapter runs offline. None of them reaches a service or spends usage. The engine's full API is in its rustdoc:
cargo doc -p claudevs --no-deps --open
To see how the engine's parts relate, read How the Engine Fits Together.
Your First Suite
This page runs the cases of an example plugin from a Rust program. You print the report, read each verdict, and turn the result into a process exit code.
Before you start
The harness starts hooks through sh -c and creates a case's default project with git. Both
must be on your PATH.
Add the crate to your project:
[dependencies]
claudevs = "0.1"
The snippets use two plugins from the repository, examples/01_hook_decision and
examples/02_hook_decision_broken. Their paths are relative to the claudevs crate directory, and
the snippets start there. The
examples README
says what each example plugin shows.
Run the suite
run_suite finds the case files under the plugin's tests/ directory, runs every case and every
native suite, and returns a SuiteReport. An Err means claudevs itself could not run. A failing
case is part of the report, not an error.
#![allow(unused)] fn main() { std::env::set_current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../claudevs")).unwrap(); use std::path::Path; let plugin = Path::new("examples/01_hook_decision"); let report = claudevs::run_suite(plugin, &claudevs::SuiteOptions::default())?; print!("{}", claudevs::render_human(&report)); assert!(report.all_green()); assert_eq!(claudevs::exit_code(&report), 0); Ok::<(), claudevs::Error>(()) }
Read what it printed
render_human writes one line per case and a summary line. Running the block above prints this:
ok allows-other-files
ok asks-for-secrets
ok blocks-env-file
3 passed, 0 failed (3 cases, 0 native suites)
Look at each verdict
Each CaseOutcome carries a name and a Verdict. A Verdict is Pass, or Fail with the list of
Mismatches. Verdict is #[non_exhaustive], so a match over it needs a wildcard arm. How the
Engine Fits Together explains why.
This plugin has a defect, so its cases fail:
#![allow(unused)] fn main() { std::env::set_current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../claudevs")).unwrap(); use std::path::Path; use claudevs::Verdict; let plugin = Path::new("examples/02_hook_decision_broken"); let report = claudevs::run_suite(plugin, &claudevs::SuiteOptions::default())?; for outcome in &report.outcomes { match &outcome.verdict { Verdict::Pass => println!("pass {}", outcome.name), Verdict::Fail(mismatches) => { println!("fail {} ({} mismatch)", outcome.name, mismatches.len()); } _ => println!("? {}", outcome.name), } } assert_eq!(claudevs::exit_code(&report), 1); Ok::<(), claudevs::Error>(()) }
It prints:
pass allows-other-files
pass asks-for-secrets
fail blocks-env-file (1 mismatch)
Turn it into an exit code
exit_code returns 0 when every case passed and every native suite exited 0. Otherwise it returns 1.
The value 2 is reserved for "claudevs could not run". No report ever produces it. Your program maps
an Err from run_suite to 2 itself, the way the claudevs binary does.
The next page covers the rest of the engine's surface.
Recipes
These recipes are for a caller who has worked through Your First Suite.
Every path below is relative to the claudevs crate directory and names a plugin under examples/.
Each snippet starts in that directory.
Produce a JSON report
render_json accepts a SuiteReport, a CheckReport, a WiringReport or a Diagnosis, and
nothing else. It produces the same JSON the claudevs binary prints with --json. The shape is in
the CLI reference.
#![allow(unused)] fn main() { std::env::set_current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../claudevs")).unwrap(); use std::path::Path; let report = claudevs::run_suite( Path::new("examples/01_hook_decision"), &claudevs::SuiteOptions::default(), )?; let json = claudevs::render_json(&report)?; assert!(json.contains("\"outcomes\"")); Ok::<(), claudevs::Error>(()) }
Run only some cases
SuiteOptions is #[non_exhaustive], so build it with default() and set case_filter. A case
runs when its name contains the filter. A YAML file is matched by its file stem before it is loaded,
and a Lua file's cases are matched by their entry name.
#![allow(unused)] fn main() { std::env::set_current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../claudevs")).unwrap(); use std::path::Path; let mut options = claudevs::SuiteOptions::default(); options.case_filter = Some(String::from("blocks")); let report = claudevs::run_suite(Path::new("examples/01_hook_decision"), &options)?; assert_eq!(report.outcomes.len(), 1); Ok::<(), claudevs::Error>(()) }
Run against the installed layout
run_suite_installed copies the plugin to cache/<marketplace>/<plugin>/<version>/ in a temporary
directory. It runs the same cases with CLAUDE_PLUGIN_ROOT pointing there. It returns
Error::Marketplace when no ancestor directory holds a .claude-plugin/marketplace.json.
The
08_installed_broken example
is a plugin that passes one call and fails the other.
#![allow(unused)] fn main() { std::env::set_current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../claudevs")).unwrap(); use std::path::Path; let plugin = Path::new("examples/08_installed_broken"); let options = claudevs::SuiteOptions::default(); assert!(claudevs::run_suite(plugin, &options)?.all_green()); assert!(!claudevs::run_suite_installed(plugin, &options)?.all_green()); Ok::<(), claudevs::Error>(()) }
Run check from code
claudevs::check::run(plugin_dir, strictness) runs validate, wiring, test and
test --installed, in that order, and always reports all four. Err comes back only when claudevs
itself cannot run. A failing plugin is still Ok.
A suite stage is Skipped when there are no case files, no marketplace, or an installed layout that
cannot be built. It is Failed for an unreadable plugin.json. Strictness::Strict fails
validate on the delegate's warnings as well as its errors.
Each Stage's detail is the human-rendered text of that stage. render_check_human and
check_exit_code turn the whole report into the same text and exit code the binary uses.
#![allow(unused)] fn main() { std::env::set_current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../claudevs")).unwrap(); use std::path::Path; use claudevs::{StageStatus, Strictness}; let report = claudevs::check::run(Path::new("examples/07_wiring_broken"), Strictness::Lenient)?; for stage in &report.stages { println!("{:<18} {:?}", stage.name, stage.status); } assert!( report .stages .iter() .any(|stage| stage.name == "wiring" && stage.status == StageStatus::Failed) ); assert_eq!(claudevs::check_exit_code(&report), 1); Ok::<(), claudevs::Error>(()) }
Diagnose the environment
claudevs::doctor::run returns a Diagnosis directly, not a Result. Its probes run in this
order: claude binary, plugin manifest, cases, marketplace, install layout.
A probe is Ok, Warning or Gap. Only cases can be a Warning. all_clear is false only when
a probe is a Gap. A missing claude binary is itself a Gap, so code that runs where claude
may be absent should not require all_clear to diagnose anything useful.
#![allow(unused)] fn main() { std::env::set_current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../claudevs")).unwrap(); use std::path::Path; use claudevs::ProbeStatus; let diagnosis = claudevs::doctor::run(Path::new("examples/01_hook_decision")); print!("{}", claudevs::render_doctor_human(&diagnosis)); let marketplace = diagnosis.probes.iter().find(|probe| probe.name == "marketplace"); assert_eq!(marketplace.map(|probe| probe.status), Some(ProbeStatus::Ok)); }
Run the wiring checkers alone
claudevs::wiring::run runs refs, invocations and matchers, in that order. It returns
Error::Io when the path is not a directory.
Each checker is also public on its own: wiring::refs::check, wiring::invocations::check and
wiring::matchers::check. Each returns Result<Vec<Finding>>. A Finding carries severity,
checker, file, line and message. counts() returns (errors, warnings), and all_clear()
is false only when at least one finding is an error.
#![allow(unused)] fn main() { std::env::set_current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../claudevs")).unwrap(); use std::path::Path; use claudevs::Severity; let report = claudevs::wiring::run(Path::new("examples/07_wiring_broken"))?; for finding in &report.findings { if finding.severity == Severity::Error { println!("{} {}: {}", finding.checker, finding.file, finding.message); } } assert!(!report.all_clear()); assert_eq!(report.counts(), (1, 0)); Ok::<(), claudevs::Error>(()) }
Load and run one YAML case
case::discover returns the plugin's case files, sorted, as CaseFile::Yaml or CaseFile::Lua.
case::load_yaml_case names the case after the file stem. run_case(plugin_dir, fixtures_root, case)
runs exactly one case.
Pass an absolute plugin directory. run_suite canonicalizes its path before the children it spawns
run inside their temporary project, and run_case uses whatever path it is given for
CLAUDE_PLUGIN_ROOT.
#![allow(unused)] fn main() { std::env::set_current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../claudevs")).unwrap(); use claudevs::case::CaseFile; let plugin = std::fs::canonicalize("examples/01_hook_decision")?; let fixtures = plugin.join("tests/fixtures"); for file in claudevs::case::discover(&plugin)? { if let CaseFile::Yaml(path) = file { let case = claudevs::case::load_yaml_case(&path)?; let outcome = claudevs::run_case(&plugin, &fixtures, &case)?; assert!(matches!(outcome.verdict, claudevs::Verdict::Pass), "{}", outcome.name); } } Ok::<(), Box<dyn std::error::Error>>(()) }
Run one Lua case file
case::run_lua_file runs a Lua file's data cases and its scripted cases together.
case::load_lua_file with case::plain_engine() also loads data cases. But the engine
plain_engine builds has no t handle. Only run_lua_file installs one, for callers that need
scripted cases too.
#![allow(unused)] fn main() { std::env::set_current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../claudevs")).unwrap(); let plugin = std::fs::canonicalize("examples/05_lua_cases")?; let outcomes = claudevs::case::run_lua_file( &plugin, &plugin.join("tests/fixtures"), &plugin.join("tests/force_push_test.lua"), &claudevs::SuiteOptions::default(), )?; let names: Vec<&str> = outcomes.iter().map(|outcome| outcome.name.as_str()).collect(); assert!(names.contains(&"plain_push_emits_nothing")); Ok::<(), Box<dyn std::error::Error>>(()) }
Convert a YAML case to Lua
case::migrate_to_lua loads the YAML case first and returns Error::CaseLoad for one that does not
load. It then produces a return { [<stem>] = { … } } literal.
#![allow(unused)] fn main() { std::env::set_current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../claudevs")).unwrap(); use std::path::Path; let lua = claudevs::case::migrate_to_lua(Path::new( "examples/05_lua_cases/tests/allows-plain-push.yaml", ))?; assert!(lua.starts_with("return {")); assert!(lua.contains("[\"allows-plain-push\"]")); Ok::<(), claudevs::Error>(()) }
Under the Hood
The earlier chapters show how to use claudevs. This one explains why it behaves the way it does. You do not need any of it to write a case or to run the gate. It helps when a verdict surprises you, when you wonder why a hook event is missing from the list a case accepts, or when you embed the engine in your own Rust program and want to know how the parts fit.
| Page | What it explains |
|---|---|
| Why It Works This Way | Where claudevs sits next to claude plugin validate, why a case states a meaning instead of an exit code, and why cases cover fewer events than hooks.json may use |
| How the Engine Fits Together | The two crates, every module the engine exports, the path from a plugin directory to a report, and the rules a Rust caller should know |
The pages describe the design. For the exact flags, exit codes and report shapes, see Appendix A. To call the engine from your own program, start at Embedding.
Why It Works This Way
This page explains three design choices that shape what a claudevs verdict means. To use claudevs, start at Getting Started.
What sits between validate and a live session
claude plugin validate checks "a plugin or marketplace manifest, or the skills, agents, and commands
in a directory". That is the tool's own description, from claude plugin validate --help. It does not
run a hook.
claude plugin eval sits further along. Its help describes it as running eval cases against a plugin
and reporting scored results.
claudevs sits between the two. It spawns a plugin's hooks and scripts the way Claude Code would, but against fixed payloads in throwaway projects instead of a live session. The throwaway project is there so the same case gives the same verdict on every run. A live session carries state, and that state would make today's answer depend on what happened yesterday.
flowchart LR
V["claude plugin validate<br/>checks the manifest, skills,<br/>agents and commands,<br/>runs no hook"]
C["claudevs<br/>spawns hooks and scripts<br/>with fixed payloads<br/>in throwaway projects"]
E["claude plugin eval<br/>runs eval cases<br/>and scores the results"]
V --> C --> E
Cases assert meaning, not mechanics
A case can say decision: deny instead of "exit 2" or "print blocked on stderr". claudevs owns the
step from an observed run to that meaning. The expect block is where a case states what it means.
The harness reads each observed run back into the same vocabulary and compares the two.
event: PreToolUse
payload:
tool_input:
file_path: .env
expect:
decision: deny
This case passes against any hook that denies edits to a .env file. A PreToolUse hook that exits 2 denies it. So
does a hook that prints a JSON envelope carrying permissionDecision: "deny". The case does not choose
a mechanism. The hook does, and claudevs reads whichever one it picked.
That is also why a hook can change how it says no without breaking its cases. Moving from an exit code to an envelope changes the mechanism and leaves the meaning where it was.
Appendix A lists the shapes claudevs reads.
Why cases cover fewer events than hooks.json may use
Two lists answer two different questions about a hook event.
One catalogues every event Claude Code documents. It is the full set a plugin may legitimately wire in
hooks.json, and the wiring checks read it.
The other lists only the events claudevs can build a payload for and read a hook's response to. A case
can use only these five: PreToolUse, PostToolUse, UserPromptSubmit, SessionStart and
SessionEnd.
The second list is narrower, so a plugin may wire an event that claudevs cannot run a case against. The
gap is not a defect in either list. A documented event and a runnable event are not always the same
event. A checker that reads hooks.json has to consult the wider catalogue, and a case has to work
within the narrower one.
For a plugin author the effect is simple. A wiring check can accept an event that no case can exercise, because claudevs cannot run it.
How the Engine Fits Together
This page explains how the parts of claudevs relate. It is written for a Rust caller of the engine. To call the engine, start at Embedding. For why the harness judges meaning rather than mechanics, see Why It Works This Way.
Two crates
claudevs-cli builds the claudevs binary. It is the only one of the two crates that depends on
clap. Its command-line grammar and dispatch live in one file, and nothing else parses arguments.
claudevs is the engine that binary calls. Everything the binary does, from running a suite to
rendering a report, is a call into a public function this crate exports.
Module map
Nine of the engine's modules are public. The private ones carry the pieces below, and you reach them through the crate root's re-exports.
| Module | Visibility | What it offers you |
|---|---|---|
case | public | The case model (Case, CaseKind, Expectations, Step, Invocation) and the ways to get one: discover finds case files, load_yaml_case and load_lua_file read them, run_lua_file runs a Lua file, and migrate_to_lua converts a YAML case. |
check | public | run, the one gate a plugin passes or fails. It returns a CheckReport made of Stage values. |
contract | public | What Claude Code specifies about plugin hooks: the event catalogue (catalogue, lookup), how a matcher value is evaluated (MatcherRule), the hooks.json handler (HookCommand) and which plugin files Claude Code loads. |
doctor | public | run, which reports what this environment can and cannot do as a Diagnosis of Probe values. |
harness | public | The execution harness. It builds default payloads, spawns hooks and scripts the way the runtime would (run, run_shell, run_handler), reads a run (observe) and judges it (judge, Verdict, Mismatch). |
layout | public | Installed::materialize, which copies a plugin into the shape it has once installed, and read_manifest for its plugin.json. |
types | public | Validating newtypes for domain values: CaseName, MarketplaceName, PluginName, PluginVersion, plus HookEvent. |
validate | public | run, which hands a plugin to claude plugin validate and returns a Validation. |
wiring | public | run, the static wiring checks. It returns one WiringReport. The three checkers are public submodules: refs, invocations and matchers. |
error | private | The crate's Error and Result. |
native | private | Native suites a plugin declares outside the case model, in claudevs.toml. |
report | private | Rendering a report for people and for machines, and the exit codes. |
suite | private | Running a plugin's suite: discovery, per-case execution, report data. |
The crate root re-exports what you need from the private modules, so you never name their paths:
- from
check:CheckReport,StageandStageStatus - from
doctor:Diagnosis,ProbeandProbeStatus - from
error:ErrorandResult - from
harness:MismatchandVerdict - from
native:NativeOutcome - from
report:Report,check_exit_code,doctor_exit_code,exit_code,render_check_human,render_doctor_human,render_human,render_jsonandrender_wiring_human - from
suite:CaseOutcome,SuiteOptions,SuiteReport,run_case,run_suiteandrun_suite_installed - from
validate:StrictnessandValidation - from
wiring:Finding,SeverityandWiringReport
From a plugin directory to a report
A plugin directory goes in. Each stage turns it into a report. The check gate runs four of them, and
doctor runs one probe for each thing those stages need.
flowchart TD
dir["plugin directory"]
subgraph cases["case suite"]
direction TD
discover["case::discover"] --> load["load YAML or Lua"]
load --> Case
Case --> spawn["harness: spawn"]
spawn --> observe
observe --> judge
judge --> Verdict
Verdict --> suite
end
dir --> discover
suite --> SuiteReport
dir --> wiringrun["wiring::run"] --> WiringReport
dir --> validaterun["validate::run"] --> Validation
dir --> installed["layout::Installed"] --> again["suite again"] --> InstalledReport["SuiteReport"]
SuiteReport --> checkrun["check::run"]
WiringReport --> checkrun
Validation --> checkrun
InstalledReport --> checkrun
checkrun --> CheckReport
dir -.-> doctorrun["doctor::run<br/>one probe per thing<br/>those stages need"]
doctorrun --> Diagnosis
CheckReport --> render["report module<br/>render functions and exit codes"]
Diagnosis --> render
SuiteReport --> render
WiringReport --> render
The report module turns any of these results into human text, JSON or an exit code.
The binary wraps each entry point in one subcommand:
flowchart LR
test["claudevs test<br/>[--installed]"] --> runsuite["run_suite or<br/>run_suite_installed"]
runsuite --> r1["render_human or<br/>render_json"] --> e1["exit_code"]
check["claudevs check"] --> checkrun["check::run"]
checkrun --> r2["render_check_human or<br/>render_json"] --> e2["check_exit_code"]
doctor["claudevs doctor"] --> doctorrun["doctor::run"]
doctorrun --> r3["render_doctor_human or<br/>render_json"] --> e3["doctor_exit_code"]
migrate["claudevs migrate"] --> tolua["case::migrate_to_lua"]
tolua --> out["stdout, or<br/>stem_test.lua with --write"]
One type means a test case
YAML files and Lua data tables both deserialize into RawCase and become a Case through
Case::from_raw. Nothing else in the crate models a case. A case is one of three kinds: hook, script
or flow.
Expectations state meaning, such as decision: deny. The harness owns the translation from a run into
that meaning. A case never asserts an exit code where a decision is what it means.
The harness spawns, observes, then judges
A hook command without args runs through sh -c. A hook command with args is spawned directly. A
script's argv is always spawned directly. Every spawn carries a 30-second timeout, and a killed child
is never a pass.
observe reads a run under its event's rules. judge compares that observation with the case's
expectations and lists every mismatch rather than stopping at the first. A YAML case runs in a
temporary project. A Lua case that calls t.script runs in the plugin directory unless it passes a cwd.
A failing plugin is a verdict, not an error
Error means claudevs itself could not produce a verdict. A case file that does not load is one
example. A fixture that a case names but that is not there is another. The rustdoc lists the full set.
A plugin that fails its own cases is not an Error. It is a Verdict with mismatches in it.
Wiring reads files and never runs them
The three wiring checkers answer static questions about a plugin's files without spawning anything the plugin ships. They ask whether a reference resolves, whether a script is named by anything, and whether a matcher is one claudevs can evaluate.
validate and layout reach outside the plugin
validate hands the plugin to claude plugin validate instead of repeating the manifest checks that
command already makes. It reports Unavailable when claude cannot run at all.
layout builds the installed copy that the second suite stage runs its cases against.
check and doctor compose the rest
check runs the four stages a plugin's gate needs. doctor runs one probe per thing those stages
need, so a gap it reports is exactly what would make a stage skip or fail.
Reports are data first
Human text and JSON both come from the same report structs. The sealed Report trait limits
render_json to the crate's own report types rather than any Serialize value. The set of report
types can grow, so do not depend on how many there are.
Two lists of hook events
types::HookEvent lists the events a case can run against. contract::event catalogues the events
Claude Code documents, which the wiring checkers read. The two are separate on purpose. A documented
event claudevs cannot simulate is still one a plugin may legitimately wire. Why It Works This
Way explains the reasoning.
What #[non_exhaustive] means for a caller
Every public type carries #[non_exhaustive] except these:
- the validated newtypes in
types:CaseName,MarketplaceName,PluginNameandPluginVersion - the error structs of those newtypes
InvalidHookEventcase::Invocationharness::TModule
Name them rather than counting them.
A caller cannot build such a struct with a literal. Start from Default where one exists and set the
fields from there:
#![allow(unused)] fn main() { let mut options = claudevs::SuiteOptions::default(); options.case_filter = Some(String::from("blocks")); assert_eq!(options.case_filter.as_deref(), Some("blocks")); }
A match on such an enum needs a wildcard arm. A variant the crate adds later must not become a
compile error at every call site:
#![allow(unused)] fn main() { use claudevs::StageStatus; fn mark(status: StageStatus) -> &'static str { match status { StageStatus::Passed => "ok", StageStatus::Failed => "FAIL", StageStatus::Skipped => "skip", _ => "?", } } assert_eq!(mark(StageStatus::Skipped), "skip"); }
Appendix
The appendix holds the claudevs command-line reference.
A. claudevs CLI Reference
This appendix lists every claudevs command, flag, exit code, case field and report shape. For a
walk through the same material, start at Getting Started. For
the reasoning behind it, see Under the Hood.
Commands
Command-line interface for claudevs, the Claude Code plugin lifecycle tool
Usage: claudevs <COMMAND>
Commands:
test Run a plugin's case suite plus its declared native suites
migrate Convert a YAML case to its data-Lua form
check Validate, check wiring, then run the suite in both layouts
doctor Report what this environment can and cannot do
help Print this message or the help of the given subcommand(s)
Options:
-h, --help Print help
-V, --version Print version
test
Run a plugin's case suite plus its declared native suites.
Run a plugin's case suite plus its declared native suites
Usage: claudevs test [OPTIONS] [PATH]
Arguments:
[PATH] The plugin directory [default: .]
Options:
--case <CASE> Only run cases whose name contains this substring
--installed Run against a throwaway copy in the installed cache layout
--json Emit the machine-readable report instead of the human one
-h, --help Print help
The human report ends with a summary line of the form N passed, N failed (N cases, N native suites).
A declared native suite counts toward the passed and failed totals. --case with a substring that
matches no case runs no case, but every declared native suite still runs, so the exit code is 0 only if
they all pass.
check
Validate, check wiring, then run the suite in both layouts.
Validate, check wiring, then run the suite in both layouts
Usage: claudevs check [OPTIONS] [PATH]
Arguments:
[PATH] The plugin directory [default: .]
Options:
--strict Fail on the delegate's warnings as well as its errors
--json Emit the machine-readable report instead of the human one
-h, --help Print help
doctor
Report what this environment can and cannot do.
Report what this environment can and cannot do
Usage: claudevs doctor [OPTIONS] [PATH]
Arguments:
[PATH] The plugin directory [default: .]
Options:
--json Emit the machine-readable report instead of the human one
-h, --help Print help
migrate
Convert a YAML case to its data-Lua form.
Convert a YAML case to its data-Lua form
Usage: claudevs migrate [OPTIONS] <FILE>
Arguments:
<FILE> The YAML case file
Options:
--write Replace the .yaml file with the .lua file instead of printing
-h, --help Print help
Without --write, migrate prints the Lua to stdout. With --write, it writes <stem>_test.lua
beside the YAML file, removes the YAML file, and prints <stem>.yaml -> <stem>_test.lua.
Exit codes
| Command | 0 | 1 | 2 |
|---|---|---|---|
test | Every case passed and every declared native suite exited 0. | At least one case failed, or a native suite exited non-zero. A YAML case file that cannot be loaded counts here: it is reported as one failed case and the run goes on. | claudevs itself could not run: a usage error, a plugin path that does not resolve, no case files under tests/, a Lua case file that does not load, does not return a table or holds an invalid case name, a hooks/hooks.json that is missing or not valid JSON when a hook case needs it, a claudevs.toml entry with an unknown key, a declared native suite that could not be started, or a temporary project that could not be created. |
check | No stage failed. A skipped stage does not count against it. | At least one stage failed. | The plugin path is not a directory, or some other error that a stage does not turn into a skip or a failure, such as a hooks/hooks.json that is not valid JSON while a hook case runs, or a temporary directory that cannot be created. |
doctor | No probe reports a gap. | A probe reports a gap. A warning alone never produces this. | Only when --json cannot render the report, which the report types claudevs emits never cause in practice. |
migrate | The case was printed, or written with --write. | None. | The file is not a loadable YAML case, or writing or removing a file failed. |
Case discovery
Case files are found under <plugin>/tests/, walked recursively in sorted order. A .yaml or .yml
file is one case, named by its file stem. A file named *_test.lua or test_*.lua returns a table of
named cases. Anything under tests/fixtures/ is fixture data, never a case. Finding no case files at
all is an error, not a green suite.
A case name is the file stem for YAML and the table key for Lua. It must be non-empty and use only
A-Z, a-z, 0-9, ., _ and -.
Case fields
Common to every case:
| Field | Meaning |
|---|---|
project | The fixture to materialize as the temporary project, instead of the default project. Write a bare name or fixture: <name>. |
expect | Judged after the run for a hook or script case, or after the last step for a flow case. |
Kind-specific fields. A case is exactly one of hook, script or flow:
| Kind | Field | Meaning |
|---|---|---|
| Hook | event | One of PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd. |
| Hook | hook | An optional substring that picks which hooks.json handler this case targets, when more than one survives matcher filtering. |
| Hook | payload | An object overlaid on the event's built-in default payload. Objects merge recursively field by field. Any other value replaces its counterpart outright. |
| Hook | payload_raw | Raw stdin text sent verbatim instead of a JSON payload, for hostile-input cases. It excludes payload. |
| Script | invocation.argv | The program and arguments to spawn. |
| Script | invocation.env | Extra environment variables for the child. |
| Flow | steps | A sequence of steps run in one shared project. |
A flow step is exactly one of run (an invocation) or apply_fixture (a fixture name to overlay into
the shared project). It may also carry an expect, which applies only to a run step. A step whose
expectation fails stops the flow right there.
The case's top-level expect is judged against the last run step's observation. A flow made only of
apply_fixture steps has nothing to judge but files_exist. Any other expectation on such a flow
fails rather than passing without checking anything.
{project} in invocation.argv and invocation.env is replaced with the temporary project's path at
run time.
expect fields:
| Field | Meaning |
|---|---|
exit | The exact exit code expected. |
decision | One of allow, deny, ask, defer. |
output | Accepts only "none": the hook must return no decision and no context, as How a hook run is read defines them. Any other output, such as text on stderr or a systemMessage envelope on PreToolUse, does not count. It is a hook-only assertion. Asserting it on a script or flow case is rejected when the case loads, because only a hook observation records whether anything was emitted. |
context_contains | A substring the injected context must contain. |
stdout_contains | A substring stdout must contain. |
stderr_contains | A substring stderr must contain. |
files_exist | Paths, relative to the temporary project, that must exist once the run finishes. |
Every expectation on a case is checked, and a failing case lists every mismatch rather than stopping
at the first. Unknown fields are rejected, in cases, invocations, flow steps and expect blocks alike.
Case load errors
A YAML case that fails to load is reported as a failed case with one of these messages. A Lua case file that fails to load stops the run with exit 2 and the same message. Flow step numbers start at 0.
a case is exactly one of hook (`event:`), script (`invocation:`) or flow (`steps:`); found N
`payload` and `payload_raw` are mutually exclusive
flow step N: exactly one of `run` or `apply_fixture`
`expect.output` only accepts "none", got `VALUE`
`expect.output` is a hook assertion: only a hook observation records whether anything was emitted, so this expectation could never fail here
unknown hook event `NAME` (known: PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd)
invalid case name `NAME`: names are non-empty [A-Za-z0-9._-]
An unrecognized field name reports the field together with every field the case shape accepts. For
example, a misspelled expect gives unknown field `expct`, expected one of `event`, `hook`, `payload`, `payload_raw`, `invocation`, `steps`, `project`, `expect` .
Default payloads
The built-in default payload for PreToolUse, and for PostToolUse with its own event name, has this
shape:
{
"session_id": "claudevs-test",
"cwd": "{project}",
"hook_event_name": "PreToolUse",
"tool_name": "Edit",
"tool_input": { "file_path": "{project}/file.txt" }
}
UserPromptSubmit adds "prompt": "hello". SessionStart adds "source": "startup". SessionEnd
adds "reason": "exit". The last three carry no tool_name or tool_input.
A case's payload overlay merges onto this default. Objects merge recursively and other values
replace. Before the payload is sent, {project} in any string, default or overlay alike, is replaced
with the temporary project's actual path.
How a hook run is read
A hook's stdout may carry a JSON envelope that communicates a decision in one of three shapes. They are read most-specific first. The hooks reference states no precedence between them, so this order is claudevs' own choice.
hookSpecificOutput.permissionDecision, which isallow,deny,askordefer.hookSpecificOutput.decision.behavior, which isallowordeny.- A top-level
decisionstring. It spells denial"block"rather than"deny", and claudevs reads"block"as a denial.
Whichever of these is present, the hook counts as having emitted something, whether or not its value is one claudevs reads as a decision.
Separately from any envelope, a PreToolUse hook that exits 2 is read as a denial.
hookSpecificOutput.additionalContext carries injected context. It is read independently of which
decision shape, if any, came with it.
When there is no envelope at all, bare stdout is read as injected context only for the events whose
bare output Claude Code actually surfaces. Of the five events claudevs can simulate, those are
SessionStart and UserPromptSubmit. The bare stdout of a PreToolUse, PostToolUse or
SessionEnd hook is not context.
What a spawned command gets
The child's working directory is the case's temporary project. Its environment is the process's own
environment plus CLAUDE_PLUGIN_ROOT (the plugin directory) and CLAUDE_PROJECT_DIR (the temporary
project). A script invocation's own env entries are layered on top.
A hooks.json handler uses one of two execution models. A command alone is a shell handler, run
through sh -c, so its string may use pipelines, redirection and expansion. A command paired with
args is an exec handler, spawned directly with no shell at all. Each args element is one argument
exactly as written, with no tokenization on any platform.
Every spawned child has a 30-second timeout. A child still running past it is killed, and the case fails with this message:
timeout: the child timed out and was killed before completing
Projects and fixtures
Without a project: field, a case runs against the default project. It is a git repository with a
minimal Cargo.toml, one tracked and committed file named file.txt, and one commit. The default
PreToolUse and PostToolUse payload points its tool_input.file_path at that file.
project: <name>, or project: { fixture: <name> }, copies tests/fixtures/<name>/ into a fresh
temporary directory instead. A .gitinit file inside the fixture triggers a git init plus one
commit once the copy is made. The commit is always empty: the fixture's files are copied in but never
added, so they stay untracked. The marker file is never copied into the project.
A flow's apply_fixture step, and the Lua t.apply_fixture, copies a fixture over a project that
already exists instead of starting a fresh one.
Lua cases
A *_test.lua file returns a table. Each entry is either a data case or a scripted case. A data case
is a table, parsed the same way a YAML case is. A scripted case is a function. It runs when claudevs
calls it with the harness handle t, and it passes by returning without raising an error.
t offers these functions:
| Function | Returns |
|---|---|
t.fixture(name) | The path of a fresh temporary project seeded from the named fixture alone, without the default project's files. |
t.project() | The path of a fresh temporary copy of the default project. |
t.apply_fixture(name, dir) | Overlays the named fixture into dir. |
t.hook(ref, payload?) | Runs a hook and returns {exit, stdout, stderr, decision?, context?, emitted}. ref is either an event name or a substring of a handler's command that is unique across every event's wiring. |
t.script(argv, opts?) | Runs argv directly and returns {exit, stdout, stderr}. opts.env adds environment, opts.cwd sets the working directory (the plugin directory by default), and opts.stdin feeds stdin. |
t.skill_command(skill, n) | The text of the n-th fenced command in skills/<skill>/SKILL.md. n starts at 1 and follows document order. |
t.json(path) | The decoded contents of a JSON file. |
A relative path given to t.json is read from the directory you started claudevs in, not from the
plugin directory. To read a file inside the plugin, build an absolute path from CLAUDE_PLUGIN_ROOT.
t.json's path and t.script's cwd must resolve inside the plugin directory or a temporary project
the case itself created. t.apply_fixture's dir must resolve inside a temporary project only, never
the plugin directory. t.skill_command's resolved path must stay inside the plugin directory.
Only the Lua itself runs confined with no grants. It cannot reach the sandboxed filesystem or process
modules directly. The t handle is not part of that sandbox. Every function on it runs on the host,
and t.script can spawn any program with the ambient environment. A *_test.lua file is trusted code,
on the same footing as a shell script you run locally.
claudevs.toml
A plugin may declare native suites that claudevs delegates to instead of running itself:
[[native]]
run = "airsl test --policy confined ."
Each run is spawned as sh -c in the plugin directory. Only the exit code is asserted. The combined
stdout and stderr are captured. The human report shows them only when the exit code is non-zero. The
--json report carries them for every suite. With no claudevs.toml there are no native suites at
all. An entry with any key other than run is an error, and the run exits 2.
check stages
check runs four stages in order. A failure in one does not stop the ones that follow.
| Stage | What it runs | Skipped when | Fails when |
|---|---|---|---|
validate | claude plugin validate [--strict] <path>, delegated to the installed claude binary. | The claude binary cannot run. | The delegate exits non-zero. |
wiring | The three wiring checkers below. | Never. | Any checker reports an error-severity finding. |
test | The case suite, in the source checkout. | No case files exist. | A case or declared native suite fails. |
test --installed | The case suite again, against a throwaway copy in the simulated installed layout. | No case files exist, no marketplace manifest is found above the plugin, or the simulated installed layout cannot be created. | A case or declared native suite fails, or the plugin manifest cannot be read. |
Each stage is marked ok, FAIL or skip in the human output. A summary line follows, in the form
N stages run, N failed, N skipped. A skipped stage does not count toward the number run.
Wiring checkers
Three static checkers run in this order. Each produces findings and runs nothing.
| Checker | Severity | Reports | Message |
|---|---|---|---|
refs | error | Every ${CLAUDE_PLUGIN_ROOT}/… reference in .claude-plugin/*.json and under hooks/, skills/, agents/ and commands/ (outside fenced code blocks) that does not resolve to a file in the plugin, or that escapes the plugin root through a .. segment. The unbraced form $CLAUDE_PLUGIN_ROOT is not scanned. | `${CLAUDE_PLUGIN_ROOT}/PATH` does not exist or `${CLAUDE_PLUGIN_ROOT}/PATH` escapes the plugin root |
invocations | warning | A .sh, .lua, .py or .js file that presents as executable (a shebang, an executable bit, or anything under hooks/) but is named by nothing else in the plugin, by filename, by module stem, or from inside a fenced command. Case files, anything under tests/, and language index files (__init__.py, index.js, init.lua) are exempt. | `NAME` is referenced by nothing in this plugin |
matchers | error or warning | See the findings below. | See the findings below. |
The matchers checker reports these findings:
| Finding | Severity | Message |
|---|---|---|
hooks/hooks.json is not JSON | error | is not JSON: REASON |
hooks/hooks.json has no top-level hooks object | error | has no `hooks` object at the top level |
| An event name the catalogue does not document | warning | `EVENT` is not an event this version of claudevs knows about; it may be newer than the catalogue |
| A matcher on an event that takes none | warning | `EVENT` takes no matcher, so `MATCHER` is silently ignored by the runtime |
| A matcher claudevs cannot evaluate as a regular expression | warning | claudevs cannot evaluate matcher `MATCHER` (REASON), so it cannot tell whether the runtime accepts it |
The human rendering is one line per finding, followed by a summary line. A line reads
error CHECKER FILE[:LINE] MESSAGE or warn CHECKER FILE[:LINE] MESSAGE. The summary line
reads N errors, N warnings, with 1 error and 1 warning in the singular.
doctor probes
doctor runs five probes in order. Each one reuses the code of the check stage it stands for, so it
reports what the stage would find and does not guess at the environment.
| Probe | Checks | Status it can take |
|---|---|---|
claude binary | Whether the claude binary can be delegated to for the validate stage. | ok when reachable, gap when absent. |
plugin manifest | Whether <plugin>/.claude-plugin/plugin.json can be read and names a usable name and version. | ok or gap. |
cases | Whether any case files can be discovered under tests/. | ok when at least one is found. warning when none are, because a plugin with no cases yet is incomplete, not broken. |
marketplace | Whether a .claude-plugin/marketplace.json can be found by walking up from the plugin. | ok or gap. |
install layout | Whether the simulated installed-cache layout can be created. | ok or gap. |
Each probe is marked ok, warn or gap in the human output. A summary line follows, in the form
N gaps, N warnings, with 1 gap and 1 warning in the singular. A gap fails the overall
diagnosis. A warning alone never does. The JSON report spells the middle status warning.
This is a clean diagnosis, from claudevs doctor on the 01_hook_decision example:
ok claude binary: present; `check` delegates its validate stage
ok plugin manifest: hook-decision 0.1.0
ok cases: 3 case file(s) found
ok marketplace: claudevs-examples
ok install layout: simulated at /var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/.tmpysjv4P/cache/claudevs-examples/hook-decision/0.1.0
0 gaps, 0 warnings
A clean diagnosis is not a verdict on the plugin. Every probe answers whether a stage can run at all.
A plugin whose hooks.json points at a file that does not exist reports 0 gaps, 0 warnings and exits
0 here, and so does a plugin whose hook breaks only once installed. check fails both. The
09_doctor_gaps
example walks through both shades of failure and names the two examples that show the difference.
JSON reports
Every --json report shares two conventions. A case's verdict is the plain string "Pass" or the
object {"Fail": [mismatch, …]}. Each mismatch is an object tagged by a kind field in snake_case,
for example "decision", "stdout_missing" or "file_missing".
claudevs test --json reports outcomes[] of {name, verdict}. The payload and handler fields
appear only on a failing hook case. It also reports native[] of {command, exit, output} for
declared native suites. This is the report for the 02_hook_decision_broken example:
{
"outcomes": [
{
"name": "allows-other-files",
"verdict": "Pass"
},
{
"name": "asks-for-secrets",
"verdict": "Pass"
},
{
"name": "blocks-env-file",
"verdict": {
"Fail": [
{
"kind": "decision",
"expected": "deny",
"observed": null
}
]
},
"payload": {
"cwd": "/var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/.tmpGomqj2",
"hook_event_name": "PreToolUse",
"session_id": "claudevs-test",
"tool_input": {
"file_path": ".env"
},
"tool_name": "Edit"
},
"handler": "sh \"${CLAUDE_PLUGIN_ROOT}/hooks/protect-env.sh\""
}
],
"native": []
}
claudevs check --json reports stages[] of {name, status, detail}. Each status is passed,
failed or skipped. The detail carries the same text the human renderer shows for that stage. For
validate that text is whatever claude plugin validate printed, so it changes with the installed
claude. This is the report for the 07_wiring_broken example:
{
"stages": [
{
"name": "validate",
"status": "passed",
"detail": "Validating plugin manifest: /private/tmp/claudevs-ref/examples/07_wiring_broken/.claude-plugin/plugin.json\n\nPlugin directory checks for /private/tmp/claudevs-ref/examples/07_wiring_broken. The plugin directory is the catalog that plugins are submitted to; this is a subset of what it runs.\n\n✘ Found 1 problem the plugin directory refuses a submission for:\n\n ❯ LICENSE: License missing (LICENSE_MISSING). This plugin has no LICENSE file and plugin.json has no `license`. The directory requires one of them.\n Fix: Add a LICENSE file to the plugin folder, or set `license` (an SPDX id) in plugin.json. A LICENSE at the repository root also counts for a plugin in a sub-folder.\n\n⚠ Found 1 plugin directory warning:\n\n ❯ .claude-plugin/plugin.json icon: No icon (ICON_MISSING). No icon found in the plugin. The validator looked for `icon` in plugin.json and for a file at .claude-plugin/icon.png or .svg, assets/icon.png or .svg, or a similar path.\n Fix: Add a square PNG to the plugin folder at .claude-plugin/icon.png, or set `icon` in plugin.json to the path of a square PNG or JPEG in the plugin: 512 to 2048 px on each side, under 2 MB. SVG and WebP are not accepted. That file may become the listing icon only once: the first time the plugin is saved or submitted in the developer portal. Adding or changing it later does not change the icon.\n\nThese plugin directory checks do not change the result below. To fail on problems the directory refuses a submission for, run this command with --profile directory.\n\nThe directory also runs a safety scan and a policy review that this command does not.\n\nℹ Advice (does not change the verdict):\n\n ❯ /private/tmp/claudevs-ref/examples/07_wiring_broken/README.md: This README has no line that installs \"wiring-broken\" from a marketplace. Add the install line, which works in one step on Claude Code 2.1.275 or later. Validate the folder that holds its marketplace.json to have <owner>/<repo> filled in, and the name its marketplace lists it under.\n /plugin install wiring-broken --marketplace <owner>/<repo>\n\n✔ Validation passed\n"
},
{
"name": "wiring",
"status": "failed",
"detail": " error refs hooks/hooks.json:9 `${CLAUDE_PLUGIN_ROOT}/hooks/format-on-write.sh` does not exist\n\n1 error, 0 warnings\n"
},
{
"name": "test",
"status": "passed",
"detail": " ok session-banner\n\n1 passed, 0 failed (1 cases, 0 native suites)\n"
},
{
"name": "test --installed",
"status": "passed",
"detail": " ok session-banner\n\n1 passed, 0 failed (1 cases, 0 native suites)\n"
}
]
}
claudevs doctor --json reports probes[] of {name, status, detail}. Each status is ok,
warning or gap:
{
"probes": [
{
"name": "claude binary",
"status": "ok",
"detail": "present; `check` delegates its validate stage"
},
{
"name": "plugin manifest",
"status": "ok",
"detail": "hook-decision 0.1.0"
},
{
"name": "cases",
"status": "ok",
"detail": "3 case file(s) found"
},
{
"name": "marketplace",
"status": "ok",
"detail": "claudevs-examples"
},
{
"name": "install layout",
"status": "ok",
"detail": "simulated at /var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/.tmp7lzeOL/cache/claudevs-examples/hook-decision/0.1.0"
}
]
}