# defender

Blue-team release-gate analysis for smart contract deployment and upgrade readiness. Classifies repositories, checks deploy/upgrade execution paths, CI/CD trust boundaries, config drift, secrets/signer operational security, and outputs evidence-backed release verdicts.

- **Kind:** skill
- **Source:** https://github.com/quillai-network/quillshield_skills
- **Page:** https://forefy.com/skills/8cb78344-87e9-4706-8561-01a3094c6f3e
- **API (JSON + files):** https://forefy.com/api/skills/8cb78344-87e9-4706-8561-01a3094c6f3e

---

## SKILL.md

---
name: defender
description: Blue-team release-gate analysis for smart contract deployment and upgrade readiness. Classifies repositories, checks deploy/upgrade execution paths, CI/CD trust boundaries, config drift, secrets/signer operational security, and outputs evidence-backed release verdicts.
---

# Defender

A blue-team release-gate skill for smart contract systems.

Defender determines whether a repository is safe to deploy or upgrade. It focuses on **release execution risk**, not exploit discovery.

## Use when

- deploying smart contracts
- preparing upgrades
- reviewing deploy scripts
- hardening CI/CD
- rotating admin roles
- validating ownership handoff
- enforcing release hygiene

## Non-goals

Defender does NOT replace:
- full security audits
- economic analysis
- invariant discovery
- deep proxy vulnerability analysis (`proxy-upgrade-safety`)

It focuses only on **execution safety of release**.

---

## Core rule

**Evidence first.**

Only report findings from:
- contracts
- deploy scripts
- CI workflows
- dependency manifests
- configs / address books
- tests / fork scripts
- docs / runbooks

Separate:
- **Detection** → what repo proves
- **Policy** → what should be enforced

---

## Execution order (STRICT)

1. Project classification  
2. Defence pass  
3. Severity scoring  
4. Release verdict  

---

## Reference packs

Always load:
- `references/finding-catalog.md`
- `references/severity-model.md`
- `references/evidence-query-playbook.md`

Load contextually:
- classification → `project-classification.md`
- CI → `ci-supply-chain.md`
- deploy drift → `config-drift-checks.md`
- upgrade → `upgrade-readiness.md`
- signer → `signer-opsec.md`
- false confidence → `false-confidence.md`
- post-deploy → `post-deploy-validation.md`

Templates:
- `defender-report-template.md`
- checklist templates as needed

---

# Phase 1 — Project classification

### Framework
Detect:
- Foundry / Hardhat / hybrid / other

Evidence:
- `foundry.toml`, `hardhat.config.*`, scripts

### Language
- Solidity / Vyper / Cairo / mixed

### Upgradeability
- upgradeable / immutable / mixed

Evidence:
- OZ upgrade imports
- proxies
- initializer usage

### Protocol type
Infer:
- token / vault / AMM / lending / bridge / governance / NFT / staking / other

### Deployment surface
- manual / script / CI / multisig / upgrade-task

### CI surface
- GitHub Actions / GitLab / other / none

Output classification block.

---

# Phase 2 — Defence pass

## A. Build integrity

Check:
- compiler version pinned
- optimizer pinned
- evmVersion consistency
- lockfiles committed
- no conflicting configs (Foundry vs Hardhat)
- artifacts reproducible from repo
- verification metadata aligned

Escalate if:
- build settings differ from verification
- configs produce ambiguous outputs

---

## B. Dependencies, secrets, supply chain

Check:
- committed secrets
- `.env` usage for private keys
- floating versions
- unpinned git deps
- install scripts
- dependency confusion risk
- abandoned/suspicious packages
- OZ version mismatch
- unsafe sidecar tooling
- unverified binaries

### Secret policy

Plaintext `.env` private keys are discouraged.

Preferred:
- **Foundry keystore-backed accounts**

Classify:
- private key in repo → BLOCKER/HIGH
- deploy scripts using plaintext env keys → HIGH
- `.env` for non-sensitive config → acceptable

---

## C. CI/CD trust

Check:
- unpinned GitHub Actions
- secrets in untrusted workflows
- deploys from weak branches
- no approval gate
- excessive secret access
- curl/bash installs
- unsafe runners
- mixed trust zones

Escalate if CI can deploy unsafely.

---

## D. Deployment config drift

CRITICAL

Check:
- chain ID matches target
- RPC matches chain
- deployer is correct
- constructor/initializer args final
- addresses (oracle/token/admin) valid for chain
- no test/stale addresses
- decimals correct
- verifier settings pinned
- no silent fallback logic

### Foundry FFI

- default: HIGH  
- BLOCKER if affecting deploy logic/secrets

---

## E. Deploy-script safety

Check:
- chain assertions
- deployer assertions
- env validation
- correct initialization order
- idempotency assumptions clear
- no test config reuse
- address outputs reviewable
- no opaque branching
- verification steps present

Escalate if scripts can silently misdeploy.

---

## F. Upgrade readiness (if applicable)

Check:
- implementation initialized or locked
- initializer calldata reviewed
- storage diff reviewed
- proxy admin correct
- multisig/timelock path exists
- pause/rollback defined
- fork rehearsal exists

---

## G. Signer & admin opsec

Check:
- deployer is dedicated
- secure signer preferred
- admin is multisig
- roles separated:
  - deployer / upgrader / pauser / treasury
- emergency roles documented
- no hot wallet admin unless justified
- tx review process exists

---

## H. Address & role mapping

Extract:
- owner/admin
- proxy admin
- upgrader
- pauser
- treasury
- oracle
- keeper
- timelock

Flag:
- role concentration
- EOA-only control
- zero addresses
- missing transfer flow

---

## I. Fork rehearsal

Require evidence of:
- deploy scripts tested
- initializer tested
- role transfers tested
- upgrade tested
- verification tested
- smoke tests run

Absence → HIGH (mainnet)

---

## J. Post-deploy readiness

Check defined plan for:
- verification
- ownership assertions
- pause test
- oracle checks
- event expectations
- integration smoke tests
- monitoring
- deployment manifest

---

## K. Unsafe deploy ergonomics

Check:
- one-command broadcast risk
- missing confirmations
- hidden env defaults
- CREATE/CREATE2 assumptions undocumented
- nonce-sensitive flows undocumented

---

# Phase 3 — False confidence

MANDATORY

Passing does NOT imply safety:
- unit tests
- forge test
- static analysis
- lint
- typecheck

Require:
- fork rehearsal
- permission diff
- storage diff
- address diff
- event checks
- role snapshot
- post-deploy smoke tests

---

# Phase 4 — Severity

### BLOCKER
- wrong chain
- lost admin
- leaked secrets
- broken init
- broken upgrade
- unverifiable deployment

### HIGH
- unsafe CI
- missing rehearsal
- FFI misuse
- admin EOA risk
- stale config

### MEDIUM
- should fix before mainnet

### LOW
- hygiene gaps

Specify scope:
- mainnet-only / all releases / upgrades only

---

# Phase 5 — Verdict

Always output:

- `VERDICT: BLOCK DEPLOY`
- `VERDICT: PROCEED WITH RISK`
- `VERDICT: READY FOR STAGED RELEASE`

Include:
- top blockers
- required actions
- evidence reviewed

---

# Output format

```text
DEFENDER REPORT

1. Project Classification
- Framework:
- Language:
- Upgradeability:
- Protocol Type:
- Deployment Surface:
- CI Surface:

2. Release Findings

BLOCKER:
- ...

HIGH:
- ...

MEDIUM:
- ...

LOW:
- ...

3. False Confidence Warnings
- ...

4. Release Verdict

VERDICT: ...

Top blockers:
- ...

Required actions:
- ...

Evidence reviewed:
- ...

## references

```

```

## references/case-study-mapping.md

# Case Study Mapping for Release-Gate Reviews

Use incident analogies to explain why a release finding matters.

## Usage rule

- Map the repository evidence to an incident class.
- Do not claim "same root cause" unless evidence proves it.
- Keep case-study references short and educational.

## 1) Uninitialized or unsafe upgrade execution

- Defender checks:
  - upgrade rehearsal evidence
  - initializer/reinitializer sequencing
  - proxy admin ownership clarity
- Incident class:
  - upgrade initialization mistakes and unsafe admin paths can brick or seize control.
- Public references:
  - Parity multisig postmortem discussion: https://blog.openzeppelin.com/parity-wallet-hack-reloaded

## 2) Wrong address / config drift in deployment

- Defender checks:
  - chain and deployer assertions
  - address inventory validation
  - no placeholder/testnet values in production configs
- Incident class:
  - misconfigured addresses can route control or funds incorrectly.
- Public references:
  - Wintermute OP address mismatch context: https://www.paradigm.xyz/2022/08/optimism-and-wintermute

## 3) Build/toolchain integrity gaps

- Defender checks:
  - compiler/version pinning
  - lockfile consistency
  - deployment and verification settings parity
- Incident class:
  - toolchain drift can invalidate assumptions about deployed bytecode.
- Public references:
  - Vyper compiler vulnerability context: https://github.com/vyperlang/vyper/security/advisories/GHSA-5824-cm3x-3c38

## 4) CI/CD trust boundary failure

- Defender checks:
  - pinned actions
  - secret exposure boundaries
  - protected environments and approvals
- Incident class:
  - compromised automation can lead to unauthorized production actions.
- Public references:
  - GitHub Actions hardening guidance: https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions

## 5) Signer concentration and weak admin opsec

- Defender checks:
  - separation of deployer/upgrader/pauser/treasury
  - multisig/timelock usage for critical roles
- Incident class:
  - concentrated privilege amplifies impact of one compromised signer.
- Public references:
  - Audius governance incident write-up: https://blog.audius.co/article/audius-governance-takeover-post-mortem-7-23-22

## Reporting pattern

Use one line in findings when relevant:

```text
Incident analogy: This pattern aligns with documented "<incident class>" failures where release-time control/config assumptions failed.
```

## references/ci-supply-chain.md

# CI and Supply-Chain Hardening

## CI trust checks
- pinned actions refs
- branch and environment protections
- manual approvals for production deploys
- minimal secret exposure by job
- no unsafe remote-script execution
- self-hosted runner assumptions documented

## Supply-chain checks
- floating package versions
- unpinned git dependencies
- arbitrary install scripts
- conflicting dependency versions
- suspicious binaries or downloads
- transitive tooling risk in sidecars

## Escalate when
- CI can deploy to production with weak review gates
- secrets are reachable from broad workflow contexts
- release path depends on unverified remote code or binaries

## references/compensating-controls.md

# Compensating Controls Matrix

Use this matrix to avoid binary thinking when risk cannot be fully eliminated before release.

## Policy

- Never hide risk behind compensating controls.
- Keep original finding severity and note residual risk after controls.
- Do not downgrade a finding unless controls are evidenced in-repo.

## Matrix

### C-001 Production admin is an EOA

- Base severity: HIGH
- Acceptable temporary controls:
  - explicit, time-bounded risk acceptance document
  - signer is hardware-backed with strict device policy
  - emergency pause role is separate and multisig controlled
  - short migration plan to multisig with owners named
- Residual severity floor: MEDIUM
- Do not downgrade when:
  - no migration timeline
  - same EOA also controls treasury/upgrader/pauser

### C-002 Plaintext private key env flow still documented

- Base severity: HIGH
- Acceptable temporary controls:
  - plaintext flow clearly marked non-production only
  - production path defaults to keystore-backed accounts
  - CI checks fail if plaintext key variable used in production scripts
- Residual severity floor: MEDIUM
- Do not downgrade when:
  - production guide still instructs plaintext secrets
  - scripts consume `PRIVATE_KEY` for production execution

### C-003 Unpinned CI actions in non-deploy jobs

- Base severity: MEDIUM
- Acceptable temporary controls:
  - unpinned actions isolated to non-privileged jobs
  - deploy jobs fully pinned and isolated
  - branch protections and review requirements enforced
- Residual severity floor: LOW
- Do not downgrade when:
  - floating refs exist in jobs with deploy credentials or artifact signing

### C-004 Missing fork rehearsal due urgent patch window

- Base severity: HIGH
- Acceptable temporary controls:
  - two-person script walkthrough completed and signed
  - dry-run against staging with same config and signer model
  - post-deploy rollback path pre-approved and rehearsed
- Residual severity floor: MEDIUM
- Do not downgrade when:
  - upgrade modifies storage and no rehearsal evidence exists

### C-005 Role concentration in one signer

- Base severity: HIGH
- Acceptable temporary controls:
  - transaction review checklist with two human approvers
  - max daily operation limits enforced offchain
  - independent guardian role can pause
- Residual severity floor: MEDIUM
- Do not downgrade when:
  - concentrated signer can drain funds and upgrade logic unilaterally

## Reporting requirement

When compensating controls are accepted, include this field in the finding:

```text
Compensating controls accepted: Yes
Residual risk: <severity>
Expiry: <date or block height>
Owner: <team or role>
```

## references/config-drift-checks.md

# Deployment Config Drift Checks

Deployment config drift is one of the highest-severity release risks.

## Check for
- chain ID and RPC mismatch
- deployer mismatch
- constructor or initializer args differing by environment
- stale, testnet, placeholder, or cross-chain addresses
- decimal assumptions inconsistent with live integrations
- verification metadata mismatch
- unsafe default network fallback behavior

## Address classes to review
- owner/admin
- proxy admin
- pauser/guardian
- treasury
- fee recipient
- routers
- oracles
- tokens
- keepers

## Escalate when
- scripts can run against the wrong chain silently
- wrong addresses are likely to be accepted as valid
- env resolution can change release behavior unexpectedly
- deployer identity is not asserted before broadcast

## references/evidence-query-playbook.md

# Evidence Query Playbook

Use deterministic search queries before drafting findings.

## Project classification

```bash
rg -n "foundry.toml|forge script|forge test|hardhat\.config|npx hardhat|Scarb.toml" .
rg --files | rg "\.(sol|vy)$|Scarb.toml|hardhat\.config|foundry\.toml"
```

## Upgradeability signals

```bash
rg -n "Initializable|initializer|reinitializer|UUPS|Transparent|Beacon|ProxyAdmin|upgradeTo" src contracts script test
```

## Build reproducibility

```bash
rg -n "solc|optimizer|evmVersion|viaIR|remappings|ffi" foundry.toml hardhat.config.* package.json
rg --files | rg "(package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$"
```

## Secret and signer handling

```bash
rg -n "PRIVATE_KEY|MNEMONIC|DEPLOYER_PK|AWS_SECRET|GCP_" .
rg -n "--private-key|env\(" script scripts README.md docs .github/workflows
```

## CI trust boundary

```bash
rg -n "uses: .*@(main|master|v[0-9]+)$|workflow_dispatch|pull_request|secrets: inherit|environment:" .github/workflows
rg -n "permissions:" .github/workflows
```

## Config drift and address wiring

```bash
rg -n "chainid|chainId|rpc|RPC_URL|owner|admin|treasury|oracle|router|pauser|guardian|fee" script scripts config deploy
rg -n "0x0000000000000000000000000000000000000000|TODO|REPLACE_ME" .
```

## Deploy ergonomics and fail-closed checks

```bash
rg -n "startBroadcast|broadcast|upgradeProxy|deployProxy|vm\.ffi|envOr\(" script scripts
```

## Rehearsal and post-deploy evidence

```bash
rg -n "fork|anvil|smoke|post-deploy|verify|manifest|tx hash|ownership transfer" README.md docs script test
```

## Minimum evidence list per report

Always include at least one file path from each applicable area:

- deploy or upgrade script
- chain/network config
- CI workflow
- signer/role mapping source
- rehearsal or post-deploy runbook/checklist

## references/false-confidence.md

# False Confidence Warnings

Passing these does not prove deploy safety:
- unit tests
- `forge test`
- static analysis
- lint
- typecheck

## Why
These signals mostly validate code correctness or style under expected conditions. They do not validate:
- target chain correctness
- signer correctness
- role transfer correctness
- post-deploy config correctness
- upgrade execution safety
- source verification readiness

## Stronger deployment evidence
- fork rehearsal
- permission diff before and after deployment
- storage layout diff
- expected address diff
- event assertions
- role inventory snapshot
- smoke tests against deployed state

## references/finding-catalog.md

# Defender Finding Catalog

Use this catalog to keep findings consistent across repositories.

## Output contract for each finding

For each finding, include:

- Finding ID
- Severity
- Scope (`all releases`, `mainnet only`, `upgrade releases only`, or `ci hardening only`)
- Evidence
- Why this matters
- Required action before release

## D-001 Wrong-chain deployment path

- Default severity: BLOCKER
- Scope: all releases
- Signals:
  - no chain assertion before broadcast
  - RPC URL selected by implicit fallback
  - chain id in script differs from env docs
- Evidence to collect:
  - deploy script assertions
  - `foundry.toml` / `hardhat.config.*`
  - CI deploy workflow inputs
- Escalate when:
  - deploy can silently run on an unintended chain
- False-positive guard:
  - explicit chain assertion and failing guard are present in all deploy scripts
- Required action:
  - add hard chain/deployer assertions and fail closed defaults

## D-002 Stale or cross-network address wiring

- Default severity: HIGH
- Scope: mainnet only
- Signals:
  - testnet addresses in production config
  - placeholder or zero addresses for critical roles
- Evidence to collect:
  - network config files
  - deployment manifests
  - script constants and env mapping
- Escalate when:
  - owner/admin/oracle/router/treasury addresses are wrong for target chain
- False-positive guard:
  - address book includes chain-qualified, reviewed values and verification script checks
- Required action:
  - reconcile config against chain-specific address inventory and assert at runtime

## D-003 Plaintext private key handling in release path

- Default severity: HIGH
- Scope: all releases
- Signals:
  - docs require `PRIVATE_KEY=` in `.env`
  - production deploy scripts consume raw private keys directly
- Evidence to collect:
  - docs, scripts, workflow env declarations
- Escalate when:
  - plaintext secret handling is required for production deploy
- False-positive guard:
  - keystore-backed signer path is default and documented; plaintext path disabled for production
- Required action:
  - migrate to keystore-backed accounts and remove plaintext key instructions

## D-004 Unpinned CI action references

- Default severity: MEDIUM
- Scope: ci hardening only
- Signals:
  - `uses: action@main` or broad tags without SHA pinning
- Evidence to collect:
  - `.github/workflows/*.yml`
- Escalate when:
  - release/deploy jobs depend on floating refs
- False-positive guard:
  - actions are pinned to immutable SHAs in release path
- Required action:
  - pin actions and define update cadence

## D-005 Secrets exposed to untrusted workflow triggers

- Default severity: HIGH
- Scope: all releases
- Signals:
  - deploy job secrets reachable from PR events/forks
  - broad `workflow_dispatch` with weak environment protection
- Evidence to collect:
  - workflow trigger and permission blocks
  - environment protection settings references
- Escalate when:
  - production deploy secrets can be consumed by untrusted contexts
- False-positive guard:
  - production secrets only available on protected branches/environments with approvals
- Required action:
  - split trust zones and narrow secret scope

## D-006 Reproducibility mismatch between build and verification

- Default severity: BLOCKER
- Scope: all releases
- Signals:
  - compiler settings differ across deploy and verify steps
  - lockfile absent or inconsistent
- Evidence to collect:
  - build and verify scripts
  - toolchain config files
- Escalate when:
  - deployed artifacts cannot be reproduced from repository state
- False-positive guard:
  - deterministic build recipe and matching verifier settings are documented and tested
- Required action:
  - pin toolchain and unify deploy/verify config

## D-007 Unsafe deploy script ergonomics

- Default severity: MEDIUM
- Scope: all releases
- Signals:
  - one-command broadcast without preflight checks
  - hidden defaults that choose network/signer
- Evidence to collect:
  - script entry points and argument parsing
- Escalate when:
  - scripts can execute destructive operations with minimal confirmation
- False-positive guard:
  - explicit preflight checks and dry-run mode are mandatory
- Required action:
  - add fail-fast preflight and explicit runtime prompts/assertions

## D-008 Foundry FFI in deploy-critical flow

- Default severity: HIGH
- Scope: all releases
- Signals:
  - `ffi = true` combined with deploy/upgrade scripts
  - external command output feeds addresses or calldata
- Evidence to collect:
  - `foundry.toml`
  - scripts using `vm.ffi`
- Escalate when:
  - FFI controls target addresses, secret material, or upgrade calldata
- False-positive guard:
  - FFI isolated to non-critical metadata generation and reviewed outputs
- Required action:
  - remove FFI from critical path or harden and pin execution assumptions

## D-009 Missing upgrade rehearsal evidence

- Default severity: HIGH
- Scope: upgrade releases only
- Signals:
  - no fork/staging upgrade runbook proof
  - no post-upgrade smoke plan
- Evidence to collect:
  - rehearsal scripts and logs
  - upgrade checklist completion evidence
- Escalate when:
  - storage-changing upgrade has not been rehearsed
- False-positive guard:
  - reproducible fork rehearsal exists with recorded tx sequence
- Required action:
  - run fork rehearsal and document results before release

## D-010 Initializer execution ambiguity in upgrade path

- Default severity: BLOCKER
- Scope: upgrade releases only
- Signals:
  - missing or unclear initializer/reinitializer calldata
  - initializer order not documented
- Evidence to collect:
  - upgrade scripts
  - initializer docs/tests
- Escalate when:
  - upgrade can leave contracts partially configured
- False-positive guard:
  - initialization sequence is explicit and verified on fork
- Required action:
  - define and test exact initializer sequence

## D-011 Proxy admin ownership unclear

- Default severity: HIGH
- Scope: upgrade releases only
- Signals:
  - proxy admin owner not documented
  - admin transfer path missing from runbook
- Evidence to collect:
  - ownership scripts
  - role mapping docs
- Escalate when:
  - no verified authority can execute safe upgrade/rollback
- False-positive guard:
  - multisig/timelock ownership and execution flow are explicitly verified
- Required action:
  - map and validate proxy admin ownership pre-release

## D-012 Signer concentration across critical roles

- Default severity: HIGH
- Scope: mainnet only
- Signals:
  - deployer/admin/pauser/treasury collapsed into one EOA
- Evidence to collect:
  - role mapping output
  - config and script role assignment
- Escalate when:
  - single signer compromise can seize full control
- False-positive guard:
  - documented risk acceptance with compensating controls and limits
- Required action:
  - separate duties and move critical roles to multisig/timelock

## D-013 No post-deploy validation plan

- Default severity: MEDIUM
- Scope: mainnet only
- Signals:
  - no checklist for verification, role assertions, smoke tests, monitoring handoff
- Evidence to collect:
  - runbooks and release templates
- Escalate when:
  - team has no immediate validation sequence after deployment
- False-positive guard:
  - concrete post-deploy checklist with owners and expected outputs
- Required action:
  - define and rehearse immediate post-deploy validation

## D-014 Ambiguous network/deployer fallback behavior

- Default severity: HIGH
- Scope: all releases
- Signals:
  - default network selected when env var absent
  - signer selected from first account implicitly
- Evidence to collect:
  - script env resolution logic
  - hardhat/foundry default network config
- Escalate when:
  - missing env values alter deployment target silently
- False-positive guard:
  - missing required inputs hard-fail execution
- Required action:
  - enforce explicit network and signer parameters

## D-015 Deploy CI without approval gates

- Default severity: HIGH
- Scope: all releases
- Signals:
  - deploy jobs run from push to broad branches
  - no environment reviewers or approval step
- Evidence to collect:
  - workflow trigger definitions
  - environment config references in docs
- Escalate when:
  - production deploy can execute without human gate
- False-positive guard:
  - protected environment with explicit approval policy
- Required action:
  - require controlled promotion and approvals for production

## D-016 Missing release evidence archive

- Default severity: LOW
- Scope: all releases
- Signals:
  - no deployment manifest, tx hash list, or final role snapshot stored
- Evidence to collect:
  - docs and release artifacts directory
- Escalate when:
  - team cannot reconstruct what was deployed and by whom
- False-positive guard:
  - complete archive exists and is linked in release notes
- Required action:
  - archive release evidence as part of completion criteria

## references/good-vs-bad-snippets.md

# Good vs Bad Snippets
Use these snippets as pattern anchors while reviewing deploy safety.

## 1) Chain assertion in Foundry deploy scripts

Bad:
```solidity
function run() external {
    vm.startBroadcast();
    new Core();
    vm.stopBroadcast();
}
```

Good:
```solidity
function run() external {
    uint256 expectedChainId = 1;
    require(block.chainid == expectedChainId, "wrong chain");

    address deployer = vm.addr(vm.envUint("DEPLOYER_PK"));
    require(deployer == 0x1234...ABCD, "wrong deployer");

    vm.startBroadcast();
    new Core();
    vm.stopBroadcast();
}
```

## 2) Explicit required environment values

Bad:
```solidity
string memory rpc = vm.envOr("RPC_URL", string("https://mainnet.example"));
```

Good:
```solidity
string memory rpc = vm.envString("RPC_URL");
require(bytes(rpc).length > 0, "missing RPC_URL");
```

## 3) Private key handling guidance

Bad docs pattern:
```bash
# env
PRIVATE_KEY=0xabc...
```

Better docs pattern:
```bash
# Use keystore-backed signing
cast wallet import deployer --interactive
forge script script/Deploy.s.sol:Deploy --account deployer --sender <deployer_address> --broadcast
```

## 4) GitHub Actions pinning

Bad:
```yaml
- uses: actions/checkout@v4
- uses: foundry-rs/foundry-toolchain@v1
```

Better:
```yaml
- uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608
- uses: foundry-rs/foundry-toolchain@<pinned-commit-sha>
```

## 5) Workflow trust boundary split

Bad:
```yaml
on: [pull_request]
jobs:
  deploy:
    secrets: inherit
```

Better:
```yaml
on:
  push:
    branches: ["main"]
workflow_dispatch:

jobs:
  test:
    if: github.event_name == 'pull_request'
  deploy:
    if: github.ref == 'refs/heads/main'
    environment: production
    permissions:
      contents: read
      id-token: write
```

## 6) Hardhat network safety checks

Bad:
```ts
const [deployer] = await ethers.getSigners();
await hre.run("deploy");
```

Good:
```ts
const [deployer] = await ethers.getSigners();
const network = await ethers.provider.getNetwork();
if (network.chainId !== 1n) throw new Error("wrong chain");
if (deployer.address.toLowerCase() !== EXPECTED_DEPLOYER.toLowerCase()) {
  throw new Error("wrong deployer");
}
await hre.run("deploy");
```

## 7) Upgrade script address assertions

Bad:
```ts
await upgrades.upgradeProxy(process.env.PROXY!, ImplFactory);
```

Good:
```ts
const proxy = process.env.PROXY;
if (!proxy || proxy.toLowerCase() !== EXPECTED_PROXY.toLowerCase()) {
  throw new Error("proxy mismatch");
}
await upgrades.upgradeProxy(proxy, ImplFactory);
```

## 8) Role transfer runbook evidence

Bad:
```text
Transfer ownership later.
```

Good:
```text
1. Deploy implementation and verify bytecode.
2. Transfer proxy admin to multisig 0x....
3. Confirm onchain owner(), admin(), upgrader().
4. Record tx hashes in release manifest.
```

## 9) CI deploy gates

Bad:
```yaml
on:
  push:
    branches: ['*']
```

Good:
```yaml
on:
  push:
    branches: ['main']
concurrency: production-deploy
jobs:
  deploy:
    environment: production
    # Require environment reviewers in repository settings
```

## 10) Dangerous FFI in deploy path

Bad:
```solidity
bytes memory out = vm.ffi(["bash", "-lc", "python scripts/resolve.py"]);
address treasury = abi.decode(out, (address));
```

Better:
```solidity
address treasury = vm.envAddress("TREASURY");
require(treasury != address(0), "invalid treasury");
```

## references/post-deploy-validation.md

# Post-Deploy Validation

Pre-deploy readiness should include a defined immediate post-deploy plan.

## Minimum checks
- source and bytecode verification
- ownership and admin assertions
- pause path validation where safe and appropriate
- oracle heartbeat or dependency sanity checks
- expected event emissions
- smoke-test integrations
- monitoring and alerting handoff
- deployment manifest archival

## Why this belongs in Defender
A team that has not defined its immediate post-deploy validation steps is not fully ready to release.

## references/project-classification.md

# Project Classification Guide

Defender begins by classifying the repository.

## Framework
Indicators:
- Foundry: `foundry.toml`, `forge script`, `forge test`, `forge-std`
- Hardhat: `hardhat.config.*`, `npx hardhat`, task files
- Hybrid: both Foundry and Hardhat signals present

## Language
Indicators:
- Solidity: `.sol`
- Vyper: `.vy`
- Cairo: `Scarb.toml`, Starknet layout, Cairo sources
- Mixed: more than one production language present

## Upgradeability
Indicators:
- OZ upgradeable imports
- initializer modifiers/functions
- proxy admin scripts
- deployment tasks mentioning UUPS, Transparent, Beacon, Diamond

## Protocol type
Best-effort classification from contract semantics and naming:
- token
- vault
- AMM
- lending
- bridge
- governance
- NFT
- staking
- other

## Deployment surface
Look for:
- manual scripts
- CI-triggered deploys
- multisig execution plans
- upgrade-only execution tasks

## CI surface
Look for:
- `.github/workflows/*.yml`
- `.gitlab-ci.yml`
- alternative pipeline directories

## references/severity-model.md

# Defender Severity Model

## BLOCKER
A release-blocking issue that can directly cause:
- wrong-chain deployment
- wrong-address configuration
- leaked secrets
- lost admin control
- broken initialization
- broken upgrade execution
- unverifiable release artifacts

Typical examples:
- production RPC/chain mismatch
- stale or testnet admin/oracle addresses in mainnet config
- plaintext production private key handling wired into deploy flow
- implementation left initializable
- missing required initializer sequence

## HIGH
A material increase in compromise or release-failure risk.

Typical examples:
- admin remains a single EOA for production-critical system
- upgrade path not rehearsed
- CI can deploy from weak triggers or weak trust boundaries
- FFI in deploy path affects release decisions
- no fork rehearsal for mainnet release

## MEDIUM
Should be fixed before mainnet, but may be tolerable for testnet or staging with explicit acknowledgement.

Typical examples:
- weakly documented verification flow
- partial signer role mapping
- incomplete but not absent post-deploy checklist

## LOW
Hygiene, documentation, or observability gaps that reduce assurance.

Typical examples:
- no explicit deployment manifest template
- weakly documented smoke tests
- inconsistent naming or release notes

## Environment-aware guidance

When possible, note whether the issue blocks:
- all releases
- mainnet only
- upgrade releases only
- CI hardening only

## references/signer-opsec.md

# Signer and Admin Operational Security

Defender is blue-team useful when it maps the human and signer control plane.

## Preferred posture
- dedicated deployer
- secure signer path
- production admin via multisig
- role separation across deployer, upgrader, pauser, treasury
- emergency authorities documented

## Risk indicators
- personal wallet used as deployer and long-term admin
- production admin remains EOA
- hot wallet required for emergency response
- role concentration in one signer
- no documented transaction review before signing

## Secret handling
Do not recommend plaintext `.env` storage for private keys.
Prefer Foundry keystore-backed signer flows.

## references/upgrade-readiness.md

# Upgrade Release Readiness

Defender does not replace deep upgrade vulnerability analysis. It evaluates whether the upgrade can be executed safely.

## Review points
- implementation initialized or intentionally uninitializable
- initializer calldata reviewed
- storage layout diff reviewed
- proxy admin ownership confirmed
- timelock or multisig path confirmed
- rollback authority known
- pause authority known
- fork rehearsal completed

## Typical blockers
- implementation left open to initialization
- proxy admin ownership unclear
- storage layout diff absent before upgrade
- initializer sequence not rehearsed
- upgrade signer path undocumented

## templates

```

```

## templates/defender-report-block-deploy-example.md

# DEFENDER REPORT (Example: BLOCK DEPLOY)

## 1. Project Classification

- Framework: Foundry
- Language: Solidity
- Upgradeability: upgradeable (UUPS)
- Protocol Type: vault
- Deployment Surface: script-driven (`script/Deploy.s.sol`) and CI-triggered (`.github/workflows/release.yml`)
- CI Surface: GitHub Actions

## 2. Release Findings

### BLOCKER

- D-001 Wrong-chain deployment path
  - Evidence: `script/Deploy.s.sol` broadcasts without `block.chainid` assertion and uses `vm.envOr("RPC_URL", ...)` fallback.
  - Scope: all releases
  - Required action: add chain/deployer hard assertions and remove fallback network defaults.

- D-006 Reproducibility mismatch between deploy and verify
  - Evidence: `foundry.toml` uses one compiler profile while `script/Verify.s.sol` passes different optimizer settings.
  - Scope: all releases
  - Required action: unify compiler and optimizer settings for deploy and verification.

### HIGH

- D-003 Plaintext private key handling in release path
  - Evidence: `README.md` instructs `PRIVATE_KEY=` for production broadcast.
  - Scope: all releases
  - Required action: switch docs and scripts to keystore-backed signing.

- D-005 Secrets exposed to untrusted triggers
  - Evidence: `.github/workflows/release.yml` contains deploy job with `secrets: inherit` and `pull_request` trigger.
  - Scope: all releases
  - Required action: isolate deploy job to protected branch/environment with approval gates.

### MEDIUM

- D-013 No post-deploy validation plan
  - Evidence: no runbook for role assertions, smoke tests, or verification archive.
  - Scope: mainnet only
  - Required action: add and rehearse post-deploy checklist.

### LOW

- D-016 Missing release evidence archive
  - Evidence: no manifest template for tx hashes and final role map.
  - Scope: all releases
  - Required action: require release artifact archive.

## 3. False Confidence Warnings

- Passing `forge test` does not prove deploy target correctness.
- Lint and typecheck do not validate signer role separation or CI trust boundaries.

## 4. Release Verdict

**VERDICT:** BLOCK DEPLOY

### Top blockers

- Wrong-chain execution can occur silently.
- Deployed artifacts are not reproducible from repository config.

### Required actions before release

- Add fail-closed chain/deployer assertions.
- Align deploy and verification compiler configuration.
- Remove plaintext production secret handling.
- Restrict CI deploy permissions and triggers.

### Evidence reviewed

- `script/Deploy.s.sol`
- `script/Verify.s.sol`
- `foundry.toml`
- `.github/workflows/release.yml`
- `README.md`

## templates/defender-report-proceed-with-risk-example.md

# DEFENDER REPORT (Example: PROCEED WITH RISK)

## 1. Project Classification

- Framework: Hardhat
- Language: Solidity
- Upgradeability: immutable
- Protocol Type: token
- Deployment Surface: script-driven manual deploy
- CI Surface: GitHub Actions

## 2. Release Findings

### BLOCKER

- None identified.

### HIGH

- D-012 Signer concentration across critical roles
  - Evidence: deployer, owner, and treasury are same EOA in `config/mainnet.json`.
  - Scope: mainnet only
  - Required action: migrate owner/treasury to multisig before broad TVL onboarding.

### MEDIUM

- D-004 Unpinned CI action references
  - Evidence: `.github/workflows/ci.yml` uses floating action refs for non-deploy jobs.
  - Scope: ci hardening only
  - Required action: pin all workflow actions to immutable SHAs.

- D-013 No complete post-deploy validation owner map
  - Evidence: smoke test list exists, but no owner-by-owner execution responsibility.
  - Scope: mainnet only
  - Required action: assign accountable owners per post-deploy check.

### LOW

- D-016 Missing standardized release archive naming
  - Evidence: manifests exist but naming is inconsistent.
  - Scope: all releases
  - Required action: enforce manifest naming convention.

## 3. False Confidence Warnings

- Unit tests passing does not validate operational signer safety.
- Static analysis does not prove deployment process control.

## 4. Release Verdict

**VERDICT:** PROCEED WITH RISK

### Top blockers

- None.

### Required actions before release

- Capture formal risk acceptance for EOA role concentration.
- Complete multisig migration timeline with owners and dates.
- Pin remaining action references.

### Evidence reviewed

- `config/mainnet.json`
- `.github/workflows/ci.yml`
- `docs/release-checklist.md`
- `scripts/deploy.ts`

## templates/defender-report-ready-for-staged-release-example.md

# DEFENDER REPORT (Example: READY FOR STAGED RELEASE)

## 1. Project Classification

- Framework: Foundry + Hardhat (hybrid)
- Language: Solidity
- Upgradeability: mixed (immutable modules + upgradeable governance module)
- Protocol Type: governance
- Deployment Surface: script-driven with protected CI promotion
- CI Surface: GitHub Actions

## 2. Release Findings

### BLOCKER

- None identified.

### HIGH

- None identified.

### MEDIUM

- D-004 Unpinned CI action refs outside deploy path
  - Evidence: one docs-only workflow uses floating ref.
  - Scope: ci hardening only
  - Required action: pin non-deploy workflow for consistency.

### LOW

- D-016 Release archive checklist could include dashboard links
  - Evidence: manifest includes tx hashes and role snapshot; monitoring links missing.
  - Scope: all releases
  - Required action: add monitoring URL field to manifest template.

## 3. False Confidence Warnings

- Test and lint outcomes are supporting signals only; readiness is based on deployment evidence.
- Release confidence is anchored to rehearsed execution and role verification data.

## 4. Release Verdict

**VERDICT:** READY FOR STAGED RELEASE

### Top blockers

- None.

### Required actions before release

- Pin the remaining docs workflow action ref.
- Add monitoring links to release archive template.

### Evidence reviewed

- `script/Deploy.s.sol`
- `script/UpgradeGovernance.s.sol`
- `docs/pre-mainnet.md`
- `.github/workflows/release.yml`
- `artifacts/releases/2026-03-15-mainnet-rc1.json`

## templates/defender-report-template.md

# DEFENDER REPORT

## 1. Project Classification
- Framework:
- Language:
- Upgradeability:
- Protocol Type:
- Deployment Surface:
- CI Surface:

## 2. Release Findings

### BLOCKER
- None identified / list findings

### HIGH
- None identified / list findings

### MEDIUM
- None identified / list findings

### LOW
- None identified / list findings

## 3. False Confidence Warnings
- Passing unit tests does not prove deploy safety because:
- Passing `forge test` does not prove config correctness because:
- Passing lint or typecheck does not prove signer, chain, or role readiness because:

## 4. Release Verdict
**VERDICT:** BLOCK DEPLOY / PROCEED WITH RISK / READY FOR STAGED RELEASE

### Top blockers
- 

### Required actions before release
- 

### Evidence reviewed
-

## templates/incident-response-checklist.md

# Incident Readiness Checklist

- [ ] Emergency roles documented
- [ ] Pause authority known
- [ ] Treasury control path known
- [ ] Upgrade rollback path known
- [ ] Contact and escalation path documented
- [ ] Monitoring ownership documented
- [ ] Deployment manifests archived
- [ ] Public communication owner identified

## templates/post-deploy-smoke-tests.md

# Post-Deploy Smoke Tests

- [ ] Verify source and metadata on explorer
- [ ] Assert owner/admin addresses
- [ ] Assert proxy admin and implementation linkage
- [ ] Assert pauser/guardian role assignments
- [ ] Assert treasury and fee recipient addresses
- [ ] Check oracle/dependency liveness assumptions
- [ ] Confirm expected deployment events emitted
- [ ] Run critical read-path integration checks
- [ ] Archive deployment manifest and tx hashes

## templates/pre-mainnet-checklist.md

# Pre-Mainnet Checklist

## Build and artifacts
- [ ] Compiler version pinned
- [ ] Optimizer runs pinned
- [ ] Lockfiles committed
- [ ] Verification metadata pinned
- [ ] Reproducible build path documented

## Deployment config
- [ ] Chain ID validated
- [ ] RPC validated
- [ ] Deployer address validated
- [ ] Constructor/initializer args reviewed
- [ ] No test/stale addresses remain
- [ ] Decimal assumptions checked

## Signers and roles
- [ ] Deployer is dedicated
- [ ] Admin is multisig or risk explicitly accepted
- [ ] Pauser/guardian defined
- [ ] Treasury role defined
- [ ] Upgrade role defined
- [ ] Role separation reviewed

## CI/CD
- [ ] Production deploy requires protected branch or tag
- [ ] Production deploy requires approval gate
- [ ] Actions refs pinned
- [ ] Secrets scope minimized

## Rehearsal
- [ ] Fork deployment completed
- [ ] Initializer rehearsal completed
- [ ] Ownership transfer rehearsal completed
- [ ] Verification rehearsal completed
- [ ] Smoke tests passed

## Post-deploy
- [ ] Verification plan ready
- [ ] Ownership assertions ready
- [ ] Monitoring handoff ready
- [ ] Manifest archival ready

## templates/signer-role-mapping.md

# Signer and Role Mapping

- Deployer:
- Owner/Admin:
- Proxy Admin:
- Upgrader:
- Pauser/Guardian:
- Treasury:
- Fee Recipient:
- Oracle/Updater:
- Keeper:
- Timelock:

## Observations
- Role concentration:
- EOA-only critical control:
- Missing separation of duties:
- Placeholder or zero addresses:

## templates/upgrade-checklist.md

# Upgrade Release Checklist

- [ ] Implementation intentionally locked or initialized
- [ ] Initializer or reinitializer calldata reviewed
- [ ] Storage layout diff reviewed
- [ ] Proxy admin owner confirmed
- [ ] Timelock/multisig execution path confirmed
- [ ] Pause and rollback authority confirmed
- [ ] Fork rehearsal of upgrade completed
- [ ] Post-upgrade smoke tests defined
- [ ] Source verification plan ready

