invariant-guard
Что он делает
Этот инструмент помогает писать более надежный код. Перед написанием самого кода он заставляет вас описать правила (инварианты), то, как код завершится, и особые случаи.
Когда использовать
- ✓Когда вы пишете алгоритмы, в которых могут скрываться неочевидные ошибки.
- ✓Когда работаете с повторениями (циклами) или рекурсивными вызовами.
- ✓Когда проверяете код, чтобы убедиться, что он работает во всех ситуациях.
Ссылка на скилл
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/invariant-guard/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Напиши функцию, которая находит наибольший элемент в списке, но сначала определи инвариант цикла, обоснование завершения и граничные случаи.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Инструмент заставляет вас формально описать условия, которые должны выполняться до, во время и после каждого шага вашего кода (например, цикла или рекурсии). Это помогает предотвратить распространенные ошибки, которые часто остаются незамеченными.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
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
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:
resultcontains the sum ofa[0..i)." - "At loop top:
lo ≤ target_position ≤ hi." - "At loop top:
seencontains every element processed so far;dupscontains every element that appeared at least twice."
If you cannot write the invariant in one sentence, you have not designed the loop yet.
- "At loop top:
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 − lostrictly decreases each iteration." - "
iincreases by 1 and is bounded above byn." - "
stack.lengthstrictly 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.
- Empty input (
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 (
UserIdvsOrderId). - Non-empty list type when the function requires at least one element.
- Sum type over boolean flag soup (
…
Частые вопросы
Что такое «инвариант цикла»?
Это утверждение, которое всегда истинно в начале каждого повторения цикла. Например: «переменная X всегда содержит сумму уже обработанных элементов».
Что такое «обоснование завершения»?
Это объяснение того, как цикл или рекурсивная функция в конце концов завершится. Обычно оно показывает, что некоторая величина на каждом шаге уменьшается или увеличивается и приближается к границе.
Почему сначала нужно перечислять «граничные случаи»?
Потому что многие ошибки возникают в необычных ситуациях, например в пустом списке, списке из одного элемента или при повторяющихся значениях. Если подумать о них заранее, можно избежать ошибок.
Подробности
Оригинальное описание автора
Correctness-first: forces writing the function contract, loop invariant, termination argument, and edge cases BEFORE code. Catches Boyer-Moore, leftmost binary search, QuickSelect traps.
Популярность
- Звёзды на GitHub
- 48k
- Место в рейтинге
- #4965
- Лицензия
- MIT
- Обновлён
- 15.10.2026
Комментарии
- …
Другие скиллы из этого репозитория
00-andruia-consultant
48kПомогает агенту начинать или улучшать ИИ-проекты: анализирует код, подбирает инструменты и составляет план на испанском.
007
48kАгент проводит аудит безопасности и моделирование угроз для защиты проектов.
10-andruia-skill-smith
48kПомогает агенту создавать и улучшать ИИ-инструменты: описание работы, документация и проверка структуры.
20-andruia-niche-intelligence
48kАгент составляет обзор отрасли: контекст, правила, паттерны использования и риски по надёжным источникам.
Похожие скиллы
diffs
394kПозволяет агенту создать настоящее сравнение правок в виде ссылки или файла изображения, которым можно поделиться, вместо ручной сводки.
coding-agent
394kПомогает агенту передать большую задачу по коду в Codex, Claude Code или OpenCode как фоновому исполнителю, а затем проверять ее ход.
gh-issues
394kПомогает агенту находить задачи GitHub, выбирать, над какими работать, и открывать запросы на слияние с исправлениями, включая ответы на комментарии рецензентов.