Agent Setup
Make any React repo agent-ready in 60 seconds. One command wires AGENTS.md, MCP, a CI workflow, and a governance baseline so AI agents stay inside your design-system guardrails.
AI agents (Claude, Cursor, Codex, Copilot) only build well within guardrails they can discover and validate against. fragments init produces those guardrails for any React project in one command — no signup required. Cloud users get the same setup with a token paste that pulls team rules from your org.
@usefragments/ui, theming, providers), see Install & Theming. This page covers the agent and governance layer that wraps any React codebase.Quick start
Run from your repo root. No flags needed for local-first setup:
npx @usefragments/cli initThat detects your framework and existing UI library (MUI, Chakra, Mantine, Ant Design, shadcn, …), writes the contract — including govern.canonicalSources for the detected library — classifies your components, writes the agent context files, wires a hosted MCP entry, installs the agent contract hook for every supported agent (skip with --no-hook), generates a CI workflow, and captures a governance baseline. Setup ends by running fragments doctor, which proves the enforcement chain is armed rather than assuming it. Verify the guardrails contract anytime with:
npx @usefragments/cli statusThree green ticks (context, hosted validator, CI mirror) plus a fresh Cloud sync when connected means guardrails are active. Anything else exits non-zero with a stable code so it's hookable into pre-commit and CI.
The Guardrails Contract
A repo has active guardrails when four things are true. The CLI produces all of them; fragments status verifies them.
- Agent context current.
AGENTS.mdreferences.fragments/agent-context.md, which exists and was generated against your current preset. - Validation available.
.mcp.jsonhas a hostedfragmentsentry so agents can calldesign_system/conformanddesign_system/prove_compliantmid-edit. - CI mirrors local. A workflow exists and runs the same engine you run locally, against the same preset.
- In sync with team (when Cloud-connected) — your local rules version matches what your team published in Fragments Cloud.
What init writes
Every file is idempotent. Re-running init refreshes what fragments owns without clobbering your content.
fragments.config.ts— project shape, framework, pinned preset version (e.g.universal@2), andgovern.canonicalSourceswhen an existing UI library is detected — so canonical-component enforcement works from the first scan, scoped to the component names that library actually exports.AGENTS.md— the cross-tool convention file (read by Claude, Codex, Cursor). On first run we create it; on subsequent runs we add only one line pointing at the generated context. The rest of the file is yours..fragments/agent-context.md— canonical primitives, available tokens, active rules, and the definition-of-done agents should follow. Generated on everyinitrun..mcp.json— merged conservatively. We only own thefragmentsentry; any other MCP servers you have configured are preserved. Thefragmentsentry always points at the hosted Fragments MCP endpoint with anAuthorization: Bearer ${FRAGMENTS_API_KEY}header resolved from the environment at runtime..github/workflows/fragments.yml— a PR + push workflow that runsfragments checkwith your preset, emits SARIF for GitHub code-scanning, and writes a JSON report to.fragments/governance.json..fragments/baseline.json— governance snapshot at init time. Future scans can compute deltas against this baseline..fragments/classification.json— per-component canonical mapping. Heuristic classification always runs; settingANTHROPIC_API_KEYorOPENAI_API_KEYadds an AI semantic layer for low-confidence components. Re-runfragments classifyafter adding a key.- Agent hook config — advisory contract-hook entries for Claude Code, Codex, Cursor, and Copilot (unless
--no-hook). Init also ensures@usefragments/cliis a devDependency so the hook command is repo-portable — committing.claude/settings.jsonthen arms every teammate, clone, and worktree. See Agent contract hook.
Setup finishes by running fragments doctor — a nine-plus-check prover that validates the hook entries, the pinned command, dist freshness, contract resolution, and a synthetic-payload round-trip through the exact installed hook. Because the hook chain is fail-open (a broken chain looks identical to a healthy one), doctor is the honest answer to "is it actually working?". Run it anytime; pass --json for machines or --reset-debounce to clear per-session hook state first.
Agent contract hook
MCP lets an agent pull validation when it chooses to. The contract hook pushes your guardrails into the agent as it works — so your canonical primitives and tokens reach it beforethe PR, not flagged after merge. It reads the same contract your CI runs against, so local feedback and the merge gate can't drift. init installs it for every supported agent automatically (opt out with --no-hook); the standalone command exists for repos initialized before hooks, or to retarget a single agent or mode:
npx @usefragments/cli hook install --agent allHow the contract reaches each agent depends on what that agent supports:
- Claude Code & Codex — both expose programmatic hooks, so the contract is injected automatically: the vocabulary card at session start, plus a check at the moment of each governed edit (before the agent writes a raw
<button>or a hardcoded hex). Advisory by default — add--mode blockingto also deny a write locally on a confirmed, deterministic violation (a raw color where a token exists; a canonical-component bypass) — never a judgment call, and only what CI would also fail. A deny embeds the conformed replacement — corrected content produced by the same deterministic rewrite engine asdesign_system/conform— so the agent retries with the fix instead of guessing. Producing that fix is deterministic; the agent applying it is probabilistic, so after two denies for the same file and finding set the hook downgrades to advisory and lets CI arbitrate. CI stays the source of truth. - Cursor & Copilot — these have no programmatic edit hook, so they get a static, always-on rule file instead (
.cursor/rules/fragments-design-system.mdcwithalwaysApply: true,.github/copilot-instructions.md), embedding your real canonical component names and token prefix. This is static injection, not interception: the contract rides in every conversation, but the tool cannot block a write the way the Claude/Codex hook can — and the files go stale until the next install, another reason the merge gate is the only guarantee.
Target one agent with --agent claude|codex|cursor|copilot, turn on the local deny gate, or fold installation into library setup with fragments setup --hook:
# advisory hook for one agent
npx @usefragments/cli hook install --agent codex
# local deny gate (Claude/Codex) — blocks confirmed hard violations pre-write
npx @usefragments/cli hook install --agent claude --mode blocking
# install during library setup, then remove later
npx @usefragments/cli setup --hook
npx @usefragments/cli hook uninstall --agent all@usefragments/cli is a declared dependency (init ensures this), the Claude hook command is repo-portable with no machine-absolute paths — commit .claude/settings.json and every teammate, clone, and worktree is governed after install. Without the dependency, install pins the resolved CLI path instead. Re-running never duplicates an entry, and any hooks you already configured are preserved. Prove the chain anytime with fragments doctor.The vocabulary card
The highest-leverage moment to influence an agent is before it writes code. The vocabulary card is a compact (≤2.5KB) digest of your contract, built from your confirmed canonical mappings: canonical component names with their import path, your token prefix, a short exemplar, and a contract-hash stamp so staleness is detectable. If the contract has no confirmed component names yet, the card degrades honestly to a token-prefix and canonical-preference nudge — it never fabricates names.
When it reaches each agent:
- Claude Code & Codex — injected at session start, including after a session resume, a context compaction, or a clear (long sessions would otherwise lose it), and re-stamped on prompts (debounced, so it never spams every message). Both also get the write-time check described above.
- Cursor & Copilot — the same vocabulary is embedded in their static rule files at install time. Always present in conversation context, but static: it refreshes on the next install, not per session.
Honest coverage note: injection raises the probability that the first draft is already on-system — it is measured and improving, not a guarantee. Writes that bypass hooked tools (shell-mediated file edits, un-hooked editors) are not intercepted at write time; the CI merge gate is the layer that covers everything, regardless of which agent or human produced the change.
Coming from Cloud
If you signed up at app.usefragments.comand created an org or project before running the CLI, the wizard's last screen hands you a paste token scoped to your org, project, and (for monorepos) path. Run:
npx @usefragments/cli init --token=fc_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxThe CLI uses the token to pull your governance policy, classification, and baseline from Cloud, then writes the same local files as the local-first path. Re-run anytime to refresh after your team edits rules in the dashboard.
init pulls them down to your local files when a token is present. No background sync; no surprise file changes.Verifying with fragments status
status reads the four contract items and reports a pass/fail per item. Useful both interactively and as a hook.
$ npx @usefragments/cli status
Fragments status
✓ Agent context current
.fragments/agent-context.md is referenced and current.
✓ Validation available
Fragments hosted MCP endpoint is present.
✓ CI mirrors local
.github/workflows/fragments.yml runs fragments check with universal.
- In sync with team
No Cloud sync file found; local-only project.
Guardrails active.Exit codes
status exits non-zero when any required item fails. Each item has a stable exit code so scripts can react specifically.
0— all contract items pass.11— Agent context current failed (missing or stale).12— Validation available failed (MCP entry missing or invalid).13— CI mirrors local failed (no workflow matching the active preset).14— In sync with team failed (Cloud sync stale or rules version mismatch).
Pre-commit hook
Drop into Husky / lefthook / git hooks directly:
#!/usr/bin/env sh
npx @usefragments/cli status || {
echo "Run 'fragments init' to refresh guardrails."
exit 1
}For JSON output suitable for CI dashboards, pass --json.
CI workflow
init writes a GitHub Actions workflow at .github/workflows/fragments.yml that runs fragments check on PRs and pushes, emits SARIF for GitHub code-scanning, and writes a JSON report to .fragments/governance.json.
To ingest findings into Fragments Cloud (Check Runs + inline PR review comments), add these repo secrets in your GitHub repo settings:
FRAGMENTS_API_KEY— your project-scoped Fragments Cloud key.FRAGMENTS_CLOUD_URL— optional; defaults tohttps://app.usefragments.com.
Monorepos
GitHub Actions only reads workflows from the repository root, so a project at a subpath like apps/cloud can't ship a workflow at apps/cloud/.github/workflows. status understands this: when the canonical path is missing it walks up to the git repo root and scans .github/workflows/ for any workflow that runs fragments check with the right preset, and (when present) the right --dir.
For a project under apps/cloud with multiple packages, run init from each project root. Each gets its own scoped token (when Cloud-connected) and its own context files.
# from a monorepo subpackage
cd apps/cloud
npx @usefragments/cli init
npx @usefragments/cli statusAI component classifier
On first run, init scans your components and asks an LLM to map them to canonical primitives (Button, Input, Dialog, etc.). This step uses yourAnthropic or OpenAI API key — there's no Fragments proxy and no cost on our side.
export ANTHROPIC_API_KEY=sk-ant-...
npx @usefragments/cli initIf no key is set, classification is skipped cleanly — everything else still runs. Add a key and run npx @usefragments/cli classify later when ready.
Updating
init is idempotent. Run it again to:
- Refresh
.fragments/agent-context.mdwith the latest preset rules. - Re-pull team rules from Cloud (when a token is configured).
- Re-baseline governance findings.
- Pick up a new preset version (e.g. moving from
universal@2touniversal@3).
Your AGENTS.md body is never touched after the initial pointer is added. Add --force to reinitialize an already-set-up project from scratch.
Troubleshooting
Exit code 11 — agent context. Most often: AGENTS.md doesn't reference .fragments/agent-context.md. Re-run init to add the pointer line, or add See: .fragments/agent-context.md by hand.
Exit code 12 — MCP entry. Your .mcp.json exists but the fragments server entry is missing, lacks an HTTPS URL, or has an invalid auth header. Re-run init to repair just the fragments entry — other servers stay untouched.
Exit code 13 — CI mirror. No workflow runs fragments check with the same preset as your local config. In a monorepo, ensure your root workflow passes --dir <your-project-path> or scans the whole repo.
Exit code 14 — Cloud sync. Cloud has a newer rules version, or your sync is older than the tolerance window (default 168h). Re-run init with your token to pull the latest team rules.
For machine-readable output, pass --json to status — the same checks come back as a structured object with the failing item identified by id.