Cairo auditor

From keep-starknet-strange/starknet-agentic · View interactive version

Cairo auditor is an AI agent skill from the GitHub repository keep-starknet-strange/starknet-agentic. Security audit of Cairo/Starknet code. Trigger on "audit", "check this contract", "review for security". Modes - default (full repo), deep (+ adversarial reasoning), or specific filenames.

How to use this skill

Skill file

Cairo/Starknet Security Audit

You are the orchestrator of a parallelized Cairo/Starknet security audit. Your job is to discover in-scope files, run deterministic preflight, spawn scanning agents, then merge and deduplicate their findings into a single report.

Quick Start

Starknet.js Examples

import { Account, Contract, RpcProvider } from "starknet";

const provider = new RpcProvider({ nodeUrl: process.env.STARKNET_RPC! });
const account = new Account({ provider, address: process.env.ACCOUNT_ADDRESS!, signer: process.env.PRIVATE_KEY! });
const contract = new Contract({ abi, address: process.env.CONTRACT_ADDRESS!, providerOrAccount: account });

try {
  // View call for quick sanity checks while triaging findings.
  const owner = await contract.call("owner", []);

  // State-changing probe used during exploit-path validation.
  const tx = await contract.invoke("set_owner", [owner]);
  const receipt = await provider.waitForTransaction(tx.transaction_hash);
  console.log({ finality: receipt.finality_status });
} catch (err) {
  console.error("audit probe failed", err);
}

Error Codes and Recovery

| Code | Condition | Recovery |

| --- | --- | --- |

| CAUD-001 | In-scope file discovery produced zero files | Re-run with explicit filenames and verify exclude rules did not hide target contracts. |

| CAUD-002 | Preflight scan failed or unavailable | Run python3 "{skill_root}/scripts/quality/audit_local_repo.py" manually and attach output to the audit context. |

| CAUD-003 | Agent bundle generation failed | Rebuild {workdir}/cairo-audit-agent-*-bundle.md and confirm each bundle has non-zero line count. |

| CAUD-004 | Conflicting findings across agents | Keep the highest-confidence root cause, then request a focused re-run on the disputed file. |

| CAUD-005 | Report includes only low-confidence items | Re-run deep mode with the host-specific cairo-auditor entrypoint (for example, /starknet-agentic-skills:cairo-auditor deep in Claude Code) and add deterministic checks from Semgrep/audit findings. |

| CAUD-006 | Deep mode requested but specialist agents unavailable | Re-run in an environment with Agent tool support. Where fail-closed enforcement is enabled, --allow-degraded explicitly permits fallback. |

| CAUD-007 | Deep mode host capability preflight failed | For hosts with preflight enforcement enabled, surface remediation and stop before findings unless --allow-degraded is explicitly present. |

| CAUD-008 | Agent transport instability or stalled specialist completion | Retry failed/stalled specialists once. In hosts with deep-mode enforcement enabled, unresolved specialist outages are treated as fail-closed unless explicitly degraded. |

| CAUD-009 | Strict-model requirement could not be satisfied | Re-run on a host that supports required models, or omit --strict-models to allow documented fallback. |

When to Use

When NOT to Use

Rationalizations to Reject

Mode Selection

Exclude pattern (applies to all modes):

Flags:

Host Capability Preflight (Deep Mode, Experimental)

The host-capability preflight below is an experimental hardening path. Use it when your host exposes specialist-agent capability checks.

Before Turn 1 when mode is deep, run a lightweight capability preflight and emit a one-line status:

If preflight fails (in hosts where preflight is enabled):

Remediation hints to print when preflight fails:

Host-Aware Model Routing

Select specialist model labels from detected host before spawning:

Persist the selected plan to {workdir}/cairo-audit-model-plan.txt and keep model labels in the execution trace as observed runtime values (not assumptions).

Strict-model gate:

Orchestration

Turn 1 — Discover. Print the banner, then in the same message make parallel tool calls.

First, resolve a per-run private work directory:

(a) Resolve and persist in-scope .cairo files to {workdir}/cairo-audit-files.txt per mode selection:

WORKDIR="${CAIRO_AUDITOR_WORKDIR:-$(mktemp -d "${TMPDIR:-/tmp}/cairo-auditor.XXXXXX")}"
chmod 700 "$WORKDIR"
echo "WORKDIR=$WORKDIR"
find <repo-root> \
  \( -type d \( -name test -o -name tests -o -name mock -o -name mocks -o -name example -o -name examples -o -name fixture -o -name fixtures -o -name vendor -o -name vendors -o -name preset -o -name presets \) -prune \) \
  -o \( -type f -name "*.cairo" ! -name "*_test.cairo" ! -name "*Test*.cairo" -print \) \
  | sort > "$WORKDIR/cairo-audit-files.txt"
cat "$WORKDIR/cairo-audit-files.txt"

For $filename ... mode, do not run find. Instead, run:

WORKDIR="${CAIRO_AUDITOR_WORKDIR:-$(mktemp -d "${TMPDIR:-/tmp}/cairo-auditor.XXXXXX")}"
chmod 700 "$WORKDIR"
echo "WORKDIR=$WORKDIR"
REPO_ROOT=$(python3 -c 'import os,sys; print(os.path.realpath(sys.argv[1]))' "<repo-root>")
> "$WORKDIR/cairo-audit-files.txt"
for f in "$@"; do
  [ -z "$f" ] && continue
  ABS_PATH=$(python3 - "$REPO_ROOT" "$f" <<'PY'
import os
import sys

repo_root, arg = sys.argv[1], sys.argv[2]
candidate = arg if os.path.isabs(arg) else os.path.join(repo_root, arg)
print(os.path.realpath(candidate))
PY
)
  case "$ABS_PATH" in
    "$REPO_ROOT"/*) ;;
    *) continue ;;
  esac
  [ -f "$ABS_PATH" ] || continue
  case "$ABS_PATH" in
    *.cairo) echo "$ABS_PATH" >> "$WORKDIR/cairo-audit-files.txt" ;;
  esac
done
sort -u -o "$WORKDIR/cairo-audit-files.txt" "$WORKDIR/cairo-audit-files.txt"
cat "$WORKDIR/cairo-audit-files.txt"

(b) Glob for **/references/attack-vectors/attack-vectors-1.md and resolve:

(c) If {skill_root}/scripts/quality/audit_local_repo.py exists, run the deterministic preflight for full-repo modes only (default/deep). In $filename ... mode, skip preflight so the context stays scoped to the targeted files:

BENCHMARK_BRIDGE=""
if [ -f "{skill_root}/../../scripts/quality/benchmark_cairo_auditor.py" ]; then
  BENCHMARK_BRIDGE="--enable-benchmark-bridge"
fi
python3 "{skill_root}/scripts/quality/audit_local_repo.py" --repo-root <repo-root> --scan-id preflight --output-dir "{workdir}" $BENCHMARK_BRIDGE

Print the preflight results (class counts, severity counts) as context for specialists.

Turn 2 — Prepare. In a single message, make four parallel tool calls:

(a) Read {skill_root}/agents/vector-scan.md — you will paste this full text into every agent prompt.

(b) Read {refs_root}/structured-findings.md and {refs_root}/report-formatting.md — specialists emit structured JSON, then the orchestrator renders the final report.

(c) Bash: build a static audit surface map for all in-scope files:

python3 "{skill_root}/scripts/quality/surface_map.py" \
  --repo-root <repo-root> \
  --scope-file "{workdir}/cairo-audit-files.txt" \
  --output-json "{workdir}/cairo-audit-surface-map.json" \
  --output-md "{workdir}/cairo-audit-surface-map.md"

Append a compact summary from {workdir}/cairo-audit-surface-map.md to Agent 5 prompts in deep mode.

(d) Bash: create four per-agent bundle files ({workdir}/cairo-audit-agent-{1,2,3,4}-bundle.md) in a single command. Each bundle concatenates:

Print line counts per bundle. Example command:

Before running this command, substitute placeholders ({refs_root}, {repo-root}) with the concrete paths resolved in Turn 1.

REFS="{refs_root}"
SRC="{repo-root}"
WORKDIR="{workdir}"
IN_SCOPE="$WORKDIR/cairo-audit-files.txt"
set -euo pipefail

build_code_block() {
  while IFS= read -r f; do
    [ -z "$f" ] && continue
    REL=$(echo "$f" | sed "s|$SRC/||")
    echo "### $REL"
    echo '```cairo'
    cat "$f"
    echo '```'
    echo ""
  done < "$IN_SCOPE"
}

CODE=$(build_code_block)

for i in 1 2 3 4; do
  {
    echo "$CODE"
    echo "---"
    cat "$REFS/judging.md"
    echo "---"
    cat "$REFS/structured-findings.md"
    echo "---"
    cat "$REFS/report-formatting.md"
    echo "---"
    cat "$REFS/attack-vectors/attack-vectors-$i.md"
  } > "$WORKDIR/cairo-audit-agent-$i-bundle.md"
  echo "Bundle $i: $(wc -l < "$WORKDIR/cairo-audit-agent-$i-bundle.md") lines"
done

Do NOT inline source-code files into prompts. Bundles replace raw source in prompts. Non-code context blocks (deterministic preflight summary and optional threat-intel summary) may be appended.

Turn 2.5 — Threat Intel Enrichment (Deep Mode, Optional).

When network access is available, run a small enrichment pass and write {workdir}/cairo-audit-threat-intel.md:

Threat-intel usage rules:

Turn 3 — Spawn. Use foreground Agent tool calls only (do NOT use run_in_background).

1. Wave A: Agents 1–4 in parallel.

2. Wave B: Agent 5 after Wave A completes.

1. Read {skill_root}/agents/adversarial.md for its full instructions.

2. Read {refs_root}/judging.md and {refs_root}/structured-findings.md.

3. Read {workdir}/cairo-audit-surface-map.md before free-form reasoning.

4. If present, read {workdir}/cairo-audit-threat-intel.md as a prioritization hint only.

5. Read {workdir}/cairo-audit-files.txt to obtain in-scope paths, then read only those .cairo files directly (not via bundle).

6. Reason freely — no attack vector reference. Look for logic errors, unsafe interactions, access control gaps, economic exploits, multi-step cross-function chains.

7. Apply FP gate to each finding immediately.

8. Format findings per structured-findings.md.

Specialist output handling:

After spawning, persist execution evidence that will be reused in the final report:

Transport resilience:

Integrity gate (for hosts where deep-mode enforcement is enabled):

Turn 4 — Report. Merge all agent results and emit the report in canonical order:

  1. If {skill_root}/scripts/quality/structured_report.py exists, render through it with all {workdir}/cairo-audit-agent-*-findings.json files, the preflight JSON path, {workdir}/cairo-audit-files.txt, the resolved execution-integrity value, and --proven-only when that flag is active. Use its Markdown output as the report body.
  2. Deduplicate by root cause (keep the higher-confidence version, merge broader attack path details; on confidence tie keep higher priority, then more complete path evidence).
  3. Apply evidence tags per references/judging.md Evidence Tags section:
  1. Findings with only [CODE-TRACE] (no additional tags) are valid but lower-signal; reviewers use the Evidence column in Findings Index to prioritize review order.
  2. Sort findings by priority (P0 first); within each priority tier sort by confidence (highest first).
  3. Re-number findings sequentially starting at 1.
  4. Insert one Below Confidence Threshold separator row in the findings index immediately before the first finding with confidence < 75.
  5. Print rendered findings directly — do not re-draft or re-describe them.
  6. Always include sections in this exact order: Signal Summary, Scope, Execution Trace, Findings, Dropped Candidates, Findings Index.
  7. Add scope table and findings index table per report-formatting.md.
  8. Add the disclaimer.

Dropped-candidate handling:

If --file-output is set, write the report to {repo-root}/security-review-{timestamp}.md and print the path.

After rendering, if {skill_root}/scripts/quality/deep_integrity.py exists, run its check command against {workdir} and the report path. The check validates each cairo-audit-agent-*-findings.json against references/finding.schema.json and reports the mode-specific checks applied; vector bundle artifacts are required for default and deep, but optional for targeted and degraded-deep. Pass --skip-schema only when validating an out-of-tree skill install. If it fails in non-degraded deep mode, mark Execution Integrity: FAILED and stop before publishing findings.

Banner

Before doing anything else, print this exactly:

 ██████╗ █████╗ ██╗██████╗  ██████╗      █████╗ ██╗   ██╗██████╗ ██╗████████╗ ██████╗ ██████╗
██╔════╝██╔══██╗██║██╔══██╗██╔═══██╗    ██╔══██╗██║   ██║██╔══██╗██║╚══██╔══╝██╔═══██╗██╔══██╗
██║     ███████║██║██████╔╝██║   ██║    ███████║██║   ██║██║  ██║██║   ██║   ██║   ██║██████╔╝
██║     ██╔══██║██║██╔══██╗██║   ██║    ██╔══██║██║   ██║██║  ██║██║   ██║   ██║   ██║██╔══██╗
╚██████╗██║  ██║██║██║  ██║╚██████╔╝    ██║  ██║╚██████╔╝██████╔╝██║   ██║   ╚██████╔╝██║  ██║
 ╚═════╝╚═╝  ╚═╝╚═╝╚═╝  ╚═╝ ╚═════╝     ╚═╝  ╚═╝ ╚═════╝ ╚═════╝ ╚═╝   ╚═╝    ╚═════╝ ╚═╝  ╚═╝

Version Check

After printing the banner, run two parallel tool calls: (a) Read the local VERSION file from the same directory as this skill, (b) Bash curl -sf --connect-timeout 5 --max-time 10 https://raw.githubusercontent.com/keep-starknet-strange/starknet-agentic/main/skills/cairo-auditor/VERSION. If the remote fetch succeeds and the versions differ, print:

You are not using the latest version. Update via your install method (e.g. git pull or reinstall the plugin) for best security coverage.

Then continue normally. If the fetch fails (offline, timeout), skip silently.

Use this command for the remote check:

curl -sf --connect-timeout 5 --max-time 10 https://raw.githubusercontent.com/keep-starknet-strange/starknet-agentic/main/skills/cairo-auditor/VERSION

Limitations

Reporting Contract

Each finding must include:

Specialist final outputs must be structured JSON matching references/structured-findings.md; markdown finding blocks are invalid specialist output.

Evidence Priority

  1. references/vulnerability-db/
  2. references/attack-vectors/
  3. references/audit-findings/
  4. ../cairo-contract-authoring/references/legacy-full.md
  5. ../cairo-testing/references/legacy-full.md

Output Rules

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.