House style for software development

version
2.1.0
GitHub stars
13

Install

/plugin install house-style@llm-plugins

Run it inside Claude Code after adding the marketplace with /plugin marketplace add pbdeuchler/llm-plugins.

Contents

Discovered from source

Skills 9

Authoring GitHub Issues

Overview

A good issue is a self-contained unit of work: a reader with the relevant domain experience - junior or senior - can pick it up without a verbal briefing. Getting there takes two things the prompt alone cannot give you: an understanding of the actual code, and a reasoned view of the fix. Explore first, reason second, write third.

This skill governs CONTENT and structure. Pair it with issue-hygiene for the mechanical pass (labels, title, valid markdown).

When to Use

  • User asks to "write / create / open / draft / file" a GitHub issue.
  • Turning a bug report, idea, or chat discussion into a tracked issue.

Required Behavior

1. Explore before writing. Read the relevant code paths. Trace the problem (or a feature's touch points) to its source. Cite concrete file:line references. Do not write from the prompt alone - a request you cannot locate in the code is one you do not yet understand. Fan out with read-only search agents if the surface is large.

2. Reason any solution. If you propose a fix or design, weigh the alternatives and state the tradeoff. A shallow first-thing-that-works prescription is worse than none. When genuinely unsure, surface the choice as an open question rather than feigning confidence.

3. Structure for a stranger. Include MOST of the following - this is judgment, not a template to pad. Omit a section only when it genuinely does not apply; include more often than not.

  • Summary - 1-3 sentence TL;DR.
  • What and why - the problem or goal, and its motivation or impact.
  • References - file:line, related issues/PRs, docs, external links.
  • Nuances - edge cases, constraints, gotchas, prior attempts.
  • Open questions - unknowns and decisions still to be made.
  • Definition of done / acceptance criteria - observable outcomes as a task list.

Calibrate depth so a junior with the domain background can act without hand-holding, and a senior is not buried in the obvious. If specialized domain experience is genuinely required, say so explicitly.

Public Repositories

Assume a broad, anonymous audience. Before posting:

  • No secrets, internal hostnames/URLs, customer data, employee names, or unreleased plans.
  • No exploit detail that arms an attacker; report security issues through the proper private channel, not a public issue.
  • Professional, respectful tone throughout.

Breadth of audience NEVER lowers the bar. Depth, rigor, and thoughtfulness stay the same - you simply define terms and link prerequisites instead of assuming shared context.

Output

Produce the issue body as markdown and present it for review. Create it with gh issue create only when the user asked to file or open it; otherwise hand back the draft. Then run issue-hygiene.

Template

## Summary
<one to three sentences>

## What & why
<the problem or goal, and the motivation / impact>

## References
- `path/to/file.rs:120` - <what lives here>
- #123, related docs or links

## Nuances & considerations
- <edge cases, constraints, prior attempts>

## Open questions
- <decisions still to make>

## Definition of done
- [ ] <observable, checkable outcome>

Red Flags - Stop

  • Writing the issue without having opened the code it concerns.
  • A proposed solution with no rationale or alternatives considered.
  • Padding every section to fill the template when some do not apply.
  • Pasting internal URLs, secrets, or names into a public repo.

Coding Effectively

Required Sub-Skills

ALWAYS REQUIRED:

  • defense-in-depth - Validate at every layer data passes through

CONDITIONAL: Use these sub-skills when applicable:

  • howto-develop-with-postgres - PostgreSQL database code
  • writing-good-tests - Writing or reviewing tests
  • property-based-testing - Tests for serialization, validation, normalization, pure functions

Thinking About Dependencies

A working guide to dependencies-as-parameters — practiced, not preached

Currying, dependency injection, and interfaces are one move: turn a hidden coupling into an explicit parameter, give it the narrowest useful type, and bind it as late as the budget allows. This guide is about doing that successfully, which means knowing when not to.

The first principle is economic, not moral: every seam costs indirection — a cognitive hop for the reader and often a dispatch for the machine. So the default is concrete, and you buy a seam only when it pays rent. "Program to an interface" is advice, not a commandment; applied dogmatically it produces codebases that are abstract everywhere and flexible nowhere.


What a good seam buys you

A unit whose dependencies are all parameters is a pure function: output determined by input, nothing else. That single property gives you everything downstream — it's testable (pass a different value), reasoned-about (substitute equals for equals), and swappable (the boundary varies independently of the core). The goal is always the same shape: determinism in the middle, substitutability at the edge.

You do not get that shape by abstracting everything. You get it by abstracting the right things and leaving the rest concrete.


When to add a seam

Add one only when the dependency has a real axis of variation. In practice that's a short list:

Add a seamBecause
Nondeterminism — clock, randomness, UUIDsThe real value is uncontrollable; a parameter makes the unit deterministic and testable.
I/O & external systems — DB, network, filesystem, queuesThis is your failure/latency boundary — the seam lets you inject retries, breakers, timeouts, and fault injectors.
Genuine deployment variation — payment provider, storage backend, config, feature flagsMore than one implementation actually ships or is imminent.

That's roughly it. Note the unifying trait: each is nondeterministic, effectful, external, or genuinely plural. If a dependency is none of those, it does not need a seam.


When not to — the anti-dogma rules

  1. Don't abstract pure logic. A pure function or value object has no axis of variation. Don't inject your data structures; just call the function and new the value.
  2. One permanent implementation = no interface. An interface with a single forever-implementation is pure indirection. Delete it and use the concrete type. The interface is noise the reader has to trace through to discover there was never a choice.
  3. Apply the rule of three. Two call sites isn't a pattern. Wait for the third real case before extracting the abstraction — unless the dependency is on the list above, where the test fake is a guaranteed second case and justifies the seam immediately. (That exception is the whole reason Clock is worth it and UserNameFormatter isn't.)
  4. Reach for the language feature before the framework. A runtime DI container with reflection is a re-implementation of function application. If passing an argument works, pass an argument. Containers move "is this wired correctly?" from compile time to startup time — or to the first request that hits the cold path.
  5. Don't inject the world. A dependency typed as System (touches everything) is explicit but useless — the type no longer bounds the blast radius. Inject the capability, not the container.
  6. Collapsing a premature abstraction is normal maintenance. Abstractions aren't sacred. If a seam never flexed, inline it. Backing out is cheaper than the standing tax.

How to do it well when you do

  • Narrow the contract to a capability. () => number, not Clock, when all you need is the time. Clock, not System, when you need a small set of related operations. The type should be a manifest of exactly what the unit can touch — and therefore a guarantee of what it can't.
  • The consumer owns the interface. Define the port on the high-level side, shaped to what the policy needs; let the low-level module implement it. Don't import the provider's surface. This is what makes the dependency arrow point inward toward stable policy instead of outward toward volatile detail.
  • Wire in one boring function. Construct the graph explicitly at the top of the program (constructor injection / explicit main), where a human can read the whole thing at a glance. No magic, no scanning, no annotations resolved at runtime.
  • Keep the core pure; push effects to the edge. The deterministic middle is where logic, tests, and (if you ever need it) proofs live. I/O lives in a thin shell around it.
  • Bind early on hot paths. A seam you kept for testing can be specialized away in production via partial application or monomorphization/devirtualization. Keep the flexibility at the source level; pay nothing for it at runtime where it matters.

Worked examples

Nondeterminism — and notice the seam is a plain parameter, not an interface.

// Hidden dependency on the wall clock: nondeterministic, untestable.
function isExpired(token: Token): boolean {
  return token.expiresAt < Date.now();
}

// The clock is now an input. Deterministic, trivially testable, zero ceremony.
function isExpired(token: Token, now: number): boolean {
  return token.expiresAt < now;
}

You needed a number, so you passed a number. Reach for an interface only when the dependency has behavior worth faking (several methods, state, real swap). Not everything that gets injected deserves a type with a name.

Over-abstraction — the seam that buys nothing.

// Speculative: one implementation, no axis of variation, wired through a container.
interface UserNameFormatter {
  format(u: User): string;
}
class DefaultUserNameFormatter implements UserNameFormatter {
  format(u: User) {
    return `${u.first} ${u.last}`;
  }
}

// It was always just a function.
const formatUserName = (u: User) => `${u.first} ${u.last}`;

Inject the capability, not the world.

// `system` can reach the clock, the filesystem, the network, env... blast radius = everything.
class Report {
  constructor(private system: System) {}
  build() {
    const t = this.system.clock.now(); /* ... */
  }
}

// The type now tells you the entire surface this class can touch.
class Report {
  constructor(private now: () => number) {}
  build() {
    const t = this.now(); /* ... */
  }
}

Pre-commit checklist

  • Is this dependency nondeterministic, effectful, external, or genuinely plural? If no → call it directly, don't abstract it.
  • Does the seam have a real second case? (A test fake counts only when the real dependency is one of the above.) If no → rule of three; wait.
  • Is the contract the narrowest capability that does the job? (() => number over Clock; Clock over System.)
  • Did the consumer define the interface to fit its need, or did you import the provider's surface?
  • Can you read the entire wiring graph in one function, with no framework?
  • Is the core pure, with effects pushed to the boundary?
  • On a hot path, can you bind early after keeping the seam for tests?
  • Does every existing abstraction still flex? If one never has, collapse it.

North star. Default to concrete. Add a seam when a dependency is nondeterministic, effectful, external, or genuinely varies — give it the narrowest type that does the job, wire it in plain code, and keep the core pure. Abstractions are bought with indirection; make each one pay rent. Everything called "good design" — testable, readable, swappable, provable — falls out of that one discipline, applied with judgment rather than reflex.

Writing Good Code with Types, Invariants, and Classes

A practical, non-dogmatic guide

The one idea. A type is a predicate over values, an invariant a predicate over states, a class the machinery that establishes and preserves an invariant by owning every door into its state. All three separate valid from invalid and keep you in the valid region inductively: establish the property at a boundary, preserve it under every permitted operation, and then assume it everywhere else for free. That "assume it for free" is the prize — it's where readable, testable, low-bug code comes from, because it lets every other line reason locally.

This guide is about applying that idea with judgment. The principles are a gradient of effort, not a set of commandments. The goal is correctness you can afford, not maximal encoding. Most of the wins come from the cheapest rungs; the expensive ones are for code that has earned them.


The workflow: six moves

  1. Name the invariant precisely. Before building an abstraction, state what must always be true — in words. If you can't name one, you don't have an abstraction yet; you have a data structure, and that's fine — call it that.
  2. Find the boundary where validity enters. Parse points, constructors, deserialization, the network edge, the FFI seam. This is where the predicate gets checked. Everything past it should be able to trust the result.
  3. Pick the cheapest enforcement that's actually adequate (see the cost ladder). Default low; climb only when the invariant is load-bearing and realistically gets violated.
  4. Make the signatures honest. Shape the types so a caller cannot express the invalid call, or so the failure mode is visible in the return type. Stop functions from lying about their domain.
  5. Keep operations closed over the valid set. If insert on a sorted structure returns a sorted structure, callers compose without re-checking. Closure is what lets you avoid re-validation.
  6. Test the boundary and the preservation. Exhaustively test the one door; property-test that operations keep the invariant. That's the inductive step run as an experiment.

The toolbox

Make illegal states unrepresentable — when the distinction drives behavior. Replace flag soup with a sum type. bool loading; bool error; T? data (which permits nonsense like loading-and-errored) becomes Loading | Failed(e) | Loaded(data). Use distinct newtypes for things that shouldn't mix (UserId vs OrderId, not both string). Use NonEmptyList, NonZero, Positive so the empty/zero/negative case is gone from the body rather than guarded in it.

Parse, don't validate — at every point where untrusted shape becomes trusted shape. A validator returns bool and throws the knowledge away; a parser returns the refined type and keeps it. parseEmail(s) -> Option<Email>; then everything downstream takes Email, never re-checking a raw string. The type is the proof the check happened.

Smart constructors — when the type system can't express the invariant. Sorted, balanced, in-range-across-fields, summing-to-100 — make the raw constructor private, expose one factory that establishes and asserts the invariant. One door, checked once.

Encapsulate for the invariant, not reflexively. Hide exactly what protects the invariant; expose the rest plainly. A class with a getter and setter for every field protects nothing — it's a struct wearing a disguise, and a plain record is more honest and more readable.

Assertions for the un-typeable. For invariants the language won't carry, assert/debug_assert at construction and after mutation. Executable documentation that fails near the cause. Cheap, removable in release, invaluable in debug.

Closure and total functions. Prefer operations that return the same refined type. Make partiality explicit with Result/Option rather than throwing — but only when you actually handle it; a swallowed error is a lie wearing an honest type's clothes.

At trust and process boundaries. Validate untrusted input once at the edge, convert to trusted types, trust within. For invariants that span processes, you have no shared memory and no atomic method call — design for idempotency, monotonicity, and commutativity (CRDTs are the clean version: convergence preserved by construction). Don't pretend a class invariant crosses the network.


The cost ladder

Spend the least that's adequate. Climb only when stakes and violation-likelihood justify it.

RungMechanismUse when
1Unrepresentable (types)The invariant is cheap to encode and the language carries it naturally. Best ROI when it fits.
2Enforced at one constructor / parserCan't be static, but there's a natural single entry point.
3Asserted + property-testedNo clean static or constructor enforcement; you want it caught in CI and debug builds.
4Documented + tested at the chokepointSpans systems you don't own (distributed, third-party, eventual consistency). Name the limit of the guarantee honestly.

Climbing past the rung an invariant deserves is itself a defect: it costs compile time, comprehension, and hiring, and it buries the load-bearing constraints under ceremony.


Staying non-dogmatic

These are the ways the discipline turns against itself. Watch for them.

  • Match effort to stakes. A throwaway script, a prototype, glue code: a comment and an assert is often the entire correct answer. Don't build a refinement-type cathedral around code that won't outlive the week.
  • The encoding can cost more than the bug. If making a state unrepresentable demands GADTs, dependent types, or three layers of generics, weigh the next reader's comprehension and your team's reality against the bug you're preventing. A // INVARIANT: plus an assert plus a focused test is sometimes more readable and just as safe. Clever types carry the same liability as clever anything.
  • Don't validate everywhere — validate at the boundary. Defensive checks in every layer are the opposite of this discipline: they announce that you don't trust your own types. Each redundant check can rot and diverge. Validate once; trust within. (Real trust boundaries are the exception, not the rule.)
  • Encode distinctions that matter to behavior, not every distinction that exists. Minting a separate type for every conceptual nuance fragments code into near-identical types and conversion boilerplate. If two states are interchangeable for all current callers, one type is correct.
  • Anemic encapsulation is fake encapsulation. No invariant, no reason to hide the representation. Reach for a plain data structure and stop apologizing for it.
  • "Total" can still be dishonest. Returning a default to dodge a throw, or dropping errors into an ignored Result, hides failure rather than handling it. Honest means the signature tells the truth about how it fails, not that it never does.
  • Some invariants are genuinely non-local — say so. A type can't guarantee what the runtime can violate across services. Enforce at the chokepoint, document the edge of the guarantee, test the protocol. Pretending otherwise is worse than admitting it.
  • Refactor toward this; don't rewrite for it. Tighten the highest-traffic, highest-risk boundary first — the parser, the public constructor, the recurring bug. Let everything else stay until it earns the change.
  • Friction is information. If the language fights you at every turn to encode an invariant, don't power through on principle. Maybe the invariant is wrong, the boundary is misplaced, or this isn't the layer to encode it. Listen before you reach for type gymnastics.

Quick decision heuristics

  • Can a caller construct an invalid value, and would that matter? → If yes, close the door (rung 1 or 2).
  • Am I checking the same thing in three places? → Push it to one boundary and carry a type past it.
  • Does this type's name promise something its operations can break? → Enforce it, or rename it to stop lying.
  • Type, or comment-plus-assert? → Pick whichever the next engineer reads faster. Both are legitimate.
  • What breaks if a message is duplicated, reordered, or lost? → Design for idempotency/monotonicity, not for walls that don't exist across the network.
  • Load-bearing or throwaway? → Calibrate everything above to the answer.

Checklist

  • I can state this abstraction's invariant in one sentence (or I've admitted it's just data).
  • There is a single boundary where invalid input becomes a valid, typed value.
  • Past that boundary, nothing re-validates what the type already guarantees.
  • Signatures exclude invalid inputs or make failure visible in the return type.
  • Operations are closed over the valid set, or the gap is asserted and tested.
  • I chose the lowest adequate rung on the cost ladder, not the fanciest.
  • Cross-process invariants are handled as protocols, with the guarantee's limits documented.
  • The boundary is exhaustively tested; preservation is property-tested.
  • I removed redundant defensive checks that exist only because I didn't trust my own types.

In one line: find the invariant, establish it at one door, keep every operation from breaking it, let the rest of the program assume it for free — and spend no more than the invariant is worth.

A Working Guide to State, Effects, and Honest Interfaces

How to use functional discipline to write good code — and how to know when to stop applying it.

The point of all of this is not purity. It is honesty about state and effects, kept local. You reach for each practice below because it removes more complexity than it adds. When it stops doing that, you stop. Every rule here ships with the condition under which you break it.


The one operating principle

Make the hidden dependencies in your code — mutation, failure, absence, I/O, time — explicit and local. A function should be honest about what it touches, and what it touches should be as small as possible. Everything else is tactics.

The dogma trap is treating "pure" as the goal. The goal is reasoning — yours, the next person's, and the compiler's. Spend discipline where reasoning pays off (concurrency, security boundaries, money, the long-lived core domain) and relax it where it doesn't (scripts, glue, prototypes, hot inner loops behind a clean interface).


1. Put failure and absence in the type

Do it: Expected, recoverable failure returns Result<T, E>. Possible absence returns Option<T>. The caller is forced to confront both at compile time instead of discovering them in production.

fn charge(account: &Account, cents: u64) -> Result<Receipt, ChargeError>;
//                                          ^ the contract names what can go wrong

Relax it when:

  • The failure is a bug, not a domain outcome. Invariant violations should panic/throw, not return Result. Don't make callers handle "this can't happen."
  • Wrapping adds no information. If nothing can fail, don't return Result<T, Infallible> to look consistent.
  • An Option would propagate ten layers unchanged — supply a default at the boundary and pass the plain value inward.

Smell: a signature that lies — returns T but throws, or claims to be infallible while reading a mutable global.


2. Errors as values vs. exceptions — the dividing line

The test is one question: will the caller do something different because of this?

  • Yes → value. Insufficient funds, parse failure, not-found. Part of the domain. Make it a Result/Option.
  • No → throw/panic. Out of memory, broken invariant, programmer error. Unrecoverable. Crashing loudly beats limping on with corrupt state.

Relax it when: you're at a top-level boundary — a request handler, a CLI main, a job runner. Collapsing many possible failures into one error boundary there is fine; you don't need to thread Result through code whose only response is "log it and return 500." Push the ceremony to where decisions actually branch.


3. Functional core, imperative shell

Do it: Computation and decisions live in a pure core that takes data and returns data. I/O lives in a thin shell that feeds the core and performs whatever the core decided.

// core: pure, returns a description of what to do — trivially testable
fn plan(order: &Order, inventory: &Inventory) -> Vec<Command> { /* ... */ }

// shell: performs the effects, holds the danger, stays thin
for cmd in plan(&order, &inventory) {
    execute(cmd)?; // the only place that touches the world
}

This is the highest-leverage pattern here: the core needs no mocks, and the effects are concentrated where you can watch them.

Relax it when: the program is mostly effects (an ETL job, a device driver, a streaming pipeline). The shell can be thick when the domain is genuinely effectful. Don't contort an inherently stateful thing — a parser, a connection pool, an allocator — into a pure shape it doesn't want. A stateful object with a clean interface is sometimes the honest model.


4. Immutable by default — but mutation isn't the sin

The sin is shared, observable mutable state, not mutation itself. A local mutation that no caller can observe is still referentially transparent.

fn checksum(bytes: &[u8]) -> u32 {
    let mut acc = 0u32;             // local mutation, invisible outside
    for &b in bytes { acc = acc.wrapping_mul(31).wrapping_add(b as u32); }
    acc                            // caller sees a pure function
}

Do it: Default to immutable values and transformations. Share nothing across threads/modules by default.

Relax it when: you're in a hot path. Mutate a local buffer or accumulator, reuse allocations, avoid building a fresh collection per element — all fine, provided the mutation stays inside the function and the interface stays honest. Persistent data structures are a tool, not a tax you must always pay.


5. Make illegal states unrepresentable; parse, don't validate

Do it: Encode invariants in types so wrong states won't compile. Parse untrusted input once, at the boundary, into a precise type that carries the proof inward.

struct Email(String);
impl Email {
    fn parse(s: &str) -> Result<Email, EmailError> { /* validate once */ }
}
// everything downstream takes Email, never re-checks a raw &str

Prefer sum types over flag soup (enum State beats three correlated bools), and NonEmpty<T> over "a Vec that must not be empty, see comment."

Relax it when: the type costs more than the bug it prevents. A 30-line script doesn't need a type lattice. Some invariants are cheaper as a runtime check in one smart constructor than as a type-level proof. Stop when the types get harder to read than the rule they encode.

Smell: the same validation repeated at many call sites; boolean-blind parameters; comments saying "this string is really a path / JSON / an ID."


6. Encapsulate at the interface: disclose the effect, hide the mechanism

Do it: A public contract tells the truth about what it does — can it fail, does it do I/O — and nothing about how. The interface can be pure even when the implementation mutates a local arena.

Relax it when: the caller needs to control the mechanism. If latency, ordering, or batching matters to the caller, hiding it is the wrong encapsulation — you've concealed what matters and exposed what doesn't. And don't build an abstraction boundary around something with one caller; that's ceremony, not design.


7. Compose with the uniform interface — but don't build towers

?, flatMap, and do-notation let you chain context-carrying computations and refactor the pipeline fearlessly; the monad laws are why the refactor is safe.

Relax it when: the abstraction is harder to read than the code it abstracts. Deep monad-transformer stacks and six-layer effect towers are a smell. Flatten them: a concrete application type, a small effect enum, or language-level effects/async beats a generic tower nobody on the team can read. Generality that isn't used is just cost.


8. Test the core directly; concentrate the rest at the seam

Do it: Unit-test the pure core with plain values and property tests over invariants. Integration-test the thin shell where it meets the world.

Relax it / read the signal: if testing the core requires mocking the universe, the effects have leaked into the core. The fix is the design, not more mocks — pull the I/O back out to the shell. A handful of real integration tests at the seam beat a hundred brittle mock-heavy ones.


9. Know the taxes, and choose where to pay them

Every practice here has a cost: async colors every caller, immutability allocates, effect towers obscure, and all of it loads the team's working memory. None of that means don't do it — it means spend it deliberately.

  • Pay it at concurrency boundaries, security/trust boundaries, anything handling money, and the core domain you'll maintain for years.
  • Skip it in throwaway scripts, prototypes, one-shot glue, and perf-critical inner loops (behind a clean interface).

Field rules

  • Make effects honest; make state local; reach for machinery only when it removes more complexity than it adds.
  • Failure the caller handles → value. Failure that's a bug → crash.
  • Big pure core, thin honest shell. If the core needs mocks, it isn't pure yet.
  • Mutate freely where no one can observe it; never share mutable state by default.
  • Parse untrusted input once into a precise type; let the type carry the proof.
  • Disclose what a function does; hide how it does it — unless the how is what the caller must control.
  • If the abstraction is harder to read than the thing, delete the abstraction.

The mature version of this discipline doesn't look maximally functional. It looks honest: minimal effects, kept at the edges, around a core you can actually reason about — and pragmatic mutation everywhere that honesty isn't at stake.

Property-Driven Design

When designing features, think about properties upfront. This surfaces design gaps early.

Discovery questions:

QuestionProperty TypeExample
Does it have an inverse operation?Roundtripdecode(encode(x)) == x
Is applying it twice the same as once?Idempotencef(f(x)) == f(x)
What quantities are preserved?InvariantsLength, sum, count unchanged
Is order of arguments irrelevant?Commutativityf(a, b) == f(b, a)
Can operations be regrouped?Associativityf(f(a,b), c) == f(a, f(b,c))
Is there a neutral element?Identityf(x, 0) == x
Is there a reference implementation?Oraclenew(x) == old(x)
Can output be easily verified?Easy to verifyis_sorted(sort(x))

Common design questions these reveal:

  • "What about deleted/deactivated entities?"
  • "Case-sensitive or not?"
  • "Stable sort or not? Tie-breaking rules?"
  • "Which algorithm? Configurable?"

Surface these during design, not during debugging.

Core Engineering Principles

Correctness Over Convenience

Model the full error space. No shortcuts.

  • Handle all edge cases: race conditions, timing issues, partial failures
  • Use the type system to encode correctness constraints
  • Prefer compile-time guarantees over runtime checks where possible
  • When uncertain, explore and iterate rather than assume

Don't:

  • Simplify error handling to save time
  • Ignore edge cases because "they probably won't happen"
  • Use any or equivalent to bypass type checking

Error Handling Philosophy

Two-tier model:

  1. User-facing errors: Semantic exit codes, rich diagnostics, actionable messages
  2. Internal errors: Programming errors that may panic or use internal types

Error message format: Lowercase sentence fragments for "failed to {message}".

Good: failed to connect to database: connection refused
Bad:  Failed to Connect to Database: Connection Refused

Good: invalid configuration: missing required field 'apiKey'
Bad:  Invalid Configuration: Missing Required Field 'apiKey'

Lowercase fragments compose naturally: "operation failed: " + error.message reads correctly.

Always use proper logging, and errors should always be logged via the language/framework appropriate methods.

Pragmatic Incrementalism

  • Prefer specific, composable logic over abstract frameworks
  • Evolve design incrementally rather than perfect upfront architecture
  • Don't build for hypothetical future requirements
  • Document design decisions and trade-offs when making non-obvious choices

The rule of three applies to abstraction: Don't abstract until you've seen the pattern three times. Three similar lines of code is better than a premature abstraction.

File Organization

Descriptive File Names Over Catch-All Files

Name files by what they contain, not by generic categories.

Don't create:

  • utils.go - Becomes a dumping ground for unrelated functions
  • helpers.js - Same problem
  • common.rs - What isn't common?
  • misc.go - Actively unhelpful

Do create:

  • formatter.go - String manipulation utilities
  • calendar/math.go - Date calculations
  • api/src/error_handling.rs - API error utilities
  • user-input.ts - User input validation

Why this matters:

  • Discoverability: Developers find code by scanning file names
  • Cohesion: Related code stays together
  • Prevents bloat: Hard to add unrelated code to string-formatting.ts
  • Import clarity: import { formatDate } from './date-arithmetic' is self-documenting

When you're tempted to create utils.ts: Stop. Ask what the functions have in common. Name the file after that commonality.

Module Organization

  • Keep module boundaries strict with restricted visibility
  • Platform-specific code in separate files: unix.go, windows.go, posix.go
  • Use conditional compilation or runtime checks for platform branching
  • Test helpers in dedicated modules/files, not mixed with production code

Cross-Platform Principles

Use OS-Native Logic

Don't emulate Unix on Windows or vice versa. Use each platform's native patterns.

Bad: Trying to make Windows paths behave like Unix paths everywhere.

Good: Accept platform differences, handle them explicitly.

// Platform-specific behavior
if (process.platform === "win32") {
  // Windows-native approach
} else {
  // POSIX approach
}

Platform-Specific Files

When platform differences are significant, use separate files:

process/spawn.go    // Shared interface and logic
process/unix.go     // Unix-specific implementation
process/windows.go  // Windows-specific implementation

Document Platform Differences

When behavior differs by platform, document it in comments:

// On Windows, this returns CRLF line endings.
// On Unix, this returns LF line endings.
// Callers should normalize if consistent output is needed.
function readTextFile(path: string): string { ... }

Test on All Target Platforms

Don't assume Unix behavior works on Windows. Test explicitly:

  • CI should run on all supported platforms
  • Platform-specific code paths need platform-specific tests
  • Document which platforms are supported

Common Mistakes

MistakeRealityFix
"Just put it in utils for now"utils.ts becomes 2000 lines of unrelated codeName files by purpose from the start
"Edge cases are rare"Edge cases cause production incidentsHandle them. Model the full error space.
"We might need this abstraction later"Premature abstraction is harder to remove than addWait for the third use case
"It works on my Mac"It may not work on Windows or LinuxIf deploying to a target, test on it
"The type system is too strict"Strictness catches bugs at compile timeFix the type error, don't bypass it

Red Flags

Stop and refactor when you see:

  • A utils.go or helpers.rs file growing beyond 100 lines
  • Error handling that swallows errors or uses generic messages
  • Platform-specific code mixed with cross-platform code
  • Abstractions created for single use cases
  • Type assertions (any) to bypass the type system

Defense-in-Depth Validation

Overview

When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks.

Core principle: Validate at EVERY layer data passes through. Make the bug structurally impossible.

When to Use

Use when:

  • Invalid data caused a bug deep in the call stack
  • Data crosses system boundaries (API → service → storage)
  • Multiple code paths can reach the same vulnerable code
  • Tests mock intermediate layers (bypassing validation)

Don't use when:

  • Pure internal function with single caller (validate at caller)
  • Data already validated by framework/library you trust
  • Adding validation would duplicate identical checks at adjacent layers

The Four Layers

Layer 1: Entry Point Validation

Purpose: Reject invalid input at API/system boundary

function createProject(name: string, workingDirectory: string) {
  if (!workingDirectory?.trim()) {
    throw new Error('workingDirectory cannot be empty');
  }
  if (!existsSync(workingDirectory)) {
    throw new Error(`workingDirectory does not exist: ${workingDirectory}`);
  }
  // ... proceed
}

When needed: Always. This is your first line of defense.

Layer 2: Business Logic Validation

Purpose: Ensure data makes sense for this specific operation

function initializeWorkspace(projectDir: string, sessionId: string) {
  if (!projectDir) {
    throw new Error('projectDir required for workspace initialization');
  }
  // ... proceed
}

When needed: When business rules differ from entry validation, or when mocks might bypass Layer 1.

Layer 3: Environment Guards

Purpose: Prevent dangerous operations in specific contexts

async function gitInit(directory: string) {
  if (process.env.NODE_ENV === 'test') {
    const normalized = normalize(resolve(directory));
    if (!normalized.startsWith(tmpdir())) {
      throw new Error(`Refusing git init outside temp dir in tests: ${directory}`);
    }
  }
  // ... proceed
}

When needed: When operation is destructive/irreversible, especially in test environments.

Layer 4: Debug Instrumentation

Purpose: Capture context for forensics when other layers fail

async function gitInit(directory: string) {
  logger.debug('git init', { directory, cwd: process.cwd(), stack: new Error().stack });
  // ... proceed
}

When needed: When debugging is difficult, or when you need to trace how bad data arrived.

Decision Heuristic

SituationLayers Needed
Public API, simple validation1 only
Data crosses multiple services1 + 2
Destructive operations (delete, init, write)1 + 2 + 3
Chasing a hard-to-reproduce bug1 + 2 + 3 + 4
Tests mock intermediate layersAt minimum: 1 + 3

Applying the Pattern

When you find a bug caused by invalid data:

  1. Trace the data flow - Where does the bad value originate? Where is it used?
  2. Map checkpoints - List every function/layer the data passes through
  3. Decide which layers - Use heuristic above
  4. Add validation - Entry → business → environment → debug
  5. Test each layer - Verify Layer 2 catches what bypasses Layer 1

Quick Reference

LayerQuestion It AnswersTypical Check
EntryIs input valid?Non-empty, exists, correct type
BusinessDoes it make sense here?Required for this operation, within bounds
EnvironmentIs this safe in this context?Not in prod, inside temp dir, etc.
DebugHow did we get here?Log stack, cwd, inputs

Common Mistakes

MistakeFix
One validation point, call it doneAdd at least entry + business layers
Identical checks at adjacent layersMake each layer check something different
Environment guards only in prodAdd them in test too (prevent test pollution)
Skipping debug loggingAdd it during the bug hunt, keep it
Validation but no useful error messageInclude the bad value and expected format

Key Insight

During testing, each layer catches bugs the others miss:

  • Different code paths bypass entry validation
  • Mocks bypass business logic checks
  • Edge cases need environment guards
  • Debug logging identifies structural misuse

Don't stop at one validation point. The bug isn't fixed until it's impossible.

Holistic Review

You are a group of staff engineers performing a final, comprehensive review of a completed implementation. Your job is to review every line of the diff against the implementation plan (when one exists) and against high engineering standards.

The members of your group are:

  • a grizzled systems engineer who has experience writing close to the hardware code that provides performance sensitive hot paths in systems at scale
  • an experienced distributed systems engineer who thinks deeply about how this code will interact with other code both within this project, and this specific binary or implementation, and outside of it
  • a security engineer keen to ensure that all code not only is secure against basic and known threats, but does not create any future potential for attack path escalation in a broader system
  • an infrastructure operations engineer who is obsessed about uptime and easy to debug and maintain systems
  • a product lead with long term vision on how the system will evolve under changing customer requirements

As you work through the workflow discuss amongst yourselves, provide different viewpoints, and compare and contrast different styles, approaches, opinions, and best practices. Approach code review with the context of each of your backgrounds, trying to ensure that with many eyes all bugs are shallow.

Inputs

Both inputs are optional. Resolve them before doing anything else and record what you resolved in your output.

Implementation plan (optional, but strongly preferred)

An absolute path to the plan file that drove this work. If no path was provided, try to find one before giving up:

  1. Check for an open PR on the current branch: gh pr view --json title,body -- a PR description often contains or links the plan
  2. Check the commit log for plan references: git log <base>..HEAD --format='%s%n%b'
  3. Check conventional locations for recently modified plan files: docs/plans/, plans/, *.plan.md, scratch/planning directories referenced in the repo

If you still have no plan, proceed without one: reconstruct the intent of the change from the commit log, the PR description, and the shape of the diff itself. Write that reconstructed intent down explicitly before reading any code -- it plays the role of the plan for the rest of the review. State clearly in your output that the review ran without a plan and that adherence findings carry lower confidence.

Base branch (optional)

The branch or commitish to diff against; everything between base and HEAD is in scope. If not provided, detect it:

git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null

If that fails, use whichever of main or master exists (git rev-parse --verify main / git rev-parse --verify master). If both exist and origin/HEAD is unset, use the one that is an ancestor of HEAD; if still ambiguous, stop and ask.

Workflow

1. Gather Context

Read the implementation plan in full (or write down your reconstructed intent, per Inputs). Understand what was asked for -- scope, requirements, acceptance criteria, constraints. This is your ground truth. Do not read any code yet. Think about how you personally would implement this plan, the nuances involved and any potential pitfalls.

Then generate the diff:

git diff <base>...HEAD

If the diff is too large, break it into per-file diffs:

git diff <base>...HEAD --stat
git diff <base>...HEAD -- <file>

Also collect the commit log for the implementation branch:

git log <base>..HEAD --oneline

2. Use Tests as a Guide -- and Break the Code

This step is mandatory and is the heart of the review. Deliberately breaking the code under test is how you learn whether the tests encode a real understanding of the change, and whether the change itself is built the way it claims to be. Do not skip it, and do not substitute reading the tests for running them against mutations.

First, only review the tests. Ensure that you can understand the changes that were made from just the test cases and how the test code is written. If you can not quickly or easily decipher how things changed from the tests then either test coverage needs to improve or the code changes were not done to a satisfactory level. From your understanding of the plan, how you would accomplish things, and now the tests, does it seem like test coverage is adequate? Using the tests as your guide, start to inspect what seems to be key pieces of the changes. Do these seem correct? Are they actually being tested? Do tests falsify the assumptions of this key code, or do they just test language, framework, or library truthisms? Can you immediately tell the actually crucial code is elsewhere, not explicitly tested, or there are critical assumptions baked into the combination of different pieces of code? If so these are all smells that the code is not up to par. Begin forming opinions about how this code could be improved.

If the diff contains no test changes at all for non-trivial production changes, that is an automatic Critical finding.

Then run the mutation protocol:

  1. Require a clean working tree. git status --porcelain must be empty. If it is not, stop and report -- never mutate on top of uncommitted work.
  2. Establish a green baseline. Run the test suite once, unmodified. If the baseline is red, that is an immediate Critical finding, and mutation results would be meaningless -- skip the mutations and continue to step 3 of the workflow.
  3. Select crucial code. Pick at least three pieces of code (or all of them, if the change has fewer) that the change genuinely relies on: branch conditions, boundary arithmetic, error propagation, state transitions, ordering assumptions. Not trivial lines -- code whose breakage should obviously matter.
  4. Mutate, predict, run. For each selection, make one small semantic mutation (invert a condition, off-by-one a boundary, swap arguments, drop an error check, return early). Before running anything, write down which tests you expect to fail. Run the suite. Record predicted vs. actual failures.
  5. Revert immediately. Restore the file (git checkout -- <file> or git restore <file>) and confirm git status --porcelain is empty again before making the next mutation.
  6. Judge the results. A mutation that survives (no test fails) means the code is not adequately tested, and usually means the code is not properly written either -- the crucial logic is untestable, duplicated, or not where the tests think it is. Every surviving mutation is an Important or Critical finding. Begin thinking about what is causing the poor testing practices and what changes you would make to the code.

NEVER leave a mutation in the tree. Verify the working tree is clean before moving on, and again before writing your report.

3. Read Changed Files in Full

Do not review only the diff hunks. For every file that changed, read the entire file so you can evaluate the change in its full context -- imports, surrounding functions, module structure.

git diff <base>...HEAD --name-only

Read each file listed.

4. Analyze

Now that you have the whole picture, compare it against the assumptions and mental model you made when initially reading the plan and reviewing the tests. Evaluate the implementation across seven dimensions. For each dimension, produce findings.

4a. Correctness
  • Does the code do what the plan asks?
  • Are there logic errors, off-by-one bugs, race conditions, nil dereferences?
  • Are error cases handled? Are errors propagated correctly?
  • Are edge cases covered (empty input, boundary values, concurrent access)?
  • Do tests actually assert the right behavior, or do they pass vacuously?
4b. Elegance
  • Is the code clean and readable?
  • Are names descriptive and consistent?
  • Is there unnecessary duplication that should be extracted?
  • Is complexity proportional to the problem being solved?
  • Would a new team member understand this code without extensive explanation?
  • Can this code be refactored to be more elegant, simple, and reduce possible code paths?
  • Is this code too intertwined, does it conflate concerns, and are things tightly coupled?
4c. Simplicity
  • Could any function, type, or abstraction be removed without losing capability?
  • Are there over-engineered patterns (unnecessary interfaces, premature abstraction, speculative generality)?
  • Is the solution the simplest one that works, or has complexity crept in?
  • Are there unnecessary dependencies or imports?
  • Is the code unnecessarily verbose or too complicated?
  • Can any unused or single use code be removed or simplified in a refactor?
4d. Design Principles
  • Is state minimized and managed explicitly?
  • Are side effects isolated from pure logic?
  • Is the code modular -- can pieces be tested and reasoned about independently?
  • Are responsibilities clearly separated?
  • Is the dependency direction correct (concrete depends on abstract, not the reverse)?
4e. Idiomatic Usage
  • Does the code use language/framework/library features correctly?
  • Are there patterns that fight the ecosystem (e.g., manual iteration where a standard library method exists, hand-rolled error types where the language has conventions)?
  • Are community conventions followed (naming, file layout, module structure)?
  • Are there deprecated APIs or anti-patterns?
4f. Plan Adherence
  • Does the implementation cover every requirement in the plan?
  • Are there additions beyond what the plan specified? If so, are they justified or scope creep?
  • Are acceptance criteria met?
  • Are there requirements that were partially implemented or subtly misinterpreted?
  • If the plan specifies constraints (performance, compatibility, no breaking changes), are they respected?

When no plan exists, review against your reconstructed intent instead, and flag mismatches between what the commits claim and what the code does. Label this section "Intent Adherence" in your output and note the reduced confidence.

4g. Test Coverage
  • Are there tests for every new public function/method?
  • Do tests cover both happy and sad paths?
  • Are all error return values tested (not just success)?
  • Do tests assert behavior, not implementation details?
  • Are there integration tests where unit tests alone are insufficient?
  • Are test names descriptive of what they verify?
  • What did the mutation protocol prove? Surviving mutations are coverage findings, not footnotes.

If test coverage is inadequate, this is an Important or Critical finding depending on what's missing.

5. Classify Findings

Every finding gets a severity:

SeverityCriteriaExamples
CriticalBroken correctness, data loss risk, security vulnerability, plan requirement missingLogic bug in core path, SQL injection, unimplemented acceptance criterion, red test baseline
ImportantMeaningful quality issue, design violation, missing edge case handlingUnnecessary complexity, poor error propagation, leaky abstraction, surviving mutation
MinorStyle, naming, small readability improvements, minor redundancyInconsistent casing, unused import, overly verbose variable name

Output Contract

Your response MUST follow this structure exactly:

## Holistic Review

**Plan:** [plan file path, or "none -- intent reconstructed from commits/PR"]
**Base:** [base branch/commitish, note if auto-detected]
**Files Changed:** [count]
**Commits:** [count]

### Summary

[2-4 sentences: overall assessment. Was the plan followed? What is the general quality level? What stands out -- good or bad? If no plan existed, say so here.]

### Mutation Results

**Baseline:** green / red

| # | Mutation                          | Location    | Predicted failures | Actual failures | Verdict           |
| - | --------------------------------- | ----------- | ------------------ | --------------- | ----------------- |
| 1 | [what was broken and how]         | [file:line] | [tests]            | [tests]         | caught / survived |

[If mutations were skipped (red baseline), state that and why.]

### Findings

#### Critical

- **[C1] [file:line] [short title]**
  [Description of the issue. What's wrong, why it matters, what should change.]

#### Important

- **[I1] [file:line] [short title]**
  [Description.]

#### Minor

- **[M1] [file:line] [short title]**
  [Description.]

### Plan Adherence

[Title this "Intent Adherence" if no plan existed.]

| Requirement             | Status                  | Notes                    |
| ----------------------- | ----------------------- | ------------------------ |
| [requirement from plan] | Met / Partial / Missing | [explanation if not Met] |

### Verdict

**PASS** -- Zero issues found. Implementation is ready.
**FAIL** -- [N] Critical, [N] Important, [N] Minor issues must be addressed.

If there are zero findings in a severity category, write "None." under that heading.

Rules

  • Read every changed file in full. Diff hunks without context miss structural problems.
  • Read the plan (or write down reconstructed intent) before reviewing code. You cannot assess adherence to ground truth you haven't established.
  • Run the mutation protocol. A review whose Mutation Results section is empty without a stated reason is incomplete.
  • Restore every mutation. The only edits you may make are temporary mutations, and each one must be reverted before you proceed. Ending the review with a dirty working tree is a review failure regardless of findings.
  • Do not fix code. You are a reviewer, not an implementor. Report findings; someone else fixes them.
  • Do not soften findings. If something is wrong, say so directly. Do not hedge with "you might want to consider" -- state the issue and its severity.
  • Do not invent requirements. Review against what the plan actually says, not what you think it should say. If the plan doesn't mention performance testing, don't flag missing performance tests. Without a plan, hold the same line against your reconstructed intent.
  • Be thorough. A holistic review that misses issues is worse than no review -- it creates false confidence. Take the time to read everything.
  • Every finding needs a location. file:line for code issues. If a finding is architectural (no single line), reference the most relevant file.
  • PASS requires zero issues across all severities. Minor issues are not optional. A review with only Minor issues is still a FAIL.

PostgreSQL Development Patterns

Overview

Enforce transaction safety, type safety, and naming conventions to prevent data corruption and runtime errors.

Core principles:

  • Transactions prevent partial updates (data corruption)
  • Type safety catches errors at compile time
  • Naming conventions ensure consistency
  • Read-write separation prevents accidental mutations

Transaction Management

Transaction vs Query Execution

Methods that START transactions:

  • Must NOT accept a specific connection/executor parameter, takes things like a database pool or client
  • Create the transaction and then pass that transaction object to an underlying method that performs the actual query
  • Usually exported or public

Methods that PARTICIPATE in transactions:

  • MUST accept a generic connection/executor parameter
  • Execute queries using the provided executor
  • Usually unexported or private

What DOES NOT count as "starting a transaction":

  • Single INSERT/UPDATE/DELETE operations
  • Atomic operations like onConflictDoUpdate
  • SELECT queries

Type Safety

Primary Keys

Default: ULID stored as UUID

  • When in doubt, use ULID: "Most things can leak in some way"
  • Prevents ID enumeration attacks
  • Time-sortable for indexing efficiency

Exceptions (context-dependent):

  • Pure join tables (composite PK from both FKs)
  • Small lookup tables (serial/identity acceptable)
  • Internal-only tables with no user visibility (serial/identity acceptable)

Rule: If unsure whether data will be user-visible, use ULID.

Financial Data

Use exact decimal types (numeric/decimal) for monetary values:

  • Never use float/double for money (causes rounding errors)
  • Use numeric/decimal with appropriate precision and scale
  • Example: numeric(19, 4) for general financial data

Why: Floating-point types accumulate rounding errors. Exact decimal types prevent financial discrepancies.

JSONB Columns

ALWAYS type JSONB columns in your ORM/schema:

  • Use typed schema when structure is known
  • Use Record<string, unknown> if truly schemaless
  • Never leave JSONB untyped

Why: Prevents runtime errors from accessing undefined properties or wrong types.

Read-Write Separation

Maintain separate client types at compile time:

  • Read-write client: Full mutation capabilities
  • Read-only client: Mutation methods removed at type level
  • Default to read-only for query methods
  • Use read-write only when mutations needed

Why: Prevents accidental writes to replica, enforces deliberate mutation choices.

Naming Conventions

Database Identifiers

All database objects use snake_case:

  • Tables: user_preferences, order_items
  • Columns: created_at, user_id, is_active
  • Indexes: idx_tablename_columns (e.g., idx_users_email)
  • Foreign keys: fk_tablename_reftable (e.g., fk_orders_users)

Application code: Map to idiomatic case (camelCase in TypeScript, etc.)

Schema Patterns

Standard mixins:

  • created_at, updated_at timestamps on all tables
  • deleted_at for soft deletion when needed
  • tenant_id for multi-tenant tables (project-dependent)

Proactive indexing:

  • All foreign key columns
  • Columns used in WHERE clauses
  • Columns used in JOIN conditions
  • Columns used in ORDER BY

Concurrency

Default isolation (Read Committed) for most operations.

Use stricter isolation when:

  • Financial operations: Serializable isolation
  • Inventory/count operations: Serializable isolation
  • Critical sections: Pessimistic locking (SELECT ... FOR UPDATE)

Migrations

Always use generate + migrate workflow:

  1. Generate migration file
  2. Review migration SQL
  3. Apply migration to database

Never use auto-push workflow in production.

Common Mistakes

MistakeRealityFix
"This is one operation, doesn't need transaction"Multi-step operations without transactions cause partial updates and data corruptionWrap in transaction with TX_ prefix
"Single atomic operation needs TX_ prefix"TX_ is for explicit transaction blocks, not atomic operationsNo TX_ for single INSERT/UPDATE/DELETE
"UUID is just a string"Type confusion causes runtime errors (wrong ID formats, failed lookups)Use strict UUID type in language
"I'll type JSONB later when schema stabilizes"Untyped JSONB leads to undefined property access and type errorsType immediately with known fields or Record<string, unknown>
"Read client vs write client doesn't matter"Using wrong client bypasses separation, allows accidental mutationsUse read-only client by default, switch deliberately
"I'll add indexes when we see performance issues"Missing indexes on foreign keys cause slow queries from day oneAdd indexes proactively for FKs and common filters
"This table won't be user-visible, use serial"Requirements change, IDs leak in logs/URLs/errorsUse ULID by default unless certain it's internal-only
"Float/double is fine for money, close enough"Rounding errors accumulate, causing financial discrepancies (0.01 differences multiply)Use numeric/decimal types for exact arithmetic

Red Flags - STOP and Refactor

Transaction management:

  • Method calls .transaction() but no TX_ prefix
  • Method has TX_ prefix but accepts executor parameter
  • Multi-step operation without transaction wrapper

Type safety:

  • JSONB column without type annotation
  • UUID/ULID stored as plain string type
  • No separation between read and write clients
  • Float/double types for monetary values

Schema:

  • Missing indexes on foreign keys
  • No created_at/updated_at timestamps
  • camelCase or PascalCase in database identifiers

All of these mean: Stop and fix immediately.

GitHub Issue Hygiene

Overview

A mechanical hygiene pass over a GitHub issue: correct title, correct labels and metadata, valid markdown body. This is the lint layer - it does NOT judge whether the issue is well-reasoned or complete (that is authoring-issues). Run it after drafting an issue, or when asked to tidy or triage existing ones.

All edits go through the gh CLI. Verify current state before changing anything, and change only what is wrong (minimal edits).

When to Use

  • Creating or editing an issue and about to finalize it.
  • User asks to "clean up", "triage", "retitle", "tag", "label", or "fix up" an issue.
  • Immediately after authoring-issues produces a draft.
  • Bulk triage of a backlog.

The Checklist

Title

  • Reflects the CURRENT body. If the scope changed, update the title to match.
  • Concise and specific, imperative or noun-phrase. No trailing period.
  • Follow the repo's existing prefix convention if one exists (e.g. area:, [component]) - check sibling issues first; do not invent one.

Labels and metadata

  • List the repo's real labels first: gh label list. NEVER apply a label that does not exist unless explicitly asked to create one.
  • Apply at least a type (bug/feature/chore/...) and an area/component label when those label families exist.
  • Set assignee, milestone, and project only when known; do not guess.
  • Link related work in the body: Closes #N, Refs #N. Mark duplicates.

Body markdown

  • Headings nest correctly (no skipped levels); use sentence case.
  • Every fenced code block is closed and language-tagged.
  • Lists and task lists are well-formed (- [ ] / - [x]); tables have aligned header separators.
  • Links and #issue / @user references resolve.
  • No placeholder or broken text left behind.

Commands

gh issue view <n> --json title,body,labels,assignees,milestone
gh label list                                   # real labels before tagging
gh issue edit <n> --title "..." \
  --add-label bug --add-label "area:api" \
  --milestone "v1.2"
gh issue create --title "..." --body-file draft.md --label bug

Render-check the body (gh issue view <n> --web, or preview the markdown) before declaring done.

Red Flags - Stop

  • Inventing a label or milestone that does not exist in the repo.
  • Rewriting the body's CONTENT to "improve" it - that is authoring-issues, not hygiene.
  • Altering meaning while "fixing markdown".
  • Leaving the title describing an older version of the body.

Property-Based Testing

Overview

Property-based testing (PBT) generates random inputs and verifies that properties hold for all of them. Instead of testing specific examples, you test invariants.

When PBT beats example-based tests:

  • Serialization pairs (encode/decode)
  • Pure functions with clear contracts
  • Validators and normalizers
  • Data structure operations

Property Catalog

PropertyFormulaWhen to Use
Roundtripdecode(encode(x)) == xSerialization, conversion pairs
Idempotencef(f(x)) == f(x)Normalization, formatting, sorting
InvariantProperty holds before/afterAny transformation
Commutativityf(a, b) == f(b, a)Binary/set operations
Associativityf(f(a,b), c) == f(a, f(b,c))Combining operations
Identityf(x, identity) == xOperations with neutral element
Inversef(g(x)) == xencrypt/decrypt, compress/decompress
Oraclenew_impl(x) == reference(x)Optimization, refactoring
Easy to Verifyis_sorted(sort(x))Complex algorithms
No ExceptionNo crash on valid inputBaseline (weakest)

Strength hierarchy (weakest to strongest):

No Exception -> Type Preservation -> Invariant -> Idempotence -> Roundtrip

Always aim for the strongest property that applies.

Pattern Detection

Use PBT when you see:

PatternPropertyPriority
encode/decode, serialize/deserializeRoundtripHIGH
toJSON/fromJSON, pack/unpackRoundtripHIGH
Pure functions with clear contractsMultipleHIGH
normalize, sanitize, canonicalizeIdempotenceMEDIUM
is_valid, validate with normalizersValid after normalizeMEDIUM
Sorting, ordering, comparatorsIdempotence + orderingMEDIUM
Custom collections (add/remove/get)InvariantsMEDIUM
Builder/factory patternsOutput invariantsLOW

When NOT to Use

  • Simple CRUD without transformation logic
  • UI/presentation logic
  • Integration tests requiring complex external setup
  • Code with side effects that cannot be isolated
  • Prototyping where requirements are fluid
  • Tests where specific examples suffice and edge cases are understood

Library Quick Reference

LanguageLibraryImport
PythonHypothesisfrom hypothesis import given, strategies as st
TypeScript/JSfast-checkimport fc from 'fast-check'
Rustproptestuse proptest::prelude::*
Gorapidimport "pgregory.net/rapid"
Javajqwik@Property annotations
HaskellQuickCheckimport Test.QuickCheck

For library-specific syntax and patterns: Use @ed3d-research-agents:internet-researcher to get current documentation.

Input Strategy Best Practices

  1. Constrain early: Build constraints INTO the strategy, not via assume()

    # GOOD
    st.integers(min_value=1, max_value=100)
    
    # BAD - high rejection rate
    st.integers().filter(lambda x: 1 <= x <= 100)
    
  2. Size limits: Prevent slow tests

    st.lists(st.integers(), max_size=100)
    st.text(max_size=1000)
    
  3. Realistic data: Match real-world constraints

    st.integers(min_value=0, max_value=150)  # Real ages, not arbitrary ints
    
  4. Reuse strategies: Define once, use across tests

    valid_users = st.builds(User, ...)
    
    @given(valid_users)
    def test_one(user): ...
    
    @given(valid_users)
    def test_two(user): ...
    

Settings Guide

# Development (fast feedback)
@settings(max_examples=10)

# CI (thorough)
@settings(max_examples=200)

# Nightly/Release (exhaustive)
@settings(max_examples=1000, deadline=None)

Quality Checklist

Before committing PBT tests:

  • Not tautological (assertion doesn't compare same expression)
  • Strong assertion (not just "no crash")
  • Not vacuous (inputs not over-filtered by assume())
  • Edge cases covered with explicit examples (@example)
  • No reimplementation of function logic in assertion
  • Strategy constraints are realistic
  • Settings appropriate for context

Red Flags

  • Tautological: assert sorted(xs) == sorted(xs) tests nothing
  • Only "no crash": Always look for stronger properties
  • Vacuous: Multiple assume() calls filter out most inputs
  • Reimplementation: assert add(a, b) == a + b if that's how add is implemented
  • Missing edge cases: No @example([]), @example([1]) decorators
  • Overly constrained: Many assume() calls means redesign the strategy

Common Mistakes

MistakeFix
Testing mock behaviorTest real behavior
Reimplementing function in testUse algebraic properties
Filtering with assume()Build constraints into strategy
No edge case examplesAdd @example decorators
One property onlyAdd multiple properties (length, ordering, etc.)

Writing for a Technical Audience

Overview

Core principle: Technical writing must be clear, concise, and authentic. Clarity and technical depth are not opposites - you can have both. Avoid AI writing patterns that make content feel robotic or inauthentic.  Why this matters: Developers value their time. Clear documentation builds trust. AI-like writing patterns (identified through research) make content feel generic and untrustworthy. Technical depth without clarity frustrates users. Clarity without depth leaves them stuck.

When to Use

Use this skill when:

  • Writing API documentation or references
  • Creating guides, tutorials, or how-to content
  • Documenting code, features, or architecture
  • Writing technical blog posts or articles
  • Reviewing technical content for clarity

Trigger symptoms:

  • "Does this sound too robotic?"
  • Writing feels formal or stiff
  • Using phrases like "delve into" or "leverage"
  • Explaining obvious things instead of getting to the point
  • Uncertain if content is clear enough

The Three Pillars

1. Clarity

Developers should understand on first read. No re-reading required.

Techniques:

  • Short sentences (15-20 words average)
  • Short paragraphs (2-4 sentences)
  • Active voice over passive
  • One concept per paragraph
  • Define technical terms on first use

2. Conciseness

Every word serves a purpose. Remove noise and filler.

Techniques:

  • Delete throat-clearing ("Let me explain," "It's important to note")
  • Cut hedging language ("basically," "generally speaking")
  • Remove marketing fluff ("powerful," "robust," "seamless")
  • Use direct language ("use" not "leverage," "show" not "illuminate")

3. Consistency

Same terminology, structure, and voice throughout.

Techniques:

  • Pick one term and stick to it (not "endpoint," "URL," "route" interchangeably)
  • Use consistent code formatting
  • Maintain same tone across all content
  • Follow established patterns for similar content types

Avoid AI Writing Patterns

Research shows specific phrases and structures that readers identify as AI-generated. Avoid these to maintain authenticity.

AI Phrases to Never Use

AI PhraseWhy It's BadUse Instead
"delve into"Overly formal, 269x spike post-ChatGPT"explore," "examine," "look at"
"leverage"Corporate jargon"use," "take advantage of"
"robust" / "seamless"Vague marketing adjectivesBe specific about what you mean
"at its core"Condescending simplification"fundamentally" (use rarely) or delete
"cutting-edge" / "revolutionary"Empty hypeDescribe actual features
"streamline" / "optimize"Vague promises"speed up," "reduce," "improve"
"foster" / "cultivate"Bland corporate speakUse direct action verbs
"unlock the potential"Cliched metaphorState specific outcome
"in today's fast-paced world"Generic fillerDelete entirely
"needless to say"If needless, don't say itDelete

Throat-Clearing to Delete

Never start with:

  • "Let me explain..."
  • "It's important to note that..."
  • "It's worth noting..."
  • "In essence..."
  • "Let's explore..."

Fix: Start with substance. Delete the preamble.

Hedging Language to Eliminate

HedgedConfident
"I think we should...""We should..."
"It would be great if...""Please do X"
"Should be able to...""Can complete..."
"Basically..."Delete it
"Generally speaking..."Be specific or remove
"One might argue...""This indicates..."

Why hedging fails: Makes you sound uncertain even when you're correct. State facts directly.

Transition Word Overuse

AI defaults to formal Victorian-era connectors. Use simpler alternatives or break paragraphs.

Overused AIBetter
Moreover / FurthermorePlus, also, and
However / NeverthelessBut, though, still
AdditionallyAnd, plus
Consequently / As a resultSo, then
That being saidBut (or delete)
Indeed / InterestinglyOften delete entirely
In conclusionEnd cleanly without announcing it

Technical Writing Patterns

Explain WHY for These Cases

ALWAYS explain why when:

  1. Design decisions with tradeoffs

    • Good: "We use pagination instead of cursors because it's simpler for most use cases and maintains consistent ordering"
    • Bad: "We use pagination" (no context for when to deviate)
  2. Non-obvious patterns

    • Good: "Row Level Security must be enabled on all tables exposed via the Data API because it enforces security at the database level, preventing bypass through direct SQL access"
    • Bad: "Enable RLS on all tables" (why?)
  3. Breaking from conventions

    • Good: "This API uses POST for reads because GET requests can't include request bodies in some HTTP clients"
    • Bad: "Use POST to fetch data" (violates REST conventions without justification)

When "how" alone suffices:

  • Mechanical steps with no alternatives ("Click Save")
  • Standard practices ("Use npm install")
  • When you genuinely don't know why (document behavior, note uncertainty)

Code Examples: One Excellent Example

Don't:

  • Implement in 5 languages
  • Create fill-in-the-blank templates
  • Write perfect-world examples with no error handling

Do:

  • One complete, runnable example
  • Include error handling
  • Show realistic usage
  • Comment WHY, not what

Good Example Pattern:

# Good: Complete, realistic, explains why
try:
    response = await fetch_user(user_id)
    # Check status before assuming success - API returns 200 for "not found"
    if response.status != 200:
        raise APIError(f"Failed to fetch user: {response.status}")
    return response.json()
except NetworkError as e:
    # Network failures are retryable - log and re-raise for retry logic
    logger.warning(f"Network error fetching user {user_id}: {e}")
    raise

Bad Example Pattern:

# Bad: Perfect world, no context, brittle
response = await fetch_user(user_id)
return response.json()

Progressive Disclosure

Layer complexity. Simple first, then depth.

Pattern:

  1. Basic explanation - what it does, core concept
  2. Simple example - minimal working code
  3. Advanced section - edge cases, configuration, tradeoffs
  4. Reference - complete API surface

Good:

## Authentication

All API requests require an API key in the Authorization header:

```bash
curl -H "Authorization: Bearer YOUR_API_KEY" https://api.example.com/users

Advanced: Token Rotation

For production systems, rotate API keys every 90 days...


**Bad:**
```markdown
## Authentication

Authentication can be performed using several methods including API keys, OAuth 2.0, or JWT tokens. The choice depends on your security requirements, user experience goals, and architectural constraints. Let's explore each option...

(Too much upfront. Start simple.)

Anti-Patterns from Real Documentation

1. Assumes Too Much

Bad:

"Simply connect your ETLOrchestrator to the HydraNode endpoint. Once a connection is established, instantiate a DataStream by passing your KinesisConfiguration."

Why it fails: Jargon firehose with no definitions, no links, no onramp for beginners.

Fix: Define terms, link to prerequisites, provide Getting Started guide.

2. Perfect World Examples

Bad:

const myFile = document.getElementById('file-input').files[0];
const response = await uploadFile('/api/upload', myFile);
console.log('File uploaded successfully!');

Why it fails: No error handling, ignores edge cases (no file selected, network failure, file too large).

Fix: Wrap in try-catch, check response status, handle undefined files.

3. Vague and Unhelpful

Bad:

  • getUser(userId): "Gets a user by their ID."
  • class DataProcessor: "A class for processing data."
  • processData(data): "Processes the data."

Why it fails: Tautological. Says nothing beyond the function name.

Fix: Describe behavior, parameters, return values, exceptions. "Fetches user record from database, returns null if user doesn't exist. Throws AuthError if API key lacks read permissions."

Pro-Examples from Industry Leaders

Supabase (Clarity + Depth)

"Row Level Security (RLS) is a PostgreSQL feature that allows you to control which rows a user can access in a table. When you enable RLS on a table, all SELECT, INSERT, UPDATE, and DELETE operations are subject to a security policy. A policy is a SQL expression that returns a boolean value. If the expression returns true, the operation is allowed to proceed. If it returns false or null, the operation is denied."

Why it works: Defines RLS, explains scope (CRUD operations), defines mechanism (policy = SQL boolean expression). Dense with information, perfectly clear.

Stripe (Predictable Contract)

"Stripe uses conventional HTTP response codes to indicate the success or failure of an API request. In general: Codes in the 2xx range indicate success. Codes in the 4xx range indicate an error that failed given the information provided. Codes in the 5xx range indicate an error with Stripe's servers."

Why it works: Establishes predictable contract for fundamental API behavior. Technical, precise, immediately useful.

Astro (Anticipates Questions)

"You can run create-astro anywhere on your machine, so you don't have to create an empty directory for your project first. If you don't have an empty directory yet, the wizard will help you create one."

Why it works: Anticipates common beginner question ("Do I need to make a folder first?") and answers it proactively.

Tailwind CSS (Teaches Philosophy)

"The biggest maintainability concern when using a utility-first approach is managing commonly repeated utility combinations. The traditional approach is to extract repeated utilities into a component class. We believe that @apply should be used sparingly. The best way to manage repeated utility combinations is to create reusable components with a templating language."

Why it works: Identifies problem, presents common solution, explains why that solution is suboptimal, guides toward better approach. Teaches philosophy, not just features.

Writing That Feels Human

Use Contractions

AI defaults to:

  • "It is important that you do not..."
  • "You will need to..."

Human writing:

  • "It's important that you don't..."
  • "You'll need to..."

Vary Sentence Length

AI writes: Every paragraph is 3-4 sentences. Every sentence is 15-20 words. Everything feels perfectly balanced and rhythmic in an uncanny way.

Human writes: Short sentences create emphasis. Longer sentences provide context, explanation, or explore nuance that requires more breathing room. Mix them. Create rhythm naturally.

Add Personality

AI avoids:

  • First person ("I," "we")
  • Opinions
  • Personal anecdotes
  • Humor

Human includes:

  • "We tried the obvious solution first and it failed"
  • "I found this approach more practical because..."
  • Opinions grounded in experience
  • Self-aware observations

Break Grammar Rules Intentionally

AI never:

  • Starts sentences with "And" or "But"
  • Uses sentence fragments
  • Ends with prepositions

Human does:

  • "And that's exactly the point." (emphasis)
  • "This is what we're dealing with." (natural)

Be Specific

AI writes vaguely:

  • "This approach offers significant benefits"
  • "Companies have seen improved results"

Human writes specifically:

  • "We reduced latency from 450ms to 120ms"
  • "Three team members raised concerns about X"

Code Comments and Documentation

Punctuation

Always use periods at the end of code comments.

// Good: Validates user input before processing.
// Bad: validates user input before processing

Headings

Use sentence case in all headings. Never title case.

Good: ## Error handling patterns
Bad:  ## Error Handling Patterns

Good: ### When to use async
Bad:  ### When To Use Async

Error Messages

Format error messages as lowercase sentence fragments. They compose naturally when chained.

Good: failed to parse configuration: invalid JSON at line 42
Bad:  Failed to Parse Configuration: Invalid JSON at Line 42

The lowercase format works because errors often chain: "operation failed: " + innerError.message reads correctly.

Red Flags - Review Checklist

Before publishing, check for these issues:

  • No AI phrases ("delve," "leverage," "robust," "at its core")
  • No throat-clearing openings ("Let me explain," "It's important to note")
  • No hedging language ("basically," "generally speaking")
  • No marketing fluff ("powerful," "revolutionary," "cutting-edge")
  • Sentence length varies (not all 15-20 words)
  • Paragraph length varies (not all 3-4 sentences)
  • Contractions used naturally ("it's" not "it is")
  • Active voice, clear actors (not "it can be seen that")
  • Code examples include error handling
  • WHY explained for design decisions
  • Technical terms defined on first use
  • Specific numbers/names/details (not vague claims)
  • Read aloud test - does it sound natural?
  • Code comments end with periods
  • Headings use sentence case (not Title Case)
  • Error messages are lowercase sentence fragments

Common Mistakes and Fixes

MistakeRealityFix
"Just being thorough with explanations"You're explaining obvious things.Delete explanations of what developers already know.
"Keeping it professional with formal language"Formal = robotic.Use contractions, conversational tone, natural language.
"Covering all the edge cases upfront"Overwhelms reader.Basic case first, advanced section for edge cases.
"Using precise technical terminology"Jargon without definitions loses readers.Define terms on first use, link to glossary.
"Being careful with hedging language"Hedging makes you sound uncertain.State facts directly. Remove qualifiers.
"Perfect code examples look cleaner"Perfect world examples are brittle in practice.Include error handling, show realistic usage.
"More examples = more helpful"Too many examples = noise.One excellent, complete example beats five shallow ones.

Summary

Technical writing in three rules:

  1. Clear and concise - Short sentences, short paragraphs, active voice, no filler
  2. Authentic voice - Contractions, varied rhythm, personality, specific details
  3. Explain why - Design decisions, tradeoffs, non-obvious patterns need justification

Avoid AI markers: No "delve," "leverage," "robust." No throat-clearing. No hedging. No formal transitions.

One excellent example beats five mediocre ones. Include error handling. Show realistic usage.

Technical depth + clarity are not opposites. You can have both. Supabase, Stripe, and Cloudflare prove this daily.

Read aloud test: If it sounds robotic or overly formal, rewrite it.

Writing Good Tests

Philosophy

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

Tests verify real behavior, not implementation details. The goal is confidence that your code works. Coverage numbers are neccessary but not sufficient.

Core principles:

  1. Test behavior, not implementation — refactoring shouldn't break tests
  2. Integration tests provide better confidence-to-cost ratio than unit tests
  3. Wait for actual conditions, not arbitrary timeouts
  4. Mock strategically — real dependencies when feasible, mocks for external systems
  5. NEVER pollute production code with test-only methods

Test Structure

Always prefer and use table driven tests, with a single test function that is then given a name, fed an input, and then asserts output and error return equality.

Once this is implemented, test cases should be cheap and easy to add. Ensure there are cases for all possible success and error cases. If possible exhaustively test for all side effects. If a side effect is contained within the function that is being tested and not part of the return, but has a material effect on how the function behaves consider mocking. This could also be a potential bad code smell, and a refactor of the function to make it more testable should be considered.

package foo

import (
	"errors"
	"fmt"
	"testing"
)

var (
	ErrEmpty      = errors.New("empty")
	ErrNotInt     = errors.New("not an int")
	ErrOutOfRange = errors.New("out of range")
)

func TestParsePort(t *testing.T) {
	t.Parallel()

	type tc struct {
		name string
		in   string
		want int
		err  error
	}

	tests := []tc{
		{
			name: "valid_low",
			in:   "1",
			want: 1,
		},
		{
			name: "valid_high",
			in:   "65535",
			want: 65535,
		},
		{
			name: "empty",
			in:   "",
			err:  ErrEmpty,
		},
		{
			name: "not_int",
			in:   "abc",
			err:  ErrNotInt,
		},
		{
			name: "out_of_range_zero",
			in:   "0",
			err:  ErrOutOfRange,
		},
		{
			name: "out_of_range_too_big",
			in:   "70000",
			err:  ErrOutOfRange,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			got, err := ParsePort(tt.in)

			if !errors.Is(err, tt.err) {
				t.Fatalf("error mismatch: want %v, got %v", tt.err, err)
			}

			if tt.err != nil {
				return
			}

			if got != tt.want {
				t.Fatalf("value mismatch: want %d, got %d", tt.want, got)
			}
		})
	}
}

One action per test. Multiple assertions are fine if they verify the same behavior.

Condition-Based Waiting

Flaky tests often guess at timing. This creates race conditions where tests pass locally but fail in CI.

Wait for conditions, not time:

// BAD: Guessing at timing
await new Promise((r) => setTimeout(r, 50));
const result = getResult();

// GOOD: Waiting for condition
await waitFor(() => getResult() !== undefined);
const result = getResult();

Generic Polling Function

async function waitFor<T>(
  condition: () => T | undefined | null | false,
  description: string,
  timeoutMs = 5000,
): Promise<T> {
  const startTime = Date.now();

  while (true) {
    const result = condition();
    if (result) return result;

    if (Date.now() - startTime > timeoutMs) {
      throw new Error(
        `Timeout waiting for ${description} after ${timeoutMs}ms`,
      );
    }

    await new Promise((r) => setTimeout(r, 10)); // Poll every 10ms
  }
}

Quick Patterns

ScenarioPattern
Wait for eventwaitFor(() => events.find(e => e.type === 'DONE'))
Wait for statewaitFor(() => machine.state === 'ready')
Wait for countwaitFor(() => items.length >= 5)

When Arbitrary Timeout IS Correct

Only when testing actual timing behavior (debounce, throttle, intervals):

// Testing tool that ticks every 100ms
await waitForEvent(manager, "TOOL_STARTED"); // First: wait for condition
await new Promise((r) => setTimeout(r, 200)); // Then: wait for 2 ticks
// Comment explains WHY: 200ms = 2 ticks at 100ms intervals

Mocking Strategy

"You don't hate mocks; you hate side-effects." — J.B. Rainsberger

Mocks reveal where side-effects complicate your code. Use them strategically, not reflexively.

Don't Mock What You Don't Own

Create thin wrappers around third-party libraries. Mock YOUR wrapper, not the library.

// BAD: Mock the HTTP client directly
const mockClient = vi.mocked(httpx.Client);

// GOOD: Create your own wrapper
class RegistryClient {
  constructor(private client: HttpClient) {}
  async getRepos() {
    return this.client.get("https://registry.example.com/v2/_catalog");
  }
}

// Mock your wrapper
vi.mock("./registry-client");

This simplifies tests AND improves your design.

Managed vs Unmanaged Dependencies

Dependency TypeExampleStrategy
Managed (you control it)Your database, your file systemUse REAL instances
Unmanaged (external)Third-party APIs, SMTP, message busUse MOCKS

Communications with managed dependencies are implementation details — you can refactor them freely. Communications with unmanaged dependencies are observable behavior — mocking protects against external changes.

Anti-Pattern: Testing Mock Behavior

// BAD: Testing that the mock exists
test('renders sidebar', () => {
  render(<Page />);
  expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument();
});

// GOOD: Test real behavior
test('renders sidebar', () => {
  render(<Page />);
  expect(screen.getByRole('navigation')).toBeInTheDocument();
});

Gate: Before asserting on any mock element, ask: "Am I testing real behavior or mock existence?"

Anti-Pattern: Mocking Without Understanding

// BAD: Mock breaks test logic
test("detects duplicate server", () => {
  // Mock prevents config write that test depends on!
  vi.mock("ToolCatalog", () => ({
    discoverAndCacheTools: vi.fn().mockResolvedValue(undefined),
  }));
  await addServer(config);
  await addServer(config); // Should throw - but won't!
});

// GOOD: Mock at correct level
test("detects duplicate server", () => {
  vi.mock("MCPServerManager"); // Just mock slow server startup
  await addServer(config); // Config written
  await addServer(config); // Duplicate detected
});

Gate: Before mocking, ask: "What side effects does this have? Does my test depend on them?"

Anti-Pattern: Incomplete Mocks

Mock the COMPLETE data structure as it exists in reality:

// BAD: Partial mock
const mockResponse = {
  status: "success",
  data: { userId: "123" },
  // Missing: metadata that downstream code uses
};

// GOOD: Mirror real API
const mockResponse = {
  status: "success",
  data: { userId: "123", name: "Alice" },
  metadata: { requestId: "req-789", timestamp: 1234567890 },
};

When Mocks Become Too Complex

Warning signs:

  • Mock setup longer than test logic
  • Mocking everything to make test pass
  • Test breaks when mock changes

"As the number of mocks grows, the probability of testing the mock instead of the desired code goes up." — Codurance

Consider integration tests with real components — often simpler than elaborate mocks.

Anti-Pattern: Test-Only Methods in Production

// BAD: destroy() only used in tests
class Session {
  async destroy() {
    /* cleanup */
  }
}

// GOOD: Test utilities handle cleanup
// test-utils/session-helpers.ts
export async function cleanupSession(session: Session) {
  const workspace = session.getWorkspaceInfo();
  if (workspace) {
    await workspaceManager.destroyWorkspace(workspace.id);
  }
}

Gate: Before adding any method to production class, ask: "Is this only used by tests?" If yes, put it in test utilities.

Test Isolation

Tests should not depend on execution order. But isolation doesn't mean cleaning up everything.

What to Clean Up

Long-lived resources MUST be cleaned up:

  • Virtual machines, containers
  • Kubernetes jobs, pods, deployments
  • Cloud resources (instances, buckets)
  • Background processes, daemons

Prefer product tools for cleanup when possible:

afterAll(async () => {
  // Use the product's own cleanup mechanisms
  await deployment.delete();
  await job.terminate();
});

Side-channel cleanup when product tools aren't available:

afterAll(async () => {
  // Direct cleanup when product doesn't provide it
  await exec("kubectl delete job test-job-123");
});

What's OK to Leave

Database artifacts are fine to leave around. Trying to clean up test data perfectly is a fool's errand and makes multi-step integration tests nearly impossible.

  • Test records in databases
  • Log entries
  • Cached data that expires

The database should handle its own lifecycle. Tests that require pristine state should create unique identifiers, not depend on cleanup.

Preventing Order Dependencies

// Use unique identifiers instead of depending on clean state
const testId = `test-${Date.now()}-${Math.random()}`;
const user = await createUser({ email: `${testId}@test.com` });

Quick Reference

ProblemFix
Arbitrary setTimeout in testsUse condition-based waiting
Assert on mock elementsTest real component or unmock
Mock third-party directlyCreate wrapper, mock wrapper
Test-only methods in productionMove to test utilities
Mock without understandingUnderstand dependencies first
Incomplete mocksMirror real API completely
Over-complex mocksConsider integration tests
Long-lived resources left runningClean up VMs, k8s jobs, cloud resources

Red Flags

Stop and reconsider when you see:

  • Arbitrary setTimeout/sleep without justification
  • Assertions on mock elements or test IDs
  • Methods only called in test files
  • Mock setup is >50% of test code
  • "Mocking just to be safe"
  • Test depends on another test running first
  • Long-lived resources not cleaned up

TDD Connection

TDD prevents most testing anti-patterns:

  • Write test first → forces thinking about what you're testing
  • Watch it fail → confirms test tests real behavior, not mocks
  • Minimal implementation → no test-only methods creep in
  • Real dependencies first → you see what test needs before mocking

Property-Based Testing

For certain patterns, property-based testing provides stronger coverage than example-based tests. See property-based-testing skill for complete reference.

When to Use PBT

PatternExampleWhy PBT
Serialization pairsencode/decode, toJSON/fromJSONRoundtrip property catches edge cases
Normalizerssanitize, canonicalize, formatIdempotence property ensures stability
Validatorsis_valid, validateValid-after-normalize property
Pure functionsBusiness logic, calculationsMultiple properties verify contract
Sorting/orderingsort, rank, compareOrdering + idempotence properties

When NOT to Use PBT

  • Simple CRUD without transformation
  • UI/presentation logic
  • Integration tests requiring external setup
  • When specific examples suffice and edge cases are well-understood
  • Prototyping with fluid requirements

PBT Quality Gates

Before committing property-based tests:

  • Not tautological: Assertion doesn't compare same expression (sorted(xs) == sorted(xs) tests nothing)
  • Strong property: Not just "no crash" - aim for roundtrip, idempotence, or invariants
  • No reimplementation: Don't restate function logic in assertion (assert add(a,b) == a+b)
  • Realistic constraints: Strategy matches real-world input constraints

Sponsors

Details

Marketplace
pbdeuchler/llm-plugins
Source
plugins/house-style
Author
PBD
Category
Community

More from pbdeuchler/llm-plugins

All 7