Identify missing assertions, preconditions, postconditions, and invariants in code. Use to add defensive programming that catches bugs early, makes code self-documenting, and surfaces violations before they cause hard-to-debug failures downstream. Trigger for: "add defensive checks", "make this code fail fast", "harden this module", "I want to catch invalid state early", or during code review when you want to improve robustness.
Assertions are executable documentation. They make your code say what it expects, and scream immediately when those expectations are violated — rather than silently corrupting state and failing mysteriously later.
The goal: find where the code makes implicit assumptions and make those assumptions explicit and enforceable.
Read the target code and identify these categories at every function boundary:
Things that must be true before a function executes:
Things that must be true after a function returns:
Properties that must hold throughout a class's lifetime:
Not all assertions are equal. Prioritize by what happens without them:
Prevents crashes, data corruption, or silent incorrect results:
Catches algorithmic mistakes:
Enforces API contracts:
Validates security constraints:
For each finding, generate language-appropriate assertion code:
JavaScript/TypeScript:
// Precondition
if (userId == null) throw new Error("userId is required");
console.assert(amount > 0, `Expected positive amount, got ${amount}`);
// Postcondition
const result = processPayment(amount);
console.assert(result.transactionId != null, "Payment must produce a transaction ID");
Python:
# Precondition
assert user_id is not None, "user_id is required"
assert amount > 0, f"Expected positive amount, got {amount}"
# Invariant (check after mutations)
assert len(self.items) <= self.max_size, "Size invariant violated"
Java:
// Precondition
assert userId != null : "userId is required";
if (amount <= 0) throw new IllegalArgumentException("amount must be positive: " + amount);
C/C++:
assert(user_id != NULL);
assert(amount > 0);
# Assertion Analysis Report
**Files analyzed:** [N]
**Existing assertions found:** [N]
**Recommended additions:** [N]
**Critical missing:** [N]
---
## Priority 1 — Safety Critical (Add Immediately)
### [File:function:line]
**Current code:**
```[language]
[code without assertion]
Recommended:
[assertion + protected code]
Why: [what crash or corruption this prevents] Risk without it: [specific failure mode]
[repeat for each safety-critical finding]
[same format]
[same format]
| Component | Current Assertions | Recommended | Priority |
|---|---|---|---|
| [module] | [N] | [+N] | High |
Add null/undefined checks and bounds checks where crashes are possible.
Add algorithm invariants and state validation.
Add contract assertions and security validations.
Consider enabling assertions differently per environment: