The Complete Production SOP: How to Deploy and Run GrowthBook Open-Source Feature Flags & A/B Testing in Autonomous AI Agents
Step-by-step SOP to install and run GrowthBook Feature Flags & A/B Testing in Codex, Claude Code, and Cursor. Includes verified prompts, configs, and troubleshooting.
Technical Overview & Architectural Context
Autonomous coding agents frequently stumble when implementing feature flag architectures and experiment tracking. Without structured SOP boundaries, LLMs routinely hardcode experiment variants, miss vital exposure tracking callbacks, invent non-existent SDK parameters, or trigger rendering race conditions prior to flag hydration. These hallucinations break Bayesian experiment pipelines, contaminate telemetry warehouses, and introduce runtime flicker in client-facing applications. The GrowthBook Open-Source Feature Flags & A/B Testing skill establishes deterministic procedural constraints for autonomous agents. It enforces the exact lifecycle: instantiating the GrowthBook client with strict host and key bindings, configuring immutable tracking callbacks that log exposure events, pre-hydrating targeting attributes (such as user ID, company, or geo-location), and wrapping feature evaluations in resilient fallbacks. By restricting filesystem writes to workspace paths and keeping execution inside standard sandbox boundaries, this skill ensures zero telemetry leakage and reliable, production-ready experimentation code.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Skill Manifest Mounting & Discovery
Mount the SKILL.md specification into your project repository or global agent rules directory.
Agent runtimes such as Claude Code, Cursor, and Codex discover procedural capabilities via project-level or user-level skill folders. By mounting the GrowthBook skill into `.agents/skills/growthbook-ab-testing-feature-flags/SKILL.md` or `.cursor/rules/`, your agent automatically indexes the activation triggers ('run ab test growthbook', 'setup growthbook sdk', 'tracking callback growthbook') and strictly adheres to the execution SOP.
mkdir -p .agents/skills/growthbook-ab-testing-feature-flags && curl -fsSL https://askills.dev/api/skills/growthbook-ab-testing-feature-flags/raw -o .agents/skills/growthbook-ab-testing-feature-flags/SKILL.md---
name: "growthbook-ab-testing-feature-flags"
description: "Run statistically sound A/B tests and feature rollouts using self-hosted GrowthBook."
metadata:
author: "GrowthBook"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "run ab test growthbook"
- "setup growthbook sdk"
- "tracking callback growthbook"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Execution SOP
1. Initialize SDK: const gb = new GrowthBook({ apiHost, clientKey, trackingCallback }).
2. Load features: await gb.loadFeatures({ autoRefresh: true }).
3. Run experiment: const { value } = gb.run({ key: 'pricing-test', variations: ['Control', 'Variant A'] });
4. Send exposure event in trackingCallback to warehouse for automated statistical analysis.Place the SKILL.md in project-level `.agents/skills/` to allow version control alongside application source, ensuring every developer and CI agent accesses the identical experimentation SOP.
Do not grant shell_exec or elevated network access to the agent during feature flag insertion; all SDK configurations must operate strictly within workspace file editing boundaries.
SDK Dependency Installation & Secrets Configuration
Install official client libraries and declare GrowthBook environment variables securely.
Provide the runtime environment with the `@growthbook/growthbook` SDK and declare the client key and host endpoint in `.env.local`. Autonomous agents must reference process environment variables rather than hardcoding production keys into repository commits.
npm install @growthbook/growthbook && echo 'NEXT_PUBLIC_GROWTHBOOK_API_HOST="https://growthbook.internal.domain"
NEXT_PUBLIC_GROWTHBOOK_CLIENT_KEY="sdk-xyz123456789"' >> .env.localimport { GrowthBook } from '@growthbook/growthbook';
export const growthbook = new GrowthBook({
apiHost: process.env.NEXT_PUBLIC_GROWTHBOOK_API_HOST || 'https://growthbook.internal.domain',
clientKey: process.env.NEXT_PUBLIC_GROWTHBOOK_CLIENT_KEY || '',
enableDevMode: process.env.NODE_ENV !== 'production',
trackingCallback: (experiment, result) => {
// Telemetry pipeline ingestion (e.g., Segment, PostHog, or internal endpoint)
if (typeof window !== 'undefined' && (window as any).analytics) {
(window as any).analytics.track('Experiment Viewed', {
experimentId: experiment.key,
variationId: result.variationId,
value: result.value,
hashAttribute: experiment.hashAttribute || 'id',
});
}
},
});Use `enableDevMode: true` in local development so the agent can inspect the internal feature decision map via browser dev tools or console logs without spamming the telemetry warehouse.
Verify `.env.local` is present in `.gitignore`. Unchecked agents may accidentally commit staging GrowthBook client keys into public repositories.
Trigger Invocation & Targeted Experiment Implementation
Invoke the skill using tested natural language triggers to implement fullstack flag evaluation.
Trigger the autonomous agent with prompt triggers matching the frontmatter specification. The agent will read targeting attributes (such as user ID and tenant role), await feature initialization, and wrap UI elements or server logic in deterministic variation gates.
import React, { useEffect, useState } from 'react';
import { growthbook } from '@/lib/growthbook';
interface CheckoutPricingProps {
userId: string;
country: string;
}
export const CheckoutPricing: React.FC<CheckoutPricingProps> = ({ userId, country }) => {
const [ready, setReady] = useState(false);
useEffect(() => {
growthbook.setAttributes({ id: userId, country });
growthbook.loadFeatures({ autoRefresh: true })
.then(() => setReady(true))
.catch((err) => {
console.error('GrowthBook hydration failed:', err);
setReady(true);
});
}, [userId, country]);
if (!ready) return <div className="skeleton">Loading pricing tier...</div>;
const { value: tier } = growthbook.run({
key: 'checkout-pricing-model',
variations: ['monthly_flat', 'annual_discounted'],
});
return (
<div className="pricing-card">
<h3>Selected Plan: {tier === 'annual_discounted' ? 'Annual Saver (20% Off)' : 'Standard Monthly'}</h3>
</div>
);
};Ensure the agent invokes `growthbook.setAttributes()` prior to invoking `growthbook.run()` or evaluating feature rules to prevent misattributed salt hashing.
Avoid invoking `growthbook.run()` inside pure render cycles without setting user attributes, as this defaults hashing to anonymous sessions and fractures cohort data.
Automated Linting, Typecheck & Experiment Verification Gate
Execute automated self-healing checks and unit test assertions on feature flag branches.
Before accepting the agent's work, enforce a verification gate that asserts TypeScript strict compliance, checks for missing dependency hooks, and verifies that mocked experiments correctly evaluate both control and variant paths in unit tests.
npx tsc --noEmit && npm test -- --testPathPattern=growthbookimport { render, screen } from '@testing-library/react';
import { CheckoutPricing } from '../CheckoutPricing';
import { growthbook } from '@/lib/growthbook';
describe('CheckoutPricing A/B Test', () => {
afterEach(() => {
growthbook.destroy();
});
it('evaluates control variant properly', async () => {
growthbook.setForcedVariations({ 'checkout-pricing-model': 0 });
render(<CheckoutPricing userId="user_1" country="US" />);
expect(await screen.findByText(/Standard Monthly/i)).toBeInTheDocument();
});
it('evaluates discount variant properly', async () => {
growthbook.setForcedVariations({ 'checkout-pricing-model': 1 });
render(<CheckoutPricing userId="user_2" country="US" />);
expect(await screen.findByText(/Annual Saver/i)).toBeInTheDocument();
});
});Use `growthbook.setForcedVariations()` in agent-generated unit tests to test deterministic branch rendering without mocking complex network payloads.
Failing to invoke `growthbook.destroy()` between test suites will retain cached attributes and pollute downstream test assertions.
Real-World Scenario: Instrument New Onboarding Flow with GrowthBook Bayesian Experimentation
“Setup growthbook sdk in our Next.js dashboard app. Run ab test growthbook for the onboarding flow with key 'onboarding-redesign-2026'. Control is 'legacy_stepper' and Variant is 'interactive_canvas'. Configure tracking callback growthbook to emit Segment events, target users where 'betaTester' is true, and write unit tests for both variations.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent attempted to invoke gb.loadFeatures() against an unreachable self-hosted GrowthBook API URL or the runtime sandbox blocked external outbound network calls during build time.
growthbook.loadFeatures({ timeout: 2000, skipCache: false }).catch(() => console.warn('Using cached or fallback features due to network limitation'));Root Cause: The agent executed growthbook.run() or growthbook.isOn() before invoking growthbook.setAttributes() with the expected identity identifier.
growthbook.setAttributes({ id: currentUser.id, companyId: currentUser.companyId, country: currentUser.country });Frequently Asked Questions (GrowthBook Open-Source Feature Flags & A/B Testing SOP)
Q:Can I use GrowthBook Open-Source Feature Flags & A/B Testing across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the open SKILL.md specification. All modern runtimes (Codex, Claude Code CLI, Cursor IDE, Windsurf) parse the YAML frontmatter, execution triggers, and operational rules equivalently.
Q:How does GrowthBook Open-Source Feature Flags & A/B Testing prevent context window overflow during long agent sessions?
The skill provides tight procedural guardrails rather than massive code dumps. It restricts the agent to 4 focused implementation steps, enforces local typechecking, and leverages concise SDK utilities like setForcedVariations, eliminating hundreds of lines of speculative boilerplate.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a security score of 98/100. It requires read and write permissions only within the local workspace directory (`fs_write: 'workspace'`) and operates without elevated root or broad container access.
Ready to equip your autonomous agent with GrowthBook Open-Source Feature Flags & A/B Testing?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.