Invariant first coding

From Kevin-Liu-01/Agent-Machines · View interactive version

Invariant first coding is an AI agent skill from the GitHub repository Kevin-Liu-01/Agent-Machines. Reason from proven invariants before coding. Use when reviewing fallback logic, narrowing types, handling conversions, deciding whether an error path is real or impossible, removing overdefensive code, or when the user questions whether code is being too theatrical, too hedged, or not fail-closed en

How to use this skill

Skill file

Invariant-First Coding

Write code that matches the real system.

If a system invariant already proves a condition, encode that invariant

directly. Do not add fallback branches, saturation logic, or “safe-looking”

defaults just to appear careful.

This skill is about coding and review discipline, not architecture or

testing in isolation.

The rule

Before writing or approving a branch, ask:

  1. What is the real invariant?
  2. Is this case actually reachable?
  3. If it is reachable, is it normal runtime behavior or an invariant violation?
  4. What is the honest way to encode that distinction?

If the branch exists only because a conversion is typed as fallible, or because

the author felt nervous, that branch is probably theater.

What counts as theater

Common examples:

The problem is not style. The problem is lying about the system.

Classify the situation first

Every suspicious branch is one of three things:

1. Real runtime case

The case can happen during correct operation.

Examples:

Handle it as part of the interface contract.

2. Invariant violation

The case should be impossible if the surrounding system is correct.

Examples:

Do not paper over this with fallback behavior. Assert it, crash fast, or return

an explicit internal error, depending on the layer.

3. Type-system artifact

The language forces a fallible conversion or optional path, but the domain has

already ruled failure out.

Examples:

Prefer code that states the invariant plainly instead of pretending the

conversion is meaningfully uncertain.

Preferred responses

Prefer narrower types

If the value is naturally bounded, choose a type that encodes the bound.

Bad:

let slots = u32::try_from(count).unwrap_or(u32::MAX);

Better:

let slots = u32::try_from(count)
    .expect("per-host slot count must fit in u32");

Best, if practical:

struct HostSlotCount(u16);

The goal is to make invalid states unrepresentable or at least explicit.

Prefer assertions for impossible states

If a condition is impossible by invariant, say so.

Bad:

let count = u32::try_from(value).unwrap_or(u32::MAX);

Good:

let count = u32::try_from(value)
    .expect("workspace count must fit in u32");

Use:

Prefer typed errors for real runtime failures

If the case can happen normally, model it.

Bad:

let enabled = env::var("FEATURE").ok().unwrap_or("false".into()) == "true";

Good:

let raw = env::var("FEATURE").map_err(ConfigError::MissingFeatureFlag)?;
let enabled = parse_feature_flag(&raw)?;

Prefer deleting dead fallbacks

If an old branch no longer represents a real mode, delete it.

Bad:

if canUsePrimary() {
    return primary()
}
return fallback()

Good:

if !canUsePrimary() {
    return ErrPrimaryUnavailable
}
return primary()

Or, if the primary is the only supported mode:

return primary()

Layer-specific guidance

API boundary

At an API boundary:

Internal service or daemon

Inside a daemon or service:

Startup and configuration

During startup:

Startup is one of the few legitimate places for hard assertions.

Questions to ask during review

Use this checklist when you see defensive-looking code:

Language-specific hints

Rust

mask impossible states.

Example:

fn u32_from_host_slot_count(value: usize) -> u32 {
    u32::try_from(value).expect("per-host slot count must fit in u32")
}

Go

states if the process must stay alive.

General

best effort.

not happen.

Anti-patterns

Bad: defensive theater

Code that exists only to make the author feel prudent:

Bad: hidden degradation

If the interface promises strong semantics, do not quietly weaken them in the

implementation.

Bad: uncertain comments

Comments like:

without stating the actual invariant are a red flag.

State the invariant, or redesign the code.

Completion checklist

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.