Skip to main content

CODE PATTERNS

53 reference implementations. Match these shapes when you write.

These aren't suggestions. They're battle-tested shapes that every agent knows how to read. Write your code to match these patterns and the whole team can review, test, and extend it without asking what you meant.

Stark avatarStark
53 patterns|14 with multi-framework tabs|6 domains

WEB

The foundation. Every web app starts here.

api-route.tsAPI Route4 frameworks

Validation, auth, service call, consistent response format.

export async function POST(req: NextRequest) {
  const body = schema.parse(await req.json())
  const result = await service.create(body)
  return NextResponse.json(result)
}
View with framework tabs →
service.tsService4 frameworks

Business logic, ownership checks, typed errors.

export class ProjectService {
  async create(data: CreateInput): Promise<Project> {
    // ownership check, validation, persist
  }
}
View with framework tabs →
component.tsxComponent4 frameworks

Loading, empty, error, success states. Keyboard accessible.

export function ProjectList({ projects }: Props) {
  if (!projects) return <Skeleton />
  if (projects.length === 0) return <Empty />
  return <ul role="list">...</ul>
}
View with framework tabs →
middleware.tsMiddleware4 frameworks

Auth, request logging, rate limiting.

export function withAuth(handler: Handler) {
  return async (req: NextRequest) => {
    const session = await getSession(req)
    if (!session) return unauthorized()
    return handler(req, session)
  }
}
View with framework tabs →
error-handling.tsError Handling4 frameworks

Canonical error strategy — single source of truth.

export class ApiError extends Error {
  constructor(
    public code: ErrorCode,
    message: string,
    public status: number = 500
  ) { super(message) }
}
View with framework tabs →
job-queue.tsJob Queue4 frameworks

Background jobs: idempotency, retry, dead letter queue.

export async function processJob(job: Job) {
  if (await isProcessed(job.id)) return // idempotent
  try { await execute(job) }
  catch { await retry(job) }
}
View with framework tabs →
multi-tenant.tsMulti-Tenant4 frameworks

Workspace scoping, tenant isolation, role-based access.

export function scopedQuery<T>(workspace: string) {
  return db.query<T>()
    .where('workspace_id', workspace)
    // tenant isolation enforced
}
View with framework tabs →
sse-endpoint.tsSSE EndpointNext.js

Server-Sent Events: lifecycle, keepalive, timeout, and React hook.

export function GET(req: NextRequest) {
  const stream = new ReadableStream({
    start(controller) {
      const send = (data: string) =>
        controller.enqueue(`data: ${data}\n\n`)
    }
  })
}
View full pattern →
third-party-script.tsThird-Party ScriptTypeScript

External script loading with 3 states: loading, ready, error.

type ScriptState = 'loading' | 'ready' | 'error';

function loadScript(src: string) {
  const el = document.createElement('script');
  el.onload = () => state = 'ready';
  el.onerror = () => state = 'error';
}
View full pattern →
combobox.tsxCombobox2 frameworks

Accessible combobox with value source management, keyboard nav, async search.

function useCombobox<T>(options: ComboboxOptions<T>) {
  const [isOpen, setIsOpen] = useState(false)
  const [query, setQuery] = useState("")
  // Two value sources: display vs search
}
View with framework tabs →
design-tokens.tsDesign TokensTypeScript

Semantic color/type tokens with one indirection layer, so a theme pivot is a token change, not a component-wide find-replace.

const tokenColor = (role) => `var(--vf-color-${role.replace(/[.\s]+/g, '-')})`
// component references SEMANTIC tokens only — never a hex, never a pixel literal
style = { background: tokenColor('accent'), color: tokenColor('text.on-accent') }
View full pattern →
error-message-categorization.tsxError Message CategorizationReact

Categorize errors at the UI boundary (network / auth / validation / server / quota / unknown) before choosing copy, so users see actionable messages, not raw internals.

export function classify(err: NormalizedError): ErrorCategory {
  if (err.isNetworkError) return 'network'
  if (QUOTA_CODES.has((err.code ?? '').toLowerCase())) return 'quota'
  switch (err.status) { case 402: return 'quota'; case 401: return 'auth'; /* ... */ }
}
View full pattern →

SYSTEMS

Infrastructure that runs itself.

ad-platform-adapter.tsAd Platform AdapterTypeScript

Split interface: setup (interactive) + runtime adapter + read-only daemon.

interface AdPlatformAdapter {
  createCampaign(config: CampaignConfig): Promise<Campaign>
  getCampaignMetrics(id: string): Promise<Metrics>
  pauseCampaign(id: string): Promise<void>
}
View full pattern →
financial-transaction.tsFinancial TransactionTypeScript

Branded Cents type, hash-chained append log, atomic writes, per-project path resolution.

type Cents = number & { __brand: "cents" };
function toCents(dollars: number): Cents {
  return Math.round(dollars * 100) as Cents;
}
View full pattern →
daemon-process.tsDaemon ProcessTypeScript

PID management, Unix socket API, job scheduler, signal handling, per-project configuration.

class Daemon {
  async start() {
    this.writePid();
    this.startSocket();
    this.scheduleJobs();
    process.on("SIGTERM", () => this.shutdown());
  }
}
View full pattern →
revenue-source-adapter.tsRevenue Source AdapterTypeScript

Read-only revenue interface with Stripe + Paddle reference implementations.

interface RevenueAdapter {
  getTransactions(since: Date): Promise<Transaction[]>
  getBalance(): Promise<Cents>
  getSubscriptionMRR(): Promise<Cents>
}
View full pattern →
oauth-token-lifecycle.tsOAuth Token LifecycleTypeScript

Refresh at 80% TTL, failure escalation, vault integration.

class TokenManager {
  async getToken(): Promise<string> {
    if (this.shouldRefresh()) await this.refresh();
    return this.accessToken;
  }
}
View full pattern →
outbound-rate-limiter.tsOutbound Rate LimiterTypeScript

Token bucket for external API calls with per-platform limits.

class RateLimiter {
  async acquire(): Promise<void> {
    while (this.tokens <= 0) {
      await this.waitForRefill();
    }
    this.tokens--;
  }
}
View full pattern →
database-migration.tsDatabase MigrationTypeScript

Safe migrations: backward-compatible adds, batched ops, rollback.

// Safe column add: nullable first, backfill, constrain
await db.schema.alterTable('users', (t) => {
  t.string('email_verified').nullable();
});
await batchUpdate('users', setDefault);
View full pattern →
data-pipeline.tsData PipelineTypeScript

ETL pipeline: typed stages, checkpoint/resume, quality checks.

const pipeline = new Pipeline([
  extract(source),
  validate(schema),
  transform(normalize),
  load(destination),
]);
await pipeline.run({ checkpoint: true });
View full pattern →
backtest-engine.tsBacktest EngineTypeScript

Walk-forward backtesting: no-lookahead, slippage, metrics.

const engine = new BacktestEngine(strategy);
const result = await engine.run(historicalData, {
  slippage: 0.001,
  commission: 0.0005,
});
console.log(result.sharpeRatio);
View full pattern →
execution-safety.tsExecution SafetyTypeScript

Trading execution: order validation, position limits, paper/live toggle.

const order = validateOrder({
  symbol: 'BTC/USDT',
  side: 'buy',
  size: 0.1,
}, exchangeRules);
await executor.submit(order);
View full pattern →
e2e-test.tsE2E Test2 frameworks

Playwright E2E + axe-core a11y: page objects, auth helpers, network mocks, CWV measurement.

test('homepage loads and is accessible', async ({ page }) => {
  await page.goto('/');
  await expect(page.getByRole('heading')).toBeVisible();
  const results = await new AxeBuilder({ page }).analyze();
  expect(results.violations).toHaveLength(0);
});
View with framework tabs →
browser-review.tsBrowser Review2 frameworks

Browser intelligence: console errors, behavioral walkthroughs, a11y audit, visual inspection.

async function browserReview(page: Page) {
  const errors: string[] = [];
  page.on('console', m => {
    if (m.type() === 'error') errors.push(m.text());
  });
  await page.goto('/');
  return { errors, screenshot: await page.screenshot() };
}
View with framework tabs →
stablecoin-adapter.tsStablecoin Adapter2 frameworks

Stablecoin off-ramp: Circle USDC adapter, transfer lifecycle, settlement.

interface StablecoinAdapter {
  getBalance(): Promise<BalanceCents>;
  initiateOfframp(amount: Cents): Promise<Transfer>;
  getTransferStatus(id: string): Promise<TransferState>;
}
View with framework tabs →
ad-billing-adapter.tsAd Billing Adapter2 frameworks

Ad platform billing: invoice reads, debit tracking, spend projection.

type BillingCapability =
  | 'FULLY_FUNDABLE'
  | 'MONITORED_ONLY'
  | 'UNSUPPORTED';

interface AdBillingAdapter {
  classifyBilling(): Promise<BillingCapability>;
  getInvoices(): Promise<Invoice[]>;
}
View with framework tabs →
funding-plan.tsFunding Plan2 frameworks

Treasury funding pipeline: state machine, policy engine, rebalancing.

type FundingPlanState =
  | 'DRAFT' | 'APPROVED'
  | 'EXECUTING' | 'SETTLED' | 'FAILED';

interface FundingPlan {
  id: string;
  state: FundingPlanState;
  amountCents: Cents;
  reason: string;
}
View with framework tabs →
kongo-integration.tsKongo Integration2 frameworks

Landing page engine: authenticated client, from-PRD page generation, growth signal polling, webhook handlers.

interface KongoClientConfig {
  apiKey: string;     // ke_live_ prefix, vault-sourced
  baseUrl?: string;   // Default: https://kongo.io/api/v1
  rateLimitPerMinute?: number;
}
View with framework tabs →
audit-log.tsAudit LogTypeScript

System-event NULL trap resolution: schema relaxation vs sentinel + JSONB tag. Append-only invariants with hash-chained integrity.

// Pattern 2: sentinel + JSONB tag
await writeSystemAudit(db, {
  action: 'retention.sweep',
  resource_type: 'job',
  resource_id: jobId,
  decisions: { reason: 'scheduled' },
});
View full pattern →
deploy-preflight.tsDeploy PreflightTypeScript

Pre-deploy secret + sensitive-path scan. Catches credentials in env files, methodology paths reachable from CDN root, missing ignore patterns.

// CI step before wrangler/vercel/firebase:
// - run: npx tsx docs/patterns/deploy-preflight.ts ./dist
// Exits non-zero on any hit. Never auto-filters.
View full pattern →
multi-tenant-pool-bypass.tsMulti-Tenant Pool BypassTypeScript

ContextVar wrapper for cross-tenant lifespan/daemon code that runs outside the request lifecycle. Splits acquisition between tenant pool (RLS-enforced) and admin pool (cross-tenant).

await preOrgResolutionScope(async () => {
  const session = await db.query('SELECT org_id FROM sessions WHERE token = $1', [token]);
  return withTenant(session.org_id, () => handler(session));
});
View full pattern →
multi-tenant-property-test.tsMulti-Tenant Property TestTypeScript

Property-based isolation test: for any orgs A,B, A's writes never appear in B's reads. The test that survives every refactor.

test('writes by org A never appear in reads by org B', async () => {
  await fc.assert(fc.asyncProperty(
    fc.constantFrom(...readEndpoints),
    randomPayload(),
    async (endpoint, payload) => { /* leak check */ },
  ));
});
View full pattern →
nginx-vhost.confNginx VhostNginx

Cloudflare-Flexible-safe origin vhost: origin security header stack, ACME http-01 passthrough, per-tenant logs, and deliberately NO HTTP->HTTPS redirect to avoid the Flexible-SSL loop.

# Cloudflare Flexible: edge does HTTPS, this hop is HTTP.
# NO `return 301 https://...` here — it would loop.
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
location ^~ /.well-known/acme-challenge/ { root /var/www/acme; try_files $uri =404; }
proxy_set_header X-Forwarded-Proto https;
View full pattern →
post-deploy-probe.shPost-Deploy ProbeBash

Post-deploy health probe that asserts sensitive paths are NOT publicly served. Probes a denylist (.env, .git/config, methodology docs, SSH keys) against the live deploy URL and exits non-zero on any 200.

# DEPLOY_URL=https://example.com bash docs/patterns/post-deploy-probe.sh
# Probes a denylist against the LIVE deploy. Exits non-zero on any 200.
# LEAK  200  -> https://example.com/.env    ← rollback and fix the surface
# ok    404  -> https://example.com/.git/config
View full pattern →
rls-test-fixture.pyRLS Test Fixturepytest

The db_as_app SAVEPOINT fixture: run RLS-policy assertions under a NOSUPERUSER NOBYPASSRLS app role, not the Testcontainers SUPERUSER bootstrap role that silently bypasses FORCE RLS.

@pytest_asyncio.fixture
async def db_as_app(db):
    await db.execute("SAVEPOINT rls_test")
    try:
        await db.execute(f"SET LOCAL ROLE {APP_ROLE_NAME}")
        yield db
    finally:
        await db.execute("ROLLBACK TO SAVEPOINT rls_test")
View full pattern →
structural-sql-sentinel.pyStructural SQL Sentinelpytest

Adversarial-test discipline for SQL-shape sentinels. A fail-open regex must match every commuted, cast, IS NULL, and coalesce variant — and prove it can fail.

@pytest.mark.parametrize("form", POSITIVE_FORMS)
def test_sentinel_catches_fail_open_form(form: str) -> None:
    """Every known fail-open variant must trip the sentinel."""
    assert policy_is_fail_open(form), \
        f"SENTINEL GAP: form did not trip — '{form}'"
View full pattern →

AI

The intelligence layer.

ai-orchestrator.tsAI OrchestratorTypeScript

Agent loop, tool use, retry, circuit breaker, fallback.

async function agentLoop(messages: Message[]) {
  for (let i = 0; i < MAX_ITERATIONS; i++) {
    const response = await model.complete(messages);
    if (response.stopReason === 'end_turn') return;
    // Execute tool calls, append results
  }
}
View full pattern →
ai-classifier.tsAI ClassifierTypeScript

Classification with confidence thresholds, human fallback.

async function classify(input: string) {
  const { label, confidence } = await model.classify(input);
  if (confidence > 0.9) return autoAct(label);
  if (confidence > 0.7) return softAct(label);
  return humanReview(input);
}
View full pattern →
ai-router.tsAI RouterTypeScript

Intent-based routing with fallback chains.

const intents = ['create_order', 'check_status', 'cancel'] as const;

async function route(input: string) {
  const intent = await detectIntent(input, intents);
  return handlers[intent](input);
}
View full pattern →
prompt-template.tsPrompt TemplateTypeScript

Versioned prompts with variable injection, testing.

const template = new PromptTemplate({
  version: '1.2',
  text: 'Classify this {{category}}: {{input}}',
  variables: ['category', 'input'],
});
View full pattern →
ai-eval.tsAI EvalTypeScript

Golden datasets, scoring, regression detection.

const suite = new EvalSuite('classifier-v2', [
  { input: 'refund please', expected: 'refund' },
  { input: 'where is my order', expected: 'status' },
]);
await suite.run(classifyFn);
View full pattern →
ai-tool-schema.tsAI Tool SchemaTypeScript

Type-safe tool definitions with provider adapters.

const searchTool = defineTool({
  name: 'search',
  description: 'Search the knowledge base',
  parameters: z.object({ query: z.string() }),
  execute: async ({ query }) => search(query),
});
View full pattern →
ai-prompt-safety.tsAI Prompt SafetyTypeScript

Type A (instructions to the model, statistical) vs Type B (constraints on the tool, enforced). The distinction that prevents prompt-injection-by-design.

const AUTHORITY: InstructionTextControl = {
  type: 'instruction',
  text: 'Only execute approved commands.',
  defeatedBy: ['prompt injection', 'novel approval markers'],
};

const APPROVED: AllowlistConstraint = {
  type: 'constraint',
  enforcement: 'allowlist',
};
View full pattern →
llm-state-dedup.tsLLM State DedupTypeScript

LLM-emitted ids are display labels, not primary keys. Content-hash dedup with logical-key fallback for command-string drift.

// LLM emitted id varies across cycles for the same operation
// Dedup on content hash instead:
const key = shellCommandHash(proposal.command); // sha256 of canonical form
if (seen.has(key)) skipApproval();
View full pattern →

DISCIPLINE

Engineering discipline. The shapes that keep work shippable.

adr-verification-gate.mdADR Verification GateReference

Fixture Bindability discipline. Every ADR's verification gate must include 'Can the gate FAIL under this fixture?' Refactor-correctness is not fix-correctness.

## Verification Gate

**Fixture:** <data set or scenario>
**Can the gate FAIL under this fixture?** <yes/no + algebraic rationale>
**Fixture-bindability proof:** <one sentence>
**Rehearsed at:** <commit-sha or "not yet">
View full pattern →
refactor-extraction.mdRefactor Extraction (8-commit per-entity)Reference

Per-entity large-refactor template with IDOR matrix discipline. The shape that keeps cross-tenant boundaries intact during code reshuffles.

# Commit plan (one per entity + scaffold + cleanup)
| # | Commit | Cumulative LOC |
|---|--------|----------------|
| 1 | scaffold | 1861 |
| 2 | extract people | 1694 |
| 8 | cleanup | 597 |
View full pattern →
autonomous-ops-triage-policy.mdAutonomous Ops Triage PolicyReference

4-bucket model (self-resolving / runbook-safe / operator-approval / hard-never) plus a SessionStart hook visibility rule for ops-flavored projects.

Is the action on the forbidden list (D)?  -> log + alert, STOP
Has an approved runbook (B)?              -> execute runbook, log, STOP
Reversible + low blast + pre-authorized?  -> Bucket A: execute, log
otherwise                                 -> Bucket C: propose, wait
View full pattern →
codemod-hygiene.mdCodemod HygieneReference

After a jscodeshift/recast codemod, strip incidental reformatting so the diff shows only the semantic change.

# Hygiene procedure
1. Run the codemod on a clean tree.
2. Separate semantic hunks from reformatting hunks.
3. Revert incidental hunks (git checkout -p), re-apply only the semantic change.
4. OR run the formatter scoped to changed files BEFORE the codemod.
View full pattern →