invariant-guard — Correctness-First Coding
The model knows what a loop invariant is. It knows recursion needs a base case. It knows about empty lists, integer overflow, and the difference between < and ≤. It just does not write these down before producing code, so it ships subtle correctness bugs that tests do not catch.
invariant-guard fixes the behavior. State the invariants. State the base case. State the termination argument. State the edge cases. Then write the code — and verify that the code maintains what you stated.
Violating the letter of these rules is violating the spirit of the skill. "I know this algorithm" is the exact rationalization that ships off-by-one and missing-postcondition bugs.
When to Use
Use invariant-guard when writing or reviewing algorithms where the obvious implementation is subtly wrong:
- Postcondition stronger than the loop's natural invariant: Boyer–Moore majority, Floyd's cycle detection, leftmost vs any binary search, QuickSelect partition.
- In-place mutation with read+write pointers: dedup-in-place, partition, rotate.
- Recursion with multiple parameters or accumulator state.
- Off-by-one suspects with duplicates, empty inputs, boundary values.
- Iterative refinements that must terminate: fixed-point, Newton, EM.
- Any function where you catch yourself thinking "I know this algorithm" — the trap is usually in the contract, not the loop body.
Prerequisites
- The algorithm family must be chosen before applying this skill. If the algorithm is unclear, load
lemmaly first.
- For mathematical, probabilistic, FFT, or geometry algorithms, load
mathguard. Invariants for approximate algorithms include ε-bounds, not equality.
- Load
invariant-guard after the algorithm has been chosen and before the loop body is written.
Procedure
The Iron Law
NO LOOP OR RECURSION WITHOUT A WRITTEN INVARIANT AND TERMINATION ARGUMENT
If you cannot write the invariant in one sentence, you have not designed the loop. Write code anyway and you are coding by guess — and the bug will be in the case you did not enumerate.
Non-negotiable rules
Every loop gets a one-line invariant. Before writing any loop, state in one sentence what is true at the top of every iteration. Examples:
- "At loop top:
result contains the sum of a[0..i)."
- "At loop top:
lo ≤ target_position ≤ hi."
- "At loop top:
seen contains every element processed so far; dups contains every element that appeared at least twice."
If you cannot write the invariant in one sentence, you have not designed the loop yet.
Every loop gets a one-line termination argument. Name the quantity that strictly decreases (or strictly increases toward a bound) on every iteration. Examples:
- "
hi − lo strictly decreases each iteration."
- "
i increases by 1 and is bounded above by n."
- "
stack.length strictly decreases each pop; nothing pushes inside this branch."
No termination argument, no loop.
Every recursion gets an explicit base case and a measure. Before writing a recursive function, state:
- The base case(s) — the smallest inputs that return without recursing.
- The measure — a non-negative integer that strictly decreases on every recursive call (e.g.
len(xs), hi − lo, depth, n).
- The combination — how the recursive results combine into the answer.
No base case + measure, no recursion. (Mutual recursion: state the measure across the cycle.)
List edge cases before writing, not after. For every function operating on a collection or number, list which of these apply and how they behave:
- Empty input (
[], "", null, undefined, None).
- Singleton (
[x]).
- All-equal elements.
- Already-sorted / reverse-sorted input.
- Duplicates (when uniqueness is assumed).
- Negative numbers, zero, exactly the boundary value.
- Integer overflow / underflow at the type max/min.
- NaN, ±Infinity,
-0, denormals (for floats).
- Off-by-one boundaries: index 0, index n−1, index n, length 0, length 1.
- Concurrent modification while iterating.
The cases that apply must each have a one-phrase expected behavior written down.
Make illegal states unreachable, not just unhandled. Prefer encoding constraints in types and structure so the wrong state cannot be constructed:
- Sum type over boolean flag soup (
Loading | Loaded(data) | Error(msg) not {loading, data, error}).
- Newtype for IDs that must not be swapped (
UserId vs OrderId).
- Non-empty list type when the function requires at least one element.
- Parsed value at the boundary, not validated repeatedly downstream (parse-don't-validate).
If the language cannot encode it, write the invariant as a comment and assert it at the boundary.
The pre-write protocol
Before producing non-trivial code that has loops, recursion, or non-trivial state, your message must contain — in this order:
- Function contract — preconditions, postconditions, and what the function returns. One line each.
- Loop invariants — one per loop. (Rule 1.)
- Termination arguments — one per loop or recursion. (Rules 2, 3.)
- Base cases and measure — for recursion. (Rule 3.)
- Edge case table — bullets, one per applicable case, with expected behavior. (Rule 4.)
- Illegal states made unrepresentable — name the types or asserts that enforce invariants. (Rule 5.)
- The code.
- Self-check — one line per loop confirming the invariant holds at top, body preserves it, and exit implies postcondition.
If any of 1–6 is missing, do not emit code.
Worked trap — Boyer–Moore majority vote
This is the canonical "the trap is in the contract, not the loop body" case.
Naive baseline (what gets shipped without the skill):
function findMajority(arr: number[]): number | null {
if (arr.length === 0) return null;
let candidate = arr[0], count = 0;
for (const x of arr) {
if (count === 0) candidate = x;
if (x === candidate) count++; else count--;
}
return candidate; // BUG: returns the candidate even when no majority exists
}
This implementation fails on [1,2,3] (returns 3, expected null) and [2,2,1,1] (returns 1, expected null). The voting loop is correct; the postcondition is wrong.
Why the protocol catches it. Writing step 1 (function contract) forces the postcondition in plain language:
Returns x iff count(x, arr) > arr.length / 2; else null.
Then writing step 2 (loop invariant) forces the invariant of the voting pass:
If a strict majority element exists in arr, it equals candidate when the loop exits.
These two statements are not equivalent. The loop invariant guarantees "if a majority exists, it is the candidate" — not "the candidate is a majority." Once you write both down, the gap is visible: you need a second pass to verify, or the postcondition is unmet.
Correct implementation that survives the protocol:
function findMajority(arr: number[]): number | null {
if (arr.length === 0) return null;
// Pass 1: vote.
let candidate = arr[0], count = 0;
// inv: if a strict majority exists in arr, it equals candidate at every count===0 reset.
for (const x of arr) {
if (count === 0) candidate = x;
if (x === candidate) count++; else count--;
}
// Pass 2: verify — the voting invariant is strictly weaker than the postcondition.
let tally = 0;
// inv: tally = count of candidate in arr[0..i).
for (const x of arr) if (x === candidate) tally++;
return tally * 2 > arr.length ? candidate : null;
}
Pattern to generalize. The same trap appears in:
- Floyd's cycle detection — finding the meeting point tells you a cycle exists, not where it starts. You need a second walk.
- Two-pointer "find any" vs "find leftmost" — the loop invariant for one does not satisfy the postcondition of the other.
- QuickSelect partition — the loop returns a position; the postcondition is that the element at that position is the k-th smallest. Off by one in the partition invariant silently breaks it.
- DP with reconstruction — the table tells you the optimum value; reconstructing the optimum path needs separate invariants on the choice array.
In every case: write the postcondition first; write the loop invariant second; check that the second implies the first. If not, you are missing a pass, a check, or an auxiliary state.
Canonical example — binary search for the leftmost match
Most "I know binary search" implementations are written for "find any match." The trap is the postcondition.
Problem. Given a sorted array with duplicates, return the index of the leftmost occurrence of target, or -1.
Without the protocol — returns any match
function leftmost(a: number[], target: number): number {
let lo = 0, hi = a.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (a[mid] === target) return mid; // returns ANY occurrence
if (a[mid] < target) lo = mid + 1; else hi = mid - 1;
}
return -1;
}
// leftmost([1,2,2,2,3], 2) → may return 2, not 1
The loop invariant ("target lies in a[lo..hi] if anywhere") is satisfied. But the postcondition ("returned index is the smallest i with a[i] === target") is strictly stronger. The loop body's early return abandons the search before reaching the leftmost.
With the protocol — contract-driven leftmost
function leftmost(a: number[], target: number): number {
// contract:
// pre: a is sorted ascending
// post: returns smallest i with a[i] === target, or -1 if absent
let lo = 0, hi = a.length; // half-open [lo, hi)
// inv: every index < lo has a[i] < target; every index ≥ hi has a[i] > target OR is past leftmost match
// term: hi - lo strictly halves each iteration
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (a[mid] < target) lo = mid + 1; else hi = mid;
}
// exit: lo === hi, and by invariant lo is the leftmost index where a[lo] >= target
return lo < a.length && a[lo] === target ? lo : -1;
}
Same loop shape. The difference is the contract was written first — and the loop body was chosen to maintain an invariant that implies the postcondition.
Common invariant patterns to reach for
| Loop / algorithm shape |
Canonical invariant |
Termination |
| Linear scan accumulating |
acc = f(a[0..i)) at top |
i increases by 1, bounded by n |
| Two-pointer (sorted) |
target (if any) lies in a[lo..hi] |
hi − lo strictly decreases |
| Binary search |
target (if present) ∈ a[lo..hi] and a[lo..hi] non-empty |
hi − lo strictly halves |
| Sliding window |
window [l..r) satisfies the constraint; answer ≥ best so far |
r advances at least once per outer iter |
| BFS |
every node at distance < d has been popped; queue contains some at distance d |
strict node count decrease per pop |
| DFS / recursion on tree |
result for subtree rooted at v = combine(children results) |
depth (or remaining nodes) strictly decreases |
| Divide and conquer |
result on a[lo..hi] = combine(results on the two halves) |
hi − lo strictly halves |
| Greedy with priority queue |
extracted item is globally optimal for the remaining problem |
heap size strictly decreases per extract |
| Union-Find op |
find(x) always returns the canonical root of x's component |
tree height bounded by O(log n) (with rank) |
| In-place partition |
a[0..i) < pivot; a[i..j) ≥ pivot; a[j..n) unseen |
n − j strictly decreases |
Edge case table — defaults to consider
| Input shape |
Cases to check |
| Array / list |
empty, singleton, all-equal, sorted, reversed, with duplicates |
| String |
empty, single char, all whitespace, unicode (surrogates, combining), bytes vs code points |
| Integer |
0, 1, −1, MIN, MAX, MAX − 1, near overflow in arithmetic, division by 0 |
| Float |
0.0, −0.0, NaN, ±Inf, denormal, exact comparison should be ε-based |
| Map / dict |
empty, missing key (default vs error), key collision semantics |
| Tree / graph |
empty, single node, cycle (if undirected), self-loop, multigraph, disconnected |
| Stream / iterator |
empty, infinite, single yield, exception mid-iteration |
| Time / date |
DST transition, leap second/day, timezone offset, epoch boundary |
| Concurrent |
empty contention, single thread, max contention, cancellation mid-op |
Output discipline
Code you emit must:
- Have one comment per loop stating the invariant (use
// inv: or # inv:).
- Have one comment per recursion stating the base case and measure.
- Handle every edge case you listed in step 5, or explicitly delegate ("throws on empty — caller responsibility").
- Assert preconditions at function entry when the language supports it cheaply.
- Use types (sum types, newtypes, non-empty, non-null) over runtime checks where the language allows.
When to escalate or redirect
- The function is performance-critical and you have not picked the algorithm — go back to
lemmaly first; pick the algorithm, then state its invariants here.
- The technique is mathematical (probabilistic, FFT, geometry) — load
mathguard; invariants for approximate algorithms include ε-bounds, not equality.
- The code is concurrent — invariants must account for interleaving; explicitly state "single-threaded only" if that is the assumption.
Pitfalls
Rationalizations to watch for
| Excuse |
Reality |
| "I know this algorithm — single pass, done." |
Knowing the loop ≠ knowing the contract. The trap usually lives in the postcondition the loop does not enforce. |
| "I traced it in my head, it works." |
Mental tracing skips edge cases. Write the invariant; check it implies the postcondition. |
| "Edge cases are obvious." |
Then write them down in 30 seconds. If they are obvious, the table is cheap. If they are not, the table just saved you. |
| "Tests will catch it." |
Tests catch the examples you thought of. The trap is the example you did not. Postconditions catch all examples. |
| "The postcondition is implied." |
If it were, the natural loop invariant would equal it. When they differ (Boyer–Moore, leftmost search, QuickSelect), you need a second pass, an extra check, or auxiliary state. |
| "Adding a verification pass feels redundant." |
Boyer–Moore voting + verification is still O(n). "Feels redundant" is the rationalization that ships the bug. |
Red flags — STOP and write the invariant first
- About to write
while (...) without having stated what is true on entry.
- About to write
if (i === n − 1) or if (i === n) — boundary suspicious, restate the invariant.
- About to recurse without naming the base case in this message.
- About to write
// TODO: handle empty — handle it now or change the type so empty is impossible.
- About to use
== on floats.
- About to compare across signed/unsigned or across types where overflow rolls.
- About to silently swallow an error in the middle of a loop ("just continue").
- Tests pass but you did not actually state what the function guarantees.
- "It works on the examples I tried."
Limitations
- Not an automated prover. invariant-guard requires the author to write invariants; it does not mechanically check them. Pair with property-based tests for stronger evidence.
- Concurrency is out of scope by default. Stated invariants assume single-threaded execution unless explicitly extended; multi-threaded reasoning needs additional happens-before / linearizability arguments.
- Float and overflow edge cases are language-specific. The edge-case table is a checklist, not a substitute for understanding your language's numeric semantics.
- Will slow down trivial code. For one-liners that obviously cannot fail, the protocol is overhead; reserve it for non-trivial loops, recursion, and in-place mutation.
- Documentation is the only enforcement. If the author skips writing the invariants, this skill cannot detect that — pair with code review or a PR template that asks for the contract.
Verification
Before claiming the function is correct, verify the following checklist:
Cannot check every box? The code is example-correct, not behavior-correct. Either fill the gap or downgrade the function's claimed contract.
Tests verify examples. Invariants verify behavior. AI assistants ship example-correct, behavior-wrong code by default. invariant-guard makes them reason about behavior first.
Related Skills
lemmaly — algorithm choice must be settled before invariants; load lemmaly first if the algorithm family is unclear.
mathguard — ε-bounded postconditions for approximate / randomized algorithms.
complexity-cuts — if 3+ optimization transformations have failed tests, the bug is a missing contract, not a missing optimization — escalate here.
1---
2name: invariant-guard
3description: "Forces a written function contract, loop invariant, termination argument, and edge-case table before emitting loops or recursion (Boyer-Moore, leftmost binary search, QuickSelect traps). Use when writing or reviewing algorithms whose obvious implementation is subtly wrong. Not for choosing which algorithm to use (lemmaly) or epsilon-bounded math (mathguard). Do not use for trivial one-liners or as an automated prover."
4version: 1.0.1
5risk: safe
6source: community
7source_repo: morsechimwai/lemmaly
8source_type: community
9date_added: "2026-05-26"
10tags: [algorithms, correctness, loop-invariants, contracts, edge-cases, verification]
11tools: [claude-code, antigravity, cursor, gemini-cli, codex-cli]
12license: "Apache-2.0"
13license_source: "https://github.com/morsechimwai/lemmaly/blob/main/LICENSE"
14metadata:
15 source: https://skillmd.com/skills/kayforkind/invariant-guard
16---
17
18# invariant-guard — Correctness-First Coding
19
20The model knows what a loop invariant is. It knows recursion needs a base case. It knows about empty lists, integer overflow, and the difference between `<` and `≤`. It just does not write these down before producing code, so it ships subtle correctness bugs that tests do not catch.
21
22invariant-guard fixes the behavior. State the invariants. State the base case. State the termination argument. State the edge cases. Then write the code — and verify that the code maintains what you stated.
23
24**Violating the letter of these rules is violating the spirit of the skill.** "I know this algorithm" is the exact rationalization that ships off-by-one and missing-postcondition bugs.
25
26## When to Use
27
28Use **invariant-guard** when writing or reviewing algorithms where the obvious implementation is subtly wrong:
29
30- Postcondition stronger than the loop's natural invariant: Boyer–Moore majority, Floyd's cycle detection, leftmost vs any binary search, QuickSelect partition.
31- In-place mutation with read+write pointers: dedup-in-place, partition, rotate.
32- Recursion with multiple parameters or accumulator state.
33- Off-by-one suspects with duplicates, empty inputs, boundary values.
34- Iterative refinements that must terminate: fixed-point, Newton, EM.
35- Any function where you catch yourself thinking "I know this algorithm" — the trap is usually in the contract, not the loop body.
36
37## Prerequisites
38
39- The algorithm family must be chosen before applying this skill. If the algorithm is unclear, load **`lemmaly`** first.
40- For mathematical, probabilistic, FFT, or geometry algorithms, load **`mathguard`**. Invariants for approximate algorithms include ε-bounds, not equality.
41- Load `invariant-guard` *after* the algorithm has been chosen and *before* the loop body is written.
42
43## Procedure
44
45### The Iron Law
46
47```text
48NO LOOP OR RECURSION WITHOUT A WRITTEN INVARIANT AND TERMINATION ARGUMENT
49```
50
51If you cannot write the invariant in one sentence, you have not designed the loop. Write code anyway and you are coding by guess — and the bug will be in the case you did not enumerate.
52
53### Non-negotiable rules
54
551. **Every loop gets a one-line invariant.** Before writing any loop, state in one sentence what is true at the top of every iteration. Examples:
56 - "At loop top: `result` contains the sum of `a[0..i)`."
57 - "At loop top: `lo ≤ target_position ≤ hi`."
58 - "At loop top: `seen` contains every element processed so far; `dups` contains every element that appeared at least twice."
59
60 If you cannot write the invariant in one sentence, you have not designed the loop yet.
61
622. **Every loop gets a one-line termination argument.** Name the quantity that strictly decreases (or strictly increases toward a bound) on every iteration. Examples:
63 - "`hi − lo` strictly decreases each iteration."
64 - "`i` increases by 1 and is bounded above by `n`."
65 - "`stack.length` strictly decreases each pop; nothing pushes inside this branch."
66
67 No termination argument, no loop.
68
693. **Every recursion gets an explicit base case and a measure.** Before writing a recursive function, state:
70 - The base case(s) — the smallest inputs that return without recursing.
71 - The measure — a non-negative integer that strictly decreases on every recursive call (e.g. `len(xs)`, `hi − lo`, `depth`, `n`).
72 - The combination — how the recursive results combine into the answer.
73
74 No base case + measure, no recursion. (Mutual recursion: state the measure across the cycle.)
75
764. **List edge cases before writing, not after.** For every function operating on a collection or number, list which of these apply and how they behave:
77 - Empty input (`[]`, `""`, `null`, `undefined`, `None`).
78 - Singleton (`[x]`).
79 - All-equal elements.
80 - Already-sorted / reverse-sorted input.
81 - Duplicates (when uniqueness is assumed).
82 - Negative numbers, zero, exactly the boundary value.
83 - Integer overflow / underflow at the type max/min.
84 - NaN, ±Infinity, `-0`, denormals (for floats).
85 - Off-by-one boundaries: index 0, index n−1, index n, length 0, length 1.
86 - Concurrent modification while iterating.
87
88 The cases that apply must each have a one-phrase expected behavior written down.
89
905. **Make illegal states unreachable, not just unhandled.** Prefer encoding constraints in types and structure so the wrong state cannot be constructed:
91 - Sum type over boolean flag soup (`Loading | Loaded(data) | Error(msg)` not `{loading, data, error}`).
92 - Newtype for IDs that must not be swapped (`UserId` vs `OrderId`).
93 - Non-empty list type when the function requires at least one element.
94 - Parsed value at the boundary, not validated repeatedly downstream (parse-don't-validate).
95
96 If the language cannot encode it, write the invariant as a comment and assert it at the boundary.
97
98### The pre-write protocol
99
100Before producing non-trivial code that has loops, recursion, or non-trivial state, your message must contain — in this order:
101
1021. **Function contract** — preconditions, postconditions, and what the function returns. One line each.
1032. **Loop invariants** — one per loop. (Rule 1.)
1043. **Termination arguments** — one per loop or recursion. (Rules 2, 3.)
1054. **Base cases and measure** — for recursion. (Rule 3.)
1065. **Edge case table** — bullets, one per applicable case, with expected behavior. (Rule 4.)
1076. **Illegal states made unrepresentable** — name the types or asserts that enforce invariants. (Rule 5.)
1087. **The code.**
1098. **Self-check** — one line per loop confirming the invariant holds at top, body preserves it, and exit implies postcondition.
110
111If any of 1–6 is missing, do not emit code.
112
113### Worked trap — Boyer–Moore majority vote
114
115This is the canonical "the trap is in the contract, not the loop body" case.
116
117**Naive baseline (what gets shipped without the skill):**
118
119```typescript
120function findMajority(arr: number[]): number | null {
121 if (arr.length === 0) return null;
122 let candidate = arr[0], count = 0;
123 for (const x of arr) {
124 if (count === 0) candidate = x;
125 if (x === candidate) count++; else count--;
126 }
127 return candidate; // BUG: returns the candidate even when no majority exists
128}
129```
130
131This implementation fails on `[1,2,3]` (returns `3`, expected `null`) and `[2,2,1,1]` (returns `1`, expected `null`). The voting loop is correct; the postcondition is wrong.
132
133**Why the protocol catches it.** Writing **step 1 (function contract)** forces the postcondition in plain language:
134
135> Returns `x` iff `count(x, arr) > arr.length / 2`; else `null`.
136
137Then writing **step 2 (loop invariant)** forces the invariant of the voting pass:
138
139> If a strict majority element exists in `arr`, it equals `candidate` when the loop exits.
140
141These two statements are not equivalent. The loop invariant guarantees "if a majority exists, it is the candidate" — not "the candidate is a majority." Once you write both down, the gap is visible: you need a second pass to verify, or the postcondition is unmet.
142
143**Correct implementation that survives the protocol:**
144
145```typescript
146function findMajority(arr: number[]): number | null {
147 if (arr.length === 0) return null;
148 // Pass 1: vote.
149 let candidate = arr[0], count = 0;
150 // inv: if a strict majority exists in arr, it equals candidate at every count===0 reset.
151 for (const x of arr) {
152 if (count === 0) candidate = x;
153 if (x === candidate) count++; else count--;
154 }
155 // Pass 2: verify — the voting invariant is strictly weaker than the postcondition.
156 let tally = 0;
157 // inv: tally = count of candidate in arr[0..i).
158 for (const x of arr) if (x === candidate) tally++;
159 return tally * 2 > arr.length ? candidate : null;
160}
161```
162
163**Pattern to generalize.** The same trap appears in:
164
165- **Floyd's cycle detection** — finding the meeting point tells you a cycle exists, *not* where it starts. You need a second walk.
166- **Two-pointer "find any"** vs **"find leftmost"** — the loop invariant for one does not satisfy the postcondition of the other.
167- **QuickSelect partition** — the loop returns a position; the postcondition is that the element at that position is the k-th smallest. Off by one in the partition invariant silently breaks it.
168- **DP with reconstruction** — the table tells you the optimum value; reconstructing the optimum path needs separate invariants on the choice array.
169
170In every case: **write the postcondition first; write the loop invariant second; check that the second implies the first. If not, you are missing a pass, a check, or an auxiliary state.**
171
172### Canonical example — binary search for the leftmost match
173
174Most "I know binary search" implementations are written for "find any match." The trap is the postcondition.
175
176**Problem.** Given a sorted array with duplicates, return the index of the **leftmost** occurrence of `target`, or `-1`.
177
178**Without the protocol — returns any match**
179
180```ts
181function leftmost(a: number[], target: number): number {
182 let lo = 0, hi = a.length - 1;
183 while (lo <= hi) {
184 const mid = (lo + hi) >> 1;
185 if (a[mid] === target) return mid; // returns ANY occurrence
186 if (a[mid] < target) lo = mid + 1; else hi = mid - 1;
187 }
188 return -1;
189}
190// leftmost([1,2,2,2,3], 2) → may return 2, not 1
191```
192
193The loop invariant ("target lies in `a[lo..hi]` if anywhere") is satisfied. But the postcondition ("returned index is the *smallest* `i` with `a[i] === target`") is strictly stronger. The loop body's early return abandons the search before reaching the leftmost.
194
195**With the protocol — contract-driven leftmost**
196
197```ts
198function leftmost(a: number[], target: number): number {
199 // contract:
200 // pre: a is sorted ascending
201 // post: returns smallest i with a[i] === target, or -1 if absent
202 let lo = 0, hi = a.length; // half-open [lo, hi)
203 // inv: every index < lo has a[i] < target; every index ≥ hi has a[i] > target OR is past leftmost match
204 // term: hi - lo strictly halves each iteration
205 while (lo < hi) {
206 const mid = (lo + hi) >> 1;
207 if (a[mid] < target) lo = mid + 1; else hi = mid;
208 }
209 // exit: lo === hi, and by invariant lo is the leftmost index where a[lo] >= target
210 return lo < a.length && a[lo] === target ? lo : -1;
211}
212```
213
214Same loop shape. The difference is the contract was written first — and the loop body was chosen to maintain an invariant that *implies* the postcondition.
215
216### Common invariant patterns to reach for
217
218| Loop / algorithm shape | Canonical invariant | Termination |
219|---|---|---|
220| Linear scan accumulating | `acc = f(a[0..i))` at top | `i` increases by 1, bounded by `n` |
221| Two-pointer (sorted) | `target (if any) lies in a[lo..hi]` | `hi − lo` strictly decreases |
222| Binary search | `target (if present) ∈ a[lo..hi]` and `a[lo..hi]` non-empty | `hi − lo` strictly halves |
223| Sliding window | window `[l..r)` satisfies the constraint; answer ≥ best so far | `r` advances at least once per outer iter |
224| BFS | every node at distance < d has been popped; queue contains some at distance d | strict node count decrease per pop |
225| DFS / recursion on tree | result for subtree rooted at v = combine(children results) | depth (or remaining nodes) strictly decreases |
226| Divide and conquer | result on `a[lo..hi]` = combine(results on the two halves) | `hi − lo` strictly halves |
227| Greedy with priority queue | extracted item is globally optimal for the remaining problem | heap size strictly decreases per extract |
228| Union-Find op | `find(x)` always returns the canonical root of x's component | tree height bounded by O(log n) (with rank) |
229| In-place partition | `a[0..i)` < pivot; `a[i..j)` ≥ pivot; `a[j..n)` unseen | `n − j` strictly decreases |
230
231### Edge case table — defaults to consider
232
233| Input shape | Cases to check |
234|---|---|
235| Array / list | empty, singleton, all-equal, sorted, reversed, with duplicates |
236| String | empty, single char, all whitespace, unicode (surrogates, combining), bytes vs code points |
237| Integer | 0, 1, −1, MIN, MAX, MAX − 1, near overflow in arithmetic, division by 0 |
238| Float | 0.0, −0.0, NaN, ±Inf, denormal, exact comparison should be ε-based |
239| Map / dict | empty, missing key (default vs error), key collision semantics |
240| Tree / graph | empty, single node, cycle (if undirected), self-loop, multigraph, disconnected |
241| Stream / iterator | empty, infinite, single yield, exception mid-iteration |
242| Time / date | DST transition, leap second/day, timezone offset, epoch boundary |
243| Concurrent | empty contention, single thread, max contention, cancellation mid-op |
244
245### Output discipline
246
247Code you emit must:
248
249- Have one comment per loop stating the invariant (use `// inv:` or `# inv:`).
250- Have one comment per recursion stating the base case and measure.
251- Handle every edge case you listed in step 5, or explicitly delegate ("throws on empty — caller responsibility").
252- Assert preconditions at function entry when the language supports it cheaply.
253- Use types (sum types, newtypes, non-empty, non-null) over runtime checks where the language allows.
254
255### When to escalate or redirect
256
257- The function is performance-critical and you have not picked the algorithm — go back to **`lemmaly`** first; pick the algorithm, then state its invariants here.
258- The technique is mathematical (probabilistic, FFT, geometry) — load **`mathguard`**; invariants for approximate algorithms include ε-bounds, not equality.
259- The code is concurrent — invariants must account for interleaving; explicitly state "single-threaded only" if that is the assumption.
260
261## Pitfalls
262
263### Rationalizations to watch for
264
265| Excuse | Reality |
266| --- | --- |
267| "I know this algorithm — single pass, done." | Knowing the loop ≠ knowing the contract. The trap usually lives in the postcondition the loop does not enforce. |
268| "I traced it in my head, it works." | Mental tracing skips edge cases. Write the invariant; check it implies the postcondition. |
269| "Edge cases are obvious." | Then write them down in 30 seconds. If they are obvious, the table is cheap. If they are not, the table just saved you. |
270| "Tests will catch it." | Tests catch the examples you thought of. The trap is the example you did not. Postconditions catch all examples. |
271| "The postcondition is implied." | If it were, the natural loop invariant would equal it. When they differ (Boyer–Moore, leftmost search, QuickSelect), you need a second pass, an extra check, or auxiliary state. |
272| "Adding a verification pass feels redundant." | Boyer–Moore voting + verification is still O(n). "Feels redundant" is the rationalization that ships the bug. |
273
274### Red flags — STOP and write the invariant first
275
276- About to write `while (...)` without having stated what is true on entry.
277- About to write `if (i === n − 1)` or `if (i === n)` — boundary suspicious, restate the invariant.
278- About to recurse without naming the base case in this message.
279- About to write `// TODO: handle empty` — handle it now or change the type so empty is impossible.
280- About to use `==` on floats.
281- About to compare across signed/unsigned or across types where overflow rolls.
282- About to silently swallow an error in the middle of a loop ("just continue").
283- Tests pass but you did not actually state what the function guarantees.
284- "It works on the examples I tried."
285
286### Limitations
287
288- **Not an automated prover.** invariant-guard requires the author to *write* invariants; it does not mechanically check them. Pair with property-based tests for stronger evidence.
289- **Concurrency is out of scope by default.** Stated invariants assume single-threaded execution unless explicitly extended; multi-threaded reasoning needs additional happens-before / linearizability arguments.
290- **Float and overflow edge cases are language-specific.** The edge-case table is a checklist, not a substitute for understanding your language's numeric semantics.
291- **Will slow down trivial code.** For one-liners that obviously cannot fail, the protocol is overhead; reserve it for non-trivial loops, recursion, and in-place mutation.
292- **Documentation is the only enforcement.** If the author skips writing the invariants, this skill cannot detect that — pair with code review or a PR template that asks for the contract.
293
294## Verification
295
296Before claiming the function is correct, verify the following checklist:
297
298- [ ] Every loop has a one-line `// inv:` comment in code.
299- [ ] Every loop has a termination argument written down (in comment or PR description).
300- [ ] Every recursion names its base case and measure in code.
301- [ ] The function's postcondition is written and is implied by the exit state of the last loop.
302- [ ] Every applicable edge case from the table has a test or an explicit "delegated to caller" note.
303- [ ] At least one test exercises each non-trivial boundary (empty, singleton, max, off-by-one).
304- [ ] Illegal states the function rejects are either unrepresentable in the type, or asserted at entry.
305- [ ] For approximate/randomized algorithms (escalated to mathguard): ε-bounds are part of the postcondition, not equality.
306
307Cannot check every box? The code is example-correct, not behavior-correct. Either fill the gap or downgrade the function's claimed contract.
308
309> **Tests verify examples. Invariants verify behavior. AI assistants ship example-correct, behavior-wrong code by default. invariant-guard makes them reason about behavior first.**
310
311## Related Skills
312
313- `lemmaly` — algorithm choice must be settled before invariants; load lemmaly first if the algorithm family is unclear.
314- `mathguard` — ε-bounded postconditions for approximate / randomized algorithms.
315- `complexity-cuts` — if 3+ optimization transformations have failed tests, the bug is a missing contract, not a missing optimization — escalate here.