Formal verification, reachability analysis, and an AI-agent safety interlock for Flagsmith.
The LLM proposes, the solver disposes, the human signs.
Overview · Screenshots · Architecture · User Flows · Flagsmith Surfaces · Quickstart · Interlock & Tiers · MCP Setup · Docs
Feature-flag dashboards show which flags exist, not which combinations of targeting rules make reachable. A sampled preview over 2,000 test users only checks those 2,000 rows (demo/sample_check.py finds 0 violations on the demo environment). Yet a single user landing where four segments overlap (beta_pro, eu_legacy_retired, eu_users, mobile_modern) receives new_pricing=B while legacy_tax_rules=false (I-001 VIOLATED).
FlagProof replaces sampling with mathematical proof:
- Exhaustive SMT Verification: Encodes Flagsmith segments,
ALL/ANY/NONErule trees, priorities, multivariate allocations, andPERCENTAGE_SPLITbuckets into Z3 and re-checks standalone SMT-LIB 2.6 queries withcvc5. - Real-Engine Replay Oracle: Every violation witness and counterfactual is replayed through
flagsmith-flag-engine(102/102parity cases agree with0disagreements). - Honest Coverage &
UNKNOWNDowngrade: Unsupported operators (such asREGEX) never produce a falsePROVED— affected invariants downgrade toUNKNOWNwith exact rule coverage (13/14). - AI Agent Interlock: Intercepts Flagsmith MCP writes via a Claude Code
PreToolUsehook, blocks unsafe mutations with concrete witnesses, and requires human sign-off with hash-bound receipts for safe changes.
Start with JUDGES.md for the 60-second offline walkthrough, or open the static outputs directly: docs/sample-report.html · docs/sample-atlas.html.
flowchart LR
Agent["AI Agent / PR / CLI"] --> Hook["Interlock Hook (never emits allow)"]
Doc["Flagsmith Env Doc + flagproof.yaml"] --> Enc["Z3 Encoder (rule coverage tracked)"]
Hook --> Enc
Enc --> Solver["Z3 + cvc5 Second-Solver Recheck"]
Solver -->|SAT| Oracle["flagsmith-flag-engine Replay"]
Oracle -->|Confirmed| Deny["VIOLATED / Deny + Witness + Safe Fix Candidates"]
Solver -->|UNSAT + 100% cone| Ask["PROVED -> Receipt + Tier T0..T3 -> Human Sign-Off"]
Solver -->|Unsupported in cone| Unk["UNKNOWN (unsupported_rule)"]
| Check | Result | Evidence |
|---|---|---|
| Engine Parity | 102/102 agree, 0 disagree |
vendor/engine-test-data via flagproof parity |
| Mutation Testing | 5/5 mutants killed |
scripts/mutation_check.py |
| Second-Solver Recheck | 3/3 SMT-LIB 2.6 queries verified |
cvc5==1.4.2 via flagproof bundle verify |
| Bench-lite Suite | 16/16 match expected (7/7 unsafe blocked) |
tests/e2e/test_bench.py |
| Test Suite & Types | 259 passed, 1 skipped, mypy & ruff clean |
pytest, mypy src, ruff check |
sequenceDiagram
participant Dev as Developer / AI Agent
participant Hook as Interlock (PreToolUse)
participant Solver as Z3 + Flagsmith Engine
participant CI as GitHub Actions (CODEOWNERS)
participant API as Flagsmith Management API
Dev->>Hook: Propose flag / segment change
Hook->>Solver: Verify invariants & keeps
alt Violation Found (T3)
Solver-->>Hook: SAT + Engine-Confirmed Witness
Hook-->>Dev: DENY with witness & safe fix candidates
else Proved Safe (T0-T2)
Solver-->>Hook: UNSAT + Receipt Hash
Hook-->>Dev: ASK human with receipt_id & exposure tier
Dev->>CI: Open PR for human review
CI->>Solver: Re-prove live environment before write
CI->>API: Apply change (auto-rollback on failure)
end
| Flagsmith Surface | How FlagProof Uses It |
|---|---|
Environment Document (ser.*) |
Source of truth fetched live or loaded from offline snapshots |
flagsmith-flag-engine (11.1.2) |
Replay oracle: every witness and counterfactual is confirmed against the real engine |
Segments & ALL/ANY/NONE Rules |
Encoded into Z3 logic; unsupported operators downgrade PROVED to UNKNOWN |
| Segment Overrides & Priorities | First-match semantics, shadowed overrides, collision merge orders, culprit bisect |
Multivariate & PERCENTAGE_SPLIT |
Bucket intervals, symbolic single-query ramp pre-proof, experiment arm intervals |
| Identities & Traits | Witness generation, explain, and minimal why-not counterfactuals (identifiers hashed) |
| Management API | CI-only flagproof apply (FLAGSMITH_ADMIN_KEY) with pre-reproof, post-verify, and auto-rollback |
| Webhooks | flagproof watch receiver with constant-time HMAC-SHA256 verification and rate limiting |
| Official Flagsmith MCP | Interlock (PreToolUse hook) intercepts write tools, denies unsafe writes, and asks humans with receipts |
| Experiments | Experiment Pre-flight (E1–E4) proves arm invariants, reachability, and override-pinned cohorts before launch |
No API keys or LLM credentials are required for the offline verification path:
git clone --recurse-submodules https://github.com/Monolithic-Dev/FlagProof.git
cd FlagProof
make install # uv sync --all-extras && git submodule update --init --recursive
# Run offline verification & generate HTML witness report
NO_BROWSER=1 make demo# 1. Compare sampling vs formal proof
uv run python demo/sample_check.py
uv run flagproof verify --document demo/environment-document.json --invariants flagproof.yaml --no-llm --roster demo/roster.json
# 2. Explore reachable states & lint dead rules
uv run flagproof atlas --document demo/environment-document.json --format text
uv run flagproof lint --document demo/environment-document.json
# 3. Verify proposed changes & generate proved fixes
uv run flagproof diff --document demo/environment-document.json --change demo/agent_rollout_change.json --alternatives
uv run flagproof fix --document demo/environment-document.json --finding F-0001 --no-llm
# 4. Pre-flight experiments, symbolic ramps, & natural-language queries
uv run flagproof preflight --experiment demo/experiment-checkout-cta.yaml --document demo/environment-document.json
uv run flagproof ramp --plan demo/ramp-beta-pro.yaml --document demo/environment-document.json
uv run flagproof ask "Can an EU free user ever get bulk_discount?" --document demo/environment-document.json --no-llm
uv run flagproof why-not --feature recs_v2 --state enabled --traits '{"region":"US","plan":"free","app_build":399,"is_internal":false}' --document demo/environment-document.json
# 5. Multi-change collision detection & SMT-LIB proof bundles
uv run flagproof collide demo/changes/X.json demo/changes/Y.json --document demo/environment-document.json
uv run flagproof bundle --document demo/environment-document.json --out out/bundle
uv run flagproof bundle verify out/bundleOpening this repository in Claude Code loads .claude/settings.json (PreToolUse hook running flagproof interlock) and .claude/skills/flagproof/SKILL.md.
| Capability | Autonomous Agent (MCP / Interlock) | CI Check (flagproof-check) |
Human via PR (CODEOWNERS) |
CI Apply Job (flagproof-apply) |
|---|---|---|---|---|
| Read / verify / ask / atlas / preflight / ramp / collide | Allowed (read-only ser.*) |
Runs on PR + SARIF bundle | Reviews findings & receipts | Re-proves live env before write |
| Write through Flagsmith MCP | Denied if VIOLATED; Asks human with receipt_id & tier if PROVED |
Validates changed plans | Approves fixes/** |
Re-proves live env |
Approve flagproof.yaml or fixes/ |
Blocked (scripts/author_guard.py) |
Enforces bot guard | Approves via PR | Never edits policy |
Hold FLAGSMITH_ADMIN_KEY & mutate flags |
Never | Never | Never needed locally | Only job with admin key; auto-rollbacks on failure |
Exposure Tiers:
- T0 (
NO_CHANGE): Provably equivalent behaviour. - T1 (
CONTRACTING): Shrinking risky exposure. - T2 (
EXPANDING): Expanding or mixed exposure — requires code-owner review. - T3 (
BLOCKED):VIOLATEDorUNKNOWN— cannot be approved.
claude mcp add flagproof \
--env FLAGSMITH_SERVER_KEY=ser.xxxxx \
--env FLAGSMITH_API_URL=https://api.flagsmith.com \
-- uvx flagproof mcpExposed Tools: flagproof_list_invariants, flagproof_verify_change, flagproof_explain_user, flagproof_suggest_fix, flagproof_propose_invariant, flagproof_preflight_experiment, flagproof_ramp_check, flagproof_ask, flagproof_collide.
- Pinned Versions: Python
>=3.11,z3-solver==5.4.1.0,cvc5==1.4.2,flagsmith-flag-engine==11.1.2,mcp==2.3.0,anthropic==2.14.0,pydantic==2.14.4. - Coverage Bounds: Operators marked unsupported (
REGEX, unsupported JSONPath) downgrade affected proofs toUNKNOWN; identity overrides are listed in coverage notes; proof bundleattestation.jsonandflagproof.receipt/1are hash-bound (unsigned). - Further Reading:
JUDGES.md·STATUS.md·docs/modules.md·docs/known-issues.md·docs/edge-case-status.md·SECURITY.md
Invariants and behavioural keeps are declared in flagproof.yaml and validated against the loaded Flagsmith environment:
version: 1
environment: demo
traits:
region: { type: string }
plan: { type: string }
signup_year: { type: int }
app_build: { type: int }
is_internal: { type: bool }
invariants:
- id: I-001
description: "Never serve new_pricing=B while legacy_tax_rules is off (tax mismatch)."
severity: critical
never:
all:
- { feature: new_pricing, serves: B }
- { feature: legacy_tax_rules, enabled: false }
keeps:
- id: K-001
description: "Non-EU pro users who get B today must still get B."
mode: preserve
population:
all:
- { user: { plan: { equals: pro } } }
- { user: { region: { not_equals: EU } } }
expect: { feature: new_pricing, serves: B }FlagProof/
├── src/flagproof/
│ ├── solver/ # Z3 encoder, finite fallback, domains, witness builder, unsupported tracker
│ ├── engine/ # flagsmith-flag-engine replay oracle & 102-case parity runner
│ ├── invariants/ # YAML parser, schema, Z3 compiler, concrete evaluator
│ ├── checks/ # verify, diff, fixprove, preflight, ramp, atlas, collide, simplify, lint
│ ├── interlock/ # Claude Code PreToolUse hook & Flagsmith MCP write adapter
│ ├── mcp/ # 9 read-only MCP tools (stdio / streamable-http)
│ ├── bundle/ # SMT-LIB 2.6 proof bundle export, cvc5 recheck, SARIF, SVG badge
│ ├── report/ # Single-file accessible HTML report & terminal text renderer
│ ├── agents/ # LLM explainer, fixer, policy writer (with canary & prompt-injection guard)
│ └── watch/ # HMAC-SHA256 webhook receiver & drift watcher
├── demo/ # Offline environment snapshots, 2,000-user roster, & storyboard (record.md)
├── examples/ # 01-shadowed-override, 02-priority-order-bug, 03-percentage-split-overlap
├── bench/ # 16-case Bench-lite agent proposal corpus & expected verdicts
└── tests/ # 259 passing tests (unit, property/Hypothesis, parity, e2e, agents, perf)
| Layer | Technology | Role |
|---|---|---|
| Formal Solver | z3-solver (5.4.1.0) |
Encodes Flagsmith rules, priorities, & buckets into SMT queries |
| Second Solver | cvc5 (1.4.2) |
Independent SMT-LIB 2.6 recheck for flagproof bundle verify |
| Flag Oracle | flagsmith-flag-engine (11.1.2) |
Replays every witness & counterfactual (102/102 parity) |
| Agent Protocol | mcp (2.3.0) + Claude Code Hooks |
9 read-only MCP tools + PreToolUse Interlock gate |
| LLM & Guardrails | anthropic (2.14.0) |
Optional structured explainer/fixer with canary & injection guards |
| CLI & Schemas | typer, pydantic (2.14.4) |
Canonical exit codes (0–5), strict YAML/JSON validation |
| Packaging & QA | uv, pytest, hypothesis, mypy, ruff |
Deterministic lockfile, property tests, strict typing |
| Command | Purpose |
|---|---|
flagproof verify |
Prove all invariants in flagproof.yaml over the environment document |
flagproof atlas |
Compute and render all reachable feature combinations (HTML / text / JSON) |
flagproof diff |
Verify a proposed Change (or --between OLD NEW snapshots) against invariants & keeps |
flagproof fix |
Synthesize and re-prove candidate fix plans for a violated finding |
flagproof prove |
Re-prove a saved fix plan (fixes/P-*.yaml) |
flagproof preflight |
Run E1–E4 experiment pre-flight checks (arm invariants, reachability, pinned cohorts) |
flagproof ramp |
Prove all PERCENTAGE_SPLIT values across [from, to] in a single symbolic query |
flagproof ask |
Answer natural-language questions via closed Query IR + solver + engine |
flagproof why-not |
Compute minimal trait counterfactuals explaining why a user did not receive a state |
flagproof collide |
Compose multiple changes across merge orders to detect joint violations |
flagproof simplify |
Suggest redundant-rule simplifications proved equivalent via Z3 |
flagproof lint |
Detect shadowed overrides and unreachable variants statically |
flagproof bundle |
Export SMT-LIB 2.6 queries, SARIF (results.sarif), and SVG badge |
flagproof bundle verify |
Independently re-verify exported SMT-LIB 2.6 queries with cvc5 |
flagproof explain |
Replay a specific user's traits through flagsmith-flag-engine and show deciding rules |
flagproof watch |
Start HMAC-SHA256-verified webhook receiver for live drift detection |
flagproof apply |
CI-only Management API applier with pre-reproof, post-verify, and auto-rollback |
flagproof interlock |
Claude Code PreToolUse hook adapter for Flagsmith MCP writes |
flagproof mcp |
Run the 9-tool read-only MCP server (stdio or --http) |
flagproof parity |
Run 102-case parity suite against vendor/engine-test-data |
| Exit Code | Constant | Meaning |
|---|---|---|
0 |
EXIT_OK |
All invariants PROVED (or change safe) |
1 |
EXIT_VIOLATED |
At least one invariant VIOLATED (confirmed by Flagsmith engine) |
2 |
EXIT_UNKNOWN |
At least one invariant UNKNOWN (e.g., unsupported operator in cone) |
3 |
EXIT_USAGE_ERROR |
Invalid CLI arguments, schema, or flagproof.yaml |
4 |
EXIT_FETCH_ERROR |
Flagsmith API unreachable or invalid key |
5 |
EXIT_ROLLED_BACK |
Policy refusal or post-apply auto-rollback triggered |
| Tool | Inputs | Output |
|---|---|---|
flagproof_list_invariants |
— | Declared invariants, keeps, and trait specs |
flagproof_verify_change |
change, alternatives? |
Diff verdict, new violations, preserved keeps, exposure tier, receipt_id |
flagproof_explain_user |
traits, identifier? |
Served states, deciding rules, invariant checks, engine agreement |
flagproof_suggest_fix |
finding_id or change |
Accepted & rejected fix candidates with proofs and keep checks |
flagproof_propose_invariant |
text |
Validated draft invariant in proposals/ (human PR required) |
flagproof_preflight_experiment |
experiment |
E1–E4 arm reachability, invariant verdicts, pinned cohorts |
flagproof_ramp_check |
segment, from_pct?, to_pct? |
Symbolic ramp verdict and first unsafe split threshold |
flagproof_ask |
question or query |
Solver + engine-confirmed answer with witness and coverage |
flagproof_collide |
changes, max_orders? |
Joint collision verdict and order-dependence analysis |
| Variable | Required | Purpose |
|---|---|---|
FLAGSMITH_SERVER_KEY |
For live API | Read-only server key (ser.*) to fetch environment documents |
FLAGSMITH_API_URL |
Optional | Flagsmith API base URL (default: https://api.flagsmith.com) |
FLAGSMITH_ADMIN_KEY |
CI apply only | Management API key — never used locally or by agents |
FLAGPROOF_DOCUMENT |
Optional | Path to local environment document JSON (offline mode) |
FLAGPROOF_INVARIANTS |
Optional | Path to flagproof.yaml (default: flagproof.yaml) |
ANTHROPIC_API_KEY |
Optional | Enables LLM explainer/fixer/policy-writer (bypassed with --no-llm) |
FLAGPROOF_MODEL |
Optional | Override Anthropic model name |
FLAGPROOF_LLM_REPLAY |
Optional | Directory of recorded LLM fixtures for deterministic offline replay |
- Bug-Class Examples (
examples/):01-shadowed-override:eu_usersshadowseu_pro_users(shadowed_overridelint +I-001 VIOLATED).02-priority-order-bug:promo_cohortoutranksfree_block(I-001 VIOLATED).03-percentage-split-overlap: Independent25%splits overlap (I-001 VIOLATED).
- Honest
UNKNOWNDemo:demo/unsupported-operator.jsonintroduces aREGEXrule, downgradingI-003toUNKNOWN(13/14rules covered, exit2). - Verification Commands:
uv run pytest -q # 259 passed, 1 skipped
uv run ruff check src tests scripts # All checks passed
uv run mypy src # 90 source files clean
uv run python scripts/day0_checks.py # Dependencies & MCP server
uv run python scripts/mutation_check.py # 5/5 encoder mutants killed
uv run flagproof parity # 102/102 engine-test-data agree- Key Separation: Local development, CI checks, and MCP tools only ever use the read-only
FLAGSMITH_SERVER_KEY(ser.*). Only the human-gatedflagproof-applyworkflow holdsFLAGSMITH_ADMIN_KEY. - Author Guard (
scripts/author_guard.py): Blocks automated agents or bots from approvingflagproof.yamlorfixes/**pull requests. - SARIF & PR Comments:
flagproof bundleemits GitHub-compatible SARIF (results.sarif) and SVG status badges. - Webhook Verification:
flagproof watchvalidates incoming Flagsmith webhooks with constant-time HMAC-SHA256 signatures and rate limiting.
Contributions are welcome — see CONTRIBUTING.md and SECURITY.md.
Released under the MIT License.

