[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72TQY0MEKVFG4235DBMQAPW":3,"skill-same:01M72TQY0MEKVFG4235DBMQAPW":103},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":60,"commitSha":61,"skillDirectory":62,"forksCount":14,"repositoryHtmlUrl":63,"repositoryHomepageUrl":63,"ownerHtmlUrl":64,"ownerBlogUrl":6,"ownerDescription":65,"updatedAt":66,"install":67,"resources":80},"01M72TQY0MEKVFG4235DBMQAPW","rust-code-audit",null,"Use when auditing Rust code. Finds security and perf bugs.","iberi22\u002Fskills","iberi22","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F10615454?v=4","01M72SQ2NXAA3GW0FSH053A5ES","Brahyan Belalcazar","01M72SQ2PYCH0SSA1K61NGEHDV",0,"MIT","https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Frust-code-audit\u002FSKILL.md",[],[],"2026-11-10 22:39:42",false,"---\nname: rust-code-audit\ndescription: \"Use when auditing Rust code. Finds security and perf bugs.\"\nversion: 1.1.0\nauthor: Hermes Agent\nlicense: MIT\nplatforms: [linux, macos]\nmetadata:\n  hermes:\n    tags: [audit, security, performance, code-review, rust]\n    related_skills: [requesting-code-review, codebase-inspection, systematic-debugging, github-issues, rust-code-quality-audit]\n    references:\n      - url: https:\u002F\u002Frustsec.org\u002F\n        title: \"RustSec — Security Advisory Database\"\n        year: 2026\n      - url: https:\u002F\u002Fgithub.com\u002Frustsec\u002Frustsec\n        title: \"cargo-audit — Security audit for dependencies\"\n        year: 2026\n      - url: https:\u002F\u002Fdocs.rs\u002Fsubtle\u002Flatest\u002Fsubtle\u002F\n        title: \"subtle crate — Constant-time comparisons\"\n        year: 2026\n      - url: https:\u002F\u002Ftokio.rs\u002Ftokio\u002Ftutorial\u002Fshared-state\n        title: \"Tokio Shared State Patterns\"\n        year: 2026\n      - url: https:\u002F\u002Fcheats.rs\u002F#unsafe\n        title: \"Rust Cheatsheet — Unsafe Code Patterns\"\n        year: 2026\n---\n\n# Rust Code Security & Performance Audit\n\nFull-scale audit methodology for Rust codebases. Combines web research grounding with systematic pattern-based code search to find security vulnerabilities, performance anti-patterns, and supply-chain risks.\n\n## When to Use\n\n- User requests \"security audit\", \"performance audit\", or \"code review\" of a Rust project\n- Before a release or merge of a large feature branch (50+ files, 5000+ LOC changed)\n- After merging external contributions or autonomous-agent PRs\n- When evaluating a new dependency or crate for adoption\n- As part of a recurring audit cycle (e.g., AUDIT-5-*, AUDIT-6-* series)\n- **When auditing a specific commit** — use Commit-Scoped Audit (Phase 0) instead of broad pattern search\n\n**Skip for:** single-file changes, documentation-only PRs, pre-commit review (use `requesting-code-review` instead), or quick-fix sessions.\n\n## Skill vs Related Skills\n\n| Skill | Scope | Trigger |\n|-------|-------|---------|\n| **rust-code-audit** | Full codebase audit — security + performance + supply chain | \"audit\", \"security review\", \"performance review\" |\n| `requesting-code-review` | Pre-commit diff scanning | \"commit\", \"verify\", \"ship\" |\n| `codebase-inspection` | LOC\u002Fstructure\u002FCI\u002Fdocs analysis | \"how big\", \"what's in this repo\" |\n| `systematic-debugging` | Root cause debugging of specific bugs | bug reports, test failures |\n| `github-code-review` | Reviewing other people's PRs with inline comments | \"review PR #X\" |\n| `rust-code-quality-audit` | Architecture + code quality (separate from security) | \"quality audit\", \"architecture review\" |\n\n## Phase 0 — Commit-Scoped Audit (when auditing a specific commit)\n\nWhen the audit targets a specific commit (not the whole codebase), start with `git diff` analysis to understand the scope **before** running broad pattern searches:\n\n```bash\n# 1. Understand the scope\ngit log --oneline -5              # Recent history, context\ngit diff --stat HEAD~1..HEAD      # Files changed, lines added\u002Fdeleted\n\n# 2. Diff per file for key changes\ngit diff HEAD~1..HEAD -- \u003Cfile>   # Detail per affected file\n\n# 3. List all parent commits in the wave\ngit log --oneline HEAD~N..HEAD    # All commits in this wave\u002Frelease\n```\n\n**Identify the change categories** from the diff stat before diving into patterns:\n\n| Category | What to check | Security? | Performance? |\n|----------|---------------|-----------|--------------|\n| **Type widening** (u32→u64, f32→f64) | Verify no truncation, JSON compat, operation-order bugs | ✅ Safe in Rust (widening is always lossless) | Usually neutral |\n| **Dead code removal** | Verify no needed code accidentally removed | ✅ Positive (reduced attack surface) | Marginal compile improvement |\n| **Struct consolidation** | Verify DTOs moved to shared crate, no stale imports | ✅ Positive (single source of truth) | Net LOC reduction |\n| **Dependency version bumps** | Verify semver compatibility, workspace consistency | ⚠️ Check for API breakage | Usually positive |\n| **Docs updates** | Verify workspace structure accuracy, no stale claims | Usually PASS | No impact |\n| **CLI command changes** | Verify enum match, help text accuracy | Low | Low |\n\nThen run targeted `git diff` on the specific files identified, rather than broad `search_files` across the entire codebase.\n\n## Phase 1 — Web Research Grounding (3 parallel queries)\n\nBefore examining code, establish current best practices. Run 3 web searches in parallel:\n\n```bash\n# 1. Security audit best practices\n# e.g. \"Rust security audit checklist 2026 unsafe code production\"\n\n# 2. Async performance patterns\n# e.g. \"Rust async performance optimization 2026 tokio spawn_blocking\"\n\n# 3. Supply chain \u002F dependency security\n# e.g. \"Rust supply chain security cargo audit 2026 dependency management\"\n```\n\nCapture key findings as a markdown reference. Include:\n- Current recommended tools (cargo-deny, cargo-vet, cargo-audit, Cargo Scan)\n- Known anti-patterns\n- Reference URLs\n\n## Phase 2 — Pattern-Based Code Search\n\nSearch for all security and performance patterns across the codebase. Run these searches in parallel using `search_files`:\n\n### Security Patterns\n\n| Pattern | What It Finds | Risk |\n|---------|---------------|------|\n| `unsafe` | Unsafe blocks — need audit for correctness | Memory safety violations |\n| `.unwrap()` | Panic-on-error patterns in production code | Crashes under failure |\n| `.expect(` | Assertive unwraps — less risky if descriptive | Lower risk |\n| `thread::sleep` | Blocking sleep | Worker thread starvation |\n| `std::sync::Mutex` | Sync mutex in async runtime | Contention, deadlock if held across .await |\n| `block_on` | Blocking the current thread on async code | Nested runtime, deadlock |\n| `api.?key\\|API_KEY\\|secret\\|password` | Hardcoded secrets | Credential leak |\n| `include_bytes!` | Embedded binary blobs | Supply chain risk |\n| `let _ =` | Swallowed `Result`\u002F`Error` values | Silent data loss, unlogged failures |\n| `format!.*SELECT\\|.*INSERT\\|.*DELETE\\|.*UPDATE` | SQL with format!() for identifiers | SQL injection if table names become dynamic |\n| `env::var.*path\\|env::var.*dir\\|env::var.*PATH` | Env var used to construct file paths | Path traversal if env is controllable |\n| `private_key.*String` | Private key as plain `String` in structs | Secret exposure via Debug\u002Flogs\u002Fserialization |\n| **Type narrowing\u002Fwidening** | `as u32`, `as u16`, `as i32` casts — truncation risk | Data loss |\n| **`From\u003Cu32> for u64` \u002F `Into\u003Cu64>`** | Widening: SAFE by default (From impl guaranteed in std) | ✅ Zero risk |\n| **`as u64` cast** | Widening via `as`: SAFE (no truncation) but check for op-order bugs | ✅ Safe if arithmetic happens AFTER widening |\n| **`as u32` cast from u64** | **Narrowing**: TRUNCATES silently — CRITICAL | Data loss \u002F overflow |\n| **`#[serde(untagged)]` enum changes** | Adding\u002Fremoving variants without compat checks | Deserialization failure |\n\n### Performance Patterns\n\n| Pattern | What It Finds | Risk |\n|---------|---------------|------|\n| `spawn_blocking` | Proper async offloading | ✅ Positive — count usage |\n| `thread::sleep` | Blocking in async | Worker thread starvation |\n| `std::sync::Mutex` (in async) | Non-yielding locks | Throughput degradation |\n| `.clone()` inside hot paths | Unnecessary allocations | Memory churn |\n| `DashMap` | Concurrent map | Usually fine, check for iter() across await |\n| `for m in &db.metrics` | Linear scans | O(n) on every operation |\n\n### Search Template (Rust projects)\n\n```bash\n# Run all in parallel (concurrent tool calls in Hermes)\nsearch_files(pattern=\"unsafe\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Security\nsearch_files(pattern=\"\\\\.unwrap\\\\(\\\\)\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Security\nsearch_files(pattern=\"\\\\.expect\\\\(\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Security\nsearch_files(pattern=\"thread::sleep\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Perf\u002FSec\nsearch_files(pattern=\"std::sync::Mutex\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Perf\u002FSec\nsearch_files(pattern=\"spawn_blocking\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Perf (positive)\nsearch_files(pattern=\"block_on\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Security\nsearch_files(pattern=\"api.?key|API_KEY|secret|password\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Security\nsearch_files(pattern=\"let _ =\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Swallowed errors\nsearch_files(pattern=\"format!.*SELECT|format!.*INSERT|format!.*DELETE|format!.*UPDATE\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # SQL injection\nsearch_files(pattern=\"env::var.*path|env::var.*dir|env::var.*PATH\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Env path injection\nsearch_files(pattern=\"private_key.*String|secret.*String|api_key.*String\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Secret as String\n```\n\n## Phase 3 — Deep Reading of Candidate Files\n\nFor files matching critical patterns, read the full context around matches:\n\n1. **unsafe blocks** — verify safety invariants, check for soundness holes\n2. **unwrap\u002Fexpect in production** — distinguish test code from production code paths\n3. **thread::sleep** — identify whether it's inside an `async fn` or tokio task\n4. **std::sync::Mutex** — check if locks are held across `.await` points\n5. **Hardcoded secrets** — confirm whether they're test placeholders or real credentials\n\n### Classification Rules\n\n- **Test code** (`#[cfg(test)]`, `tests\u002F` directory) — lower severity, note it\n- **Production code** — full severity\n- **Non-async functions** — `thread::sleep` is acceptable (not an async violation)\n- **Async functions \u002F tokio::spawn** — `thread::sleep` is critical\n\n## Phase 4 — Finding Documentation\n\nFor each confirmed finding, document:\n\n```\n### ID [S\u002FP]-[NN] [SEVERITY] [Brief Title]\n- **File:** path\u002Fto\u002Ffile.rs:line_number\n- **Code:** relevant code snippet (5-10 lines)\n- **Risk:** what could go wrong in production\n- **Fix:** specific change needed\n```\n\n### Severity Levels\n\n| Level | Meaning | Action |\n|-------|---------|--------|\n| 🔴 **CRITICAL** | Blocks worker thread, crashes on failure path, or exposes secrets | Fix immediately before merge |\n| 🟡 **HIGH** | Risk of deadlock\u002Fpanic under specific conditions, or design flaw | Fix before next release |\n| 🟢 **MEDIUM** | Suboptimal pattern, no immediate danger but tech debt grows | Schedule for next sprint |\n| ⚪ **LOW** | Minor concern, acceptable at current scale | Note for future refactoring |\n\n### Strong Points\n\nAlso document what the codebase does **right** — reinforces good practices:\n\n```\nSecurity:\n- ✅ API keys from environment variables\n- ✅ No SQL injection (parameterized queries)\n- ✅ spawn_blocking properly used on all SQLite operations\n\nPerformance:\n- ✅ virtual_fs.rs: correct spawn_blocking on all 7 operations\n- ✅ health.rs: clean async patterns, no thread::sleep\n```\n\n## Phase 5 — Issue\u002FReport Creation\n\nCreate the deliverable as a structured GitHub issue or report:\n\n```bash\n# Title format\n[AUDIT-{N}-{NN}] {Category} — {Ola\u002FWave Name}\n\n# Labels: audit, {ola\u002Fwave name}\ngh issue create \\\n  --title \"[AUDIT-5-02] Security + Performance — Ola 5\" \\\n  --label \"audit,ola5\" \\\n  --body '\u003Cstructured report>'\n```\n\n### Report Structure\n\n1. **Header** — target commit, stats, reviewer, date\n2. **Web Research Summary** — 3 queries with key findings\n3. **Security Findings** — grouped by severity (CRITICAL → LOW)\n4. **Performance Findings** — grouped by severity\n5. **Strong Points** — what the codebase does right\n6. **Summary Table** — ID, Category, Severity, Files, Description\n7. **Recommendations** — priority-ordered fix list\n8. **References** — URLs from web research\n\n## Pitfalls\n\n- **Don't skip web research** — best practices evolve fast (async patterns, tooling). Always ground the audit in current standards.\n- **Distinguish test vs production code** — `unwrap()` in tests is acceptable; in production paths it's a bug.\n- **Don't flag `std::sync::Mutex` blindly** — it's safe if never held across `.await`. Check the actual usage pattern.\n- **`spawn_blocking` has overhead** — don't recommend it for trivial sync operations (micro-second range). Use judgment on the tradeoff.\n- **Don't report every `.clone()`** — focus on clones in hot async paths or tight loops.\n- **Don't report every `unsafe`** — some FFI\u002FOS calls are inherently unsafe and well-understood (libc::kill, libc::getuid). Focus on Rust level-2 unsafety (pointer deref, layout assumptions).\n- **Supply chain audit** requires `cargo audit` + `cargo deny` — recommend adding these to CI, not just running once.\n- **Swallowed errors (`let _ =`) are easy to miss** — they don't produce warnings. Always run `search_files(pattern=\"let _ =\", ...)` as part of the security scan. Categorize by intent: fire-and-forget (acceptable) vs persistence\u002FIO (flag).\n- **Test assertions with `|| true` are dead tests** — search for `|| true` in test code. If an assertion includes `|| true`, it can never fail. This is a silent CI gap.\n- **Hardcoded test secrets behind feature gates** — if a `#[cfg(feature = \"X\")]` module contains hardcoded keys, and that feature can be enabled in release builds, the key is in the production binary. Verify feature gating matches build profiles.\n- **Env var file paths without validation** — `PathBuf::from(env::var(\"SOME_DIR\")?)` is a path traversal vector if the env is controllable. Always validate or sanitize env-derived paths.\n- **One fixed instance of a copy-pasted pattern is not a fix** — after finding an expensive or unsafe pattern, grep its siblings before declaring it resolved: `grep -rc 'store\\.get(' src\u002F\u003Ccomponent>\u002F | grep -v ':0'`. Count > 1 in files you did not touch means you found an instance of an N-instance bug. The suite will stay green either way, because it tests each module in isolation and each is correct about itself.\n- **A green suite plus an unchanged symptom means the live process is the only oracle left** — read its own output (`journalctl -u \u003Csvc> --since '10 min ago' | grep \u003Cstage>`) to see which stage actually costs. A loop that logs stages A, B, C and never reaches D localises the cost precisely, and reveals that the stage you just fixed was never the expensive one.\n- **Deploying a release build with a reduced feature set silently drops subsystems** — a CI-safe feature set can exclude the TUI, webhook or notification code the running node depends on, and the binary still builds and passes every gate. Diff meaningful symbols (counts of a feature's types) between the newly built binary and the installed one before overwriting it; file size is a hint, not proof.\n\n## Issue\u002FReport Creation — Summary Table Format\n\nWhen creating the audit issue\u002Freport, include a summary table at the bottom of each section and a consolidated table at the end. Use the PASS\u002FPASS\u002FCRITICAL\u002FHIGH scoring:\n\n```markdown\n| ID | Category | Severity | Files | Description |\n|----|----------|----------|-------|-------------|\n| S-01 | Security | PASS | ingest.rs, models.rs | Type widening u32→u64: SAFE. JSON compat preserved |\n| S-02 | Security | PASS | models.rs | f64 consistency: already correct |\n| S-03 | Security | PASS | run.rs | Dead code removal: 76 LOC removed |\n| S-04 | Security | PASS | docs\u002F | Docs updated: references corrected |\n| P-01 | Performance | PASS | models.rs | Compile impact: negligible (+71 LOC) |\n| D-01 | Dependencies | PASS | Cargo.toml | tokio 1.37→1.49: semver-compatible |\n```\n\n### Critical: authorization that is opt-in per layer\n\nA guard that each layer must remember to install is not a guard. Audit for the shape, not the individual check:\n\n| Anti-pattern | Why it fails | Correct form |\n|---|---|---|\n| `match path { … _ => true }` in a scope\u002Fpermission check | Every route nobody classified inherits *allowed* | Derive the requirement from method+path into an enum (`Read`\u002F`Write`\u002F`RootOnly`); unknown route falls to the strictest sane default |\n| `fn authorize(..) -> Result\u003C..> { Ok(()) }` with a \"scaffolding\" comment | Reads like a policy, approves everything, and its only caller may pass `Uuid::nil()` so it could never deny | Fail closed (`Err`), and delete the call site |\n| Per-route `.layer(middleware::from_fn(gate))` | Forgetting the layer ships the route open | `route_layer` on the whole sub-router: gated by construction |\n| Permission trait where a new capability reuses a broad existing method | Any holder of the broad method silently gains the capability | Add an explicit method per capability, narrowest role first |\n| A wildcard bind (`0.0.0.0`) on a service that serves authenticated routes | Publishes the auth surface to every interface; a loopback default is the one a reviewer can verify | Loopback default; widening must be an explicit, documented opt-in |\n| Capability token (lease\u002Fshort-lived) usable as a general session | Handed to a subprocess for one call, becomes node-wide access | Constrain it to the one path prefix it exists for |\n| `.unwrap_or(true)` \u002F `.unwrap_or(default_allow)` on a rate-limit or policy check | Fails open on error | Fail closed (`unwrap_or(false)`) |\n\n**Also verify the gate is real at the router level**, not just at the handler: grep the registration site and confirm every route in the sensitive family is covered by the gate function, and that the tests build their router from that same function.\n\n## Verdict Line\n\nEnd with a clear overall verdict:\n\n```markdown\n## VERDICT\n\n**Overall: ✅ PASS** — No security vulnerabilities found. All changes are safe and correct.\n```\n\nOr for findings:\n\n```markdown\n## VERDICT\n\n**Overall: ⚠️ ISSUES FOUND** — 2 CRITICAL, 3 HIGH, 1 MEDIUM. See Recommendations section.\n```\n\n---\n\n## Common Rust Audit Patterns\n\n### Critical: `thread::sleep` in async context\n\n```rust\n\u002F\u002F ❌ BAD — blocks the tokio worker thread\nasync fn integrate_branches() {\n    std::thread::sleep(policy.backoff);  \u002F\u002F BLOCKS!\n}\n\n\u002F\u002F ✅ GOOD — yields to the runtime\nasync fn integrate_branches() {\n    tokio::time::sleep(policy.backoff).await;  \u002F\u002F Yields\n}\n```\n\n### High: `std::sync::Mutex` in async with .await\n\n```rust\n\u002F\u002F ❌ DANGEROUS — lock held across .await\nasync fn bad() {\n    let guard = my_mutex.lock().unwrap();\n    do_something_async().await;  \u002F\u002F Lock held! Deadlock risk!\n}\n\n\u002F\u002F ✅ SAFE — brief synchronous scope\nasync fn good() {\n    let value = {\n        let guard = my_mutex.lock().unwrap();\n        guard.clone()  \u002F\u002F Clone before releasing\n    };\n    do_something_async().await;  \u002F\u002F Lock already released\n}\n```\n\n### High: `.unwrap()` on poisoned mutex\n\n```rust\n\u002F\u002F ❌ BAD — panics if another thread panicked\nlet conn = self.conn.lock().unwrap();\n\n\u002F\u002F ✅ GOOD — propagates error\nlet conn = self.conn.lock().map_err(|e| ...)?;\n```\n\n### High: Swallowed errors with `let _ =`\n\n```rust\n\u002F\u002F ❌ BAD — silent data loss on persistence failure\nlet _ = self.save_state();\n\n\u002F\u002F ✅ GOOD — log and propagate or at minimum warn\nif let Err(e) = self.save_state() {\n    tracing::warn!(\"Failed to persist DAO state: {:?}\", e);\n}\n```\n\n**When auditing:** Count `let _ =` instances. Categorize:\n- Event publishing \u002F fire-and-forget → acceptable (note as INFO)\n- DB\u002Ffile persistence → flag as MEDIUM-HIGH (silent data loss)\n- Error propagation from fallible ops → flag as HIGH\n\n### Medium: Hardcoded secrets in test code\n\n```rust\n\u002F\u002F ❌ DANGEROUS — real key in test, could leak if feature gate is enabled in prod\n#[cfg(feature = \"dao-evm\")]\nprivate_key: \"0x\u003C64-hex-key>\" \u002F\u002F e.g. a hardcoded Hardhat default account key\n\n\u002F\u002F ✅ BETTER — use env var or fixture\nprivate_key: std::env::var(\"TEST_EVM_PRIVATE_KEY\").expect(\"set TEST_EVM_PRIVATE_KEY\")\n```\n\n**Key question:** Is the `#[cfg(feature = \"...\")]` gate compiled into production builds? If the feature can be enabled in release, the test key is in the binary.\n\n### Medium: Private key as plain String in structs\n\n```rust\n\u002F\u002F ❌ Secret exposed via Debug, Serialize, Clone\n#[derive(Debug, Clone, Serialize)]\npub struct EvmDaoConfig {\n    pub private_key: String,  \u002F\u002F leaks in logs, error messages\n}\n\n\u002F\u002F ✅ Use secrecy crate or suppress Debug\npub struct EvmDaoConfig {\n    #[serde(skip)]\n    private_key: secrecy::SecretString,\n}\n```\n\n### Medium: Governance \u002F DAO state persistence gaps\n\n```rust\n\u002F\u002F ❌ In-memory only — data lost on restart\npub struct GovernanceDao {\n    proposals: HashMap\u003CString, Proposal>,\n    \u002F\u002F no save\u002Fload mechanism\n}\n\n\u002F\u002F ✅ Persistence layer required for production governance\n```\n\n**When auditing governance modules, check:**\n1. Is state persisted to disk\u002FDB? (HashMap-only = data loss on restart)\n2. Are save operations error-handled? (silent `let _ =` = divergence)\n3. Are Mutex unwraps in global state functions? (deadlock if poisoned)\n4. Is there a credit\u002Fbalance system? (verify credits are deducted, not just checked)\n\n### Medium: Blocking I\u002FO in async context\n\n```rust\n\u002F\u002F ❌ BAD — blocks worker thread\npub async fn record_metrics(&self, metrics: ExecutionMetrics) -> Result\u003C()> {\n    let mut db = self.read_db();  \u002F\u002F std::fs inside async fn!\n    db.metrics.push(metrics);\n    self.write_db(&db)?;\n    Ok(())\n}\n\n\u002F\u002F ✅ GOOD — offloads to blocking pool\npub async fn record_metrics(&self, metrics: ExecutionMetrics) -> Result\u003C()> {\n    let db_path = self.db_path.clone();\n    tokio::task::spawn_blocking(move || {\n        let mut db = read_db(&db_path)?;\n        db.metrics.push(metrics);\n        write_db(&db_path, &db)\n    })\n    .await??;\n    Ok(())\n}\n```\n\n### PASS: Dependency Version Bump Verification\n\nWhen a dependency version is bumped (e.g., tokio 1.37→1.49), verify:\n\n```bash\n# 1. Check if semver-compatible (same major version)\n#    1.37 → 1.49: minor bump within same major → SHOULD be compatible\n\n# 2. Check if other workspace crates already use the newer version\ngrep -rn 'tokio.*version' *\u002FCargo.toml | grep -v 'Cargo.lock'\n\n# 3. Check Cargo.lock impact\ngit diff HEAD~1..HEAD -- Cargo.lock | head -20\n\n# 4. Check if features changed\n#    e.g., tokio = { version = \"1.49\", features = [\"full\"] }\n#    vs tokio = { version = \"1.37\", features = [\"full\"] }\n```\n\n**Assessment criteria:**\n- ✅ Same major version: SAFE (semver guarantees backward compatibility)\n- ✅ Same feature set: SAFE (no feature flag changes)\n- ✅ Aligns with workspace: POSITIVE (reduces version drift)\n- ⚠️ Feature set changed: needs review (new features might pull in new transitive deps)\n- 🔴 New major version (2.x): BREAKING — requires full API audit\n- 🔴 Feature removed: BREAKING — check if the code uses the removed feature\n\n### PASS: Docs Update Verification\n\nWhen docs files change alongside code, verify accuracy:\n\n```bash\n# 1. List all docs files changed\ngit diff HEAD~1..HEAD --name-only | grep '\\.md$'\n\n# 2. Check workspace member consistency\ngrep -A 20 '\\[workspace\\]' Cargo.toml\n\n# 3. Check ARCHITECTURE.md crate map matches workspace\ngrep -E '^| `.*` \\|' ARCHITECTURE.md 2>\u002Fdev\u002Fnull\n\n# 4. Check AGENTS.md claims against Cargo.toml\n#    e.g., \"gestalt_swarm is excluded\" → verify it's NOT in workspace members\n```\n\n**Assessment criteria:**\n- ✅ Workspace members match doc claims: PASS\n- ⚠️ Discrepancy found: file issue (DOCS severity) to fix docs\n- 🔴 Major disconnect (docs say excluded, Cargo.toml includes): CRITICAL for CI\n\n### PASS: Type Widening Analysis (u32→u64)\n\nIn Rust, widening conversions are ALWAYS safe — the standard library provides `From\u003Cu32> for u64`. When auditing code that changes field types from u32 to u64:\n\n**Key verification points:**\n1. **Is the cast safe?** u32→u64 via `From`\u002F`Into` or `as` — YES, always safe (no truncation possible)\n2. **Is JSON serialization backward-compatible?** YES — JSON numbers are arbitrary precision; u32 and u64 both serialize as integers\n3. **Are there operation-order bugs?** Check if arithmetic happens on the narrower type BEFORE widening:\n   ```rust\n   \u002F\u002F ❌ Operates on u32 before widening — overflow risk\n   let result = (x + y) as u64;   \u002F\u002F x+y overflows as u32 first\n   \n   \u002F\u002F ✅ Widens before arithmetic — no overflow\n   let result = (x as u64) + (y as u64);\n   ```\n4. **Are the values realistic?** For priorities (50, 100, 150), both u32 and u64 are fine\n\n**When to flag:**\n- 🔴 Narrowing (u64→u32) without checked conversion — silent truncation\n- 🔴 Operation-order bug — u32 arithmetic before widening\n- ✅ Widening (u32→u64) — always PASS, document as safe\n\n## Referencias\n\n1. **RustSec**: https:\u002F\u002Frustsec.org\u002F — Security advisory database for Rust.\n2. **cargo-audit**: https:\u002F\u002Fgithub.com\u002Frustsec\u002Frustsec — Audit dependencies for known vulnerabilities.\n3. **subtle crate**: https:\u002F\u002Fdocs.rs\u002Fsubtle\u002Flatest\u002Fsubtle\u002F — Constant-time comparisons (timing attack prevention).\n4. **Tokio Shared State**: https:\u002F\u002Ftokio.rs\u002Ftokio\u002Ftutorial\u002Fshared-state — Patterns for thread-safe state in async.\n5. **Rust Cheatsheet (Unsafe)**: https:\u002F\u002Fcheats.rs\u002F#unsafe — Unsafe code patterns reference.\n6. **cargo-deny**: https:\u002F\u002Fgithub.com\u002FEmbarkStudios\u002Fcargo-deny — Deny criteria for dependencies.\n7. **cargo-vet**: https:\u002F\u002Fgithub.com\u002Fnickel-org\u002Fcargo-vet — Supply chain verification.\n8. **Rust Secure Code**: https:\u002F\u002Frust-secure-code.github.io\u002F — Security guidelines for Rust.\n\n---\n\n*Rust Code Security & Performance Audit — v1.1.0 (with references)*\n","# Rust Code Security & Performance Audit\n\nFull-scale audit methodology for Rust codebases. Combines web research grounding with systematic pattern-based code search to find security vulnerabilities, performance anti-patterns, and supply-chain risks.\n\n## When to Use\n\n- User requests \"security audit\", \"performance audit\", or \"code review\" of a Rust project\n- Before a release or merge of a large feature branch (50+ files, 5000+ LOC changed)\n- After merging external contributions or autonomous-agent PRs\n- When evaluating a new dependency or crate for adoption\n- As part of a recurring audit cycle (e.g., AUDIT-5-*, AUDIT-6-* series)\n- **When auditing a specific commit** — use Commit-Scoped Audit (Phase 0) instead of broad pattern search\n\n**Skip for:** single-file changes, documentation-only PRs, pre-commit review (use `requesting-code-review` instead), or quick-fix sessions.\n\n## Skill vs Related Skills\n\n| Skill | Scope | Trigger |\n|-------|-------|---------|\n| **rust-code-audit** | Full codebase audit — security + performance + supply chain | \"audit\", \"security review\", \"performance review\" |\n| `requesting-code-review` | Pre-commit diff scanning | \"commit\", \"verify\", \"ship\" |\n| `codebase-inspection` | LOC\u002Fstructure\u002FCI\u002Fdocs analysis | \"how big\", \"what's in this repo\" |\n| `systematic-debugging` | Root cause debugging of specific bugs | bug reports, test failures |\n| `github-code-review` | Reviewing other people's PRs with inline comments | \"review PR #X\" |\n| `rust-code-quality-audit` | Architecture + code quality (separate from security) | \"quality audit\", \"architecture review\" |\n\n## Phase 0 — Commit-Scoped Audit (when auditing a specific commit)\n\nWhen the audit targets a specific commit (not the whole codebase), start with `git diff` analysis to understand the scope **before** running broad pattern searches:\n\n```bash\n# 1. Understand the scope\ngit log --oneline -5              # Recent history, context\ngit diff --stat HEAD~1..HEAD      # Files changed, lines added\u002Fdeleted\n\n# 2. Diff per file for key changes\ngit diff HEAD~1..HEAD -- \u003Cfile>   # Detail per affected file\n\n# 3. List all parent commits in the wave\ngit log --oneline HEAD~N..HEAD    # All commits in this wave\u002Frelease\n```\n\n**Identify the change categories** from the diff stat before diving into patterns:\n\n| Category | What to check | Security? | Performance? |\n|----------|---------------|-----------|--------------|\n| **Type widening** (u32→u64, f32→f64) | Verify no truncation, JSON compat, operation-order bugs | ✅ Safe in Rust (widening is always lossless) | Usually neutral |\n| **Dead code removal** | Verify no needed code accidentally removed | ✅ Positive (reduced attack surface) | Marginal compile improvement |\n| **Struct consolidation** | Verify DTOs moved to shared crate, no stale imports | ✅ Positive (single source of truth) | Net LOC reduction |\n| **Dependency version bumps** | Verify semver compatibility, workspace consistency | ⚠️ Check for API breakage | Usually positive |\n| **Docs updates** | Verify workspace structure accuracy, no stale claims | Usually PASS | No impact |\n| **CLI command changes** | Verify enum match, help text accuracy | Low | Low |\n\nThen run targeted `git diff` on the specific files identified, rather than broad `search_files` across the entire codebase.\n\n## Phase 1 — Web Research Grounding (3 parallel queries)\n\nBefore examining code, establish current best practices. Run 3 web searches in parallel:\n\n```bash\n# 1. Security audit best practices\n# e.g. \"Rust security audit checklist 2026 unsafe code production\"\n\n# 2. Async performance patterns\n# e.g. \"Rust async performance optimization 2026 tokio spawn_blocking\"\n\n# 3. Supply chain \u002F dependency security\n# e.g. \"Rust supply chain security cargo audit 2026 dependency management\"\n```\n\nCapture key findings as a markdown reference. Include:\n- Current recommended tools (cargo-deny, cargo-vet, cargo-audit, Cargo Scan)\n- Known anti-patterns\n- Reference URLs\n\n## Phase 2 — Pattern-Based Code Search\n\nSearch for all security and performance patterns across the codebase. Run these searches in parallel using `search_files`:\n\n### Security Patterns\n\n| Pattern | What It Finds | Risk |\n|---------|---------------|------|\n| `unsafe` | Unsafe blocks — need audit for correctness | Memory safety violations |\n| `.unwrap()` | Panic-on-error patterns in production code | Crashes under failure |\n| `.expect(` | Assertive unwraps — less risky if descriptive | Lower risk |\n| `thread::sleep` | Blocking sleep | Worker thread starvation |\n| `std::sync::Mutex` | Sync mutex in async runtime | Contention, deadlock if held across .await |\n| `block_on` | Blocking the current thread on async code | Nested runtime, deadlock |\n| `api.?key\\|API_KEY\\|secret\\|password` | Hardcoded secrets | Credential leak |\n| `include_bytes!` | Embedded binary blobs | Supply chain risk |\n| `let _ =` | Swallowed `Result`\u002F`Error` values | Silent data loss, unlogged failures |\n| `format!.*SELECT\\|.*INSERT\\|.*DELETE\\|.*UPDATE` | SQL with format!() for identifiers | SQL injection if table names become dynamic |\n| `env::var.*path\\|env::var.*dir\\|env::var.*PATH` | Env var used to construct file paths | Path traversal if env is controllable |\n| `private_key.*String` | Private key as plain `String` in structs | Secret exposure via Debug\u002Flogs\u002Fserialization |\n| **Type narrowing\u002Fwidening** | `as u32`, `as u16`, `as i32` casts — truncation risk | Data loss |\n| **`From\u003Cu32> for u64` \u002F `Into\u003Cu64>`** | Widening: SAFE by default (From impl guaranteed in std) | ✅ Zero risk |\n| **`as u64` cast** | Widening via `as`: SAFE (no truncation) but check for op-order bugs | ✅ Safe if arithmetic happens AFTER widening |\n| **`as u32` cast from u64** | **Narrowing**: TRUNCATES silently — CRITICAL | Data loss \u002F overflow |\n| **`#[serde(untagged)]` enum changes** | Adding\u002Fremoving variants without compat checks | Deserialization failure |\n\n### Performance Patterns\n\n| Pattern | What It Finds | Risk |\n|---------|---------------|------|\n| `spawn_blocking` | Proper async offloading | ✅ Positive — count usage |\n| `thread::sleep` | Blocking in async | Worker thread starvation |\n| `std::sync::Mutex` (in async) | Non-yielding locks | Throughput degradation |\n| `.clone()` inside hot paths | Unnecessary allocations | Memory churn |\n| `DashMap` | Concurrent map | Usually fine, check for iter() across await |\n| `for m in &db.metrics` | Linear scans | O(n) on every operation |\n\n### Search Template (Rust projects)\n\n```bash\n# Run all in parallel (concurrent tool calls in Hermes)\nsearch_files(pattern=\"unsafe\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Security\nsearch_files(pattern=\"\\\\.unwrap\\\\(\\\\)\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Security\nsearch_files(pattern=\"\\\\.expect\\\\(\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Security\nsearch_files(pattern=\"thread::sleep\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Perf\u002FSec\nsearch_files(pattern=\"std::sync::Mutex\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Perf\u002FSec\nsearch_files(pattern=\"spawn_blocking\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Perf (positive)\nsearch_files(pattern=\"block_on\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Security\nsearch_files(pattern=\"api.?key|API_KEY|secret|password\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Security\nsearch_files(pattern=\"let _ =\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Swallowed errors\nsearch_files(pattern=\"format!.*SELECT|format!.*INSERT|format!.*DELETE|format!.*UPDATE\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # SQL injection\nsearch_files(pattern=\"env::var.*path|env::var.*dir|env::var.*PATH\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Env path injection\nsearch_files(pattern=\"private_key.*String|secret.*String|api_key.*String\", file_glob=\"*.rs\", path=\"\u002Fpath\u002Fto\u002Frepo\")  # Secret as String\n```\n\n## Phase 3 — Deep Reading of Candidate Files\n\nFor files matching critical patterns, read the full context around matches:\n\n1. **unsafe blocks** — verify safety invariants, check for soundness holes\n2. **unwrap\u002Fexpect in production** — distinguish test code from production code paths\n3. **thread::sleep** — identify whether it's inside an `async fn` or tokio task\n4. **std::sync::Mutex** — check if locks are held across `.await` points\n5. **Hardcoded secrets** — confirm whether they're test placeholders or real credentials\n\n### Classification Rules\n\n- **Test code** (`#[cfg(test)]`, `tests\u002F` directory) — lower severity, note it\n- **Production code** — full severity\n- **Non-async functions** — `thread::sleep` is acceptable (not an async violation)\n- **Async functions \u002F tokio::spawn** — `thread::sleep` is critical\n\n## Phase 4 — Finding Documentation\n\nFor each confirmed finding, document:\n\n```\n### ID [S\u002FP]-[NN] [SEVERITY] [Brief Title]\n- **File:** path\u002Fto\u002Ffile.rs:line_number\n- **Code:** relevant code snippet (5-10 lines)\n- **Risk:** what could go wrong in production\n- **Fix:** specific change needed\n```\n\n### Severity Levels\n\n| Level | Meaning | Action |\n|-------|---------|--------|\n| 🔴 **CRITICAL** | Blocks worker thread, crashes on failure path, or exposes secrets | Fix immediately before merge |\n| 🟡 **HIGH** | Risk of deadlock\u002Fpanic under specific conditions, or design flaw | Fix before next release |\n| 🟢 **MEDIUM** | Suboptimal pattern, no immediate danger but tech debt grows | Schedule for next sprint |\n| ⚪ **LOW** | Minor concern, acceptable at current scale | Note for future refactoring |\n\n### Strong Points\n\nAlso document what the codebase does **right** — reinforces good practices:\n\n```\nSecurity:\n- ✅ API keys from environment variables\n- ✅ No SQL injection (parameterized queries)\n- ✅ spawn_blocking properly used on all SQLite operations\n\nPerformance:\n- ✅ virtual_fs.rs: correct spawn_blocking on all 7 operations\n- ✅ health.rs: clean async patterns, no thread::sleep\n```\n\n## Phase 5 — Issue\u002FReport Creation\n\nCreate the deliverable as a structured GitHub issue or report:\n\n```bash\n# Title format\n[AUDIT-{N}-{NN}] {Category} — {Ola\u002FWave Name}\n\n# Labels: audit, {ola\u002Fwave name}\ngh issue create \\\n  --title \"[AUDIT-5-02] Security + Performance — Ola 5\" \\\n  --label \"audit,ola5\" \\\n  --body '\u003Cstructured report>'\n```\n\n### Report Structure\n\n1. **Header** — target commit, stats, reviewer, date\n2. **Web Research Summary** — 3 queries with key findings\n3. **Security Findings** — grouped by severity (CRITICAL → LOW)\n4. **Performance Findings** — grouped by severity\n5. **Strong Points** — what the codebase does right\n6. **Summary Table** — ID, Category, Severity, Files, Description\n7. **Recommendations** — priority-ordered fix list\n8. **References** — URLs from web research\n\n## Pitfalls\n\n- **Don't skip web research** — best practices evolve fast (async patterns, tooling). Always ground the audit in current standards.\n- **Distinguish test vs production code** — `unwrap()` in tests is acceptable; in production paths it's a bug.\n- **Don't flag `std::sync::Mutex` blindly** — it's safe if never held across `.await`. Check the actual usage pattern.\n- **`spawn_blocking` has overhead** — don't recommend it for trivial sync operations (micro-second range). Use judgment on the tradeoff.\n- **Don't report every `.clone()`** — focus on clones in hot async paths or tight loops.\n- **Don't report every `unsafe`** — some FFI\u002FOS calls are inherently unsafe and well-understood (libc::kill, libc::getuid). Focus on Rust level-2 unsafety (pointer deref, layout assumptions).\n- **Supply chain audit** requires `cargo audit` + `cargo deny` — recommend adding these to CI, not just running once.\n- **Swallowed errors (`let _ =`) are easy to miss** — they don't produce warnings. Always run `search_files(pattern=\"let _ =\", ...)` as part of the security scan. Categorize by intent: fire-and-forget (acceptable) vs persistence\u002FIO (flag).\n- **Test assertions with `|| true` are dead tests** — search for `|| true` in test code. If an assertion includes `|| true`, it can never fail. This is a silent CI gap.\n- **Hardcoded test secrets behind feature gates** — if a `#[cfg(feature = \"X\")]` module contains hardcoded keys, and that feature can be enabled in release builds, the key is in the production binary. Verify feature gating matches build profiles.\n- **Env var file paths without validation** — `PathBuf::from(env::var(\"SOME_DIR\")?)` is a path traversal vector if the env is controllable. Always validate or sanitize env-derived paths.\n- **One fixed instance of a copy-pasted pattern is not a fix** — after finding an expensive or unsafe pattern, grep its siblings before declaring it resolved: `grep -rc 'store\\.get(' src\u002F\u003Ccomponent>\u002F | grep -v ':0'`. Count > 1 in files you did not touch means you found an instance of an N-instance bug. The suite will stay green either way, because it tests each module in isolation and each is correct about itself.\n- **A green suite plus an unchanged symptom means the live process is the only oracle left** — read its own output (`journalctl -u \u003Csvc> --since '10 min ago' | grep \u003Cstage>`) to see which stage actually costs. A loop that logs stages A, B, C and never reaches D localises the cost precisely, and reveals that the stage you just fixed was never the expensive one.\n- **Deploying a release build with a reduced feature set silently drops subsystems** — a CI-safe feature set can exclude the TUI, webhook or notification code the running node depends on, and the binary still builds and passes every gate. Diff meaningful symbols (counts of a feature's types) between the newly built binary and the installed one before overwriting it; file size is a hint, not proof.\n\n## Issue\u002FReport Creation — Summary Table Format\n\nWhen creating the audit issue\u002Freport, include a summary table at the bottom of each section and a consolidated table at the end. Use the PASS\u002FPASS\u002FCRITICAL\u002FHIGH scoring:\n\n```markdown\n| ID | Category | Severity | Files | Description |\n|----|----------|----------|-------|-------------|\n| S-01 | Security | PASS | ingest.rs, models.rs | Type widening u32→u64: SAFE. JSON compat preserved |\n| S-02 | Security | PASS | models.rs | f64 consistency: already correct |\n| S-03 | Security | PASS | run.rs | Dead code removal: 76 LOC removed |\n| S-04 | Security | PASS | docs\u002F | Docs updated: references corrected |\n| P-01 | Performance | PASS | models.rs | Compile impact: negligible (+71 LOC) |\n| D-01 | Dependencies | PASS | Cargo.toml | tokio 1.37→1.49: semver-compatible |\n```\n\n### Critical: authorization that is opt-in per layer\n\nA guard that each layer must remember to install is not a guard. Audit for the shape, not the individual check:\n\n| Anti-pattern | Why it fails | Correct form |\n|---|---|---|\n| `match path { … _ => true }` in a scope\u002Fpermission check | Every route nobody classified inherits *allowed* | Derive the requirement from method+path into an enum (`Read`\u002F`Write`\u002F`RootOnly`); unknown route falls to the strictest sane default |\n| `fn authorize(..) -> Result\u003C..> { Ok(()) }` with a \"scaffolding\" comment | Reads like a policy, approves everything, and its only caller may pass `Uuid::nil()` so it could never deny | Fail closed (`Err`), and delete the call site |\n| Per-route `.layer(middleware::from_fn(gate))` | Forgetting the layer ships the route open | `route_layer` on the whole sub-router: gated by construction |\n| Permission trait where a new capability reuses a broad existing method | Any holder of the broad method silently gains the capability | Add an explicit method per capability, narrowest role first |\n| A wildcard bind (`0.0.0.0`) on a service that serves authenticated routes | Publishes the auth surface to every interface; a loopback default is the one a reviewer can verify | Loopback default; widening must be an explicit, documented opt-in |\n| Capability token (lease\u002Fshort-lived) usable as a general session | Handed to a subprocess for one call, becomes node-wide access | Constrain it to the one path prefix it exists for |\n| `.unwrap_or(true)` \u002F `.unwrap_or(default_allow)` on a rate-limit or policy check | Fails open on error | Fail closed (`unwrap_or(false)`) |\n\n**Also verify the gate is real at the router level**, not just at the handler: grep the registration site and confirm every route in the sensitive family is covered by the gate function, and that the tests build their router from that same function.\n\n## Verdict Line\n\nEnd with a clear overall verdict:\n\n```markdown\n## VERDICT\n\n**Overall: ✅ PASS** — No security vulnerabilities found. All changes are safe and correct.\n```\n\nOr for findings:\n\n```markdown\n## VERDICT\n\n**Overall: ⚠️ ISSUES FOUND** — 2 CRITICAL, 3 HIGH, 1 MEDIUM. See Recommendations section.\n```\n\n---\n\n## Common Rust Audit Patterns\n\n### Critical: `thread::sleep` in async context\n\n```rust\n\u002F\u002F ❌ BAD — blocks the tokio worker thread\nasync fn integrate_branches() {\n    std::thread::sleep(policy.backoff);  \u002F\u002F BLOCKS!\n}\n\n\u002F\u002F ✅ GOOD — yields to the runtime\nasync fn integrate_branches() {\n    tokio::time::sleep(policy.backoff).await;  \u002F\u002F Yields\n}\n```\n\n### High: `std::sync::Mutex` in async with .await\n\n```rust\n\u002F\u002F ❌ DANGEROUS — lock held across .await\nasync fn bad() {\n    let guard = my_mutex.lock().unwrap();\n    do_something_async().await;  \u002F\u002F Lock held! Deadlock risk!\n}\n\n\u002F\u002F ✅ SAFE — brief synchronous scope\nasync fn good() {\n    let value = {\n        let guard = my_mutex.lock().unwrap();\n        guard.clone()  \u002F\u002F Clone before releasing\n    };\n    do_something_async().await;  \u002F\u002F Lock already released\n}\n```\n\n### High: `.unwrap()` on poisoned mutex\n\n```rust\n\u002F\u002F ❌ BAD — panics if another thread panicked\nlet conn = self.conn.lock().unwrap();\n\n\u002F\u002F ✅ GOOD — propagates error\nlet conn = self.conn.lock().map_err(|e| ...)?;\n```\n\n### High: Swallowed errors with `let _ =`\n\n```rust\n\u002F\u002F ❌ BAD — silent data loss on persistence failure\nlet _ = self.save_state();\n\n\u002F\u002F ✅ GOOD — log and propagate or at minimum warn\nif let Err(e) = self.save_state() {\n    tracing::warn!(\"Failed to persist DAO state: {:?}\", e);\n}\n```\n\n**When auditing:** Count `let _ =` instances. Categorize:\n- Event publishing \u002F fire-and-forget → acceptable (note as INFO)\n- DB\u002Ffile persistence → flag as MEDIUM-HIGH (silent data loss)\n- Error propagation from fallible ops → flag as HIGH\n\n### Medium: Hardcoded secrets in test code\n\n```rust\n\u002F\u002F ❌ DANGEROUS — real key in test, could leak if feature gate is enabled in prod\n#[cfg(feature = \"dao-evm\")]\nprivate_key: \"0x\u003C64-hex-key>\" \u002F\u002F e.g. a hardcoded Hardhat default account key\n\n\u002F\u002F ✅ BETTER — use env var or fixture\nprivate_key: std::env::var(\"TEST_EVM_PRIVATE_KEY\").expect(\"set TEST_EVM_PRIVATE_KEY\")\n```\n\n**Key question:** Is the `#[cfg(feature = \"...\")]` gate compiled into production builds? If the feature can be enabled in release, the test key is in the binary.\n\n### Medium: Private key as plain String in structs\n\n```rust\n\u002F\u002F ❌ Secret exposed via Debug, Serialize, Clone\n#[derive(Debug, Clone, Serialize)]\npub struct EvmDaoConfig {\n    pub private_key: String,  \u002F\u002F leaks in logs, error messages\n}\n\n\u002F\u002F ✅ Use secrecy crate or suppress Debug\npub struct EvmDaoConfig {\n    #[serde(skip)]\n    private_key: secrecy::SecretString,\n}\n```\n\n### Medium: Governance \u002F DAO state persistence gaps\n\n```rust\n\u002F\u002F ❌ In-memory only — data lost on restart\npub struct GovernanceDao {\n    proposals: HashMap\u003CString, Proposal>,\n    \u002F\u002F no save\u002Fload mechanism\n}\n\n\u002F\u002F ✅ Persistence layer required for production governance\n```\n\n**When auditing governance modules, check:**\n1. Is state persisted to disk\u002FDB? (HashMap-only = data loss on restart)\n2. Are save operations error-handled? (silent `let _ =` = divergence)\n3. Are Mutex unwraps in global state functions? (deadlock if poisoned)\n4. Is there a credit\u002Fbalance system? (verify credits are deducted, not just checked)\n\n### Medium: Blocking I\u002FO in async context\n\n```rust\n\u002F\u002F ❌ BAD — blocks worker thread\npub async fn record_metrics(&self, metrics: ExecutionMetrics) -> Result\u003C()> {\n    let mut db = self.read_db();  \u002F\u002F std::fs inside async fn!\n    db.metrics.push(metrics);\n    self.write_db(&db)?;\n    Ok(())\n}\n\n\u002F\u002F ✅ GOOD — offloads to blocking pool\npub async fn record_metrics(&self, metrics: ExecutionMetrics) -> Result\u003C()> {\n    let db_path = self.db_path.clone();\n    tokio::task::spawn_blocking(move || {\n        let mut db = read_db(&db_path)?;\n        db.metrics.push(metrics);\n        write_db(&db_path, &db)\n    })\n    .await??;\n    Ok(())\n}\n```\n\n### PASS: Dependency Version Bump Verification\n\nWhen a dependency version is bumped (e.g., tokio 1.37→1.49), verify:\n\n```bash\n# 1. Check if semver-compatible (same major version)\n#    1.37 → 1.49: minor bump within same major → SHOULD be compatible\n\n# 2. Check if other workspace crates already use the newer version\ngrep -rn 'tokio.*version' *\u002FCargo.toml | grep -v 'Cargo.lock'\n\n# 3. Check Cargo.lock impact\ngit diff HEAD~1..HEAD -- Cargo.lock | head -20\n\n# 4. Check if features changed\n#    e.g., tokio = { version = \"1.49\", features = [\"full\"] }\n#    vs tokio = { version = \"1.37\", features = [\"full\"] }\n```\n\n**Assessment criteria:**\n- ✅ Same major version: SAFE (semver guarantees backward compatibility)\n- ✅ Same feature set: SAFE (no feature flag changes)\n- ✅ Aligns with workspace: POSITIVE (reduces version drift)\n- ⚠️ Feature set changed: needs review (new features might pull in new transitive deps)\n- 🔴 New major version (2.x): BREAKING — requires full API audit\n- 🔴 Feature removed: BREAKING — check if the code uses the removed feature\n\n### PASS: Docs Update Verification\n\nWhen docs files change alongside code, verify accuracy:\n\n```bash\n# 1. List all docs files changed\ngit diff HEAD~1..HEAD --name-only | grep '\\.md$'\n\n# 2. Check workspace member consistency\ngrep -A 20 '\\[workspace\\]' Cargo.toml\n\n# 3. Check ARCHITECTURE.md crate map matches workspace\ngrep -E '^| `.*` \\|' ARCHITECTURE.md 2>\u002Fdev\u002Fnull\n\n# 4. Check AGENTS.md claims against Cargo.toml\n#    e.g., \"gestalt_swarm is excluded\" → verify it's NOT in workspace members\n```\n\n**Assessment criteria:**\n- ✅ Workspace members match doc claims: PASS\n- ⚠️ Discrepancy found: file issue (DOCS severity) to fix docs\n- 🔴 Major disconnect (docs say excluded, Cargo.toml includes): CRITICAL for CI\n\n### PASS: Type Widening Analysis (u32→u64)\n\nIn Rust, widening conversions are ALWAYS safe — the standard library provides `From\u003Cu32> for u64`. When auditing code that changes field types from u32 to u64:\n\n**Key verification points:**\n1. **Is the cast safe?** u32→u64 via `From`\u002F`Into` or `as` — YES, always safe (no truncation possible)\n2. **Is JSON serialization backward-compatible?** YES — JSON numbers are arbitrary precision; u32 and u64 both serialize as integers\n3. **Are there operation-order bugs?** Check if arithmetic happens on the narrower type BEFORE widening:\n   ```rust\n   \u002F\u002F ❌ Operates on u32 before widening — overflow risk\n   let result = (x + y) as u64;   \u002F\u002F x+y overflows as u32 first\n   \n   \u002F\u002F ✅ Widens before arithmetic — no overflow\n   let result = (x as u64) + (y as u64);\n   ```\n4. **Are the values realistic?** For priorities (50, 100, 150), both u32 and u64 are fine\n\n**When to flag:**\n- 🔴 Narrowing (u64→u32) without checked conversion — silent truncation\n- 🔴 Operation-order bug — u32 arithmetic before widening\n- ✅ Widening (u32→u64) — always PASS, document as safe\n\n## Referencias\n\n1. **RustSec**: https:\u002F\u002Frustsec.org\u002F — Security advisory database for Rust.\n2. **cargo-audit**: https:\u002F\u002Fgithub.com\u002Frustsec\u002Frustsec — Audit dependencies for known vulnerabilities.\n3. **subtle crate**: https:\u002F\u002Fdocs.rs\u002Fsubtle\u002Flatest\u002Fsubtle\u002F — Constant-time comparisons (timing attack prevention).\n4. **Tokio Shared State**: https:\u002F\u002Ftokio.rs\u002Ftokio\u002Ftutorial\u002Fshared-state — Patterns for thread-safe state in async.\n5. **Rust Cheatsheet (Unsafe)**: https:\u002F\u002Fcheats.rs\u002F#unsafe — Unsafe code patterns reference.\n6. **cargo-deny**: https:\u002F\u002Fgithub.com\u002FEmbarkStudios\u002Fcargo-deny — Deny criteria for dependencies.\n7. **cargo-vet**: https:\u002F\u002Fgithub.com\u002Fnickel-org\u002Fcargo-vet — Supply chain verification.\n8. **Rust Secure Code**: https:\u002F\u002Frust-secure-code.github.io\u002F — Security guidelines for Rust.\n\n---\n\n*Rust Code Security & Performance Audit — v1.1.0 (with references)*\n",{"name":5,"author":24,"license":15,"version":25,"metadata":26,"platforms":57,"description":7},"Hermes Agent","1.1.0",{"hermes":27},{"tags":28,"references":34,"related_skills":51},[29,30,31,32,33],"audit","security","performance","code-review","rust",[35,39,42,45,48],{"url":36,"year":37,"title":38},"https:\u002F\u002Frustsec.org\u002F",2026,"RustSec — Security Advisory Database",{"url":40,"year":37,"title":41},"https:\u002F\u002Fgithub.com\u002Frustsec\u002Frustsec","cargo-audit — Security audit for dependencies",{"url":43,"year":37,"title":44},"https:\u002F\u002Fdocs.rs\u002Fsubtle\u002Flatest\u002Fsubtle\u002F","subtle crate — Constant-time comparisons",{"url":46,"year":37,"title":47},"https:\u002F\u002Ftokio.rs\u002Ftokio\u002Ftutorial\u002Fshared-state","Tokio Shared State Patterns",{"url":49,"year":37,"title":50},"https:\u002F\u002Fcheats.rs\u002F#unsafe","Rust Cheatsheet — Unsafe Code Patterns",[52,53,54,55,56],"requesting-code-review","codebase-inspection","systematic-debugging","github-issues","rust-code-quality-audit",[58,59],"linux","macos","main","688810f2886d212632acf81e532b24e483dd8b98","skills\u002Fsoftware-development\u002Frust-code-audit","https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills","https:\u002F\u002Fgithub.com\u002Fiberi22","Senior WEB Full-Stack","2026-10-12 02:46:21",{"source":8,"skillName":5,"commands":68,"prompt":78,"zipAvailable":79},[69,72,75],{"tool":70,"command":71},"npx","npx skills add iberi22\u002Fskills --skill rust-code-audit",{"tool":73,"command":74},"bunx","bunx skills add iberi22\u002Fskills --skill rust-code-audit",{"tool":76,"command":77},"pnpm","pnpm dlx skills add iberi22\u002Fskills --skill rust-code-audit","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Frust-code-audit\u002FSKILL.md",true,[81,87,91,95,99],{"path":82,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":85,"sourceHtmlUrl":86},"references\u002Fauthorization-deny-by-default.md","REFERENCE","参考文档",5988,"https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Frust-code-audit\u002Freferences\u002Fauthorization-deny-by-default.md",{"path":88,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":89,"sourceHtmlUrl":90},"references\u002Fgestalt-ola6-audit.md",3377,"https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Frust-code-audit\u002Freferences\u002Fgestalt-ola6-audit.md",{"path":92,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":93,"sourceHtmlUrl":94},"references\u002Fperf-bug-verification.md",4809,"https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Frust-code-audit\u002Freferences\u002Fperf-bug-verification.md",{"path":96,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":97,"sourceHtmlUrl":98},"references\u002Fweb-research.md",4086,"https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Frust-code-audit\u002Freferences\u002Fweb-research.md",{"path":100,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":101,"sourceHtmlUrl":102},"references\u002Fxavier-wavex12-audit-patterns.md",3719,"https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Frust-code-audit\u002Freferences\u002Fxavier-wavex12-audit-patterns.md",[104,110,117,123,129,135],{"skillNo":105,"name":106,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":19},"01M72TWQEQD46ZC9TRBAABF78P","web-design-guidelines","https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fweb\u002Fweb-design-guidelines\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":19},"01M72TWMQFTYD08DGXVAXRPPEB","blocked-page-recovery","Use when a fetch fails: 403\u002F429, paywall, WAF, bot wall. Recovers the page via archives and provenance-checked fallbacks.","https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fweb\u002Fblocked-page-recovery\u002FSKILL.md",[],[],{"skillNo":118,"name":119,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":120,"categories":121,"keywords":122,"publishedAt":19},"01M72TVQMS3HCTX18C8T97WTQQ","studio-coach","https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Ftools\u002Fstudio-coach\u002FSKILL.md",[],[],{"skillNo":124,"name":125,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":19},"01M72TVNA2PR9RZW0ZAXYP1G6J","src-generator","https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Ftools\u002Fsrc-generator\u002FSKILL.md",[],[],{"skillNo":130,"name":131,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":132,"categories":133,"keywords":134,"publishedAt":19},"01M72TVEJHHB6SAT3R3TY9MJKS","sqlite-pro","https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Ftools\u002Fsqlite-pro\u002FSKILL.md",[],[],{"skillNo":136,"name":137,"nameZh":6,"description":138,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":139,"categories":140,"keywords":141,"publishedAt":19},"01M72TVC2EVBHQHCX96VTTYKB8","rigor-evaluator","Use when you need a quick heuristic rigor score (10 criteria, 0-2 each) for the features in a .gitcore\u002Ffeatures.json file, to decide which features are ready to ship.","https:\u002F\u002Fgithub.com\u002Fiberi22\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Ftools\u002Frigor-evaluator\u002FSKILL.md",[],[]]