Skip to content
AGENT RESOURCE · 20 Feb 2026

Code Style Guide

Write for understanding, optimize for limited attention. I use some version of this guide in most of my projects, to help keep them LLM and human friendly.

READ
20 min read
WORDS
3920
BUILD
20 Feb 2026
code stylesoftware engineeringbest practicestypescript
§ 01

Introduction

Core Principle: Context is finite. Every token — code, comment, structure — competes for limited attention. Maximize signal, minimize noise. Write for two audiences: humans with limited working memory and AI agents with bounded context windows.

§ 02

Philosophy

The optimal code is the minimum necessary to solve the problem correctly. Every additional line is debt.

Progressive Disclosure: Structure code layer-by-layer. Readers grasp high-level flow immediately, drilling into details only when needed. File names indicate purpose. Directory structures mirror conceptual hierarchies. Function names describe behavior without reading implementation.

Self-Documenting: Names eliminate need for comments. Comments explain "why," never "what." If you chose algorithm A over B for subtle reasons, state that. If you're working around a library bug, explain it.

Aggressive Minimalism: Before adding code, ask: "Is this the simplest solution?" Before adding a comment: "Does this clarify something non-obvious?" Before introducing an abstraction: "Does this reduce complexity, or merely relocate it?"

AHA Over DRY: Avoid Hasty Abstractions. Wait for the 3rd duplication before extracting. The wrong abstraction is worse than duplication. Three similar lines of code is better than a premature abstraction.

§ 03

Progressive Disclosure

Structure every layer of your system so readers — human or agent — get the right level of detail at the right time. No one should need to read 2000 lines to understand what a module does.

The Zoom Principle

Code should work like a map: zoom out for the big picture, zoom in for street-level detail. Each zoom level should be self-sufficient.

text023 LN
1// Level 0: Directory structure tells you what exists
2src/
3├── authentication/ # "There's an auth system"
4├── orders/ # "There's an order system"
5├── payments/ # "There's a payment system"
6└── README.md # How they connect
7
8// Level 1: Index file tells you what it can do
9// authentication/index.ts
10export { authenticateUser } from './authenticate';
11export { refreshSession } from './sessions';
12export { revokeAccess } from './revoke';
13// No implementation visible — just capabilities
14
15// Level 2: Function signature tells you the contract
16async function authenticateUser(
17 credentials: UserCredentials,
18 db: Database,
19 clock: Clock
20): Promise<Result<AuthSession, AuthError>>
21
22// Level 3: Implementation tells you how
23// Only read this when you need to change the behaviour

File-Level Disclosure

Every file should answer "what is this?" in its first 10 lines. Implementation details belong below.

typescript028 LN
1// ✅ Top of file reveals purpose, contract, and shape
2/**
3 * Order Processing Pipeline
4 *
5 * Validates → enriches → prices → submits orders.
6 * Entry point: processOrder()
7 * Error strategy: Result types, no throws
8 */
9
10// Types first — the contract
11type ProcessOrderInput = { /* ... */ };
12type ProcessOrderResult = Result<Receipt, ProcessError>;
13
14// Public API second
15export async function processOrder(input: ProcessOrderInput): Promise<ProcessOrderResult> {
16 const validated = validateOrder(input);
17 if (!validated.ok) return validated;
18
19 const enriched = await enrichWithInventory(validated.value);
20 if (!enriched.ok) return enriched;
21
22 return submitOrder(enriched.value);
23}
24
25// Private helpers last — only read if you need to understand a specific step
26function validateOrder(input: ProcessOrderInput): Result<ValidatedOrder, ProcessError> {
27 // ...
28}
typescript009 LN
1// ❌ Implementation soup — must read everything to understand anything
2import { db } from '../globals';
3const RETRY_COUNT = 3;
4const BACKOFF_MS = 100;
5
6function helper1() { /* ... */ }
7function helper2() { /* ... */ }
8// 200 lines later...
9export function processOrder() { /* ... */ }

Documentation Disclosure

Match documentation depth to the reader's likely intent. Most readers want "what does this do?" — very few want "why did you choose bcrypt over argon2?"

text017 LN
1Level 1 — CLAUDE.md (5 seconds)
2 "This is an order processing API. Entry: src/api/server.ts"
3
4Level 2 — Module README (30 seconds)
5 "Orders go through validate → enrich → price → submit.
6 Uses Result types. Retries on transient failures."
7
8Level 3 — Section comments (2 minutes)
9 // ========================================
10 // PRICING ENGINE
11 // ========================================
12 // Applies tiered discounts, tax rules, and currency conversion.
13 // See: docs/pricing-model.md for business rules.
14
15Level 4 — Inline "why" comments (as needed)
16 // Using ceiling division here because partial units
17 // must be billed as full units per the SLA.

API & Type Disclosure

Public interfaces should be scannable summaries. Implementation types stay internal.

typescript015 LN
1// ✅ Public types: minimal, focused, scannable
2// orders/types.ts — what consumers need to know
3export type OrderSummary = {
4 id: OrderId;
5 status: OrderStatus;
6 total: Money;
7 itemCount: number;
8 createdAt: DateTime;
9};
10
11// orders/internal-types.ts — implementation detail
12// Not exported. Contains pricing breakdowns, audit trails,
13// intermediate computation states, retry metadata, etc.
14type OrderPricingContext = { /* ... */ };
15type OrderAuditEntry = { /* ... */ };

Disclosure Anti-Patterns

  • Premature depth: Putting implementation details in README files
  • Flat disclosure: 500-line files with no visual hierarchy or grouping
  • Inverted disclosure: Helpers at top, public API buried at bottom
  • Missing levels: Jumping from directory listing straight to inline comments with nothing in between
§ 04

Naming

The #1 impact on readability. Good names eliminate mental translation overhead.

text014 LN
1// ✅ Descriptive, unambiguous
2async function validateJsonAgainstSchema(
3 schema: ZodSchema,
4 input: string
5): Promise<ValidationResult>
6
7function calculateExponentialBackoff(
8 attemptNumber: number,
9 baseDelayMs: number
10): number
11
12// ❌ Vague, abbreviated
13async function valJson(s: any, i: string): Promise<any>
14function calcBackoff(n: number, d: number): number

Rules:

  1. Be specific: activeUsers not users, httpTimeoutMs not timeout
  2. Include units: delayMs not delay, maxRetries not max
  3. Avoid abbreviations: customer not cust, configuration not cfg
  4. Use domain language: Names from business domain, not technical abstractions
  5. Boolean prefixes: isValid, hasPermission, canEdit, shouldRetry
  6. Verbs for functions: validateEmailFormat() not checkEmail(), fetchActiveUsers() not getUsers()
§ 05

Function Design

Single Responsibility with Explicit Contracts

text014 LN
1// ✅ Self-contained, explicit dependencies, typed contract
2async function authenticateUser(
3 credentials: UserCredentials,
4 database: Database,
5 currentTime: DateTime
6): Promise<Result<AuthSession, AuthError>> {
7 // All dependencies visible in signature
8 // Return type reveals all possible outcomes
9}
10
11// ❌ Hidden dependencies, unclear contract
12async function auth(data: any): Promise<any> {
13 // Uses global config, modifies global state
14}

Guard Clauses Over Nesting

Handle edge cases first, keep the happy path unindented and visible.

text020 LN
1// ✅ Guard clauses — happy path clear
2function processOrder(order: Order): Result<Receipt, ProcessError> {
3 if (!order) return err('missing_order');
4 if (order.items.length === 0) return err('empty_order');
5 if (order.total <= 0) return err('invalid_total');
6 if (!order.paymentMethod) return err('missing_payment');
7
8 return ok(completePayment(order));
9}
10
11// ❌ Nested conditions — happy path buried
12function processOrder(order: Order) {
13 if (order) {
14 if (order.items.length > 0) {
15 if (order.total > 0) {
16 // Happy path buried 4 levels deep
17 }
18 }
19 }
20}

Design Rules

  1. Single responsibility — describable in one sentence
  2. Explicit dependencies — all inputs as parameters, no hidden global state
  3. Type everything — TypeScript strict mode, Python type hints
  4. Self-contained context units — comprehensible without reading other files
  5. 50-line guideline — not a hard limit, but a refactoring trigger
§ 06

Error Handling

Result Types — Make Errors Explicit

Errors belong in function signatures, not hidden behind throw.

text019 LN
1type Result<T, E> =
2 | { ok: true; value: T }
3 | { ok: false; error: E };
4
5type UserError = 'not_found' | 'unauthorized' | 'network_failure';
6
7async function fetchUser(id: string): Promise<Result<User, UserError>> {
8 // Errors are part of the contract
9}
10
11// Usage forces error handling — compiler catches missing cases
12const result = await fetchUser(userId);
13if (!result.ok) {
14 switch (result.error) {
15 case 'not_found': return show404();
16 case 'unauthorized': return redirectLogin();
17 case 'network_failure': return showRetry();
18 }
19}

When to use Result types: API calls, file I/O, validation, any complex error path. When to use exceptions: Truly exceptional/unrecoverable situations (out of memory, corrupted state).

Branded Types — Validate at Boundaries

text011 LN
1type ValidatedEmail = string & { readonly __brand: 'ValidatedEmail' };
2type UserId = string & { readonly __brand: 'UserId' };
3
4function validateEmail(input: string): ValidatedEmail | null {
5 return isValidEmail(input) ? (input as ValidatedEmail) : null;
6}
7
8// Type system prevents using unvalidated data
9function sendEmail(to: ValidatedEmail, subject: string) {
10 // No need to re-validate — type guarantees validity
11}

Once you have a ValidatedEmail, downstream functions carry zero validation overhead. The type system encodes the knowledge that validation occurred.

Error Principles

  1. Never silently swallow errors — log or propagate, never ignore
  2. Fail fast at boundaries — validate inputs immediately, not deep in call stack
  3. Provide actionable messages — what failed, expected vs actual, how to fix
text009 LN
1// ✅ Actionable error with context
2throw new ValidationError(
3 `Email validation failed for "user_email": ` +
4 `Expected "name@domain.com", received "${input}". ` +
5 `Use validateEmailFormat() to check before calling.`
6);
7
8// ❌ Opaque
9throw new Error("Validation failed");
§ 07

File & Module Organization

Structure with Clear Boundaries

text027 LN
1// ========================================
2// PUBLIC API
3// ========================================
4
5export class UserService {
6 constructor(private readonly db: Database) {}
7
8 async createUser(data: CreateUserData): Promise<Result<User, CreateError>> {
9 // Public interface
10 }
11}
12
13// ========================================
14// VALIDATION
15// ========================================
16
17function validateUserData(data: unknown): Result<ValidatedData, ValidationError> {
18 // Grouped validation logic
19}
20
21// ========================================
22// PRIVATE HELPERS
23// ========================================
24
25function hashPassword(password: string): Promise<HashedPassword> {
26 // Internal implementation
27}

Organization Rules

  1. Group by feature/domain, not file type — authentication/, orders/, payments/
  2. Public API first — exported functions at top, helpers at bottom
  3. One major export per file — UserService.ts exports UserService
  4. Co-locate tests — UserService.test.ts next to UserService.ts
  5. 300-line guideline — not a hard limit, but a refactoring trigger
  6. Minimal cross-module dependencies — each module is a clean context boundary
text008 LN
1project/
2├── authentication/ # Self-contained context
3│ ├── index.ts # Public API only
4│ ├── credentials.ts
5│ ├── sessions.ts
6│ └── README.md # Module architecture
7├── orders/ # Independent context
8└── storage/ # Independent context
§ 08

Testing

Testing Trophy — Mostly Integration

"Write tests. Not too many. Mostly integration." — Kent C. Dodds

  1. Static Analysis (foundation): TypeScript strict mode, ESLint
  2. Unit Tests (narrow): Pure functions, complex algorithms
  3. Integration Tests (widest — most tests here): How pieces work together, where bugs actually live
  4. E2E Tests (top): Critical user journeys only

Tests as Documentation

Test names describe scenarios. Docstrings explain "why." Tests demonstrate usage.

text013 LN
1test('should reject invalid credentials without revealing if username exists', async () => {
2 // Prevents username enumeration attacks
3 const auth = new Authenticator(database);
4
5 const result = await auth.authenticate({
6 email: 'nonexistent@example.com',
7 password: 'any-password'
8 });
9
10 expect(result.ok).toBe(false);
11 expect(result.error.code).toBe('INVALID_CREDENTIALS');
12 expect(result.error.message).not.toContain('user not found');
13});

Testing Rules

  1. Test behavior, not implementation — focus on inputs/outputs, not internal state
  2. One concept per test — don't test multiple unrelated things
  3. Integration over unit — test pieces working together (more confidence per test, more resilient to refactoring)
  4. Clear test names — describe the scenario: test('user can add items to cart')
  5. 80% coverage minimum — focus on critical paths
§ 09

Observability

Structured Logging

text013 LN
1// ✅ Structured — queryable, correlated
2logger.info('Request processed', {
3 request_id: requestId,
4 user_id: userId,
5 endpoint: req.path,
6 method: req.method,
7 duration_ms: duration,
8 status_code: res.statusCode,
9 cache_hit: cacheHit
10});
11
12// ❌ Unstructured — hard to query
13logger.info(`User ${userId} accessed ${req.path}`);

What to Log

Always include: request_id, user_id, trace_id, entity IDs, operation type, duration_ms, error details.

Log at critical boundaries:

  • External API calls (request/response)
  • Database operations (query, duration)
  • Authentication/authorization decisions
  • Error occurrences with full context

One structured event per operation — derive metrics, logs, or traces from the same data. Don't instrument separately for each observability pillar.

§ 10

Agentic Coding Patterns

These patterns address the unique demands of code that will be read, modified, and executed by AI agents alongside humans.

Idempotent Operations

Agents retry. Network calls fail. Tasks get re-run. Design every mutation to be safely repeatable.

text014 LN
1// ✅ Idempotent — safe to retry
2async function ensureUserExists(
3 email: ValidatedEmail,
4 db: Database
5): Promise<User> {
6 const existing = await db.users.findByEmail(email);
7 if (existing) return existing;
8 return db.users.create({ email });
9}
10
11// ❌ Non-idempotent — duplicates on retry
12async function createUser(email: string, db: Database): Promise<User> {
13 return db.users.create({ email });
14}

Explicit State Machines Over Implicit Flows

When operations have distinct phases, model them explicitly. Agents reason about state machines far better than implicit status flags scattered across objects.

text010 LN
1type OrderState =
2 | { status: 'draft'; items: Item[] }
3 | { status: 'submitted'; items: Item[]; submittedAt: DateTime }
4 | { status: 'paid'; items: Item[]; submittedAt: DateTime; paymentId: string }
5 | { status: 'shipped'; items: Item[]; trackingNumber: string };
6
7// Each transition is a pure function with clear preconditions
8function submitOrder(order: OrderState & { status: 'draft' }): OrderState & { status: 'submitted' } {
9 return { ...order, status: 'submitted', submittedAt: DateTime.now() };
10}

Machine-Parseable Errors

Agents need structured errors alongside human-readable ones. Return error codes that can be programmatically matched, with messages that explain context.

text006 LN
1type AppError = {
2 code: 'VALIDATION_FAILED' | 'NOT_FOUND' | 'CONFLICT' | 'UPSTREAM_TIMEOUT';
3 message: string; // Human-readable explanation
4 field?: string; // Which input caused it
5 retryable: boolean; // Can the caller retry?
6};

Atomic, Independently-Verifiable Changes

Structure work so each change can be validated in isolation. This applies to commits, PRs, and function design. An agent (or reviewer) should be able to verify correctness without understanding the entire system.

text007 LN
1// ✅ Each function is independently testable and verifiable
2function parseConfig(raw: string): Result<Config, ParseError> { /* ... */ }
3function validateConfig(config: Config): Result<ValidConfig, ValidationError[]> { /* ... */ }
4function applyConfig(config: ValidConfig, system: System): Result<void, ApplyError> { /* ... */ }
5
6// ❌ Monolithic — must understand everything to verify anything
7function loadAndApplyConfig(path: string): void { /* 200 lines */ }

Convention Over Configuration

Reduce the search space for agents (and humans). Consistent patterns mean less context needed per decision.

  • Consistent file naming: UserService.ts, UserService.test.ts, UserService.types.ts
  • Predictable directory structure across features
  • Standard patterns for CRUD operations, API endpoints, error handling
  • If your project has a pattern, follow it. If it doesn't, establish one and document it

Contract-First Design

Define types before implementation. Types are the cheapest, most scannable form of documentation. An agent reading your types understands your system's data flow without reading a single function body.

text008 LN
1// Define the contract first
2interface OrderService {
3 create(data: CreateOrderInput): Promise<Result<Order, CreateOrderError>>;
4 cancel(id: OrderId, reason: CancelReason): Promise<Result<void, CancelError>>;
5 findByUser(userId: UserId, pagination: Pagination): Promise<PaginatedResult<OrderSummary>>;
6}
7
8// Then implement — the types guide everything

Observable Side Effects

Every mutation should produce structured output describing what changed. This enables agents to verify their actions and enables humans to audit.

text012 LN
1type MutationResult<T> = {
2 data: T;
3 changes: Change[]; // What was modified
4 warnings: string[]; // Non-fatal issues encountered
5};
6
7async function updateUserProfile(
8 id: UserId,
9 updates: ProfileUpdates
10): Promise<Result<MutationResult<UserProfile>, UpdateError>> {
11 // Returns both the result AND a description of what changed
12}

Context Optimisation & Token Economics

Every token an agent reads is a token it can't use for reasoning. Treat context like memory in an embedded system — budget it, measure it, and refuse to waste it.

The Context Budget

AI agents operate within fixed context windows. Your code, documentation, error messages, and tool outputs all compete for the same finite space. Code that is token-efficient isn't just neat — it directly improves agent reasoning quality.

text010 LN
1Context Window (finite)
2├── System prompt & instructions ~2-5k tokens (fixed cost)
3├── Conversation history ~variable
4├── Tool definitions ~1-10k tokens (per tool schema)
5├── Retrieved code / docs ~variable ← YOU CONTROL THIS
6├── Agent reasoning ~variable ← THIS GETS SQUEEZED
7└── Output generation ~variable ← AND SO DOES THIS
8
9The more tokens your code consumes, the less room the agent
10has to think. Optimise ruthlessly.

Semantic Compression

Collapse granular interfaces into high-level semantic operations. Instead of exposing every low-level action, expose intent-based APIs.

typescript020 LN
1// ❌ 15 granular tools = ~15k tokens of schema
2// An agent must read and reason about ALL of them
3tools: [
4 createFile, readFile, deleteFile, moveFile, copyFile,
5 listDirectory, createDirectory, deleteDirectory,
6 getFileMetadata, setFilePermissions, watchFile,
7 compressFile, decompressFile, hashFile, diffFiles
8]
9
10// ✅ 1 semantic dispatcher = ~1k tokens of schema
11// Agent reasons about intent, not mechanics
12tools: [{
13 name: "filesystem",
14 description: "Manage files and directories",
15 parameters: {
16 operation: "create | read | delete | move | copy | list | ...",
17 path: "string",
18 options: "object (operation-specific)"
19 }
20}]

This is the dispatcher pattern: consolidate related tools behind a single entry point that routes by intent. Token cost drops dramatically while functionality stays the same.

Layered Context Loading

Don't front-load everything. Provide summaries first, with drill-down paths for when the agent actually needs more detail.

typescript022 LN
1// ✅ Layered: summary first, details on demand
2function getProjectOverview(): ProjectSummary {
3 return {
4 name: "DataPipeline",
5 modules: ["ingestion", "transform", "export"],
6 entryPoint: "src/main.ts",
7 recentChanges: getRecentChangeSummary(5),
8 // Drill-down references — agent only loads what it needs
9 getModuleDetail: (name: string) => loadModuleContext(name),
10 getFileContent: (path: string) => loadFileContext(path),
11 };
12}
13
14// ❌ Eager: dumps everything into context upfront
15function getProjectContext(): FullProjectDump {
16 return {
17 allFiles: readAllFiles(), // 50k tokens
18 allTests: readAllTests(), // 30k tokens
19 allDocs: readAllDocs(), // 20k tokens
20 // Agent's context window is now full before it starts thinking
21 };
22}

Token-Aware Documentation

Write documentation that serves both human readers and token budgets. Every word should earn its place.

markdown017 LN
1# ❌ Token-heavy: narrative style, repetitive, verbose
2## Overview of the Authentication Module
3The authentication module is responsible for handling all aspects of user
4authentication within our application. This module was designed with security
5best practices in mind and implements industry-standard protocols. The module
6handles user login, token generation, session management, and token refresh
7functionality. It is important to note that this module uses JWT tokens for
8authentication purposes.
9(~80 tokens to say what could be said in 15)
10
11# ✅ Token-efficient: dense, scannable, no filler
12## Authentication
13JWT-based auth with refresh token rotation.
14- Entry: `authenticate()` → `Result<Session, AuthError>`
15- Tokens: 15min access, 7d refresh (HTTP-only cookie)
16- Storage: PostgreSQL users, Redis token blacklist
17(~40 tokens, more information conveyed)

Structured Output for Agent Consumption

When building tools or functions that agents will consume, prefer structured, parseable output over human-readable prose.

typescript016 LN
1// ✅ Agent-friendly: structured, parseable, minimal
2type BuildResult = {
3 success: boolean;
4 errors: { file: string; line: number; code: string; message: string }[];
5 warnings: { file: string; line: number; code: string; message: string }[];
6 stats: { duration_ms: number; filesProcessed: number };
7};
8
9// ❌ Human-only: requires parsing natural language
10function getBuildOutput(): string {
11 return `Build completed with 2 errors and 1 warning.
12 Error in src/auth.ts line 42: Type 'string' is not assignable...
13 Error in src/orders.ts line 18: Property 'id' does not exist...
14 Warning in src/utils.ts line 7: Unused variable 'temp'...
15 Build took 3.2 seconds, processed 47 files.`;
16}

Context Boundaries as Architecture

Design modules so an agent can work within one module without loading others. Each module should be a self-contained context unit.

typescript019 LN
1// ✅ Clean context boundary — agent only needs this module
2// payments/index.ts
3export interface PaymentService {
4 charge(input: ChargeInput): Promise<Result<Payment, PaymentError>>;
5 refund(id: PaymentId, reason: RefundReason): Promise<Result<Refund, RefundError>>;
6}
7
8// payments/types.ts — all types co-located, no external dependencies
9export type ChargeInput = {
10 amount: Money;
11 method: PaymentMethod;
12 idempotencyKey: string; // Agent-friendly: built-in retry safety
13};
14
15// payments/errors.ts — exhaustive, machine-readable
16export type PaymentError =
17 | { code: 'INSUFFICIENT_FUNDS'; available: Money }
18 | { code: 'CARD_DECLINED'; reason: string; retryable: false }
19 | { code: 'GATEWAY_TIMEOUT'; retryable: true };
text007 LN
1// ❌ Leaky context boundary — agent must load 4 modules to understand 1
2// payments/index.ts
3import { User } from '../users/types';
4import { Order } from '../orders/types';
5import { AuditLogger } from '../audit/logger';
6import { ConfigManager } from '../config/manager';
7// Agent now needs context from users/, orders/, audit/, config/

Compression Strategies Reference

StrategyBeforeAfterSavings
Semantic dispatchersN tool schemas (~N × 1k tokens)1 dispatcher (~1k tokens)~(N-1)k tokens
Layered loadingFull dump (50k tokens)Summary + drill-down (2k + on-demand)~48k idle tokens
Dense docsNarrative prose (~80 tokens/concept)Structured bullets (~40 tokens/concept)~50%
Co-located typesScattered across modulesSingle types.ts per moduleFewer file loads
Summary-first returnsFull object graphsSummary + reference IDs60-90% per call
Discriminated unionsGeneric error + message stringTyped union with code fieldEliminates parsing
§ 11

Project Navigation

CLAUDE.md at Project Root

Every project needs a navigation file. List entry points, patterns, and common tasks.

text015 LN
1# Project: Data Processing Pipeline
2
3## Entry Points
4- `src/main.ts`: CLI interface
5- `src/api/server.ts`: REST API
6- `src/processors/pipeline.ts`: Core processing
7
8## Key Patterns
9- All processors implement `Processor` interface (src/processors/base.ts)
10- Config uses Zod schemas (src/config/schemas.ts)
11- External APIs via `APIClient` (src/external/client.ts)
12
13## Common Tasks
14- Add data source → implement `DataSource` in `src/api/sources/`
15- Add transformation → implement `Transformer` in `src/processors/transformers/`

Keep under 200 lines. Update when architecture changes.

Module-Level READMEs

Every major directory gets a README answering: What is this? How does it work? What are the gotchas?

text014 LN
1# Module: User Authentication
2
3## Purpose
4JWT-based authentication with refresh token rotation
5
6## Key Decisions
7- bcrypt cost factor 12 for password hashing
8- Access tokens expire after 15 minutes
9- Refresh tokens stored in HTTP-only cookies
10
11## Dependencies
12- jose library for JWT (not jsonwebtoken — more secure)
13- PostgreSQL for user storage
14- Redis for token blacklist

Progressive Context Hierarchy

  1. CLAUDE.md / README.md at root — system overview, entry points, setup
  2. README.md per major module — module purpose, key decisions, patterns
  3. Section comments in files — group related code with clear headers
  4. Function/class docs — purpose, examples for non-obvious APIs
  5. Inline comments — only for "why" decisions
§ 12

Anti-Patterns

  • Premature optimization — Measure first, optimize second
  • Hasty abstractions — Wait for 3rd duplication before extracting
  • Clever code — Simple and obvious beats clever and compact
  • Silent failures — Log and propagate, never swallow
  • Vague interfaces — process(data: any): any provides zero guidance
  • Hidden dependencies — Global state, singletons, ambient imports
  • Nested conditionals — Use guard clauses instead
  • Comments describing "what" — If you need a comment to explain what code does, rename things
  • Premature generalization — Build for today's requirements, not hypothetical futures
  • Token bloat — Functions returning everything when callers need summaries
  • Inverted disclosure — Helpers at top, public API buried at bottom
  • Flat files — 500-line files with no visual hierarchy, grouping, or section comments
  • Leaky context boundaries — Modules that import heavily from siblings, forcing agents to load the entire codebase
  • Eager context loading — Dumping full project state into agent context when a summary would suffice
§ 13

Checklist

Before submitting code:

  • Solves the stated problem with minimal code?
  • A new developer can understand it without extensive context?
  • Errors handled with actionable messages?
  • Names clear, specific, and unambiguous?
  • Functions have single, clear responsibilities?
  • Dependencies explicit (no hidden global state)?
  • Tests cover critical paths?
  • Operations idempotent where applicable?
  • Types define contracts before implementation?
  • Would this work well with ~200 lines of surrounding context?
  • Can an agent understand this module without loading adjacent modules?
  • Are public APIs scannable in under 50 lines?
  • Do tool/function outputs use structured types, not prose?
  • Is documentation token-dense (no filler words, no repetition)?
  • Does the file follow progressive disclosure (types → public API → helpers)?

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." — Martin Fowler

END OF RESOURCE