Приоритет корректности: требует написать контракт функции, инвариант цикла, аргумент завершения и граничные случаи до кода. Ловит ловушки Бойера-Мура, левостороннего бинарного поиска и QuickSelect.

Звёзды49 917
Авторsickn33

Установка

SKILL.md

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 This Skill

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.

Pairs with lemmaly (picks the algorithm) and mathguard (picks the math). Load invariant-guard after the algorithm has been chosen and before the loop body is written.

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

  1. 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.

  2. 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.

  3. 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.)

  4. 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.

  5. 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:

  1. Function contract — preconditions, postconditions, and what the function returns. One line each.
  2. Loop invariants — one per loop. (Rule 1.)
  3. Termination arguments — one per loop or recursion. (Rules 2, 3.)
  4. Base cases and measure — for recursion. (Rule 3.)
  5. Edge case table — bullets, one per applicable case, with expected behavior. (Rule 4.)
  6. Illegal states made unrepresentable — name the types or asserts that enforce invariants. (Rule 5.)
  7. The code.
  8. 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 shapeCanonical invariantTermination
Linear scan accumulatingacc = f(a[0..i)) at topi increases by 1, bounded by n
Two-pointer (sorted)target (if any) lies in a[lo..hi]hi − lo strictly decreases
Binary searchtarget (if present) ∈ a[lo..hi] and a[lo..hi] non-emptyhi − lo strictly halves
Sliding windowwindow [l..r) satisfies the constraint; answer ≥ best so farr advances at least once per outer iter
BFSevery node at distance < d has been popped; queue contains some at distance dstrict node count decrease per pop
DFS / recursion on treeresult for subtree rooted at v = combine(children results)depth (or remaining nodes) strictly decreases
Divide and conquerresult on a[lo..hi] = combine(results on the two halves)hi − lo strictly halves
Greedy with priority queueextracted item is globally optimal for the remaining problemheap size strictly decreases per extract
Union-Find opfind(x) always returns the canonical root of x's componenttree height bounded by O(log n) (with rank)
In-place partitiona[0..i) < pivot; a[i..j) ≥ pivot; a[j..n) unseenn − j strictly decreases

Edge case table — defaults to consider

Input shapeCases to check
Array / listempty, singleton, all-equal, sorted, reversed, with duplicates
Stringempty, single char, all whitespace, unicode (surrogates, combining), bytes vs code points
Integer0, 1, −1, MIN, MAX, MAX − 1, near overflow in arithmetic, division by 0
Float0.0, −0.0, NaN, ±Inf, denormal, exact comparison should be ε-based
Map / dictempty, missing key (default vs error), key collision semantics
Tree / graphempty, single node, cycle (if undirected), self-loop, multigraph, disconnected
Stream / iteratorempty, infinite, single yield, exception mid-iteration
Time / dateDST transition, leap second/day, timezone offset, epoch boundary
Concurrentempty 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.

Rationalizations to watch for

ExcuseReality
"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.

Красные флаги — СТОП, сначала запиши инвариант

  • Собираешься написать while (...) не указав, что истинно на входе.
  • Собираешься написать if (i === n − 1) or if (i === n) — граница подозрительна, переформулируй инвариант.
  • Собираешься рекурсировать, не назвав базовый случай в этом сообщении.
  • Собираешься написать // TODO: handle empty — обработай это сейчас или измени тип так, чтобы пустое состояние стало невозможным.
  • Собираешься использовать == на числах с плавающей точкой.
  • Собираешься сравнивать знаковое с беззнаковым или значения разных типов, где переполнение приводит к циклическому переходу.
  • Собираешься молча проглотить ошибку в середине цикла ("просто продолжай").
  • Тесты проходят, но ты так и не указал, что гарантирует функция.
  • "Это работает на примерах, которые я попробовал."

Чек-лист верификации

Прежде чем утверждать, что функция корректна:

  • <!-- -->У каждого цикла есть однострочный // inv: комментарий в коде.
  • <!-- -->У каждого цикла записан аргумент завершения (в комментарии или описании PR).
  • <!-- -->Каждая рекурсия называет свой базовый случай и меру в коде.
  • <!-- -->Постусловие функции записано и следует из состояния выхода последнего цикла.
  • <!-- -->Для каждого применимого граничного случая из таблицы есть тест или явная пометка "делегировано вызывающему".
  • <!-- -->Как минимум один тест проверяет каждую нетривиальную границу (пустое, одиночное, максимум, ошибка на единицу).
  • <!-- -->Недопустимые состояния, которые функция отвергает, либо непредставимы в типе, либо проверяются утверждением на входе.
  • <!-- -->Для приближённых/рандомизированных алгоритмов (эскалировано в mathguard): ε-границы являются частью постусловия, а не равенства.

Не можешь отметить все пункты? Код корректен на примерах, но не корректен по поведению. Либо заполни пробел, либо понизь заявленный контракт функции.

Ограничения

  • Не автоматический доказатель. invariant-guard требует, чтобы автор писал инварианты; он не проверяет их механически. Сочетайте со свойство-ориентированными тестами для более сильных доказательств.
  • Конкурентность по умолчанию вне области охвата. Заявленные инварианты предполагают однопоточное выполнение, если явно не расширены; многопоточные рассуждения требуют дополнительных аргументов happens-before / линеаризуемости.
  • Граничные случаи с плавающей точкой и переполнением зависят от языка. Таблица граничных случаев — это чек-лист, а не замена пониманию числовой семантики вашего языка.
  • Замедлит тривиальный код. Для однострочников, которые очевидно не могут упасть, протокол — это накладные расходы; приберегите его для нетривиальных циклов, рекурсии и мутации на месте.
  • Документация — единственный механизм принуждения. Если автор пропускает написание инвариантов, этот навык не может это обнаружить — сочетайте с код-ревью или шаблоном PR, который запрашивает контракт.

Тезис в одной строке

Тесты проверяют примеры. Инварианты проверяют поведение. ИИ-ассистенты по умолчанию поставляют код, корректный на примерах, но неверный по поведению. invariant-guard заставляет их сначала рассуждать о поведении.

Связанные навыки

  • lemmaly — выбор алгоритма должен быть решён до инвариантов; сначала загрузите lemmaly, если семейство алгоритмов неясно.
  • mathguard — ε-ограниченные постусловия для приближённых / рандомизированных алгоритмов.
  • complexity-cuts — если 3+ оптимизационных преобразования провалили тесты, баг — это отсутствующий контракт, а не отсутствующая оптимизация — эскалируйте сюда.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: invariant-guard](https://darkplay.ru/ai/skills/sickn33-agentic-awesome-skills-invariant-guard)

Описание

Приоритет корректности: требует написать контракт функции, инвариант цикла, аргумент завершения и граничные случаи ДО кода. Ловит ловушки алгоритма Бойера-Мура, левостороннего бинарного поиска и QuickSelect.

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Network Config Revieweraffaan-m · Проверяет конфигурации роутеров и свитчей: безопасность, ошибки и риски изменений.
225 587 ★
Spec Mineraffaan-m · Извлекает поведенческие спецификации из кода для OpenSpec в виде блоков Requirement и…
225 587 ★
Type Design Analyzeraffaan-m · Анализ дизайна типов: инкапсуляция, инварианты, полезность, соблюдение.
225 587 ★
42crunch-api-security-testinganthropics · Автоматизация безопасности API прямо в Claude Code с помощью 42Crunch: аудит спецификаций…
100 комп.
Type Design Analyzeranthropics · Агент для анализа типов в кодовой базе: инкапсуляция, инварианты, ревью новых типов в PR.
31 495 ★
handoff-productivityalirezarezvani · Сжатие беседы в документ-передачу для другого агента.
510 комп.
workflow-builderalirezarezvani · Навык для построения workflow: детерминированные скрипты многоагентных процессов (.js в…
510 комп.
safety-alignmentorchestra-research · Безопасность ИИ и модерация контента: Constitutional AI, LlamaGuard, NeMo Guardrails и…
96 комп.
42crunch-api-security-testinganthropics · Автоматизация безопасности API прямо в Claude Code с 42Crunch: аудит спецификаций…
38 комп.
achilles-ep-delphianthropics · Инфраструктура безопасности агентов (RiskOracle, NoLeak, MemGuard, SecureExec, FlowCore)…
38 комп.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8