- name
- agent-spec-tool-first
- description
- CRITICAL: Use for agent-spec CLI tool workflow. Triggers on:
agent-spec, contract, lifecycle, guard, verify, explain, stamp, checkpoint, plan,
requirements, work-units, knowledge requirements, KLL, docs vs knowledge,
spec verification, task contract, spec quality, lint spec, run log,
"how to verify", "how to use agent-spec", "spec failed", "guard failed",
contract review, contract acceptance, PR review, code review workflow,
plan context, codebase scan, task sketch, implementation plan,
合约, 验证, 生命周期, 守卫, 规格检查, 质量门禁, 合约审查, 计划,
"验证失败", "怎么用 agent-spec", "spec 不通过", "工作流"
# Agent Spec Tool-First Workflow
> **Version:** 3.7.1 | **Last Updated:** 2026-08-14 | **Tracks:** agent-spec 1.4.0
You are an expert at using `agent-spec` as a CLI tool for contract-driven AI coding. Help users by:
- **Planning**: Render task contracts with `contract`, generate plan context with `plan`
- **Implementing**: Follow contract Intent, Decisions, Boundaries
- **Verifying**: Run `lifecycle` / `guard` to check code against specs
- **Reviewing**: Use `explain` for human-readable summaries, `stamp` for git trailers
- **Debugging**: Interpret verification failures and fix code accordingly
## IMPORTANT: CLI Prerequisite Check
**Before running any `agent-spec` command, Claude MUST check:**
```bash
command -v agent-spec || cargo install agent-spec
```
If `agent-spec` is not installed, inform the user:
> `agent-spec` CLI not found. Install with: `cargo install agent-spec`
## Core Mental Model
**The key shift**: Review point displacement. Human attention moves from "reading code diffs" to "writing contracts".
```
Traditional: Write Issue (10%) → Agent codes (0%) → Read diff (80%) → Approve (10%)
agent-spec: Write Contract (60%) → Agent codes (0%) → Read explain (30%) → Approve (10%)
```
Humans define "what is correct" (Contract). Machines verify "is the code correct" (lifecycle). Humans do final "Contract Acceptance" — not Code Review.
## Quick Reference
| Command | Purpose | When to Use |
|---------|---------|-------------|
| `agent-spec init` | Scaffold new spec | Starting a new task |
| `agent-spec contract <spec>` | Render Task Contract | Before coding - read the execution plan |
| `agent-spec lint <files>` | Spec quality check | After writing spec, before giving to Agent |
| `agent-spec plan <spec> --code .` | Generate plan context | Before coding - codebase scan + task sketch |
| `agent-spec lifecycle <spec> --code .` | Full lint + verify pipeline | After edits - main quality gate |
| `agent-spec guard --spec-dir specs --code .` | Repo-wide check | Pre-commit / CI - all specs at once |
| `agent-spec explain <spec> --format markdown` | PR-ready review summary | Contract Acceptance - paste into PR |
| `agent-spec explain <spec> --history` | Execution history | See how many retries the Agent needed |
| `agent-spec stamp <spec> --dry-run` | Preview git trailers | Before committing - traceability |
| `agent-spec graph --spec-dir specs` | Dependency graph (DOT) | After writing specs - visualize deps & critical path |
| `agent-spec requirements graph --gate` | Validate KLL requirements and dependency graph | After importing PRD/issue requirements |
| `agent-spec wiki status` | Check stale code live wiki articles | Session start / before broad source reading |
| `agent-spec wiki query <text>` | Search tracked live wiki articles | Before opening many source files |
| `agent-spec wiki check` | Live wiki lint + worktree status gate | Pre-commit / CI for tracked wiki |
| `agent-spec atlas build/tree/query/search/explore/context/flow/impact/affected/refs/impls/status/check/scip-gen` | Rust graph with scored retrieval, bounded context projection, explainable paths, reverse impact, identity, and independent syn/SCIP/MIR freshness; `scip-gen` invokes rust-analyzer for the optional SCIP overlay | Build before querying; use `--frozen` for review, and never infer tests from affected filenames |
| `agent-spec atlas benchmark validate/plan/summarize/score` | Validate the E0 corpus, compile paired Atlas/baseline plans, summarize fully graded receipts, or score strict E3 query observations | Evaluate correctness before performance. Default tests probe current fixtures without network access. See `docs/atlas-evaluation.md` |
| `agent-spec atlas benchmark agent-plan/agent-gate` | Compile matched Read/Grep, Atlas primitive, and B5 context arms; gate strict complete receipts | Keep all failures and query metrics. B/A and C/B are independent. Real execution is opt-in and external. See `docs/atlas-agent-ab-gate.md` |
| `agent-spec atlas benchmark serving-plan/serving-gate` | Compile and gate four-profile direct/worker burst trials | Require a pinned non-fixture repository. The disabled template and D4 fixture matrix are not promotion evidence. See `docs/atlas-agent-ab-gate.md` |
| `agent-spec atlas provider validate/conformance` | Validate an external Code Graph manifest/registration or run the F1 conformance matrix | Keep providers project-configured and opt-in. Conformance proves adapter behavior, not language quality. See `docs/code-graph-provider-kit.md` |
| `agent-spec verify <spec> --code .` | Raw verification only | When you want verify without lint gate |
| `agent-spec checkpoint status` | VCS-aware status | Check uncommitted state |
### Atlas Workflow
```bash
agent-spec atlas build --code . --graph .agent-spec/graph
agent-spec atlas search <query> --code . --graph .agent-spec/graph --limit 20
agent-spec atlas explore <query> --profile compact --code . --graph .agent-spec/graph --frozen
agent-spec atlas context <query> --profile symbol --code . --graph .agent-spec/graph --frozen
agent-spec atlas flow --from <symbol> --to <symbol> --code . --graph .agent-spec/graph --frozen
agent-spec atlas impact <symbol> --depth 3 --code . --graph .agent-spec/graph --frozen
agent-spec atlas affected --worktree --code . --graph .agent-spec/graph --frozen
agent-spec atlas status --code . --graph .agent-spec/graph --format json
agent-spec atlas check --code . --graph .agent-spec/graph
agent-spec atlas daemon start --code . --graph .agent-spec/graph
agent-spec atlas daemon status --code . --graph .agent-spec/graph
agent-spec atlas daemon service-status --code . --graph .agent-spec/graph
agent-spec atlas daemon sync --code . --graph .agent-spec/graph
agent-spec atlas daemon stop --code . --graph .agent-spec/graph
```
For E1, never infer a passing result from a checked-in plan. Run the explicit
external driver, retain every run and raw-session hash, then gate the complete
receipt. Treat machine `passed` as a candidate for human acceptance, not as an
instruction to change MCP discovery, B5 profiles, or worker defaults.
`atlas build` publishes one complete committed generation; all read surfaces
pin and report that generation. Content-addressed Cargo input plans accept
`--features`, `--target`, and repeatable `--cfg`. Incremental source edits use a
bounded reverse-dependent frontier; configure `--frontier-limit`,
`--batch-size`, and `--working-byte-limit`. A healthy zero-change build does no
resolution, validation, staging, or authority rewrite. Cancellation and build
failure preserve the old generation and orphan work for a later recovery build.
Automatic refresh reuses committed Cargo inputs; capability changes use an
explicit full-frontier fallback. The optional D3 watcher/daemon wraps these D2
build primitives, persists a
pending watermark and exposes typed `degraded` state. Writer-lock and ordinary
failures have separate bounded retries. Queries hold a reader lease until their
immutable generation read ends; ambiguous leases prevent reclamation. MCP
discovery and no-daemon queries remain deterministic. Live state never replaces
graph freshness, KLL, or lifecycle authority. See
`docs/atlas-incremental-builds.md` and `docs/atlas-live-runtime.md`.
D4 query workers are an opt-in prototype. Start the daemon with
`--query-workers 2`, inspect `daemon service-status`, and invoke
`atlas context --execution worker`. Keep direct mode for default, CI, and
single-Agent use. Preserve typed queue, deadline, memory, cancellation, panic,
circuit, fallback, generation, and lease receipts; worker mode cannot make a
stale graph fresh. See `docs/atlas-concurrent-query-serving.md`.
`status` reports recorded/current graph identity and the three layer states;
syn fresh is not authority for a stale SCIP or MIR layer. Rebuild after
`atlas-schema-mismatch` or an `atlas-query-index-*` diagnostic. A borrowed
worktree graph or stale available semantic layer cannot produce definitive
provider, binding, lifecycle-symbol, or typed trace evidence. Atlas graph
shards, the query index, and bindings are derived working data, not KLL truth.
Compact/deep `explore` budgets are fixed at 8/32/48/8/4/20/16,000 and
16/96/160/20/12/40/24,000 for seeds, nodes, edges, paths, excerpts, excerpt
lines, and bytes. Excerpts require current source hashes. Treat `flow` states
(`found`, `no-path`, `capability-unavailable`, `truncated`,
`unknown-endpoint`, `ambiguous-endpoint`) as distinct. A fresh disconnected
flow may include bounded `runtime_boundaries`; they explain async, channel,
callback, reflection, or route boundaries as heuristic query hints and never
become graph, impact, binding, lifecycle, or archive evidence. See
`docs/atlas-runtime-boundaries.md`. `affected` requires one
explicit, stdin, staged, worktree, or commit-range input and reports graph
evidence, not inferred tests.
Use `atlas context` when the Agent needs a bounded, receipt-bearing projection
rather than the legacy compact/deep explore shape. Pick one explicit
`symbol | flow | architecture | impact` profile. Inspect both
`receipt.retrieval` and `receipt.projection`; an omission is not a retrieval
miss. Follow `omissions[].continuation.argv` literally with its graph
fingerprint. Never hide required-evidence overflow, stale source, or cursor
errors. Context output is derived working data and is not a default MCP tool;
see `docs/atlas-query-context.md`.
MCP uses frozen, read-only Atlas reads. The default tool list omits
`atlas_search`; start `agent-spec mcp` with `AGENT_SPEC_MCP_ATLAS_SEARCH=1` to
list it. `atlas_explore` is unavailable unless
`AGENT_SPEC_MCP_ATLAS_EXPLORE=1`; keep the default surface until a real Agent
A/B gate passes. `atlas_context` requires `AGENT_SPEC_MCP_ATLAS_CONTEXT=1`;
its concurrent route additionally requires
`AGENT_SPEC_MCP_ATLAS_QUERY_MODE=worker`. Keep both opt-in until that gate.
For external Code Graph providers, run `atlas provider validate` before any
execution and `atlas provider conformance` before integration. Keep extractor
and semantic-enricher artifacts separate. Reject stale/partial promotion,
wrong-worktree responses, unsafe paths, unscoped ids, missing evidence,
unknown schemas, output overflow, timeout, and cancellation. A fixture pass is
not F2 language support or permission to auto-enable the provider.
## BDD-spine Commands (0.3.0)
agent-spec 0.3.0 absorbs living-spec-library + scaffolding/governance under the
BDD-spine model (Discovery → Formulation → Automation). These six commands are
additive — **verdict semantics and `is_passing` are unchanged**; every new check
is a sensor (lint / report / audit), never a silent change to pass/fail.
| Command | Purpose | When to Use |
|---------|---------|-------------|
| `agent-spec matrix <spec> --code .` | Render the coverage matrix: Rule × Scenario × Test × Verdict × Provenance (`--format text\|json\|markdown`) | See which Rules/Examples are proven by which tests, and whether evidence is Computational vs Inferential |
| `agent-spec promote <spec> --rule <id> --to <cap> --code .` | Promote a passing task Rule into `specs/capabilities/<cap>.spec.md` (living-spec library) | When a task Rule has matured and should be reused across tasks. Gate: the Rule's Examples must pass (≥1 example required); the stable `id` never changes |
| `agent-spec audit --spec-dir specs` | Aggregate spec-library health: counts, unproven rules, ungrouped scenarios, open questions, malformed rules (`--format text\|json`) | Periodic library health snapshot. **Observability only — never gates** |
| `agent-spec discover --from-codebase --code <dir> --name <n> [--out <file>]` | Reverse-engineer a draft task spec from existing test functions (one bound scenario per test + a `## Questions` seed) | Cold-start: a codebase has tests but no spec. The draft is a parseable starting point, NOT a finished contract — refine the seeded Questions |
| `agent-spec check-structure --code <dir> --forbid <substr> --in <glob>` | Mechanical layering guard: forbid a reference within a file glob; non-zero exit on violation | Enforce architecture invariants (e.g. `--forbid crate::services --in clients/**`) in CI |
| `agent-spec gen-integrations [--target agents\|cursor\|claude\|all] [--out <dir>] [--check]` | Generate per-tool integration files from one source; `--check` exits non-zero on drift | Keep agents/cursor/claude integration files in sync from a single source; use `--check` as a CI drift gate |
Notes:
- `matrix` shares `verify`'s change-set flags (`--change`, `--change-scope`, `--ai-mode`) and default semantics.
- `promote` writes to `specs/capabilities/<name>.spec.md`; the capability name is path-traversal-checked.
- `audit` and `check-structure` are mechanical and read-only (no code execution beyond scanning).
## Knowledge & Liveness Layer (0.4.0 KLL)
KLL adds a typed **knowledge layer** beside specs: durable `decision` /
`requirement` / `guidance` / `proposal` artifacts under `knowledge/`, a
`satisfies:` edge from specs back to decisions or requirements, and a **derived
liveness** answer to "is this decision/requirement still guarded by the code?"
— recomputed from current spec verdicts, never stored. A read-only MCP server
serves it all to agents with no RAG. Knowledge lives in `knowledge/`; specs
still live in `specs/`.
| Command | Purpose | When to Use |
|---------|---------|-------------|
| `agent-spec init --workspace` | Scaffold the canonical `knowledge/` tree (decisions/requirements/proposals/guidance/context + canon + `.agent-spec/config.yaml`). Idempotent | Once, to lay down the knowledge workspace beside `specs/` |
| `agent-spec trace <id> [--gate]` | Trace a decision or requirement id to the specs that `satisfy:` it and report **liveness** (honored / violated / unproven / n/a). `--gate` exits 2 on violated, warns on unproven | Check whether a recorded knowledge artifact is still enforced by passing specs; use `--gate` in CI |
| `agent-spec lint-knowledge [--format text\|json\|sarif] [--gate]` | Lint the knowledge corpus: per-doc rules + governance (id-conflict, supersession integrity, stale refs). `--gate` exits 2 on any Error | Governance gate for the knowledge base; `--format sarif` feeds GitHub Code Scanning |
| `agent-spec requirements transition <ID> --to <status>` / `requirements supersede <ID> --by <NEW>` | Explicit human governance transitions (proposed→accepted/rejected, accepted→deprecated, atomic supersession); missing status fails `graph --gate`; `--format json` emits digest-bearing machine output (facts only — no actor/authority fields; external systems bind approvals to digests) | Accept requirements before lowering; compilation never mutates status |
| `agent-spec requirements status <ID>` | Three-axis report: governance / execution / liveness with spec evidence | "Where is REQ-X?" in one command |
| `agent-spec requirements traceability <ID> [--format json\|text] [--out <file>]` | Deterministic projection of one requirement's evidence chain: clauses → satisfying specs → scenarios → bound tests → latest recorded verdicts → derived liveness; a pure read over stored trace records | Feed dashboards/orchestrators one byte-stable JSON document instead of re-deriving the join |
| `agent-spec requirements <graph\|plan\|work-units\|test-obligations\|traceability> --out <f> --provenance <m>.json` | Emit a compilation-run manifest (v2): compiler build commit + effective config + blake3 input/output digests | Record any artifact-emitting compilation as reproducible, auditable work |
| `agent-spec requirements verify-run --manifest <m>.json` | Replay the recorded compilation in memory and byte-compare against recorded digests; non-zero exit names every drifted output | Prove a recorded compilation still reproduces — determinism as an executable check |
| `agent-spec requirements compile --out <dir> [--id REQ-*] [--layout agent-spec-v1\|arc-v1] [--force]` | Per-requirement bundles (requirement doc + draft spec + traceability + compilation manifest with bundle digest); atomic writes, overwrite refusal without `--force`; `arc-v1` projects reference-compatible file names over the same content | Hand orchestrators/consumers a pinned, replayable bundle; covers accepted requirements whose work unit is ready (cold-start compile path) |
View on GitHub