Skip to content
Ivan825Public

About

Run Flagsmith experiments where the code lives: VS Code extension + AI copilot + CI check for self-hosted Flagsmith. Catch silent A/B-test failures, read honest results inline, ship the winner and delete the losing code.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Petri

Run Flagsmith experiments where the code lives.

A VS Code extension for self-hosted Flagsmith. It turns a selection into an experiment, catches broken measurement while you type, shows honest results inline, then ships the winner and deletes the losing code, with an AI copilot that asks before every change.

CI Release Open VSX npm petri-check MIT Self-hosted Flagsmith Toggle Wars tracks

Quick start · Diagnostics · Copilot · Self-hosting · Watch · Health · Pull requests · CLI · Measured · The Petri Coffee experiment

▶ Try it in your browser: paste Flagsmith SDK code and watch 17 of the 20 diagnostics and the decision rule run (the other three need a repo: the lockfile, `package.json` and the file's language). No install, no account.

20 56 s · 4 approvals 0 3 ways in
experiment bugs caught as you type, each with a fix from a one-line idea to a running experiment, every write approved changes to flags, experiments or code without your approval VS Code · Open VSX · npx petri-check / Action

The Experiment Copilot turns a plain buy button into a running experiment, asking for approval at each step

Above: select code → describe the idea → approve each request and diff → the experiment is running, and the self-hosted measurement bug is fixed on the way (3× speed). 📺 Demo video (3 min).

For judges

Where to look
Track 3: open-source, self-hosted Built for self-hosted Flagsmith first: one-command Docker setup with experimentation on, and self-hosted-only checks like PETRI012. Reuse it as a VS Code extension, a CLI or a GitHub Action. MIT, an online playground, and CI that boots a real self-hosted Flagsmith on every push: zero-click setup, an experiment, Petri's checks run live, and a planted bug caught.
Track 2: AI agent with approvals The Experiment Copilot on the Flagsmith Admin + Experiments API: idea → flag, metrics and code → start → judge → ship → delete the losing code. Every write is approved in a modal showing the exact HTTP request or diff, and logged to .petri/audit.jsonl. That rule is code, tested for every tool, not a prompt. Measured: idea → running experiment in 56 s with 4 approvals. And with vs without Petri: an agent fixes the same 6 planted bugs with half the tokens and turns.
Why the rule waits 2,000 simulated A/A experiments: peeking hourly at a "95%" banner ships a do-nothing variant 36.5% of the time; Petri's pre-registered single look ships 8.0% (4.1% with the Bonferroni bar) and still finds a real +39% winner 99.7% of the time. Peeking also ships a variant that's 20% worse about 1 time in 50; Petri's rule never did in 2,000 runs.
Track 1: a real experiment Petri Coffee: pre-registered hypothesis, three arms, primary metric + guardrail, a power calculation, 2,028 shoppers through the real SDK path on self-hosted Flagsmith at submission, and a ground-truth check: both true lifts lie inside Petri's intervals. Submitted before the pre-registered stop, so the SHIP is provisional and the experiment isn't completed.
Track 4: Agent Skill flagsmith-experiment-check: the whole job through the Flagsmith CLI (check the wiring → one-line verdicts → ⛔ flagsmith api …/complete/ → flagsmith evaluate → ⛔ remove the losing code), terse output, read-only until a gate.
Use of Flagsmith Feature flags (multivariate), Experimentation (metrics, experiments, results, exposures), the Flagsmith API, self-hosted Flagsmith, and the Flagsmith CLI's flagsmith.json + credentials. Take Flagsmith away and Petri has nothing to show.

Results panel next to the code that reads the flag

Why

Flagsmith's Experiments API is new, and so is the hard part of it: an experiment is only as good as the code that feeds it. Today its life is split across tabs: the hypothesis in a doc, the flag in the dashboard, the code in the editor, and the results somewhere you check later. The worst failures are silent:

  • An SDK on self-hosted Flagsmith sends its events to Flagsmith Cloud unless eventsApiUrl is set. Your experiment shows zero data and nothing errors.
  • trackEvent("Checkout_Completed") never counts for a metric listening to checkout_completed.
  • getValue() on an experiment flag serves the variant but records no exposure.
  • A variant without a key creates a phantom arm that splits off part of your traffic.
  • The experiment ends, and the losing branch lives in the code forever.

Other Flagsmith editor tools show flag state. Petri runs the experiment. It puts all of that in the editor, next to the line that causes it. It runs the experiment's whole lifecycle from the editor: it wires the code, starts the experiment, catches broken measurement as you type, locks what each arm serves while it runs, judges the result by one conservative rule, ships the winner and deletes the losing code, then runs your tests and undoes the edit if they fail. Every step that changes something waits for your approval.

Before, during and after

Most tools check one moment. Petri guards an experiment for its whole life:

What Petri does
Before it starts 20 diagnostics as you type; a launch gate that runs them as if the experiment were live; audience checks (overlapping experiments, segment overrides); rehearse, real visitors through your app with a recount of what Flagsmith stored; a sample size from your own baseline. Diagnostics · Rehearse
While it runs The treatment lock (PETRI013) flags changes to what an arm serves; a pre-registered stop marks an early SHIP as provisional; Petri Watch catches an arm that stops converting or enrolling and blames the commit; a health scorecard; a peek-safe sequential test. Treatment lock · Watch · Health
After it ends One decision rule with expected loss; the winner shipped behind an approval, or ramped in reviewed steps; the losing code removed and verified by your tests; decision memory above the shipped code; a report for the record. Decision rule · Pull requests

What it does

See A sidebar of flags and experiments for the selected environment. CodeLens above every flag read shows status, lift and chance to win. Hovers show the live experiment split and per-arm results. The results panel plots each arm's 95% credible interval.
Catch 20 diagnostics (PETRI001–PETRI020) in the Problems panel, each a way an experiment silently loses or skews data, with quick fixes where a safe one exists. List →
Decide One deterministic decision rule, shared by the UI and the copilot: ship only at ≥ 95% chance to win on the primary metric, with no guardrail likely hurt, no sample-ratio mismatch (Petri runs its own chi-square when Flagsmith reports none) and no phantom arms. Otherwise keep running (with how many more users would decide it), keep control or investigate. A ship verdict states the expected loss and the Bonferroni bar; a peek-safe sequential test is reported alongside. Rule →
Watch Petri Watch reads Flagsmith's hourly per-arm timelines and alerts when an arm stops converting or enrolling or the split breaks, naming the commit that caused it. A health scorecard (split, arms, missing data, storage, freshness, novelty) sits next to every result. Watch →
Act Start, pause and complete an experiment (ship a variant, keep control, or turn the flag off) from the tree, the panel or the command palette, or as pull requests (petri.plan.json, applied on merge, with a staged ramp). Then remove the losing code path; your tests run after the edit and it's undone if they fail.
Delegate The Experiment Copilot (Claude, via the Anthropic API) takes an idea all the way through: plan → flag, metrics and code → start → watch → judge → ship → delete dead code. How it works →
Trust Every write to Flagsmith shows the exact HTTP request, and every code change shows a diff, in a modal. Nothing happens without your approval, whether you clicked it or the copilot proposed it. Every decision is appended to .petri/audit.jsonl.
Self-host Petri: Start Self-Hosted Flagsmith (Docker) brings up Flagsmith with experimentation enabled, and Petri reads the Flagsmith CLI's flagsmith.json and credentials so a bound repo connects with no setup.
Approval modal showing the exact POST request the copilot wants to send
Every write to Flagsmith: the exact request, approved by you.
Copilot code change shown as a diff with an approval dialog
Every code change: a diff, applied as a normal (undoable) edit.
Hover over a flag read: the live experiment split and hypothesis
Hover: the live experiment split, hypothesis and per-arm results.
PETRI012: self-hosted SDK sending events to Flagsmith Cloud
PETRI012: this SDK would send every event to Flagsmith Cloud instead of your server.

Install

Zero setup: Open in GitHub Codespaces starts self-hosted Flagsmith with experimentation, creates the admin, project, API key and event storage, builds Petri, and connects it. Nothing to click. Or just try the checks in your browser.

VS Code, one line (needs the code command):

curl -fsSL -o petri.vsix https://github.com/Ivan825/petri/releases/latest/download/petri.vsix && code --install-extension petri.vsix

Or download petri.vsix and use Extensions → ⋯ → Install from VSIX….

Cursor, VSCodium, Windsurf, Gitpod: search Petri in Extensions. It's on Open VSX from a verified publisher. The same petri.vsix also works via Install from VSIX….

CLI / CI: npx petri-check . (no install, on npm), or the GitHub Action.

Configuration

Variable / setting Used by What for
petri.apiUrl (set by Connect) extension Flagsmith API, e.g. http://localhost:8000/api/v1 or https://api.flagsmith.com/api/v1
Organisation API key (entered in Connect, kept in VS Code SecretStorage) extension Reading flags, experiments and results; approved writes
FLAGSMITH_API_KEY_localhost_8000 / FLAGSMITH_API_KEY extension, CLI Optional: the Flagsmith CLI's credential variables, so a CLI-bound repo connects without prompts
flagsmith.json (from flagsmith init or bootstrap.mjs) extension, CLI Optional: picks the project and environment automatically
flagsmith.env (from selfhost/bootstrap.mjs, gitignored) extension, CLI Optional: the same credential variables in a file, so Petri connects with no prompt
Anthropic API key (Petri: Set Anthropic API Key) or ANTHROPIC_API_KEY copilot only Everything else works without it
FLAGSMITH_API_KEY + --environment petri-check Optional: run all 20 rules against live data instead of the code-only ones

What success looks like: open a file that reads a flag in a running experiment, and a CodeLens like 🧪 <experiment> · running · <leading arm> +<lift> on <primary metric> · <chance> to win appears above the line, with the experiment listed in the Petri sidebar.

Then

  1. No Flagsmith yet? Two commands give you one that's ready to use, with no dashboard clicks:
    docker compose -f selfhost/docker-compose.yml up -d
    node selfhost/bootstrap.mjs   # admin, organisation, project, API key, event storage → flagsmith.json + flagsmith.env
    Petri then connects by itself. (Or Petri: Start Self-Hosted Flagsmith (Docker) and set it up in the dashboard.)
  2. Otherwise, Petri: Connect to Flagsmith → http://localhost:8000 (or https://api.flagsmith.com) → paste the key → pick an environment. (A repo bound with the Flagsmith CLI connects by itself.)
  3. Open any file that reads a flag: CodeLens, hovers and diagnostics appear.
  4. Optional: Petri: Set Anthropic API Key for the Experiment Copilot.

Full walkthrough with the demo shop: docs/quickstart.md. To build from source: cd extension && npm ci && npm run package.

Use it in CI

The same diagnostics run headless, so a broken experiment fails the build instead of a week of data.

# .github/workflows/petri.yml
on: [pull_request]
jobs:
  petri:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: Ivan825/petri@v0.1.5
        with:
          environment: ${{ vars.FLAGSMITH_ENVIRONMENT }}   # optional: check against live flags and experiments
          api_url: https://flags.example.com/api/v1/      # your self-hosted Flagsmith
        env:
          FLAGSMITH_API_KEY: ${{ secrets.FLAGSMITH_API_KEY }}

Findings show up as annotations on the pull request. Locally: node action/petri-check.mjs <dir> (add --format json, --fail-on warning). Without a key it runs the code-only rules (PETRI007, PETRI008, PETRI012, PETRI014, PETRI015–PETRI020, and PETRI013 when the repo has a petri.lock.json). With FLAGSMITH_API_KEY and an environment (or a flagsmith.json from the Flagsmith CLI) it runs all twenty against the live environment, exactly as the editor does. A real run: PR #1 drops eventsApiUrl from the demo shop, and the check blocks it with an annotation on the line.

Treatment lock: catch an experiment being changed while it runs

Most tools check whether an experiment is measured right. Petri also checks it still tests what it started testing. When an experiment starts, Petri writes petri.lock.json: the variants, split and metrics, plus a fingerprint of each code path that serves the flag. Commit it, and from then on:

  • In the editor, editing a running experiment's code path shows PETRI013 as you type: "buyButtonLabel() serves running experiment … and has changed since the experiment started … the results will mix them."
  • In CI, a pull request that changes that code fails, offline, with no Flagsmith key, because the lockfile is in the repo.
  • Against Flagsmith, a variant value, split or metric edited in the dashboard mid-run is flagged, and the verdict says the results mix two treatments.

Whitespace and comment changes don't count. Completing the experiment releases the lock and keeps the decision and its evidence in the lockfile. A lens above the shipped value reads "✓ Decided by experiment … free_shipping won: +50.4% [+0.6% … +100.3%], 98% to beat control, 2,028 users", so the next person to touch it knows it was tested. Petri covers an experiment before it starts (launch gate), while it runs (treatment lock, plus a pre-registered stop that marks an early SHIP as provisional) and after it ends (decision memory). npx petri-check lock or Petri: Lock Running Experiments creates one for experiments already running. Details →

Health scorecard

The diagnostics mature experimentation platforms run before you read a result, applied to Flagsmith's data: traffic split at α = 0.001, missing conversions per arm, event storage, result freshness. Petri adds its own: measurement continuity (Watch), the treatment lock, and novelty, an early lift that fades. It shows as one line, Health: 6 pass · 1 warn, in the editor, results panel, CLI, report and MCP. Details →

Rehearse before launch

npx petri-check rehearse . --url http://localhost:3000/ --convert form sends real visitors through your app on a development environment, converts some, and recounts what Flagsmith recorded. On a shop whose free-shipping checkout route forgot trackEvent (every static rule passes), it reported "sent 15 conversions → Flagsmith counted 7 ✖". On the fixed shop, 30/30 and 15/15 ✓. Details →

Petri Watch: catch measurement breaking in production

After a deploy, one variant's checkout can stop sending its event while everything else keeps working. Petri Watch reads Flagsmith's hourly per-arm timelines of every running experiment and alerts when an arm stops converting, an arm stops enrolling, enrolment stops, or the split breaks. Each alert is statistically grounded (zero where its own rate makes that < 1% likely), and Petri blames the commit that landed just before the break. A real run, on a staged incident (a new checkout route that forgot trackEvent, which passes every static rule):

✖ #1 checkout_cta: free_shipping stopped converting on Checkout conversion at 28 Nov, 22:30: 0 conversions from 246 new users in 2 h (expected ~25).
  Likely cause: 8a459f8 "Free-shipping orders get their own checkout route (skip the delivery-fee step)" (28 Nov, 22:00), touching server.mjs.

The shop took 37 free-shipping orders in those hours, and Flagsmith counted none. The full run →

It runs in the editor (a notification and a red line in the tree), as npx petri-check watch (exits 1), hourly as a scheduled GitHub Action (command: watch, so a failed run emails you), and through MCP.

Experiments as pull requests

For teams, the approval can be a code review. Experiment changes (start, pause, complete with a decision) go in petri.plan.json. The PR shows a dry run of the exact requests, and on merge petri-check apply (or the Action, command: apply) sends them: idempotent, with production requiring an explicit opt-in on the change. Agents propose entries through MCP (petri_plan_change) without writing to Flagsmith. A ramp change rolls a decided winner out in reviewed steps (10 → 50 → 100%). Details →

Use it from any coding agent (MCP)

claude mcp add petri -- npx -y petri-check mcp     # Claude Code; same command for Cursor, Codex, Copilot via their MCP config

A prompt, wire_experiment, gives an agent Petri's wiring checklist before it writes code. Four tools:

  • petri_check: the 20 diagnostics on a repo.
  • petri_experiments: every experiment with per-arm lift, interval, chance to win, expected loss, the health scorecard, Watch alerts, the peek-safe test and Petri's verdict.
  • petri_plan_change: proposes a petri.plan.json entry plus a dry run, and changes nothing.
  • petri_rule: explains a diagnostic.

It's read-only towards Flagsmith by design: no tool can start, stop or ship an experiment, so an agent can't change production through it. Changes go through the editor's approval dialogs or a reviewed pull request.

Agent Skill

skills/flagsmith-experiment-check gives any agent the whole job through the Flagsmith CLI: check the wiring with Petri's 20 rules, read every experiment with the fixed verdict (one line each), then, behind ⛔ approval gates, complete the winner with flagsmith api, confirm it with flagsmith evaluate, and remove the losing code. Read-only until a gate, one write per approval, and terse output throughout.

The experiment we ran with it

Petri Coffee is a one-page shop whose buy button is an experiment: Buy now vs Buy now · free shipping vs Buy now · arrives tomorrow, on self-hosted Flagsmith. The primary metric is checkout conversion; the guardrail is revenue per shopper. Shoppers are simulated, but each one is a real HTTP visitor going through the real Flagsmith SDK path: identity, variant assignment, $flag_exposure, trackEvent. Only the decision to buy is random. Hypothesis, design, results and the rollout decision are in docs/experiment.md.

How it fits together

flowchart LR
  subgraph VS Code
    S[Scanner<br/>flag reads, exposures, trackEvent] --> I[Insights<br/>diagnostics + decision rule]
    St[Store<br/>flags, experiments, metrics, results] --> I
    I --> UI[CodeLens · Hover · Problems · Results panel · Tree]
    C[Copilot<br/>Claude tool loop] --> O[Operations]
    UI --> O
    O --> A{Approval modal<br/>exact request / diff}
    A -->|approved| W[Flagsmith Admin + Experiments API<br/>workspace edit]
    A --> L[.petri/audit.jsonl]
  end
  W --> F[(Self-hosted Flagsmith<br/>EXPERIMENTATION_ENABLED)]
  App[Your app + Flagsmith SDK] -->|$flag_exposure, events| F
  F --> St
Loading
  • extension/src/api.ts: Flagsmith Admin API and Experiments API client. Every write is a PlannedRequest built first and sent only after approval.
  • extension/src/insights.ts: diagnostics and the decision rule. Pure logic, no vscode import, unit-tested.
  • extension/src/copilot/: the agent loop on the official @anthropic-ai/sdk, with 12 tools that go through the same Operations and approvals as the buttons.
  • extension/src/treatment.ts (lock, decision memory, planned stop), watch.ts (Watch), health.ts (scorecard, novelty, sequential test), plan.ts (pull requests, ramp), rehearse.ts: all pure or headless, shared by the extension, the CLI, the Action and the MCP server (check.ts, cli.ts, mcp.ts).

Flagsmith quirks Petri works around

We hit these while building and confirmed them on self-hosted Flagsmith. All three were already reported upstream:

  • Server SDKs send events to Flagsmith Cloud unless eventsApiUrl is set, even when apiUrl points at your own server (flagsmith-nodejs-client#332). Petri flags it as PETRI012 and the copilot fixes it.
  • A partial PATCH …/mv-options/{id}/ returns 500 KeyError: 'feature' (Flagsmith#9119). Petri sends a full PUT instead.
  • The sample-ratio-mismatch p-value stays null for a running experiment, because starting it sets the flag's default weights to 0 (Flagsmith#9128). A tool that trusts it never sees a broken split. Petri then runs its own chi-square test of exposures against the configured split, so the decision rule's SRM guard still works. We added our three-arm reproduction and this workaround to the issue.

Development

cd extension
npm ci
npm run typecheck && npm test && npm run build   # 83 tests: every diagnostic, the decision rule and stats, Watch, health, the lock, plans, the approval policy, the CLI and MCP server

Press F5 in VS Code with the extension/ folder open to launch a development host. See CONTRIBUTING.md for the rules every change follows (no write without approval, no claim the data doesn't support) and how to add a diagnostic.

License

MIT. The self-hosted Compose file is derived from Flagsmith's (BSD-3-Clause); see NOTICE.

Built for Toggle Wars (WeMakeDevs × Flagsmith, November 2026).

About

Run Flagsmith experiments where the code lives: VS Code extension + AI copilot + CI check for self-hosted Flagsmith. Catch silent A/B-test failures, read honest results inline, ship the winner and delete the losing code.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages