Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:1ay1 Agentty Unrepresentable Invalid State

From Leeroopedia
Knowledge Sources
Domains Type_Safety, Architecture
Last Updated 2026-10-28 14:00 GMT

Overview

Design types so that invalid states cannot be represented in the first place, making compile-time enforcement replace runtime validation.

Description

The Unrepresentable_Invalid_State heuristic (also known as "parse, don't validate" or "make illegal states unrepresentable") means choosing type shapes that structurally exclude invalid combinations. Instead of a runtime check that rejects bad data after the fact, the type system prevents bad data from being constructed at all. Sum types, refinement types, strong newtype IDs, and typestate patterns are all tools for this.

In agentty this appears in: strong newtype IDs (`id.hpp`) that prevent mixing a `ThreadId` with a `ToolCallId`; refinement types (`refined.hpp`) that make an invalid `Positive<int>` unconstructible; the entitlement registry (`entitlement.hpp`) that scopes facts to an account at the type level; and the typestate IO lifecycle (`fsm.hpp`) that makes "use IO after close" a compile error.

Usage

Apply this heuristic when designing domain types, state machines, or identifiers. If a runtime check is guarding against a state that "shouldn't happen," ask whether the type can be reshaped to make that state unrepresentable instead. The cost is more type machinery; the benefit is that an entire class of bugs moves from runtime to compile time.

The Insight (Rule of Thumb)

  • Action: Replace runtime validation with type-level constraints that make invalid states unconstructible.
  • Value: Sum types, newtypes, refinement types, typestate — the invalid data never exists as a value.
  • Trade-off: More complex type definitions; but bugs are caught at compile time, not production.
  • Compatibility: Requires a type system with sum types or equivalent; C++ achieves this via `std::variant`, strong typedefs, and concepts.

Reasoning

Runtime validation is a running cost: every call site must remember to validate, and forgetting once is a bug. Type-level constraints are a one-time cost: the type is defined once, and every use site is automatically checked by the compiler. The compiler never forgets, never skips, and never fatigues. Moving the constraint from runtime to compile time eliminates the human error of forgetting to validate, and makes the valid/invalid distinction visible in every function signature.

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment