Adversarial Code Analysis
Purpose
Map the "Surface of Reality" for target code. Your goal is to distinguish:
- Contract Violations (invalid inputs the caller shouldn't send) → NOT testable
- Logic Bugs (valid inputs the code handles poorly) → TESTABLE
Analysis Checklist
1. Contract Extraction
Explicit Contracts:
- Type hints (
int, str, Optional[T], List[T])
assert statements and preconditions
- Docstring
Args, Raises, Returns sections
- Validation code at function entry
Implicit Contracts:
- Variable names implying limits (
retry_count → small positive int, buffer_size → memory-reasonable)
- Context from call sites (what values are actually passed?)
- Domain knowledge (user IDs are positive, emails contain @)
External Constraints:
- Database column limits (VARCHAR(255))
- API rate limits and timeouts
- Filesystem permissions and path length limits
2. Realism Baseline (The 3-Sigma Rule)
Use Grep to scan existing tests in tests/ and call sites in src/. Calculate boundaries:
String Inputs:
existing_lengths = [len(s) for each test string argument]
if len(existing_lengths) >= 5:
Max_Realistic_Length = mean(existing_lengths) + 3 * std(existing_lengths)
elif len(existing_lengths) >= 1:
Max_Realistic_Length = max(existing_lengths) * 2
else:
Max_Realistic_Length = 256 # Zero-sample fallback
Numeric Inputs:
existing_values = [v for each numeric argument]
if len(existing_values) >= 5:
Lower = mean(existing_values) - 3 * std(existing_values)
Upper = mean(existing_values) + 3 * std(existing_values)
elif len(existing_values) >= 1:
Lower = min(existing_values) - abs(min(existing_values))
Upper = max(existing_values) + abs(max(existing_values))
else:
Lower, Upper = -1000, 1000 # Zero-sample fallback
Special Boundaries (Always Valid):
0, -1, 1 for integers (if type allows)
- Empty string
"" (if not explicitly forbidden)
None only if type is Optional
Complex Objects:
- Max nesting depth: 3 levels (unless recursive data structure)
- Max fields: 20 (unless schema requires more)
- Zero-sample fallback: depth 2, fields 10
3. Vulnerability Surface Identification
High-Risk Patterns:
- Arithmetic: Division, modulo, floating-point accumulation, currency calculations
- Boundaries: Loop limits, array indices, string slicing
- State: Multi-step workflows, flag combinations, temporal dependencies
- Resources: File handles, connections, locks (cleanup on error paths)
- Parsing: User input, external data, format conversions
Output Format
For each target function, produce:
## Analysis: `function_name`
### Contracts
- Parameter X: Type, range [A, B], constraints
- Parameter Y: Type, must not be null/empty
### Realism Bounds (Calculated)
- String inputs: Max N characters (based on M samples, mean=P, std=Q)
- Numeric inputs: Range [X, Y]
- Objects: Max depth D, max fields F
### Realistic Edge Cases (TESTABLE)
1. [Specific input] - [Why it's realistic] - [What might break]
2. ...
### Excluded Scenarios (NOT TESTABLE - Contract Violations)
1. [Input] - [Why it violates contract]
2. ...
### Vulnerability Hypothesis
- Primary risk: [e.g., "off-by-one in loop boundary"]
- Secondary risk: [e.g., "floating point precision in total calculation"]
1---2name: adversarial-analysis3description: Analyze code to identify explicit contracts, implicit usage patterns, and realistic boundary conditions. Contains concrete formulas for calculating input realism limits. Use before generating adversarial tests.4---56# Adversarial Code Analysis78## Purpose910Map the "Surface of Reality" for target code. Your goal is to distinguish:11- **Contract Violations** (invalid inputs the caller shouldn't send) → NOT testable12- **Logic Bugs** (valid inputs the code handles poorly) → TESTABLE1314## Analysis Checklist1516### 1. Contract Extraction1718**Explicit Contracts:**19- Type hints (`int`, `str`, `Optional[T]`, `List[T]`)20- `assert` statements and preconditions21- Docstring `Args`, `Raises`, `Returns` sections22- Validation code at function entry2324**Implicit Contracts:**25- Variable names implying limits (`retry_count` → small positive int, `buffer_size` → memory-reasonable)26- Context from call sites (what values are actually passed?)27- Domain knowledge (user IDs are positive, emails contain @)2829**External Constraints:**30- Database column limits (VARCHAR(255))31- API rate limits and timeouts32- Filesystem permissions and path length limits3334### 2. Realism Baseline (The 3-Sigma Rule)3536Use `Grep` to scan existing tests in `tests/` and call sites in `src/`. Calculate boundaries:3738**String Inputs:**39```40existing_lengths = [len(s) for each test string argument]41if len(existing_lengths) >= 5:42 Max_Realistic_Length = mean(existing_lengths) + 3 * std(existing_lengths)43elif len(existing_lengths) >= 1:44 Max_Realistic_Length = max(existing_lengths) * 245else:46 Max_Realistic_Length = 256 # Zero-sample fallback47```4849**Numeric Inputs:**50```51existing_values = [v for each numeric argument]52if len(existing_values) >= 5:53 Lower = mean(existing_values) - 3 * std(existing_values)54 Upper = mean(existing_values) + 3 * std(existing_values)55elif len(existing_values) >= 1:56 Lower = min(existing_values) - abs(min(existing_values))57 Upper = max(existing_values) + abs(max(existing_values))58else:59 Lower, Upper = -1000, 1000 # Zero-sample fallback60```6162**Special Boundaries (Always Valid):**63- `0`, `-1`, `1` for integers (if type allows)64- Empty string `""` (if not explicitly forbidden)65- `None` only if type is `Optional`6667**Complex Objects:**68- Max nesting depth: 3 levels (unless recursive data structure)69- Max fields: 20 (unless schema requires more)70- Zero-sample fallback: depth 2, fields 107172### 3. Vulnerability Surface Identification7374**High-Risk Patterns:**75- **Arithmetic**: Division, modulo, floating-point accumulation, currency calculations76- **Boundaries**: Loop limits, array indices, string slicing77- **State**: Multi-step workflows, flag combinations, temporal dependencies78- **Resources**: File handles, connections, locks (cleanup on error paths)79- **Parsing**: User input, external data, format conversions8081## Output Format8283For each target function, produce:8485```86## Analysis: `function_name`8788### Contracts89- Parameter X: Type, range [A, B], constraints90- Parameter Y: Type, must not be null/empty9192### Realism Bounds (Calculated)93- String inputs: Max N characters (based on M samples, mean=P, std=Q)94- Numeric inputs: Range [X, Y]95- Objects: Max depth D, max fields F9697### Realistic Edge Cases (TESTABLE)981. [Specific input] - [Why it's realistic] - [What might break]992. ...100101### Excluded Scenarios (NOT TESTABLE - Contract Violations)1021. [Input] - [Why it violates contract]1032. ...104105### Vulnerability Hypothesis106- Primary risk: [e.g., "off-by-one in loop boundary"]107- Secondary risk: [e.g., "floating point precision in total calculation"]108```