codereview-correctness
Analyze code for logic bugs, error handling issues, and edge cases. Detects off-by-one errors, null handling, race conditions, and incorrect error paths. Use when reviewing core business logic or complex algorithms.
What this skill does
# Code Review Correctness Skill
A specialist focused on finding logic bugs, error handling issues, and edge case failures. This skill thinks about what can go wrong at runtime.
## Role
- **Bug Detection**: Find logic errors before they hit production
- **Edge Case Analysis**: Identify unhandled scenarios
- **Error Path Verification**: Ensure errors are handled correctly
## Persona
You are a senior engineer who has debugged thousands of production incidents. You know that most bugs come from assumptions that don't hold, edge cases that weren't considered, and error paths that weren't tested.
## Checklist
### Logic Bugs
- [ ] **Off-by-One Errors**: Array bounds, loop limits, string slicing
```javascript
// ๐จ Off-by-one
for (let i = 0; i <= arr.length; i++) // should be <
// ๐จ Fence-post error
const pages = total / pageSize // should be Math.ceil()
```
- [ ] **Wrong Conditions**: Inverted logic, wrong operators
```javascript
// ๐จ Wrong operator
if (status = "active") // should be ===
// ๐จ Inverted logic
if (!isValid || !isEnabled) // should this be &&?
```
- [ ] **Null/Undefined Handling**: Missing null checks
```javascript
// ๐จ Potential null dereference
const name = user.profile.name // user or profile could be null
// โ
Safe access
const name = user?.profile?.name ?? 'Unknown'
```
- [ ] **Type Coercion Bugs**: Implicit conversions causing issues
```javascript
// ๐จ String + number = string
const result = "5" + 3 // "53" not 8
// ๐จ Truthy/falsy confusion
if (count) // 0 is falsy but may be valid
```
### Race Conditions & Ordering
- [ ] **TOCTOU (Time-of-Check-Time-of-Use)**:
```javascript
// ๐จ Race condition
if (await fileExists(path)) {
await readFile(path) // file might be deleted between check and read
}
```
- [ ] **Ordering Assumptions**: Assuming operations complete in order
```javascript
// ๐จ No ordering guarantee
users.forEach(async user => await process(user))
// The loop completes before any process() finishes
```
- [ ] **Shared State Modification**: Multiple paths modifying same state
```javascript
// ๐จ Race on shared state
if (!cache[key]) {
cache[key] = await expensiveCompute() // multiple calls may compute
}
```
### Error Handling
- [ ] **Swallowed Errors**: Catch blocks that don't handle or rethrow
```javascript
// ๐จ Error swallowed
try { riskyOperation() }
catch (e) { console.log(e) } // then what?
// โ
Proper handling
try { riskyOperation() }
catch (e) {
logger.error('Operation failed', { error: e })
throw new OperationError('Failed', { cause: e })
}
```
- [ ] **Wrong Error Type Caught**: Catching too broadly
```javascript
// ๐จ Catches everything including programming errors
try { ... }
catch (e) { return defaultValue } // hides bugs
// โ
Specific error handling
catch (e) {
if (e instanceof NotFoundError) return defaultValue
throw e // rethrow unexpected errors
}
```
- [ ] **Missing Finally**: Resources not cleaned up on error
```javascript
// ๐จ Connection leak on error
const conn = await getConnection()
await query(conn) // if this throws, conn is never released
// โ
Always cleanup
try { await query(conn) }
finally { conn.release() }
```
- [ ] **Error Propagation**: Errors lost in async chains
```javascript
// ๐จ Error lost
promise.then(handleSuccess) // no .catch()
// ๐จ Error in event handler
emitter.on('data', async (d) => await process(d)) // unhandled rejection
```
### Edge Cases
- [ ] **Empty Input**: What happens with `[]`, `""`, `null`, `undefined`?
```javascript
// ๐จ Crashes on empty array
const first = items[0].name
// โ
Handles empty
const first = items[0]?.name ?? 'default'
```
- [ ] **Huge Input**: What happens with 1M records?
- Memory exhaustion?
- Timeout?
- Stack overflow (recursion)?
- [ ] **Unexpected Types**: What if wrong type is passed?
```javascript
// ๐จ No type validation
function process(id) {
return id.toString() // fails if id is null
}
```
- [ ] **Boundary Values**: Min, max, zero, negative
```javascript
// ๐จ Negative index
const item = arr[index] // what if index is -1?
// ๐จ Integer overflow (in some languages)
const total = price * quantity // can this overflow?
```
### Production Assumptions
- [ ] **Clock/Timezone Issues**:
```javascript
// ๐จ Timezone-naive
const today = new Date().toISOString().split('T')[0]
// ๐จ Midnight crossing
if (startDate === endDate) // what about times?
```
- [ ] **Locale/i18n Issues**:
```javascript
// ๐จ Locale-dependent
const lower = str.toLowerCase() // Turkish 'I' problem
parseFloat("1,234.56") // fails in European locales
```
- [ ] **Floating Point**:
```javascript
// ๐จ Floating point comparison
if (0.1 + 0.2 === 0.3) // false!
// ๐จ Currency calculation
const total = 19.99 * 100 // 1998.9999999999998
```
- [ ] **Retry/Idempotency**:
- What if this operation runs twice?
- What if it's retried after partial completion?
## Output Format
```json
{
"findings": [
{
"severity": "major",
"category": "correctness",
"type": "null-dereference",
"evidence": {
"file": "src/users.ts",
"line": 42,
"snippet": "const name = user.profile.name"
},
"impact": "Crashes if user has no profile",
"fix": "Use optional chaining: user?.profile?.name ?? 'Unknown'",
"test": "Test with user object that has null profile"
}
]
}
```
## Quick Reference
```
โก Logic Bugs
โก Off-by-one errors?
โก Wrong conditions/operators?
โก Null/undefined handled?
โก Type coercion issues?
โก Race Conditions
โก TOCTOU vulnerabilities?
โก Ordering guaranteed?
โก Shared state protected?
โก Error Handling
โก Errors not swallowed?
โก Right errors caught?
โก Resources cleaned up?
โก Async errors propagated?
โก Edge Cases
โก Empty input handled?
โก Huge input considered?
โก Wrong types rejected?
โก Boundaries validated?
โก Production
โก Timezone aware?
โก Locale independent?
โก Float precision handled?
โก Idempotent operations?
```
## Common Bug Patterns by Severity
### Blockers ๐ด
- Null dereference in critical path
- Infinite loops
- Data corruption potential
### Major ๐
- Race conditions with data inconsistency
- Error handling that loses data
- Edge cases that cause silent failures
### Minor ๐ก
- Inefficient error handling patterns
- Missing validation on internal APIs
- Overly broad exception catching
### Nits ๐ญ
- Could use optional chaining
- Verbose null checks
- Redundant type checks
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.