Skip to content
Monolithic-DevPublic

About

No description, website, or topics provided.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

FlagProof — Don't sample your flags. Prove them.

Formal verification, reachability analysis, and an AI-agent safety interlock for Flagsmith.
The LLM proposes, the solver disposes, the human signs.

FlagProof Status 259 tests passing 102/102 parity Python 3.11+ MIT License

Python Z3 SMT cvc5 Flagsmith MCP GitHub Actions Pydantic uv

Overview  ·  Screenshots  ·  Architecture  ·  User Flows  ·  Flagsmith Surfaces  ·  Quickstart  ·  Interlock & Tiers  ·  MCP Setup  ·  Docs


Overview

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/NONE rule trees, priorities, multivariate allocations, and PERCENTAGE_SPLIT buckets into Z3 and re-checks standalone SMT-LIB 2.6 queries with cvc5.
  • Real-Engine Replay Oracle: Every violation witness and counterfactual is replayed through flagsmith-flag-engine (102/102 parity cases agree with 0 disagreements).
  • Honest Coverage & UNKNOWN Downgrade: Unsupported operators (such as REGEX) never produce a false PROVED — affected invariants downgrade to UNKNOWN with exact rule coverage (13/14).
  • AI Agent Interlock: Intercepts Flagsmith MCP writes via a Claude Code PreToolUse hook, 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.


Screenshots

FlagProof HTML Verification Report showing I-001 VIOLATED with concrete witness and engine confirmation
Verification Report (out/report.html): self-contained single-file HTML report with verdicts, rule coverage, witness cards, and engine replay confirmation
FlagProof Reachable-State Atlas showing 16 reachable combinations out of 32
Reachable-State Atlas (docs/sample-atlas.html): visualizes all reachable feature combinations (16 of 32 on the demo config) and highlights overlap-depth-4 violations

Architecture

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)"]
Loading

Verification & Trust Guarantees

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

User Flows

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
Loading

How FlagProof Uses Flagsmith

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

60-Second Quickstart (Offline)

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

Core CLI Commands

# 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/bundle

Agent Interlock, Risk Tiers (T0–T3), & Sign-Off Boundary

Opening 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): VIOLATED or UNKNOWN — cannot be approved.

MCP Setup (9 Read-Only Tools)

claude mcp add flagproof \
  --env FLAGSMITH_SERVER_KEY=ser.xxxxx \
  --env FLAGSMITH_API_URL=https://api.flagsmith.com \
  -- uvx flagproof mcp

Exposed 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.


Honest Limits, Pinned Versions, & Documentation

  • 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 to UNKNOWN; identity overrides are listed in coverage notes; proof bundle attestation.json and flagproof.receipt/1 are hash-bound (unsigned).
  • Further Reading: JUDGES.md · STATUS.md · docs/modules.md · docs/known-issues.md · docs/edge-case-status.md · SECURITY.md

Invariant DSL (flagproof.yaml)

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 }

Project Structure

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)

Tech Stack

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

CLI Reference & Canonical Exit Codes

All CLI Commands

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

Canonical Exit Codes

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

MCP Tool Reference (9 Read-Only Tools)

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

Environment Variables & Configuration

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

Examples, Benchmarks, & Testing Gates

  • Bug-Class Examples (examples/):
    • 01-shadowed-override: eu_users shadows eu_pro_users (shadowed_override lint + I-001 VIOLATED).
    • 02-priority-order-bug: promo_cohort outranks free_block (I-001 VIOLATED).
    • 03-percentage-split-overlap: Independent 25% splits overlap (I-001 VIOLATED).
  • Honest UNKNOWN Demo: demo/unsupported-operator.json introduces a REGEX rule, downgrading I-003 to UNKNOWN (13/14 rules covered, exit 2).
  • 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

CI/CD & Security Model

  • Key Separation: Local development, CI checks, and MCP tools only ever use the read-only FLAGSMITH_SERVER_KEY (ser.*). Only the human-gated flagproof-apply workflow holds FLAGSMITH_ADMIN_KEY.
  • Author Guard (scripts/author_guard.py): Blocks automated agents or bots from approving flagproof.yaml or fixes/** pull requests.
  • SARIF & PR Comments: flagproof bundle emits GitHub-compatible SARIF (results.sarif) and SVG status badges.
  • Webhook Verification: flagproof watch validates incoming Flagsmith webhooks with constant-time HMAC-SHA256 signatures and rate limiting.

Contributing & License

Contributions are welcome — see CONTRIBUTING.md and SECURITY.md.
Released under the MIT License.

About

No description, website, or topics provided.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages