invariant-guard
하는 일
이 도구는 더 신뢰할 수 있는 코드를 쓰도록 돕습니다. 실제 코드를 작성하기 전에 불변식(규칙), 코드가 끝나는 방식, 특수한 경우를 설명하도록 합니다.
사용하는 경우
- ✓미묘한 버그가 있을 수 있는 알고리즘을 작성할 때.
- ✓반복(루프)이나 재귀 호출을 다룰 때.
- ✓모든 상황에서 작동하는지 확인하도록 코드를 검토하는 경우.
스킬 링크
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/invariant-guard/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“리스트에서 가장 큰 원소를 찾는 함수를 작성해 주세요. 먼저 루프 불변식, 종료 근거, 예외 상황을 정의해 주세요.”
매주 새 스킬 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
- 업데이트
- 2026. 10. 15.
댓글
- …
이 저장소의 다른 스킬
00-andruia-consultant
48k에이전트가 AI 프로젝트를 시작하거나 개선할 수 있도록 코드를 분석하고 스페인어로 실행 계획을 세워 줍니다.
007
48k에이전트가 보안 감사와 위협 모델링을 수행해 공격과 취약점으로부터 프로젝트를 보호하도록 돕습니다.
10-andruia-skill-smith
48k에이전트가 AI 도구의 작동 방식을 정의하고 문서를 쓰며 구조를 검증하도록 돕습니다.
20-andruia-niche-intelligence
48k에이전트가 신뢰할 수 있는 자료를 바탕으로 특정 산업의 맥락, 규칙, 사용 패턴, 위험을 정리한 요약을 만들도록 돕습니다.