Back to Security & Vulnerability Analysis

audit-context-building

code analysissecurity auditcontext buildingarchitectural reviewvulnerability preparationdeep comprehensionai agent skillsoftware security
⭐ 5.7kπŸ“„ CC-BY-SA-4.0πŸ•’ 2026-06-15Source β†—

Install this skill

npx skills add trailofbits/skills

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

The audit-context-building skill enforces a rigorous, bottom-up methodology for code analysis. Rather than scanning for surface-level bugs, this approach forces the agent to map every line and logical block against fundamental security principles. By applying 5 Whys and 5 Hows techniques to even the simplest functions, the agent creates a persistent, evolving mental model of the system. It treats every code branch and external interaction as a critical data point, ensuring invariants and assumptions are explicitly tracked throughout the entire call chain. This process prioritizes deep comprehension over rapid conclusions, effectively suppressing the tendency to hallucinate vulnerabilities or overlook subtle logic errors that arise from complex composition. It serves as the primary preparatory phase for technical security reviews.

When to Use This Skill

  • β€’Conducting security audits on complex smart contracts or distributed systems
  • β€’Performing architectural reviews where deep understanding of control flow is required
  • β€’Developing threat models by analyzing how specific code blocks handle inputs
  • β€’Preparing for vulnerability discovery by establishing a stable, verified mental map of the system

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • β€œBuild a deep mental model for this module
  • β€œPerform a block-by-block analysis of this file
  • β€œTrace the execution flow of this function with 5 Whys
  • β€œIdentify invariants and assumptions for the current call chain
  • β€œExecute the context building phase for this codebase

Pro Tips

  • πŸ’‘Pair this skill with a 'threat modeling' skill immediately afterward to leverage the deep context for proactive security analysis.
  • πŸ’‘Specify the exact scope (e.g., 'focus on the authentication module') to guide the granular analysis and prevent scope creep.
  • πŸ’‘Use the generated context model as a living document, prompting updates as new code or insights emerge.

What this skill does

  • β€’Performs line-by-line micro-analysis of code blocks
  • β€’Traces full execution flow across internal and external function calls
  • β€’Maintains a persistent, evolving state of identified invariants and assumptions
  • β€’Applies First Principles, 5 Whys, and 5 Hows to isolate logical dependencies
  • β€’Explicitly logs contradiction of previous assumptions as evidence emerges

When not to use it

  • βœ•Generating quick vulnerability findings or exploit payloads
  • βœ•Formulating recommendations for code fixes or patches
  • βœ•Performing superficial overviews or high-level status summaries

Example workflow

  1. Perform a top-level scan to identify actors, entrypoints, and storage structures
  2. Select a high-priority function and execute block-by-block analysis
  3. Apply the 5 Whys to verify the purpose and assumptions of each logical line
  4. Trace internal calls by moving into sub-functions to verify invariant continuity
  5. Document findings in a persistent context file to anchor the mental model

Prerequisites

  • –Full access to the target source code
  • –A clear definition of the system boundary
  • –A defined entry point or module to begin exploration

Pitfalls & limitations

  • !Can be time-intensive and slow compared to high-level scanning
  • !Requires active vigilance to avoid skipping helpers or minor functions
  • !Vulnerable to context window limits if the codebase is excessively large

FAQ

Why is this skill so slow?
It prioritizes granular accuracy and logical verification over speed. Slowing down prevents the agent from making flawed assumptions that lead to false positives later.
Does this skill identify bugs?
No. It focuses exclusively on building a verified understanding of the system's logic and structure to prepare the agent for a later, separate vulnerability hunting phase.
How does it handle external, unknown code?
It treats unknown external calls as adversarial. The agent maps inputs and expected behaviors as if the target could return malicious or unpredictable data.

How it compares

While manual analysis is often prone to human error and 'gist-level' skipping, this skill enforces a strict, recursive protocol that prevents the agent from making unproven leaps in logic.

Source & trust

⭐ 5.7k starsπŸ“„ CC-BY-SA-4.0πŸ•’ Updated 2026-06-15
πŸ“„ Full skill instructions β€” original source: trailofbits/skills
# 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:

1. Identify major modules/files/contracts.
2. Note obvious public/external entrypoints.
3. Identify likely actors (users, owners, relayers, oracles, other contracts).
4. Identify important storage variables, dicts, state structs, or cells.
5. 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:

1. **Purpose**
- Why the function exists and its role in the system.

2. **Inputs & Assumptions**
- Parameters and implicit inputs (state, sender, env).
- Preconditions and constraints.

3. **Outputs & Effects**
- Return values.
- State/storage writes.
- Events/messages.
- External interactions.

4. **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 [FUNCTION_MICRO_ANALYSIS_EXAMPLE.md](resources/FUNCTION_MICRO_ANALYSIS_EXAMPLE.md) for a complete walkthrough demonstrating:
- Full micro-analysis of a DEX swap function
- Application of First Principles, 5 Whys, and 5 Hows
- Block-by-block analysis with invariants and assumptions
- Cross-function dependency mapping
- Risk analysis for external interactions

This example demonstrates the level of depth and structure required for all analyzed functions.

---

### 5.4 Output Requirements

When performing ultra-granular analysis, Claude MUST structure output following the format defined in [OUTPUT_REQUIREMENTS.md](resources/OUTPUT_REQUIREMENTS.md).

Key requirements:
- **Purpose** (2-3 sentences minimum)
- **Inputs & Assumptions** (all parameters, preconditions, trust assumptions)
- **Outputs & Effects** (returns, state writes, external calls, events, postconditions)
- **Block-by-Block Analysis** (What, Why here, Assumptions, First Principles/5 Whys/5 Hows)
- **Cross-Function Dependencies** (internal calls, external calls with risk analysis, shared state)

Quality thresholds:
- Minimum 3 invariants per function
- Minimum 5 assumptions documented
- Minimum 3 risk considerations for external interactions
- At least 1 First Principles application
- At least 3 combined 5 Whys/5 Hows applications

---

### 5.5 Completeness Checklist

Before concluding micro-analysis of a function, verify against the [COMPLETENESS_CHECKLIST.md](resources/COMPLETENESS_CHECKLIST.md):

- **Structural Completeness**: All required sections present (Purpose, Inputs, Outputs, Block-by-Block, Dependencies)
- **Content Depth**: Minimum thresholds met (invariants, assumptions, risk analysis, First Principles)
- **Continuity & Integration**: Cross-references, propagated assumptions, invariant couplings
- **Anti-Hallucination**: Line number citations, no vague statements, evidence-based claims

Analysis is complete when all checklist items are satisfied and no unresolved "unclear" items remain.

---

## 6. Phase 3 β€” Global System Understanding

After sufficient micro-analysis:

1. **State & Invariant Reconstruction**
- Map reads/writes of each state variable.
- Derive multi-function and multi-module invariants.

2. **Workflow Reconstruction**
- Identify end-to-end flows (deposit, withdraw, lifecycle, upgrades).
- Track how state transforms across these flows.
- Record assumptions that persist across steps.

3. **Trust Boundary Mapping**
- Actor β†’ entrypoint β†’ behavior.
- Identify untrusted input paths.
- Privilege changes and implicit role expectations.

4. **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. Subagent Usage

Claude may spawn subagents for:
- Dense or complex functions.
- Long data-flow or control-flow chains.
- Cryptographic / mathematical logic.
- Complex state machines.
- Multi-module workflow reconstruction.

Subagents must:
- Follow the same micro-first rules.
- Return summaries that Claude integrates into its global model.

---

## 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.

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/audit-context-building/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/trailofbits/skills/audit-context-building/SKILL.md
  • Cursor: ~/.cursor/skills/trailofbits/skills/audit-context-building/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/trailofbits/skills/audit-context-building/SKILL.md

πŸš€ Install with CLI:
npx skills add trailofbits/skills

Read the Master Guide: Mastering Agent Skills β†’

Recommended Rules

View more rules β†’

Recommended Workflows

View more workflows β†’

Recommended MCP Servers

View more MCP servers β†’

Take It Further

Maximize your productivity with these powerful resources

πŸ“‹

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
πŸ“–

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid security & vulnerability analysis issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under Security & Vulnerability Analysis and is published by Trail of Bits, maintained in trailofbits/skills.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.