Install
$ agentstack add skill-redhatproductsecurity-prodsec-skills-audit-context-building ✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ✓ Network access No
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
Verified badge
Passed review? Show it. Paste this badge into your README, it links to the public security report.
Reliability & compatibility
Declared compatibility
Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.
We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.
How agent discovery & health will work →About
Deep Context Builder Skill (Ultra-Granular Pure Context Mode)
1. Purpose
This skill governs how Claude thinks during the context-building phase of an audit.
When active, Claude will:
- Perform line-by-line / block-by-block code analysis by default.
- Apply First Principles, 5 Whys, and 5 Hows at micro scale.
- Continuously link insights → functions → modules → entire system.
- Maintain a stable, explicit mental model that evolves with new evidence.
- Identify invariants, assumptions, flows, and reasoning hazards.
This skill defines a structured analysis format (see Example: Function Micro-Analysis below) and runs before the vulnerability-hunting phase.
2. When to Use This Skill
Use when:
- Deep comprehension is needed before bug or vulnerability discovery.
- You want bottom-up understanding instead of high-level guessing.
- Reducing hallucinations, contradictions, and context loss is critical.
- Preparing for security auditing, architecture review, or threat modeling.
Do not use for:
- Vulnerability findings
- Fix recommendations
- Exploit reasoning
- Severity/impact rating
3. How This Skill Behaves
When active, Claude will:
- Default to ultra-granular analysis of each block and line.
- Apply micro-level First Principles, 5 Whys, and 5 Hows.
- Build and refine a persistent global mental model.
- Update earlier assumptions when contradicted ("Earlier I thought X; now Y.").
- Periodically anchor summaries to maintain stable context.
- Avoid speculation; express uncertainty explicitly when needed.
Goal: deep, accurate understanding, not conclusions.
Rationalizations (Do Not Skip)
| Rationalization | Why It's Wrong | Required Action | |-----------------|----------------|-----------------| | "I get the gist" | Gist-level understanding misses edge cases | Line-by-line analysis required | | "This function is simple" | Simple functions compose into complex bugs | Apply 5 Whys anyway | | "I'll remember this invariant" | You won't. Context degrades. | Write it down explicitly | | "External call is probably fine" | External = adversarial until proven otherwise | Jump into code or model as hostile | | "I can skip this helper" | Helpers contain assumptions that propagate | Trace the full call chain | | "This is taking too long" | Rushed context = hallucinated vulnerabilities later | Slow is fast |
4. Phase 1 — Initial Orientation (Bottom-Up Scan)
Before deep analysis, Claude performs a minimal mapping:
- Identify major modules/files/contracts.
- Note obvious public/external entrypoints.
- Identify likely actors (users, owners, relayers, oracles, other contracts).
- Identify important storage variables, dicts, state structs, or cells.
- Build a preliminary structure without assuming behavior.
This establishes anchors for detailed analysis.
5. Phase 2 — Ultra-Granular Function Analysis (Default Mode)
Every non-trivial function receives full micro analysis.
5.1 Per-Function Microstructure Checklist
For each function:
- Purpose
- Why the function exists and its role in the system.
- Inputs & Assumptions
- Parameters and implicit inputs (state, sender, env).
- Preconditions and constraints.
- Outputs & Effects
- Return values.
- State/storage writes.
- Events/messages.
- External interactions.
- Block-by-Block / Line-by-Line Analysis
For each logical block:
- What it does.
- Why it appears here (ordering logic).
- What assumptions it relies on.
- What invariants it establishes or maintains.
- What later logic depends on it.
Apply per-block:
- First Principles
- 5 Whys
- 5 Hows
5.2 Cross-Function & External Flow Analysis
(Full Integration of Jump-Into-External-Code Rule)
When encountering calls, continue the same micro-first analysis across boundaries.
Internal Calls
- Jump into the callee immediately.
- Perform block-by-block analysis of relevant code.
- Track flow of data, assumptions, and invariants:
caller → callee → return → caller.
- Note if callee logic behaves differently in this specific call context.
External Calls — Two Cases
Case A — External Call to a Contract Whose Code Exists in the Codebase Treat as an internal call:
- Jump into the target contract/function.
- Continue block-by-block micro-analysis.
- Propagate invariants and assumptions seamlessly.
- Consider edge cases based on the actual code, not a black-box guess.
Case B — External Call Without Available Code (True External / Black Box) Analyze as adversarial:
- Describe payload/value/gas or parameters sent.
- Identify assumptions about the target.
- Consider all outcomes:
- revert
- incorrect/strange return values
- unexpected state changes
- misbehavior
- reentrancy (if applicable)
Continuity Rule
Treat the entire call chain as one continuous execution flow. Never reset context. All invariants, assumptions, and data dependencies must propagate across calls.
5.3 Complete Analysis Example
See ## Inlined: Function Micro-Analysis Example at the end of this document for a full walkthrough (DEX swap), demonstrating depth and structure required for all analyzed functions.
5.4 Output Requirements
When performing ultra-granular analysis, structure output per ## Inlined: Output Requirements at the end of this document (mandatory sections and quality thresholds).
5.5 Completeness Checklist
Before concluding micro-analysis of a function, verify against ## Inlined: Completeness Checklist at the end of this document.
6. Phase 3 — Global System Understanding
After sufficient micro-analysis:
- State & Invariant Reconstruction
- Map reads/writes of each state variable.
- Derive multi-function and multi-module invariants.
- Workflow Reconstruction
- Identify end-to-end flows (deposit, withdraw, lifecycle, upgrades).
- Track how state transforms across these flows.
- Record assumptions that persist across steps.
- Trust Boundary Mapping
- Actor → entrypoint → behavior.
- Identify untrusted input paths.
- Privilege changes and implicit role expectations.
- Complexity & Fragility Clustering
- Functions with many assumptions.
- High branching logic.
- Multi-step dependencies.
- Coupled state changes across modules.
These clusters help guide the vulnerability-hunting phase.
7. Stability & Consistency Rules
(Anti-Hallucination, Anti-Contradiction)
Claude must:
- Never reshape evidence to fit earlier assumptions.
When contradicted:
- Update the model.
- State the correction explicitly.
- Periodically anchor key facts
Summarize core:
- invariants
- state relationships
- actor roles
- workflows
- Avoid vague guesses
Use:
- "Unclear; need to inspect X."
instead of:
- "It probably…"
- Cross-reference constantly
Connect new insights to previous state, flows, and invariants to maintain global coherence.
8. Delegating Focused Analysis
Split dense or complex work across separate focused sessions or reviewers when helpful:
- Dense or complex functions
- Long data-flow or control-flow chains
- Cryptographic / mathematical logic
- Complex state machines
- Multi-module workflow reconstruction
Each focused pass should follow the full microstructure checklist, cross-function flow rules, and quality thresholds in this skill, and enforce the pure-context-building constraint (no vulnerability findings).
Delegated work must:
- Follow the same micro-first rules
- Return summaries you integrate into a global model
(See upstream Trail of Bits prodsec-skills for companion agent/plugin wiring if you use that distribution.)
9. Relationship to Other Phases
This skill runs before:
- Vulnerability discovery
- Classification / triage
- Report writing
- Impact modeling
- Exploit reasoning
It exists solely to build:
- Deep understanding
- Stable context
- System-level clarity
10. Non-Goals
While active, Claude should NOT:
- Identify vulnerabilities
- Propose fixes
- Generate proofs-of-concept
- Model exploits
- Assign severity or impact
This is pure context building only.
Inlined: Output Requirements
Output Requirements
When performing ultra-granular analysis, structure output following the Per-Function Microstructure Checklist format demonstrated in ## Inlined: Function Micro-Analysis Example (later in this document).
Required Structure
For EACH analyzed function, output MUST include:
1. Purpose (mandatory)
- Clear statement of function's role in the system
- Impact on system state, security, or economics
- Minimum 2-3 sentences
2. Inputs & Assumptions (mandatory)
- All parameters (explicit and implicit)
- All preconditions
- All trust assumptions
- Each input must identify: type, source, trust level
- Minimum 3 assumptions documented
3. Outputs & Effects (mandatory)
- Return values (or "void" if none)
- All state writes
- All external interactions
- All events emitted
- All postconditions
- Minimum 3 effects documented
4. Block-by-Block Analysis (mandatory) For EACH logical code block, document:
- What: What the block does (1 sentence)
- Why here: Why this ordering/placement (1 sentence)
- Assumptions: What must be true (1+ items)
- Depends on: What prior state/logic this relies on
- First Principles / 5 Whys / 5 Hows: Apply at least ONE per block
Minimum standards:
- Analyze at minimum: ALL conditional branches, ALL external calls, ALL state modifications
- For complex blocks (>5 lines): Apply First Principles AND 5 Whys or 5 Hows
- For simple blocks (= amountIn
- Pool has sufficient liquidity to output at least minAmountOut
- block.timestamp = minAmountOut` (slippage protection enforced)
- Pool reserves updated:
reserve0 * reserve1 >= k_before(constant product maintained with fee) - User received exactly amountOut of tokenOut
- Pool received exactly amountIn of tokenIn
- Fee collected:
amountIn * 0.003remains in pool as liquidity
Block-by-Block Analysis:
// L90: Deadline validation (modifier: ensure(deadline))
modifier ensure(uint256 deadline) {
require(block.timestamp 0, "Invalid input amount");
require(minAmountOut > 0, "Invalid minimum output");
require(tokenIn != tokenOut, "Identical tokens");
- What: Validates basic input sanity (non-zero amounts, different tokens)
- Why here: Second line of defense; cheap checks before expensive operations
- Assumption: Zero amounts indicate user error, not intentional probe
- Invariant established:
amountIn > 0 && minAmountOut > 0 && tokenIn != tokenOut - First Principles: Fail fast on invalid input before consuming gas on computation/storage
- 5 Hows:
- How to ensure valid swap? → Check inputs meet minimum requirements
- How to check minimum requirements? → Test amounts > 0 and tokens differ
- How to handle violations? → Revert with descriptive error
- How to order checks? → Cheapest first (inequality checks before storage reads)
- How to communicate failure? → Require statements with clear messages
// L98-99: Pool resolution
address pair = pairs[tokenIn][tokenOut];
require(pair != address(0), "Pool does not exist");
- What: Looks up liquidity pool address for token pair, validates existence
- Why here: Must identify pool before reading reserves or executing transfers
- Assumption:
pairsmapping is populated with valid pool addresses during pool creation; no race conditions - Depends on: Factory having called createPair(tokenIn, tokenOut) previously
- Invariant established:
pair != 0x0(valid pool address exists) - Risk: If pairs mapping is corrupted or pool address is incorrect, funds could be sent to wrong address
// L102-103: Reserve reads
(uint112 reserveIn, uint112 reserveOut) = getReserves(pair, tokenIn, tokenOut);
require(reserveIn > 0 && reserveOut > 0, "Insufficient liquidity");
- What: Reads current pool reserves for tokenIn and tokenOut, validates pool has liquidity
- Why here: Need current reserves to calculate output amount; must confirm pool is operational
- Assumption:
reserves[pair]storage is synchronized with actual pool token balances - Invariant established:
reserveIn > 0 && reserveOut > 0(pool is liquid) - Depends on: Sync mechanism keeping reserves accurate (called after transfers/swaps)
- 5 Whys:
- Why read reserves? → Need current pool state for price calculation
- Why must reserves be > 0? → Division by zero in formula if empty
- Why check liquidity here? → Cheaper to fail now than after transferFrom
- Why not just try the swap? → Better UX with specific error message
- Why trust reserves storage? → Alternative is querying balances (expensive)
// L108-109: Fee application
uint256 amountInWithFee = amountIn * 997;
uint256 numerator = amountInWithFee * reserveOut;
- What: Applies 0.3% protocol fee by multiplying amountIn by 997 (instead of deducting 3)
- Why here: Fee must be applied before price calculation to affect output amount
- Assumption: 997/1000 = 0.997 = (1 - 0.003) represents 0.3% fee deduction
- Invariant maintained:
amountInWithFee = amountIn * 0.997(3/1000 fee taken) - First Principles: Fees modify effective input, reducing output proportionally
- 5 Whys:
- Why multiply by 997? → Gas optimization: avoids separate subtraction step
- Why not amountIn * 0.997? → Solidity doesn't support floating point
- Why 0.3% fee? → Protocol parameter (Uniswap V2 standard, commonly copied)
- Why apply before calculation? → Fee reduces input amount, must affect price
- Why not apply after? → Would incorrectly calculate output at full amountIn
// L110-111: Output calculation (constant product formula)
uint256 denominator = (reserveIn * 1000) + amountInWithFee;
uint256 amountOut = numerator / denominator;
- What: Calculates output amount using AMM constant product formula:
Δy = (x * Δx_fee) / (y + Δx_fee) - Why here: After fee application; core pricing logic of the AMM
- Assumption:
k = reserveIn * reserveOutis the invariant to maintain (with fee adding to k) - Invariant formula:
(reserveIn + amountIn) * (reserveOut - amountOut) >= reserveIn * reserveOut - First Principles: Constant product AMM maintains
x * y = k(with fee slightly increasing k) - 5 Whys:
- Why this formula? → Constant product market maker (x * y = k)
- Why not linear pricing? → Would drain pool at constant price (exploitable)
- Why multiply reserveIn by 1000? → Match denominator scale with numerator (997 * 1000)
- Why divide? → Solving for Δy in: (x + Δx_fee) * (y - Δy) = k
- Why this maintains k? → New product = (reserveIn + amountIn0.997) (reserveOut - amountOut) ≈ k * 1.003
- Mathematical verification:
- Given:
k = reserveIn * reserveOut - New reserves:
reserveIn' = reserveIn + amountIn,reserveOut' = reserveOut - amountOut - With fee:
amountInWithFee = amountIn * 0.997 - Solving
(reserveIn + amountIn) * (reserveOut - amountOut) = k: reserveOut - amountOut = k / (reserveIn + amountIn)amountOut = reserveOut - k / (reserveIn + amountIn)- Substituting and simplifying yields the formula above
// L115: Slippage protection enforcement
require(amountOut >= minAmountOut, "Slippage exceeded");
- What: Validates calculated output meets user's minimum acceptable amount
- Why here: After calculation, before any state changes or transfers (fail fast if insufficient)
- Assumption: User calculated minAmountOut from current reserves and their acceptable slippage tolerance
- Invariant enforced:
amountOut >= minAmountOut(user-defined slippage limit)
…
Source & license
This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: RedHatProductSecurity
- Source: RedHatProductSecurity/prodsec-skills
- License: Apache-2.0
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet, be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.