Skip to main content
Glama
README.md
# FlagGraph

[![CI](https://github.com/SaumoPal97/flaggraph/actions/workflows/ci.yml/badge.svg)](https://github.com/SaumoPal97/flaggraph/actions/workflows/ci.yml)
[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)

**Find stale feature flags, see exactly what their removal deletes, and let a coding agent clean them up safely, using a code graph in [Relate](https://github.com/relatedb/relate).**

**Try it on any public repo, nothing to install:** put `saumopal97.github.io/flaggraph/` in front of a GitHub URL, for example
[saumopal97.github.io/flaggraph/github.com/Unleash/unleash/tree/main/frontend/src](https://saumopal97.github.io/flaggraph/github.com/Unleash/unleash/tree/main/frontend/src),
or open the [web app](https://saumopal97.github.io/flaggraph/) and use **Set up**. The code is fetched from GitHub, parsed with tree-sitter and analysed by Relate, all compiled to WebAssembly and running in your tab.

Feature flags are how teams ship safely: wrap a feature in `if (flags.isEnabled("new-checkout"))`, roll it out, roll back if it breaks. After the rollout, the flag and the dead code path behind it usually stay in the codebase for good. Uber [wrote about this](https://www.uber.com/us/en/blog/ai-code-cleanup/): their in-house AutoClean has removed more than 16,000 stale flags and over 1,000,000 lines of code.

Their post names the hard part. Replacing the flag call with `true` is mechanical. Deciding what else can go is not, because the value travels

```
flag  ->  config field  ->  call argument  ->  parameter  ->  if / ternary / && / early return  ->  code only that branch used
```

and any other caller along the way can keep code alive. Those are graph questions, so FlagGraph builds the graph, for any team, with any flag tool.

## Built on Relate

Relate does the work everywhere FlagGraph runs. The analysis is written once, as Cypher, and runs unchanged on three Relate surfaces:

| Where | Relate surface | What happens there |
|---|---|---|
| **Your browser** ([web app](https://saumopal97.github.io/flaggraph/)) | `@relate/relate-wasm` | Build the graph of a GitHub repo or local folder, plan every flag, draw value flows, run your own Cypher. The **Under the hood** page shows the pipeline timings and a live log of every query Relate ran. |
| **Your machine** (`flaggraph` CLI) | `relate-db`, embedded in Python | Index local code (uncommitted changes included) into one `.flaggraph/graph.rl` file, plan, and **verify** cleanups by diffing graphs. |
| **Your coding agent** | MCP server over the embedded store | Any MCP client (Cursor, Copilot, Codex, Claude Code, …) queries the same graph while it edits, then verifies its own work. |

The browser engine ([`viewer/engine/`](viewer/engine/)) and the CLI engine ([`flaggraph/`](flaggraph/)) produce identical plans; [`tests/test_parity.py`](tests/test_parity.py) checks every field of every plan, and the two agree on all 84 flags of the Unleash run. Relate features in use: embedded in-process queries, single-file stores, variable-length paths (`[:FLOWS_TO*0..12]`), `all()`/`any()` list predicates over relationship lists, `UNWIND` batch writes, multi-type patterns (`[:CALLS|REFERENCES]`), `UNION`, and the WebAssembly build.

## Where it runs

| | Web app (browser) | CLI | Coding agent |
|---|---|---|---|
| **Use it to** | analyse a public GitHub repo or a local folder, rank stale flags, read plans, try what-ifs, query | index local code, plan, verify, run in CI | edit the code and verify the edit |
| **Install** | none | `pip install "git+https://github.com/SaumoPal97/flaggraph"` | `flaggraph setup` (any MCP client) |
| **Your code goes** | GitHub (or your disk) → your tab, nowhere else | nowhere | to the model provider your agent uses |

## What it does

| | |
|---|---|
| **Set up** (web app) | Point at a GitHub URL or local folder; the flag SDK and in-house flag functions (`useUiFlag`, …) are detected; add flag state from your provider or work code-only; pick how your agent connects. |
| `flaggraph stale` | Flags that serve one value and have not changed in 30+ days, ranked by how much dead code their removal deletes, with owning teams. Also flags read in code but deleted from the flag service, and flags nothing reads. |
| `flaggraph plan <flag>` | The removal plan: what to inline, which branch dies, which parameters and config fields go, which functions lose their last caller, which tests change, and what blocks a full cleanup. `--assume true` plans a retirement before you flip the switch (and is how code-only mode works). |
| `flaggraph verify <flag> --after <repo>` | Re-indexes the changed code and checks it against the original graph, deterministically ([below](#verification-without-an-llm)). |
| `flaggraph setup` | Registers FlagGraph's MCP server with your coding agents, auto-detected ([below](#use-it-from-your-coding-agent)). |
| `flaggraph import <provider> export.json` | Converts a LaunchDarkly, GrowthBook or Unleash export into `flags.json`. |
| `flaggraph mcp` | The MCP server: `stale_flags`, `cleanup_plan`, `function_context`, `verify_cleanup`, `graph_query`. |

## Try it in two minutes

Python 3.11+. No server, no account, no API key.

```bash
git clone https://github.com/SaumoPal97/flaggraph && cd flaggraph
python3 -m venv .venv && . .venv/bin/activate
pip install -e .

flaggraph --repo examples/acme-shop index
flaggraph --repo examples/acme-shop stale
flaggraph --repo examples/acme-shop plan new-checkout-pipeline
flaggraph --repo examples/acme-shop plan legacy-tax-engine
```

The same web app as the live demo, locally: `make viewer`, then open http://127.0.0.1:8765.

No flag-service export? Delete `flags.json` (or never write one) and FlagGraph works **code-only**: it finds every flag read and plans any retirement with `plan <flag> --assume true|false`.

`examples/acme-shop` is a small TypeScript store with eight flags and the hard cases on purpose:

* **`new-checkout-pipeline`** is Uber's example: read in `loadConfig`, stored in `cfg.useNewPipeline`, passed into `processOrder(order, useNewPipeline)`. But the support tool `replayOrder` also calls `processOrder` with `!forceLegacy`, so a grep-and-delete would remove a pipeline support still uses. FlagGraph inlines the flag, drops the config field, and keeps the parameter, naming the caller that blocks it.
* **`legacy-tax-engine`** has served `false` for 229 days. Its branch dies, and so do `legacyTax` and `roundCents`, which only that branch called: 11 lines and a test file to update.
* **`recommendations-v2`** passes through two parameters before its `if`; both parameters go.
* **`search-autocomplete`** was deleted from the flag service but is still read in code, so it always gets its fallback.
* **`one-click-reorder`** (50% A/B test) and **`holiday-promo-2026`** (rolled out 5 days ago) are left alone.

## Real-world run: the Unleash frontend

[Unleash](https://github.com/Unleash/unleash)'s own web UI reads its feature flags with `useUiFlag('…')`: 4,877 TypeScript files with React components, hooks, lazy-loaded modules and path aliases. FlagGraph indexes it in about **5 seconds**. In a what-if run (each flag retired at its open-source default), the plans were checked line by line against the source; for example, finishing the `singlePageStrategyForm` rollout (`--assume true`) deletes the legacy form path, 879 lines across 26 files, correctly telling apart two different components that are both called `FeatureStrategySegment`. Details, numbers and how to reproduce: [`examples/unleash`](examples/unleash/).

## Works with your flag tool

**Reading flags in code.** Calls of the form `name("flag-key", fallback?)` are recognised for the common SDKs out of the box: Unleash (`isEnabled`, `useFlag`), LaunchDarkly (`boolVariation`, `variation`), GrowthBook (`isOn`, `useFeatureIsOn`), PostHog (`isFeatureEnabled`, `useFeatureFlagEnabled`), Statsig (`checkGate`), OpenFeature (`getBooleanValue`, `useBooleanFlagValue`) and Flagsmith (`hasFeature`). Your own wrapper is one setting away:

```toml
# .flaggraph.toml in the repo root
accessors = ["useUiFlag"]          # added to the built-in list
include = ["frontend/src"]          # folders to index (default: everything)
flags = "flags.json"
stale_days = 30
```

In the web app, **Set up** detects the SDK from `package.json` and imports, and suggests in-house wrappers it sees called with flag-like keys (on Unleash's own frontend it finds `useUiFlag` by itself).

**Flag state.** FlagGraph needs, per flag, whether it is on, the value everyone gets (if only one) and when it last changed. Export it from your provider's API and convert it (or upload the export on the Set up page; the format is detected):

```bash
curl -H "Authorization: $LD_API_KEY" "https://app.launchdarkly.com/api/v2/flags/default?env=production" > ld.json
flaggraph import launchdarkly ld.json --environment production      # also: growthbook, unleash
```

The converters follow each provider's documented API shape and are covered by fixture tests; anything they cannot classify (targeting rules, partial rollouts) is treated as still varying and never cleaned up. Any other source works too: write `flags.json` in the format of [`examples/acme-shop/flags.json`](examples/acme-shop/flags.json).

## Use it from your coding agent

FlagGraph is a standard [MCP](https://modelcontextprotocol.io) server, so any agent that supports MCP can use it. Nothing in FlagGraph calls an LLM: indexing, planning and verification are deterministic. The agent only does the typing, and the server hands it the workflow (plan, check callers, edit, verify) when it connects.

```bash
pip install "git+https://github.com/SaumoPal97/flaggraph"
cd your-repo
flaggraph setup          # detects Cursor, VS Code and Claude Code and registers the server in this project
flaggraph index
```

Then ask your agent: *"Use the flaggraph tools to find the stalest feature flag, remove it by its plan, and verify it."*

| Agent | How |
|---|---|
| Any MCP client | `{"mcpServers": {"flaggraph": {"command": "flaggraph", "args": ["--repo", "/path/to/repo", "mcp"]}}}` |
| Cursor | `flaggraph setup cursor` → `.cursor/mcp.json` |
| VS Code (Copilot agent mode) | `flaggraph setup vscode` → `.vscode/mcp.json` |
| Codex CLI | `flaggraph setup codex` → `~/.codex/config.toml` (global, backed up first) |
| Windsurf | `flaggraph setup windsurf` → `~/.codeium/windsurf/mcp_config.json` (global, backed up first) |
| Claude Code | `flaggraph setup claude-code` (also adds a `flag-cleanup` skill), or the plugin: `/plugin install flaggraph --marketplace SaumoPal97/flaggraph` |
| Claude Desktop | `flaggraph setup claude-desktop` (global, backed up first) |
| No agent | Copy the plan or the agent prompt from the web app and follow it by hand |

Global configs are only changed when you name that agent; `flaggraph setup` on its own touches project files only.

**Continuous cleanup, AutoClean style.** `flaggraph setup claude-code --github-action` adds an example [workflow](flaggraph/templates/flaggraph-cleanup.yml): every week it picks the stale flag with the most dead code, lets an agent remove it, runs `flaggraph verify`, and opens a pull request with the plan and the checks. The example's editing step uses `anthropics/claude-code-action`; the FlagGraph steps around it are agent-neutral, so that one step can be swapped for another agent's action.

## How the graph works

`flaggraph index` parses every `.ts`/`.tsx` file with tree-sitter and follows boolean values through variables, object-literal config fields, call arguments and parameters, and records every `if`, ternary, `&&` guard and early return they decide. It writes one Relate store (`.flaggraph/graph.rl`):

```
(:Flag)-[:FLOWS_TO]->(:ConfigField)-[:FLOWS_TO]->(:Param)-[:GUARDS]->(:Branch)-[:IN]->(:Function)
(:Function)-[:READS_FLAG]->(:Flag)            (:Function)-[:CALLS|REFERENCES {arms}]->(:Function)
(:Function)-[:READS_FIELD]->(:ConfigField)    (:Param)-[:PARAM_OF]->(:Function)
(:File)-[:DEFINES]->(:Function)               (:File)-[:OWNED_BY]->(:Team)          (from CODEOWNERS)
(:File)-[:MENTIONS_FLAG]->(:Flag)             (test files that set a flag)
```

Plans are Cypher over that graph. "Follow the value":

```cypher
MATCH p = (:Flag {key: $key})-[:FLOWS_TO*0..12]->(x)-[:GUARDS]->(b:Branch)-[:IN]->(fn:Function)
RETURN [n IN nodes(p) | coalesce(n.name, n.key)] AS flow, b.condition, fn.name
```

"Which functions lose their last caller once the dead branches go" (iterated until nothing changes):

```cypher
MATCH (c:Function)-[k:CALLS|REFERENCES]->(g:Function) WHERE NOT c.is_test
WITH g, collect({caller: c.id, arms: k.arms}) AS calls
WHERE all(x IN calls WHERE x.caller IN $dead_callers OR any(a IN x.arms WHERE a IN $dead_arms))
RETURN g
```

## Verification without an LLM

Uber's AutoClean sends each diff through one reviewer agent per correctness property. Several of those properties are graph questions, so FlagGraph answers them deterministically by comparing the graph before and after the change:

| Check | Fails when |
|---|---|
| `flag_removed` | code or tests still read or set the flag |
| `other_flags_intact` | any other flag is read more or less often than before (intent drift) |
| `stays_in_scope` | a changed or deleted function is outside the flag's blast radius |
| `no_new_functions` | the cleanup added code |
| `no_constant_params` | a parameter is left that every caller sets to the same literal |
| `no_constant_branches` | `if (false)` or `true ? a : b` is left behind |
| `no_new_orphans` | a function lost all its callers but was not deleted |
| `planned_deletions` | functions the plan said would die still exist (warning) |

A sloppy cleanup of `legacy-tax-engine` that also "tidied" another flag, left `if (false)` behind and kept the dead helper fails three checks and warns on a fourth; the correct cleanup passes all eight (`tests/test_verify.py`).

## Limitations

A focused flow analysis, not a type checker ([ADR-0003](docs/adr/0003-static-analysis-scope.md)). It follows boolean flag values through the shapes above in TypeScript/TSX; values passed through classes, stored closures or dynamic property access are not followed yet, and other languages are not supported yet. Anything it cannot follow becomes a blocker in the plan, never a guess.

## Development

```bash
pip install -e ".[dev]"
make check          # ruff lint + format check + pytest (CI runs it on Linux, macOS and Windows)
cd tests/parity && npm install   # enables the browser-vs-CLI parity tests
```

Conventions follow Relate's: [Keep a Changelog](CHANGELOG.md) with change fragments in [`.changes/`](.changes/README.md), decision records in [`docs/adr/`](docs/adr/), CI with a fresh-install smoke test, tag-driven releases. See [CONTRIBUTING.md](CONTRIBUTING.md).

## Built with

Relate (graph, as a Python library and as WebAssembly), tree-sitter + tree-sitter-typescript (parsing, natively and as WebAssembly), rich (terminal), the MCP Python SDK. Inspired by Uber's AutoClean write-up; no Uber code is used. The Unleash run analyses Unleash's public source; nothing from it is copied here.

**AI assistance:** built with substantial help from Claude (Anthropic) via Claude Code, for design discussion, code generation and testing. All code was reviewed and run by the author.

## License

Apache-2.0