Skip to content

Add Gemini AI agent for protocol code analysis#16

Open
Copilot wants to merge 5 commits intomainfrom
copilot/analyze-code-vulnerabilities
Open

Add Gemini AI agent for protocol code analysis#16
Copilot wants to merge 5 commits intomainfrom
copilot/analyze-code-vulnerabilities

Conversation

Copy link

Copilot AI commented Feb 15, 2026

Implements a Gemini-powered code analysis agent targeting protocol vulnerabilities, ZK-Circuit issues, and DAO stability concerns.

Changes

CLI Tool (scripts/gemini_agent.js)

  • Gemini 2.5 Flash Preview integration for code analysis
  • Returns Protocol Stability Score (1-10) and flaw summaries
  • Outputs repaired code blocks when issues detected
  • Node.js 18+ compatible (native fetch)

GitHub Actions (.github/workflows/gemini-code-analysis.yml)

  • Manual dispatch for single-file analysis
  • Auto-analyzes changed files in PRs (.go, .js, .ts, .sol)
  • Requires GEMINI_API_KEY secret

Documentation (scripts/GEMINI_AGENT_README.md)

  • CLI usage and API key setup
  • GitHub Actions integration guide

Usage

# Local analysis
node scripts/gemini_agent.js path/to/contract.sol --api-key=$GEMINI_API_KEY

# Workflow dispatch
# Actions → "Gemini Code Analysis" → Run workflow

Agent prompt specializes in elite protocol engineering: mathematical stability, ZK-Circuit correctness, and DAO attack vectors.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • generativelanguage.googleapis.com
    • Triggering command: /home/REDACTED/work/_temp/ghcca-node/node/bin/node node scripts/gemini_agent.js /tmp/gemini-test/test.js --api-key=test123 (dns block)
    • Triggering command: /home/REDACTED/work/_temp/ghcca-node/node/bin/node node scripts/gemini_agent.js scripts/gemini_agent.js --api-key=test_key_123 (dns block)
    • Triggering command: /home/REDACTED/work/_temp/ghcca-node/node/bin/node node scripts/gemini_agent.js scripts/gemini_agent.js --api-key=test123 (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Original prompt

// --- Conceptual Gemini Agent Script (Node.js) ---

const fs = require('fs');
const path = require('path');

// NOTE: In a real Node.js environment, you would use an external library like
// 'node-fetch' for making HTTP requests, and potentially 'dotenv' for keys.
// For this example, we assume basic fetch is available or polyfilled.

const GEMINI_MODEL = 'gemini-2.5-flash-preview-09-2025';

// Use a simple prompt designed for code repair/analysis
const AGENT_SYSTEM_PROMPT = `Act as an elite protocol engineer specializing in ZK-Circuits and DAO stability. Analyze the provided code block for vulnerabilities, deviations from best practices, and mathematical instability.

  1. Assign a Protocol Stability Score (1-10).
  2. Provide a brief summary of Potential Flaws.
  3. If flaws exist, provide the REPAIRED CODE BLOCK only. Do not provide any conversational text before the repaired code. If the code is perfect, output 'NO REPAIR NEEDED'.`;

/**

  • Executes the Gemini API call to analyze the given code snippet.

  • @param {string} codeContent - The content of the file to analyze.

  • @param {string} filePath - The name of the file being analyzed.

  • @param {string} apiKey - The Gemini API key.
    */
    async function runAnalysis(codeContent, filePath, apiKey) {
    if (!apiKey) {
    console.error("Error: GEMINI_API_KEY is missing. Check GitHub Secrets configuration.");
    return;
    }

    const apiUrl = https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent?key=${apiKey};

    // The user query includes the file content to be analyzed
    const userQuery = Analyze the protocol code for ${filePath}:\n\n\``\n${codeContent}\n````;

    const payload = {
    contents: [{ parts: [{ text: userQuery }] }],
    systemInstruction: { parts: [{ text: AGENT_SYSTEM_PROMPT }] },
    // For code analysis, grounding is usually not necessary unless you need real-time data
    // tools: [{ "google_search": {} }],
    };

    let response;
    try {
    // Simple fetch example (replace with node-fetch in a real project)
    response = await fetch(apiUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
    });

     if (!response.ok) {
         throw new Error(`HTTP error! status: ${response.status}`);
     }
    
     const result = await response.json();
     const analysisText = result.candidates?.[0]?.content?.parts?.[0]?.text || "Agent failed to generate response.";
     
     console.log(`\n### Protocol Analysis for ${filePath} ###`);
     console.log(analysisText);
    
     // --- DEEP THINK REPAIR LOGIC ---
     // A real agent would look for the 'REPAIRED CODE BLOCK' and attempt to 
     // write it back to the file system or comment on the PR using the GitHub Token.
     const repairNeeded = analysisText.includes('REPAIRED CODE BLOCK') || analysisText.includes('NO REPAIR NEEDED');
     if (repairNeeded) {
          console.log("Analysis Complete. Check output for repair instructions.");
     }
    

    } catch (error) {
    console.error(\n--- FAILED ANALYSIS for ${filePath} ---);
    console.error(Gemini Agent Error: ${error.message});
    }
    }

/**

  • Main execution function to handle command-line arguments.
    */
    async function main() {
    const filePath = process.argv[2];
    const apiKeyArg = process.argv.find(arg => arg.startsWith('--api-key='));

    if (!filePath || !apiKeyArg) {
    console.error("Usage: node gemini_agent.js --api-key=<your_key>");
    return;
    }

    const apiKey = apiKeyArg.split('=')[1];

    try {
    const codeContent = fs.readFileSync(path.resolve(filePath), 'utf8');
    await runAnalysis(codeContent, filePath, apiKey);
    } catch (error) {
    console.error(Error reading file ${filePath}: ${error.message});
    }
    }

// Ensure fetch is available in Node.js environment
if (typeof fetch === 'undefined') {
global.fetch = require('node-fetch'); // NOTE: This requires 'npm install node-fetch' in a real setup
}

main();


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI and others added 3 commits February 15, 2026 04:57
Co-authored-by: FuzzysTodd <157565446+FuzzysTodd@users.noreply.github.com>
Co-authored-by: FuzzysTodd <157565446+FuzzysTodd@users.noreply.github.com>
…versions

Co-authored-by: FuzzysTodd <157565446+FuzzysTodd@users.noreply.github.com>
Copilot AI changed the title [WIP] Analyze code for vulnerabilities and stability issues Add Gemini AI agent for protocol code analysis Feb 15, 2026
Copilot AI requested a review from FuzzysTodd February 15, 2026 05:02
@FuzzysTodd FuzzysTodd marked this pull request as ready for review February 15, 2026 06:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments