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.
StarkWEB
The foundation. Every web app starts here.
api-route.tsAPI Route4 frameworksValidation, 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)
}service.tsService4 frameworksBusiness logic, ownership checks, typed errors.
export class ProjectService {
async create(data: CreateInput): Promise<Project> {
// ownership check, validation, persist
}
}component.tsxComponent4 frameworksLoading, 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>
}middleware.tsMiddleware4 frameworksAuth, 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)
}
}error-handling.tsError Handling4 frameworksCanonical error strategy — single source of truth.
export class ApiError extends Error {
constructor(
public code: ErrorCode,
message: string,
public status: number = 500
) { super(message) }
}job-queue.tsJob Queue4 frameworksBackground 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) }
}multi-tenant.tsMulti-Tenant4 frameworksWorkspace scoping, tenant isolation, role-based access.
export function scopedQuery<T>(workspace: string) {
return db.query<T>()
.where('workspace_id', workspace)
// tenant isolation enforced
}sse-endpoint.tsSSE EndpointNext.jsServer-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`)
}
})
}third-party-script.tsThird-Party ScriptTypeScriptExternal 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';
}combobox.tsxCombobox2 frameworksAccessible 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
}design-tokens.tsDesign TokensTypeScriptSemantic 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') }error-message-categorization.tsxError Message CategorizationReactCategorize 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'; /* ... */ }
}MOBILE
Take the forge mobile.
mobile-screen.tsxMobile ScreenReact NativeReact Native screen with safe area, Dynamic Type, and 4 states.
export function ProfileScreen() {
const insets = useSafeAreaInsets()
const { data, error, loading } = useProfile()
if (loading) return <ScreenSkeleton />
}mobile-service.tsMobile ServiceReact NativeOffline-first data with sync queue, conflict resolution, and retry.
export class OfflineService {
async read(id: string) {
return localStore.get(id) ?? await api.fetch(id)
}
}GAME
Real-time. Frame-perfect.
game-loop.tsGame LoopTypeScriptFixed-timestep game loop with interpolation, pause/resume, and frame budgets.
class GameLoop {
tick(dt: number) {
this.accumulator += dt
while (this.accumulator >= STEP) {
this.update(STEP)
}
}
}game-state.tsGame StateTypeScriptHierarchical state machine with enter/exit hooks, history, and save/load.
class StateMachine {
transition(to: string) {
this.current.exit()
this.current = this.states[to]
this.current.enter()
}
}game-entity.tsGame Entity (ECS)TypeScriptEntity Component System with component stores, systems, and object pooling.
class World {
createEntity(): number {
return this.nextId++
}
addComponent<T>(entity: number, type: string, data: T) {
this.stores[type].set(entity, data)
}
}SYSTEMS
Infrastructure that runs itself.
ad-platform-adapter.tsAd Platform AdapterTypeScriptSplit 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>
}financial-transaction.tsFinancial TransactionTypeScriptBranded 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;
}daemon-process.tsDaemon ProcessTypeScriptPID 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());
}
}revenue-source-adapter.tsRevenue Source AdapterTypeScriptRead-only revenue interface with Stripe + Paddle reference implementations.
interface RevenueAdapter {
getTransactions(since: Date): Promise<Transaction[]>
getBalance(): Promise<Cents>
getSubscriptionMRR(): Promise<Cents>
}oauth-token-lifecycle.tsOAuth Token LifecycleTypeScriptRefresh at 80% TTL, failure escalation, vault integration.
class TokenManager {
async getToken(): Promise<string> {
if (this.shouldRefresh()) await this.refresh();
return this.accessToken;
}
}outbound-rate-limiter.tsOutbound Rate LimiterTypeScriptToken bucket for external API calls with per-platform limits.
class RateLimiter {
async acquire(): Promise<void> {
while (this.tokens <= 0) {
await this.waitForRefill();
}
this.tokens--;
}
}database-migration.tsDatabase MigrationTypeScriptSafe 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);data-pipeline.tsData PipelineTypeScriptETL pipeline: typed stages, checkpoint/resume, quality checks.
const pipeline = new Pipeline([
extract(source),
validate(schema),
transform(normalize),
load(destination),
]);
await pipeline.run({ checkpoint: true });backtest-engine.tsBacktest EngineTypeScriptWalk-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);execution-safety.tsExecution SafetyTypeScriptTrading execution: order validation, position limits, paper/live toggle.
const order = validateOrder({
symbol: 'BTC/USDT',
side: 'buy',
size: 0.1,
}, exchangeRules);
await executor.submit(order);e2e-test.tsE2E Test2 frameworksPlaywright 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);
});browser-review.tsBrowser Review2 frameworksBrowser 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() };
}stablecoin-adapter.tsStablecoin Adapter2 frameworksStablecoin off-ramp: Circle USDC adapter, transfer lifecycle, settlement.
interface StablecoinAdapter {
getBalance(): Promise<BalanceCents>;
initiateOfframp(amount: Cents): Promise<Transfer>;
getTransferStatus(id: string): Promise<TransferState>;
}ad-billing-adapter.tsAd Billing Adapter2 frameworksAd platform billing: invoice reads, debit tracking, spend projection.
type BillingCapability =
| 'FULLY_FUNDABLE'
| 'MONITORED_ONLY'
| 'UNSUPPORTED';
interface AdBillingAdapter {
classifyBilling(): Promise<BillingCapability>;
getInvoices(): Promise<Invoice[]>;
}funding-plan.tsFunding Plan2 frameworksTreasury funding pipeline: state machine, policy engine, rebalancing.
type FundingPlanState =
| 'DRAFT' | 'APPROVED'
| 'EXECUTING' | 'SETTLED' | 'FAILED';
interface FundingPlan {
id: string;
state: FundingPlanState;
amountCents: Cents;
reason: string;
}kongo-integration.tsKongo Integration2 frameworksLanding 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;
}audit-log.tsAudit LogTypeScriptSystem-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' },
});deploy-preflight.tsDeploy PreflightTypeScriptPre-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.
multi-tenant-pool-bypass.tsMulti-Tenant Pool BypassTypeScriptContextVar 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));
});multi-tenant-property-test.tsMulti-Tenant Property TestTypeScriptProperty-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 */ },
));
});nginx-vhost.confNginx VhostNginxCloudflare-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;post-deploy-probe.shPost-Deploy ProbeBashPost-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
rls-test-fixture.pyRLS Test FixturepytestThe 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")structural-sql-sentinel.pyStructural SQL SentinelpytestAdversarial-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}'"AI
The intelligence layer.
ai-orchestrator.tsAI OrchestratorTypeScriptAgent 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
}
}ai-classifier.tsAI ClassifierTypeScriptClassification 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);
}ai-router.tsAI RouterTypeScriptIntent-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);
}prompt-template.tsPrompt TemplateTypeScriptVersioned prompts with variable injection, testing.
const template = new PromptTemplate({
version: '1.2',
text: 'Classify this {{category}}: {{input}}',
variables: ['category', 'input'],
});ai-eval.tsAI EvalTypeScriptGolden 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);ai-tool-schema.tsAI Tool SchemaTypeScriptType-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),
});ai-prompt-safety.tsAI Prompt SafetyTypeScriptType 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',
};llm-state-dedup.tsLLM State DedupTypeScriptLLM-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();
DISCIPLINE
Engineering discipline. The shapes that keep work shippable.
adr-verification-gate.mdADR Verification GateReferenceFixture 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">
refactor-extraction.mdRefactor Extraction (8-commit per-entity)ReferencePer-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 |
autonomous-ops-triage-policy.mdAutonomous Ops Triage PolicyReference4-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
codemod-hygiene.mdCodemod HygieneReferenceAfter 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.