惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
MongoDB | Blog
MongoDB | Blog
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
D
Docker
S
Secure Thoughts
B
Blog
M
MIT News - Artificial intelligence
P
Privacy International News Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
A
Arctic Wolf
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
SegmentFault 最新的问题
WordPress大学
WordPress大学
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tenable Blog
Last Week in AI
Last Week in AI
A
About on SuperTechFans
T
Tor Project blog
Microsoft Azure Blog
Microsoft Azure Blog
Hugging Face - Blog
Hugging Face - Blog
月光博客
月光博客
L
Lohrmann on Cybersecurity
Security Latest
Security Latest
P
Proofpoint News Feed
有赞技术团队
有赞技术团队
P
Privacy & Cybersecurity Law Blog
Spread Privacy
Spread Privacy
AWS News Blog
AWS News Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
小众软件
小众软件
宝玉的分享
宝玉的分享
量子位
Forbes - Security
Forbes - Security
T
Threatpost
Google DeepMind News
Google DeepMind News
T
Threat Research - Cisco Blogs
H
Help Net Security
Help Net Security
Help Net Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
SecWiki News
SecWiki News
I
InfoQ
C
Cyber Attacks, Cyber Crime and Cyber Security
Stack Overflow Blog
Stack Overflow Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
NeuroGuard: AI-Native Code Security Using Gemma 4's Glass-Box Thinking Mode
Tyler H · 2026-05-13 · via DEV Community

Submitted to the Build With Gemma 4 track of the Dev.to Google Gemma 4 Challenge.

TL;DR: I built neuroguard — a CLI that uses Gemma 4's ThinkingConfig(include_thoughts=True) API to stream the model's full cognitive trace in a split-pane terminal UI while it finds security vulnerabilities and produces a SAST-verified secure rewrite. Install: pip install neuroguard-ai. Full source: github.com/tyy130/neuroguard-ai.


The Problem I Kept Running Into

security
Studies find the majority of AI-generated applications ship to production with OWASP Top 10 vulnerabilities. I've seen it firsthand. The worst cases aren't SQL injections from typos — they're hallucinated bypasses: an AI agent removes authentication middleware to resolve a compilation error, silently stripping the application of its entire security layer.

The frustrating thing is that a human reviewer wouldn't make this mistake, because they'd reason about what the code does before deleting it. The AI just optimized for "code compiles" without the security reasoning step.

The root cause is opacity. When a black-box LLM generates insecure code, you can't see why. You get the output without the reasoning. And without the reasoning, you can't tell if the model considered security at all — or silently decided to ignore it.

I wanted to fix that.


What Makes Gemma 4 Different

Before Gemma 4, I had three options for transparent reasoning:

  • GPT-4o / standard Claude: chain-of-thought is completely hidden. You get the answer, never the reasoning.
  • DeepSeek-R1: reasoning is exposed, but as raw <think>...</think> tags embedded in the final text response. You have to parse it out, it's structurally mixed with the answer, and there's no clean API boundary between reasoning and output.
  • Gemma 4: ThinkingConfig(include_thoughts=True) emits reasoning tokens as structurally separate stream parts — each chunk has a thought=True field. The reasoning and the response are separated at the API level, not by text parsing.

That API-level separation is what makes NeuroGuard possible. I can route thought parts to a left pane and response parts to a right pane in real-time, with no regex parsing, no risk of the boundary getting confused, no thought tokens leaking into the final output.


How NeuroGuard Works

┌─────────────────────────────┬────────────────────────────┐
  🧠 Gemma 4 Thinking          🔒 Secure Rewrite         
  ─────────────────────────    ─────────────────────────  
  ...the SQL query on line                                
  47 concatenates user input                              
  directly. This is a                                     
  classic injection vector.                               
  The fix is parameterized                                
  queries...                   from flask import Flask   
                               import sqlite3            
  ...the eval() on line 62                                
  executes arbitrary strings   def get_user(user_id):    
  from the request body.           conn = sqlite3.connect
  This is RCE...                   cursor.execute(       
                                       "SELECT * FROM    │
│                             │           users WHERE      │
│                             │           id = ?", (id,))  
└─────────────────────────────┴────────────────────────────┘
  Bandit: 4 findings   CLEAN (0 findings in rewrite)

Enter fullscreen mode Exit fullscreen mode

The left pane streams as Gemma 4 reasons. The right pane fills in as it produces the secure rewrite. Bandit runs on the rewrite at the end and confirms the fix is real.

The Core API Call

response = client.models.generate_content_stream(
    model="gemma-4-31b-it",
    contents=[types.Content(role="user", parts=[types.Part(text=prompt)])],
    config=types.GenerateContentConfig(
        system_instruction=SYSTEM_PROMPT,
        thinking_config=types.ThinkingConfig(
            include_thoughts=True,
            thinking_budget=thinking_budget,  # scales with SAST severity
        ),
    ),
)

for chunk in response:
    for part in chunk.candidates[0].content.parts:
        if getattr(part, "thought", False):
            yield f"<think>{part.text}"   # → left pane
        elif part.text:
            yield part.text               # → right pane

Enter fullscreen mode Exit fullscreen mode

That's it. No regex. No text parsing. The thought=True flag on stream parts is the entire separation mechanism.

Making the Thinking Load-Bearing

The key design decision was making the thinking trace load-bearing, not decorative. I inject SAST findings from Bandit/semgrep directly into the prompt before the model starts reasoning:

SAST pre-scan findings (ground truth — confirm or refute each in your reasoning):

  [HIGH] B608 hardcoded_sql_expressions — line 47
  [HIGH] B307 eval() — line 62
  [MEDIUM] B105 hardcoded_password_string — line 12

Enter fullscreen mode Exit fullscreen mode

Now the model's thinking trace is explicitly reasoning about concrete, tool-verified findings. It can't skip them. It either confirms the finding and fixes it, or explains why it's a false positive. Either way, you have an auditable chain of evidence tied to specific lines.

The thinking budget scales automatically: 4096 + HIGH_count × 512 + MEDIUM_count × 256 tokens (capped at 16384). Files with more HIGH findings get proportionally deeper reasoning.


What It Looks Like in Practice

The built-in demo (demo/vuln_sample.py) is a Flask app with 5 intentional vulnerabilities:

# demo/vuln_sample.py — intentionally vulnerable

SECRET_KEY = "supersecret123"   # hardcoded secret

@app.route("/admin")            # no auth check
def admin_panel():
    return "Admin panel"

@app.route("/user")
def get_user():
    user_id = request.args.get("id")
    query = f"SELECT * FROM users WHERE id = {user_id}"  # SQL injection
    ...

@app.route("/eval")
def run_code():
    code = request.args.get("code")
    return str(eval(code))      # RCE

Enter fullscreen mode Exit fullscreen mode

Running neuroguard review demo/vuln_sample.py:

  1. Bandit finds 4 HIGH/MEDIUM findings in the original
  2. Those findings are injected into the prompt
  3. Gemma 4 streams its reasoning — you watch it identify the injection vector, explain the attack path, and reason through the fix
  4. The secure rewrite uses parameterized queries, removes eval(), moves the secret to env vars
  5. Bandit runs on the rewrite: 0 findings

The thinking trace is the proof of work. You don't have to trust the rewrite blindly — you can see the exact chain of reasoning that produced it.


SAST + LLM: Two Layers of Confidence

One thing I deliberately avoided was making this "just an LLM." Bandit (for Python) and semgrep/regex patterns (for JS/TS) run before the model sees the code. The findings are facts fed into the reasoning layer.

After the rewrite, they run again. The exit code is non-zero if the original had HIGH/MEDIUM findings — so in CI/CD, your pipeline fails on vulnerable code:

# .github/workflows/neuroguard.yml
- name: Security review
  run: neuroguard review src/ --format json
  env:
    GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}

Enter fullscreen mode Exit fullscreen mode

You can also get a Slack notification with Gemma 4's reasoning excerpt, post a GitHub PR comment automatically, or pipe JSON to any webhook:

neuroguard review app.py --notify-slack https://hooks.slack.com/...
neuroguard review app.py --format json | jq '.thinking' | head -20

Enter fullscreen mode Exit fullscreen mode


The Architecture

neuroguard/
├── agent.py           # Gemma 4 streaming client — ThinkingConfig, retry/fallback
├── thinking_parser.py # Routes <think> parts to left pane, response to right
├── prompts.py         # Language-aware prompt + SAST findings injection
├── cli.py             # Typer CLI: review, install-hooks, --format json/text
├── integrations.py    # Slack Block Kit, webhook, GitHub PR comments
├── tools/
│   ├── sast.py        # Bandit wrapper → Python findings
│   └── js_sast.py     # semgrep + regex fallback → JS/TS findings
└── ui.py              # Rich split-pane Live layout (12fps)

Enter fullscreen mode Exit fullscreen mode

Model fallback: If the 31B dense model hits a rate limit, NeuroGuard falls back to gemma-4-26b-a4b-it (MoE, ~4B active params) automatically. The demo never stalls.

Language support: Python, JavaScript, TypeScript, JSX, TSX.


Try It

pip install neuroguard-ai
export GEMINI_API_KEY=your_key   # free at https://aistudio.google.com/apikey

# against your own code
neuroguard review app.py

# against the built-in vulnerable demo
git clone https://github.com/tyy130/neuroguard-ai
cd neuroguard-ai
neuroguard review demo/vuln_sample.py

Enter fullscreen mode Exit fullscreen mode

You'll see Gemma 4's full reasoning trace in real-time, then a clean, Bandit-verified secure rewrite.


Why This Matters Beyond the Demo

The shift happening in software development right now is that AI generates the first draft of most code. That's not going to stop. But "vibe coding" — accepting AI output without verification — is already producing an epidemic of OWASP vulnerabilities in production systems.

The answer isn't to distrust AI-generated code. It's to demand transparency from the model before you trust the output. Gemma 4's Thinking Mode makes that possible at the API level for the first time.

NeuroGuard is a concrete demonstration of what that looks like: the model can't silently delete an auth check if its reasoning is visible. The audit trail is the security control.

Apache 2.0. The Kaggle weights mean you can run this on-premise — no code ever leaves your network.


Links: