
Graph Evolution
- 2.6k installs
- 6.4k repo stars
- Updated August 4, 2026
- trailofbits/skills
graph-evolution builds Trailmark graphs at two snapshots and reports security-focused structural diffs beyond text patches.
About
The graph-evolution skill compares Trailmark code graphs at two source snapshots to find security-relevant structural changes text diffs miss. Use cases include new attack paths, complexity shifts, blast radius growth, taint propagation changes, and privilege boundary modifications across commits, tags, or directories. Prerequisites require trailmark installed via uv pip install; manual source comparison is forbidden when the tool fails. Phase 1 creates git worktrees for before and after refs. Phase 2 builds graphs with QueryEngine.from_directory, runs engine.preanalysis for blast radius and taint data, and exports JSON summaries. Phase 3 runs both trailmark diff --json and the plugin graph_diff.py helper for subgraph membership changes; stop if either writes empty JSON. Phase 4 interprets nodes added removed modified, edges, entrypoints, and subgraph deltas into a security-focused markdown report. Phase 5 cleans worktrees. Reject rationalizations to skip preanalysis or rely on text diff alone. Related skills differential-review handles line diffs, trailmark handles single snapshots, diagramming-code handles diagrams, and genotoxic handles mutation triage.
- Compare two git refs or directories with Trailmark structural diff.
- engine.preanalysis required on both snapshots before diffing.
- Run trailmark diff --json and graph_diff.py subgraph helper.
- Surfaces attack paths, blast radius, taint, and privilege boundary shifts.
- Five-phase workflow: worktrees, build graphs, diff, report, cleanup.
Graph Evolution by the numbers
- 2,620 all-time installs (skills.sh)
- +116 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #198 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
graph-evolution capabilities & compatibility
- Capabilities
- git worktree snapshot isolation · trailmark preanalysis and json export · native and subgraph structural diff merging · security focused markdown report generation
- Use cases
- security audit · code review · research
- Platforms
- macOS · Linux
- Runs
- Runs locally
- Pricing
- Free
What graph-evolution says it does
Surfaces security-relevant changes that text-level diffs miss
Without pre-analysis, you miss taint changes, blast radius growth, and privilege boundary shifts
npx skills add https://github.com/trailofbits/skills --skill graph-evolutionAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2.6k |
|---|---|
| repo stars | ★ 6.4k |
| Security audit | 3 / 3 scanners passed |
| Last updated | August 4, 2026 |
| Repository | trailofbits/skills ↗ |
What security-relevant structural changes occurred between these two commits or tags?
Compare Trailmark code graphs between git refs to surface security-relevant structural diffs beyond text patches.
Who is it for?
Security reviews comparing audit snapshots, release tags, or branch heads in codebases with trailmark installed.
Skip if: Skip for line-level review only; use differential-review or single-snapshot trailmark instead.
When should I use this skill?
User compares commits for attack surface growth, structural evolution, or security changes text diffs miss.
What you get
A markdown report from native and subgraph diffs highlighting attack paths, taint, and boundary shifts.
- structural security diff report
- classified graph evolution metrics
By the numbers
- Includes graph_diff.py and 2 reference docs for metrics and reports
- Requires two snapshot graphs with preanalysis on each
Files
Graph Evolution
Builds Trailmark code graphs at two source snapshots and computes a structural diff. Surfaces security-relevant changes that text-level diffs miss: new attack paths, complexity shifts, blast radius growth, taint propagation changes, and privilege boundary modifications.
When to Use
- Comparing two git refs to understand what structurally changed
- Auditing a range of commits for security-relevant evolution
- Detecting new attack paths created by code changes
- Finding functions whose blast radius or complexity grew silently
- Identifying taint propagation changes across refactors
- Pre-release structural comparison (tag-to-tag or branch-to-branch)
When NOT to Use
- Line-level code review (use
differential-reviewfor text-diff analysis) - Single-snapshot analysis (use the
trailmarkskill directly) - Diagram generation from a single snapshot (use the
diagramming-codeskill) - Mutation testing triage (use the
genotoxicskill)
Rationalizations to Reject
| Rationalization | Why It's Wrong | Required Action |
|---|---|---|
| "We just need the structural diff, skip pre-analysis" | Without pre-analysis, you miss taint changes, blast radius growth, and privilege boundary shifts | Run engine.preanalysis() on both snapshots |
| "Text diff covers what changed" | Text diffs miss new attack paths, transitive complexity shifts, and subgraph membership changes | Use structural diff to complement text diff |
| "Only added nodes matter" | Removed security functions and shifted privilege boundaries are equally dangerous | Review removals and modifications, not just additions |
| "Low-severity structural changes can be ignored" | INFO-level changes (dead code removal) can mask removed security checks | Classify every change, review removals for replaced functionality |
| "One snapshot's graph is enough for comparison" | Single-snapshot analysis can't detect evolution — you need both before and after | Always build and export both graphs |
| "Tool isn't installed, I'll compare manually" | Manual comparison misses what graph analysis catches | Install trailmark first |
---
Prerequisites
trailmark must be installed. If uv run trailmark fails, run:
uv pip install trailmarkDO NOT fall back to "manual comparison" or reading source files as a substitute for running trailmark. The tool must be installed and used programmatically. If installation fails, report the error.
---
Quick Start
# Compare two git refs (e.g., tags, branches, commits)
# 1. Build graphs at each snapshot
# 2. Run pre-analysis on both
# 3. Compute structural diff
# 4. Generate report
# Step-by-step: see Workflow below---
Decision Tree
├─ Need to understand what each metric means?
│ └─ Read: references/evolution-metrics.md
│
├─ Need the report output format?
│ └─ Read: references/report-format.md
│
├─ Already have two graph JSON exports?
│ └─ Jump to Phase 3 (run native diff + graph_diff.py)
│
└─ Starting from two git refs?
└─ Start at Phase 1---
Workflow
Graph Evolution Progress:
- [ ] Phase 1: Create snapshots (git worktrees)
- [ ] Phase 2: Build graphs + pre-analysis on both snapshots
- [ ] Phase 3: Compute structural diff
- [ ] Phase 4: Interpret diff and generate report
- [ ] Phase 5: Clean up worktreesPhase 1: Create Snapshots
Use git worktrees to get clean copies of each ref without disturbing the working tree.
# Create temp directories for worktrees
BEFORE_DIR=$(mktemp -d)
AFTER_DIR=$(mktemp -d)
# Create worktrees (run from repo root)
git worktree add "$BEFORE_DIR" {before_ref}
git worktree add "$AFTER_DIR" {after_ref}If comparing two directories instead of git refs, skip this phase and use the directory paths directly in Phase 2.
Phase 2: Build Graphs and Run Pre-Analysis
Build Trailmark graphs for both snapshots and run pre-analysis on each. Pre-analysis computes blast radius, taint propagation, privilege boundaries, and entrypoint enumeration.
from trailmark.query.api import QueryEngine
def build_and_export(target_dir, output_path, language="auto"):
"""Build graph, run pre-analysis, export JSON."""
engine = QueryEngine.from_directory(target_dir, language=language)
engine.preanalysis()
json_str = engine.to_json()
with open(output_path, "w") as f:
f.write(json_str)
return engine.summary()
import tempfile, os
work_dir = tempfile.mkdtemp(prefix="trailmark_evolution_")
before_json = os.path.join(work_dir, "before_graph.json")
after_json = os.path.join(work_dir, "after_graph.json")
before_summary = build_and_export(
"{before_dir}", before_json
)
after_summary = build_and_export(
"{after_dir}", after_json
)Verify both graphs built successfully by checking the summary output. If either fails, rerun with an explicit language or comma-separated list instead of auto.
Phase 3: Compute Structural Diff
Run both:
1. Trailmark's native structural diff for nodes, edges, and entrypoints 2. The plugin's graph_diff.py helper for subgraph membership changes
Using the same work_dir from Phase 2:
trailmark diff --json "{before_dir}" "{after_dir}" > "{work_dir}/trailmark_diff.json" || \
uv run trailmark diff --json "{before_dir}" "{after_dir}" > "{work_dir}/trailmark_diff.json"
uv run {baseDir}/scripts/graph_diff.py \
--before "{before_json}" \
--after "{after_json}" > "{work_dir}/subgraph_diff.json"If either diff command fails or writes an empty JSON file, stop and report the error instead of continuing to Phase 4.
The native Trailmark diff contains:
| Key | Contents |
|---|---|
summary_delta | Changes in node/edge/entrypoint counts |
nodes.added | New functions, classes, methods |
nodes.removed | Deleted functions, classes, methods |
nodes.modified | Functions with changed CC, params, line span |
edges.added | New call/inheritance/import relationships |
edges.removed | Deleted relationships |
entrypoints | Added, removed, and modified entrypoints |
The subgraph diff contains:
| Key | Contents |
|---|---|
subgraphs | Per-subgraph membership changes (tainted, high_blast_radius, etc.) |
Phase 4: Interpret Diff and Generate Report
Read both diff JSON files and generate a security-focused markdown report. See references/report-format.md for the full template.
Interpretation priorities (highest to lowest):
1. New tainted paths — nodes entering the tainted subgraph, especially if they also appear in added edges targeting sensitive functions 2. Privilege boundary changes — new or removed trust transitions from the native entrypoint/edge diff plus the subgraph diff 3. Attack surface growth — new entrypoints, especially untrusted_external, from trailmark_diff.json 4. Blast radius increases — nodes entering high_blast_radius 5. Complexity spikes — CC increases > 3 on tainted or entrypoint-reachable nodes 6. Structural additions — new nodes and edges (review needed) 7. Structural removals — verify removed security functions were replaced
Cross-reference structural changes with git diff {before_ref}..{after_ref} to add source-level context to findings.
Severity classification:
| Severity | Structural Signal |
|---|---|
| CRITICAL | New tainted path to sensitive function, removed auth boundary |
| HIGH | New entrypoint + high blast radius, large CC increase on tainted node |
| MEDIUM | New trust-boundary-crossing edges, moderate CC increase |
| LOW | Added nodes without entrypoint reachability |
| INFO | Dead code removal, complexity reductions |
For detailed metric definitions, see references/evolution-metrics.md.
Phase 5: Clean Up
Remove git worktrees after the report is written:
git worktree remove "{before_dir}"
git worktree remove "{after_dir}"---
Diff Reference
trailmark diff --json BEFORE AFTER
uv run {baseDir}/scripts/graph_diff.py [OPTIONS]Use trailmark diff for:
- Node/edge changes
- Added/removed/modified entrypoints
- Human-readable structural diff reports
Use graph_diff.py for:
- Subgraph membership changes derived from
engine.preanalysis() tainted,high_blast_radius,privilege_boundary, and related sets
| Argument | Default | Description |
|---|---|---|
--before | required | Path to the "before" graph JSON |
--after | required | Path to the "after" graph JSON |
--indent | 2 | JSON output indentation |
graph_diff.py input format: Trailmark JSON exports from engine.to_json(). graph_diff.py output: JSON structural diff for nodes, edges, and subgraphs.
---
Quality Checklist
Before delivering the report:
- [ ] Both graphs built successfully (check summaries)
- [ ] Pre-analysis ran on both snapshots
- [ ] Native Trailmark diff computed and non-empty (
trailmark_diff.json) - [ ] Subgraph diff computed and non-empty (
subgraph_diff.json) - [ ] All subgraph changes interpreted (tainted, blast radius, etc.)
- [ ] Critical findings include evidence (node IDs, edge diffs)
- [ ] Severity levels assigned to all findings
- [ ] Source-level context added via git diff cross-reference
- [ ] Worktrees cleaned up (or temp dirs removed)
- [ ] Report written to
GRAPH_EVOLUTION_*.md
---
Integration
trailmark skill: Phase 2 uses the trailmark API for graph building and pre-analysis. All trailmark query patterns work on either snapshot's engine.
differential-review skill: Use graph-evolution for structural analysis, differential-review for line-level code review. The two are complementary — graph-evolution finds attack paths that text diffs miss, while differential-review provides git blame context and micro-adversarial analysis.
genotoxic skill: If graph-evolution reveals new high-CC tainted nodes, feed them to genotoxic for mutation testing triage.
diagramming-code skill: Generate before/after diagrams to visualize structural changes. Use call-graph or data-flow diagrams focused on changed nodes.
---
Supporting Documentation
- [references/evolution-metrics.md](references/evolution-metrics.md) —
What each structural metric means and why it matters for security
- [references/report-format.md](references/report-format.md) —
Report template, severity classification, and example findings
interface:
icon_small: "assets/trail-of-bits-mark.svg"
icon_large: "assets/trail-of-bits-mark.svg"
brand_color: "#D83A34"
<svg xmlns="http://www.w3.org/2000/svg" width="94" height="56" fill="none" viewBox="0 0 94 56"><path fill="#F0F4F7" d="m34.04 54.662-7.61-4.147L24.593 56l9.433-1.335c-.029 0-.043 0 .014-.003"/><path fill="#F0F4F7" d="m34.039 54.662-.014.003c.035 0 .096-.003.014-.003m26.191-2.67 6.124-1.804 2.301-7.26-5.655.387zM74.805 5.478l-4.68-3.035-2.62 8.332 5.15 1.548zM43.224 3.532s3.172.973 4.423 1.328l4.508 1.335L52.234 0l-7.928 1.576zm-31.473 23.14 5.566.014 1.982-6.216-5.06-1.342c-.538 1.708-1.94 5.837-2.488 7.544M1.394 20.896l4.164 4.338 2.398-7.696-5.11-1.357zm88.205 24.841c-.086-2.18-.692-2.894-1.978-4.232l-6.71.447c1.871 1.175 3.018 2.63 3.255 4.583.261 2.145-2.068 4.623-4.322 4.623-1.258 0-1.885-.987-1.885-2.12.035-.845.333-1.942.777-2.673h-5.691c-.444 1.136-.813 2.418-.813 3.625 0 4.136 3.659 5.197 7.131 5.197 3.62 0 6.616-.696 8.501-4.03.85-1.505 1.806-3.663 1.735-5.42M18.804.56 1.362.576 0 4.86l6.394-.007-3.161 9.962 5.114 1.356 3.551-11.322 5.544-.007z"/><path fill="#F0F4F7" d="M20.707 15.898c.628-.04 1.258-.04 1.886-.04 1.035-.003 2.587.072 2.587 1.499.004.987-.366 2.233-.66 3.184-.551 1.942-1.214 3.88-1.325 5.858l5.727-.007c-.151-3.185 1.842-5.968 1.838-9.117 0-2.123-1.627-2.964-3.512-3.294l.552-.075c4.103-.554 6.39-3.738 6.386-7.729-.004-4.423-3.738-5.666-7.544-5.662l-6.576.007c-1.87 5.751-3.645 11.534-5.462 17.31l5.057 1.339zM24.245 4.58l1.849-.004c1.369 0 2.734.327 2.738 1.939.003 1.977-1.437 5.31-3.803 5.31l-3.031.004zm11.959 21.883 2.949-5.531 7.06-.008-.215 5.564 5.544-.004.441-18.94-4.763-1.43a89 89 0 0 0-.677 10.71h-.036l-5.322.004c1.914-3.586 3.749-7.2 5.4-10.906L42.77 4.775 30.437 26.466zm39.249-.036 1.402-4.214-7.43.01 2.753-8.612-5.15-1.548-4.584 14.375zm-34.411 1.658h-7.28l-6.834 21.18 8.698 4.694c5.208-.196 8.856-4.012 8.856-9.252 0-2.013-1.258-3.586-3.215-4.136 3.846-.877 6.319-3.33 6.319-7.356-.004-3.923-3.072-5.13-6.544-5.13m-2.993 20.318c-1.036 1.537-2.143 1.647-3.881 1.647h-2.254l2.476-7.611c1.81.07 5.024-.366 5.024 2.268 0 1.168-.698 2.744-1.365 3.696m-.444-9.667h-2.072l2.18-6.7c1.626.075 4.694-.436 4.694 2.053.04 2.928-1.846 4.647-4.802 4.647M58.67 9.582l-5.522 18.29-4.878 14.836 5.856-.447 4.23-13.2h.006l5.713-17.878c-.796-.22-3.964-1.228-5.404-1.601m2.738 18.542-1.37 4.278h6.398l-2.993 9.525 5.584-.38 2.913-9.145h5.541l1.37-4.278zm25.351-.259c-5.726 0-9.127 3.951-9.127 9.444.007.798.727 2.765 2.2 3.422l6.888-.462c-1.172-.98-3.243-3.29-3.243-4.519 0-1.686.95-3.891 2.91-3.891 1.33 0 2.143.366 2.143 1.793 0 .916-.444 1.757-.702 2.638h5.322c.333-.77.849-2.528.849-3.334.004-3.994-3.913-5.09-7.24-5.09m-63.15.372c-2.605 0-2.978 1.906-3.623 3.93-.215.728-.623 1.615-.623 2.379 0 1.47 1.315 1.75 2.537 1.75 1.494.01 2.29-.487 2.82-1.878.362-.952 1.305-3.568 1.305-4.488 0-1.303-1.326-1.693-2.416-1.693m.728 1.87c0 .328-.373 1.392-.498 1.765l-.577 1.782c-.226.675-.498 1.449-1.359 1.449-.487 0-.802-.28-.802-.785 0-.653.509-1.864.724-2.538.215-.671.498-2.01 1.247-2.269.168-.056.351-.078.534-.078.34 0 .749.302.749.664zm5.902 2.674.394-1.292H28.37l.613-1.928h2.38l.42-1.292h-4.126l-2.48 7.924h1.735l1.075-3.412z"/></svg>
Evolution Metrics Reference
This document explains each structural metric the graph-evolution skill tracks and why it matters for security analysis.
Contents
- Node changes (added, removed, modified)
- Edge changes (added, removed)
- Complexity evolution
- Attack surface changes
- Blast radius shifts
- Taint propagation changes
- Privilege boundary changes
---
Node Changes
Added Nodes
New functions, methods, classes, or modules introduced between snapshots.
Security relevance:
- New code has no review history and may lack test coverage
- New public functions expand the attack surface
- New classes may introduce state management complexity
Triage: Cross-reference added nodes against the after graph's entrypoints subgraph. Added nodes that are entrypoint-reachable get highest review priority.
Removed Nodes
Functions, methods, or classes deleted between snapshots.
Security relevance:
- Removed validation functions may indicate weakened security controls
- Removed error handlers can expose unhandled edge cases
- Dead code removal is generally positive (reduces attack surface)
Triage: Check if removed nodes had privilege_boundary or taint_propagation annotations. If so, verify the security function was replaced, not just deleted.
Modified Nodes
Nodes present in both snapshots whose properties changed. Tracked properties:
| Property | What Changed | Security Concern |
|---|---|---|
cyclomatic_complexity | Control flow complexity | Higher CC = more paths to test |
parameters | Function signature | New params may accept untrusted input |
return_type | Return type annotation | Type changes can break callers |
line_span | Lines of code | Significant growth may indicate added logic |
---
Edge Changes
Added Edges
New call relationships between functions.
Security relevance:
- New calls from untrusted entrypoints to sensitive functions create
attack paths that did not previously exist
- New
inheritsorimplementsedges can change polymorphic dispatch - Cross-module calls may violate existing trust boundaries
Triage: For each added calls edge, check if source is in the tainted subgraph and target handles sensitive operations.
Removed Edges
Call relationships that no longer exist.
Security relevance:
- Removed validation calls may mean input is no longer checked
- Removed authorization calls can create privilege escalation
- Usually benign during refactoring, but verify removed edges
between security-relevant nodes
---
Complexity Evolution
Tracks per-node cyclomatic complexity changes between snapshots.
Thresholds:
| CC Delta | Significance |
|---|---|
| +1 to +3 | Minor — likely a new branch or error check |
| +4 to +9 | Moderate — new logic paths need test coverage |
| +10 or more | Major — function is becoming difficult to reason about |
| Negative | Positive — simplification usually reduces bug surface |
Aggregate signals:
- Mean CC increase across all modified nodes indicates codebase is
growing more complex
- Functions that crossed the CC > 10 threshold are new fuzzing
candidates (per the genotoxic skill's criteria)
---
Attack Surface Changes
Derived from the entrypoints subgraph.
New entrypoints: Nodes that appear in the after entrypoints but not before. Each new entrypoint is a new way external input reaches the system.
Removed entrypoints: Nodes that were entrypoints in before but not after. Usually positive (reduced surface), but verify the functionality wasn't just moved.
Trust level changes: Compare entrypoint trust levels between snapshots. A function changing from trusted_internal to untrusted_external is a significant security event.
---
Blast Radius Shifts
Derived from the high_blast_radius subgraph (nodes with 10+ downstream dependents).
New high-blast nodes: Nodes that entered high_blast_radius in after. These now affect many downstream functions — bugs here have wide impact.
Reduced blast radius: Nodes that left high_blast_radius. Usually positive (decoupling), but verify the downstream functions weren't orphaned.
---
Taint Propagation Changes
Derived from the tainted subgraph (nodes reachable from untrusted entrypoints).
Newly tainted: Nodes that entered tainted in after. These can now be reached by untrusted input and must validate their inputs.
De-tainted: Nodes that left tainted. Usually means a trust boundary was added or an entrypoint was removed.
Critical combination: Nodes that are both newly tainted AND had their CC increase. These are the highest-priority review targets.
---
Privilege Boundary Changes
Derived from the privilege_boundary subgraph (edges where trust levels change).
New boundary crossings: Functions that appeared on a privilege boundary. These are points where trust transitions happen — common vulnerability locations.
Removed boundaries: Privilege boundaries that disappeared. Could mean trust was flattened (potentially unsafe) or that the boundary moved (needs verification).
Report Format Reference
Output format for graph-evolution reports. The report is a markdown file summarizing structural changes between two code graph snapshots.
Contents
- Report filename convention
- Section-by-section template
- Severity classification
- Example snippets
---
Filename Convention
GRAPH_EVOLUTION_<project>_<before-ref>_<after-ref>.mdExample: GRAPH_EVOLUTION_myapp_v1.2.0_v1.3.0.md
---
Report Template
# Graph Evolution Report
**Project:** {project_name}
**Before:** {before_ref} ({before_date})
**After:** {after_ref} ({after_date})
**Language:** {language}
## Summary
| Metric | Before | After | Delta |
|--------|--------|-------|-------|
| Total nodes | N | N | +/-N |
| Functions | N | N | +/-N |
| Classes | N | N | +/-N |
| Call edges | N | N | +/-N |
| Entrypoints | N | N | +/-N |
## Critical Structural Changes
Changes with direct security implications. Each finding includes
the structural evidence and affected nodes.
### [SEVERITY] Finding title
**What changed:** Description of the structural change
**Evidence:** Node IDs, edge diffs, subgraph membership
**Security impact:** Why this matters
**Recommendation:** What to review or test
## Attack Surface Evolution
### New Entrypoints
| Node | Kind | Trust Level | File |
|------|------|------------|------|
### Removed Entrypoints
| Node | Kind | Trust Level | File |
|------|------|------------|------|
## Complexity Evolution
### Increased Complexity (CC delta > 0)
| Node | Before CC | After CC | Delta | File |
|------|-----------|----------|-------|------|
### Decreased Complexity (CC delta < 0)
| Node | Before CC | After CC | Delta | File |
|------|-----------|----------|-------|------|
## Taint Propagation Changes
### Newly Tainted Nodes
| Node | Kind | Tainted Via | File |
|------|------|-------------|------|
### De-Tainted Nodes
| Node | Kind | File |
|------|------|------|
## Blast Radius Shifts
### Nodes Entering high_blast_radius
| Node | Kind | Downstream Count | File |
|------|------|-----------------|------|
### Nodes Leaving high_blast_radius
| Node | Kind | File |
|------|------|------|
## Privilege Boundary Changes
### New Boundary Crossings
| Node | Trust Transition | File |
|------|-----------------|------|
### Removed Boundary Crossings
| Node | Trust Transition | File |
|------|-----------------|------|
## New Code (Added Nodes)
| Node | Kind | CC | File |
|------|------|----|------|
## Removed Code (Deleted Nodes)
| Node | Kind | CC | File |
|------|------|----|------|
## New Call Relationships (Added Edges)
| Source | Target | Kind |
|--------|--------|------|
## Removed Call Relationships (Deleted Edges)
| Source | Target | Kind |
|--------|--------|------|
## Methodology
- **Tool:** Trailmark graph-evolution
- **Before snapshot:** {before_ref}
- **After snapshot:** {after_ref}
- **Pre-analysis:** blast radius, taint, privilege boundaries,
entrypoints
- **Limitations:** {honest scope disclosure}---
Severity Classification
Classify structural findings by security impact:
| Severity | Criteria |
|---|---|
| CRITICAL | New tainted path to sensitive function, removed auth boundary |
| HIGH | New entrypoint + high blast radius, CC increase > 10 on tainted node |
| MEDIUM | New call edges crossing trust boundaries, moderate CC increase |
| LOW | Added nodes without entrypoint reachability, cosmetic changes |
| INFO | Dead code removal, complexity reductions, positive changes |
---
Example: Critical Finding
### [CRITICAL] New untrusted path to database query
**What changed:** Function `parse_user_input` (added) calls
`execute_query` (existing, tainted). This edge did not exist in the
before snapshot.
**Evidence:**
- Added edge: `parse_user_input` → `execute_query` (calls, certain)
- `execute_query` is in `high_blast_radius` (47 downstream nodes)
- `parse_user_input` is in `tainted` subgraph
- `parse_user_input` CC = 12 (above fuzzing threshold)
**Security impact:** Untrusted external input can now reach database
query execution through a complex, high-blast-radius path.
**Recommendation:**
1. Verify input validation on `parse_user_input`
2. Add parameterized query usage in `execute_query`
3. Write fuzz harness targeting `parse_user_input`# /// script
# requires-python = ">=3.12"
# ///
"""Compute structural diff between two Trailmark graph JSON exports.
Compares nodes, edges, complexity, subgraph membership, and
pre-analysis results to surface security-relevant structural changes.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
def load_graph(path: str) -> dict[str, Any]:
"""Load and validate a Trailmark JSON export."""
data = json.loads(Path(path).read_text())
for key in ("nodes", "edges"):
if key not in data:
print(f"ERROR: Missing '{key}' in {path}", file=sys.stderr)
sys.exit(1)
return data
def diff_nodes(
before: dict[str, Any],
after: dict[str, Any],
) -> dict[str, Any]:
"""Compute added, removed, and modified nodes."""
before_ids = set(before.keys())
after_ids = set(after.keys())
added = _summarize_nodes(after, after_ids - before_ids)
removed = _summarize_nodes(before, before_ids - after_ids)
modified = _find_modified(before, after, before_ids & after_ids)
return {"added": added, "removed": removed, "modified": modified}
def _summarize_nodes(
nodes: dict[str, Any],
ids: set[str],
) -> list[dict[str, Any]]:
"""Extract summary dicts for a set of node IDs."""
result = []
for nid in sorted(ids):
node = nodes[nid]
result.append(
{
"id": nid,
"name": node.get("name", ""),
"kind": node.get("kind", ""),
"file": _node_file(node),
"cyclomatic_complexity": node.get("cyclomatic_complexity"),
}
)
return result
def _node_file(node: dict[str, Any]) -> str:
"""Extract file path from a node's location."""
loc = node.get("location", {})
if isinstance(loc, dict):
return loc.get("file_path", "")
return ""
def _find_modified(
before: dict[str, Any],
after: dict[str, Any],
shared_ids: set[str],
) -> list[dict[str, Any]]:
"""Find nodes present in both with changed properties."""
modified = []
for nid in sorted(shared_ids):
b, a = before[nid], after[nid]
changes = _compare_node_properties(b, a)
if changes:
modified.append({"id": nid, "changes": changes})
return modified
def _compare_node_properties(
before: dict[str, Any],
after: dict[str, Any],
) -> dict[str, Any]:
"""Compare security-relevant properties of two node versions."""
changes: dict[str, Any] = {}
cc_b = before.get("cyclomatic_complexity")
cc_a = after.get("cyclomatic_complexity")
if cc_b != cc_a:
changes["cyclomatic_complexity"] = {
"before": cc_b,
"after": cc_a,
}
params_b = _param_signature(before)
params_a = _param_signature(after)
if params_b != params_a:
changes["parameters"] = {
"before": params_b,
"after": params_a,
}
ret_b = _return_type_str(before)
ret_a = _return_type_str(after)
if ret_b != ret_a:
changes["return_type"] = {"before": ret_b, "after": ret_a}
span_b = _line_span(before)
span_a = _line_span(after)
if span_b != span_a:
changes["line_span"] = {"before": span_b, "after": span_a}
return changes
def _param_signature(node: dict[str, Any]) -> list[str]:
"""Extract parameter names from a node."""
params = node.get("parameters", ())
if isinstance(params, (list, tuple)):
return [p.get("name", "") if isinstance(p, dict) else str(p) for p in params]
return []
def _return_type_str(node: dict[str, Any]) -> str | None:
"""Extract return type string from a node."""
rt = node.get("return_type")
if isinstance(rt, dict):
return rt.get("name")
return rt
def _line_span(node: dict[str, Any]) -> int:
"""Compute line count from a node's location."""
loc = node.get("location", {})
if isinstance(loc, dict):
start = loc.get("start_line", 0)
end = loc.get("end_line", 0)
return max(0, end - start + 1)
return 0
def diff_edges(
before: list[dict[str, Any]],
after: list[dict[str, Any]],
) -> dict[str, Any]:
"""Compute added and removed edges."""
before_set = {_edge_key(e) for e in before}
after_set = {_edge_key(e) for e in after}
added = sorted(after_set - before_set)
removed = sorted(before_set - after_set)
return {
"added": [_parse_edge_key(k) for k in added],
"removed": [_parse_edge_key(k) for k in removed],
}
def _edge_key(edge: dict[str, Any]) -> str:
"""Create a hashable key for an edge."""
src = edge.get("source", edge.get("source_id", ""))
tgt = edge.get("target", edge.get("target_id", ""))
kind = edge.get("kind", "")
return f"{src}|{tgt}|{kind}"
def _parse_edge_key(key: str) -> dict[str, str]:
"""Convert an edge key back to a dict."""
source, target, kind = key.split("|", 2)
return {"source": source, "target": target, "kind": kind}
def diff_subgraphs(
before: dict[str, list[str]],
after: dict[str, list[str]],
) -> dict[str, Any]:
"""Compute per-subgraph membership changes."""
all_names = sorted(set(before.keys()) | set(after.keys()))
changes: dict[str, Any] = {}
for name in all_names:
b_ids = set(before.get(name, []))
a_ids = set(after.get(name, []))
added = sorted(a_ids - b_ids)
removed = sorted(b_ids - a_ids)
if added or removed:
changes[name] = {"added": added, "removed": removed}
return changes
def compute_summary_delta(
before: dict[str, Any],
after: dict[str, Any],
) -> dict[str, Any]:
"""Compute deltas for summary statistics."""
b_sum = before.get("summary", {})
a_sum = after.get("summary", {})
delta: dict[str, Any] = {}
for key in ("total_nodes", "functions", "classes", "call_edges", "entrypoints"):
b_val = b_sum.get(key, 0)
a_val = a_sum.get(key, 0)
if b_val != a_val:
delta[key] = {
"before": b_val,
"after": a_val,
"delta": a_val - b_val,
}
return delta
def compute_diff(
before: dict[str, Any],
after: dict[str, Any],
) -> dict[str, Any]:
"""Compute the full structural diff between two graphs."""
return {
"summary_delta": compute_summary_delta(before, after),
"nodes": diff_nodes(
before.get("nodes", {}),
after.get("nodes", {}),
),
"edges": diff_edges(
before.get("edges", []),
after.get("edges", []),
),
"subgraphs": diff_subgraphs(
before.get("subgraphs", {}),
after.get("subgraphs", {}),
),
}
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(
description="Structural diff between Trailmark graphs",
)
parser.add_argument(
"--before",
required=True,
help="Path to the 'before' graph JSON export",
)
parser.add_argument(
"--after",
required=True,
help="Path to the 'after' graph JSON export",
)
parser.add_argument(
"--indent",
type=int,
default=2,
help="JSON output indentation (default: 2)",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> None:
"""Entry point: load graphs, compute diff, print JSON."""
args = parse_args(argv)
before = load_graph(args.before)
after = load_graph(args.after)
diff = compute_diff(before, after)
print(json.dumps(diff, indent=args.indent))
if __name__ == "__main__":
main()
Related skills
How it compares
Use graph-evolution alongside text diffs when security-relevant structure—not just lines—may have shifted between releases.
FAQ
Can I skip preanalysis on one snapshot?
No. Run engine.preanalysis on both snapshots or you miss taint and blast radius changes.
What if trailmark is not installed?
Install with uv pip install trailmark; do not fall back to manual source comparison.
Which diff outputs must I read?
Both trailmark diff JSON and graph_diff.py subgraph JSON before generating the report.
Is Graph Evolution safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.